Skip to content

Commit

Permalink
bitcoin: Use no_std attribute
Browse files Browse the repository at this point in the history
As we do for other crates; default to `no_std`.

The major issues with this is that we have, up until now, assumed we
have `extern crate std` in tests. Most of this patch is fixing the
feature gating to use stuff from `extern crate alloc` and correctly
feature gating on "std" if required.
  • Loading branch information
tcharding committed May 3, 2024
1 parent 9ed6741 commit 59d831f
Show file tree
Hide file tree
Showing 22 changed files with 68 additions and 25 deletions.
13 changes: 8 additions & 5 deletions bitcoin/src/bip158.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,17 +561,20 @@ impl<'a, W: Write> BitStreamWriter<'a, W> {

#[cfg(test)]
mod test {
use std::collections::HashMap;

use hex::test_hex_unwrap as hex;
use serde_json::Value;

use super::*;
use crate::consensus::encode::deserialize;
use crate::ScriptBuf;

#[test]
#[cfg(feature = "std")]
fn test_blockfilters() {
use std::collections::HashMap;

use serde_json::Value;

use crate::consensus::encode::deserialize;
use crate::ScriptBuf;

// test vectors from: https://github.com/jimpo/bitcoin/blob/c7efb652f3543b001b4dd22186a354605b14f47e/src/test/data/blockfilters.json
let data = include_str!("../tests/data/blockfilters.json");

Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,8 @@ mod benches {

use super::Block;
use crate::consensus::{deserialize, Decodable, Encodable};
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[bench]
pub fn bench_stream_reader(bh: &mut Bencher) {
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/blockdata/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ mod test {
use super::*;
use crate::consensus::encode::serialize;
use crate::consensus::params;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn bitcoin_genesis_first_transaction() {
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/blockdata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub mod fee_rate {
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn fee_convenience_functions_agree() {
Expand Down
6 changes: 4 additions & 2 deletions bitcoin/src/blockdata/opcodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,10 +541,9 @@ impl Ordinary {

#[cfg(test)]
mod tests {
use std::collections::HashSet;

use super::*;

#[cfg(feature = "std")]
macro_rules! roundtrip {
($unique:expr, $op:ident) => {
assert_eq!($op, Opcode::from($op.to_u8()));
Expand Down Expand Up @@ -631,7 +630,10 @@ mod tests {
}

#[test]
#[cfg(feature = "std")]
fn str_roundtrip() {
use std::collections::HashSet;

let mut unique = HashSet::new();
roundtrip!(unique, OP_PUSHBYTES_0);
roundtrip!(unique, OP_PUSHBYTES_1);
Expand Down
7 changes: 5 additions & 2 deletions bitcoin/src/blockdata/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2039,7 +2039,7 @@ mod tests {
}

#[test]
#[cfg(feature = "bitcoinconsensus")]
#[cfg(all(feature = "bitcoinconsensus", feature = "std"))]
fn transaction_verify() {
use std::collections::HashMap;

Expand Down Expand Up @@ -2433,9 +2433,10 @@ mod tests {
}

#[test]
#[cfg(feature = "std")]
fn sequence_debug_output() {
let seq = Sequence::from_seconds_floor(1000);
println!("{:?}", seq)
std::println!("{:?}", seq)
}

#[test]
Expand Down Expand Up @@ -2470,6 +2471,8 @@ mod benches {

use super::Transaction;
use crate::consensus::{deserialize, Encodable};
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

const SOME_TX: &str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";

Expand Down
3 changes: 2 additions & 1 deletion bitcoin/src/blockdata/witness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -567,13 +567,14 @@ mod test {
}

#[test]
#[cfg(feature = "std")]
fn witness_debug_can_display_empty_instruction() {
let witness = Witness {
witness_elements: 1,
content: append_u32_vec(vec![], &[0]),
indices_start: 2,
};
println!("{:?}", witness);
std::println!("{:?}", witness);
}

#[test]
Expand Down
8 changes: 6 additions & 2 deletions bitcoin/src/crypto/sighash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1448,14 +1448,14 @@ impl<E: std::error::Error + 'static> std::error::Error for SigningDataError<E> {

#[cfg(test)]
mod tests {
use std::str::FromStr;

use hashes::HashEngine;
use hex::{test_hex_unwrap as hex, FromHex};

use super::*;
use crate::blockdata::locktime::absolute;
use crate::consensus::deserialize;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

extern crate serde_json;

Expand Down Expand Up @@ -1770,6 +1770,8 @@ mod tests {
#[cfg(feature = "serde")]
#[test]
fn bip_341_sighash_tests() {
use core::str::FromStr;

use hex::DisplayHex;

fn sighash_deser_numeric<'de, D>(deserializer: D) -> Result<TapSighashType, D::Error>
Expand Down Expand Up @@ -1962,6 +1964,8 @@ mod tests {

#[test]
fn sighashtype_fromstr_display() {
use core::str::FromStr;

let sighashtypes = vec![
("SIGHASH_DEFAULT", TapSighashType::Default),
("SIGHASH_ALL", TapSighashType::All),
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/hash_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub use crate::{
mod tests {
use super::*;
use crate::hashes::Hash;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;
use crate::{
LegacySighash, PubkeyHash, ScriptHash, SegwitV0Sighash, TapSighash, WPubkeyHash,
WScriptHash, XKeyIdentifier,
Expand Down
16 changes: 10 additions & 6 deletions bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
//! happen the implementations diverge one day.
//! * `ordered` - (dependency), adds implementations of `ArbitraryOrdOrd` to some structs.

#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
#![no_std]
// Experimental features we need.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(bench, feature(test))]
Expand All @@ -55,6 +55,9 @@ extern crate test;
#[macro_use]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "base64")]
/// Encodes and decodes base64 as bytes or utf8.
pub extern crate base64;
Expand Down Expand Up @@ -141,22 +144,23 @@ pub use crate::{
taproot::{TapBranchTag, TapLeafHash, TapLeafTag, TapNodeHash, TapTweakHash, TapTweakTag},
};

/// The `rust-bitcoin` crate requires an allocator.
#[rustfmt::skip]
#[allow(unused_imports)]
mod prelude {
#[cfg(all(not(feature = "std"), not(test)))]
#[cfg(not(feature = "std"))]
pub use alloc::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, slice, rc};

#[cfg(all(not(feature = "std"), not(test), any(not(rust_v_1_60), target_has_atomic = "ptr")))]
#[cfg(all(not(feature = "std"), any(not(rust_v_1_60), target_has_atomic = "ptr")))]
pub use alloc::sync;

#[cfg(any(feature = "std", test))]
#[cfg(feature = "std")]
pub use std::{string::{String, ToString}, vec::Vec, boxed::Box, borrow::{Borrow, BorrowMut, Cow, ToOwned}, rc, sync};

#[cfg(all(not(feature = "std"), not(test)))]
#[cfg(not(feature = "std"))]
pub use alloc::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};

#[cfg(any(feature = "std", test))]
#[cfg(feature = "std")]
pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};

pub use crate::io::sink;
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,8 @@ mod tests {
use super::Network;
use crate::consensus::encode::{deserialize, serialize};
use crate::p2p::ServiceFlags;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn serialize_test() {
Expand Down
3 changes: 3 additions & 0 deletions bitcoin/src/p2p/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use io::{BufRead, Read, Write};

use crate::consensus::encode::{self, Decodable, Encodable, ReadExt, VarInt, WriteExt};
use crate::p2p::ServiceFlags;
use crate::prelude::*;

/// A message which can be sent on the Bitcoin network
#[derive(Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -311,6 +312,8 @@ mod test {
use super::{AddrV2, AddrV2Message, Address};
use crate::consensus::encode::{deserialize, serialize};
use crate::p2p::ServiceFlags;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn serialize_address_test() {
Expand Down
3 changes: 3 additions & 0 deletions bitcoin/src/p2p/message_blockdata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::blockdata::transaction::{Txid, Wtxid};
use crate::consensus::encode::{self, Decodable, Encodable};
use crate::internal_macros::impl_consensus_encoding;
use crate::p2p;
use crate::prelude::*;

/// An inventory item.
#[derive(PartialEq, Eq, Clone, Debug, Copy, Hash, PartialOrd, Ord)]
Expand Down Expand Up @@ -150,6 +151,8 @@ mod tests {

use super::{GetBlocksMessage, GetHeadersMessage};
use crate::consensus::encode::{deserialize, serialize};
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn getblocks_message_test() {
Expand Down
1 change: 1 addition & 0 deletions bitcoin/src/p2p/message_bloom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use io::{BufRead, Write};

use crate::consensus::{encode, Decodable, Encodable, ReadExt};
use crate::internal_macros::impl_consensus_encoding;
use crate::prelude::*;

/// `filterload` message sets the current bloom filter
#[derive(Clone, PartialEq, Eq, Debug)]
Expand Down
1 change: 1 addition & 0 deletions bitcoin/src/p2p/message_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use crate::bip158::{FilterHash, FilterHeader};
use crate::blockdata::block::BlockHash;
use crate::internal_macros::impl_consensus_encoding;
use crate::prelude::*;

/// getcfilters message
#[derive(PartialEq, Eq, Clone, Debug)]
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/p2p/message_network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ mod tests {
use super::{Reject, RejectReason, VersionMessage};
use crate::consensus::encode::{deserialize, serialize};
use crate::p2p::ServiceFlags;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn version_message_test() {
Expand Down
4 changes: 3 additions & 1 deletion bitcoin/src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,8 @@ impl kani::Arbitrary for U256 {
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

impl<T: Into<u128>> From<T> for Target {
fn from(x: T) -> Self { Self(U256::from(x)) }
Expand Down Expand Up @@ -1710,7 +1712,7 @@ mod tests {

#[test]
fn target_is_met_by_for_target_equals_hash() {
use std::str::FromStr;
use core::str::FromStr;

use hashes::Hash;

Expand Down
2 changes: 1 addition & 1 deletion bitcoin/src/psbt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1568,7 +1568,7 @@ mod tests {

mod bip_vectors {
#[cfg(feature = "base64")]
use std::str::FromStr;
use core::str::FromStr;

use super::*;
use crate::psbt::map::Map;
Expand Down
2 changes: 2 additions & 0 deletions bitcoin/src/sign_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ pub fn signed_msg_hash(msg: &str) -> sha256d::Hash {
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)] // Less maintenance to just import this in tests.
use crate::prelude::*;

#[test]
fn test_signed_msg_hash() {
Expand Down
4 changes: 3 additions & 1 deletion bitcoin/tests/bip_174.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! Tests PSBT integration vectors from BIP 174
//! defined at <https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki#test-vectors>

#![cfg(feature = "std")]

use core::str::FromStr;
use std::collections::BTreeMap;
use std::str::FromStr;

use bitcoin::bip32::{Fingerprint, IntoDerivationPath, KeySource, Xpriv, Xpub};
use bitcoin::blockdata::opcodes::OP_0;
Expand Down
4 changes: 2 additions & 2 deletions bitcoin/tests/psbt-sign-taproot.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![cfg(not(feature = "rand-std"))]
#![cfg(all(not(feature = "rand-std"), feature = "std"))]

use core::str::FromStr;
use std::collections::BTreeMap;
use std::str::FromStr;

use bitcoin::bip32::{DerivationPath, Fingerprint};
use bitcoin::consensus::encode::serialize_hex;
Expand Down
4 changes: 2 additions & 2 deletions bitcoin/tests/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
// let mut file = File::create("/tmp/script_bincode").unwrap();
// file.write_all(&got).unwrap();

#![cfg(feature = "serde")]
#![cfg(all(feature = "serde", feature = "std"))]

use core::str::FromStr;
use std::collections::BTreeMap;
use std::str::FromStr;

use bincode::serialize;
use bitcoin::bip32::{ChildNumber, KeySource, Xpriv, Xpub};
Expand Down

0 comments on commit 59d831f

Please sign in to comment.