From 9a8694fae56f8d8a8e240dcf090dc55c37e0c929 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Sun, 5 Nov 2023 11:16:53 +0100 Subject: [PATCH 1/2] Add `params` method to `Network` Writing `network.params()` is less annoying than `Params::network()`, so this adds it. Making it return a static could also improve performance. --- bitcoin/src/consensus/params.rs | 2 +- bitcoin/src/network.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/bitcoin/src/consensus/params.rs b/bitcoin/src/consensus/params.rs index e2d747f8..5d019d16 100644 --- a/bitcoin/src/consensus/params.rs +++ b/bitcoin/src/consensus/params.rs @@ -50,7 +50,7 @@ pub struct Params { impl Params { /// Creates parameters set for the given network. - pub fn new(network: Network) -> Self { + pub const fn new(network: Network) -> Self { match network { Network::Bitcoin => Params { network: Network::Bitcoin, diff --git a/bitcoin/src/network.rs b/bitcoin/src/network.rs index cd3d3042..c66ab070 100644 --- a/bitcoin/src/network.rs +++ b/bitcoin/src/network.rs @@ -27,6 +27,7 @@ use internals::write_err; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; +use crate::consensus::Params; use crate::constants::ChainHash; use crate::p2p::Magic; use crate::prelude::{String, ToOwned}; @@ -144,6 +145,17 @@ impl Network { pub fn from_chain_hash(chain_hash: ChainHash) -> Option { Network::try_from(chain_hash).ok() } + + /// Returns the associated network parameters. + pub const fn params(self) -> &'static Params { + const PARAMS: [Params; 4] = [ + Params::new(Network::Bitcoin), + Params::new(Network::Testnet), + Params::new(Network::Signet), + Params::new(Network::Regtest), + ]; + &PARAMS[self as usize] + } } #[cfg(feature = "serde")] From 9282cc4dad83f86ce550cbf23b83cd2bd468df91 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Sun, 5 Nov 2023 11:35:08 +0100 Subject: [PATCH 2/2] Implement standard conversions `Network`->`Params` --- bitcoin/src/consensus/params.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/bitcoin/src/consensus/params.rs b/bitcoin/src/consensus/params.rs index 5d019d16..4382bec8 100644 --- a/bitcoin/src/consensus/params.rs +++ b/bitcoin/src/consensus/params.rs @@ -116,3 +116,27 @@ impl Params { self.pow_target_timespan / self.pow_target_spacing } } + +impl From for Params { + fn from(value: Network) -> Self { + Self::new(value) + } +} + +impl From<&Network> for Params { + fn from(value: &Network) -> Self { + Self::new(*value) + } +} + +impl From for &'static Params { + fn from(value: Network) -> Self { + value.params() + } +} + +impl From<&Network> for &'static Params { + fn from(value: &Network) -> Self { + value.params() + } +}