From 30a09670e8a53cb74bf5a40f83cecfcc74d94d36 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 17 Apr 2024 10:27:24 +1000 Subject: [PATCH] Add docs for custom signets We have started using `AsRef` in a few places as a function parameter. If a user of the library wishes to use these functions they need to create a type that can implement this trait. Because we use `non_exhaustive` on the `Params` struct it is not possible to just construct a `Params` type. This may be surprising for some folk. Add module level docs to the `consensus::params` module with an example of how to create a type that can be used to describe a custom signet network. Use fields inspired by Mutiny Wallet's described usage. Close: #2690 --- bitcoin/src/consensus/params.rs | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/bitcoin/src/consensus/params.rs b/bitcoin/src/consensus/params.rs index a6863ca3..10554eed 100644 --- a/bitcoin/src/consensus/params.rs +++ b/bitcoin/src/consensus/params.rs @@ -5,6 +5,65 @@ //! This module provides a predefined set of parameters for different Bitcoin //! chains (such as mainnet, testnet). //! +//! # Custom Signets Example +//! +//! In various places in this crate we take `AsRef` as a parameter, in order to create a +//! custom type that can be used is such places you might want to do the following: +//! +//! ``` +//! use bitcoin::consensus::Params; +//! use bitcoin::{p2p, Script, ScriptBuf, Network, Target}; +//! +//! const POW_TARGET_SPACING: u64 = 120; // Two minutes. +//! const MAGIC: [u8; 4] = [1, 2, 3, 4]; +//! +//! pub struct CustomParams { +//! params: Params, +//! magic: [u8; 4], +//! challenge_script: ScriptBuf, +//! } +//! +//! impl CustomParams { +//! /// Creates a new custom params. +//! pub fn new() -> Self { +//! let mut params = Params::new(Network::Signet); +//! params.pow_target_spacing = POW_TARGET_SPACING; +//! +//! // This would be something real (see BIP-325). +//! let challenge_script = ScriptBuf::new(); +//! +//! Self { +//! params, +//! magic: MAGIC, +//! challenge_script, +//! } +//! } +//! +//! /// Returns the custom magic bytes. +//! pub fn magic(&self) -> p2p::Magic { p2p::Magic::from_bytes(self.magic) } +//! +//! /// Returns the custom signet challenge script. +//! pub fn challenge_script(&self) -> &Script { &self.challenge_script } +//! } +//! +//! impl AsRef for CustomParams { +//! fn as_ref(&self) -> &Params { &self.params } +//! } +//! +//! impl Default for CustomParams { +//! fn default() -> Self { Self::new() } +//! } +//! +//! # { // Just check the code above is usable. +//! # let target = Target::MAX_ATTAINABLE_SIGNET; +//! # +//! # let signet = Params::SIGNET; +//! # let _ = target.difficulty(signet); +//! # +//! # let custom = CustomParams::new(); +//! # let _ = target.difficulty(custom); +//! # } +//! ``` use crate::network::Network; #[cfg(doc)]