Merge rust-bitcoin/rust-bitcoin#6992: primitives: Correct and clarify docs
What changed, and why it matters
This is a documentation-only pull request for the rust-bitcoin primitives crate. It corrects and clarifies comments, README text, and rustdoc descriptions. No executable code, logic, or behavior was changed. The changes improve accuracy of descriptions about block validation, transaction decoding rules, opcodes, and witness behavior, but they do not alter how the software runs or fix any vulnerability.
No security action required. This is a documentation-only change. Reviewers may optionally verify that the corrected documentation now accurately reflects the existing implementation behavior, but no code deployment or vulnerability response is needed.
Security signals we found
Documentation-only change explicitly labeled 'Docs only changes' in PR description
No code logic, function signatures, or control flow modified
No unsafe blocks, cryptographic operations, or network/serialization parsing changes
References to CVE-2012-2459 are in comments only, not new mitigations
Evidence from the diff
The merge commit contains only documentation edits across 16 files in primitives/. Changes include: correcting stale/unstable README notes, documenting crate features and MSRV, fixing opcode descriptions (e.g., OP_ENDIF, OP_WITHIN argument order, OP_HASH160 hash name), clarifying that block validate() does not check proof of work, adding decoder rejection rules for TransactionDecoder and BlockDecoder, correcting ntxid computation description to include witness clearing, and standardizing grammar/capitalization. No Rust source logic, function signatures, control flow, or safety checks were modified.
Changed components
primitives/README.mdprimitives/src/block.rsprimitives/src/hash_types/ntxid.rsprimitives/src/hash_types/transaction_merkle_node.rsprimitives/src/hash_types/txid.rsprimitives/src/hash_types/witness_merkle_node.rsprimitives/src/lib.rsprimitives/src/merkle_tree.rsprimitives/src/opcodes.rsprimitives/src/script/borrowed.rsprimitives/src/script/builder.rsprimitives/src/script/mod.rsprimitives/src/script/owned.rsprimitives/src/script/push_bytes.rsprimitives/src/transaction.rsprimitives/src/witness.rsInspect captured patch +213 / −166
### primitives/README.md
@@ -3,11 +3,6 @@
This crate provides primitive data types that are used throughout the
[`rust-bitcoin`](https://github.com/rust-bitcoin) ecosystem.
-## Semver compliance
-
-Functions marked as unstable (e.g. `foo__unstable`) are not guaranteed to uphold semver compliance.
-They are primarily provided to support `rust-bitcoin`.
-
## `bitcoin-primitives 0.102.0`
This is the start of the 1.0.0 release candidate cycle. We will
### primitives/src/block.rs
@@ -114,14 +114,11 @@ pub use crate::hash_types::{BlockHash, BlockHashDecoder, BlockHashEncoder, Witne
#[cfg(feature = "alloc")]
const WITNESS_COMMITMENT_MAGIC: [u8; 6] = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];
-/// Marker for whether or not a block has been validated.
+/// Marker for whether or not a block has passed the checks in [`validate`].
///
-/// We define valid as:
+/// See [`validate`] for what is checked.
///
-/// * The Merkle root of the header matches Merkle root of the transaction list.
-/// * The witness commitment in coinbase matches the transaction list.
-///
-/// See `bitcoin::block::BlockUncheckedExt::validate()`.
+/// [`validate`]: Block<Unchecked>::validate
#[cfg(feature = "alloc")]
pub trait Validation: sealed::Validation + Sync + Send + Sized + Unpin {
/// Indicates whether this [`Validation`] is [`Checked`] or not.
@@ -163,9 +160,13 @@ impl Block<Unchecked> {
Self { header, transactions, witness_root: None, _marker: PhantomData::<Unchecked> }
}
- /// Ignores block validation logic and just assumes you know what you are doing.
+ /// Skips the block checks performed by [`validate`].
///
/// You should only use this function if you trust the block i.e., it comes from a trusted node.
+ /// Otherwise use [`validate`].
+ ///
+ /// `witness_root` is returned by [`cached_witness_root`], pass `None` if it has not been
+ /// computed.
///
/// # Examples
///
@@ -224,20 +225,29 @@ impl Block<Unchecked> {
#[inline]
pub fn as_parts(&self) -> (&Header, &[Transaction]) { (&self.header, &self.transactions) }
- /// Validates (or checks) a block.
+ /// Checks a block's coinbase, Merkle root, and witness commitment.
///
- /// We define valid as:
+ /// This checks that:
///
- /// * The Merkle root of the header matches Merkle root of the transaction list.
- /// * The witness commitment in coinbase matches the transaction list.
+ /// * The first transaction is a coinbase transaction.
+ /// * The Merkle root of the header matches the Merkle root of the transaction list.
+ /// * If the coinbase has a witness commitment, it matches the transaction list and its
+ /// witness has exactly one 32-byte reserved value. A commitment is required if any
+ /// transaction has witness data.
+ ///
+ /// This does not check proof of work or fully validate the transactions. The witness root
+ /// computed when a commitment is present is cached and can be retrieved with
+ /// [`cached_witness_root`]. If you trust the block you can skip these checks with
+ /// [`assume_checked`].
///
/// # Errors
///
/// Returns an error if:
+ ///
/// * The block has no transactions.
/// * The first transaction is not a coinbase transaction.
/// * The Merkle root of the header does not match the Merkle root of the transaction list.
- /// * The witness commitment in the coinbase does not match the transaction list.
+ /// * A witness commitment is invalid or missing when witness data is present.
///
/// # Examples
///
@@ -312,7 +322,11 @@ impl Block<Unchecked> {
compute_merkle_root(&self.transactions) == Some(self.header.merkle_root)
}
- /// Computes the witness commitment for a list of transactions.
+ /// Computes the witness root and witness commitment for the block's transactions.
+ ///
+ /// The `witness_reserved_value` is the single item in the coinbase input witness.
+ ///
+ /// Returns [`None`] if the witness root cannot be computed, see [`compute_witness_root`].
pub fn compute_witness_commitment(
&self,
witness_reserved_value: &[u8],
@@ -460,7 +474,8 @@ impl From<&Block> for BlockHash {
fn from(block: &Block) -> Self { block.block_hash() }
}
-/// Marker that the block's merkle root has been successfully validated.
+/// Marker that the block passed the checks in [`validate`] or was marked checked with
+/// [`assume_checked`]. This does not imply full consensus validation.
///
/// # Examples
///
@@ -489,7 +504,9 @@ impl Validation for Checked {
const IS_CHECKED: bool = true;
}
-/// Marker that the block's merkle root has not been validated.
+/// Marker that the block has not passed the checks in [`validate`].
+///
+/// [`validate`]: Block<Unchecked>::validate
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg(feature = "alloc")]
pub enum Unchecked {}
@@ -587,6 +604,11 @@ crate::decoder_newtype! {
/// The decoder for the [`Block`] type.
///
/// This decoder can only produce a [`Block<Unchecked>`].
+ ///
+ /// Decoding fails if the block weight exceeds the maximum block weight of 4,000,000 weight
+ /// units, or if any of its transactions fail to decode (see [`TransactionDecoder`]).
+ ///
+ /// [`TransactionDecoder`]: crate::transaction::TransactionDecoder
#[derive(Debug, Clone)]
pub struct BlockDecoder(BlockInnerDecoder);
@@ -625,9 +647,9 @@ fn block_weight_wu(transactions: &[Transaction]) -> u64 {
/// # Returns
///
/// [`None`] if the iterator was empty, or if the transaction list contains
-/// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
+/// consecutive duplicates which would trigger CVE-2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
-/// compute their merkle roots.
+/// compute their Merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the [`Option`] returned by this method!
@@ -646,9 +668,9 @@ where
/// # Returns
///
/// [`None`] if the iterator was empty, or if the transaction list contains
-/// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
+/// consecutive duplicates which would trigger CVE-2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
-/// compute their merkle roots.
+/// compute their Merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the [`Option`] returned by this method!
### primitives/src/hash_types/ntxid.rs
@@ -14,14 +14,14 @@ use hashes::sha256d;
/// Computed on a transaction that has had the signatures removed.
///
/// This type is needed only for legacy (pre-Segwit or P2SH-wrapped segwit version 0)
-/// applications. This method clears the `script_sig` field of each input, which in Segwit
-/// transactions is already empty, so for Segwit transactions the ntxid will be equal to the
-/// txid, and you should simply use the latter.
+/// applications. Computing it clears the `script_sig` and `witness` fields of each input. The
+/// `script_sig` in Segwit transactions is already empty, so for Segwit transactions the ntxid
+/// will be equal to the txid, and you should simply use the latter.
///
/// This gives a way to identify a transaction that is "the same" as another in the sense of
/// having the same inputs and outputs.
///
-/// A coinbase `script_sig` is not a signature and may contain a BIP-34 height commitment, so
+/// A coinbase `script_sig` is not a signature and may contain a BIP-0034 height commitment, so
/// for a coinbase transaction the ntxid is equal to the txid.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Ntxid(sha256d::Hash);
### primitives/src/hash_types/transaction_merkle_node.rs
@@ -29,23 +29,23 @@ type Inner = sha256d::Hash;
include!("./generic.rs");
impl TxMerkleNode {
- /// Convert a [`Txid`] hash to a leaf node of the tree.
+ /// Converts a [`Txid`] hash to a leaf node of the tree.
#[inline]
pub fn from_leaf(leaf: Txid) -> Self { MerkleNode::from_leaf(leaf) }
- /// Combine two nodes to get a single node. The final node of a tree is called the "root".
+ /// Combines two nodes to get a single node. The final node of a tree is called the "root".
#[inline]
#[must_use]
pub fn combine(&self, other: &Self) -> Self { MerkleNode::combine(self, other) }
- /// Given an iterator of leaves, compute the Merkle root.
+ /// Computes the Merkle root from an iterator of leaves.
///
/// # Returns
///
/// [`None`] if the iterator was empty, or if the transaction list contains
- /// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
+ /// consecutive duplicates which would trigger CVE-2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
- /// compute their merkle roots.
+ /// compute their Merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the [`Option`] returned by this method!
### primitives/src/hash_types/txid.rs
@@ -18,7 +18,7 @@ use crate::OutPoint;
///
/// For compatibility with the existing Bitcoin infrastructure and historical and current
/// versions of the Bitcoin Core software itself, this and other [`sha256d::Hash`] types, are
-/// serialized in reverse byte order when converted to a hex string via [`std::fmt::Display`]
+/// serialized in reverse byte order when converted to a hex string via [`core::fmt::Display`]
/// trait operations.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Txid(sha256d::Hash);
### primitives/src/hash_types/witness_merkle_node.rs
@@ -29,23 +29,23 @@ type Inner = sha256d::Hash;
include!("./generic.rs");
impl WitnessMerkleNode {
- /// Convert a [`Wtxid`] hash to a leaf node of the tree.
+ /// Converts a [`Wtxid`] hash to a leaf node of the tree.
#[inline]
pub fn from_leaf(leaf: Wtxid) -> Self { MerkleNode::from_leaf(leaf) }
- /// Combine two nodes to get a single node. The final node of a tree is called the "root".
+ /// Combines two nodes to get a single node. The final node of a tree is called the "root".
#[inline]
#[must_use]
pub fn combine(&self, other: &Self) -> Self { MerkleNode::combine(self, other) }
- /// Given an iterator of leaves, compute the Merkle root.
+ /// Computes the Merkle root from an iterator of leaves.
///
/// # Returns
///
/// [`None`] if the iterator was empty, or if the transaction list contains
- /// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
+ /// consecutive duplicates which would trigger CVE-2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
- /// compute their merkle roots.
+ /// compute their Merkle roots.
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the [`Option`] returned by this method!
### primitives/src/lib.rs
@@ -10,6 +10,17 @@
//! This crate can be used in a no-std environment but a lot of the functionality requires an
//! allocator i.e., requires the `alloc` feature to be enabled.
//!
+//! ## Features
+//!
+//! * `std` (default) - turns on `std` integration, mainly the `std::error::Error` trait. Implies
+//! `alloc`.
+//! * `alloc` - turns on the types that require an allocator, such as `Transaction`, `Block`,
+//! `Witness` and the script types.
+//! * `hex` (default) - turns on parsing and formatting types as hex strings.
+//! * `serde` - causes the crate to depend on `serde` and provide support for serializing and
+//! deserializing its types. Implies `alloc` and `hex`.
+//! * `arbitrary` - causes the crate to depend on `arbitrary` and implement the `Arbitrary` trait.
+//!
//! ### serde
//!
//! The consensus encodable types ([`Block`], [`block::Header`], [`Transaction`], [`TxIn`], and
@@ -29,6 +40,11 @@
//! # }
//! ```
//!
+//! ## MSRV
+//!
+//! This crate supports Rust 1.74, however some of its dependencies may not do so or may require
+//! pinning. Similarly, some features may require newer Rust version (implicitly or explicitly).
+//!
//! [`rust-bitcoin`]: <https://github.com/rust-bitcoin/rust-bitcoin>
#![no_std]
### primitives/src/merkle_tree.rs
@@ -39,20 +39,20 @@ pub(crate) trait MerkleNode: Copy + PartialEq {
/// The hash (TXID or WTXID) of a transaction in the tree.
type Leaf: TxIdentifier;
- /// Convert a hash to a leaf node of the tree.
+ /// Converts a hash to a leaf node of the tree.
fn from_leaf(leaf: Self::Leaf) -> Self;
- /// Combine two nodes to get a single node. The final node of a tree is called the "root".
+ /// Combines two nodes to get a single node. The final node of a tree is called the "root".
#[must_use]
fn combine(&self, other: &Self) -> Self;
- /// Given an iterator of leaves, compute the Merkle root.
+ /// Computes the Merkle root from an iterator of leaves.
///
/// # Returns
///
/// [`None`] if the iterator was empty, or if the transaction list contains
- /// consecutive duplicates which would trigger CVE 2012-2459. Blocks with duplicate
+ /// consecutive duplicates which would trigger CVE-2012-2459. Blocks with duplicate
/// transactions will always be invalid, so there is no harm in us refusing to
- /// compute their merkle roots.
+ /// compute their Merkle roots.
///
/// Also returns [`None`] if the `alloc` feature is disabled and `iter` has more than
/// 32,767 transactions.
@@ -81,7 +81,7 @@ pub(crate) trait MerkleNode: Copy + PartialEq {
if left.1 == right.1 {
// Reject duplicate trees since they are guaranteed-invalid (Bitcoin does
// not allow duplicate transactions in block) but can be used to confuse
- // nodes about legitimate blocks. See CVE 2012-2459 and the block comment
+ // nodes about legitimate blocks. See CVE-2012-2459 and the block comment
// below.
return None;
}
@@ -93,7 +93,7 @@ pub(crate) trait MerkleNode: Copy + PartialEq {
// ...then, deal with incomplete trees. Bitcoin does a weird thing in
// which it doubles-up nodes of the tree to fill out the tree, rather
// than treating incomplete branches specially. This makes this tree
- // construction vulnerable to collisions (see CVE 2012-2459).
+ // construction vulnerable to collisions (see CVE-2012-2459).
//
// (It is also vulnerable to collisions because it does not distinguish
// between internal nodes and transactions, but collisions of this
@@ -126,7 +126,7 @@ fn calculate_root_batched(mut nodes: Vec<[u8; 32]>) -> Option<[u8; 32]> {
}
while nodes.len() > 1 {
- // check consecutive duplicates which would trigger CVE 2012-245
+ // check consecutive duplicates which would trigger CVE-2012-2459
for pair in nodes.chunks_exact(2) {
if pair[0] == pair[1] {
return None;
@@ -202,7 +202,7 @@ impl MerkleNode for WitnessMerkleNode {
}
}
-/// Error types for the merkle tree module.
+/// Error types for the Merkle tree module.
pub mod error {
#[doc(inline)]
pub use crate::hash_types::{TxMerkleNodeDecoderError, WitnessMerkleNodeDecoderError};
@@ -242,7 +242,7 @@ mod tests {
#[test]
fn tx_merkle_node_duplicate_leaves() {
let leaf = Txid::from_byte_array([3; 32]);
- // Duplicate transaction list should be rejected (CVE 2012‑2459).
+ // Duplicate transaction list should be rejected (CVE-2012-2459).
let root = TxMerkleNode::calculate_root([leaf, leaf]);
assert_eq!(root, None);
}
### primitives/src/opcodes.rs
@@ -87,118 +87,118 @@ macro_rules! all_opcodes {
}
all_opcodes! {
- OP_1NEGATE => 0x4f, "Push the array `0x81` onto the stack.";
- OP_1 => 0x51, "Push the array `0x01` onto the stack.";
- OP_2 => 0x52, "Push the array `0x02` onto the stack.";
- OP_3 => 0x53, "Push the array `0x03` onto the stack.";
- OP_4 => 0x54, "Push the array `0x04` onto the stack.";
- OP_5 => 0x55, "Push the array `0x05` onto the stack.";
- OP_6 => 0x56, "Push the array `0x06` onto the stack.";
- OP_7 => 0x57, "Push the array `0x07` onto the stack.";
- OP_8 => 0x58, "Push the array `0x08` onto the stack.";
- OP_9 => 0x59, "Push the array `0x09` onto the stack.";
- OP_10 => 0x5a, "Push the array `0x0a` onto the stack.";
- OP_11 => 0x5b, "Push the array `0x0b` onto the stack.";
- OP_12 => 0x5c, "Push the array `0x0c` onto the stack.";
- OP_13 => 0x5d, "Push the array `0x0d` onto the stack.";
- OP_14 => 0x5e, "Push the array `0x0e` onto the stack.";
- OP_15 => 0x5f, "Push the array `0x0f` onto the stack.";
- OP_16 => 0x60, "Push the array `0x10` onto the stack.";
+ OP_1NEGATE => 0x4f, "Pushes the array `0x81` onto the stack.";
+ OP_1 => 0x51, "Pushes the array `0x01` onto the stack.";
+ OP_2 => 0x52, "Pushes the array `0x02` onto the stack.";
+ OP_3 => 0x53, "Pushes the array `0x03` onto the stack.";
+ OP_4 => 0x54, "Pushes the array `0x04` onto the stack.";
+ OP_5 => 0x55, "Pushes the array `0x05` onto the stack.";
+ OP_6 => 0x56, "Pushes the array `0x06` onto the stack.";
+ OP_7 => 0x57, "Pushes the array `0x07` onto the stack.";
+ OP_8 => 0x58, "Pushes the array `0x08` onto the stack.";
+ OP_9 => 0x59, "Pushes the array `0x09` onto the stack.";
+ OP_10 => 0x5a, "Pushes the array `0x0a` onto the stack.";
+ OP_11 => 0x5b, "Pushes the array `0x0b` onto the stack.";
+ OP_12 => 0x5c, "Pushes the array `0x0c` onto the stack.";
+ OP_13 => 0x5d, "Pushes the array `0x0d` onto the stack.";
+ OP_14 => 0x5e, "Pushes the array `0x0e` onto the stack.";
+ OP_15 => 0x5f, "Pushes the array `0x0f` onto the stack.";
+ OP_16 => 0x60, "Pushes the array `0x10` onto the stack.";
OP_NOP => 0x61, "Does nothing.";
- OP_IF => 0x63, "Pop and execute the next statements if a nonzero element was popped.";
- OP_NOTIF => 0x64, "Pop and execute the next statements if a zero element was popped.";
- OP_ELSE => 0x67, "Execute statements if those after the previous `OP_IF` were not, and vice-versa. \
+ OP_IF => 0x63, "Pops and executes the next statements if a nonzero element was popped.";
+ OP_NOTIF => 0x64, "Pops and executes the next statements if a zero element was popped.";
+ OP_ELSE => 0x67, "Executes statements if those after the previous `OP_IF` were not, and vice-versa. \
If there is no previous `OP_IF`, this acts as a RETURN.";
- OP_ENDIF => 0x68, "Pop and execute the next statements if a zero element was popped.";
- OP_VERIFY => 0x69, "If the top value is zero or the stack is empty, fail; otherwise, pop the stack.";
- OP_RETURN => 0x6a, "Fail the script immediately. (Must be executed.).";
- OP_TOALTSTACK => 0x6b, "Pop one element from the main stack onto the alt stack.";
- OP_FROMALTSTACK => 0x6c, "Pop one element from the alt stack onto the main stack.";
+ OP_ENDIF => 0x68, "Ends an `OP_IF` or `OP_NOTIF` block.";
+ OP_VERIFY => 0x69, "Fails if the top value is zero or the stack is empty, otherwise pops the stack.";
+ OP_RETURN => 0x6a, "Fails the script immediately (must be executed).";
+ OP_TOALTSTACK => 0x6b, "Pops one element from the main stack onto the alt stack.";
+ OP_FROMALTSTACK => 0x6c, "Pops one element from the alt stack onto the main stack.";
OP_2DROP => 0x6d, "Drops the top two stack items.";
OP_2DUP => 0x6e, "Duplicates the top two stack items as `AB` -> `ABAB`.";
OP_3DUP => 0x6f, "Duplicates the top three stack items as `ABC` -> `ABCABC`.";
OP_2OVER => 0x70, "Duplicates the third and fourth items from the top of the stack.";
OP_2ROT => 0x71, "Moves the two stack items four spaces back to the front, as `xxxxAB` -> `ABxxxx`.";
OP_2SWAP => 0x72, "Swaps the top two pairs, as `ABCD` -> `CDAB`.";
- OP_IFDUP => 0x73, "Duplicate the top stack element unless it is zero.";
- OP_DEPTH => 0x74, "Push the current number of stack items onto the stack.";
+ OP_IFDUP => 0x73, "Duplicates the top stack element unless it is zero.";
+ OP_DEPTH => 0x74, "Pushes the current number of stack items onto the stack.";
OP_DROP => 0x75, "Drops the top stack item.";
OP_DUP => 0x76, "Duplicates the top stack item.";
OP_NIP => 0x77, "Drops the second-to-top stack item.";
OP_OVER => 0x78, "Copies the second-to-top stack item, as `xA` -> `AxA`.";
- OP_PICK => 0x79, "Pop the top stack element as N. Copy the Nth stack element to the top.";
- OP_ROLL => 0x7a, "Pop the top stack element as N. Move the Nth stack element to the top.";
- OP_ROT => 0x7b, "Rotate the top three stack items, as `[top next1 next2]` -> `[next2 top next1]`.";
- OP_SWAP => 0x7c, "Swap the top two stack items.";
- OP_TUCK => 0x7d, "Copy the top stack item to before the second item, as `[top next]` -> `[top next top]`.";
+ OP_PICK => 0x79, "Pops the top stack element as N. Copies the Nth stack element to the top.";
+ OP_ROLL => 0x7a, "Pops the top stack element as N. Moves the Nth stack element to the top.";
+ OP_ROT => 0x7b, "Rotates the top three stack items, as `[top next1 next2]` -> `[next2 top next1]`.";
+ OP_SWAP => 0x7c, "Swaps the top two stack items.";
+ OP_TUCK => 0x7d, "Copies the top stack item to before the second item, as `[top next]` -> `[top next top]`.";
OP_SIZE => 0x82, "Pushes the length of the top stack item onto the stack.";
OP_EQUAL => 0x87, "Pushes 1 if the inputs are exactly equal, 0 otherwise.";
OP_EQUALVERIFY => 0x88, "Returns success if the inputs are exactly equal, failure otherwise.";
- OP_1ADD => 0x8b, "Increment the top stack element in place.";
- OP_1SUB => 0x8c, "Decrement the top stack element in place.";
- OP_NEGATE => 0x8f, "Multiply the top stack item by -1 in place.";
- OP_ABS => 0x90, "Absolute value the top stack item in place.";
- OP_NOT => 0x91, "Map 0 to 1 and everything else to 0, in place.";
- OP_0NOTEQUAL => 0x92, "Map 0 to 0 and everything else to 1, in place.";
- OP_ADD => 0x93, "Pop two stack items and push their sum.";
- OP_SUB => 0x94, "Pop two stack items and push the second minus the top.";
- OP_BOOLAND => 0x9a, "Pop the top two stack items and push 1 if both are nonzero, else push 0.";
- OP_BOOLOR => 0x9b, "Pop the top two stack items and push 1 if either is nonzero, else push 0.";
- OP_NUMEQUAL => 0x9c, "Pop the top two stack items and push 1 if both are numerically equal, else push 0.";
- OP_NUMEQUALVERIFY => 0x9d, "Pop the top two stack items and return success if both are numerically equal, else return failure.";
- OP_NUMNOTEQUAL => 0x9e, "Pop the top two stack items and push 0 if both are numerically equal, else push 1.";
- OP_LESSTHAN => 0x9f, "Pop the top two items; push 1 if the second is less than the top, 0 otherwise.";
- OP_GREATERTHAN => 0xa0, "Pop the top two items; push 1 if the second is greater than the top, 0 otherwise.";
- OP_LESSTHANOREQUAL => 0xa1, "Pop the top two items; push 1 if the second is <= the top, 0 otherwise.";
- OP_GREATERTHANOREQUAL => 0xa2, "Pop the top two items; push 1 if the second is >= the top, 0 otherwise.";
- OP_MIN => 0xa3, "Pop the top two items; push the smaller.";
- OP_MAX => 0xa4, "Pop the top two items; push the larger.";
- OP_WITHIN => 0xa5, "Pop the top three items; if the top is >= the second and < the third, push 1, otherwise push 0.";
- OP_RIPEMD160 => 0xa6, "Pop the top stack item and push its RIPEMD160 hash.";
- OP_SHA1 => 0xa7, "Pop the top stack item and push its SHA1 hash.";
- OP_SHA256 => 0xa8, "Pop the top stack item and push its SHA256 hash.";
- OP_HASH160 => 0xa9, "Pop the top stack item and push its RIPEMD(SHA256) hash.";
- OP_HASH256 => 0xaa, "Pop the top stack item and push its SHA256(SHA256) hash.";
- OP_CODESEPARATOR => 0xab, "Ignore this and everything preceding when deciding what to sign when signature-checking.";
- OP_CHECKSIG => 0xac, "<https://en.bitcoin.it/wiki/OP_CHECKSIG> pushing 1/0 for success/failure.";
- OP_CHECKSIGVERIFY => 0xad, "<https://en.bitcoin.it/wiki/OP_CHECKSIG> returning success/failure.";
- OP_CHECKMULTISIG => 0xae, "Pop N, N pubkeys, M, M signatures, a dummy (due to bug in reference code), \
- and verify that all M signatures are valid. Push 1 for 'all valid', 0 otherwise.";
- OP_CHECKMULTISIGVERIFY => 0xaf, "Like the above but return success/failure.";
- OP_CHECKSIGADD => 0xba, "`OP_CHECKSIGADD` post tapscript.";
+ OP_1ADD => 0x8b, "Increments the top stack element in place.";
+ OP_1SUB => 0x8c, "Decrements the top stack element in place.";
+ OP_NEGATE => 0x8f, "Multiplies the top stack item by -1 in place.";
+ OP_ABS => 0x90, "Replaces the top stack item with its absolute value, in place.";
+ OP_NOT => 0x91, "Maps 0 to 1 and everything else to 0, in place.";
+ OP_0NOTEQUAL => 0x92, "Maps 0 to 0 and everything else to 1, in place.";
+ OP_ADD => 0x93, "Pops two stack items and pushes their sum.";
+ OP_SUB => 0x94, "Pops two stack items and pushes the second minus the top.";
+ OP_BOOLAND => 0x9a, "Pops the top two stack items and pushes 1 if both are nonzero, else pushes 0.";
+ OP_BOOLOR => 0x9b, "Pops the top two stack items and pushes 1 if either is nonzero, else pushes 0.";
+ OP_NUMEQUAL => 0x9c, "Pops the top two stack items and pushes 1 if both are numerically equal, else pushes 0.";
+ OP_NUMEQUALVERIFY => 0x9d, "Pops the top two stack items and returns success if both are numerically equal, else returns failure.";
+ OP_NUMNOTEQUAL => 0x9e, "Pops the top two stack items and pushes 0 if both are numerically equal, else pushes 1.";
+ OP_LESSTHAN => 0x9f, "Pops the top two items; pushes 1 if the second is less than the top, 0 otherwise.";
+ OP_GREATERTHAN => 0xa0, "Pops the top two items; pushes 1 if the second is greater than the top, 0 otherwise.";
+ OP_LESSTHANOREQUAL => 0xa1, "Pops the top two items; pushes 1 if the second is <= the top, 0 otherwise.";
+ OP_GREATERTHANOREQUAL => 0xa2, "Pops the top two items; pushes 1 if the second is >= the top, 0 otherwise.";
+ OP_MIN => 0xa3, "Pops the top two items; pushes the smaller.";
+ OP_MAX => 0xa4, "Pops the top two items; pushes the larger.";
+ OP_WITHIN => 0xa5, "Pops the top three items; if the third is >= the second and < the top, pushes 1, otherwise pushes 0.";
+ OP_RIPEMD160 => 0xa6, "Pops the top stack item and pushes its RIPEMD160 hash.";
+ OP_SHA1 => 0xa7, "Pops the top stack item and pushes its SHA1 hash.";
+ OP_SHA256 => 0xa8, "Pops the top stack item and pushes its SHA256 hash.";
+ OP_HASH160 => 0xa9, "Pops the top stack item and pushes its RIPEMD160(SHA256) hash.";
+ OP_HASH256 => 0xaa, "Pops the top stack item and pushes its SHA256(SHA256) hash.";
+ OP_CODESEPARATOR => 0xab, "Ignores this and everything preceding when deciding what to sign when signature-checking.";
+ OP_CHECKSIG => 0xac, "Pops a public key and a signature and pushes 1 for a successful check or 0 for a failed check. Invalid encodings may fail the script.";
+ OP_CHECKSIGVERIFY => 0xad, "Same as `OP_CHECKSIG` followed by `OP_VERIFY`.";
+ OP_CHECKMULTISIG => 0xae, "Pops N, N pubkeys, M, M signatures, a dummy (due to bug in reference code), \
+ and verifies that all M signatures are valid. Pushes 1 for 'all valid', 0 otherwise.";
+ OP_CHECKMULTISIGVERIFY => 0xaf, "Same as `OP_CHECKMULTISIG` followed by `OP_VERIFY`.";
+ OP_CHECKSIGADD => 0xba, "Pops a public key, a number `n` and a signature in tapscript; pushes `n + 1` for a successful check or `n` for an empty signature. Invalid inputs fail the script. Unknown public key types accept any nonempty signature.";
}
-/// Read the following byte as a length, and read the following
+/// Reads the following byte as a length, and reads the following
/// bytes as a push of that length.
#[cfg(feature = "alloc")]
pub(crate) const OP_PUSHDATA1: u8 = 0x4c;
-/// Read the following 2 bytes as a little-endian length, and read the following
+/// Reads the following 2 bytes as a little-endian length, and reads the following
/// bytes as a push of that length.
#[cfg(feature = "alloc")]
pub(crate) const OP_PUSHDATA2: u8 = 0x4d;
-/// Read the following 4 bytes as a little-endian length, and read the following
+/// Reads the following 4 bytes as a little-endian length, and reads the following
/// bytes as a push of that length.
#[cfg(any(feature = "alloc", test))]
pub(crate) const OP_PUSHDATA4: u8 = 0x4e;
-/// Push an empty array onto the stack.
+/// Pushes an empty array onto the stack.
pub(crate) const OP_PUSHBYTES_0: Opcode = Opcode::from_u8(0x00);
-/// Push the next 2 bytes as an array onto the stack.
+/// Pushes the next 2 bytes as an array onto the stack.
#[cfg(feature = "alloc")]
pub(crate) const OP_PUSHBYTES_2: Opcode = Opcode::from_u8(0x02);
-/// Push the next 20 bytes as an array onto the stack.
+/// Pushes the next 20 bytes as an array onto the stack.
#[cfg(feature = "alloc")]
pub(crate) const OP_PUSHBYTES_20: Opcode = Opcode::from_u8(0x14);
-/// Push the next 32 bytes as an array onto the stack.
+/// Pushes the next 32 bytes as an array onto the stack.
#[cfg(feature = "alloc")]
pub(crate) const OP_PUSHBYTES_32: Opcode = Opcode::from_u8(0x20);
-/// Format a byte as a script opcode.
+/// Formats a byte as a script opcode.
#[cfg(feature = "alloc")]
pub(crate) fn fmt_opcode(op: u8, f: &mut fmt::Formatter) -> fmt::Result {
match op {
### primitives/src/script/borrowed.rs
@@ -26,7 +26,7 @@ use crate::{ScriptPubKey, WitnessScript};
crate::transparent_newtype! {
/// Bitcoin script slice.
///
- /// *[See also the `bitcoin::script` module](super).*
+ /// *[See also the `script` module](super).*
///
/// [`Script`] is a script slice, the most primitive script type. It's usually seen in its borrowed
/// form `&Script`. It is always encoded as a series of bytes representing the opcodes and data
@@ -47,8 +47,9 @@ crate::transparent_newtype! {
///
/// Slicing is similar to how `str` works: some ranges may be incorrect and indexing by
/// `usize` is not supported. However, as opposed to `std`, we have no way of checking
- /// correctness without causing linear complexity so there are **no panics on invalid
- /// ranges!** If you supply an invalid range, you'll get a garbled script.
+ /// correctness without causing linear complexity so there are **no panics on ranges that
+ /// are not at an instruction boundary!** If you supply such a range, you'll get a garbled
+ /// script. As with slices, a range that is out of bounds does panic.
///
/// The range is considered valid if it's at a boundary of instruction. Care must be taken
/// especially with push operations because you could get a reference to arbitrary
@@ -82,10 +83,10 @@ crate::transparent_newtype! {
pub struct Script<T>(PhantomData<T>, [u8]);
impl<T> Script<T> {
- /// Treat byte slice as [`Script`].
+ /// Treats a byte slice as a [`Script`].
pub const fn from_bytes(bytes: &_) -> &Self;
- /// Treat mutable byte slice as [`Script`].
+ /// Treats a mutable byte slice as a [`Script`].
pub fn from_bytes_mut(bytes: &mut _) -> &mut Self;
pub(crate) fn from_boxed_bytes(bytes: Box<_>) -> Box<Self>;
@@ -145,7 +146,9 @@ impl<T> Script<T> {
/// Consensus encodes the script as lower-case hex.
///
/// Consensus encoding includes a length prefix. To hex encode without the length prefix use
- /// `to_hex_string_no_length_prefix`.
+ /// [`to_hex_string_no_length_prefix`].
+ ///
+ /// [`to_hex_string_no_length_prefix`]: Self::to_hex_string_no_length_prefix
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
pub fn to_hex_string_prefixed(&self) -> String {
@@ -158,7 +161,9 @@ impl<T> Script<T> {
/// Encodes the script as lower-case hex.
///
/// This is **not** consensus encoding. The returned hex string will not include the length
- /// prefix. See `to_hex_string_prefixed`.
+ /// prefix. See [`to_hex_string_prefixed`].
+ ///
+ /// [`to_hex_string_prefixed`]: Self::to_hex_string_prefixed
#[cfg(feature = "alloc")]
#[cfg(feature = "hex")]
pub fn to_hex_string_no_length_prefix(&self) -> String {
@@ -296,7 +301,7 @@ impl ScriptPubKey {
&& self.as_bytes()[2..] == P2A_PROGRAM
}
- /// Check if this is a consensus-valid `OP_RETURN` output.
+ /// Checks whether this is a consensus-valid `OP_RETURN` output.
///
/// To validate if the `OP_RETURN` obeys Bitcoin Core's current standardness policy, use
/// `bitcoin::ScriptPubKeyExt::is_standard_op_return()` instead.
### primitives/src/script/builder.rs
@@ -6,7 +6,7 @@ use super::{PushBytes, Script, ScriptBuf};
use crate::opcodes::Opcode;
use crate::prelude::Vec;
-/// An Object which can be used to construct a script piece by piece.
+/// An object which can be used to construct a script piece by piece.
///
/// # Panics
///
@@ -33,7 +33,7 @@ use crate::prelude::Vec;
pub struct Builder<T>(ScriptBuf<T>);
impl<T> Builder<T> {
- /// Constructs a new empty script.
+ /// Constructs a new builder for an empty script.
#[inline]
pub const fn new() -> Self { Self(ScriptBuf::new()) }
@@ -75,7 +75,7 @@ impl<T> Builder<T> {
/// Converts the [`Builder`] into [`ScriptBuf`].
pub fn into_script(self) -> ScriptBuf<T> { self.0 }
- /// Returns the internal script
+ /// Returns the internal script.
pub fn as_script(&self) -> &Script<T> { &self.0 }
}
### primitives/src/script/mod.rs
@@ -124,7 +124,7 @@ pub type ScriptCode = Script<ScriptCodeTag>;
/// The maximum allowed redeem script size for a P2SH output.
pub const MAX_REDEEM_SCRIPT_SIZE: usize = 520;
-/// The maximum allowed redeem script size of the witness script.
+/// The maximum allowed size of a witness script.
pub const MAX_WITNESS_SCRIPT_SIZE: usize = 10_000;
/// The P2A program which is given by 0x4e73.
### primitives/src/script/owned.rs
@@ -145,7 +145,7 @@ impl<T> ScriptBuf<T> {
///
/// Unlike `reserve`, this will not deliberately over-allocate to speculatively avoid frequent
/// allocations. After calling `reserve_exact`, capacity will be greater than or equal to
- /// `self.len() + additional`. Does nothing if the capacity is already sufficient.
+ /// `self.len() + additional_len`. Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the collection more space than it requests. Therefore,
/// capacity cannot be relied upon to be precisely minimal. Prefer [`reserve`]
### primitives/src/script/push_bytes.rs
@@ -257,13 +257,13 @@ mod primitive {
#[inline]
pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) }
- /// Reserve capacity for `additional_capacity` bytes.
+ /// Reserves capacity for `additional_capacity` bytes.
#[inline]
pub fn reserve(&mut self, additional_capacity: usize) {
self.0.reserve(additional_capacity);
}
- /// Try pushing a single byte.
+ /// Tries to push a single byte.
///
/// # Errors
///
@@ -277,7 +277,7 @@ mod primitive {
Ok(())
}
- /// Try appending a slice to [`PushBytesBuf`]
+ /// Tries to append a slice to [`PushBytesBuf`].
///
/// # Errors
///
@@ -290,11 +290,11 @@ mod primitive {
Ok(())
}
- /// Remove the last byte from buffer if any.
+ /// Removes the last byte from the buffer, if any.
#[inline]
pub fn pop(&mut self) -> Option<u8> { self.0.pop() }
- /// Remove the byte at `index` and return it.
+ /// Removes the byte at `index` and returns it.
///
/// # Panics
///
@@ -303,22 +303,22 @@ mod primitive {
#[track_caller]
pub fn remove(&mut self, index: usize) -> u8 { self.0.remove(index) }
- /// Remove all bytes from buffer without affecting capacity.
+ /// Removes all bytes from the buffer without affecting capacity.
#[inline]
pub fn clear(&mut self) { self.0.clear() }
- /// Remove bytes from buffer past `len`.
+ /// Removes bytes from the buffer past `len`.
#[inline]
pub fn truncate(&mut self, len: usize) { self.0.truncate(len) }
- /// Extracts [`PushBytes`] slice
+ /// Extracts a [`PushBytes`] slice.
#[inline]
pub fn as_push_bytes(&self) -> &PushBytes {
// length guaranteed by our invariant
PushBytes::from_slice_unchecked(&self.0)
}
- /// Extracts mutable [`PushBytes`] slice
+ /// Extracts a mutable [`PushBytes`] slice.
#[inline]
pub fn as_mut_push_bytes(&mut self) -> &mut PushBytes {
// length guaranteed by our invariant
### primitives/src/transaction.rs
@@ -164,10 +164,6 @@ pub use crate::hash_types::{Ntxid, Txid, Wtxid};
/// on their representation as a `u32`, which is not a semantically meaningful
/// order, and therefore the ordering on [`Transaction`] itself is not semantically
/// meaningful either.
-///
-/// The ordering is, however, consistent with the ordering present in this library
-/// before this change, so users should not notice any breakage (here) when
-/// transitioning from 0.29 to 0.30.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg(feature = "alloc")]
pub struct Transaction {
@@ -195,14 +191,14 @@ impl Transaction {
/// Computes a "normalized TXID" which does not include any signatures.
///
/// This function is needed only for legacy (pre-Segwit or P2SH-wrapped segwit version 0)
- /// applications. This method clears the `script_sig` field of each input, which in Segwit
- /// transactions is already empty, so for Segwit transactions the ntxid will be equal to the
- /// txid, and you should simply use the latter.
+ /// applications. This method clears the `script_sig` and `witness` fields of each input. The
+ /// `script_sig` in Segwit transactions is already empty, so for Segwit transactions the ntxid
+ /// will be equal to the txid, and you should simply use the latter.
///
/// This gives a way to identify a transaction that is "the same" as another in the sense of
/// having the same inputs and outputs.
///
- /// A coinbase `script_sig` is not a signature and may contain a BIP-34 height commitment, so
+ /// A coinbase `script_sig` is not a signature and may contain a BIP-0034 height commitment, so
/// for a coinbase transaction the ntxid is equal to the txid.
#[doc(alias = "ntxid")]
pub fn compute_ntxid(&self) -> Ntxid {
@@ -513,6 +509,18 @@ encoding::encoder_newtype_exact! {
}
/// The decoder for the [`Transaction`] type.
+///
+/// As well as checking the encoding, the decoder rejects some transactions that cannot be valid
+/// in a block. Decoding fails if the transaction:
+///
+/// * Has no outputs.
+/// * Is heavier than the maximum block weight.
+/// * Has more than one input and any of them spends the null (coinbase) prevout.
+/// * Is a coinbase transaction with a `script_sig` shorter than 2 or longer than 100 bytes.
+/// * Spends the same outpoint more than once.
+/// * Has outputs whose total value exceeds [`Amount::MAX_MONEY`].
+/// * Has inputs and uses the SegWit serialization but all of its witnesses are empty. Zero-input
+/// transactions use SegWit serialization to avoid ambiguity (see [`Transaction`]).
#[cfg(feature = "alloc")]
#[derive(Debug, Clone)]
pub struct TransactionDecoder {
@@ -847,10 +855,13 @@ pub struct TxIn {
/// The script which pushes values on the stack which will cause
/// the referenced output's script to be accepted.
pub script_sig: ScriptSigBuf,
- /// The sequence number, which suggests to miners which of two
- /// conflicting transactions should be preferred, or 0xFFFFFFFF
- /// to ignore this feature. This is generally never used since
- /// the miner behavior cannot be enforced.
+ /// The sequence number.
+ ///
+ /// Used to enable the transaction lock time, to encode a relative lock time ([BIP-0068])
+ /// and to signal replaceability ([BIP-0125]).
+ ///
+ /// [BIP-0068]: <https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki>
+ /// [BIP-0125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>
pub sequence: Sequence,
/// Witness data: an array of byte-arrays.
/// Note that this field is *not* (de)serialized with the rest of the [`TxIn`] in
@@ -2466,7 +2477,7 @@ mod tests {
#[cfg(feature = "alloc")]
fn compute_ntxid_preserves_coinbase_script_sig() {
let mut tx_in = TxIn::EMPTY_COINBASE;
- // BIP-34 height 840001.
+ // BIP-0034 height 840001.
tx_in.script_sig = ScriptSigBuf::from_bytes(vec![0x03, 0x41, 0xd1, 0x0c]);
let first = Transaction {
@@ -2477,7 +2488,7 @@ mod tests {
};
let mut second = first.clone();
- // BIP-34 height 840002.
+ // BIP-0034 height 840002.
second.inputs[0].script_sig = ScriptSigBuf::from_bytes(vec![0x03, 0x42, 0xd1, 0x0c]);
assert_ne!(first.compute_txid(), second.compute_txid());
### primitives/src/witness.rs
@@ -2,7 +2,7 @@
//! A witness.
//!
-//! This module contains the [`Witness`] struct and related methods to operate on it
+//! This module contains the [`Witness`] struct and related methods to operate on it.
//!
//! # Examples
//!
@@ -98,7 +98,7 @@ const MAX_WITNESS_SIZE: usize = 4_000_000;
/// For serialization and deserialization performance it is stored internally as a single [`Vec`],
/// saving some allocations.
///
-/// [SegWit upgrade]: <https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki>
+/// [SegWit upgrade]: <https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki>
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Witness {
/// Contains the witness [`Vec<Vec<u8>>`] serialization.
@@ -142,7 +142,8 @@ impl Witness {
/// is larger than that maximum.
///
/// # Examples
- /// ```
+ ///
+ /// ```rust
/// use bitcoin_primitives::witness::Witness;
///
/// let mut witness = Witness::from_slice(&[b"A", b"B", b"C", b"D"]);
@@ -182,7 +183,7 @@ impl Witness {
#[inline]
pub fn is_empty(&self) -> bool { self.witness_elements == 0 }
- /// Returns a struct implementing [`Iterator`].
+ /// Returns an iterator over the witness elements.
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[inline]
pub fn iter(&self) -> Iter<'_> {
@@ -195,10 +196,6 @@ impl Witness {
/// Returns the number of bytes this witness contributes to a transaction's total size.
///
- /// # Panics
- ///
- /// If the size calculation overflows.
- ///
/// # Examples
///
/// ```rust
@@ -289,7 +286,8 @@ impl Witness {
/// Returns [`None`] if the requested index is beyond the witness's elements.
///
/// # Examples
- /// ```
+ ///
+ /// ```rust
/// use bitcoin_primitives::witness::Witness;
///
/// let mut witness = Witness::new();Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.