Skip to content

Commit

Permalink
fixes for chain_config v3
Browse files Browse the repository at this point in the history
  * move NodeState and ValidatedState to `impl`
  * wrap `bid_reciepient` in an `Option`
  * Implement from `v0_1::ResolvableChainConfig` for `v0_3::ResolvableChainConfig`
  • Loading branch information
tbro committed Jul 17, 2024
1 parent 635da50 commit f1be763
Show file tree
Hide file tree
Showing 15 changed files with 177 additions and 123 deletions.
18 changes: 15 additions & 3 deletions types/src/v0/impls/auction.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
eth_signature_key::{EthKeyPair, SigningError},
v0_3::{BidTx, BidTxBody, FullNetworkTx},
FeeAccount, FeeAmount, FeeError, FeeInfo, NamespaceId, ValidatedState,
FeeAccount, FeeAmount, FeeError, FeeInfo, NamespaceId,
};
use committable::{Commitment, Committable};
use ethers::types::Signature;
Expand All @@ -16,6 +16,8 @@ use std::str::FromStr;
use thiserror::Error;
use url::Url;

use super::state::ValidatedState;

impl FullNetworkTx {
pub fn execute(
&self,
Expand Down Expand Up @@ -176,15 +178,25 @@ impl BidTx {
let recipient = chain_config.bid_recipient;
// Charge the bid amount
state
.charge_fee(FeeInfo::new(self.account(), self.amount()), recipient)
.charge_fee(
FeeInfo::new(self.account(), self.amount()),
// TODO This code is only called from v0_3, so should be safe to unwrap,
// but maybe we should guard against the error anyway
recipient.unwrap(),
)
.map_err(ExecutionError::from)?;

// TODO are gas and bid funded to same recipient? Possibly
// gas would be funded to recipient sequencing
// fee recipient?
// Charge the the gas amount
state
.charge_fee(FeeInfo::new(self.account(), self.gas_price()), recipient)
.charge_fee(
FeeInfo::new(self.account(), self.gas_price()),
// TODO This code is only called from v0_3, so should be safe to unwrap,
// but maybe we should guard against the error anyway
recipient.unwrap(),
)
.map_err(ExecutionError::from)?;

Ok(())
Expand Down
7 changes: 4 additions & 3 deletions types/src/v0/impls/block/full_payload/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ use jf_vid::VidScheme;
use sha2::Digest;

use crate::{
ChainConfig, Index, Iter, NamespaceId, NodeState, NsIndex, NsPayload, NsPayloadBuilder,
NsPayloadRange, NsTable, NsTableBuilder, Payload, PayloadByteLen, SeqTypes, Transaction,
TxProof, ValidatedState,
v0::impls::{instance_state::NodeState, state::ValidatedState},
v0_3::ChainConfig,
Index, Iter, NamespaceId, NsIndex, NsPayload, NsPayloadBuilder, NsPayloadRange, NsTable,
NsTableBuilder, Payload, PayloadByteLen, SeqTypes, Transaction, TxProof,
};

impl Payload {
Expand Down
18 changes: 3 additions & 15 deletions types/src/v0/impls/chain_config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::str::FromStr;

use bytesize::ByteSize;
use committable::Commitment;
use derive_more::From;
Expand All @@ -10,7 +9,7 @@ use sequencer_utils::{
};
use snafu::Snafu;

use crate::{BlockSize, ChainConfig, ChainId, ResolvableChainConfig};
use crate::{BlockSize, ChainId};

impl_serde_from_string_or_integer!(ChainId);
impl_to_fixed_bytes!(ChainId, U256);
Expand Down Expand Up @@ -77,19 +76,6 @@ impl FromStringOrInteger for BlockSize {
}
}

impl Default for ChainConfig {
fn default() -> Self {
Self {
chain_id: U256::from(35353).into(), // arbitrarily chosen chain ID
max_block_size: 10240.into(),
base_fee: 0.into(),
fee_contract: None,
fee_recipient: Default::default(),
bid_recipient: Default::default(),
}
}
}

#[derive(Clone, Debug, From, Snafu)]
pub struct ParseSizeError {
msg: String,
Expand All @@ -101,6 +87,8 @@ pub fn parse_size(s: &str) -> Result<u64, ParseSizeError> {

#[cfg(test)]
mod tests {
use crate::v0_3::{ChainConfig, ResolvableChainConfig};

use super::*;

#[test]
Expand Down
20 changes: 13 additions & 7 deletions types/src/v0/impls/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ use vbs::version::Version;
use crate::{
v0::header::{EitherOrVersion, VersionedHeader},
v0_1, v0_2,
v0_3::{self, FullNetworkTx, IterableFeeInfo},
BlockMerkleCommitment, BlockSize, BuilderSignature, ChainConfig, FeeAccount, FeeAmount,
FeeInfo, FeeMerkleCommitment, Header, L1BlockInfo, L1Snapshot, Leaf, NamespaceId, NodeState,
NsTable, NsTableValidationError, ResolvableChainConfig, SeqTypes, UpgradeType, ValidatedState,
v0_3::{self, ChainConfig, FullNetworkTx, IterableFeeInfo, ResolvableChainConfig},
BlockMerkleCommitment, BlockSize, BuilderSignature, FeeAccount, FeeAmount, FeeInfo,
FeeMerkleCommitment, Header, L1BlockInfo, L1Snapshot, Leaf, NamespaceId, NsTable,
NsTableValidationError, SeqTypes, UpgradeType,
};

use super::{instance_state::NodeState, state::ValidatedState};

/// Possible proposal validation failures
#[derive(Error, Debug, Eq, PartialEq)]
pub enum ProposalValidationError {
Expand Down Expand Up @@ -542,8 +544,12 @@ impl Header {

impl Header {
/// A commitment to a ChainConfig or a full ChainConfig.
pub fn chain_config(&self) -> &ResolvableChainConfig {
field!(self.chain_config)
pub fn chain_config(&self) -> v0_3::ResolvableChainConfig {
match self {
Self::V1(fields) => v0_3::ResolvableChainConfig::from(&fields.chain_config),
Self::V2(fields) => v0_3::ResolvableChainConfig::from(&fields.chain_config),
Self::V3(fields) => fields.chain_config,
}
}

pub fn height(&self) -> u64 {
Expand Down Expand Up @@ -958,7 +964,7 @@ mod test_headers {
use super::*;
use crate::{
eth_signature_key::EthKeyPair, v0::impls::instance_state::mock::MockStateCatchup,
validate_proposal, NodeState,
validate_proposal,
};

#[derive(Debug, Default)]
Expand Down
39 changes: 36 additions & 3 deletions types/src/v0/impls/instance_state.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,45 @@
use std::{collections::BTreeMap, sync::Arc};

use hotshot_types::traits::{node_implementation::NodeType, states::InstanceState};
use std::{collections::BTreeMap, sync::Arc};
use vbs::version::{StaticVersionType, Version};

use crate::{
v0::traits::StateCatchup, ChainConfig, L1Client, NodeState, SeqTypes, Upgrade, ValidatedState,
v0::traits::StateCatchup, v0_3::ChainConfig, GenesisHeader, L1BlockInfo, L1Client, SeqTypes,
Upgrade,
};

use super::state::ValidatedState;

/// Represents the immutable state of a node.
///
/// For mutable state, use `ValidatedState`.
#[derive(Debug, Clone)]
pub struct NodeState {
pub node_id: u64,
pub chain_config: crate::v0_3::ChainConfig,
pub l1_client: L1Client,
pub peers: Arc<dyn StateCatchup>,
pub genesis_header: GenesisHeader,
pub genesis_state: ValidatedState,
pub l1_genesis: Option<L1BlockInfo>,

/// Map containing all planned and executed upgrades.
///
/// Currently, only one upgrade can be executed at a time.
/// For multiple upgrades, the node needs to be restarted after each upgrade.
///
/// This field serves as a record for planned and past upgrades,
/// listed in the genesis TOML file. It will be very useful if multiple upgrades
/// are supported in the future.
pub upgrades: BTreeMap<Version, Upgrade>,
/// Current version of the sequencer.
///
/// This version is checked to determine if an upgrade is planned,
/// and which version variant for versioned types
/// to use in functions such as genesis.
/// (example: genesis returns V2 Header if version is 0.2)
pub current_version: Version,
}

impl NodeState {
pub fn new(
node_id: u64,
Expand Down
4 changes: 2 additions & 2 deletions types/src/v0/impls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ mod transaction;

pub use fee_info::FeeError;
pub use header::ProposalValidationError;
pub use instance_state::mock;
pub use state::{validate_proposal, BuilderValidationError, StateValidationError};
pub use instance_state::{mock, NodeState};
pub use state::{validate_proposal, BuilderValidationError, StateValidationError, ValidatedState};
30 changes: 21 additions & 9 deletions types/src/v0/impls/state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::ops::Add;

use anyhow::bail;
use committable::Committable;
use ethers::types::Address;
Expand All @@ -21,15 +19,20 @@ use jf_merkle_tree::{
};
use jf_vid::VidScheme;
use num_traits::CheckedSub;
use serde::{Deserialize, Serialize};
use std::ops::Add;
use thiserror::Error;
use vbs::version::Version;

use super::{auction::ExecutionError, fee_info::FeeError, header::ProposalValidationError};
use super::{
auction::ExecutionError, fee_info::FeeError, header::ProposalValidationError,
instance_state::NodeState,
};
use crate::{
v0_3::{FullNetworkTx, IterableFeeInfo},
BlockMerkleTree, ChainConfig, Delta, FeeAccount, FeeAmount, FeeInfo, FeeMerkleTree, Header,
Leaf, NodeState, NsTableValidationError, PayloadByteLen, ResolvableChainConfig, SeqTypes,
UpgradeType, ValidatedState, BLOCK_MERKLE_TREE_HEIGHT, FEE_MERKLE_TREE_HEIGHT,
v0_3::{ChainConfig, FullNetworkTx, IterableFeeInfo, ResolvableChainConfig},
BlockMerkleTree, Delta, FeeAccount, FeeAmount, FeeInfo, FeeMerkleTree, Header, Leaf,
NsTableValidationError, PayloadByteLen, SeqTypes, UpgradeType, BLOCK_MERKLE_TREE_HEIGHT,
FEE_MERKLE_TREE_HEIGHT,
};

/// Possible builder validation failures
Expand All @@ -54,6 +57,15 @@ pub enum StateValidationError {

impl StateDelta for Delta {}

#[derive(Hash, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct ValidatedState {
/// Frontier of Block Merkle Tree
pub block_merkle_tree: BlockMerkleTree,
/// Fee Merkle Tree
pub fee_merkle_tree: FeeMerkleTree,
pub chain_config: ResolvableChainConfig,
}

impl Default for ValidatedState {
fn default() -> Self {
let block_merkle_tree =
Expand Down Expand Up @@ -337,7 +349,7 @@ impl ValidatedState {
validated_state.apply_upgrade(instance, version);

let chain_config = validated_state
.get_chain_config(instance, proposed_header.chain_config())
.get_chain_config(instance, &proposed_header.chain_config())
.await?;

if Some(chain_config) != validated_state.chain_config.resolve() {
Expand Down Expand Up @@ -627,7 +639,7 @@ impl HotShotState<SeqTypes> for ValidatedState {
Self {
fee_merkle_tree,
block_merkle_tree,
chain_config: *block_header.chain_config(),
chain_config: block_header.chain_config(),
}
}
/// Construct a genesis validated state.
Expand Down
8 changes: 4 additions & 4 deletions types/src/v0/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub use impls::{
pub use utils::*;
use vbs::version::StaticVersion;

// TODO can we expand this documentation to include not only what this code does but why we need it?

// This is the single source of truth for minor versions supported by this major version.
//
// It is written as a higher-level macro which takes a macro invocation as an argument and appends
Expand Down Expand Up @@ -69,7 +71,6 @@ reexport_unchanged_types!(
BlockMerkleCommitment,
BlockMerkleTree,
BuilderSignature,
ChainConfig,
ChainId,
Delta,
FeeAccount,
Expand All @@ -85,7 +86,6 @@ reexport_unchanged_types!(
L1Client,
L1Snapshot,
NamespaceId,
NodeState,
NsIndex,
NsIter,
NsPayload,
Expand All @@ -103,7 +103,6 @@ reexport_unchanged_types!(
NumTxsUnchecked,
Payload,
PayloadByteLen,
ResolvableChainConfig,
Transaction,
TxIndex,
TxIter,
Expand All @@ -114,7 +113,6 @@ reexport_unchanged_types!(
TxTableEntriesRange,
Upgrade,
UpgradeType,
ValidatedState,
BlockSize,
);

Expand All @@ -134,6 +132,7 @@ impl NodeType for SeqTypes {
type Membership = GeneralStaticCommittee<Self, PubKey>;
type BuilderSignatureKey = FeeAccount;
type Base = StaticVersion<0, 1>;
// TODO we could have comments describing the role of these types in upgrades/versioning
type Upgrade = StaticVersion<0, 2>;
const UPGRADE_HASH: [u8; 32] = [
1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
Expand All @@ -148,6 +147,7 @@ pub type PrivKey = <PubKey as SignatureKey>::PrivateKey;

pub type NetworkConfig = hotshot_orchestrator::config::NetworkConfig<PubKey>;

use self::impls::{NodeState, ValidatedState};
pub use crate::v0_1::{
BLOCK_MERKLE_TREE_HEIGHT, FEE_MERKLE_TREE_HEIGHT, NS_ID_BYTE_LEN, NS_OFFSET_BYTE_LEN,
NUM_NSS_BYTE_LEN, NUM_TXS_BYTE_LEN, TX_OFFSET_BYTE_LEN,
Expand Down
6 changes: 4 additions & 2 deletions types/src/v0/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ use hotshot_types::{
use serde::{de::DeserializeOwned, Serialize};

use crate::{
AccountQueryData, BackoffParams, BlockMerkleTree, ChainConfig, Event, FeeAccount,
FeeMerkleCommitment, Leaf, NetworkConfig, NodeState, SeqTypes, ValidatedState,
v0::impls::ValidatedState, v0_3::ChainConfig, AccountQueryData, BackoffParams, BlockMerkleTree,
Event, FeeAccount, FeeMerkleCommitment, Leaf, NetworkConfig, SeqTypes,
};

use super::impls::NodeState;

#[async_trait]
pub trait StateCatchup: Send + Sync + std::fmt::Debug {
/// Try to fetch the given account state, failing without retrying if unable.
Expand Down
12 changes: 12 additions & 0 deletions types/src/v0/v0_1/chain_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,15 @@ impl From<ChainConfig> for ResolvableChainConfig {
}
}
}

impl Default for ChainConfig {
fn default() -> Self {
Self {
chain_id: U256::from(35353).into(), // arbitrarily chosen chain ID
max_block_size: 10240.into(),
base_fee: 0.into(),
fee_contract: None,
fee_recipient: Default::default(),
}
}
}
Loading

0 comments on commit f1be763

Please sign in to comment.