trezor / trezor-crypto

:lock: Don't use this repo, use the new monorepo instead:
https://github.com/trezor/trezor-firmware
MIT License
501 stars 201 forks source link

Mnemonic -> Ext Key Problem: Usage error or compiler issue. #208

Closed FellGleaming closed 4 years ago

FellGleaming commented 4 years ago

Hi, I know this is a deprecated library, but I have some legacy code being supported. In converting a mnemonic phrase to an ext key pair, I am able to successfully create a seed and root key, but in creating the m/0' extended key pair, I get a value that does not match expectations. I have pared down the code to the fragment below; am I using the library improperly, or perhaps have I miscompiled with improper flags?

    const char* mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
    const char* passphrase = "";
    uint8_t seed[SEED_LEN];

    // generate seed: this creates a value that matches expectations.
    mnemonic_to_seed(mnemonic, passphrase, seed, 0);

    char rootkey[KEYLEN], extprivkey[KEYLEN], extpubkey[KEYLEN];
    uint32_t fingerprint = 0;
    HDNode node;

    // generate master node: creates a value that matches expectations
    hdnode_from_seed(seed, 64, SECP256K1_NAME, &node);
    hdnode_fill_public_key(&node);

    // extract node root key
    hdnode_serialize_private(&node, fingerprint, VERSION_PRIVATE, rootkey, sizeof(rootkey));

    // generate m/0' ext key pair.
    hdnode_private_ckd_prime(&node, 0);
    hdnode_fill_public_key(&node);

    // private & public key buffers do NOT match expected value.
    hdnode_serialize_private(&node, fingerprint, VERSION_PRIVATE, extprivkey, sizeof(extprivkey));
    hdnode_serialize_public(&node, fingerprint, VERSION_PUBLIC, extpubkey, sizeof(extpubkey));

Edit: Adding output. Ext Private Key generated: xprv9tu9RdvSZ2FH6WseyBa1Kcbi7v9VteFDou2GDKGuSApf8Q55p47noHAjQ4qRWyLBBykBHBoy5oepeHMFshu7rahxbjRWrAJnikYytMrwAd1 Expected Value (from IanColeman.io/Bip39): xprv9ukW2Usuz4v7Yd2EC4vNXaMckdsEdgBA9n7MQbqMJbW9FuHDWWjDwzEM2h6XmFnrzX7JVmfcNWMEVoRauU6hQpbokqPPNTbdycW9fHSPYyF

prusnak commented 4 years ago

You need to update the parent fingerprint using hdnode_fingerprint.

    // generate m/0' ext key pair.
+   fingerprint = hdnode_fingerprint(&node);
    hdnode_private_ckd_prime(&node, 0);
    hdnode_fill_public_key(&node);