Merge rust-bitcoin/rust-bitcoin#2172: Add `params` method to `Network`

9282cc4dad Implement standard conversions `Network`->`Params` (Martin Habovstiak)
9a8694fae5 Add `params` method to `Network` (Martin Habovstiak)

Pull request description:

  Writing `network.params()` is less annoying than `Params::network()`, so this adds it. Making it return a static could also improve performance.

  Didn't do `Params` -> `Network` conversions because of #2173

ACKs for top commit:
  tcharding:
    ACK 9282cc4dad
  apoelstra:
    ACK 9282cc4dad

Tree-SHA512: 6455956fd2c937b7212c9bab6ac7cfa05fb99b5da955f4f6690d7056cbe3902a3dadf94352c76b6866655b2e34a936191362a1cc81b33a5b252dd21dbc84d7b6
This commit is contained in:
Andrew Poelstra 2023-11-18 18:19:52 +00:00
commit c12debfd0c
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
2 changed files with 37 additions and 1 deletions

View File

@ -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,
@ -116,3 +116,27 @@ impl Params {
self.pow_target_timespan / self.pow_target_spacing
}
}
impl From<Network> 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<Network> for &'static Params {
fn from(value: Network) -> Self {
value.params()
}
}
impl From<&Network> for &'static Params {
fn from(value: &Network) -> Self {
value.params()
}
}

View File

@ -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> {
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")]