Skip to main content

fedimint_core/
lib.rs

1#![deny(clippy::pedantic, clippy::nursery)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::cast_possible_wrap)]
4#![allow(clippy::cast_precision_loss)]
5#![allow(clippy::cast_sign_loss)]
6#![allow(clippy::cognitive_complexity)]
7#![allow(clippy::doc_markdown)]
8#![allow(clippy::future_not_send)]
9#![allow(clippy::missing_const_for_fn)]
10#![allow(clippy::missing_errors_doc)]
11#![allow(clippy::missing_panics_doc)]
12#![allow(clippy::module_name_repetitions)]
13#![allow(clippy::must_use_candidate)]
14#![allow(clippy::needless_lifetimes)]
15#![allow(clippy::redundant_pub_crate)]
16#![allow(clippy::return_self_not_must_use)]
17#![allow(clippy::similar_names)]
18#![allow(clippy::transmute_ptr_to_ptr)]
19#![allow(clippy::unsafe_derive_deserialize)]
20
21//! Fedimint Core library
22//!
23//! `fedimint-core` contains commonly used types, utilities and primitives,
24//! shared between both client and server code.
25//!
26//! Things that are server-side only typically live in `fedimint-server`, and
27//! client-side only in `fedimint-client`.
28//!
29//! ### Wasm support
30//!
31//! All code in `fedimint-core` needs to compile on Wasm, and `fedimint-core`
32//! includes helpers and wrappers around non-wasm-safe utitlies.
33//!
34//! In particular:
35//!
36//! * [`fedimint_core::task`] for task spawning and control
37//! * [`fedimint_core::time`] for time-related operations
38
39extern crate self as fedimint_core;
40
41#[cfg(feature = "uniffi")]
42uniffi::setup_scaffolding!();
43
44use std::fmt::{self, Debug};
45use std::io::Error;
46use std::ops::{self, Range};
47use std::str::FromStr;
48
49pub use amount::*;
50/// Mostly re-exported for [`Decodable`] macros.
51pub use anyhow;
52use bitcoin::address::NetworkUnchecked;
53pub use bitcoin::hashes::Hash as BitcoinHash;
54use bitcoin::{Address, Network};
55use envs::BitcoinRpcConfig;
56use lightning::util::ser::Writeable;
57use lightning_types::features::Bolt11InvoiceFeatures;
58pub use macro_rules_attribute::apply;
59pub use peer_id::*;
60use serde::{Deserialize, Deserializer, Serialize, Serializer};
61use thiserror::Error;
62pub use tiered::Tiered;
63pub use tiered_multi::*;
64use util::SafeUrl;
65pub use {bitcoin, hex, secp256k1};
66
67use crate::encoding::{Decodable, DecodeError, Encodable};
68use crate::module::registry::ModuleDecoderRegistry;
69
70/// Admin (guardian) client types
71pub mod admin_client;
72/// Bitcoin amount types
73mod amount;
74/// Federation-stored client backups
75pub mod backup;
76/// Legacy serde encoding for `bls12_381`
77pub mod bls12_381_serde;
78/// Federation configuration
79pub mod config;
80/// Fundamental types
81pub mod core;
82/// Database handling
83pub mod db;
84/// Consensus encoding
85pub mod encoding;
86pub mod endpoint_constants;
87/// Common environment variables
88pub mod envs;
89pub mod epoch;
90/// Formatting helpers
91pub mod fmt_utils;
92/// Federation invite code
93pub mod invite_code;
94pub mod log;
95/// Common macros
96#[macro_use]
97pub mod macros;
98/// Base 32 encoding
99pub mod base32;
100/// Extendable module sysystem
101pub mod module;
102/// Peer networking
103pub mod net;
104/// `PeerId` type
105mod peer_id;
106/// Runtime (wasm32 vs native) differences handling
107pub mod runtime;
108/// Rustls support
109pub mod rustls;
110/// Peer setup code for setup ceremony
111pub mod setup_code;
112/// Task handling, including wasm safe logic
113pub mod task;
114/// Types handling per-denomination values
115pub mod tiered;
116/// Types handling multiple per-denomination values
117pub mod tiered_multi;
118/// Time handling, wasm safe functionality
119pub mod time;
120/// Timing helpers
121pub mod timing;
122/// Fedimint transaction (inpus + outputs + signature) types
123pub mod transaction;
124/// Peg-in txo proofs
125pub mod txoproof;
126/// General purpose utilities
127pub mod util;
128/// Version
129pub mod version;
130
131/// Atomic BFT unit containing consensus items
132pub mod session_outcome;
133
134// It's necessary to wrap `hash_newtype!` in a module because the generated code
135// references a module called "core", but we export a conflicting module in this
136// file.
137mod txid {
138    use bitcoin::hashes::hash_newtype;
139    use bitcoin::hashes::sha256::Hash as Sha256;
140
141    hash_newtype!(
142        /// A transaction id for peg-ins, peg-outs and reissuances
143        pub struct TransactionId(Sha256);
144    );
145}
146pub use txid::TransactionId;
147
148#[cfg(feature = "uniffi")]
149uniffi::custom_type!(TransactionId, String, {
150    lower: |txid| txid.to_string(),
151    try_lift: |s| TransactionId::from_str(&s).map_err(Into::into),
152});
153
154pub struct TransactionIdShortFmt<'a>(&'a TransactionId);
155pub struct TransactionIdFullFmt<'a>(&'a TransactionId);
156
157impl TransactionId {
158    pub fn fmt_short(&self) -> TransactionIdShortFmt<'_> {
159        TransactionIdShortFmt(self)
160    }
161
162    pub fn fmt_full(&self) -> TransactionIdFullFmt<'_> {
163        TransactionIdFullFmt(self)
164    }
165}
166
167impl std::fmt::Display for TransactionIdShortFmt<'_> {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        let bytes = &self.0[..];
170        format_hex(&bytes[..4], f)?;
171        f.write_str("_")?;
172        format_hex(&bytes[28..], f)
173    }
174}
175
176impl std::fmt::Display for TransactionIdFullFmt<'_> {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        let bytes = &self.0[..];
179        format_hex(bytes, f)
180    }
181}
182
183/// Bitcoin chain identifier
184///
185/// This is a newtype wrapper around [`bitcoin::BlockHash`] representing the
186/// block hash at height 1, which uniquely identifies a Bitcoin chain (mainnet,
187/// testnet, signet, regtest, or custom networks), unlike genesis block hash
188/// which is often the same for same types of networks (e.g. mutinynet vs
189/// signet4).
190///
191/// Using a distinct type instead of raw `BlockHash` provides type safety and
192/// makes the intent clearer when passing chain identifiers through APIs.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
194pub struct ChainId(pub bitcoin::BlockHash);
195
196#[cfg(feature = "uniffi")]
197uniffi::custom_type!(ChainId, String, {
198    lower: |c| c.to_string(),
199    try_lift: |s| ChainId::from_str(&s).map_err(Into::into),
200});
201
202impl ChainId {
203    /// Create a new `ChainId` from a `BlockHash`
204    pub fn new(block_hash: bitcoin::BlockHash) -> Self {
205        Self(block_hash)
206    }
207
208    /// Get the inner `BlockHash`
209    pub fn block_hash(&self) -> bitcoin::BlockHash {
210        self.0
211    }
212}
213
214impl From<bitcoin::BlockHash> for ChainId {
215    fn from(block_hash: bitcoin::BlockHash) -> Self {
216        Self(block_hash)
217    }
218}
219
220impl From<ChainId> for bitcoin::BlockHash {
221    fn from(chain_id: ChainId) -> Self {
222        chain_id.0
223    }
224}
225
226impl std::fmt::Display for ChainId {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        write!(f, "{}", self.0)
229    }
230}
231
232impl FromStr for ChainId {
233    type Err = bitcoin::hashes::hex::HexToArrayError;
234
235    fn from_str(s: &str) -> Result<Self, Self::Err> {
236        bitcoin::BlockHash::from_str(s).map(Self)
237    }
238}
239
240impl Serialize for ChainId {
241    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
242    where
243        S: Serializer,
244    {
245        self.0.serialize(serializer)
246    }
247}
248
249impl<'de> Deserialize<'de> for ChainId {
250    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
251    where
252        D: Deserializer<'de>,
253    {
254        bitcoin::BlockHash::deserialize(deserializer).map(Self)
255    }
256}
257
258/// Amount of bitcoin to send, or `All` to send all available funds
259#[derive(Debug, Eq, PartialEq, Copy, Hash, Clone)]
260pub enum BitcoinAmountOrAll {
261    All,
262    Amount(bitcoin::Amount),
263}
264
265impl std::fmt::Display for BitcoinAmountOrAll {
266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267        match self {
268            Self::All => write!(f, "all"),
269            Self::Amount(amount) => write!(f, "{amount}"),
270        }
271    }
272}
273
274impl FromStr for BitcoinAmountOrAll {
275    type Err = anyhow::Error;
276
277    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
278        if s.eq_ignore_ascii_case("all") {
279            Ok(Self::All)
280        } else {
281            let amount = Amount::from_str(s)?;
282            Ok(Self::Amount(amount.try_into()?))
283        }
284    }
285}
286
287// Custom serde to handle both "all" and numbers/strings
288impl<'de> Deserialize<'de> for BitcoinAmountOrAll {
289    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
290    where
291        D: Deserializer<'de>,
292    {
293        use serde::de::Error;
294
295        struct Visitor;
296
297        impl serde::de::Visitor<'_> for Visitor {
298            type Value = BitcoinAmountOrAll;
299
300            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
301                write!(f, "a bitcoin amount as number or 'all'")
302            }
303
304            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
305            where
306                E: Error,
307            {
308                if v.eq_ignore_ascii_case("all") {
309                    Ok(BitcoinAmountOrAll::All)
310                } else {
311                    let sat: u64 = v.parse().map_err(E::custom)?;
312                    Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(sat)))
313                }
314            }
315
316            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
317            where
318                E: Error,
319            {
320                Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(v)))
321            }
322
323            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
324            where
325                E: Error,
326            {
327                if v < 0 {
328                    return Err(E::custom("amount cannot be negative"));
329                }
330                Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(
331                    v as u64,
332                )))
333            }
334        }
335
336        deserializer.deserialize_any(Visitor)
337    }
338}
339
340impl Serialize for BitcoinAmountOrAll {
341    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
342    where
343        S: Serializer,
344    {
345        match self {
346            Self::All => serializer.serialize_str("all"),
347            Self::Amount(a) => serializer.serialize_u64(a.to_sat()),
348        }
349    }
350}
351
352/// `InPoint` represents a globally unique input in a transaction
353///
354/// Hence, a transaction ID and the input index is required.
355#[derive(
356    Debug,
357    Clone,
358    Copy,
359    Eq,
360    PartialEq,
361    PartialOrd,
362    Ord,
363    Hash,
364    Deserialize,
365    Serialize,
366    Encodable,
367    Decodable,
368)]
369pub struct InPoint {
370    /// The referenced transaction ID
371    pub txid: TransactionId,
372    /// As a transaction may have multiple inputs, this refers to the index of
373    /// the input in a transaction
374    pub in_idx: u64,
375}
376
377impl std::fmt::Display for InPoint {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        write!(f, "{}:{}", self.txid, self.in_idx)
380    }
381}
382
383/// `OutPoint` represents a globally unique output in a transaction
384///
385/// Hence, a transaction ID and the output index is required.
386#[derive(
387    Debug,
388    Clone,
389    Copy,
390    Eq,
391    PartialEq,
392    PartialOrd,
393    Ord,
394    Hash,
395    Deserialize,
396    Serialize,
397    Encodable,
398    Decodable,
399)]
400#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
401pub struct OutPoint {
402    /// The referenced transaction ID
403    pub txid: TransactionId,
404    /// As a transaction may have multiple outputs, this refers to the index of
405    /// the output in a transaction
406    pub out_idx: u64,
407}
408
409impl std::fmt::Display for OutPoint {
410    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
411        write!(f, "{}:{}", self.txid, self.out_idx)
412    }
413}
414
415/// A contiguous range of input/output indexes
416#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
417pub struct IdxRange {
418    start: u64,
419    end: u64,
420}
421
422impl IdxRange {
423    pub fn new_single(start: u64) -> Option<Self> {
424        start.checked_add(1).map(|end| Self { start, end })
425    }
426
427    pub fn start(self) -> u64 {
428        self.start
429    }
430
431    pub fn count(self) -> usize {
432        self.into_iter().count()
433    }
434
435    pub fn from_inclusive(range: ops::RangeInclusive<u64>) -> Option<Self> {
436        range.end().checked_add(1).map(|end| Self {
437            start: *range.start(),
438            end,
439        })
440    }
441}
442
443impl From<Range<u64>> for IdxRange {
444    fn from(Range { start, end }: Range<u64>) -> Self {
445        Self { start, end }
446    }
447}
448
449impl IntoIterator for IdxRange {
450    type Item = u64;
451    type IntoIter = ops::Range<u64>;
452
453    fn into_iter(self) -> Self::IntoIter {
454        ops::Range {
455            start: self.start,
456            end: self.end,
457        }
458    }
459}
460
461/// Represents a range of output indices for a single transaction
462#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
463pub struct OutPointRange {
464    pub txid: TransactionId,
465    idx_range: IdxRange,
466}
467
468impl OutPointRange {
469    pub fn new(txid: TransactionId, idx_range: IdxRange) -> Self {
470        Self { txid, idx_range }
471    }
472
473    pub fn new_single(txid: TransactionId, idx: u64) -> Option<Self> {
474        IdxRange::new_single(idx).map(|idx_range| Self { txid, idx_range })
475    }
476
477    pub fn start_idx(self) -> u64 {
478        self.idx_range.start()
479    }
480
481    pub fn out_idx_iter(self) -> impl Iterator<Item = u64> {
482        self.idx_range.into_iter()
483    }
484
485    pub fn count(self) -> usize {
486        self.idx_range.count()
487    }
488
489    pub fn start_out_point(self) -> OutPoint {
490        OutPoint {
491            txid: self.txid,
492            out_idx: self.idx_range.start(),
493        }
494    }
495
496    pub fn end_out_point(self) -> OutPoint {
497        OutPoint {
498            txid: self.txid,
499            out_idx: self.idx_range.end,
500        }
501    }
502
503    pub fn txid(&self) -> TransactionId {
504        self.txid
505    }
506}
507
508impl IntoIterator for OutPointRange {
509    type Item = OutPoint;
510    type IntoIter = OutPointRangeIter;
511
512    fn into_iter(self) -> Self::IntoIter {
513        OutPointRangeIter {
514            txid: self.txid,
515            inner: self.idx_range.into_iter(),
516        }
517    }
518}
519
520pub struct OutPointRangeIter {
521    txid: TransactionId,
522    inner: ops::Range<u64>,
523}
524
525impl Iterator for OutPointRangeIter {
526    type Item = OutPoint;
527
528    fn next(&mut self) -> Option<Self::Item> {
529        self.inner.next().map(|idx| OutPoint {
530            txid: self.txid,
531            out_idx: idx,
532        })
533    }
534}
535
536impl Encodable for TransactionId {
537    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
538        let bytes = &self[..];
539        writer.write_all(bytes)?;
540        Ok(())
541    }
542}
543
544impl Decodable for TransactionId {
545    fn consensus_decode_partial<D: std::io::Read>(
546        d: &mut D,
547        _modules: &ModuleDecoderRegistry,
548    ) -> Result<Self, DecodeError> {
549        let mut bytes = [0u8; 32];
550        d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
551        Ok(Self::from_byte_array(bytes))
552    }
553}
554
555#[derive(
556    Copy,
557    Clone,
558    Debug,
559    PartialEq,
560    Ord,
561    PartialOrd,
562    Eq,
563    Hash,
564    Serialize,
565    Deserialize,
566    Encodable,
567    Decodable,
568)]
569pub struct Feerate {
570    pub sats_per_kvb: u64,
571}
572
573impl fmt::Display for Feerate {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        f.write_fmt(format_args!("{}sat/kvb", self.sats_per_kvb))
576    }
577}
578
579impl Feerate {
580    pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount {
581        let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000;
582        bitcoin::Amount::from_sat(sats)
583    }
584}
585
586const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64;
587
588/// Converts weight to virtual bytes, defined in [BIP-141] as weight / 4
589/// (rounded up to the next integer).
590///
591/// [BIP-141]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#transaction-size-calculations
592pub fn weight_to_vbytes(weight: u64) -> u64 {
593    weight.div_ceil(WITNESS_SCALE_FACTOR)
594}
595
596#[derive(Debug, Error)]
597pub enum CoreError {
598    #[error("Mismatching outcome variant: expected {0}, got {1}")]
599    MismatchingVariant(&'static str, &'static str),
600}
601
602// Encode features for a bolt11 invoice without encoding the length.
603// This functionality was available in `lightning` v0.0.123, but has since been
604// removed. See the original code here:
605// https://docs.rs/lightning/0.0.123/src/lightning/ln/features.rs.html#745-750
606// https://docs.rs/lightning/0.0.123/src/lightning/ln/features.rs.html#1008-1012
607pub fn encode_bolt11_invoice_features_without_length(features: &Bolt11InvoiceFeatures) -> Vec<u8> {
608    let mut feature_bytes = vec![];
609    for f in features.le_flags().iter().rev() {
610        f.write(&mut feature_bytes)
611            .expect("Writing to byte vec can't fail");
612    }
613    feature_bytes
614}
615
616/// Outputs hex into an object implementing `fmt::Write`.
617///
618/// Vendored from `bitcoin_hashes` v0.11.0:
619/// <https://docs.rs/bitcoin_hashes/0.11.0/src/bitcoin_hashes/hex.rs.html#173-189>
620pub fn format_hex(data: &[u8], f: &mut std::fmt::Formatter) -> std::fmt::Result {
621    let prec = f.precision().unwrap_or(2 * data.len());
622    let width = f.width().unwrap_or(2 * data.len());
623    for _ in (2 * data.len())..width {
624        f.write_str("0")?;
625    }
626    for ch in data.iter().take(prec / 2) {
627        write!(f, "{:02x}", *ch)?;
628    }
629    if prec < 2 * data.len() && prec % 2 == 1 {
630        write!(f, "{:x}", data[prec / 2] / 16)?;
631    }
632    Ok(())
633}
634
635/// Gets the (approximate) network from a bitcoin address.
636///
637/// This function mimics how `Address.network` is calculated in bitcoin v0.30.
638/// However, that field was removed in more recent versions in part because it
639/// can only distinguish between `Bitcoin`, `Testnet` and `Regtest`.
640///
641/// As of bitcoin v0.32.4, `Address::is_valid_for_network()` performs equality
642/// checks using `NetworkKind` and `KnownHrp`, which only distinguish between
643/// `Bitcoin`, `Testnet` and `Regtest`.
644/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/address/mod.rs.html#709-716>
645/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/network.rs.html#51-58>
646/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/address/mod.rs.html#200-209>
647pub fn get_network_for_address(address: &Address<NetworkUnchecked>) -> Network {
648    if address.is_valid_for_network(Network::Bitcoin) {
649        Network::Bitcoin
650    } else if address.is_valid_for_network(Network::Testnet) {
651        Network::Testnet
652    } else if address.is_valid_for_network(Network::Regtest) {
653        Network::Regtest
654    } else {
655        panic!("Address is not valid for any network");
656    }
657}
658
659/// Returns the default esplora server according to the network
660pub fn default_esplora_server(network: Network, port: Option<String>) -> BitcoinRpcConfig {
661    BitcoinRpcConfig {
662        kind: "esplora".to_string(),
663        url: match network {
664            Network::Bitcoin => SafeUrl::parse("https://mempool.space/api/"),
665            Network::Testnet => SafeUrl::parse("https://mempool.space/testnet/api/"),
666            Network::Testnet4 => SafeUrl::parse("https://mempool.space/testnet4/api/"),
667            Network::Signet => SafeUrl::parse("https://mutinynet.com/api/"),
668            Network::Regtest => SafeUrl::parse(&format!(
669                "http://127.0.0.1:{}/",
670                port.unwrap_or_else(|| String::from("50002"))
671            )),
672        }
673        .expect("Failed to parse default esplora server"),
674    }
675}
676
677#[cfg(test)]
678mod tests;