diff --git a/execution_engine/src/runtime/mint_internal.rs b/execution_engine/src/runtime/mint_internal.rs index 5bf26e0aaf..d137b65109 100644 --- a/execution_engine/src/runtime/mint_internal.rs +++ b/execution_engine/src/runtime/mint_internal.rs @@ -64,7 +64,7 @@ where .read_addressable_entity_by_account_hash(account_hash) .map_err(|err| { error!(%err, "error reading addressable entity by account hash"); - ProviderError::AddressableEntityByAccountHash(account_hash) + ProviderError::AccountHash(account_hash) }) } diff --git a/execution_engine/src/runtime_context/mod.rs b/execution_engine/src/runtime_context/mod.rs index 96d4638256..8f92cd8f4e 100644 --- a/execution_engine/src/runtime_context/mod.rs +++ b/execution_engine/src/runtime_context/mod.rs @@ -1230,7 +1230,7 @@ where ) -> Result { self.tracking_copy .borrow_mut() - .get_legacy_contract(legacy_contract) + .get_contract(legacy_contract) .map_err(Into::into) } diff --git a/execution_engine_testing/test_support/src/wasm_test_builder.rs b/execution_engine_testing/test_support/src/wasm_test_builder.rs index 048481f36b..f5e3bb3e63 100644 --- a/execution_engine_testing/test_support/src/wasm_test_builder.rs +++ b/execution_engine_testing/test_support/src/wasm_test_builder.rs @@ -1922,7 +1922,7 @@ where let req = TrieRequest::new(state_hash, None); self.data_access_layer() .trie(req) - .into_legacy() + .into_raw() .unwrap() .map(|bytes| bytesrepr::deserialize(bytes.into_inner().into()).unwrap()) } diff --git a/node/src/components/binary_port.rs b/node/src/components/binary_port.rs index 519bf71db0..1040f093f6 100644 --- a/node/src/components/binary_port.rs +++ b/node/src/components/binary_port.rs @@ -394,7 +394,7 @@ where BinaryResponse::new_error(ErrorCode::FunctionDisabled, protocol_version) } else { let req = TrieRequest::new(trie_key, None); - match effect_builder.get_trie(req).await.into_legacy() { + match effect_builder.get_trie(req).await.into_raw() { Ok(result) => BinaryResponse::from_value( GetTrieFullResult::new(result.map(TrieRaw::into_inner)), protocol_version, diff --git a/node/src/components/contract_runtime.rs b/node/src/components/contract_runtime.rs index 97274180ba..a4a0859690 100644 --- a/node/src/components/contract_runtime.rs +++ b/node/src/components/contract_runtime.rs @@ -767,7 +767,7 @@ impl ContractRuntime { let req = TrieRequest::new(trie_key, Some(chunk_index)); let maybe_raw = data_access_layer .trie(req) - .into_legacy() + .into_raw() .map_err(ContractRuntimeError::FailedToRetrieveTrieById)?; let ret = match maybe_raw { Some(raw) => Some(TrieOrChunk::new(raw.into(), chunk_index)?), diff --git a/storage/src/block_store/block_provider.rs b/storage/src/block_store/block_provider.rs index 9625a8c216..d3290360c0 100644 --- a/storage/src/block_store/block_provider.rs +++ b/storage/src/block_store/block_provider.rs @@ -2,17 +2,22 @@ use super::error::BlockStoreError; /// A block store that supports read/write operations consistently. pub trait BlockStoreProvider { + /// Reader alias. type Reader<'a>: BlockStoreTransaction where Self: 'a; + /// ReaderWriter alias. type ReaderWriter<'a>: BlockStoreTransaction where Self: 'a; + /// Check out read only handle. fn checkout_ro(&self) -> Result, BlockStoreError>; + /// Check out read write handle. fn checkout_rw(&mut self) -> Result, BlockStoreError>; } +/// Block store transaction. pub trait BlockStoreTransaction { /// Commit changes to the block store. fn commit(self) -> Result<(), BlockStoreError>; @@ -21,12 +26,18 @@ pub trait BlockStoreTransaction { fn rollback(self); } +/// Data reader definition. pub trait DataReader { + /// Read item at key. fn read(&self, key: K) -> Result, BlockStoreError>; + /// Returns true if item exists at key, else false. fn exists(&self, key: K) -> Result; } +/// Data write definition. pub trait DataWriter { + /// Write item to store and return key. fn write(&mut self, data: &T) -> Result; + /// Delete item at key from store. fn delete(&mut self, key: K) -> Result<(), BlockStoreError>; } diff --git a/storage/src/block_store/error.rs b/storage/src/block_store/error.rs index 0e7ff4b330..976357e6d5 100644 --- a/storage/src/block_store/error.rs +++ b/storage/src/block_store/error.rs @@ -2,6 +2,7 @@ use casper_types::{BlockHash, EraId, TransactionHash}; use std::fmt::Debug; use thiserror::Error; +/// Block store error. #[derive(Debug, Error)] pub enum BlockStoreError { /// Found a duplicate block entry of the specified height. diff --git a/storage/src/block_store/lmdb/indexed_lmdb_block_store.rs b/storage/src/block_store/lmdb/indexed_lmdb_block_store.rs index dae84469dd..464e74b634 100644 --- a/storage/src/block_store/lmdb/indexed_lmdb_block_store.rs +++ b/storage/src/block_store/lmdb/indexed_lmdb_block_store.rs @@ -27,6 +27,7 @@ use casper_types::{ BlockSignatures, Digest, EraId, ProtocolVersion, Transaction, TransactionHash, Transfer, }; +/// Indexed lmdb block store. #[derive(DataSize, Debug)] pub struct IndexedLmdbBlockStore { /// Block store @@ -124,6 +125,7 @@ impl IndexedLmdbBlockStore { Ok(()) } + /// Ctor. pub fn new( block_store: LmdbBlockStore, hard_reset_to_start_of_era: Option, diff --git a/storage/src/block_store/lmdb/lmdb_block_store.rs b/storage/src/block_store/lmdb/lmdb_block_store.rs index baacf426e0..5abbb96e4f 100644 --- a/storage/src/block_store/lmdb/lmdb_block_store.rs +++ b/storage/src/block_store/lmdb/lmdb_block_store.rs @@ -51,6 +51,7 @@ const OS_FLAGS: EnvironmentFlags = EnvironmentFlags::WRITE_MAP; #[cfg(target_os = "macos")] const OS_FLAGS: EnvironmentFlags = EnvironmentFlags::empty(); +/// Lmdb block store. #[derive(DataSize, Debug)] pub struct LmdbBlockStore { /// Storage location. @@ -82,6 +83,7 @@ pub struct LmdbBlockStore { } impl LmdbBlockStore { + /// Ctor. pub fn new(root_path: &Path, total_size: usize) -> Result { // Create the environment and databases. let env = new_environment(total_size, root_path)?; @@ -127,6 +129,7 @@ impl LmdbBlockStore { }) } + /// Write finality signatures. pub fn write_finality_signatures( &self, txn: &mut RwTransaction, diff --git a/storage/src/block_store/mod.rs b/storage/src/block_store/mod.rs index 657f924aff..baa9ae7d50 100644 --- a/storage/src/block_store/mod.rs +++ b/storage/src/block_store/mod.rs @@ -1,6 +1,8 @@ mod block_provider; mod error; +/// Block store lmdb logic. pub mod lmdb; +/// Block store types. pub mod types; pub use block_provider::{BlockStoreProvider, BlockStoreTransaction, DataReader, DataWriter}; diff --git a/storage/src/block_store/types/approvals_hashes.rs b/storage/src/block_store/types/approvals_hashes.rs index ccbf0543a1..3398dfcf7f 100644 --- a/storage/src/block_store/types/approvals_hashes.rs +++ b/storage/src/block_store/types/approvals_hashes.rs @@ -39,6 +39,7 @@ pub struct ApprovalsHashes { } impl ApprovalsHashes { + /// Ctor. pub fn new( block_hash: BlockHash, approvals_hashes: Vec, @@ -51,6 +52,7 @@ impl ApprovalsHashes { } } + /// Verify block. pub fn verify(&self, block: &Block) -> Result<(), ApprovalsHashesValidationError> { if *self.merkle_proof_approvals.key() != Key::ChecksumRegistry { return Err(ApprovalsHashesValidationError::InvalidKeyType); @@ -92,6 +94,7 @@ impl ApprovalsHashes { Ok(()) } + /// Deploy ids. pub(crate) fn deploy_ids( &self, v1_block: &BlockV1, @@ -106,6 +109,7 @@ impl ApprovalsHashes { .collect()) } + /// Transaction ids. pub fn transaction_ids( &self, v2_block: &BlockV2, @@ -119,10 +123,12 @@ impl ApprovalsHashes { .collect() } + /// Block hash. pub fn block_hash(&self) -> &BlockHash { &self.block_hash } + /// Approvals hashes. pub fn approvals_hashes(&self) -> Vec { self.approvals_hashes.clone() } @@ -197,7 +203,9 @@ pub enum ApprovalsHashesValidationError { /// The state root hash implied by the Merkle proof doesn't match that in the block. #[error("state root hash implied by the Merkle proof doesn't match that in the block")] StateRootHashMismatch { + /// Proof state root hash. proof_state_root_hash: Digest, + /// Block state root hash. block_state_root_hash: Digest, }, @@ -212,10 +220,13 @@ pub enum ApprovalsHashesValidationError { /// The approvals checksum provided doesn't match one calculated from the approvals. #[error("provided approvals checksum doesn't match one calculated from the approvals")] ApprovalsChecksumMismatch { + /// Computed approvals checksum. computed_approvals_checksum: Digest, + /// Value in proof. value_in_proof: Digest, }, + /// Variant mismatch. #[error("mismatch in variants: {0:?}")] #[data_size(skip)] VariantMismatch(Box), diff --git a/storage/src/block_store/types/block_hash_height_and_era.rs b/storage/src/block_store/types/block_hash_height_and_era.rs index 10a9591c42..4ef2ab7f10 100644 --- a/storage/src/block_store/types/block_hash_height_and_era.rs +++ b/storage/src/block_store/types/block_hash_height_and_era.rs @@ -6,10 +6,14 @@ use rand::Rng; use casper_types::testing::TestRng; use casper_types::{BlockHash, BlockHashAndHeight, EraId}; +/// Aggregates block identifying information. #[derive(Clone, Copy, Debug, DataSize)] pub struct BlockHashHeightAndEra { + /// Block hash. pub block_hash: BlockHash, + /// Block height. pub block_height: u64, + /// EraId pub era_id: EraId, } diff --git a/storage/src/block_store/types/mod.rs b/storage/src/block_store/types/mod.rs index ceb012c4cb..96fbc90ab6 100644 --- a/storage/src/block_store/types/mod.rs +++ b/storage/src/block_store/types/mod.rs @@ -18,39 +18,62 @@ pub(crate) use approvals_hashes::LegacyApprovalsHashes; pub(crate) use deploy_metadata_v1::DeployMetadataV1; pub(in crate::block_store) use transfers::Transfers; +/// Exeuction results. pub type ExecutionResults = HashMap; +/// Transaction finalized approvals. pub struct TransactionFinalizedApprovals { + /// Transaction hash. pub transaction_hash: TransactionHash, + /// Finalized approvals. pub finalized_approvals: BTreeSet, } +/// Block execution results. pub struct BlockExecutionResults { + /// Block info. pub block_info: BlockHashHeightAndEra, + /// Execution results. pub exec_results: ExecutionResults, } +/// Block transfers. pub struct BlockTransfers { + /// Block hash. pub block_hash: BlockHash, + /// Transfers. pub transfers: Vec, } +/// State store. pub struct StateStore { + /// Key. pub key: Cow<'static, [u8]>, + /// Value. pub value: Vec, } +/// State store key. pub struct StateStoreKey(pub(super) Cow<'static, [u8]>); impl StateStoreKey { + /// Ctor. pub fn new(key: Cow<'static, [u8]>) -> Self { StateStoreKey(key) } } +/// Block tip anchor. pub struct Tip; + +/// Latest switch block anchor. pub struct LatestSwitchBlock; +/// Block height. pub type BlockHeight = u64; + +/// Switch block header alias. pub type SwitchBlockHeader = BlockHeader; + +/// Switch block alias. pub type SwitchBlock = Block; diff --git a/storage/src/data_access_layer.rs b/storage/src/data_access_layer.rs index 9d3e82eeed..21ae587b03 100644 --- a/storage/src/data_access_layer.rs +++ b/storage/src/data_access_layer.rs @@ -7,31 +7,44 @@ use casper_types::{execution::Effects, Digest, EraId}; use crate::tracking_copy::TrackingCopy; mod addressable_entity; +/// Auction provider. pub mod auction; +/// Balance provider. pub mod balance; mod balance_hold; +/// Bids provider. pub mod bids; mod block_global; +/// Block rewards provider. pub mod block_rewards; mod entry_points; +/// Era validators provider. pub mod era_validators; mod execution_results_checksum; mod fee; mod flush; +/// Forced undelegate provider. pub mod forced_undelegate; mod genesis; +/// Handle fee provider. pub mod handle_fee; mod handle_refund; mod key_prefix; +/// Mint provider. pub mod mint; +/// Prefixed values provider. pub mod prefixed_values; mod protocol_upgrade; +/// Prune provider. pub mod prune; +/// Query provider. pub mod query; mod round_seigniorage; mod seigniorage_recipients; +/// Step provider. pub mod step; mod system_entity_registry; +/// Tagged values provider. pub mod tagged_values; mod total_supply; mod trie; @@ -75,37 +88,47 @@ pub use system_entity_registry::{ pub use total_supply::{TotalSupplyRequest, TotalSupplyResult}; pub use trie::{PutTrieRequest, PutTrieResult, TrieElement, TrieRequest, TrieResult}; +/// Block placeholder. pub struct Block { _era_id: EraId, } +/// Block provider definition. pub trait BlockProvider { + /// Block provider error type. type Error; + /// Read block by height. fn read_block_by_height(&self, _height: usize) -> Result, Self::Error> { // TODO: We need to implement this todo!() } } +/// Anchor struct for block store functionality. #[derive(Default, Copy, Clone)] pub struct BlockStore(()); impl BlockStore { + /// Ctor. pub fn new() -> Self { BlockStore(()) } } -// We're currently putting it here, but in future it needs to move to its own crate. +/// Data access layer. #[derive(Copy, Clone)] pub struct DataAccessLayer { + /// Block store instance. pub block_store: BlockStore, + /// Memoized state. pub state: S, + /// Max query depth. pub max_query_depth: u64, } impl DataAccessLayer { + /// Returns reference to current state of the data access layer. pub fn state(&self) -> &S { &self.state } diff --git a/storage/src/data_access_layer/addressable_entity.rs b/storage/src/data_access_layer/addressable_entity.rs index 24147882f0..724251296c 100644 --- a/storage/src/data_access_layer/addressable_entity.rs +++ b/storage/src/data_access_layer/addressable_entity.rs @@ -37,6 +37,7 @@ pub enum AddressableEntityResult { /// An addressable entity. entity: AddressableEntity, }, + /// Failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/auction.rs b/storage/src/data_access_layer/auction.rs index 24818fa7bf..c947547d51 100644 --- a/storage/src/data_access_layer/auction.rs +++ b/storage/src/data_access_layer/auction.rs @@ -36,46 +36,77 @@ pub enum AuctionMethodError { }, } +/// Auction method to interact with. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AuctionMethod { + /// Activate bid. ActivateBid { + /// Validator public key (must match initiating address). validator: PublicKey, }, + /// Add bid. AddBid { + /// Validator public key (must match initiating address). public_key: PublicKey, + /// Delegation rate for this validator bid. delegation_rate: DelegationRate, + /// Bid amount. amount: U512, + /// Minimum delegation amount for this validator bid. minimum_delegation_amount: u64, + /// Maximum delegation amount for this validator bid. maximum_delegation_amount: u64, }, + /// Withdraw bid. WithdrawBid { + /// Validator public key. public_key: PublicKey, + /// Bid amount. amount: U512, }, + /// Delegate to validator. Delegate { + /// Delegator public key. delegator: PublicKey, + /// Validator public key. validator: PublicKey, + /// Delegation amount. amount: U512, + /// Max delegators per validator. max_delegators_per_validator: u32, }, + /// Undelegate from validator. Undelegate { + /// Delegator public key. delegator: PublicKey, + /// Validator public key. validator: PublicKey, + /// Undelegation amount. amount: U512, }, + /// Undelegate from validator and attempt delegation to new validator after unbonding delay + /// elapses. Redelegate { + /// Delegator public key. delegator: PublicKey, + /// Validator public key. validator: PublicKey, + /// Redelegation amount. amount: U512, + /// New validator public key. new_validator: PublicKey, }, + /// Change the public key associated with a validator to a different public key. ChangeBidPublicKey { + /// Current public key. public_key: PublicKey, + /// New public key. new_public_key: PublicKey, }, } impl AuctionMethod { + /// Form auction method from parts. pub fn from_parts( entry_point: TransactionEntryPoint, runtime_args: &RuntimeArgs, @@ -210,6 +241,7 @@ impl AuctionMethod { } } +/// Bidding request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BiddingRequest { /// The runtime config. @@ -251,48 +283,59 @@ impl BiddingRequest { } } + /// Returns the config. pub fn config(&self) -> &NativeRuntimeConfig { &self.config } + /// Returns the state hash. pub fn state_hash(&self) -> Digest { self.state_hash } + /// Returns the protocol version. pub fn protocol_version(&self) -> ProtocolVersion { self.protocol_version } + /// Returns the auction method. pub fn auction_method(&self) -> &AuctionMethod { &self.auction_method } + /// Returns the transaction hash. pub fn transaction_hash(&self) -> TransactionHash { self.transaction_hash } + /// Returns the initiator. pub fn initiator(&self) -> &InitiatorAddr { &self.initiator } + /// Returns the authorization keys. pub fn authorization_keys(&self) -> &BTreeSet { &self.authorization_keys } } +/// Auction method ret. #[derive(Debug, Clone)] pub enum AuctionMethodRet { + /// Unit. Unit, + /// Updated amount. UpdatedAmount(U512), } +/// Bidding result. #[derive(Debug)] pub enum BiddingResult { /// Invalid state root hash. RootNotFound, /// Bidding request succeeded Success { - // The ret value, if any. + /// The ret value, if any. ret: AuctionMethodRet, /// Effects of bidding interaction. effects: Effects, diff --git a/storage/src/data_access_layer/balance.rs b/storage/src/data_access_layer/balance.rs index 63c5041260..d0f99b20e0 100644 --- a/storage/src/data_access_layer/balance.rs +++ b/storage/src/data_access_layer/balance.rs @@ -48,18 +48,28 @@ pub enum ProofHandling { /// Represents a way to make a balance inquiry. #[derive(Debug, Clone, PartialEq, Eq)] pub enum BalanceIdentifier { + /// Use system refund purse (held by handle payment system contract). Refund, + /// Use system payment purse (held by handle payment system contract). Payment, + /// Use system accumulate purse (held by handle payment system contract). Accumulate, + /// Use purse associated to specified uref. Purse(URef), + /// Use main purse of entity derived from public key. Public(PublicKey), + /// Use main purse of entity from account hash. Account(AccountHash), + /// Use main purse of entity. Entity(EntityAddr), + /// Use purse at Key::Purse(URefAddr). Internal(URefAddr), + /// Penalized account identifier. PenalizedAccount(AccountHash), } impl BalanceIdentifier { + /// Returns underlying uref addr from balance identifier, if any. pub fn as_purse_addr(&self) -> Option { match self { BalanceIdentifier::Internal(addr) => Some(*addr), @@ -173,6 +183,7 @@ impl From for BalanceIdentifier { } } +/// Processing hold balance handling. #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub struct ProcessingHoldBalanceHandling {} @@ -204,6 +215,7 @@ impl From<(HoldBalanceHandling, u64)> for ProcessingHoldBalanceHandling { } } +/// Gas hold balance handling. #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub struct GasHoldBalanceHandling { handling: HoldBalanceHandling, @@ -389,6 +401,7 @@ impl BalanceRequest { } } +/// Available balance checker. pub trait AvailableBalanceChecker { /// Calculate and return available balance. fn available_balance( @@ -433,6 +446,7 @@ pub trait AvailableBalanceChecker { } } + /// Calculates amortization. fn amortization( &self, hold_kind: BalanceHoldAddrTag, @@ -559,12 +573,15 @@ impl AvailableBalanceChecker for BTreeMap { } } +/// Proofs result. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ProofsResult { + /// Not requested. NotRequested { /// Any time-relevant active holds on the balance, without proofs. balance_holds: BTreeMap, }, + /// Proofs. Proofs { /// A proof that the given value is present in the Merkle trie. total_balance_proof: Box>, @@ -645,6 +662,7 @@ impl ProofsResult { } } +/// Balance failure. #[derive(Debug, Clone)] pub enum BalanceFailure { /// Failed to calculate amortization (checked multiplication). @@ -688,6 +706,7 @@ pub enum BalanceResult { /// Proofs result. proofs_result: ProofsResult, }, + /// Failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/balance_hold.rs b/storage/src/data_access_layer/balance_hold.rs index f97e65d382..f25f6a6abe 100644 --- a/storage/src/data_access_layer/balance_hold.rs +++ b/storage/src/data_access_layer/balance_hold.rs @@ -11,10 +11,13 @@ use casper_types::{ use std::fmt::{Display, Formatter}; use thiserror::Error; +/// Balance hold kind. #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub enum BalanceHoldKind { + /// All balance holds. #[default] All, + /// Selection of a specific kind of balance. Tag(BalanceHoldAddrTag), } @@ -28,14 +31,21 @@ impl BalanceHoldKind { } } +/// Balance hold mode. #[derive(Debug, Clone, PartialEq, Eq)] pub enum BalanceHoldMode { + /// Balance hold request. Hold { + /// Balance identifier. identifier: BalanceIdentifier, + /// Hold amount. hold_amount: U512, + /// How should insufficient balance be handled. insufficient_handling: InsufficientBalanceHandling, }, + /// Clear balance holds. Clear { + /// Identifier of balance to be cleared of holds. identifier: BalanceIdentifier, }, } @@ -60,6 +70,7 @@ pub enum InsufficientBalanceHandling { Noop, } +/// Balance hold request. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct BalanceHoldRequest { state_hash: Digest, @@ -156,10 +167,18 @@ impl BalanceHoldRequest { #[derive(Error, Debug, Clone)] #[non_exhaustive] pub enum BalanceHoldError { + /// Tracking copy error. TrackingCopy(TrackingCopyError), + /// Balance error. Balance(BalanceFailure), - InsufficientBalance { remaining_balance: U512 }, + /// Insufficient balance error. + InsufficientBalance { + /// Remaining balance error. + remaining_balance: U512, + }, + /// Unexpected wildcard variant error. UnexpectedWildcardVariant, // programmer error, + /// Unexpected hold value error. UnexpectedHoldValue(StoredValue), } @@ -225,6 +244,7 @@ pub enum BalanceHoldResult { } impl BalanceHoldResult { + /// Success ctor. pub fn success( holds: Option>, total_balance: U512, @@ -317,6 +337,7 @@ impl BalanceHoldResult { } } + /// Error message. pub fn error_message(&self) -> String { match self { BalanceHoldResult::Success { hold, held, .. } => { diff --git a/storage/src/data_access_layer/bids.rs b/storage/src/data_access_layer/bids.rs index befeebd4ae..88b5da03f2 100644 --- a/storage/src/data_access_layer/bids.rs +++ b/storage/src/data_access_layer/bids.rs @@ -31,6 +31,7 @@ pub enum BidsResult { /// Current bids. bids: Vec, }, + /// Failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/block_global.rs b/storage/src/data_access_layer/block_global.rs index 0d2d754cd5..38b54160d1 100644 --- a/storage/src/data_access_layer/block_global.rs +++ b/storage/src/data_access_layer/block_global.rs @@ -3,9 +3,12 @@ use casper_types::{execution::Effects, BlockTime, Digest, ProtocolVersion}; use std::fmt::{Display, Formatter}; use thiserror::Error; +/// Block global kind. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum BlockGlobalKind { + /// Block time. BlockTime(BlockTime), + /// Message count. MessageCount(u64), } @@ -15,6 +18,7 @@ impl Default for BlockGlobalKind { } } +/// Block global request. #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] pub struct BlockGlobalRequest { state_hash: Digest, @@ -53,6 +57,7 @@ impl BlockGlobalRequest { } } +/// Block global result. #[derive(Error, Debug, Clone)] pub enum BlockGlobalResult { /// Returned if a passed state root hash is not found. diff --git a/storage/src/data_access_layer/block_rewards.rs b/storage/src/data_access_layer/block_rewards.rs index 3d0676de5a..e4c2d9fd5a 100644 --- a/storage/src/data_access_layer/block_rewards.rs +++ b/storage/src/data_access_layer/block_rewards.rs @@ -12,6 +12,7 @@ use crate::{ tracking_copy::TrackingCopyError, }; +/// Block rewards request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BlockRewardsRequest { config: Config, @@ -22,6 +23,7 @@ pub struct BlockRewardsRequest { } impl BlockRewardsRequest { + /// Ctor. pub fn new( config: Config, state_hash: Digest, @@ -64,24 +66,34 @@ impl BlockRewardsRequest { } } +/// Block rewards error. #[derive(Clone, Error, Debug)] pub enum BlockRewardsError { + /// Undistributed rewards error. #[error("Undistributed rewards")] UndistributedRewards, + /// Tracking copy error. #[error(transparent)] TrackingCopy(TrackingCopyError), + /// Registry entry not found error. #[error("Registry entry not found: {0}")] RegistryEntryNotFound(String), + /// Transfer error. #[error(transparent)] Transfer(TransferError), + /// Auction error. #[error("Auction error: {0}")] Auction(AuctionError), } +/// Block reward result. #[derive(Debug, Clone)] pub enum BlockRewardsResult { + /// Root not found in global state. RootNotFound, + /// Block rewards failure error. Failure(BlockRewardsError), + /// Success result. Success { /// State hash after distribution outcome is committed to the global state. post_state_hash: Digest, @@ -91,6 +103,7 @@ pub enum BlockRewardsResult { } impl BlockRewardsResult { + /// Returns true if successful, else false. pub fn is_success(&self) -> bool { matches!(self, BlockRewardsResult::Success { .. }) } diff --git a/storage/src/data_access_layer/entry_points.rs b/storage/src/data_access_layer/entry_points.rs index a0b28188cb..26b263523a 100644 --- a/storage/src/data_access_layer/entry_points.rs +++ b/storage/src/data_access_layer/entry_points.rs @@ -37,6 +37,7 @@ pub enum EntryPointsResult { /// An addressable entity. entry_point: EntryPointValue, }, + /// Failure result. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/execution_results_checksum.rs b/storage/src/data_access_layer/execution_results_checksum.rs index a206dd6099..cc4d77e510 100644 --- a/storage/src/data_access_layer/execution_results_checksum.rs +++ b/storage/src/data_access_layer/execution_results_checksum.rs @@ -1,6 +1,7 @@ use crate::tracking_copy::TrackingCopyError; use casper_types::Digest; +/// Execution results checksum literal. pub const EXECUTION_RESULTS_CHECKSUM_NAME: &str = "execution_results_checksum"; /// Represents a request to obtain current execution results checksum. diff --git a/storage/src/data_access_layer/fee.rs b/storage/src/data_access_layer/fee.rs index 5f8d9355f1..9b11da254a 100644 --- a/storage/src/data_access_layer/fee.rs +++ b/storage/src/data_access_layer/fee.rs @@ -12,6 +12,7 @@ use casper_types::{ use crate::tracking_copy::TrackingCopyError; +/// Fee request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FeeRequest { config: NativeRuntimeConfig, @@ -21,6 +22,7 @@ pub struct FeeRequest { } impl FeeRequest { + /// Ctor. pub fn new( config: NativeRuntimeConfig, state_hash: Digest, @@ -87,26 +89,37 @@ impl FeeRequest { } } +/// Fee error. #[derive(Clone, Error, Debug)] pub enum FeeError { + /// No fees distributed error. #[error("Undistributed fees")] NoFeesDistributed, + /// Tracking copy error. #[error(transparent)] TrackingCopy(TrackingCopyError), + /// Registry entry not found. #[error("Registry entry not found: {0}")] RegistryEntryNotFound(String), + /// Transfer error. #[error(transparent)] Transfer(TransferError), + /// Named keys not found. #[error("Named keys not found")] NamedKeysNotFound, + /// Administrative accounts not found. #[error("Administrative accounts not found")] AdministrativeAccountsNotFound, } +/// Fee result. #[derive(Debug, Clone)] pub enum FeeResult { + /// Root not found in global state. RootNotFound, + /// Failure result. Failure(FeeError), + /// Success result. Success { /// List of transfers that happened during execution. transfers: Vec, @@ -118,6 +131,7 @@ pub enum FeeResult { } impl FeeResult { + /// Returns true if successful, else false. pub fn is_success(&self) -> bool { matches!(self, FeeResult::Success { .. }) } diff --git a/storage/src/data_access_layer/flush.rs b/storage/src/data_access_layer/flush.rs index e28ab0582e..b3853b00f4 100644 --- a/storage/src/data_access_layer/flush.rs +++ b/storage/src/data_access_layer/flush.rs @@ -32,6 +32,7 @@ impl FlushResult { matches!(self, FlushResult::Success) } + /// Transforms flush result to global state error, if relevant. pub fn as_error(self) -> Result<(), GlobalStateError> { match self { FlushResult::ManualSyncDisabled | FlushResult::Success => Ok(()), diff --git a/storage/src/data_access_layer/forced_undelegate.rs b/storage/src/data_access_layer/forced_undelegate.rs index 70a562d1a2..5f05e1f668 100644 --- a/storage/src/data_access_layer/forced_undelegate.rs +++ b/storage/src/data_access_layer/forced_undelegate.rs @@ -8,6 +8,7 @@ use crate::{ tracking_copy::TrackingCopyError, }; +/// Forced undelegate request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ForcedUndelegateRequest { config: Config, @@ -17,6 +18,7 @@ pub struct ForcedUndelegateRequest { } impl ForcedUndelegateRequest { + /// Ctor. pub fn new( config: Config, state_hash: Digest, @@ -52,22 +54,31 @@ impl ForcedUndelegateRequest { } } +/// Forced undelegation error. #[derive(Clone, Error, Debug)] pub enum ForcedUndelegateError { + /// Tracking copy error. #[error(transparent)] TrackingCopy(TrackingCopyError), + /// Registry entry not found error. #[error("Registry entry not found: {0}")] RegistryEntryNotFound(String), + /// Transfer error. #[error(transparent)] Transfer(TransferError), + /// Auction error. #[error("Auction error: {0}")] Auction(AuctionError), } +/// Forced undelegation result. #[derive(Debug, Clone)] pub enum ForcedUndelegateResult { + /// Root hash not found in global state. RootNotFound, + /// Forced undelegation failed. Failure(ForcedUndelegateError), + /// Forced undelgation succeeded. Success { /// State hash after distribution outcome is committed to the global state. post_state_hash: Digest, @@ -77,6 +88,7 @@ pub enum ForcedUndelegateResult { } impl ForcedUndelegateResult { + /// Returns true if successful, else false. pub fn is_success(&self) -> bool { matches!(self, Self::Success { .. }) } diff --git a/storage/src/data_access_layer/genesis.rs b/storage/src/data_access_layer/genesis.rs index 7125c7d20f..b032c99a12 100644 --- a/storage/src/data_access_layer/genesis.rs +++ b/storage/src/data_access_layer/genesis.rs @@ -73,8 +73,11 @@ impl Distribution for Standard { /// Represents a result of a `genesis` request. #[derive(Debug, Clone)] pub enum GenesisResult { + /// Genesis fatal. Fatal(String), + /// Genesis failure. Failure(GenesisError), + /// Genesis success. Success { /// State hash after genesis is committed to the global state. post_state_hash: Digest, diff --git a/storage/src/data_access_layer/handle_fee.rs b/storage/src/data_access_layer/handle_fee.rs index 8b3853555d..b8fd5fad84 100644 --- a/storage/src/data_access_layer/handle_fee.rs +++ b/storage/src/data_access_layer/handle_fee.rs @@ -7,26 +7,40 @@ use casper_types::{ U512, }; +/// Handle fee mode. #[derive(Debug, Clone, PartialEq, Eq)] pub enum HandleFeeMode { + /// Pay the fee. Pay { + /// Initiator. initiator_addr: Box, + /// Source. source: Box, + /// Target. target: Box, + /// Amount. amount: U512, }, + /// Burn the fee. Burn { + /// Source. source: BalanceIdentifier, + /// Amount. amount: Option, }, + /// Validator credit (used in no fee mode). Credit { + /// Validator. validator: Box, + /// Amount. amount: U512, + /// EraId. era_id: EraId, }, } impl HandleFeeMode { + /// Ctor for Pay mode. pub fn pay( initiator_addr: Box, source: BalanceIdentifier, @@ -60,6 +74,7 @@ impl HandleFeeMode { } } +/// Handle fee request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HandleFeeRequest { /// The runtime config. @@ -93,22 +108,27 @@ impl HandleFeeRequest { } } + /// Returns config. pub fn config(&self) -> &NativeRuntimeConfig { &self.config } + /// Returns state hash. pub fn state_hash(&self) -> Digest { self.state_hash } + /// Returns handle protocol version. pub fn protocol_version(&self) -> ProtocolVersion { self.protocol_version } + /// Returns handle transaction hash. pub fn transaction_hash(&self) -> TransactionHash { self.transaction_hash } + /// Returns handle fee mode. pub fn handle_fee_mode(&self) -> &HandleFeeMode { &self.handle_fee_mode } @@ -120,7 +140,10 @@ pub enum HandleFeeResult { /// Invalid state root hash. RootNotFound, /// Handle request succeeded. - Success { effects: Effects }, + Success { + /// Handle fee effects. + effects: Effects, + }, /// Handle request failed. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/handle_refund.rs b/storage/src/data_access_layer/handle_refund.rs index ab7fb36038..9b022b70f2 100644 --- a/storage/src/data_access_layer/handle_refund.rs +++ b/storage/src/data_access_layer/handle_refund.rs @@ -7,43 +7,75 @@ use casper_types::{ }; use num_rational::Ratio; +/// Selects refund operation. #[derive(Debug, Clone, PartialEq, Eq)] pub enum HandleRefundMode { + /// Burn. Burn { + /// Refund limit. limit: U512, + /// Refund cost. cost: U512, + /// Refund consumed. consumed: U512, + /// Refund gas price. gas_price: u8, + /// Refund source. source: Box, + /// Refund ratio. ratio: Ratio, }, + /// Refund. Refund { + /// Refund initiator. initiator_addr: Box, + /// Refund limit. limit: U512, + /// Refund cost. cost: U512, + /// Refund consumed. consumed: U512, + /// Refund gas price. gas_price: u8, + /// Refund ratio. ratio: Ratio, + /// Refund source. source: Box, + /// Target for refund. target: Box, }, + /// Place a custom hold. CustomHold { + /// Refund initiator. initiator_addr: Box, + /// Refund limit. limit: U512, + /// Refund cost. cost: U512, + /// Refund gas price. gas_price: u8, }, + /// Refund amount. RefundAmount { + /// Refund limit. limit: U512, + /// Refund cost. cost: U512, + /// Refund consumed. consumed: U512, + /// Refund gas price. gas_price: u8, + /// Refund ratio. ratio: Ratio, + /// Refund source. source: Box, }, + /// Set refund purse. SetRefundPurse { + /// Target for refund. target: Box, }, + /// Clear refund purse. ClearRefundPurse, } @@ -61,6 +93,7 @@ impl HandleRefundMode { } } +/// Handle refund request. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HandleRefundRequest { /// The runtime config. @@ -93,34 +126,42 @@ impl HandleRefundRequest { } } + /// Returns a reference to the config. pub fn config(&self) -> &NativeRuntimeConfig { &self.config } + /// Returns the state hash. pub fn state_hash(&self) -> Digest { self.state_hash } + /// Returns the protocol version. pub fn protocol_version(&self) -> ProtocolVersion { self.protocol_version } + /// Returns the transaction hash. pub fn transaction_hash(&self) -> TransactionHash { self.transaction_hash } + /// Returns the refund mode. pub fn refund_mode(&self) -> &HandleRefundMode { &self.refund_mode } } +/// Handle refund result. #[derive(Debug)] pub enum HandleRefundResult { /// Invalid state root hash. RootNotFound, /// Handle refund request succeeded. Success { + /// The effects. effects: Effects, + /// The amount, if any. amount: Option, }, /// Invalid phase selected (programmer error). diff --git a/storage/src/data_access_layer/mint.rs b/storage/src/data_access_layer/mint.rs index 08710925b9..7680432796 100644 --- a/storage/src/data_access_layer/mint.rs +++ b/storage/src/data_access_layer/mint.rs @@ -11,7 +11,9 @@ use crate::system::transfer::{TransferArgs, TransferError}; /// Transfer details. #[derive(Debug, Clone, PartialEq, Eq)] pub enum TransferRequestArgs { + /// Provides opaque arguments in runtime format. Raw(RuntimeArgs), + /// Provides explicit structured args. Explicit(TransferArgs), } @@ -81,10 +83,12 @@ impl TransferRequest { } } + /// Returns a reference to the runtime config. pub fn config(&self) -> &NativeRuntimeConfig { &self.config } + /// Returns a reference to the transfer config. pub fn transfer_config(&self) -> &TransferConfig { self.config.transfer_config() } @@ -133,6 +137,7 @@ impl TransferRequest { } } +/// Transfer result. #[derive(Debug, Clone)] pub enum TransferResult { /// Invalid state root hash. @@ -157,6 +162,7 @@ impl TransferResult { } } + /// Returns transfers. pub fn transfers(&self) -> Vec { match self { TransferResult::RootNotFound | TransferResult::Failure(_) => vec![], @@ -164,6 +170,7 @@ impl TransferResult { } } + /// Returns transfer error, if any. pub fn error(&self) -> Option { if let Self::Failure(error) = self { Some(error.clone()) diff --git a/storage/src/data_access_layer/prefixed_values.rs b/storage/src/data_access_layer/prefixed_values.rs index 54e557f855..942af11fb0 100644 --- a/storage/src/data_access_layer/prefixed_values.rs +++ b/storage/src/data_access_layer/prefixed_values.rs @@ -41,5 +41,6 @@ pub enum PrefixedValuesResult { /// Current values. values: Vec, }, + /// Failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/round_seigniorage.rs b/storage/src/data_access_layer/round_seigniorage.rs index c19dd2d88b..77405d1235 100644 --- a/storage/src/data_access_layer/round_seigniorage.rs +++ b/storage/src/data_access_layer/round_seigniorage.rs @@ -43,5 +43,6 @@ pub enum RoundSeigniorageRateResult { /// The current rate. rate: Ratio, }, + /// Failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/step.rs b/storage/src/data_access_layer/step.rs index 44bc0a2877..860cde6809 100644 --- a/storage/src/data_access_layer/step.rs +++ b/storage/src/data_access_layer/step.rs @@ -114,10 +114,12 @@ impl StepRequest { } } + /// Returns the config. pub fn config(&self) -> &Config { &self.config } + /// Returns the transfer config. pub fn transfer_config(&self) -> TransferConfig { self.config.transfer_config().clone() } @@ -215,6 +217,7 @@ pub enum StepResult { } impl StepResult { + /// Returns if step is successful. pub fn is_success(&self) -> bool { matches!(self, StepResult::Success { .. }) } diff --git a/storage/src/data_access_layer/system_entity_registry.rs b/storage/src/data_access_layer/system_entity_registry.rs index d9d4623a9a..c1f1c67e8b 100644 --- a/storage/src/data_access_layer/system_entity_registry.rs +++ b/storage/src/data_access_layer/system_entity_registry.rs @@ -7,7 +7,9 @@ use casper_types::{ /// Used to specify is the requestor wants the registry itself or a named entry within it. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SystemEntityRegistrySelector { + /// Requests all system entity entries. All, + /// Requests system entity by name. ByName(String), } @@ -66,15 +68,17 @@ impl SystemEntityRegistryRequest { } } + /// Returns the state hash. pub fn state_hash(&self) -> Digest { self.state_hash } - /// The selector. + /// Returns the current selector. pub fn selector(&self) -> &SystemEntityRegistrySelector { &self.selector } + /// Protocol version. pub fn protocol_version(&self) -> ProtocolVersion { self.protocol_version } @@ -83,7 +87,9 @@ impl SystemEntityRegistryRequest { /// The payload of a successful request. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SystemEntityRegistryPayload { + /// All registry entries. All(SystemEntityRegistry), + /// Specific system entity registry entry. EntityKey(Key), } @@ -110,11 +116,13 @@ pub enum SystemEntityRegistryResult { } impl SystemEntityRegistryResult { + /// Is success. pub fn is_success(&self) -> bool { matches!(self, SystemEntityRegistryResult::Success { .. }) } - pub fn as_legacy(&self) -> Result { + /// As registry payload. + pub fn as_registry_payload(&self) -> Result { match self { SystemEntityRegistryResult::RootNotFound => Err("Root not found".to_string()), SystemEntityRegistryResult::SystemEntityRegistryNotFound => { diff --git a/storage/src/data_access_layer/tagged_values.rs b/storage/src/data_access_layer/tagged_values.rs index 12a91907b5..bf430bb8a5 100644 --- a/storage/src/data_access_layer/tagged_values.rs +++ b/storage/src/data_access_layer/tagged_values.rs @@ -2,9 +2,10 @@ use crate::tracking_copy::TrackingCopyError; use casper_types::{Digest, KeyTag, StoredValue}; +/// Tagged values selector. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum TaggedValuesSelection { - // All values under the specified key tag. + /// All values under the specified key tag. All(KeyTag), } @@ -54,5 +55,6 @@ pub enum TaggedValuesResult { /// Current values. values: Vec, }, + /// Tagged value failure. Failure(TrackingCopyError), } diff --git a/storage/src/data_access_layer/trie.rs b/storage/src/data_access_layer/trie.rs index 57330521f2..cfc09f645b 100644 --- a/storage/src/data_access_layer/trie.rs +++ b/storage/src/data_access_layer/trie.rs @@ -55,7 +55,8 @@ pub enum TrieResult { } impl TrieResult { - pub fn into_legacy(self) -> Result, GlobalStateError> { + /// Transform trie result to raw state. + pub fn into_raw(self) -> Result, GlobalStateError> { match self { TrieResult::ValueNotFound(_) => Ok(None), TrieResult::Success { element } => match element { @@ -83,6 +84,7 @@ impl PutTrieRequest { &self.raw } + /// Take raw trie value. pub fn take_raw(self) -> TrieRaw { self.raw } diff --git a/storage/src/global_state/state/mod.rs b/storage/src/global_state/state/mod.rs index 3123dc7e2b..7ac9257df4 100644 --- a/storage/src/global_state/state/mod.rs +++ b/storage/src/global_state/state/mod.rs @@ -127,13 +127,17 @@ pub enum CommitError { TrieNotFoundInCache(Digest), } +/// Scratch provider. pub trait ScratchProvider: CommitProvider { + /// Get scratch state to db. fn get_scratch_global_state(&self) -> ScratchGlobalState; + /// Write scratch state to db. fn write_scratch_to_db( &self, state_root_hash: Digest, scratch_global_state: ScratchGlobalState, ) -> Result; + /// Prune items for imputed keys. fn prune_keys(&self, state_root_hash: Digest, keys: &[Key]) -> TriePruneResult; } @@ -147,6 +151,7 @@ pub trait CommitProvider: StateProvider { effects: Effects, ) -> Result; + /// Commit values to global state. fn commit_values( &self, state_hash: Digest, @@ -602,6 +607,7 @@ pub trait CommitProvider: StateProvider { } } + /// Gets block global data. fn block_global(&self, request: BlockGlobalRequest) -> BlockGlobalResult { let state_hash = request.state_hash(); let tc = match self.tracking_copy(state_hash) { diff --git a/storage/src/global_state/trie/mod.rs b/storage/src/global_state/trie/mod.rs index 4593aacce2..bf1d5f50c3 100644 --- a/storage/src/global_state/trie/mod.rs +++ b/storage/src/global_state/trie/mod.rs @@ -376,6 +376,7 @@ impl Trie { } } + /// Tag type for current trie element. pub fn tag_type(&self) -> String { match self { Trie::Leaf { .. } => "Leaf".to_string(), diff --git a/storage/src/global_state/trie_store/mod.rs b/storage/src/global_state/trie_store/mod.rs index e6e7eff507..286daa997a 100644 --- a/storage/src/global_state/trie_store/mod.rs +++ b/storage/src/global_state/trie_store/mod.rs @@ -2,6 +2,7 @@ //! //! See the [lmdb](lmdb/index.html#usage) modules for usage examples. pub mod lmdb; +/// Trie store operational logic. pub mod operations; // An in-mem cache backed up by a store that is used to optimize batch writes. diff --git a/storage/src/global_state/trie_store/operations/mod.rs b/storage/src/global_state/trie_store/operations/mod.rs index 102dc3398a..aa374cb832 100644 --- a/storage/src/global_state/trie_store/operations/mod.rs +++ b/storage/src/global_state/trie_store/operations/mod.rs @@ -27,11 +27,15 @@ use self::store_wrappers::NonDeserializingStore; use super::{cache::TrieCache, TrieStoreCacheError}; +/// Result of attemptint to read a record from the trie store. #[allow(clippy::enum_variant_names)] #[derive(Debug, PartialEq, Eq)] pub enum ReadResult { + /// Requested item found in trie store. Found(V), + /// Requested item not found in trie store. NotFound, + /// Root hash not found in trie store. RootNotFound, } @@ -403,11 +407,16 @@ where } } +/// Result of attempting to prune an item from the trie store. #[derive(Debug, PartialEq, Eq)] pub enum TriePruneResult { + /// Successfully pruned item from trie store. Pruned(Digest), + /// Requested key not found in trie store. MissingKey, + /// Root hash not found in trie store. RootNotFound, + /// Prune failure. Failure(GlobalStateError), } @@ -852,13 +861,18 @@ where }) } +/// Result of attemptint to write to trie store. #[derive(Debug, PartialEq, Eq)] pub enum WriteResult { + /// Record written to trie store. Written(Digest), + /// Record already exists in trie store. AlreadyExists, + /// Requested global state root hash does not exist in trie store. RootNotFound, } +/// Write to trie store. pub fn write( txn: &mut T, store: &S, @@ -952,6 +966,7 @@ where } } +/// Batch write to trie store. pub fn batch_write( txn: &mut T, store: &S, @@ -1006,6 +1021,7 @@ struct VisitedTrieNode { path: Vec, } +/// Iterator for trie store keys. pub struct KeysIterator<'a, 'b, K, V, T, S: TrieStore> { initial_descend: VecDeque, visited: Vec, diff --git a/storage/src/lib.rs b/storage/src/lib.rs index daa1c011ac..6e67e41a27 100644 --- a/storage/src/lib.rs +++ b/storage/src/lib.rs @@ -6,12 +6,19 @@ html_logo_url = "https://raw.githubusercontent.com/CasperLabs/casper-node/master/images/CasperLabs_Logo_Symbol_RGB.png" )] #![cfg_attr(docsrs, feature(doc_auto_cfg))] +#![warn(missing_docs)] +/// Address generator logic. pub mod address_generator; +/// Block store logic. pub mod block_store; +/// Data access layer logic. pub mod data_access_layer; +/// Global state logic. pub mod global_state; +/// Storage layer logic. pub mod system; +/// Tracking copy. pub mod tracking_copy; pub use address_generator::{AddressGenerator, AddressGeneratorBuilder}; diff --git a/storage/src/system.rs b/storage/src/system.rs index 697858bf86..246f0643cd 100644 --- a/storage/src/system.rs +++ b/storage/src/system.rs @@ -1,9 +1,18 @@ +/// Auction logic. pub mod auction; +/// Error definition. pub mod error; +/// Genesis logic. pub mod genesis; +/// Handle payment logic. pub mod handle_payment; +/// Mint logic. pub mod mint; +/// Protocol upgrade logic. pub mod protocol_upgrade; +/// Runtime native logic. pub mod runtime_native; +/// Standard payment logic. pub mod standard_payment; +/// Transfer logic. pub mod transfer; diff --git a/storage/src/system/auction.rs b/storage/src/system/auction.rs index 0461bd9d0d..df2a9ab440 100644 --- a/storage/src/system/auction.rs +++ b/storage/src/system/auction.rs @@ -1,5 +1,7 @@ mod auction_native; +/// Auction business logic. pub mod detail; +/// System logic providers. pub mod providers; use std::collections::BTreeMap; @@ -1027,6 +1029,7 @@ fn rewards_per_validator( Ok(results) } +/// Aggregated rewards data for a validator. #[derive(Debug, Default)] pub struct RewardsPerValidator { validator_reward: U512, diff --git a/storage/src/system/auction/detail.rs b/storage/src/system/auction/detail.rs index 4a01ccde42..a4978fce74 100644 --- a/storage/src/system/auction/detail.rs +++ b/storage/src/system/auction/detail.rs @@ -51,6 +51,7 @@ where provider.write(uref, value) } +/// Aggregated bid data for a Validator. #[derive(Debug, Default)] pub struct ValidatorBidsDetail { validator_bids: ValidatorBids, @@ -59,6 +60,7 @@ pub struct ValidatorBidsDetail { } impl ValidatorBidsDetail { + /// Ctor. pub fn new() -> Self { ValidatorBidsDetail { validator_bids: BTreeMap::new(), @@ -210,6 +212,7 @@ pub fn prune_validator_credits

( } } +/// Returns the imputed validator bids. pub fn get_validator_bids

(provider: &mut P, era_id: EraId) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -238,6 +241,7 @@ where Ok(ret) } +/// Sets the imputed validator bids. pub fn set_validator_bids

(provider: &mut P, validators: ValidatorBids) -> Result<(), Error> where P: StorageProvider + RuntimeProvider + ?Sized, @@ -249,6 +253,7 @@ where Ok(()) } +/// Returns the unbonding purses. pub fn get_unbonding_purses

(provider: &mut P) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -269,6 +274,7 @@ where Ok(ret) } +/// Sets the unbonding purses. pub fn set_unbonding_purses

( provider: &mut P, unbonding_purses: UnbondingPurses, @@ -282,6 +288,7 @@ where Ok(()) } +/// Returns the era id. pub fn get_era_id

(provider: &mut P) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -289,6 +296,7 @@ where read_from(provider, ERA_ID_KEY) } +/// Sets the era id. pub fn set_era_id

(provider: &mut P, era_id: EraId) -> Result<(), Error> where P: StorageProvider + RuntimeProvider + ?Sized, @@ -296,6 +304,7 @@ where write_to(provider, ERA_ID_KEY, era_id) } +/// Returns the era end timestamp. pub fn get_era_end_timestamp_millis

