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
21extern crate self as fedimint_core;
40
41use std::fmt::{self, Debug};
42use std::io::Error;
43use std::str::FromStr;
44
45pub use amount::*;
46pub 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
66pub mod admin_client;
68mod amount;
70pub mod backup;
72pub mod bls12_381_serde;
74pub mod config;
76pub mod core;
78pub mod db;
80pub mod encoding;
82pub mod endpoint_constants;
83pub mod envs;
85pub mod epoch;
86pub mod fmt_utils;
88pub mod invite_code;
90pub mod log;
91#[macro_use]
93pub mod macros;
94pub mod base32;
96pub mod module;
98pub mod net;
100mod peer_id;
102pub mod runtime;
104pub mod task;
106pub mod tiered;
108pub mod tiered_multi;
110pub mod time;
112pub mod timing;
114pub mod transaction;
116pub mod txoproof;
118pub mod util;
120pub mod version;
122
123pub mod session_outcome;
125
126mod txid {
130 use bitcoin::hashes::hash_newtype;
131 use bitcoin::hashes::sha256::Hash as Sha256;
132
133 hash_newtype!(
134 pub struct TransactionId(Sha256);
136 );
137}
138pub use txid::TransactionId;
139
140#[derive(Debug, Eq, PartialEq, Copy, Hash, Clone, Serialize, Deserialize)]
142#[serde(rename_all = "snake_case")]
143pub enum BitcoinAmountOrAll {
144 All,
145 #[serde(untagged)]
146 Amount(#[serde(with = "bitcoin::amount::serde::as_sat")] bitcoin::Amount),
147}
148
149impl std::fmt::Display for BitcoinAmountOrAll {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 match self {
152 Self::All => write!(f, "all"),
153 Self::Amount(amount) => write!(f, "{amount}"),
154 }
155 }
156}
157
158impl FromStr for BitcoinAmountOrAll {
159 type Err = anyhow::Error;
160
161 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
162 if s == "all" {
163 Ok(Self::All)
164 } else {
165 let amount = Amount::from_str(s)?;
166 Ok(Self::Amount(amount.try_into()?))
167 }
168 }
169}
170
171#[derive(
175 Debug,
176 Clone,
177 Copy,
178 Eq,
179 PartialEq,
180 PartialOrd,
181 Ord,
182 Hash,
183 Deserialize,
184 Serialize,
185 Encodable,
186 Decodable,
187)]
188pub struct InPoint {
189 pub txid: TransactionId,
191 pub in_idx: u64,
194}
195
196impl std::fmt::Display for InPoint {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 write!(f, "{}:{}", self.txid, self.in_idx)
199 }
200}
201
202#[derive(
206 Debug,
207 Clone,
208 Copy,
209 Eq,
210 PartialEq,
211 PartialOrd,
212 Ord,
213 Hash,
214 Deserialize,
215 Serialize,
216 Encodable,
217 Decodable,
218)]
219pub struct OutPoint {
220 pub txid: TransactionId,
222 pub out_idx: u64,
225}
226
227impl std::fmt::Display for OutPoint {
228 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229 write!(f, "{}:{}", self.txid, self.out_idx)
230 }
231}
232
233impl Encodable for TransactionId {
234 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
235 let bytes = &self[..];
236 writer.write_all(bytes)?;
237 Ok(())
238 }
239}
240
241impl Decodable for TransactionId {
242 fn consensus_decode_partial<D: std::io::Read>(
243 d: &mut D,
244 _modules: &ModuleDecoderRegistry,
245 ) -> Result<Self, DecodeError> {
246 let mut bytes = [0u8; 32];
247 d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
248 Ok(Self::from_byte_array(bytes))
249 }
250}
251
252#[derive(
253 Copy,
254 Clone,
255 Debug,
256 PartialEq,
257 Ord,
258 PartialOrd,
259 Eq,
260 Hash,
261 Serialize,
262 Deserialize,
263 Encodable,
264 Decodable,
265)]
266pub struct Feerate {
267 pub sats_per_kvb: u64,
268}
269
270impl fmt::Display for Feerate {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 f.write_fmt(format_args!("{}sat/kvb", self.sats_per_kvb))
273 }
274}
275
276impl Feerate {
277 pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount {
278 let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000;
279 bitcoin::Amount::from_sat(sats)
280 }
281}
282
283const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64;
284
285pub fn weight_to_vbytes(weight: u64) -> u64 {
290 weight.div_ceil(WITNESS_SCALE_FACTOR)
291}
292
293#[derive(Debug, Error)]
294pub enum CoreError {
295 #[error("Mismatching outcome variant: expected {0}, got {1}")]
296 MismatchingVariant(&'static str, &'static str),
297}
298
299pub fn encode_bolt11_invoice_features_without_length(features: &Bolt11InvoiceFeatures) -> Vec<u8> {
305 let mut feature_bytes = vec![];
306 for f in features.le_flags().iter().rev() {
307 f.write(&mut feature_bytes)
308 .expect("Writing to byte vec can't fail");
309 }
310 feature_bytes
311}
312
313pub fn format_hex(data: &[u8], f: &mut std::fmt::Formatter) -> std::fmt::Result {
318 let prec = f.precision().unwrap_or(2 * data.len());
319 let width = f.width().unwrap_or(2 * data.len());
320 for _ in (2 * data.len())..width {
321 f.write_str("0")?;
322 }
323 for ch in data.iter().take(prec / 2) {
324 write!(f, "{:02x}", *ch)?;
325 }
326 if prec < 2 * data.len() && prec % 2 == 1 {
327 write!(f, "{:x}", data[prec / 2] / 16)?;
328 }
329 Ok(())
330}
331
332pub fn get_network_for_address(address: &Address<NetworkUnchecked>) -> Network {
345 if address.is_valid_for_network(Network::Bitcoin) {
346 Network::Bitcoin
347 } else if address.is_valid_for_network(Network::Testnet) {
348 Network::Testnet
349 } else if address.is_valid_for_network(Network::Regtest) {
350 Network::Regtest
351 } else {
352 panic!("Address is not valid for any network");
353 }
354}
355
356pub fn default_esplora_server(network: Network, port: Option<String>) -> BitcoinRpcConfig {
358 BitcoinRpcConfig {
359 kind: "esplora".to_string(),
360 url: match network {
361 Network::Bitcoin => SafeUrl::parse("https://mempool.space/api/"),
362 Network::Testnet => SafeUrl::parse("https://mempool.space/testnet/api/"),
363 Network::Testnet4 => SafeUrl::parse("https://mempool.space/testnet4/api/"),
364 Network::Signet => SafeUrl::parse("https://mutinynet.com/api/"),
365 Network::Regtest => SafeUrl::parse(&format!(
366 "http://127.0.0.1:{}/",
367 port.unwrap_or_else(|| String::from("50002"))
368 )),
369 _ => panic!("Failed to parse default esplora server"),
370 }
371 .expect("Failed to parse default esplora server"),
372 }
373}
374
375#[cfg(test)]
376mod tests;