Skip to main content

heika_wallet/
slip10.rs

1//! SLIP-10 の ed25519 での鍵の導出。Symbol のウォレットが使うパスは [`symbol_path`] で作る。
2//!
3//! ed25519 には hardened の導出しかないので、番号は常に hardened として扱う。
4//! Symbol の SDK(`sdk/python/symbolchain/Bip32.py`)と同じく、渡された番号に hardened のビットを立てて使うので、
5//! `44` と `0x8000002C` は同じ `44'` になる。
6
7use heika_core::key::PrivateKey;
8use heika_core::network::NetworkIdentifier;
9use hmac::digest::FixedOutput;
10use hmac::{Hmac, KeyInit, Mac};
11use sha2::Sha512;
12use zeroize::Zeroizing;
13
14const HARDENED: u32 = 0x8000_0000;
15/// ルートを導出する HMAC の鍵。
16const CURVE: &[u8] = b"ed25519 seed";
17
18/// Symbol のウォレットがアカウントの鍵を導出するパス `m/44'/<coin type>'/<アカウント>'/0'/0'`。
19///
20/// coin type はメインネットなら 4343、それ以外なら 1。SDK の `SymbolFacade.bip32_path` と同じ。
21pub fn symbol_path(network: NetworkIdentifier, account: u32) -> [u32; 5] {
22    let coin_type = if network == NetworkIdentifier::MAINNET {
23        4343
24    } else {
25        1
26    };
27    [44, coin_type, account, 0, 0]
28}
29
30/// ハーベストの鍵の役割。[`harvest_path`] の4番目の番号になる。
31///
32/// [`symbol_path`] の4番目は 0 なので、1 から始めて、間違えて同じシードを渡してもアカウントの鍵にはならないようにする。
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum HarvestRole {
35    /// ブロックに署名するリモートアカウント
36    Remote = 1,
37    /// VRF
38    Vrf = 2,
39}
40
41/// ハーベストの鍵を導出するパス `m/44'/<coin type>'/<アカウント>'/<役割>'/<作り直しの番号>'`。
42///
43/// heika だけの約束。アカウントの鍵とは別のシード(キーストアの `Harvest-Secret`)から導出するので、
44/// [`symbol_path`] と同じ形でもぶつからない。作り直しの番号は、鍵を作り直すたびに1つ上げる。
45pub fn harvest_path(
46    network: NetworkIdentifier,
47    account: u32,
48    role: HarvestRole,
49    rotation: u32,
50) -> [u32; 5] {
51    let [purpose, coin_type, account, ..] = symbol_path(network, account);
52    [purpose, coin_type, account, role as u32, rotation]
53}
54
55/// 秘密鍵とチェーンコードの組。使い終わるとメモリを0で上書きする。
56#[derive(Clone)]
57pub struct ExtendedKey {
58    private_key: Zeroizing<[u8; 32]>,
59    chain_code: Zeroizing<[u8; 32]>,
60}
61
62impl ExtendedKey {
63    /// BIP 39 などのシードからルート `m` を作る。
64    pub fn from_seed(seed: &[u8]) -> Self {
65        Self::from_hmac(CURVE, seed)
66    }
67
68    /// 子を導出する。
69    pub fn derive(&self, index: u32) -> Self {
70        let mut data = Zeroizing::new([0; 1 + 32 + 4]);
71        data[1..33].copy_from_slice(&*self.private_key);
72        data[33..].copy_from_slice(&(index | HARDENED).to_be_bytes());
73        Self::from_hmac(&*self.chain_code, &*data)
74    }
75
76    /// 番号を順にたどって子孫を導出する。
77    pub fn derive_path(&self, path: &[u32]) -> Self {
78        path.iter()
79            .fold(self.clone(), |node, &index| node.derive(index))
80    }
81
82    pub fn private_key(&self) -> PrivateKey {
83        PrivateKey::from_bytes(&self.private_key)
84    }
85
86    /// HMAC-SHA512 の前半を秘密鍵に、後半をチェーンコードにする。
87    fn from_hmac(key: &[u8], data: &[u8]) -> Self {
88        let mut mac = Hmac::<Sha512>::new_from_slice(key).expect("HMAC takes a key of any length");
89        mac.update(data);
90        let mut output = Zeroizing::new([0; 64]);
91        mac.finalize_into(
92            (&mut output[..])
93                .try_into()
94                .expect("SHA-512 outputs 64 bytes"),
95        );
96        let mut private_key = Zeroizing::new([0; 32]);
97        let mut chain_code = Zeroizing::new([0; 32]);
98        private_key.copy_from_slice(&output[..32]);
99        chain_code.copy_from_slice(&output[32..]);
100        Self {
101            private_key,
102            chain_code,
103        }
104    }
105}
106
107impl std::fmt::Debug for ExtendedKey {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str("ExtendedKey(..)")
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use heika_core::key::PublicKey;
117
118    // SLIP-10 の文書にある ed25519 のテストベクター 1
119    const SEED: [u8; 16] = [
120        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
121        0x0F,
122    ];
123
124    fn assert_keys(key: &ExtendedKey, private_key: &str, public_key: &str) {
125        let private = key.private_key();
126        assert_eq!(*private.to_hex(), private_key);
127        assert_eq!(
128            PublicKey::from_private_key(&private).to_string(),
129            public_key
130        );
131    }
132
133    #[test]
134    fn derives_the_root_from_the_seed() {
135        assert_keys(
136            &ExtendedKey::from_seed(&SEED),
137            "2B4BE7F19EE27BBF30C667B642D5F4AA69FD169872F8FC3059C08EBAE2EB19E7",
138            "A4B2856BFEC510ABAB89753FAC1AC0E1112364E7D250545963F135F2A33188ED",
139        );
140    }
141
142    #[test]
143    fn derives_hardened_children() {
144        let root = ExtendedKey::from_seed(&SEED);
145        assert_keys(
146            &root.derive(0),
147            "68E0FE46DFB67E368C75379ACEC591DAD19DF3CDE26E63B93A8E704F1DADE7A3",
148            "8C8A13DF77A28F3445213A0F432FDE644ACAA215FC72DCDF300D5EFAA85D350C",
149        );
150        assert_keys(
151            &root.derive_path(&[0, 1]),
152            "B1D0BAD404BF35DA785A64CA1AC54B2617211D2777696FBFFAF208F746AE84F2",
153            "1932A5270F335BED617D5B935C80AEDB1A35BD9FC1E31ACAFD5372C30F5C1187",
154        );
155    }
156
157    #[test]
158    fn treats_indices_with_the_hardened_bit_the_same() {
159        let root = ExtendedKey::from_seed(&SEED);
160        assert_eq!(
161            *root.derive(0x8000_0001).private_key().to_hex(),
162            *root.derive(1).private_key().to_hex()
163        );
164    }
165
166    #[test]
167    fn empty_path_is_the_node_itself() {
168        let root = ExtendedKey::from_seed(&SEED);
169        assert_eq!(
170            *root.derive_path(&[]).private_key().to_hex(),
171            *root.private_key().to_hex()
172        );
173    }
174
175    #[test]
176    fn symbol_path_uses_the_coin_type_of_the_network() {
177        assert_eq!(
178            symbol_path(NetworkIdentifier::MAINNET, 2),
179            [44, 4343, 2, 0, 0]
180        );
181        assert_eq!(symbol_path(NetworkIdentifier::TESTNET, 2), [44, 1, 2, 0, 0]);
182    }
183
184    #[test]
185    fn debug_hides_the_key() {
186        assert_eq!(
187            format!("{:?}", ExtendedKey::from_seed(&SEED)),
188            "ExtendedKey(..)"
189        );
190    }
191}