bitcoin/
lib.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! # Rust Bitcoin Library
4//!
5//! This is a library that supports the Bitcoin network protocol and associated
6//! primitives. It is designed for Rust programs built to work with the Bitcoin
7//! network.
8//!
9//! Except for its dependency on libsecp256k1 (and optionally libbitcoinconsensus),
10//! this library is written entirely in Rust. It illustrates the benefits of
11//! strong type safety, including ownership and lifetime, for financial and/or cryptographic software.
12//!
13//! See README.md for detailed documentation about development and supported
14//! environments.
15//!
16//! ## Available feature flags
17//!
18//! * `std` - the usual dependency on `std` (default).
19//! * `secp-recovery` - enables calculating public key from a signature and message.
20//! * `base64` - (dependency), enables encoding of PSBTs and message signatures.
21//! * `rand` - (dependency), makes it more convenient to generate random values.
22//! * `serde` - (dependency), implements `serde`-based serialization and
23//!                 deserialization.
24//! * `secp-lowmemory` - optimizations for low-memory devices.
25//! * `bitcoinconsensus-std` - enables `std` in `bitcoinconsensus` and communicates it
26//!                            to this crate so it knows how to implement
27//!                            `std::error::Error`. At this time there's a hack to
28//!                            achieve the same without this feature but it could
29//!                            happen the implementations diverge one day.
30//! * `ordered` - (dependency), adds implementations of `ArbitraryOrdOrd` to some structs.
31
32#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
33// Experimental features we need.
34#![cfg_attr(docsrs, feature(doc_auto_cfg))]
35#![cfg_attr(bench, feature(test))]
36// Coding conventions.
37#![warn(missing_docs)]
38// Instead of littering the codebase for non-fuzzing code just globally allow.
39#![cfg_attr(fuzzing, allow(dead_code, unused_imports))]
40// Exclude lints we don't think are valuable.
41#![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134
42#![allow(clippy::manual_range_contains)] // More readable than clippy's format.
43#![allow(clippy::needless_borrows_for_generic_args)] // https://github.com/rust-lang/rust-clippy/issues/12454
44// For 0.32.x releases only.
45#![allow(deprecated)]
46
47// Disable 16-bit support at least for now as we can't guarantee it yet.
48#[cfg(target_pointer_width = "16")]
49compile_error!(
50    "rust-bitcoin currently only supports architectures with pointers wider than 16 bits, let us
51    know if you want 16-bit support. Note that we do NOT guarantee that we will implement it!"
52);
53
54#[cfg(bench)]
55extern crate test;
56
57#[macro_use]
58extern crate alloc;
59
60#[cfg(feature = "base64")]
61/// Encodes and decodes base64 as bytes or utf8.
62pub extern crate base64;
63
64/// Bitcoin base58 encoding and decoding.
65pub extern crate base58;
66
67/// Re-export the `bech32` crate.
68pub extern crate bech32;
69
70/// Rust implementation of cryptographic hash function algorithms.
71pub extern crate hashes;
72
73/// Re-export the `hex-conservative` crate.
74pub extern crate hex;
75
76/// Re-export the `bitcoin-io` crate.
77pub extern crate io;
78
79/// Re-export the `ordered` crate.
80#[cfg(feature = "ordered")]
81pub extern crate ordered;
82
83/// Rust wrapper library for Pieter Wuille's libsecp256k1.  Implements ECDSA and BIP 340 signatures
84/// for the SECG elliptic curve group secp256k1 and related utilities.
85pub extern crate secp256k1;
86
87#[cfg(feature = "serde")]
88#[macro_use]
89extern crate actual_serde as serde;
90
91#[cfg(test)]
92#[macro_use]
93mod test_macros;
94mod internal_macros;
95#[cfg(feature = "serde")]
96mod serde_utils;
97
98#[macro_use]
99pub mod p2p;
100pub mod address;
101pub mod bip152;
102pub mod bip158;
103pub mod bip32;
104pub mod blockdata;
105pub mod consensus;
106// Private until we either make this a crate or flatten it - still to be decided.
107pub(crate) mod crypto;
108pub mod error;
109pub mod hash_types;
110pub mod merkle_tree;
111pub mod network;
112pub mod policy;
113pub mod pow;
114pub mod psbt;
115pub mod sign_message;
116pub mod taproot;
117
118#[rustfmt::skip]                // Keep public re-exports separate.
119#[doc(inline)]
120pub use crate::{
121    address::{Address, AddressType, KnownHrp},
122    amount::{Amount, Denomination, SignedAmount},
123    bip158::{FilterHash, FilterHeader},
124    bip32::XKeyIdentifier,
125    blockdata::block::{self, Block, BlockHash, TxMerkleNode, WitnessMerkleNode, WitnessCommitment},
126    blockdata::constants,
127    blockdata::fee_rate::FeeRate,
128    blockdata::locktime::{self, absolute, relative},
129    blockdata::opcodes::{self, Opcode},
130    blockdata::script::witness_program::{self, WitnessProgram},
131    blockdata::script::witness_version::{self, WitnessVersion},
132    blockdata::script::{self, Script, ScriptBuf, ScriptHash, WScriptHash},
133    blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut, Txid, Wtxid},
134    blockdata::weight::Weight,
135    blockdata::witness::{self, Witness},
136    consensus::encode::VarInt,
137    consensus::params,
138    crypto::ecdsa,
139    crypto::key::{self, PrivateKey, PubkeyHash, PublicKey, CompressedPublicKey, WPubkeyHash, XOnlyPublicKey},
140    crypto::sighash::{self, LegacySighash, SegwitV0Sighash, TapSighash, TapSighashTag},
141    merkle_tree::MerkleBlock,
142    network::{Network, NetworkKind},
143    pow::{CompactTarget, Target, Work},
144    psbt::Psbt,
145    sighash::{EcdsaSighashType, TapSighashType},
146    taproot::{TapBranchTag, TapLeafHash, TapLeafTag, TapNodeHash, TapTweakHash, TapTweakTag},
147};
148
149#[rustfmt::skip]
150#[allow(unused_imports)]
151mod prelude {
152    #[cfg(all(not(feature = "std"), not(test)))]
153    pub use alloc::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, slice, rc};
154
155    #[cfg(all(not(feature = "std"), not(test), any(not(rust_v_1_60), target_has_atomic = "ptr")))]
156    pub use alloc::sync;
157
158    #[cfg(any(feature = "std", test))]
159    pub use std::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, rc, sync};
160
161    #[cfg(all(not(feature = "std"), not(test)))]
162    pub use alloc::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
163
164    #[cfg(any(feature = "std", test))]
165    pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
166
167    pub use crate::io::sink;
168
169    pub use hex::DisplayHex;
170}
171
172pub mod amount {
173    //! Bitcoin amounts.
174    //!
175    //! This module mainly introduces the [Amount] and [SignedAmount] types.
176    //! We refer to the documentation on the types for more information.
177
178    use crate::consensus::{encode, Decodable, Encodable};
179    use crate::io::{Read, Write};
180
181    #[rustfmt::skip]            // Keep public re-exports separate.
182    #[doc(inline)]
183    pub use units::amount::{
184        Amount, CheckedSum, Denomination, Display, ParseAmountError, SignedAmount,
185    };
186    #[cfg(feature = "serde")]
187    pub use units::amount::serde;
188
189    impl Decodable for Amount {
190        #[inline]
191        fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
192            Ok(Amount::from_sat(Decodable::consensus_decode(r)?))
193        }
194    }
195
196    impl Encodable for Amount {
197        #[inline]
198        fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
199            self.to_sat().consensus_encode(w)
200        }
201    }
202}
203
204/// Unit parsing utilities.
205pub mod parse {
206    /// Re-export everything from the [`units::parse`] module.
207    pub use units::parse::ParseIntError;
208}