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