Skip to content

Commit

Permalink
Merge pull request bitcoin#104 from LNP-BP/feat/chainparam
Browse files Browse the repository at this point in the history
Refactoring bp::Network into Chain and ChainParams: closes bitcoin#102
  • Loading branch information
dr-orlovsky committed Sep 24, 2020
2 parents 819f4c0 + c49e143 commit a586d9e
Show file tree
Hide file tree
Showing 13 changed files with 1,561 additions and 215 deletions.
1,413 changes: 1,413 additions & 0 deletions src/bp/chain.rs

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions src/bp/dbc/types.rs
Expand Up @@ -60,8 +60,6 @@ pub enum ScriptInfo {
pub(super) mod strict_encoding {
use super::*;
use crate::strict_encoding::{Error, StrictDecode, StrictEncode};
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive, ToPrimitive};
use std::io;

#[derive(FromPrimitive, ToPrimitive)]
Expand Down
4 changes: 2 additions & 2 deletions src/bp/mod.rs
Expand Up @@ -16,14 +16,14 @@ use bitcoin::hashes::{sha256d, Hash};
#[macro_use]
pub mod tagged256;
pub mod blind;
pub mod chain;
pub mod dbc;
pub mod network;
pub mod scripts;
mod seals;
pub mod short_id;
mod strict_encoding;

pub use network::{MagicNumber, Network};
pub use chain::{Chains, P2pNetworkId};
pub use scripts::*;
pub use seals::*;
pub use short_id::*;
Expand Down
145 changes: 0 additions & 145 deletions src/bp/network.rs

This file was deleted.

52 changes: 14 additions & 38 deletions src/bp/strict_encoding.rs
Expand Up @@ -15,14 +15,17 @@ use std::io;

use bitcoin::hashes::{hash160, sha256, sha256d, sha512};
use bitcoin::util::psbt::PartiallySignedTransaction;
use bitcoin::{secp256k1, util::bip32, OutPoint, Script, Txid, XpubIdentifier};
use bitcoin::{secp256k1, util::bip32, BlockHash, OutPoint, Script, Txid, XpubIdentifier};

use super::{blind::OutpointHash, blind::OutpointReveal, Network, ShortId};
use super::{blind::OutpointHash, blind::OutpointReveal, ShortId};
use crate::strict_encoding::{self, Error, StrictDecode, StrictEncode};

impl strict_encoding::Strategy for Txid {
type Strategy = strict_encoding::strategies::HashFixedBytes;
}
impl strict_encoding::Strategy for BlockHash {
type Strategy = strict_encoding::strategies::HashFixedBytes;
}
impl strict_encoding::Strategy for OutpointHash {
type Strategy = strict_encoding::strategies::HashFixedBytes;
}
Expand Down Expand Up @@ -175,24 +178,6 @@ impl StrictDecode for bitcoin::Network {
}
}

impl StrictEncode for Network {
type Error = Error;

#[inline]
fn strict_encode<E: io::Write>(&self, e: E) -> Result<usize, Self::Error> {
Ok(self.as_magic().strict_encode(e)?)
}
}

impl StrictDecode for Network {
type Error = Error;

#[inline]
fn strict_decode<D: io::Read>(d: D) -> Result<Self, Self::Error> {
Ok(Self::from_magic(u32::strict_decode(d)?))
}
}

