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
41use std::fmt::{self, Debug};
42use std::io::Error;
43use std::str::FromStr;
44
45pub use amount::*;
46/// Mostly re-exported for [`Decodable`] macros.
47pub use anyhow;
48use bitcoin::address::NetworkUnchecked;
49pub use bitcoin::hashes::Hash as BitcoinHash;
50use bitcoin::{Address, Network};
51use envs::BitcoinRpcConfig;
52use lightning::util::ser::Writeable;
53use lightning_types::features::Bolt11InvoiceFeatures;
54pub use macro_rules_attribute::apply;
55pub use peer_id::*;
56use serde::{Deserialize, Serialize};
57use thiserror::Error;
58pub use tiered::Tiered;
59pub use tiered_multi::*;
60use util::SafeUrl;
61pub use {bitcoin, hex, secp256k1};
62
63use crate::encoding::{Decodable, DecodeError, Encodable};
64use crate::module::registry::ModuleDecoderRegistry;
65
66/// Admin (guardian) client types
67pub mod admin_client;
68/// Bitcoin amount types
69mod amount;
70/// Federation-stored client backups
71pub mod backup;
72/// Legacy serde encoding for `bls12_381`
73pub mod bls12_381_serde;
74/// Federation configuration
75pub mod config;
76/// Fundamental types
77pub mod core;
78/// Database handling
79pub mod db;
80/// Consensus encoding
81pub mod encoding;
82pub mod endpoint_constants;
83/// Common environment variables
84pub mod envs;
85pub mod epoch;
86/// Formatting helpers
87pub mod fmt_utils;
88/// Federation invite code
89pub mod invite_code;
90pub mod iroh_prod;
91pub mod log;
92/// Common macros
93#[macro_use]
94pub mod macros;
95/// Base 32 encoding
96pub mod base32;
97/// Extendable module sysystem
98pub mod module;
99/// Peer networking
100pub mod net;
101/// `PeerId` type
102mod peer_id;
103/// Runtime (wasm32 vs native) differences handling
104pub mod runtime;
105/// Peer setup code for setup ceremony
106pub mod setup_code;
107/// Task handling, including wasm safe logic
108pub mod task;
109/// Types handling per-denomination values
110pub mod tiered;
111/// Types handling multiple per-denomination values
112pub mod tiered_multi;
113/// Time handling, wasm safe functionality
114pub mod time;
115/// Timing helpers
116pub mod timing;
117/// Fedimint transaction (inpus + outputs + signature) types
118pub mod transaction;
119/// Peg-in txo proofs
120pub mod txoproof;
121/// General purpose utilities
122pub mod util;
123/// Version
124pub mod version;
125
126/// Atomic BFT unit containing consensus items
127pub mod session_outcome;
128
129// It's necessary to wrap `hash_newtype!` in a module because the generated code
130// references a module called "core", but we export a conflicting module in this
131// file.
132mod txid {
133    use bitcoin::hashes::hash_newtype;
134    use bitcoin::hashes::sha256::Hash as Sha256;
135
136    hash_newtype!(
137        /// A transaction id for peg-ins, peg-outs and reissuances
138        pub struct TransactionId(Sha256);
139    );
140}
141pub use txid::TransactionId;
142
143/// Amount of bitcoin to send, or `All` to send all available funds
144#[derive(Debug, Eq, PartialEq, Copy, Hash, Clone, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum BitcoinAmountOrAll {
147    All,
148    #[serde(untagged)]
149    Amount(#[serde(with = "bitcoin::amount::serde::as_sat")] bitcoin::Amount),
150}
151
152impl std::fmt::Display for BitcoinAmountOrAll {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        match self {
155            Self::All => write!(f, "all"),
156            Self::Amount(amount) => write!(f, "{amount}"),
157        }
158    }
159}
160
161impl FromStr for BitcoinAmountOrAll {
162    type Err = anyhow::Error;
163
164    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
165        if s == "all" {
166            Ok(Self::All)
167        } else {
168            let amount = Amount::from_str(s)?;
169            Ok(Self::Amount(amount.try_into()?))
170        }
171    }
172}
173
174/// `InPoint` represents a globally unique input in a transaction
175///
176/// Hence, a transaction ID and the input index is required.
177#[derive(
178    Debug,
179    Clone,
180    Copy,
181    Eq,
182    PartialEq,
183    PartialOrd,
184    Ord,
185    Hash,
186    Deserialize,
187    Serialize,
188    Encodable,
189    Decodable,
190)]
191pub struct InPoint {
192    /// The referenced transaction ID
193    pub txid: TransactionId,
194    /// As a transaction may have multiple inputs, this refers to the index of
195    /// the input in a transaction
196    pub in_idx: u64,
197}
198
199impl std::fmt::Display for InPoint {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        write!(f, "{}:{}", self.txid, self.in_idx)
202    }
203}
204
205/// `OutPoint` represents a globally unique output in a transaction
206///
207/// Hence, a transaction ID and the output index is required.
208#[derive(
209    Debug,
210    Clone,
211    Copy,
212    Eq,
213    PartialEq,
214    PartialOrd,
215    Ord,
216    Hash,
217    Deserialize,
218    Serialize,
219    Encodable,
220    Decodable,
221)]
222pub struct OutPoint {
223    /// The referenced transaction ID
224    pub txid: TransactionId,
225    /// As a transaction may have multiple outputs, this refers to the index of
226    /// the output in a transaction
227    pub out_idx: u64,
228}
229
230impl std::fmt::Display for OutPoint {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        write!(f, "{}:{}", self.txid, self.out_idx)
233    }
234}
235
236impl Encodable for TransactionId {
237    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
238        let bytes = &self[..];
239        writer.write_all(bytes)?;
240        Ok(())
241    }
242}
243
244impl Decodable for TransactionId {
245    fn consensus_decode_partial<D: std::io::Read>(
246        d: &mut D,
247        _modules: &ModuleDecoderRegistry,
248    ) -> Result<Self, DecodeError> {
249        let mut bytes = [0u8; 32];
250        d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
251        Ok(Self::from_byte_array(bytes))
252    }
253}
254
255#[derive(
256    Copy,
257    Clone,
258    Debug,
259    PartialEq,
260    Ord,
261    PartialOrd,
262    Eq,
263    Hash,
264    Serialize,
265    Deserialize,
266    Encodable,
267    Decodable,
268)]
269pub struct Feerate {
270    pub sats_per_kvb: u64,
271}
272
273impl fmt::Display for Feerate {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.write_fmt(format_args!("{}sat/kvb", self.sats_per_kvb))
276    }
277}
278
279impl Feerate {
280    pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount {
281        let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000;
282        bitcoin::Amount::from_sat(sats)
283    }
284}
285
286const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64;
287
288/// Converts weight to virtual bytes, defined in [BIP-141] as weight / 4
289/// (rounded up to the next integer).
290///
291/// [BIP-141]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#transaction-size-calculations
292pub fn weight_to_vbytes(weight: u64) -> u64 {
293    weight.div_ceil(WITNESS_SCALE_FACTOR)
294}
295
296#[derive(Debug, Error)]
297pub enum CoreError {
298    #[error("Mismatching outcome variant: expected {0}, got {1}")]
299    MismatchingVariant(&'static str, &'static str),
300}
301
302// Encode features for a bolt11 invoice without encoding the length.
303// This functionality was available in `lightning` v0.0.123, but has since been
304// removed. See the original code here:
305// https://docs.rs/lightning/0.0.123/src/lightning/ln/features.rs.html#745-750
306// https://docs.rs/lightning/0.0.123/src/lightning/ln/features.rs.html#1008-1012
307pub fn encode_bolt11_invoice_features_without_length(features: &Bolt11InvoiceFeatures) -> Vec<u8> {
308    let mut feature_bytes = vec![];
309    for f in features.le_flags().iter().rev() {
310        f.write(&mut feature_bytes)
311            .expect("Writing to byte vec can't fail");
312    }
313    feature_bytes
314}
315
316/// Outputs hex into an object implementing `fmt::Write`.
317///
318/// Vendored from `bitcoin_hashes` v0.11.0:
319/// <https://docs.rs/bitcoin_hashes/0.11.0/src/bitcoin_hashes/hex.rs.html#173-189>
320pub fn format_hex(data: &[u8], f: &mut std::fmt::Formatter) -> std::fmt::Result {
321    let prec = f.precision().unwrap_or(2 * data.len());
322    let width = f.width().unwrap_or(2 * data.len());
323    for _ in (2 * data.len())..width {
324        f.write_str("0")?;
325    }
326    for ch in data.iter().take(prec / 2) {
327        write!(f, "{:02x}", *ch)?;
328    }
329    if prec < 2 * data.len() && prec % 2 == 1 {
330        write!(f, "{:x}", data[prec / 2] / 16)?;
331    }
332    Ok(())
333}
334
335/// Gets the (approximate) network from a bitcoin address.
336///
337/// This function mimics how `Address.network` is calculated in bitcoin v0.30.
338/// However, that field was removed in more recent versions in part because it
339/// can only distinguish between `Bitcoin`, `Testnet` and `Regtest`.
340///
341/// As of bitcoin v0.32.4, `Address::is_valid_for_network()` performs equality
342/// checks using `NetworkKind` and `KnownHrp`, which only distinguish between
343/// `Bitcoin`, `Testnet` and `Regtest`.
344/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/address/mod.rs.html#709-716>
345/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/network.rs.html#51-58>
346/// <https://docs.rs/bitcoin/0.32.4/src/bitcoin/address/mod.rs.html#200-209>
347pub fn get_network_for_address(address: &Address<NetworkUnchecked>) -> Network {
348    if address.is_valid_for_network(Network::Bitcoin) {
349        Network::Bitcoin
350    } else if address.is_valid_for_network(Network::Testnet) {
351        Network::Testnet
352    } else if address.is_valid_for_network(Network::Regtest) {
353        Network::Regtest
354    } else {
355        panic!("Address is not valid for any network");
356    }
357}
358
359/// Returns the default esplora server according to the network
360pub fn default_esplora_server(network: Network, port: Option<String>) -> BitcoinRpcConfig {
361    BitcoinRpcConfig {
362        kind: "esplora".to_string(),
363        url: match network {
364            Network::Bitcoin => SafeUrl::parse("https://mempool.space/api/"),
365            Network::Testnet => SafeUrl::parse("https://mempool.space/testnet/api/"),
366            Network::Testnet4 => SafeUrl::parse("https://mempool.space/testnet4/api/"),
367            Network::Signet => SafeUrl::parse("https://mutinynet.com/api/"),
368            Network::Regtest => SafeUrl::parse(&format!(
369                "http://127.0.0.1:{}/",
370                port.unwrap_or_else(|| String::from("50002"))
371            )),
372            _ => panic!("Failed to parse default esplora server"),
373        }
374        .expect("Failed to parse default esplora server"),
375    }
376}
377
378#[cfg(test)]
379mod tests;