(provider: &mut P) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -303,6 +312,7 @@ where read_from(provider, ERA_END_TIMESTAMP_MILLIS_KEY) } +/// Sets the era end timestamp. pub fn set_era_end_timestamp_millis

( provider: &mut P, era_end_timestamp_millis: u64, @@ -317,6 +327,7 @@ where ) } +/// Returns seigniorage recipients snapshot. pub fn get_seigniorage_recipients_snapshot

( provider: &mut P, ) -> Result @@ -326,6 +337,7 @@ where read_from(provider, SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY) } +/// Set seigniorage recipients snapshot. pub fn set_seigniorage_recipients_snapshot

( provider: &mut P, snapshot: SeigniorageRecipientsSnapshot, @@ -336,6 +348,7 @@ where write_to(provider, SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY, snapshot) } +/// Returns the number of validator slots. pub fn get_validator_slots

(provider: &mut P) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -353,6 +366,7 @@ where Ok(validator_slots) } +/// Returns auction delay. pub fn get_auction_delay

(provider: &mut P) -> Result where P: StorageProvider + RuntimeProvider + ?Sized, @@ -782,6 +796,7 @@ where Ok(updated_amount) } +/// Returns validator bid by key. pub fn read_validator_bid

(provider: &mut P, bid_key: &Key) -> Result, Error> where P: StorageProvider + ?Sized, @@ -826,6 +841,7 @@ where Err(Error::ValidatorNotFound) } +/// Returns all delegator bids for imputed validator. pub fn read_delegator_bids

