From 4c610c5538dbfb2e9015720c62cfcf70ae46ca73 Mon Sep 17 00:00:00 2001 From: Moncef AOUDIA Date: Wed, 16 Nov 2022 18:23:09 +0100 Subject: [PATCH] refactor: merge and clean --- Cargo.lock | 74 ++++---- massa-api/Cargo.toml | 2 +- massa-api/src/lib.rs | 2 +- massa-api/src/private.rs | 1 - massa-api/src/public.rs | 160 +++++++----------- massa-execution-worker/src/active_history.rs | 19 ++- .../src/speculative_roll_state.rs | 31 ++-- massa-execution-worker/src/tests/mock.rs | 3 +- .../src/tests/scenarios_mandatories.rs | 54 +++--- .../src/tests/tests_active_history.rs | 31 ++-- massa-pos-exports/src/deferred_credits.rs | 19 ++- massa-sdk/Cargo.toml | 2 +- massa-sdk/src/lib.rs | 2 +- 13 files changed, 183 insertions(+), 217 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc3575f96c..350f09b5b37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1416,8 +1416,9 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0ee76536f6a303b67c13a99ecae0002bb388674dbf416094dde808263ea229c" dependencies = [ "jsonrpsee-client-transport", "jsonrpsee-core", @@ -1432,8 +1433,9 @@ dependencies = [ [[package]] name = "jsonrpsee-client-transport" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74c8f8f21b684623d23be8b6fcb101594f4e95d8a505ffd0568de863d93668f4" dependencies = [ "anyhow", "futures-channel", @@ -1456,8 +1458,9 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f57020f4c98b6c6e8848fb115e61227fba6993517bee0faa38e4db627a9f7254" dependencies = [ "anyhow", "arrayvec", @@ -1484,8 +1487,9 @@ dependencies = [ [[package]] name = "jsonrpsee-http-client" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca71086fd13ad0991cd4a0e50c9f4c59488b1acfac4a528c448c2e10020aa1e" dependencies = [ "async-trait", "hyper", @@ -1502,8 +1506,9 @@ dependencies = [ [[package]] name = "jsonrpsee-proc-macros" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d335519bfe970511318f2780b7716f91d99d67fbf32ac3ea94b5f2f6c9818a4d" dependencies = [ "heck 0.4.0", "proc-macro-crate", @@ -1514,8 +1519,9 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff5de9e3d6280c5354882e001494bc6ffb3ea31ac7dd81440f997aa380039e39" dependencies = [ "futures-channel", "futures-util", @@ -1535,8 +1541,9 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88c88c764104fef883eb8a832d0d77688a63f67d75b385f5cdae7b3db8925288" dependencies = [ "anyhow", "beef", @@ -1548,8 +1555,9 @@ dependencies = [ [[package]] name = "jsonrpsee-wasm-client" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d11a058951524f3f6e02e94c26d5c189a5df0f2dea81339147c603b9eb7c511d" dependencies = [ "jsonrpsee-client-transport", "jsonrpsee-core", @@ -1558,8 +1566,9 @@ dependencies = [ [[package]] name = "jsonrpsee-ws-client" -version = "0.15.1" -source = "git+https://github.com/paritytech/jsonrpsee?branch=master#425b1b6eb75ecdc5a1ebab10d22cbd41b68399ec" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea609539b5062f856a43652fd01d8ed8df40cd4d7067be6f6b7ce81d8bbd03be" dependencies = [ "http", "jsonrpsee-client-transport", @@ -1851,7 +1860,7 @@ dependencies = [ "bitvec", "displaydoc", "fix-hidden-lifetime-bug", - "futures 0.3.24", + "futures", "lazy_static", "massa_async_pool", "massa_consensus_exports", @@ -1913,8 +1922,8 @@ dependencies = [ "massa_signature", "massa_storage", "massa_time", - "nom 7.1.1", - "serde 1.0.145", + "nom", + "serde", "serde_json", "thiserror", ] @@ -1933,7 +1942,7 @@ dependencies = [ "massa_time", "num", "parking_lot", - "serde 1.0.145", + "serde", "serde_json", "tracing", ] @@ -2061,27 +2070,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "massa_graph" -version = "0.1.0" -dependencies = [ - "displaydoc", - "massa_execution_exports", - "massa_hash", - "massa_logging", - "massa_models", - "massa_pos_exports", - "massa_serialization", - "massa_signature", - "massa_storage", - "nom 7.1.1", - "num", - "serde 1.0.145", - "serde_json", - "thiserror", - "tracing", -] - [[package]] name = "massa_hash" version = "0.1.0" diff --git a/massa-api/Cargo.toml b/massa-api/Cargo.toml index 14846bc9571..18626c638be 100644 --- a/massa-api/Cargo.toml +++ b/massa-api/Cargo.toml @@ -7,7 +7,7 @@ edition = "2021" [dependencies] displaydoc = "0.2" -jsonrpsee = { git = "https://github.com/paritytech/jsonrpsee", branch = "master", features = ["server", "macros"] } +jsonrpsee = { version = "0.16.0", features = ["server", "macros"] } async-trait = "0.1.58" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.87" diff --git a/massa-api/src/lib.rs b/massa-api/src/lib.rs index 6edb33a2a06..75039f5ad7c 100644 --- a/massa-api/src/lib.rs +++ b/massa-api/src/lib.rs @@ -7,7 +7,7 @@ use crate::error::ApiError::WrongAPI; use jsonrpsee::core::{Error as JsonRpseeError, RpcResult}; use jsonrpsee::proc_macros::rpc; use jsonrpsee::server::{ServerBuilder, ServerHandle}; -use massa_consensus_exports::{ConsensusCommandSender, ConsensusConfig}; +use massa_consensus_exports::ConsensusController; use massa_execution_exports::ExecutionController; use massa_models::api::{ AddressInfo, BlockInfo, BlockSummary, DatastoreEntryInput, DatastoreEntryOutput, diff --git a/massa-api/src/private.rs b/massa-api/src/private.rs index 87f47ee3c38..7ec0d646d3d 100644 --- a/massa-api/src/private.rs +++ b/massa-api/src/private.rs @@ -6,7 +6,6 @@ use crate::{MassaRpcServer, Private, RpcServer, StopHandle, Value, API}; use async_trait::async_trait; use jsonrpsee::core::{Error as JsonRpseeError, RpcResult}; -use massa_consensus_exports::{ConsensusCommandSender, ConsensusConfig}; use massa_execution_exports::ExecutionController; use massa_models::api::{ AddressInfo, BlockInfo, BlockSummary, DatastoreEntryInput, DatastoreEntryOutput, diff --git a/massa-api/src/public.rs b/massa-api/src/public.rs index d93f6248d49..31980b1238a 100644 --- a/massa-api/src/public.rs +++ b/massa-api/src/public.rs @@ -6,7 +6,8 @@ use crate::error::ApiError; use crate::{MassaRpcServer, Public, RpcServer, StopHandle, Value, API}; use async_trait::async_trait; use jsonrpsee::core::{Error as JsonRpseeError, RpcResult}; -use massa_consensus_exports::{ConsensusCommandSender, ConsensusConfig}; +use massa_consensus_exports::block_status::DiscardReason; +use massa_consensus_exports::ConsensusController; use massa_execution_exports::{ ExecutionController, ExecutionStackElement, ReadOnlyExecutionRequest, ReadOnlyExecutionTarget, }; @@ -301,6 +302,7 @@ impl MassaRpcServer for API { let network_command_sender = self.0.network_command_sender.clone(); let network_config = self.0.network_settings.clone(); let version = self.0.version; + let api_settings = self.0.api_settings.clone(); let compensation_millis = self.0.compensation_millis; let pool_command_sender = self.0.pool_command_sender.clone(); let node_id = self.0.node_id; @@ -311,9 +313,9 @@ impl MassaRpcServer for API { }; let last_slot_result = get_latest_block_slot_at_timestamp( - consensus_settings.thread_count, - consensus_settings.t0, - consensus_settings.genesis_timestamp, + api_settings.thread_count, + api_settings.t0, + api_settings.genesis_timestamp, now, ); let last_slot = match last_slot_result { @@ -322,19 +324,18 @@ impl MassaRpcServer for API { }; let execution_stats = execution_controller.get_stats(); - - let (consensus_stats_result, network_stats_resultat, peers_result) = tokio::join!( - consensus_command_sender.get_stats(), - network_command_sender.get_network_stats(), - network_command_sender.get_peers() - ); - + let consensus_stats_result = consensus_controller.get_stats(); let consensus_stats = match consensus_stats_result { Ok(consensus_stats) => consensus_stats, Err(e) => return Err(ApiError::from(e).into()), }; - let network_stats = match network_stats_resultat { + let (network_stats_result, peers_result) = tokio::join!( + network_command_sender.get_network_stats(), + network_command_sender.get_peers() + ); + + let network_stats = match network_stats_result { Ok(network_stats) => network_stats, Err(e) => return Err(ApiError::from(e).into()), }; @@ -351,7 +352,7 @@ impl MassaRpcServer for API { let next_slot_result = last_slot .unwrap_or_else(|| Slot::new(0, 0)) - .get_next_slot(consensus_settings.thread_count); + .get_next_slot(api_settings.thread_count); let next_slot = match next_slot_result { Ok(next_slot) => next_slot, @@ -373,30 +374,26 @@ impl MassaRpcServer for API { }) .collect(), last_slot, - next_slot: next_slot, + next_slot, execution_stats, - consensus_stats: consensus_stats, - network_stats: network_stats, + consensus_stats, + network_stats, pool_stats, config, current_cycle: last_slot .unwrap_or_else(|| Slot::new(0, 0)) - .get_cycle(consensus_settings.periods_per_cycle), + .get_cycle(api_settings.periods_per_cycle), }) } - fn get_cliques(&self) -> BoxFuture, ApiError>> { - let consensus_command_sender = self.0.consensus_command_sender.clone(); - let clicques_result = consensus_command_sender.get_cliques().await; - match clicques_result { - Ok(cliques) => Ok(cliques), - Err(e) => Err(ApiError::from(e).into()), - } + async fn get_cliques(&self) -> RpcResult> { + let consensus_controller = self.0.consensus_controller.clone(); + Ok(consensus_controller.get_cliques()) } async fn get_stakers(&self) -> RpcResult> { let execution_controller = self.0.execution_controller.clone(); - let api_config = self.0.api_settings.clone(); + let cfg = self.0.api_settings.clone(); let compensation_millis = self.0.compensation_millis; let now = match MassaTime::now(compensation_millis) { @@ -454,11 +451,10 @@ impl MassaRpcServer for API { let in_pool = self.0.pool_command_sender.contains_operations(&ops); let api_cfg = self.0.api_settings.clone(); - let consensus_command_sender = self.0.consensus_command_sender.clone(); - let closure = async move || { - if ops.len() as u64 > api_cfg.max_arguments { - return Err(ApiError::BadRequest("too many arguments".into())); - } + let consensus_controller = self.0.consensus_controller.clone(); + if ops.len() as u64 > api_cfg.max_arguments { + return Err(ApiError::BadRequest("too many arguments".into()).into()); + } // check finality by cross-referencing Consensus and looking for final blocks that contain the op let is_final: Vec = { @@ -469,15 +465,7 @@ impl MassaRpcServer for API { .cloned() .collect(); - let involved_block_statuses = match consensus_command_sender - .get_block_statuses(&involved_blocks) - .await - { - Ok(block_statues) => block_statues, - Err(e) => { - return Err(ApiError::from(e).into()); - } - }; + let involved_block_statuses = consensus_controller.get_block_statuses(&involved_blocks); let block_statuses: PreHashMap = involved_blocks .into_iter() @@ -543,29 +531,20 @@ impl MassaRpcServer for API { let consensus_controller = self.0.consensus_controller.clone(); let api_cfg = self.0.api_settings.clone(); - // check finality by cross-referencing Consensus and looking for final blocks that contain the endorsement - let is_final: Vec = { - let involved_blocks: Vec = storage_info - .iter() - .flat_map(|(_ed, bs)| bs.iter()) - .unique() - .cloned() - .collect(); - let involved_block_statuses = consensus_command_sender - .get_block_statuses(&involved_blocks) - .await?; - let block_statuses: PreHashMap = involved_blocks - .into_iter() - .zip(involved_block_statuses.into_iter()) - .collect(); - storage_info - .iter() - .map(|(_ed, bs)| { - bs.iter() - .any(|b| block_statuses.get(b) == Some(&BlockGraphStatus::Final)) - }) - .collect() - }; + if eds.len() as u64 > api_cfg.max_arguments { + return Err(ApiError::BadRequest("too many arguments".into()).into()); + } + + // check finality by cross-referencing Consensus and looking for final blocks that contain the endorsement + let is_final: Vec = { + let involved_blocks: Vec = storage_info + .iter() + .flat_map(|(_ed, bs)| bs.iter()) + .unique() + .cloned() + .collect(); + + let involved_block_statuses = consensus_controller.get_block_statuses(&involved_blocks); let block_statuses: PreHashMap = involved_blocks .into_iter() @@ -604,8 +583,8 @@ impl MassaRpcServer for API { /// gets a block. Returns None if not found /// only active blocks are returned - fn get_block(&self, id: BlockId) -> BoxFuture> { - let consensus_command_sender = self.0.consensus_command_sender.clone(); + async fn get_block(&self, id: BlockId) -> RpcResult { + let consensus_controller = self.0.consensus_controller.clone(); let storage = self.0.storage.clone_without_refs(); let block = match storage.read_blocks().get(&id).cloned() { Some(b) => b.content, @@ -614,13 +593,11 @@ impl MassaRpcServer for API { } }; - let graph_status = match consensus_command_sender.get_block_statuses(&[id]).await { - Ok(block_status) => block_status - .into_iter() - .next() - .expect("expected get_block_statuses to return one element"), - Err(e) => return Err(ApiError::from(e).into()), - }; + let graph_status = consensus_controller + .get_block_statuses(&[id]) + .into_iter() + .next() + .expect("expected get_block_statuses to return one element"); let is_final = graph_status == BlockGraphStatus::Final; let is_in_blockclique = graph_status == BlockGraphStatus::ActiveInBlockclique; @@ -640,20 +617,11 @@ impl MassaRpcServer for API { }) } - fn get_blockclique_block_by_slot( - &self, - slot: Slot, - ) -> BoxFuture, ApiError>> { - let consensus_command_sender = self.0.consensus_command_sender.clone(); + async fn get_blockclique_block_by_slot(&self, slot: Slot) -> RpcResult> { + let consensus_controller = self.0.consensus_controller.clone(); let storage = self.0.storage.clone_without_refs(); - let block_id_option = match consensus_command_sender - .get_blockclique_block_at_slot(slot) - .await - { - Ok(graph) => graph, - Err(e) => return Err(ApiError::from(e).into()), - }; + let block_id_option = consensus_controller.get_blockclique_block_at_slot(slot); let block_id = match block_id_option { Some(id) => id, @@ -669,18 +637,15 @@ impl MassaRpcServer for API { /// gets an interval of the block graph from consensus, with time filtering /// time filtering is done consensus-side to prevent communication overhead - fn get_graph_interval( - &self, - time: TimeInterval, - ) -> BoxFuture, ApiError>> { - let consensus_command_sender = self.0.consensus_command_sender.clone(); - let consensus_settings = self.0.consensus_config.clone(); + async fn get_graph_interval(&self, time: TimeInterval) -> RpcResult> { + let consensus_controller = self.0.consensus_controller.clone(); + let api_settings = self.0.api_settings.clone(); // filter blocks from graph_export let time_range_to_slot_range_result = time_range_to_slot_range( - consensus_settings.thread_count, - consensus_settings.t0, - consensus_settings.genesis_timestamp, + api_settings.thread_count, + api_settings.t0, + api_settings.genesis_timestamp, time.start, time.end, ); @@ -690,10 +655,7 @@ impl MassaRpcServer for API { Err(e) => return Err(ApiError::from(e).into()), }; - let graph = match consensus_command_sender - .get_block_graph_status(start_slot, end_slot) - .await - { + let graph = match consensus_controller.get_block_graph_status(start_slot, end_slot) { Ok(graph) => graph, Err(e) => return Err(ApiError::from(e).into()), }; @@ -938,10 +900,8 @@ impl MassaRpcServer for API { let ids: Vec = verified_ops.iter().map(|op| op.id).collect(); cmd_sender.add_operations(to_send.clone()); - let _propagate_operation = match protocol_sender.propagate_operations(to_send).await { - Ok(()) => (), - Err(e) => return Err(ApiError::from(e).into()), - }; + let _propagate_operation = protocol_sender.propagate_operations(to_send); + Ok(ids) } diff --git a/massa-execution-worker/src/active_history.rs b/massa-execution-worker/src/active_history.rs index 9706a7d965c..bc119414dfb 100644 --- a/massa-execution-worker/src/active_history.rs +++ b/massa-execution-worker/src/active_history.rs @@ -161,15 +161,18 @@ impl ActiveHistory { } /// Gets the deferred credits for a given address that will be credited at a given slot - pub(crate) fn get_adress_deferred_credit_for(&self, addr: &Address, slot: &Slot) -> Option { - for hist_item in self.0 - .iter() - .rev() { + pub(crate) fn get_adress_deferred_credit_for( + &self, + addr: &Address, + slot: &Slot, + ) -> Option { + for hist_item in self.0.iter().rev() { if let Some(v) = hist_item - .state_changes - .pos_changes - .deferred_credits - .get_address_deferred_credit_for_slot(addr, slot) { + .state_changes + .pos_changes + .deferred_credits + .get_address_deferred_credit_for_slot(addr, slot) + { return Some(v); } } diff --git a/massa-execution-worker/src/speculative_roll_state.rs b/massa-execution-worker/src/speculative_roll_state.rs index 795f1e29a47..911076e4ee3 100644 --- a/massa-execution-worker/src/speculative_roll_state.rs +++ b/massa-execution-worker/src/speculative_roll_state.rs @@ -136,15 +136,14 @@ impl SpeculativeRollState { .saturating_add(roll_price.saturating_mul_u64(roll_count)); // Remove the rolls - self - .added_changes + self.added_changes .roll_changes .insert(*seller_addr, owned_count.saturating_sub(roll_count)); // Add deferred credits (reimbursement) corresponding to the sold rolls value self.added_changes - .deferred_credits - .insert(*seller_addr, target_slot, new_deferred_credits); + .deferred_credits + .insert(*seller_addr, target_slot, new_deferred_credits); Ok(()) } @@ -277,26 +276,32 @@ impl SpeculativeRollState { /// Gets the deferred credits for a given address that will be credited at a given slot fn get_address_deferred_credit_for_slot(&self, addr: &Address, slot: &Slot) -> Option { - // search in the added changes - if let Some(v) = self.added_changes + if let Some(v) = self + .added_changes .deferred_credits - .get_address_deferred_credit_for_slot(addr, slot) { + .get_address_deferred_credit_for_slot(addr, slot) + { return Some(v); } // search in the history - if let Some(v) = self.active_history + if let Some(v) = self + .active_history .read() - .get_adress_deferred_credit_for(addr, slot) { + .get_adress_deferred_credit_for(addr, slot) + { return Some(v); } // search in the final state - if let Some(v) = self.final_state + if let Some(v) = self + .final_state .read() - .pos_state.deferred_credits - .get_address_deferred_credit_for_slot(addr, slot) { + .pos_state + .deferred_credits + .get_address_deferred_credit_for_slot(addr, slot) + { return Some(v); } @@ -490,7 +495,7 @@ impl SpeculativeRollState { credits.extend( self.active_history .read() - .get_all_deferred_credits_for(slot) + .get_all_deferred_credits_for(slot), ); // added deferred credits diff --git a/massa-execution-worker/src/tests/mock.rs b/massa-execution-worker/src/tests/mock.rs index 98618eeb0f1..9a8c224b4bb 100644 --- a/massa-execution-worker/src/tests/mock.rs +++ b/massa-execution-worker/src/tests/mock.rs @@ -95,8 +95,7 @@ pub fn get_sample_state() -> Result<(Arc>, NamedTempFile, Tem }; let (_, selector_controller) = start_selector_worker(SelectorConfig::default()) .expect("could not start selector controller"); - let mut final_state = - FinalState::new(cfg, Box::new(ledger), selector_controller).unwrap(); + let mut final_state = FinalState::new(cfg, Box::new(ledger), selector_controller).unwrap(); final_state.compute_initial_draws().unwrap(); final_state.pos_state.create_initial_cycle(); Ok((Arc::new(RwLock::new(final_state)), tempfile, tempdir)) diff --git a/massa-execution-worker/src/tests/scenarios_mandatories.rs b/massa-execution-worker/src/tests/scenarios_mandatories.rs index fd4c9948c04..b7c8f5f1f44 100644 --- a/massa-execution-worker/src/tests/scenarios_mandatories.rs +++ b/massa-execution-worker/src/tests/scenarios_mandatories.rs @@ -19,11 +19,11 @@ use massa_models::{ use massa_signature::KeyPair; use massa_storage::Storage; use massa_time::MassaTime; +use num::rational::Ratio; use serial_test::serial; use std::{ cmp::Reverse, collections::BTreeMap, collections::HashMap, str::FromStr, time::Duration, }; -use num::rational::Ratio; #[test] #[serial] @@ -459,7 +459,6 @@ pub fn roll_buy() { #[test] #[serial] pub fn roll_sell() { - // Try to sell 10 rolls (operation 1) then 1 rolls (operation 2) // Check for resulting roll count + resulting deferred credits @@ -494,11 +493,7 @@ pub fn roll_sell() { let address = Address::from_public_key(&keypair.get_public_key()); // get initial balance - let balance_initial = sample_state - .read() - .ledger - .get_balance(&address) - .unwrap(); + let balance_initial = sample_state.read().ledger.get_balance(&address).unwrap(); // get initial roll count let roll_count_initial = sample_state.read().pos_state.get_rolls_for(&address); @@ -510,7 +505,9 @@ pub fn roll_sell() { Operation { fee: Amount::zero(), expire_period: 10, - op: OperationType::RollSell { roll_count: roll_sell_1 }, + op: OperationType::RollSell { + roll_count: roll_sell_1, + }, }, OperationSerializer::new(), &keypair, @@ -520,15 +517,22 @@ pub fn roll_sell() { Operation { fee: Amount::zero(), expire_period: 10, - op: OperationType::RollSell { roll_count: roll_sell_2 }, + op: OperationType::RollSell { + roll_count: roll_sell_2, + }, }, OperationSerializer::new(), &keypair, ) - .unwrap(); + .unwrap(); // create the block containing the roll buy operation storage.store_operations(vec![operation1.clone(), operation2.clone()]); - let block = create_block(KeyPair::generate(), vec![operation1, operation2], Slot::new(1, 0)).unwrap(); + let block = create_block( + KeyPair::generate(), + vec![operation1, operation2], + Slot::new(1, 0), + ) + .unwrap(); // store the block in storage storage.store_block(block.clone()); // set the block as final so the sell and credits are processed @@ -547,12 +551,15 @@ pub fn roll_sell() { let mut credits = PreHashMap::default(); let roll_remaining = roll_count_initial - roll_sell_1 - roll_sell_2; let roll_sold = roll_sell_1 + roll_sell_2; - credits.insert(address, exec_cfg.roll_price - .checked_mul_u64(roll_sold) - .unwrap() + credits.insert( + address, + exec_cfg.roll_price.checked_mul_u64(roll_sold).unwrap(), ); - assert_eq!(sample_read.pos_state.get_rolls_for(&address), roll_remaining); + assert_eq!( + sample_read.pos_state.get_rolls_for(&address), + roll_remaining + ); assert_eq!( sample_read .pos_state @@ -570,15 +577,18 @@ pub fn roll_sell() { ); // Now check balance - let balances = controller - .get_final_and_candidate_balance(&[address]); + let balances = controller.get_final_and_candidate_balance(&[address]); let candidate_balance = balances.get(0).unwrap().1.unwrap(); - assert_eq!(candidate_balance, exec_cfg.roll_price - .checked_mul_u64(roll_sell_1 + roll_sell_2) - .unwrap() - .checked_add(balance_initial) - .unwrap()); + assert_eq!( + candidate_balance, + exec_cfg + .roll_price + .checked_mul_u64(roll_sell_1 + roll_sell_2) + .unwrap() + .checked_add(balance_initial) + .unwrap() + ); // stop the execution controller manager.stop(); diff --git a/massa-execution-worker/src/tests/tests_active_history.rs b/massa-execution-worker/src/tests/tests_active_history.rs index bfe263421d8..8f0e4e37c12 100644 --- a/massa-execution-worker/src/tests/tests_active_history.rs +++ b/massa-execution-worker/src/tests/tests_active_history.rs @@ -1,20 +1,19 @@ -use std::collections::{BTreeMap, VecDeque}; -use massa_execution_exports::ExecutionOutput; use crate::active_history::ActiveHistory; +use massa_execution_exports::ExecutionOutput; use massa_models::slot::Slot; +use std::collections::{BTreeMap, VecDeque}; -use serial_test::serial; use massa_final_state::StateChanges; use massa_hash::Hash; use massa_models::address::Address; use massa_models::amount::Amount; use massa_models::prehash::{CapacityAllocator, PreHashMap}; use massa_pos_exports::{DeferredCredits, PoSChanges}; +use serial_test::serial; #[test] #[serial] fn test_active_history_deferred_credits() { - let slot1 = Slot::new(2, 2); let slot2 = Slot::new(4, 11); @@ -33,12 +32,9 @@ fn test_active_history_deferred_credits() { ph2.insert(addr1, amount_a1_s2); ph2.insert(addr2, amount_a2_s2); - let credits = DeferredCredits { 0: BTreeMap::from( - [ - (slot1, ph1), - (slot2, ph2) - ] - )}; + let credits = DeferredCredits { + 0: BTreeMap::from([(slot1, ph1), (slot2, ph2)]), + }; let exec_output_1 = ExecutionOutput { slot: Slot::new(1, 0), @@ -50,16 +46,21 @@ fn test_active_history_deferred_credits() { seed_bits: Default::default(), roll_changes: Default::default(), production_stats: Default::default(), - deferred_credits: credits + deferred_credits: credits, }, - executed_ops_changes: Default::default() + executed_ops_changes: Default::default(), }, - events: Default::default() + events: Default::default(), }; - let active_history = ActiveHistory { 0: VecDeque::from([exec_output_1]) }; + let active_history = ActiveHistory { + 0: VecDeque::from([exec_output_1]), + }; - assert_eq!(active_history.get_adress_deferred_credit_for(&addr1, &slot2), Some(amount_a1_s2)); + assert_eq!( + active_history.get_adress_deferred_credit_for(&addr1, &slot2), + Some(amount_a1_s2) + ); let deferred_credit_for_slot1 = active_history.get_all_deferred_credits_for(&slot1); assert_eq!(deferred_credit_for_slot1.get(&addr1), Some(&amount_a1_s1)); diff --git a/massa-pos-exports/src/deferred_credits.rs b/massa-pos-exports/src/deferred_credits.rs index ebdf1fc500c..8acd7405caf 100644 --- a/massa-pos-exports/src/deferred_credits.rs +++ b/massa-pos-exports/src/deferred_credits.rs @@ -55,12 +55,16 @@ impl DeferredCredits { } /// Gets the deferred credits for a given address that will be credited at a given slot - pub fn get_address_deferred_credit_for_slot(&self, addr: &Address, slot: &Slot) -> Option { - if let Some(v) = self.0 + pub fn get_address_deferred_credit_for_slot( + &self, + addr: &Address, + slot: &Slot, + ) -> Option { + if let Some(v) = self + .0 .get(slot) - .and_then(|slot_credits| - slot_credits.get(addr) - ) { + .and_then(|slot_credits| slot_credits.get(addr)) + { return Some(*v); } None @@ -68,12 +72,9 @@ impl DeferredCredits { /// Insert/overwrite a deferred credit pub fn insert(&mut self, addr: Address, slot: Slot, amount: Amount) { - let entry = self.0 - .entry(slot) - .or_default(); + let entry = self.0.entry(slot).or_default(); entry.insert(addr, amount); } - } /// Serializer for `DeferredCredits` diff --git a/massa-sdk/Cargo.toml b/massa-sdk/Cargo.toml index 3f2ba020107..3179576ab14 100644 --- a/massa-sdk/Cargo.toml +++ b/massa-sdk/Cargo.toml @@ -4,5 +4,5 @@ version = "0.1.0" edition = "2021" [dependencies] -jsonrpsee = { git = "https://github.com/paritytech/jsonrpsee", branch = "master", features = ["client"] } +jsonrpsee = { version = "0.16.0", features = ["client"] } massa_models = { path = "../massa-models" } diff --git a/massa-sdk/src/lib.rs b/massa-sdk/src/lib.rs index e5cc21a6933..d64521a0aea 100644 --- a/massa-sdk/src/lib.rs +++ b/massa-sdk/src/lib.rs @@ -57,7 +57,7 @@ impl RpcClient { pub async fn from_url(url: &str) -> RpcClient { match HttpClientBuilder::default().build(url) { Ok(http_client) => RpcClient { - http_client: http_client, + http_client, }, Err(_) => panic!("unable to connect to Node."), }