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, 1);
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 *shachain)
49 shachain->num_valid = 0;
52 bool shachain_add_hash(struct shachain *chain,
53 shachain_index_t index, const struct sha256 *hash)
57 for (i = 0; i < chain->num_valid; i++) {
58 /* If we could derive this value, we don't need it,
59 * not any others (since they're in order). */
60 if (can_derive(index, chain->known[i].index)) {
63 /* Make sure the others derive as expected! */
64 derive(index, chain->known[i].index, hash, &expect);
65 if (memcmp(&expect, &chain->known[i].hash,
72 /* This can happen if you skip indices! */
73 assert(i < sizeof(chain->known) / sizeof(chain->known[0]));
74 chain->known[i].index = index;
75 chain->known[i].hash = *hash;
76 chain->num_valid = i+1;
80 bool shachain_get_hash(const struct shachain *chain,
81 shachain_index_t index, struct sha256 *hash)
85 for (i = 0; i < chain->num_valid; i++) {
86 /* If we can get from key to index only by resetting bits,
87 * we can derive from it => index has no bits key doesn't. */
88 if (!can_derive(chain->known[i].index, index))
91 derive(chain->known[i].index, index, &chain->known[i].hash,