bitcoin/
lib.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! # Rust Dogecoin Library
4//!
5//! This is a library that supports both the Bitcoin and Dogecoin network protocol
6//! and associated primitives. It is designed for Rust programs built to work with
7//! the Bitcoin and Dogecoin 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_notable_trait))]
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 dogecoin;
109pub mod error;
110pub mod hash_types;
111pub mod merkle_tree;
112pub mod network;
113pub mod policy;
114pub mod pow;
115pub mod psbt;
116pub mod sign_message;
117pub mod taproot;
118
119#[rustfmt::skip]                // Keep public re-exports separate.
120#[doc(inline)]
121pub use crate::{
122    address::{Address, AddressType, KnownHrp},
123    amount::{Amount, Denomination, SignedAmount},
124    bip158::{FilterHash, FilterHeader},
125    bip32::XKeyIdentifier,
126    blockdata::block::{self, Block, BlockHash, TxMerkleNode, WitnessMerkleNode, WitnessCommitment},
127    blockdata::constants,
128    blockdata::fee_rate::FeeRate,
129    blockdata::locktime::{self, absolute, relative},
130    blockdata::opcodes::{self, Opcode},
131    blockdata::script::witness_program::{self, WitnessProgram},
132    blockdata::script::witness_version::{self, WitnessVersion},
133    blockdata::script::{self, Script, ScriptBuf, ScriptHash, WScriptHash},
134    blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut, Txid, Wtxid},
135    blockdata::weight::Weight,
136    blockdata::witness::{self, Witness},
137    consensus::encode::VarInt,
138    consensus::params,
139    crypto::ecdsa,
140    crypto::key::{self, PrivateKey, PubkeyHash, PublicKey, CompressedPublicKey, WPubkeyHash, XOnlyPublicKey},
141    crypto::sighash::{self, LegacySighash, SegwitV0Sighash, TapSighash, TapSighashTag},
142    merkle_tree::MerkleBlock,
143    network::{Network, NetworkKind},
144    pow::{CompactTarget, Target, Work},
145    psbt::Psbt,
146    sighash::{EcdsaSighashType, TapSighashType},
147    taproot::{TapBranchTag, TapLeafHash, TapLeafTag, TapNodeHash, TapTweakHash, TapTweakTag},
148};
149
150#[rustfmt::skip]
151#[allow(unused_imports)]
152mod prelude {
153    #[cfg(all(not(feature = "std"), not(test)))]
154    pub use alloc::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, slice, rc};
155
156    #[cfg(all(not(feature = "std"), not(test), any(not(rust_v_1_60), target_has_atomic = "ptr")))]
157    pub use alloc::sync;
158
159    #[cfg(any(feature = "std", test))]
160    pub use std::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, rc, sync};
161
162    #[cfg(all(not(feature = "std"), not(test)))]
163    pub use alloc::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
164
165    #[cfg(any(feature = "std", test))]
166    pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
167
168    pub use crate::io::sink;
169
170    pub use hex::DisplayHex;
171}
172
173pub mod amount {
174    //! Bitcoin amounts.
175    //!
176    //! This module mainly introduces the [Amount] and [SignedAmount] types.
177    //! We refer to the documentation on the types for more information.
178
179    use crate::consensus::{encode, Decodable, Encodable};
180    use crate::io::{Read, Write};
181
182    #[rustfmt::skip]            // Keep public re-exports separate.
183    #[doc(inline)]
184    pub use units::amount::{
185        Amount, CheckedSum, Denomination, Display, ParseAmountError, SignedAmount,
186    };
187    #[cfg(feature = "serde")]
188    pub use units::amount::serde;
189
190    impl Decodable for Amount {
191        #[inline]
192        fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
193            Ok(Amount::from_sat(Decodable::consensus_decode(r)?))
194        }
195    }
196
197    impl Encodable for Amount {
198        #[inline]
199        fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
200            self.to_sat().consensus_encode(w)
201        }
202    }
203}
204
205/// Unit parsing utilities.
206pub mod parse {
207    /// Re-export everything from the [`units::parse`] module.
208    pub use units::parse::ParseIntError;
209}