( provider: &mut P, validator_public_key: &PublicKey, @@ -848,6 +864,7 @@ where Ok(ret) } +/// Returns delegator bid by key. pub fn read_delegator_bid

(provider: &mut P, bid_key: &Key) -> Result, Error> where P: RuntimeProvider + ?Sized + StorageProvider, @@ -862,6 +879,7 @@ where } } +/// Applies seigniorage recipient changes. pub fn seigniorage_recipients( validator_weights: &ValidatorWeights, validator_bids: &ValidatorBids, @@ -972,6 +990,7 @@ where } } +/// Returns all delegators for imputed validator. pub fn delegators

( provider: &mut P, validator_public_key: &PublicKey, diff --git a/storage/src/system/error.rs b/storage/src/system/error.rs index 8fc7058bf0..cfb8c1914e 100644 --- a/storage/src/system/error.rs +++ b/storage/src/system/error.rs @@ -3,6 +3,8 @@ use casper_types::account::AccountHash; /// Implementation level errors for system contract providers #[derive(Debug)] pub enum ProviderError { + /// System contract registry. SystemEntityRegistry, - AddressableEntityByAccountHash(AccountHash), + /// Account hash. + AccountHash(AccountHash), } diff --git a/storage/src/system/genesis.rs b/storage/src/system/genesis.rs index a181b5bbc9..81ad4c368c 100644 --- a/storage/src/system/genesis.rs +++ b/storage/src/system/genesis.rs @@ -135,6 +135,7 @@ impl fmt::Display for GenesisError { } } +/// State for genesis installer. pub struct GenesisInstaller where S: StateProvider + ?Sized, @@ -149,6 +150,7 @@ impl GenesisInstaller where S: StateProvider + ?Sized, { + /// Ctor. pub fn new( genesis_config_hash: Digest, protocol_version: ProtocolVersion, @@ -171,6 +173,7 @@ where } } + /// Finalize genesis. pub fn finalize(self) -> Effects { self.tracking_copy.borrow().effects() } @@ -605,6 +608,7 @@ where Ok(contract_hash) } + /// Create genesis accounts. pub fn create_accounts(&self, total_supply_key: Key) -> Result<(), Box> { let accounts = { let mut ret: Vec = self.config.accounts_iter().cloned().collect(); diff --git a/storage/src/system/handle_payment.rs b/storage/src/system/handle_payment.rs index b9854da1ed..a093e18b6e 100644 --- a/storage/src/system/handle_payment.rs +++ b/storage/src/system/handle_payment.rs @@ -1,7 +1,10 @@ mod handle_payment_native; mod internal; +/// Provides mint logic for handle payment processing. pub mod mint_provider; +/// Provides runtime logic for handle payment processing. pub mod runtime_provider; +/// Provides storage logic for handle payment processing. pub mod storage_provider; use casper_types::{ diff --git a/storage/src/system/mint.rs b/storage/src/system/mint.rs index bbcd0b48b4..539da23b29 100644 --- a/storage/src/system/mint.rs +++ b/storage/src/system/mint.rs @@ -1,7 +1,11 @@ pub(crate) mod detail; +/// Provides native mint processing. mod mint_native; +/// Provides runtime logic for mint processing. pub mod runtime_provider; +/// Provides storage logic for mint processing. pub mod storage_provider; +/// Provides system logic for mint processing. pub mod system_provider; use num_rational::Ratio; diff --git a/storage/src/system/mint/mint_native.rs b/storage/src/system/mint/mint_native.rs index d2801ec1a6..44d15a2f26 100644 --- a/storage/src/system/mint/mint_native.rs +++ b/storage/src/system/mint/mint_native.rs @@ -61,7 +61,7 @@ where Ok((_, entity)) => Ok(Some(entity)), Err(tce) => { error!(%tce, "error reading addressable entity by account hash"); - Err(ProviderError::AddressableEntityByAccountHash(account_hash)) + Err(ProviderError::AccountHash(account_hash)) } } } diff --git a/storage/src/system/mint/runtime_provider.rs b/storage/src/system/mint/runtime_provider.rs index fbebcfa1a3..19e24b18cf 100644 --- a/storage/src/system/mint/runtime_provider.rs +++ b/storage/src/system/mint/runtime_provider.rs @@ -12,11 +12,13 @@ pub trait RuntimeProvider { /// This method should return the immediate caller of the current context. fn get_immediate_caller(&self) -> Option; + /// Is the caller standard payment logic? fn is_called_from_standard_payment(&self) -> bool; /// Get system entity registry. fn get_system_entity_registry(&self) -> Result; + /// Read addressable entity by account hash. fn read_addressable_entity_by_account_hash( &mut self, account_hash: AccountHash, diff --git a/storage/src/system/protocol_upgrade.rs b/storage/src/system/protocol_upgrade.rs index 7f28840fe9..3cae245272 100644 --- a/storage/src/system/protocol_upgrade.rs +++ b/storage/src/system/protocol_upgrade.rs @@ -168,6 +168,7 @@ where } } + /// Apply a protocol upgrade. pub fn upgrade( mut self, pre_state_hash: Digest, @@ -492,6 +493,7 @@ where )) } + /// Migrate the system account to addressable entity if necessary. pub fn migrate_system_account( &mut self, pre_state_hash: Digest, @@ -759,6 +761,7 @@ where Ok(()) } + /// Applies the necessary changes if a new auction delay is part of the upgrade. pub fn handle_new_auction_delay( &mut self, auction: AddressableEntityHash, @@ -781,6 +784,7 @@ where Ok(()) } + /// Applies the necessary changes if a new locked funds period is part of the upgrade. pub fn handle_new_locked_funds_period_millis( &mut self, auction: AddressableEntityHash, @@ -803,6 +807,7 @@ where Ok(()) } + /// Applies the necessary changes if a new unbonding delay is part of the upgrade. pub fn handle_new_unbonding_delay( &mut self, auction: AddressableEntityHash, @@ -827,6 +832,7 @@ where Ok(()) } + /// Applies the necessary changes if a new round seigniorage rate is part of the upgrade. pub fn handle_new_round_seigniorage_rate( &mut self, mint: AddressableEntityHash, diff --git a/storage/src/system/runtime_native.rs b/storage/src/system/runtime_native.rs index 0aeeb92a6e..8f04d8bfb8 100644 --- a/storage/src/system/runtime_native.rs +++ b/storage/src/system/runtime_native.rs @@ -12,6 +12,7 @@ use num_rational::Ratio; use std::{cell::RefCell, collections::BTreeSet, rc::Rc}; use tracing::error; +/// Configuration settings. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Config { transfer_config: TransferConfig, @@ -28,6 +29,7 @@ pub struct Config { } impl Config { + /// Ctor. #[allow(clippy::too_many_arguments)] pub const fn new( transfer_config: TransferConfig, @@ -57,6 +59,7 @@ impl Config { } } + /// Ctor from chainspec. pub fn from_chainspec(chainspec: &Chainspec) -> Self { let transfer_config = TransferConfig::from_chainspec(chainspec); let fee_handling = chainspec.core_config.fee_handling; @@ -87,50 +90,62 @@ impl Config { ) } + /// Returns transfer config. pub fn transfer_config(&self) -> &TransferConfig { &self.transfer_config } + /// Returns fee handling setting. pub fn fee_handling(&self) -> &FeeHandling { &self.fee_handling } + /// Returns refund handling setting. pub fn refund_handling(&self) -> &RefundHandling { &self.refund_handling } + /// Returns vesting schedule period millis setting. pub fn vesting_schedule_period_millis(&self) -> u64 { self.vesting_schedule_period_millis } + /// Returns if auction bids are allowed. pub fn allow_auction_bids(&self) -> bool { self.allow_auction_bids } + /// Returns if rewards should be computed. pub fn compute_rewards(&self) -> bool { self.compute_rewards } + /// Returns max delegators per validator setting. pub fn max_delegators_per_validator(&self) -> u32 { self.max_delegators_per_validator } + /// Returns minimum delegation amount setting. pub fn minimum_delegation_amount(&self) -> u64 { self.minimum_delegation_amount } + /// Returns balance hold interval setting. pub fn balance_hold_interval(&self) -> u64 { self.balance_hold_interval } + /// Returns include credit setting. pub fn include_credits(&self) -> bool { self.include_credits } + /// Returns validator credit cap setting. pub fn credit_cap(&self) -> Ratio { self.credit_cap } + /// Changes the transfer config. pub fn set_transfer_config(self, transfer_config: TransferConfig) -> Self { Config { transfer_config, @@ -148,12 +163,20 @@ impl Config { } } +/// Configuration for transfer. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum TransferConfig { + /// Transfers are affected by the existence of administrative_accounts. This is a + /// behavior specific to private or managed chains, not a public chain. Administered { + /// Retrusn the set of account hashes for all administrators. administrative_accounts: BTreeSet, + /// If true, transfers are unrestricted. + /// If false, the source and / or target of a transfer must be an administrative account. allow_unrestricted_transfers: bool, }, + /// Transfers are not affected by the existence of administrative_accounts (the standard + /// behavior). #[default] Unadministered, } @@ -232,12 +255,16 @@ impl TransferConfig { } } +/// Id for runtime processing. pub enum Id { + /// Hash of current transaction. Transaction(TransactionHash), + /// An arbitrary set of bytes to be used as a seed value. Seed(Vec), } impl Id { + /// Ctor for id enum. pub fn seed(&self) -> Vec { match self { Id::Transaction(hash) => hash.digest().into_vec(), @@ -246,6 +273,7 @@ impl Id { } } +/// State held by an instance of runtime native. pub struct RuntimeNative { config: Config, id: Id, @@ -268,6 +296,7 @@ impl RuntimeNative where S: StateReader, { + /// Ctor. #[allow(clippy::too_many_arguments)] pub fn new( config: Config, @@ -388,102 +417,127 @@ where }) } + /// Returns mutable reference to address generator. pub fn address_generator(&mut self) -> &mut AddressGenerator { &mut self.address_generator } + /// Returns reference to config. pub fn config(&self) -> &Config { &self.config } + /// Returns reference to transfer config. pub fn transfer_config(&self) -> &TransferConfig { &self.config.transfer_config } + /// Returns protocol version. pub fn protocol_version(&self) -> ProtocolVersion { self.protocol_version } + /// Returns handle to tracking copy. pub fn tracking_copy(&self) -> Rc>> { Rc::clone(&self.tracking_copy) } + /// Returns account hash being used by this instance. pub fn address(&self) -> AccountHash { self.address } + /// Changes the account hash being used by this instance. pub fn with_address(&mut self, account_hash: AccountHash) { self.address = account_hash; } + /// Returns the entity key being used by this instance. pub fn entity_key(&self) -> &Key { &self.entity_key } + /// Returns the addressable entity being used by this instance. pub fn addressable_entity(&self) -> &AddressableEntity { &self.addressable_entity } + /// Changes the addressable entity being used by this instance. pub fn with_addressable_entity(&mut self, entity: AddressableEntity) { self.addressable_entity = entity; } + /// Returns a reference to the named keys being used by this instance. pub fn named_keys(&self) -> &NamedKeys { &self.named_keys } + /// Returns a mutable reference to the named keys being used by this instance. pub fn named_keys_mut(&mut self) -> &mut NamedKeys { &mut self.named_keys } + /// Returns a reference to the access rights being used by this instance. pub fn access_rights(&self) -> &ContextAccessRights { &self.access_rights } + /// Returns a mutable reference to the access rights being used by this instance. pub fn access_rights_mut(&mut self) -> &mut ContextAccessRights { &mut self.access_rights } + /// Extends the access rights being used by this instance. pub fn extend_access_rights(&mut self, urefs: &[URef]) { self.access_rights.extend(urefs) } + /// Returns the remaining spending limit. pub fn remaining_spending_limit(&self) -> U512 { self.remaining_spending_limit } + /// Set remaining spending limit. pub fn set_remaining_spending_limit(&mut self, remaining: U512) { self.remaining_spending_limit = remaining; } + /// Get references to transfers. pub fn transfers(&self) -> &Vec { &self.transfers } + /// Push transfer instance. pub fn push_transfer(&mut self, transfer: Transfer) { self.transfers.push(transfer); } + /// Get id. pub fn id(&self) -> &Id { &self.id } + /// Get phase. pub fn phase(&self) -> Phase { self.phase } + /// Vesting schedule period in milliseconds. pub fn vesting_schedule_period_millis(&self) -> u64 { self.config.vesting_schedule_period_millis } + /// Are auction bids allowed? pub fn allow_auction_bids(&self) -> bool { self.config.allow_auction_bids } + /// Are rewards computed? pub fn compute_rewards(&self) -> bool { self.config.compute_rewards } + /// Extracts transfer items. pub fn into_transfers(self) -> Vec { self.transfers } diff --git a/storage/src/system/transfer.rs b/storage/src/system/transfer.rs index b5992a38ae..809b42cc13 100644 --- a/storage/src/system/transfer.rs +++ b/storage/src/system/transfer.rs @@ -15,6 +15,7 @@ use crate::{ tracking_copy::{TrackingCopy, TrackingCopyEntityExt, TrackingCopyError, TrackingCopyExt}, }; +/// Transfer error. #[derive(Clone, Error, Debug)] pub enum TransferError { /// Invalid key variant. diff --git a/storage/src/tracking_copy/ext.rs b/storage/src/tracking_copy/ext.rs index 21bcc66712..243dcf59de 100644 --- a/storage/src/tracking_copy/ext.rs +++ b/storage/src/tracking_copy/ext.rs @@ -104,10 +104,9 @@ pub trait TrackingCopyExt { /// Gets a package by hash. fn get_package(&mut self, package_hash: PackageHash) -> Result; - fn get_legacy_contract( - &mut self, - legacy_contract: ContractHash, - ) -> Result; + + /// Get a Contract record. + fn get_contract(&mut self, contract_hash: ContractHash) -> Result; /// Gets the system entity registry. fn get_system_entity_registry(&self) -> Result; @@ -652,13 +651,10 @@ where } } - fn get_legacy_contract( - &mut self, - legacy_contract: ContractHash, - ) -> Result { - let key = Key::Hash(legacy_contract.value()); + fn get_contract(&mut self, contract_hash: ContractHash) -> Result { + let key = Key::Hash(contract_hash.value()); match self.read(&key)? { - Some(StoredValue::Contract(legacy_contract)) => Ok(legacy_contract), + Some(StoredValue::Contract(contract)) => Ok(contract), Some(other) => Err(Self::Error::TypeMismatch(StoredValueTypeMismatch::new( "Contract".to_string(), other.type_name(), diff --git a/storage/src/tracking_copy/ext_entity.rs b/storage/src/tracking_copy/ext_entity.rs index 1aceaa1115..2f560259ac 100644 --- a/storage/src/tracking_copy/ext_entity.rs +++ b/storage/src/tracking_copy/ext_entity.rs @@ -25,9 +25,13 @@ use crate::{ /// Fees purse handling. #[derive(Debug, Clone, PartialEq, Eq)] pub enum FeesPurseHandling { + /// Transfer fees to proposer. ToProposer(AccountHash), + /// Transfer all fees to a system-wide accumulation purse, for future disbursement. Accumulate, + /// Burn all fees. Burn, + /// No fees are charged. None(URef), } @@ -76,6 +80,8 @@ pub trait TrackingCopyEntityExt { entity_addr: EntityAddr, named_keys: NamedKeys, ) -> Result<(), Self::Error>; + + /// Migrate entry points from Contract to top level entries. fn migrate_entry_points( &mut self, entity_addr: EntityAddr, @@ -92,12 +98,14 @@ pub trait TrackingCopyEntityExt { stored_value: StoredValue, ) -> Result<(), Self::Error>; + /// Migrate Account to AddressableEntity. fn migrate_account( &mut self, account_hash: AccountHash, protocol_version: ProtocolVersion, ) -> Result<(), Self::Error>; + /// Create an addressable entity to receive transfer to a non-existent addressable entity. fn create_new_addressable_entity_on_transfer( &mut self, account_hash: AccountHash, @@ -105,11 +113,14 @@ pub trait TrackingCopyEntityExt { protocol_version: ProtocolVersion, ) -> Result<(), Self::Error>; + /// Create an addressable entity instance using the field data of an account instance. fn create_addressable_entity_from_account( &mut self, account: Account, protocol_version: ProtocolVersion, ) -> Result<(), Self::Error>; + + /// Migrate ContractPackage to Package. fn migrate_package( &mut self, legacy_package_key: Key, diff --git a/storage/src/tracking_copy/mod.rs b/storage/src/tracking_copy/mod.rs index dd90f8c83d..3a35cf0488 100644 --- a/storage/src/tracking_copy/mod.rs +++ b/storage/src/tracking_copy/mod.rs @@ -239,6 +239,7 @@ impl> TrackingCopyCache { self.reads_cached.get_refresh(key).map(|v| &*v) } + /// Get cached items by prefix. fn get_muts_cached_by_byte_prefix(&self, prefix: &[u8]) -> Vec { self.muts_cached .range(prefix.to_vec()..) @@ -247,6 +248,7 @@ impl> TrackingCopyCache { .collect() } + /// Does the prune cache contain key. pub fn is_pruned(&self, key: &Key) -> bool { self.prunes_cached.contains(key) } @@ -390,6 +392,7 @@ where self.effects.clone() } + /// Destructure cached entries. pub fn destructure(self) -> (Vec<(Key, StoredValue)>, BTreeSet, Effects) { let (writes, prunes) = self.cache.into_muts(); let writes: Vec<(Key, StoredValue)> = writes.into_iter().map(|(k, v)| (k.0, v)).collect(); @@ -397,6 +400,7 @@ where (writes, prunes, self.effects) } + /// Get record by key. pub fn get(&mut self, key: &Key) -> Result, TrackingCopyError> { if let Some(value) = self.cache.get(key) { return Ok(Some(value.to_owned())); @@ -419,6 +423,7 @@ where self.get_by_byte_prefix(&[*key_tag as u8]) } + /// Get keys by prefix. pub fn get_keys_by_prefix( &self, key_prefix: &KeyPrefix, diff --git a/utils/global-state-update-gen/src/system_entity_registry.rs b/utils/global-state-update-gen/src/system_entity_registry.rs index 12c0723280..40b8facc73 100644 --- a/utils/global-state-update-gen/src/system_entity_registry.rs +++ b/utils/global-state-update-gen/src/system_entity_registry.rs @@ -128,7 +128,7 @@ fn generate_system_entity_registry_using_global_state(data_dir: &Path, state_has let registry = match builder .data_access_layer() .system_entity_registry(registry_req) - .as_legacy() + .as_registry_payload() .expect("should have payload") { SystemEntityRegistryPayload::All(registry) => registry,