+static int count_trailing_zeroes(shachain_index_t index)
+{
+#if HAVE_BUILTIN_CTZLL
+ return index ? __builtin_ctzll(index) : INDEX_BITS;
+#else
+ int i;
+
+ for (i = 0; i < INDEX_BITS; i++) {
+ if (index & (1ULL << i))
+ break;
+ }
+ return i;
+#endif
+}
+
+static bool can_derive(shachain_index_t from, shachain_index_t to)
+{
+ shachain_index_t mask;
+
+ /* Corner case: can always derive from seed. */
+ if (from == 0)
+ return true;
+
+ /* Leading bits must be the same */
+ mask = ~((1ULL << count_trailing_zeroes(from))-1);
+ return ((from ^ to) & mask) == 0;
+}
+
+static void derive(shachain_index_t from, shachain_index_t to,
+ const struct sha256 *from_hash,
+ struct sha256 *hash)