Skip to main content

fedimint_walletv2_common/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::must_use_candidate)]
6#![allow(clippy::return_self_not_must_use)]
7
8use std::collections::BTreeMap;
9use std::time::Duration;
10
11use bitcoin::hashes::{Hash, hash160, sha256};
12use bitcoin::key::TapTweak;
13use bitcoin::{Address, PubkeyHash, ScriptBuf, ScriptHash, Txid, WPubkeyHash, WScriptHash};
14use config::WalletClientConfig;
15pub use fedimint_core::config::ExcessiveRelativeFeeError;
16use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind};
17use fedimint_core::encoding::{Decodable, Encodable};
18use fedimint_core::module::{CommonModuleInit, ModuleCommon, ModuleConsensusVersion};
19use fedimint_core::{
20    NumPeersExt, PeerId, extensible_associated_module_type, plugin_types_trait_impl_common,
21};
22use miniscript::descriptor::Wsh;
23use secp256k1::ecdsa::Signature;
24use secp256k1::{PublicKey, Scalar, SecretKey, XOnlyPublicKey};
25use serde::{Deserialize, Serialize};
26use thiserror::Error;
27
28pub mod config;
29pub mod endpoint_constants;
30
31#[cfg(test)]
32mod tests;
33
34pub const KIND: ModuleKind = ModuleKind::from_static_str("walletv2");
35
36pub const MODULE_CONSENSUS_VERSION: ModuleConsensusVersion = ModuleConsensusVersion::new(1, 0);
37
38/// Number of confirmations required for a transaction to be considered as
39/// final by the federation. The block that mines the transaction does
40/// not count towards the number of confirmations.
41pub const CONFIRMATION_FINALITY_DELAY: u64 = 6;
42
43/// How many blocks a peer's block count vote trails its bitcoin backend: the
44/// finality delay, plus one block of slack. Processing a new consensus block
45/// count waits for the local backend to report the consensus count plus the
46/// finality delay, and without the slack that is exactly the block the voter
47/// saw, so a backend a little behind, or a backend status that is stale (it is
48/// polled once a minute), stalled item processing on every new block.
49///
50/// Lives here rather than in the server so that the client can tell how deep a
51/// peg-in has to be before the federation claims it.
52pub const BLOCK_COUNT_VOTE_DELAY: u64 = CONFIRMATION_FINALITY_DELAY + 1;
53
54/// Returns a sleep duration of 1 second in test environments or 60 seconds in
55/// production. Used for polling intervals where faster feedback is needed
56/// during testing.
57pub fn sleep_duration() -> Duration {
58    if fedimint_core::envs::is_running_in_test_env!() {
59        Duration::from_secs(1)
60    } else {
61        Duration::from_mins(1)
62    }
63}
64
65pub fn descriptor(pks: &BTreeMap<PeerId, PublicKey>, tweak: &sha256::Hash) -> Wsh<PublicKey> {
66    let scalar = Scalar::from_be_bytes(tweak.to_byte_array()).expect("Hash is within field order");
67    // Every guardian key is tweaked by the same point t*G. Compute it once
68    // instead of repeating the scalar multiplication for each guardian on every
69    // candidate in the client's probabilistic address search.
70    // Zero is a valid additive tweak, but cannot be represented as a public key.
71    let tweak_pk = (scalar != Scalar::ZERO).then(|| {
72        PublicKey::from_secret_key(
73            secp256k1::SECP256K1,
74            &SecretKey::from_slice(&tweak.to_byte_array()).expect("Nonzero scalar is a valid key"),
75        )
76    });
77
78    Wsh::new_sortedmulti(
79        pks.to_num_peers().threshold(),
80        pks.values()
81            .map(|pk| {
82                tweak_pk.map_or(*pk, |tweak_pk| {
83                    pk.combine(&tweak_pk)
84                        .expect("Failed to tweak bitcoin public key")
85                })
86            })
87            .collect::<Vec<PublicKey>>(),
88    )
89    .expect("Failed to construct Descriptor")
90}
91
92pub fn tweak_public_key(pk: &PublicKey, tweak: &sha256::Hash) -> PublicKey {
93    pk.add_exp_tweak(
94        secp256k1::SECP256K1,
95        &Scalar::from_be_bytes(tweak.to_byte_array()).expect("Hash is within field order"),
96    )
97    .expect("Failed to tweak bitcoin public key")
98}
99
100/// Returns true if the script pubkey potentially belongs to the federation.
101/// This uses a probabilistic filter - only ~1/65536 of P2WSH scripts pass.
102pub fn is_potential_receive(script_pubkey: &ScriptBuf, pks_hash: &sha256::Hash) -> bool {
103    (script_pubkey, pks_hash)
104        .consensus_hash::<sha256::Hash>()
105        .to_byte_array()
106        .iter()
107        .take(2)
108        .all(|b| *b == 0)
109}
110
111#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encodable, Decodable)]
112pub struct FederationWallet {
113    pub value: bitcoin::Amount,
114    pub outpoint: bitcoin::OutPoint,
115    pub tweak: sha256::Hash,
116}
117
118#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encodable, Decodable)]
119pub struct TxInfo {
120    pub index: u64,
121    pub txid: bitcoin::Txid,
122    pub input: bitcoin::Amount,
123    pub output: bitcoin::Amount,
124    pub fee: bitcoin::Amount,
125    pub vbytes: u64,
126    pub created: u64,
127}
128
129impl TxInfo {
130    pub fn feerate(&self) -> u64 {
131        self.fee.to_sat() / self.vbytes
132    }
133}
134
135#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
136pub struct OutputInfo {
137    pub index: u64,
138    pub script: ScriptBuf,
139    pub value: bitcoin::Amount,
140    pub spent: bool,
141    pub outpoint: Option<bitcoin::OutPoint>,
142}
143
144/// An output passing the probabilistic receive filter that a guardian can see,
145/// but which is not yet deep enough to have entered the federation's consensus
146/// output log.
147///
148/// This is advisory, non-consensus data: it is derived from a single guardian's
149/// local view of the chain and its mempool, and may be revoked by a reorg, an
150/// eviction or a replacement. It exists purely so a client can show a peg-in's
151/// progress instead of nothing at all while it waits out the module's
152/// confirmation finality delay.
153#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
154pub struct PendingOutput {
155    pub script: ScriptBuf,
156    pub outpoint: bitcoin::OutPoint,
157    pub value: bitcoin::Amount,
158    /// Height of the block that mined this output, or `None` while it is only
159    /// in the guardian's mempool.
160    ///
161    /// A mempool output is the weakest signal the federation offers: it is not
162    /// mined, not final, and can vanish entirely. Only guardians whose bitcoin
163    /// backend can enumerate a mempool report these at all.
164    pub height: Option<u64>,
165}
166
167/// A guardian's local, advisory view of the receive outputs it can see but the
168/// federation has not recorded yet, together with the block count that view was
169/// derived from.
170///
171/// Two kinds of output land here: candidates sitting in the guardian's mempool,
172/// and the receive outputs of the handful of blocks below its local chain tip.
173/// That block window is measured against the guardian's own tip rather than the
174/// consensus block count, so an output keeps being reported for a while *after*
175/// it becomes final - deliberately, so that a progress display does not blank
176/// out in the gap between finality and the claim landing. Presence here
177/// therefore does not mean a deposit is still unclaimed.
178///
179/// The block count is returned alongside the outputs so that a client computes
180/// confirmations against a single consistent view rather than mixing a height
181/// from one guardian with a chain tip from another.
182#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
183pub struct PendingOutputs {
184    /// The responding guardian's local block count, or `None` before the first
185    /// successful scan or while its bitcoin backend is unavailable.
186    ///
187    /// The API retains its numeric wire format: `None` is encoded as `0` and
188    /// nonzero counts as numbers. This is not a freshness or finality
189    /// guarantee.
190    /// A `Some(0)` also encodes as `0` and decodes as `None`.
191    ///
192    /// A mined output's confirmations are `block_count - height`, which counts
193    /// the block that mined it as the first confirmation. Note this is offset
194    /// by one from [`BLOCK_COUNT_VOTE_DELAY`], which does not count the mining
195    /// block, so a peg-in becomes claimable at `BLOCK_COUNT_VOTE_DELAY + 1`
196    /// confirmations.
197    #[serde(
198        serialize_with = "serialize_pending_block_count",
199        deserialize_with = "deserialize_pending_block_count"
200    )]
201    pub block_count: Option<u64>,
202    pub outputs: Vec<PendingOutput>,
203    /// How much of its mempool this guardian inspected for these outputs.
204    ///
205    /// Distinguishes "no unmined peg-ins" from "this guardian could not look",
206    /// which an esplora-backed guardian never can. Without it a client could
207    /// not tell an empty mempool from a blind guardian.
208    pub mempool_visibility: MempoolVisibility,
209}
210
211// Serde's field serializer requires a reference to the field.
212#[allow(clippy::ref_option)]
213fn serialize_pending_block_count<S: serde::Serializer>(
214    block_count: &Option<u64>,
215    serializer: S,
216) -> Result<S::Ok, S::Error> {
217    block_count.unwrap_or(0).serialize(serializer)
218}
219
220fn deserialize_pending_block_count<'de, D: serde::Deserializer<'de>>(
221    deserializer: D,
222) -> Result<Option<u64>, D::Error> {
223    u64::deserialize(deserializer).map(|count| (count != 0).then_some(count))
224}
225
226/// How much of a mempool was inspected for unmined peg-ins.
227///
228/// Ordered from least to most visibility, so the best of several views is
229/// their maximum.
230#[derive(
231    Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
232)]
233pub enum MempoolVisibility {
234    /// Nothing unmined is reported, either because the backend cannot
235    /// enumerate a mempool (as esplora never can), because the mempool scan is
236    /// turned off, or because listing the mempool failed.
237    #[default]
238    Unavailable,
239    /// The mempool was listed, but not all of its transactions were
240    /// inspected: either fetching some of them failed, or the scan ran out of
241    /// its time budget and is still working through them. The latter is
242    /// normal on a healthy backend while a large mempool is first scanned.
243    ///
244    /// Every unmined output reported is real, but the set may be short of
245    /// transactions the guardian has but has not inspected yet.
246    Partial,
247    /// Every transaction in the guardian's mempool was inspected, so a deposit
248    /// that is not reported had not reached this mempool when it was scanned.
249    ///
250    /// This describes one guardian's local snapshot, not the network: a
251    /// payment that is not reported may still have been broadcast and not
252    /// have propagated to this node yet.
253    Complete,
254}
255
256#[derive(Debug)]
257pub struct WalletCommonInit;
258
259impl CommonModuleInit for WalletCommonInit {
260    const CONSENSUS_VERSION: ModuleConsensusVersion = MODULE_CONSENSUS_VERSION;
261    const KIND: ModuleKind = KIND;
262
263    type ClientConfig = WalletClientConfig;
264
265    fn decoder() -> Decoder {
266        WalletModuleTypes::decoder()
267    }
268}
269
270pub struct WalletModuleTypes;
271
272plugin_types_trait_impl_common!(
273    KIND,
274    WalletModuleTypes,
275    WalletClientConfig,
276    WalletInput,
277    WalletOutput,
278    WalletOutputOutcome,
279    WalletConsensusItem,
280    WalletInputError,
281    WalletOutputError
282);
283
284#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
285pub enum WalletConsensusItem {
286    BlockCount(u64),
287    Feerate(Option<u64>),
288    Signatures(Txid, Vec<Signature>),
289    #[encodable_default]
290    Default {
291        variant: u64,
292        bytes: Vec<u8>,
293    },
294}
295
296impl std::fmt::Display for WalletConsensusItem {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        match self {
299            WalletConsensusItem::BlockCount(count) => {
300                write!(f, "Wallet Block Count {count}")
301            }
302            WalletConsensusItem::Feerate(feerate) => {
303                write!(f, "Wallet Feerate Vote {feerate:?}")
304            }
305            WalletConsensusItem::Signatures(..) => {
306                write!(f, "Wallet Signatures")
307            }
308            WalletConsensusItem::Default { variant, .. } => {
309                write!(f, "Unknown Wallet CI variant={variant}")
310            }
311        }
312    }
313}
314
315extensible_associated_module_type!(WalletInput, WalletInputV0, UnknownWalletInputVariantError);
316
317#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
318pub struct WalletInputV0 {
319    pub output_index: u64,
320    pub tweak: PublicKey,
321    pub fee: bitcoin::Amount,
322}
323
324impl std::fmt::Display for WalletInputV0 {
325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326        write!(f, "Wallet PegIn for output index {}", self.output_index)
327    }
328}
329
330extensible_associated_module_type!(
331    WalletOutput,
332    WalletOutputV0,
333    UnknownWalletOutputVariantError
334);
335
336#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
337pub struct WalletOutputV0 {
338    pub destination: StandardScript,
339    pub value: bitcoin::Amount,
340    pub fee: bitcoin::Amount,
341}
342
343impl std::fmt::Display for WalletOutputV0 {
344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345        write!(f, "Wallet PegOut {}", self.value)
346    }
347}
348
349#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
350pub struct WalletOutputOutcome;
351
352impl std::fmt::Display for WalletOutputOutcome {
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354        write!(f, "Wallet Output Outcome")
355    }
356}
357
358#[derive(Debug, Error, Encodable, Decodable, Hash, Clone, Eq, PartialEq)]
359pub enum WalletInputError {
360    #[error("The wallet input version is not supported by this federation")]
361    UnknownInputVariant(#[from] UnknownWalletInputVariantError),
362    #[error("The output has already been claimed")]
363    OutputAlreadySpent,
364    #[error("Unknown output index")]
365    UnknownOutputIndex,
366    #[error("The tweak does not match the output script")]
367    WrongTweak,
368    #[error("No up to date feerate is available at the moment. Please try again later.")]
369    NoConsensusFeerateAvailable,
370    #[error("The total transaction fee is too low. Please construct a new transaction.")]
371    InsufficientTotalFee,
372    #[error("Constructing the pegin transaction caused an arithmetic overflow")]
373    ArithmeticOverflow,
374}
375
376#[derive(Debug, Error, Encodable, Decodable, Hash, Clone, Eq, PartialEq)]
377pub enum WalletOutputError {
378    #[error("The wallet output version is not supported by this federation")]
379    UnknownOutputVariant(#[from] UnknownWalletOutputVariantError),
380    #[error("The output value is below the dust limit.")]
381    UnderDustLimit,
382    #[error("The federation does not have any funds yet")]
383    NoFederationUTXO,
384    #[error("No up to date feerate is available at the moment. Please try again later.")]
385    NoConsensusFeerateAvailable,
386    #[error("The total transaction fee is too low. Please construct a new transaction.")]
387    InsufficientTotalFee,
388    #[error("The change value is below the dust limit.")]
389    ChangeUnderDustLimit,
390    #[error("Constructing the pegout transaction caused an arithmetic overflow")]
391    ArithmeticOverflow,
392    #[error("Unknown script variant")]
393    UnknownScriptVariant,
394}
395
396#[derive(Debug, Clone, Eq, PartialEq, Hash, Encodable, Decodable, Serialize, Deserialize)]
397pub enum StandardScript {
398    P2PKH(hash160::Hash),
399    P2SH(hash160::Hash),
400    P2WPKH(hash160::Hash),
401    P2WSH(sha256::Hash),
402    P2TR(XOnlyPublicKey),
403    #[encodable_default]
404    Default {
405        variant: u64,
406        bytes: Vec<u8>,
407    },
408}
409
410impl StandardScript {
411    pub fn from_address(address: &Address) -> Option<Self> {
412        if let Some(hash) = address.pubkey_hash() {
413            return Some(StandardScript::P2PKH(hash.to_raw_hash()));
414        }
415
416        if let Some(hash) = address.script_hash() {
417            return Some(StandardScript::P2SH(hash.to_raw_hash()));
418        }
419
420        let program = address.witness_program()?;
421
422        if program.is_p2wpkh() {
423            return Some(StandardScript::P2WPKH(
424                hash160::Hash::from_slice(program.program().as_bytes())
425                    .expect("Witness program is 20 bytes"),
426            ));
427        }
428
429        if program.is_p2wsh() {
430            return Some(StandardScript::P2WSH(
431                sha256::Hash::from_slice(program.program().as_bytes())
432                    .expect("Witness program is 32 bytes"),
433            ));
434        }
435
436        if program.is_p2tr() {
437            return Some(StandardScript::P2TR(
438                XOnlyPublicKey::from_slice(program.program().as_bytes())
439                    .expect("Witness program is 32 bytes"),
440            ));
441        }
442
443        None
444    }
445
446    pub fn script_pubkey(&self) -> Option<ScriptBuf> {
447        match self {
448            Self::P2PKH(hash) => Some(ScriptBuf::new_p2pkh(&PubkeyHash::from_raw_hash(*hash))),
449            Self::P2SH(hash) => Some(ScriptBuf::new_p2sh(&ScriptHash::from_raw_hash(*hash))),
450            Self::P2WPKH(hash) => Some(ScriptBuf::new_p2wpkh(&WPubkeyHash::from_raw_hash(*hash))),
451            Self::P2WSH(hash) => Some(ScriptBuf::new_p2wsh(&WScriptHash::from_raw_hash(*hash))),
452            Self::P2TR(pk) => Some(ScriptBuf::new_p2tr_tweaked(pk.dangerous_assume_tweaked())),
453            Self::Default { .. } => None,
454        }
455    }
456}
457
458#[cfg(test)]
459fn assert_standard_script_roundtrip(addr: &str, variant: fn(&StandardScript) -> bool) {
460    let address = addr
461        .parse::<bitcoin::Address<bitcoin::address::NetworkUnchecked>>()
462        .expect("Failed to parse address")
463        .require_network(bitcoin::Network::Bitcoin)
464        .expect("Wrong network");
465
466    let script = StandardScript::from_address(&address)
467        .expect("Failed to convert address to StandardScript");
468
469    assert!(variant(&script), "Unexpected StandardScript variant");
470
471    assert_eq!(Some(address.script_pubkey()), script.script_pubkey());
472}
473
474#[test]
475fn test_standard_script_p2pkh() {
476    assert_standard_script_roundtrip("1QJVDzdqb1VpbDK7uDeyVXy9mR27CJiyhY", |s| {
477        matches!(s, StandardScript::P2PKH(..))
478    });
479}
480
481#[test]
482fn test_standard_script_p2sh() {
483    assert_standard_script_roundtrip("33iFwdLuRpW1uK1RTRqsoi8rR4NpDzk66k", |s| {
484        matches!(s, StandardScript::P2SH(..))
485    });
486}
487
488#[test]
489fn test_standard_script_p2wpkh() {
490    assert_standard_script_roundtrip("bc1qvzvkjn4q3nszqxrv3nraga2r822xjty3ykvkuw", |s| {
491        matches!(s, StandardScript::P2WPKH(..))
492    });
493}
494
495#[test]
496fn test_standard_script_p2wsh() {
497    assert_standard_script_roundtrip(
498        "bc1qwqdg6squsna38e46795at95yu9atm8azzmyvckulcc7kytlcckxswvvzej",
499        |s| matches!(s, StandardScript::P2WSH(..)),
500    );
501}
502
503#[test]
504fn test_standard_script_p2tr() {
505    assert_standard_script_roundtrip(
506        "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr",
507        |s| matches!(s, StandardScript::P2TR(..)),
508    );
509}
510
511#[test]
512fn test_standard_script_unknown_witness_version() {
513    let address = "bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y"
514        .parse::<bitcoin::Address<bitcoin::address::NetworkUnchecked>>()
515        .expect("Failed to parse address")
516        .require_network(bitcoin::Network::Bitcoin)
517        .expect("Wrong network");
518
519    assert!(StandardScript::from_address(&address).is_none());
520}