From 590648e92f0601d7f2fdd022514b398b22476018 Mon Sep 17 00:00:00 2001 From: GideonBature Date: Fri, 5 Jun 2026 22:19:01 +0100 Subject: [PATCH 1/4] Format codebase with cargo fmt --- .../rpc/bitcoin_rpc/bitcoin_rpc.rs | 4 +- src/communicative/rpc/bitcoin_rpc/mod.rs | 2 +- src/communicative/tcp/client/mod.rs | 23 ++-- .../tcp/client/peer_tcp_client.rs | 4 +- src/communicative/tcp/client/tcp_client.rs | 2 +- src/communicative/tcp/mod.rs | 16 +-- .../server/handle_batchcontainer_request.rs | 44 +++---- ..._batchcontainer_by_prevoutpoint_request.rs | 25 ++-- .../server/handle_batchrecord_request.rs | 9 +- .../in_flight_sync/bodies/response_body.rs | 5 +- .../server/handle_in_flight_sync_request.rs | 7 +- .../tcp/protocol/liftup_v1/bodies/mod.rs | 4 +- .../liftup_v1/bodies/response_body.rs | 7 +- src/communicative/tcp/protocol/mod.rs | 6 +- .../tcp/protocol/move/client/request_move.rs | 7 +- .../protocol/swapout/bodies/response_body.rs | 7 +- src/communicative/tcp/protocol/swapout/mod.rs | 4 +- .../swapout/server/handle_swapout_request.rs | 6 +- src/communicative/tcp/server/server.rs | 2 +- .../batch_container/batch_container.rs | 2 +- src/constructive/bitcoiny/batch_record/mod.rs | 2 +- .../batch_txn/signed_batch_txn/error/mod.rs | 2 +- .../signed_batch_txn/signed_batch_txn.rs | 9 +- .../error/construct_error.rs | 2 +- .../batch_txn/unsigned_batch_txn/error/mod.rs | 2 +- .../calldata_elements/sbe/decode/decode.rs | 96 ++++++++-------- .../calldata_elements/sbe/decode/list.rs | 19 +-- src/constructive/core_types/calldata/mod.rs | 4 +- .../entities/account/account/account.rs | 14 ++- .../account/ext/codec/sbe/decode/decode.rs | 22 ++-- .../account/unregistered_account/ext/mod.rs | 2 +- .../ext/register_with_db/mod.rs | 2 +- .../account/unregistered_account/mod.rs | 2 +- .../ext/codec/sbe/encode/encode.rs | 4 +- .../validate_root_account.rs | 14 ++- .../ext/mod.rs | 2 +- .../ext/sync_with_registry/mod.rs | 2 +- .../sync_with_registry_error.rs | 6 +- .../ext/mod.rs | 2 +- .../ext/sync_with_registry/mod.rs | 2 +- ...egistered_but_unconfigured_root_account.rs | 2 +- .../unregistered_root_account/ext/mod.rs | 2 +- .../ext/register_with_db/mod.rs | 2 +- .../unregistered_root_account.rs | 2 +- .../entities/contract/ape/encode/encode.rs | 6 +- .../contract/ext/codec/sbe/decode/decode.rs | 15 ++- .../ext/codec/ape/encode/encode.rs | 5 +- .../ext/codec/sbe/decode/decode.rs | 9 +- .../ops_budget/ext/codec/sbe/decode/decode.rs | 20 ++-- .../ops_budget/ext/codec/sbe/encode/encode.rs | 4 +- .../ops_price/ext/codec/ape/decode/decode.rs | 8 +- .../ops_price/ext/codec/ape/encode/encode.rs | 5 +- .../ops_price/ext/codec/sbe/decode/decode.rs | 9 +- .../core_types/ops_price/ops_price.rs | 2 +- .../target/ext/codec/ape/decode/error/mod.rs | 2 +- .../target/ext/codec/ape/decode/mod.rs | 2 +- .../target/ext/codec/ape/encode/encode.rs | 5 +- .../target/ext/codec/ape/encode/error/mod.rs | 2 +- .../target/ext/codec/ape/encode/mod.rs | 2 +- .../target/ext/codec/sbe/decode/decode.rs | 9 +- .../maybe_common/common/common_long/mod.rs | 2 +- .../val/long_val/ape/encode/encode.rs | 4 +- src/constructive/entries/entry/entry.rs | 4 +- .../entry/ext/codec/ape/decode/decode.rs | 11 +- .../entry/ext/codec/ape/encode/encode.rs | 2 +- .../entry/ext/codec/sbe/decode/decode.rs | 16 +-- .../codec/sbe/encode/error/encode_error.rs | 1 - .../entries/entry_fees/entry_fees.rs | 30 +++-- .../call/ext/codec/ape/decode/decode.rs | 51 ++++----- .../call/ext/codec/ape/encode/encode.rs | 22 ++-- .../codec/sbe/decode/error/decode_error.rs | 37 ++++-- .../entries/entry_kinds/config/config.rs | 5 +- .../config/ext/codec/ape/decode/decode.rs | 7 +- .../config/ext/codec/ape/encode/encode.rs | 10 +- .../config/ext/codec/sbe/decode/decode.rs | 108 ++++++++++-------- .../codec/sbe/decode/error/decode_error.rs | 64 ++++++++--- .../entries/entry_kinds/deploy/deploy.rs | 12 +- .../deploy/ext/codec/ape/encode/encode.rs | 4 +- .../deploy/ext/codec/sbe/decode/decode.rs | 72 +++++++----- .../codec/sbe/decode/error/decode_error.rs | 35 ++++-- .../liftup/ext/codec/ape/encode/encode.rs | 4 +- .../entries/entry_kinds/liftup/ext/mod.rs | 2 +- .../ext/signature/bls_sign/error/mod.rs | 2 +- .../signature/sighash/error/sighash_error.rs | 2 +- .../entries/entry_kinds/liftup/liftup.rs | 5 +- src/constructive/entries/entry_kinds/mod.rs | 2 +- .../move/ext/codec/sbe/decode/decode.rs | 53 +++++---- .../codec/sbe/decode/error/decode_error.rs | 35 ++++-- .../validate_overall/validate_overall.rs | 8 +- .../swapout/ext/codec/ape/decode/decode.rs | 12 +- .../swapout/ext/codec/sbe/decode/decode.rs | 48 +++++--- .../codec/sbe/decode/error/decode_error.rs | 26 ++++- .../ext/signature/bls_verify/bls_verify.rs | 4 +- .../entries/entry_kinds/swapout/swapout.rs | 5 +- src/constructive/mod.rs | 4 +- .../lift/lift/ext/codec/sbe/decode/decode.rs | 4 +- .../liftv2/ext/codec/sbe/decode/decode.rs | 44 +++++-- src/constructive/txout_types/mod.rs | 2 +- .../txout_types/pinless_self/pinless_self.rs | 2 - .../pinless_self/unknown/unknown.rs | 5 +- .../txout_types/projector/projector.rs | 2 +- .../config_execution/config_execution.rs | 8 +- .../deploy_execution/deploy_execution.rs | 4 +- .../entry_executions/liftup_execution/mod.rs | 2 +- .../move_execution/move_execution.rs | 4 +- .../swapout_execution/swapout_execution.rs | 4 +- src/executive/exec_ctx/exec_ctx.rs | 47 +++++--- .../vm/opcodes/opcodes/callinfo/op_caller.rs | 2 +- src/executive/vm/opcodes/opcodes/flow/mod.rs | 4 +- src/executive/vm/opcodes/opcodes/push/mod.rs | 20 ++-- .../vm/opcodes/opcodes/signature/mod.rs | 2 +- src/executive/vm/program/compiler/compiler.rs | 6 +- .../vm/program/compiler/compiler_error.rs | 2 +- .../vm/program/method/compiler/compiler.rs | 2 +- src/executive/vm/program/method/mod.rs | 2 +- src/executive/vm/program/mod.rs | 2 +- src/executive/vm/program_execution/mod.rs | 2 +- .../vm/program_execution/program_exec_ctx.rs | 5 +- .../archival_manager/archival_manager.rs | 36 +++--- .../errors/construction_error.rs | 5 +- src/inscriptive/flame_manager/delta/delta.rs | 5 +- src/inscriptive/graveyard/delta/delta.rs | 3 +- src/inscriptive/graveyard/graveyard.rs | 4 +- src/inscriptive/params_manager/mod.rs | 2 +- .../params_manager/params_manager.rs | 3 +- .../privileges_manager/delta/delta.rs | 2 +- .../elements/exemption/exemption.rs | 4 +- .../elements/exemption/mod.rs | 2 +- .../privileges_manager/privileges_manager.rs | 56 ++++++--- .../bodies/account_body/account_body.rs | 4 +- .../registry/errors/apply_changes_error.rs | 5 +- .../errors/update_account_bls_key_error.rs | 1 - src/inscriptive/registry/registry.rs | 5 +- src/inscriptive/utxo_set/mod.rs | 2 +- src/operative/cli/cli.rs | 55 ++++++--- .../cli/commands/common_commands/mod.rs | 4 +- .../commands/common_commands/runexplorer.rs | 67 +++++++---- .../cli/commands/engine_commands/mod.rs | 1 + src/operative/cli/commands/mod.rs | 2 +- .../cli/commands/node_commands/batchrecord.rs | 24 ++-- .../cli/commands/node_commands/comp.rs | 8 +- .../cli/commands/node_commands/config.rs | 11 +- .../cli/commands/node_commands/deploy.rs | 3 +- .../cli/commands/node_commands/mod.rs | 6 +- .../cli/commands/node_commands/rank.rs | 6 +- .../cli/commands/node_commands/swapout.rs | 5 +- src/operative/cli/mod.rs | 2 +- src/operative/run_args/chain.rs | 2 +- src/operative/runner/mod.rs | 2 +- src/operative/runner/runner.rs | 2 +- src/operative/tasks/chain_sync/chain_sync.rs | 6 +- src/operative/tasks/chain_sync/mod.rs | 2 +- .../engine_session/session_pool/error/mod.rs | 4 +- .../session_pool/session_pool.rs | 34 ++++-- .../in_flight_batch_sync.rs | 5 +- src/transmutative/bls/bls_ser.rs | 4 +- src/transmutative/bls/verify.rs | 7 +- src/transmutative/codec/csv.rs | 2 +- src/transmutative/codec/prefix.rs | 2 +- src/transmutative/hash.rs | 72 ++++++++++-- tests/batchtxn.rs | 10 +- tests/opcodec.rs | 2 +- tests/program.rs | 22 ++-- tests/stack.rs | 2 +- tests/stack_uint.rs | 35 ++++-- 165 files changed, 1142 insertions(+), 801 deletions(-) diff --git a/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs b/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs index 31f5563d..7e6f18bc 100644 --- a/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs +++ b/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs @@ -1,6 +1,6 @@ use crate::communicative::rpc::bitcoin_rpc::bitcoin_rpc_error::{ - BitcoinRPCBroadcastRawTransactionError, BitcoinRPCGetChainTipError, BitcoinRPCRetrieveBlockError, - BitcoinRPCGetMempoolFeeRateError, BitcoinRPCValidateRPCError, + BitcoinRPCBroadcastRawTransactionError, BitcoinRPCGetChainTipError, + BitcoinRPCGetMempoolFeeRateError, BitcoinRPCRetrieveBlockError, BitcoinRPCValidateRPCError, }; use crate::communicative::rpc::bitcoin_rpc::bitcoin_rpc_holder::BitcoinRPCHolder; use crate::operative::run_args::chain::Chain; diff --git a/src/communicative/rpc/bitcoin_rpc/mod.rs b/src/communicative/rpc/bitcoin_rpc/mod.rs index 248bfad6..24e95b71 100644 --- a/src/communicative/rpc/bitcoin_rpc/mod.rs +++ b/src/communicative/rpc/bitcoin_rpc/mod.rs @@ -1,3 +1,3 @@ -pub mod bitcoin_rpc_error; pub mod bitcoin_rpc; +pub mod bitcoin_rpc_error; pub mod bitcoin_rpc_holder; diff --git a/src/communicative/tcp/client/mod.rs b/src/communicative/tcp/client/mod.rs index f8f99e78..08340b63 100644 --- a/src/communicative/tcp/client/mod.rs +++ b/src/communicative/tcp/client/mod.rs @@ -1,10 +1,6 @@ mod peer_tcp_client; mod tcp_client; -pub use crate::communicative::tcp::protocol::batchrecord::{ - BatchRecordRequestBody, BatchRecordResponseBody, BatchRecordResponseError, - BatchRecordSuccessBody, -}; pub use crate::communicative::tcp::protocol::batchcontainer::{ BatchContainerRequestBody, BatchContainerResponseBody, BatchContainerResponseError, BatchContainerSuccessBody, @@ -13,6 +9,18 @@ pub use crate::communicative::tcp::protocol::batchcontainer_by_prevoutpoint::{ BatchContainerByPrevOutpointRequestBody, BatchContainerByPrevOutpointResponseBody, BatchContainerByPrevOutpointResponseError, BatchContainerByPrevOutpointSuccessBody, }; +pub use crate::communicative::tcp::protocol::batchrecord::{ + BatchRecordRequestBody, BatchRecordResponseBody, BatchRecordResponseError, + BatchRecordSuccessBody, +}; +pub use crate::communicative::tcp::protocol::config::{ + ConfigRequestBody, ConfigResponseBody, ConfigResponseError, ConfigSuccessBody, + ExecConfigInPoolError, +}; +pub use crate::communicative::tcp::protocol::deploy::{ + DeployRequestBody, DeployResponseBody, DeployResponseError, DeploySuccessBody, + ExecDeployInPoolError, +}; pub use crate::communicative::tcp::protocol::in_flight_sync::{ InFlightSyncRequestBody, InFlightSyncResponseBody, InFlightSyncResponseError, }; @@ -23,13 +31,6 @@ pub use crate::communicative::tcp::protocol::liftup_v1::{ pub use crate::communicative::tcp::protocol::r#move::{ ExecMoveInPoolError, MoveRequestBody, MoveResponseBody, MoveResponseError, MoveSuccessBody, }; -pub use crate::communicative::tcp::protocol::config::{ - ExecConfigInPoolError, ConfigRequestBody, ConfigResponseBody, ConfigResponseError, ConfigSuccessBody, -}; -pub use crate::communicative::tcp::protocol::deploy::{ - DeployRequestBody, DeployResponseBody, DeployResponseError, DeploySuccessBody, - ExecDeployInPoolError, -}; pub use crate::communicative::tcp::protocol::swapout::{ ExecSwapoutInPoolError, SwapoutRequestBody, SwapoutResponseBody, SwapoutResponseError, SwapoutSuccessBody, diff --git a/src/communicative/tcp/client/peer_tcp_client.rs b/src/communicative/tcp/client/peer_tcp_client.rs index 0a589d13..09a02014 100644 --- a/src/communicative/tcp/client/peer_tcp_client.rs +++ b/src/communicative/tcp/client/peer_tcp_client.rs @@ -1,10 +1,10 @@ use crate::communicative::peer::peer::PEER; -use crate::communicative::tcp::protocol::batchrecord::client::request_batchrecord; -use crate::communicative::tcp::protocol::batchrecord::BatchRecordResponseBody; use crate::communicative::tcp::protocol::batchcontainer::client::request_batchcontainer; use crate::communicative::tcp::protocol::batchcontainer::BatchContainerResponseBody; use crate::communicative::tcp::protocol::batchcontainer_by_prevoutpoint::client::request_batchcontainer_by_prevoutpoint; use crate::communicative::tcp::protocol::batchcontainer_by_prevoutpoint::BatchContainerByPrevOutpointResponseBody; +use crate::communicative::tcp::protocol::batchrecord::client::request_batchrecord; +use crate::communicative::tcp::protocol::batchrecord::BatchRecordResponseBody; use crate::communicative::tcp::protocol::config::client::request_config; use crate::communicative::tcp::protocol::config::ConfigResponseBody; use crate::communicative::tcp::protocol::deploy::client::request_deploy; diff --git a/src/communicative/tcp/client/tcp_client.rs b/src/communicative/tcp/client/tcp_client.rs index a27a3595..34cdb1d1 100644 --- a/src/communicative/tcp/client/tcp_client.rs +++ b/src/communicative/tcp/client/tcp_client.rs @@ -1,6 +1,6 @@ -use crate::communicative::tcp::protocol::batchrecord::BatchRecordResponseBody; use crate::communicative::tcp::protocol::batchcontainer::BatchContainerResponseBody; use crate::communicative::tcp::protocol::batchcontainer_by_prevoutpoint::BatchContainerByPrevOutpointResponseBody; +use crate::communicative::tcp::protocol::batchrecord::BatchRecordResponseBody; use crate::communicative::tcp::protocol::config::ConfigResponseBody; use crate::communicative::tcp::protocol::deploy::DeployResponseBody; use crate::communicative::tcp::protocol::in_flight_sync::InFlightSyncResponseBody; diff --git a/src/communicative/tcp/mod.rs b/src/communicative/tcp/mod.rs index 6d5d4667..f6dfd2f7 100644 --- a/src/communicative/tcp/mod.rs +++ b/src/communicative/tcp/mod.rs @@ -5,10 +5,6 @@ pub mod request_error; pub mod server; pub mod tcp; -pub use protocol::batchrecord::{ - BatchRecordRequestBody, BatchRecordResponseBody, BatchRecordResponseError, - BatchRecordSuccessBody, -}; pub use protocol::batchcontainer::{ BatchContainerRequestBody, BatchContainerResponseBody, BatchContainerResponseError, BatchContainerSuccessBody, @@ -17,6 +13,14 @@ pub use protocol::batchcontainer_by_prevoutpoint::{ BatchContainerByPrevOutpointRequestBody, BatchContainerByPrevOutpointResponseBody, BatchContainerByPrevOutpointResponseError, BatchContainerByPrevOutpointSuccessBody, }; +pub use protocol::batchrecord::{ + BatchRecordRequestBody, BatchRecordResponseBody, BatchRecordResponseError, + BatchRecordSuccessBody, +}; +pub use protocol::deploy::{ + DeployRequestBody, DeployResponseBody, DeployResponseError, DeploySuccessBody, + ExecDeployInPoolError, +}; pub use protocol::in_flight_sync::{ InFlightSyncRequestBody, InFlightSyncResponseBody, InFlightSyncResponseError, }; @@ -27,10 +31,6 @@ pub use protocol::liftup_v1::{ pub use protocol::r#move::{ ExecMoveInPoolError, MoveRequestBody, MoveResponseBody, MoveResponseError, MoveSuccessBody, }; -pub use protocol::deploy::{ - DeployRequestBody, DeployResponseBody, DeployResponseError, DeploySuccessBody, - ExecDeployInPoolError, -}; pub use protocol::swapout::{ ExecSwapoutInPoolError, SwapoutRequestBody, SwapoutResponseBody, SwapoutResponseError, SwapoutSuccessBody, diff --git a/src/communicative/tcp/protocol/batchcontainer/server/handle_batchcontainer_request.rs b/src/communicative/tcp/protocol/batchcontainer/server/handle_batchcontainer_request.rs index 334ec524..ebd118d1 100644 --- a/src/communicative/tcp/protocol/batchcontainer/server/handle_batchcontainer_request.rs +++ b/src/communicative/tcp/protocol/batchcontainer/server/handle_batchcontainer_request.rs @@ -10,28 +10,27 @@ pub async fn handle_batchcontainer_request( archival_manager: &Option, ) -> Option { // 1 Deserialize the request body. - let BatchContainerRequestBody { batch_height } = match BatchContainerRequestBody::deserialize( - payload, - ) { - Some(req) => req, - None => { - let body = BatchContainerResponseBody::err( - BatchContainerResponseError::DeserializeBatchContainerRequestError, - ); - let bytes = body.serialize().unwrap_or_default(); - return Some(TCPPackage::new( - PackageKind::BatchContainerProtocol, - timestamp, - &bytes, - )); - } - }; + let BatchContainerRequestBody { batch_height } = + match BatchContainerRequestBody::deserialize(payload) { + Some(req) => req, + None => { + let body = BatchContainerResponseBody::err( + BatchContainerResponseError::DeserializeBatchContainerRequestError, + ); + let bytes = body.serialize().unwrap_or_default(); + return Some(TCPPackage::new( + PackageKind::BatchContainerProtocol, + timestamp, + &bytes, + )); + } + }; // 2 Resolve the batch container from the archival manager (if configured). let response_body = match archival_manager { - None => { - BatchContainerResponseBody::err(BatchContainerResponseError::ArchivalManagerUnavailableError) - } + None => BatchContainerResponseBody::err( + BatchContainerResponseError::ArchivalManagerUnavailableError, + ), Some(archival_manager) => { let _archival_manager = archival_manager.lock().await; let batch_container = _archival_manager @@ -45,8 +44,11 @@ pub async fn handle_batchcontainer_request( let response_bytes = response_body.serialize().unwrap_or_default(); // 4 Construct the response package. - let response_package = - TCPPackage::new(PackageKind::BatchContainerProtocol, timestamp, &response_bytes); + let response_package = TCPPackage::new( + PackageKind::BatchContainerProtocol, + timestamp, + &response_bytes, + ); // 5 Return the response package. Some(response_package) diff --git a/src/communicative/tcp/protocol/batchcontainer_by_prevoutpoint/server/handle_batchcontainer_by_prevoutpoint_request.rs b/src/communicative/tcp/protocol/batchcontainer_by_prevoutpoint/server/handle_batchcontainer_by_prevoutpoint_request.rs index 96e605ca..99790599 100644 --- a/src/communicative/tcp/protocol/batchcontainer_by_prevoutpoint/server/handle_batchcontainer_by_prevoutpoint_request.rs +++ b/src/communicative/tcp/protocol/batchcontainer_by_prevoutpoint/server/handle_batchcontainer_by_prevoutpoint_request.rs @@ -13,21 +13,20 @@ pub async fn handle_batchcontainer_by_prevoutpoint_request( // 1 Deserialize the request body. let BatchContainerByPrevOutpointRequestBody { prev_payload_outpoint, - } = - match BatchContainerByPrevOutpointRequestBody::deserialize(payload) { - Some(req) => req, - None => { - let body = BatchContainerByPrevOutpointResponseBody::err( + } = match BatchContainerByPrevOutpointRequestBody::deserialize(payload) { + Some(req) => req, + None => { + let body = BatchContainerByPrevOutpointResponseBody::err( BatchContainerByPrevOutpointResponseError::DeserializeBatchContainerByPrevOutpointRequestError, ); - let bytes = body.serialize().unwrap_or_default(); - return Some(TCPPackage::new( - PackageKind::BatchContainerByPrevOutpointProtocol, - timestamp, - &bytes, - )); - } - }; + let bytes = body.serialize().unwrap_or_default(); + return Some(TCPPackage::new( + PackageKind::BatchContainerByPrevOutpointProtocol, + timestamp, + &bytes, + )); + } + }; // 2 Resolve the batch container from the archival manager (if configured). let response_body = match archival_manager { diff --git a/src/communicative/tcp/protocol/batchrecord/server/handle_batchrecord_request.rs b/src/communicative/tcp/protocol/batchrecord/server/handle_batchrecord_request.rs index 55380ba0..4136b211 100644 --- a/src/communicative/tcp/protocol/batchrecord/server/handle_batchrecord_request.rs +++ b/src/communicative/tcp/protocol/batchrecord/server/handle_batchrecord_request.rs @@ -10,9 +10,8 @@ pub async fn handle_batchrecord_request( archival_manager: &Option, ) -> Option { // 1 Deserialize the request body. - let BatchRecordRequestBody { batch_height } = match BatchRecordRequestBody::deserialize( - payload, - ) { + let BatchRecordRequestBody { batch_height } = match BatchRecordRequestBody::deserialize(payload) + { Some(req) => req, None => { let body = BatchRecordResponseBody::err( @@ -29,7 +28,9 @@ pub async fn handle_batchrecord_request( // 2 Resolve the batch record from the archival manager (if configured). let response_body = match archival_manager { - None => BatchRecordResponseBody::err(BatchRecordResponseError::ArchivalManagerUnavailableError), + None => { + BatchRecordResponseBody::err(BatchRecordResponseError::ArchivalManagerUnavailableError) + } Some(archival_manager) => { let _archival_manager = archival_manager.lock().await; let batch_record = _archival_manager.batch_record_by_height(batch_height); diff --git a/src/communicative/tcp/protocol/in_flight_sync/bodies/response_body.rs b/src/communicative/tcp/protocol/in_flight_sync/bodies/response_body.rs index ebfd9f6f..3f7c443b 100644 --- a/src/communicative/tcp/protocol/in_flight_sync/bodies/response_body.rs +++ b/src/communicative/tcp/protocol/in_flight_sync/bodies/response_body.rs @@ -74,7 +74,10 @@ impl InFlightSyncResponseBody { } InFlightSyncResponseBody::BatchDownload(batch_container) => { let mut result = Map::new(); - result.insert("kind".to_string(), Value::String("batch_download".to_string())); + result.insert( + "kind".to_string(), + Value::String("batch_download".to_string()), + ); result.insert("batch_container".to_string(), batch_container.json()); let mut obj = Map::new(); diff --git a/src/communicative/tcp/protocol/in_flight_sync/server/handle_in_flight_sync_request.rs b/src/communicative/tcp/protocol/in_flight_sync/server/handle_in_flight_sync_request.rs index 5dd72c37..418d381c 100644 --- a/src/communicative/tcp/protocol/in_flight_sync/server/handle_in_flight_sync_request.rs +++ b/src/communicative/tcp/protocol/in_flight_sync/server/handle_in_flight_sync_request.rs @@ -69,8 +69,11 @@ pub async fn handle_in_flight_sync_request( let response_bytes = response_body.serialize().unwrap_or_default(); // 4 Construct the response package. - let response_package = - TCPPackage::new(PackageKind::InFlightSyncProtocol, timestamp, &response_bytes); + let response_package = TCPPackage::new( + PackageKind::InFlightSyncProtocol, + timestamp, + &response_bytes, + ); // 5 Return the response package. Some(response_package) diff --git a/src/communicative/tcp/protocol/liftup_v1/bodies/mod.rs b/src/communicative/tcp/protocol/liftup_v1/bodies/mod.rs index 1008f387..ea0b76d9 100644 --- a/src/communicative/tcp/protocol/liftup_v1/bodies/mod.rs +++ b/src/communicative/tcp/protocol/liftup_v1/bodies/mod.rs @@ -4,6 +4,4 @@ mod request_body; mod response_body; pub use request_body::LiftupV1RequestBody; -pub use response_body::{ - LiftupV1ResponseBody, LiftupV1ResponseError, LiftupV1SuccessBody, -}; +pub use response_body::{LiftupV1ResponseBody, LiftupV1ResponseError, LiftupV1SuccessBody}; diff --git a/src/communicative/tcp/protocol/liftup_v1/bodies/response_body.rs b/src/communicative/tcp/protocol/liftup_v1/bodies/response_body.rs index ec29a8a8..b689c6bb 100644 --- a/src/communicative/tcp/protocol/liftup_v1/bodies/response_body.rs +++ b/src/communicative/tcp/protocol/liftup_v1/bodies/response_body.rs @@ -103,12 +103,7 @@ impl LiftupV1ResponseBody { } } - pub fn ok( - entry_id: [u8; 32], - batch_height: u64, - batch_timestamp: u64, - entry: Entry, - ) -> Self { + pub fn ok(entry_id: [u8; 32], batch_height: u64, batch_timestamp: u64, entry: Entry) -> Self { Self::Ok(LiftupV1SuccessBody { entry_id, batch_height, diff --git a/src/communicative/tcp/protocol/mod.rs b/src/communicative/tcp/protocol/mod.rs index 88149185..1fb7fd30 100644 --- a/src/communicative/tcp/protocol/mod.rs +++ b/src/communicative/tcp/protocol/mod.rs @@ -1,12 +1,12 @@ //! TCP application protocols (ping, liftup v1, …). -pub mod batchrecord; pub mod batchcontainer; pub mod batchcontainer_by_prevoutpoint; +pub mod batchrecord; +pub mod config; +pub mod deploy; pub mod in_flight_sync; pub mod liftup_v1; pub mod r#move; pub mod ping; -pub mod config; pub mod swapout; -pub mod deploy; diff --git a/src/communicative/tcp/protocol/move/client/request_move.rs b/src/communicative/tcp/protocol/move/client/request_move.rs index 4b681098..78fb8e05 100644 --- a/src/communicative/tcp/protocol/move/client/request_move.rs +++ b/src/communicative/tcp/protocol/move/client/request_move.rs @@ -27,11 +27,8 @@ pub async fn request_move( .ok_or(RequestError::RequestSerializationError)?; // 3 Construct the request package. - let request_package = TCPPackage::new( - PackageKind::MoveProtocol, - Utc::now().timestamp(), - &payload, - ); + let request_package = + TCPPackage::new(PackageKind::MoveProtocol, Utc::now().timestamp(), &payload); // 4 Send the request package. let socket: SOCKET = peer diff --git a/src/communicative/tcp/protocol/swapout/bodies/response_body.rs b/src/communicative/tcp/protocol/swapout/bodies/response_body.rs index 94f08431..4af7b1cc 100644 --- a/src/communicative/tcp/protocol/swapout/bodies/response_body.rs +++ b/src/communicative/tcp/protocol/swapout/bodies/response_body.rs @@ -100,12 +100,7 @@ impl SwapoutResponseBody { } } - pub fn ok( - entry_id: [u8; 32], - batch_height: u64, - batch_timestamp: u64, - entry: Entry, - ) -> Self { + pub fn ok(entry_id: [u8; 32], batch_height: u64, batch_timestamp: u64, entry: Entry) -> Self { Self::Ok(SwapoutSuccessBody { entry_id, batch_height, diff --git a/src/communicative/tcp/protocol/swapout/mod.rs b/src/communicative/tcp/protocol/swapout/mod.rs index 65c63d35..7a1a0e42 100644 --- a/src/communicative/tcp/protocol/swapout/mod.rs +++ b/src/communicative/tcp/protocol/swapout/mod.rs @@ -5,4 +5,6 @@ pub mod client; pub mod server; pub use crate::operative::tasks::engine_session::session_pool::error::exec_swapout_in_pool_error::ExecSwapoutInPoolError; -pub use bodies::{SwapoutRequestBody, SwapoutResponseBody, SwapoutResponseError, SwapoutSuccessBody}; +pub use bodies::{ + SwapoutRequestBody, SwapoutResponseBody, SwapoutResponseError, SwapoutSuccessBody, +}; diff --git a/src/communicative/tcp/protocol/swapout/server/handle_swapout_request.rs b/src/communicative/tcp/protocol/swapout/server/handle_swapout_request.rs index 56689873..4f7f1459 100644 --- a/src/communicative/tcp/protocol/swapout/server/handle_swapout_request.rs +++ b/src/communicative/tcp/protocol/swapout/server/handle_swapout_request.rs @@ -22,7 +22,8 @@ pub async fn handle_swapout_request( } = match SwapoutRequestBody::deserialize(payload) { Some(req) => req, None => { - let body = SwapoutResponseBody::err(SwapoutResponseError::DeserializeSwapoutRequestError); + let body = + SwapoutResponseBody::err(SwapoutResponseError::DeserializeSwapoutRequestError); let bytes = body.serialize().unwrap_or_default(); return Some(TCPPackage::new( PackageKind::SwapoutProtocol, @@ -76,7 +77,8 @@ pub async fn handle_swapout_request( .serialize() .unwrap_or_default(); - let response_package = TCPPackage::new(PackageKind::SwapoutProtocol, timestamp, &response_bytes); + let response_package = + TCPPackage::new(PackageKind::SwapoutProtocol, timestamp, &response_bytes); Some(response_package) } diff --git a/src/communicative/tcp/server/server.rs b/src/communicative/tcp/server/server.rs index a2cf079e..5126b059 100644 --- a/src/communicative/tcp/server/server.rs +++ b/src/communicative/tcp/server/server.rs @@ -1,5 +1,5 @@ -use super::connection::handle_socket; use super::super::tcp::port_number; +use super::connection::handle_socket; use crate::inscriptive::archival_manager::archival_manager::ARCHIVAL_MANAGER; use crate::operative::run_args::{chain::Chain, operating_kind::OperatingKind}; use crate::operative::tasks::engine_session::session_pool::session_pool::SESSION_POOL; diff --git a/src/constructive/bitcoiny/batch_container/batch_container.rs b/src/constructive/bitcoiny/batch_container/batch_container.rs index 62a96ad1..21eb0efd 100644 --- a/src/constructive/bitcoiny/batch_container/batch_container.rs +++ b/src/constructive/bitcoiny/batch_container/batch_container.rs @@ -1,5 +1,5 @@ use crate::constructive::bitcoiny::batch_txn::signed_batch_txn::signed_batch_txn::SignedBatchTxn; -use bitcoin::{OutPoint, TxOut, hashes::Hash as _}; +use bitcoin::{hashes::Hash as _, OutPoint, TxOut}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; diff --git a/src/constructive/bitcoiny/batch_record/mod.rs b/src/constructive/bitcoiny/batch_record/mod.rs index 5bc9175d..f0135536 100644 --- a/src/constructive/bitcoiny/batch_record/mod.rs +++ b/src/constructive/bitcoiny/batch_record/mod.rs @@ -1 +1 @@ -pub mod batch_record; \ No newline at end of file +pub mod batch_record; diff --git a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/error/mod.rs b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/error/mod.rs index d7723128..06a905e8 100644 --- a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/error/mod.rs +++ b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/error/mod.rs @@ -1 +1 @@ -pub mod construct_error; \ No newline at end of file +pub mod construct_error; diff --git a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs index 749308ab..be834991 100644 --- a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs +++ b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs @@ -92,12 +92,9 @@ impl SignedBatchTxn { let mut swapout_tx_outputs = Vec::new(); for entry in &entries { if let Entry::Swapout(swapout) = entry { - let scriptpubkey = swapout - .pinless_self - .calculated_scriptpubkey() - .ok_or( - SignedBatchTxnConstructError::SwapoutPinlessSelfCalculatedScriptpubkeyError, - )?; + let scriptpubkey = swapout.pinless_self.calculated_scriptpubkey().ok_or( + SignedBatchTxnConstructError::SwapoutPinlessSelfCalculatedScriptpubkeyError, + )?; let txout = TxOut { value: Amount::from_sat(u64::from(swapout.amount)), script_pubkey: ScriptBuf::from(scriptpubkey), diff --git a/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/construct_error.rs b/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/construct_error.rs index 13292f7c..2bbde087 100644 --- a/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/construct_error.rs +++ b/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/construct_error.rs @@ -5,4 +5,4 @@ pub enum UnsignedBatchTxnConstructError { ChangeValueProjectorValueCheckedSubError, ChangeValueSwapoutValueCheckedSubError, NewPayloadScriptpubkeyError, -} \ No newline at end of file +} diff --git a/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/mod.rs b/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/mod.rs index d7723128..06a905e8 100644 --- a/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/mod.rs +++ b/src/constructive/bitcoiny/batch_txn/unsigned_batch_txn/error/mod.rs @@ -1 +1 @@ -pub mod construct_error; \ No newline at end of file +pub mod construct_error; diff --git a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs index aface655..5ab8c85b 100644 --- a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs +++ b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs @@ -1,8 +1,8 @@ use crate::constructive::calldata::element::calldata_element::CalldataElement; use crate::constructive::calldata::element::sbe::decode::error::decode_errors::{ - BoolSBEDecodeError, BytesSBEDecodeError, CalldataElementSBEDecodeError, - CallAccountSBEDecodeError, CallContractSBEDecodeError, PayableSBEDecodeError, U16SBEDecodeError, - U32SBEDecodeError, U64SBEDecodeError, U8SBEDecodeError, VarbytesSBEDecodeError, + BoolSBEDecodeError, BytesSBEDecodeError, CallAccountSBEDecodeError, CallContractSBEDecodeError, + CalldataElementSBEDecodeError, PayableSBEDecodeError, U16SBEDecodeError, U32SBEDecodeError, + U64SBEDecodeError, U8SBEDecodeError, VarbytesSBEDecodeError, }; use crate::constructive::calldata::element_type::CalldataElementType; use crate::constructive::entity::account::account::account::Account; @@ -11,7 +11,9 @@ use crate::constructive::entity::contract::ext::codec::sbe::encode::encode::CONT const MAX_VARBYTES_LEN: u16 = 4095; -fn parse_element_type(bytes: &[u8]) -> Result<(CalldataElementType, usize), CalldataElementSBEDecodeError> { +fn parse_element_type( + bytes: &[u8], +) -> Result<(CalldataElementType, usize), CalldataElementSBEDecodeError> { if bytes.is_empty() { return Err(CalldataElementSBEDecodeError::CalldataElementSBEEmptyBufferError); } @@ -52,56 +54,50 @@ impl CalldataElement { let (element, payload_consumed) = match element_type { CalldataElementType::U8 => { if payload.is_empty() { - return Err(CalldataElementSBEDecodeError::U8(U8SBEDecodeError::InsufficientPayloadBytes { - got: 0, - })); + return Err(CalldataElementSBEDecodeError::U8( + U8SBEDecodeError::InsufficientPayloadBytes { got: 0 }, + )); } (CalldataElement::U8(payload[0]), 1) } CalldataElementType::U16 => { if payload.len() < 2 { - return Err(CalldataElementSBEDecodeError::U16(U16SBEDecodeError::InsufficientPayloadBytes { - got: payload.len(), - })); + return Err(CalldataElementSBEDecodeError::U16( + U16SBEDecodeError::InsufficientPayloadBytes { got: payload.len() }, + )); } - let value = u16::from_le_bytes( - payload[0..2].try_into().map_err(|_| { - CalldataElementSBEDecodeError::U16(U16SBEDecodeError::BytesConversionError) - })?, - ); + let value = u16::from_le_bytes(payload[0..2].try_into().map_err(|_| { + CalldataElementSBEDecodeError::U16(U16SBEDecodeError::BytesConversionError) + })?); (CalldataElement::U16(value), 2) } CalldataElementType::U32 => { if payload.len() < 4 { - return Err(CalldataElementSBEDecodeError::U32(U32SBEDecodeError::InsufficientPayloadBytes { - got: payload.len(), - })); + return Err(CalldataElementSBEDecodeError::U32( + U32SBEDecodeError::InsufficientPayloadBytes { got: payload.len() }, + )); } - let value = u32::from_le_bytes( - payload[0..4].try_into().map_err(|_| { - CalldataElementSBEDecodeError::U32(U32SBEDecodeError::BytesConversionError) - })?, - ); + let value = u32::from_le_bytes(payload[0..4].try_into().map_err(|_| { + CalldataElementSBEDecodeError::U32(U32SBEDecodeError::BytesConversionError) + })?); (CalldataElement::U32(value), 4) } CalldataElementType::U64 => { if payload.len() < 8 { - return Err(CalldataElementSBEDecodeError::U64(U64SBEDecodeError::InsufficientPayloadBytes { - got: payload.len(), - })); + return Err(CalldataElementSBEDecodeError::U64( + U64SBEDecodeError::InsufficientPayloadBytes { got: payload.len() }, + )); } - let value = u64::from_le_bytes( - payload[0..8].try_into().map_err(|_| { - CalldataElementSBEDecodeError::U64(U64SBEDecodeError::BytesConversionError) - })?, - ); + let value = u64::from_le_bytes(payload[0..8].try_into().map_err(|_| { + CalldataElementSBEDecodeError::U64(U64SBEDecodeError::BytesConversionError) + })?); (CalldataElement::U64(value), 8) } CalldataElementType::Bool => { if payload.is_empty() { - return Err(CalldataElementSBEDecodeError::Bool(BoolSBEDecodeError::InsufficientPayloadBytes { - got: 0, - })); + return Err(CalldataElementSBEDecodeError::Bool( + BoolSBEDecodeError::InsufficientPayloadBytes { got: 0 }, + )); } let value = match payload[0] { 0x00 => false, @@ -116,23 +112,27 @@ impl CalldataElement { } CalldataElementType::Account => { let account = Account::decode_sbe(payload).map_err(|e| { - CalldataElementSBEDecodeError::Account(CallAccountSBEDecodeError::AccountSBEDecodeError(e)) + CalldataElementSBEDecodeError::Account( + CallAccountSBEDecodeError::AccountSBEDecodeError(e), + ) })?; let consumed = account_sbe_payload_len(&account); (CalldataElement::Account(account), consumed) } CalldataElementType::Contract => { let contract = Contract::decode_sbe(payload).map_err(|e| { - CalldataElementSBEDecodeError::Contract(CallContractSBEDecodeError::ContractSBEDecodeError(e)) + CalldataElementSBEDecodeError::Contract( + CallContractSBEDecodeError::ContractSBEDecodeError(e), + ) })?; (CalldataElement::Contract(contract), CONTRACT_SBE_LEN) } CalldataElementType::Bytes(index) => { let byte_length = index as usize + 1; if byte_length < 1 || byte_length > 256 { - return Err(CalldataElementSBEDecodeError::Bytes(BytesSBEDecodeError::InvalidBytesLength( - byte_length, - ))); + return Err(CalldataElementSBEDecodeError::Bytes( + BytesSBEDecodeError::InvalidBytesLength(byte_length), + )); } if payload.len() < byte_length { return Err(CalldataElementSBEDecodeError::Bytes( @@ -150,7 +150,9 @@ impl CalldataElement { CalldataElementType::Varbytes => { if payload.len() < 2 { return Err(CalldataElementSBEDecodeError::Varbytes( - VarbytesSBEDecodeError::InsufficientPayloadBytesForLength { got: payload.len() }, + VarbytesSBEDecodeError::InsufficientPayloadBytesForLength { + got: payload.len(), + }, )); } let byte_length = u16::from_le_bytes([payload[0], payload[1]]); @@ -176,16 +178,14 @@ impl CalldataElement { CalldataElementType::Payable => { if payload.len() < 4 { return Err(CalldataElementSBEDecodeError::Payable( - PayableSBEDecodeError::InsufficientPayloadBytes { - got: payload.len(), - }, + PayableSBEDecodeError::InsufficientPayloadBytes { got: payload.len() }, )); } - let value = u32::from_le_bytes( - payload[0..4].try_into().map_err(|_| { - CalldataElementSBEDecodeError::Payable(PayableSBEDecodeError::BytesConversionError) - })?, - ); + let value = u32::from_le_bytes(payload[0..4].try_into().map_err(|_| { + CalldataElementSBEDecodeError::Payable( + PayableSBEDecodeError::BytesConversionError, + ) + })?); (CalldataElement::Payable(value), 4) } }; diff --git a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs index 475f3834..a163f485 100644 --- a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs +++ b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs @@ -6,9 +6,9 @@ pub fn decode_calldata_elements_sbe( bytes: &[u8], ) -> Result, CalldataElementsSBEDecodeError> { if bytes.len() < 4 { - return Err(CalldataElementsSBEDecodeError::InsufficientBytesForElementCount { - got: bytes.len(), - }); + return Err( + CalldataElementsSBEDecodeError::InsufficientBytesForElementCount { got: bytes.len() }, + ); } let count = u32::from_le_bytes( @@ -21,17 +21,18 @@ pub fn decode_calldata_elements_sbe( let mut elements = Vec::with_capacity(count); for _ in 0..count { - let (element, remaining) = CalldataElement::decode_sbe(rest).map_err(|e| { - CalldataElementsSBEDecodeError::Element(e) - })?; + let (element, remaining) = CalldataElement::decode_sbe(rest) + .map_err(|e| CalldataElementsSBEDecodeError::Element(e))?; elements.push(element); rest = remaining; } if !rest.is_empty() { - return Err(CalldataElementsSBEDecodeError::TrailingBytesAfterCalldataList { - trailing: rest.len(), - }); + return Err( + CalldataElementsSBEDecodeError::TrailingBytesAfterCalldataList { + trailing: rest.len(), + }, + ); } Ok(elements) diff --git a/src/constructive/core_types/calldata/mod.rs b/src/constructive/core_types/calldata/mod.rs index bf825ace..64439214 100644 --- a/src/constructive/core_types/calldata/mod.rs +++ b/src/constructive/core_types/calldata/mod.rs @@ -1,5 +1,5 @@ -pub mod calldata_elements; pub mod calldata_element_type; +pub mod calldata_elements; -pub use calldata_elements as element; pub use calldata_element_type as element_type; +pub use calldata_elements as element; diff --git a/src/constructive/core_types/entities/account/account/account.rs b/src/constructive/core_types/entities/account/account/account.rs index d95830b4..ef86e92d 100644 --- a/src/constructive/core_types/entities/account/account/account.rs +++ b/src/constructive/core_types/entities/account/account/account.rs @@ -18,10 +18,7 @@ pub enum Account { impl Account { /// Returns the `Account` for the given account key from the `Registry`. - pub async fn account_from_registry( - account_key: [u8; 32], - registry: ®ISTRY, - ) -> Account { + pub async fn account_from_registry(account_key: [u8; 32], registry: ®ISTRY) -> Account { // 1 Retrieve the account info if it is registered. let account_info = { // 1.1 Lock the registry. @@ -104,10 +101,15 @@ impl Account { // 2.b The `Account` is unregistered. Self::UnregisteredAccount(unregistered_account) => { - obj.insert("kind".to_string(), Value::String("unregistered".to_string())); + obj.insert( + "kind".to_string(), + Value::String("unregistered".to_string()), + ); obj.insert( "account_key_to_be_registered".to_string(), - Value::String(hex::encode(unregistered_account.account_key_to_be_registered)), + Value::String(hex::encode( + unregistered_account.account_key_to_be_registered, + )), ); } } diff --git a/src/constructive/core_types/entities/account/account/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/entities/account/account/ext/codec/sbe/decode/decode.rs index 4783a209..024e67a6 100644 --- a/src/constructive/core_types/entities/account/account/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/entities/account/account/ext/codec/sbe/decode/decode.rs @@ -32,9 +32,10 @@ impl Account { } // 4.a.2 Decode the account key to be registered. - let account_key_to_be_registered: [u8; 32] = payload[0..32] - .try_into() - .map_err(|_| AccountSBEDecodeError::UnregisteredAccountSBEAccountKeyBytesConversionError)?; + let account_key_to_be_registered: [u8; 32] = + payload[0..32].try_into().map_err(|_| { + AccountSBEDecodeError::UnregisteredAccountSBEAccountKeyBytesConversionError + })?; // 4.a.3 Ensure no trailing bytes after the account key. if payload.len() != 32 { @@ -63,9 +64,9 @@ impl Account { } // 4.b.2 Decode the account key. - let account_key: [u8; 32] = payload[0..32] - .try_into() - .map_err(|_| AccountSBEDecodeError::RegisteredAccountSBEAccountKeyBytesConversionError)?; + let account_key: [u8; 32] = payload[0..32].try_into().map_err(|_| { + AccountSBEDecodeError::RegisteredAccountSBEAccountKeyBytesConversionError + })?; // 4.b.3 Ensure the payload holds the 8-byte little-endian registry index after the key. if payload.len() < 32 + 8 { @@ -77,11 +78,10 @@ impl Account { } // 4.b.4 Decode the registry index. - let registry_index = u64::from_le_bytes( - payload[32..40] - .try_into() - .map_err(|_| AccountSBEDecodeError::RegisteredAccountSBERegistryIndexBytesConversionError)?, - ); + let registry_index = + u64::from_le_bytes(payload[32..40].try_into().map_err(|_| { + AccountSBEDecodeError::RegisteredAccountSBERegistryIndexBytesConversionError + })?); // 4.b.5 Ensure no trailing bytes after the registry index. if payload.len() != 32 + 8 { diff --git a/src/constructive/core_types/entities/account/account/unregistered_account/ext/mod.rs b/src/constructive/core_types/entities/account/account/unregistered_account/ext/mod.rs index bbc8d727..a1f4254c 100644 --- a/src/constructive/core_types/entities/account/account/unregistered_account/ext/mod.rs +++ b/src/constructive/core_types/entities/account/account/unregistered_account/ext/mod.rs @@ -1 +1 @@ -pub mod register_with_db; \ No newline at end of file +pub mod register_with_db; diff --git a/src/constructive/core_types/entities/account/account/unregistered_account/ext/register_with_db/mod.rs b/src/constructive/core_types/entities/account/account/unregistered_account/ext/register_with_db/mod.rs index bad1311c..8c4c6295 100644 --- a/src/constructive/core_types/entities/account/account/unregistered_account/ext/register_with_db/mod.rs +++ b/src/constructive/core_types/entities/account/account/unregistered_account/ext/register_with_db/mod.rs @@ -1,2 +1,2 @@ +pub mod register_with_db; pub mod register_with_db_error; -pub mod register_with_db; \ No newline at end of file diff --git a/src/constructive/core_types/entities/account/account/unregistered_account/mod.rs b/src/constructive/core_types/entities/account/account/unregistered_account/mod.rs index 0c0a29bf..efe97a61 100644 --- a/src/constructive/core_types/entities/account/account/unregistered_account/mod.rs +++ b/src/constructive/core_types/entities/account/account/unregistered_account/mod.rs @@ -1,2 +1,2 @@ pub mod ext; -pub mod unregistered_account; \ No newline at end of file +pub mod unregistered_account; diff --git a/src/constructive/core_types/entities/account/root_account/ext/codec/sbe/encode/encode.rs b/src/constructive/core_types/entities/account/root_account/ext/codec/sbe/encode/encode.rs index 0972914a..dae5094d 100644 --- a/src/constructive/core_types/entities/account/root_account/ext/codec/sbe/encode/encode.rs +++ b/src/constructive/core_types/entities/account/root_account/ext/codec/sbe/encode/encode.rs @@ -96,7 +96,9 @@ impl RootAccount { // 2.c.3 Encode the registry index. bytes.extend( - registered_and_configured_root_account.registry_index.to_le_bytes(), + registered_and_configured_root_account + .registry_index + .to_le_bytes(), ); // 2.c.4 Encode the BLS key. diff --git a/src/constructive/core_types/entities/account/root_account/ext/validate_root_account/validate_root_account.rs b/src/constructive/core_types/entities/account/root_account/ext/validate_root_account/validate_root_account.rs index 32598d9e..501dbf5b 100644 --- a/src/constructive/core_types/entities/account/root_account/ext/validate_root_account/validate_root_account.rs +++ b/src/constructive/core_types/entities/account/root_account/ext/validate_root_account/validate_root_account.rs @@ -89,8 +89,9 @@ impl RootAccount { let _registry = registry.lock().await; // 1.b.3.2 Get account info by account key. - let account_info = _registry - .get_account_info_by_account_key(registered_but_unconfigured_root_account.account_key); + let account_info = _registry.get_account_info_by_account_key( + registered_but_unconfigured_root_account.account_key, + ); // 1.b.3.3 Match on account info. match account_info { @@ -124,7 +125,9 @@ impl RootAccount { } // 1.c `RegisteredAndConfiguredRootAccount` - RootAccount::RegisteredAndConfiguredRootAccount(registered_and_configured_root_account) => { + RootAccount::RegisteredAndConfiguredRootAccount( + registered_and_configured_root_account, + ) => { // 1.c.1 Validate Schnorr / BLS key material. if !registered_and_configured_root_account.validate_schnorr_and_bls_key() { return Err( @@ -138,8 +141,9 @@ impl RootAccount { let _registry = registry.lock().await; // 1.c.2.2 Get account info by account key. - let account_info = _registry - .get_account_info_by_account_key(registered_and_configured_root_account.account_key); + let account_info = _registry.get_account_info_by_account_key( + registered_and_configured_root_account.account_key, + ); // 1.c.2.3 Match on account info. match account_info { diff --git a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/mod.rs b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/mod.rs index 2924bfea..1911026d 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/mod.rs @@ -1 +1 @@ -pub mod sync_with_registry; \ No newline at end of file +pub mod sync_with_registry; diff --git a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/mod.rs b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/mod.rs index 286fb6db..4ab6c6ff 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/mod.rs @@ -1,2 +1,2 @@ +pub mod sync_with_registry; pub mod sync_with_registry_error; -pub mod sync_with_registry; \ No newline at end of file diff --git a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/sync_with_registry_error.rs b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/sync_with_registry_error.rs index 9394b1be..9030232e 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/sync_with_registry_error.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_and_configured_root_account/ext/sync_with_registry/sync_with_registry_error.rs @@ -3,5 +3,7 @@ use crate::inscriptive::registry::errors::update_account_call_counter_and_last_a /// Errors associated with syncing a `RegisteredAndConfiguredRootAccount` with the `Registry`. #[derive(Debug, Clone)] pub enum RegisteredAndConfiguredRootAccountSyncWithRegistryError { - RegistryUpdateAccountCallCounterAndLastActivityTimestampError(RMUpdateAccountCallCounterAndLastActivityTimestampError), -} \ No newline at end of file + RegistryUpdateAccountCallCounterAndLastActivityTimestampError( + RMUpdateAccountCallCounterAndLastActivityTimestampError, + ), +} diff --git a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/mod.rs b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/mod.rs index 2924bfea..1911026d 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/mod.rs @@ -1 +1 @@ -pub mod sync_with_registry; \ No newline at end of file +pub mod sync_with_registry; diff --git a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/sync_with_registry/mod.rs b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/sync_with_registry/mod.rs index 286fb6db..4ab6c6ff 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/sync_with_registry/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/ext/sync_with_registry/mod.rs @@ -1,2 +1,2 @@ +pub mod sync_with_registry; pub mod sync_with_registry_error; -pub mod sync_with_registry; \ No newline at end of file diff --git a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/registered_but_unconfigured_root_account.rs b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/registered_but_unconfigured_root_account.rs index 7ac78d28..9a61c034 100644 --- a/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/registered_but_unconfigured_root_account.rs +++ b/src/constructive/core_types/entities/account/root_account/registered_but_unconfigured_root_account/registered_but_unconfigured_root_account.rs @@ -1,10 +1,10 @@ use crate::constructive::entity::account::root_account::root_account::verify_bls_key_authorization_signature; use crate::{ + inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig, transmutative::bls::bls_ser::{ deserialize_bls_key, deserialize_schnorr_signature, serialize_bls_key, serialize_schnorr_signature, }, - inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig, }; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; diff --git a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/mod.rs b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/mod.rs index bbc8d727..a1f4254c 100644 --- a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/mod.rs @@ -1 +1 @@ -pub mod register_with_db; \ No newline at end of file +pub mod register_with_db; diff --git a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/register_with_db/mod.rs b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/register_with_db/mod.rs index bad1311c..8c4c6295 100644 --- a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/register_with_db/mod.rs +++ b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/ext/register_with_db/mod.rs @@ -1,2 +1,2 @@ +pub mod register_with_db; pub mod register_with_db_error; -pub mod register_with_db; \ No newline at end of file diff --git a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/unregistered_root_account.rs b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/unregistered_root_account.rs index b3d4cd73..9fda97de 100644 --- a/src/constructive/core_types/entities/account/root_account/unregistered_root_account/unregistered_root_account.rs +++ b/src/constructive/core_types/entities/account/root_account/unregistered_root_account/unregistered_root_account.rs @@ -1,9 +1,9 @@ use crate::constructive::entity::account::root_account::root_account::verify_bls_key_authorization_signature; +use crate::inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig; use crate::transmutative::bls::bls_ser::{ deserialize_bls_key, deserialize_schnorr_signature, serialize_bls_key, serialize_schnorr_signature, }; -use crate::inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig; use crate::transmutative::secp::schnorr::Bytes32; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; diff --git a/src/constructive/core_types/entities/contract/ape/encode/encode.rs b/src/constructive/core_types/entities/contract/ape/encode/encode.rs index df8be045..f6db39df 100644 --- a/src/constructive/core_types/entities/contract/ape/encode/encode.rs +++ b/src/constructive/core_types/entities/contract/ape/encode/encode.rs @@ -26,9 +26,9 @@ impl Contract { let _registry = registry.lock().await; // 3.2 Retrieve the rank value from the registry. - _registry.get_rank_by_contract_id(contract_id).ok_or( - ContractAPEEncodeError::UnableToRetrieveRankValueFromRegistry(contract_id), - )? + _registry + .get_rank_by_contract_id(contract_id) + .ok_or(ContractAPEEncodeError::UnableToRetrieveRankValueFromRegistry(contract_id))? }; // 4 Match on whether to encode the rank value as a `LongVal` or a `ShortVal`. diff --git a/src/constructive/core_types/entities/contract/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/entities/contract/ext/codec/sbe/decode/decode.rs index 21552722..f254aebe 100644 --- a/src/constructive/core_types/entities/contract/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/entities/contract/ext/codec/sbe/decode/decode.rs @@ -12,15 +12,14 @@ impl Contract { }); } - let contract_id: [u8; 32] = bytes[0..32].try_into().map_err(|_| { - ContractSBEDecodeError::ContractSBEContractIdBytesConversionError - })?; + let contract_id: [u8; 32] = bytes[0..32] + .try_into() + .map_err(|_| ContractSBEDecodeError::ContractSBEContractIdBytesConversionError)?; - let registry_index = u64::from_le_bytes( - bytes[32..40] - .try_into() - .map_err(|_| ContractSBEDecodeError::ContractSBERegistryIndexBytesConversionError)?, - ); + let registry_index = + u64::from_le_bytes(bytes[32..40].try_into().map_err(|_| { + ContractSBEDecodeError::ContractSBERegistryIndexBytesConversionError + })?); Ok(Contract::new(contract_id, registry_index)) } diff --git a/src/constructive/core_types/method_index/ext/codec/ape/encode/encode.rs b/src/constructive/core_types/method_index/ext/codec/ape/encode/encode.rs index 92177683..5592983e 100644 --- a/src/constructive/core_types/method_index/ext/codec/ape/encode/encode.rs +++ b/src/constructive/core_types/method_index/ext/codec/ape/encode/encode.rs @@ -10,10 +10,7 @@ impl MethodIndex { /// /// When `methods_len` exceeds 255, the index is written as a raw u16 (16 little-endian /// bits). Otherwise it is encoded as an [`AtomicVal`] with `methods_len` as the upper bound. - pub fn encode_ape( - &self, - methods_len: usize, - ) -> Result { + pub fn encode_ape(&self, methods_len: usize) -> Result { if methods_len > U8_METHOD_INDEX_UPPER_BOUND { Ok(BitVec::from_bytes(&self.index.to_le_bytes())) } else { diff --git a/src/constructive/core_types/method_index/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/method_index/ext/codec/sbe/decode/decode.rs index d648374f..4fe69e49 100644 --- a/src/constructive/core_types/method_index/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/method_index/ext/codec/sbe/decode/decode.rs @@ -6,12 +6,9 @@ impl MethodIndex { /// /// The buffer must be exactly two bytes (little-endian `u16` index). pub fn decode_sbe(bytes: &[u8]) -> Result { - let arr: [u8; 2] = - bytes - .try_into() - .map_err(|_| MethodIndexSBEDecodeError::MethodIndexSBEInvalidPayloadLength { - got: bytes.len(), - })?; + let arr: [u8; 2] = bytes.try_into().map_err(|_| { + MethodIndexSBEDecodeError::MethodIndexSBEInvalidPayloadLength { got: bytes.len() } + })?; Ok(MethodIndex::new(u16::from_le_bytes(arr))) } diff --git a/src/constructive/core_types/ops_budget/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/ops_budget/ext/codec/sbe/decode/decode.rs index 5fe5069f..4c723762 100644 --- a/src/constructive/core_types/ops_budget/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/ops_budget/ext/codec/sbe/decode/decode.rs @@ -15,9 +15,7 @@ impl OpsBudget { pub fn decode_sbe(bytes: &[u8]) -> Result<(OpsBudget, &[u8]), OpsBudgetSBEDecodeError> { // 1 Read the presence byte. if bytes.is_empty() { - return Err(OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { - got: 0, - }); + return Err(OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { got: 0 }); } match bytes[0] { @@ -27,9 +25,11 @@ impl OpsBudget { // 2.b Present — tier byte plus compact value bytes. 1 => { if bytes.len() < 2 { - return Err(OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { - got: bytes.len(), - }); + return Err( + OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { + got: bytes.len(), + }, + ); } let compact_len = short_val_compact_len(bytes[1]).ok_or( @@ -37,9 +37,11 @@ impl OpsBudget { )?; if bytes.len() < 2 + compact_len { - return Err(OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { - got: bytes.len(), - }); + return Err( + OpsBudgetSBEDecodeError::OpsBudgetSBEInsufficientPayloadBytes { + got: bytes.len(), + }, + ); } let budget = ShortVal::from_compact_bytes(&bytes[2..2 + compact_len]) diff --git a/src/constructive/core_types/ops_budget/ext/codec/sbe/encode/encode.rs b/src/constructive/core_types/ops_budget/ext/codec/sbe/encode/encode.rs index 985a1432..559f01ca 100644 --- a/src/constructive/core_types/ops_budget/ext/codec/sbe/encode/encode.rs +++ b/src/constructive/core_types/ops_budget/ext/codec/sbe/encode/encode.rs @@ -1,5 +1,7 @@ use crate::constructive::core_types::ops_budget::ops_budget::OpsBudget; -use crate::constructive::core_types::valtypes::val::short_val::short_val::{ShortVal, ShortValTier}; +use crate::constructive::core_types::valtypes::val::short_val::short_val::{ + ShortVal, ShortValTier, +}; type Bytes = Vec; diff --git a/src/constructive/core_types/ops_price/ext/codec/ape/decode/decode.rs b/src/constructive/core_types/ops_price/ext/codec/ape/decode/decode.rs index 6a643a23..fed0049e 100644 --- a/src/constructive/core_types/ops_price/ext/codec/ape/decode/decode.rs +++ b/src/constructive/core_types/ops_price/ext/codec/ape/decode/decode.rs @@ -26,12 +26,12 @@ impl OpsPrice { .map_err(OpsPriceAPEDecodeError::LongValAPEDecodeError)? .value(); - let ops_price_ppm = base_ops_price - .checked_add(overhead) - .ok_or(OpsPriceAPEDecodeError::OpsPriceTotalOverflow { + let ops_price_ppm = base_ops_price.checked_add(overhead).ok_or( + OpsPriceAPEDecodeError::OpsPriceTotalOverflow { base_ops_price, overhead, - })?; + }, + )?; Ok(OpsPrice::new(ops_price_ppm)) } diff --git a/src/constructive/core_types/ops_price/ext/codec/ape/encode/encode.rs b/src/constructive/core_types/ops_price/ext/codec/ape/encode/encode.rs index 09fb84a1..2d65dce2 100644 --- a/src/constructive/core_types/ops_price/ext/codec/ape/encode/encode.rs +++ b/src/constructive/core_types/ops_price/ext/codec/ape/encode/encode.rs @@ -9,10 +9,7 @@ impl OpsPrice { /// When `ops_price_ppm` equals `base_ops_price`, a single `true` bit is written. /// Otherwise a `false` bit is written followed by the overhead (`ops_price_ppm - base_ops_price`) /// as a [`LongVal`]. Encoding fails if `ops_price_ppm` is less than `base_ops_price`. - pub fn encode_ape( - &self, - base_ops_price: u32, - ) -> Result { + pub fn encode_ape(&self, base_ops_price: u32) -> Result { let base_ops_price = u64::from(base_ops_price); if self.ops_price_ppm < base_ops_price { diff --git a/src/constructive/core_types/ops_price/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/ops_price/ext/codec/sbe/decode/decode.rs index f3b73868..51863928 100644 --- a/src/constructive/core_types/ops_price/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/ops_price/ext/codec/sbe/decode/decode.rs @@ -5,12 +5,9 @@ use super::error::decode_error::OpsPriceSBEDecodeError; impl OpsPrice { /// Decodes an `OpsPrice` from Structural Byte-scope Encoding (SBE) bytes produced by [`OpsPrice::encode_sbe`]. pub fn decode_sbe(bytes: &[u8]) -> Result { - let arr: [u8; 8] = - bytes - .try_into() - .map_err(|_| OpsPriceSBEDecodeError::OpsPriceSBEInvalidPayloadLength { - got: bytes.len(), - })?; + let arr: [u8; 8] = bytes.try_into().map_err(|_| { + OpsPriceSBEDecodeError::OpsPriceSBEInvalidPayloadLength { got: bytes.len() } + })?; Ok(OpsPrice::new(u64::from_le_bytes(arr))) } diff --git a/src/constructive/core_types/ops_price/ops_price.rs b/src/constructive/core_types/ops_price/ops_price.rs index 04b9ceea..e080c760 100644 --- a/src/constructive/core_types/ops_price/ops_price.rs +++ b/src/constructive/core_types/ops_price/ops_price.rs @@ -11,4 +11,4 @@ impl OpsPrice { pub fn new(ops_price_ppm: u64) -> OpsPrice { OpsPrice { ops_price_ppm } } -} \ No newline at end of file +} diff --git a/src/constructive/core_types/target/ext/codec/ape/decode/error/mod.rs b/src/constructive/core_types/target/ext/codec/ape/decode/error/mod.rs index 58cd63ca..a16f767b 100644 --- a/src/constructive/core_types/target/ext/codec/ape/decode/error/mod.rs +++ b/src/constructive/core_types/target/ext/codec/ape/decode/error/mod.rs @@ -1 +1 @@ -pub mod decode_error; \ No newline at end of file +pub mod decode_error; diff --git a/src/constructive/core_types/target/ext/codec/ape/decode/mod.rs b/src/constructive/core_types/target/ext/codec/ape/decode/mod.rs index cc514610..9a740781 100644 --- a/src/constructive/core_types/target/ext/codec/ape/decode/mod.rs +++ b/src/constructive/core_types/target/ext/codec/ape/decode/mod.rs @@ -1,2 +1,2 @@ pub mod decode; -pub mod error; \ No newline at end of file +pub mod error; diff --git a/src/constructive/core_types/target/ext/codec/ape/encode/encode.rs b/src/constructive/core_types/target/ext/codec/ape/encode/encode.rs index a52502cf..5329fb70 100644 --- a/src/constructive/core_types/target/ext/codec/ape/encode/encode.rs +++ b/src/constructive/core_types/target/ext/codec/ape/encode/encode.rs @@ -9,10 +9,7 @@ impl Target { /// When `execution_batch_height` equals `targeted_at_batch_height`, a single `false` bit /// indicates full overlap. Otherwise a `true` bit and two further bits encode the batch gap /// between execution and target heights in the range 1..=4 (`00`..=`11` map to gaps 1..=4). - pub fn encode_ape( - &self, - execution_batch_height: u64, - ) -> Result { + pub fn encode_ape(&self, execution_batch_height: u64) -> Result { // 1 Get `targeted_at_batch_height` from `self`. let targeted = self.targeted_at_batch_height; diff --git a/src/constructive/core_types/target/ext/codec/ape/encode/error/mod.rs b/src/constructive/core_types/target/ext/codec/ape/encode/error/mod.rs index 561ec315..4c6cc627 100644 --- a/src/constructive/core_types/target/ext/codec/ape/encode/error/mod.rs +++ b/src/constructive/core_types/target/ext/codec/ape/encode/error/mod.rs @@ -1 +1 @@ -pub mod encode_error; \ No newline at end of file +pub mod encode_error; diff --git a/src/constructive/core_types/target/ext/codec/ape/encode/mod.rs b/src/constructive/core_types/target/ext/codec/ape/encode/mod.rs index 56774f3f..15eeefa6 100644 --- a/src/constructive/core_types/target/ext/codec/ape/encode/mod.rs +++ b/src/constructive/core_types/target/ext/codec/ape/encode/mod.rs @@ -1,2 +1,2 @@ pub mod encode; -pub mod error; \ No newline at end of file +pub mod error; diff --git a/src/constructive/core_types/target/ext/codec/sbe/decode/decode.rs b/src/constructive/core_types/target/ext/codec/sbe/decode/decode.rs index 044ebc5a..ffeb561a 100644 --- a/src/constructive/core_types/target/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/core_types/target/ext/codec/sbe/decode/decode.rs @@ -8,9 +8,12 @@ impl Target { /// The buffer must be exactly eight bytes (little-endian `u64` batch height). pub fn decode_sbe(bytes: &[u8]) -> Result { // 1 Require exactly eight bytes for the little-endian `u64`. - let arr: [u8; 8] = bytes.try_into().map_err(|_| TargetSBEDecodeError::TargetSBEInvalidPayloadLength { - got: bytes.len(), - })?; + let arr: [u8; 8] = + bytes + .try_into() + .map_err(|_| TargetSBEDecodeError::TargetSBEInvalidPayloadLength { + got: bytes.len(), + })?; // 2 Decode the height and construct the `Target`. Ok(Target::new(u64::from_le_bytes(arr))) diff --git a/src/constructive/core_types/valtypes/maybe_common/common/common_long/mod.rs b/src/constructive/core_types/valtypes/maybe_common/common/common_long/mod.rs index aad6b331..93b8525b 100644 --- a/src/constructive/core_types/valtypes/maybe_common/common/common_long/mod.rs +++ b/src/constructive/core_types/valtypes/maybe_common/common/common_long/mod.rs @@ -1,2 +1,2 @@ -pub mod common_long; pub mod ape; +pub mod common_long; diff --git a/src/constructive/core_types/valtypes/val/long_val/ape/encode/encode.rs b/src/constructive/core_types/valtypes/val/long_val/ape/encode/encode.rs index 0f948545..e3280cd0 100644 --- a/src/constructive/core_types/valtypes/val/long_val/ape/encode/encode.rs +++ b/src/constructive/core_types/valtypes/val/long_val/ape/encode/encode.rs @@ -1,6 +1,4 @@ -use crate::constructive::core_types::valtypes::val::long_val::long_val::{ - LongVal, LongValTier, -}; +use crate::constructive::core_types::valtypes::val::long_val::long_val::{LongVal, LongValTier}; use bit_vec::BitVec; /// Airly Payload Encoding (APE) encoding for `LongVal`. diff --git a/src/constructive/entries/entry/entry.rs b/src/constructive/entries/entry/entry.rs index f5e2ba07..6dd2d72a 100644 --- a/src/constructive/entries/entry/entry.rs +++ b/src/constructive/entries/entry/entry.rs @@ -1,10 +1,10 @@ -use crate::{constructive::entry::entry_kinds::call::call::Call, transmutative::hash::Hash}; use crate::constructive::entry::entry_kinds::config::config::Config; use crate::constructive::entry::entry_kinds::deploy::deploy::Deploy; use crate::constructive::entry::entry_kinds::liftup::liftup::Liftup; use crate::constructive::entry::entry_kinds::r#move::r#move::Move; use crate::constructive::entry::entry_kinds::swapout::swapout::Swapout; use crate::transmutative::hash::HashTag; +use crate::{constructive::entry::entry_kinds::call::call::Call, transmutative::hash::Hash}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -115,7 +115,7 @@ impl Entry { // 6 Return the hash. Some(hash) - }, + } Entry::Swapout(swapout) => { let mut preimage = Vec::::new(); preimage.extend(batch_height.to_le_bytes()); diff --git a/src/constructive/entries/entry/ext/codec/ape/decode/decode.rs b/src/constructive/entries/entry/ext/codec/ape/decode/decode.rs index 05f5f291..a0e147ae 100644 --- a/src/constructive/entries/entry/ext/codec/ape/decode/decode.rs +++ b/src/constructive/entries/entry/ext/codec/ape/decode/decode.rs @@ -165,7 +165,7 @@ impl Entry { .await .map_err(EntryAPEDecodeError::SwapoutEntryAPEDecodeError)?; Entry::Swapout(swapout_entry) - }, + } } } @@ -181,9 +181,9 @@ impl Entry { // 2.b.2.b.1.b.1.a The `Entry` is in the `Outer Lowermost Branch`. false => { // 2.b.2.b.1.b.1.a.1 Collect one bit to determine if the `Entry` is a `Deploy` or a `Config`. - let deploy_or_config_bit = bit_stream - .next() - .ok_or(EntryAPEDecodeError::DeployOrConfigBitCollectError)?; + let deploy_or_config_bit = bit_stream.next().ok_or( + EntryAPEDecodeError::DeployOrConfigBitCollectError, + )?; // 2.b.2.b.1.b.1.a.2 Match on whether the `Entry` is a `Deploy` or a `Config`. match deploy_or_config_bit { @@ -237,7 +237,8 @@ impl Entry { let collected_bits = match (decode_start_stream, decode_start_remaining) { (Some(mut start_stream), Some(start_remaining)) => { let consumed_bits_len = start_remaining.saturating_sub(bit_stream.len()); - let consumed_bits: bit_vec::BitVec = start_stream.by_ref().take(consumed_bits_len).collect(); + let consumed_bits: bit_vec::BitVec = + start_stream.by_ref().take(consumed_bits_len).collect(); Some(consumed_bits) } _ => None, diff --git a/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs index 245f2e64..c1c19f4f 100644 --- a/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs @@ -1,5 +1,5 @@ -use crate::constructive::entry::entry::ext::codec::ape::encode::error::encode_error::EntryAPEEncodeError; use crate::constructive::entry::entry::entry::Entry; +use crate::constructive::entry::entry::ext::codec::ape::encode::error::encode_error::EntryAPEEncodeError; use crate::inscriptive::registry::registry::REGISTRY; use bit_vec::BitVec; diff --git a/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs index 56b76207..5a6717dc 100644 --- a/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs @@ -23,15 +23,15 @@ impl Entry { match entry_kind_byte { // 3.a `Move` (`0x00`): decode from the full buffer (`Move::decode_sbe` consumes the tag). 0x00 => { - let move_entry = Move::decode_sbe(bytes) - .map_err(EntrySBEDecodeError::MoveSBEDecodeError)?; + let move_entry = + Move::decode_sbe(bytes).map_err(EntrySBEDecodeError::MoveSBEDecodeError)?; Ok(Entry::Move(move_entry)) } 0x01 => { - let call = Call::decode_sbe(bytes) - .map_err(EntrySBEDecodeError::CallSBEDecodeError)?; + let call = + Call::decode_sbe(bytes).map_err(EntrySBEDecodeError::CallSBEDecodeError)?; Ok(Entry::Call(call)) } @@ -48,13 +48,13 @@ impl Entry { Ok(Entry::Swapout(swapout)) } 0x06 => { - let deploy = Deploy::decode_sbe(bytes) - .map_err(EntrySBEDecodeError::DeploySBEDecodeError)?; + let deploy = + Deploy::decode_sbe(bytes).map_err(EntrySBEDecodeError::DeploySBEDecodeError)?; Ok(Entry::Deploy(deploy)) } 0x07 => { - let config = Config::decode_sbe(bytes) - .map_err(EntrySBEDecodeError::ConfigSBEDecodeError)?; + let config = + Config::decode_sbe(bytes).map_err(EntrySBEDecodeError::ConfigSBEDecodeError)?; Ok(Entry::Config(config)) } diff --git a/src/constructive/entries/entry/ext/codec/sbe/encode/error/encode_error.rs b/src/constructive/entries/entry/ext/codec/sbe/encode/error/encode_error.rs index d281475b..0374fa7d 100644 --- a/src/constructive/entries/entry/ext/codec/sbe/encode/error/encode_error.rs +++ b/src/constructive/entries/entry/ext/codec/sbe/encode/error/encode_error.rs @@ -14,5 +14,4 @@ pub enum EntrySBEEncodeError { SwapoutSBEEncodeError(SwapoutSBEEncodeError), DeploySBEEncodeError(DeploySBEEncodeError), ConfigSBEEncodeError(ConfigSBEEncodeError), - } diff --git a/src/constructive/entries/entry_fees/entry_fees.rs b/src/constructive/entries/entry_fees/entry_fees.rs index 4563887d..e7bb4307 100644 --- a/src/constructive/entries/entry_fees/entry_fees.rs +++ b/src/constructive/entries/entry_fees/entry_fees.rs @@ -84,9 +84,15 @@ impl EntryFees { total_pre_subsidy, subsidy_breakdown, } => { - obj.insert("entry_kind".to_string(), Value::String("liftup".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("liftup".to_string()), + ); obj.insert("base_fee".to_string(), Value::Number((*base_fee).into())); - obj.insert("per_lift_fee".to_string(), Value::Number((*per_lift_fee).into())); + obj.insert( + "per_lift_fee".to_string(), + Value::Number((*per_lift_fee).into()), + ); obj.insert( "total_pre_subsidy".to_string(), Value::Number((*total_pre_subsidy).into()), @@ -110,17 +116,17 @@ impl EntryFees { "total_pre_subsidy".to_string(), Value::Number((*total_pre_subsidy).into()), ); - obj.insert( - "subsidy_breakdown".to_string(), - subsidy_breakdown.json(), - ); + obj.insert("subsidy_breakdown".to_string(), subsidy_breakdown.json()); } EntryFees::Swapout { base_fee, total_pre_subsidy, subsidy_breakdown, } => { - obj.insert("entry_kind".to_string(), Value::String("swapout".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("swapout".to_string()), + ); obj.insert("base_fee".to_string(), Value::Number((*base_fee).into())); obj.insert( "total_pre_subsidy".to_string(), @@ -142,7 +148,10 @@ impl EntryFees { projector_config_updated, flame_config_updated, } => { - obj.insert("entry_kind".to_string(), Value::String("config".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("config".to_string()), + ); obj.insert("base_fee".to_string(), Value::Number((*base_fee).into())); obj.insert( "total_pre_subsidy".to_string(), @@ -176,7 +185,10 @@ impl EntryFees { program_bytes_len, contract_id, } => { - obj.insert("entry_kind".to_string(), Value::String("deploy".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("deploy".to_string()), + ); obj.insert("base_fee".to_string(), Value::Number((*base_fee).into())); obj.insert( "total_pre_subsidy".to_string(), diff --git a/src/constructive/entries/entry_kinds/call/ext/codec/ape/decode/decode.rs b/src/constructive/entries/entry_kinds/call/ext/codec/ape/decode/decode.rs index f6c96970..35f3fa88 100644 --- a/src/constructive/entries/entry_kinds/call/ext/codec/ape/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/call/ext/codec/ape/decode/decode.rs @@ -1,3 +1,4 @@ +use crate::constructive::calldata::element::ape::decode::error::decode_errors::CalldataElementAPEDecodeError; use crate::constructive::calldata::element_type::CalldataElementType; use crate::constructive::core_types::calldata::calldata_elements::calldata_element::CalldataElement; use crate::constructive::core_types::method_index::method_index::MethodIndex; @@ -6,9 +7,8 @@ use crate::constructive::core_types::ops_price::ops_price::OpsPrice; use crate::constructive::core_types::target::target::Target; use crate::constructive::entity::account::root_account::root_account::RootAccount; use crate::constructive::entity::contract::contract::Contract; -use crate::constructive::calldata::element::ape::decode::error::decode_errors::CalldataElementAPEDecodeError; -use crate::constructive::entry::entry_kinds::call::ext::codec::ape::decode::error::decode_error::CallEntryAPEDecodeError; use crate::constructive::entry::entry_kinds::call::call::Call; +use crate::constructive::entry::entry_kinds::call::ext::codec::ape::decode::error::decode_error::CallEntryAPEDecodeError; use crate::constructive::valtype::val::short_val::short_val::ShortVal; use crate::inscriptive::registry::registry::REGISTRY; @@ -22,13 +22,10 @@ impl Call { decode_contract_rank_as_longval: bool, registry: ®ISTRY, ) -> Result { - let account: RootAccount = RootAccount::decode_ape( - bit_stream, - decode_account_rank_as_longval, - registry, - ) - .await - .map_err(CallEntryAPEDecodeError::AccountAPEDecodeError)?; + let account: RootAccount = + RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) + .await + .map_err(CallEntryAPEDecodeError::AccountAPEDecodeError)?; let contract: Contract = Contract::decode_ape(bit_stream, registry, decode_contract_rank_as_longval) @@ -58,10 +55,12 @@ impl Call { contract_id, method_index.index(), ) - .ok_or(CallEntryAPEDecodeError::UnableToRetrieveMethodArgTypesFromRegistry { - contract_id, - method_index: method_index.index(), - })? + .ok_or( + CallEntryAPEDecodeError::UnableToRetrieveMethodArgTypesFromRegistry { + contract_id, + method_index: method_index.index(), + }, + )? }; let calldata_count = ShortVal::decode_ape(bit_stream) @@ -83,22 +82,16 @@ impl Call { _ => false, }; - let calldata_element = CalldataElement::decode_ape( - bit_stream, - arg_type, - registry, - decode_rank_as_longval, - ) - .await - .map_err(CallEntryAPEDecodeError::CalldataElementAPEDecodeError)?; - - calldata_element - .validate() - .map_err(|e| { - CallEntryAPEDecodeError::CalldataElementAPEDecodeError( - CalldataElementAPEDecodeError::ValidationError(e), - ) - })?; + let calldata_element = + CalldataElement::decode_ape(bit_stream, arg_type, registry, decode_rank_as_longval) + .await + .map_err(CallEntryAPEDecodeError::CalldataElementAPEDecodeError)?; + + calldata_element.validate().map_err(|e| { + CallEntryAPEDecodeError::CalldataElementAPEDecodeError( + CalldataElementAPEDecodeError::ValidationError(e), + ) + })?; calldata_elements.push(calldata_element); } diff --git a/src/constructive/entries/entry_kinds/call/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry_kinds/call/ext/codec/ape/encode/encode.rs index fa5df651..20fd383c 100644 --- a/src/constructive/entries/entry_kinds/call/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry_kinds/call/ext/codec/ape/encode/encode.rs @@ -1,5 +1,5 @@ -use crate::constructive::entry::entry_kinds::call::ext::codec::ape::encode::error::encode_error::CallAPEEncodeError; use crate::constructive::entry::entry_kinds::call::call::Call; +use crate::constructive::entry::entry_kinds::call::ext::codec::ape::encode::error::encode_error::CallAPEEncodeError; use crate::constructive::valtype::val::short_val::short_val::ShortVal; use crate::inscriptive::registry::registry::REGISTRY; use bit_vec::BitVec; @@ -36,9 +36,9 @@ impl Call { let _registry = registry.lock().await; _registry .get_contract_methods_len_by_contract_id(contract_id) - .ok_or(CallAPEEncodeError::UnableToRetrieveContractMethodsLenFromRegistry( - contract_id, - ))? + .ok_or( + CallAPEEncodeError::UnableToRetrieveContractMethodsLenFromRegistry(contract_id), + )? }; bits.extend( @@ -54,10 +54,12 @@ impl Call { contract_id, self.method_index.index(), ) - .ok_or(CallAPEEncodeError::UnableToRetrieveMethodArgTypesFromRegistry { - contract_id, - method_index: self.method_index.index(), - })? + .ok_or( + CallAPEEncodeError::UnableToRetrieveMethodArgTypesFromRegistry { + contract_id, + method_index: self.method_index.index(), + }, + )? }; if self.calldata_elements.len() != arg_types.len() { @@ -67,9 +69,7 @@ impl Call { }); } - bits.extend( - ShortVal::new(self.calldata_elements.len() as u32).encode_ape(), - ); + bits.extend(ShortVal::new(self.calldata_elements.len() as u32).encode_ape()); for calldata_element in self.calldata_elements.iter() { calldata_element diff --git a/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/error/decode_error.rs b/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/error/decode_error.rs index 1dd05880..d2d51fe5 100644 --- a/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/error/decode_error.rs +++ b/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/error/decode_error.rs @@ -9,33 +9,52 @@ use crate::constructive::entity::contract::ext::codec::sbe::decode::error::decod /// Errors that can occur when decoding a `Call` from Structural Byte-scope Encoding (SBE) bytes. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum CallSBEDecodeError { - InvalidEntryKindByteError { expected: u8, got: u8 }, - CallSBEInsufficientBytesForRootAccountLengthPrefix { got_total: usize }, + InvalidEntryKindByteError { + expected: u8, + got: u8, + }, + CallSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: usize, + }, CallSBELengthPrefixBytesConversionError, CallSBERootAccountLengthPrefixExceedsPayload { root_len: usize, got_after_prefix: usize, }, CallSBERootAccount(RootAccountSBEDecodeError), - CallSBEInsufficientBytesForContractLengthPrefix { got_total: usize }, + CallSBEInsufficientBytesForContractLengthPrefix { + got_total: usize, + }, CallSBEContractLengthPrefixExceedsPayload { contract_len: usize, got_after_prefix: usize, }, CallSBEContract(ContractSBEDecodeError), - CallSBEInsufficientBytesForMethodIndex { got_total: usize }, + CallSBEInsufficientBytesForMethodIndex { + got_total: usize, + }, CallSBEMethodIndex(MethodIndexSBEDecodeError), - CallSBEInsufficientBytesForCalldataLengthPrefix { got_total: usize }, + CallSBEInsufficientBytesForCalldataLengthPrefix { + got_total: usize, + }, CallSBECalldataLengthPrefixExceedsPayload { calldata_len: usize, got_after_prefix: usize, }, CallSBECalldata(CalldataElementsSBEDecodeError), - CallSBEInsufficientBytesForOpsBudget { got_total: usize }, + CallSBEInsufficientBytesForOpsBudget { + got_total: usize, + }, CallSBEOpsBudget(OpsBudgetSBEDecodeError), - CallSBEInsufficientBytesForOpsPrice { got_total: usize }, + CallSBEInsufficientBytesForOpsPrice { + got_total: usize, + }, CallSBEOpsPrice(OpsPriceSBEDecodeError), - CallSBEInsufficientBytesForTarget { got_total: usize }, + CallSBEInsufficientBytesForTarget { + got_total: usize, + }, CallSBETarget(TargetSBEDecodeError), - CallSBETrailingBytesAfterCall { trailing: usize }, + CallSBETrailingBytesAfterCall { + trailing: usize, + }, } diff --git a/src/constructive/entries/entry_kinds/config/config.rs b/src/constructive/entries/entry_kinds/config/config.rs index 363d8750..51640186 100644 --- a/src/constructive/entries/entry_kinds/config/config.rs +++ b/src/constructive/entries/entry_kinds/config/config.rs @@ -40,7 +40,10 @@ impl Config { /// Returns the config entry as a JSON object. pub fn json(&self) -> Value { let mut obj = Map::new(); - obj.insert("entry_kind".to_string(), Value::String("config".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("config".to_string()), + ); obj.insert("root_account".to_string(), self.root_account.json()); obj.insert( "secondary_aggregation_key".to_string(), diff --git a/src/constructive/entries/entry_kinds/config/ext/codec/ape/decode/decode.rs b/src/constructive/entries/entry_kinds/config/ext/codec/ape/decode/decode.rs index b1edcb14..c18fd722 100644 --- a/src/constructive/entries/entry_kinds/config/ext/codec/ape/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/config/ext/codec/ape/decode/decode.rs @@ -15,9 +15,10 @@ impl Config { decode_account_rank_as_longval: bool, registry: ®ISTRY, ) -> Result { - let root_account = RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) - .await - .map_err(ConfigAPEDecodeError::RootAccountAPEDecodeError)?; + let root_account = + RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) + .await + .map_err(ConfigAPEDecodeError::RootAccountAPEDecodeError)?; let secondary_aggregation_key_present = bit_stream .next() diff --git a/src/constructive/entries/entry_kinds/config/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry_kinds/config/ext/codec/ape/encode/encode.rs index e7ad65c8..2b1775fe 100644 --- a/src/constructive/entries/entry_kinds/config/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry_kinds/config/ext/codec/ape/encode/encode.rs @@ -24,8 +24,9 @@ impl Config { match &self.secondary_aggregation_key { Some(key) => { bits.push(true); - let key_len = u32::try_from(key.len()) - .map_err(|_| ConfigAPEEncodeError::SecondaryAggregationKeyLenTooLarge(key.len()))?; + let key_len = u32::try_from(key.len()).map_err(|_| { + ConfigAPEEncodeError::SecondaryAggregationKeyLenTooLarge(key.len()) + })?; bits.extend(ShortVal::new(key_len).encode_ape()); bits.extend(BitVec::from_bytes(key)); } @@ -44,8 +45,9 @@ impl Config { Some(flame_config) => { bits.push(true); let flame_config_bytes = flame_config.to_bytes(); - let flame_len = u32::try_from(flame_config_bytes.len()) - .map_err(|_| ConfigAPEEncodeError::FlameConfigLenTooLarge(flame_config_bytes.len()))?; + let flame_len = u32::try_from(flame_config_bytes.len()).map_err(|_| { + ConfigAPEEncodeError::FlameConfigLenTooLarge(flame_config_bytes.len()) + })?; bits.extend(ShortVal::new(flame_len).encode_ape()); bits.extend(BitVec::from_bytes(&flame_config_bytes)); } diff --git a/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/decode.rs index 9f846f4b..ecebd7eb 100644 --- a/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/decode.rs @@ -8,9 +8,11 @@ impl Config { /// Decodes a `Config` from Structural Byte-scope Encoding (SBE) bytes. pub fn decode_sbe(bytes: &[u8]) -> Result { if bytes.is_empty() { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForRootAccountLengthPrefix { - got_total: 0, - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: 0, + }, + ); } if bytes[0] != 0x07 { return Err(ConfigSBEDecodeError::InvalidEntryKindByteError { @@ -20,21 +22,23 @@ impl Config { } if bytes.len() < 5 { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForRootAccountLengthPrefix { - got_total: bytes.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: bytes.len(), + }, + ); } - let root_len = u32::from_le_bytes( - bytes[1..5] - .try_into() - .map_err(|_| ConfigSBEDecodeError::ConfigSBERootAccountLengthPrefixBytesConversionError)?, - ) as usize; + let root_len = u32::from_le_bytes(bytes[1..5].try_into().map_err(|_| { + ConfigSBEDecodeError::ConfigSBERootAccountLengthPrefixBytesConversionError + })?) as usize; let after_root_len_prefix = &bytes[5..]; if after_root_len_prefix.len() < root_len { - return Err(ConfigSBEDecodeError::ConfigSBERootAccountLengthPrefixExceedsPayload { - root_len, - got_after_prefix: after_root_len_prefix.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBERootAccountLengthPrefixExceedsPayload { + root_len, + got_after_prefix: after_root_len_prefix.len(), + }, + ); } let (root_slice, mut tail) = after_root_len_prefix.split_at(root_len); let root_account = RootAccount::decode_sbe(root_slice) @@ -55,17 +59,17 @@ impl Config { got_total: bytes.len(), }); } - let secondary_len = u32::from_le_bytes( - tail[0..4] - .try_into() - .map_err(|_| ConfigSBEDecodeError::ConfigSBESecondaryAggregationLengthPrefixBytesConversionError)?, - ) as usize; + let secondary_len = u32::from_le_bytes(tail[0..4].try_into().map_err(|_| { + ConfigSBEDecodeError::ConfigSBESecondaryAggregationLengthPrefixBytesConversionError + })?) as usize; tail = &tail[4..]; if tail.len() < secondary_len { - return Err(ConfigSBEDecodeError::ConfigSBESecondaryAggregationLengthPrefixExceedsPayload { - key_len: secondary_len, - got_after_prefix: tail.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBESecondaryAggregationLengthPrefixExceedsPayload { + key_len: secondary_len, + got_after_prefix: tail.len(), + }, + ); } let (secondary_slice, tail_after_secondary) = tail.split_at(secondary_len); let secondary_aggregation_key = if secondary_present { @@ -83,17 +87,21 @@ impl Config { tail = tail_after_secondary; if tail.is_empty() { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForProjectorConfigPresenceFlag { - got_total: bytes.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForProjectorConfigPresenceFlag { + got_total: bytes.len(), + }, + ); } let projector_present = tail[0] != 0; tail = &tail[1..]; let projector_config = if projector_present { if tail.len() < 32 { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForProjectorConfigPayload { - got_total: bytes.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForProjectorConfigPayload { + got_total: bytes.len(), + }, + ); } let projector_bytes: [u8; 32] = tail[0..32] .try_into() @@ -105,29 +113,33 @@ impl Config { }; if tail.is_empty() { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForFlameConfigPresenceFlag { - got_total: bytes.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForFlameConfigPresenceFlag { + got_total: bytes.len(), + }, + ); } let flame_present = tail[0] != 0; tail = &tail[1..]; if tail.len() < 4 { - return Err(ConfigSBEDecodeError::ConfigSBEInsufficientBytesForFlameConfigLengthPrefix { - got_total: bytes.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEInsufficientBytesForFlameConfigLengthPrefix { + got_total: bytes.len(), + }, + ); } - let flame_len = u32::from_le_bytes( - tail[0..4] - .try_into() - .map_err(|_| ConfigSBEDecodeError::ConfigSBEFlameConfigLengthPrefixBytesConversionError)?, - ) as usize; + let flame_len = u32::from_le_bytes(tail[0..4].try_into().map_err(|_| { + ConfigSBEDecodeError::ConfigSBEFlameConfigLengthPrefixBytesConversionError + })?) as usize; tail = &tail[4..]; if tail.len() < flame_len { - return Err(ConfigSBEDecodeError::ConfigSBEFlameConfigLengthPrefixExceedsPayload { - flame_len, - got_after_prefix: tail.len(), - }); + return Err( + ConfigSBEDecodeError::ConfigSBEFlameConfigLengthPrefixExceedsPayload { + flame_len, + got_after_prefix: tail.len(), + }, + ); } let (flame_slice, tail_after_flame) = tail.split_at(flame_len); let flame_config = if flame_present { @@ -136,9 +148,9 @@ impl Config { .map(Some)? } else { if flame_len != 0 { - return Err(ConfigSBEDecodeError::ConfigSBEFlameConfigPresenceLengthMismatch { - flame_len, - }); + return Err( + ConfigSBEDecodeError::ConfigSBEFlameConfigPresenceLengthMismatch { flame_len }, + ); } None }; diff --git a/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/error/decode_error.rs b/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/error/decode_error.rs index d9822aed..92e36943 100644 --- a/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/error/decode_error.rs +++ b/src/constructive/entries/entry_kinds/config/ext/codec/sbe/decode/error/decode_error.rs @@ -4,26 +4,60 @@ use crate::constructive::core_types::target::ext::codec::sbe::decode::error::dec /// Errors that can occur when decoding a `Config` from Structural Byte-scope Encoding (SBE) bytes. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ConfigSBEDecodeError { - InvalidEntryKindByteError { expected: u8, got: u8 }, - ConfigSBEInsufficientBytesForRootAccountLengthPrefix { got_total: usize }, + InvalidEntryKindByteError { + expected: u8, + got: u8, + }, + ConfigSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: usize, + }, ConfigSBERootAccountLengthPrefixBytesConversionError, - ConfigSBERootAccountLengthPrefixExceedsPayload { root_len: usize, got_after_prefix: usize }, + ConfigSBERootAccountLengthPrefixExceedsPayload { + root_len: usize, + got_after_prefix: usize, + }, ConfigSBERootAccountDecodeError(RootAccountSBEDecodeError), - ConfigSBEInsufficientBytesForSecondaryAggregationPresenceFlag { got_total: usize }, - ConfigSBEInsufficientBytesForSecondaryAggregationLengthPrefix { got_total: usize }, + ConfigSBEInsufficientBytesForSecondaryAggregationPresenceFlag { + got_total: usize, + }, + ConfigSBEInsufficientBytesForSecondaryAggregationLengthPrefix { + got_total: usize, + }, ConfigSBESecondaryAggregationLengthPrefixBytesConversionError, - ConfigSBESecondaryAggregationLengthPrefixExceedsPayload { key_len: usize, got_after_prefix: usize }, - ConfigSBESecondaryAggregationPresenceLengthMismatch { key_len: usize }, - ConfigSBEInsufficientBytesForProjectorConfigPresenceFlag { got_total: usize }, - ConfigSBEInsufficientBytesForProjectorConfigPayload { got_total: usize }, + ConfigSBESecondaryAggregationLengthPrefixExceedsPayload { + key_len: usize, + got_after_prefix: usize, + }, + ConfigSBESecondaryAggregationPresenceLengthMismatch { + key_len: usize, + }, + ConfigSBEInsufficientBytesForProjectorConfigPresenceFlag { + got_total: usize, + }, + ConfigSBEInsufficientBytesForProjectorConfigPayload { + got_total: usize, + }, ConfigSBEProjectorConfigPresenceMismatch, - ConfigSBEInsufficientBytesForFlameConfigPresenceFlag { got_total: usize }, - ConfigSBEInsufficientBytesForFlameConfigLengthPrefix { got_total: usize }, + ConfigSBEInsufficientBytesForFlameConfigPresenceFlag { + got_total: usize, + }, + ConfigSBEInsufficientBytesForFlameConfigLengthPrefix { + got_total: usize, + }, ConfigSBEFlameConfigLengthPrefixBytesConversionError, - ConfigSBEFlameConfigLengthPrefixExceedsPayload { flame_len: usize, got_after_prefix: usize }, + ConfigSBEFlameConfigLengthPrefixExceedsPayload { + flame_len: usize, + got_after_prefix: usize, + }, ConfigSBEFlameConfigDecodeError, - ConfigSBEFlameConfigPresenceLengthMismatch { flame_len: usize }, - ConfigSBEInsufficientBytesForTarget { got_total: usize }, + ConfigSBEFlameConfigPresenceLengthMismatch { + flame_len: usize, + }, + ConfigSBEInsufficientBytesForTarget { + got_total: usize, + }, ConfigSBETargetDecodeError(TargetSBEDecodeError), - ConfigSBETrailingBytesAfterConfig { trailing: usize }, + ConfigSBETrailingBytesAfterConfig { + trailing: usize, + }, } diff --git a/src/constructive/entries/entry_kinds/deploy/deploy.rs b/src/constructive/entries/entry_kinds/deploy/deploy.rs index bb0a1d77..22913720 100644 --- a/src/constructive/entries/entry_kinds/deploy/deploy.rs +++ b/src/constructive/entries/entry_kinds/deploy/deploy.rs @@ -19,7 +19,12 @@ pub struct Deploy { impl Deploy { /// Creates a new `Deploy` entry kind. - pub fn new(root_account: RootAccount, program: Program, initial_balance: u32, target: Target) -> Self { + pub fn new( + root_account: RootAccount, + program: Program, + initial_balance: u32, + target: Target, + ) -> Self { Self { root_account, program, @@ -31,7 +36,10 @@ impl Deploy { /// Returns the deploy entry as a JSON object. pub fn json(&self) -> Value { let mut obj = Map::new(); - obj.insert("entry_kind".to_string(), Value::String("deploy".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("deploy".to_string()), + ); obj.insert("root_account".to_string(), self.root_account.json()); obj.insert("program".to_string(), self.program.json()); obj.insert( diff --git a/src/constructive/entries/entry_kinds/deploy/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry_kinds/deploy/ext/codec/ape/encode/encode.rs index ecffb6f9..d01e1b16 100644 --- a/src/constructive/entries/entry_kinds/deploy/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry_kinds/deploy/ext/codec/ape/encode/encode.rs @@ -26,8 +26,8 @@ impl Deploy { .program .compile() .map_err(|_| DeployAPEEncodeError::ProgramCompileError)?; - let program_len = - u32::try_from(program_bytes.len()).map_err(|_| DeployAPEEncodeError::ProgramLenTooLarge(program_bytes.len()))?; + let program_len = u32::try_from(program_bytes.len()) + .map_err(|_| DeployAPEEncodeError::ProgramLenTooLarge(program_bytes.len()))?; bits.extend(ShortVal::new(program_len).encode_ape()); bits.extend(BitVec::from_bytes(&program_bytes)); diff --git a/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/decode.rs index 2f485b98..61958e7b 100644 --- a/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/decode.rs @@ -9,9 +9,11 @@ impl Deploy { /// Decodes a `Deploy` from Structural Byte-scope Encoding (SBE) bytes. pub fn decode_sbe(bytes: &[u8]) -> Result { if bytes.is_empty() { - return Err(DeploySBEDecodeError::DeploySBEInsufficientBytesForRootAccountLengthPrefix { - got_total: 0, - }); + return Err( + DeploySBEDecodeError::DeploySBEInsufficientBytesForRootAccountLengthPrefix { + got_total: 0, + }, + ); } if bytes[0] != 0x06 { return Err(DeploySBEDecodeError::InvalidEntryKindByteError { @@ -21,42 +23,47 @@ impl Deploy { } if bytes.len() < 5 { - return Err(DeploySBEDecodeError::DeploySBEInsufficientBytesForRootAccountLengthPrefix { - got_total: bytes.len(), - }); + return Err( + DeploySBEDecodeError::DeploySBEInsufficientBytesForRootAccountLengthPrefix { + got_total: bytes.len(), + }, + ); } - let root_len = u32::from_le_bytes( - bytes[1..5] - .try_into() - .map_err(|_| DeploySBEDecodeError::DeploySBERootAccountLengthPrefixBytesConversionError)?, - ) as usize; + let root_len = u32::from_le_bytes(bytes[1..5].try_into().map_err(|_| { + DeploySBEDecodeError::DeploySBERootAccountLengthPrefixBytesConversionError + })?) as usize; let after_root_len_prefix = &bytes[5..]; if after_root_len_prefix.len() < root_len { - return Err(DeploySBEDecodeError::DeploySBERootAccountLengthPrefixExceedsPayload { - root_len, - got_after_prefix: after_root_len_prefix.len(), - }); + return Err( + DeploySBEDecodeError::DeploySBERootAccountLengthPrefixExceedsPayload { + root_len, + got_after_prefix: after_root_len_prefix.len(), + }, + ); } let (root_slice, mut tail) = after_root_len_prefix.split_at(root_len); let root_account = RootAccount::decode_sbe(root_slice) .map_err(DeploySBEDecodeError::DeploySBERootAccountDecodeError)?; if tail.len() < 4 { - return Err(DeploySBEDecodeError::DeploySBEInsufficientBytesForProgramLengthPrefix { - got_total: bytes.len(), - }); + return Err( + DeploySBEDecodeError::DeploySBEInsufficientBytesForProgramLengthPrefix { + got_total: bytes.len(), + }, + ); } - let program_len = u32::from_le_bytes( - tail[0..4] - .try_into() - .map_err(|_| DeploySBEDecodeError::DeploySBEProgramLengthPrefixBytesConversionError)?, - ) as usize; + let program_len = + u32::from_le_bytes(tail[0..4].try_into().map_err(|_| { + DeploySBEDecodeError::DeploySBEProgramLengthPrefixBytesConversionError + })?) as usize; tail = &tail[4..]; if tail.len() < program_len { - return Err(DeploySBEDecodeError::DeploySBEProgramLengthPrefixExceedsPayload { - program_len, - got_after_prefix: tail.len(), - }); + return Err( + DeploySBEDecodeError::DeploySBEProgramLengthPrefixExceedsPayload { + program_len, + got_after_prefix: tail.len(), + }, + ); } let (program_slice, tail_after_program) = tail.split_at(program_len); let program = Program::decompile(&mut program_slice.iter().cloned()) @@ -64,9 +71,11 @@ impl Deploy { tail = tail_after_program; if tail.len() < 4 { - return Err(DeploySBEDecodeError::DeploySBEInsufficientBytesForInitialBalance { - got_total: bytes.len(), - }); + return Err( + DeploySBEDecodeError::DeploySBEInsufficientBytesForInitialBalance { + got_total: bytes.len(), + }, + ); } let initial_balance = u32::from_le_bytes( tail[0..4] @@ -80,7 +89,8 @@ impl Deploy { got_total: bytes.len(), }); } - let target = Target::decode_sbe(&tail[0..8]).map_err(DeploySBEDecodeError::DeploySBETargetDecodeError)?; + let target = Target::decode_sbe(&tail[0..8]) + .map_err(DeploySBEDecodeError::DeploySBETargetDecodeError)?; tail = &tail[8..]; if !tail.is_empty() { diff --git a/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/error/decode_error.rs b/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/error/decode_error.rs index f7d67d78..feda9bb4 100644 --- a/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/error/decode_error.rs +++ b/src/constructive/entries/entry_kinds/deploy/ext/codec/sbe/decode/error/decode_error.rs @@ -4,18 +4,37 @@ use crate::constructive::core_types::target::ext::codec::sbe::decode::error::dec /// Errors that can occur when decoding a `Deploy` from Structural Byte-scope Encoding (SBE) bytes. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum DeploySBEDecodeError { - InvalidEntryKindByteError { expected: u8, got: u8 }, - DeploySBEInsufficientBytesForRootAccountLengthPrefix { got_total: usize }, + InvalidEntryKindByteError { + expected: u8, + got: u8, + }, + DeploySBEInsufficientBytesForRootAccountLengthPrefix { + got_total: usize, + }, DeploySBERootAccountLengthPrefixBytesConversionError, - DeploySBERootAccountLengthPrefixExceedsPayload { root_len: usize, got_after_prefix: usize }, + DeploySBERootAccountLengthPrefixExceedsPayload { + root_len: usize, + got_after_prefix: usize, + }, DeploySBERootAccountDecodeError(RootAccountSBEDecodeError), - DeploySBEInsufficientBytesForProgramLengthPrefix { got_total: usize }, + DeploySBEInsufficientBytesForProgramLengthPrefix { + got_total: usize, + }, DeploySBEProgramLengthPrefixBytesConversionError, - DeploySBEProgramLengthPrefixExceedsPayload { program_len: usize, got_after_prefix: usize }, + DeploySBEProgramLengthPrefixExceedsPayload { + program_len: usize, + got_after_prefix: usize, + }, DeploySBEProgramDecompileError, - DeploySBEInsufficientBytesForInitialBalance { got_total: usize }, + DeploySBEInsufficientBytesForInitialBalance { + got_total: usize, + }, DeploySBEInitialBalanceBytesConversionError, - DeploySBEInsufficientBytesForTarget { got_total: usize }, + DeploySBEInsufficientBytesForTarget { + got_total: usize, + }, DeploySBETargetDecodeError(TargetSBEDecodeError), - DeploySBETrailingBytesAfterDeploy { trailing: usize }, + DeploySBETrailingBytesAfterDeploy { + trailing: usize, + }, } diff --git a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs index 831455bc..6aab1b89 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs @@ -32,7 +32,9 @@ impl Liftup { // 3 Encode the `Target`. { // 3.1 Encode the `Target`. - let target_bits = self.target.encode_ape(execution_batch_height) + let target_bits = self + .target + .encode_ape(execution_batch_height) .map_err(|e| LiftupAPEEncodeError::TargetAPEEncodeError(e))?; // 3.2 Extend the bit vector with the `Target` bit vector. diff --git a/src/constructive/entries/entry_kinds/liftup/ext/mod.rs b/src/constructive/entries/entry_kinds/liftup/ext/mod.rs index 42a21f00..4de86ee5 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/mod.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/mod.rs @@ -1,3 +1,3 @@ pub mod codec; -pub mod signature; pub mod pre_validations; +pub mod signature; diff --git a/src/constructive/entries/entry_kinds/liftup/ext/signature/bls_sign/error/mod.rs b/src/constructive/entries/entry_kinds/liftup/ext/signature/bls_sign/error/mod.rs index 22cf3370..fb3c161d 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/signature/bls_sign/error/mod.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/signature/bls_sign/error/mod.rs @@ -1 +1 @@ -pub mod bls_sign_error; \ No newline at end of file +pub mod bls_sign_error; diff --git a/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/error/sighash_error.rs b/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/error/sighash_error.rs index d1cdf409..eabec829 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/error/sighash_error.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/error/sighash_error.rs @@ -4,4 +4,4 @@ use crate::constructive::entries::entry_kinds::liftup::ext::codec::sbe::encode:: #[derive(Debug, Clone)] pub enum LiftupSighashError { SBEEncodeError(LiftupSBEEncodeError), -} \ No newline at end of file +} diff --git a/src/constructive/entries/entry_kinds/liftup/liftup.rs b/src/constructive/entries/entry_kinds/liftup/liftup.rs index faf6ae2d..f65ffda4 100644 --- a/src/constructive/entries/entry_kinds/liftup/liftup.rs +++ b/src/constructive/entries/entry_kinds/liftup/liftup.rs @@ -42,7 +42,10 @@ impl Liftup { let mut obj = Map::new(); // 2 Insert the entry kind. - obj.insert("entry_kind".to_string(), Value::String("liftup".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("liftup".to_string()), + ); // 3 Insert the root account. obj.insert("account".to_string(), self.root_account.json()); diff --git a/src/constructive/entries/entry_kinds/mod.rs b/src/constructive/entries/entry_kinds/mod.rs index 1e2f607d..5ba270bf 100644 --- a/src/constructive/entries/entry_kinds/mod.rs +++ b/src/constructive/entries/entry_kinds/mod.rs @@ -3,4 +3,4 @@ pub mod config; pub mod deploy; pub mod liftup; pub mod r#move; -pub mod swapout; \ No newline at end of file +pub mod swapout; diff --git a/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/decode.rs index b49bcf8c..4952cd83 100644 --- a/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/decode.rs @@ -10,9 +10,9 @@ impl Move { pub fn decode_sbe(bytes: &[u8]) -> Result { // 1 Validate the leading `Move` entry kind tag. if bytes.is_empty() { - return Err(MoveSBEDecodeError::MoveSBEInsufficientBytesForFromLengthPrefix { - got_total: 0, - }); + return Err( + MoveSBEDecodeError::MoveSBEInsufficientBytesForFromLengthPrefix { got_total: 0 }, + ); } if bytes[0] != 0x00 { return Err(MoveSBEDecodeError::InvalidEntryKindByteError { @@ -23,13 +23,17 @@ impl Move { // 2 Decode the sender (`from`) payload length prefix. if bytes.len() < 5 { - return Err(MoveSBEDecodeError::MoveSBEInsufficientBytesForFromLengthPrefix { - got_total: bytes.len(), - }); + return Err( + MoveSBEDecodeError::MoveSBEInsufficientBytesForFromLengthPrefix { + got_total: bytes.len(), + }, + ); } - let from_len = u32::from_le_bytes(bytes[1..5].try_into().map_err(|_| { - MoveSBEDecodeError::MoveSBEFromLengthPrefixBytesConversionError - })?) as usize; + let from_len = u32::from_le_bytes( + bytes[1..5] + .try_into() + .map_err(|_| MoveSBEDecodeError::MoveSBEFromLengthPrefixBytesConversionError)?, + ) as usize; let after_from_len_prefix = &bytes[5..]; if after_from_len_prefix.len() < from_len { return Err(MoveSBEDecodeError::MoveSBEFromLengthPrefixExceedsPayload { @@ -40,18 +44,22 @@ impl Move { // 3 Decode sender `RootAccount`. let (from_slice, after_from) = after_from_len_prefix.split_at(from_len); - let from = - RootAccount::decode_sbe(from_slice).map_err(MoveSBEDecodeError::MoveSBEFromRootAccount)?; + let from = RootAccount::decode_sbe(from_slice) + .map_err(MoveSBEDecodeError::MoveSBEFromRootAccount)?; // 4 Decode the receiver (`to`) payload length prefix. if after_from.len() < 4 { - return Err(MoveSBEDecodeError::MoveSBEInsufficientBytesForToLengthPrefix { - got_total: bytes.len(), - }); + return Err( + MoveSBEDecodeError::MoveSBEInsufficientBytesForToLengthPrefix { + got_total: bytes.len(), + }, + ); } - let to_len = u32::from_le_bytes(after_from[0..4].try_into().map_err(|_| { - MoveSBEDecodeError::MoveSBEToLengthPrefixBytesConversionError - })?) as usize; + let to_len = u32::from_le_bytes( + after_from[0..4] + .try_into() + .map_err(|_| MoveSBEDecodeError::MoveSBEToLengthPrefixBytesConversionError)?, + ) as usize; let after_to_len_prefix = &after_from[4..]; if after_to_len_prefix.len() < to_len { return Err(MoveSBEDecodeError::MoveSBEToLengthPrefixExceedsPayload { @@ -70,9 +78,11 @@ impl Move { got_total: bytes.len(), }); } - let amount = u32::from_le_bytes(after_to[0..4].try_into().map_err(|_| { - MoveSBEDecodeError::MoveSBEAmountBytesConversionError - })?); + let amount = u32::from_le_bytes( + after_to[0..4] + .try_into() + .map_err(|_| MoveSBEDecodeError::MoveSBEAmountBytesConversionError)?, + ); // 7 Decode target. if after_to.len() < 12 { @@ -80,7 +90,8 @@ impl Move { got_total: bytes.len(), }); } - let target = Target::decode_sbe(&after_to[4..12]).map_err(MoveSBEDecodeError::MoveSBETarget)?; + let target = + Target::decode_sbe(&after_to[4..12]).map_err(MoveSBEDecodeError::MoveSBETarget)?; // 8 Reject trailing bytes. let tail = &after_to[12..]; diff --git a/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/error/decode_error.rs b/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/error/decode_error.rs index 47f10480..26c44885 100644 --- a/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/error/decode_error.rs +++ b/src/constructive/entries/entry_kinds/move/ext/codec/sbe/decode/error/decode_error.rs @@ -5,18 +5,37 @@ use crate::constructive::entity::account::root_account::ext::codec::sbe::decode: /// Errors that can occur when decoding a `Move` from Structural Byte-scope Encoding (SBE) bytes. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MoveSBEDecodeError { - InvalidEntryKindByteError { expected: u8, got: u8 }, - MoveSBEInsufficientBytesForFromLengthPrefix { got_total: usize }, + InvalidEntryKindByteError { + expected: u8, + got: u8, + }, + MoveSBEInsufficientBytesForFromLengthPrefix { + got_total: usize, + }, MoveSBEFromLengthPrefixBytesConversionError, - MoveSBEFromLengthPrefixExceedsPayload { from_len: usize, got_after_prefix: usize }, + MoveSBEFromLengthPrefixExceedsPayload { + from_len: usize, + got_after_prefix: usize, + }, MoveSBEFromRootAccount(RootAccountSBEDecodeError), - MoveSBEInsufficientBytesForToLengthPrefix { got_total: usize }, + MoveSBEInsufficientBytesForToLengthPrefix { + got_total: usize, + }, MoveSBEToLengthPrefixBytesConversionError, - MoveSBEToLengthPrefixExceedsPayload { to_len: usize, got_after_prefix: usize }, + MoveSBEToLengthPrefixExceedsPayload { + to_len: usize, + got_after_prefix: usize, + }, MoveSBEToAccount(AccountSBEDecodeError), - MoveSBEInsufficientBytesForAmount { got_total: usize }, + MoveSBEInsufficientBytesForAmount { + got_total: usize, + }, MoveSBEAmountBytesConversionError, - MoveSBEInsufficientBytesForTarget { got_total: usize }, + MoveSBEInsufficientBytesForTarget { + got_total: usize, + }, MoveSBETarget(TargetSBEDecodeError), - MoveSBETrailingBytesAfterMove { trailing: usize }, + MoveSBETrailingBytesAfterMove { + trailing: usize, + }, } diff --git a/src/constructive/entries/entry_kinds/move/ext/pre_validations/validate_overall/validate_overall.rs b/src/constructive/entries/entry_kinds/move/ext/pre_validations/validate_overall/validate_overall.rs index 5adaa425..a754e22c 100644 --- a/src/constructive/entries/entry_kinds/move/ext/pre_validations/validate_overall/validate_overall.rs +++ b/src/constructive/entries/entry_kinds/move/ext/pre_validations/validate_overall/validate_overall.rs @@ -58,11 +58,9 @@ impl Move { let _coin_manager = coin_manager.lock().await; // 6.2 Resolve sender balance. - let available = _coin_manager - .get_account_balance(from_account_key) - .ok_or(MoveValidateOverallError::FromAccountNotFoundInCoinManagerError( - from_account_key, - ))?; + let available = _coin_manager.get_account_balance(from_account_key).ok_or( + MoveValidateOverallError::FromAccountNotFoundInCoinManagerError(from_account_key), + )?; // 6.3 Reject if sender balance is insufficient. if available < required { diff --git a/src/constructive/entries/entry_kinds/swapout/ext/codec/ape/decode/decode.rs b/src/constructive/entries/entry_kinds/swapout/ext/codec/ape/decode/decode.rs index 09e35731..136b8a94 100644 --- a/src/constructive/entries/entry_kinds/swapout/ext/codec/ape/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/swapout/ext/codec/ape/decode/decode.rs @@ -15,9 +15,10 @@ impl Swapout { decode_account_rank_as_longval: bool, registry: ®ISTRY, ) -> Result { - let root_account = RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) - .await - .map_err(|_| SwapoutAPEDecodeError::RootAccountAPEDecodeError)?; + let root_account = + RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) + .await + .map_err(|_| SwapoutAPEDecodeError::RootAccountAPEDecodeError)?; let target = Target::decode_ape(bit_stream, execution_batch_height) .map_err(|_| SwapoutAPEDecodeError::TargetAPEDecodeError)?; let default_or_unknown_bit = bit_stream @@ -31,7 +32,10 @@ impl Swapout { .map_err(|_| SwapoutAPEDecodeError::SwapoutTxOutputCollectError)?; let pinless_self = if default_or_unknown_bit { - PinlessSelf::new_unknown(txout.script_pubkey.as_bytes().to_vec(), Some((outpoint, txout))) + PinlessSelf::new_unknown( + txout.script_pubkey.as_bytes().to_vec(), + Some((outpoint, txout)), + ) } else { PinlessSelf::new_default(root_account.account_key(), Some((outpoint, txout))) }; diff --git a/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/decode.rs index f64bb813..c4aab1fc 100644 --- a/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/decode.rs @@ -8,9 +8,11 @@ impl Swapout { /// Decodes a `Swapout` from Structural Byte-scope Encoding (SBE) bytes. pub fn decode_sbe(bytes: &[u8]) -> Result { if bytes.is_empty() { - return Err(SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { - got_total: 0, - }); + return Err( + SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: 0, + }, + ); } if bytes[0] != 0x05 { return Err(SwapoutSBEDecodeError::InvalidEntryKindByteError { @@ -19,9 +21,11 @@ impl Swapout { }); } if bytes.len() < 5 { - return Err(SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { - got_total: bytes.len(), - }); + return Err( + SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: bytes.len(), + }, + ); } let root_len_u32 = u32::from_le_bytes(bytes[1..5].try_into().map_err(|_| { @@ -30,10 +34,12 @@ impl Swapout { let root_len = root_len_u32 as usize; let after_root_prefix = &bytes[5..]; if after_root_prefix.len() < root_len { - return Err(SwapoutSBEDecodeError::SwapoutSBERootAccountLengthPrefixExceedsPayload { - root_len, - got_after_prefix: after_root_prefix.len(), - }); + return Err( + SwapoutSBEDecodeError::SwapoutSBERootAccountLengthPrefixExceedsPayload { + root_len, + got_after_prefix: after_root_prefix.len(), + }, + ); } let (root_slice, after_root) = after_root_prefix.split_at(root_len); @@ -41,9 +47,11 @@ impl Swapout { .map_err(|_| SwapoutSBEDecodeError::SwapoutSBERootAccountDecodeError)?; if after_root.len() < 12 { - return Err(SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForTargetAndAmount { - got_total: bytes.len(), - }); + return Err( + SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForTargetAndAmount { + got_total: bytes.len(), + }, + ); } // Matches `encode_sbe`: LE `amount` (4) then `target` SBE (8). @@ -60,9 +68,11 @@ impl Swapout { let pinless_slice = &after_root[12..]; if pinless_slice.is_empty() { - return Err(SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForPinlessSelfKind { - got_total: bytes.len(), - }); + return Err( + SwapoutSBEDecodeError::SwapoutSBEInsufficientBytesForPinlessSelfKind { + got_total: bytes.len(), + }, + ); } let pinless_kind = pinless_slice[0]; @@ -81,7 +91,11 @@ impl Swapout { let custom_scriptpubkey = pinless_slice[1..].to_vec(); PinlessSelf::new_unknown(custom_scriptpubkey, None) } - b => return Err(SwapoutSBEDecodeError::SwapoutSBEInvalidPinlessSelfKindByte(b)), + b => { + return Err(SwapoutSBEDecodeError::SwapoutSBEInvalidPinlessSelfKindByte( + b, + )) + } }; Ok(Swapout::new(root_account, amount, target, pinless_self)) diff --git a/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/error/decode_error.rs b/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/error/decode_error.rs index 4fa8d4c2..7beee49c 100644 --- a/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/error/decode_error.rs +++ b/src/constructive/entries/entry_kinds/swapout/ext/codec/sbe/decode/error/decode_error.rs @@ -1,13 +1,27 @@ /// Enum to represent errors that can occur when decoding a `Swapout` from Structural Byte-scope Encoding (SBE) bytes. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum SwapoutSBEDecodeError { - InvalidEntryKindByteError { expected: u8, got: u8 }, - SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { got_total: usize }, + InvalidEntryKindByteError { + expected: u8, + got: u8, + }, + SwapoutSBEInsufficientBytesForRootAccountLengthPrefix { + got_total: usize, + }, SwapoutSBERootAccountLengthPrefixBytesConversionError, - SwapoutSBERootAccountLengthPrefixExceedsPayload { root_len: usize, got_after_prefix: usize }, + SwapoutSBERootAccountLengthPrefixExceedsPayload { + root_len: usize, + got_after_prefix: usize, + }, SwapoutSBERootAccountDecodeError, - SwapoutSBEInsufficientBytesForTargetAndAmount { got_total: usize }, - SwapoutSBEInsufficientBytesForPinlessSelfKind { got_total: usize }, + SwapoutSBEInsufficientBytesForTargetAndAmount { + got_total: usize, + }, + SwapoutSBEInsufficientBytesForPinlessSelfKind { + got_total: usize, + }, SwapoutSBEInvalidPinlessSelfKindByte(u8), - SwapoutSBETrailingBytesAfterSwapout { trailing: usize }, + SwapoutSBETrailingBytesAfterSwapout { + trailing: usize, + }, } diff --git a/src/constructive/entries/entry_kinds/swapout/ext/signature/bls_verify/bls_verify.rs b/src/constructive/entries/entry_kinds/swapout/ext/signature/bls_verify/bls_verify.rs index 6a9719f5..f77bed21 100644 --- a/src/constructive/entries/entry_kinds/swapout/ext/signature/bls_verify/bls_verify.rs +++ b/src/constructive/entries/entry_kinds/swapout/ext/signature/bls_verify/bls_verify.rs @@ -5,7 +5,9 @@ use crate::transmutative::bls::verify::bls_verify as bls_verify_message; impl Swapout { /// Verifies a BLS signature over this `Swapout`’s signature message (sighash). pub fn bls_verify(&self, bls_signature: [u8; 96]) -> Result<(), SwapoutBLSVerifyError> { - let sighash = self.sighash().map_err(SwapoutBLSVerifyError::SighashError)?; + let sighash = self + .sighash() + .map_err(SwapoutBLSVerifyError::SighashError)?; let bls_public_key = self.root_account.bls_key(); match bls_verify_message(&bls_public_key, sighash, bls_signature) { true => Ok(()), diff --git a/src/constructive/entries/entry_kinds/swapout/swapout.rs b/src/constructive/entries/entry_kinds/swapout/swapout.rs index 9b4bf957..e7e684b1 100644 --- a/src/constructive/entries/entry_kinds/swapout/swapout.rs +++ b/src/constructive/entries/entry_kinds/swapout/swapout.rs @@ -31,7 +31,10 @@ impl Swapout { pub fn json(&self) -> Value { let mut obj = Map::new(); - obj.insert("entry_kind".to_string(), Value::String("swapout".to_string())); + obj.insert( + "entry_kind".to_string(), + Value::String("swapout".to_string()), + ); obj.insert("account".to_string(), self.root_account.json()); obj.insert("amount".to_string(), Value::Number(self.amount.into())); obj.insert( diff --git a/src/constructive/mod.rs b/src/constructive/mod.rs index 9f771035..18753656 100644 --- a/src/constructive/mod.rs +++ b/src/constructive/mod.rs @@ -5,9 +5,9 @@ pub mod txout_types; pub use entries as entry; +pub use bitcoiny::taproot; +pub use bitcoiny::txn; pub use core_types::calldata; pub use core_types::entities as entity; pub use core_types::valtypes as valtype; -pub use bitcoiny::taproot; -pub use bitcoiny::txn; pub use txout_types as txo; diff --git a/src/constructive/txout_types/lift/lift/ext/codec/sbe/decode/decode.rs b/src/constructive/txout_types/lift/lift/ext/codec/sbe/decode/decode.rs index 08c59b80..da244107 100644 --- a/src/constructive/txout_types/lift/lift/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/txout_types/lift/lift/ext/codec/sbe/decode/decode.rs @@ -19,8 +19,8 @@ impl Lift { // 2.a `Unknown` (`0x00`): shared body only (no v1/v2 script template). 0x00 => { let payload = &bytes[1..]; - let (account_key, engine_key, outpoint, txout) = decode_lift_v1_sbe_body(payload) - .map_err(LiftSBEDecodeError::LiftUnknown)?; + let (account_key, engine_key, outpoint, txout) = + decode_lift_v1_sbe_body(payload).map_err(LiftSBEDecodeError::LiftUnknown)?; Ok(Lift::Unknown { account_key, engine_key, diff --git a/src/constructive/txout_types/lift/lift_versions/liftv2/ext/codec/sbe/decode/decode.rs b/src/constructive/txout_types/lift/lift_versions/liftv2/ext/codec/sbe/decode/decode.rs index 1801a06e..ced7e676 100644 --- a/src/constructive/txout_types/lift/lift_versions/liftv2/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/txout_types/lift/lift_versions/liftv2/ext/codec/sbe/decode/decode.rs @@ -12,7 +12,9 @@ fn decode_lift_v2_sbe_body( // 1 Decode the 32-byte Schnorr account key. if total < 32 { - return Err(LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForAccountKey { got_total: total }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForAccountKey { got_total: total }, + ); } let (account_slice, rest) = payload.split_at(32); let account_key = account_slice @@ -21,7 +23,11 @@ fn decode_lift_v2_sbe_body( // 2 Decode the 32-byte Schnorr engine key. if rest.len() < 32 { - return Err(LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForEngineKey { got_total: rest.len() }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForEngineKey { + got_total: rest.len(), + }, + ); } let (engine_slice, rest) = rest.split_at(32); let engine_key = engine_slice @@ -30,7 +36,11 @@ fn decode_lift_v2_sbe_body( // 3 Decode the 36-byte outpoint (`OutpointExt::from_bytes36`). if rest.len() < 36 { - return Err(LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForOutPoint { got_total: rest.len() }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForOutPoint { + got_total: rest.len(), + }, + ); } let (outpoint_slice, rest) = rest.split_at(36); let outpoint_bytes: [u8; 36] = outpoint_slice @@ -41,23 +51,31 @@ fn decode_lift_v2_sbe_body( // 4 Decode the `TxOut` prefix: 8-byte little-endian value. if rest.len() < 8 { - return Err(LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutValue { got_total: rest.len() }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutValue { + got_total: rest.len(), + }, + ); } let (value_slice, rest) = rest.split_at(8); // 5 Read the 1-byte script-pubkey length prefix and the script bytes. if rest.is_empty() { return Err( - LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutScriptLengthPrefix { got_total: 0 }, + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutScriptLengthPrefix { + got_total: 0, + }, ); } let script_len = rest[0] as usize; let rest = &rest[1..]; if rest.len() < script_len { - return Err(LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutScriptPayload { - got_total: rest.len(), - script_len, - }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEInsufficientBytesForTxOutScriptPayload { + got_total: rest.len(), + script_len, + }, + ); } let (script_slice, trailing) = rest.split_at(script_len); @@ -66,8 +84,8 @@ fn decode_lift_v2_sbe_body( txout_bytes.extend_from_slice(value_slice); txout_bytes.push(script_len as u8); txout_bytes.extend_from_slice(script_slice); - let txout = - TxOut::from_bytes(&txout_bytes).ok_or(LiftV2SBEDecodeError::LiftV2SBEFailedToDecodeTxOutError)?; + let txout = TxOut::from_bytes(&txout_bytes) + .ok_or(LiftV2SBEDecodeError::LiftV2SBEFailedToDecodeTxOutError)?; // 7 Ensure no bytes trail after the encoded `TxOut`. if !trailing.is_empty() { @@ -93,7 +111,9 @@ impl LiftV2 { // 2 Split the discriminant from the payload and verify it is `0x02`. let (tag, payload) = bytes.split_at(1); if tag[0] != 0x02 { - return Err(LiftV2SBEDecodeError::LiftV2SBEExpectedVariantDiscriminant0x02Error { got: tag[0] }); + return Err( + LiftV2SBEDecodeError::LiftV2SBEExpectedVariantDiscriminant0x02Error { got: tag[0] }, + ); } // 3 Decode the payload body (keys, outpoint, `TxOut`). diff --git a/src/constructive/txout_types/mod.rs b/src/constructive/txout_types/mod.rs index dd185e66..2ecc76c7 100644 --- a/src/constructive/txout_types/mod.rs +++ b/src/constructive/txout_types/mod.rs @@ -1,4 +1,4 @@ pub mod lift; -pub mod pinless_self; pub mod payload; +pub mod pinless_self; pub mod projector; diff --git a/src/constructive/txout_types/pinless_self/pinless_self.rs b/src/constructive/txout_types/pinless_self/pinless_self.rs index 58687fa4..fd800bd7 100644 --- a/src/constructive/txout_types/pinless_self/pinless_self.rs +++ b/src/constructive/txout_types/pinless_self/pinless_self.rs @@ -65,6 +65,4 @@ impl PinlessSelf { PinlessSelf::Unknown(pinless_self_unknown) => pinless_self_unknown.json(), } } - } - diff --git a/src/constructive/txout_types/pinless_self/unknown/unknown.rs b/src/constructive/txout_types/pinless_self/unknown/unknown.rs index 54613cdb..ddd76654 100644 --- a/src/constructive/txout_types/pinless_self/unknown/unknown.rs +++ b/src/constructive/txout_types/pinless_self/unknown/unknown.rs @@ -33,7 +33,10 @@ impl PinlessSelfUnknown { Some((outpoint, txout)) => { let mut o = Map::new(); let mut outpoint_json = Map::new(); - outpoint_json.insert("txid".to_string(), Value::String(hex::encode(outpoint.txid))); + outpoint_json.insert( + "txid".to_string(), + Value::String(hex::encode(outpoint.txid)), + ); outpoint_json.insert("vout".to_string(), Value::Number(outpoint.vout.into())); o.insert("outpoint".to_string(), Value::Object(outpoint_json)); diff --git a/src/constructive/txout_types/projector/projector.rs b/src/constructive/txout_types/projector/projector.rs index 522d618e..0d4f24ce 100644 --- a/src/constructive/txout_types/projector/projector.rs +++ b/src/constructive/txout_types/projector/projector.rs @@ -71,4 +71,4 @@ fn projector_location_json((outpoint, txout): &(OutPoint, TxOut)) -> Value { o.insert("outpoint".to_string(), json_outpoint(outpoint)); o.insert("txout".to_string(), json_txout(txout)); Value::Object(o) -} \ No newline at end of file +} diff --git a/src/executive/entry_executions/config_execution/config_execution.rs b/src/executive/entry_executions/config_execution/config_execution.rs index f7943a75..e37b03f6 100644 --- a/src/executive/entry_executions/config_execution/config_execution.rs +++ b/src/executive/entry_executions/config_execution/config_execution.rs @@ -27,7 +27,11 @@ impl ExecCtx { .as_ref() .map(|v| v.len() as u64) .unwrap_or(0) - + if config.projector_config.is_some() { 32 } else { 0 } + + if config.projector_config.is_some() { + 32 + } else { + 0 + } + config .flame_config .as_ref() @@ -102,7 +106,7 @@ impl ExecCtx { let fee_debit = 0u64 .checked_add(fees_after_subsidy) .ok_or(ConfigExecutionError::ConfigFeeDebitOverflow)?; - + decrease_account_balance_with_coin_manager(&self.coin_manager, account_key, fee_debit) .await .map_err(ConfigExecutionError::CoinManagerAccountBalanceDownError)?; diff --git a/src/executive/entry_executions/deploy_execution/deploy_execution.rs b/src/executive/entry_executions/deploy_execution/deploy_execution.rs index 2f4a7295..311ec91f 100644 --- a/src/executive/entry_executions/deploy_execution/deploy_execution.rs +++ b/src/executive/entry_executions/deploy_execution/deploy_execution.rs @@ -3,6 +3,7 @@ use crate::constructive::entry::entry_fees::entry_fees::EntryFees; use crate::constructive::entry::entry_kinds::deploy::deploy::Deploy; use crate::executive::entry_executions::deploy_execution::error::deploy_execution_error::DeployExecutionError; use crate::executive::exec_ctx::exec_ctx::ExecCtx; +use crate::executive::executable::compiler::compiler::ProgramCompiler; use crate::inscriptive::coin_manager::coin_manager::COIN_MANAGER; use crate::inscriptive::coin_manager::errors::balance_update_errors::CMAccountBalanceDownError; use crate::inscriptive::privileges_manager::bodies::contract_body::contract_body::PrivilegesManagerContractBody; @@ -10,7 +11,6 @@ use crate::inscriptive::privileges_manager::elements::exemption::exemption::Exem use crate::inscriptive::privileges_manager::elements::exemption::exemption::ExemptionSubsidyBreakdown; use crate::inscriptive::privileges_manager::elements::liveness_flag::liveness_flag::LivenessFlag; use crate::inscriptive::privileges_manager::errors::update_error::PMUpdateAccountError; -use crate::executive::executable::compiler::compiler::ProgramCompiler; impl ExecCtx { /// Executes a `Deploy` entry. @@ -104,7 +104,7 @@ impl ExecCtx { let total_debit = fees_after_subsidy .checked_add(deploy.initial_balance as u64) .ok_or(DeployExecutionError::DeployFeeDebitOverflow)?; - + decrease_account_balance_with_coin_manager(&self.coin_manager, account_key, total_debit) .await .map_err(DeployExecutionError::CoinManagerAccountBalanceDownError)?; diff --git a/src/executive/entry_executions/liftup_execution/mod.rs b/src/executive/entry_executions/liftup_execution/mod.rs index 77e9e578..11adcb75 100644 --- a/src/executive/entry_executions/liftup_execution/mod.rs +++ b/src/executive/entry_executions/liftup_execution/mod.rs @@ -1,2 +1,2 @@ -pub mod liftup_execution; pub mod error; +pub mod liftup_execution; diff --git a/src/executive/entry_executions/move_execution/move_execution.rs b/src/executive/entry_executions/move_execution/move_execution.rs index b68fb4c5..494f1ea1 100644 --- a/src/executive/entry_executions/move_execution/move_execution.rs +++ b/src/executive/entry_executions/move_execution/move_execution.rs @@ -85,7 +85,7 @@ impl ExecCtx { fees_pre_subsidy, latest_activity_timestamp, ) - .await? + .await? } RootAccount::RegisteredAndConfiguredRootAccount( registered_and_configured_root_account, @@ -103,7 +103,7 @@ impl ExecCtx { fees_pre_subsidy, latest_activity_timestamp, ) - .await? + .await? } }; diff --git a/src/executive/entry_executions/swapout_execution/swapout_execution.rs b/src/executive/entry_executions/swapout_execution/swapout_execution.rs index 24db2863..88c35132 100644 --- a/src/executive/entry_executions/swapout_execution/swapout_execution.rs +++ b/src/executive/entry_executions/swapout_execution/swapout_execution.rs @@ -99,7 +99,7 @@ impl ExecCtx { fees_pre_subsidy, latest_activity_timestamp, ) - .await? + .await? } RootAccount::RegisteredAndConfiguredRootAccount( registered_and_configured_root_account, @@ -117,7 +117,7 @@ impl ExecCtx { fees_pre_subsidy, latest_activity_timestamp, ) - .await? + .await? } }; diff --git a/src/executive/exec_ctx/exec_ctx.rs b/src/executive/exec_ctx/exec_ctx.rs index c5ae6b8e..49915597 100644 --- a/src/executive/exec_ctx/exec_ctx.rs +++ b/src/executive/exec_ctx/exec_ctx.rs @@ -522,8 +522,10 @@ impl ExecCtx { .ok_or(BatchExecutionError::FailedToIterAndGetProjectorTxOutputError)?; // 23.a.2 Get the new projector outpoint. - let new_projector_outpoint = - OutPoint::from_txid_and_vout(batch_container.signed_batch_txn.txid(), tx_output_index_cursor); + let new_projector_outpoint = OutPoint::from_txid_and_vout( + batch_container.signed_batch_txn.txid(), + tx_output_index_cursor, + ); // 23.a.3 Construct the projector. let projector = Some(Projector { @@ -552,20 +554,23 @@ impl ExecCtx { // 26 Initialize the executed entry account BLS keys list. let mut executed_entry_account_bls_keys: Vec<[u8; 48]> = Vec::new(); let collect_entry_ape_bits = self.archival_manager.is_some(); - let mut collected_entry_ape_bits: Option> = collect_entry_ape_bits.then(Vec::new); + let mut collected_entry_ape_bits: Option> = + collect_entry_ape_bits.then(Vec::new); let batch_txid = batch_container.signed_batch_txn.txid(); - let remaining_tx_outputs_for_entries: Vec<(OutPoint, bitcoin::TxOut)> = bitcoin_tx_outputs_iter - .cloned() - .enumerate() - .map(|(i, txout)| { - ( - OutPoint::from_txid_and_vout(batch_txid, tx_output_index_cursor + i as u32), - txout, - ) - }) - .collect(); - let mut remaining_tx_outputs_for_entries_iter = remaining_tx_outputs_for_entries.into_iter(); + let remaining_tx_outputs_for_entries: Vec<(OutPoint, bitcoin::TxOut)> = + bitcoin_tx_outputs_iter + .cloned() + .enumerate() + .map(|(i, txout)| { + ( + OutPoint::from_txid_and_vout(batch_txid, tx_output_index_cursor + i as u32), + txout, + ) + }) + .collect(); + let mut remaining_tx_outputs_for_entries_iter = + remaining_tx_outputs_for_entries.into_iter(); // 27 Decode entries from the payload one by one and execute them. while ape_bitstream.len() > 0 { @@ -631,7 +636,10 @@ impl ExecCtx { // 27.2.b The `Entry` is a `Move`. Entry::Move(move_entry) => { // 27.2.b.1 Execute the `Move` `Entry`. - match self.execute_move_internal(&move_entry, batch_timestamp).await { + match self + .execute_move_internal(&move_entry, batch_timestamp) + .await + { // 27.2.b.1.a Success. Ok(fees) => { // 27.2.b.1.a.1 Add the move entry to the executed entries. @@ -660,7 +668,10 @@ impl ExecCtx { } } Entry::Swapout(swapout) => { - match self.execute_swapout_internal(&swapout, batch_timestamp).await { + match self + .execute_swapout_internal(&swapout, batch_timestamp) + .await + { Ok(fees) => { executed_entries.push(Entry::new_swapout(swapout.clone())); executed_entry_fees.push(fees); @@ -673,7 +684,9 @@ impl ExecCtx { executed_entry_sighashes.push(sighash); executed_entry_account_bls_keys.push(swapout.root_account.bls_key()); } - Err(error) => return Err(BatchExecutionError::SwapoutExecutionError(error)), + Err(error) => { + return Err(BatchExecutionError::SwapoutExecutionError(error)) + } } } Entry::Deploy(deploy) => { diff --git a/src/executive/vm/opcodes/opcodes/callinfo/op_caller.rs b/src/executive/vm/opcodes/opcodes/callinfo/op_caller.rs index 0db2ba34..766518df 100644 --- a/src/executive/vm/opcodes/opcodes/callinfo/op_caller.rs +++ b/src/executive/vm/opcodes/opcodes/callinfo/op_caller.rs @@ -1,6 +1,6 @@ use crate::executive::{ - vm::program_execution::caller::Caller, stack::{stack_error::StackError, stack_holder::StackHolder, stack_item::StackItem}, + vm::program_execution::caller::Caller, }; use serde::{Deserialize, Serialize}; diff --git a/src/executive/vm/opcodes/opcodes/flow/mod.rs b/src/executive/vm/opcodes/opcodes/flow/mod.rs index 0a970f9e..82a9043a 100644 --- a/src/executive/vm/opcodes/opcodes/flow/mod.rs +++ b/src/executive/vm/opcodes/opcodes/flow/mod.rs @@ -2,9 +2,9 @@ pub mod op_else; pub mod op_endif; pub mod op_fail; pub mod op_if; +pub mod op_jump; pub mod op_nop; pub mod op_notif; pub mod op_returnall; -pub mod op_jump; +pub mod op_returnsome; pub mod op_verify; -pub mod op_returnsome; \ No newline at end of file diff --git a/src/executive/vm/opcodes/opcodes/push/mod.rs b/src/executive/vm/opcodes/opcodes/push/mod.rs index 262d6024..047795a0 100644 --- a/src/executive/vm/opcodes/opcodes/push/mod.rs +++ b/src/executive/vm/opcodes/opcodes/push/mod.rs @@ -1,5 +1,10 @@ -pub mod op_false; -pub mod op_true; +pub mod op_10; +pub mod op_11; +pub mod op_12; +pub mod op_13; +pub mod op_14; +pub mod op_15; +pub mod op_16; pub mod op_2; pub mod op_3; pub mod op_4; @@ -8,11 +13,6 @@ pub mod op_6; pub mod op_7; pub mod op_8; pub mod op_9; -pub mod op_10; -pub mod op_11; -pub mod op_12; -pub mod op_13; -pub mod op_14; -pub mod op_15; -pub mod op_16; -pub mod op_pushdata; \ No newline at end of file +pub mod op_false; +pub mod op_pushdata; +pub mod op_true; diff --git a/src/executive/vm/opcodes/opcodes/signature/mod.rs b/src/executive/vm/opcodes/opcodes/signature/mod.rs index cc1161cc..2d91fddc 100644 --- a/src/executive/vm/opcodes/opcodes/signature/mod.rs +++ b/src/executive/vm/opcodes/opcodes/signature/mod.rs @@ -1,4 +1,4 @@ -pub mod op_checkblssigagg; pub mod op_checkblssig; +pub mod op_checkblssigagg; pub mod op_checkschnorrsig; pub mod op_checkschnorrsigbip340; diff --git a/src/executive/vm/program/compiler/compiler.rs b/src/executive/vm/program/compiler/compiler.rs index b48def81..1fcc2eaa 100644 --- a/src/executive/vm/program/compiler/compiler.rs +++ b/src/executive/vm/program/compiler/compiler.rs @@ -85,8 +85,10 @@ impl ProgramCompiler for Program { .try_into() .map_err(|_| ProgramDecompileError::MetadataLengthBytesCollectError)?; let metadata_len = u16::from_le_bytes(metadata_len_bytes) as usize; - let metadata_bytes: Vec = - bytecode_stream.by_ref().take(metadata_len).collect::>(); + let metadata_bytes: Vec = bytecode_stream + .by_ref() + .take(metadata_len) + .collect::>(); if metadata_bytes.len() != metadata_len { return Err(ProgramDecompileError::MetadataBytesCollectError); } diff --git a/src/executive/vm/program/compiler/compiler_error.rs b/src/executive/vm/program/compiler/compiler_error.rs index d7007e2e..33d720ae 100644 --- a/src/executive/vm/program/compiler/compiler_error.rs +++ b/src/executive/vm/program/compiler/compiler_error.rs @@ -1,7 +1,7 @@ -use crate::executive::executable::program_error::ProgramConstructionError; use crate::executive::executable::method::compiler::compiler_error::{ MethodCompileError, MethodDecompileError, }; +use crate::executive::executable::program_error::ProgramConstructionError; use std::fmt; /// The error that occurs when compiling a program. diff --git a/src/executive/vm/program/method/compiler/compiler.rs b/src/executive/vm/program/method/compiler/compiler.rs index 5f6f3045..c8aa47ba 100644 --- a/src/executive/vm/program/method/compiler/compiler.rs +++ b/src/executive/vm/program/method/compiler/compiler.rs @@ -3,8 +3,8 @@ use crate::{ executive::{ executable::method::{ compiler::compiler_error::{MethodCompileError, MethodDecompileError}, - program_method::ProgramMethod, method_type::MethodType, + program_method::ProgramMethod, }, opcode::{compiler::compiler::OpcodeCompiler, opcode::Opcode}, }, diff --git a/src/executive/vm/program/method/mod.rs b/src/executive/vm/program/method/mod.rs index 2603b83a..8c3ff683 100644 --- a/src/executive/vm/program/method/mod.rs +++ b/src/executive/vm/program/method/mod.rs @@ -1,5 +1,5 @@ pub mod compiler; pub mod limits; -pub mod program_method; pub mod method_error; pub mod method_type; +pub mod program_method; diff --git a/src/executive/vm/program/mod.rs b/src/executive/vm/program/mod.rs index 5926e9f8..3df02159 100644 --- a/src/executive/vm/program/mod.rs +++ b/src/executive/vm/program/mod.rs @@ -1,6 +1,6 @@ pub mod compiler; pub mod program; pub use program as executable; -pub mod program_error; pub mod limits; pub mod method; +pub mod program_error; diff --git a/src/executive/vm/program_execution/mod.rs b/src/executive/vm/program_execution/mod.rs index ed76d730..4e8c0035 100644 --- a/src/executive/vm/program_execution/mod.rs +++ b/src/executive/vm/program_execution/mod.rs @@ -1,4 +1,4 @@ pub mod caller; pub mod exec; -pub mod program_exec_ctx; pub mod exec_error; +pub mod program_exec_ctx; diff --git a/src/executive/vm/program_execution/program_exec_ctx.rs b/src/executive/vm/program_execution/program_exec_ctx.rs index 55235434..a96f169c 100644 --- a/src/executive/vm/program_execution/program_exec_ctx.rs +++ b/src/executive/vm/program_execution/program_exec_ctx.rs @@ -1,13 +1,12 @@ use crate::{ constructive::entry::entry_kinds::call::call::Call, executive::{ - vm::program_execution::{caller::Caller, exec::execute, exec_error::ExecutionError}, stack::stack_item::StackItem, + vm::program_execution::{caller::Caller, exec::execute, exec_error::ExecutionError}, }, inscriptive::{ coin_manager::coin_manager::COIN_MANAGER, params_manager::params_manager::PARAMS_MANAGER, - registry::registry::REGISTRY, - state_manager::state_manager::STATE_MANAGER, + registry::registry::REGISTRY, state_manager::state_manager::STATE_MANAGER, }, }; use std::sync::Arc; diff --git a/src/inscriptive/archival_manager/archival_manager.rs b/src/inscriptive/archival_manager/archival_manager.rs index dc275740..9af5058a 100644 --- a/src/inscriptive/archival_manager/archival_manager.rs +++ b/src/inscriptive/archival_manager/archival_manager.rs @@ -42,7 +42,8 @@ pub type ARCHIVAL_MANAGER = Arc>; fn entry_involves_account(entry: &Entry, account_key: [u8; 32]) -> bool { match entry { Entry::Move(move_entry) => { - move_entry.from.account_key() == account_key || move_entry.to.account_key() == account_key + move_entry.from.account_key() == account_key + || move_entry.to.account_key() == account_key } Entry::Call(call) => call.account.account_key() == account_key, Entry::Liftup(liftup) => liftup.root_account.account_key() == account_key, @@ -183,22 +184,20 @@ impl ArchivalManager { &self, prev_payload_outpoint: &OutPoint, ) -> Option { - self.in_memory_records - .values() - .find_map(|record| { - record - .batch_container - .signed_batch_txn - .tx_inputs - .first() - .and_then(|(outpoint, _, _)| { - if outpoint.txid == prev_payload_outpoint.txid { - Some(record.batch_container.clone()) - } else { - None - } - }) - }) + self.in_memory_records.values().find_map(|record| { + record + .batch_container + .signed_batch_txn + .tx_inputs + .first() + .and_then(|(outpoint, _, _)| { + if outpoint.txid == prev_payload_outpoint.txid { + Some(record.batch_container.clone()) + } else { + None + } + }) + }) } /// JSON for a full batch record (`BatchRecord::json`), resolved by batch txid. @@ -264,8 +263,7 @@ impl ArchivalManager { entry, collected_bits, fees, - ) = - self.entry_record_by_entry_id(entry_id)?; + ) = self.entry_record_by_entry_id(entry_id)?; // 2 Build the JSON object for the Entry record. let mut obj = Map::new(); diff --git a/src/inscriptive/archival_manager/errors/construction_error.rs b/src/inscriptive/archival_manager/errors/construction_error.rs index 023d07dc..70f7b8df 100644 --- a/src/inscriptive/archival_manager/errors/construction_error.rs +++ b/src/inscriptive/archival_manager/errors/construction_error.rs @@ -4,5 +4,8 @@ pub enum ArchivalConstructionError { DBOpenError(sled::Error), CorruptRecord(u64), UnexpectedDbKeyLength(usize), - HeightKeyMismatch { db_key_height: u64, record_batch_height: u64 }, + HeightKeyMismatch { + db_key_height: u64, + record_batch_height: u64, + }, } diff --git a/src/inscriptive/flame_manager/delta/delta.rs b/src/inscriptive/flame_manager/delta/delta.rs index ef528818..f7ea6caf 100644 --- a/src/inscriptive/flame_manager/delta/delta.rs +++ b/src/inscriptive/flame_manager/delta/delta.rs @@ -29,10 +29,7 @@ impl FMDelta { } /// Epheremally registers an account in the delta. - pub fn ephemerally_register_account( - &mut self, - account_key: AccountKey, - ) -> bool { + pub fn ephemerally_register_account(&mut self, account_key: AccountKey) -> bool { // 1 Check if the account has just been ephemerally registered in the delta. match self.is_account_ephemerally_registered(account_key) { // 1.a The account has just been ephemerally registered in the delta. diff --git a/src/inscriptive/graveyard/delta/delta.rs b/src/inscriptive/graveyard/delta/delta.rs index 6d02361e..4e12f8c0 100644 --- a/src/inscriptive/graveyard/delta/delta.rs +++ b/src/inscriptive/graveyard/delta/delta.rs @@ -43,8 +43,7 @@ impl GraveyardDelta { /// Epheremally burries an account and the amount of satoshi they are owed for redemption. pub fn ephemerally_bury_account(&mut self, account_key: [u8; 32], redemption_amount: u64) { - self.accounts_to_bury - .insert(account_key, redemption_amount); + self.accounts_to_bury.insert(account_key, redemption_amount); } /// Epheremally redeems an account and its corresponding redemption amount. diff --git a/src/inscriptive/graveyard/graveyard.rs b/src/inscriptive/graveyard/graveyard.rs index 398d21f2..e348ea41 100644 --- a/src/inscriptive/graveyard/graveyard.rs +++ b/src/inscriptive/graveyard/graveyard.rs @@ -159,9 +159,7 @@ impl Graveyard { // 2 Check if the account has already been permanently buried. if self.in_memory_buried_accounts.contains_key(&account_key) { - return Err( - GraveyardBuryAccountError::AccountIsAlreadyPermanentlyBuried(account_key), - ); + return Err(GraveyardBuryAccountError::AccountIsAlreadyPermanentlyBuried(account_key)); } // 3 Epheremally bury the account in the delta. diff --git a/src/inscriptive/params_manager/mod.rs b/src/inscriptive/params_manager/mod.rs index 8f7709c6..d3103f64 100644 --- a/src/inscriptive/params_manager/mod.rs +++ b/src/inscriptive/params_manager/mod.rs @@ -1,2 +1,2 @@ -pub mod params_manager; pub mod params_holder; +pub mod params_manager; diff --git a/src/inscriptive/params_manager/params_manager.rs b/src/inscriptive/params_manager/params_manager.rs index aa4a68d5..344282af 100644 --- a/src/inscriptive/params_manager/params_manager.rs +++ b/src/inscriptive/params_manager/params_manager.rs @@ -216,7 +216,8 @@ impl ParamsManager { } pub fn set_swapout_entry_base_fee(&mut self, value: u64) { - self.get_mut_ephemeral_params_holder().swapout_entry_base_fee = value; + self.get_mut_ephemeral_params_holder() + .swapout_entry_base_fee = value; } pub fn set_config_entry_base_fee(&mut self, value: u64) { diff --git a/src/inscriptive/privileges_manager/delta/delta.rs b/src/inscriptive/privileges_manager/delta/delta.rs index fdce1868..f6ff32b2 100644 --- a/src/inscriptive/privileges_manager/delta/delta.rs +++ b/src/inscriptive/privileges_manager/delta/delta.rs @@ -103,4 +103,4 @@ impl PrivilegesManagerDelta { .insert(contract_id, contract_body); true } -} \ No newline at end of file +} diff --git a/src/inscriptive/privileges_manager/elements/exemption/exemption.rs b/src/inscriptive/privileges_manager/elements/exemption/exemption.rs index b872a8e9..13593a0c 100644 --- a/src/inscriptive/privileges_manager/elements/exemption/exemption.rs +++ b/src/inscriptive/privileges_manager/elements/exemption/exemption.rs @@ -194,7 +194,9 @@ impl Exemption { // 2 Subsidize the direct credit only if active. let direct_credit = match self.direct_credit { - Some((direct_credit, direct_expiry)) if current_timestamp <= direct_expiry => direct_credit, + Some((direct_credit, direct_expiry)) if current_timestamp <= direct_expiry => { + direct_credit + } _ => 0, }; diff --git a/src/inscriptive/privileges_manager/elements/exemption/mod.rs b/src/inscriptive/privileges_manager/elements/exemption/mod.rs index 91db5699..ac15062f 100644 --- a/src/inscriptive/privileges_manager/elements/exemption/mod.rs +++ b/src/inscriptive/privileges_manager/elements/exemption/mod.rs @@ -1,2 +1,2 @@ pub mod exemption; -pub mod periodic_resource; \ No newline at end of file +pub mod periodic_resource; diff --git a/src/inscriptive/privileges_manager/privileges_manager.rs b/src/inscriptive/privileges_manager/privileges_manager.rs index 0b94b1d0..3bd1eee5 100644 --- a/src/inscriptive/privileges_manager/privileges_manager.rs +++ b/src/inscriptive/privileges_manager/privileges_manager.rs @@ -438,15 +438,13 @@ impl PrivilegesManager { account_body: PrivilegesManagerAccountBody, ) -> Result<(), PMRegisterAccountError> { if self.is_account_ephemerally_registered(account_key) { - return Err(PMRegisterAccountError::AccountHasJustBeenEphemerallyRegistered( - account_key, - )); + return Err( + PMRegisterAccountError::AccountHasJustBeenEphemerallyRegistered(account_key), + ); } if self.is_account_permanently_registered(account_key) { - return Err(PMRegisterAccountError::AccountIsAlreadyPermanentlyRegistered( - account_key, - )); + return Err(PMRegisterAccountError::AccountIsAlreadyPermanentlyRegistered(account_key)); } self.delta @@ -461,15 +459,15 @@ impl PrivilegesManager { contract_body: PrivilegesManagerContractBody, ) -> Result<(), PMRegisterContractError> { if self.is_contract_ephemerally_registered(contract_id) { - return Err(PMRegisterContractError::ContractHasJustBeenEphemerallyRegistered( - contract_id, - )); + return Err( + PMRegisterContractError::ContractHasJustBeenEphemerallyRegistered(contract_id), + ); } if self.is_contract_permanently_registered(contract_id) { - return Err(PMRegisterContractError::ContractIsAlreadyPermanentlyRegistered( - contract_id, - )); + return Err( + PMRegisterContractError::ContractIsAlreadyPermanentlyRegistered(contract_id), + ); } self.delta @@ -509,7 +507,11 @@ impl PrivilegesManager { /// Returns account txfee exemptions. pub fn get_account_txfee_exemptions(&self, account_key: AccountKey) -> Option { - if let Some(value) = self.delta.updated_account_txfee_exemptions.get(&account_key) { + if let Some(value) = self + .delta + .updated_account_txfee_exemptions + .get(&account_key) + { return Some(value.clone()); } @@ -897,7 +899,10 @@ impl PrivilegesManager { for (account_key, liveness_flag) in self.delta.updated_account_liveness_flags.iter() { { let tree = self.on_disk_accounts.open_tree(account_key)?; - tree.insert(ACCOUNT_LIVENESS_FLAG_SPECIAL_DB_KEY, liveness_flag.to_bytes())?; + tree.insert( + ACCOUNT_LIVENESS_FLAG_SPECIAL_DB_KEY, + liveness_flag.to_bytes(), + )?; } if let Some(account_body) = self.in_memory_accounts.get_mut(account_key) { @@ -909,7 +914,10 @@ impl PrivilegesManager { for (account_key, hierarchy) in self.delta.updated_account_hierarchies.iter() { { let tree = self.on_disk_accounts.open_tree(account_key)?; - tree.insert(ACCOUNT_HIERARCHY_SPECIAL_DB_KEY, [hierarchy.to_bytecode()].as_slice())?; + tree.insert( + ACCOUNT_HIERARCHY_SPECIAL_DB_KEY, + [hierarchy.to_bytecode()].as_slice(), + )?; } if let Some(account_body) = self.in_memory_accounts.get_mut(account_key) { @@ -980,7 +988,8 @@ impl PrivilegesManager { } // 9 Save updated account can-deploy-contract switches. - for (account_key, can_deploy_contract) in self.delta.updated_account_can_deploy_contract.iter() + for (account_key, can_deploy_contract) in + self.delta.updated_account_can_deploy_contract.iter() { { let tree = self.on_disk_accounts.open_tree(account_key)?; @@ -999,7 +1008,10 @@ impl PrivilegesManager { for (contract_id, liveness_flag) in self.delta.updated_contract_liveness_flags.iter() { { let tree = self.on_disk_contracts.open_tree(contract_id)?; - tree.insert(CONTRACT_LIVENESS_FLAG_SPECIAL_DB_KEY, liveness_flag.to_bytes())?; + tree.insert( + CONTRACT_LIVENESS_FLAG_SPECIAL_DB_KEY, + liveness_flag.to_bytes(), + )?; } if let Some(contract_body) = self.in_memory_contracts.get_mut(contract_id) { @@ -1012,7 +1024,10 @@ impl PrivilegesManager { { let tree = self.on_disk_contracts.open_tree(contract_id)?; let immutability_byte = if *immutability { 1u8 } else { 0u8 }; - tree.insert(CONTRACT_IMMUTABILITY_SPECIAL_DB_KEY, [immutability_byte].as_slice())?; + tree.insert( + CONTRACT_IMMUTABILITY_SPECIAL_DB_KEY, + [immutability_byte].as_slice(), + )?; } if let Some(contract_body) = self.in_memory_contracts.get_mut(contract_id) { @@ -1024,7 +1039,10 @@ impl PrivilegesManager { for (contract_id, tax_exemptions) in self.delta.updated_contract_tax_exemptions.iter() { { let tree = self.on_disk_contracts.open_tree(contract_id)?; - tree.insert(CONTRACT_TAX_EXEMPTIONS_SPECIAL_DB_KEY, tax_exemptions.to_bytes())?; + tree.insert( + CONTRACT_TAX_EXEMPTIONS_SPECIAL_DB_KEY, + tax_exemptions.to_bytes(), + )?; } if let Some(contract_body) = self.in_memory_contracts.get_mut(contract_id) { diff --git a/src/inscriptive/registry/bodies/account_body/account_body.rs b/src/inscriptive/registry/bodies/account_body/account_body.rs index 25f529ff..1eedcdbe 100644 --- a/src/inscriptive/registry/bodies/account_body/account_body.rs +++ b/src/inscriptive/registry/bodies/account_body/account_body.rs @@ -1,5 +1,5 @@ -use serde_json::{Map, Value}; use crate::inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig; +use serde_json::{Map, Value}; /// BLS key of an account. type AccountBLSKey = [u8; 48]; @@ -16,7 +16,7 @@ pub struct RMAccountBody { // Assigned registry index of an account. pub registry_index: u64, - // Ever-increasing call counter of an account. + // Ever-increasing call counter of an account. pub call_counter: u64, // Last observed activity timestamp of an account. diff --git a/src/inscriptive/registry/errors/apply_changes_error.rs b/src/inscriptive/registry/errors/apply_changes_error.rs index 0aa15a87..8c85d83e 100644 --- a/src/inscriptive/registry/errors/apply_changes_error.rs +++ b/src/inscriptive/registry/errors/apply_changes_error.rs @@ -26,5 +26,8 @@ pub enum RMApplyChangesError { ContractNotFoundInMemory(ContractId), ContractCallCounterUpdateError(ContractId, u64, sled::Error), ContractLastActivityTimestampUpdateError(ContractId, u64, sled::Error), - ProgramCompileError(ContractId, crate::executive::executable::compiler::compiler_error::ProgramCompileError), + ProgramCompileError( + ContractId, + crate::executive::executable::compiler::compiler_error::ProgramCompileError, + ), } diff --git a/src/inscriptive/registry/errors/update_account_bls_key_error.rs b/src/inscriptive/registry/errors/update_account_bls_key_error.rs index 47544e59..0f5595b5 100644 --- a/src/inscriptive/registry/errors/update_account_bls_key_error.rs +++ b/src/inscriptive/registry/errors/update_account_bls_key_error.rs @@ -12,4 +12,3 @@ pub enum RMUpdateAccountBLSKeyError { BLSKeyIsAlreadyEpheremallySet(AccountKey, AccountBLSKey), BLSKeyIsConflictingWithAnAlreadyRegisteredBLSKey(AccountBLSKey), } - diff --git a/src/inscriptive/registry/registry.rs b/src/inscriptive/registry/registry.rs index 4404746e..cfba7739 100644 --- a/src/inscriptive/registry/registry.rs +++ b/src/inscriptive/registry/registry.rs @@ -725,10 +725,7 @@ impl Registry { } /// Returns the number of methods on a contract's executable. - pub fn get_contract_methods_len_by_contract_id( - &self, - contract_id: [u8; 32], - ) -> Option { + pub fn get_contract_methods_len_by_contract_id(&self, contract_id: [u8; 32]) -> Option { self.get_contract_body_by_contract_id(contract_id) .map(|body| body.executable.methods_len()) } diff --git a/src/inscriptive/utxo_set/mod.rs b/src/inscriptive/utxo_set/mod.rs index 2e2569c5..08f1c699 100644 --- a/src/inscriptive/utxo_set/mod.rs +++ b/src/inscriptive/utxo_set/mod.rs @@ -1 +1 @@ -pub mod utxo_set; \ No newline at end of file +pub mod utxo_set; diff --git a/src/operative/cli/cli.rs b/src/operative/cli/cli.rs index cc419457..0a716c7b 100644 --- a/src/operative/cli/cli.rs +++ b/src/operative/cli/cli.rs @@ -1,8 +1,8 @@ use crate::communicative::peer::peer::PEER; use crate::inscriptive::archival_manager::archival_manager::ARCHIVAL_MANAGER; use crate::inscriptive::coin_manager::coin_manager::COIN_MANAGER; -use crate::inscriptive::flame_manager::flame_manager::FLAME_MANAGER; use crate::inscriptive::flame_manager::flame_config::flame_config::FMAccountFlameConfig; +use crate::inscriptive::flame_manager::flame_manager::FLAME_MANAGER; use crate::inscriptive::graveyard::graveyard::GRAVEYARD; use crate::inscriptive::params_manager::params_manager::PARAMS_MANAGER; use crate::inscriptive::privileges_manager::privileges_manager::PRIVILEGES_MANAGER; @@ -71,7 +71,9 @@ pub async fn run_engine_cli( ) .await; } - "rootaccount" => common_commands::rootaccount::rootaccount_command(key_holder, registry).await, + "rootaccount" => { + common_commands::rootaccount::rootaccount_command(key_holder, registry).await + } "engine" => common_commands::engine::engine_command(chain), "print" => match parts.get(1).map(String::as_str) { Some("registry") => common_commands::registry::registry_command(registry).await, @@ -96,7 +98,10 @@ pub async fn run_engine_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -124,7 +129,10 @@ pub async fn run_engine_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -152,7 +160,10 @@ pub async fn run_engine_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -263,7 +274,10 @@ pub async fn run_node_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -291,7 +305,10 @@ pub async fn run_node_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -319,7 +336,10 @@ pub async fn run_node_cli( let account_key = match parse_account_key(account_key_str) { Some(key) => key, None => { - eprintln!("{}", "Invalid account key: expected 32-byte hex.".yellow()); + eprintln!( + "{}", + "Invalid account key: expected 32-byte hex.".yellow() + ); continue; } }; @@ -370,8 +390,7 @@ pub async fn run_node_cli( None => { eprintln!( "{}", - "Usage: batchrecord (non-negative integer)." - .yellow() + "Usage: batchrecord (non-negative integer).".yellow() ); continue; } @@ -440,10 +459,7 @@ pub async fn run_node_cli( node_commands::rank::account_rank_command(registry, account_key).await; } _ => { - eprintln!( - "{}", - "Usage: account rank .".yellow() - ); + eprintln!("{}", "Usage: account rank .".yellow()); } } } @@ -466,10 +482,7 @@ pub async fn run_node_cli( node_commands::rank::contract_rank_command(registry, contract_id).await; } _ => { - eprintln!( - "{}", - "Usage: contract rank .".yellow() - ); + eprintln!("{}", "Usage: contract rank .".yellow()); } } } @@ -735,7 +748,11 @@ fn parse_hex_bytes(s: &str) -> Option> { fn parse_config_fields( args: &[String], -) -> Option<(Option>, Option<[u8; 32]>, Option)> { +) -> Option<( + Option>, + Option<[u8; 32]>, + Option, +)> { let mut sak: Option> = None; let mut pc: Option<[u8; 32]> = None; let mut fc: Option = None; diff --git a/src/operative/cli/commands/common_commands/mod.rs b/src/operative/cli/commands/common_commands/mod.rs index e84e61d9..a38de8cc 100644 --- a/src/operative/cli/commands/common_commands/mod.rs +++ b/src/operative/cli/commands/common_commands/mod.rs @@ -1,9 +1,9 @@ -pub mod coinmanager; pub mod clear; +pub mod coinmanager; pub mod engine; pub mod flamemanager; pub mod graveyard; pub mod registry; pub mod rootaccount; pub mod runexplorer; -pub mod tip; \ No newline at end of file +pub mod tip; diff --git a/src/operative/cli/commands/common_commands/runexplorer.rs b/src/operative/cli/commands/common_commands/runexplorer.rs index 0f52d67e..dbee6d9c 100644 --- a/src/operative/cli/commands/common_commands/runexplorer.rs +++ b/src/operative/cli/commands/common_commands/runexplorer.rs @@ -76,7 +76,10 @@ pub async fn runexplorer_command( .route("/entry/:entry_id", get(page_entry_by_id)) .route("/account/:account_id/:section", get(page_account_section)) .route("/account/:account_id", get(page_account_root_redirect)) - .route("/contract/:contract_id/:section", get(page_contract_section)) + .route( + "/contract/:contract_id/:section", + get(page_contract_section), + ) .route("/contract/:contract_id", get(page_contract_root_redirect)) .with_state(state); @@ -96,7 +99,11 @@ pub async fn runexplorer_command( .yellow() ); } else { - eprintln!("{} {}", format!("runexplorer: failed to bind {}:", addr).yellow(), e); + eprintln!( + "{} {}", + format!("runexplorer: failed to bind {}:", addr).yellow(), + e + ); } return; } @@ -773,8 +780,7 @@ fn site_header(search_value: &str) -> String { "#, - logo_src, - q + logo_src, q ) } @@ -875,9 +881,9 @@ fn expandable_mono_html(full: &str, head: usize, tail: usize, id_prefix: &str) - fn account_avatar_emoji(account_key: [u8; 32]) -> &'static str { // Deterministic avatar choice from public key bytes. const AVATARS: [&str; 40] = [ - "👻", "🦘", "🐱", "🐰", "🦊", "🐼", "🐨", "🦁", "🐯", "🐸", "🐵", "🐶", "🐻", "🦉", - "🦄", "🐙", "🐧", "🦋", "🦒", "🦔", "🐺", "🦇", "🦅", "🐬", "🐢", "🦓", "🐘", "🦥", - "🦦", "🦩", "🦜", "🐿️", "🦝", "🐆", "🐮", "🐗", "🐭", "🐹", "🦎", "🦛", + "👻", "🦘", "🐱", "🐰", "🦊", "🐼", "🐨", "🦁", "🐯", "🐸", "🐵", "🐶", "🐻", "🦉", "🦄", + "🐙", "🐧", "🦋", "🦒", "🦔", "🐺", "🦇", "🦅", "🐬", "🐢", "🦓", "🐘", "🦥", "🦦", "🦩", + "🦜", "🐿️", "🦝", "🐆", "🐮", "🐗", "🐭", "🐹", "🦎", "🦛", ]; let idx = (account_key[0] as usize) % AVATARS.len(); AVATARS[idx] @@ -982,7 +988,8 @@ fn explorer_vip_tab_inner( .unwrap_or(&default_periodic); let period_label = explorer_format_period_for_bar(pr.period); let suffix = format!("/ per {}", period_label); - let discount_label = explorer_vip_discount_percent_label(txfee.discount.map(|v| v.0).unwrap_or(0)); + let discount_label = + explorer_vip_discount_percent_label(txfee.discount.map(|v| v.0).unwrap_or(0)); let direct_coins = explorer_format_coins_u64(txfee.direct_credit.map(|v| v.0).unwrap_or(0)); let limit_coins = explorer_format_coins_u64(pr.limit); format!( @@ -1119,7 +1126,12 @@ async fn page_accounts(State(st): State) -> Html { .and_then(|v| v.as_str()) .and_then(|v| v.parse::().ok()) .unwrap_or(0); - parsed.push((registry_index, account_key, call_counter, last_activity_timestamp)); + parsed.push(( + registry_index, + account_key, + call_counter, + last_activity_timestamp, + )); } } parsed @@ -1266,7 +1278,9 @@ async fn page_account_section( )); } if history_rows.is_empty() { - history_rows = r#"No transaction history in archival records."#.to_string(); + history_rows = + r#"No transaction history in archival records."# + .to_string(); } let privileges_json = if let Some(ref pb) = privilege_body { @@ -1298,7 +1312,8 @@ async fn page_account_section( .and_then(|v| serde_json::to_value(v).ok()) .unwrap_or(Value::Object(Map::new())) }; - let vtxo_pretty = serde_json::to_string_pretty(&vtxo_json).unwrap_or_else(|_| "null".to_string()); + let vtxo_pretty = + serde_json::to_string_pretty(&vtxo_json).unwrap_or_else(|_| "null".to_string()); let npub = account_key.to_npub().unwrap_or_else(|| "n/a".to_string()); let npub_short = if npub.len() > 16 { @@ -1723,9 +1738,12 @@ async fn page_contracts(State(st): State) -> Html { Html(layout( "Contracts — Cube explorer", - &format!(r#"

Contracts

+ &format!( + r#"

Contracts

Contracts indexed by registry order.

-{}
IndexProgram nameContract IDCall counterLast time called
"#, table_rows), +{}
IndexProgram nameContract IDCall counterLast time called
"#, + table_rows + ), "", )) } @@ -1804,9 +1822,7 @@ async fn page_batch_by_txid( State(st): State, Path(txid_hex): Path, ) -> impl IntoResponse { - let txid_bytes: Option<[u8; 32]> = Txid::from_str(&txid_hex) - .ok() - .map(|t| t.to_byte_array()); + let txid_bytes: Option<[u8; 32]> = Txid::from_str(&txid_hex).ok().map(|t| t.to_byte_array()); let Some(txid_bytes) = txid_bytes else { return ( StatusCode::BAD_REQUEST, @@ -1867,7 +1883,9 @@ async fn page_entry_by_id( m.entry_record_by_entry_id(&entry_id) }; - let Some((batch_height, batch_txid_bytes, batch_ts, _eid, entry, collected_bits, fees)) = resolved else { + let Some((batch_height, batch_txid_bytes, batch_ts, _eid, entry, collected_bits, fees)) = + resolved + else { return ( StatusCode::NOT_FOUND, Html(layout( @@ -1890,7 +1908,8 @@ async fn page_entry_by_id( html_escape(&batch_txid), html_escape(&batch_txid), ); - let entry_json = serde_json::to_string_pretty(&entry.json()).unwrap_or_else(|_| "{}".to_string()); + let entry_json = + serde_json::to_string_pretty(&entry.json()).unwrap_or_else(|_| "{}".to_string()); let entry_fees_json = serde_json::to_string_pretty(&fees.map(|v| v.json()).unwrap_or(serde_json::Value::Null)) .unwrap_or_else(|_| "null".to_string()); @@ -1937,9 +1956,7 @@ async fn page_entry_by_id( _ => String::new(), }; let collected_bits_html = match collected_bits { - Some(bits) => { - expandable_mono_html(&bits, 28, 16, "ape-bits") - } + Some(bits) => expandable_mono_html(&bits, 28, 16, "ape-bits"), None => "N/A (non-archival record)".to_string(), }; @@ -2012,7 +2029,9 @@ fn render_batch_page(chain: Chain, record: &BatchRecord) -> String { }; let amount_cell = match entry { Entry::Move(move_entry) => explorer_format_coins_u64(move_entry.amount as u64), - Entry::Liftup(liftup) => explorer_format_coins_u64(liftup.liftup_sum_value_in_satoshis()), + Entry::Liftup(liftup) => { + explorer_format_coins_u64(liftup.liftup_sum_value_in_satoshis()) + } Entry::Swapout(swapout) => explorer_format_coins_u64(swapout.amount as u64), Entry::Deploy(deploy) => explorer_format_coins_u64(deploy.initial_balance as u64), Entry::Call(_) | Entry::Config(_) => "N/A".to_string(), @@ -2024,7 +2043,9 @@ fn render_batch_page(chain: Chain, record: &BatchRecord) -> String { account_link_npub_truncated(move_entry.to.account_key()) ), Entry::Liftup(liftup) => account_link_npub_truncated(liftup.root_account.account_key()), - Entry::Swapout(swapout) => account_link_npub_truncated(swapout.root_account.account_key()), + Entry::Swapout(swapout) => { + account_link_npub_truncated(swapout.root_account.account_key()) + } Entry::Call(call) => account_link_npub_truncated(call.account.account_key()), Entry::Deploy(deploy) => account_link_npub_truncated(deploy.root_account.account_key()), Entry::Config(config) => account_link_npub_truncated(config.root_account.account_key()), diff --git a/src/operative/cli/commands/engine_commands/mod.rs b/src/operative/cli/commands/engine_commands/mod.rs index e69de29b..8b137891 100644 --- a/src/operative/cli/commands/engine_commands/mod.rs +++ b/src/operative/cli/commands/engine_commands/mod.rs @@ -0,0 +1 @@ + diff --git a/src/operative/cli/commands/mod.rs b/src/operative/cli/commands/mod.rs index e7ac3501..f6f5c14c 100644 --- a/src/operative/cli/commands/mod.rs +++ b/src/operative/cli/commands/mod.rs @@ -1,3 +1,3 @@ +pub mod common_commands; pub mod engine_commands; pub mod node_commands; -pub mod common_commands; \ No newline at end of file diff --git a/src/operative/cli/commands/node_commands/batchrecord.rs b/src/operative/cli/commands/node_commands/batchrecord.rs index f0c7e11e..9d06f961 100644 --- a/src/operative/cli/commands/node_commands/batchrecord.rs +++ b/src/operative/cli/commands/node_commands/batchrecord.rs @@ -6,19 +6,17 @@ use serde_json::to_string_pretty; // batchrecord pub async fn batchrecord_command(batch_height: u64, engine_peer: &PEER) { // 1 Request the batch record from the engine. - let (batchrecord_response_body, duration) = match engine_peer - .request_batchrecord(batch_height) - .await - { - Ok((body, duration)) => (body, duration), - Err(error) => { - println!( - "{}", - format!("Error requesting batch record: {:?}", error).red() - ); - return; - } - }; + let (batchrecord_response_body, duration) = + match engine_peer.request_batchrecord(batch_height).await { + Ok((body, duration)) => (body, duration), + Err(error) => { + println!( + "{}", + format!("Error requesting batch record: {:?}", error).red() + ); + return; + } + }; // 2 Match the batch record result (wire enum, not `Result`). match batchrecord_response_body { diff --git a/src/operative/cli/commands/node_commands/comp.rs b/src/operative/cli/commands/node_commands/comp.rs index 23c43e4b..ae5f6998 100644 --- a/src/operative/cli/commands/node_commands/comp.rs +++ b/src/operative/cli/commands/node_commands/comp.rs @@ -4,7 +4,8 @@ use crate::executive::{ compiler::compiler::ProgramCompiler, executable::Program, method::{ - compiler::compiler::MethodCompiler, method_type::MethodType, program_method::ProgramMethod, + compiler::compiler::MethodCompiler, method_type::MethodType, + program_method::ProgramMethod, }, }, opcode::{compiler::compiler::OpcodeCompiler, opcode::Opcode}, @@ -171,7 +172,10 @@ fn parse_comp_program_arguments<'a>( } // Validate all method hex blobs up front for better argument disambiguation. - if method_bytes_args.iter().any(|m| parse_hex_bytes(m).is_none()) { + if method_bytes_args + .iter() + .any(|m| parse_hex_bytes(m).is_none()) + { continue; } diff --git a/src/operative/cli/commands/node_commands/config.rs b/src/operative/cli/commands/node_commands/config.rs index 2d5e782f..92ca0793 100644 --- a/src/operative/cli/commands/node_commands/config.rs +++ b/src/operative/cli/commands/node_commands/config.rs @@ -24,10 +24,7 @@ pub async fn config_command( engine_peer: &PEER, ) { if secondary_aggregation_key.is_none() && projector_config.is_none() && flame_config.is_none() { - println!( - "{}", - "Error: provide at least one of sak, pc, fc.".red() - ); + println!("{}", "Error: provide at least one of sak, pc, fc.".red()); return; } @@ -58,7 +55,11 @@ pub async fn config_command( .as_ref() .map(|v| v.len() as u64) .unwrap_or(0) - + if config.projector_config.is_some() { 32 } else { 0 } + + if config.projector_config.is_some() { + 32 + } else { + 0 + } + config .flame_config .as_ref() diff --git a/src/operative/cli/commands/node_commands/deploy.rs b/src/operative/cli/commands/node_commands/deploy.rs index dd434b5a..5994d79f 100644 --- a/src/operative/cli/commands/node_commands/deploy.rs +++ b/src/operative/cli/commands/node_commands/deploy.rs @@ -56,7 +56,8 @@ pub async fn deploy_command( }; let pre_subsidy_fee = match params_holder.deploy_entry_base_fee.checked_add( - (program_bytes.len() as u64).saturating_mul(params_holder.deploy_entry_per_program_byte_fee), + (program_bytes.len() as u64) + .saturating_mul(params_holder.deploy_entry_per_program_byte_fee), ) { Some(v) => v, None => { diff --git a/src/operative/cli/commands/node_commands/mod.rs b/src/operative/cli/commands/node_commands/mod.rs index 3532a1fb..ea955058 100644 --- a/src/operative/cli/commands/node_commands/mod.rs +++ b/src/operative/cli/commands/node_commands/mod.rs @@ -1,11 +1,10 @@ pub mod batchrecord; pub mod coins; pub mod comp; -pub mod conn; pub mod config; -pub mod deploy; +pub mod conn; pub mod decompile; -pub mod rank; +pub mod deploy; pub mod liftaddr; pub mod lifts; pub mod liftup; @@ -13,4 +12,5 @@ pub mod liftuplocal; pub mod r#move; pub mod npub; pub mod ping; +pub mod rank; pub mod swapout; diff --git a/src/operative/cli/commands/node_commands/rank.rs b/src/operative/cli/commands/node_commands/rank.rs index 16af1846..0b11a2cc 100644 --- a/src/operative/cli/commands/node_commands/rank.rs +++ b/src/operative/cli/commands/node_commands/rank.rs @@ -11,8 +11,7 @@ pub async fn account_rank_command(registry: ®ISTRY, account_key: [u8; 32]) { Some(rank) => println!("{}", rank), None => eprintln!( "{}", - "No rank for this account key in the registry (not registered on disk)." - .yellow() + "No rank for this account key in the registry (not registered on disk).".yellow() ), } } @@ -27,8 +26,7 @@ pub async fn contract_rank_command(registry: ®ISTRY, contract_id: [u8; 32]) { Some(rank) => println!("{}", rank), None => eprintln!( "{}", - "No rank for this contract id in the registry (not registered on disk)." - .yellow() + "No rank for this contract id in the registry (not registered on disk).".yellow() ), } } diff --git a/src/operative/cli/commands/node_commands/swapout.rs b/src/operative/cli/commands/node_commands/swapout.rs index 59971efd..c0718dfe 100644 --- a/src/operative/cli/commands/node_commands/swapout.rs +++ b/src/operative/cli/commands/node_commands/swapout.rs @@ -91,7 +91,10 @@ pub async fn swapout_command( let swapout_bls_signature: [u8; 96] = match swapout.bls_sign(key_holder) { Ok(signature) => signature, Err(error) => { - println!("{}", format!("Error BLS signing swapout: {:?}", error).red()); + println!( + "{}", + format!("Error BLS signing swapout: {:?}", error).red() + ); return; } }; diff --git a/src/operative/cli/mod.rs b/src/operative/cli/mod.rs index a893b8ea..18a4aecb 100644 --- a/src/operative/cli/mod.rs +++ b/src/operative/cli/mod.rs @@ -1,2 +1,2 @@ +pub mod cli; pub mod commands; -pub mod cli; \ No newline at end of file diff --git a/src/operative/run_args/chain.rs b/src/operative/run_args/chain.rs index d739240e..d7281dcc 100644 --- a/src/operative/run_args/chain.rs +++ b/src/operative/run_args/chain.rs @@ -17,4 +17,4 @@ impl ToString for Chain { Chain::Mainnet => "mainnet".to_string(), } } -} \ No newline at end of file +} diff --git a/src/operative/runner/mod.rs b/src/operative/runner/mod.rs index 422db304..748377a9 100644 --- a/src/operative/runner/mod.rs +++ b/src/operative/runner/mod.rs @@ -1 +1 @@ -pub mod runner; \ No newline at end of file +pub mod runner; diff --git a/src/operative/runner/runner.rs b/src/operative/runner/runner.rs index 2867cc65..70359035 100644 --- a/src/operative/runner/runner.rs +++ b/src/operative/runner/runner.rs @@ -17,8 +17,8 @@ use crate::inscriptive::flame_manager::flame_manager::FlameManager; use crate::inscriptive::flame_manager::flame_manager::FLAME_MANAGER; use crate::inscriptive::graveyard::graveyard::Graveyard; use crate::inscriptive::graveyard::graveyard::GRAVEYARD; -use crate::inscriptive::params_manager::params_manager::PARAMS_MANAGER; use crate::inscriptive::params_manager::params_manager::ParamsManager; +use crate::inscriptive::params_manager::params_manager::PARAMS_MANAGER; use crate::inscriptive::privileges_manager::privileges_manager::PrivilegesManager; use crate::inscriptive::privileges_manager::privileges_manager::PRIVILEGES_MANAGER; use crate::inscriptive::registry::registry::Registry; diff --git a/src/operative/tasks/chain_sync/chain_sync.rs b/src/operative/tasks/chain_sync/chain_sync.rs index 11bfd946..839df703 100644 --- a/src/operative/tasks/chain_sync/chain_sync.rs +++ b/src/operative/tasks/chain_sync/chain_sync.rs @@ -10,10 +10,8 @@ use crate::{ inscriptive::{ archival_manager::archival_manager::ARCHIVAL_MANAGER, baked, coin_manager::coin_manager::COIN_MANAGER, flame_manager::flame_manager::FLAME_MANAGER, - graveyard::graveyard::GRAVEYARD, - params_manager::params_manager::PARAMS_MANAGER, - privileges_manager::privileges_manager::PRIVILEGES_MANAGER, - registry::registry::REGISTRY, + graveyard::graveyard::GRAVEYARD, params_manager::params_manager::PARAMS_MANAGER, + privileges_manager::privileges_manager::PRIVILEGES_MANAGER, registry::registry::REGISTRY, state_manager::state_manager::STATE_MANAGER, sync_manager::sync_manager::SYNC_MANAGER, utxo_set::utxo_set::UTXO_SET, }, diff --git a/src/operative/tasks/chain_sync/mod.rs b/src/operative/tasks/chain_sync/mod.rs index e2870238..cdd90162 100644 --- a/src/operative/tasks/chain_sync/mod.rs +++ b/src/operative/tasks/chain_sync/mod.rs @@ -1 +1 @@ -pub mod chain_sync; \ No newline at end of file +pub mod chain_sync; diff --git a/src/operative/tasks/engine_session/session_pool/error/mod.rs b/src/operative/tasks/engine_session/session_pool/error/mod.rs index 15fc7c26..208c5505 100644 --- a/src/operative/tasks/engine_session/session_pool/error/mod.rs +++ b/src/operative/tasks/engine_session/session_pool/error/mod.rs @@ -1,6 +1,6 @@ -pub mod exec_liftup_in_pool_error; -pub mod exec_move_in_pool_error; pub mod exec_config_in_pool_error; pub mod exec_deploy_in_pool_error; +pub mod exec_liftup_in_pool_error; +pub mod exec_move_in_pool_error; pub mod exec_swapout_in_pool_error; pub mod into_batch_container_error; diff --git a/src/operative/tasks/engine_session/session_pool/session_pool.rs b/src/operative/tasks/engine_session/session_pool/session_pool.rs index 7b86cbaf..39464d39 100644 --- a/src/operative/tasks/engine_session/session_pool/session_pool.rs +++ b/src/operative/tasks/engine_session/session_pool/session_pool.rs @@ -22,10 +22,10 @@ use crate::inscriptive::registry::registry::REGISTRY; use crate::inscriptive::state_manager::state_manager::STATE_MANAGER; use crate::inscriptive::sync_manager::sync_manager::SYNC_MANAGER; use crate::inscriptive::utxo_set::utxo_set::UTXO_SET; -use crate::operative::tasks::engine_session::session_pool::error::exec_liftup_in_pool_error::ExecLiftupInPoolError; -use crate::operative::tasks::engine_session::session_pool::error::exec_move_in_pool_error::ExecMoveInPoolError; use crate::operative::tasks::engine_session::session_pool::error::exec_config_in_pool_error::ExecConfigInPoolError; use crate::operative::tasks::engine_session::session_pool::error::exec_deploy_in_pool_error::ExecDeployInPoolError; +use crate::operative::tasks::engine_session::session_pool::error::exec_liftup_in_pool_error::ExecLiftupInPoolError; +use crate::operative::tasks::engine_session::session_pool::error::exec_move_in_pool_error::ExecMoveInPoolError; use crate::operative::tasks::engine_session::session_pool::error::exec_swapout_in_pool_error::ExecSwapoutInPoolError; use crate::operative::tasks::engine_session::session_pool::error::into_batch_container_error::IntoBatchContainerError; use crate::transmutative::bls::agg::bls_aggregate; @@ -390,7 +390,7 @@ impl SessionPool { &mut self, liftup: &Liftup, liftup_bls_signature: [u8; 96], - ) -> Result<(EntryId, Entry, BatchHeight, BatchTimestamp), ExecLiftupInPoolError> { + ) -> Result<(EntryId, Entry, BatchHeight, BatchTimestamp), ExecLiftupInPoolError> { // 1 Check the pool session status. match self.state { // 1.a The session is inactive. @@ -568,7 +568,9 @@ impl SessionPool { self.exec_ctx.lock().await.rollback_last().await; } // 5.b.2 Return the error. - Err(ExecMoveInPoolError::MoveExecutionError(format!("{error:?}"))) + Err(ExecMoveInPoolError::MoveExecutionError(format!( + "{error:?}" + ))) } } } @@ -580,7 +582,9 @@ impl SessionPool { ) -> Result<(EntryId, Entry, BatchHeight, BatchTimestamp), ExecSwapoutInPoolError> { match self.state { SessionPoolState::Inactive => return Err(ExecSwapoutInPoolError::SessionInactiveError), - SessionPoolState::Suspended => return Err(ExecSwapoutInPoolError::SessionSuspendedError), + SessionPoolState::Suspended => { + return Err(ExecSwapoutInPoolError::SessionSuspendedError) + } SessionPoolState::Break => return Err(ExecSwapoutInPoolError::SessionBreakError), _ => { if self.added_entries.len() >= MAX_IN_POOL_ENTRIES { @@ -602,7 +606,9 @@ impl SessionPool { swapout_bls_signature, ) .await - .map_err(|err| ExecSwapoutInPoolError::SwapoutValidateOverallError(format!("{err:?}")))?; + .map_err(|err| { + ExecSwapoutInPoolError::SwapoutValidateOverallError(format!("{err:?}")) + })?; { let mut _exec_ctx = self.exec_ctx.lock().await; @@ -643,7 +649,9 @@ impl SessionPool { ) -> Result<(EntryId, Entry, BatchHeight, BatchTimestamp), ExecConfigInPoolError> { match self.state { SessionPoolState::Inactive => return Err(ExecConfigInPoolError::SessionInactiveError), - SessionPoolState::Suspended => return Err(ExecConfigInPoolError::SessionSuspendedError), + SessionPoolState::Suspended => { + return Err(ExecConfigInPoolError::SessionSuspendedError) + } SessionPoolState::Break => return Err(ExecConfigInPoolError::SessionBreakError), _ => { if self.added_entries.len() >= MAX_IN_POOL_ENTRIES { @@ -664,7 +672,9 @@ impl SessionPool { .root_account .validate_root_account(&self.registry, &self.graveyard) .await - .map_err(|err| ExecConfigInPoolError::ConfigValidateRootAccountError(format!("{err:?}")))?; + .map_err(|err| { + ExecConfigInPoolError::ConfigValidateRootAccountError(format!("{err:?}")) + })?; if let Err((targeted_at_batch_height, execution_batch_height)) = config.target.validate(batch_height) @@ -714,7 +724,9 @@ impl SessionPool { ) -> Result<(EntryId, Entry, BatchHeight, BatchTimestamp), ExecDeployInPoolError> { match self.state { SessionPoolState::Inactive => return Err(ExecDeployInPoolError::SessionInactiveError), - SessionPoolState::Suspended => return Err(ExecDeployInPoolError::SessionSuspendedError), + SessionPoolState::Suspended => { + return Err(ExecDeployInPoolError::SessionSuspendedError) + } SessionPoolState::Break => return Err(ExecDeployInPoolError::SessionBreakError), _ => { if self.added_entries.len() >= MAX_IN_POOL_ENTRIES { @@ -740,7 +752,9 @@ impl SessionPool { .root_account .validate_root_account(&self.registry, &self.graveyard) .await - .map_err(|err| ExecDeployInPoolError::DeployValidateRootAccountError(format!("{err:?}")))?; + .map_err(|err| { + ExecDeployInPoolError::DeployValidateRootAccountError(format!("{err:?}")) + })?; if let Err((targeted_at_batch_height, execution_batch_height)) = deploy.target.validate(batch_height) diff --git a/src/operative/tasks/in_flight_batch_sync/in_flight_batch_sync.rs b/src/operative/tasks/in_flight_batch_sync/in_flight_batch_sync.rs index ac2f19e6..df90cbfa 100644 --- a/src/operative/tasks/in_flight_batch_sync/in_flight_batch_sync.rs +++ b/src/operative/tasks/in_flight_batch_sync/in_flight_batch_sync.rs @@ -42,7 +42,10 @@ pub async fn in_flight_batch_sync_background_task( { Ok((response_body, _)) => response_body, Err(error) => { - eprintln!("In-flight sync request failed: {:?}. Retrying in 5s...", error); + eprintln!( + "In-flight sync request failed: {:?}. Retrying in 5s...", + error + ); tokio::time::sleep(Duration::from_secs(5)).await; continue; } diff --git a/src/transmutative/bls/bls_ser.rs b/src/transmutative/bls/bls_ser.rs index 67a596f0..bf683cd4 100644 --- a/src/transmutative/bls/bls_ser.rs +++ b/src/transmutative/bls/bls_ser.rs @@ -47,9 +47,7 @@ where } /// Helper function to deserialize [u8; 64] from a byte vector. -pub fn deserialize_schnorr_signature<'de, D>( - deserializer: D, -) -> Result +pub fn deserialize_schnorr_signature<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { diff --git a/src/transmutative/bls/verify.rs b/src/transmutative/bls/verify.rs index 819bf10a..2c845506 100644 --- a/src/transmutative/bls/verify.rs +++ b/src/transmutative/bls/verify.rs @@ -60,10 +60,5 @@ pub fn bls_verify_aggregate( .collect::>>(); // Verify the aggregate signature. - bls::aggregate_verify( - keys, - messages, - &aggregate_signature.to_vec(), - &message_tag, - ) + bls::aggregate_verify(keys, messages, &aggregate_signature.to_vec(), &message_tag) } diff --git a/src/transmutative/codec/csv.rs b/src/transmutative/codec/csv.rs index cd73c6fe..26a0915e 100644 --- a/src/transmutative/codec/csv.rs +++ b/src/transmutative/codec/csv.rs @@ -100,4 +100,4 @@ fn pad_four(input: Bytes) -> Bytes { } padded -} \ No newline at end of file +} diff --git a/src/transmutative/codec/prefix.rs b/src/transmutative/codec/prefix.rs index a24928aa..4274db01 100644 --- a/src/transmutative/codec/prefix.rs +++ b/src/transmutative/codec/prefix.rs @@ -89,4 +89,4 @@ impl Prefix for Bytes { bytes.extend(self); bytes } -} \ No newline at end of file +} diff --git a/src/transmutative/hash.rs b/src/transmutative/hash.rs index b836e4e1..672a681f 100644 --- a/src/transmutative/hash.rs +++ b/src/transmutative/hash.rs @@ -66,19 +66,67 @@ impl HashTag { } HashTag::FlameConfig => format!("{}/{}", baked::PROJECT_TAG, "flameconfig"), // Sighashes - HashTag::LiftupEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "liftup"), - HashTag::SwapoutEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "swapout"), - HashTag::MoveEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "move"), - HashTag::ConfigEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "config"), - HashTag::DeployEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "deploy"), - HashTag::CallEntrySighash => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "sighash", "entry", "call"), + HashTag::LiftupEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "liftup" + ), + HashTag::SwapoutEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "swapout" + ), + HashTag::MoveEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "move" + ), + HashTag::ConfigEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "config" + ), + HashTag::DeployEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "deploy" + ), + HashTag::CallEntrySighash => format!( + "{}/{}/{}/{}", + baked::PROJECT_TAG, + "sighash", + "entry", + "call" + ), // Entry IDs - HashTag::LiftupEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "liftup"), - HashTag::SwapoutEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "swapout"), - HashTag::MoveEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "move"), - HashTag::ConfigEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "config"), - HashTag::DeployEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "deploy"), - HashTag::CallEntryID => format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "call"), + HashTag::LiftupEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "liftup") + } + HashTag::SwapoutEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "swapout") + } + HashTag::MoveEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "move") + } + HashTag::ConfigEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "config") + } + HashTag::DeployEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "deploy") + } + HashTag::CallEntryID => { + format!("{}/{}/{}/{}", baked::PROJECT_TAG, "id", "entry", "call") + } } } } diff --git a/tests/batchtxn.rs b/tests/batchtxn.rs index ee8c9bfd..00ae4b15 100644 --- a/tests/batchtxn.rs +++ b/tests/batchtxn.rs @@ -104,9 +104,8 @@ mod batchtxn_test { .serialize_xonly(); // 13 Encode the tweaked key for the payload to fund into an address. - let payload_to_fund_taproot_address = - encode_p2tr(chain, payload_to_fund_taproot_key) - .expect("Failed to encode taproot address."); + let payload_to_fund_taproot_address = encode_p2tr(chain, payload_to_fund_taproot_key) + .expect("Failed to encode taproot address."); println!( "Payload to fund taproot address: {}", @@ -140,9 +139,8 @@ mod batchtxn_test { Some(prev_payload_location), ); - let liftv1_address = - return_liftv1_address(chain, user_public_key, engine_public_key) - .expect("Failed to get liftv1 address."); + let liftv1_address = return_liftv1_address(chain, user_public_key, engine_public_key) + .expect("Failed to get liftv1 address."); println!("Liftv1 address: {}", liftv1_address); diff --git a/tests/opcodec.rs b/tests/opcodec.rs index b37b856f..6e2f1ede 100644 --- a/tests/opcodec.rs +++ b/tests/opcodec.rs @@ -3,13 +3,13 @@ mod opcodec_tests { use cube::executive::{ opcode::{ compiler::{compiler::OpcodeCompiler, compiler_error::OpcodeDecompileError}, + opcode::Opcode, opcodes::push::{ op_10::OP_10, op_11::OP_11, op_12::OP_12, op_13::OP_13, op_14::OP_14, op_15::OP_15, op_16::OP_16, op_2::OP_2, op_3::OP_3, op_4::OP_4, op_5::OP_5, op_6::OP_6, op_7::OP_7, op_8::OP_8, op_9::OP_9, op_false::OP_FALSE, op_pushdata::OP_PUSHDATA, op_true::OP_TRUE, }, - opcode::Opcode, }, stack::stack_error::StackError, }; diff --git a/tests/program.rs b/tests/program.rs index 50256ff8..ca24b8d5 100644 --- a/tests/program.rs +++ b/tests/program.rs @@ -7,8 +7,8 @@ mod executable_and_method_tests { compiler::compiler::ProgramCompiler, executable::Executable, method::{ - compiler::compiler::MethodCompiler, program_method::ProgramMethod, - method_type::MethodType, + compiler::compiler::MethodCompiler, method_type::MethodType, + program_method::ProgramMethod, }, }, opcode::{ @@ -37,8 +37,7 @@ mod executable_and_method_tests { Opcode::OP_FAIL(OP_FAIL), ]; - let method = - ProgramMethod::new(method_name, method_type, call_element_types, script); + let method = ProgramMethod::new(method_name, method_type, call_element_types, script); assert!(method.is_err()); } @@ -74,8 +73,7 @@ mod executable_and_method_tests { Opcode::OP_FAIL(OP_FAIL), ]; - let method = - ProgramMethod::new(method_name, method_type, call_element_types, script); + let method = ProgramMethod::new(method_name, method_type, call_element_types, script); assert!(method.is_err()); } @@ -92,8 +90,7 @@ mod executable_and_method_tests { Opcode::OP_PUSHDATA(OP_PUSHDATA(vec![0xde, 0xad, 0xbe, 0xef])), ]; - let method = - ProgramMethod::new(method_name, method_type, call_element_types, script); + let method = ProgramMethod::new(method_name, method_type, call_element_types, script); assert!(method.is_err()); } @@ -111,8 +108,7 @@ mod executable_and_method_tests { Opcode::OP_RETURNALL(OP_RETURNALL), ]; - let method = - ProgramMethod::new(method_name, method_type, call_element_types, script); + let method = ProgramMethod::new(method_name, method_type, call_element_types, script); assert!(method.is_err()); } @@ -129,8 +125,7 @@ mod executable_and_method_tests { Opcode::OP_RETURNALL(OP_RETURNALL), ]; - let method = - ProgramMethod::new(method_name, method_type, call_element_types, script); + let method = ProgramMethod::new(method_name, method_type, call_element_types, script); assert!(method.is_ok()); } @@ -154,8 +149,7 @@ mod executable_and_method_tests { let mut method_compiled_bytestream = method.compile().unwrap().into_iter(); - let method_decompiled = - ProgramMethod::decompile(&mut method_compiled_bytestream).unwrap(); + let method_decompiled = ProgramMethod::decompile(&mut method_compiled_bytestream).unwrap(); assert_eq!(method, method_decompiled); diff --git a/tests/stack.rs b/tests/stack.rs index e4905cda..756b71f9 100644 --- a/tests/stack.rs +++ b/tests/stack.rs @@ -1,7 +1,6 @@ #[cfg(test)] mod stack_tests { use cube::executive::{ - vm::program_execution::caller::Caller, opcode::opcodes::{ altstack::{op_fromaltstack::OP_FROMALTSTACK, op_toaltstack::OP_TOALTSTACK}, arithmetic::op_add::OP_ADD, @@ -23,6 +22,7 @@ mod stack_tests { stack_item::StackItem, stack_uint::{StackItemUintExt, StackUint}, }, + vm::program_execution::caller::Caller, }; #[test] diff --git a/tests/stack_uint.rs b/tests/stack_uint.rs index 68560a8b..0f229042 100644 --- a/tests/stack_uint.rs +++ b/tests/stack_uint.rs @@ -77,22 +77,34 @@ mod stack_uint_tests { // Test 1_000_000 let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(1000000)); - assert_eq!(stack_item.to_stack_uint().unwrap(), StackUint::from(1000000)); + assert_eq!( + stack_item.to_stack_uint().unwrap(), + StackUint::from(1000000) + ); assert_eq!(stack_item.bytes().len(), 3); // Test 16777215 let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(16777215)); - assert_eq!(stack_item.to_stack_uint().unwrap(), StackUint::from(16777215)); + assert_eq!( + stack_item.to_stack_uint().unwrap(), + StackUint::from(16777215) + ); assert_eq!(stack_item.bytes().len(), 3); // Test 16777216 (now we are in the 4-byte range) let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(16777216)); - assert_eq!(stack_item.to_stack_uint().unwrap(), StackUint::from(16777216)); + assert_eq!( + stack_item.to_stack_uint().unwrap(), + StackUint::from(16777216) + ); assert_eq!(stack_item.bytes().len(), 4); // Test 1_000_000_000 let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(1000000000)); - assert_eq!(stack_item.to_stack_uint().unwrap(), StackUint::from(1000000000)); + assert_eq!( + stack_item.to_stack_uint().unwrap(), + StackUint::from(1000000000) + ); assert_eq!(stack_item.bytes().len(), 4); // Test 4,294,967,295 @@ -136,7 +148,8 @@ mod stack_uint_tests { assert_eq!(stack_item.bytes().len(), 6); // Test 281474976710655 - let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(281474976710655_i64)); + let stack_item: StackItem = + StackItem::from_stack_uint(StackUint::from(281474976710655_i64)); assert_eq!( stack_item.to_stack_uint().unwrap(), StackUint::from(281474976710655_i64) @@ -144,7 +157,8 @@ mod stack_uint_tests { assert_eq!(stack_item.bytes().len(), 6); // Test 281474976710656 (now we are in the 7-byte range) - let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(281474976710656_i64)); + let stack_item: StackItem = + StackItem::from_stack_uint(StackUint::from(281474976710656_i64)); assert_eq!( stack_item.to_stack_uint().unwrap(), StackUint::from(281474976710656_i64) @@ -152,7 +166,8 @@ mod stack_uint_tests { assert_eq!(stack_item.bytes().len(), 7); // Test 72057594037927935 - let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(72057594037927935_i64)); + let stack_item: StackItem = + StackItem::from_stack_uint(StackUint::from(72057594037927935_i64)); assert_eq!( stack_item.to_stack_uint().unwrap(), StackUint::from(72057594037927935_i64) @@ -160,7 +175,8 @@ mod stack_uint_tests { assert_eq!(stack_item.bytes().len(), 7); // Test 72057594037927936 (now we are in the 8-byte range) - let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(72057594037927936_i64)); + let stack_item: StackItem = + StackItem::from_stack_uint(StackUint::from(72057594037927936_i64)); assert_eq!( stack_item.to_stack_uint().unwrap(), StackUint::from(72057594037927936_i64) @@ -168,7 +184,8 @@ mod stack_uint_tests { assert_eq!(stack_item.bytes().len(), 8); // Test 18446744073709551615 - let stack_item: StackItem = StackItem::from_stack_uint(StackUint::from(18446744073709551615_u64)); + let stack_item: StackItem = + StackItem::from_stack_uint(StackUint::from(18446744073709551615_u64)); assert_eq!( stack_item.to_stack_uint().unwrap(), StackUint::from(18446744073709551615_u64) From 3ea9749ba4e8a24e04d5c6b003e2857c30aa0272 Mon Sep 17 00:00:00 2001 From: GideonBature Date: Fri, 5 Jun 2026 22:28:51 +0100 Subject: [PATCH 2/4] Fix clippy errors and warnings --- Cargo.toml | 10 + src/communicative/nns/client.rs | 8 +- src/communicative/nns/relay.rs | 6 +- src/communicative/peer/manager.rs | 19 +- src/communicative/peer/peer.rs | 45 ++- .../rpc/bitcoin_rpc/bitcoin_rpc.rs | 2 +- .../ping/server/handle_ping_request.rs | 2 +- src/communicative/tcp/server/connection.rs | 8 +- src/communicative/tcp/server/server.rs | 2 +- src/communicative/tcp/tcp.rs | 21 +- .../bitcoiny/batch_record/batch_record.rs | 2 +- .../signed_batch_txn/signed_batch_txn.rs | 12 +- src/constructive/bitcoiny/taproot.rs | 27 +- src/constructive/bitcoiny/txn/ext.rs | 2 +- .../calldata/calldata_element_type.rs | 4 +- .../calldata_elements/ape/decode/decode.rs | 10 +- .../calldata_elements/ape/encode/encode.rs | 4 +- .../calldata_elements/calldata_element.rs | 15 +- .../calldata_elements/sbe/decode/decode.rs | 2 +- .../calldata_elements/sbe/decode/list.rs | 4 +- .../account/ext/codec/ape/decode/decode.rs | 8 +- .../ext/codec/ape/decode/decode.rs | 11 +- .../account/root_account/root_account.rs | 20 +- .../entities/contract/ape/decode/decode.rs | 9 +- .../maybe_common/ape/decode/decode.rs | 4 +- .../valtypes/val/long_val/long_val.rs | 2 +- .../valtypes/val/short_val/short_val.rs | 2 +- .../entry/ext/codec/ape/encode/encode.rs | 4 +- .../entry/ext/codec/sbe/decode/decode.rs | 4 +- .../entry/ext/codec/sbe/encode/encode.rs | 2 +- .../call/ext/codec/sbe/decode/decode.rs | 6 +- .../liftup/ext/codec/ape/decode/decode.rs | 6 +- .../liftup/ext/codec/ape/encode/encode.rs | 4 +- .../liftup/ext/signature/sighash/sighash.rs | 2 +- .../lift/lift_versions/liftv1/liftv1.rs | 2 +- .../lift/lift_versions/liftv2/liftv2.rs | 14 +- .../txout_types/payload/payload.rs | 13 +- src/executive/exec_ctx/exec_ctx.rs | 12 +- .../opcodes/opcodes/arithmetic/op_lshift.rs | 6 +- .../opcodes/opcodes/digest/op_blake2bvar.rs | 2 +- .../opcodes/opcodes/digest/op_blake2svar.rs | 2 +- .../opcodes/opcodes/digest/op_taggedhash.rs | 5 +- .../vm/opcodes/opcodes/push/op_pushdata.rs | 4 +- .../opcodes/shadowing/op_shadow_alloc.rs | 2 +- .../opcodes/shadowing/op_shadow_dealloc.rs | 2 +- .../opcodes/shadowing/op_shadow_down.rs | 2 +- .../opcodes/shadowing/op_shadow_down_all.rs | 2 +- .../opcodes/opcodes/shadowing/op_shadow_up.rs | 2 +- .../opcodes/shadowing/op_shadow_up_all.rs | 2 +- .../vm/opcodes/opcodes/storage/op_swrite.rs | 2 +- src/executive/vm/program/compiler/compiler.rs | 6 +- .../vm/program/method/compiler/compiler.rs | 6 +- .../vm/program/method/program_method.rs | 34 +- src/executive/vm/program/program.rs | 7 +- src/executive/vm/program_execution/exec.rs | 291 ++++++++---------- .../vm/program_execution/program_exec_ctx.rs | 7 +- src/executive/vm/stack/stack.rs | 6 + src/executive/vm/stack/stack_holder.rs | 4 +- src/executive/vm/stack/stack_item.rs | 5 + .../archival_manager/archival_manager.rs | 28 +- .../bodies/account_body/account_body.rs | 4 +- .../bodies/contract_body/contract_body.rs | 4 +- .../shadow_space/shadow_space.rs | 16 +- src/inscriptive/coin_manager/coin_manager.rs | 23 +- src/inscriptive/coin_manager/delta/delta.rs | 6 +- .../flame_selection/flame_selection.rs | 8 +- src/inscriptive/flame_manager/delta/delta.rs | 2 +- src/inscriptive/flame_manager/flame/flame.rs | 2 +- .../flame_manager/flame_manager.rs | 16 +- src/inscriptive/graveyard/graveyard.rs | 39 ++- .../params_manager/params_manager.rs | 4 +- .../periodic_resource/periodic_resource.rs | 10 +- .../elements/liveness_flag/liveness_flag.rs | 2 +- .../privileges_manager/privileges_manager.rs | 8 +- src/inscriptive/registry/delta/delta.rs | 19 +- src/inscriptive/registry/registry.rs | 24 +- src/inscriptive/state_manager/delta/delta.rs | 4 +- .../state_manager/state_manager.rs | 36 +-- src/inscriptive/sync_manager/sync_manager.rs | 4 +- src/inscriptive/utxo_set/utxo_set.rs | 34 +- src/operative/cli/cli.rs | 10 +- .../commands/common_commands/runexplorer.rs | 8 +- .../cli/commands/node_commands/comp.rs | 6 +- src/operative/main.rs | 21 +- src/operative/run_args/chain.rs | 16 +- src/operative/run_args/operating_kind.rs | 14 +- src/operative/run_args/resource_mode.rs | 14 +- src/operative/run_args/sync_mode.rs | 14 +- src/operative/runner/runner.rs | 25 +- .../tasks/engine_session/engine_session.rs | 2 +- .../session_pool/session_pool.rs | 2 +- src/transmutative/bls/key.rs | 4 +- src/transmutative/codec/address.rs | 6 +- src/transmutative/codec/csv.rs | 4 +- src/transmutative/codec/prefix.rs | 2 +- src/transmutative/hash.rs | 14 +- src/transmutative/key.rs | 5 +- src/transmutative/musig/keyagg.rs | 28 +- src/transmutative/musig/session.rs | 59 ++-- src/transmutative/secp/authenticable.rs | 5 +- src/transmutative/secp/into.rs | 15 +- src/transmutative/secp/schnorr.rs | 10 +- tests/batchtxn.rs | 12 +- tests/bls.rs | 5 +- tests/coin_manager.rs | 12 +- tests/graveyard.rs | 6 +- tests/key.rs | 9 +- tests/musig.rs | 6 +- tests/schnorr.rs | 13 +- tests/simul.rs | 6 +- tests/taproot.rs | 13 +- 111 files changed, 621 insertions(+), 767 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0983fc54..9bc21ad1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,3 +39,13 @@ path = "src/lib.rs" [[bin]] name = "cube" path = "src/operative/main.rs" + +[lints.clippy] +module_inception = "allow" +result_large_err = "allow" +too_many_arguments = "allow" +wrong_self_convention = "allow" +large_enum_variant = "allow" +manual_div_ceil = "allow" +assign_op_pattern = "allow" +manual_async_fn = "allow" diff --git a/src/communicative/nns/client.rs b/src/communicative/nns/client.rs index ce9f9c67..f88d9168 100644 --- a/src/communicative/nns/client.rs +++ b/src/communicative/nns/client.rs @@ -55,10 +55,8 @@ impl NNSClient { .send_event_builder(note_publish_event) .await { - Ok(ok) => { - return Some(ok.as_bytes().to_owned()); - } - Err(_) => return None, - }; + Ok(ok) => Some(ok.as_bytes().to_owned()), + Err(_) => None, + } } } diff --git a/src/communicative/nns/relay.rs b/src/communicative/nns/relay.rs index 920bad8d..e59a9d3e 100644 --- a/src/communicative/nns/relay.rs +++ b/src/communicative/nns/relay.rs @@ -1,5 +1,3 @@ -use std::future::Future; - pub const DEFAULT_RELAY_LIST: [&str; 5] = [ "wss://relay.damus.io", "wss://relay.primal.net", @@ -9,11 +7,11 @@ pub const DEFAULT_RELAY_LIST: [&str; 5] = [ ]; pub trait Relay { - fn add_default_relay_list(&self) -> impl Future + Send; + fn add_default_relay_list(&self) -> impl std::future::Future + Send; } impl Relay for nostr_sdk::Client { - fn add_default_relay_list(&self) -> impl Future + Send { + fn add_default_relay_list(&self) -> impl std::future::Future + Send { async move { // Add the list of default relays. for relay in DEFAULT_RELAY_LIST { diff --git a/src/communicative/peer/manager.rs b/src/communicative/peer/manager.rs index e1ca7187..07a47551 100644 --- a/src/communicative/peer/manager.rs +++ b/src/communicative/peer/manager.rs @@ -30,7 +30,7 @@ impl PeerManager { chain: Chain, nns_client: &NNSClient, kind: PeerKind, - keys: &Vec<[u8; 32]>, + keys: &[[u8; 32]], ) -> Option { let manager_ = PeerManager { chain, @@ -81,10 +81,7 @@ impl PeerManager { } pub fn is_peer(&self, key: [u8; 32]) -> bool { - match self.retrieve_peer(key) { - Some(_) => return true, - None => return false, - } + self.retrieve_peer(key).is_some() } pub async fn peer_socket(&self, key: [u8; 32]) -> Option { @@ -104,22 +101,19 @@ impl PeerManager { _peer.connection() }; - match conn { - Some(_) => return true, - None => return false, - } + conn.is_some() } } #[async_trait] pub trait PeerManagerExt { - async fn add_peers(&mut self, kind: PeerKind, keys: &Vec<[u8; 32]>) -> u64; + async fn add_peers(&mut self, kind: PeerKind, keys: &[[u8; 32]]) -> u64; } #[async_trait] impl PeerManagerExt for PEER_MANAGER { /// Tries to connect to a list of peers and returns the number of peers connected. - async fn add_peers(&mut self, kind: PeerKind, keys: &Vec<[u8; 32]>) -> u64 { + async fn add_peers(&mut self, kind: PeerKind, keys: &[[u8; 32]]) -> u64 { let chain = { let _self = self.lock().await; _self.chain() @@ -138,8 +132,7 @@ impl PeerManagerExt for PEER_MANAGER { } let peer_list_ = Arc::clone(&peer_list_); - let kind = kind.clone(); - let key = key.clone(); + let key = *key; let nns_client = { let _self = self.lock().await; _self.nns_client.clone() diff --git a/src/communicative/peer/peer.rs b/src/communicative/peer/peer.rs index 264ecd3b..ea0a4e9f 100644 --- a/src/communicative/peer/peer.rs +++ b/src/communicative/peer/peer.rs @@ -53,7 +53,7 @@ impl Peer { nns_client: &NNSClient, ) -> Result { let (socket_, addr) = { - match connect_nns(key, &nns_client, chain).await { + match connect_nns(key, nns_client, chain).await { Ok(socket) => { let addr = match socket.peer_addr() { Ok(addr) => addr, @@ -106,10 +106,7 @@ impl Peer { } pub fn connected(&self) -> bool { - match self.connection() { - Some(_) => true, - None => false, - } + self.connection().is_some() } pub fn socket(&self) -> Option { @@ -123,12 +120,10 @@ impl Peer { pub fn addr(&self) -> String { match self.connection() { Some(connection) => { - return format!("{}:{}", connection.1.ip(), connection.1.port()); - } - None => { - return "Dead.".to_string(); + format!("{}:{}", connection.1.ip(), connection.1.port()) } - }; + None => "Dead.".to_string(), + } } } @@ -155,22 +150,20 @@ impl PeerConnection for PEER { async fn disconnection(&self) { loop { - loop { - match self.ping().await { - Ok(_) => break, - Err(_) => { - let mut failure_iter: u8 = 0; - loop { - if failure_iter < 3 { - failure_iter += 1; - tokio::time::sleep(Duration::from_secs(5)).await; - continue; - } else { - let mut _peer = self.lock().await; - _peer.set_connection(None); - - return (); - } + match self.ping().await { + Ok(_) => {} + Err(_) => { + let mut failure_iter: u8 = 0; + loop { + if failure_iter < 3 { + failure_iter += 1; + tokio::time::sleep(Duration::from_secs(5)).await; + continue; + } else { + let mut _peer = self.lock().await; + _peer.set_connection(None); + + return; } } } diff --git a/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs b/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs index 7e6f18bc..caa1acee 100644 --- a/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs +++ b/src/communicative/rpc/bitcoin_rpc/bitcoin_rpc.rs @@ -105,7 +105,7 @@ pub fn get_mempool_min_fee_rate( // Bitcoin Core returns mempool minimum fee as BTC/kvB. // Convert BTC/kvB -> sat/kvB -> sat/vbyte, rounded up to avoid underpaying. let mempool_min_fee_sat_per_kvb = mempool_info.mempool_min_fee.to_sat(); - let mempool_min_fee_sat_per_vbyte = ((mempool_min_fee_sat_per_kvb + 999) / 1000).max(1); + let mempool_min_fee_sat_per_vbyte = mempool_min_fee_sat_per_kvb.div_ceil(1000).max(1); Ok(mempool_min_fee_sat_per_vbyte) } diff --git a/src/communicative/tcp/protocol/ping/server/handle_ping_request.rs b/src/communicative/tcp/protocol/ping/server/handle_ping_request.rs index d1d1f663..e480b760 100644 --- a/src/communicative/tcp/protocol/ping/server/handle_ping_request.rs +++ b/src/communicative/tcp/protocol/ping/server/handle_ping_request.rs @@ -4,7 +4,7 @@ use crate::communicative::tcp::package::{PackageKind, TCPPackage}; /// Builds the ping response package, or `None` if the request payload is invalid. pub async fn handle_ping_request(timestamp: i64, payload: &[u8]) -> Option { - if payload != &[0x00] { + if payload != [0x00] { return None; } diff --git a/src/communicative/tcp/server/connection.rs b/src/communicative/tcp/server/connection.rs index 456e7fdd..a8346d73 100644 --- a/src/communicative/tcp/server/connection.rs +++ b/src/communicative/tcp/server/connection.rs @@ -24,7 +24,7 @@ pub async fn handle_socket( let mut package_kind_buffer = [0; 1]; match tcp::read( - &mut *_socket, + &mut _socket, &mut package_kind_buffer, Some(IDLE_CLIENT_TIMEOUT), ) @@ -44,7 +44,7 @@ pub async fn handle_socket( let timeout_duration = PAYLOAD_READ_TIMEOUT; let mut timestamp_buffer = [0; 8]; - match tcp::read(&mut *_socket, &mut timestamp_buffer, Some(timeout_duration)).await { + match tcp::read(&mut _socket, &mut timestamp_buffer, Some(timeout_duration)).await { Ok(_) => (), Err(tcp::TCPError::ConnErr) => break, Err(tcp::TCPError::Timeout) => continue, @@ -58,7 +58,7 @@ pub async fn handle_socket( }; let mut payload_len_buffer = [0; 4]; - match tcp::read(&mut *_socket, &mut payload_len_buffer, Some(remaining_time)).await { + match tcp::read(&mut _socket, &mut payload_len_buffer, Some(remaining_time)).await { Ok(_) => (), Err(tcp::TCPError::ConnErr) => break, Err(tcp::TCPError::Timeout) => continue, @@ -75,7 +75,7 @@ pub async fn handle_socket( match payload_len { 0 => continue, _ => { - match tcp::read(&mut *_socket, &mut payload_bufer, Some(remaining_time)).await { + match tcp::read(&mut _socket, &mut payload_bufer, Some(remaining_time)).await { Ok(_) => (), Err(tcp::TCPError::ConnErr) => break, Err(tcp::TCPError::Timeout) => continue, diff --git a/src/communicative/tcp/server/server.rs b/src/communicative/tcp/server/server.rs index 5126b059..c6074efd 100644 --- a/src/communicative/tcp/server/server.rs +++ b/src/communicative/tcp/server/server.rs @@ -68,6 +68,6 @@ pub async fn run( .await; }); }, - OperatingKind::Node => return, + OperatingKind::Node => (), } } diff --git a/src/communicative/tcp/tcp.rs b/src/communicative/tcp/tcp.rs index 622138a6..02ea5f02 100644 --- a/src/communicative/tcp/tcp.rs +++ b/src/communicative/tcp/tcp.rs @@ -42,7 +42,7 @@ pub async fn open_port(chain: Chain) -> bool { }; for result in add_ports([upnp_config]) { - if let Ok(_) = result { + if result.is_ok() { return true; } } @@ -199,7 +199,7 @@ pub async fn request( let timeout_duration = timeout.unwrap_or(Duration::from_millis(3_000)); // Default timeout: 3000 ms // Write the request buffer with timeout. - write(&mut *_socket, &package.serialize(), Some(timeout_duration)).await?; + write(&mut _socket, &package.serialize(), Some(timeout_duration)).await?; let remaining_time = timeout_duration .checked_sub(start.elapsed()) @@ -214,7 +214,7 @@ pub async fn request( .ok_or(TCPError::Timeout)?; - let response_package = match pop(&mut *_socket, Some(remaining_time)).await { + let response_package = match pop(&mut _socket, Some(remaining_time)).await { Some(package) => package, None => return Err(TCPError::Timeout), }; @@ -232,13 +232,12 @@ pub async fn request( } pub async fn connectivity() -> bool { - match tokio::time::timeout( - Duration::from_secs(TCP_RESPONSE_TIMEOUT), - TcpStream::connect("8.8.8.8:53"), + matches!( + tokio::time::timeout( + Duration::from_secs(TCP_RESPONSE_TIMEOUT), + TcpStream::connect("8.8.8.8:53"), + ) + .await, + Ok(Ok(_stream)) ) - .await - { - Ok(Ok(_stream)) => true, - _ => false, - } } diff --git a/src/constructive/bitcoiny/batch_record/batch_record.rs b/src/constructive/bitcoiny/batch_record/batch_record.rs index d5c5e8e1..cd832165 100644 --- a/src/constructive/bitcoiny/batch_record/batch_record.rs +++ b/src/constructive/bitcoiny/batch_record/batch_record.rs @@ -156,7 +156,7 @@ impl BatchRecord { Value::Array( self.expired_projector_outpoints .iter() - .map(|op| json_outpoint(op)) + .map(json_outpoint) .collect(), ), ); diff --git a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs index be834991..b65afd4f 100644 --- a/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs +++ b/src/constructive/bitcoiny/batch_txn/signed_batch_txn/signed_batch_txn.rs @@ -55,10 +55,8 @@ impl SignedBatchTxn { engine_keyholder: &KeyHolder, ) -> Result { // Prev projectors are not supported for the time being - { - if prev_projectors.len() != 0 { - return Err(SignedBatchTxnConstructError::PrevProjectorsNotSupportedError); - } + if !prev_projectors.is_empty() { + return Err(SignedBatchTxnConstructError::PrevProjectorsNotSupportedError); }; let prev_payload_tx_input: (OutPoint, TxOut) = match prev_payload.location() { @@ -72,7 +70,7 @@ impl SignedBatchTxn { projector .location .as_ref() - .map(|(outpoint, txout)| (outpoint.clone(), txout.clone())) + .map(|(outpoint, txout)| (*outpoint, txout.clone())) .ok_or(SignedBatchTxnConstructError::ProjectorLocationNotFoundError) }) .collect::, _>>()?; @@ -231,7 +229,7 @@ impl SignedBatchTxn { let tx_inputs: Vec<(OutPoint, TxOut, Witness)> = unsigned_batch_txn .tx_inputs .into_iter() - .zip(tx_input_witnesses.into_iter()) + .zip(tx_input_witnesses) .map(|((outpoint, txout), witness)| (outpoint, txout, witness)) .collect(); @@ -245,7 +243,7 @@ impl SignedBatchTxn { pub fn tx_input_outpoints(&self) -> Vec { self.tx_inputs .iter() - .map(|(outpoint, _, _)| outpoint.clone()) + .map(|(outpoint, _, _)| *outpoint) .collect() } diff --git a/src/constructive/bitcoiny/taproot.rs b/src/constructive/bitcoiny/taproot.rs index 45ae9fe6..eeb06474 100644 --- a/src/constructive/bitcoiny/taproot.rs +++ b/src/constructive/bitcoiny/taproot.rs @@ -161,11 +161,10 @@ impl TapRoot { } pub fn tap_branch(&self) -> [u8; 32] { - let uppermost_branch = match &self.tree { + match &self.tree { Some(tree) => tree.tap_branch(), None => [0x00u8; 32], - }; - uppermost_branch + } } pub fn tap_tweak(&self) -> [u8; 32] { @@ -176,7 +175,7 @@ impl TapRoot { } pub fn tweaked_key(&self) -> Option { - if let Some(_) = &self.tree { + if self.tree.is_some() { let tweak = Scalar::from_slice(&self.tap_tweak()).ok()?; let tweaked_key = self.inner_key_lifted() + tweak.base_point_mul(); @@ -249,17 +248,16 @@ impl TapTree { pub fn path(&self, index: usize) -> Vec { // Given leaf index return the merkle path - let path_vec = match tree_builder(&self.leaves, Some(index)).1 { + match tree_builder(&self.leaves, Some(index)).1 { Some(vec) => vec, None => panic!(), - }; - path_vec + } } } // tree_builder returns given a vector of leaves, the tree root, // and optionally a merkle path corresponding to some leaf -pub fn tree_builder(leaves: &Vec, index: Option) -> (Branch, Option>) { +pub fn tree_builder(leaves: &[TapLeaf], index: Option) -> (Branch, Option>) { // Initialize path as empty let path: Vec = Vec::::new(); @@ -275,10 +273,7 @@ pub fn tree_builder(leaves: &Vec, index: Option) -> (Branch, Opt } _ => { let mut path: Vec = Vec::::new(); - let mut lookup: Option = match index.clone() { - Some(index) => Some(leaves[index].into_branch()), - None => None, - }; + let mut lookup: Option = index.map(|index| leaves[index].into_branch()); // Number of TapTree levels is = log2(number of TapLeaves) let num_levels: u8 = (leaves.len() as f64).log2() as u8; @@ -290,8 +285,8 @@ pub fn tree_builder(leaves: &Vec, index: Option) -> (Branch, Opt for level in 0..(num_levels + 1) { // If it is the level zero, initialize current_level with individual TapLeaves if level == 0 { - for i in 0..leaves.len() { - current_level.push(leaves[i].clone().into_branch()); + for leaf in leaves.iter() { + current_level.push(leaf.clone().into_branch()); } } else { // If it is the level one or above, move above_level items into current_level, and reset above_level @@ -341,10 +336,10 @@ pub fn tree_builder(leaves: &Vec, index: Option) -> (Branch, Opt // Lookup match? let mut match_bool: bool = false; - if &first_bytes == &lookup_bytes { + if first_bytes == lookup_bytes { path.extend(&second_bytes); match_bool = true; - } else if &second_bytes == &lookup_bytes { + } else if second_bytes == lookup_bytes { path.extend(&first_bytes); match_bool = true; } diff --git a/src/constructive/bitcoiny/txn/ext.rs b/src/constructive/bitcoiny/txn/ext.rs index 72c7cea2..76b12f9d 100644 --- a/src/constructive/bitcoiny/txn/ext.rs +++ b/src/constructive/bitcoiny/txn/ext.rs @@ -89,7 +89,7 @@ impl TxOutExt for TxOut { // Extend bytes. bytes.extend_from_slice(&value); bytes.extend_from_slice(&script_pubkey_len); - bytes.extend_from_slice(&script_pubkey); + bytes.extend_from_slice(script_pubkey); bytes } diff --git a/src/constructive/core_types/calldata/calldata_element_type.rs b/src/constructive/core_types/calldata/calldata_element_type.rs index 35c60f46..bb2cb4f0 100644 --- a/src/constructive/core_types/calldata/calldata_element_type.rs +++ b/src/constructive/core_types/calldata/calldata_element_type.rs @@ -62,9 +62,7 @@ impl CalldataElementType { Some(0x04) => Some(CalldataElementType::Bool), Some(0x05) => Some(CalldataElementType::Account), Some(0x06) => Some(CalldataElementType::Contract), - Some(0x07) => bytecode_stream - .next() - .map(|index| CalldataElementType::Bytes(index)), + Some(0x07) => bytecode_stream.next().map(CalldataElementType::Bytes), Some(0x08) => Some(CalldataElementType::Varbytes), Some(0x09) => Some(CalldataElementType::Payable), _ => None, diff --git a/src/constructive/core_types/calldata/calldata_elements/ape/decode/decode.rs b/src/constructive/core_types/calldata/calldata_elements/ape/decode/decode.rs index 2fd94aca..a63782a1 100644 --- a/src/constructive/core_types/calldata/calldata_elements/ape/decode/decode.rs +++ b/src/constructive/core_types/calldata/calldata_elements/ape/decode/decode.rs @@ -25,7 +25,7 @@ impl CalldataElement { /// * `element_type` - The type of the `CallElement`. /// * `registry_manager` - The `Registry Manager`. /// * `decode_rank_as_longval` - Whether to decode the rank value as a `LongVal` or a `ShortVal`. - pub async fn decode_ape<'a>( + pub async fn decode_ape( bit_stream: &mut bit_vec::Iter<'_>, element_type: CalldataElementType, registry: ®ISTRY, @@ -142,7 +142,7 @@ impl CalldataElement { // Decode the `Account`. CalldataElementType::Account => { // Decode the `Account`. - let account = Account::decode_ape(bit_stream, ®istry, decode_rank_as_longval) + let account = Account::decode_ape(bit_stream, registry, decode_rank_as_longval) .await .map_err(|e| { CalldataElementAPEDecodeError::Account( @@ -160,7 +160,7 @@ impl CalldataElement { // Decode the `Contract`. CalldataElementType::Contract => { // Decode the `Contract`. - let contract = Contract::decode_ape(bit_stream, ®istry, decode_rank_as_longval) + let contract = Contract::decode_ape(bit_stream, registry, decode_rank_as_longval) .await .map_err(|e| { CalldataElementAPEDecodeError::Contract( @@ -181,14 +181,14 @@ impl CalldataElement { let byte_length = index as usize + 1; // Check if the data length is valid. - if byte_length < 1 || byte_length > 256 { + if !(1..=256).contains(&byte_length) { return Err(CalldataElementAPEDecodeError::Bytes( BytesAPEDecodeError::InvalidBytesLength(byte_length), )); } // Get the number of bits to collect. - let bit_length = byte_length as usize * 8; + let bit_length = byte_length * 8; // Collect the data bits. let mut data_bits = BitVec::new(); diff --git a/src/constructive/core_types/calldata/calldata_elements/ape/encode/encode.rs b/src/constructive/core_types/calldata/calldata_elements/ape/encode/encode.rs index 23a4cd6d..cc4865fa 100644 --- a/src/constructive/core_types/calldata/calldata_elements/ape/encode/encode.rs +++ b/src/constructive/core_types/calldata/calldata_elements/ape/encode/encode.rs @@ -84,7 +84,7 @@ impl CalldataElement { let bits = account .encode_ape(registry, encode_account_rank_as_longval) .await - .map_err(|e| CalldataElementAPEEncodeError::AccountAPEEncodeError(e))?; + .map_err(CalldataElementAPEEncodeError::AccountAPEEncodeError)?; // Return the bits. Ok(bits) @@ -94,7 +94,7 @@ impl CalldataElement { let bits = contract .encode_ape(registry, encode_contract_rank_as_longval) .await - .map_err(|e| CalldataElementAPEEncodeError::ContractAPEEncodeError(e))?; + .map_err(CalldataElementAPEEncodeError::ContractAPEEncodeError)?; // Return the bits. Ok(bits) diff --git a/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs b/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs index 6cdfa555..21537859 100644 --- a/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs +++ b/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs @@ -85,10 +85,9 @@ impl CalldataElement { let value_as_stack_uint = StackUint::from_u32(value_as_u32); // Convert the value to a `StackItem`. - let value_as_stack_item = StackItem::from_stack_uint(value_as_stack_uint); // Return the stack item. - value_as_stack_item + StackItem::from_stack_uint(value_as_stack_uint) } // 0-2 bytes in stack. CalldataElement::U16(value) => { @@ -99,10 +98,9 @@ impl CalldataElement { let value_as_stack_uint = StackUint::from_u32(value_as_u32); // Convert the value to a `StackItem`. - let value_as_stack_item = StackItem::from_stack_uint(value_as_stack_uint); // Return the stack item. - value_as_stack_item + StackItem::from_stack_uint(value_as_stack_uint) } // 0-4 bytes in stack. CalldataElement::U32(value) => { @@ -110,10 +108,9 @@ impl CalldataElement { let value_as_stack_uint = StackUint::from_u32(*value); // Convert the value to a `StackItem`. - let value_as_stack_item = StackItem::from_stack_uint(value_as_stack_uint); // Return the stack item. - value_as_stack_item + StackItem::from_stack_uint(value_as_stack_uint) } // 0-8 bytes in stack. CalldataElement::U64(value) => { @@ -121,10 +118,9 @@ impl CalldataElement { let value_as_stack_uint = StackUint::from_u64(*value); // Convert the value to a `StackItem`. - let value_as_stack_item = StackItem::from_stack_uint(value_as_stack_uint); // Return the stack item. - value_as_stack_item + StackItem::from_stack_uint(value_as_stack_uint) } // 0-1 bytes in stack. CalldataElement::Bool(value) => match value { @@ -147,10 +143,9 @@ impl CalldataElement { let value_as_stack_uint = StackUint::from_u32(*value); // Convert the value to a `StackItem`. - let value_as_stack_item = StackItem::from_stack_uint(value_as_stack_uint); // Return the stack item. - value_as_stack_item + StackItem::from_stack_uint(value_as_stack_uint) } } } diff --git a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs index 5ab8c85b..15f0dd67 100644 --- a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs +++ b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/decode.rs @@ -129,7 +129,7 @@ impl CalldataElement { } CalldataElementType::Bytes(index) => { let byte_length = index as usize + 1; - if byte_length < 1 || byte_length > 256 { + if !(1..=256).contains(&byte_length) { return Err(CalldataElementSBEDecodeError::Bytes( BytesSBEDecodeError::InvalidBytesLength(byte_length), )); diff --git a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs index a163f485..fa74e793 100644 --- a/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs +++ b/src/constructive/core_types/calldata/calldata_elements/sbe/decode/list.rs @@ -21,8 +21,8 @@ pub fn decode_calldata_elements_sbe( let mut elements = Vec::with_capacity(count); for _ in 0..count { - let (element, remaining) = CalldataElement::decode_sbe(rest) - .map_err(|e| CalldataElementsSBEDecodeError::Element(e))?; + let (element, remaining) = + CalldataElement::decode_sbe(rest).map_err(CalldataElementsSBEDecodeError::Element)?; elements.push(element); rest = remaining; } diff --git a/src/constructive/core_types/entities/account/account/ext/codec/ape/decode/decode.rs b/src/constructive/core_types/entities/account/account/ext/codec/ape/decode/decode.rs index aacfdfc5..37fbd69f 100644 --- a/src/constructive/core_types/entities/account/account/ext/codec/ape/decode/decode.rs +++ b/src/constructive/core_types/entities/account/account/ext/codec/ape/decode/decode.rs @@ -17,12 +17,12 @@ impl Account { let rank: u64 = match decode_rank_as_longval { // 1.a The rank is decoded as a `LongVal`. true => LongVal::decode_ape(bit_stream) - .map_err(|e| AccountAPEDecodeError::FailedToDecodeRankValueAsLongVal(e))? + .map_err(AccountAPEDecodeError::FailedToDecodeRankValueAsLongVal)? .value(), // 1.b The rank is decoded as a `ShortVal`. false => ShortVal::decode_ape(bit_stream) - .map_err(|e| AccountAPEDecodeError::FailedToDecodeRankValueAsShortVal(e))? + .map_err(AccountAPEDecodeError::FailedToDecodeRankValueAsShortVal)? .value() as u64, }; @@ -52,7 +52,7 @@ impl Account { let account = Account::UnregisteredAccount(unregistered_account); // 2.a.6 Return the unregistered `Account`. - return Ok(account); + Ok(account) } // 2.b The `Account` is registered. @@ -69,7 +69,7 @@ impl Account { }; // 2.b.2 Return the `Account`. - return Ok(account); + Ok(account) } } } diff --git a/src/constructive/core_types/entities/account/root_account/ext/codec/ape/decode/decode.rs b/src/constructive/core_types/entities/account/root_account/ext/codec/ape/decode/decode.rs index 352917b5..2cbfc23b 100644 --- a/src/constructive/core_types/entities/account/root_account/ext/codec/ape/decode/decode.rs +++ b/src/constructive/core_types/entities/account/root_account/ext/codec/ape/decode/decode.rs @@ -28,19 +28,18 @@ impl RootAccount { // 1.a The rank is decoded as a `LongVal`. true => { // 1.a.1 Decode the rank value as a `LongVal`. - let rank = LongVal::decode_ape(bit_stream) - .map_err(|e| RootAccountAPEDecodeError::FailedToDecodeRankValueAsLongVal(e))? - .value(); // 1.a.2 Return the rank value as a `u64`. - rank + LongVal::decode_ape(bit_stream) + .map_err(RootAccountAPEDecodeError::FailedToDecodeRankValueAsLongVal)? + .value() } // 1.b The rank is decoded as a `ShortVal`. false => { // 1.b.1 Decode the rank value as a `ShortVal`. let rank = ShortVal::decode_ape(bit_stream) - .map_err(|e| RootAccountAPEDecodeError::FailedToDecodeRankValueAsShortVal(e))? + .map_err(RootAccountAPEDecodeError::FailedToDecodeRankValueAsShortVal)? .value(); // 1.b.2 Return the rank value as a `u64`. @@ -370,7 +369,7 @@ impl RootAccount { ); // 2.b.2.b.6 Return the `RootAccount`. - return Ok(root_account); + Ok(root_account) } } } diff --git a/src/constructive/core_types/entities/account/root_account/root_account.rs b/src/constructive/core_types/entities/account/root_account/root_account.rs index 57acbe6a..95445514 100644 --- a/src/constructive/core_types/entities/account/root_account/root_account.rs +++ b/src/constructive/core_types/entities/account/root_account/root_account.rs @@ -65,12 +65,11 @@ impl RootAccount { ); // 5.a.1.a.2 Construct the `RootAccount`. - let root_account = Self::RegisteredAndConfiguredRootAccount( - registered_and_configured_root_account, - ); // 5.a.1.a.3 Return the `RootAccount`. - root_account + Self::RegisteredAndConfiguredRootAccount( + registered_and_configured_root_account, + ) } // 5.a.1.b The BLS key is not configured. @@ -95,12 +94,11 @@ impl RootAccount { ); // 5.a.1.b.3 Construct the `RootAccount`. - let root_account = Self::RegisteredButUnconfiguredRootAccount( - registered_but_unconfigured_root_account, - ); // 5.a.1.b.4 Return the `RootAccount`. - root_account + Self::RegisteredButUnconfiguredRootAccount( + registered_but_unconfigured_root_account, + ) } } } @@ -125,10 +123,9 @@ impl RootAccount { ); // 5.b.3 Construct the `RootAccount`. - let root_account = Self::UnregisteredRootAccount(unregistered_root_account); // 5.b.4 Return the `RootAccount`. - root_account + Self::UnregisteredRootAccount(unregistered_root_account) } } } @@ -253,10 +250,9 @@ pub fn bls_key_authorization_message( preimage.extend(flame_config_hash); // 6 Hash the preimage to get the message. - let message = preimage.hash(Some(HashTag::BLSKeyAuthorizationMessage)); // 7 Return the message. - message + preimage.hash(Some(HashTag::BLSKeyAuthorizationMessage)) } /// Verifies the BLS key authorization signature. diff --git a/src/constructive/core_types/entities/contract/ape/decode/decode.rs b/src/constructive/core_types/entities/contract/ape/decode/decode.rs index 5738ae32..ee5397a8 100644 --- a/src/constructive/core_types/entities/contract/ape/decode/decode.rs +++ b/src/constructive/core_types/entities/contract/ape/decode/decode.rs @@ -18,19 +18,18 @@ impl Contract { // 1.a The rank is decoded as a `LongVal`. true => { // 1.a.1 Decode the rank value as a `LongVal`. - let rank = LongVal::decode_ape(bit_stream) - .map_err(|e| ContractAPEDecodeError::FailedToDecodeRankValueAsLongVal(e))? - .value(); // 1.a.2 Return the rank value as a `u64`. - rank + LongVal::decode_ape(bit_stream) + .map_err(ContractAPEDecodeError::FailedToDecodeRankValueAsLongVal)? + .value() } // 1.b The rank is decoded as a `ShortVal`. false => { // 1.b.1 Decode the rank value as a `ShortVal`. let rank = ShortVal::decode_ape(bit_stream) - .map_err(|e| ContractAPEDecodeError::FailedToDecodeRankValueAsShortVal(e))? + .map_err(ContractAPEDecodeError::FailedToDecodeRankValueAsShortVal)? .value(); // 1.b.2 Return the rank value as a `u64`. diff --git a/src/constructive/core_types/valtypes/maybe_common/maybe_common/ape/decode/decode.rs b/src/constructive/core_types/valtypes/maybe_common/maybe_common/ape/decode/decode.rs index fc66fbbd..3ca74988 100644 --- a/src/constructive/core_types/valtypes/maybe_common/maybe_common/ape/decode/decode.rs +++ b/src/constructive/core_types/valtypes/maybe_common/maybe_common/ape/decode/decode.rs @@ -68,7 +68,7 @@ where MaybeCommonValueType::Short => { // 2.b.1.a.1 Decode uncommon short value. let uncommon_short_val = ShortVal::decode_ape(bit_stream) - .map_err(|e| MaybeCommonAPEDecodeError::ShortValAPEDecodeError(e))?; + .map_err(MaybeCommonAPEDecodeError::ShortValAPEDecodeError)?; // 2.b.1.a.2 Return the uncommon short value. Ok(MaybeCommon::Uncommon(uncommon_short_val.into())) @@ -78,7 +78,7 @@ where MaybeCommonValueType::Long => { // 2.b.1.b.1 Decode uncommon long value. let uncommon_long_val = LongVal::decode_ape(bit_stream) - .map_err(|e| MaybeCommonAPEDecodeError::LongValAPEDecodeError(e))?; + .map_err(MaybeCommonAPEDecodeError::LongValAPEDecodeError)?; // 2.b.1.b.2 Return the uncommon long value. Ok(MaybeCommon::Uncommon(uncommon_long_val.into())) diff --git a/src/constructive/core_types/valtypes/val/long_val/long_val.rs b/src/constructive/core_types/valtypes/val/long_val/long_val.rs index 27706812..092f0afd 100644 --- a/src/constructive/core_types/valtypes/val/long_val/long_val.rs +++ b/src/constructive/core_types/valtypes/val/long_val/long_val.rs @@ -126,7 +126,7 @@ impl LongVal { /// Implement `Commonable` for `LongVal`. impl Commonable for LongVal { fn maybe_common_value(&self) -> MaybeCommonValue { - MaybeCommonValue::Long(self.clone()) + MaybeCommonValue::Long(*self) } fn maybe_common_value_type() -> MaybeCommonValueType { diff --git a/src/constructive/core_types/valtypes/val/short_val/short_val.rs b/src/constructive/core_types/valtypes/val/short_val/short_val.rs index 1c1beffc..e8bade71 100644 --- a/src/constructive/core_types/valtypes/val/short_val/short_val.rs +++ b/src/constructive/core_types/valtypes/val/short_val/short_val.rs @@ -85,7 +85,7 @@ impl ShortVal { /// Implement `Commonable` for `ShortVal`. impl Commonable for ShortVal { fn maybe_common_value(&self) -> MaybeCommonValue { - MaybeCommonValue::Short(self.clone()) + MaybeCommonValue::Short(*self) } fn maybe_common_value_type() -> MaybeCommonValueType { diff --git a/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs index c1c19f4f..469823c5 100644 --- a/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry/ext/codec/ape/encode/encode.rs @@ -56,7 +56,7 @@ impl Entry { base_ops_price, ) .await - .map_err(|e| EntryAPEEncodeError::CallAPEEncodeError(e))?; + .map_err(EntryAPEEncodeError::CallAPEEncodeError)?; // 2.a.3 Extend the `Entry` APE bit vector with the `Call` APE bit vector. bits.extend(call_bits); @@ -78,7 +78,7 @@ impl Entry { encode_account_rank_as_longval, ) .await - .map_err(|e| EntryAPEEncodeError::LiftupAPEEncodeError(e))?; + .map_err(EntryAPEEncodeError::LiftupAPEEncodeError)?; // 2.b.3 Extend the `Entry` APE bit vector with the `Liftup` APE bit vector. bits.extend(liftup_bits); diff --git a/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs index 5a6717dc..d7010bbe 100644 --- a/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry/ext/codec/sbe/decode/decode.rs @@ -37,8 +37,8 @@ impl Entry { // 3.c `Liftup` (`0x04`): decode from the full buffer (`Liftup::decode_sbe` consumes the tag). 0x04 => { - let liftup = Liftup::decode_sbe(bytes) - .map_err(|err| EntrySBEDecodeError::LiftupSBEDecodeError(err))?; + let liftup = + Liftup::decode_sbe(bytes).map_err(EntrySBEDecodeError::LiftupSBEDecodeError)?; Ok(Entry::Liftup(liftup)) } diff --git a/src/constructive/entries/entry/ext/codec/sbe/encode/encode.rs b/src/constructive/entries/entry/ext/codec/sbe/encode/encode.rs index 0ef933ba..5df64d17 100644 --- a/src/constructive/entries/entry/ext/codec/sbe/encode/encode.rs +++ b/src/constructive/entries/entry/ext/codec/sbe/encode/encode.rs @@ -22,7 +22,7 @@ impl Entry { // 1.b The `Entry` is a `Liftup` — SBE is the `Liftup` encoding (leading `0x04` is inside `Liftup::encode_sbe`). Entry::Liftup(liftup) => liftup .encode_sbe() - .map_err(|err| EntrySBEEncodeError::LiftupSBEEncodeError(err)), + .map_err(EntrySBEEncodeError::LiftupSBEEncodeError), Entry::Swapout(swapout) => swapout .encode_sbe() .map_err(EntrySBEEncodeError::SwapoutSBEEncodeError), diff --git a/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/decode.rs b/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/decode.rs index d70c06c6..e7b985f2 100644 --- a/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/call/ext/codec/sbe/decode/decode.rs @@ -28,11 +28,11 @@ fn read_u32_len_prefix( Ok((len, &bytes[4..])) } -fn take_length_prefixed<'a>( - bytes: &'a [u8], +fn take_length_prefixed( + bytes: &[u8], insufficient_prefix: impl FnOnce(usize) -> CallSBEDecodeError, prefix_exceeds: impl FnOnce(usize, usize) -> CallSBEDecodeError, -) -> Result<(&'a [u8], &'a [u8]), CallSBEDecodeError> { +) -> Result<(&[u8], &[u8]), CallSBEDecodeError> { let (len_u32, rest) = read_u32_len_prefix(bytes, insufficient_prefix)?; let len = len_u32 as usize; if rest.len() < len { diff --git a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/decode/decode.rs b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/decode/decode.rs index 6bec3fe8..9acf3103 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/decode/decode.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/decode/decode.rs @@ -23,15 +23,15 @@ impl Liftup { let root_account: RootAccount = RootAccount::decode_ape(bit_stream, decode_account_rank_as_longval, registry) .await - .map_err(|e| LiftupAPEDecodeError::RootAccountAPEDecodeError(e))?; + .map_err(LiftupAPEDecodeError::RootAccountAPEDecodeError)?; // 2 Decode the `Target` from the bitstream. let target: Target = Target::decode_ape(bit_stream, execution_batch_height) - .map_err(|e| LiftupAPEDecodeError::TargetAPEDecodeError(e))?; + .map_err(LiftupAPEDecodeError::TargetAPEDecodeError)?; // 3 Decode the number of lifts. let number_of_lifts: u32 = ShortVal::decode_ape(bit_stream) - .map_err(|e| LiftupAPEDecodeError::NumberOfLiftsAPEDecodeError(e))? + .map_err(LiftupAPEDecodeError::NumberOfLiftsAPEDecodeError)? .value(); // 4 Collect the outpoints for each lift. diff --git a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs index 6aab1b89..5de97a37 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/codec/ape/encode/encode.rs @@ -23,7 +23,7 @@ impl Liftup { .root_account .encode_ape(registry, encode_account_rank_as_longval) .await - .map_err(|e| LiftupAPEEncodeError::RootAccountAPEEncodeError(e))?; + .map_err(LiftupAPEEncodeError::RootAccountAPEEncodeError)?; // 2.2 Extend the bit vector with the `RootAccount` bit vector. bits.extend(root_account_bits); @@ -35,7 +35,7 @@ impl Liftup { let target_bits = self .target .encode_ape(execution_batch_height) - .map_err(|e| LiftupAPEEncodeError::TargetAPEEncodeError(e))?; + .map_err(LiftupAPEEncodeError::TargetAPEEncodeError)?; // 3.2 Extend the bit vector with the `Target` bit vector. bits.extend(target_bits); diff --git a/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/sighash.rs b/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/sighash.rs index ea81ec47..3ccc9faa 100644 --- a/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/sighash.rs +++ b/src/constructive/entries/entry_kinds/liftup/ext/signature/sighash/sighash.rs @@ -8,7 +8,7 @@ impl Liftup { // 1 Encode the `Liftup` as SBE bytes for the sighash preimage. let sighash_preimage = self .encode_sbe() - .map_err(|err| LiftupSighashError::SBEEncodeError(err))?; + .map_err(LiftupSighashError::SBEEncodeError)?; // 2 Hash the sighash preimage with the 'LiftupEntrySighash' tag. let sighash = sighash_preimage.hash(Some(HashTag::LiftupEntrySighash)); diff --git a/src/constructive/txout_types/lift/lift_versions/liftv1/liftv1.rs b/src/constructive/txout_types/lift/lift_versions/liftv1/liftv1.rs index 4e4f6d0a..d07b3582 100644 --- a/src/constructive/txout_types/lift/lift_versions/liftv1/liftv1.rs +++ b/src/constructive/txout_types/lift/lift_versions/liftv1/liftv1.rs @@ -52,7 +52,7 @@ impl LiftV1 { let self_scriptpubkey = self.txout.script_pubkey.as_bytes(); // 3 Validate the scriptpubkeys. - if &calculated_scriptpubkey != self_scriptpubkey { + if calculated_scriptpubkey != self_scriptpubkey { return false; } diff --git a/src/constructive/txout_types/lift/lift_versions/liftv2/liftv2.rs b/src/constructive/txout_types/lift/lift_versions/liftv2/liftv2.rs index bc053aaf..4d8fb9f1 100644 --- a/src/constructive/txout_types/lift/lift_versions/liftv2/liftv2.rs +++ b/src/constructive/txout_types/lift/lift_versions/liftv2/liftv2.rs @@ -50,7 +50,7 @@ impl LiftV2 { let self_scriptpubkey = self.txout.script_pubkey.as_bytes(); // 3 Validate the scriptpubkeys. - if &calculated_scriptpubkey != self_scriptpubkey { + if calculated_scriptpubkey != self_scriptpubkey { return false; } @@ -124,14 +124,10 @@ impl LiftV2 { /// Returns a taproot for the LiftV2 struct. pub fn return_liftv2_taproot(account_key: [u8; 32], engine_key: [u8; 32]) -> Option { // 1 Construct the keys - let keys: Vec = { - let mut keys = Vec::::new(); - - keys.push(account_key.into_point().unwrap()); - keys.push(engine_key.into_point().unwrap()); - - keys - }; + let keys: Vec = vec![ + account_key.into_point().unwrap(), + engine_key.into_point().unwrap(), + ]; // 2 Construct the key aggregation context let key_agg_ctx = MusigKeyAggCtx::new(&keys, None)?; diff --git a/src/constructive/txout_types/payload/payload.rs b/src/constructive/txout_types/payload/payload.rs index 1f8e1bbe..e535a322 100644 --- a/src/constructive/txout_types/payload/payload.rs +++ b/src/constructive/txout_types/payload/payload.rs @@ -58,9 +58,7 @@ impl Payload { /// Returns the outpoint for the Payload. pub fn outpoint(&self) -> Option { - self.location - .as_ref() - .map(|(outpoint, _txout)| outpoint.clone()) + self.location.as_ref().map(|(outpoint, _txout)| *outpoint) } /// Returns the txout for the Payload. @@ -304,12 +302,11 @@ pub fn genesis_payload(chain: Chain) -> Payload { ); // 9 Construct the genesis payload with location. - let genesis_payload = Payload::new( + + // 10 Return the genesis payload. + Payload::new( engine_key, genesis_payload_without_location.payload_bytes.clone(), Some(location), - ); - - // 10 Return the genesis payload. - genesis_payload + ) } diff --git a/src/executive/exec_ctx/exec_ctx.rs b/src/executive/exec_ctx/exec_ctx.rs index 49915597..2e4e0d74 100644 --- a/src/executive/exec_ctx/exec_ctx.rs +++ b/src/executive/exec_ctx/exec_ctx.rs @@ -328,7 +328,7 @@ impl ExecCtx { .lock() .await .insert_batch_record(batch_record.clone()) - .map_err(|error| ApplyChangesError::ArchivalManagerInsertBatchRecordError(error))?; + .map_err(ApplyChangesError::ArchivalManagerInsertBatchRecordError)?; } // 15 Flush the changes. @@ -435,12 +435,11 @@ impl ExecCtx { // 17 Iterate one tx input to get the prev payload outpoint. let prev_payload_outpoint = { // 17.1 Iterate one tx input for the payload. - let bitcoin_tx_input = bitcoin_tx_inputs_iter - .next() - .ok_or(BatchExecutionError::FailedToIterAndGetPayloadTxInputError)?; // 17.2 Return the payload outpoint. - bitcoin_tx_input.clone() + bitcoin_tx_inputs_iter + .next() + .ok_or(BatchExecutionError::FailedToIterAndGetPayloadTxInputError)? }; // 18 Check if the prev payload outpoint matches to the payload tip outpoint in the sync manager. @@ -502,8 +501,7 @@ impl ExecCtx { // 22.1 Iterate one tx input for the expired projector. let expired_projector_outpoint = bitcoin_tx_inputs_iter .next() - .ok_or(BatchExecutionError::FailedToIterateExpiredProjectorsError)? - .clone(); + .ok_or(BatchExecutionError::FailedToIterateExpiredProjectorsError)?; // 22.2 Add the expired projector outpoint to the expired projector outpoints list. expired_projector_outpoints.push(expired_projector_outpoint); diff --git a/src/executive/vm/opcodes/opcodes/arithmetic/op_lshift.rs b/src/executive/vm/opcodes/opcodes/arithmetic/op_lshift.rs index a6b9ed95..ede2f896 100644 --- a/src/executive/vm/opcodes/opcodes/arithmetic/op_lshift.rs +++ b/src/executive/vm/opcodes/opcodes/arithmetic/op_lshift.rs @@ -50,14 +50,12 @@ impl OP_LSHIFT { let bit_shift = shift_amount % 8; // Add leading zeros for byte shift - for _ in 0..byte_shift { - result.push(0); - } + result.extend(std::iter::repeat_n(0u8, byte_shift)); // Handle bit shifting if bit_shift == 0 { // Just copy the bytes - result.extend_from_slice(&a_bytes); + result.extend_from_slice(a_bytes); } else { // Need to handle bit shifting across byte boundaries let mut carry = 0u8; diff --git a/src/executive/vm/opcodes/opcodes/digest/op_blake2bvar.rs b/src/executive/vm/opcodes/opcodes/digest/op_blake2bvar.rs index 58aee087..81cc667b 100644 --- a/src/executive/vm/opcodes/opcodes/digest/op_blake2bvar.rs +++ b/src/executive/vm/opcodes/opcodes/digest/op_blake2bvar.rs @@ -47,7 +47,7 @@ impl OP_BLAKE2BVAR { .map_err(|_| StackError::BLAKE2bVarOutputSizeError)?; // Update the hasher with the preimage. - hasher.update(&preimage.bytes()); + hasher.update(preimage.bytes()); // Create a buffer to store the hash. let mut output_buffer = vec![0u8; output_size_as_usize]; diff --git a/src/executive/vm/opcodes/opcodes/digest/op_blake2svar.rs b/src/executive/vm/opcodes/opcodes/digest/op_blake2svar.rs index 86ec0528..552ecbf8 100644 --- a/src/executive/vm/opcodes/opcodes/digest/op_blake2svar.rs +++ b/src/executive/vm/opcodes/opcodes/digest/op_blake2svar.rs @@ -47,7 +47,7 @@ impl OP_BLAKE2SVAR { .map_err(|_| StackError::BLAKE2sVarOutputSizeError)?; // Update the hasher with the preimage. - hasher.update(&preimage.bytes()); + hasher.update(preimage.bytes()); // Create a buffer to store the hash. let mut output_buffer = vec![0u8; output_size_as_usize]; diff --git a/src/executive/vm/opcodes/opcodes/digest/op_taggedhash.rs b/src/executive/vm/opcodes/opcodes/digest/op_taggedhash.rs index 83a41c7a..98830971 100644 --- a/src/executive/vm/opcodes/opcodes/digest/op_taggedhash.rs +++ b/src/executive/vm/opcodes/opcodes/digest/op_taggedhash.rs @@ -54,10 +54,7 @@ const TAGGEDHASH_OPS_OUTPUT_LEN: u32 = 32; // Calculate the number of ops for a OP_TAGGEDHASH opcode. fn calculate_ops(preimage_len: u32) -> u32 { // Calculate the gap between the preimage length and the output length. - let gap = match TAGGEDHASH_OPS_OUTPUT_LEN.checked_sub(preimage_len) { - Some(gap) => gap, - None => 0, - }; + let gap = TAGGEDHASH_OPS_OUTPUT_LEN.saturating_sub(preimage_len); // Return the number of ops. TAGGEDHASH_OPS_BASE + (TAGGEDHASH_OPS_MULTIPLIER * gap) diff --git a/src/executive/vm/opcodes/opcodes/push/op_pushdata.rs b/src/executive/vm/opcodes/opcodes/push/op_pushdata.rs index c314b5cb..79f52805 100644 --- a/src/executive/vm/opcodes/opcodes/push/op_pushdata.rs +++ b/src/executive/vm/opcodes/opcodes/push/op_pushdata.rs @@ -62,9 +62,9 @@ impl OP_PUSHDATA { // Data might or might not be a minimal push. 1 => { // Check if the data is a minimal push. - match data.get(0) { + match data.first() { // Should have been encoded as OP_0..OP_16. - Some(value) if value >= &0 && value <= &16 => false, + Some(value) if (&0..=&16).contains(&value) => false, // Validation passes otherwise. _ => true, } diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_alloc.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_alloc.rs index 2f8ac2cc..5bc4a6bb 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_alloc.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_alloc.rs @@ -41,7 +41,7 @@ impl OP_SHADOW_ALLOC { let mut _coin_manager = coin_manager.lock().await; _coin_manager .contract_shadow_alloc_account(self_contract_id_bytes, account_key_bytes) - .map_err(|error| ShadowOpsError::ShadowAllocError(error)) + .map_err(ShadowOpsError::ShadowAllocError) .map_err(StackError::ShadowOpsError)?; } diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_dealloc.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_dealloc.rs index 4697f02a..722a4bea 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_dealloc.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_dealloc.rs @@ -41,7 +41,7 @@ impl OP_SHADOW_DEALLOC { let mut _coin_manager = coin_manager.lock().await; _coin_manager .contract_shadow_dealloc_account(self_contract_id_bytes, account_key_bytes) - .map_err(|error| ShadowOpsError::ShadowDeallocError(error)) + .map_err(ShadowOpsError::ShadowDeallocError) .map_err(StackError::ShadowOpsError)?; } diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down.rs index 03a3fe36..867526a0 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down.rs @@ -57,7 +57,7 @@ impl OP_SHADOW_DOWN { let mut _coin_manager = coin_manager.lock().await; _coin_manager .shadow_down(self_contract_id_bytes, account_key_bytes, amount_as_u64) - .map_err(|error| ShadowOpsError::ShadowAllocDownError(error)) + .map_err(ShadowOpsError::ShadowAllocDownError) .map_err(StackError::ShadowOpsError)?; } diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down_all.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down_all.rs index 514d29bc..413ea3e5 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down_all.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_down_all.rs @@ -44,7 +44,7 @@ impl OP_SHADOW_DOWN_ALL { let mut _coin_manager = coin_manager.lock().await; _coin_manager .shadow_down_all(self_contract_id_bytes, amount_as_u64) - .map_err(|error| ShadowOpsError::ShadowAllocDownAllError(error)) + .map_err(ShadowOpsError::ShadowAllocDownAllError) .map_err(StackError::ShadowOpsError)?; } Ok(()) diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up.rs index 01750b7a..5ad299ee 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up.rs @@ -57,7 +57,7 @@ impl OP_SHADOW_UP { let mut _coin_manager = coin_manager.lock().await; _coin_manager .shadow_up(self_contract_id_bytes, account_key_bytes, amount_as_u64) - .map_err(|error| ShadowOpsError::ShadowAllocUpError(error)) + .map_err(ShadowOpsError::ShadowAllocUpError) .map_err(StackError::ShadowOpsError)?; } diff --git a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up_all.rs b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up_all.rs index f39022fb..8a97f0ee 100644 --- a/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up_all.rs +++ b/src/executive/vm/opcodes/opcodes/shadowing/op_shadow_up_all.rs @@ -43,7 +43,7 @@ impl OP_SHADOW_UP_ALL { let mut _coin_manager = coin_manager.lock().await; _coin_manager .shadow_up_all(self_contract_id_bytes, amount_as_u64) - .map_err(|error| ShadowOpsError::ShadowAllocUpAllError(error)) + .map_err(ShadowOpsError::ShadowAllocUpAllError) .map_err(StackError::ShadowOpsError)?; } diff --git a/src/executive/vm/opcodes/opcodes/storage/op_swrite.rs b/src/executive/vm/opcodes/opcodes/storage/op_swrite.rs index d30cc840..e3295420 100644 --- a/src/executive/vm/opcodes/opcodes/storage/op_swrite.rs +++ b/src/executive/vm/opcodes/opcodes/storage/op_swrite.rs @@ -59,7 +59,7 @@ impl OP_SWRITE { } // Calculate the number of ops. - let ops = calculate_ops(key.len() as u32, value.len() as u32); + let ops = calculate_ops(key.len(), value.len()); // Increment the ops counter. stack_holder.increment_ops(ops)?; diff --git a/src/executive/vm/program/compiler/compiler.rs b/src/executive/vm/program/compiler/compiler.rs index 1fcc2eaa..59684e6f 100644 --- a/src/executive/vm/program/compiler/compiler.rs +++ b/src/executive/vm/program/compiler/compiler.rs @@ -43,7 +43,7 @@ impl ProgramCompiler for Program { executable_bytes.extend( method .compile() - .map_err(|e| ProgramCompileError::MethodCompileError(e))?, + .map_err(ProgramCompileError::MethodCompileError)?, ); } @@ -109,13 +109,13 @@ impl ProgramCompiler for Program { let mut methods = Vec::::new(); for _ in 0..method_count { let method = ProgramMethod::decompile(bytecode_stream) - .map_err(|e| ProgramDecompileError::MethodDecompileError(e))?; + .map_err(ProgramDecompileError::MethodDecompileError)?; methods.push(method); } // Construct the executable. let executable = Program::new(program_name, metadata, methods) - .map_err(|e| ProgramDecompileError::ProgramConstructError(e))?; + .map_err(ProgramDecompileError::ProgramConstructError)?; // Return the executable. Ok(executable) diff --git a/src/executive/vm/program/method/compiler/compiler.rs b/src/executive/vm/program/method/compiler/compiler.rs index c8aa47ba..534cab8c 100644 --- a/src/executive/vm/program/method/compiler/compiler.rs +++ b/src/executive/vm/program/method/compiler/compiler.rs @@ -53,7 +53,7 @@ impl MethodCompiler for ProgramMethod { method_bytes.extend( opcode .compile() - .map_err(|e| MethodCompileError::OpcodeCompileError(e))?, + .map_err(MethodCompileError::OpcodeCompileError)?, ); } @@ -119,14 +119,14 @@ impl MethodCompiler for ProgramMethod { let mut opcodes = Vec::::new(); for _ in 0..opcodes_count { let opcode = Opcode::decompile(&mut bytecode_stream) - .map_err(|e| MethodDecompileError::OpcodeDecompileError(e))?; + .map_err(MethodDecompileError::OpcodeDecompileError)?; opcodes.push(opcode); } // Construct the method. let method = ProgramMethod::new(method_name, method_type, calldata_element_types, opcodes) - .map_err(|e| MethodDecompileError::MethodConstructError(e))?; + .map_err(MethodDecompileError::MethodConstructError)?; // Return the method. Ok(method) diff --git a/src/executive/vm/program/method/program_method.rs b/src/executive/vm/program/method/program_method.rs index 3977ec1b..3bc1f03e 100644 --- a/src/executive/vm/program/method/program_method.rs +++ b/src/executive/vm/program/method/program_method.rs @@ -1,7 +1,7 @@ use super::{ limits::{ MAX_METHOD_ARG_COUNT, MAX_METHOD_NAME_LENGTH, MAX_METHOD_OPCODE_COUNT, - MIN_METHOD_ARG_COUNT, MIN_METHOD_NAME_LENGTH, MIN_METHOD_OPCODE_COUNT, + MIN_METHOD_NAME_LENGTH, MIN_METHOD_OPCODE_COUNT, }, method_error::{MethodConstructionError, ScriptValidationError}, method_type::MethodType, @@ -47,7 +47,7 @@ impl ProgramMethod { } // Check arg count. - if arg_types.len() > MAX_METHOD_ARG_COUNT || arg_types.len() < MIN_METHOD_ARG_COUNT { + if arg_types.len() > MAX_METHOD_ARG_COUNT { return Err(MethodConstructionError::ArgCountError); } @@ -101,15 +101,10 @@ impl ProgramMethod { /// Validates the script. pub fn validate_script(&self) -> Result<(), ScriptValidationError> { for opcode in self.script.iter() { - match opcode { - // Check for non minimal push data. - Opcode::OP_PUSHDATA(op_pushdata) => { - if op_pushdata.0.len() == 1 && !OP_PUSHDATA::check_minimal_push(&op_pushdata.0) - { - return Err(ScriptValidationError::NonMinimalDataPushError); - } + if let Opcode::OP_PUSHDATA(op_pushdata) = opcode { + if op_pushdata.0.len() == 1 && !OP_PUSHDATA::check_minimal_push(&op_pushdata.0) { + return Err(ScriptValidationError::NonMinimalDataPushError); } - _ => {} } } @@ -117,7 +112,7 @@ impl ProgramMethod { } /// Matches the args to the arg types. - pub fn match_args(&self, args: &Vec) -> bool { + pub fn match_args(&self, args: &[StackItem]) -> bool { // Check if the number of args matches the number of arg types. if args.len() != self.arg_types.len() { return false; @@ -189,28 +184,19 @@ impl ProgramMethod { } /// Get the payable allocation value. - pub fn payable_allocation_value(&self, args: &Vec) -> Option { + pub fn payable_allocation_value(&self, args: &[StackItem]) -> Option { // Get the payable arg value. for (index, arg_type) in self.arg_types.iter().enumerate() { // Check if the arg type is a payable. if *arg_type == CalldataElementType::Payable { // Get the payable arg. - let payable_arg = match args.get(index) { - Some(arg) => arg, - None => return None, - }; + let payable_arg = args.get(index)?; // Convert the arg to a `StackUint`. - let payable_arg_as_stack_uint = match payable_arg.to_stack_uint() { - Some(arg) => arg, - None => return None, - }; + let payable_arg_as_stack_uint = payable_arg.to_stack_uint()?; // Convert the arg to a u32. - let payable_arg_as_u32 = match payable_arg_as_stack_uint.to_u32() { - Some(arg) => arg, - None => return None, - }; + let payable_arg_as_u32 = payable_arg_as_stack_uint.to_u32()?; // Return the arg value. return Some(payable_arg_as_u32); diff --git a/src/executive/vm/program/program.rs b/src/executive/vm/program/program.rs index 7bd73efa..d2f0cf7c 100644 --- a/src/executive/vm/program/program.rs +++ b/src/executive/vm/program/program.rs @@ -54,7 +54,7 @@ impl Program { // Validate the methods. Self::validate_methods_inner(&methods) - .map_err(|e| ProgramConstructionError::MethodValidationError(e))?; + .map_err(ProgramConstructionError::MethodValidationError)?; // Order the methods. let ordered_methods = Self::order_methods(methods); @@ -131,7 +131,7 @@ impl Program { } /// Validates the methods. - fn validate_methods_inner(methods: &Vec) -> Result<(), MethodValidationError> { + fn validate_methods_inner(methods: &[ProgramMethod]) -> Result<(), MethodValidationError> { // Check for duplicate method names. { let mut method_names = HashSet::::new(); @@ -171,10 +171,9 @@ impl Program { }; // Get the contract ID hash. - let contract_id = compiled_bytes.hash(Some(HashTag::ContractID)); // Return the contract ID. - contract_id + compiled_bytes.hash(Some(HashTag::ContractID)) } /// Returns the executable as a JSON object. diff --git a/src/executive/vm/program_execution/exec.rs b/src/executive/vm/program_execution/exec.rs index c513dc80..acf87fe3 100644 --- a/src/executive/vm/program_execution/exec.rs +++ b/src/executive/vm/program_execution/exec.rs @@ -239,86 +239,70 @@ pub async fn execute( // Data push opcodes. Opcode::OP_FALSE(OP_FALSE) => { OP_FALSE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_PUSHDATA(op_pushdata) => { op_pushdata .execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_TRUE(OP_TRUE) => { OP_TRUE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2(OP_2) => { - OP_2::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_2::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_3(OP_3) => { - OP_3::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_3::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_4(OP_4) => { - OP_4::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_4::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_5(OP_5) => { - OP_5::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_5::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_6(OP_6) => { - OP_6::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_6::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_7(OP_7) => { - OP_7::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_7::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_8(OP_8) => { - OP_8::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_8::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_9(OP_9) => { - OP_9::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_9::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_10(OP_10) => { - OP_10::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_10::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_11(OP_11) => { - OP_11::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_11::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_12(OP_12) => { - OP_12::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_12::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_13(OP_13) => { - OP_13::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_13::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_14(OP_14) => { - OP_14::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_14::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_15(OP_15) => { - OP_15::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_15::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_16(OP_16) => { - OP_16::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_16::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } // Flow control opcodes. Opcode::OP_NOP(_) => { - OP_NOP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_NOP::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_JUMP(_) => { // Retrieve the new opcode index. let new_opcode_index = OP_JUMP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; // If the new opcode index is within the bounds of the opcodes, set the new opcode index. // Otherwise, return an error. @@ -328,12 +312,11 @@ pub async fn execute( } } Opcode::OP_IF(_) => { - OP_IF::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_IF::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NOTIF(_) => { OP_NOTIF::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_RETURNALL(_) => { // If this is not an active execution, return immediately. @@ -343,7 +326,7 @@ pub async fn execute( // Return all items from the stack. let return_items = OP_RETURNALL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; // Get the ops spent. let internal_ops_counter = stack_holder.internal_ops_counter(); @@ -362,7 +345,7 @@ pub async fn execute( // Return some items from the stack. let return_items = OP_RETURNSOME::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; // Get the ops spent. let internal_ops_counter = stack_holder.internal_ops_counter(); @@ -375,359 +358,345 @@ pub async fn execute( } Opcode::OP_ELSE(_) => { OP_ELSE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ENDIF(_) => { OP_ENDIF::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_VERIFY(_) => { OP_VERIFY::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_FAIL(_) => { OP_FAIL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Altstack operations. Opcode::OP_TOALTSTACK(_) => { OP_TOALTSTACK::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_FROMALTSTACK(_) => { OP_FROMALTSTACK::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Stack operations. Opcode::OP_2DROP(OP_2DROP) => { OP_2DROP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2DUP(OP_2DUP) => { OP_2DUP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_3DUP(OP_3DUP) => { OP_3DUP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2OVER(OP_2OVER) => { OP_2OVER::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2ROT(OP_2ROT) => { OP_2ROT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2SWAP(OP_2SWAP) => { OP_2SWAP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_IFDUP(OP_IFDUP) => { OP_IFDUP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_DEPTH(OP_DEPTH) => { OP_DEPTH::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_DROP(OP_DROP) => { OP_DROP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_DUP(OP_DUP) => { - OP_DUP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_DUP::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NIP(OP_NIP) => { - OP_NIP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_NIP::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_OVER(OP_OVER) => { OP_OVER::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_PICK(OP_PICK) => { OP_PICK::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ROLL(OP_ROLL) => { OP_ROLL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ROT(OP_ROT) => { - OP_ROT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_ROT::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SWAP(OP_SWAP) => { OP_SWAP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_TUCK(OP_TUCK) => { OP_TUCK::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Splice opcodes. Opcode::OP_CAT(OP_CAT) => { - OP_CAT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_CAT::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SPLIT(OP_SPLIT) => { OP_SPLIT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_LEFT(OP_LEFT) => { OP_LEFT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_RIGHT(OP_RIGHT) => { OP_RIGHT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SIZE(OP_SIZE) => { OP_SIZE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Bitwise opcodes. Opcode::OP_INVERT(OP_INVERT) => { OP_INVERT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_AND(OP_AND) => { - OP_AND::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_AND::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_OR(OP_OR) => { - OP_OR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_OR::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_XOR(OP_XOR) => { - OP_XOR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_XOR::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_EQUAL(OP_EQUAL) => { OP_EQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_EQUALVERIFY(OP_EQUALVERIFY) => { OP_EQUALVERIFY::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_REVERSE(OP_REVERSE) => { OP_REVERSE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Arithmetic opcodes. Opcode::OP_1ADD(OP_1ADD) => { OP_1ADD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_1SUB(OP_1SUB) => { OP_1SUB::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2MUL(OP_2MUL) => { OP_2MUL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_2DIV(OP_2DIV) => { OP_2DIV::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ADDMOD(OP_ADDMOD) => { OP_ADDMOD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MULMOD(OP_MULMOD) => { OP_MULMOD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NOT(OP_NOT) => { - OP_NOT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_NOT::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_0NOTEQUAL(OP_0NOTEQUAL) => { OP_0NOTEQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ADD(OP_ADD) => { - OP_ADD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_ADD::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SUB(OP_SUB) => { - OP_SUB::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_SUB::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MUL(OP_MUL) => { - OP_MUL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_MUL::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_DIV(OP_DIV) => { - OP_DIV::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_DIV::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_LSHIFT(OP_LSHIFT) => { OP_LSHIFT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_RSHIFT(OP_RSHIFT) => { OP_RSHIFT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_BOOLAND(OP_BOOLAND) => { OP_BOOLAND::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_BOOLOR(OP_BOOLOR) => { OP_BOOLOR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NUMEQUAL(OP_NUMEQUAL) => { OP_NUMEQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NUMEQUALVERIFY(OP_NUMEQUALVERIFY) => { OP_NUMEQUALVERIFY::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_NUMNOTEQUAL(OP_NUMNOTEQUAL) => { OP_NUMNOTEQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_LESSTHAN(OP_LESSTHAN) => { OP_LESSTHAN::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_GREATERTHAN(OP_GREATERTHAN) => { OP_GREATERTHAN::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_LESSTHANOREQUAL(OP_LESSTHANOREQUAL) => { OP_LESSTHANOREQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_GREATERTHANOREQUAL(OP_GREATERTHANOREQUAL) => { OP_GREATERTHANOREQUAL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MIN(OP_MIN) => { - OP_MIN::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_MIN::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MAX(OP_MAX) => { - OP_MAX::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + OP_MAX::execute(&mut stack_holder).map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_WITHIN(OP_WITHIN) => { OP_WITHIN::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Digest opcodes. Opcode::OP_RIPEMD160(OP_RIPEMD160) => { OP_RIPEMD160::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHA1(OP_SHA1) => { OP_SHA1::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHA256(OP_SHA256) => { OP_SHA256::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_HASH160(OP_HASH160) => { OP_HASH160::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_HASH256(OP_HASH256) => { OP_HASH256::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_TAGGEDHASH(OP_TAGGEDHASH) => { OP_TAGGEDHASH::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_BLAKE2BVAR(OP_BLAKE2BVAR) => { OP_BLAKE2BVAR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_BLAKE2SVAR(OP_BLAKE2SVAR) => { OP_BLAKE2SVAR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Secp opcodes. Opcode::OP_SECPSCALARADD(OP_SECPSCALARADD) => { OP_SECPSCALARADD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SECPSCALARMUL(OP_SECPSCALARMUL) => { OP_SECPSCALARMUL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SECPPOINTADD(OP_SECPPOINTADD) => { OP_SECPPOINTADD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SECPPOINTMUL(OP_SECPPOINTMUL) => { OP_SECPPOINTMUL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_PUSHSECPGENERATORPOINT(OP_PUSHSECPGENERATORPOINT) => { OP_PUSHSECPGENERATORPOINT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ISZEROSECPSCALAR(OP_ISZEROSECPSCALAR) => { OP_ISZEROSECPSCALAR::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_ISINFINITESECPPOINT(OP_ISINFINITESECPPOINT) => { OP_ISINFINITESECPPOINT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Digital signature opcodes. Opcode::OP_CHECKSCHNORRSIG(OP_CHECKSCHNORRSIG) => { OP_CHECKSCHNORRSIG::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_CHECKSCHNORRSIGBIP340(OP_CHECKSCHNORRSIGBIP340) => { OP_CHECKSCHNORRSIGBIP340::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_CHECKBLSSIG(OP_CHECKBLSSIG) => { OP_CHECKBLSSIG::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_CHECKBLSSIGAGG(OP_CHECKBLSSIGAGG) => { OP_CHECKBLSSIGAGG::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Call info opcodes. Opcode::OP_CALLER(OP_CALLER) => { OP_CALLER::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_OPSBUDGET(OP_OPSBUDGET) => { OP_OPSBUDGET::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_OPSCOUNTER(OP_OPSCOUNTER) => { OP_OPSCOUNTER::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_OPSPRICE(OP_OPSPRICE) => { OP_OPSPRICE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_TIMESTAMP(OP_TIMESTAMP) => { OP_TIMESTAMP::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Call opcodes. Opcode::OP_CALL(_) => { @@ -739,7 +708,7 @@ pub async fn execute( // Get the information about the internal call. let (method_index_to_be_called, call_arg_values) = OP_CALL::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; // Call the internal contract. return Box::pin(execute( @@ -769,7 +738,7 @@ pub async fn execute( // Get the information about the external call. let (contract_id_to_be_called, method_index_to_be_called, call_arg_values) = OP_CALLEXT::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; // Raise and error if the same contract is being called as an external call. if contract_id_to_be_called == contract_id { @@ -802,98 +771,98 @@ pub async fn execute( Opcode::OP_SHADOW_ALLOC(OP_SHADOW_ALLOC) => { OP_SHADOW_ALLOC::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_HAS_ALLOC(OP_SHADOW_HAS_ALLOC) => { OP_SHADOW_HAS_ALLOC::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_DEALLOC(OP_SHADOW_DEALLOC) => { OP_SHADOW_DEALLOC::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_ALLOC_VAL(OP_SHADOW_ALLOC_VAL) => { OP_SHADOW_ALLOC_VAL::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_UP(OP_SHADOW_UP) => { OP_SHADOW_UP::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_DOWN(OP_SHADOW_DOWN) => { OP_SHADOW_DOWN::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_UP_ALL(OP_SHADOW_UP_ALL) => { OP_SHADOW_UP_ALL::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_DOWN_ALL(OP_SHADOW_DOWN_ALL) => { OP_SHADOW_DOWN_ALL::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_NUM_ALLOCS(OP_SHADOW_NUM_ALLOCS) => { OP_SHADOW_NUM_ALLOCS::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SHADOW_ALLOCS_SUM(OP_SHADOW_ALLOCS_SUM) => { OP_SHADOW_ALLOCS_SUM::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Coin opcodes. Opcode::OP_EXT_BALANCE(OP_EXT_BALANCE) => { OP_EXT_BALANCE::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SELF_BALANCE(OP_SELF_BALANCE) => { OP_SELF_BALANCE::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_TRANSFER(OP_TRANSFER) => { OP_TRANSFER::execute(&mut stack_holder, coin_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Storage opcodes. Opcode::OP_SWRITE(OP_SWRITE) => { OP_SWRITE::execute(&mut stack_holder, state_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_SREAD(OP_SREAD) => { OP_SREAD::execute(&mut stack_holder, state_manager) .await - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } // Memory opcodes. Opcode::OP_MWRITE(OP_MWRITE) => { OP_MWRITE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MREAD(OP_MREAD) => { OP_MREAD::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } Opcode::OP_MFREE(OP_MFREE) => { OP_MFREE::execute(&mut stack_holder) - .map_err(|error| ExecutionError::OpcodeExecutionError(error))?; + .map_err(ExecutionError::OpcodeExecutionError)?; } } } - return Err(ExecutionError::MethodNotReturnedAnyItemsError); + Err(ExecutionError::MethodNotReturnedAnyItemsError) } diff --git a/src/executive/vm/program_execution/program_exec_ctx.rs b/src/executive/vm/program_execution/program_exec_ctx.rs index a96f169c..a9d22883 100644 --- a/src/executive/vm/program_execution/program_exec_ctx.rs +++ b/src/executive/vm/program_execution/program_exec_ctx.rs @@ -84,10 +84,7 @@ impl ProgramExecCtx { let timestamp = self.timestamp; // The ops budget is the ops budget of the call. - let ops_budget = match call.ops_budget() { - Some(ops_budget) => ops_budget, - None => 0, - }; + let ops_budget = call.ops_budget().unwrap_or_default(); // Check if the base ops price is the same as the base ops price of the call. if call.ops_price_total() != self.base_ops_price { @@ -191,7 +188,7 @@ impl ProgramExecCtx { } // Return the error. - return Err(error); + Err(error) } } } diff --git a/src/executive/vm/stack/stack.rs b/src/executive/vm/stack/stack.rs index 7a1fb714..c2b48514 100644 --- a/src/executive/vm/stack/stack.rs +++ b/src/executive/vm/stack/stack.rs @@ -54,6 +54,12 @@ impl Stack { self.0.last().cloned().ok_or(StackError::EmptyStack) } } + +impl Default for Stack { + fn default() -> Self { + Self::new() + } +} impl fmt::Display for Stack { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f)?; diff --git a/src/executive/vm/stack/stack_holder.rs b/src/executive/vm/stack/stack_holder.rs index 46af702f..09b64a8f 100644 --- a/src/executive/vm/stack/stack_holder.rs +++ b/src/executive/vm/stack/stack_holder.rs @@ -42,7 +42,7 @@ pub struct StackHolder { flow_encounters: Vec, } -impl<'a> StackHolder { +impl StackHolder { /// Creates a new stack holder. pub fn new( caller: Caller, @@ -130,7 +130,7 @@ impl<'a> StackHolder { /// Returns the caller. pub fn caller(&self) -> Caller { - self.caller.clone() + self.caller } /// Returns the timestamp. diff --git a/src/executive/vm/stack/stack_item.rs b/src/executive/vm/stack/stack_item.rs index 5b177d09..4d1b3999 100644 --- a/src/executive/vm/stack/stack_item.rs +++ b/src/executive/vm/stack/stack_item.rs @@ -30,6 +30,11 @@ impl StackItem { self.0.len() as u32 } + /// Returns whether the stack item is empty. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// Returns whether the stack item is false. pub fn is_false(&self) -> bool { self.0.is_empty() diff --git a/src/inscriptive/archival_manager/archival_manager.rs b/src/inscriptive/archival_manager/archival_manager.rs index 9af5058a..fb50946f 100644 --- a/src/inscriptive/archival_manager/archival_manager.rs +++ b/src/inscriptive/archival_manager/archival_manager.rs @@ -25,6 +25,17 @@ pub type BatchTimestamp = u64; /// Type alias for the entry id. pub type EntryId = [u8; 32]; +/// Entry lookup result returned by `entry_record_by_entry_id`. +pub type EntryRecord = ( + BatchHeight, + BatchTxid, + BatchTimestamp, + EntryId, + Entry, + Option, + Option, +); + /// Local storage manager for `BatchRecord` for nodes that run in archival mode. pub struct ArchivalManager { // In-memory batch records keyed by batch height. @@ -64,7 +75,7 @@ impl ArchivalManager { /// Constructs an `ArchivalManager` by opening storage and loading existing `BatchRecord`s. pub fn new(chain: Chain) -> Result { // 1 Open the archival manager db. - let db_path = format!("storage/{}/archival_manager", chain.to_string()); + let db_path = format!("storage/{}/archival_manager", chain); let in_db_records = sled::open(&db_path).map_err(ArchivalConstructionError::DBOpenError)?; // 2 Initialize the in-memory map of loaded records. @@ -210,18 +221,7 @@ impl ArchivalManager { } /// Returns an Entry record by entry id. - pub fn entry_record_by_entry_id( - &self, - entry_id: &[u8; 32], - ) -> Option<( - BatchHeight, - BatchTxid, - BatchTimestamp, - EntryId, - Entry, - Option, - Option, - )> { + pub fn entry_record_by_entry_id(&self, entry_id: &[u8; 32]) -> Option { // 1 Walk batches in ascending batch height order. for h in sorted_batch_heights(&self.in_memory_records) { let record = &self.in_memory_records[&h]; @@ -388,7 +388,7 @@ impl ArchivalManager { /// Erases the archival manager database directory for the chain. pub fn erase_archival_manager(chain: Chain) { // 1 Resolve the archival manager db path. - let path = format!("storage/{}/archival_manager", chain.to_string()); + let path = format!("storage/{}/archival_manager", chain); // 2 Remove the directory tree. let _ = std::fs::remove_dir_all(path); diff --git a/src/inscriptive/coin_manager/bodies/account_body/account_body.rs b/src/inscriptive/coin_manager/bodies/account_body/account_body.rs index cd0fa6f6..28855afa 100644 --- a/src/inscriptive/coin_manager/bodies/account_body/account_body.rs +++ b/src/inscriptive/coin_manager/bodies/account_body/account_body.rs @@ -22,8 +22,8 @@ impl CMAccountBody { /// Constructs a fresh new account body. pub fn new(balance: SatoshiAmount, global_shadow_allocs_sum: SatiSatoshiAmount) -> Self { Self { - balance: balance, - global_shadow_allocs_sum: global_shadow_allocs_sum, + balance, + global_shadow_allocs_sum, } } diff --git a/src/inscriptive/coin_manager/bodies/contract_body/contract_body.rs b/src/inscriptive/coin_manager/bodies/contract_body/contract_body.rs index 5ab1ca52..609f8170 100644 --- a/src/inscriptive/coin_manager/bodies/contract_body/contract_body.rs +++ b/src/inscriptive/coin_manager/bodies/contract_body/contract_body.rs @@ -19,8 +19,8 @@ impl CMContractBody { /// Constructs a fresh new contract body. pub fn new(balance: SatoshiAmount, shadow_space: ShadowSpace) -> Self { Self { - balance: balance, - shadow_space: shadow_space, + balance, + shadow_space, } } diff --git a/src/inscriptive/coin_manager/bodies/contract_body/shadow_space/shadow_space.rs b/src/inscriptive/coin_manager/bodies/contract_body/shadow_space/shadow_space.rs index c20362b4..10308f62 100644 --- a/src/inscriptive/coin_manager/bodies/contract_body/shadow_space/shadow_space.rs +++ b/src/inscriptive/coin_manager/bodies/contract_body/shadow_space/shadow_space.rs @@ -42,14 +42,13 @@ impl ShadowSpace { allocs: HashMap, ) -> Self { // 1 Construct the shadow space. - let shadow_space = Self { - allocs_sum: allocs_sum, - allocs: allocs, - shadow_up_all_down_alls: 0, - }; // 2 Return the shadow space. - shadow_space + Self { + allocs_sum, + allocs, + shadow_up_all_down_alls: 0, + } } /// Updates the allocations sum. @@ -71,10 +70,7 @@ impl ShadowSpace { /// Removes an allocation from the shadow space. pub fn remove_alloc(&mut self, account_key: ACCOUNT_KEY) -> bool { // 1 Remove the allocation from the allocations map. - match self.allocs.remove(&account_key) { - Some(_) => true, - None => false, - } + self.allocs.remove(&account_key).is_some() } /// Adds a deferred proportional change to the shadow space. diff --git a/src/inscriptive/coin_manager/coin_manager.rs b/src/inscriptive/coin_manager/coin_manager.rs index b6a62ffd..7e3c0d8b 100644 --- a/src/inscriptive/coin_manager/coin_manager.rs +++ b/src/inscriptive/coin_manager/coin_manager.rs @@ -76,7 +76,7 @@ pub type COIN_MANAGER = Arc>; impl CoinManager { pub fn new(chain: Chain) -> Result { // 1 Open the accounts db. - let accounts_db_path = format!("storage/{}/coins/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/coins/accounts", chain); let accounts_db = sled::open(accounts_db_path).map_err(|e| { CMConstructionError::AccountConstructionError(CMConstructionAccountError::DBOpenError( e, @@ -84,7 +84,7 @@ impl CoinManager { })?; // 2 Open the contracts db. - let contracts_db_path = format!("storage/{}/coins/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/coins/contracts", chain); let contracts_db = sled::open(contracts_db_path).map_err(|e| { CMConstructionError::ContractConstructionError( CMConstructionContractError::DBOpenError(e), @@ -405,7 +405,7 @@ impl CoinManager { pub fn get_account_balance(&self, account_key: AccountKey) -> Option { // 1 Try to get from the delta first. if let Some(value) = self.delta.updated_account_balances.get(&account_key) { - return Some(value.clone()); + return Some(*value); } // 2 And then try to get from the permanent in-memory states. @@ -418,7 +418,7 @@ impl CoinManager { pub fn get_contract_balance(&self, contract_id: ContractId) -> Option { // 1 Try to get from the delta first. if let Some(value) = self.delta.updated_contract_balances.get(&contract_id) { - return Some(value.clone()); + return Some(*value); } // 2 And then try to get from the permanent in-memory states. @@ -439,7 +439,7 @@ impl CoinManager { .updated_global_shadow_allocs_sums .get(&account_key) { - return Some(value.clone()); + return Some(*value); } // 2 And then try to get from the permanent in-memory states. @@ -507,7 +507,7 @@ impl CoinManager { let base_allocs_sum_in_sati_satoshis = (base_allocs_sum_in_satoshis as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; let deferred_change_in_sati_satoshis = - (deferred_change_in_satoshis.abs() as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; + (deferred_change_in_satoshis.unsigned_abs() as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; // 2.6 Calculate the proportional change for this account in this contract. let individual_change_in_sati_satoshis = if deferred_change_in_satoshis > 0 { @@ -678,7 +678,7 @@ impl CoinManager { // 2.8 Convert the deferred change in satoshis to sati-satoshis. let deferred_change_in_sati_satoshis = - (deferred_change_in_satoshis.abs() as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; + (deferred_change_in_satoshis.unsigned_abs() as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; // 2.9 Calculate the proportional change for this account (matching apply_changes logic). let individual_change_in_sati_satoshis = if deferred_change_in_satoshis > 0 { @@ -1708,7 +1708,8 @@ impl CoinManager { let base_allocs_sum_in_sati_satoshis = (base_allocs_sum_in_satoshis as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; let deferred_change_in_sati_satoshis = - (deferred_change_in_satoshis.abs() as u128) * ONE_SATOSHI_IN_SATI_SATOSHIS; + (deferred_change_in_satoshis.unsigned_abs() as u128) + * ONE_SATOSHI_IN_SATI_SATOSHIS; // 5.1.4 Iterate over all allocations and apply proportional changes. let allocs_copy: Vec<(AccountKey, SatiSatoshiAmount)> = @@ -1874,7 +1875,7 @@ impl CoinManager { { // Update the shadow alloc value on-disk. tree.insert( - shadow_account_key.to_vec(), + shadow_account_key, shadow_alloc_value.to_le_bytes().to_vec(), ) .map_err(|e| { @@ -2055,13 +2056,13 @@ impl CoinManager { /// Erases the coin manager by db paths. pub fn erase_coin_manager(chain: Chain) { // Accounts db path. - let accounts_db_path = format!("storage/{}/coins/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/coins/accounts", chain); // Erase the accounts db path. let _ = std::fs::remove_dir_all(accounts_db_path); // Contracts db path. - let contracts_db_path = format!("storage/{}/coins/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/coins/contracts", chain); // Erase the contracts db path. let _ = std::fs::remove_dir_all(contracts_db_path); diff --git a/src/inscriptive/coin_manager/delta/delta.rs b/src/inscriptive/coin_manager/delta/delta.rs index ee54f45f..2f1d93d7 100644 --- a/src/inscriptive/coin_manager/delta/delta.rs +++ b/src/inscriptive/coin_manager/delta/delta.rs @@ -78,7 +78,6 @@ impl CMDelta { /// ACCOUNT RELATED METHODS /// /// ------------------------------------------------------------ - /// Epheremally updates an account's balance. pub fn ephemerally_update_account_balance( &mut self, @@ -100,7 +99,6 @@ impl CMDelta { /// CONTRACT RELATED METHODS /// /// ------------------------------------------------------------ - /// Epheremally updates a contract's balance. pub fn ephemerally_update_contract_balance( &mut self, @@ -114,7 +112,7 @@ impl CMDelta { pub fn ephemerally_insert_alloc(&mut self, contract_id: ContractId, account_key: AccountKey) { self.allocs_list .entry(contract_id) - .or_insert_with(Vec::new) + .or_default() .push(account_key); } @@ -122,7 +120,7 @@ impl CMDelta { pub fn ephemerally_insert_dealloc(&mut self, contract_id: ContractId, account_key: AccountKey) { self.deallocs_list .entry(contract_id) - .or_insert_with(Vec::new) + .or_default() .push(account_key); } diff --git a/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs b/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs index f34cdd09..35a2298a 100644 --- a/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs +++ b/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs @@ -24,13 +24,7 @@ pub fn return_flames_to_fund( } // 2 Calculate the gap amount. - let gap_amount: SatoshiAmount = match target_value.checked_sub(current_flame_set_sum_value) { - // 2.1 Gap amount is none. Return none. - None => return None, - - // 2.2 Gap amount is some. Return the gap amount. - Some(gap_amount) => gap_amount, - }; + let gap_amount: SatoshiAmount = target_value.checked_sub(current_flame_set_sum_value)?; // 3 Initialize the list of flames to return. let mut flames = Vec::::new(); diff --git a/src/inscriptive/flame_manager/delta/delta.rs b/src/inscriptive/flame_manager/delta/delta.rs index f7ea6caf..91d77a38 100644 --- a/src/inscriptive/flame_manager/delta/delta.rs +++ b/src/inscriptive/flame_manager/delta/delta.rs @@ -33,7 +33,7 @@ impl FMDelta { // 1 Check if the account has just been ephemerally registered in the delta. match self.is_account_ephemerally_registered(account_key) { // 1.a The account has just been ephemerally registered in the delta. - true => return false, + true => false, // 1.b The account has not just been ephemerally registered in the delta. false => { diff --git a/src/inscriptive/flame_manager/flame/flame.rs b/src/inscriptive/flame_manager/flame/flame.rs index 0fcf558a..1889a7d4 100644 --- a/src/inscriptive/flame_manager/flame/flame.rs +++ b/src/inscriptive/flame_manager/flame/flame.rs @@ -63,7 +63,7 @@ impl Flame { // 1 Decode the flame tier. let (flame_tier, remaining_bytes) = { // 1.1 Check if there are enough bytes for the flame tier length (1 byte). - if bytes.len() < 1 { + if bytes.is_empty() { return None; } diff --git a/src/inscriptive/flame_manager/flame_manager.rs b/src/inscriptive/flame_manager/flame_manager.rs index 396a3979..65fdc12e 100644 --- a/src/inscriptive/flame_manager/flame_manager.rs +++ b/src/inscriptive/flame_manager/flame_manager.rs @@ -49,7 +49,7 @@ impl FlameManager { /// Constructs a fresh new 'FlameManager'. pub fn new(chain: Chain) -> Result { // 1 Open the accounts db. - let accounts_db_path = format!("storage/{}/flames/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/flames/accounts", chain); let accounts_db = sled::open(accounts_db_path).map_err(FMConstructionError::AccountsDBOpenError)?; @@ -114,7 +114,7 @@ impl FlameManager { // 3.4.4 Store the flame grouped by rollup height. account_flames_by_height .entry(rollup_height) - .or_insert_with(Vec::new) + .or_default() .push((flame_index, flame)); } @@ -170,13 +170,9 @@ impl FlameManager { account_key: AccountKey, ) -> Option>> { // 1 Check if the account is permanently registered. - match self.in_memory_flame_set.get(&account_key) { - // 1.a The account has a flame set. - Some(flame_set) => Some(flame_set.to_owned()), - - // 1.b The account does not have a flame set. - None => None, - } + self.in_memory_flame_set + .get(&account_key) + .map(|flame_set| flame_set.to_owned()) } /// Epheremally registers an account. @@ -521,7 +517,7 @@ impl FlameManager { /// Erases the flame manager by db path. pub fn erase_flame_manager(chain: Chain) { // Flame manager db path. - let flame_manager_db_path = format!("storage/{}/flames/accounts", chain.to_string()); + let flame_manager_db_path = format!("storage/{}/flames/accounts", chain); // Erase the path. let _ = std::fs::remove_dir_all(flame_manager_db_path); diff --git a/src/inscriptive/graveyard/graveyard.rs b/src/inscriptive/graveyard/graveyard.rs index e348ea41..e61d868c 100644 --- a/src/inscriptive/graveyard/graveyard.rs +++ b/src/inscriptive/graveyard/graveyard.rs @@ -45,7 +45,7 @@ pub type GRAVEYARD = Arc>; impl Graveyard { pub fn new(chain: Chain) -> Result { // 1 Open the graveyard db. - let graveyard_db_path = format!("storage/{}/graveyard", chain.to_string()); + let graveyard_db_path = format!("storage/{}/graveyard", chain); let graveyard_db = sled::open(graveyard_db_path).map_err(GraveyardConstructionError::DBOpenError)?; @@ -54,28 +54,25 @@ impl Graveyard { HashMap::::new(); // 3 Iterate over all items in the graveyard db to collect the buried accounts. - for lookup in graveyard_db.iter() { - // 3.1 Get the key and value. - if let Ok((key, val)) = lookup { - // 3.1.1 Deserialize the account key. - let account_key: [u8; 32] = key.as_ref().try_into().map_err(|_| { - GraveyardConstructionError::UnableToDeserializeAccountKeyBytesFromDBKey( + for (key, val) in graveyard_db.iter().flatten() { + // 3.1.1 Deserialize the account key. + let account_key: [u8; 32] = key.as_ref().try_into().map_err(|_| { + GraveyardConstructionError::UnableToDeserializeAccountKeyBytesFromDBKey( + key.to_vec(), + ) + })?; + + // 3.1.2 Deserialize the coins redemption amount. + let redemption_amount: u64 = + u64::from_le_bytes(val.as_ref().try_into().map_err(|_| { + GraveyardConstructionError::UnableToDeserializeRedemptionAmountBytesFromDBValue( key.to_vec(), + val.to_vec(), ) - })?; - - // 3.1.2 Deserialize the coins redemption amount. - let redemption_amount: u64 = - u64::from_le_bytes(val.as_ref().try_into().map_err(|_| { - GraveyardConstructionError::UnableToDeserializeRedemptionAmountBytesFromDBValue( - key.to_vec(), - val.to_vec(), - ) - })?); + })?); - // 3.1.3 Insert the buried account into the in-memory buried accounts. - in_memory_buried_accounts.insert(account_key, redemption_amount); - } + // 3.1.3 Insert the buried account into the in-memory buried accounts. + in_memory_buried_accounts.insert(account_key, redemption_amount); } // 4 Construct the graveyard. @@ -309,7 +306,7 @@ impl Graveyard { /// Erases the graveyard by db path. pub fn erase_graveyard(chain: Chain) { // Graveyard db path. - let graveyard_db_path = format!("storage/{}/graveyard", chain.to_string()); + let graveyard_db_path = format!("storage/{}/graveyard", chain); // Erase the path. let _ = std::fs::remove_dir_all(graveyard_db_path); diff --git a/src/inscriptive/params_manager/params_manager.rs b/src/inscriptive/params_manager/params_manager.rs index 344282af..05601f4f 100644 --- a/src/inscriptive/params_manager/params_manager.rs +++ b/src/inscriptive/params_manager/params_manager.rs @@ -52,7 +52,7 @@ impl ParamsManager { /// Creates a new params manager. pub fn new(chain: Chain) -> Result { // 1 Open params db. - let params_db_path = format!("storage/{}/params", chain.to_string()); + let params_db_path = format!("storage/{}/params", chain); let params_db = sled::open(params_db_path)?; // 2 Start with the default params holder. @@ -380,6 +380,6 @@ impl ParamsManager { /// Erases the params manager by db path. pub fn erase_params_manager(chain: Chain) { - let params_db_path = format!("storage/{}/params", chain.to_string()); + let params_db_path = format!("storage/{}/params", chain); let _ = std::fs::remove_dir_all(params_db_path); } diff --git a/src/inscriptive/privileges_manager/elements/exemption/periodic_resource/periodic_resource.rs b/src/inscriptive/privileges_manager/elements/exemption/periodic_resource/periodic_resource.rs index 1267d698..916c2901 100644 --- a/src/inscriptive/privileges_manager/elements/exemption/periodic_resource/periodic_resource.rs +++ b/src/inscriptive/privileges_manager/elements/exemption/periodic_resource/periodic_resource.rs @@ -59,7 +59,7 @@ impl PeriodicResource { let new_amount = self.limit; // 3.a.2 Return the new amount. - return Some(new_amount); + Some(new_amount) } // 3.b If the time passed is less than the period. @@ -75,9 +75,9 @@ impl PeriodicResource { let new_amount = new_amount.min(self.limit); // 3.b.4 Return the new amount. - return Some(new_amount); + Some(new_amount) } - }; + } } /// Refills the resource, then consumes the given amount, then updates and returns the new consume amount left. @@ -98,14 +98,14 @@ impl PeriodicResource { // Consume amount is fulyl subsided, so the consume amount left is 0. let consume_amount_left = 0; - return Some(consume_amount_left); + Some(consume_amount_left) } else { // Resource is exhausted, thus the new current left is 0. self.latest_left = 0; // Consume amount is exceeded the resource, thus the consume amount left is the consume amount minus the current left. let consume_amount_left = consume_amount - current_left; - return Some(consume_amount_left); + Some(consume_amount_left) } } diff --git a/src/inscriptive/privileges_manager/elements/liveness_flag/liveness_flag.rs b/src/inscriptive/privileges_manager/elements/liveness_flag/liveness_flag.rs index c8ee239a..3f956314 100644 --- a/src/inscriptive/privileges_manager/elements/liveness_flag/liveness_flag.rs +++ b/src/inscriptive/privileges_manager/elements/liveness_flag/liveness_flag.rs @@ -127,7 +127,7 @@ impl LivenessFlag { /// Deserializes the liveness flag from bytes. pub fn from_bytes(bytes: &[u8]) -> Option { // 1 Check if there are enough bytes for the liveness flag. - if bytes.len() < 1 { + if bytes.is_empty() { return None; } diff --git a/src/inscriptive/privileges_manager/privileges_manager.rs b/src/inscriptive/privileges_manager/privileges_manager.rs index 3bd1eee5..f2b9e344 100644 --- a/src/inscriptive/privileges_manager/privileges_manager.rs +++ b/src/inscriptive/privileges_manager/privileges_manager.rs @@ -65,12 +65,12 @@ impl PrivilegesManager { /// Creates a new privileges manager. pub fn new(chain: Chain) -> Result { // 1 Open the accounts db. - let accounts_db_path = format!("storage/{}/privileges/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/privileges/accounts", chain); let accounts_db = sled::open(accounts_db_path) .map_err(PrivilegesManagerConstructionError::AccountsDBOpenError)?; // 2 Open the contracts db. - let contracts_db_path = format!("storage/{}/privileges/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/privileges/contracts", chain); let contracts_db = sled::open(contracts_db_path) .map_err(PrivilegesManagerConstructionError::ContractsDBOpenError)?; @@ -1062,9 +1062,9 @@ impl PrivilegesManager { /// Erases the privileges manager by db paths. pub fn erase_privileges_manager(chain: Chain) { - let accounts_db_path = format!("storage/{}/privileges/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/privileges/accounts", chain); let _ = std::fs::remove_dir_all(accounts_db_path); - let contracts_db_path = format!("storage/{}/privileges/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/privileges/contracts", chain); let _ = std::fs::remove_dir_all(contracts_db_path); } diff --git a/src/inscriptive/registry/delta/delta.rs b/src/inscriptive/registry/delta/delta.rs index 3915fdcc..7c89aa2f 100644 --- a/src/inscriptive/registry/delta/delta.rs +++ b/src/inscriptive/registry/delta/delta.rs @@ -23,20 +23,23 @@ type CallCounterDelta = u16; /// Activity timestamp. type ActivityTimestamp = u64; +/// A pending account registration in the registry delta. +type NewAccountRegistration = ( + AccountKey, + ActivityTimestamp, + Option, + Option, + Option, + Option, +); + /// A struct for containing ephemeral state differences to be applied for 'RegistryManager'. #[derive(Clone)] pub struct RMDelta { // ACCOUNT RELATED VALUES /// /// ------------------------------------------------------------ // New accounts to register. - pub new_accounts_to_register: Vec<( - AccountKey, - ActivityTimestamp, - Option, - Option, - Option, - Option, - )>, + pub new_accounts_to_register: Vec, // Updated account call counters for a given account. pub updated_account_call_counters: HashMap, diff --git a/src/inscriptive/registry/registry.rs b/src/inscriptive/registry/registry.rs index cfba7739..166d8261 100644 --- a/src/inscriptive/registry/registry.rs +++ b/src/inscriptive/registry/registry.rs @@ -98,12 +98,12 @@ impl Registry { /// Constructs a fresh new registry. pub fn new(chain: Chain) -> Result { // 1 Open the accounts db. - let accounts_db_path = format!("storage/{}/registry/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/registry/accounts", chain); let accounts_db = sled::open(accounts_db_path).map_err(RMConstructionError::AccountsDBOpenError)?; // 2 Open the contracts db. - let contracts_db_path = format!("storage/{}/registry/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/registry/contracts", chain); let contracts_db = sled::open(contracts_db_path).map_err(RMConstructionError::ContractsDBOpenError)?; @@ -191,7 +191,7 @@ impl Registry { } // 0x03 key byte represents the primary BLS key. BLS_KEY_SPECIAL_DB_KEY => { - if value.as_ref().len() > 0 { + if !value.as_ref().is_empty() { // Get the primary BLS key bytes. let bls_key_bytes: [u8; 48] = value.as_ref().try_into().map_err(|_| { RMConstructionError::UnableToDeserializeAccountPrimaryBLSKeyBytesFromTreeValue(account_key, value.to_vec()) @@ -203,12 +203,12 @@ impl Registry { } // 0x04 key byte represents the secondary aggregation key. SECONDARY_AGGREGATION_KEY_SPECIAL_DB_KEY => { - if value.as_ref().len() > 0 { + if !value.as_ref().is_empty() { // Convert the value to a secondary aggregation key bytes. let secondary_aggregation_key_bytes: Vec = value.as_ref().to_vec(); // If the secondary aggregation key bytes are not empty, update the secondary aggregation key. - if secondary_aggregation_key_bytes.len() > 0 { + if !secondary_aggregation_key_bytes.is_empty() { secondary_aggregation_key = Some(secondary_aggregation_key_bytes); } } @@ -227,7 +227,7 @@ impl Registry { } // 0x06 key byte represents the account flame config. ACCOUNT_FLAME_CONFIG_SPECIAL_DB_KEY => { - if value.as_ref().len() > 0 { + if !value.as_ref().is_empty() { let flame_config_deserialized = FMAccountFlameConfig::from_bytes(value.as_ref()) .ok_or( RMConstructionError::UnableToDeserializeAccountFlameConfigBytesFromTreeValue( @@ -240,7 +240,7 @@ impl Registry { } // 0x07 key byte represents the projector config. PROJECTOR_CONFIG_SPECIAL_DB_KEY => { - if value.as_ref().len() > 0 { + if !value.as_ref().is_empty() { let projector_config_bytes: [u8; 32] = value.as_ref().try_into().map_err(|_| { RMConstructionError::UnableToDeserializeAccountProjectorConfigBytesFromTreeValue( @@ -593,15 +593,13 @@ impl Registry { } // 2 Try to get from the delta's new accounts to register (ephemeral registrations). - if let Some((_, _, _, _, _, flame_config)) = self + if let Some((_, _, _, _, _, Some(flame_config))) = self .delta .new_accounts_to_register .iter() .find(|(key, _, _, _, _, _)| key == &account_key) { - if let Some(flame_config) = flame_config { - return Some(flame_config.clone()); - } + return Some(flame_config.clone()); } // 3 And then try to get from the permanent in-memory states. @@ -1647,13 +1645,13 @@ impl Registry { /// Erases the registry manager by db paths. pub fn erase_registry(chain: Chain) { // Accounts db path. - let accounts_db_path = format!("storage/{}/registry/accounts", chain.to_string()); + let accounts_db_path = format!("storage/{}/registry/accounts", chain); // Erase the accounts db path. let _ = std::fs::remove_dir_all(accounts_db_path); // Contracts db path. - let contracts_db_path = format!("storage/{}/registry/contracts", chain.to_string()); + let contracts_db_path = format!("storage/{}/registry/contracts", chain); // Erase the contracts db path. let _ = std::fs::remove_dir_all(contracts_db_path); diff --git a/src/inscriptive/state_manager/delta/delta.rs b/src/inscriptive/state_manager/delta/delta.rs index c879ba40..bb11afea 100644 --- a/src/inscriptive/state_manager/delta/delta.rs +++ b/src/inscriptive/state_manager/delta/delta.rs @@ -105,7 +105,7 @@ impl SMDelta { // 2 Insert the state into the new or updated states. self.new_or_updated_contract_states .entry(contract_id) - .or_insert_with(HashMap::new) + .or_default() .insert(key.clone(), value.clone()); } @@ -128,7 +128,7 @@ impl SMDelta { // 2 Insert the key into the removed states. self.removed_contract_states .entry(contract_id) - .or_insert_with(Vec::new) + .or_default() .push(key.clone()); } } diff --git a/src/inscriptive/state_manager/state_manager.rs b/src/inscriptive/state_manager/state_manager.rs index 95918cae..6f6c0a6f 100644 --- a/src/inscriptive/state_manager/state_manager.rs +++ b/src/inscriptive/state_manager/state_manager.rs @@ -43,7 +43,7 @@ impl StateManager { /// Constructs a fresh new 'StateManager'. pub fn new(chain: Chain) -> Result { // 1 Open the states db. - let states_db_path = format!("storage/{}/states", chain.to_string()); + let states_db_path = format!("storage/{}/states", chain); let states_db = sled::open(states_db_path).map_err(SMConstructionError::DBOpenError)?; // 2 Initialize the in-memory states. @@ -174,10 +174,8 @@ impl StateManager { optimized: bool, ) -> Result, SMInsertUpdateStateError> { // 1 If not optimized, check if the contract is registered. - if !optimized { - if !self.is_contract_registered(contract_id) { - return Err(SMInsertUpdateStateError::ContractNotRegistered(contract_id)); - } + if !optimized && !self.is_contract_registered(contract_id) { + return Err(SMInsertUpdateStateError::ContractNotRegistered(contract_id)); } // 2 Check if the value already exists. @@ -192,7 +190,7 @@ impl StateManager { ); // 2.a.2 Return the previous value for updated. - return Ok(Some(existing_value)); + Ok(Some(existing_value)) } // 2.b Insert the value. None => { @@ -204,7 +202,7 @@ impl StateManager { ); // 2.b.2 Return None for newly inserted. - return Ok(None); + Ok(None) } } } @@ -219,14 +217,12 @@ impl StateManager { optimized: bool, ) -> Result<(), SMRemoveStateError> { // 1 If not optimized, check if the contract is registered. - if !optimized { - if !self.is_contract_registered(contract_id) { - return Err(SMRemoveStateError::ContractNotRegistered(contract_id)); - } + if !optimized && !self.is_contract_registered(contract_id) { + return Err(SMRemoveStateError::ContractNotRegistered(contract_id)); } // 2 Return error if the state does not exist. - if let None = self.get_state_value(contract_id, key) { + if self.get_state_value(contract_id, key).is_none() { return Err(SMRemoveStateError::StateDoesNotExist( contract_id, key.clone(), @@ -256,7 +252,7 @@ impl StateManager { // 1.1.1 Open the tree. This creates a new tree since it does not exist. self.on_disk_states .open_tree(contract_id) - .map_err(|e| SMApplyChangesError::TreeOpenError(contract_id.clone(), e))?; + .map_err(|e| SMApplyChangesError::TreeOpenError(*contract_id, e))?; } // 1.2 In-memory insertion. @@ -266,7 +262,7 @@ impl StateManager { // 1.2.2 Insert the contract state into the in-memory states. self.in_memory_states - .insert(contract_id.clone(), fresh_new_contract_state_holder); + .insert(*contract_id, fresh_new_contract_state_holder); } } @@ -278,14 +274,14 @@ impl StateManager { let tree = self .on_disk_states .open_tree(contract_id) - .map_err(|e| SMApplyChangesError::TreeOpenError(contract_id.clone(), e))?; + .map_err(|e| SMApplyChangesError::TreeOpenError(*contract_id, e))?; // 2.1.2 Insert the states into the tree. for (ephemeral_state_key, ephemeral_state_value) in ephemeral_states.iter() { tree.insert(ephemeral_state_key, ephemeral_state_value.clone()) .map_err(|e| { SMApplyChangesError::TreeValueInsertError( - contract_id.clone(), + *contract_id, ephemeral_state_key.clone(), ephemeral_state_value.clone(), e, @@ -298,7 +294,7 @@ impl StateManager { { // 2.2.1 Get the mutable contract state holder from the in-memory states. let mut_contract_state_holder = self.in_memory_states.get_mut(contract_id).ok_or( - SMApplyChangesError::ContractIdNotFoundInMemory(contract_id.clone()), + SMApplyChangesError::ContractIdNotFoundInMemory(*contract_id), )?; // 2.2.2 Insert the states into the contract state holder. @@ -317,13 +313,13 @@ impl StateManager { let tree = self .on_disk_states .open_tree(contract_id) - .map_err(|e| SMApplyChangesError::TreeOpenError(contract_id.clone(), e))?; + .map_err(|e| SMApplyChangesError::TreeOpenError(*contract_id, e))?; // 3.1.2 Remove the states from the tree. for state_key_to_remove in state_keys_to_remove.iter() { tree.remove(state_key_to_remove).map_err(|e| { SMApplyChangesError::TreeValueRemoveError( - contract_id.clone(), + *contract_id, state_key_to_remove.clone(), e, ) @@ -384,7 +380,7 @@ impl StateManager { /// Erases the state manager by db path. pub fn erase_state_manager(chain: Chain) { // States db path. - let states_db_path = format!("storage/{}/states", chain.to_string()); + let states_db_path = format!("storage/{}/states", chain); // Erase the path. let _ = std::fs::remove_dir_all(states_db_path); diff --git a/src/inscriptive/sync_manager/sync_manager.rs b/src/inscriptive/sync_manager/sync_manager.rs index 40428280..11e02c23 100644 --- a/src/inscriptive/sync_manager/sync_manager.rs +++ b/src/inscriptive/sync_manager/sync_manager.rs @@ -32,7 +32,7 @@ pub type SYNC_MANAGER = Arc>; impl SyncManager { pub fn new(chain: Chain) -> Result { // 1 Open the sync manager db. - let db_path = format!("storage/{}/sync_manager", chain.to_string()); + let db_path = format!("storage/{}/sync_manager", chain); let db = sled::open(db_path).map_err(SMConstructionError::DBOpenError)?; // 2 Get the bitcoin sync height tip from the db. @@ -149,7 +149,7 @@ impl SyncManager { /// Erases the sync manager by db path. pub fn erase_sync_manager(chain: Chain) { // Sync manager db path. - let sync_manager_db_path = format!("storage/{}/sync_manager", chain.to_string()); + let sync_manager_db_path = format!("storage/{}/sync_manager", chain); // Erase the sync manager db path. let _ = std::fs::remove_dir_all(sync_manager_db_path); diff --git a/src/inscriptive/utxo_set/utxo_set.rs b/src/inscriptive/utxo_set/utxo_set.rs index 9b822ff2..50641fd6 100644 --- a/src/inscriptive/utxo_set/utxo_set.rs +++ b/src/inscriptive/utxo_set/utxo_set.rs @@ -41,24 +41,22 @@ impl UTXOSet { /// Creates the UTXOSet instance. pub fn new(chain: Chain) -> Option { // Collect UTXOs from db. - let utxos_path = format!("{}/{}/{}", "storage", chain.to_string(), "utxo_set"); + let utxos_path = format!("{}/{}/{}", "storage", chain, "utxo_set"); let utxos_db = sled::open(utxos_path).ok()?; let mut utxos = HashMap::::new(); // Load UTXOs from db. - for lookup in utxos_db.iter() { - if let Ok((key, val)) = lookup { - // Deserialize outpoint. - let outpoint_bytes: [u8; 36] = key.as_ref().try_into().ok()?; - let outpoint = OutPoint::from_bytes36(&outpoint_bytes)?; + for (key, val) in utxos_db.iter().flatten() { + // Deserialize outpoint. + let outpoint_bytes: [u8; 36] = key.as_ref().try_into().ok()?; + let outpoint = OutPoint::from_bytes36(&outpoint_bytes)?; - // Deserialize txout. - let txout = TxOut::from_bytes(val.as_ref())?; + // Deserialize txout. + let txout = TxOut::from_bytes(val.as_ref())?; - // Insert utxo. - utxos.insert(outpoint, txout); - } + // Insert utxo. + utxos.insert(outpoint, txout); } // Construct the UTXOSet instance. @@ -81,18 +79,18 @@ impl UTXOSet { /// Inserts a utxo into the set. pub fn insert_utxo(&mut self, outpoint: &OutPoint, txout: &TxOut) { // Insert utxo into the in-memory set. - if let None = self.utxos.insert(outpoint.clone(), txout.clone()) { + if self.utxos.insert(*outpoint, txout.clone()).is_none() { // Insert utxo into the in-storage set. - let _ = self.utxos_db.insert(&outpoint.bytes_36(), txout.bytes()); + let _ = self.utxos_db.insert(outpoint.bytes_36(), txout.bytes()); } } /// Removes a utxo from the set. pub fn remove_utxo(&mut self, outpoint: &OutPoint) { // Remove utxo from the in-memory set. - if let Some(_) = self.utxos.remove(outpoint) { + if self.utxos.remove(outpoint).is_some() { // Remove utxo from the in-storage set. - let _ = self.utxos_db.remove(&outpoint.bytes_36()); + let _ = self.utxos_db.remove(outpoint.bytes_36()); } } @@ -136,7 +134,7 @@ impl UTXOSet { lifts.push(Lift::new_liftv1( account_key, engine_key, - outpoint.clone(), + *outpoint, txout.clone(), )); @@ -149,7 +147,7 @@ impl UTXOSet { lifts.push(Lift::new_liftv2( account_key, engine_key, - outpoint.clone(), + *outpoint, txout.clone(), )); } @@ -182,7 +180,7 @@ impl UTXOSet { /// Erases the UTXO set by db path. pub fn erase_utxo_set(chain: Chain) { // UTXO set db path. - let utxo_set_db_path = format!("storage/{}/utxo_set", chain.to_string()); + let utxo_set_db_path = format!("storage/{}/utxo_set", chain); // Erase the UTXO set db path. let _ = std::fs::remove_dir_all(utxo_set_db_path); diff --git a/src/operative/cli/cli.rs b/src/operative/cli/cli.rs index 0a716c7b..1312043a 100644 --- a/src/operative/cli/cli.rs +++ b/src/operative/cli/cli.rs @@ -676,7 +676,7 @@ fn parse_cli_parts(line: Result) -> Option> { let line = match line { Ok(line) => line, Err(_) => { - eprintln!("{}", format!("Invalid line.").yellow()); + eprintln!("{}", "Invalid line.".to_string().yellow()); return None; } }; @@ -746,13 +746,13 @@ fn parse_hex_bytes(s: &str) -> Option> { hex::decode(s.trim_start_matches("0x")).ok() } -fn parse_config_fields( - args: &[String], -) -> Option<( +type ConfigFields = ( Option>, Option<[u8; 32]>, Option, -)> { +); + +fn parse_config_fields(args: &[String]) -> Option { let mut sak: Option> = None; let mut pc: Option<[u8; 32]> = None; let mut fc: Option = None; diff --git a/src/operative/cli/commands/common_commands/runexplorer.rs b/src/operative/cli/commands/common_commands/runexplorer.rs index dbee6d9c..68a8349f 100644 --- a/src/operative/cli/commands/common_commands/runexplorer.rs +++ b/src/operative/cli/commands/common_commands/runexplorer.rs @@ -892,7 +892,7 @@ fn account_avatar_emoji(account_key: [u8; 32]) -> &'static str { fn explorer_format_u64_dec_groups(s: &str) -> String { let mut out = String::new(); for (i, ch) in s.chars().enumerate() { - if i > 0 && (s.len() - i) % 3 == 0 { + if i > 0 && (s.len() - i).is_multiple_of(3) { out.push(','); } out.push(ch); @@ -1451,7 +1451,7 @@ async fn page_account_section( html_escape(avatar_emoji), html_escape(&npub_short), account_vip_title_emoji_html, - hierarchy.to_string(), + hierarchy, html_escape(&nostr_profile_url), html_escape(&account_hex), html_escape(&account_hex), @@ -1785,7 +1785,7 @@ async fn page_batches(State(st): State) -> Html { let body = format!( r#"

{} Latest batches

{}
HeightTxidNumber of EntriesSeen
"#, - st.chain.to_string(), + st.chain, if table_rows.is_empty() { r#"No batches in archival storage yet."#.to_string() } else { @@ -2092,7 +2092,7 @@ fn render_batch_page(chain: Chain, record: &BatchRecord) -> String { txid_cell, txid, { - let bls_full = hex::encode(&record.aggregate_bls_signature); + let bls_full = hex::encode(record.aggregate_bls_signature); expandable_mono_html(&bls_full, 28, 16, "bls-agg-sig") }, record.payload_version, diff --git a/src/operative/cli/commands/node_commands/comp.rs b/src/operative/cli/commands/node_commands/comp.rs index ae5f6998..8dbc2af2 100644 --- a/src/operative/cli/commands/node_commands/comp.rs +++ b/src/operative/cli/commands/node_commands/comp.rs @@ -128,9 +128,9 @@ fn comp_program(parts: Vec<&str>) { println!("0x{}", hex::encode(compiled)); } -fn parse_comp_program_arguments<'a>( - parts: &'a Vec<&'a str>, -) -> Option<(String, Option>, usize, &'a [&'a str])> { +type CompProgramArguments<'a> = (String, Option>, usize, &'a [&'a str]); + +fn parse_comp_program_arguments<'a>(parts: &'a [&'a str]) -> Option> { // Expected minimum: // comp program if parts.len() < 5 { diff --git a/src/operative/main.rs b/src/operative/main.rs index 3afcf83d..b2d9fbf2 100644 --- a/src/operative/main.rs +++ b/src/operative/main.rs @@ -135,7 +135,7 @@ fn print_nsec_frame(nsec: &str) { } /// Generates a random secret key and prints it as an nsec. -fn gensec(args: &Vec) { +fn gensec(args: &[String]) { // 1 Match the argument name. match args[1].to_lowercase().as_str() { // 1.a Command is 'gensec'. @@ -165,7 +165,6 @@ fn gensec(args: &Vec) { drop(nsec); // 1.a.4 Return. - return; } // 1.b Command is invalid. @@ -174,7 +173,7 @@ fn gensec(args: &Vec) { } /// Prints genesis params as pretty JSON (random engine key + genesis payload P2TR address). -fn genesis(args: &Vec) { +fn genesis(args: &[String]) { // 1 Match the argument name. match args[1].to_lowercase().as_str() { // 1.a Command is 'genesis'. @@ -269,7 +268,7 @@ fn genesis(args: &Vec) { } /// Runs the appropriate mode based on the arguments. -fn run(args: &Vec) { +fn run(args: &[String]) { // 1 Parse resource mode. let resource_mode = match args[1].to_lowercase().as_str() { "pruned" => ResourceMode::Pruned, @@ -338,16 +337,13 @@ fn run(args: &Vec) { // 6.2.3 Get the handle. let handle = stdin.lock(); - // 6.2.4 Drop stdin. - drop(stdin); - // 6.2.5 Parse the input. - for line in handle.lines() { + if let Some(line) = handle.lines().next() { // 6.2.5.1 Unwrap the line. let line = line.unwrap(); // 6.2.5.2 Parse the parts. - let parts: Vec<&str> = line.trim().split_whitespace().collect(); + let parts: Vec<&str> = line.split_whitespace().collect(); // 6.2.5.3 Check if the parts length is valid. if parts.len() != 1 { @@ -371,9 +367,6 @@ fn run(args: &Vec) { // 6.2.5.7 Drop the nsec. drop(nsec); - - // 6.2.5.8 Break the loop. - break; } } // @@ -412,9 +405,7 @@ fn run(args: &Vec) { fn print_correct_usage() { eprintln!( "{}", - format!( - "Usage:\n gensec\n genesis \n \n\nIn engine/node CLI (archival mode): runexplorer " - ) + "Usage:\n gensec\n genesis \n \n\nIn engine/node CLI (archival mode): runexplorer ".to_string() .red() ); } diff --git a/src/operative/run_args/chain.rs b/src/operative/run_args/chain.rs index d7281dcc..3ba43a8d 100644 --- a/src/operative/run_args/chain.rs +++ b/src/operative/run_args/chain.rs @@ -1,3 +1,5 @@ +use std::fmt; + /// Chain type. #[derive(Debug, Copy, Clone, PartialEq)] pub enum Chain { @@ -9,12 +11,12 @@ pub enum Chain { Mainnet, } -impl ToString for Chain { - fn to_string(&self) -> String { - match self { - Chain::Testbed => "testbed".to_string(), - Chain::Signet => "signet".to_string(), - Chain::Mainnet => "mainnet".to_string(), - } +impl fmt::Display for Chain { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Chain::Testbed => "testbed", + Chain::Signet => "signet", + Chain::Mainnet => "mainnet", + }) } } diff --git a/src/operative/run_args/operating_kind.rs b/src/operative/run_args/operating_kind.rs index 1cedbda0..8dcb852e 100644 --- a/src/operative/run_args/operating_kind.rs +++ b/src/operative/run_args/operating_kind.rs @@ -1,3 +1,5 @@ +use std::fmt; + /// Operating kind type. #[derive(Debug, Copy, Clone, PartialEq)] pub enum OperatingKind { @@ -5,11 +7,11 @@ pub enum OperatingKind { Engine, } -impl ToString for OperatingKind { - fn to_string(&self) -> String { - match self { - OperatingKind::Node => "node".to_string(), - OperatingKind::Engine => "engine".to_string(), - } +impl fmt::Display for OperatingKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + OperatingKind::Node => "node", + OperatingKind::Engine => "engine", + }) } } diff --git a/src/operative/run_args/resource_mode.rs b/src/operative/run_args/resource_mode.rs index 0a28dcd0..3a9ebfa7 100644 --- a/src/operative/run_args/resource_mode.rs +++ b/src/operative/run_args/resource_mode.rs @@ -1,3 +1,5 @@ +use std::fmt; + /// Operating mode type. #[derive(Debug, Copy, Clone, PartialEq)] pub enum ResourceMode { @@ -5,11 +7,11 @@ pub enum ResourceMode { Archival, } -impl ToString for ResourceMode { - fn to_string(&self) -> String { - match self { - ResourceMode::Pruned => "pruned".to_string(), - ResourceMode::Archival => "archival".to_string(), - } +impl fmt::Display for ResourceMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + ResourceMode::Pruned => "pruned", + ResourceMode::Archival => "archival", + }) } } diff --git a/src/operative/run_args/sync_mode.rs b/src/operative/run_args/sync_mode.rs index 26ecb9ce..3f2bfad1 100644 --- a/src/operative/run_args/sync_mode.rs +++ b/src/operative/run_args/sync_mode.rs @@ -1,3 +1,5 @@ +use std::fmt; + /// Sync inflight type. #[derive(Debug, Copy, Clone, PartialEq)] pub enum SyncMode { @@ -5,11 +7,11 @@ pub enum SyncMode { ConfirmedOnly, } -impl ToString for SyncMode { - fn to_string(&self) -> String { - match self { - SyncMode::InFlight => "in-flight".to_string(), - SyncMode::ConfirmedOnly => "confirmed-only".to_string(), - } +impl fmt::Display for SyncMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + SyncMode::InFlight => "in-flight", + SyncMode::ConfirmedOnly => "confirmed-only", + }) } } diff --git a/src/operative/runner/runner.rs b/src/operative/runner/runner.rs index 70359035..679ebd22 100644 --- a/src/operative/runner/runner.rs +++ b/src/operative/runner/runner.rs @@ -69,10 +69,10 @@ pub async fn run( // 3 Print the initializing message according to the operating kind. match operating_kind { OperatingKind::Engine => { - println!("{}", "Initializing engine."); + println!("Initializing engine."); } OperatingKind::Node => { - println!("{}", "Initializing node."); + println!("Initializing node."); } } @@ -200,10 +200,8 @@ pub async fn run( // 8 Spawn chain syncer to sync Bitcoin blocks. { - let chain = chain.clone(); let rpc_holder = rpc_holder.clone(); let engine_conn = pre_sync_engine_conn.clone(); - let engine_key = engine_key; let registry = Arc::clone(®istry); let graveyard = Arc::clone(&graveyard); let coin_manager = Arc::clone(&coin_manager); @@ -237,12 +235,12 @@ pub async fn run( // 9 Initial Block Download (IBD) encapsulation. { - println!("{}", "Syncing chain."); + println!("Syncing chain."); // #9 Await chain to be fully synced. sync_manager.await_ibd().await; - println!("{}", "Syncing complete."); + println!("Syncing complete."); } // 11 Operating-kind-specific initializations. @@ -256,18 +254,17 @@ pub async fn run( } // 11.a.2 Open port 6272 for incoming connections. - match open_port(chain).await { - true => println!( + if open_port(chain).await { + println!( "{}", format!("Opened port '{}'.", port_number(chain)).green() - ), - false => (), + ) } // 11.a.3 Run NNS server in the background. { let nns_client = nns_client.clone(); - let _ = tokio::spawn(async move { + tokio::spawn(async move { let _ = nns::server::run(&nns_client, operating_kind).await; }); } @@ -292,7 +289,6 @@ pub async fn run( let session_pool = Arc::clone(&session_pool); let sync_manager = Arc::clone(&sync_manager); let rpc_holder = rpc_holder.clone(); - let engine_key = engine_key.clone(); let utxo_set = Arc::clone(&utxo_set); let registry = Arc::clone(®istry); let graveyard = Arc::clone(&graveyard); @@ -304,7 +300,7 @@ pub async fn run( let archival_manager = archival_manager.clone(); let key_holder = Arc::clone(&key_holder); - let _ = tokio::spawn(async move { + tokio::spawn(async move { let _ = engine_batch_builder_background_task( &session_pool, &sync_manager, @@ -328,9 +324,8 @@ pub async fn run( // 11.a.6 Run the TCP server in the background. { let keys = Arc::clone(&key_holder); - let chain = chain.clone(); let session_pool = Arc::clone(&session_pool); - let _ = tokio::spawn(async move { + tokio::spawn(async move { tcp_server::server::run(operating_kind, chain, keys, &session_pool).await; }); } diff --git a/src/operative/tasks/engine_session/engine_session.rs b/src/operative/tasks/engine_session/engine_session.rs index 26e89883..1c9afc54 100644 --- a/src/operative/tasks/engine_session/engine_session.rs +++ b/src/operative/tasks/engine_session/engine_session.rs @@ -130,7 +130,7 @@ pub async fn engine_batch_builder_background_task( // 9.1 Try to get the batch container. let batch_container_result = { let mut _session_pool = session_pool.lock().await; - _session_pool.into_batch_container(&engine_keyholder).await + _session_pool.into_batch_container(engine_keyholder).await }; // 9.2 Match the batch container result. diff --git a/src/operative/tasks/engine_session/session_pool/session_pool.rs b/src/operative/tasks/engine_session/session_pool/session_pool.rs index 39464d39..6e9e1e6f 100644 --- a/src/operative/tasks/engine_session/session_pool/session_pool.rs +++ b/src/operative/tasks/engine_session/session_pool/session_pool.rs @@ -375,7 +375,7 @@ impl SessionPool { bitcoin_transaction_feerate, engine_keyholder, ) - .map_err(|err| IntoBatchContainerError::SignedBatchTxnConstructError(err))?; + .map_err(IntoBatchContainerError::SignedBatchTxnConstructError)?; // 17 Construct the batch container. let batch_container = diff --git a/src/transmutative/bls/key.rs b/src/transmutative/bls/key.rs index 004f29bb..a8f01736 100644 --- a/src/transmutative/bls/key.rs +++ b/src/transmutative/bls/key.rs @@ -50,7 +50,7 @@ pub fn bls_secret_key_bytes_to_bls_secret_key(secret_key_bytes: [u8; 48]) -> BLS /// pub fn bls_public_key_bytes_to_bls_public_key(public_key_bytes: [u8; 48]) -> Option { // 1 Convert the 48-byte public key to a BLS public key. - public_key_bytes.try_into().ok() + Some(public_key_bytes.into()) } /// Converts a BLS secret key to a BLS public key. @@ -61,5 +61,5 @@ pub fn bls_public_key_bytes_to_bls_public_key(public_key_bytes: [u8; 48]) -> Opt /// pub fn bls_secret_key_to_bls_public_key(secret_key: BLSSecretKey) -> Option { // 1 Convert the BLS secret key to a BLS public key. - bls::sk_to_pk(secret_key).try_into().ok() + Some(bls::sk_to_pk(secret_key)) } diff --git a/src/transmutative/codec/address.rs b/src/transmutative/codec/address.rs index 52f7fad6..49e52e3e 100644 --- a/src/transmutative/codec/address.rs +++ b/src/transmutative/codec/address.rs @@ -8,8 +8,6 @@ type ScriptPubKey = Vec; /// This function takes a network type and returns the corresponding HRP. /// /// # Arguments -/// - fn hrp_from_chain(chain: Chain) -> Option { match chain { Chain::Signet | Chain::Testbed => Hrp::parse("tb").ok(), @@ -70,12 +68,10 @@ pub fn encode_p2wpkh(chain: Chain, witness_program: [u8; 20]) -> Option /// * `address` - The Bech32-encoded Bitcoin address to decode. /// /// # Returns -/// - pub fn address_to_spk(chain: Chain, address: &str) -> Option { let mut spk = Vec::::new(); - let (hrp, version, program) = match segwit::decode(&address) { + let (hrp, version, program) = match segwit::decode(address) { Ok(result) => result, Err(_) => return None, }; diff --git a/src/transmutative/codec/csv.rs b/src/transmutative/codec/csv.rs index 26a0915e..a27b4392 100644 --- a/src/transmutative/codec/csv.rs +++ b/src/transmutative/codec/csv.rs @@ -70,14 +70,14 @@ fn days_to_bytes(days: u8, cscript_num: bool) -> Bytes { if blocks <= 255 { // Single-byte vec.push(blocks as u8); - if cscript_num == true && blocks > 127 { + if cscript_num && blocks > 127 { // CScriptNum vec.push(0x00); } } else { // Two-bytes vec.extend(vec![(blocks & 0xFF) as u8, (blocks >> 8 & 0xFF) as u8]); - if cscript_num == true && blocks > 32767 { + if cscript_num && blocks > 32767 { // CScriptNum vec.push(0x00); } diff --git a/src/transmutative/codec/prefix.rs b/src/transmutative/codec/prefix.rs index 4274db01..3bf7a51d 100644 --- a/src/transmutative/codec/prefix.rs +++ b/src/transmutative/codec/prefix.rs @@ -16,7 +16,7 @@ impl Prefix for Bytes { let mut bytes = Vec::::new(); let data_len = self.len(); - if data_len == 1 && (&self[0] == &0x81 || &self[0] <= &16) { + if data_len == 1 && (self[0] == 0x81 || self[0] <= 16) { // Check minimal push. // https://github.com/bitcoin/bitcoin/blob/master/src/script/script.cpp#L366 match &self[0] { diff --git a/src/transmutative/hash.rs b/src/transmutative/hash.rs index 672a681f..be0e3fa2 100644 --- a/src/transmutative/hash.rs +++ b/src/transmutative/hash.rs @@ -50,13 +50,13 @@ impl HashTag { HashTag::BIP340Challenge => format!("{}/{}", "BIP0340", "challenge"), HashTag::SecretNonce => format!("{}/{}", baked::PROJECT_TAG, "secretnonce"), HashTag::SecretKey => format!("{}/{}", baked::PROJECT_TAG, "secretkey"), - HashTag::TapLeaf => format!("TapLeaf"), - HashTag::TapBranch => format!("TapBranch"), - HashTag::TapTweak => format!("TapTweak"), - HashTag::TapSighash => format!("TapSighash"), - HashTag::KeyAggList => format!("KeyAgg list"), - HashTag::KeyAggCoef => format!("KeyAgg coefficient"), - HashTag::MusigNonceCoef => format!("MuSig/noncecoef"), + HashTag::TapLeaf => "TapLeaf".to_string(), + HashTag::TapBranch => "TapBranch".to_string(), + HashTag::TapTweak => "TapTweak".to_string(), + HashTag::TapSighash => "TapSighash".to_string(), + HashTag::KeyAggList => "KeyAgg list".to_string(), + HashTag::KeyAggCoef => "KeyAgg coefficient".to_string(), + HashTag::MusigNonceCoef => "MuSig/noncecoef".to_string(), HashTag::BLSSecretKey => format!("{}/{}", baked::PROJECT_TAG, "bls/secretkey"), HashTag::CustomString(tag) => tag.clone(), HashTag::CustomBytes(tag) => tag.clone().into_iter().map(|b| b as char).collect(), diff --git a/src/transmutative/key.rs b/src/transmutative/key.rs index 14fc83b1..950a4f6d 100644 --- a/src/transmutative/key.rs +++ b/src/transmutative/key.rs @@ -143,10 +143,7 @@ impl KeyHolder { // 5.1.1 Zeroize the temporary BLS secret key bytes immediately after use. bls_secret_key_bytes_.zeroize(); // 5.2 Compute BLS public key from BLS secret key. - let bls_public_key: BLSPublicKey = match bls_secret_key_to_bls_public_key(bls_secret_key) { - Some(bls_public_key) => bls_public_key, - None => return None, - }; + let bls_public_key: BLSPublicKey = bls_secret_key_to_bls_public_key(bls_secret_key)?; // 5.3 Serialize BLS public key to 48 bytes. let bls_public_key_bytes: [u8; 48] = match bls_public_key.try_into() { Ok(bls_public_key_bytes) => bls_public_key_bytes, diff --git a/src/transmutative/musig/keyagg.rs b/src/transmutative/musig/keyagg.rs index a7bdcb34..f13e8417 100644 --- a/src/transmutative/musig/keyagg.rs +++ b/src/transmutative/musig/keyagg.rs @@ -13,7 +13,7 @@ pub struct MusigKeyAggCtx { } impl MusigKeyAggCtx { - pub fn new(keys: &Vec, tweak: Option) -> Option { + pub fn new(keys: &[Point], tweak: Option) -> Option { let keys = sort_keys(keys); let key_coefs = key_coefs(&keys)?; let agg_inner_key = key_agg(&keys, &key_coefs)?; @@ -25,7 +25,7 @@ impl MusigKeyAggCtx { MaybePoint::Infinity => return None, } } - None => agg_inner_key.clone(), + None => agg_inner_key, }; let ctx = MusigKeyAggCtx { @@ -48,15 +48,15 @@ impl MusigKeyAggCtx { } pub fn agg_inner_key(&self) -> Point { - self.agg_inner_key.clone() + self.agg_inner_key } pub fn tweak(&self) -> Option { - self.tweak.clone() + self.tweak } pub fn agg_key(&self) -> Point { - self.agg_key.clone() + self.agg_key } pub fn key_index(&self, key: Point) -> Option { @@ -70,19 +70,19 @@ impl MusigKeyAggCtx { } } -fn sort_keys(keys: &Vec) -> Vec { - let mut keys = keys.clone(); +fn sort_keys(keys: &[Point]) -> Vec { + let mut keys = keys.to_owned(); keys.sort(); keys } -fn get_second_key(keys: &Vec) -> Option { +fn get_second_key(keys: &[Point]) -> Option { let second_key = keys.get(1)?; Some(second_key.to_owned()) } -fn hash_keys(keys: &Vec) -> Option<[u8; 32]> { +fn hash_keys(keys: &[Point]) -> Option<[u8; 32]> { let mut preimage = Vec::::with_capacity(keys.len() * 33); for key in keys { @@ -94,7 +94,7 @@ fn hash_keys(keys: &Vec) -> Option<[u8; 32]> { Some(hash) } -fn keyagg_coef_internal(keys: &Vec, key: Point, second_key: Point) -> Option { +fn keyagg_coef_internal(keys: &[Point], key: Point, second_key: Point) -> Option { let coef = match key == second_key { true => Scalar::one(), false => { @@ -114,8 +114,8 @@ fn keyagg_coef_internal(keys: &Vec, key: Point, second_key: Point) -> Opt Some(coef) } -fn key_coefs(keys: &Vec) -> Option> { - let second_key = get_second_key(&keys)?; +fn key_coefs(keys: &[Point]) -> Option> { + let second_key = get_second_key(keys)?; let mut coefs = Vec::::with_capacity(keys.len()); @@ -127,7 +127,7 @@ fn key_coefs(keys: &Vec) -> Option> { Some(coefs) } -fn key_agg(keys: &Vec, key_coefs: &Vec) -> Option { +fn key_agg(keys: &[Point], key_coefs: &[Scalar]) -> Option { if keys.len() != key_coefs.len() { return None; }; @@ -136,7 +136,7 @@ fn key_agg(keys: &Vec, key_coefs: &Vec) -> Option { for (index, key) in keys.iter().enumerate() { let key_coef = key_coefs[index]; - agg_key = agg_key + (key.to_owned() * key_coef); + agg_key += key.to_owned() * key_coef; } let agg_key = match agg_key { diff --git a/src/transmutative/musig/session.rs b/src/transmutative/musig/session.rs index 3750eebf..4baa2a03 100644 --- a/src/transmutative/musig/session.rs +++ b/src/transmutative/musig/session.rs @@ -33,11 +33,15 @@ impl MusigSessionCtx { } pub fn insert_nonce(&mut self, key: Point, hiding_nonce: Point, binding_nonce: Point) -> bool { - if let None = self.key_agg_ctx.key_index(key) { + if self.key_agg_ctx.key_index(key).is_none() { return false; } - if let Some(_) = self.nonces.insert(key, (hiding_nonce, binding_nonce)) { + if self + .nonces + .insert(key, (hiding_nonce, binding_nonce)) + .is_some() + { return false; } @@ -64,7 +68,7 @@ impl MusigSessionCtx { None => return, }; - if let None = self.nonce_coef { + if self.nonce_coef.is_none() { self.nonce_coef = Some(nonce_coef) }; @@ -73,7 +77,7 @@ impl MusigSessionCtx { MaybePoint::Infinity => return, }; - if let None = self.agg_nonce { + if self.agg_nonce.is_none() { self.agg_nonce = Some(agg_nonce) }; @@ -83,7 +87,7 @@ impl MusigSessionCtx { None => return, }; - if let None = self.challenge { + if self.challenge.is_none() { self.challenge = Some(challenge) }; } @@ -119,34 +123,25 @@ impl MusigSessionCtx { secet_binding_nonce: Scalar, ) -> Option { let public_key = secret_key.base_point_mul(); - let key_coef = match self.key_agg_ctx.key_coef(public_key) { - Some(coef) => coef, - None => return None, - }; + let key_coef = self.key_agg_ctx.key_coef(public_key)?; - let (hiding_public_nonce, binding_public_nonce) = match self.nonces.get(&public_key) { - Some(tuple) => tuple, - None => return None, - }; + let (hiding_public_nonce, binding_public_nonce) = self.nonces.get(&public_key)?; - if secret_hiding_nonce.base_point_mul() != hiding_public_nonce.to_owned() { + if secret_hiding_nonce.base_point_mul() != *hiding_public_nonce { return None; }; - if secet_binding_nonce.base_point_mul() != binding_public_nonce.to_owned() { + if secet_binding_nonce.base_point_mul() != *binding_public_nonce { return None; }; let mut secret_key = secret_key.negate_if(self.key_agg_ctx.agg_inner_key().parity()); - if let Some(_) = self.key_agg_ctx.tweak() { + if self.key_agg_ctx.tweak().is_some() { secret_key = secret_key.negate_if(self.key_agg_ctx.agg_key().parity()); } - let challenge = match self.challenge { - Some(challenge) => challenge, - None => return None, - }; + let challenge = self.challenge?; let nonce_coef = self.nonce_coef?; let agg_nonce = self.agg_nonce?; @@ -167,7 +162,7 @@ impl MusigSessionCtx { } pub fn insert_partial_sig(&mut self, signer_key: Point, partial_sig: Scalar) -> bool { - if let Some(_) = self.partial_sigs.get(&signer_key) { + if self.partial_sigs.contains_key(&signer_key) { return false; } @@ -183,7 +178,7 @@ impl MusigSessionCtx { let mut key = signer_key.negate_if(self.key_agg_ctx.agg_inner_key().parity()); - if let Some(_) = self.key_agg_ctx.tweak() { + if self.key_agg_ctx.tweak().is_some() { key = key.negate_if(self.key_agg_ctx.agg_key().parity()); } @@ -226,7 +221,7 @@ impl MusigSessionCtx { let mut blame_list = Vec::::new(); for key in self.key_agg_ctx.keys().iter() { - if let None = self.partial_sigs.get(&key) { + if !self.partial_sigs.contains_key(key) { blame_list.push(key.to_owned()); } } @@ -236,14 +231,14 @@ impl MusigSessionCtx { pub fn agg_sig(&self) -> Option { println!("mara 0: {}", self.blame_list().len()); - if self.blame_list().len() != 0 { + if !self.blame_list().is_empty() { return None; } println!("mara 1"); let mut agg_sig = MaybeScalar::Zero; for (_, partial_sig) in self.partial_sigs.iter() { - agg_sig = agg_sig + partial_sig.to_owned(); + agg_sig += partial_sig.to_owned(); } let challenge = self.challenge?; @@ -252,15 +247,15 @@ impl MusigSessionCtx { let parity: bool = self.key_agg_ctx.agg_key().parity().into(); if parity { - agg_sig = agg_sig + (challenge * tweak) * Scalar::max() + agg_sig += (challenge * tweak) * Scalar::max() } else { - agg_sig = agg_sig + (challenge * tweak) + agg_sig += challenge * tweak } } match agg_sig { - MaybeScalar::Valid(scalar) => return Some(scalar), - MaybeScalar::Zero => return None, + MaybeScalar::Valid(scalar) => Some(scalar), + MaybeScalar::Zero => None, } } @@ -313,15 +308,15 @@ fn nonce_coef( } fn pre_nonce_agg(nonces: &HashMap) -> Option<(Point, Point)> { - let mut sorted_nonces: Vec<_> = nonces.into_iter().collect(); + let mut sorted_nonces: Vec<_> = nonces.iter().collect(); sorted_nonces.sort_by_key(|(key, _)| *key); let mut hiding_agg_nonce_ = MaybePoint::Infinity; let mut binding_agg_nonce_ = MaybePoint::Infinity; for (_, (hiding_nonce, binding_nonce)) in sorted_nonces { - hiding_agg_nonce_ = hiding_agg_nonce_ + hiding_nonce.to_owned(); - binding_agg_nonce_ = binding_agg_nonce_ + binding_nonce.to_owned(); + hiding_agg_nonce_ += hiding_nonce.to_owned(); + binding_agg_nonce_ += binding_nonce.to_owned(); } let hiding_agg_nonce = match hiding_agg_nonce_ { diff --git a/src/transmutative/secp/authenticable.rs b/src/transmutative/secp/authenticable.rs index 92f31d37..201f40a8 100644 --- a/src/transmutative/secp/authenticable.rs +++ b/src/transmutative/secp/authenticable.rs @@ -38,10 +38,7 @@ where /// Serialize the authenticable object. pub fn serialize(&self) -> Vec { - match serde_json::to_vec(self) { - Ok(bytes) => bytes, - Err(_) => vec![], - } + serde_json::to_vec(self).unwrap_or_default() } /// Get the object. diff --git a/src/transmutative/secp/into.rs b/src/transmutative/secp/into.rs index 543abab7..5e8c6140 100644 --- a/src/transmutative/secp/into.rs +++ b/src/transmutative/secp/into.rs @@ -155,7 +155,7 @@ impl IntoPoint for Vec { let ba = bytes .into_byte_array_32() .map_err(|_| SecpError::InvalidPoint)?; - return ba.into_point(); + ba.into_point() } 33 => { let mut bytes = Vec::::with_capacity(33); @@ -164,9 +164,9 @@ impl IntoPoint for Vec { let ba = bytes .into_byte_array_33() .map_err(|_| SecpError::InvalidPoint)?; - return ba.into_point(); + ba.into_point() } - _ => return Err(SecpError::InvalidPoint), + _ => Err(SecpError::InvalidPoint), } } } @@ -190,8 +190,8 @@ impl IntoScalar for [u8; 32] { } fn into_reduced_scalar(&self) -> Result { - let scalar = match MaybeScalar::reduce_from(&self) { - MaybeScalar::Zero => Scalar::reduce_from(&self), + let scalar = match MaybeScalar::reduce_from(self) { + MaybeScalar::Zero => Scalar::reduce_from(self), MaybeScalar::Valid(point) => point, }; @@ -240,10 +240,7 @@ impl IntoSigTuple for [u8; 64] { Err(_) => return None, }; - let public_nonce_point = match public_nonce.to_even_point() { - Some(public_nonce_point_) => public_nonce_point_, - None => return None, - }; + let public_nonce_point = public_nonce.to_even_point()?; let s_commitment: [u8; 32] = match self[32..].try_into() { Ok(bytes) => bytes, diff --git a/src/transmutative/secp/schnorr.rs b/src/transmutative/secp/schnorr.rs index 7e68aa8a..e615e0d7 100644 --- a/src/transmutative/secp/schnorr.rs +++ b/src/transmutative/secp/schnorr.rs @@ -233,18 +233,12 @@ impl Bytes32 for [u8; 32] { /// Returns whether the given bytes represent a valid scalar. fn is_valid_secret(&self) -> bool { - match Scalar::from_slice(self) { - Ok(_) => true, - Err(_) => false, - } + Scalar::from_slice(self).is_ok() } /// Returns whether the given bytes represent a valid even point. fn is_valid_public(&self) -> bool { - match self.to_even_point() { - Some(_) => true, - None => false, - } + self.to_even_point().is_some() } } diff --git a/tests/batchtxn.rs b/tests/batchtxn.rs index 00ae4b15..12589dfd 100644 --- a/tests/batchtxn.rs +++ b/tests/batchtxn.rs @@ -25,14 +25,14 @@ mod batchtxn_test { // 1 Construct Engine secret key. let engine_secret_key: [u8; 32] = hex::decode("2b9906a26e64b48f8f94cf17e9681cf189c74b73d5fe69c2906550a2dcc33b5f") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert secret key hex.".to_string())?; // 2 Construct Engine public key. let engine_public_key: [u8; 32] = hex::decode("f437f28e3d9dc4638fe24699feeb89c094544163706faea65b2b72f91cb7267a") - .map_err(|_| format!("Failed to parse public key hex."))? + .map_err(|_| "Failed to parse public key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert public key hex.".to_string())?; @@ -50,14 +50,14 @@ mod batchtxn_test { // 5 Construct User secret key. let user_secret_key: [u8; 32] = hex::decode("5280340afb7ade681b5d761b621818ef73ea6a10a425304d68d27a5d823df403") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert secret key hex.".to_string())?; // 6 Construct User public key. let user_public_key: [u8; 32] = hex::decode("06971ffe504c95152517d1be306b89b69e2f33c2c0e2a06b55f09d087b639d50") - .map_err(|_| format!("Failed to parse public key hex."))? + .map_err(|_| "Failed to parse public key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert public key hex.".to_string())?; @@ -117,7 +117,7 @@ mod batchtxn_test { // d1e3db2e7141123a9132976cda6285e6fdd10fe36bbd73fd724c8f4a989985de let prev_payload_txid: [u8; 32] = hex::decode("de8599984a8f4c72fd73bd6be30fd1fde68562da6c9732913a1241712edbe3d1") - .map_err(|_| format!("Failed to parse prev payload txid hex."))? + .map_err(|_| "Failed to parse prev payload txid hex.".to_string())? .try_into() .map_err(|_| "Failed to convert prev payload txid hex.".to_string())?; @@ -147,7 +147,7 @@ mod batchtxn_test { // 28d024000e05c1683f11b3ea60623a2529ce20e75b019a3d3280236a5a1e625e let funded_lift_txid: [u8; 32] = hex::decode("5e621e5a6a2380323d9a015be720ce29253a6260eab3113f68c1050e0024d028") - .map_err(|_| format!("Failed to parse prev payload txid hex."))? + .map_err(|_| "Failed to parse prev payload txid hex.".to_string())? .try_into() .map_err(|_| "Failed to convert prev payload txid hex.".to_string())?; diff --git a/tests/bls.rs b/tests/bls.rs index 9805006a..9fff7477 100644 --- a/tests/bls.rs +++ b/tests/bls.rs @@ -107,10 +107,7 @@ mod bls_test { // Aggregate the signatures. let aggregate_signature: [u8; 96] = - bls_aggregate(vec![signature_1, signature_2, signature_3]) - .unwrap() - .try_into() - .unwrap(); + bls_aggregate(vec![signature_1, signature_2, signature_3]).unwrap(); // Verify the aggregate signature. assert!(bls_verify_aggregate( diff --git a/tests/coin_manager.rs b/tests/coin_manager.rs index f24495b2..5db7f655 100644 --- a/tests/coin_manager.rs +++ b/tests/coin_manager.rs @@ -85,7 +85,7 @@ mod coin_manager_tests { let is_registered = _coin_manager.is_account_registered(ACCOUNT_KEY_1); // 5.5 The account should not be registered yet because changes are not applied yet. - assert_eq!(is_registered, false); + assert!(!is_registered); // 5.6 Apply the changes. let result = _coin_manager.apply_changes(); @@ -98,7 +98,7 @@ mod coin_manager_tests { // 5.11 Check if the account is registered. let is_registered = _coin_manager.is_account_registered(ACCOUNT_KEY_1); - assert_eq!(is_registered, true); + assert!(is_registered); // 5.12 Check if the account balance is 0. let account_balance = _coin_manager.get_account_balance(ACCOUNT_KEY_1); @@ -196,7 +196,7 @@ mod coin_manager_tests { // 6.5 Check if the account is registered. let is_registered = _coin_manager.is_account_registered(ACCOUNT_KEY_2); - assert_eq!(is_registered, true); + assert!(is_registered); // 6.6 Check if the account balance is 500. let account_balance = _coin_manager.get_account_balance(ACCOUNT_KEY_2); @@ -252,7 +252,7 @@ mod coin_manager_tests { // 7.5 Check if the account is registered. let is_registered = _coin_manager.is_account_registered(ACCOUNT_KEY_3); - assert_eq!(is_registered, true); + assert!(is_registered); } // 8 Register a contract. @@ -266,7 +266,7 @@ mod coin_manager_tests { // 8.7 Check if the contract is registered. Should fail since changes are not applied yet. let is_registered = _coin_manager.is_contract_registered(CONTRACT_ID_1); - assert_eq!(is_registered, false); + assert!(!is_registered); // 8.8 Apply changes. let result = _coin_manager.apply_changes(); @@ -277,7 +277,7 @@ mod coin_manager_tests { // 8.10 Check if the contract is registered. let is_registered = _coin_manager.is_contract_registered(CONTRACT_ID_1); - assert_eq!(is_registered, true); + assert!(is_registered); } // 9 Contract balance updates. diff --git a/tests/graveyard.rs b/tests/graveyard.rs index ed882597..01dd522f 100644 --- a/tests/graveyard.rs +++ b/tests/graveyard.rs @@ -69,7 +69,7 @@ mod graveyard_tests { let _graveyard = graveyard.lock().await; // 6.2 Check if the account is buried. - assert_eq!(_graveyard.is_account_buried(ACCOUNT_KEY_1), true); + assert!(_graveyard.is_account_buried(ACCOUNT_KEY_1)); } // 7 Retrieve the redemption amount for the account. @@ -107,7 +107,7 @@ mod graveyard_tests { let _graveyard = graveyard.lock().await; // 9.2 Check if the account is buried. - assert_eq!(_graveyard.is_account_buried(ACCOUNT_KEY_2), true); + assert!(_graveyard.is_account_buried(ACCOUNT_KEY_2)); } // 10 Retrieve the redemption amount for the account. @@ -237,7 +237,7 @@ mod graveyard_tests { let _graveyard = graveyard.lock().await; // 18.2 Check if the account is buried. - assert_eq!(_graveyard.is_account_buried(ACCOUNT_KEY_3), true); + assert!(_graveyard.is_account_buried(ACCOUNT_KEY_3)); } // 19 Retrieve the redemption amount for the account. diff --git a/tests/key.rs b/tests/key.rs index 22efe2f2..c26d3976 100644 --- a/tests/key.rs +++ b/tests/key.rs @@ -1,13 +1,12 @@ #[cfg(test)] mod key_tests { use cube::transmutative::key::{FromNostrKeyStr, ToNostrKeyStr}; - use hex; #[test] fn to_nsec() -> Result<(), String> { let secret_key_bytes: [u8; 32] = hex::decode("bceef655b5a034911f1c3718ce056531b45ef03b4c7b1f15629e867294011a7d") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Invalid key length. Expected 32 bytes.".to_string())?; @@ -33,7 +32,7 @@ mod key_tests { let expected_secret_key_bytes: [u8; 32] = hex::decode("bceef655b5a034911f1c3718ce056531b45ef03b4c7b1f15629e867294011a7d") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Invalid key length. Expected 32 bytes.".to_string())?; @@ -46,7 +45,7 @@ mod key_tests { fn to_npub() -> Result<(), String> { let public_key_bytes: [u8; 32] = hex::decode("cbecda1c7d37d4c0aa5466243bb4a0018c31bf06d74fa7338290dd3068db4fed") - .map_err(|_| format!("Failed to parse public key hex."))? + .map_err(|_| "Failed to parse public key hex.".to_string())? .try_into() .map_err(|_| "Invalid key length. Expected 32 bytes.".to_string())?; @@ -72,7 +71,7 @@ mod key_tests { let expected_public_key_bytes: [u8; 32] = hex::decode("cbecda1c7d37d4c0aa5466243bb4a0018c31bf06d74fa7338290dd3068db4fed") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Invalid key length. Expected 32 bytes.".to_string())?; diff --git a/tests/musig.rs b/tests/musig.rs index 60b7cdda..056d1024 100644 --- a/tests/musig.rs +++ b/tests/musig.rs @@ -71,7 +71,7 @@ mod musig_standalone { signer_1_binding_public_nonce, )); - assert_eq!(session_ctx.ready(), false); + assert!(!session_ctx.ready()); // Siner 2 inserting their nonce. @@ -95,7 +95,7 @@ mod musig_standalone { signer_2_binding_public_nonce, )); - assert_eq!(session_ctx.ready(), false); + assert!(!session_ctx.ready()); // Siner 3 inserting their nonce. @@ -119,7 +119,7 @@ mod musig_standalone { signer_3_binding_public_nonce, )); - assert_eq!(session_ctx.ready(), true); + assert!(session_ctx.ready()); // Agg nonce diff --git a/tests/schnorr.rs b/tests/schnorr.rs index ffd01204..c23a5e44 100644 --- a/tests/schnorr.rs +++ b/tests/schnorr.rs @@ -1,19 +1,18 @@ #[cfg(test)] mod schnorr_tests { use cube::transmutative::secp::schnorr::{self, SchnorrSigningMode}; - use hex; #[test] fn sign() -> Result<(), String> { let message: [u8; 32] = hex::decode("1dd8312636f6a0bf3d21fa2855e63072507453e93a5ced4301b364e91c9d87d6") - .map_err(|_| format!("Failed to parse message hex."))? + .map_err(|_| "Failed to parse message hex.".to_string())? .try_into() .map_err(|_| "Failed to convert message hex.".to_string())?; let secret_key: [u8; 32] = hex::decode("2795044ce0f83f718bc79c5f2add1e52521978df91ce9b7f82c9097191d33602") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert secret key hex.".to_string())?; @@ -26,24 +25,24 @@ mod schnorr_tests { fn verify() -> Result<(), String> { let message: [u8; 32] = hex::decode("1dd8312636f6a0bf3d21fa2855e63072507453e93a5ced4301b364e91c9d87d6") - .map_err(|_| format!("Failed to parse message hex."))? + .map_err(|_| "Failed to parse message hex.".to_string())? .try_into() .map_err(|_| "Failed to convert message hex.".to_string())?; let public_key: [u8; 32] = hex::decode("d0ea35e4a5d654109aef6b175672ea98099212a42d028fcf8bd4e38c137ff15a") - .map_err(|_| format!("Failed to parse public key hex."))? + .map_err(|_| "Failed to parse public key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert public key hex.".to_string())?; let signature: [u8; 64] = hex::decode("836be8788ceed5850363f9f70bd0566f2d1822b709aa150affc854421cc4c982507f831e8ec808e5bd06ce6310ae8c1624df34d345964f5b0bae72467a7b230b") - .map_err(|_| format!("Failed to parse signature hex."))? + .map_err(|_| "Failed to parse signature hex.".to_string())? .try_into() .map_err(|_| "Failed to convert signature hex.".to_string())?; schnorr::verify_xonly(public_key, message, signature, SchnorrSigningMode::Cube) - .then(|| ()) + .then_some(()) .ok_or("Failed to verify signature.")?; Ok(()) diff --git a/tests/simul.rs b/tests/simul.rs index 9cea1ab6..5c6d9522 100644 --- a/tests/simul.rs +++ b/tests/simul.rs @@ -44,7 +44,7 @@ mod simul_tests { use cube::operative::tasks::engine_session::session_pool::session_pool::SessionPool; use cube::operative::tasks::engine_session::session_pool::session_pool::SESSION_POOL; use cube::transmutative::key::KeyHolder; - use hex; + use serde_json::to_string_pretty; use std::sync::Arc; @@ -67,14 +67,14 @@ mod simul_tests { // 3 Construct self secret key. let secret_key: [u8; 32] = hex::decode("2795044ce0f83f718bc79c5f2add1e52521978df91ce9b7f82c9097191d33602") - .map_err(|_| format!("Failed to parse secret key hex."))? + .map_err(|_| "Failed to parse secret key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert secret key hex.".to_string())?; // 4 Construct self public key. let public_key: [u8; 32] = hex::decode("d0ea35e4a5d654109aef6b175672ea98099212a42d028fcf8bd4e38c137ff15a") - .map_err(|_| format!("Failed to parse public key hex."))? + .map_err(|_| "Failed to parse public key hex.".to_string())? .try_into() .map_err(|_| "Failed to convert public key hex.".to_string())?; diff --git a/tests/taproot.rs b/tests/taproot.rs index 9e8511f5..31c62ff4 100644 --- a/tests/taproot.rs +++ b/tests/taproot.rs @@ -133,7 +133,7 @@ mod taproot_tests { let expected_spk = hex::decode("512085dbf94f892274c41acb75d48daf338c739d1157c70963912db526c4cad30d1a")?; assert_eq!(tap_root_with_odd.spk().unwrap(), expected_spk); - assert_eq!(tap_root_with_odd.tweaked_key_parity().unwrap(), true); + assert!(tap_root_with_odd.tweaked_key_parity().unwrap()); // Test with even tweaked key @@ -143,7 +143,7 @@ mod taproot_tests { let expected_spk = hex::decode("51201fbb64a309f43ee6a442cd293a9df3ce3bbb0864a2215a1091c06521021f9de4")?; assert_eq!(tap_root_with_even.spk().unwrap(), expected_spk); - assert_eq!(tap_root_with_even.tweaked_key_parity().unwrap(), false); + assert!(!tap_root_with_even.tweaked_key_parity().unwrap()); Ok(()) } @@ -317,14 +317,7 @@ mod taproot_tests { let tap_leaf_4: TapLeaf = TapLeaf::new(vec![0xdd]); let tap_leaf_5: TapLeaf = TapLeaf::new(vec![0xee]); - let mut leaves: Vec = vec![]; - - // Test single-leaf - aa - leaves.push(tap_leaf_1); - leaves.push(tap_leaf_2); - leaves.push(tap_leaf_3); - leaves.push(tap_leaf_4); - leaves.push(tap_leaf_5); + let leaves: Vec = vec![tap_leaf_1, tap_leaf_2, tap_leaf_3, tap_leaf_4, tap_leaf_5]; let tap_tree: TapTree = TapTree::new(leaves.clone()); From 9b202a27f22bf7686b33e06094ed97b6f832e713 Mon Sep 17 00:00:00 2001 From: GideonBature Date: Fri, 5 Jun 2026 22:32:39 +0100 Subject: [PATCH 3/4] Add CI checks for every PR to main branch --- .github/workflows/ci.yml | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..47394213 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + pull_request: + branches: + - main + push: + branches: + - main + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + checks: + name: Rust checks + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Cache cargo registry and build artifacts + uses: Swatinem/rust-cache@v2 + + - name: cargo fmt + run: cargo fmt --all -- --check + + - name: cargo check + run: cargo check --all-targets + + - name: cargo clippy + run: cargo clippy --all-targets -- -D warnings + + - name: cargo build + run: cargo build --all-targets + + - name: cargo test + run: cargo test --all-targets From ba6aa7c2f411da3118502589a84eb9c8ffe581ea Mon Sep 17 00:00:00 2001 From: GideonBature Date: Fri, 5 Jun 2026 22:46:59 +0100 Subject: [PATCH 4/4] Fix clippy error from CI check --- .../calldata/calldata_elements/calldata_element.rs | 11 +++++------ .../algorithms/flame_selection/flame_selection.rs | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs b/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs index 21537859..89590d2b 100644 --- a/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs +++ b/src/constructive/core_types/calldata/calldata_elements/calldata_element.rs @@ -37,13 +37,12 @@ impl CalldataElement { }); } } - CalldataElement::Varbytes(bytes) => { - if bytes.len() > MAX_VARBYTES_LEN { - return Err(CalldataElementValidationError::VarbytesLengthExceedsMax { - len: bytes.len(), - }); - } + CalldataElement::Varbytes(bytes) if bytes.len() > MAX_VARBYTES_LEN => { + return Err(CalldataElementValidationError::VarbytesLengthExceedsMax { + len: bytes.len(), + }); } + CalldataElement::Varbytes(_) => {} _ => {} } Ok(()) diff --git a/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs b/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs index 35a2298a..04a67ccc 100644 --- a/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs +++ b/src/inscriptive/flame_manager/algorithms/flame_selection/flame_selection.rs @@ -118,7 +118,7 @@ pub fn return_flames_to_fund( } // 4.b.2 Sort tiers in descending order by value (largest first). - available_tiers.sort_by(|a, b| b.0.cmp(&a.0)); + available_tiers.sort_by_key(|tier| std::cmp::Reverse(tier.0)); // 4.b.2.1 Store the smallest tier for rounding up if needed. let smallest_tier = available_tiers.last().cloned();