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 setup_code;
106pub mod task;
108pub mod tiered;
110pub mod tiered_multi;
112pub mod time;
114pub mod timing;
116pub mod transaction;
118pub mod txoproof;
120pub mod util;
122pub mod version;
124
125pub mod session_outcome;
127
128mod txid {
132 use bitcoin::hashes::hash_newtype;
133 use bitcoin::hashes::sha256::Hash as Sha256;
134
135 hash_newtype!(
136 pub struct TransactionId(Sha256);
138 );
139}
140pub use txid::TransactionId;
141
142#[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#[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 pub txid: TransactionId,
193 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#[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 pub txid: TransactionId,
224 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
287pub 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
301pub 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
315pub 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
334pub 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
358pub 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;