8000 Add `ValidationError` by tcharding · Pull Request #1874 · rust-bitcoin/rust-bitcoin · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add ValidationError #1874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 45 additions & 15 deletions bitcoin/src/blockdata/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use super::Weight;
use crate::blockdata::script;
use crate::blockdata::transaction::Transaction;
use crate::consensus::{encode, Decodable, Encodable};
use crate::error::Error::{self, BlockBadProofOfWork, BlockBadTarget};
pub use crate::hash_types::BlockHash;
use crate::hash_types::{TxMerkleNode, WitnessCommitment, WitnessMerkleNode, Wtxid};
use crate::internal_macros::impl_consensus_encoding;
Expand Down Expand Up @@ -72,16 +71,16 @@ impl Header {
pub fn difficulty_float(&self) -> f64 { self.target().difficulty_float() }

/// Checks that the proof-of-work for the block is valid, returning the block hash.
pub fn validate_pow(&self, required_target: Target) -> Result<BlockHash, Error> {
pub fn validate_pow(&self, required_target: Target) -> Result<BlockHash, ValidationError> {
let target = self.target();
if target != required_target {
return Err(BlockBadTarget);
return Err(ValidationError::BadTarget);
}
let block_hash = self.block_hash();
if target.is_met_by(block_hash) {
Ok(block_hash)
} else {
Err(BlockBadProofOfWork)
Err(ValidationError::BadProofOfWork)
}
}

Expand Down Expand Up @@ -337,6 +336,22 @@ impl Block {
}
}

impl From<Header> for BlockHash {
fn from(header: Header) -> BlockHash { header.block_hash() }
}

impl From<&Header> for BlockHash {
fn from(header: &Header) -> BlockHash { header.block_hash() }
}

impl From<Block> for BlockHash {
fn from(block: Block) -> BlockHash { block.block_hash() }
}

impl From<&Block> for BlockHash {
fn from(block: &Block) -> BlockHash { block.block_hash() }
}

/// An error when looking up a BIP34 block height.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
Expand Down Expand Up @@ -375,20 +390,35 @@ impl std::error::Error for Bip34Error {
}
}

impl From<Header> for BlockHash {
fn from(header: Header) -> BlockHash { header.block_hash() }
/// A block validation error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
/// The header hash is not below the target.
BadProofOfWork,
/// The `target` field of a block header did not match the expected difficulty.
BadTarget,
}

impl From<&Header> for BlockHash {
fn from(header: &Header) -> BlockHash { header.block_hash() }
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use ValidationError::*;

impl From<Block> for BlockHash {
fn from(block: Block) -> BlockHash { block.block_hash() }
match *self {
BadProofOfWork => f.write_str("block target correct but not attained"),
BadTarget => f.write_str("block target incorrect"),
}
}
}

impl From<&Block> for BlockHash {
fn from(block: &Block) -> BlockHash { block.block_hash() }
#[cfg(feature = "std")]
impl std::error::Error for ValidationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use self::ValidationError::*;

match *self {
BadProofOfWork | BadTarget => None,
}
}
}

#[cfg(test)]
Expand Down Expand Up @@ -528,15 +558,15 @@ mod tests {

// test with zero target
match some_header.validate_pow(Target::ZERO) {
Err(BlockBadTarget) => (),
Err(ValidationError::BadTarget) => (),
_ => panic!("unexpected result from validate_pow"),
}

// test with modified header
let mut invalid_header: Header = some_header;
invalid_header.version.0 += 1;
match invalid_header.validate_pow(invalid_header.target()) {
Err(BlockBadProofOfWork) => (),
Err(ValidationError::BadProofOfWork) => (),
_ => panic!("unexpected result from validate_pow"),
}
}
Expand Down
45 changes: 0 additions & 45 deletions bitcoin/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,8 @@

//! Contains error types and other error handling tools.

use core::fmt;

use internals::write_err;

use crate::consensus::encode;
pub use crate::parse::ParseIntError;

/// A general error code, other errors should implement conversions to/from this
/// if appropriate.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// Encoding error
Encode(encode::Error),
/// The header hash is not below the target
BlockBadProofOfWork,
/// The `target` field of a block header did not match the expected difficulty
BlockBadTarget,
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Encode(ref e) => write_err!(f, "encoding error"; e),
Error::BlockBadProofOfWork => f.write_str("block target correct but not attained"),
Error::BlockBadTarget => f.write_str("block target incorrect"),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use self::Error::*;

match self {
Encode(e) => Some(e),
BlockBadProofOfWork | BlockBadTarget => None,
}
}
}

#[doc(hidden)]
impl From<encode::Error> for Error {
fn from(e: encode::Error) -> Error { Error::Encode(e) }
}

/// Impls std::error::Error for the specified type with appropriate attributes, possibly returning
/// source.
macro_rules! impl_std_error {
Expand Down
1 change: 0 additions & 1 deletion bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ pub use crate::blockdata::{constants, opcodes};
pub use crate::consensus::encode::VarInt;
pub use crate::crypto::key::{self, PrivateKey, PublicKey};
pub use crate::crypto::{ecdsa, sighash};
pub use crate::error::Error;
pub use crate::hash_types::{
BlockHash, PubkeyHash, ScriptHash, Txid, WPubkeyHash, WScriptHash, Wtxid,
};
Expand Down
0