impl StrictEncode for ShortId {
type Error = Error;

Expand Down Expand Up @@ -368,20 +353,24 @@ impl StrictDecode for bip32::ExtendedPubKey {
}

#[cfg(test)]
mod test {
pub(crate) mod test {
use std::{convert::TryFrom, fmt::Debug, str::FromStr};

use bitcoin::{hashes::hex::FromHex, secp256k1::Message, BlockHash};

use super::*;
use crate::bp::{short_id::Descriptor, BlockChecksum, TxChecksum};
use bitcoin::{hashes::hex::FromHex, secp256k1::Message, BlockHash};
use std::{convert::TryFrom, fmt::Debug, str::FromStr};

fn encode_decode<T: StrictEncode + StrictDecode>(object: &T) -> Result<(T, usize), Error> {
pub(crate) fn encode_decode<T: StrictEncode + StrictDecode>(
object: &T,
) -> Result<(T, usize), Error> {
let mut encoded_object: Vec<u8> = vec![];
let written = object.strict_encode(&mut encoded_object).unwrap();
let decoded_object = T::strict_decode(&encoded_object[..]).unwrap();
Ok((decoded_object, written))
}

fn test_suite<T: StrictEncode + StrictDecode + PartialEq + Debug>(
pub(crate) fn test_suite<T: StrictEncode + StrictDecode + PartialEq + Debug>(
object: &T,
test_vec: &[u8],
test_size: usize,
Expand All @@ -404,29 +393,16 @@ mod test {
let testnet_bytes = &[0x0Bu8, 0x11u8, 0x09u8, 0x07u8][..];
let regtest_bytes = &[0xFAu8, 0xBFu8, 0xB5u8, 0xDAu8][..];
let signet_bytes = &[0x0Au8, 0x03u8, 0xCFu8, 0x40u8][..];
let random_bytes = &[0xA1u8, 0xA2u8, 0xA3u8, 0xA4u8][..];

let mainnet = bitcoin::Network::strict_decode(mainnet_bytes).unwrap();
let testnet = bitcoin::Network::strict_decode(testnet_bytes).unwrap();
let regtest = bitcoin::Network::strict_decode(regtest_bytes).unwrap();
let signet = bitcoin::Network::strict_decode(signet_bytes).unwrap();

let bp_mainnet = Network::strict_decode(mainnet_bytes).unwrap();
let bp_testnet = Network::strict_decode(testnet_bytes).unwrap();
let bp_regtest = Network::strict_decode(regtest_bytes).unwrap();
let bp_signet = Network::strict_decode(signet_bytes).unwrap();
let bp_other = Network::strict_decode(random_bytes).unwrap();

assert!(test_suite(&mainnet, &mainnet_bytes, 4).is_ok());
assert!(test_suite(&testnet, &testnet_bytes, 4).is_ok());
assert!(test_suite(&regtest, &regtest_bytes, 4).is_ok());
assert!(test_suite(&signet, &signet_bytes, 4).is_ok());

assert!(test_suite(&bp_mainnet, &mainnet_bytes, 4).is_ok());
assert!(test_suite(&bp_testnet, &testnet_bytes, 4).is_ok());
assert!(test_suite(&bp_regtest, &regtest_bytes, 4).is_ok());
assert!(test_suite(&bp_signet, &signet_bytes, 4).is_ok());
assert!(test_suite(&bp_other, &random_bytes, 4).is_ok());
}

#[test]
Expand Down
2 changes: 0 additions & 2 deletions src/common/data_format.rs
Expand Up @@ -18,8 +18,6 @@ use ::core::fmt::{Display, Formatter};
use ::core::str::pattern::Pattern;
use ::core::str::FromStr;

use num_traits::{FromPrimitive, ToPrimitive};

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, ToPrimitive, FromPrimitive)]
pub enum DataFormat {
Yaml,
Expand Down
58 changes: 52 additions & 6 deletions src/paradigms/strict_encoding.rs
Expand Up @@ -90,11 +90,10 @@ where
}

/// Possible errors during strict encoding and decoding process
#[derive(Debug, From, Error)]
#[derive(Clone, PartialEq, Eq, Debug, From, Error)]
pub enum Error {
/// I/O Error
#[derive_from]
Io(io::Error),
Io(io::ErrorKind),

/// UTF8 Conversion Error
#[derive_from(std::str::Utf8Error, std::string::FromUtf8Error)]
Expand Down Expand Up @@ -139,11 +138,23 @@ pub enum Error {
DataIntegrityError(String),
}

impl From<Error> for fmt::Error {
fn from(_: Error) -> Self {
fmt::Error
}
}

impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Self::Io(err.kind())
}
}

impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use Error::*;
match self {
Io(e) => write!(f, "I/O error: {}", e),
Io(kind) => write!(f, "I/O error: {:?}", kind),
Utf8Conversion => write!(f, "String data are not in valid UTF-8 encoding"),
ExceedMaxItems(size) => write!(
f,
Expand Down Expand Up @@ -220,6 +231,19 @@ macro_rules! strict_encode_list {
}
}

#[macro_export]
macro_rules! strict_decode_self {
( $decoder:ident; $($item:ident),+ ) => {
{
Self {
$(
$item: StrictDecode::strict_decode(&mut $decoder)?,
)+
}
}
};
}

#[macro_export]
macro_rules! impl_enum_strict_encoding {
($type:ty) => {
Expand All @@ -228,6 +252,8 @@ macro_rules! impl_enum_strict_encoding {

#[inline]
fn strict_encode<E: ::std::io::Write>(&self, e: E) -> Result<usize, Self::Error> {
use ::num_traits::ToPrimitive;

match self.to_u8() {
Some(result) => result.strict_encode(e),
None => Err($crate::strict_encoding::Error::EnumValueOverflow(
Expand All @@ -242,6 +268,8 @@ macro_rules! impl_enum_strict_encoding {

#[inline]
fn strict_decode<D: ::std::io::Read>(d: D) -> Result<Self, Self::Error> {
use ::num_traits::FromPrimitive;

let value = u8::strict_decode(d)?;
match Self::from_u8(value) {
Some(result) => Ok(result),
Expand Down Expand Up @@ -384,9 +412,9 @@ pub mod strategies {
#[inline]
fn from(e: bitcoin::consensus::encode::Error) -> Self {
Error::Io(if let bitcoin::consensus::encode::Error::Io(io_err) = e {
io_err
io_err.kind()
} else {
io::Error::new(io::ErrorKind::Other, "")
io::ErrorKind::Other
})
}
}
Expand Down Expand Up @@ -430,6 +458,24 @@ mod number_little_endian {
type Strategy = strategies::BitcoinConsensus;
}

impl StrictEncode for bool {
type Error = Error;
fn strict_encode<E: io::Write>(&self, mut e: E) -> Result<usize, Error> {
(*self as u8).strict_encode(&mut e)
}
}

impl StrictDecode for bool {
type Error = Error;
fn strict_decode<D: io::Read>(mut d: D) -> Result<Self, Error> {
match u8::strict_decode(&mut d)? {
0 => Ok(false),
1 => Ok(true),
v => Err(Error::ValueOutOfRange("boolean", 0..1, v as u128)),
}
}
}

impl StrictEncode for usize {
type Error = Error;
fn strict_encode<E: io::Write>(&self, mut e: E) -> Result<usize, Error> {
Expand Down

0 comments on commit a586d9e

Please sign in to comment.