fedimint_wallet_common/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#![deny(clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::return_self_not_must_use)]

use std::hash::Hasher;

use bitcoin::address::NetworkUnchecked;
use bitcoin::psbt::raw::ProprietaryKey;
use bitcoin::{secp256k1, Address, Amount, BlockHash, TxOut, Txid};
use config::WalletClientConfig;
use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind};
use fedimint_core::encoding::btc::NetworkLegacyEncodingWrapper;
use fedimint_core::encoding::{Decodable, Encodable};
use fedimint_core::module::{CommonModuleInit, ModuleCommon, ModuleConsensusVersion};
use fedimint_core::{extensible_associated_module_type, plugin_types_trait_impl_common, Feerate};
use impl_tools::autoimpl;
use miniscript::Descriptor;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::error;

use crate::keys::CompressedPublicKey;
use crate::txoproof::{PegInProof, PegInProofError};

pub mod config;
pub mod endpoint_constants;
pub mod envs;
pub mod keys;
pub mod tweakable;
pub mod txoproof;

pub const KIND: ModuleKind = ModuleKind::from_static_str("wallet");
pub const MODULE_CONSENSUS_VERSION: ModuleConsensusVersion = ModuleConsensusVersion::new(2, 2);

/// Used for estimating a feerate that will confirm within a target number of
/// blocks.
///
/// Since the wallet's UTXOs are a shared resource, we need to reduce the risk
/// of a peg-out transaction getting stuck in the mempool, hence we use a low
/// confirmation target. Other fee bumping techniques, such as RBF and CPFP, can
/// help mitigate this problem but are out-of-scope for this version of the
/// wallet.
pub const CONFIRMATION_TARGET: u16 = 1;

/// To further mitigate the risk of a peg-out transaction getting stuck in the
/// mempool, we multiply the feerate estimate returned from the backend by this
/// value.
pub const FEERATE_MULTIPLIER: u64 = 4;

pub type PartialSig = Vec<u8>;

pub type PegInDescriptor = Descriptor<CompressedPublicKey>;

#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
pub enum WalletConsensusItem {
    BlockCount(u32), /* FIXME: use block hash instead, but needs more complicated
                      * * verification logic */
    Feerate(Feerate),
    PegOutSignature(PegOutSignatureItem),
    ModuleConsensusVersion(ModuleConsensusVersion),
    #[encodable_default]
    Default {
        variant: u64,
        bytes: Vec<u8>,
    },
}

impl std::fmt::Display for WalletConsensusItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WalletConsensusItem::BlockCount(count) => {
                write!(f, "Wallet Block Count {count}")
            }
            WalletConsensusItem::Feerate(feerate) => {
                write!(
                    f,
                    "Wallet Feerate with sats per kvb {}",
                    feerate.sats_per_kvb
                )
            }
            WalletConsensusItem::PegOutSignature(sig) => {
                write!(f, "Wallet PegOut signature for Bitcoin TxId {}", sig.txid)
            }
            WalletConsensusItem::ModuleConsensusVersion(version) => {
                write!(
                    f,
                    "Wallet Consensus Version {}.{}",
                    version.major, version.minor
                )
            }
            WalletConsensusItem::Default { variant, .. } => {
                write!(f, "Unknown Wallet CI variant={variant}")
            }
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Encodable, Decodable)]
pub struct PegOutSignatureItem {
    pub txid: Txid,
    pub signature: Vec<secp256k1::ecdsa::Signature>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encodable, Decodable)]
pub struct SpendableUTXO {
    #[serde(with = "::fedimint_core::encoding::as_hex")]
    pub tweak: [u8; 33],
    #[serde(with = "bitcoin::amount::serde::as_sat")]
    pub amount: bitcoin::Amount,
}

/// A transaction output, either unspent or consumed
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct TxOutputSummary {
    pub outpoint: bitcoin::OutPoint,
    #[serde(with = "bitcoin::amount::serde::as_sat")]
    pub amount: bitcoin::Amount,
}

/// Summary of the coins within the wallet.
///
/// Coins within the wallet go from spendable, to consumed in a transaction that
/// does not have threshold signatures (unsigned), to threshold signed and
/// unconfirmed on-chain (unconfirmed).
///
/// This summary provides the most granular view possible of coins in the
/// wallet.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct WalletSummary {
    /// All UTXOs available as inputs for transactions
    pub spendable_utxos: Vec<TxOutputSummary>,
    /// Transaction outputs consumed in peg-out transactions that have not
    /// reached threshold signatures
    pub unsigned_peg_out_txos: Vec<TxOutputSummary>,
    /// Change UTXOs created from peg-out transactions that have not reached
    /// threshold signatures
    pub unsigned_change_utxos: Vec<TxOutputSummary>,
    /// Transaction outputs consumed in peg-out transactions that have reached
    /// threshold signatures waiting for finality delay confirmations
    pub unconfirmed_peg_out_txos: Vec<TxOutputSummary>,
    /// Change UTXOs created from peg-out transactions that have reached
    /// threshold signatures waiting for finality delay confirmations
    pub unconfirmed_change_utxos: Vec<TxOutputSummary>,
}

