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
38pub const CONFIRMATION_FINALITY_DELAY: u64 = 6;
42
43pub const BLOCK_COUNT_VOTE_DELAY: u64 = CONFIRMATION_FINALITY_DELAY + 1;
53
54pub 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 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
100pub 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#[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 pub height: Option<u64>,
165}
166
167#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
183pub struct PendingOutputs {
184 #[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 pub mempool_visibility: MempoolVisibility,
209}
210
211#[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#[derive(
231 Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
232)]
233pub enum MempoolVisibility {
234 #[default]
238 Unavailable,
239 Partial,
247 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}