sapio_bitcoin/
lib.rs

1// Rust Bitcoin Library
2// Written in 2014 by
3//   Andrew Poelstra <apoelstra@wpsoftware.net>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! # Rust Bitcoin Library
16//!
17//! This is a library that supports the Bitcoin network protocol and associated
18//! primitives. It is designed for Rust programs built to work with the Bitcoin
19//! network.
20//!
21//! It is also written entirely in Rust to illustrate the benefits of strong type
22//! safety, including ownership and lifetime, for financial and/or cryptographic
23//! software.
24//!
25//! See README.md for detailed documentation about development and supported
26//! environments.
27//!
28//! ## Available feature flags
29//!
30//! * `std` - the usual dependency on `std` (default).
31//! * `secp-recovery` - enables calculating public key from a signature and message.
32//! * `base64` - (dependency), enables encoding of PSBTs and message signatures.
33//! * `unstable` - enables unstable features for testing.
34//! * `rand` - (dependency), makes it more convenient to generate random values.
35//! * `use-serde` - (dependency), implements `serde`-based serialization and
36//!                 deserialization.
37//! * `secp-lowmemory` - optimizations for low-memory devices.
38//! * `no-std` - enables additional features required for this crate to be usable
39//!              without std. Does **not** disable `std`. Depends on `hashbrown`
40//!              and `core2`.
41//!
42
43#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
44
45// Experimental features we need
46#![cfg_attr(all(test, feature = "unstable"), feature(test))]
47
48#![cfg_attr(docsrs, feature(doc_cfg))]
49
50// Coding conventions
51#![forbid(unsafe_code)]
52#![deny(non_upper_case_globals)]
53#![deny(non_camel_case_types)]
54#![deny(non_snake_case)]
55#![deny(unused_mut)]
56#![deny(dead_code)]
57#![deny(unused_imports)]
58#![deny(missing_docs)]
59#![deny(unused_must_use)]
60#![deny(broken_intra_doc_links)]
61
62#[cfg(not(any(feature = "std", feature = "no-std")))]
63compile_error!("at least one of the `std` or `no-std` features must be enabled");
64
65// Disable 16-bit support at least for now as we can't guarantee it yet.
66#[cfg(target_pointer_width = "16")]
67compile_error!("rust-bitcoin currently only supports architectures with pointers wider
68                than 16 bits, let us know if you want 16-bit support. Note that we do
69                NOT guarantee that we will implement it!");
70
71#[cfg(feature = "no-std")]
72#[macro_use]
73extern crate alloc;
74#[cfg(feature = "no-std")]
75extern crate core2;
76
77#[cfg(any(feature = "std", test))]
78extern crate core; // for Rust 1.29 and no-std tests
79
80// Re-exported dependencies.
81#[macro_use] pub extern crate bitcoin_hashes as hashes;
82pub extern crate secp256k1;
83pub extern crate bech32;
84
85#[cfg(feature = "no-std")]
86extern crate hashbrown;
87
88#[cfg(feature = "base64")]
89#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
90pub extern crate base64;
91
92#[cfg(feature="bitcoinconsensus")] extern crate bitcoinconsensus;
93#[cfg(feature = "serde")] #[macro_use] extern crate serde;
94#[cfg(all(test, feature = "serde"))] extern crate serde_json;
95#[cfg(all(test, feature = "serde"))] extern crate serde_test;
96#[cfg(all(test, feature = "serde"))] extern crate bincode;
97#[cfg(all(test, feature = "unstable"))] extern crate test;
98#[cfg(feature = "schemars")] extern crate schemars;
99
100#[cfg(target_pointer_width = "16")]
101compile_error!("rust-bitcoin cannot be used on 16-bit architectures");
102
103#[cfg(test)]
104#[macro_use]
105mod test_macros;
106#[macro_use]
107mod internal_macros;
108#[cfg(feature = "serde")]
109mod serde_utils;
110
111#[macro_use]
112pub mod network;
113pub mod blockdata;
114pub mod util;
115pub mod consensus;
116pub mod hash_types;
117pub mod policy;
118
119pub use hash_types::*;
120pub use blockdata::block::Block;
121pub use blockdata::block::BlockHeader;
122pub use blockdata::script::Script;
123pub use blockdata::transaction::Transaction;
124pub use blockdata::transaction::TxIn;
125pub use blockdata::transaction::TxOut;
126pub use blockdata::transaction::OutPoint;
127pub use blockdata::transaction::EcdsaSighashType;
128pub use blockdata::witness::Witness;
129pub use consensus::encode::VarInt;
130pub use network::constants::Network;
131pub use util::Error;
132pub use util::address::Address;
133pub use util::address::AddressType;
134pub use util::amount::Amount;
135pub use util::amount::Denomination;
136pub use util::amount::SignedAmount;
137pub use util::merkleblock::MerkleBlock;
138pub use util::sighash::SchnorrSighashType;
139
140pub use util::ecdsa::{self, EcdsaSig, EcdsaSigError};
141pub use util::schnorr::{self, SchnorrSig, SchnorrSigError};
142pub use util::key::{PrivateKey, PublicKey, XOnlyPublicKey, KeyPair};
143pub use util::psbt;
144#[allow(deprecated)]
145pub use blockdata::transaction::SigHashType;
146
147#[cfg(feature = "std")]
148use std::io;
149#[cfg(not(feature = "std"))]
150use core2::io;
151
152#[cfg(not(feature = "std"))]
153mod io_extras {
154    /// A writer which will move data into the void.
155    pub struct Sink {
156        _priv: (),
157    }
158
159    /// Creates an instance of a writer which will successfully consume all data.
160    pub const fn sink() -> Sink {
161        Sink { _priv: () }
162    }
163
164    impl core2::io::Write for Sink {
165        #[inline]
166        fn write(&mut self, buf: &[u8]) -> core2::io::Result<usize> {
167            Ok(buf.len())
168        }
169
170        #[inline]
171        fn flush(&mut self) -> core2::io::Result<()> {
172            Ok(())
173        }
174    }
175}
176
177mod prelude {
178    #[cfg(all(not(feature = "std"), not(test)))]
179    pub use alloc::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Cow, ToOwned}, slice, rc, sync};
180
181    #[cfg(any(feature = "std", test))]
182    pub use std::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Cow, ToOwned}, slice, rc, sync};
183
184    #[cfg(all(not(feature = "std"), not(test)))]
185    pub use alloc::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
186
187    #[cfg(any(feature = "std", test))]
188    pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
189
190    #[cfg(feature = "std")]
191    pub use std::io::sink;
192
193    #[cfg(not(feature = "std"))]
194    pub use io_extras::sink;
195
196    #[cfg(feature = "hashbrown")]
197    pub use hashbrown::HashSet;
198
199    #[cfg(not(feature = "hashbrown"))]
200    pub use std::collections::HashSet;
201}
202
203#[cfg(all(test, feature = "unstable"))] use tests::EmptyWrite;
204
205#[cfg(all(test, feature = "unstable"))]
206mod tests {
207    use core::fmt::Arguments;
208    use io::{IoSlice, Result, Write};
209
210    #[derive(Default, Clone, Debug, PartialEq, Eq)]
211    pub struct EmptyWrite;
212
213    impl Write for EmptyWrite {
214        fn write(&mut self, buf: &[u8]) -> Result<usize> {
215            Ok(buf.len())
216        }
217        fn write_vectored(&mut self, bufs: &[IoSlice]) -> Result<usize> {
218            Ok(bufs.iter().map(|s| s.len()).sum())
219        }
220        fn flush(&mut self) -> Result<()> {
221            Ok(())
222        }
223
224        fn write_all(&mut self, _: &[u8]) -> Result<()> {
225            Ok(())
226        }
227        fn write_fmt(&mut self, _: Arguments) -> Result<()> {
228            Ok(())
229        }
230    }
231}