impl WalletSummary {
    fn sum<'a>(txos: impl Iterator<Item = &'a TxOutputSummary>) -> Amount {
        txos.fold(Amount::ZERO, |acc, txo| txo.amount + acc)
    }

    /// Total amount of all spendable UTXOs
    pub fn total_spendable_balance(&self) -> Amount {
        WalletSummary::sum(self.spendable_utxos.iter())
    }

    /// Total amount of all transaction outputs from peg-out transactions that
    /// have not reached threshold signatures
    pub fn total_unsigned_peg_out_balance(&self) -> Amount {
        WalletSummary::sum(self.unsigned_peg_out_txos.iter())
    }

    /// Total amount of all change UTXOs from peg-out transactions that have not
    /// reached threshold signatures
    pub fn total_unsigned_change_balance(&self) -> Amount {
        WalletSummary::sum(self.unsigned_change_utxos.iter())
    }

    /// Total amount of all transaction outputs from peg-out transactions that
    /// have reached threshold signatures waiting for finality delay
    /// confirmations
    pub fn total_unconfirmed_peg_out_balance(&self) -> Amount {
        WalletSummary::sum(self.unconfirmed_peg_out_txos.iter())
    }

    /// Total amount of all change UTXOs from peg-out transactions that have
    /// reached threshold signatures waiting for finality delay confirmations
    pub fn total_unconfirmed_change_balance(&self) -> Amount {
        WalletSummary::sum(self.unconfirmed_change_utxos.iter())
    }

    /// Total amount of all transaction outputs from peg-out transactions that
    /// are either waiting for threshold signatures or confirmations. This is
    /// the total in-flight amount leaving the wallet.
    pub fn total_pending_peg_out_balance(&self) -> Amount {
        self.total_unsigned_peg_out_balance() + self.total_unconfirmed_peg_out_balance()
    }

    /// Total amount of all change UTXOs from peg-out transactions that are
    /// either waiting for threshold signatures or confirmations. This is the
    /// total in-flight amount that will become spendable by the wallet.
    pub fn total_pending_change_balance(&self) -> Amount {
        self.total_unsigned_change_balance() + self.total_unconfirmed_change_balance()
    }

    /// Total amount of immediately spendable UTXOs and pending change UTXOs.
    /// This is the spendable balance once all transactions confirm.
    pub fn total_owned_balance(&self) -> Amount {
        self.total_spendable_balance() + self.total_pending_change_balance()
    }

    /// All transaction outputs from peg-out transactions that are either
    /// waiting for threshold signatures or confirmations. These are all the
    /// in-flight coins leaving the wallet.
    pub fn pending_peg_out_txos(&self) -> Vec<TxOutputSummary> {
        self.unsigned_peg_out_txos
            .clone()
            .into_iter()
            .chain(self.unconfirmed_peg_out_txos.clone())
            .collect()
    }

    /// All change UTXOs from peg-out transactions that are either waiting for
    /// threshold signatures or confirmations. These are all the in-flight coins
    /// that will become spendable by the wallet.
    pub fn pending_change_utxos(&self) -> Vec<TxOutputSummary> {
        self.unsigned_change_utxos
            .clone()
            .into_iter()
            .chain(self.unconfirmed_change_utxos.clone())
            .collect()
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct PegOutFees {
    pub fee_rate: Feerate,
    pub total_weight: u64,
}

impl PegOutFees {
    pub fn new(sats_per_kvb: u64, total_weight: u64) -> Self {
        PegOutFees {
            fee_rate: Feerate { sats_per_kvb },
            total_weight,
        }
    }

    pub fn amount(&self) -> Amount {
        self.fee_rate.calculate_fee(self.total_weight)
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct PegOut {
    pub recipient: Address<NetworkUnchecked>,
    #[serde(with = "bitcoin::amount::serde::as_sat")]
    pub amount: bitcoin::Amount,
    pub fees: PegOutFees,
}

extensible_associated_module_type!(
    WalletOutputOutcome,
    WalletOutputOutcomeV0,
    UnknownWalletOutputOutcomeVariantError
);

impl WalletOutputOutcome {
    pub fn new_v0(txid: bitcoin::Txid) -> WalletOutputOutcome {
        WalletOutputOutcome::V0(WalletOutputOutcomeV0(txid))
    }
}

/// Contains the Bitcoin transaction id of the transaction created by the
/// withdraw request
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct WalletOutputOutcomeV0(pub bitcoin::Txid);

impl std::fmt::Display for WalletOutputOutcomeV0 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Wallet PegOut Bitcoin TxId {}", self.0)
    }
}

#[derive(Debug)]
pub struct WalletCommonInit;

impl CommonModuleInit for WalletCommonInit {
    const CONSENSUS_VERSION: ModuleConsensusVersion = MODULE_CONSENSUS_VERSION;
    const KIND: ModuleKind = KIND;

    type ClientConfig = WalletClientConfig;

    fn decoder() -> Decoder {
        WalletModuleTypes::decoder()
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub enum WalletInput {
    V0(WalletInputV0),
    V1(WalletInputV1),
    #[encodable_default]
    Default {
        variant: u64,
        bytes: Vec<u8>,
    },
}

impl WalletInput {
    pub fn maybe_v0_ref(&self) -> Option<&WalletInputV0> {
        match self {
            WalletInput::V0(v0) => Some(v0),
            _ => None,
        }
    }
}

#[derive(
    Debug,
    thiserror::Error,
    Clone,
    Eq,
    PartialEq,
    Hash,
    serde::Deserialize,
    serde::Serialize,
    fedimint_core::encoding::Encodable,
    fedimint_core::encoding::Decodable,
)]
#[error("Unknown {} variant {variant}", stringify!($name))]
pub struct UnknownWalletInputVariantError {
    pub variant: u64,
}

impl std::fmt::Display for WalletInput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            WalletInput::V0(inner) => std::fmt::Display::fmt(&inner, f),
            WalletInput::V1(inner) => std::fmt::Display::fmt(&inner, f),
            WalletInput::Default { variant, .. } => {
                write!(f, "Unknown variant (variant={variant})")
            }
        }
    }
}

