bitnet/
lib.rs

1// Written in 2014 by Andrew Poelstra <apoelstra@wpsoftware.net>
2// SPDX-License-Identifier: CC0-1.0
3
4//! # Rust Bitcoin Library
5//!
6//! This is a library that supports the Bitcoin network protocol and associated
7//! primitives. It is designed for Rust programs built to work with the Bitcoin
8//! network.
9//!
10//! It is also written entirely in Rust to illustrate the benefits of strong type
11//! safety, including ownership and lifetime, for financial and/or cryptographic
12//! software.
13//!
14//! See README.md for detailed documentation about development and supported
15//! environments.
16//!
17//! ## Available feature flags
18//!
19//! * `std` - the usual dependency on `std` (default).
20//! * `secp-recovery` - enables calculating public key from a signature and message.
21//! * `base64` - (dependency), enables encoding of PSBTs and message signatures.
22//! * `rand` - (dependency), makes it more convenient to generate random values.
23//! * `serde` - (dependency), implements `serde`-based serialization and
24//!                 deserialization.
25//! * `secp-lowmemory` - optimizations for low-memory devices.
26//! * `no-std` - enables additional features required for this crate to be usable
27//!              without std. Does **not** disable `std`. Depends on `core2`.
28//! * `bitcoinconsensus-std` - enables `std` in `bitcoinconsensus` and communicates it
29//!                            to this crate so it knows how to implement
30//!                            `std::error::Error`. At this time there's a hack to
31//!                            achieve the same without this feature but it could
32//!                            happen the implementations diverge one day.
33
34#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
35// Experimental features we need.
36#![cfg_attr(bench, feature(test))]
37#![cfg_attr(docsrs, feature(doc_cfg))]
38// Coding conventions
39#![warn(missing_docs)]
40// Instead of littering the codebase for non-fuzzing code just globally allow.
41#![cfg_attr(fuzzing, allow(dead_code, unused_imports))]
42
43#[cfg(not(any(feature = "std", feature = "no-std")))]
44compile_error!("at least one of the `std` or `no-std` features must be enabled");
45
46// Disable 16-bit support at least for now as we can't guarantee it yet.
47#[cfg(target_pointer_width = "16")]
48compile_error!(
49    "rust-bitcoin currently only supports architectures with pointers wider than 16 bits, let us
50    know if you want 16-bit support. Note that we do NOT guarantee that we will implement it!"
51);
52
53#[cfg(bench)]
54extern crate test;
55
56#[macro_use]
57extern crate alloc;
58
59#[cfg(feature = "base64")]
60#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
61pub extern crate base64;
62pub extern crate bech32;
63pub extern crate bitcoin_hashes as hashes;
64#[cfg(feature = "bitcoinconsensus")]
65#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
66pub extern crate bitcoinconsensus;
67pub extern crate secp256k1;
68
69#[cfg(feature = "serde")]
70#[macro_use]
71extern crate actual_serde as serde;
72
73#[cfg(test)]
74#[macro_use]
75mod test_macros;
76mod internal_macros;
77mod parse;
78#[cfg(feature = "serde")]
79mod serde_utils;
80
81#[macro_use]
82pub mod network;
83pub mod address;
84pub mod amount;
85pub mod base58;
86pub mod bip152;
87pub mod bip158;
88pub mod bip32;
89pub mod blockdata;
90pub mod consensus;
91// Private until we either make this a crate or flatten it - still to be decided.
92pub(crate) mod crypto;
93pub mod error;
94pub mod hash_types;
95pub mod merkle_tree;
96pub mod policy;
97pub mod pow;
98pub mod psbt;
99pub mod sign_message;
100pub mod string;
101pub mod taproot;
102pub mod util;
103
104// May depend on crate features and we don't want to bother with it
105#[allow(unused)]
106#[cfg(feature = "std")]
107use std::error::Error as StdError;
108#[cfg(feature = "std")]
109use std::io;
110
111#[allow(unused)]
112#[cfg(not(feature = "std"))]
113use core2::error::Error as StdError;
114#[cfg(not(feature = "std"))]
115use core2::io;
116
117pub use crate::address::{Address, AddressType};
118pub use crate::amount::{Amount, Denomination, SignedAmount};
119pub use crate::blockdata::block::{self, Block};
120pub use crate::blockdata::fee_rate::FeeRate;
121pub use crate::blockdata::locktime::{self, absolute, relative};
122pub use crate::blockdata::script::{self, Script, ScriptBuf};
123pub use crate::blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut};
124pub use crate::blockdata::weight::Weight;
125pub use crate::blockdata::witness::{self, Witness};
126pub use crate::blockdata::{constants, opcodes};
127pub use crate::consensus::encode::VarInt;
128pub use crate::crypto::key::{self, PrivateKey, PublicKey};
129pub use crate::crypto::{ecdsa, sighash};
130pub use crate::error::Error;
131pub use crate::hash_types::{
132    BlockHash, PubkeyHash, ScriptHash, Txid, WPubkeyHash, WScriptHash, Wtxid,
133};
134pub use crate::merkle_tree::MerkleBlock;
135pub use crate::network::constants::Network;
136pub use crate::pow::{CompactTarget, Target, Work};
137
138#[cfg(not(feature = "std"))]
139mod io_extras {
140    /// A writer which will move data into the void.
141    pub struct Sink {
142        _priv: (),
143    }
144
145    /// Creates an instance of a writer which will successfully consume all data.
146    pub const fn sink() -> Sink { Sink { _priv: () } }
147
148    impl core2::io::Write for Sink {
149        #[inline]
150        fn write(&mut self, buf: &[u8]) -> core2::io::Result<usize> { Ok(buf.len()) }
151
152        #[inline]
153        fn flush(&mut self) -> core2::io::Result<()> { Ok(()) }
154    }
155}
156
157#[rustfmt::skip]
158mod prelude {
159    #[cfg(all(not(feature = "std"), not(test)))]
160    pub use alloc::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, Cow, ToOwned}, slice, rc};
161
162    #[cfg(all(not(feature = "std"), not(test), any(not(rust_v_1_60), target_has_atomic = "ptr")))]
163    pub use alloc::sync;
164
165    #[cfg(any(feature = "std", test))]
166    pub use std::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, Cow, ToOwned}, slice, rc, sync};
167
168    #[cfg(all(not(feature = "std"), not(test)))]
169    pub use alloc::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
170
171    #[cfg(any(feature = "std", test))]
172    pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
173
174    #[cfg(feature = "std")]
175    pub use std::io::sink;
176
177    #[cfg(not(feature = "std"))]
178    pub use crate::io_extras::sink;
179
180    pub use bitcoin_internals::hex::display::DisplayHex;
181}
182
183#[cfg(bench)]
184use bench::EmptyWrite;
185
186#[cfg(bench)]
187mod bench {
188    use core::fmt::Arguments;
189
190    use crate::io::{IoSlice, Result, Write};
191
192    #[derive(Default, Clone, Debug, PartialEq, Eq)]
193    pub struct EmptyWrite;
194
195    impl Write for EmptyWrite {
196        fn write(&mut self, buf: &[u8]) -> Result<usize> { Ok(buf.len()) }
197        fn write_vectored(&mut self, bufs: &[IoSlice]) -> Result<usize> {
198            Ok(bufs.iter().map(|s| s.len()).sum())
199        }
200        fn flush(&mut self) -> Result<()> { Ok(()) }
201
202        fn write_all(&mut self, _: &[u8]) -> Result<()> { Ok(()) }
203        fn write_fmt(&mut self, _: Arguments) -> Result<()> { Ok(()) }
204    }
205}