aboutsummaryrefslogtreecommitdiff
path: root/src/hdk.rs
blob: 830b7c37b0636ae7a608012d7a75b21b4352217e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//! Module implementing the hierachical deterministic key derivation scheme.

mod path;

pub use self::path::{Component, Path};
use crate::account::PrivateKey;
use anyhow::{Context as _, Result};
use hmac::{Hmac, Mac as _};
use secp256k1::{PublicKey, Secp256k1, SecretKey, Signing};
use sha2::Sha512;

/// A value indicating a path component is hardened.
const HARDENED: u32 = 0x8000_0000;

/// Creates a new extended private key for an account index using the standard
/// Ethereum HD path.
pub fn derive_index(seed: impl AsRef<[u8]>, account_index: usize) -> Result<PrivateKey> {
    derive(seed, &format!("m/44'/60'/0'/0/{}", account_index).parse()?)
}

/// Creates a new extended private key from a seed.
pub fn derive(seed: impl AsRef<[u8]>, path: &Path) -> Result<PrivateKey> {
    derive_slice(seed.as_ref(), path)
}

fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> {
    let mut extended_key = {
        let mut hmac = Hmac::<Sha512>::new_from_slice(b"Bitcoin seed")?;
        hmac.update(seed.as_ref());
        hmac.finalize().into_bytes()
    };

    let secp = Secp256k1::signing_only();
    for (i, component) in path.components().enumerate() {
        let (secret, chain_code) = extended_key.split_at(32);

        let mut hmac: Hmac<Sha512> = Hmac::<Sha512>::new_from_slice(chain_code)?;
        let value = match component {
            Component::Hardened(value) => {
                hmac.update(&[0]);
                hmac.update(secret);
                value | HARDENED
            }
            Component::Normal(value) => {
                hmac.update(&public_key(&secp, secret)?);
                value
            }
        };
        hmac.update(&value.to_be_bytes());

        let mut child_key = hmac.finalize().into_bytes();
        let child_secret = SecretKey::from_slice(&child_key[..32])
            .and_then(|mut key| {
                key.add_assign(secret)?;
                Ok(key)
            })
            .with_context(|| {
                format!("path '{}' component #{} yields invalid child key", path, i)
            })?;
        child_key[..32].copy_from_slice(child_secret.as_ref());

        extended_key = child_key
    }

    PrivateKey::new(&extended_key[..32])
}

fn public_key<C>(secp: &Secp256k1<C>, secret: &[u8]) -> Result<[u8; 33]>
where
    C: Signing,
{
    let secret_key = SecretKey::from_slice(secret)?;
    let public_key = PublicKey::from_secret_key(secp, &secret_key);
    Ok(public_key.serialize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{account::Address, ganache::DETERMINISTIC_MNEMONIC, mnemonic::Mnemonic};
    use hex_literal::hex;

    #[test]
    fn ganache_deterministic_mnemonic() {
        let mnemonic = DETERMINISTIC_MNEMONIC.parse::<Mnemonic>().unwrap();
        let path = "m/44'/60'/0'/0/0".parse::<Path>().unwrap();

        let account = derive(mnemonic.seed(""), &path).unwrap();
        assert_eq!(
            account.address(),
            Address(hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")),
        );
    }
}