impl WalletInput {
    pub fn new_v0(peg_in_proof: PegInProof) -> WalletInput {
        WalletInput::V0(WalletInputV0(Box::new(peg_in_proof)))
    }

    pub fn new_v1(peg_in_proof: &PegInProof) -> WalletInput {
        WalletInput::V1(WalletInputV1 {
            outpoint: peg_in_proof.outpoint(),
            tweak_contract_key: *peg_in_proof.tweak_contract_key(),
            tx_out: peg_in_proof.tx_output(),
        })
    }
}

#[autoimpl(Deref, DerefMut using self.0)]
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct WalletInputV0(pub Box<PegInProof>);

#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct WalletInputV1 {
    pub outpoint: bitcoin::OutPoint,
    pub tweak_contract_key: secp256k1::PublicKey,
    pub tx_out: TxOut,
}

impl std::fmt::Display for WalletInputV0 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Wallet PegIn with Bitcoin TxId {}",
            self.0.outpoint().txid
        )
    }
}

impl std::fmt::Display for WalletInputV1 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Wallet PegIn V1 with TxId {}", self.outpoint.txid)
    }
}

extensible_associated_module_type!(
    WalletOutput,
    WalletOutputV0,
    UnknownWalletOutputVariantError
);

impl WalletOutput {
    pub fn new_v0_peg_out(
        recipient: Address,
        amount: bitcoin::Amount,
        fees: PegOutFees,
    ) -> WalletOutput {
        WalletOutput::V0(WalletOutputV0::PegOut(PegOut {
            recipient: recipient.into_unchecked(),
            amount,
            fees,
        }))
    }
    pub fn new_v0_rbf(fees: PegOutFees, txid: Txid) -> WalletOutput {
        WalletOutput::V0(WalletOutputV0::Rbf(Rbf { fees, txid }))
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub enum WalletOutputV0 {
    PegOut(PegOut),
    Rbf(Rbf),
}

/// Allows a user to bump the fees of a `PendingTransaction`
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct Rbf {
    /// Fees expressed as an increase over existing peg-out fees
    pub fees: PegOutFees,
    /// Bitcoin tx id to bump the fees for
    pub txid: Txid,
}

impl WalletOutputV0 {
    pub fn amount(&self) -> Amount {
        match self {
            WalletOutputV0::PegOut(pegout) => pegout.amount + pegout.fees.amount(),
            WalletOutputV0::Rbf(rbf) => rbf.fees.amount(),
        }
    }
}

impl std::fmt::Display for WalletOutputV0 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WalletOutputV0::PegOut(pegout) => {
                write!(
                    f,
                    "Wallet PegOut {} to {}",
                    pegout.amount,
                    pegout.recipient.clone().assume_checked()
                )
            }
            WalletOutputV0::Rbf(rbf) => write!(f, "Wallet RBF {:?} to {}", rbf.fees, rbf.txid),
        }
    }
}

