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