1 /* MIT (BSD) license - see LICENSE file for details */
2 #include <ccan/crypto/shachain/shachain.h>
3 #include <ccan/ilog/ilog.h>
8 #define INDEX_BITS ((sizeof(shachain_index_t)) * CHAR_BIT)
10 static void change_bit(unsigned char *arr, size_t index)
12 arr[index / CHAR_BIT] ^= (1 << (index % CHAR_BIT));
15 static unsigned int count_trailing_zeroes(shachain_index_t index)
17 #if HAVE_BUILTIN_CTZLL
18 return index ? (unsigned int)__builtin_ctzll(index) : INDEX_BITS;
22 for (i = 0; i < INDEX_BITS; i++) {
23 if (index & (1ULL << i))
30 static bool can_derive(shachain_index_t from, shachain_index_t to)
32 shachain_index_t mask;
34 /* Corner case: can always derive from seed. */
38 /* Leading bits must be the same */
39 mask = ~((1ULL << count_trailing_zeroes(from))-1);
40 return ((from ^ to) & mask) == 0;
43 static void derive(shachain_index_t from, shachain_index_t to,
44 const struct sha256 *from_hash,
47 shachain_index_t branches;
50 assert(can_derive(from, to));
52 /* We start with the first hash. */
55 /* This represents the bits set in to, and not from. */
57 for (i = ilog64(branches) - 1; i >= 0; i--) {
58 if (((branches >> i) & 1)) {
59 change_bit(hash->u.u8, i);
60 sha256(hash, hash, sizeof(*hash));
65 void shachain_from_seed(const struct sha256 *seed, shachain_index_t index,
68 derive(0, index, seed, hash);
71 void shachain_init(struct shachain *chain)
77 bool shachain_add_hash(struct shachain *chain,
78 shachain_index_t index, const struct sha256 *hash)
82 /* You have to insert them in order! */
83 assert(index == chain->min_index - 1 ||
84 (index == (shachain_index_t)(-1ULL) && chain->num_valid == 0));
86 pos = count_trailing_zeroes(index);
88 /* All derivable answers must be valid. */
89 /* FIXME: Is it sufficient to check just the next answer? */
90 for (i = 0; i < pos; i++) {
93 /* Make sure the others derive as expected! */
94 derive(index, chain->known[i].index, hash, &expect);
95 if (memcmp(&expect, &chain->known[i].hash, sizeof(expect)))
99 chain->known[pos].index = index;
100 chain->known[pos].hash = *hash;
101 if (pos + 1 > chain->num_valid)
102 chain->num_valid = pos + 1;
103 chain->min_index = index;
107 bool shachain_get_hash(const struct shachain *chain,
108 shachain_index_t index, struct sha256 *hash)
112 for (i = 0; i < chain->num_valid; i++) {
113 /* If we can get from key to index only by resetting bits,
114 * we can derive from it => index has no bits key doesn't. */
115 if (!can_derive(chain->known[i].index, index))
118 derive(chain->known[i].index, index, &chain->known[i].hash,