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 /* We can only ever *unset* bits, so to must only have bits in from. */
14 static bool can_derive(shachain_index_t from, shachain_index_t to)
16 return (~from & to) == 0;
19 static void derive(shachain_index_t from, shachain_index_t to,
20 const struct sha256 *from_hash,
23 shachain_index_t branches;
26 assert(can_derive(from, to));
28 /* We start with the first hash. */
31 /* This represents the bits set in from, and not to. */
33 for (i = ilog64(branches) - 1; i >= 0; i--) {
34 if (((branches >> i) & 1)) {
35 change_bit(hash->u.u8, i);
36 sha256(hash, hash, sizeof(*hash));
41 void shachain_from_seed(const struct sha256 *seed, shachain_index_t index,
44 derive((shachain_index_t)-1ULL, index, seed, hash);
47 void shachain_init(struct shachain *chain)
53 bool shachain_add_hash(struct shachain *chain,
54 shachain_index_t index, const struct sha256 *hash)
58 /* You have to insert them in order! */
59 assert(index == chain->max_index + 1 ||
60 (index == 0 && chain->num_valid == 0));
62 for (i = 0; i < chain->num_valid; i++) {
63 /* If we could derive this value, we don't need it,
64 * not any others (since they're in order). */
65 if (can_derive(index, chain->known[i].index)) {
68 /* Make sure the others derive as expected! */
69 derive(index, chain->known[i].index, hash, &expect);
70 if (memcmp(&expect, &chain->known[i].hash,
77 /* This can happen if you skip indices! */
78 assert(i < sizeof(chain->known) / sizeof(chain->known[0]));
79 chain->known[i].index = index;
80 chain->known[i].hash = *hash;
81 chain->num_valid = i+1;
82 chain->max_index = index;
86 bool shachain_get_hash(const struct shachain *chain,
87 shachain_index_t index, struct sha256 *hash)
91 for (i = 0; i < chain->num_valid; i++) {
92 /* If we can get from key to index only by resetting bits,
93 * we can derive from it => index has no bits key doesn't. */
94 if (!can_derive(chain->known[i].index, index))
97 derive(chain->known[i].index, index, &chain->known[i].hash,