1
0

AddressCalc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 "rust/cjdns_sys/Rffi.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. bool AddressCalc_validAddress(const uint8_t address[16])
  29. {
  30. uint64_t significant_bits;
  31. Bits_memcpy (&significant_bits, address, sizeof(uint64_t));
  32. return (significant_bits & ADDRESS_PREFIX_MASK) == ADDRESS_PREFIX_U64;
  33. }
  34. void AddressCalc_makeValidAddress(uint8_t address[16])
  35. {
  36. uint64_t significant_bits;
  37. Bits_memcpy (&significant_bits, address, sizeof(uint64_t));
  38. significant_bits &= ~ADDRESS_PREFIX_MASK; // zero out the prefix
  39. significant_bits |= ADDRESS_PREFIX_U64; // put the new prefix
  40. Bits_memcpy (address, &significant_bits, sizeof(uint64_t));
  41. }
  42. bool AddressCalc_addressForPublicKey(uint8_t addressOut[16], const uint8_t key[32])
  43. {
  44. uint8_t hash[64];
  45. Rffi_crypto_hash_sha512(hash, key, 32);
  46. Rffi_crypto_hash_sha512(hash, hash, sizeof hash);
  47. if (addressOut) {
  48. Bits_memcpy(addressOut, hash, 16);
  49. }
  50. return AddressCalc_validAddress(addressOut);
  51. }