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 checked_count(self) -> Option<usize> {
443 usize::try_from(self.end.checked_sub(self.start)?).ok()
444 }
445
446 pub fn from_inclusive(range: ops::RangeInclusive<u64>) -> Option<Self> {
447 range.end().checked_add(1).map(|end| Self {
448 start: *range.start(),
449 end,
450 })
451 }
452}
453
454impl From<Range<u64>> for IdxRange {
455 fn from(Range { start, end }: Range<u64>) -> Self {
456 Self { start, end }
457 }
458}
459
460impl IntoIterator for IdxRange {
461 type Item = u64;
462 type IntoIter = ops::Range<u64>;
463
464 fn into_iter(self) -> Self::IntoIter {
465 ops::Range {
466 start: self.start,
467 end: self.end,
468 }
469 }
470}
471
472#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Encodable, Decodable)]
474pub struct OutPointRange {
475 pub txid: TransactionId,
476 idx_range: IdxRange,
477}
478
479impl OutPointRange {
480 pub fn new(txid: TransactionId, idx_range: IdxRange) -> Self {
481 Self { txid, idx_range }
482 }
483
484 pub fn new_single(txid: TransactionId, idx: u64) -> Option<Self> {
485 IdxRange::new_single(idx).map(|idx_range| Self { txid, idx_range })
486 }
487
488 pub fn start_idx(self) -> u64 {
489 self.idx_range.start()
490 }
491
492 pub fn out_idx_iter(self) -> impl Iterator<Item = u64> {
493 self.idx_range.into_iter()
494 }
495
496 pub fn count(self) -> usize {
497 self.idx_range.count()
498 }
499
500 pub fn checked_count(self) -> Option<usize> {
502 self.idx_range.checked_count()
503 }
504
505 pub fn start_out_point(self) -> OutPoint {
506 OutPoint {
507 txid: self.txid,
508 out_idx: self.idx_range.start(),
509 }
510 }
511
512 pub fn end_out_point(self) -> OutPoint {
513 OutPoint {
514 txid: self.txid,
515 out_idx: self.idx_range.end,
516 }
517 }
518
519 pub fn txid(&self) -> TransactionId {
520 self.txid
521 }
522}
523
524impl IntoIterator for OutPointRange {
525 type Item = OutPoint;
526 type IntoIter = OutPointRangeIter;
527
528 fn into_iter(self) -> Self::IntoIter {
529 OutPointRangeIter {
530 txid: self.txid,
531 inner: self.idx_range.into_iter(),
532 }
533 }
534}
535
536pub struct OutPointRangeIter {
537 txid: TransactionId,
538 inner: ops::Range<u64>,
539}
540
541impl Iterator for OutPointRangeIter {
542 type Item = OutPoint;
543
544 fn next(&mut self) -> Option<Self::Item> {
545 self.inner.next().map(|idx| OutPoint {
546 txid: self.txid,
547 out_idx: idx,
548 })
549 }
550}
551
552impl Encodable for TransactionId {
553 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
554 let bytes = &self[..];
555 writer.write_all(bytes)?;
556 Ok(())
557 }
558}
559
560impl Decodable for TransactionId {
561 fn consensus_decode_partial<D: std::io::Read>(
562 d: &mut D,
563 _modules: &ModuleDecoderRegistry,
564 ) -> Result<Self, DecodeError> {
565 let mut bytes = [0u8; 32];
566 d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
567 Ok(Self::from_byte_array(bytes))
568 }
569}
570
571#[derive(
572 Copy,
573 Clone,
574 Debug,
575 PartialEq,
576 Ord,
577 PartialOrd,
578 Eq,
579 Hash,
580 Serialize,
581 Deserialize,
582 Encodable,
583 Decodable,
584)]
585pub struct Feerate {
586 pub sats_per_kvb: u64,
587}
588
589impl fmt::Display for Feerate {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 f.write_fmt(format_args!("{}sat/kvb", self.sats_per_kvb))
592 }
593}
594
595impl Feerate {
596 pub fn calculate_fee(&self, weight: u64) -> bitcoin::Amount {
597 let sats = weight_to_vbytes(weight) * self.sats_per_kvb / 1000;
598 bitcoin::Amount::from_sat(sats)
599 }
600
601 pub fn wrapping_calculate_fee(&self, weight: u64) -> bitcoin::Amount {
609 let sats = weight_to_vbytes(weight).wrapping_mul(self.sats_per_kvb) / 1000;
610 bitcoin::Amount::from_sat(sats)
611 }
612
613 pub fn checked_calculate_fee(&self, weight: u64) -> Option<bitcoin::Amount> {
620 let sats = weight_to_vbytes(weight).checked_mul(self.sats_per_kvb)? / 1000;
621 (sats <= bitcoin::Amount::MAX_MONEY.to_sat()).then(|| bitcoin::Amount::from_sat(sats))
622 }
623}
624
625const WITNESS_SCALE_FACTOR: u64 = bitcoin::constants::WITNESS_SCALE_FACTOR as u64;
626
627pub fn weight_to_vbytes(weight: u64) -> u64 {
632 weight.div_ceil(WITNESS_SCALE_FACTOR)
633}
634
635#[derive(Debug, Error)]
636pub enum CoreError {
637 #[error("Mismatching outcome variant: expected {0}, got {1}")]
638 MismatchingVariant(&'static str, &'static str),
639}
640
641pub fn encode_bolt11_invoice_features_without_length(features: &Bolt11InvoiceFeatures) -> Vec<u8> {
647 let mut feature_bytes = vec![];
648 for f in features.le_flags().iter().rev() {
649 f.write(&mut feature_bytes)
650 .expect("Writing to byte vec can't fail");
651 }
652 feature_bytes
653}
654
655pub fn format_hex(data: &[u8], f: &mut std::fmt::Formatter) -> std::fmt::Result {
660 let prec = f.precision().unwrap_or(2 * data.len());
661 let width = f.width().unwrap_or(2 * data.len());
662 for _ in (2 * data.len())..width {
663 f.write_str("0")?;
664 }
665 for ch in data.iter().take(prec / 2) {
666 write!(f, "{:02x}", *ch)?;
667 }
668 if prec < 2 * data.len() && prec % 2 == 1 {
669 write!(f, "{:x}", data[prec / 2] / 16)?;
670 }
671 Ok(())
672}
673
674pub fn get_network_for_address(address: &Address<NetworkUnchecked>) -> Network {
687 if address.is_valid_for_network(Network::Bitcoin) {
688 Network::Bitcoin
689 } else if address.is_valid_for_network(Network::Testnet) {
690 Network::Testnet
691 } else if address.is_valid_for_network(Network::Regtest) {
692 Network::Regtest
693 } else {
694 panic!("Address is not valid for any network");
695 }
696}
697
698pub fn default_esplora_server(network: Network, port: Option<String>) -> BitcoinRpcConfig {
700 BitcoinRpcConfig {
701 kind: "esplora".to_string(),
702 url: match network {
703 Network::Bitcoin => SafeUrl::parse("https://mempool.space/api/"),
704 Network::Testnet => SafeUrl::parse("https://mempool.space/testnet/api/"),
705 Network::Testnet4 => SafeUrl::parse("https://mempool.space/testnet4/api/"),
706 Network::Signet => SafeUrl::parse("https://mutinynet.com/api/"),
707 Network::Regtest => SafeUrl::parse(&format!(
708 "http://127.0.0.1:{}/",
709 port.unwrap_or_else(|| String::from("50002"))
710 )),
711 }
712 .expect("Failed to parse default esplora server"),
713 }
714}
715
716#[cfg(test)]
717mod tests;