clightning-dumpkeys

dump clightning output descriptors
git clone git://jb55.com/clightning-dumpkeys
Log | Files | Refs | README | LICENSE

bip32.c (24279B)


      1 
      2 #include "hmac.h"
      3 #include "ripemd160.h"
      4 #include "sha512.h"
      5 #include "endian.h"
      6 #include "compiler.h"
      7 #include "bip32.h"
      8 #include "ec.h"
      9 #include "hash.h"
     10 #include "base58.h"
     11 #include "short_types.h"
     12 
     13 #include <stdbool.h>
     14 #include <stddef.h>
     15 #include <string.h>
     16 #include <stdio.h>
     17 
     18 #define EC_PRIVATE_KEY_LEN 32
     19 #define BIP32_ALL_DEFINED_FLAGS (BIP32_FLAG_KEY_PRIVATE | BIP32_FLAG_KEY_PUBLIC | BIP32_FLAG_SKIP_HASH)
     20 
     21 static const unsigned char SEED[] = {
     22     'B', 'i', 't', 'c', 'o', 'i', 'n', ' ', 's', 'e', 'e', 'd'
     23 };
     24 
     25 /* LCOV_EXCL_START */
     26 /* Check assumptions we expect to hold true */
     27 UNUSED static void assert_bip32_assumptions(void) 
     28 {
     29 #define key_off(member) offsetof(struct ext_key,  member)
     30 #define key_size(member) sizeof(((struct ext_key *)0)->member)
     31 
     32     /* Our ripend buffers must be uint32_t aligned and the correct size */
     33     BUILD_ASSERT(key_off(parent160) % sizeof(uint32_t) == 0);
     34     BUILD_ASSERT(key_off(hash160) % sizeof(uint32_t) == 0);
     35     BUILD_ASSERT(key_size(parent160) == sizeof(struct ripemd160));
     36     BUILD_ASSERT(key_size(hash160) == sizeof(struct ripemd160));
     37     BUILD_ASSERT(key_size(priv_key) == EC_PRIVATE_KEY_LEN + 1);
     38 
     39     /* Our keys following the parity byte must be uint64_t aligned */
     40     BUILD_ASSERT((key_off(priv_key) + 1) % sizeof(uint64_t) == 0);
     41     BUILD_ASSERT((key_off(pub_key) + 1) % sizeof(uint64_t) == 0);
     42 
     43     /* child_num must be contigous after priv_key */
     44     BUILD_ASSERT((key_off(priv_key) + key_size(priv_key)) == key_off(child_num));
     45 
     46     /* We use priv_key[0] to determine if this extended key is public or
     47      * private, If priv_key[0] is BIP32_FLAG_KEY_PRIVATE then this key is private
     48      * with a computed public key present. If set to BIP32_FLAG_KEY_PUBLIC then
     49      * this is a public key with no private key (A BIP32 'neutered' key).
     50      *
     51      * For this to work BIP32_FLAG_KEY_PRIVATE must be zero so the whole 33 byte
     52      * private key is valid when serialized, and BIP32_FLAG_KEY_PUBLIC cannot be
     53      * 2 or 3 as they are valid parity bytes for public keys.
     54      */
     55     BUILD_ASSERT(BIP32_FLAG_KEY_PRIVATE == 0);
     56     BUILD_ASSERT(BIP32_FLAG_KEY_PUBLIC != BIP32_FLAG_KEY_PRIVATE &&
     57                  BIP32_FLAG_KEY_PUBLIC != 2u &&
     58                  BIP32_FLAG_KEY_PUBLIC != 3u);
     59 }
     60 /* LCOV_EXCL_STOP */
     61 
     62 static bool mem_is_zero(const void *mem, size_t len)
     63 {
     64     size_t i;
     65     for (i = 0; i < len; ++i)
     66         if (((const unsigned char *)mem)[i])
     67             return false;
     68     return true;
     69 }
     70 
     71 static bool child_is_hardened(uint32_t child_num)
     72 {
     73     return child_num >= BIP32_INITIAL_HARDENED_CHILD;
     74 }
     75 
     76 static bool version_is_valid(uint32_t ver, uint32_t flags)
     77 {
     78     if (ver == BIP32_VER_MAIN_PRIVATE || ver == BIP32_VER_TEST_PRIVATE)
     79         return true;
     80 
     81     return flags == BIP32_FLAG_KEY_PUBLIC &&
     82            (ver == BIP32_VER_MAIN_PUBLIC || ver == BIP32_VER_TEST_PUBLIC);
     83 }
     84 
     85 static bool version_is_mainnet(uint32_t ver)
     86 {
     87     return ver == BIP32_VER_MAIN_PRIVATE || ver == BIP32_VER_MAIN_PUBLIC;
     88 }
     89 
     90 static bool key_is_private(const struct ext_key *hdkey)
     91 {
     92     return hdkey->priv_key[0] == BIP32_FLAG_KEY_PRIVATE;
     93 }
     94 
     95 static void key_strip_private_key(struct ext_key *key_out)
     96 {
     97     key_out->priv_key[0] = BIP32_FLAG_KEY_PUBLIC;
     98     memclear(key_out->priv_key + 1, sizeof(key_out->priv_key) - 1);
     99 }
    100 
    101 /* Compute a public key from a private key */
    102 static int key_compute_pub_key(const secp256k1_context *ctx,
    103 			       struct ext_key *key_out)
    104 {
    105 	return wally_ec_public_key_from_private_key(ctx,
    106 						    key_out->priv_key + 1,
    107 						    EC_PRIVATE_KEY_LEN,
    108 						    key_out->pub_key,
    109 						    sizeof(key_out->pub_key));
    110 }
    111 
    112 static void key_compute_hash160(struct ext_key *key_out)
    113 {
    114     hash160(key_out->pub_key, sizeof(key_out->pub_key),
    115 	    key_out->hash160, sizeof(key_out->hash160));
    116 }
    117 
    118 int bip32_key_free(const struct ext_key *hdkey)
    119 {
    120     if (!hdkey)
    121         return WALLY_EINVAL;
    122     memclear((void *)hdkey, sizeof(*hdkey));
    123     free((void *)hdkey);
    124     return WALLY_OK;
    125 }
    126 
    127 static bool is_valid_seed_len(size_t len) {
    128     return len == BIP32_ENTROPY_LEN_512 || len == BIP32_ENTROPY_LEN_256 ||
    129            len == BIP32_ENTROPY_LEN_128;
    130 }
    131 
    132 int bip32_key_from_seed(
    133 	const secp256k1_context *ctx,
    134 	const unsigned char *bytes, size_t bytes_len,
    135 	uint32_t version, uint32_t flags,
    136 	struct ext_key *key_out)
    137 {
    138     struct hmac_sha512 hmac;
    139 
    140     if (!bytes || !is_valid_seed_len(bytes_len) ||
    141         !version_is_valid(version, BIP32_FLAG_KEY_PRIVATE) ||
    142         (flags & ~BIP32_FLAG_SKIP_HASH) || !key_out)
    143     {
    144 	    return WALLY_EINVAL;
    145     }
    146 
    147     memclear(key_out, sizeof(*key_out));
    148     key_out->version = version;
    149 
    150     /* Generate private key and chain code */
    151     hmac_sha512(&hmac, SEED, sizeof(SEED), bytes, bytes_len);
    152 
    153     /* Check that the generated private key is valid */
    154     if (!secp256k1_ec_seckey_verify(ctx, hmac.sha.u.u8)) {
    155 	    memclear(&hmac, sizeof(hmac));
    156 	    return WALLY_ERROR; /* Invalid private key */
    157     }
    158 
    159     /* Copy the private key and set its prefix */
    160     key_out->priv_key[0] = BIP32_FLAG_KEY_PRIVATE;
    161     memcpy(key_out->priv_key + 1, hmac.sha.u.u8, sizeof(hmac) / 2);
    162     if (key_compute_pub_key(ctx, key_out) != WALLY_OK) {
    163         memclear(&hmac, sizeof(hmac));
    164         memclear(key_out, sizeof(*key_out));
    165 	printf("\n");
    166         return WALLY_EINVAL;
    167     }
    168 
    169     /* Copy the chain code */
    170     memcpy(key_out->chain_code, hmac.sha.u.u8 + sizeof(hmac.sha) / 2,
    171 	   sizeof(hmac.sha) / 2);
    172 
    173     key_out->depth = 0; /* Master key, depth 0 */
    174     key_out->child_num = 0;
    175     if (!(flags & BIP32_FLAG_SKIP_HASH))
    176         key_compute_hash160(key_out);
    177     memclear(&hmac, sizeof(hmac));
    178     return WALLY_OK;
    179 }
    180 
    181 #define ALLOC_KEY() \
    182     if (!output) \
    183         return WALLY_EINVAL; \
    184     *output = malloc(sizeof(struct ext_key)); \
    185     if (!*output) \
    186         return WALLY_ENOMEM; \
    187     memclear((void *)*output, sizeof(struct ext_key))
    188 
    189 int bip32_key_from_seed_alloc(const secp256k1_context *ctx,
    190 			      const unsigned char *bytes, size_t bytes_len,
    191                               uint32_t version, uint32_t flags,
    192                               struct ext_key **output)
    193 {
    194     int ret;
    195 
    196     ALLOC_KEY();
    197     ret = bip32_key_from_seed(ctx, bytes, bytes_len, version, flags, *output);
    198     if (ret != WALLY_OK) {
    199         free((void *)*output);
    200         *output = NULL;
    201     }
    202     return ret;
    203 }
    204 
    205 static unsigned char *copy_out(unsigned char *dest,
    206                                const void *src, size_t len)
    207 {
    208     memcpy(dest, src, len);
    209     return dest + len;
    210 }
    211 
    212 static bool key_is_valid(const struct ext_key *hdkey)
    213 {
    214     bool is_private = key_is_private(hdkey);
    215     bool is_master = !hdkey->depth;
    216     int8_t ver_flags = is_private ? BIP32_FLAG_KEY_PRIVATE : BIP32_FLAG_KEY_PUBLIC;
    217 
    218     if (!version_is_valid(hdkey->version, ver_flags)) {
    219     	    return false;
    220     }
    221 
    222     if (mem_is_zero(hdkey->chain_code, sizeof(hdkey->chain_code)) ||
    223         (hdkey->pub_key[0] != 0x2 && hdkey->pub_key[0] != 0x3) ||
    224         mem_is_zero(hdkey->pub_key + 1, sizeof(hdkey->pub_key) - 1))
    225         return false;
    226 
    227     if (hdkey->priv_key[0] != BIP32_FLAG_KEY_PUBLIC &&
    228         hdkey->priv_key[0] != BIP32_FLAG_KEY_PRIVATE)
    229         return false;
    230 
    231     if (is_private &&
    232         mem_is_zero(hdkey->priv_key + 1, sizeof(hdkey->priv_key) - 1))
    233         return false;
    234 
    235     if (is_master &&
    236         !mem_is_zero(hdkey->parent160, sizeof(hdkey->parent160)))
    237 	    return false;
    238 
    239     return true;
    240 }
    241 
    242 int bip32_key_serialize(const struct ext_key *hdkey, uint32_t flags,
    243                         unsigned char *bytes_out, size_t len)
    244 {
    245     const bool serialize_private = !(flags & BIP32_FLAG_KEY_PUBLIC);
    246     unsigned char *out = bytes_out;
    247     uint32_t tmp32;
    248     beint32_t tmp32_be;
    249 
    250     if (flags & ~BIP32_FLAG_KEY_PUBLIC)
    251         return WALLY_EINVAL; /* Only this flag makes sense here */
    252 
    253     /* Validate our arguments and then the input key */
    254     if (!hdkey ||
    255         (serialize_private && !key_is_private(hdkey)) ||
    256         !key_is_valid(hdkey) ||
    257         !bytes_out || len != BIP32_SERIALIZED_LEN)
    258         return WALLY_EINVAL;
    259 
    260 
    261     tmp32 = hdkey->version;
    262     if (!serialize_private) {
    263         /* Change version if serializing the public part of a private key */
    264         if (tmp32 == BIP32_VER_MAIN_PRIVATE)
    265             tmp32 = BIP32_VER_MAIN_PUBLIC;
    266         else if (tmp32 == BIP32_VER_TEST_PRIVATE)
    267             tmp32 = BIP32_VER_TEST_PUBLIC;
    268     }
    269     tmp32_be = cpu_to_be32(tmp32);
    270     out = copy_out(out, &tmp32_be, sizeof(tmp32_be));
    271 
    272     *out++ = hdkey->depth;
    273 
    274     /* Save the first 32 bits of the parent key (aka fingerprint) only */
    275     out = copy_out(out, hdkey->parent160, sizeof(uint32_t));
    276 
    277 
    278     tmp32_be = cpu_to_be32(hdkey->child_num);
    279     out = copy_out(out, &tmp32_be, sizeof(tmp32_be));
    280 
    281     out = copy_out(out, hdkey->chain_code, sizeof(hdkey->chain_code));
    282 
    283     if (serialize_private)
    284         copy_out(out, hdkey->priv_key, sizeof(hdkey->priv_key));
    285     else
    286         copy_out(out, hdkey->pub_key, sizeof(hdkey->pub_key));
    287 
    288     return WALLY_OK;
    289 }
    290 
    291 static const unsigned char *copy_in(void *dest,
    292                                     const unsigned char *src, size_t len)
    293 {
    294     memcpy(dest, src, len);
    295     return src + len;
    296 }
    297 
    298 /* Wipe a key and return failure for the caller to propigate */
    299 static int wipe_key_fail(struct ext_key *key_out)
    300 {
    301     memclear(key_out, sizeof(*key_out));
    302     return WALLY_EINVAL;
    303 }
    304 
    305 int bip32_key_unserialize(const secp256k1_context *ctx,
    306 			  const unsigned char *bytes, size_t bytes_len,
    307                           struct ext_key *key_out)
    308 {
    309     if (!bytes || bytes_len != BIP32_SERIALIZED_LEN || !key_out)
    310         return WALLY_EINVAL;
    311 
    312     memclear(key_out, sizeof(*key_out));
    313 
    314     bytes = copy_in(&key_out->version, bytes, sizeof(key_out->version));
    315     key_out->version = be32_to_cpu(key_out->version);
    316     if (!version_is_valid(key_out->version, BIP32_FLAG_KEY_PUBLIC))
    317         return wipe_key_fail(key_out);
    318 
    319     bytes = copy_in(&key_out->depth, bytes, sizeof(key_out->depth));
    320 
    321     /* We only have a partial fingerprint available. Copy it, but the
    322      * user will need to call bip32_key_set_parent() (FIXME: Implement)
    323      * later if they want it to be fully populated.
    324      */
    325     bytes = copy_in(key_out->parent160, bytes, sizeof(uint32_t));
    326     bytes = copy_in(&key_out->child_num, bytes, sizeof(key_out->child_num));
    327     key_out->child_num = be32_to_cpu(key_out->child_num);
    328     bytes = copy_in(key_out->chain_code, bytes, sizeof(key_out->chain_code));
    329 
    330     if (bytes[0] == BIP32_FLAG_KEY_PRIVATE) {
    331         if (key_out->version == BIP32_VER_MAIN_PUBLIC ||
    332             key_out->version == BIP32_VER_TEST_PUBLIC)
    333             return wipe_key_fail(key_out); /* Private key data in public key */
    334 
    335         copy_in(key_out->priv_key, bytes, sizeof(key_out->priv_key));
    336         if (key_compute_pub_key(ctx, key_out) != WALLY_OK)
    337             return wipe_key_fail(key_out);
    338     } else {
    339         if (key_out->version == BIP32_VER_MAIN_PRIVATE ||
    340             key_out->version == BIP32_VER_TEST_PRIVATE)
    341             return wipe_key_fail(key_out); /* Public key data in private key */
    342 
    343         copy_in(key_out->pub_key, bytes, sizeof(key_out->pub_key));
    344         key_strip_private_key(key_out);
    345     }
    346 
    347     key_compute_hash160(key_out);
    348     return WALLY_OK;
    349 }
    350 
    351 int bip32_key_unserialize_alloc(
    352 	const secp256k1_context *ctx,
    353 	const unsigned char *bytes,
    354 	size_t bytes_len, struct ext_key **output)
    355 {
    356     int ret;
    357 
    358     ALLOC_KEY();
    359     ret = bip32_key_unserialize(ctx, bytes, bytes_len, *output);
    360     if (ret) {
    361         free(*output);
    362         *output = 0;
    363     }
    364     return ret;
    365 }
    366 
    367 /* BIP32: Child Key Derivations
    368  *
    369  * The spec doesn't have a simple table of derivations, its:
    370  *
    371  * Parent   Child    Hardened  Status  Path  In Spec
    372  * private  private  no        OK      m/n   Y
    373  * private  private  yes       OK      m/nH  Y
    374  * private  public   no        OK      -     N
    375  * private  public   yes       OK      -     N
    376  * public   private  no        FAIL   (N/A) (N/A)
    377  * public   private  yes       FAIL   (N/A) (N/A)
    378  * public   public   no        OK      M/n   N
    379  * public   public   yes       FAIL    M/nH (N/A)
    380  *
    381  * The spec path nomenclature only expresses derivations where the parent
    382  * and desired child type match. For private->public the derivation is
    383  * described in terms of private-private and public->public, but there are
    384  * no test vectors or paths describing these values to validate against.
    385  * Further, there are no public-public vectors in the BIP32 spec either.
    386  */
    387 int bip32_key_from_parent(const secp256k1_context *ctx,
    388 			  const struct ext_key *hdkey,
    389 			  uint32_t child_num, uint32_t flags,
    390 			  struct ext_key *key_out)
    391 {
    392     struct hmac_sha512 hmac;
    393     const bool we_are_private = hdkey && key_is_private(hdkey);
    394     const bool derive_private = !(flags & BIP32_FLAG_KEY_PUBLIC);
    395     const bool hardened = child_is_hardened(child_num);
    396 
    397     if (flags & ~BIP32_ALL_DEFINED_FLAGS)
    398         return WALLY_EINVAL; /* These flags are not defined yet */
    399 
    400     if (!hdkey || !key_out)
    401         return WALLY_EINVAL;
    402 
    403     if (!we_are_private && (derive_private || hardened))
    404         return wipe_key_fail(key_out); /* Unsupported derivation */
    405 
    406     if (hdkey->depth == 0xff)
    407         return wipe_key_fail(key_out); /* Maximum depth reached */
    408 
    409     /*
    410      *  Private parent -> private child:
    411      *    CKDpriv((kpar, cpar), i) -> (ki, ci)
    412      *
    413      *  Private parent -> public child:
    414      *    N(CKDpriv((kpar, cpar), i) -> (ki, ci))
    415      *  As we always calculate the public key, we can derive a public
    416      *  child by deriving a private one and stripping its private key.
    417      *
    418      * Public parent -> non hardened public child
    419      *    CKDpub((Kpar, cpar), i) -> (Ki, ci)
    420      */
    421 
    422     /* NB: We use the key_outs' priv_key+child_num to hold 'Data' here */
    423     if (hardened) {
    424         /* Hardened: Data = 0x00 || ser256(kpar) || ser32(i)) */
    425         memcpy(key_out->priv_key, hdkey->priv_key, sizeof(hdkey->priv_key));
    426     } else {
    427         /* Non Hardened Private: Data = serP(point(kpar)) || ser32(i)
    428          * Non Hardened Public : Data = serP(kpar) || ser32(i)
    429          *   point(kpar) when par is private is the public key.
    430          */
    431         memcpy(key_out->priv_key, hdkey->pub_key, sizeof(hdkey->pub_key));
    432     }
    433 
    434     /* This is the '|| ser32(i)' part of the above */
    435     key_out->child_num = cpu_to_be32(child_num);
    436 
    437     /* I = HMAC-SHA512(Key = cpar, Data) */
    438     hmac_sha512(&hmac, hdkey->chain_code, sizeof(hdkey->chain_code),
    439                      key_out->priv_key,
    440                      sizeof(key_out->priv_key) + sizeof(key_out->child_num));
    441 
    442     /* Split I into two 32-byte sequences, IL and IR
    443      * The returned chain code ci is IR (i.e. the 2nd half of our hmac sha512)
    444      */
    445     memcpy(key_out->chain_code, hmac.sha.u.u8 + sizeof(hmac.sha) / 2,
    446            sizeof(key_out->chain_code));
    447 
    448     if (we_are_private) {
    449         /* The returned child key ki is parse256(IL) + kpar (mod n)
    450          * In case parse256(IL) ≥ n or ki = 0, the resulting key is invalid
    451          * (NOTE: privkey_tweak_add checks both conditions)
    452          */
    453         memcpy(key_out->priv_key, hdkey->priv_key, sizeof(hdkey->priv_key));
    454         if (!secp256k1_ec_privkey_tweak_add(ctx, key_out->priv_key + 1,
    455 					    hmac.sha.u.u8)) {
    456             memclear(&hmac.sha, sizeof(hmac.sha));
    457             return wipe_key_fail(key_out); /* Out of bounds FIXME: Iterate to the next? */
    458         }
    459 
    460         if (key_compute_pub_key(ctx, key_out) != WALLY_OK) {
    461             memclear(&hmac.sha, sizeof(hmac.sha));
    462             return wipe_key_fail(key_out);
    463         }
    464     } else {
    465         /* The returned child key ki is point(parse256(IL) + kpar)
    466          * In case parse256(IL) ≥ n or Ki is the point at infinity, the
    467          * resulting key is invalid (NOTE: pubkey_tweak_add checks both
    468          * conditions)
    469          */
    470         secp256k1_pubkey pub_key;
    471         size_t len = sizeof(key_out->pub_key);
    472 
    473         /* FIXME: Out of bounds on pubkey_tweak_add */
    474         if (!secp256k1_ec_pubkey_parse(ctx, &pub_key, hdkey->pub_key,
    475                           sizeof(hdkey->pub_key)) ||
    476 
    477             !secp256k1_ec_privkey_tweak_add(ctx, pub_key.data,
    478 					    hmac.sha.u.u8) ||
    479 
    480             !secp256k1_ec_pubkey_serialize(ctx, key_out->pub_key,
    481 					   &len, &pub_key,
    482                               SECP256K1_EC_COMPRESSED) ||
    483             len != sizeof(key_out->pub_key)) {
    484             memclear(&hmac.sha, sizeof(hmac.sha));
    485             return wipe_key_fail(key_out);
    486         }
    487     }
    488 
    489     if (derive_private) {
    490         if (version_is_mainnet(hdkey->version))
    491             key_out->version = BIP32_VER_MAIN_PRIVATE;
    492         else
    493             key_out->version = BIP32_VER_TEST_PRIVATE;
    494 
    495     } else {
    496         if (version_is_mainnet(hdkey->version))
    497             key_out->version = BIP32_VER_MAIN_PUBLIC;
    498         else
    499             key_out->version = BIP32_VER_TEST_PUBLIC;
    500 
    501         key_strip_private_key(key_out);
    502     }
    503 
    504     key_out->depth = hdkey->depth + 1;
    505     key_out->child_num = child_num;
    506     if (flags & BIP32_FLAG_SKIP_HASH) {
    507 	    memclear_2(&key_out->parent160, sizeof(key_out->parent160),
    508 		       &key_out->hash160, sizeof(key_out->hash160));
    509     }
    510     else {
    511         memcpy(key_out->parent160, hdkey->hash160, sizeof(hdkey->hash160));
    512         key_compute_hash160(key_out);
    513     }
    514     memclear(&hmac.sha, sizeof(hmac.sha));
    515     return WALLY_OK;
    516 }
    517 
    518 int bip32_key_from_parent_alloc(
    519 	const secp256k1_context *ctx,
    520 	const struct ext_key *hdkey,
    521 	uint32_t child_num, uint32_t flags,
    522 	struct ext_key **output)
    523 {
    524     int ret;
    525 
    526     ALLOC_KEY();
    527     ret = bip32_key_from_parent(ctx, hdkey, child_num, flags, *output);
    528     if (ret) {
    529         free(*output);
    530         *output = 0;
    531     }
    532     return ret;
    533 }
    534 
    535 int bip32_key_from_parent_path(
    536 	const secp256k1_context *ctx,
    537 	const struct ext_key *hdkey,
    538 	const uint32_t *child_path, size_t child_path_len,
    539 	uint32_t flags, struct ext_key *key_out)
    540 {
    541     /* Optimization: We can skip hash calculations for internal nodes */
    542     uint32_t derivation_flags = flags | BIP32_FLAG_SKIP_HASH;
    543     struct ext_key tmp[2];
    544     size_t i, tmp_idx = 0;
    545     int ret = WALLY_OK;
    546 
    547     if (flags & ~BIP32_ALL_DEFINED_FLAGS)
    548         return WALLY_EINVAL; /* These flags are not defined yet */
    549 
    550     if (!hdkey || !child_path || !child_path_len || !key_out)
    551         return WALLY_EINVAL;
    552 
    553     for (i = 0; i < child_path_len; ++i) {
    554         struct ext_key *derived = &tmp[tmp_idx];
    555 
    556         if (i + 2 >= child_path_len)
    557             derivation_flags = flags; /* Use callers flags for the final derivations */
    558 
    559         ret = bip32_key_from_parent(ctx, hdkey, child_path[i],
    560 				    derivation_flags, derived);
    561 
    562         if (ret != WALLY_OK)
    563             break;
    564 
    565         hdkey = derived;    /* Derived becomes next parent */
    566         tmp_idx = !tmp_idx; /* Use free slot in tmp for next derived */
    567     }
    568 
    569     if (ret == WALLY_OK)
    570         memcpy(key_out, hdkey, sizeof(*key_out));
    571 
    572     memclear(tmp, sizeof(tmp));
    573     return ret;
    574 }
    575 
    576 int bip32_key_from_parent_path_alloc(
    577 	const secp256k1_context *ctx,
    578 	const struct ext_key *hdkey,
    579 	const uint32_t *child_path, size_t child_path_len,
    580 	uint32_t flags,
    581 	struct ext_key **output)
    582 {
    583     int ret;
    584 
    585     ALLOC_KEY();
    586     ret = bip32_key_from_parent_path(ctx, hdkey, child_path,
    587 				     child_path_len, flags, *output);
    588     if (ret) {
    589         free(*output);
    590         *output = 0;
    591     }
    592     return ret;
    593 }
    594 
    595 int bip32_key_init_alloc(
    596 	const secp256k1_context *ctx,
    597 	uint32_t version, uint32_t depth, uint32_t child_num,
    598 	const unsigned char *chain_code, size_t chain_code_len,
    599 	const unsigned char *pub_key, size_t pub_key_len,
    600 	const unsigned char *priv_key, size_t priv_key_len,
    601 	const unsigned char *hash160, size_t hash160_len,
    602 	const unsigned char *parent160, size_t parent160_len,
    603 	struct ext_key **output)
    604 {
    605     struct ext_key *key_out;
    606 
    607     if (!output)
    608         return WALLY_EINVAL;
    609     *output = NULL;
    610 
    611     switch (version) {
    612     case BIP32_VER_MAIN_PRIVATE:
    613     case BIP32_VER_TEST_PRIVATE:
    614         if (!priv_key || priv_key_len != key_size(priv_key) - 1)
    615             return WALLY_EINVAL;
    616         break;
    617     case BIP32_VER_MAIN_PUBLIC:
    618     case BIP32_VER_TEST_PUBLIC:
    619         if (!pub_key || pub_key_len != key_size(pub_key))
    620             return WALLY_EINVAL;
    621         break;
    622     }
    623 
    624     if (!chain_code || chain_code_len != key_size(chain_code))
    625         return WALLY_EINVAL;
    626 
    627     if ((priv_key && priv_key_len != key_size(priv_key) - 1) || (!priv_key && priv_key_len) ||
    628         (pub_key && pub_key_len != key_size(pub_key)) || (!pub_key && pub_key_len) ||
    629         (hash160 && hash160_len != key_size(hash160)) || (!hash160 && hash160_len) ||
    630         (parent160 && parent160_len != key_size(parent160)))
    631         return WALLY_EINVAL;
    632 
    633     ALLOC_KEY();
    634 
    635     key_out = *output;
    636     key_out->version = version;
    637     key_out->depth = depth;
    638     key_out->child_num = child_num;
    639 
    640     memcpy(key_out->chain_code, chain_code, key_size(chain_code));
    641     if (priv_key && version != BIP32_VER_MAIN_PUBLIC && version != BIP32_VER_TEST_PUBLIC)
    642         memcpy(key_out->priv_key + 1, priv_key, key_size(priv_key) - 1);
    643     else
    644         key_out->priv_key[0] = BIP32_FLAG_KEY_PUBLIC;
    645     if (pub_key)
    646         memcpy(key_out->pub_key, pub_key, key_size(pub_key));
    647     else if (version == BIP32_VER_MAIN_PRIVATE || version == BIP32_VER_TEST_PRIVATE) {
    648         /* Compute the public key if not given */
    649 	    int ret = key_compute_pub_key(ctx, key_out);
    650         if (ret != WALLY_OK) {
    651             memclear(key_out, sizeof(*key_out));
    652             free(key_out);
    653             *output = 0;
    654             return ret;
    655         }
    656     }
    657     if (hash160)
    658         memcpy(key_out->hash160, hash160, key_size(hash160));
    659     else
    660         key_compute_hash160(key_out);
    661     if (parent160)
    662         memcpy(key_out->parent160, parent160, key_size(parent160));
    663 
    664     return WALLY_OK;
    665 }
    666 
    667 int bip32_key_to_base58(const struct ext_key *hdkey,
    668                         uint32_t flags,
    669                         char **output)
    670 {
    671     int ret;
    672     unsigned char bytes[BIP32_SERIALIZED_LEN];
    673 
    674     if ((ret = bip32_key_serialize(hdkey, flags, bytes, sizeof(bytes))))
    675         return ret;
    676 
    677     ret = wally_base58_from_bytes(bytes, BIP32_SERIALIZED_LEN,
    678 				  BASE58_FLAG_CHECKSUM, output);
    679 
    680     memclear(bytes, sizeof(bytes));
    681     return ret;
    682 }
    683 
    684 int bip32_key_from_base58(
    685 	const secp256k1_context *ctx,
    686 	const char *base58,
    687 	struct ext_key *output)
    688 {
    689     int ret;
    690     unsigned char bytes[BIP32_SERIALIZED_LEN + BASE58_CHECKSUM_LEN];
    691     size_t written;
    692 
    693     if ((ret = wally_base58_to_bytes(base58, BASE58_FLAG_CHECKSUM, bytes, sizeof(bytes), &written)))
    694         return ret;
    695 
    696     if (written != BIP32_SERIALIZED_LEN)
    697 	    ret = WALLY_EINVAL;
    698     else
    699 	    ret = bip32_key_unserialize(ctx, bytes,
    700 					BIP32_SERIALIZED_LEN, output);
    701 
    702     memclear(bytes, sizeof(bytes));
    703     return ret;
    704 }
    705 
    706 int bip32_key_from_base58_alloc(
    707 	const secp256k1_context *ctx,
    708 	const char *base58, struct ext_key **output)
    709 {
    710     int ret;
    711 
    712     ALLOC_KEY();
    713     ret = bip32_key_from_base58(ctx, base58, *output);
    714     if (ret) {
    715         free(*output);
    716         *output = 0;
    717     }
    718     return ret;
    719 }
    720 
    721 #if defined (SWIG_JAVA_BUILD) || defined (SWIG_PYTHON_BUILD) || defined (SWIG_JAVASCRIPT_BUILD)
    722 
    723 /* Getters for ext_key values */
    724 
    725 static int getb_impl(const struct ext_key *hdkey,
    726                      const unsigned char *src, size_t src_len,
    727                      unsigned char *bytes_out, size_t len)
    728 {
    729     if (!hdkey || !bytes_out || len != src_len)
    730         return WALLY_EINVAL;
    731     memcpy(bytes_out, src, len);
    732     return WALLY_OK;
    733 }
    734 
    735 #define GET_B(name) \
    736     int bip32_key_get_ ## name(const struct ext_key *hdkey, unsigned char *bytes_out, size_t len) { \
    737         return getb_impl(hdkey, hdkey->name, sizeof(hdkey->name), bytes_out, len); \
    738     }
    739 
    740 GET_B(chain_code)
    741 GET_B(parent160)
    742 GET_B(hash160)
    743 GET_B(pub_key)
    744 
    745 int bip32_key_get_priv_key(const struct ext_key *hdkey, unsigned char *bytes_out, size_t len) {
    746     return getb_impl(hdkey, hdkey->priv_key + 1, sizeof(hdkey->priv_key) - 1, bytes_out, len);
    747 }
    748 
    749 
    750 #define GET_I(name) \
    751     int bip32_key_get_ ## name(const struct ext_key *hdkey, size_t *written) { \
    752         if (written) *written = 0; \
    753         if (!hdkey || !written) return WALLY_EINVAL; \
    754         *written = hdkey->name; \
    755         return WALLY_OK; \
    756     }
    757 
    758 GET_I(depth)
    759 GET_I(child_num)
    760 GET_I(version)
    761 
    762 #endif /* SWIG_JAVA_BUILD/SWIG_PYTHON_BUILD */