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
41#[cfg(feature = "uniffi")]
42uniffi::setup_scaffolding!();
43
44use std::fmt::{self, Debug};
45use std::io::Error;
46use std::ops::{self, Range};
47use std::str::FromStr;
48
49pub use amount::*;
50pub use anyhow;
52use bitcoin::address::NetworkUnchecked;
53pub use bitcoin::hashes::Hash as BitcoinHash;
54use bitcoin::{Address, Network};
55use envs::BitcoinRpcConfig;
56use lightning::util::ser::Writeable;
57use lightning_types::features::Bolt11InvoiceFeatures;
58pub use macro_rules_attribute::apply;
59pub use peer_id::*;
60use serde::{Deserialize, Deserializer, Serialize, Serializer};
61use thiserror::Error;
62pub use tiered::Tiered;
63pub use tiered_multi::*;
64use util::SafeUrl;
65pub use {bitcoin, hex, secp256k1};
66
67use crate::encoding::{Decodable, DecodeError, Encodable};
68use crate::module::registry::ModuleDecoderRegistry;
69
70pub mod admin_client;
72mod amount;
74pub mod backup;
76pub mod bls12_381_serde;
78pub mod config;
80pub mod core;
82pub mod db;
84pub mod encoding;
86pub mod endpoint_constants;
87pub mod envs;
89pub mod epoch;
90pub mod fmt_utils;
92pub mod invite_code;
94pub mod log;
95#[macro_use]
97pub mod macros;
98pub mod base32;
100pub mod module;
102pub mod net;
104mod peer_id;
106pub mod runtime;
108pub mod rustls;
110pub mod setup_code;
112pub mod task;
114pub mod tiered;
116pub mod tiered_multi;
118pub mod time;
120pub mod timing;
122pub mod transaction;
124pub mod txoproof;
126pub mod util;
128pub mod version;
130
131pub mod session_outcome;
133
134mod txid {
138 use bitcoin::hashes::hash_newtype;
139 use bitcoin::hashes::sha256::Hash as Sha256;
140
141 hash_newtype!(
142 pub struct TransactionId(Sha256);
144 );
145}
146pub use txid::TransactionId;
147
148#[cfg(feature = "uniffi")]
149uniffi::custom_type!(TransactionId, String, {
150 lower: |txid| txid.to_string(),
151 try_lift: |s| TransactionId::from_str(&s).map_err(Into::into),
152});
153
154pub struct TransactionIdShortFmt<'a>(&'a TransactionId);
155pub struct TransactionIdFullFmt<'a>(&'a TransactionId);
156
157impl TransactionId {
158 pub fn fmt_short(&self) -> TransactionIdShortFmt<'_> {
159 TransactionIdShortFmt(self)
160 }
161
162 pub fn fmt_full(&self) -> TransactionIdFullFmt<'_> {
163 TransactionIdFullFmt(self)
164 }
165}
166
167impl std::fmt::Display for TransactionIdShortFmt<'_> {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 let bytes = &self.0[..];
170 format_hex(&bytes[..4], f)?;
171 f.write_str("_")?;
172 format_hex(&bytes[28..], f)
173 }
174}
175
176impl std::fmt::Display for TransactionIdFullFmt<'_> {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 let bytes = &self.0[..];
179 format_hex(bytes, f)
180 }
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
194pub struct ChainId(pub bitcoin::BlockHash);
195
196#[cfg(feature = "uniffi")]
197uniffi::custom_type!(ChainId, String, {
198 lower: |c| c.to_string(),
199 try_lift: |s| ChainId::from_str(&s).map_err(Into::into),
200});
201
202impl ChainId {
203 pub fn new(block_hash: bitcoin::BlockHash) -> Self {
205 Self(block_hash)
206 }
207
208 pub fn block_hash(&self) -> bitcoin::BlockHash {
210 self.0
211 }
212}
213
214impl From<bitcoin::BlockHash> for ChainId {
215 fn from(block_hash: bitcoin::BlockHash) -> Self {
216 Self(block_hash)
217 }
218}
219
220impl From<ChainId> for bitcoin::BlockHash {
221 fn from(chain_id: ChainId) -> Self {
222 chain_id.0
223 }
224}
225
226impl std::fmt::Display for ChainId {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 write!(f, "{}", self.0)
229 }
230}
231
232impl FromStr for ChainId {
233 type Err = bitcoin::hashes::hex::HexToArrayError;
234
235 fn from_str(s: &str) -> Result<Self, Self::Err> {
236 bitcoin::BlockHash::from_str(s).map(Self)
237 }
238}
239
240impl Serialize for ChainId {
241 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
242 where
243 S: Serializer,
244 {
245 self.0.serialize(serializer)
246 }
247}
248
249impl<'de> Deserialize<'de> for ChainId {
250 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
251 where
252 D: Deserializer<'de>,
253 {
254 bitcoin::BlockHash::deserialize(deserializer).map(Self)
255 }
256}
257
258#[derive(Debug, Eq, PartialEq, Copy, Hash, Clone)]
260pub enum BitcoinAmountOrAll {
261 All,
262 Amount(bitcoin::Amount),
263}
264
265impl std::fmt::Display for BitcoinAmountOrAll {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 match self {
268 Self::All => write!(f, "all"),
269 Self::Amount(amount) => write!(f, "{amount}"),
270 }
271 }
272}
273
274impl FromStr for BitcoinAmountOrAll {
275 type Err = anyhow::Error;
276
277 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
278 if s.eq_ignore_ascii_case("all") {
279 Ok(Self::All)
280 } else {
281 let amount = Amount::from_str(s)?;
282 Ok(Self::Amount(amount.try_into()?))
283 }
284 }
285}
286
287impl<'de> Deserialize<'de> for BitcoinAmountOrAll {
289 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
290 where
291 D: Deserializer<'de>,
292 {
293 use serde::de::Error;
294
295 struct Visitor;
296
297 impl serde::de::Visitor<'_> for Visitor {
298 type Value = BitcoinAmountOrAll;
299
300 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
301 write!(f, "a bitcoin amount as number or 'all'")
302 }
303
304 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
305 where
306 E: Error,
307 {
308 if v.eq_ignore_ascii_case("all") {
309 Ok(BitcoinAmountOrAll::All)
310 } else {
311 let sat: u64 = v.parse().map_err(E::custom)?;
312 Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(sat)))
313 }
314 }
315
316 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
317 where
318 E: Error,
319 {
320 Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(v)))
321 }
322
323 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
324 where
325 E: Error,
326 {
327 if v < 0 {
328 return Err(E::custom("amount cannot be negative"));
329 }
330 Ok(BitcoinAmountOrAll::Amount(bitcoin::Amount::from_sat(
331 v as u64,
332 )))
333 }
334 }
335
336 deserializer.deserialize_any(Visitor)
337 }
338}
339
340impl Serialize for BitcoinAmountOrAll {
341 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
342 where
343 S: Serializer,
344 {
345 match self {
346 Self::All => serializer.serialize_str("all"),
347 Self::Amount(a) => serializer.serialize_u64(a.to_sat()),
348 }
349 }
350}
351
352#[derive(
356 Debug,
357 Clone,
358 Copy,
359 Eq,
360 PartialEq,
361 PartialOrd,
362 Ord,
363 Hash,
364 Deserialize,
365 Serialize,
366 Encodable,
367 Decodable,
368)]
369pub struct InPoint {
370 pub txid: TransactionId,
372 pub in_idx: u64,
375}
376
377impl std::fmt::Display for InPoint {
378 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379 write!(f, "{}:{}", self.txid, self.in_idx)
380 }
381}
382
383#[derive(
387 Debug,
388 Clone,
389 Copy,
390 Eq,
391 PartialEq,
392 PartialOrd,
393 Ord,
394 Hash,
395 Deserialize,
396 Serialize,
397 Encodable,
398 Decodable,
399)]
400#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
401pub struct OutPoint {
402 pub txid: TransactionId,
404 pub out_idx: u64,
407}
408
409impl std::fmt::Display for OutPoint {
410 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
411 write!(f, "{}:{}", self.txid, self.out_idx)
412 }
413}
414
415#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
417pub struct IdxRange {
418 start: u64,
419 end: u64,
420}
421
422impl IdxRange {
423 pub fn new_single(start: u64) -> Option<Self> {
424 start.checked_add(1).map(|end| Self { start, end })
425 }
426
427 pub fn start(self) -> u64 {
428 self.start
429 }
430
431 pub fn count(self) -> usize {
432 self.into_iter().count()
433 }
434
435 pub fn from_inclusive(range: ops::RangeInclusive<u64>) -> Option<Self> {
436 range.end().checked_add(1).map(|end| Self {
437 start: *range.start(),
438 end,
439 })
440 }
441}
442
443impl From<Range<u64>> for IdxRange {
444 fn from(Range { start, end }: Range<u64>) -> Self {
445 Self { start, end }
446 }
447}
448
449impl IntoIterator for IdxRange {
450 type Item = u64;
451 type IntoIter = ops::Range<u64>;
452
453 fn into_iter(self) -> Self::IntoIter {
454 ops::Range {
455 start: self.start,
456 end: self.end,
457 }
458 }
459}
460
461#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
463pub struct OutPointRange {
464 pub txid: TransactionId,
465 idx_range: IdxRange,
466}
467
468impl OutPointRange {
469 pub fn new(txid: TransactionId, idx_range: IdxRange) -> Self {
470 Self { txid, idx_range }
471 }
472
473 pub fn new_single(txid: TransactionId, idx: u64) -> Option<Self> {
474 IdxRange::new_single(idx).map(|idx_range| Self { txid, idx_range })
475 }
476
477 pub fn start_idx(self) -> u64 {
478 self.idx_range.start()
479 }
480
481 pub fn out_idx_iter(self) -> impl Iterator<Item = u64> {
482 self.idx_range.into_iter()
483 }
484
485 pub fn count(self) -> usize {
486 self.idx_range.count()
487 }
488
489 pub fn start_out_point(self) -> OutPoint {
490 OutPoint {
491 txid: self.txid,
492 out_idx: self.idx_range.start(),
493 }
494 }
495
496 pub fn end_out_point(self) -> OutPoint {
497 OutPoint {
498 txid: self.txid,
499 out_idx: self.idx_range.end,
500 }
501 }
502
503 pub fn txid(&self) -> TransactionId {
504 self.txid
505 }
506}
507
508impl IntoIterator for OutPointRange {
509 type Item = OutPoint;
510 type IntoIter = OutPointRangeIter;
511
512 fn into_iter(self) -> Self::IntoIter {
513 OutPointRangeIter {
514 txid: self.txid,
515 inner: self.idx_range.into_iter(),
516 }
517 }
518}
519
520pub struct OutPointRangeIter {
521 txid: TransactionId,
522 inner: ops::Range<u64>,
523}
524
525impl Iterator for OutPointRangeIter {
526 type Item = OutPoint;
527
528 fn next(&mut self) -> Option<Self::Item> {
529 self.inner.next().map(|idx| OutPoint {
530 txid: self.txid,
531 out_idx: idx,
532 })
533 }
534}
535
536impl Encodable for TransactionId {
537 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
538 let bytes = &self[..];
539 writer.write_all(bytes)?;
540 Ok(())
541 }
542}
543
544impl Decodable for TransactionId {
545 fn consensus_decode_partial<D: std::io::Read>(
546 d: &mut D,
547 _modules: &ModuleDecoderRegistry,
548 ) -> Result<Self, DecodeError> {
549 let mut bytes = [0u8; 32];
550 d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
551 Ok(Self::from_byte_array(bytes))
552 }
553}
554
555#[derive(
556 Copy,
557 Clone,
558 Debug,
559 PartialEq,
560 Ord,
561 PartialOrd,
562 Eq,
563 Hash,
564 Serialize,
565 Deserialize,
566 Encodable,
567 Decodable,
568)]
569pub struct Feerate {
570 pub sats_per_kvb: u64,
571}
572
573impl fmt::Display for Feerate {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 f.write_fmt(format_args!("{}sat/kvb", self.sats_per_kvb))
576 }
577}
578
579impl Feerate {
580 pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount {
581 let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000;
582 bitcoin::Amount::from_sat(sats)
583 }
584}
585
586const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64;
587
588pub fn weight_to_vbytes(weight: u64) -> u64 {
593 weight.div_ceil(WITNESS_SCALE_FACTOR)
594}
595
596#[derive(Debug, Error)]
597pub enum CoreError {
598 #[error("Mismatching outcome variant: expected {0}, got {1}")]
599 MismatchingVariant(&'static str, &'static str),
600}
601
602pub fn encode_bolt11_invoice_features_without_length(features: &Bolt11InvoiceFeatures) -> Vec<u8> {
608 let mut feature_bytes = vec![];
609 for f in features.le_flags().iter().rev() {
610 f.write(&mut feature_bytes)
611 .expect("Writing to byte vec can't fail");
612 }
613 feature_bytes
614}
615
616pub fn format_hex(data: &[u8], f: &mut std::fmt::Formatter) -> std::fmt::Result {
621 let prec = f.precision().unwrap_or(2 * data.len());
622 let width = f.width().unwrap_or(2 * data.len());
623 for _ in (2 * data.len())..width {
624 f.write_str("0")?;
625 }
626 for ch in data.iter().take(prec / 2) {
627 write!(f, "{:02x}", *ch)?;
628 }
629 if prec < 2 * data.len() && prec % 2 == 1 {
630 write!(f, "{:x}", data[prec / 2] / 16)?;
631 }
632 Ok(())
633}
634
635pub fn get_network_for_address(address: &Address<NetworkUnchecked>) -> Network {
648 if address.is_valid_for_network(Network::Bitcoin) {
649 Network::Bitcoin
650 } else if address.is_valid_for_network(Network::Testnet) {
651 Network::Testnet
652 } else if address.is_valid_for_network(Network::Regtest) {
653 Network::Regtest
654 } else {
655 panic!("Address is not valid for any network");
656 }
657}
658
659pub fn default_esplora_server(network: Network, port: Option<String>) -> BitcoinRpcConfig {
661 BitcoinRpcConfig {
662 kind: "esplora".to_string(),
663 url: match network {
664 Network::Bitcoin => SafeUrl::parse("https://mempool.space/api/"),
665 Network::Testnet => SafeUrl::parse("https://mempool.space/testnet/api/"),
666 Network::Testnet4 => SafeUrl::parse("https://mempool.space/testnet4/api/"),
667 Network::Signet => SafeUrl::parse("https://mutinynet.com/api/"),
668 Network::Regtest => SafeUrl::parse(&format!(
669 "http://127.0.0.1:{}/",
670 port.unwrap_or_else(|| String::from("50002"))
671 )),
672 }
673 .expect("Failed to parse default esplora server"),
674 }
675}
676
677#[cfg(test)]
678mod tests;