What changed, and why it matters
This commit adds a new example file showing how to use serde serialization with Bitcoin consensus encoding in the rust-bitcoin library. It is purely documentation/example code and does not change any library behavior or fix any bug.
No security action needed. Review as normal documentation/example addition if desired.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit introduces bitcoin/examples/serde.rs, registers it in Cargo.toml as an example requiring std and serde features, and adds it to the test script’s EXAMPLES list. The example demonstrates deriving Serialize/Deserialize on a struct containing Header, Amount, and FeeRate fields with various serde helper modules. No production code is modified.
Changed components
bitcoin/examples/serde.rs (new example)bitcoin/Cargo.toml (example registration)bitcoin/contrib/test_vars.sh (CI example list)Inspect captured patch +64 / −1
diff --git a/bitcoin/Cargo.toml b/bitcoin/Cargo.toml
index 2e3ff37a..acaaf85a 100644
--- a/bitcoin/Cargo.toml
+++ b/bitcoin/Cargo.toml
@@ -95,5 +95,9 @@ required-features = ["std"]
name = "script"
required-features = ["std"]
+[[example]]
+name = "serde"
+required-features = ["std", "serde"]
+
[lints.rust]
unexpected_cfgs = { level = "deny", check-cfg = ['cfg(bench)', 'cfg(fuzzing)', 'cfg(kani)'] }
diff --git a/bitcoin/contrib/test_vars.sh b/bitcoin/contrib/test_vars.sh
index f28ecdb3..0e566596 100644
--- a/bitcoin/contrib/test_vars.sh
+++ b/bitcoin/contrib/test_vars.sh
@@ -11,4 +11,4 @@ FEATURES_WITH_STD="rand-std serde secp-recovery bitcoinconsensus base64 arbitrar
FEATURES_WITHOUT_STD="rand serde secp-recovery bitcoinconsensus base64 arbitrary"
# Run these examples.
-EXAMPLES="ecdsa-psbt:std,bitcoinconsensus sign-tx-segwit-v0:rand-std sign-tx-taproot:rand-std taproot-psbt:bitcoinconsensus,rand-std sighash:std"
+EXAMPLES="ecdsa-psbt:std,bitcoinconsensus sign-tx-segwit-v0:rand-std sign-tx-taproot:rand-std taproot-psbt:bitcoinconsensus,rand-std sighash:std serde:std,serde"
diff --git a/bitcoin/examples/serde.rs b/bitcoin/examples/serde.rs
new file mode 100644
index 00000000..81f9faf6
--- /dev/null
+++ b/bitcoin/examples/serde.rs
@@ -0,0 +1,59 @@
+//! Serializing with `serde` and `consensus::{Encodable, Decodable}`
+//!
+//! All types that implement consensus encoding traits can be serde de/serialized.
+//! For integer types that can have multiple units we typically provide a few different modules.
+
+use bitcoin::block::{Header, Version};
+use bitcoin::consensus::serde::Hex;
+use bitcoin::consensus::{self};
+use bitcoin::{
+ amount, fee_rate, Amount, BlockHash, BlockTime, CompactTarget, FeeRate, TxMerkleNode,
+};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+pub struct Foo {
+ /// Consensus encoded into hex is often the best option.
+ #[serde(with = "consensus::serde::With::<Hex>")]
+ header: Header,
+
+ /// This works but it's little-endian which may be hard to read.
+ ///
+ /// Integer wrapper types are more readable if the explicitly use a unit.
+ #[serde(with = "consensus::serde::With::<Hex>")]
+ this: Amount,
+
+ /// `Amount` can use sats or bitcoin (`as_btc`).
+ #[serde(with = "amount::serde::as_sat")]
+ that: Amount,
+
+ /// `FeeRate` can use kilo weight units or virtual bytes, both floor and ceil.
+ #[serde(with = "fee_rate::serde::as_sat_per_kwu_floor")]
+ fee_rate: FeeRate,
+}
+
+fn main() {
+ let f = Foo {
+ header: dummy_header(),
+ this: Amount::ONE_SAT,
+ that: Amount::ONE_BTC,
+ fee_rate: FeeRate::DUST,
+ };
+
+ let s = serde_json::to_string(&f).unwrap();
+ println!("{s}");
+
+ let deser = serde_json::from_str::<Foo>(&s).unwrap();
+ assert_eq!(deser, f);
+}
+
+fn dummy_header() -> Header {
+ Header {
+ version: Version::ONE,
+ prev_blockhash: BlockHash::from_byte_array([0x99; 32]),
+ merkle_root: TxMerkleNode::from_byte_array([0x77; 32]),
+ time: BlockTime::from(2),
+ bits: CompactTarget::from_consensus(3),
+ nonce: 4,
+ }
+}
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.