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 iroh_prod;
91pub mod log;
92#[macro_use]
94pub mod macros;
95pub mod base32;
97pub mod module;
99pub mod net;
101mod peer_id;
103pub mod runtime;
105pub mod setup_code;
107pub mod task;
109pub mod tiered;
111pub mod tiered_multi;
113pub mod time;
115pub mod timing;
117pub mod transaction;
119pub mod txoproof;
121pub mod util;
123pub mod version;
125
126pub mod session_outcome;
128
129mod txid {
133 use bitcoin::hashes::hash_newtype;
134 use bitcoin::hashes::sha256::Hash as Sha256;
135
136 hash_newtype!(
137 pub struct TransactionId(Sha256);
139 );
140}
141pub use txid::TransactionId;
142
143#[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#[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 pub txid: TransactionId,
194 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#[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 pub txid: TransactionId,
225 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
288pub 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
302pub 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
316pub 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
335pub 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
359pub 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;