1use 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;
15const CURVE: &[u8] = b"ed25519 seed";
17
18pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum HarvestRole {
35 Remote = 1,
37 Vrf = 2,
39}
40
41pub 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#[derive(Clone)]
57pub struct ExtendedKey {
58 private_key: Zeroizing<[u8; 32]>,
59 chain_code: Zeroizing<[u8; 32]>,
60}
61
62impl ExtendedKey {
63 pub fn from_seed(seed: &[u8]) -> Self {
65 Self::from_hmac(CURVE, seed)
66 }
67
68 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 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 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 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}