Skip to main content

fedimint_client_module/
secret.rs

1use std::fmt::Debug;
2use std::io::{Read, Write};
3
4use fedimint_core::config::FederationId;
5use fedimint_core::core::{Account, ModuleInstanceId};
6use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
7use fedimint_core::module::registry::ModuleRegistry;
8use fedimint_derive_secret::{ChildId, DerivableSecret};
9use rand::{CryptoRng, Rng, RngCore};
10
11// Derived from pre-root-secret (pre-federation-derived)
12const TYPE_PRE_ROOT_SECRET_HASH: ChildId = ChildId(0);
13
14// Derived from federation-root-secret
15const TYPE_MODULE: ChildId = ChildId(0);
16const TYPE_BACKUP: ChildId = ChildId(1);
17
18// Derived from a module-root-secret, to namespace the non-primary accounts.
19//
20// Sits far above anything a module derives at that level, so an account
21// subtree can never collide with a module's own children: mintv2 derives
22// `ChildId(denomination)` with denomination a `u8`, lnv2 derives `ChildId(0)`
23// and `ChildId(1)`, and walletv2 derives `ChildId(address_index)` counting up
24// from zero one address at a time.
25const TYPE_ACCOUNT: ChildId = ChildId(0xACC0_0000_0000_0000);
26
27pub trait DeriveableSecretClientExt {
28    fn derive_module_secret(&self, module_instance_id: ModuleInstanceId) -> DerivableSecret;
29    fn derive_backup_secret(&self) -> DerivableSecret;
30    fn derive_pre_root_secret_hash(&self) -> [u8; 8];
31    fn derive_account_secret(&self, account: Account) -> DerivableSecret;
32}
33
34impl DeriveableSecretClientExt for DerivableSecret {
35    fn derive_module_secret(&self, module_instance_id: ModuleInstanceId) -> DerivableSecret {
36        assert_eq!(self.level(), 0);
37        self.child_key(TYPE_MODULE)
38            .child_key(ChildId(u64::from(module_instance_id)))
39    }
40
41    fn derive_backup_secret(&self) -> DerivableSecret {
42        assert_eq!(self.level(), 0);
43        self.child_key(TYPE_BACKUP)
44    }
45
46    /// Account-scoped root, to be called on a module root secret.
47    ///
48    /// [`Account::Primary`] returns the module root unchanged, so every path a
49    /// released client has already derived stays bit-for-bit what it was and
50    /// no existing wallet's money moves. That costs the tree its uniformity —
51    /// this is a `match` where every other hop is just a hop — and the
52    /// alternative was to re-key every client in the field.
53    fn derive_account_secret(&self, account: Account) -> DerivableSecret {
54        if account == Account::Primary {
55            return self.clone();
56        }
57
58        self.child_key(TYPE_ACCOUNT)
59            .child_key(ChildId(u64::from(account.index())))
60    }
61
62    fn derive_pre_root_secret_hash(&self) -> [u8; 8] {
63        // Note: this hash is derived from a pre-root-secret: one passed from the
64        // outside, before the federation ID is used to derive the
65        // federation-specific-root-secret, which gets level reset to 0.
66        // Because of that we don't care about asserting the level.
67        self.child_key(TYPE_PRE_ROOT_SECRET_HASH).to_random_bytes()
68    }
69}
70
71/// Trait defining a way to generate, serialize and deserialize a root secret.
72/// It defines a `Encoding` associated type which represents a specific
73/// representation of a secret (e.g. a bip39, slip39, CODEX32, … struct) and
74/// then defines the methods necessary for the client to interact with it.
75///
76/// We use a strategy pattern (i.e. implementing the trait on a zero sized type
77/// with the actual secret struct as an associated type instead of implementing
78/// the necessary functions directly on the secret struct) to allow external
79/// implementations on third-party types without wrapping them in newtypes.
80pub trait RootSecretStrategy: Debug {
81    /// Type representing the secret
82    type Encoding: Clone;
83
84    /// Conversion function from the external encoding to the internal one
85    fn to_root_secret(secret: &Self::Encoding) -> DerivableSecret;
86
87    /// Serialization function for the external encoding
88    fn consensus_encode(
89        secret: &Self::Encoding,
90        writer: &mut impl std::io::Write,
91    ) -> std::io::Result<()>;
92
93    /// Deserialization function for the external encoding
94    fn consensus_decode_partial(
95        reader: &mut impl std::io::Read,
96    ) -> Result<Self::Encoding, DecodeError>;
97
98    /// Random generation function for the external secret type
99    fn random<R>(rng: &mut R) -> Self::Encoding
100    where
101        R: rand::RngCore + rand::CryptoRng;
102}
103
104/// Just uses 64 random bytes and derives the secret from them
105#[derive(Debug)]
106pub struct PlainRootSecretStrategy;
107
108impl RootSecretStrategy for PlainRootSecretStrategy {
109    type Encoding = [u8; 64];
110
111    fn to_root_secret(secret: &Self::Encoding) -> DerivableSecret {
112        const FEDIMINT_CLIENT_NONCE: &[u8] = b"Fedimint Client Salt";
113        DerivableSecret::new_root(secret.as_ref(), FEDIMINT_CLIENT_NONCE)
114    }
115
116    fn consensus_encode(secret: &Self::Encoding, writer: &mut impl Write) -> std::io::Result<()> {
117        secret.consensus_encode(writer)
118    }
119
120    fn consensus_decode_partial(reader: &mut impl Read) -> Result<Self::Encoding, DecodeError> {
121        Self::Encoding::consensus_decode_partial(reader, &ModuleRegistry::default())
122    }
123
124    fn random<R>(rng: &mut R) -> Self::Encoding
125    where
126        R: RngCore + CryptoRng,
127    {
128        let mut secret = [0u8; 64];
129        rng.fill(&mut secret);
130        secret
131    }
132}
133
134/// Convenience function to derive fedimint-client root secret
135/// using the default (0) wallet number, given a global root secret
136/// that's managed externally by a consumer of fedimint-client.
137///
138/// See docs/secret_derivation.md
139///
140/// `global_root_secret/<key-type=per-federation=0>/<federation-id>/
141/// <wallet-number=0>/<key-type=fedimint-client=0>`
142pub fn get_default_client_secret(
143    global_root_secret: &DerivableSecret,
144    federation_id: &FederationId,
145) -> DerivableSecret {
146    let multi_federation_root_secret = global_root_secret.child_key(ChildId(0));
147    let federation_root_secret = multi_federation_root_secret.federation_key(federation_id);
148    let federation_wallet_root_secret = federation_root_secret.child_key(ChildId(0)); // wallet-number=0
149    federation_wallet_root_secret.child_key(ChildId(0)) // key-type=fedimint-client=0
150}