1 /* MIT (BSD) license - see LICENSE file for details */
2 #include <ccan/crypto/shachain/shachain.h>
3 #include <ccan/ilog/ilog.h>
8 static void change_bit(unsigned char *arr, size_t index)
10 arr[index / CHAR_BIT] ^= (1 << (index % CHAR_BIT));
13 static void derive(shachain_index_t index, size_t bits, struct sha256 *hash)
17 for (i = bits - 1; i >= 0; i--) {
18 if (!((index >> i) & 1)) {
19 change_bit(hash->u.u8, i);
20 sha256(hash, hash, 1);
25 void shachain_from_seed(const struct sha256 *seed, shachain_index_t index,
29 derive(index, sizeof(index) * CHAR_BIT, hash);
32 void shachain_init(struct shachain *shachain)
34 shachain->num_valid = 0;
37 /* We can only ever *unset* bits, so to must only have bits in from. */
38 static bool can_derive(shachain_index_t from, shachain_index_t to)
40 return (~from & to) == 0;
43 void shachain_add_hash(struct shachain *chain,
44 shachain_index_t index, const struct sha256 *hash)
48 for (i = 0; i < chain->num_valid; i++) {
49 /* If we could derive this value, we don't need it,
50 * not any others (since they're in order). */
51 if (can_derive(index, chain->known[i].index))
55 /* This can happen if you skip indices! */
56 assert(i < sizeof(chain->known) / sizeof(chain->known[0]));
57 chain->known[i].index = index;
58 chain->known[i].hash = *hash;
59 chain->num_valid = i+1;
62 bool shachain_get_hash(const struct shachain *chain,
63 shachain_index_t index, struct sha256 *hash)
67 for (i = 0; i < chain->num_valid; i++) {
68 shachain_index_t diff;
70 /* If we can get from key to index only by resetting bits,
71 * we can derive from it => index has no bits key doesn't. */
72 if (!can_derive(chain->known[i].index, index))
75 /* Start from this hash. */
76 *hash = chain->known[i].hash;
78 /* This indicates the bits which are in 'index' and
80 diff = index ^ chain->known[i].index;
82 /* Using ilog64 here is an optimization. */
83 derive(~diff, ilog64(diff), hash);