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