iop_keyvault/cc.rs
1use super::*;
2
3/// Size of the chain code in bytes
4pub const CHAIN_CODE_SIZE: usize = 32;
5
6/// Chain code for key derivation in extended private and public keys.
7/// This is a 256-bit secret key that is completely independent of the private
8/// key and is used as an extension to the cryptographic domain, basically an
9/// extra state during iteration.
10#[derive(Clone)]
11pub struct ChainCode([u8; CHAIN_CODE_SIZE]);
12
13impl ChainCode {
14 /// The chain code serialized in a format that can be fed to [`from_bytes`]
15 ///
16 /// [`from_bytes`]: #method.from_bytes
17 pub fn to_bytes(&self) -> [u8; CHAIN_CODE_SIZE] {
18 self.0
19 }
20
21 /// Creates a chain code from a byte slice possibly returned by the [`to_bytes`] method.
22 ///
23 /// # Error
24 /// If `bytes` is not [`CHAIN_CODE_SIZE`] long
25 ///
26 /// [`to_bytes`]: #method.to_bytes
27 /// [`CHAIN_CODE_SIZE`]: ../constant.CHAIN_CODE_SIZE
28 pub fn from_bytes<D: AsRef<[u8]>>(bytes: D) -> Result<Self> {
29 let bytes = bytes.as_ref();
30 ensure! {
31 bytes.len() == CHAIN_CODE_SIZE,
32 "Chain code length is not {}",
33 CHAIN_CODE_SIZE
34 }
35 let mut cc = [0u8; CHAIN_CODE_SIZE];
36 cc.copy_from_slice(bytes);
37 Ok(Self(cc))
38 }
39}