diff --git a/Cargo.lock b/Cargo.lock index f96d50adf..ec8a77ae9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1323,7 +1323,6 @@ dependencies = [ "sequencer", "sequencer-utils", "serde", - "snafu 0.8.4", "surf", "surf-disco", "tide-disco", @@ -2935,7 +2934,6 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.8", - "snafu 0.8.4", "static_assertions", "surf-disco", "tagged-base64", @@ -4389,7 +4387,6 @@ dependencies = [ "reqwest 0.12.5", "sequencer-utils", "serde", - "snafu 0.8.4", "surf-disco", "tide-disco", "time 0.3.36", @@ -6124,7 +6121,6 @@ dependencies = [ "sequencer", "sequencer-utils", "serde", - "snafu 0.8.4", "surf", "surf-disco", "tagged-base64", diff --git a/Cargo.toml b/Cargo.toml index 31e6d0eb3..a46ef7e4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -107,7 +107,6 @@ jf-relation = { git = "https://github.com/EspressoSystems/jellyfish", tag = "0.4 jf-utils = { git = "https://github.com/EspressoSystems/jellyfish", tag = "0.4.5" } libp2p = { version = "0.53", default-features = false } log-panics = { version = "2.0", features = ["with-backtrace"] } -snafu = "0.8" strum = { version = "0.26", features = ["derive"] } surf-disco = "0.9" tagged-base64 = "0.4" diff --git a/builder/Cargo.toml b/builder/Cargo.toml index 3acb054c2..38d81e3ce 100644 --- a/builder/Cargo.toml +++ b/builder/Cargo.toml @@ -40,7 +40,6 @@ rand = "0.8.5" sequencer = { path = "../sequencer", features = ["testing"] } sequencer-utils = { path = "../utils" } serde = { workspace = true } -snafu = { workspace = true } surf = "2.3.1" surf-disco = { workspace = true } tide-disco = { workspace = true } diff --git a/builder/src/bin/permissioned-builder.rs b/builder/src/bin/permissioned-builder.rs index 7936a0a28..2532ad0b9 100644 --- a/builder/src/bin/permissioned-builder.rs +++ b/builder/src/bin/permissioned-builder.rs @@ -5,7 +5,7 @@ use std::{ use anyhow::{bail, Context}; use builder::permissioned::init_node; use clap::Parser; -use espresso_types::eth_signature_key::EthKeyPair; +use espresso_types::{eth_signature_key::EthKeyPair, parse_duration}; use ethers::types::Address; use hotshot_types::{ data::ViewNumber, @@ -14,9 +14,7 @@ use hotshot_types::{ traits::{metrics::NoMetrics, node_implementation::ConsensusTime}, }; use libp2p::Multiaddr; -use sequencer::{ - options::parse_duration, persistence::no_storage::NoStorage, Genesis, L1Params, NetworkParams, -}; +use sequencer::{persistence::no_storage::NoStorage, Genesis, L1Params, NetworkParams}; use sequencer_utils::logging; use url::Url; use vbs::version::{StaticVersion, StaticVersionType}; diff --git a/builder/src/bin/permissionless-builder.rs b/builder/src/bin/permissionless-builder.rs index ca8d81e22..f1e394471 100644 --- a/builder/src/bin/permissionless-builder.rs +++ b/builder/src/bin/permissionless-builder.rs @@ -1,14 +1,12 @@ -use std::{num::NonZeroUsize, path::PathBuf, str::FromStr, time::Duration}; +use std::{num::NonZeroUsize, path::PathBuf, time::Duration}; use builder::non_permissioned::{build_instance_state, BuilderConfig}; use clap::Parser; -use cld::ClDuration; -use espresso_types::eth_signature_key::EthKeyPair; +use espresso_types::{eth_signature_key::EthKeyPair, parse_duration}; use hotshot::traits::ValidatedState; use hotshot_types::{data::ViewNumber, traits::node_implementation::ConsensusTime}; use sequencer::{Genesis, L1Params}; use sequencer_utils::logging; -use snafu::Snafu; use url::Url; use vbs::version::{StaticVersion, StaticVersionType}; @@ -88,19 +86,6 @@ struct NonPermissionedBuilderOptions { logging: logging::Config, } -#[derive(Clone, Debug, Snafu)] -struct ParseDurationError { - reason: String, -} - -fn parse_duration(s: &str) -> Result { - ClDuration::from_str(s) - .map(Duration::from) - .map_err(|err| ParseDurationError { - reason: err.to_string(), - }) -} - #[async_std::main] async fn main() -> anyhow::Result<()> { let opt = NonPermissionedBuilderOptions::parse(); diff --git a/builder/src/lib.rs b/builder/src/lib.rs index 6a64f41bb..bb8e6e958 100755 --- a/builder/src/lib.rs +++ b/builder/src/lib.rs @@ -165,7 +165,6 @@ pub mod testing { use portpicker::pick_unused_port; use sequencer::state_signature::StateSignatureMemStorage; use serde::{Deserialize, Serialize}; - use snafu::{guide::feature_flags, *}; use vbs::version::StaticVersion; use super::*; diff --git a/hotshot-state-prover/Cargo.toml b/hotshot-state-prover/Cargo.toml index e0d89ecb4..e1b216273 100644 --- a/hotshot-state-prover/Cargo.toml +++ b/hotshot-state-prover/Cargo.toml @@ -36,7 +36,6 @@ jf-utils = { workspace = true } reqwest = { workspace = true } sequencer-utils = { path = "../utils" } serde = { workspace = true } -snafu = { workspace = true } surf-disco = { workspace = true } tide-disco = { workspace = true } time = { workspace = true } diff --git a/hotshot-state-prover/src/bin/state-prover.rs b/hotshot-state-prover/src/bin/state-prover.rs index 30405cee4..79079a6e6 100644 --- a/hotshot-state-prover/src/bin/state-prover.rs +++ b/hotshot-state-prover/src/bin/state-prover.rs @@ -1,8 +1,7 @@ -use std::{str::FromStr as _, time::Duration}; +use std::time::Duration; use clap::Parser; -use cld::ClDuration; -use espresso_types::SeqTypes; +use espresso_types::{parse_duration, SeqTypes}; use ethers::{ providers::{Http, Middleware, Provider}, signers::{coins_bip39::English, MnemonicBuilder, Signer}, @@ -12,7 +11,6 @@ use hotshot_stake_table::config::STAKE_TABLE_CAPACITY; use hotshot_state_prover::service::{run_prover_once, run_prover_service, StateProverConfig}; use hotshot_types::traits::node_implementation::NodeType; use sequencer_utils::logging; -use snafu::Snafu; use url::Url; use vbs::version::StaticVersionType; @@ -85,19 +83,6 @@ struct Args { logging: logging::Config, } -#[derive(Clone, Debug, Snafu)] -pub struct ParseDurationError { - reason: String, -} - -fn parse_duration(s: &str) -> Result { - ClDuration::from_str(s) - .map(Duration::from) - .map_err(|err| ParseDurationError { - reason: err.to_string(), - }) -} - #[async_std::main] async fn main() { let args = Args::parse(); diff --git a/marketplace-builder/Cargo.toml b/marketplace-builder/Cargo.toml index 540baf81a..d7ff67244 100644 --- a/marketplace-builder/Cargo.toml +++ b/marketplace-builder/Cargo.toml @@ -40,7 +40,6 @@ portpicker = { workspace = true } rand = "0.8.5" sequencer = { path = "../sequencer", features = ["testing"] } serde = { workspace = true } -snafu = { workspace = true } surf = "2.3.1" surf-disco = { workspace = true } tagged-base64 = { workspace = true } diff --git a/marketplace-builder/src/bin/marketplace-builder.rs b/marketplace-builder/src/bin/marketplace-builder.rs index 4450ef1ff..2adfbdb5f 100644 --- a/marketplace-builder/src/bin/marketplace-builder.rs +++ b/marketplace-builder/src/bin/marketplace-builder.rs @@ -1,9 +1,10 @@ -use std::{num::NonZeroUsize, path::PathBuf, str::FromStr, time::Duration}; +use std::{num::NonZeroUsize, path::PathBuf, time::Duration}; use async_compatibility_layer::logging::{setup_backtrace, setup_logging}; use clap::Parser; -use cld::ClDuration; -use espresso_types::{eth_signature_key::EthKeyPair, FeeAmount, NamespaceId, SeqTypes}; +use espresso_types::{ + eth_signature_key::EthKeyPair, parse_duration, FeeAmount, NamespaceId, SeqTypes, +}; use hotshot::traits::ValidatedState; use hotshot_types::{data::ViewNumber, traits::node_implementation::ConsensusTime}; use marketplace_builder::{ @@ -12,7 +13,6 @@ use marketplace_builder::{ }; use marketplace_builder_core::testing::basic_test::NodeType; use sequencer::{Genesis, L1Params}; -use snafu::Snafu; use url::Url; use vbs::version::StaticVersionType; @@ -118,19 +118,6 @@ struct NonPermissionedBuilderOptions { bid_amount: FeeAmount, } -#[derive(Clone, Debug, Snafu)] -struct ParseDurationError { - reason: String, -} - -fn parse_duration(s: &str) -> Result { - ClDuration::from_str(s) - .map(Duration::from) - .map_err(|err| ParseDurationError { - reason: err.to_string(), - }) -} - #[async_std::main] async fn main() -> anyhow::Result<()> { setup_logging(); diff --git a/marketplace-solver/src/options.rs b/marketplace-solver/src/options.rs index acb458131..679bf9ad3 100644 --- a/marketplace-solver/src/options.rs +++ b/marketplace-solver/src/options.rs @@ -1,7 +1,7 @@ -use std::{str::FromStr, time::Duration}; +use std::time::Duration; use clap::Parser; -use thiserror::Error; +use espresso_types::parse_duration; use tide_disco::Url; use crate::database::PostgresClient; @@ -68,13 +68,3 @@ impl DatabaseOptions { PostgresClient::connect(self).await } } - -#[derive(Clone, Debug, Error)] -#[error("failed to parse `{0}`")] -pub struct ParseDurationError(String); - -pub fn parse_duration(s: &str) -> Result { - cld::ClDuration::from_str(s) - .map(Duration::from) - .map_err(|err| ParseDurationError(err.to_string())) -} diff --git a/node-metrics/Cargo.toml b/node-metrics/Cargo.toml index 51afc0430..512738057 100644 --- a/node-metrics/Cargo.toml +++ b/node-metrics/Cargo.toml @@ -21,6 +21,9 @@ futures = { workspace = true } hotshot = { workspace = true } hotshot-query-service = { workspace = true } hotshot-stake-table = { workspace = true } + +# Dependencies for feature `testing` +hotshot-testing = { workspace = true, optional = true } hotshot-types = { workspace = true } prometheus-parse = { version = "^0.2.5" } reqwest = { workspace = true } @@ -34,6 +37,3 @@ toml = { workspace = true } tracing = { workspace = true } url = { workspace = true } vbs = { workspace = true } - -# Dependencies for feature `testing` -hotshot-testing = { workspace = true, optional = true } diff --git a/sequencer/Cargo.toml b/sequencer/Cargo.toml index ec5bcf611..e50d4c37d 100644 --- a/sequencer/Cargo.toml +++ b/sequencer/Cargo.toml @@ -88,7 +88,7 @@ sequencer-utils = { path = "../utils" } serde = { workspace = true } serde_json = { workspace = true } sha2 = "0.10" # TODO temporary, used only for VID, should be set in hotshot -snafu = { workspace = true } +snafu = "0.8" static_assertions = "1" strum = { workspace = true } surf-disco = { workspace = true } @@ -101,7 +101,6 @@ tracing-subscriber = "0.3.18" url = { workspace = true } vbs = { workspace = true } vec1 = { workspace = true } - [package.metadata.cargo-udeps.ignore] normal = ["hotshot-testing"] diff --git a/sequencer/src/api/endpoints.rs b/sequencer/src/api/endpoints.rs index 1f8161c79..d32703c45 100644 --- a/sequencer/src/api/endpoints.rs +++ b/sequencer/src/api/endpoints.rs @@ -51,6 +51,9 @@ pub(super) type AvailState = Arc type AvailabilityApi = Api, availability::Error, Ver>; +// TODO (abdul): replace snafu with `this_error` in hotshot query service +// Snafu has been replaced by `this_error` everywhere. +// However, the query service still uses snafu pub(super) fn availability( bind_version: Ver, ) -> Result> diff --git a/sequencer/src/bin/cdn-broker.rs b/sequencer/src/bin/cdn-broker.rs index a2a3500d6..91a605f35 100644 --- a/sequencer/src/bin/cdn-broker.rs +++ b/sequencer/src/bin/cdn-broker.rs @@ -3,12 +3,9 @@ use anyhow::{Context, Result}; use cdn_broker::{reexports::crypto::signature::KeyPair, Broker, Config}; use clap::Parser; -use espresso_types::SeqTypes; +use espresso_types::{parse_size, SeqTypes}; use hotshot_types::traits::{node_implementation::NodeType, signature_key::SignatureKey}; -use sequencer::{ - network::cdn::{ProductionDef, WrappedSignatureKey}, - options::parse_size, -}; +use sequencer::network::cdn::{ProductionDef, WrappedSignatureKey}; use sha2::Digest; use tracing_subscriber::EnvFilter; diff --git a/sequencer/src/bin/cdn-marshal.rs b/sequencer/src/bin/cdn-marshal.rs index 445c9b665..0cd88d495 100644 --- a/sequencer/src/bin/cdn-marshal.rs +++ b/sequencer/src/bin/cdn-marshal.rs @@ -4,8 +4,8 @@ use anyhow::{Context, Result}; use cdn_marshal::{Config, Marshal}; use clap::Parser; -use espresso_types::SeqTypes; -use sequencer::{network::cdn::ProductionDef, options::parse_size}; +use espresso_types::{parse_size, SeqTypes}; +use sequencer::network::cdn::ProductionDef; use tracing_subscriber::EnvFilter; #[derive(Parser, Debug)] diff --git a/sequencer/src/bin/commitment-task.rs b/sequencer/src/bin/commitment-task.rs index 2eee0937b..b62443cf4 100644 --- a/sequencer/src/bin/commitment-task.rs +++ b/sequencer/src/bin/commitment-task.rs @@ -2,14 +2,11 @@ use std::{io, time::Duration}; use async_std::task::spawn; use clap::Parser; -use espresso_types::SeqTypes; +use espresso_types::{parse_duration, SeqTypes}; use ethers::prelude::*; use futures::FutureExt; use hotshot_types::traits::node_implementation::NodeType; -use sequencer::{ - hotshot_commitment::{run_hotshot_commitment_task, CommitmentTaskOptions}, - options::parse_duration, -}; +use sequencer::hotshot_commitment::{run_hotshot_commitment_task, CommitmentTaskOptions}; use sequencer_utils::logging; use tide_disco::{error::ServerError, Api}; use url::Url; diff --git a/sequencer/src/bin/nasty-client.rs b/sequencer/src/bin/nasty-client.rs index d4c87698b..5f0f27116 100644 --- a/sequencer/src/bin/nasty-client.rs +++ b/sequencer/src/bin/nasty-client.rs @@ -20,7 +20,9 @@ use async_std::{ use clap::Parser; use committable::Committable; use derivative::Derivative; -use espresso_types::{v0_3::IterableFeeInfo, BlockMerkleTree, FeeMerkleTree, Header, SeqTypes}; +use espresso_types::{ + parse_duration, v0_3::IterableFeeInfo, BlockMerkleTree, FeeMerkleTree, Header, SeqTypes, +}; use futures::{ future::{FutureExt, TryFuture, TryFutureExt}, stream::{Peekable, StreamExt}, @@ -38,7 +40,7 @@ use jf_merkle_tree::{ ForgetableMerkleTreeScheme, MerkleCommitment, MerkleTreeScheme, UniversalMerkleTreeScheme, }; use rand::{seq::SliceRandom, RngCore}; -use sequencer::{api::endpoints::NamespaceProofQueryData, options::parse_duration}; +use sequencer::api::endpoints::NamespaceProofQueryData; use sequencer_utils::logging; use serde::de::DeserializeOwned; use std::{ diff --git a/sequencer/src/bin/orchestrator.rs b/sequencer/src/bin/orchestrator.rs index fed39f64c..f80b5c8a1 100644 --- a/sequencer/src/bin/orchestrator.rs +++ b/sequencer/src/bin/orchestrator.rs @@ -2,13 +2,12 @@ use std::{num::NonZeroUsize, time::Duration}; use clap::Parser; use derive_more::From; -use espresso_types::PubKey; +use espresso_types::{parse_duration, PubKey, Ratio}; use ethers::utils::hex::{self, FromHexError}; use hotshot_orchestrator::{ config::{Libp2pConfig, NetworkConfig}, run_orchestrator, }; -use sequencer::options::{parse_duration, Ratio}; use sequencer_utils::logging; use snafu::Snafu; use url::Url; diff --git a/sequencer/src/bin/submit-transactions.rs b/sequencer/src/bin/submit-transactions.rs index 2708149c1..0eecb4045 100644 --- a/sequencer/src/bin/submit-transactions.rs +++ b/sequencer/src/bin/submit-transactions.rs @@ -8,7 +8,7 @@ use std::{ use async_std::task::{sleep, spawn}; use clap::Parser; use committable::{Commitment, Committable}; -use espresso_types::{SeqTypes, Transaction}; +use espresso_types::{parse_duration, parse_size, SeqTypes, Transaction}; use futures::{ channel::mpsc::{self, Sender}, sink::SinkExt, @@ -19,7 +19,6 @@ use hotshot_types::traits::node_implementation::NodeType; use rand::{Rng, RngCore, SeedableRng}; use rand_chacha::ChaChaRng; use rand_distr::Distribution; -use sequencer::options::{parse_duration, parse_size}; use sequencer_utils::logging; use surf_disco::{Client, Url}; use tide_disco::{error::ServerError, App}; diff --git a/sequencer/src/options.rs b/sequencer/src/options.rs index 5e367c201..83f8d40dc 100644 --- a/sequencer/src/options.rs +++ b/sequencer/src/options.rs @@ -5,22 +5,15 @@ use std::{ collections::{HashMap, HashSet}, fmt::{self, Formatter}, iter::once, - num::ParseIntError, path::PathBuf, - str::FromStr, - time::Duration, }; use anyhow::{bail, Context}; -use bytesize::ByteSize; use clap::{error::ErrorKind, Args, FromArgMatches, Parser}; -use cld::ClDuration; use derivative::Derivative; -use derive_more::From; use espresso_types::BackoffParams; use hotshot_types::{light_client::StateSignKey, signature_key::BLSPrivKey}; use libp2p::Multiaddr; -use snafu::Snafu; use url::Url; use crate::{api, persistence}; @@ -304,28 +297,6 @@ fn fmt_opt_urls( Ok(()) } -#[derive(Clone, Debug, Snafu)] -pub struct ParseDurationError { - reason: String, -} - -pub fn parse_duration(s: &str) -> Result { - ClDuration::from_str(s) - .map(Duration::from) - .map_err(|err| ParseDurationError { - reason: err.to_string(), - }) -} - -#[derive(Clone, Debug, From, Snafu)] -pub struct ParseSizeError { - msg: String, -} - -pub fn parse_size(s: &str) -> Result { - Ok(s.parse::()?.0) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Ratio { pub numerator: u64, @@ -356,34 +327,6 @@ impl Ord for Ratio { } } -#[derive(Debug, Snafu)] -pub enum ParseRatioError { - #[snafu(display("numerator and denominator must be separated by :"))] - MissingDelimiter, - InvalidNumerator { - err: ParseIntError, - }, - InvalidDenominator { - err: ParseIntError, - }, -} - -impl FromStr for Ratio { - type Err = ParseRatioError; - - fn from_str(s: &str) -> Result { - let (num, den) = s.split_once(':').ok_or(ParseRatioError::MissingDelimiter)?; - Ok(Self { - numerator: num - .parse() - .map_err(|err| ParseRatioError::InvalidNumerator { err })?, - denominator: den - .parse() - .map_err(|err| ParseRatioError::InvalidDenominator { err })?, - }) - } -} - #[derive(Clone, Debug)] struct ModuleArgs(Vec); diff --git a/sequencer/src/persistence/sql.rs b/sequencer/src/persistence/sql.rs index 4802abb89..08ed947cd 100644 --- a/sequencer/src/persistence/sql.rs +++ b/sequencer/src/persistence/sql.rs @@ -9,6 +9,7 @@ use async_trait::async_trait; use clap::Parser; use derivative::Derivative; use espresso_types::{ + parse_duration, v0::traits::{PersistenceOptions, SequencerPersistence, StateCatchup}, BackoffParams, Leaf, NetworkConfig, }; @@ -31,7 +32,7 @@ use hotshot_types::{ vote::HasViewNumber, }; -use crate::{catchup::SqlStateCatchup, options::parse_duration, SeqTypes, ViewNumber}; +use crate::{catchup::SqlStateCatchup, SeqTypes, ViewNumber}; /// Options for Postgres-backed persistence. #[derive(Parser, Clone, Derivative, Default)] diff --git a/types/Cargo.toml b/types/Cargo.toml index 806d8259a..ee88afdbe 100644 --- a/types/Cargo.toml +++ b/types/Cargo.toml @@ -43,7 +43,6 @@ sequencer-utils = { path = "../utils" } serde = { workspace = true } serde_json = { workspace = true } sha2 = "0.10" # TODO temporary, used only for VID, should be set in hotshot -snafu = { workspace = true } static_assertions = { workspace = true } surf-disco = { workspace = true } tagged-base64 = { workspace = true } diff --git a/types/src/eth_signature_key.rs b/types/src/eth_signature_key.rs index d50068e48..88890b29d 100644 --- a/types/src/eth_signature_key.rs +++ b/types/src/eth_signature_key.rs @@ -14,7 +14,7 @@ use ethers::{ }; use hotshot_types::traits::signature_key::BuilderSignatureKey; use serde::{Deserialize, Serialize}; -use snafu::Snafu; +use thiserror::Error; use crate::FeeAccount; @@ -113,8 +113,9 @@ impl Ord for EthKeyPair { } } -#[derive(Clone, Debug, Snafu)] -pub struct SigningError; +#[derive(Debug, Error)] +#[error("Failed to sign builder message")] +pub struct SigningError(#[from] WalletError); pub type BuilderSignature = Signature; @@ -133,7 +134,7 @@ impl BuilderSignatureKey for FeeAccount { ) -> Result { let wallet = private_key.signer(); let message_hash = ethers::utils::hash_message(data); - wallet.sign_hash(message_hash).map_err(|_| SigningError) + wallet.sign_hash(message_hash).map_err(SigningError::from) } fn generated_from_seed_indexed(seed: [u8; 32], index: u64) -> (Self, Self::BuilderPrivateKey) { diff --git a/types/src/v0/error.rs b/types/src/v0/error.rs deleted file mode 100644 index 58dea8b58..000000000 --- a/types/src/v0/error.rs +++ /dev/null @@ -1,31 +0,0 @@ -use core::fmt::Debug; - -use serde::{Deserialize, Serialize}; -use snafu::Snafu; - -// TODO: Remove global error -// issue #1681 (https://github.com/EspressoSystems/espresso-sequencer/issues/1681) -#[derive(Clone, Debug, Snafu, Deserialize, Serialize)] -pub enum Error { - // TODO: Can we nest these errors in a `ValidationError` to group them? - - // Parent state commitment of block doesn't match current state commitment - IncorrectParent, - - // New view number isn't strictly after current view - IncorrectView, - - // Genesis block either has zero or more than one transaction - GenesisWrongSize, - - // Genesis transaction not present in genesis block - MissingGenesis, - - // Genesis transaction in non-genesis block - UnexpectedGenesis, - - // Merkle tree error - MerkleTreeError { error: String }, - - BlockBuilding, -} diff --git a/types/src/v0/impls/block/full_payload/payload.rs b/types/src/v0/impls/block/full_payload/payload.rs index 87d21178e..06b7bae51 100644 --- a/types/src/v0/impls/block/full_payload/payload.rs +++ b/types/src/v0/impls/block/full_payload/payload.rs @@ -3,6 +3,7 @@ use std::{collections::BTreeMap, sync::Arc}; use async_trait::async_trait; use committable::Committable; use hotshot_query_service::availability::QueryablePayload; +use hotshot_types::data::ViewNumber; use hotshot_types::{ traits::{BlockPayload, EncodeBytes}, utils::BuilderCommitment, @@ -10,6 +11,7 @@ use hotshot_types::{ }; use jf_vid::VidScheme; use sha2::Digest; +use thiserror::Error; use crate::{ v0::impls::{NodeState, ValidatedState}, @@ -18,6 +20,20 @@ use crate::{ NsTableBuilder, Payload, PayloadByteLen, SeqTypes, Transaction, TxProof, }; +#[derive(serde::Deserialize, serde::Serialize, Error, Debug, Eq, PartialEq)] +pub enum BlockBuildingError { + #[error("Parent state commitment {0} of block doesn't match current state commitment")] + IncorrectParent(String), + #[error("New view number ({new:?}) isn't strictly after current view ({curr:?})")] + IncorrectView { new: ViewNumber, curr: ViewNumber }, + #[error("Genesis block either has zero or more than one transaction")] + GenesisWrongSize, + #[error("Genesis transaction not present in genesis block")] + MissingGenesis, + #[error("Genesis transaction in non-genesis block")] + UnexpectedGenesis, +} + impl Payload { pub fn ns_table(&self) -> &NsTable { &self.ns_table @@ -63,7 +79,7 @@ impl Payload { // accounting for block byte length limit let max_block_byte_len: usize = u64::from(chain_config.max_block_size) .try_into() - .map_err(|_| >::Error::BlockBuilding)?; + .expect("too large max block size for architecture"); let mut block_byte_len = NsTableBuilder::header_byte_len(); // add each tx to its namespace @@ -118,7 +134,7 @@ impl Payload { impl BlockPayload for Payload { // TODO BlockPayload trait eliminate unneeded args, return vals of type // `Self::Metadata` https://github.com/EspressoSystems/HotShot/issues/3300 - type Error = crate::Error; + type Error = BlockBuildingError; type Transaction = Transaction; type Instance = NodeState; type Metadata = NsTable; diff --git a/types/src/v0/impls/chain_config.rs b/types/src/v0/impls/chain_config.rs index 1c664cd22..4c755ed4c 100644 --- a/types/src/v0/impls/chain_config.rs +++ b/types/src/v0/impls/chain_config.rs @@ -1,14 +1,13 @@ -use bytesize::ByteSize; -use derive_more::From; use ethers::types::U256; use sequencer_utils::{ impl_serde_from_string_or_integer, impl_to_fixed_bytes, ser::FromStringOrInteger, }; -use snafu::Snafu; use std::str::FromStr; use crate::{BlockSize, ChainId}; +use super::parse_size; + impl_serde_from_string_or_integer!(ChainId); impl_to_fixed_bytes!(ChainId, U256); @@ -74,15 +73,6 @@ impl FromStringOrInteger for BlockSize { } } -#[derive(Clone, Debug, From, Snafu)] -pub struct ParseSizeError { - msg: String, -} - -pub fn parse_size(s: &str) -> Result { - Ok(s.parse::()?.0) -} - #[cfg(test)] mod tests { use crate::v0_3::{ChainConfig, ResolvableChainConfig}; diff --git a/types/src/v0/impls/header.rs b/types/src/v0/impls/header.rs index 91e105a5e..9fdc6dad0 100644 --- a/types/src/v0/impls/header.rs +++ b/types/src/v0/impls/header.rs @@ -19,7 +19,6 @@ use serde::{ Deserialize, Deserializer, Serialize, Serializer, }; use serde_json::{Map, Value}; -use snafu::Snafu; use std::fmt; use thiserror::Error; use time::OffsetDateTime; @@ -29,53 +28,12 @@ use crate::{ v0::header::{EitherOrVersion, VersionedHeader}, v0_1, v0_2, v0_3::{self, ChainConfig, IterableFeeInfo, SolverAuctionResults}, - BlockMerkleCommitment, BlockSize, BuilderSignature, FeeAccount, FeeAmount, FeeInfo, - FeeMerkleCommitment, Header, L1BlockInfo, L1Snapshot, Leaf, NamespaceId, NsTable, - NsTableValidationError, SeqTypes, UpgradeType, + BlockMerkleCommitment, BuilderSignature, FeeAccount, FeeAmount, FeeInfo, FeeMerkleCommitment, + Header, L1BlockInfo, L1Snapshot, Leaf, NamespaceId, NsTable, SeqTypes, UpgradeType, }; use super::{instance_state::NodeState, state::ValidatedState}; -/// Possible proposal validation failures -#[derive(Error, Debug, Eq, PartialEq)] -pub enum ProposalValidationError { - #[error("Invalid ChainConfig: expected={expected}, proposal={proposal}")] - InvalidChainConfig { expected: String, proposal: String }, - - #[error( - "Invalid Payload Size: (max_block_size={max_block_size}, proposed_block_size={block_size})" - )] - MaxBlockSizeExceeded { - max_block_size: BlockSize, - block_size: BlockSize, - }, - #[error("Insufficient Fee: block_size={max_block_size}, base_fee={base_fee}, proposed_fee={proposed_fee}")] - InsufficientFee { - max_block_size: BlockSize, - base_fee: FeeAmount, - proposed_fee: FeeAmount, - }, - #[error("Invalid Height: parent_height={parent_height}, proposal_height={proposal_height}")] - InvalidHeight { - parent_height: u64, - proposal_height: u64, - }, - #[error("Invalid Block Root Error: expected={expected_root}, proposal={proposal_root}")] - InvalidBlockRoot { - expected_root: BlockMerkleCommitment, - proposal_root: BlockMerkleCommitment, - }, - #[error("Invalid Fee Root Error: expected={expected_root}, proposal={proposal_root}")] - InvalidFeeRoot { - expected_root: FeeMerkleCommitment, - proposal_root: FeeMerkleCommitment, - }, - #[error("Invalid namespace table: {err}")] - InvalidNsTable { err: NsTableValidationError }, - #[error("Some fee amount or their sum total out of range")] - SomeFeeAmountOutOfRange, -} - impl v0_1::Header { pub(crate) fn commit(&self) -> Commitment
{ let mut bmt_bytes = vec![]; @@ -735,8 +693,8 @@ impl Header { } } -#[derive(Debug, Snafu)] -#[snafu(display("Invalid Block Header {msg}"))] +#[derive(Debug, Error)] +#[error("Invalid Block Header {msg}")] pub struct InvalidBlockHeader { msg: String, } @@ -1130,7 +1088,7 @@ mod test_headers { use super::*; use crate::{ eth_signature_key::EthKeyPair, v0::impls::instance_state::mock::MockStateCatchup, - validate_proposal, + validate_proposal, ProposalValidationError, }; #[derive(Debug, Default)] diff --git a/types/src/v0/impls/mod.rs b/types/src/v0/impls/mod.rs index 9b02a921a..ef3975673 100644 --- a/types/src/v0/impls/mod.rs +++ b/types/src/v0/impls/mod.rs @@ -12,6 +12,6 @@ mod state; mod transaction; pub use fee_info::FeeError; -pub use header::ProposalValidationError; pub use instance_state::{mock, NodeState}; +pub use state::ProposalValidationError; pub use state::{validate_proposal, BuilderValidationError, StateValidationError, ValidatedState}; diff --git a/types/src/v0/impls/state.rs b/types/src/v0/impls/state.rs index 76e64107c..a38839119 100644 --- a/types/src/v0/impls/state.rs +++ b/types/src/v0/impls/state.rs @@ -26,8 +26,8 @@ use thiserror::Error; use vbs::version::Version; use super::{ - auction::ExecutionError, fee_info::FeeError, header::ProposalValidationError, - instance_state::NodeState, + auction::ExecutionError, fee_info::FeeError, instance_state::NodeState, BlockMerkleCommitment, + BlockSize, FeeMerkleCommitment, }; use crate::{ v0_3::{ChainConfig, FullNetworkTx, IterableFeeInfo, ResolvableChainConfig}, @@ -36,6 +36,15 @@ use crate::{ FEE_MERKLE_TREE_HEIGHT, }; +/// This enum is not used in code but functions as an index of +/// possible validation errors. +#[allow(dead_code)] +pub enum StateValidationError { + ProposalValidation(ProposalValidationError), + BuilderValidation(BuilderValidationError), + Fee(FeeError), +} + /// Possible builder validation failures #[derive(Error, Debug, Eq, PartialEq)] pub enum BuilderValidationError { @@ -47,13 +56,44 @@ pub enum BuilderValidationError { InvalidBuilderSignature, } -/// This enum is not used in code but functions as an index of -/// possible validation errors. -#[allow(dead_code)] -pub enum StateValidationError { - ProposalValidation(ProposalValidationError), - BuilderValidation(BuilderValidationError), - Fee(FeeError), +/// Possible proposal validation failures +#[derive(Error, Debug, Eq, PartialEq)] +pub enum ProposalValidationError { + #[error("Invalid ChainConfig: expected={expected}, proposal={proposal}")] + InvalidChainConfig { expected: String, proposal: String }, + + #[error( + "Invalid Payload Size: (max_block_size={max_block_size}, proposed_block_size={block_size})" + )] + MaxBlockSizeExceeded { + max_block_size: BlockSize, + block_size: BlockSize, + }, + #[error("Insufficient Fee: block_size={max_block_size}, base_fee={base_fee}, proposed_fee={proposed_fee}")] + InsufficientFee { + max_block_size: BlockSize, + base_fee: FeeAmount, + proposed_fee: FeeAmount, + }, + #[error("Invalid Height: parent_height={parent_height}, proposal_height={proposal_height}")] + InvalidHeight { + parent_height: u64, + proposal_height: u64, + }, + #[error("Invalid Block Root Error: expected={expected_root}, proposal={proposal_root}")] + InvalidBlockRoot { + expected_root: BlockMerkleCommitment, + proposal_root: BlockMerkleCommitment, + }, + #[error("Invalid Fee Root Error: expected={expected_root}, proposal={proposal_root}")] + InvalidFeeRoot { + expected_root: FeeMerkleCommitment, + proposal_root: FeeMerkleCommitment, + }, + #[error("Invalid namespace table: {err}")] + InvalidNsTable { err: NsTableValidationError }, + #[error("Some fee amount or their sum total out of range")] + SomeFeeAmountOutOfRange, } impl StateDelta for Delta {} diff --git a/types/src/v0/mod.rs b/types/src/v0/mod.rs index 85dac4d76..3a9e0c0d1 100644 --- a/types/src/v0/mod.rs +++ b/types/src/v0/mod.rs @@ -6,12 +6,10 @@ use hotshot_types::{ }; use serde::{Deserialize, Serialize}; -mod error; mod header; mod impls; pub mod traits; mod utils; -pub use error::*; pub use header::Header; pub use impls::{ mock, validate_proposal, BuilderValidationError, FeeError, ProposalValidationError, diff --git a/types/src/v0/utils.rs b/types/src/v0/utils.rs index 6452cf7d1..ccd830a04 100644 --- a/types/src/v0/utils.rs +++ b/types/src/v0/utils.rs @@ -1,12 +1,12 @@ use anyhow::Context; use async_std::task::sleep; +use bytesize::ByteSize; use clap::Parser; use derive_more::{Display, From, Into}; use futures::future::BoxFuture; use rand::Rng; use sequencer_utils::{impl_serde_from_string_or_integer, ser::FromStringOrInteger}; use serde::{Deserialize, Serialize}; -use snafu::Snafu; use std::{ cmp::{min, Ordering}, fmt::{self, Debug, Display, Formatter}, @@ -14,6 +14,7 @@ use std::{ str::FromStr, time::Duration, }; +use thiserror::Error; use time::{ format_description::well_known::Rfc3339 as TimestampFormat, macros::time, Date, OffsetDateTime, }; @@ -106,16 +107,14 @@ impl Ord for Ratio { } } -#[derive(Debug, Snafu)] +#[derive(Debug, Error)] pub enum ParseRatioError { - #[snafu(display("numerator and denominator must be separated by :"))] + #[error("numerator and denominator must be separated by :")] MissingDelimiter, - InvalidNumerator { - err: ParseIntError, - }, - InvalidDenominator { - err: ParseIntError, - }, + #[error("Invalid numerator {err:?}")] + InvalidNumerator { err: ParseIntError }, + #[error("Invalid denominator {err:?}")] + InvalidDenominator { err: ParseIntError }, } impl FromStr for Ratio { @@ -134,7 +133,8 @@ impl FromStr for Ratio { } } -#[derive(Clone, Debug, Snafu)] +#[derive(Clone, Debug, Error)] +#[error("Failed to parse duration {reason}")] pub struct ParseDurationError { reason: String, } @@ -147,6 +147,16 @@ pub fn parse_duration(s: &str) -> Result { }) } +#[derive(Clone, Debug, From, Error)] +#[error("failed to parse ByteSize. {msg}")] +pub struct ParseSizeError { + msg: String, +} + +pub fn parse_size(s: &str) -> Result { + Ok(s.parse::()?.0) +} + pub const MIN_RETRY_DELAY: Duration = Duration::from_millis(500); pub const MAX_RETRY_DELAY: Duration = Duration::from_secs(5); pub const BACKOFF_FACTOR: u32 = 2;