1
0

AddressCalc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/Bits.h"
  16. #include "util/Endian.h"
  17. #include "crypto/AddressCalc.h"
  18. #include <sodium/crypto_hash_sha512.h>
  19. #include <stdint.h>
  20. #include <stdbool.h>
  21. /* These two constants are in big endian so they can be compared
  22. * immediately with a uint8_t[] containing an address.
  23. */
  24. #define ADDRESS_PREFIX_U64 (Endian_hostToBigEndian64( \
  25. ((uint64_t) AddressCalc_ADDRESS_PREFIX) << (64 - AddressCalc_ADDRESS_PREFIX_BITS)))
  26. #define ADDRESS_PREFIX_MASK (Endian_hostToBigEndian64( \
  27. UINT64_MAX << (64 - AddressCalc_ADDRESS_PREFIX_BITS)))
  28. #include <stdio.h>
  29. bool AddressCalc_validAddress(const uint8_t address[16])
  30. {
  31. uint64_t significant_bits;
  32. Bits_memcpy (&significant_bits, address, sizeof(uint64_t));
  33. return (significant_bits & ADDRESS_PREFIX_MASK) == ADDRESS_PREFIX_U64;
  34. }
  35. void AddressCalc_makeValidAddress(uint8_t address[16])
  36. {
  37. uint64_t significant_bits;
  38. Bits_memcpy (&significant_bits, address, sizeof(uint64_t));
  39. significant_bits &= ~ADDRESS_PREFIX_MASK; // zero out the prefix
  40. significant_bits |= ADDRESS_PREFIX_U64; // put the new prefix
  41. Bits_memcpy (address, &significant_bits, sizeof(uint64_t));
  42. }
  43. bool AddressCalc_addressForPublicKey(uint8_t addressOut[16], const uint8_t key[32])
  44. {
  45. uint8_t hash[crypto_hash_sha512_BYTES];
  46. crypto_hash_sha512(hash, key, 32);
  47. crypto_hash_sha512(hash, hash, crypto_hash_sha512_BYTES);
  48. if (addressOut) {
  49. Bits_memcpy(addressOut, hash, 16);
  50. }
  51. return AddressCalc_validAddress(addressOut);
  52. }