pub struct WalletModuleTypes;

pub fn proprietary_tweak_key() -> ProprietaryKey {
    ProprietaryKey {
        prefix: b"fedimint".to_vec(),
        subtype: 0x00,
        key: vec![],
    }
}

impl std::hash::Hash for PegOutSignatureItem {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.txid.hash(state);
        for sig in &self.signature {
            sig.serialize_der().hash(state);
        }
    }
}

impl PartialEq for PegOutSignatureItem {
    fn eq(&self, other: &PegOutSignatureItem) -> bool {
        self.txid == other.txid && self.signature == other.signature
    }
}

impl Eq for PegOutSignatureItem {}

plugin_types_trait_impl_common!(
    KIND,
    WalletModuleTypes,
    WalletClientConfig,
    WalletInput,
    WalletOutput,
    WalletOutputOutcome,
    WalletConsensusItem,
    WalletInputError,
    WalletOutputError
);

#[derive(Debug, Error, Clone)]
pub enum WalletCreationError {
    #[error("Connected bitcoind is on wrong network, expected {0}, got {1}")]
    WrongNetwork(NetworkLegacyEncodingWrapper, NetworkLegacyEncodingWrapper),
    #[error("Error querying bitcoind: {0}")]
    RpcError(String),
    #[error("Feerate source error: {0}")]
    FeerateSourceError(String),
}

#[derive(Debug, Error, Encodable, Decodable, Hash, Clone, Eq, PartialEq)]
pub enum WalletInputError {
    #[error("Unknown block hash in peg-in proof: {0}")]
    UnknownPegInProofBlock(BlockHash),
    #[error("Invalid peg-in proof: {0}")]
    PegInProofError(#[from] PegInProofError),
    #[error("The peg-in was already claimed")]
    PegInAlreadyClaimed,
    #[error("The wallet input version is not supported by this federation")]
    UnknownInputVariant(#[from] UnknownWalletInputVariantError),
    #[error("Unknown UTXO")]
    UnknownUTXO,
    #[error("Wrong output script")]
    WrongOutputScript,
    #[error("Wrong tx out")]
    WrongTxOut,
}

#[derive(Debug, Error, Encodable, Decodable, Hash, Clone, Eq, PartialEq)]
pub enum WalletOutputError {
    #[error("Connected bitcoind is on wrong network, expected {0}, got {1}")]
    WrongNetwork(NetworkLegacyEncodingWrapper, NetworkLegacyEncodingWrapper),
    #[error("Peg-out fee rate {0:?} is set below consensus {1:?}")]
    PegOutFeeBelowConsensus(Feerate, Feerate),
    #[error("Not enough SpendableUTXO")]
    NotEnoughSpendableUTXO,
    #[error("Peg out amount was under the dust limit")]
    PegOutUnderDustLimit,
    #[error("RBF transaction id not found")]
    RbfTransactionIdNotFound,
    #[error("Peg-out fee weight {0} doesn't match actual weight {1}")]
    TxWeightIncorrect(u64, u64),
    #[error("Peg-out fee rate is below min relay fee")]
    BelowMinRelayFee,
    #[error("The wallet output version is not supported by this federation")]
    UnknownOutputVariant(#[from] UnknownWalletOutputVariantError),
}

// For backwards-compatibility with old clients, we use an UnknownOutputVariant
// error when a client attempts a deprecated RBF withdrawal.
// see: https://github.com/fedimint/fedimint/issues/5453
pub const DEPRECATED_RBF_ERROR: WalletOutputError =
    WalletOutputError::UnknownOutputVariant(UnknownWalletOutputVariantError { variant: 1 });

#[derive(Debug, Error)]
pub enum ProcessPegOutSigError {
    #[error("No unsigned transaction with id {0} exists")]
    UnknownTransaction(Txid),
    #[error("Expected {0} signatures, got {1}")]
    WrongSignatureCount(usize, usize),
    #[error("Bad Sighash")]
    SighashError,
    #[error("Malformed signature: {0}")]
    MalformedSignature(secp256k1::Error),
    #[error("Invalid signature")]
    InvalidSignature,
    #[error("Duplicate signature")]
    DuplicateSignature,
    #[error("Missing change tweak")]
    MissingOrMalformedChangeTweak,
    #[error("Error finalizing PSBT {0:?}")]
    ErrorFinalizingPsbt(Vec<miniscript::psbt::Error>),
}