From 72d45f57e07a6d64b0eba88106676951ab02513c Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Sat, 2 Nov 2024 14:34:13 -0700 Subject: [PATCH] Fix clippy in stacks node Signed-off-by: Jacinta Ferrant --- stackslib/src/chainstate/stacks/tests/mod.rs | 4 +- .../burnchains/bitcoin_regtest_controller.rs | 187 ++- .../src/burnchains/mocknet_controller.rs | 6 +- testnet/stacks-node/src/chain_data.rs | 53 +- testnet/stacks-node/src/config.rs | 144 +- testnet/stacks-node/src/event_dispatcher.rs | 72 +- testnet/stacks-node/src/globals.rs | 11 +- testnet/stacks-node/src/keychain.rs | 24 +- testnet/stacks-node/src/main.rs | 19 +- testnet/stacks-node/src/nakamoto_node.rs | 8 +- .../stacks-node/src/nakamoto_node/miner.rs | 59 +- testnet/stacks-node/src/nakamoto_node/peer.rs | 6 +- .../stacks-node/src/nakamoto_node/relayer.rs | 51 +- .../src/nakamoto_node/sign_coordinator.rs | 16 +- testnet/stacks-node/src/neon_node.rs | 467 ++++--- testnet/stacks-node/src/node.rs | 68 +- testnet/stacks-node/src/operations.rs | 3 +- .../stacks-node/src/run_loop/boot_nakamoto.rs | 6 +- testnet/stacks-node/src/run_loop/helium.rs | 24 +- testnet/stacks-node/src/run_loop/mod.rs | 11 +- testnet/stacks-node/src/run_loop/nakamoto.rs | 17 +- testnet/stacks-node/src/run_loop/neon.rs | 44 +- testnet/stacks-node/src/stacks_events.rs | 2 +- testnet/stacks-node/src/syncctl.rs | 20 +- testnet/stacks-node/src/tenure.rs | 9 +- .../stacks-node/src/tests/bitcoin_regtest.rs | 36 +- testnet/stacks-node/src/tests/epoch_205.rs | 68 +- testnet/stacks-node/src/tests/epoch_21.rs | 686 ++++------ testnet/stacks-node/src/tests/epoch_22.rs | 275 ++-- testnet/stacks-node/src/tests/epoch_23.rs | 46 +- testnet/stacks-node/src/tests/epoch_24.rs | 206 ++- testnet/stacks-node/src/tests/epoch_25.rs | 8 +- testnet/stacks-node/src/tests/integrations.rs | 397 +++--- testnet/stacks-node/src/tests/mempool.rs | 179 +-- testnet/stacks-node/src/tests/mod.rs | 203 +-- .../src/tests/nakamoto_integrations.rs | 648 ++++----- .../src/tests/neon_integrations.rs | 1195 +++++++---------- testnet/stacks-node/src/tests/signer/mod.rs | 32 +- testnet/stacks-node/src/tests/signer/v0.rs | 271 ++-- testnet/stacks-node/src/tests/stackerdb.rs | 40 +- 40 files changed, 2392 insertions(+), 3229 deletions(-) diff --git a/stackslib/src/chainstate/stacks/tests/mod.rs b/stackslib/src/chainstate/stacks/tests/mod.rs index 8b66c019f0..6e6fdfd8f7 100644 --- a/stackslib/src/chainstate/stacks/tests/mod.rs +++ b/stackslib/src/chainstate/stacks/tests/mod.rs @@ -475,14 +475,14 @@ impl TestStacksNode { }; if StacksChainState::has_stored_block( - &self.chainstate.db(), + self.chainstate.db(), &self.chainstate.blocks_path, &consensus_hash, &bc.block_header_hash, ) .unwrap() && !StacksChainState::is_block_orphaned( - &self.chainstate.db(), + self.chainstate.db(), &consensus_hash, &bc.block_header_hash, ) diff --git a/testnet/stacks-node/src/burnchains/bitcoin_regtest_controller.rs b/testnet/stacks-node/src/burnchains/bitcoin_regtest_controller.rs index 82282926d3..06cc4799ff 100644 --- a/testnet/stacks-node/src/burnchains/bitcoin_regtest_controller.rs +++ b/testnet/stacks-node/src/burnchains/bitcoin_regtest_controller.rs @@ -186,12 +186,11 @@ pub fn make_bitcoin_indexer( let (_, network_type) = config.burnchain.get_bitcoin_network(); let indexer_runtime = BitcoinIndexerRuntime::new(network_type); - let burnchain_indexer = BitcoinIndexer { + BitcoinIndexer { config: indexer_config, runtime: indexer_runtime, - should_keep_running: should_keep_running, - }; - burnchain_indexer + should_keep_running, + } } pub fn get_satoshis_per_byte(config: &Config) -> u64 { @@ -215,7 +214,7 @@ impl LeaderBlockCommitFees { let mut fees = LeaderBlockCommitFees::estimated_fees_from_payload(payload, config); fees.spent_in_attempts = cmp::max(1, self.spent_in_attempts); fees.final_size = self.final_size; - fees.fee_rate = self.fee_rate + get_rbf_fee_increment(&config); + fees.fee_rate = self.fee_rate + get_rbf_fee_increment(config); fees.is_rbf_enabled = true; fees } @@ -306,8 +305,7 @@ impl BitcoinRegtestController { burnchain: Option, should_keep_running: Option>, ) -> Self { - std::fs::create_dir_all(&config.get_burnchain_path_str()) - .expect("Unable to create workdir"); + std::fs::create_dir_all(config.get_burnchain_path_str()).expect("Unable to create workdir"); let (_, network_id) = config.burnchain.get_bitcoin_network(); let res = SpvClient::new( @@ -434,11 +432,10 @@ impl BitcoinRegtestController { /// Get the default Burnchain instance from our config fn default_burnchain(&self) -> Burnchain { - let burnchain = match &self.burnchain_config { + match &self.burnchain_config { Some(burnchain) => burnchain.clone(), None => self.config.get_burnchain(), - }; - burnchain + } } /// Get the PoX constants in use @@ -491,7 +488,7 @@ impl BitcoinRegtestController { (None, Some(chain_tip)) => chain_tip.clone(), (Some(state_transition), _) => { let burnchain_tip = BurnchainTip { - block_snapshot: block_snapshot, + block_snapshot, state_transition: BurnchainStateTransitionOps::from(state_transition), received_at: Instant::now(), }; @@ -501,7 +498,7 @@ impl BitcoinRegtestController { (None, None) => { // can happen at genesis let burnchain_tip = BurnchainTip { - block_snapshot: block_snapshot, + block_snapshot, state_transition: BurnchainStateTransitionOps::noop(), received_at: Instant::now(), }; @@ -602,8 +599,8 @@ impl BitcoinRegtestController { }; let burnchain_tip = BurnchainTip { - block_snapshot: block_snapshot, - state_transition: state_transition, + block_snapshot, + state_transition, received_at: Instant::now(), }; @@ -641,11 +638,11 @@ impl BitcoinRegtestController { let filter_addresses = vec![addr2str(&address)]; let pubk = if self.config.miner.segwit { - let mut p = public_key.clone(); + let mut p = *public_key; p.set_compressed(true); p } else { - public_key.clone() + *public_key }; test_debug!("Import public key '{}'", &pubk.to_hex()); @@ -753,11 +750,11 @@ impl BitcoinRegtestController { } let pubk = if self.config.miner.segwit && epoch_id >= StacksEpochId::Epoch21 { - let mut p = public_key.clone(); + let mut p = *public_key; p.set_compressed(true); p } else { - public_key.clone() + *public_key }; // Configure UTXO filter @@ -1013,7 +1010,7 @@ impl BitcoinRegtestController { let mut bytes = self.config.burnchain.magic_bytes.as_bytes().to_vec(); payload .consensus_serialize(&mut bytes) - .map_err(|e| BurnchainControllerError::SerializerError(e))?; + .map_err(BurnchainControllerError::SerializerError)?; bytes }; @@ -1026,10 +1023,8 @@ impl BitcoinRegtestController { }; tx.output = vec![consensus_output]; - tx.output.push( - PoxAddress::Standard(payload.recipient.clone(), None) - .to_bitcoin_tx_out(DUST_UTXO_LIMIT), - ); + tx.output + .push(PoxAddress::Standard(payload.recipient, None).to_bitcoin_tx_out(DUST_UTXO_LIMIT)); self.finalize_tx( epoch_id, @@ -1099,7 +1094,7 @@ impl BitcoinRegtestController { let mut bytes = self.config.burnchain.magic_bytes.as_bytes().to_vec(); payload .consensus_serialize(&mut bytes) - .map_err(|e| BurnchainControllerError::SerializerError(e))?; + .map_err(BurnchainControllerError::SerializerError)?; bytes }; @@ -1113,8 +1108,7 @@ impl BitcoinRegtestController { tx.output = vec![consensus_output]; tx.output.push( - PoxAddress::Standard(payload.delegate_to.clone(), None) - .to_bitcoin_tx_out(DUST_UTXO_LIMIT), + PoxAddress::Standard(payload.delegate_to, None).to_bitcoin_tx_out(DUST_UTXO_LIMIT), ); self.finalize_tx( @@ -1180,7 +1174,7 @@ impl BitcoinRegtestController { let mut bytes = self.config.burnchain.magic_bytes.as_bytes().to_vec(); payload .consensus_serialize(&mut bytes) - .map_err(|e| BurnchainControllerError::SerializerError(e))?; + .map_err(BurnchainControllerError::SerializerError)?; bytes }; @@ -1271,7 +1265,7 @@ impl BitcoinRegtestController { tx.output = vec![consensus_output]; tx.output - .push(PoxAddress::Standard(payload.output.clone(), None).to_bitcoin_tx_out(output_amt)); + .push(PoxAddress::Standard(payload.output, None).to_bitcoin_tx_out(output_amt)); self.finalize_tx( epoch_id, @@ -1347,7 +1341,7 @@ impl BitcoinRegtestController { let mut bytes = self.config.burnchain.magic_bytes.as_bytes().to_vec(); payload .consensus_serialize(&mut bytes) - .map_err(|e| BurnchainControllerError::SerializerError(e))?; + .map_err(BurnchainControllerError::SerializerError)?; bytes }; @@ -1388,10 +1382,9 @@ impl BitcoinRegtestController { fn magic_bytes(&self) -> Vec { #[cfg(test)] { - if let Some(set_bytes) = TEST_MAGIC_BYTES + if let Some(set_bytes) = *TEST_MAGIC_BYTES .lock() .expect("FATAL: test magic bytes mutex poisoned") - .clone() { return set_bytes.to_vec(); } @@ -1399,6 +1392,7 @@ impl BitcoinRegtestController { self.config.burnchain.magic_bytes.as_bytes().to_vec() } + #[allow(clippy::too_many_arguments)] fn send_block_commit_operation( &mut self, epoch_id: StacksEpochId, @@ -1407,7 +1401,7 @@ impl BitcoinRegtestController { utxos_to_include: Option, utxos_to_exclude: Option, previous_fees: Option, - previous_txids: &Vec, + previous_txids: &[Txid], ) -> Result { let _ = self.sortdb_mut(); let burn_chain_tip = self @@ -1433,6 +1427,7 @@ impl BitcoinRegtestController { ) } + #[allow(clippy::too_many_arguments)] fn send_block_commit_operation_at_burnchain_height( &mut self, epoch_id: StacksEpochId, @@ -1441,7 +1436,7 @@ impl BitcoinRegtestController { utxos_to_include: Option, utxos_to_exclude: Option, mut estimated_fees: LeaderBlockCommitFees, - previous_txids: &Vec, + previous_txids: &[Txid], burnchain_block_height: u64, ) -> Result { let public_key = signer.get_public_key(); @@ -1502,8 +1497,8 @@ impl BitcoinRegtestController { debug!("Transaction relying on UTXOs: {:?}", utxos); let txid = Txid::from_bytes(&txid[..]).unwrap(); - let mut txids = previous_txids.clone(); - txids.push(txid.clone()); + let mut txids = previous_txids.to_vec(); + txids.push(txid); let ongoing_block_commit = OngoingBlockCommit { payload, utxos, @@ -1537,15 +1532,8 @@ impl BitcoinRegtestController { // Are we currently tracking an operation? if self.ongoing_block_commit.is_none() || !self.allow_rbf { // Good to go, let's build the transaction and send it. - let res = self.send_block_commit_operation( - epoch_id, - payload, - signer, - None, - None, - None, - &vec![], - ); + let res = + self.send_block_commit_operation(epoch_id, payload, signer, None, None, None, &[]); return res; } @@ -1574,7 +1562,7 @@ impl BitcoinRegtestController { None, None, None, - &vec![], + &[], ); return res; } else { @@ -1589,13 +1577,13 @@ impl BitcoinRegtestController { .map_err(|_| BurnchainControllerError::BurnchainError)?; let mut found_last_mined_at = false; while traversal_depth < UTXO_CACHE_STALENESS_LIMIT { - if &burn_chain_tip.block_hash == &ongoing_op.utxos.bhh { + if burn_chain_tip.block_hash == ongoing_op.utxos.bhh { found_last_mined_at = true; break; } let parent = BurnchainDB::get_burnchain_block( - &burnchain_db.conn(), + burnchain_db.conn(), &burn_chain_tip.parent_block_hash, ) .map_err(|_| BurnchainControllerError::BurnchainError)?; @@ -1609,15 +1597,8 @@ impl BitcoinRegtestController { "Possible presence of fork or stale UTXO cache, invalidating cached set of UTXOs."; "cached_burn_block_hash" => %ongoing_op.utxos.bhh, ); - let res = self.send_block_commit_operation( - epoch_id, - payload, - signer, - None, - None, - None, - &vec![], - ); + let res = + self.send_block_commit_operation(epoch_id, payload, signer, None, None, None, &[]); return res; } @@ -1659,7 +1640,7 @@ impl BitcoinRegtestController { None, Some(ongoing_op.utxos.clone()), None, - &vec![], + &[], ) } else { // Case 2) ii): Attempt to RBF @@ -1724,9 +1705,9 @@ impl BitcoinRegtestController { } else { // Fetch some UTXOs let addr = self.get_miner_address(epoch_id, public_key); - let utxos = match self.get_utxos( + match self.get_utxos( epoch_id, - &public_key, + public_key, total_required, utxos_to_exclude, block_height, @@ -1741,8 +1722,7 @@ impl BitcoinRegtestController { ); return Err(BurnchainControllerError::NoUTXOs); } - }; - utxos + } }; // Prepare a backbone for the tx @@ -1756,6 +1736,7 @@ impl BitcoinRegtestController { Ok((transaction, utxos)) } + #[allow(clippy::too_many_arguments)] fn finalize_tx( &mut self, epoch_id: StacksEpochId, @@ -1884,7 +1865,7 @@ impl BitcoinRegtestController { debug!("Not enough change to clear dust limit. Not adding change address."); } - for (_i, utxo) in utxos_set.utxos.iter().enumerate() { + for utxo in utxos_set.utxos.iter() { let input = TxIn { previous_output: OutPoint { txid: utxo.txid, @@ -2118,7 +2099,7 @@ impl BitcoinRegtestController { } }; - transaction.map(|tx| SerializedTx::new(tx)) + transaction.map(SerializedTx::new) } #[cfg(test)] @@ -2139,7 +2120,7 @@ impl BitcoinRegtestController { for pk in pks { debug!("Import public key '{}'", &pk.to_hex()); - if let Err(e) = BitcoinRPCRequest::import_public_key(&self.config, &pk) { + if let Err(e) = BitcoinRPCRequest::import_public_key(&self.config, pk) { warn!("Error when importing pubkey: {e:?}"); } } @@ -2165,7 +2146,7 @@ impl BitcoinRegtestController { // otherwise, round robin generate blocks for i in 0..num_blocks { - let pk = &pks[usize::try_from(i % pks.len()).unwrap()]; + let pk = &pks[i % pks.len()]; let address = self.get_miner_address(StacksEpochId::Epoch21, pk); if i < pks.len() { debug!( @@ -2249,10 +2230,7 @@ impl BurnchainController for BitcoinRegtestController { target_block_height_opt: Option, ) -> Result<(BurnchainTip, u64), BurnchainControllerError> { // if no target block height is given, just fetch the first burnchain block. - self.receive_blocks( - false, - target_block_height_opt.map_or_else(|| Some(1), |x| Some(x)), - ) + self.receive_blocks(false, target_block_height_opt.map_or_else(|| Some(1), Some)) } fn sync( @@ -2351,13 +2329,13 @@ impl SerializedTx { } pub fn txid(&self) -> Txid { - self.txid.clone() + self.txid } pub fn to_hex(&self) -> String { let formatted_bytes: Vec = self.bytes.iter().map(|b| format!("{:02x}", b)).collect(); - format!("{}", formatted_bytes.join("")) + formatted_bytes.join("").to_string() } } @@ -2419,7 +2397,7 @@ impl ParsedUTXO { } (lhs, rhs) => { warn!("Error while converting BTC to sat {:?} - {:?}", lhs, rhs); - return None; + None } } } @@ -2516,13 +2494,12 @@ impl BitcoinRPCRequest { .unwrap_or_else(|_| panic!("FATAL: failed to encode infallible data as HTTP request")); request.add_header("Connection".into(), "close".into()); - match (&config.burnchain.username, &config.burnchain.password) { - (Some(username), Some(password)) => { - let auth_token = format!("Basic {}", encode(format!("{}:{}", username, password))); - request.add_header("Authorization".into(), auth_token); - } - (_, _) => {} - }; + if let (Some(username), Some(password)) = + (&config.burnchain.username, &config.burnchain.password) + { + let auth_token = format!("Basic {}", encode(format!("{}:{}", username, password))); + request.add_header("Authorization".into(), auth_token); + } request } @@ -2535,7 +2512,7 @@ impl BitcoinRPCRequest { id: "stacks".to_string(), jsonrpc: "2.0".to_string(), }; - let res = BitcoinRPCRequest::send(&config, payload)?; + let res = BitcoinRPCRequest::send(config, payload)?; debug!("Got raw transaction {}: {:?}", txid, &res); Ok(res.get("result").unwrap().as_str().unwrap().to_string()) } @@ -2548,7 +2525,7 @@ impl BitcoinRPCRequest { id: "stacks".to_string(), jsonrpc: "2.0".to_string(), }; - let res = BitcoinRPCRequest::send(&config, payload)?; + let res = BitcoinRPCRequest::send(config, payload)?; let confirmations = res .get("result") .ok_or_else(|| RPCError::Parsing("No 'result' field in bitcoind RPC response".into()))? @@ -2575,7 +2552,7 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let res = BitcoinRPCRequest::send(&config, payload)?; + let res = BitcoinRPCRequest::send(config, payload)?; debug!( "Generated {} blocks to {}: {:?}", num_blocks, &address, &res @@ -2598,21 +2575,17 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let mut res = BitcoinRPCRequest::send(&config, payload)?; - let bhh = match res.as_object_mut() { - Some(res) => { - let res = res - .get("result") - .ok_or(RPCError::Parsing("Failed to get bestblockhash".to_string()))?; - let bhh: String = serde_json::from_value(res.to_owned()) - .map_err(|_| RPCError::Parsing("Failed to get bestblockhash".to_string()))?; - let bhh = BurnchainHeaderHash::from_hex(&bhh) - .map_err(|_| RPCError::Parsing("Failed to get bestblockhash".to_string()))?; - bhh - } - _ => return Err(RPCError::Parsing("Failed to get UTXOs".to_string())), + let mut res = BitcoinRPCRequest::send(config, payload)?; + let Some(res) = res.as_object_mut() else { + return Err(RPCError::Parsing("Failed to get UTXOs".to_string())); }; - + let res = res + .get("result") + .ok_or(RPCError::Parsing("Failed to get bestblockhash".to_string()))?; + let bhh_string: String = serde_json::from_value(res.to_owned()) + .map_err(|_| RPCError::Parsing("Failed to get bestblockhash".to_string()))?; + let bhh = BurnchainHeaderHash::from_hex(&bhh_string) + .map_err(|_| RPCError::Parsing("Failed to get bestblockhash".to_string()))?; let min_conf = 0i64; let max_conf = 9999999i64; let minimum_amount = ParsedUTXO::sat_to_serialized_btc(minimum_sum_amount); @@ -2630,7 +2603,7 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let mut res = BitcoinRPCRequest::send(&config, payload)?; + let mut res = BitcoinRPCRequest::send(config, payload)?; let txids_to_filter = if let Some(utxos_to_exclude) = utxos_to_exclude { utxos_to_exclude .utxos @@ -2710,7 +2683,7 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let json_resp = BitcoinRPCRequest::send(&config, payload)?; + let json_resp = BitcoinRPCRequest::send(config, payload)?; if let Some(e) = json_resp.get("error") { if !e.is_null() { @@ -2756,9 +2729,9 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let result = BitcoinRPCRequest::send(&config, payload)?; + let result = BitcoinRPCRequest::send(config, payload)?; let checksum = result - .get(&"result".to_string()) + .get("result") .and_then(|res| res.as_object()) .and_then(|obj| obj.get("checksum")) .and_then(|checksum_val| checksum_val.as_str()) @@ -2776,7 +2749,7 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - BitcoinRPCRequest::send(&config, payload)?; + BitcoinRPCRequest::send(config, payload)?; } Ok(()) } @@ -2790,7 +2763,7 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - let mut res = BitcoinRPCRequest::send(&config, payload)?; + let mut res = BitcoinRPCRequest::send(config, payload)?; let mut wallets = Vec::new(); match res.as_object_mut() { Some(ref mut object) => match object.get_mut("result") { @@ -2828,12 +2801,12 @@ impl BitcoinRPCRequest { jsonrpc: "2.0".to_string(), }; - BitcoinRPCRequest::send(&config, payload)?; + BitcoinRPCRequest::send(config, payload)?; Ok(()) } pub fn send(config: &Config, payload: BitcoinRPCRequest) -> RPCResult { - let request = BitcoinRPCRequest::build_rpc_request(&config, &payload); + let request = BitcoinRPCRequest::build_rpc_request(config, &payload); let timeout = Duration::from_secs(u64::from(config.burnchain.timeout)); let host = request.preamble().host.hostname(); @@ -2841,9 +2814,9 @@ impl BitcoinRPCRequest { let response = send_http_request(&host, port, request, timeout)?; if let HttpResponsePayload::JSON(js) = response.destruct().1 { - return Ok(js); + Ok(js) } else { - return Err(RPCError::Parsing("Did not get a JSON response".into())); + Err(RPCError::Parsing("Did not get a JSON response".into())) } } } @@ -3025,7 +2998,7 @@ mod tests { Some(utxo_set), None, leader_fees, - &vec![], + &[], 2212, ) .unwrap(); diff --git a/testnet/stacks-node/src/burnchains/mocknet_controller.rs b/testnet/stacks-node/src/burnchains/mocknet_controller.rs index d518f5bdea..a626cfb443 100644 --- a/testnet/stacks-node/src/burnchains/mocknet_controller.rs +++ b/testnet/stacks-node/src/burnchains/mocknet_controller.rs @@ -44,8 +44,8 @@ impl MocknetController { let burnchain = config.get_burnchain(); Self { - config: config, - burnchain: burnchain, + config, + burnchain, db: None, queued_operations: VecDeque::new(), chain_tip: None, @@ -54,7 +54,7 @@ impl MocknetController { fn build_next_block_header(current_block: &BlockSnapshot) -> BurnchainBlockHeader { let curr_hash = ¤t_block.burn_header_hash.to_bytes()[..]; - let next_hash = Sha256Sum::from_data(&curr_hash); + let next_hash = Sha256Sum::from_data(curr_hash); let block = BurnchainBlock::Bitcoin(BitcoinBlock::new( current_block.block_height + 1, diff --git a/testnet/stacks-node/src/chain_data.rs b/testnet/stacks-node/src/chain_data.rs index b1e32c15ea..c7fdaf6cee 100644 --- a/testnet/stacks-node/src/chain_data.rs +++ b/testnet/stacks-node/src/chain_data.rs @@ -81,7 +81,7 @@ impl MinerStats { { commits_at_sortition.push(missed); } else { - missed_commits_map.insert(missed.intended_sortition.clone(), vec![missed]); + missed_commits_map.insert(missed.intended_sortition, vec![missed]); } } @@ -106,8 +106,7 @@ impl MinerStats { &sortition_id, )?; if let Some(missed_commit_in_block) = missed_commits_map.remove(&sortition_id) { - missed_commits_at_height - .extend(missed_commit_in_block.into_iter().map(|x| x.clone())); + missed_commits_at_height.extend(missed_commit_in_block.into_iter().cloned()); } windowed_missed_commits.push(missed_commits_at_height); @@ -223,7 +222,7 @@ impl MinerStats { all_miners: &[&str], ) -> Result, String> { let (exit_code, stdout, _stderr) = - Self::run_subprocess(&self.unconfirmed_commits_helper, &all_miners)?; + Self::run_subprocess(&self.unconfirmed_commits_helper, all_miners)?; if exit_code != 0 { return Err(format!( "Failed to run `{}`: exit code {}", @@ -255,7 +254,7 @@ impl MinerStats { }; let mut decoded_pox_addrs = vec![]; for pox_addr_hex in unconfirmed_commit.pox_addrs.iter() { - let Ok(pox_addr_bytes) = hex_bytes(&pox_addr_hex) else { + let Ok(pox_addr_bytes) = hex_bytes(pox_addr_hex) else { return Err(format!("Not a hex string: `{}`", &pox_addr_hex)); }; let Some(bitcoin_addr) = @@ -279,8 +278,8 @@ impl MinerStats { let mocked_commit = LeaderBlockCommitOp { treatment: vec![], sunset_burn: 0, - block_header_hash: BlockHeaderHash(DEADBEEF.clone()), - new_seed: VRFSeed(DEADBEEF.clone()), + block_header_hash: BlockHeaderHash(DEADBEEF), + new_seed: VRFSeed(DEADBEEF), parent_block_ptr: 1, parent_vtxindex: 1, key_block_ptr: 1, @@ -295,7 +294,7 @@ impl MinerStats { block_height: next_block_height, burn_parent_modulus: ((next_block_height.saturating_sub(1)) % BURN_BLOCK_MINED_AT_MODULUS) as u8, - burn_header_hash: BurnchainHeaderHash(DEADBEEF.clone()), + burn_header_hash: BurnchainHeaderHash(DEADBEEF), }; unconfirmed_spends.push(mocked_commit); @@ -306,7 +305,7 @@ impl MinerStats { /// Convert a list of burn sample points into a probability distribution by candidate's /// apparent sender (e.g. miner address). pub fn burn_dist_to_prob_dist(burn_dist: &[BurnSamplePoint]) -> HashMap { - if burn_dist.len() == 0 { + if burn_dist.is_empty() { return HashMap::new(); } if burn_dist.len() == 1 { @@ -343,13 +342,11 @@ impl MinerStats { if commit.commit_outs.len() != expected_pox_addrs.len() { return false; } - for i in 0..commit.commit_outs.len() { - if commit.commit_outs[i].to_burnchain_repr() - != expected_pox_addrs[i].to_burnchain_repr() - { + for (i, commit_out) in commit.commit_outs.iter().enumerate() { + if commit_out.to_burnchain_repr() != expected_pox_addrs[i].to_burnchain_repr() { info!( "Skipping invalid unconfirmed block-commit: {:?} != {:?}", - &commit.commit_outs[i].to_burnchain_repr(), + &commit_out.to_burnchain_repr(), expected_pox_addrs[i].to_burnchain_repr() ); return false; @@ -391,7 +388,7 @@ impl MinerStats { let (dist, total_spend) = Self::get_spend_distribution( active_miners_and_commits, unconfirmed_block_commits, - &expected_pox_addrs, + expected_pox_addrs, ); let mut probs = HashMap::new(); @@ -444,8 +441,8 @@ impl MinerStats { let mocked_commit = LeaderBlockCommitOp { treatment: vec![], sunset_burn: 0, - block_header_hash: BlockHeaderHash(DEADBEEF.clone()), - new_seed: VRFSeed(DEADBEEF.clone()), + block_header_hash: BlockHeaderHash(DEADBEEF), + new_seed: VRFSeed(DEADBEEF), parent_block_ptr: 2, parent_vtxindex: 2, key_block_ptr: 2, @@ -455,13 +452,13 @@ impl MinerStats { burn_fee: last_commit.burn_fee, input: (last_commit.txid, expected_input_index), apparent_sender: last_commit.apparent_sender.clone(), - txid: Txid(DEADBEEF.clone()), + txid: Txid(DEADBEEF), vtxindex: 1, block_height: next_block_height, burn_parent_modulus: ((next_block_height.saturating_sub(1)) % BURN_BLOCK_MINED_AT_MODULUS) as u8, - burn_header_hash: BurnchainHeaderHash(DEADBEEF.clone()), + burn_header_hash: BurnchainHeaderHash(DEADBEEF), }; commit_table.insert(miner.to_string(), mocked_commit); } @@ -473,13 +470,11 @@ impl MinerStats { if commit.commit_outs.len() != expected_pox_addrs.len() { return false; } - for i in 0..commit.commit_outs.len() { - if commit.commit_outs[i].to_burnchain_repr() - != expected_pox_addrs[i].to_burnchain_repr() - { + for (i, commit_out) in commit.commit_outs.iter().enumerate() { + if commit_out.to_burnchain_repr() != expected_pox_addrs[i].to_burnchain_repr() { info!( "Skipping invalid unconfirmed block-commit: {:?} != {:?}", - &commit.commit_outs[i].to_burnchain_repr(), + &commit_out.to_burnchain_repr(), expected_pox_addrs[i].to_burnchain_repr() ); return false; @@ -520,9 +515,7 @@ impl MinerStats { SortitionDB::get_block_commits_by_block(sortdb.conn(), &tip.sortition_id)?; for commit in commits.into_iter() { let miner = commit.apparent_sender.to_string(); - if miners.get(&miner).is_none() { - miners.insert(miner, commit); - } + miners.entry(miner).or_insert(commit); } tip = SortitionDB::get_block_snapshot(sortdb.conn(), &tip.parent_sortition_id)? .ok_or(DBError::NotFoundError)?; @@ -750,11 +743,11 @@ echo < Result { let mut config: ConfigFile = toml::from_str(content).map_err(|e| format!("Invalid toml: {}", e))?; @@ -367,7 +368,7 @@ impl Config { let Ok(config) = Config::from_config_file(config_file, false) else { return self.miner.clone(); }; - return config.miner; + config.miner } pub fn get_node_config(&self, resolve_bootstrap_nodes: bool) -> NodeConfig { @@ -380,7 +381,7 @@ impl Config { let Ok(config) = Config::from_config_file(config_file, resolve_bootstrap_nodes) else { return self.node.clone(); }; - return config.node; + config.node } /// Apply any test settings to this burnchain config struct @@ -411,7 +412,7 @@ impl Config { "Override first_burn_block_hash from {} to {}", burnchain.first_block_hash, first_burn_block_hash ); - burnchain.first_block_hash = BurnchainHeaderHash::from_hex(&first_burn_block_hash) + burnchain.first_block_hash = BurnchainHeaderHash::from_hex(first_burn_block_hash) .expect("Invalid first_burn_block_hash"); } @@ -525,7 +526,7 @@ impl Config { } // check if the Epoch 3.0 burnchain settings as configured are going to be valid. - self.check_nakamoto_config(&burnchain); + self.check_nakamoto_config(burnchain); } fn check_nakamoto_config(&self, burnchain: &Burnchain) { @@ -612,7 +613,7 @@ impl Config { let _ = StacksEpoch::validate_epochs(epochs); // sanity check: v1_unlock_height must happen after pox-2 instantiation - let epoch21_index = StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch21) + let epoch21_index = StacksEpoch::find_epoch_by_id(epochs, StacksEpochId::Epoch21) .expect("FATAL: no epoch 2.1 defined"); let epoch21 = &epochs[epoch21_index]; @@ -810,7 +811,7 @@ impl Config { } if burnchain.mode == "helium" && burnchain.local_mining_public_key.is_none() { - return Err(format!("Config is missing the setting `burnchain.local_mining_public_key` (mandatory for helium)")); + return Err("Config is missing the setting `burnchain.local_mining_public_key` (mandatory for helium)".into()); } let is_mainnet = burnchain.mode == "mainnet"; @@ -834,27 +835,17 @@ impl Config { burnchain.peer_version, ); } - } else { - if is_mainnet && resolve_bootstrap_nodes { - let bootstrap_node = ConfigFile::mainnet().node.unwrap().bootstrap_node.unwrap(); - node.set_bootstrap_nodes( - bootstrap_node, - burnchain.chain_id, - burnchain.peer_version, - ); - } + } else if is_mainnet && resolve_bootstrap_nodes { + let bootstrap_node = ConfigFile::mainnet().node.unwrap().bootstrap_node.unwrap(); + node.set_bootstrap_nodes(bootstrap_node, burnchain.chain_id, burnchain.peer_version); } if let Some(deny_nodes) = deny_nodes { node.set_deny_nodes(deny_nodes, burnchain.chain_id, burnchain.peer_version); } // Validate the node config - if is_mainnet { - if node.use_test_genesis_chainstate == Some(true) { - return Err(format!( - "Attempted to run mainnet node with `use_test_genesis_chainstate`" - )); - } + if is_mainnet && node.use_test_genesis_chainstate == Some(true) { + return Err("Attempted to run mainnet node with `use_test_genesis_chainstate`".into()); } if node.stacker || node.miner { @@ -869,10 +860,10 @@ impl Config { let initial_balances: Vec = match config_file.ustx_balance { Some(balances) => { - if is_mainnet && balances.len() > 0 { - return Err(format!( - "Attempted to run mainnet node with specified `initial_balances`" - )); + if is_mainnet && !balances.is_empty() { + return Err( + "Attempted to run mainnet node with specified `initial_balances`".into(), + ); } balances .iter() @@ -913,16 +904,12 @@ impl Config { }; // check for observer config in env vars - match std::env::var("STACKS_EVENT_OBSERVER") { - Ok(val) => { - events_observers.insert(EventObserverConfig { - endpoint: val, - events_keys: vec![EventKeyType::AnyEvent], - timeout_ms: 1_000, - }); - () - } - _ => (), + if let Ok(val) = std::env::var("STACKS_EVENT_OBSERVER") { + events_observers.insert(EventObserverConfig { + endpoint: val, + events_keys: vec![EventKeyType::AnyEvent], + timeout_ms: 1_000, + }); }; let connection_options = match config_file.connection_options { @@ -1070,14 +1057,11 @@ impl Config { } pub fn is_mainnet(&self) -> bool { - match self.burnchain.mode.as_str() { - "mainnet" => true, - _ => false, - } + matches!(self.burnchain.mode.as_str(), "mainnet") } pub fn is_node_event_driven(&self) -> bool { - self.events_observers.len() > 0 + !self.events_observers.is_empty() } pub fn make_nakamoto_block_builder_settings( @@ -1157,12 +1141,11 @@ impl Config { /// part dependent on the state machine getting block data back to the miner quickly, and thus /// the poll time is dependent on the first attempt time. pub fn get_poll_time(&self) -> u64 { - let poll_timeout = if self.node.miner { + if self.node.miner { cmp::min(1000, self.miner.first_attempt_time_ms / 2) } else { 1000 - }; - poll_timeout + } } } @@ -1253,7 +1236,7 @@ impl BurnchainConfig { username: None, password: None, timeout: 60, - magic_bytes: BLOCKSTACK_MAGIC_MAINNET.clone(), + magic_bytes: BLOCKSTACK_MAGIC_MAINNET, local_mining_public_key: None, process_exit_at_block_height: None, poll_time_secs: 10, // TODO: this is a testnet specific value. @@ -1298,8 +1281,7 @@ impl BurnchainConfig { let mut addrs_iter = format!("{}:{}", self.peer_host, self.rpc_port) .to_socket_addrs() .unwrap(); - let sock_addr = addrs_iter.next().unwrap(); - sock_addr + addrs_iter.next().unwrap() } pub fn get_bitcoin_network(&self) -> (String, BitcoinNetworkType) { @@ -1320,15 +1302,15 @@ pub struct StacksEpochConfigFile { start_height: i64, } -pub const EPOCH_CONFIG_1_0_0: &'static str = "1.0"; -pub const EPOCH_CONFIG_2_0_0: &'static str = "2.0"; -pub const EPOCH_CONFIG_2_0_5: &'static str = "2.05"; -pub const EPOCH_CONFIG_2_1_0: &'static str = "2.1"; -pub const EPOCH_CONFIG_2_2_0: &'static str = "2.2"; -pub const EPOCH_CONFIG_2_3_0: &'static str = "2.3"; -pub const EPOCH_CONFIG_2_4_0: &'static str = "2.4"; -pub const EPOCH_CONFIG_2_5_0: &'static str = "2.5"; -pub const EPOCH_CONFIG_3_0_0: &'static str = "3.0"; +pub const EPOCH_CONFIG_1_0_0: &str = "1.0"; +pub const EPOCH_CONFIG_2_0_0: &str = "2.0"; +pub const EPOCH_CONFIG_2_0_5: &str = "2.05"; +pub const EPOCH_CONFIG_2_1_0: &str = "2.1"; +pub const EPOCH_CONFIG_2_2_0: &str = "2.2"; +pub const EPOCH_CONFIG_2_3_0: &str = "2.3"; +pub const EPOCH_CONFIG_2_4_0: &str = "2.4"; +pub const EPOCH_CONFIG_2_5_0: &str = "2.5"; +pub const EPOCH_CONFIG_3_0_0: &str = "3.0"; #[derive(Clone, Deserialize, Default, Debug)] pub struct AffirmationOverride { @@ -1978,9 +1960,8 @@ impl NodeConfig { /// Get a SocketAddr for this node's RPC endpoint which uses the loopback address pub fn get_rpc_loopback(&self) -> Option { let rpc_port = SocketAddr::from_str(&self.rpc_bind) - .or_else(|e| { + .map_err(|e| { error!("Could not parse node.rpc_bind configuration setting as SocketAddr: {e}"); - Err(()) }) .ok()? .port(); @@ -2090,8 +2071,8 @@ impl NodeConfig { peer_version: u32, ) { for part in bootstrap_nodes.split(',') { - if part.len() > 0 { - self.add_bootstrap_node(&part, chain_id, peer_version); + if !part.is_empty() { + self.add_bootstrap_node(part, chain_id, peer_version); } } } @@ -2109,8 +2090,8 @@ impl NodeConfig { pub fn set_deny_nodes(&mut self, deny_nodes: String, chain_id: u32, peer_version: u32) { for part in deny_nodes.split(',') { - if part.len() > 0 { - self.add_deny_node(&part, chain_id, peer_version); + if !part.is_empty() { + self.add_deny_node(part, chain_id, peer_version); } } } @@ -2124,10 +2105,7 @@ impl NodeConfig { MARFOpenOpts::new( hash_mode, - &self - .marf_cache_strategy - .as_ref() - .unwrap_or(&"noop".to_string()), + self.marf_cache_strategy.as_deref().unwrap_or("noop"), false, ) } @@ -2288,21 +2266,21 @@ impl ConnectionOptionsFile { let mut read_only_call_limit = HELIUM_DEFAULT_CONNECTION_OPTIONS .read_only_call_limit .clone(); - self.read_only_call_limit_write_length.map(|x| { + if let Some(x) = self.read_only_call_limit_write_length { read_only_call_limit.write_length = x; - }); - self.read_only_call_limit_write_count.map(|x| { + } + if let Some(x) = self.read_only_call_limit_write_count { read_only_call_limit.write_count = x; - }); - self.read_only_call_limit_read_length.map(|x| { + } + if let Some(x) = self.read_only_call_limit_read_length { read_only_call_limit.read_length = x; - }); - self.read_only_call_limit_read_count.map(|x| { + } + if let Some(x) = self.read_only_call_limit_read_count { read_only_call_limit.read_count = x; - }); - self.read_only_call_limit_runtime.map(|x| { + } + if let Some(x) = self.read_only_call_limit_runtime { read_only_call_limit.runtime = x; - }); + }; let default = ConnectionOptions::default(); Ok(ConnectionOptions { read_only_call_limit, @@ -2353,7 +2331,7 @@ impl ConnectionOptionsFile { .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.soft_max_clients_per_host), walk_interval: self .walk_interval - .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.walk_interval.clone()), + .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.walk_interval), walk_seed_probability: self .walk_seed_probability .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.walk_seed_probability), @@ -2375,7 +2353,7 @@ impl ConnectionOptionsFile { .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.maximum_call_argument_size), download_interval: self .download_interval - .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.download_interval.clone()), + .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.download_interval), inv_sync_interval: self .inv_sync_interval .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.inv_sync_interval), @@ -2396,7 +2374,7 @@ impl ConnectionOptionsFile { force_disconnect_interval: self.force_disconnect_interval, max_http_clients: self .max_http_clients - .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.max_http_clients.clone()), + .unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.max_http_clients), connect_timeout: self.connect_timeout.unwrap_or(10), handshake_timeout: self.handshake_timeout.unwrap_or(5), max_sockets: self.max_sockets.unwrap_or(800) as usize, @@ -2457,7 +2435,7 @@ impl NodeConfigFile { name: self.name.unwrap_or(default_node_config.name), seed: match self.seed { Some(seed) => hex_bytes(&seed) - .map_err(|_e| format!("node.seed should be a hex encoded string"))?, + .map_err(|_e| "node.seed should be a hex encoded string".to_string())?, None => default_node_config.seed, }, working_dir: std::env::var("STACKS_WORKING_DIR") @@ -2471,8 +2449,9 @@ impl NodeConfigFile { .data_url .unwrap_or_else(|| format!("http://{rpc_bind}")), local_peer_seed: match self.local_peer_seed { - Some(seed) => hex_bytes(&seed) - .map_err(|_e| format!("node.local_peer_seed should be a hex encoded string"))?, + Some(seed) => hex_bytes(&seed).map_err(|_e| { + "node.local_peer_seed should be a hex encoded string".to_string() + })?, None => default_node_config.local_peer_seed, }, miner, @@ -2527,7 +2506,7 @@ impl NodeConfigFile { .unwrap_or(default_node_config.chain_liveness_poll_time_secs), stacker_dbs: self .stacker_dbs - .unwrap_or(vec![]) + .unwrap_or_default() .iter() .filter_map(|contract_id| QualifiedContractIdentifier::parse(contract_id).ok()) .collect(), @@ -2714,6 +2693,7 @@ pub struct AtlasConfigFile { impl AtlasConfigFile { // Can't inplement `Into` trait because this takes a parameter + #[allow(clippy::wrong_self_convention)] fn into_config(&self, mainnet: bool) -> AtlasConfig { let mut conf = AtlasConfig::new(mainnet); if let Some(val) = self.attachments_max_size { diff --git a/testnet/stacks-node/src/event_dispatcher.rs b/testnet/stacks-node/src/event_dispatcher.rs index bb05cd6128..dd587077a6 100644 --- a/testnet/stacks-node/src/event_dispatcher.rs +++ b/testnet/stacks-node/src/event_dispatcher.rs @@ -181,6 +181,12 @@ impl InnerStackerDBChannel { } } +impl Default for StackerDBChannel { + fn default() -> Self { + Self::new() + } +} + impl StackerDBChannel { pub const fn new() -> Self { Self { @@ -256,7 +262,7 @@ where serializer.serialize_str(&value.to_string()) } -fn serialize_pox_addresses(value: &Vec, serializer: S) -> Result +fn serialize_pox_addresses(value: &[PoxAddress], serializer: S) -> Result where S: serde::Serializer, { @@ -402,8 +408,8 @@ impl EventObserver { let id: i64 = row.get(0)?; let url: String = row.get(1)?; let payload_text: String = row.get(2)?; - let payload: serde_json::Value = serde_json::from_str(&payload_text) - .map_err(|e| db_error::SerializationError(e))?; + let payload: serde_json::Value = + serde_json::from_str(&payload_text).map_err(db_error::SerializationError)?; let timeout_ms: u64 = row.get(3)?; Ok((id, url, payload, timeout_ms)) }, @@ -642,7 +648,7 @@ impl EventObserver { TransactionOrigin::Burn(op) => ( op.txid().to_string(), "00".to_string(), - BlockstackOperationType::blockstack_op_to_json(&op), + BlockstackOperationType::blockstack_op_to_json(op), ), TransactionOrigin::Stacks(ref tx) => { let txid = tx.txid().to_string(); @@ -776,6 +782,7 @@ impl EventObserver { self.send_payload(payload, PATH_BURN_BLOCK_SUBMIT); } + #[allow(clippy::too_many_arguments)] fn make_new_block_processed_payload( &self, filtered_events: Vec<(usize, &(bool, Txid, &StacksTransactionEvent))>, @@ -806,12 +813,15 @@ impl EventObserver { }) .collect(); - let mut tx_index: u32 = 0; let mut serialized_txs = vec![]; - for receipt in receipts.iter() { - let payload = EventObserver::make_new_block_txs_payload(receipt, tx_index); + for (tx_index, receipt) in receipts.iter().enumerate() { + let payload = EventObserver::make_new_block_txs_payload( + receipt, + tx_index + .try_into() + .expect("BUG: more receipts than U32::MAX"), + ); serialized_txs.push(payload); - tx_index += 1; } let signer_bitvec_value = signer_bitvec_opt @@ -821,7 +831,7 @@ impl EventObserver { let (reward_set_value, cycle_number_value) = match &reward_set_data { Some(data) => ( - serde_json::to_value(&RewardSetEventPayload::from_reward_set(&data.reward_set)) + serde_json::to_value(RewardSetEventPayload::from_reward_set(&data.reward_set)) .unwrap_or_default(), serde_json::to_value(data.cycle_number).unwrap_or_default(), ), @@ -1097,6 +1107,12 @@ impl BlockEventDispatcher for EventDispatcher { } } +impl Default for EventDispatcher { + fn default() -> Self { + EventDispatcher::new() + } +} + impl EventDispatcher { pub fn new() -> EventDispatcher { EventDispatcher { @@ -1125,7 +1141,7 @@ impl EventDispatcher { ) { // lazily assemble payload only if we have observers let interested_observers = self.filter_observers(&self.burn_block_observers_lookup, true); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1149,6 +1165,7 @@ impl EventDispatcher { /// - dispatch_matrix: a vector where each index corresponds to the hashset of event indexes /// that each respective event observer is subscribed to /// - events: a vector of all events from all the tx receipts + #[allow(clippy::type_complexity)] fn create_dispatch_matrix_and_event_vector<'a>( &self, receipts: &'a Vec, @@ -1241,6 +1258,7 @@ impl EventDispatcher { (dispatch_matrix, events) } + #[allow(clippy::too_many_arguments)] pub fn process_chain_tip( &self, block: &StacksBlockEventData, @@ -1264,7 +1282,7 @@ impl EventDispatcher { let all_receipts = receipts.to_owned(); let (dispatch_matrix, events) = self.create_dispatch_matrix_and_event_vector(&all_receipts); - if dispatch_matrix.len() > 0 { + if !dispatch_matrix.is_empty() { let mature_rewards_vec = if let Some(rewards_info) = mature_rewards_info { mature_rewards .iter() @@ -1297,7 +1315,7 @@ impl EventDispatcher { let payload = self.registered_observers[observer_id] .make_new_block_processed_payload( filtered_events, - &block, + block, metadata, receipts, parent_index_hash, @@ -1342,7 +1360,7 @@ impl EventDispatcher { ) }) .collect(); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } let flattened_receipts = processed_unconfirmed_state @@ -1390,12 +1408,12 @@ impl EventDispatcher { .enumerate() .filter_map(|(obs_id, observer)| { let lookup_ix = u16::try_from(obs_id).expect("FATAL: more than 2^16 observers"); - if lookup.contains(&lookup_ix) { - return Some(observer); - } else if include_any && self.any_event_observers_lookup.contains(&lookup_ix) { - return Some(observer); + if lookup.contains(&lookup_ix) + || (include_any && self.any_event_observers_lookup.contains(&lookup_ix)) + { + Some(observer) } else { - return None; + None } }) .collect() @@ -1405,7 +1423,7 @@ impl EventDispatcher { // lazily assemble payload only if we have observers let interested_observers = self.filter_observers(&self.mempool_observers_lookup, true); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1427,7 +1445,7 @@ impl EventDispatcher { ) { let interested_observers = self.filter_observers(&self.miner_observers_lookup, false); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1456,7 +1474,7 @@ impl EventDispatcher { ) { let interested_observers = self.filter_observers(&self.mined_microblocks_observers_lookup, false); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1483,7 +1501,7 @@ impl EventDispatcher { tx_events: Vec, ) { let interested_observers = self.filter_observers(&self.miner_observers_lookup, false); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1502,7 +1520,7 @@ impl EventDispatcher { block_size: block_size_bytes, cost: consumed.clone(), tx_events, - miner_signature: block.header.miner_signature.clone(), + miner_signature: block.header.miner_signature, signer_signature_hash: block.header.signer_signature_hash(), signer_signature: block.header.signer_signature.clone(), signer_bitvec, @@ -1558,7 +1576,7 @@ impl EventDispatcher { // lazily assemble payload only if we have observers let interested_observers = self.filter_observers(&self.mempool_observers_lookup, true); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1577,9 +1595,9 @@ impl EventDispatcher { } } - pub fn process_new_attachments(&self, attachments: &Vec<(AttachmentInstance, Attachment)>) { + pub fn process_new_attachments(&self, attachments: &[(AttachmentInstance, Attachment)]) { let interested_observers: Vec<_> = self.registered_observers.iter().enumerate().collect(); - if interested_observers.len() < 1 { + if interested_observers.is_empty() { return; } @@ -1598,7 +1616,7 @@ impl EventDispatcher { &self, asset_identifier: &AssetIdentifier, event_index: usize, - dispatch_matrix: &mut Vec>, + dispatch_matrix: &mut [HashSet], ) { if let Some(observer_indexes) = self.assets_observers_lookup.get(asset_identifier) { for o_i in observer_indexes { diff --git a/testnet/stacks-node/src/globals.rs b/testnet/stacks-node/src/globals.rs index b1ddf2e82b..3e527e76e4 100644 --- a/testnet/stacks-node/src/globals.rs +++ b/testnet/stacks-node/src/globals.rs @@ -23,6 +23,7 @@ use crate::TipCandidate; pub type NeonGlobals = Globals; /// Command types for the relayer thread, issued to it by other threads +#[allow(clippy::large_enum_variant)] pub enum RelayerDirective { /// Handle some new data that arrived on the network (such as blocks, transactions, and HandleNetResult(NetworkResult), @@ -99,6 +100,7 @@ impl Clone for Globals { } impl Globals { + #[allow(clippy::too_many_arguments)] pub fn new( coord_comms: CoordinatorChannels, miner_status: Arc>, @@ -289,8 +291,8 @@ impl Globals { let active_key = RegisteredKey { target_block_height, vrf_public_key: op.public_key, - block_height: op.block_height as u64, - op_vtxindex: op.vtxindex as u32, + block_height: op.block_height, + op_vtxindex: op.vtxindex, memo: op.memo, }; @@ -450,10 +452,7 @@ impl Globals { /// Clear the initiative flag and return its value pub fn take_initiative(&self) -> Option { match self.initiative.lock() { - Ok(mut initiative) => { - let ret = (*initiative).take(); - ret - } + Ok(mut initiative) => (*initiative).take(), Err(_e) => { error!("FATAL: failed to lock initiative"); panic!(); diff --git a/testnet/stacks-node/src/keychain.rs b/testnet/stacks-node/src/keychain.rs index b6df8549c4..9402ebbad5 100644 --- a/testnet/stacks-node/src/keychain.rs +++ b/testnet/stacks-node/src/keychain.rs @@ -123,10 +123,7 @@ impl Keychain { let proof = VRF::prove(&sk, bytes.as_ref()); // Ensure that the proof is valid by verifying - let is_valid = match VRF::verify(&pk, &proof, bytes.as_ref()) { - Ok(v) => v, - Err(_) => false, - }; + let is_valid = VRF::verify(&pk, &proof, bytes.as_ref()).unwrap_or(false); assert!(is_valid); proof } @@ -178,7 +175,7 @@ impl Keychain { } /// Sign a transaction as if we were the origin - pub fn sign_as_origin(&self, tx_signer: &mut StacksTransactionSigner) -> () { + pub fn sign_as_origin(&self, tx_signer: &mut StacksTransactionSigner) { let sk = self.get_secret_key(); tx_signer .sign_origin(&sk) @@ -333,7 +330,7 @@ mod tests { } }; sk.set_compress_public(true); - self.microblocks_secret_keys.push(sk.clone()); + self.microblocks_secret_keys.push(sk); debug!("Microblock keypair rotated"; "burn_block_height" => %burn_block_height, @@ -346,7 +343,7 @@ mod tests { self.microblocks_secret_keys.last().cloned() } - pub fn sign_as_origin(&self, tx_signer: &mut StacksTransactionSigner) -> () { + pub fn sign_as_origin(&self, tx_signer: &mut StacksTransactionSigner) { let num_keys = if self.secret_keys.len() < self.threshold as usize { self.secret_keys.len() } else { @@ -370,12 +367,9 @@ mod tests { }; // Generate the proof - let proof = VRF::prove(&vrf_sk, bytes.as_ref()); + let proof = VRF::prove(vrf_sk, bytes.as_ref()); // Ensure that the proof is valid by verifying - let is_valid = match VRF::verify(vrf_pk, &proof, bytes.as_ref()) { - Ok(v) => v, - Err(_) => false, - }; + let is_valid = VRF::verify(vrf_pk, &proof, bytes.as_ref()).unwrap_or(false); assert!(is_valid); Some(proof) } @@ -385,7 +379,7 @@ mod tests { let public_keys = self .secret_keys .iter() - .map(|ref pk| StacksPublicKey::from_private(pk)) + .map(StacksPublicKey::from_private) .collect(); let version = if is_mainnet { self.hash_mode.to_version_mainnet() @@ -518,7 +512,7 @@ mod tests { TransactionVersion::Testnet, k1.get_transaction_auth().unwrap(), TransactionPayload::TokenTransfer( - recv_addr.clone().into(), + recv_addr.into(), 123, TokenTransferMemo([0u8; 34]), ), @@ -527,7 +521,7 @@ mod tests { TransactionVersion::Testnet, k2.get_transaction_auth().unwrap(), TransactionPayload::TokenTransfer( - recv_addr.clone().into(), + recv_addr.into(), 123, TokenTransferMemo([0u8; 34]), ), diff --git a/testnet/stacks-node/src/main.rs b/testnet/stacks-node/src/main.rs index fcdc9f5847..e795101c94 100644 --- a/testnet/stacks-node/src/main.rs +++ b/testnet/stacks-node/src/main.rs @@ -93,18 +93,18 @@ fn cli_pick_best_tip(config_path: &str, at_stacks_height: Option) -> TipCan at_stacks_height, ); - let best_tip = BlockMinerThread::inner_pick_best_tip(stacks_tips, HashMap::new()).unwrap(); - best_tip + BlockMinerThread::inner_pick_best_tip(stacks_tips, HashMap::new()).unwrap() } /// Implementation of `get_miner_spend` CLI option +#[allow(clippy::incompatible_msrv)] fn cli_get_miner_spend( config_path: &str, mine_start: Option, at_burnchain_height: Option, ) -> u64 { info!("Loading config at path {}", config_path); - let config = match ConfigFile::from_path(&config_path) { + let config = match ConfigFile::from_path(config_path) { Ok(config_file) => Config::from_config_file(config_file, true).unwrap(), Err(e) => { warn!("Invalid config file: {}", e); @@ -155,7 +155,7 @@ fn cli_get_miner_spend( &config, &keychain, &burnchain, - &mut sortdb, + &sortdb, &commit_outs, mine_start.unwrap_or(tip.block_height), at_burnchain_height, @@ -171,7 +171,7 @@ fn cli_get_miner_spend( else { return 0.0; }; - if active_miners_and_commits.len() == 0 { + if active_miners_and_commits.is_empty() { warn!("No active miners detected; using config file burn_fee_cap"); return 0.0; } @@ -207,12 +207,11 @@ fn cli_get_miner_spend( ); let win_probs = if config.miner.fast_rampup { // look at spends 6+ blocks in the future - let win_probs = MinerStats::get_future_win_distribution( + MinerStats::get_future_win_distribution( &active_miners_and_commits, &unconfirmed_block_commits, &commit_outs, - ); - win_probs + ) } else { // look at the current spends let Ok(unconfirmed_burn_dist) = miner_stats @@ -229,8 +228,7 @@ fn cli_get_miner_spend( return 0.0; }; - let win_probs = MinerStats::burn_dist_to_prob_dist(&unconfirmed_burn_dist); - win_probs + MinerStats::burn_dist_to_prob_dist(&unconfirmed_burn_dist) }; info!("Unconfirmed spend distribution: {:?}", &spend_dist); @@ -428,7 +426,6 @@ fn main() { let mut run_loop = helium::RunLoop::new(conf); if let Err(e) = run_loop.start(num_round) { warn!("Helium runloop exited: {}", e); - return; } } else if conf.burnchain.mode == "neon" || conf.burnchain.mode == "nakamoto-neon" diff --git a/testnet/stacks-node/src/nakamoto_node.rs b/testnet/stacks-node/src/nakamoto_node.rs index 7cda49e10d..ecf37ae0ec 100644 --- a/testnet/stacks-node/src/nakamoto_node.rs +++ b/testnet/stacks-node/src/nakamoto_node.rs @@ -148,7 +148,7 @@ impl StacksNode { let burnchain = runloop.get_burnchain(); let atlas_config = config.atlas.clone(); let mut keychain = Keychain::default(config.node.seed.clone()); - if let Some(mining_key) = config.miner.mining_key.clone() { + if let Some(mining_key) = config.miner.mining_key { keychain.set_nakamoto_sk(mining_key); } @@ -195,7 +195,7 @@ impl StacksNode { match &data_from_neon.leader_key_registration_state { LeaderKeyRegistrationState::Active(registered_key) => { let pubkey_hash = keychain.get_nakamoto_pkh(); - if pubkey_hash.as_ref() == ®istered_key.memo { + if pubkey_hash.as_ref() == registered_key.memo { data_from_neon.leader_key_registration_state } else { LeaderKeyRegistrationState::Inactive @@ -366,7 +366,7 @@ pub(crate) fn save_activated_vrf_key(path: &str, activated_key: &RegisteredKey) return; }; - let mut f = match fs::File::create(&path) { + let mut f = match fs::File::create(path) { Ok(f) => f, Err(e) => { warn!("Failed to create {}: {:?}", &path, &e); @@ -374,7 +374,7 @@ pub(crate) fn save_activated_vrf_key(path: &str, activated_key: &RegisteredKey) } }; - if let Err(e) = f.write_all(key_json.as_str().as_bytes()) { + if let Err(e) = f.write_all(key_json.as_bytes()) { warn!("Failed to write activated VRF key to {}: {:?}", &path, &e); return; } diff --git a/testnet/stacks-node/src/nakamoto_node/miner.rs b/testnet/stacks-node/src/nakamoto_node/miner.rs index 150762e965..042df70be1 100644 --- a/testnet/stacks-node/src/nakamoto_node/miner.rs +++ b/testnet/stacks-node/src/nakamoto_node/miner.rs @@ -67,6 +67,7 @@ pub static TEST_SKIP_P2P_BROADCAST: std::sync::Mutex> = std::sync:: /// miner thread sleep before trying again? const ABORT_TRY_AGAIN_MS: u64 = 200; +#[allow(clippy::large_enum_variant)] pub enum MinerDirective { /// The miner won sortition so they should begin a new tenure BeginTenure { @@ -424,7 +425,7 @@ impl BlockMinerThread { // update mined-block counters and mined-tenure counters self.globals.counters.bump_naka_mined_blocks(); - if !self.last_block_mined.is_none() { + if self.last_block_mined.is_some() { // this is the first block of the tenure, bump tenure counter self.globals.counters.bump_naka_mined_tenures(); } @@ -573,12 +574,12 @@ impl BlockMinerThread { &self.burnchain, &sort_db, &mut chain_state, - &stackerdbs, + stackerdbs, &self.globals.counters, &self.burn_election_block.consensus_hash, )?; - return Ok((reward_set, signature)); + Ok((reward_set, signature)) } /// Fault injection -- possibly fail to broadcast @@ -590,13 +591,12 @@ impl BlockMinerThread { .fault_injection_block_push_fail_probability .unwrap_or(0) .min(100); - let will_drop = if drop_prob > 0 { + if drop_prob > 0 { let throw: u8 = thread_rng().gen_range(0..100); throw < drop_prob } else { false - }; - will_drop + } } /// Store a block to the chainstate, and if successful (it should be since we mined it), @@ -621,7 +621,7 @@ impl BlockMinerThread { let (headers_conn, staging_tx) = chain_state.headers_conn_and_staging_tx_begin()?; let accepted = NakamotoChainState::accept_block( &chainstate_config, - &block, + block, &mut sortition_handle, &staging_tx, headers_conn, @@ -704,7 +704,7 @@ impl BlockMinerThread { miner_privkey, &sort_db, &self.burn_block, - &stackerdbs, + stackerdbs, SignerMessage::BlockPushed(block), MinerSlotID::BlockPushed, chain_state.mainnet, @@ -869,24 +869,21 @@ impl BlockMinerThread { "Stacks block parent ID may be an epoch2x block: {}", &self.parent_tenure_id ); - let epoch2_header = - NakamotoChainState::get_block_header(chain_state.db(), &self.parent_tenure_id) - .map_err(|e| { - error!( - "Could not query header info for epoch2x tenure block ID {}: {:?}", - &self.parent_tenure_id, &e - ); - NakamotoNodeError::ParentNotFound - })? - .ok_or_else(|| { - error!( - "No header info for epoch2x tenure block ID {}", - &self.parent_tenure_id - ); - NakamotoNodeError::ParentNotFound - })?; - - epoch2_header + NakamotoChainState::get_block_header(chain_state.db(), &self.parent_tenure_id) + .map_err(|e| { + error!( + "Could not query header info for epoch2x tenure block ID {}: {:?}", + &self.parent_tenure_id, &e + ); + NakamotoNodeError::ParentNotFound + })? + .ok_or_else(|| { + error!( + "No header info for epoch2x tenure block ID {}", + &self.parent_tenure_id + ); + NakamotoNodeError::ParentNotFound + })? } }; @@ -1147,9 +1144,9 @@ impl BlockMinerThread { let parent_block_id = parent_block_info.stacks_parent_header.index_block_hash(); let mut payload = TenureChangePayload { - tenure_consensus_hash: self.burn_election_block.consensus_hash.clone(), + tenure_consensus_hash: self.burn_election_block.consensus_hash, prev_tenure_consensus_hash: parent_tenure_info.parent_tenure_consensus_hash, - burn_view_consensus_hash: self.burn_election_block.consensus_hash.clone(), + burn_view_consensus_hash: self.burn_election_block.consensus_hash, previous_tenure_end: parent_block_id, previous_tenure_blocks: u32::try_from(parent_tenure_info.parent_tenure_blocks) .expect("FATAL: more than u32 blocks in a tenure"), @@ -1252,7 +1249,7 @@ impl ParentStacksBlockInfo { } let Ok(Some(parent_tenure_header)) = - NakamotoChainState::get_block_header(chain_state.db(), &parent_tenure_id) + NakamotoChainState::get_block_header(chain_state.db(), parent_tenure_id) else { warn!("Failed loading parent tenure ID"; "parent_tenure_id" => %parent_tenure_id); return Err(NakamotoNodeError::ParentNotFound); @@ -1293,7 +1290,7 @@ impl ParentStacksBlockInfo { } else { 1 }; - let parent_tenure_consensus_hash = parent_tenure_header.consensus_hash.clone(); + let parent_tenure_consensus_hash = parent_tenure_header.consensus_hash; Some(ParentTenureInfo { parent_tenure_blocks, parent_tenure_consensus_hash, @@ -1321,7 +1318,7 @@ impl ParentStacksBlockInfo { let account = chain_state .with_read_only_clarity_tx( &burn_db - .index_handle_at_block(&chain_state, &stacks_tip_header.index_block_hash()) + .index_handle_at_block(chain_state, &stacks_tip_header.index_block_hash()) .map_err(|_| NakamotoNodeError::UnexpectedChainState)?, &stacks_tip_header.index_block_hash(), |conn| StacksChainState::get_account(conn, &principal), diff --git a/testnet/stacks-node/src/nakamoto_node/peer.rs b/testnet/stacks-node/src/nakamoto_node/peer.rs index 004023ea26..78deb69b9f 100644 --- a/testnet/stacks-node/src/nakamoto_node/peer.rs +++ b/testnet/stacks-node/src/nakamoto_node/peer.rs @@ -227,6 +227,7 @@ impl PeerThread { /// Run one pass of the p2p/http state machine /// Return true if we should continue running passes; false if not + #[allow(clippy::borrowed_box)] pub(crate) fn run_one_pass( &mut self, indexer: &B, @@ -238,7 +239,7 @@ impl PeerThread { ) -> bool { // initial block download? let ibd = self.globals.sync_comms.get_ibd(); - let download_backpressure = self.results_with_data.len() > 0; + let download_backpressure = !self.results_with_data.is_empty(); let poll_ms = if !download_backpressure && self.net.has_more_downloads() { // keep getting those blocks -- drive the downloader state-machine debug!( @@ -258,7 +259,7 @@ impl PeerThread { // NOTE: handler_args must be created such that it outlives the inner net.run() call and // doesn't ref anything within p2p_thread. let handler_args = RPCHandlerArgs { - exit_at_block_height: self.config.burnchain.process_exit_at_block_height.clone(), + exit_at_block_height: self.config.burnchain.process_exit_at_block_height, genesis_chainstate_hash: Sha256Sum::from_hex(stx_genesis::GENESIS_CHAINSTATE_HASH) .unwrap(), event_observer: Some(event_dispatcher), @@ -266,7 +267,6 @@ impl PeerThread { cost_metric: Some(cost_metric.as_ref()), fee_estimator: fee_estimator.map(|boxed_estimator| boxed_estimator.as_ref()), coord_comms: Some(&self.globals.coord_comms), - ..RPCHandlerArgs::default() }; self.net.run( indexer, diff --git a/testnet/stacks-node/src/nakamoto_node/relayer.rs b/testnet/stacks-node/src/nakamoto_node/relayer.rs index ef01f67f4b..441d7ecd2c 100644 --- a/testnet/stacks-node/src/nakamoto_node/relayer.rs +++ b/testnet/stacks-node/src/nakamoto_node/relayer.rs @@ -67,6 +67,7 @@ use crate::run_loop::RegisteredKey; use crate::BitcoinRegtestController; /// Command types for the Nakamoto relayer thread, issued to it by other threads +#[allow(clippy::large_enum_variant)] pub enum RelayerDirective { /// Handle some new data that arrived on the network (such as blocks, transactions, and HandleNetResult(NetworkResult), @@ -142,7 +143,7 @@ impl LastCommit { /// What's the parent tenure's tenure-start block hash? pub fn parent_tenure_id(&self) -> StacksBlockId { - StacksBlockId(self.block_commit.block_header_hash.clone().0) + StacksBlockId(self.block_commit.block_header_hash.0) } /// What's the stacks tip at the time of commit? @@ -167,7 +168,7 @@ impl LastCommit { /// Set our txid pub fn set_txid(&mut self, txid: &Txid) { - self.txid = Some(txid.clone()); + self.txid = Some(*txid); } } @@ -302,6 +303,8 @@ impl RelayerThread { /// have we waited for the right conditions under which to start mining a block off of our /// chain tip? + #[allow(clippy::nonminimal_bool)] + #[allow(clippy::eq_op)] fn has_waited_for_latest_blocks(&self) -> bool { // a network download pass took place (self.min_network_download_passes <= self.last_network_download_passes @@ -497,7 +500,7 @@ impl RelayerThread { BlockstackOperationType::LeaderKeyRegister(LeaderKeyRegisterOp { public_key: vrf_public_key, memo: miner_pkh.as_bytes().to_vec(), - consensus_hash: consensus_hash.clone(), + consensus_hash: *consensus_hash, vtxindex: 0, txid: Txid([0u8; 32]), block_height: 0, @@ -564,7 +567,7 @@ impl RelayerThread { let highest_tenure_start_block_header = NakamotoChainState::get_tenure_start_block_header( &mut self.chainstate.index_conn(), &stacks_tip, - &tip_block_ch, + tip_block_ch, ) .map_err(|e| { error!( @@ -730,9 +733,7 @@ impl RelayerThread { /// * last_burn_block corresponds to the canonical sortition DB's chain tip /// * the time of issuance is sufficiently recent /// * there are no unprocessed stacks blocks in the staging DB - /// * the relayer has already tried a download scan that included this sortition (which, if a - /// block was found, would have placed it into the staging DB and marked it as - /// unprocessed) + /// * the relayer has already tried a download scan that included this sortition (which, if a block was found, would have placed it into the staging DB and marked it as unprocessed) /// * a miner thread is not running already fn create_block_miner( &mut self, @@ -750,11 +751,11 @@ impl RelayerThread { return Err(NakamotoNodeError::FaultInjection); } - let burn_header_hash = burn_tip.burn_header_hash.clone(); + let burn_header_hash = burn_tip.burn_header_hash; let burn_chain_sn = SortitionDB::get_canonical_burn_chain_tip(self.sortdb.conn()) .expect("FATAL: failed to query sortition DB for canonical burn chain tip"); - let burn_chain_tip = burn_chain_sn.burn_header_hash.clone(); + let burn_chain_tip = burn_chain_sn.burn_header_hash; if burn_chain_tip != burn_header_hash { debug!( @@ -1067,7 +1068,7 @@ impl RelayerThread { // sign and broadcast let mut op_signer = self.keychain.generate_op_signer(); let res = self.bitcoin_controller.submit_operation( - last_committed.get_epoch_id().clone(), + *last_committed.get_epoch_id(), BlockstackOperationType::LeaderBlockCommit(last_committed.get_block_commit().clone()), &mut op_signer, 1, @@ -1299,7 +1300,7 @@ impl RelayerThread { let mut saved_key_opt = None; if let Some(path) = self.config.miner.activated_vrf_key_path.as_ref() { saved_key_opt = - Self::load_saved_vrf_key(&path, &self.keychain.get_nakamoto_pkh()); + Self::load_saved_vrf_key(path, &self.keychain.get_nakamoto_pkh()); } if let Some(saved_key) = saved_key_opt { debug!("Relayer: resuming VRF key"); @@ -1371,9 +1372,9 @@ pub mod test { let pubkey_hash = Hash160::from_node_public_key(&pk); let path = "/tmp/does_not_exist.json"; - _ = std::fs::remove_file(&path); + _ = std::fs::remove_file(path); - let res = RelayerThread::load_saved_vrf_key(&path, &pubkey_hash); + let res = RelayerThread::load_saved_vrf_key(path, &pubkey_hash); assert!(res.is_none()); } @@ -1384,13 +1385,13 @@ pub mod test { let pubkey_hash = Hash160::from_node_public_key(&pk); let path = "/tmp/empty.json"; - File::create(&path).expect("Failed to create test file"); - assert!(Path::new(&path).exists()); + File::create(path).expect("Failed to create test file"); + assert!(Path::new(path).exists()); - let res = RelayerThread::load_saved_vrf_key(&path, &pubkey_hash); + let res = RelayerThread::load_saved_vrf_key(path, &pubkey_hash); assert!(res.is_none()); - std::fs::remove_file(&path).expect("Failed to delete test file"); + std::fs::remove_file(path).expect("Failed to delete test file"); } #[test] @@ -1403,15 +1404,15 @@ pub mod test { let json_content = r#"{ "hello": "world" }"#; // Write the JSON content to the file - let mut file = File::create(&path).expect("Failed to create test file"); + let mut file = File::create(path).expect("Failed to create test file"); file.write_all(json_content.as_bytes()) .expect("Failed to write to test file"); - assert!(Path::new(&path).exists()); + assert!(Path::new(path).exists()); - let res = RelayerThread::load_saved_vrf_key(&path, &pubkey_hash); + let res = RelayerThread::load_saved_vrf_key(path, &pubkey_hash); assert!(res.is_none()); - std::fs::remove_file(&path).expect("Failed to delete test file"); + std::fs::remove_file(path).expect("Failed to delete test file"); } #[test] @@ -1432,10 +1433,10 @@ pub mod test { let path = "/tmp/vrf_key.json"; save_activated_vrf_key(path, &key); - let res = RelayerThread::load_saved_vrf_key(&path, &pubkey_hash); + let res = RelayerThread::load_saved_vrf_key(path, &pubkey_hash); assert!(res.is_some()); - std::fs::remove_file(&path).expect("Failed to delete test file"); + std::fs::remove_file(path).expect("Failed to delete test file"); } #[test] @@ -1460,9 +1461,9 @@ pub mod test { let pk = Secp256k1PublicKey::from_private(keychain.get_nakamoto_sk()); let pubkey_hash = Hash160::from_node_public_key(&pk); - let res = RelayerThread::load_saved_vrf_key(&path, &pubkey_hash); + let res = RelayerThread::load_saved_vrf_key(path, &pubkey_hash); assert!(res.is_none()); - std::fs::remove_file(&path).expect("Failed to delete test file"); + std::fs::remove_file(path).expect("Failed to delete test file"); } } diff --git a/testnet/stacks-node/src/nakamoto_node/sign_coordinator.rs b/testnet/stacks-node/src/nakamoto_node/sign_coordinator.rs index 697dddeb03..b2f892e1f1 100644 --- a/testnet/stacks-node/src/nakamoto_node/sign_coordinator.rs +++ b/testnet/stacks-node/src/nakamoto_node/sign_coordinator.rs @@ -188,6 +188,7 @@ impl SignCoordinator { } /// Send a message over the miners contract using a `StacksPrivateKey` + #[allow(clippy::too_many_arguments)] pub fn send_miners_message( miner_sk: &StacksPrivateKey, sortdb: &SortitionDB, @@ -199,7 +200,7 @@ impl SignCoordinator { miners_session: &mut StackerDBSession, election_sortition: &ConsensusHash, ) -> Result<(), String> { - let Some(slot_range) = NakamotoChainState::get_miner_slot(sortdb, tip, &election_sortition) + let Some(slot_range) = NakamotoChainState::get_miner_slot(sortdb, tip, election_sortition) .map_err(|e| format!("Failed to read miner slot information: {e:?}"))? else { return Err("No slot for miner".into()); @@ -222,7 +223,7 @@ impl SignCoordinator { .saturating_add(1); let mut chunk = StackerDBChunkData::new(slot_id, slot_version, message.serialize_to_vec()); chunk - .sign(&miner_sk) + .sign(miner_sk) .map_err(|_| "Failed to sign StackerDB chunk")?; match miners_session.put_chunk(&chunk) { @@ -270,13 +271,14 @@ impl SignCoordinator { /// to the signers, and then waits for the signers to respond /// with their signatures. It does so in two ways, concurrently: /// * It waits for signer StackerDB messages with signatures. If enough signatures can be - /// found, then the block can be broadcast. + /// found, then the block can be broadcast. /// * It waits for the chainstate to contain the relayed block. If so, then its signatures are - /// loaded and returned. This can happen if the node receives the block via a signer who - /// fetched all signatures and assembled the signature vector, all before we could. + /// loaded and returned. This can happen if the node receives the block via a signer who + /// fetched all signatures and assembled the signature vector, all before we could. // Mutants skip here: this function is covered via integration tests, // which the mutation testing does not see. #[cfg_attr(test, mutants::skip)] + #[allow(clippy::too_many_arguments)] pub fn run_sign_v0( &mut self, block: &NakamotoBlock, @@ -306,7 +308,7 @@ impl SignCoordinator { &self.message_key, sortdb, burn_tip, - &stackerdbs, + stackerdbs, block_proposal_message, MinerSlotID::BlockProposal, self.is_mainnet, @@ -367,7 +369,7 @@ impl SignCoordinator { return Ok(stored_block.header.signer_signature); } - if Self::check_burn_tip_changed(&sortdb, &burn_tip) { + if Self::check_burn_tip_changed(sortdb, burn_tip) { debug!("SignCoordinator: Exiting due to new burnchain tip"); return Err(NakamotoNodeError::BurnchainTipChanged); } diff --git a/testnet/stacks-node/src/neon_node.rs b/testnet/stacks-node/src/neon_node.rs index dcfa855c9b..efc64bf8e7 100644 --- a/testnet/stacks-node/src/neon_node.rs +++ b/testnet/stacks-node/src/neon_node.rs @@ -62,79 +62,85 @@ /// [11] Notifies about new transaction attachment events /// [12] Signals VRF key registration /// -/// When the node is running, there are 4-5 active threads at once. They are: +/// When the node is running, there are 4-5 active threads at once. They are: /// -/// * **RunLoop Thread**: This is the main thread, whose code body lives in src/run_loop/neon.rs. -/// This thread is responsible for: -/// * Bootup -/// * Running the burnchain indexer -/// * Notifying the ChainsCoordinator thread when there are new burnchain blocks to process +/// * **RunLoop Thread**: +/// This is the main thread, whose code body lives in `src/run_loop/neon.rs`. +/// This thread is responsible for: +/// * Bootup +/// * Running the burnchain indexer +/// * Notifying the ChainsCoordinator thread when there are new burnchain blocks to process /// -/// * **Relayer Thread**: This is the thread that stores and relays blocks and microblocks. Both -/// it and the ChainsCoordinator thread are very I/O-heavy threads, and care has been taken to -/// ensure that neither one attempts to acquire a write-lock in the underlying databases. -/// Specifically, this thread directs the ChainsCoordinator thread when to process new Stacks -/// blocks, and it directs the miner thread (if running) to stop when either it or the -/// ChainsCoordinator thread needs to acquire the write-lock. -/// This thread is responsible for: -/// * Receiving new blocks and microblocks from the P2P thread via a shared channel -/// * (Sychronously) requesting the CoordinatorThread to process newly-stored Stacks blocks and -/// microblocks -/// * Building up the node's unconfirmed microblock stream state, and sharing it with the P2P -/// thread so it can answer queries about the unconfirmed microblock chain -/// * Pushing newly-discovered blocks and microblocks to the P2P thread for broadcast -/// * Registering the VRF public key for the miner -/// * Spawning the block and microblock miner threads, and stopping them if their continued -/// execution would inhibit block or microblock storage or processing. -/// * Submitting the burnchain operation to commit to a freshly-mined block +/// * **Relayer Thread**: +/// This is the thread that stores and relays blocks and microblocks. Both +/// it and the ChainsCoordinator thread are very I/O-heavy threads, and care has been taken to +/// ensure that neither one attempts to acquire a write-lock in the underlying databases. +/// Specifically, this thread directs the ChainsCoordinator thread when to process new Stacks +/// blocks, and it directs the miner thread (if running) to stop when either it or the +/// ChainsCoordinator thread needs to acquire the write-lock. +/// This thread is responsible for: +/// * Receiving new blocks and microblocks from the P2P thread via a shared channel +/// * (Synchronously) requesting the CoordinatorThread to process newly-stored Stacks blocks +/// and microblocks +/// * Building up the node's unconfirmed microblock stream state, and sharing it with the P2P +/// thread so it can answer queries about the unconfirmed microblock chain +/// * Pushing newly-discovered blocks and microblocks to the P2P thread for broadcast +/// * Registering the VRF public key for the miner +/// * Spawning the block and microblock miner threads, and stopping them if their continued +/// execution would inhibit block or microblock storage or processing. +/// * Submitting the burnchain operation to commit to a freshly-mined block /// -/// * **Miner thread**: This is the thread that actually produces new blocks and microblocks. It -/// is spawned only by the Relayer thread to carry out mining activity when the underlying -/// chainstate is not needed by either the Relayer or ChainsCoordinator threeads. -/// This thread does the following: -/// * Walk the mempool DB to build a new block or microblock -/// * Return the block or microblock to the Relayer thread +/// * **Miner Thread**: +/// This is the thread that actually produces new blocks and microblocks. It +/// is spawned only by the Relayer thread to carry out mining activity when the underlying +/// chainstate is not needed by either the Relayer or ChainsCoordinator threads. +/// This thread does the following: +/// * Walk the mempool DB to build a new block or microblock +/// * Return the block or microblock to the Relayer thread /// -/// * **P2P Thread**: This is the thread that communicates with the rest of the p2p network, and -/// handles RPC requests. It is meant to do as little storage-write I/O as possible to avoid lock -/// contention with the Miner, Relayer, and ChainsCoordinator threads. In particular, it forwards -/// data it receives from the p2p thread to the Relayer thread for I/O-bound processing. At the -/// time of this writing, it still requires holding a write-lock to handle some RPC request, but -/// future work will remove this so that this thread's execution will not interfere with the -/// others. This is the only thread that does socket I/O. -/// This thread runs the PeerNetwork state machines, which include the following: -/// * Learning the node's public IP address -/// * Discovering neighbor nodes -/// * Forwarding newly-discovered blocks, microblocks, and transactions from the Relayer thread to -/// other neighbors -/// * Synchronizing block and microblock inventory state with other neighbors -/// * Downloading blocks and microblocks, and passing them to the Relayer for storage and processing -/// * Downloading transaction attachments as their hashes are discovered during block processing -/// * Synchronizing the local mempool database with other neighbors -/// (notifications for new attachments come from a shared channel in the ChainsCoordinator thread) -/// * Handling HTTP requests +/// * **P2P Thread**: +/// This is the thread that communicates with the rest of the P2P network, and +/// handles RPC requests. It is meant to do as little storage-write I/O as possible to avoid lock +/// contention with the Miner, Relayer, and ChainsCoordinator threads. In particular, it forwards +/// data it receives from the P2P thread to the Relayer thread for I/O-bound processing. At the +/// time of this writing, it still requires holding a write-lock to handle some RPC requests, but +/// future work will remove this so that this thread's execution will not interfere with the +/// others. This is the only thread that does socket I/O. +/// This thread runs the PeerNetwork state machines, which include the following: +/// * Learning the node's public IP address +/// * Discovering neighbor nodes +/// * Forwarding newly-discovered blocks, microblocks, and transactions from the Relayer thread +/// to other neighbors +/// * Synchronizing block and microblock inventory state with other neighbors +/// * Downloading blocks and microblocks, and passing them to the Relayer for storage and +/// processing +/// * Downloading transaction attachments as their hashes are discovered during block processing +/// * Synchronizing the local mempool database with other neighbors +/// (notifications for new attachments come from a shared channel in the ChainsCoordinator thread) +/// * Handling HTTP requests /// -/// * **ChainsCoordinator Thread**: This thread process sortitions and Stacks blocks and -/// microblocks, and handles PoX reorgs should they occur (this mainly happens in boot-up). It, -/// like the Relayer thread, is a very I/O-heavy thread, and it will hold a write-lock on the -/// chainstate DBs while it works. Its actions are controlled by a CoordinatorComms structure in -/// the Globals shared state, which the Relayer thread and RunLoop thread both drive (the former -/// drives Stacks blocks processing, the latter sortitions). -/// This thread is responsible for: -/// * Responding to requests from other threads to process sortitions -/// * Responding to requests from other threads to process Stacks blocks and microblocks -/// * Processing PoX chain reorgs, should they ever happen -/// * Detecting attachment creation events, and informing the P2P thread of them so it can go -/// and download them +/// * **ChainsCoordinator Thread**: +/// This thread processes sortitions and Stacks blocks and +/// microblocks, and handles PoX reorgs should they occur (this mainly happens in boot-up). It, +/// like the Relayer thread, is a very I/O-heavy thread, and it will hold a write-lock on the +/// chainstate DBs while it works. Its actions are controlled by a CoordinatorComms structure in +/// the Globals shared state, which the Relayer thread and RunLoop thread both drive (the former +/// drives Stacks blocks processing, the latter sortitions). +/// This thread is responsible for: +/// * Responding to requests from other threads to process sortitions +/// * Responding to requests from other threads to process Stacks blocks and microblocks +/// * Processing PoX chain reorgs, should they ever happen +/// * Detecting attachment creation events, and informing the P2P thread of them so it can go +/// and download them /// /// In addition to the mempool and chainstate databases, these threads share access to a Globals -/// singleton that contains soft state shared between threads. Mainly, the Globals struct is meant -/// to store inter-thread shared singleton communication media all in one convenient struct. Each -/// thread has a handle to the struct's shared state handles. Global state includes: -/// * The global flag as to whether or not the miner thread can be running -/// * The global shutdown flag that, when set, causes all threads to terminate -/// * Sender channel endpoints that can be shared between threads -/// * Metrics about the node's behavior (e.g. number of blocks processed, etc.) +/// singleton that contains soft state shared between threads. Mainly, the Globals struct is meant +/// to store inter-thread shared singleton communication media all in one convenient struct. Each +/// thread has a handle to the struct's shared state handles. Global state includes: +/// * The global flag as to whether or not the miner thread can be running +/// * The global shutdown flag that, when set, causes all threads to terminate +/// * Sender channel endpoints that can be shared between threads +/// * Metrics about the node's behavior (e.g. number of blocks processed, etc.) /// /// This file may be refactored in the future into a full-fledged module. use std::cmp; @@ -230,6 +236,7 @@ pub const BLOCK_PROCESSOR_STACK_SIZE: usize = 32 * 1024 * 1024; // 32 MB type MinedBlocks = HashMap; /// Result of running the miner thread. It could produce a Stacks block or a microblock. +#[allow(clippy::large_enum_variant)] pub(crate) enum MinerThreadResult { Block( AssembledAnchorBlock, @@ -646,8 +653,8 @@ impl MicroblockMinerThread { sortdb: Some(sortdb), mempool: Some(mempool), event_dispatcher: relayer_thread.event_dispatcher.clone(), - parent_consensus_hash: ch.clone(), - parent_block_hash: bhh.clone(), + parent_consensus_hash: ch, + parent_block_hash: bhh, miner_key, frequency, last_mined: 0, @@ -743,7 +750,7 @@ impl MicroblockMinerThread { let mint_result = { let ic = sortdb.index_handle_at_block( - &chainstate, + chainstate, &block_snapshot.get_canonical_stacks_block_id(), )?; let mut microblock_miner = match StacksMicroblockBuilder::resume_unconfirmed( @@ -810,7 +817,7 @@ impl MicroblockMinerThread { use std::path::Path; if let Ok(path) = std::env::var("STACKS_BAD_BLOCKS_DIR") { // record this microblock somewhere - if !fs::metadata(&path).is_ok() { + if fs::metadata(&path).is_err() { fs::create_dir_all(&path) .unwrap_or_else(|_| panic!("FATAL: could not create '{}'", &path)); } @@ -827,7 +834,7 @@ impl MicroblockMinerThread { r#"{{"microblock":"{}","parent_consensus":"{}","parent_block":"{}"}}"#, &mblock_bits_hex, &self.parent_consensus_hash, &self.parent_block_hash ); - file.write_all(&mblock_json.as_bytes()).unwrap_or_else(|_| { + file.write_all(mblock_json.as_bytes()).unwrap_or_else(|_| { panic!("FATAL: failed to write microblock bits to '{:?}'", &path) }); info!( @@ -873,7 +880,7 @@ impl MicroblockMinerThread { // update unconfirmed state cost self.cost_so_far = new_cost; self.quantity += 1; - return Ok(mined_microblock); + Ok(mined_microblock) } /// Can this microblock miner mine off of this given tip? @@ -1086,6 +1093,7 @@ impl BlockMinerThread { } /// Constructs and returns a LeaderBlockCommitOp out of the provided params. + #[allow(clippy::too_many_arguments)] fn inner_generate_block_commit_op( &self, block_header_hash: BlockHeaderHash, @@ -1202,7 +1210,7 @@ impl BlockMinerThread { .expect("FATAL: could not query chain tips") }; - if stacks_tips.len() == 0 { + if stacks_tips.is_empty() { return vec![]; } @@ -1213,7 +1221,7 @@ impl BlockMinerThread { .filter(|candidate| Self::is_on_canonical_burnchain_fork(candidate, &sortdb_tip_handle)) .collect(); - if stacks_tips.len() == 0 { + if stacks_tips.is_empty() { return vec![]; } @@ -1269,7 +1277,7 @@ impl BlockMinerThread { pub(crate) fn sort_and_populate_candidates( mut candidates: Vec, ) -> Vec { - if candidates.len() == 0 { + if candidates.is_empty() { return candidates; } candidates.sort_by(|tip1, tip2| { @@ -1373,7 +1381,7 @@ impl BlockMinerThread { // identify leaf tips -- i.e. blocks with no children let parent_consensus_hashes: HashSet<_> = stacks_tips .iter() - .map(|x| x.parent_consensus_hash.clone()) + .map(|x| x.parent_consensus_hash) .collect(); let mut leaf_tips: Vec<_> = stacks_tips @@ -1381,7 +1389,7 @@ impl BlockMinerThread { .filter(|x| !parent_consensus_hashes.contains(&x.consensus_hash)) .collect(); - if leaf_tips.len() == 0 { + if leaf_tips.is_empty() { return None; } @@ -1502,7 +1510,7 @@ impl BlockMinerThread { } } - if scores.len() == 0 { + if scores.is_empty() { // revert to prior tie-breaking scheme return None; } @@ -1576,14 +1584,14 @@ impl BlockMinerThread { let chain_tip = ChainTip::genesis( &burnchain_params.first_block_hash, - burnchain_params.first_block_height.into(), + burnchain_params.first_block_height, burnchain_params.first_block_timestamp.into(), ); ( Some(ParentStacksBlockInfo { stacks_parent_header: chain_tip.metadata, - parent_consensus_hash: FIRST_BURNCHAIN_CONSENSUS_HASH.clone(), + parent_consensus_hash: FIRST_BURNCHAIN_CONSENSUS_HASH, parent_block_burn_height: 0, parent_block_total_burn: 0, parent_winning_vtxindex: 0, @@ -1671,7 +1679,7 @@ impl BlockMinerThread { { if (prev_block.anchored_block.header.parent_microblock == BlockHeaderHash([0u8; 32]) - && stream.len() == 0) + && stream.is_empty()) || (prev_block.anchored_block.header.parent_microblock != BlockHeaderHash([0u8; 32]) && stream.len() @@ -1699,30 +1707,26 @@ impl BlockMinerThread { best_attempt = cmp::max(best_attempt, prev_block.attempt); } - } else { - if !force { - // no microblock stream to confirm, and the stacks tip hasn't changed - info!("Relayer: Stacks tip is unchanged since we last tried to mine a block off of {}/{} at height {} with {} txs, in {} at burn height {}, and no microblocks present", - &prev_block.parent_consensus_hash, &prev_block.anchored_block.header.parent_block, prev_block.anchored_block.header.total_work.work, - prev_block.anchored_block.txs.len(), prev_block.burn_hash, parent_block_burn_height); + } else if !force { + // no microblock stream to confirm, and the stacks tip hasn't changed + info!("Relayer: Stacks tip is unchanged since we last tried to mine a block off of {}/{} at height {} with {} txs, in {} at burn height {}, and no microblocks present", + &prev_block.parent_consensus_hash, &prev_block.anchored_block.header.parent_block, prev_block.anchored_block.header.total_work.work, + prev_block.anchored_block.txs.len(), prev_block.burn_hash, parent_block_burn_height); - return None; - } + return None; } - } else { - if self.burn_block.burn_header_hash == prev_block.burn_hash { - // only try and re-mine if there was no sortition since the last chain tip - info!("Relayer: Stacks tip has changed to {}/{} since we last tried to mine a block in {} at burn height {}; attempt was {} (for Stacks tip {}/{})", + } else if self.burn_block.burn_header_hash == prev_block.burn_hash { + // only try and re-mine if there was no sortition since the last chain tip + info!("Relayer: Stacks tip has changed to {}/{} since we last tried to mine a block in {} at burn height {}; attempt was {} (for Stacks tip {}/{})", parent_consensus_hash, stacks_parent_header.anchored_header.block_hash(), prev_block.burn_hash, parent_block_burn_height, prev_block.attempt, &prev_block.parent_consensus_hash, &prev_block.anchored_block.header.parent_block); - best_attempt = cmp::max(best_attempt, prev_block.attempt); - // Since the chain tip has changed, we should try to mine a new block, even - // if it has less transactions than the previous block we mined, since that - // previous block would now be a reorg. - max_txs = 0; - } else { - info!("Relayer: Burn tip has changed to {} ({}) since we last tried to mine a block in {}", - &self.burn_block.burn_header_hash, self.burn_block.block_height, &prev_block.burn_hash); - } + best_attempt = cmp::max(best_attempt, prev_block.attempt); + // Since the chain tip has changed, we should try to mine a new block, even + // if it has less transactions than the previous block we mined, since that + // previous block would now be a reorg. + max_txs = 0; + } else { + info!("Relayer: Burn tip has changed to {} ({}) since we last tried to mine a block in {}", + &self.burn_block.burn_header_hash, self.burn_block.block_height, &prev_block.burn_hash); } } (best_attempt + 1, max_txs) @@ -1838,7 +1842,7 @@ impl BlockMinerThread { }; if let Some((ref microblocks, ref poison_opt)) = µblock_info_opt { - if let Some(ref tail) = microblocks.last() { + if let Some(tail) = microblocks.last() { debug!( "Confirm microblock stream tailed at {} (seq {})", &tail.block_hash(), @@ -1848,8 +1852,7 @@ impl BlockMinerThread { // try and confirm as many microblocks as we can (but note that the stream itself may // be too long; we'll try again if that happens). - stacks_parent_header.microblock_tail = - microblocks.last().clone().map(|blk| blk.header.clone()); + stacks_parent_header.microblock_tail = microblocks.last().map(|blk| blk.header.clone()); if let Some(poison_payload) = poison_opt { debug!("Detected poisoned microblock fork: {:?}", &poison_payload); @@ -1868,7 +1871,7 @@ impl BlockMinerThread { if let Err(e) = mem_pool.miner_submit( chain_state, sortdb, - &parent_consensus_hash, + parent_consensus_hash, &stacks_parent_header.anchored_header.block_hash(), &poison_microblock_tx, Some(&self.event_dispatcher), @@ -1920,6 +1923,7 @@ impl BlockMinerThread { } /// Obtain the target burn fee cap, when considering how well this miner is performing. + #[allow(clippy::too_many_arguments)] pub fn get_mining_spend_amount( config: &Config, keychain: &Keychain, @@ -1974,7 +1978,7 @@ impl BlockMinerThread { else { return config_file_burn_fee_cap; }; - if active_miners_and_commits.len() == 0 { + if active_miners_and_commits.is_empty() { warn!("No active miners detected; using config file burn_fee_cap"); return config_file_burn_fee_cap; } @@ -2009,16 +2013,15 @@ impl BlockMinerThread { let (spend_dist, _total_spend) = MinerStats::get_spend_distribution( &active_miners_and_commits, &unconfirmed_block_commits, - &recipients, + recipients, ); let win_probs = if miner_config.fast_rampup { // look at spends 6+ blocks in the future - let win_probs = MinerStats::get_future_win_distribution( + MinerStats::get_future_win_distribution( &active_miners_and_commits, &unconfirmed_block_commits, - &recipients, - ); - win_probs + recipients, + ) } else { // look at the current spends let Ok(unconfirmed_burn_dist) = miner_stats @@ -2038,8 +2041,7 @@ impl BlockMinerThread { return config_file_burn_fee_cap; }; - let win_probs = MinerStats::burn_dist_to_prob_dist(&unconfirmed_burn_dist); - win_probs + MinerStats::burn_dist_to_prob_dist(&unconfirmed_burn_dist) }; info!("Unconfirmed spend distribution: {:?}", &spend_dist); @@ -2102,6 +2104,7 @@ impl BlockMinerThread { /// Produce the block-commit for this anchored block, if we can. /// Returns the op on success /// Returns None if we fail somehow. + #[allow(clippy::too_many_arguments)] pub fn make_block_commit( &self, burn_db: &mut SortitionDB, @@ -2227,12 +2230,10 @@ impl BlockMinerThread { if let Some(highest_unprocessed_block_sn) = highest_unprocessed_block_sn_opt { if stacks_tip.anchored_header.height() + u64::from(burnchain.pox_constants.prepare_length) - - 1 - >= highest_unprocessed.height + > highest_unprocessed.height && highest_unprocessed_block_sn.block_height + u64::from(burnchain.pox_constants.prepare_length) - - 1 - >= sort_tip.block_height + > sort_tip.block_height { // we're close enough to the chain tip that it's a bad idea for us to mine // -- we'll likely create an orphan @@ -2243,7 +2244,7 @@ impl BlockMinerThread { } } // we can mine - return false; + false } /// Only used in mock signing to generate a peer info view @@ -2301,16 +2302,14 @@ impl BlockMinerThread { // Just wait a min amount of time for the mock signatures to come in while mock_signatures.len() < slot_ids.len() && mock_poll_start.elapsed() < timeout { let chunks = stackerdbs.get_latest_chunks(&signers_contract_id, &slot_ids)?; - for chunk in chunks { - if let Some(chunk) = chunk { - if let Ok(SignerMessage::MockSignature(mock_signature)) = - SignerMessage::consensus_deserialize(&mut chunk.as_slice()) + for chunk in chunks.into_iter().flatten() { + if let Ok(SignerMessage::MockSignature(mock_signature)) = + SignerMessage::consensus_deserialize(&mut chunk.as_slice()) + { + if mock_signature.mock_proposal == *mock_proposal + && !mock_signatures.contains(&mock_signature) { - if mock_signature.mock_proposal == *mock_proposal - && !mock_signatures.contains(&mock_signature) - { - mock_signatures.push(mock_signature); - } + mock_signatures.push(mock_signature); } } } @@ -2325,19 +2324,17 @@ impl BlockMinerThread { StackerDBSession::new(&self.config.node.rpc_bind, miner_contract_id); let miner_slot_ids: Vec<_> = (0..MINER_SLOT_COUNT * 2).collect(); if let Ok(messages) = miners_stackerdb.get_latest_chunks(&miner_slot_ids) { - for message in messages { - if let Some(message) = message { - if message.is_empty() { - continue; - } - let Ok(SignerMessage::MockBlock(mock_block)) = - SignerMessage::consensus_deserialize(&mut message.as_slice()) - else { - continue; - }; - if mock_block.mock_proposal.peer_info == *peer_info { - return true; - } + for message in messages.into_iter().flatten() { + if message.is_empty() { + continue; + } + let Ok(SignerMessage::MockBlock(mock_block)) = + SignerMessage::consensus_deserialize(&mut message.as_slice()) + else { + continue; + }; + if mock_block.mock_proposal.peer_info == *peer_info { + return true; } } } @@ -2939,6 +2936,8 @@ impl RelayerThread { /// have we waited for the right conditions under which to start mining a block off of our /// chain tip? + #[allow(clippy::nonminimal_bool)] + #[allow(clippy::eq_op)] pub fn has_waited_for_latest_blocks(&self) -> bool { // a network download pass took place (self.min_network_download_passes <= self.last_network_download_passes @@ -3022,7 +3021,7 @@ impl RelayerThread { net_receipts.processed_unconfirmed_state.receipts.len(); if num_unconfirmed_microblock_tx_receipts > 0 { if let Some(unconfirmed_state) = self.chainstate_ref().unconfirmed_state.as_ref() { - let canonical_tip = unconfirmed_state.confirmed_chain_tip.clone(); + let canonical_tip = unconfirmed_state.confirmed_chain_tip; self.event_dispatcher.process_new_microblocks( canonical_tip, net_receipts.processed_unconfirmed_state, @@ -3094,7 +3093,7 @@ impl RelayerThread { if !Relayer::static_check_problematic_relayed_block( self.chainstate_ref().mainnet, epoch_id, - &anchored_block, + anchored_block, ASTRules::PrecheckSize, ) { // nope! @@ -3107,7 +3106,7 @@ impl RelayerThread { use std::path::Path; if let Ok(path) = std::env::var("STACKS_BAD_BLOCKS_DIR") { // record this block somewhere - if !fs::metadata(&path).is_ok() { + if fs::metadata(&path).is_err() { fs::create_dir_all(&path) .unwrap_or_else(|_| panic!("FATAL: could not create '{}'", &path)); } @@ -3123,7 +3122,7 @@ impl RelayerThread { r#"{{"block":"{}","consensus":"{}"}}"#, &block_bits_hex, &consensus_hash ); - file.write_all(&block_json.as_bytes()).unwrap_or_else(|_| { + file.write_all(block_json.as_bytes()).unwrap_or_else(|_| { panic!("FATAL: failed to write block bits to '{:?}'", &path) }); info!( @@ -3154,8 +3153,8 @@ impl RelayerThread { chainstate.preprocess_anchored_block( &ic, consensus_hash, - &anchored_block, - &parent_consensus_hash, + anchored_block, + parent_consensus_hash, 0, ) })?; @@ -3283,15 +3282,13 @@ impl RelayerThread { }; // advertize _and_ push blocks for now - let blocks_available = Relayer::load_blocks_available_data( - self.sortdb_ref(), - vec![consensus_hash.clone()], - ) - .expect("Failed to obtain block information for a block we mined."); + let blocks_available = + Relayer::load_blocks_available_data(self.sortdb_ref(), vec![consensus_hash]) + .expect("Failed to obtain block information for a block we mined."); let block_data = { let mut bd = HashMap::new(); - bd.insert(consensus_hash.clone(), mined_block.clone()); + bd.insert(consensus_hash, mined_block.clone()); bd }; @@ -3314,7 +3311,7 @@ impl RelayerThread { ); miner_tip = Self::pick_higher_tip(miner_tip, None); } else { - let ch = snapshot.consensus_hash.clone(); + let ch = snapshot.consensus_hash; let bh = mined_block.block_hash(); let height = mined_block.header.total_work.work; @@ -3391,7 +3388,7 @@ impl RelayerThread { let tenures = if let Some(last_ch) = self.last_tenure_consensus_hash.as_ref() { let mut tenures = vec![]; let last_sn = - SortitionDB::get_block_snapshot_consensus(self.sortdb_ref().conn(), &last_ch) + SortitionDB::get_block_snapshot_consensus(self.sortdb_ref().conn(), last_ch) .expect("FATAL: failed to query sortition DB") .expect("FATAL: unknown prior consensus hash"); @@ -3470,8 +3467,7 @@ impl RelayerThread { .expect("FATAL: failed to query sortition DB") .expect("FATAL: no snapshot for consensus hash"); - let old_last_mined_blocks = - mem::replace(&mut self.last_mined_blocks, MinedBlocks::new()); + let old_last_mined_blocks = mem::take(&mut self.last_mined_blocks); self.last_mined_blocks = Self::clear_stale_mined_blocks(this_burn_tip.block_height, old_last_mined_blocks); @@ -3553,7 +3549,7 @@ impl RelayerThread { /// cost since we won't be mining it anymore. fn setup_microblock_mining_state(&mut self, new_miner_tip: Option) { // update state - let my_miner_tip = std::mem::replace(&mut self.miner_tip, None); + let my_miner_tip = std::mem::take(&mut self.miner_tip); let best_tip = Self::pick_higher_tip(my_miner_tip.clone(), new_miner_tip.clone()); if best_tip == new_miner_tip && best_tip != my_miner_tip { // tip has changed @@ -3597,7 +3593,7 @@ impl RelayerThread { BlockstackOperationType::LeaderKeyRegister(LeaderKeyRegisterOp { public_key: vrf_public_key, memo, - consensus_hash: consensus_hash.clone(), + consensus_hash: *consensus_hash, vtxindex: 0, txid: Txid([0u8; 32]), block_height: 0, @@ -3676,14 +3672,14 @@ impl RelayerThread { /// Create the block miner thread state. /// Only proceeds if all of the following are true: - /// * the miner is not blocked - /// * last_burn_block corresponds to the canonical sortition DB's chain tip - /// * the time of issuance is sufficiently recent - /// * there are no unprocessed stacks blocks in the staging DB - /// * the relayer has already tried a download scan that included this sortition (which, if a - /// block was found, would have placed it into the staging DB and marked it as - /// unprocessed) - /// * a miner thread is not running already + /// * The miner is not blocked + /// * `last_burn_block` corresponds to the canonical sortition DB's chain tip + /// * The time of issuance is sufficiently recent + /// * There are no unprocessed stacks blocks in the staging DB + /// * The relayer has already tried a download scan that included this sortition (which, if a + /// block was found, would have placed it into the staging DB and marked it as + /// unprocessed) + /// * A miner thread is not running already fn create_block_miner( &mut self, registered_key: RegisteredKey, @@ -3724,11 +3720,11 @@ impl RelayerThread { } } - let burn_header_hash = last_burn_block.burn_header_hash.clone(); + let burn_header_hash = last_burn_block.burn_header_hash; let burn_chain_sn = SortitionDB::get_canonical_burn_chain_tip(self.sortdb_ref().conn()) .expect("FATAL: failed to query sortition DB for canonical burn chain tip"); - let burn_chain_tip = burn_chain_sn.burn_header_hash.clone(); + let burn_chain_tip = burn_chain_sn.burn_header_hash; if burn_chain_tip != burn_header_hash { debug!( @@ -3797,6 +3793,7 @@ impl RelayerThread { /// Try to start up a block miner thread with this given VRF key and current burnchain tip. /// Returns true if the thread was started; false if it was not (for any reason) + #[allow(clippy::incompatible_msrv)] pub fn block_miner_thread_try_start( &mut self, registered_key: RegisteredKey, @@ -3898,11 +3895,13 @@ impl RelayerThread { true } - /// Start up a microblock miner thread if we can: - /// * no miner thread must be running already - /// * the miner must not be blocked - /// * we must have won the sortition on the stacks chain tip - /// Returns true if the thread was started; false if not. + /// Start up a microblock miner thread if possible: + /// * No miner thread must be running already + /// * The miner must not be blocked + /// * We must have won the sortition on the Stacks chain tip + /// + /// Returns `true` if the thread was started; `false` if not. + #[allow(clippy::incompatible_msrv)] pub fn microblock_miner_thread_try_start(&mut self) -> bool { let miner_tip = match self.miner_tip.as_ref() { Some(tip) => tip.clone(), @@ -4003,8 +4002,7 @@ impl RelayerThread { last_mined_block.burn_block_height, &self.last_mined_blocks, ) - .len() - == 0 + .is_empty() { // first time we've mined a block in this burnchain block debug!( @@ -4019,8 +4017,8 @@ impl RelayerThread { &last_mined_block.anchored_block.block_hash() ); - let bhh = last_mined_block.burn_hash.clone(); - let orig_bhh = last_mined_block.orig_burn_hash.clone(); + let bhh = last_mined_block.burn_hash; + let orig_bhh = last_mined_block.orig_burn_hash; let tenure_begin = last_mined_block.tenure_begin; self.last_mined_blocks.insert( @@ -4058,7 +4056,7 @@ impl RelayerThread { let num_mblocks = chainstate .unconfirmed_state .as_ref() - .map(|ref unconfirmed| unconfirmed.num_microblocks()) + .map(|unconfirmed| unconfirmed.num_microblocks()) .unwrap_or(0); (processed_unconfirmed_state, num_mblocks) @@ -4134,14 +4132,16 @@ impl RelayerThread { None } - /// Try to join with the miner thread. If we succeed, join the thread and return true. - /// Otherwise, if the thread is still running, return false; + /// Try to join with the miner thread. If successful, join the thread and return `true`. + /// Otherwise, if the thread is still running, return `false`. + /// /// Updates internal state gleaned from the miner, such as: - /// * new stacks block data - /// * new keychain state - /// * new metrics - /// * new unconfirmed state - /// Returns true if joined; false if not. + /// * New Stacks block data + /// * New keychain state + /// * New metrics + /// * New unconfirmed state + /// + /// Returns `true` if joined; `false` if not. pub fn miner_thread_try_join(&mut self) -> bool { if let Some(thread_handle) = self.miner_thread.take() { let new_thread_handle = self.inner_miner_thread_try_join(thread_handle); @@ -4193,7 +4193,7 @@ impl RelayerThread { RelayerDirective::RegisterKey(last_burn_block) => { let mut saved_key_opt = None; if let Some(path) = self.config.miner.activated_vrf_key_path.as_ref() { - saved_key_opt = Self::load_saved_vrf_key(&path); + saved_key_opt = Self::load_saved_vrf_key(path); } if let Some(saved_key) = saved_key_opt { self.globals.resume_leader_key(saved_key); @@ -4266,8 +4266,8 @@ impl ParentStacksBlockInfo { ) -> Result { let stacks_tip_header = StacksChainState::get_anchored_block_header_info( chain_state.db(), - &mine_tip_ch, - &mine_tip_bh, + mine_tip_ch, + mine_tip_bh, ) .unwrap() .ok_or_else(|| { @@ -4358,9 +4358,9 @@ impl ParentStacksBlockInfo { Ok(ParentStacksBlockInfo { stacks_parent_header: stacks_tip_header, - parent_consensus_hash: mine_tip_ch.clone(), + parent_consensus_hash: *mine_tip_ch, parent_block_burn_height: parent_block_height, - parent_block_total_burn: parent_block_total_burn, + parent_block_total_burn, parent_winning_vtxindex, coinbase_nonce, }) @@ -4412,16 +4412,14 @@ impl PeerThread { .make_cost_metric() .unwrap_or_else(|| Box::new(UnitMetric)); - let mempool = MemPoolDB::open( + MemPoolDB::open( config.is_mainnet(), config.burnchain.chain_id, &config.get_chainstate_path_str(), cost_estimator, metric, ) - .expect("Database failure opening mempool"); - - mempool + .expect("Database failure opening mempool") } /// Instantiate the p2p thread. @@ -4531,6 +4529,7 @@ impl PeerThread { /// Run one pass of the p2p/http state machine /// Return true if we should continue running passes; false if not + #[allow(clippy::borrowed_box)] pub fn run_one_pass( &mut self, indexer: &B, @@ -4542,7 +4541,7 @@ impl PeerThread { ) -> bool { // initial block download? let ibd = self.globals.sync_comms.get_ibd(); - let download_backpressure = self.results_with_data.len() > 0; + let download_backpressure = !self.results_with_data.is_empty(); let poll_ms = if !download_backpressure && self.get_network().has_more_downloads() { // keep getting those blocks -- drive the downloader state-machine debug!( @@ -4566,11 +4565,7 @@ impl PeerThread { // NOTE: handler_args must be created such that it outlives the inner net.run() call and // doesn't ref anything within p2p_thread. let handler_args = RPCHandlerArgs { - exit_at_block_height: p2p_thread - .config - .burnchain - .process_exit_at_block_height - .clone(), + exit_at_block_height: p2p_thread.config.burnchain.process_exit_at_block_height, genesis_chainstate_hash: Sha256Sum::from_hex(stx_genesis::GENESIS_CHAINSTATE_HASH) .unwrap(), event_observer: Some(event_dispatcher), @@ -4726,32 +4721,32 @@ impl StacksNode { .make_cost_metric() .unwrap_or_else(|| Box::new(UnitMetric)); - let mempool = MemPoolDB::open( + MemPoolDB::open( config.is_mainnet(), config.burnchain.chain_id, &config.get_chainstate_path_str(), cost_estimator, metric, ) - .expect("BUG: failed to instantiate mempool"); - - mempool + .expect("BUG: failed to instantiate mempool") } - /// Set up the Peer DB and update any soft state from the config file. This includes: - /// * blacklisted/whitelisted nodes - /// * node keys - /// * bootstrap nodes - /// Returns the instantiated PeerDB + /// Set up the Peer DB and update any soft state from the config file. This includes: + /// * Blacklisted/whitelisted nodes + /// * Node keys + /// * Bootstrap nodes + /// + /// Returns the instantiated `PeerDB`. + /// /// Panics on failure. fn setup_peer_db( config: &Config, burnchain: &Burnchain, stackerdb_contract_ids: &[QualifiedContractIdentifier], ) -> PeerDB { - let data_url = UrlString::try_from(format!("{}", &config.node.data_url)).unwrap(); + let data_url = UrlString::try_from(config.node.data_url.to_string()).unwrap(); let initial_neighbors = config.node.bootstrap_node.clone(); - if initial_neighbors.len() > 0 { + if !initial_neighbors.is_empty() { info!( "Will bootstrap from peers {}", VecDisplay(&initial_neighbors) @@ -4778,7 +4773,7 @@ impl StacksNode { config.burnchain.chain_id, burnchain.network_id, Some(node_privkey), - config.connection_options.private_key_lifetime.clone(), + config.connection_options.private_key_lifetime, PeerAddress::from_socketaddr(&p2p_addr), p2p_sock.port(), data_url, @@ -4798,12 +4793,12 @@ impl StacksNode { // allow all bootstrap nodes { - let mut tx = peerdb.tx_begin().unwrap(); + let tx = peerdb.tx_begin().unwrap(); for initial_neighbor in initial_neighbors.iter() { // update peer in case public key changed - PeerDB::update_peer(&mut tx, &initial_neighbor).unwrap(); + PeerDB::update_peer(&tx, initial_neighbor).unwrap(); PeerDB::set_allow_peer( - &mut tx, + &tx, initial_neighbor.addr.network_id, &initial_neighbor.addr.addrbytes, initial_neighbor.addr.port, @@ -4820,10 +4815,10 @@ impl StacksNode { // deny all config-denied peers { - let mut tx = peerdb.tx_begin().unwrap(); + let tx = peerdb.tx_begin().unwrap(); for denied in config.node.deny_nodes.iter() { PeerDB::set_deny_peer( - &mut tx, + &tx, denied.addr.network_id, &denied.addr.addrbytes, denied.addr.port, @@ -4836,9 +4831,9 @@ impl StacksNode { // update services to indicate we can support mempool sync and stackerdb { - let mut tx = peerdb.tx_begin().unwrap(); + let tx = peerdb.tx_begin().unwrap(); PeerDB::set_local_services( - &mut tx, + &tx, (ServiceFlags::RPC as u16) | (ServiceFlags::RELAY as u16) | (ServiceFlags::STACKERDB as u16), @@ -4867,7 +4862,7 @@ impl StacksNode { .expect("Error while loading stacks epochs"); let view = { - let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()) + let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()) .expect("Failed to get sortition tip"); SortitionDB::get_burnchain_view(&sortdb.index_conn(), &burnchain, &sortition_tip) .unwrap() @@ -4914,7 +4909,7 @@ impl StacksNode { _ => panic!("Unable to retrieve local peer"), }; - let p2p_net = PeerNetwork::new( + PeerNetwork::new( peerdb, atlasdb, stackerdbs, @@ -4925,9 +4920,7 @@ impl StacksNode { config.connection_options.clone(), stackerdb_machines, epochs, - ); - - p2p_net + ) } /// Main loop of the relayer. @@ -5223,9 +5216,9 @@ impl StacksNode { .globals .relay_send .send(RelayerDirective::ProcessTenure( - snapshot.consensus_hash.clone(), - snapshot.parent_burn_header_hash.clone(), - snapshot.winning_stacks_block_hash.clone(), + snapshot.consensus_hash, + snapshot.parent_burn_header_hash, + snapshot.winning_stacks_block_hash, )) .is_ok(); } @@ -5270,13 +5263,11 @@ impl StacksNode { block_height, op.apparent_sender, &op.block_header_hash ); last_sortitioned_block = Some((block_snapshot.clone(), op.vtxindex)); - } else { - if self.is_miner { - info!( - "Received burnchain block #{} including block_commit_op - {} ({})", - block_height, op.apparent_sender, &op.block_header_hash - ); - } + } else if self.is_miner { + info!( + "Received burnchain block #{} including block_commit_op - {} ({})", + block_height, op.apparent_sender, &op.block_header_hash + ); } } @@ -5313,7 +5304,7 @@ impl StacksNode { return ret; }; - let mut f = match fs::File::create(&path) { + let mut f = match fs::File::create(path) { Ok(f) => f, Err(e) => { warn!("Failed to create {}: {:?}", &path, &e); @@ -5321,13 +5312,13 @@ impl StacksNode { } }; - if let Err(e) = f.write_all(key_json.as_str().as_bytes()) { + if let Err(e) = f.write_all(key_json.as_bytes()) { warn!("Failed to write activated VRF key to {}: {:?}", &path, &e); return ret; } info!("Saved activated VRF key to {}", &path); - return ret; + ret } /// Join all inner threads diff --git a/testnet/stacks-node/src/node.rs b/testnet/stacks-node/src/node.rs index 1895912ba5..8aebd4814a 100644 --- a/testnet/stacks-node/src/node.rs +++ b/testnet/stacks-node/src/node.rs @@ -151,6 +151,7 @@ pub fn get_names(use_test_chainstate_data: bool) -> Box bool { impl Node { /// Instantiate and initialize a new node, given a config - pub fn new(config: Config, boot_block_exec: Box ()>) -> Self { + pub fn new(config: Config, boot_block_exec: Box) -> Self { let use_test_genesis_data = if config.burnchain.mode == "mocknet" { use_test_genesis_chainstate(&config) } else { @@ -407,14 +408,14 @@ impl Node { Config::assert_valid_epoch_settings(&burnchain, &epochs); let view = { - let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()) + let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()) .expect("Failed to get sortition tip"); SortitionDB::get_burnchain_view(&sortdb.index_conn(), &burnchain, &sortition_tip) .unwrap() }; // create a new peerdb - let data_url = UrlString::try_from(format!("{}", self.config.node.data_url)).unwrap(); + let data_url = UrlString::try_from(self.config.node.data_url.to_string()).unwrap(); let initial_neighbors = self.config.node.bootstrap_node.clone(); @@ -452,7 +453,7 @@ impl Node { self.config.burnchain.chain_id, burnchain.network_id, Some(node_privkey), - self.config.connection_options.private_key_lifetime.clone(), + self.config.connection_options.private_key_lifetime, PeerAddress::from_socketaddr(&p2p_addr), p2p_sock.port(), data_url, @@ -464,10 +465,10 @@ impl Node { println!("DENY NEIGHBORS {:?}", &self.config.node.deny_nodes); { - let mut tx = peerdb.tx_begin().unwrap(); + let tx = peerdb.tx_begin().unwrap(); for denied in self.config.node.deny_nodes.iter() { PeerDB::set_deny_peer( - &mut tx, + &tx, denied.addr.network_id, &denied.addr.addrbytes, denied.addr.port, @@ -488,7 +489,7 @@ impl Node { }; let event_dispatcher = self.event_dispatcher.clone(); - let exit_at_block_height = self.config.burnchain.process_exit_at_block_height.clone(); + let exit_at_block_height = self.config.burnchain.process_exit_at_block_height; let p2p_net = PeerNetwork::new( peerdb, @@ -577,9 +578,9 @@ impl Node { // Registered key has been mined new_key = Some(RegisteredKey { vrf_public_key: op.public_key.clone(), - block_height: op.block_height as u64, - op_vtxindex: op.vtxindex as u32, - target_block_height: (op.block_height as u64) - 1, + block_height: op.block_height, + op_vtxindex: op.vtxindex, + target_block_height: op.block_height - 1, memo: op.memo.clone(), }); } @@ -649,7 +650,7 @@ impl Node { burnchain.pox_constants, ) .expect("Error while opening sortition db"); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()) + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()) .expect("FATAL: failed to query canonical burn chain tip"); // Generates a proof out of the sortition hash provided in the params. @@ -734,7 +735,7 @@ impl Node { anchored_block_from_ongoing_tenure.header.block_hash(), burn_fee, ®istered_key, - &burnchain_tip, + burnchain_tip, VRFSeed::from_proof(&vrf_proof), ); @@ -802,7 +803,7 @@ impl Node { .preprocess_anchored_block( &ic, consensus_hash, - &anchored_block, + anchored_block, &parent_consensus_hash, 0, ) @@ -813,7 +814,7 @@ impl Node { let res = self .chain_state .preprocess_streamed_microblock( - &consensus_hash, + consensus_hash, &anchored_block.block_hash(), microblock, ) @@ -849,31 +850,28 @@ impl Node { match process_blocks_at_tip { Err(e) => panic!("Error while processing block - {:?}", e), Ok(ref mut blocks) => { - if blocks.len() == 0 { + if blocks.is_empty() { break; } else { for block in blocks.iter() { - match block { - (Some(epoch_receipt), _) => { - let attachments_instances = - self.get_attachment_instances(epoch_receipt, &atlas_config); - if !attachments_instances.is_empty() { - for new_attachment in attachments_instances.into_iter() { - if let Err(e) = - atlas_db.queue_attachment_instance(&new_attachment) - { - warn!( - "Atlas: Error writing attachment instance to DB"; - "err" => ?e, - "index_block_hash" => %new_attachment.index_block_hash, - "contract_id" => %new_attachment.contract_id, - "attachment_index" => %new_attachment.attachment_index, - ); - } + if let (Some(epoch_receipt), _) = block { + let attachments_instances = + self.get_attachment_instances(epoch_receipt, &atlas_config); + if !attachments_instances.is_empty() { + for new_attachment in attachments_instances.into_iter() { + if let Err(e) = + atlas_db.queue_attachment_instance(&new_attachment) + { + warn!( + "Atlas: Error writing attachment instance to DB"; + "err" => ?e, + "index_block_hash" => %new_attachment.index_block_hash, + "contract_id" => %new_attachment.contract_id, + "attachment_index" => %new_attachment.attachment_index, + ); } } } - _ => {} } } @@ -990,7 +988,7 @@ impl Node { BlockstackOperationType::LeaderKeyRegister(LeaderKeyRegisterOp { public_key: vrf_public_key, memo: vec![], - consensus_hash: consensus_hash.clone(), + consensus_hash: *consensus_hash, vtxindex: 1, txid, block_height: 0, diff --git a/testnet/stacks-node/src/operations.rs b/testnet/stacks-node/src/operations.rs index 4680098d2b..0109077a5f 100644 --- a/testnet/stacks-node/src/operations.rs +++ b/testnet/stacks-node/src/operations.rs @@ -31,8 +31,7 @@ impl BurnchainOpSigner { } pub fn get_public_key(&mut self) -> Secp256k1PublicKey { - let public_key = Secp256k1PublicKey::from_private(&self.secret_key); - public_key + Secp256k1PublicKey::from_private(&self.secret_key) } pub fn sign_message(&mut self, hash: &[u8]) -> Option { diff --git a/testnet/stacks-node/src/run_loop/boot_nakamoto.rs b/testnet/stacks-node/src/run_loop/boot_nakamoto.rs index 85ace37fa4..2333167334 100644 --- a/testnet/stacks-node/src/run_loop/boot_nakamoto.rs +++ b/testnet/stacks-node/src/run_loop/boot_nakamoto.rs @@ -137,8 +137,8 @@ impl BootRunLoop { /// node depending on the current burnchain height. pub fn start(&mut self, burnchain_opt: Option, mine_start: u64) { match self.active_loop { - InnerLoops::Epoch2(_) => return self.start_from_neon(burnchain_opt, mine_start), - InnerLoops::Epoch3(_) => return self.start_from_naka(burnchain_opt, mine_start), + InnerLoops::Epoch2(_) => self.start_from_neon(burnchain_opt, mine_start), + InnerLoops::Epoch3(_) => self.start_from_naka(burnchain_opt, mine_start), } } @@ -227,7 +227,7 @@ impl BootRunLoop { // if loop exited, do the transition info!("Epoch-3.0 boundary reached, stopping Epoch-2.x run loop"); neon_term_switch.store(false, Ordering::SeqCst); - return true + true }) } diff --git a/testnet/stacks-node/src/run_loop/helium.rs b/testnet/stacks-node/src/run_loop/helium.rs index 2922ce584a..c61581553c 100644 --- a/testnet/stacks-node/src/run_loop/helium.rs +++ b/testnet/stacks-node/src/run_loop/helium.rs @@ -21,10 +21,7 @@ impl RunLoop { } /// Sets up a runloop and node, given a config. - pub fn new_with_boot_exec( - config: Config, - boot_exec: Box ()>, - ) -> Self { + pub fn new_with_boot_exec(config: Config, boot_exec: Box) -> Self { // Build node based on config let node = Node::new(config.clone(), boot_exec); @@ -174,17 +171,14 @@ impl RunLoop { None => None, }; - match artifacts_from_tenure { - Some(ref artifacts) => { - // Have each node receive artifacts from the current tenure - self.node.commit_artifacts( - &artifacts.anchored_block, - &artifacts.parent_block, - &mut burnchain, - artifacts.burn_fee, - ); - } - None => {} + if let Some(artifacts) = &artifacts_from_tenure { + // Have each node receive artifacts from the current tenure + self.node.commit_artifacts( + &artifacts.anchored_block, + &artifacts.parent_block, + &mut burnchain, + artifacts.burn_fee, + ); } let (new_burnchain_tip, _) = burnchain.sync(None)?; diff --git a/testnet/stacks-node/src/run_loop/mod.rs b/testnet/stacks-node/src/run_loop/mod.rs index b2b9aa3f75..ce4c06a16c 100644 --- a/testnet/stacks-node/src/run_loop/mod.rs +++ b/testnet/stacks-node/src/run_loop/mod.rs @@ -37,6 +37,7 @@ macro_rules! info_green { }) } +#[allow(clippy::type_complexity)] pub struct RunLoopCallbacks { on_burn_chain_initialized: Option)>, on_new_burn_chain_state: Option, @@ -45,6 +46,12 @@ pub struct RunLoopCallbacks { on_new_tenure: Option, } +impl Default for RunLoopCallbacks { + fn default() -> Self { + Self::new() + } +} + impl RunLoopCallbacks { pub fn new() -> RunLoopCallbacks { RunLoopCallbacks { @@ -167,7 +174,7 @@ pub fn announce_boot_receipts( event_dispatcher: &mut EventDispatcher, chainstate: &StacksChainState, pox_constants: &PoxConstants, - boot_receipts: &Vec, + boot_receipts: &[StacksTransactionReceipt], ) { let block_header_0 = StacksChainState::get_genesis_header_info(chainstate.db()) .expect("FATAL: genesis block header not stored"); @@ -189,7 +196,7 @@ pub fn announce_boot_receipts( Txid([0x00; 32]), &[], None, - block_header_0.burn_header_hash.clone(), + block_header_0.burn_header_hash, block_header_0.burn_header_height, block_header_0.burn_header_timestamp, &ExecutionCost::zero(), diff --git a/testnet/stacks-node/src/run_loop/nakamoto.rs b/testnet/stacks-node/src/run_loop/nakamoto.rs index 3d94b1c351..de836568d2 100644 --- a/testnet/stacks-node/src/run_loop/nakamoto.rs +++ b/testnet/stacks-node/src/run_loop/nakamoto.rs @@ -100,7 +100,7 @@ impl RunLoop { config, globals: None, coordinator_channels: Some(channels), - counters: counters.unwrap_or_else(|| Counters::new()), + counters: counters.unwrap_or_default(), should_keep_running, event_dispatcher, pox_watchdog: None, @@ -167,9 +167,8 @@ impl RunLoop { if self.config.node.miner { let keychain = Keychain::default(self.config.node.seed.clone()); let mut op_signer = keychain.generate_op_signer(); - match burnchain.create_wallet_if_dne() { - Err(e) => warn!("Error when creating wallet: {:?}", e), - _ => {} + if let Err(e) = burnchain.create_wallet_if_dne() { + warn!("Error when creating wallet: {:?}", e); } let mut btc_addrs = vec![( StacksEpochId::Epoch2_05, @@ -285,7 +284,6 @@ impl RunLoop { let mut atlas_config = AtlasConfig::new(self.config.is_mainnet()); let genesis_attachments = GenesisData::new(use_test_genesis_data) .read_name_zonefiles() - .into_iter() .map(|z| Attachment::new(z.zonefile_content.as_bytes().to_vec())) .collect(); atlas_config.genesis_attachments = Some(genesis_attachments); @@ -296,7 +294,7 @@ impl RunLoop { let moved_atlas_config = self.config.atlas.clone(); let moved_config = self.config.clone(); let moved_burnchain_config = burnchain_config.clone(); - let mut coordinator_dispatcher = self.event_dispatcher.clone(); + let coordinator_dispatcher = self.event_dispatcher.clone(); let atlas_db = AtlasDB::connect( moved_atlas_config.clone(), &self.config.get_atlas_db_file_path(), @@ -325,13 +323,12 @@ impl RunLoop { require_affirmed_anchor_blocks: moved_config .node .require_affirmed_anchor_blocks, - ..ChainsCoordinatorConfig::new() }; ChainsCoordinator::run( coord_config, chain_state_db, moved_burnchain_config, - &mut coordinator_dispatcher, + &coordinator_dispatcher, coordinator_receivers, moved_atlas_config, cost_estimator.as_deref_mut(), @@ -382,7 +379,7 @@ impl RunLoop { Some(sn) => sn, None => { debug!("No canonical stacks chain tip hash present"); - let sn = SortitionDB::get_first_block_snapshot(&sortdb.conn()) + let sn = SortitionDB::get_first_block_snapshot(sortdb.conn()) .expect("BUG: failed to get first-ever block snapshot"); sn } @@ -477,7 +474,7 @@ impl RunLoop { // Make sure at least one sortition has happened, and make sure it's globally available let sortdb = burnchain.sortdb_mut(); let (rc_aligned_height, sn) = - RunLoop::get_reward_cycle_sortition_db_height(&sortdb, &burnchain_config); + RunLoop::get_reward_cycle_sortition_db_height(sortdb, &burnchain_config); let burnchain_tip_snapshot = if sn.block_height == burnchain_config.first_block_height { // need at least one sortition to happen. diff --git a/testnet/stacks-node/src/run_loop/neon.rs b/testnet/stacks-node/src/run_loop/neon.rs index a18a61988b..7be8939d9e 100644 --- a/testnet/stacks-node/src/run_loop/neon.rs +++ b/testnet/stacks-node/src/run_loop/neon.rs @@ -369,9 +369,8 @@ impl RunLoop { if self.config.node.miner { let keychain = Keychain::default(self.config.node.seed.clone()); let mut op_signer = keychain.generate_op_signer(); - match burnchain.create_wallet_if_dne() { - Err(e) => warn!("Error when creating wallet: {:?}", e), - _ => {} + if let Err(e) = burnchain.create_wallet_if_dne() { + warn!("Error when creating wallet: {:?}", e); } let mut btc_addrs = vec![( StacksEpochId::Epoch2_05, @@ -490,14 +489,11 @@ impl RunLoop { burnchain_controller .start(Some(target_burnchain_block_height)) .map_err(|e| { - match e { - Error::CoordinatorClosed => { - if !should_keep_running.load(Ordering::SeqCst) { - info!("Shutdown initiated during burnchain initialization: {}", e); - return burnchain_error::ShutdownInitiated; - } - } - _ => {} + if matches!(e, Error::CoordinatorClosed) + && !should_keep_running.load(Ordering::SeqCst) + { + info!("Shutdown initiated during burnchain initialization: {}", e); + return burnchain_error::ShutdownInitiated; } error!("Burnchain controller stopped: {}", e); panic!(); @@ -581,7 +577,6 @@ impl RunLoop { let mut atlas_config = AtlasConfig::new(self.config.is_mainnet()); let genesis_attachments = GenesisData::new(use_test_genesis_data) .read_name_zonefiles() - .into_iter() .map(|z| Attachment::new(z.zonefile_content.as_bytes().to_vec())) .collect(); atlas_config.genesis_attachments = Some(genesis_attachments); @@ -592,7 +587,7 @@ impl RunLoop { let moved_atlas_config = self.config.atlas.clone(); let moved_config = self.config.clone(); let moved_burnchain_config = burnchain_config.clone(); - let mut coordinator_dispatcher = self.event_dispatcher.clone(); + let coordinator_dispatcher = self.event_dispatcher.clone(); let atlas_db = AtlasDB::connect( moved_atlas_config.clone(), &self.config.get_atlas_db_file_path(), @@ -621,13 +616,12 @@ impl RunLoop { require_affirmed_anchor_blocks: moved_config .node .require_affirmed_anchor_blocks, - ..ChainsCoordinatorConfig::new() }; ChainsCoordinator::run( coord_config, chain_state_db, moved_burnchain_config, - &mut coordinator_dispatcher, + &coordinator_dispatcher, coordinator_receivers, moved_atlas_config, cost_estimator.as_deref_mut(), @@ -685,7 +679,7 @@ impl RunLoop { Some(sn) => sn, None => { debug!("No canonical stacks chain tip hash present"); - let sn = SortitionDB::get_first_block_snapshot(&sortdb.conn()) + let sn = SortitionDB::get_first_block_snapshot(sortdb.conn()) .expect("BUG: failed to get first-ever block snapshot"); sn } @@ -737,7 +731,7 @@ impl RunLoop { let indexer = make_bitcoin_indexer(config, Some(globals.should_keep_running.clone())); let heaviest_affirmation_map = match static_get_heaviest_affirmation_map( - &burnchain, + burnchain, &indexer, &burnchain_db, sortdb, @@ -885,7 +879,7 @@ impl RunLoop { let indexer = make_bitcoin_indexer(config, Some(globals.should_keep_running.clone())); let heaviest_affirmation_map = match static_get_heaviest_affirmation_map( - &burnchain, + burnchain, &indexer, &burnchain_db, sortdb, @@ -899,11 +893,11 @@ impl RunLoop { }; let canonical_affirmation_map = match static_get_canonical_affirmation_map( - &burnchain, + burnchain, &indexer, &burnchain_db, sortdb, - &chain_state_db, + chain_state_db, &sn.sortition_id, ) { Ok(am) => am, @@ -1018,15 +1012,13 @@ impl RunLoop { ) .unwrap(); - let liveness_thread_handle = thread::Builder::new() + thread::Builder::new() .name(format!("chain-liveness-{}", config.node.rpc_bind)) .stack_size(BLOCK_PROCESSOR_STACK_SIZE) .spawn(move || { Self::drive_chain_liveness(globals, config, burnchain, sortdb, chain_state_db) }) - .expect("FATAL: failed to spawn chain liveness thread"); - - liveness_thread_handle + .expect("FATAL: failed to spawn chain liveness thread") } /// Starts the node runloop. @@ -1109,7 +1101,7 @@ impl RunLoop { // Make sure at least one sortition has happened, and make sure it's globally available let sortdb = burnchain.sortdb_mut(); let (rc_aligned_height, sn) = - RunLoop::get_reward_cycle_sortition_db_height(&sortdb, &burnchain_config); + RunLoop::get_reward_cycle_sortition_db_height(sortdb, &burnchain_config); let burnchain_tip_snapshot = if sn.block_height == burnchain_config.first_block_height { // need at least one sortition to happen. @@ -1137,7 +1129,7 @@ impl RunLoop { .tx_begin() .expect("FATAL: failed to begin burnchain DB tx"); for (reward_cycle, affirmation) in self.config.burnchain.affirmation_overrides.iter() { - tx.set_override_affirmation_map(*reward_cycle, affirmation.clone()).expect(&format!("FATAL: failed to set affirmation override ({affirmation}) for reward cycle {reward_cycle}")); + tx.set_override_affirmation_map(*reward_cycle, affirmation.clone()).unwrap_or_else(|_| panic!("FATAL: failed to set affirmation override ({affirmation}) for reward cycle {reward_cycle}")); } tx.commit() .expect("FATAL: failed to commit burnchain DB tx"); diff --git a/testnet/stacks-node/src/stacks_events.rs b/testnet/stacks-node/src/stacks_events.rs index f63b17a6ab..2f96bbfe66 100644 --- a/testnet/stacks-node/src/stacks_events.rs +++ b/testnet/stacks-node/src/stacks_events.rs @@ -92,7 +92,7 @@ fn handle_connection(mut stream: TcpStream) { contents ); - stream.write(response.as_bytes()).unwrap(); + let _nmb_bytes = stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); } } diff --git a/testnet/stacks-node/src/syncctl.rs b/testnet/stacks-node/src/syncctl.rs index ff68126a83..d4c05ec7fe 100644 --- a/testnet/stacks-node/src/syncctl.rs +++ b/testnet/stacks-node/src/syncctl.rs @@ -69,7 +69,7 @@ impl PoxSyncWatchdogComms { self.interruptable_sleep(1)?; std::hint::spin_loop(); } - return Ok(true); + Ok(true) } fn interruptable_sleep(&self, secs: u64) -> Result<(), burnchain_error> { @@ -95,7 +95,7 @@ impl PoxSyncWatchdogComms { self.interruptable_sleep(1)?; std::hint::spin_loop(); } - return Ok(true); + Ok(true) } pub fn should_keep_running(&self) -> bool { @@ -192,7 +192,7 @@ impl PoxSyncWatchdog { new_processed_blocks: VecDeque::new(), last_attachable_query: 0, last_processed_query: 0, - max_samples: max_samples, + max_samples, max_staging: 10, watch_start_ts: 0, last_block_processed_ts: 0, @@ -200,7 +200,7 @@ impl PoxSyncWatchdog { estimated_block_process_time: 5.0, steady_state_burnchain_sync_interval: burnchain_poll_time, steady_state_resync_ts: 0, - chainstate: chainstate, + chainstate, relayer_comms: watchdog_comms, }) } @@ -213,7 +213,7 @@ impl PoxSyncWatchdog { fn count_attachable_stacks_blocks(&mut self) -> Result { // number of staging blocks that have arrived since the last sortition let cnt = StacksChainState::count_attachable_staging_blocks( - &self.chainstate.db(), + self.chainstate.db(), self.max_staging, self.last_attachable_query, ) @@ -229,7 +229,7 @@ impl PoxSyncWatchdog { fn count_processed_stacks_blocks(&mut self) -> Result { // number of staging blocks that have arrived since the last sortition let cnt = StacksChainState::count_processed_staging_blocks( - &self.chainstate.db(), + self.chainstate.db(), self.max_staging, self.last_processed_query, ) @@ -281,7 +281,7 @@ impl PoxSyncWatchdog { /// Is a derivative approximately flat, with a maximum absolute deviation from 0? /// Return whether or not the sample is mostly flat, and how many points were over the given /// error bar in either direction. - fn is_mostly_flat(deriv: &Vec, error: i64) -> (bool, usize) { + fn is_mostly_flat(deriv: &[i64], error: i64) -> (bool, usize) { let mut total_deviates = 0; let mut ret = true; for d in deriv.iter() { @@ -294,7 +294,7 @@ impl PoxSyncWatchdog { } /// low and high pass filter average -- take average without the smallest and largest values - fn hilo_filter_avg(samples: &Vec) -> f64 { + fn hilo_filter_avg(samples: &[i64]) -> f64 { // take average with low and high pass let mut min = i64::MAX; let mut max = i64::MIN; @@ -358,7 +358,7 @@ impl PoxSyncWatchdog { } let block_wait_times = - StacksChainState::measure_block_wait_time(&chainstate.db(), start_height, end_height) + StacksChainState::measure_block_wait_time(chainstate.db(), start_height, end_height) .expect("BUG: failed to query chainstate block-processing times"); PoxSyncWatchdog::hilo_filter_avg(&block_wait_times) @@ -386,7 +386,7 @@ impl PoxSyncWatchdog { } let block_download_times = StacksChainState::measure_block_download_time( - &chainstate.db(), + chainstate.db(), start_height, end_height, ) diff --git a/testnet/stacks-node/src/tenure.rs b/testnet/stacks-node/src/tenure.rs index 5dd67cddab..7322133889 100644 --- a/testnet/stacks-node/src/tenure.rs +++ b/testnet/stacks-node/src/tenure.rs @@ -41,7 +41,8 @@ pub struct Tenure { parent_block_total_burn: u64, } -impl<'a> Tenure { +impl Tenure { + #[allow(clippy::too_many_arguments)] pub fn new( parent_block: ChainTip, coinbase_tx: StacksTransaction, @@ -82,7 +83,7 @@ impl<'a> Tenure { elapsed = Instant::now().duration_since(self.burnchain_tip.received_at); } - let (mut chain_state, _) = StacksChainState::open( + let (chain_state, _) = StacksChainState::open( self.config.is_mainnet(), self.config.burnchain.chain_id, &self.config.get_chainstate_path_str(), @@ -91,13 +92,13 @@ impl<'a> Tenure { .unwrap(); let (anchored_block, _, _) = StacksBlockBuilder::build_anchored_block( - &mut chain_state, + &chain_state, burn_dbconn, &mut self.mem_pool, &self.parent_block.metadata, self.parent_block_total_burn, self.vrf_proof.clone(), - self.microblock_pubkeyhash.clone(), + self.microblock_pubkeyhash, &self.coinbase_tx, BlockBuilderSettings::limited(), None, diff --git a/testnet/stacks-node/src/tests/bitcoin_regtest.rs b/testnet/stacks-node/src/tests/bitcoin_regtest.rs index 90b1310183..702f6d5953 100644 --- a/testnet/stacks-node/src/tests/bitcoin_regtest.rs +++ b/testnet/stacks-node/src/tests/bitcoin_regtest.rs @@ -43,21 +43,18 @@ impl BitcoinCoreController { fn add_rpc_cli_args(&self, command: &mut Command) { command.arg(format!("-rpcport={}", self.config.burnchain.rpc_port)); - match ( + if let (Some(username), Some(password)) = ( &self.config.burnchain.username, &self.config.burnchain.password, ) { - (Some(username), Some(password)) => { - command - .arg(format!("-rpcuser={username}")) - .arg(format!("-rpcpassword={password}")); - } - _ => {} + command + .arg(format!("-rpcuser={username}")) + .arg(format!("-rpcpassword={password}")); } } pub fn start_bitcoind(&mut self) -> BitcoinResult<()> { - std::fs::create_dir_all(&self.config.get_burnchain_path_str()).unwrap(); + std::fs::create_dir_all(self.config.get_burnchain_path_str()).unwrap(); let mut command = Command::new("bitcoind"); command @@ -104,7 +101,7 @@ impl BitcoinCoreController { } pub fn stop_bitcoind(&mut self) -> Result<(), BitcoinCoreError> { - if let Some(_) = self.bitcoind_process.take() { + if self.bitcoind_process.take().is_some() { let payload = BitcoinRPCRequest { method: "stop".to_string(), params: vec![], @@ -217,11 +214,11 @@ fn bitcoind_integration(segwit_flag: bool) { .callbacks .on_new_burn_chain_state(|round, burnchain_tip, chain_tip| { let block = &burnchain_tip.block_snapshot; - let expected_total_burn = BITCOIND_INT_TEST_COMMITS * (round as u64 + 1); + let expected_total_burn = BITCOIND_INT_TEST_COMMITS * (round + 1); assert_eq!(block.total_burn, expected_total_burn); - assert_eq!(block.sortition, true); - assert_eq!(block.num_sortitions, round as u64 + 1); - assert_eq!(block.block_height, round as u64 + 2003); + assert!(block.sortition); + assert_eq!(block.num_sortitions, round + 1); + assert_eq!(block.block_height, round + 2003); let leader_key = "f888e0cab5c16de8edf72b544a189ece5c0b95cd9178606c970789ac71d17bb4"; match round { @@ -246,7 +243,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert!(op.parent_vtxindex == 0); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } } @@ -270,7 +267,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert_eq!(op.parent_block_ptr, 2003); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } @@ -299,7 +296,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert_eq!(op.parent_block_ptr, 2004); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } @@ -328,7 +325,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert_eq!(op.parent_block_ptr, 2005); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } @@ -357,7 +354,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert_eq!(op.parent_block_ptr, 2006); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } @@ -386,7 +383,7 @@ fn bitcoind_integration(segwit_flag: bool) { assert_eq!(op.parent_block_ptr, 2007); assert_eq!(op.burn_fee, BITCOIND_INT_TEST_COMMITS); } - _ => assert!(false), + _ => panic!("Unexpected operation"), } } @@ -464,7 +461,6 @@ fn bitcoind_integration(segwit_flag: bool) { }, _ => {} }; - return }); // Use block's hook for asserting expectations diff --git a/testnet/stacks-node/src/tests/epoch_205.rs b/testnet/stacks-node/src/tests/epoch_205.rs index 076a5f61f3..6fe0018ced 100644 --- a/testnet/stacks-node/src/tests/epoch_205.rs +++ b/testnet/stacks-node/src/tests/epoch_205.rs @@ -19,9 +19,7 @@ use stacks::core::{ PEER_VERSION_EPOCH_2_05, PEER_VERSION_EPOCH_2_1, }; use stacks_common::codec::StacksMessageCodec; -use stacks_common::types::chainstate::{ - BlockHeaderHash, BurnchainHeaderHash, StacksAddress, VRFSeed, -}; +use stacks_common::types::chainstate::{BlockHeaderHash, BurnchainHeaderHash, VRFSeed}; use stacks_common::util::hash::hex_bytes; use stacks_common::util::sleep_ms; @@ -50,7 +48,7 @@ fn test_exact_block_costs() { let spender_sk = StacksPrivateKey::new(); let spender_addr = PrincipalData::from(to_addr(&spender_sk)); - let spender_addr_c32 = StacksAddress::from(to_addr(&spender_sk)); + let spender_addr_c32 = to_addr(&spender_sk); let epoch_205_transition_height = 210; let transactions_to_broadcast = 25; @@ -256,10 +254,8 @@ fn test_exact_block_costs() { if dbget_txs.len() >= 2 { processed_txs_before_205 = true; } - } else { - if dbget_txs.len() >= 2 { - processed_txs_after_205 = true; - } + } else if dbget_txs.len() >= 2 { + processed_txs_after_205 = true; } assert_eq!(mined_anchor_cost, anchor_cost as u64); @@ -287,7 +283,7 @@ fn test_dynamic_db_method_costs() { let spender_sk = StacksPrivateKey::new(); let spender_addr = PrincipalData::from(to_addr(&spender_sk)); - let spender_addr_c32 = StacksAddress::from(to_addr(&spender_sk)); + let spender_addr_c32 = to_addr(&spender_sk); let contract_name = "test-contract"; let epoch_205_transition_height = 210; @@ -455,8 +451,7 @@ fn test_dynamic_db_method_costs() { .as_i64() .unwrap(); eprintln!( - "Burn height = {}, runtime_cost = {}, function_name = {}", - burn_height, runtime_cost, function_name + "Burn height = {burn_height}, runtime_cost = {runtime_cost}, function_name = {function_name}" ); if function_name == "db-get1" { @@ -569,21 +564,20 @@ fn transition_empty_blocks() { ) .unwrap(); let res = StacksChainState::block_crosses_epoch_boundary( - &chainstate.db(), + chainstate.db(), &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip, ) .unwrap(); debug!( - "Epoch transition at {} ({}/{}) height {}: {}", + "Epoch transition at {} ({}/{}) height {}: {res}", &StacksBlockHeader::make_index_block_hash( &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip ), &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip, - tip_info.burn_block_height, - res + tip_info.burn_block_height ); if tip_info.burn_block_height == epoch_2_05 { @@ -831,7 +825,7 @@ fn test_cost_limit_switch_version205() { &test_observer::get_blocks(), |transaction| match &transaction.payload { TransactionPayload::SmartContract(contract, ..) => { - contract.name == ContractName::try_from("increment-contract").unwrap() + contract.name == ContractName::from("increment-contract") } _ => false, }, @@ -847,7 +841,7 @@ fn test_cost_limit_switch_version205() { 0, 1000, conf.burnchain.chain_id, - &creator_addr.into(), + &creator_addr, "increment-contract", "increment-many", &[], @@ -863,7 +857,7 @@ fn test_cost_limit_switch_version205() { &test_observer::get_blocks(), |transaction| match &transaction.payload { TransactionPayload::ContractCall(contract) => { - contract.contract_name == ContractName::try_from("increment-contract").unwrap() + contract.contract_name == ContractName::from("increment-contract") } _ => false, }, @@ -882,7 +876,7 @@ fn test_cost_limit_switch_version205() { 0, 1000, conf.burnchain.chain_id, - &creator_addr.into(), + &creator_addr, "increment-contract", "increment-many", &[], @@ -897,7 +891,7 @@ fn test_cost_limit_switch_version205() { &test_observer::get_blocks(), |transaction| match &transaction.payload { TransactionPayload::ContractCall(contract) => { - contract.contract_name == ContractName::try_from("increment-contract").unwrap() + contract.contract_name == ContractName::from("increment-contract") } _ => false, }, @@ -916,10 +910,7 @@ fn bigger_microblock_streams_in_2_05() { return; } - let spender_sks: Vec<_> = (0..10) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..10).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -993,7 +984,7 @@ fn bigger_microblock_streams_in_2_05() { 0, 1049230, conf.burnchain.chain_id, - &format!("large-{}", ix), + &format!("large-{ix}"), &format!(" ;; a single one of these transactions consumes over half the runtime budget (define-constant BUFF_TO_BYTE (list @@ -1035,9 +1026,8 @@ fn bigger_microblock_streams_in_2_05() { ) ) (begin - (crash-me \"{}\")) - ", - &format!("large-contract-{}", &ix) + (crash-me \"large-contract-{ix}\")) + " ) ) }) @@ -1176,9 +1166,9 @@ fn bigger_microblock_streams_in_2_05() { let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); if let TransactionPayload::SmartContract(tsc, ..) = parsed.payload { - if tsc.name.to_string().find("costs-2").is_some() { + if tsc.name.to_string().contains("costs-2") { in_205 = true; - } else if tsc.name.to_string().find("large").is_some() { + } else if tsc.name.to_string().contains("large") { num_big_microblock_txs += 1; if in_205 { total_big_txs_per_microblock_205 += 1; @@ -1209,7 +1199,7 @@ fn bigger_microblock_streams_in_2_05() { max_big_txs_per_microblock_20 = num_big_microblock_txs; } - eprintln!("Epoch size: {:?}", &total_execution_cost); + eprintln!("Epoch size: {total_execution_cost:?}"); if !in_205 && total_execution_cost.exceeds(&epoch_20_stream_cost) { epoch_20_stream_cost = total_execution_cost; @@ -1232,21 +1222,13 @@ fn bigger_microblock_streams_in_2_05() { } eprintln!( - "max_big_txs_per_microblock_20: {}, total_big_txs_per_microblock_20: {}", - max_big_txs_per_microblock_20, total_big_txs_per_microblock_20 - ); - eprintln!( - "max_big_txs_per_microblock_205: {}, total_big_txs_per_microblock_205: {}", - max_big_txs_per_microblock_205, total_big_txs_per_microblock_205 - ); - eprintln!( - "confirmed stream execution in 2.0: {:?}", - &epoch_20_stream_cost + "max_big_txs_per_microblock_20: {max_big_txs_per_microblock_20}, total_big_txs_per_microblock_20: {total_big_txs_per_microblock_20}" ); eprintln!( - "confirmed stream execution in 2.05: {:?}", - &epoch_205_stream_cost + "max_big_txs_per_microblock_205: {max_big_txs_per_microblock_205}, total_big_txs_per_microblock_205: {total_big_txs_per_microblock_205}" ); + eprintln!("confirmed stream execution in 2.0: {epoch_20_stream_cost:?}"); + eprintln!("confirmed stream execution in 2.05: {epoch_205_stream_cost:?}"); // stuff happened assert!(epoch_20_stream_cost.runtime > 0); diff --git a/testnet/stacks-node/src/tests/epoch_21.rs b/testnet/stacks-node/src/tests/epoch_21.rs index 8f6c466318..ebe14bae16 100644 --- a/testnet/stacks-node/src/tests/epoch_21.rs +++ b/testnet/stacks-node/src/tests/epoch_21.rs @@ -1,6 +1,7 @@ use std::collections::{HashMap, HashSet}; use std::{env, thread}; +use ::core::str; use clarity::vm::types::{PrincipalData, QualifiedContractIdentifier}; use clarity::vm::ClarityVersion; use stacks::burnchains::bitcoin::address::{ @@ -46,7 +47,7 @@ use crate::tests::neon_integrations::*; use crate::tests::*; use crate::{neon, BitcoinRegtestController, BurnchainController, Keychain}; -const MINER_BURN_PUBLIC_KEY: &'static str = +const MINER_BURN_PUBLIC_KEY: &str = "03dc62fe0b8964d01fc9ca9a5eec0e22e557a12cc656919e648f04e0b26fea5faa"; fn advance_to_2_1( @@ -210,7 +211,7 @@ fn advance_to_2_1( ) .unwrap(); let res = StacksChainState::block_crosses_epoch_boundary( - &chainstate.db(), + chainstate.db(), &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip, ) @@ -264,13 +265,13 @@ fn advance_to_2_1( assert_eq!(account.nonce, 9); eprintln!("Begin Stacks 2.1"); - return ( + ( conf, btcd_controller, btc_regtest_controller, blocks_processed, channel, - ); + ) } #[test] @@ -285,7 +286,7 @@ fn transition_adds_burn_block_height() { let spender_sk = StacksPrivateKey::new(); let spender_addr = PrincipalData::from(to_addr(&spender_sk)); - let spender_addr_c32 = StacksAddress::from(to_addr(&spender_sk)); + let spender_addr_c32 = to_addr(&spender_sk); let (conf, _btcd_controller, mut btc_regtest_controller, blocks_processed, coord_channel) = advance_to_2_1( @@ -411,9 +412,8 @@ fn transition_adds_burn_block_height() { // strip leading `0x` eprintln!("{:#?}", &cev); let clarity_serialized_value = hex_bytes( - &String::from_utf8( - cev.get("raw_value").unwrap().as_str().unwrap().as_bytes()[2..] - .to_vec(), + str::from_utf8( + &cev.get("raw_value").unwrap().as_str().unwrap().as_bytes()[2..], ) .unwrap(), ) @@ -544,7 +544,7 @@ fn transition_fixes_bitcoin_rigidity() { let spender_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_stx_addr: StacksAddress = to_addr(&spender_sk); - let spender_addr: PrincipalData = spender_stx_addr.clone().into(); + let spender_addr: PrincipalData = spender_stx_addr.into(); let _spender_btc_addr = BitcoinAddress::from_bytes_legacy( BitcoinNetworkType::Regtest, LegacyBitcoinAddressType::PublicKeyHash, @@ -554,7 +554,7 @@ fn transition_fixes_bitcoin_rigidity() { let spender_2_sk = StacksPrivateKey::from_hex(SK_2).unwrap(); let spender_2_stx_addr: StacksAddress = to_addr(&spender_2_sk); - let spender_2_addr: PrincipalData = spender_2_stx_addr.clone().into(); + let spender_2_addr: PrincipalData = spender_2_stx_addr.into(); let epoch_2_05 = 210; let epoch_2_1 = 215; @@ -655,7 +655,7 @@ fn transition_fixes_bitcoin_rigidity() { // okay, let's send a pre-stx op for a transfer-stx op that will get mined before the 2.1 epoch let pre_stx_op = PreStxOp { - output: spender_stx_addr.clone(), + output: spender_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -687,8 +687,8 @@ fn transition_fixes_bitcoin_rigidity() { let recipient_sk = StacksPrivateKey::new(); let recipient_addr = to_addr(&recipient_sk); let transfer_stx_op = TransferStxOp { - sender: spender_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_stx_addr, + recipient: recipient_addr, transfered_ustx: 100_000, memo: vec![], // to be filled in @@ -698,7 +698,7 @@ fn transition_fixes_bitcoin_rigidity() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_sk, false); assert!( btc_regtest_controller @@ -728,7 +728,7 @@ fn transition_fixes_bitcoin_rigidity() { ) .unwrap(); let res = StacksChainState::block_crosses_epoch_boundary( - &chainstate.db(), + chainstate.db(), &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip, ) @@ -812,7 +812,7 @@ fn transition_fixes_bitcoin_rigidity() { // okay, let's send a pre-stx op. let pre_stx_op = PreStxOp { - output: spender_stx_addr.clone(), + output: spender_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -840,8 +840,8 @@ fn transition_fixes_bitcoin_rigidity() { let recipient_sk = StacksPrivateKey::new(); let recipient_addr = to_addr(&recipient_sk); let transfer_stx_op = TransferStxOp { - sender: spender_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_stx_addr, + recipient: recipient_addr, transfered_ustx: 100_000, memo: vec![], // to be filled in @@ -851,7 +851,7 @@ fn transition_fixes_bitcoin_rigidity() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_sk, false); assert!( btc_regtest_controller @@ -885,7 +885,7 @@ fn transition_fixes_bitcoin_rigidity() { // okay, let's send a pre-stx op. let pre_stx_op = PreStxOp { - output: spender_2_stx_addr.clone(), + output: spender_2_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -914,8 +914,8 @@ fn transition_fixes_bitcoin_rigidity() { // let's fire off our transfer op. let transfer_stx_op = TransferStxOp { - sender: spender_2_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_2_stx_addr, + recipient: recipient_addr, transfered_ustx: 100_000, memo: vec![], // to be filled in @@ -925,7 +925,7 @@ fn transition_fixes_bitcoin_rigidity() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_2_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_2_sk, false); btc_regtest_controller .submit_manual( @@ -952,7 +952,7 @@ fn transition_fixes_bitcoin_rigidity() { // let's fire off another transfer op that will fall outside the window let pre_stx_op = PreStxOp { - output: spender_2_stx_addr.clone(), + output: spender_2_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -980,8 +980,8 @@ fn transition_fixes_bitcoin_rigidity() { }; let transfer_stx_op = TransferStxOp { - sender: spender_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_stx_addr, + recipient: recipient_addr, transfered_ustx: 123, memo: vec![], // to be filled in @@ -991,7 +991,7 @@ fn transition_fixes_bitcoin_rigidity() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_2_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_2_sk, false); btc_regtest_controller .submit_manual( @@ -1070,11 +1070,7 @@ fn transition_adds_get_pox_addr_recipients() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let (conf, _btcd_controller, mut btc_regtest_controller, blocks_processed, coord_channel) = advance_to_2_1(initial_balances, None, Some(pox_constants.clone()), false); @@ -1094,7 +1090,7 @@ fn transition_adds_get_pox_addr_recipients() { .iter() .enumerate() { - let spender_sk = spender_sks[i].clone(); + let spender_sk = spender_sks[i]; let pox_addr_tuple = execute( &format!( "{{ hashbytes: 0x{}, version: 0x{:02x} }}", @@ -1126,9 +1122,8 @@ fn transition_adds_get_pox_addr_recipients() { } // stack some STX to segwit addressses - for i in 4..7 { - let spender_sk = spender_sks[i].clone(); - let pubk = Secp256k1PublicKey::from_private(&spender_sk); + for (i, spender_sk) in spender_sks.iter().enumerate().take(7).skip(4) { + let pubk = Secp256k1PublicKey::from_private(spender_sk); let version = i as u8; let bytes = match i { 4 => { @@ -1147,7 +1142,7 @@ fn transition_adds_get_pox_addr_recipients() { .unwrap() .unwrap(); let tx = make_contract_call( - &spender_sk, + spender_sk, 0, 300, conf.burnchain.chain_id, @@ -1183,7 +1178,7 @@ fn transition_adds_get_pox_addr_recipients() { ) "; - let spender_addr_c32 = StacksAddress::from(to_addr(&spender_sks[0])); + let spender_addr_c32 = to_addr(&spender_sks[0]); let contract_tx = make_contract_publish( &spender_sks[0], 1, @@ -1202,9 +1197,7 @@ fn transition_adds_get_pox_addr_recipients() { // mine through two reward cycles // now let's mine until the next reward cycle starts ... - while sort_height - < (stack_sort_height as u64) + (((2 * pox_constants.reward_cycle_length) + 1) as u64) - { + while sort_height < stack_sort_height + (((2 * pox_constants.reward_cycle_length) + 1) as u64) { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = coord_channel.get_sortitions_processed(); eprintln!("Sort height: {}", sort_height); @@ -1244,13 +1237,12 @@ fn transition_adds_get_pox_addr_recipients() { let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); if parsed.txid() == cc_txid { // check events for this block - for (_i, event) in events.iter().enumerate() { + for event in events.iter() { if let Some(cev) = event.get("contract_event") { // strip leading `0x` let clarity_serialized_value = hex_bytes( - &String::from_utf8( - cev.get("raw_value").unwrap().as_str().unwrap().as_bytes()[2..] - .to_vec(), + str::from_utf8( + &cev.get("raw_value").unwrap().as_str().unwrap().as_bytes()[2..], ) .unwrap(), ) @@ -1313,9 +1305,10 @@ fn transition_adds_get_pox_addr_recipients() { for pox_addr_value in pox_addr_tuples.into_iter() { let pox_addr = - PoxAddress::try_from_pox_tuple(false, &pox_addr_value).expect( - &format!("FATAL: invalid PoX tuple {:?}", &pox_addr_value), - ); + PoxAddress::try_from_pox_tuple(false, &pox_addr_value) + .unwrap_or_else(|| { + panic!("FATAL: invalid PoX tuple {pox_addr_value:?}") + }); eprintln!("at {}: {:?}", burn_block_height, &pox_addr); if !pox_addr.is_burn() { found_pox_addrs.insert(pox_addr); @@ -1388,7 +1381,7 @@ fn transition_adds_mining_from_segwit() { let utxos = btc_regtest_controller .get_all_utxos(&Secp256k1PublicKey::from_hex(MINER_BURN_PUBLIC_KEY).unwrap()); - assert!(utxos.len() > 0); + assert!(!utxos.is_empty()); // all UTXOs should be segwit for utxo in utxos.iter() { @@ -1428,7 +1421,7 @@ fn transition_adds_mining_from_segwit() { SortitionDB::get_block_commits_by_block(sortdb.conn(), &tip.sortition_id).unwrap(); assert_eq!(commits.len(), 1); - let txid = commits[0].txid.clone(); + let txid = commits[0].txid; let tx = btc_regtest_controller.get_raw_transaction(&txid); eprintln!("tx = {:?}", &tx); @@ -1462,11 +1455,7 @@ fn transition_removes_pox_sunset() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -1518,8 +1507,8 @@ fn transition_removes_pox_sunset() { 4 * prepare_phase_len / 5, 5, 15, - (sunset_start_rc * reward_cycle_len - 1).into(), - (sunset_end_rc * reward_cycle_len).into(), + sunset_start_rc * reward_cycle_len - 1, + sunset_end_rc * reward_cycle_len, (epoch_21 as u32) + 1, u32::MAX, u32::MAX, @@ -1573,11 +1562,8 @@ fn transition_removes_pox_sunset() { let pox_info = get_pox_info(&http_origin).unwrap(); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); - assert_eq!(pox_info.current_cycle.is_pox_active, false); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); + assert!(!pox_info.current_cycle.is_pox_active); assert_eq!(pox_info.next_cycle.stacked_ustx, 0); let tx = make_contract_call( @@ -1617,11 +1603,8 @@ fn transition_removes_pox_sunset() { // pox must activate let pox_info = get_pox_info(&http_origin).unwrap(); eprintln!("pox_info in pox-1 = {:?}", &pox_info); - assert_eq!(pox_info.current_cycle.is_pox_active, true); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); + assert!(pox_info.current_cycle.is_pox_active); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); // advance to 2.1 while sort_height <= epoch_21 + 1 { @@ -1636,11 +1619,8 @@ fn transition_removes_pox_sunset() { // though the v1 block height has passed, the pox-2 contract won't be managing reward sets // until the next reward cycle eprintln!("pox_info in pox-2 = {:?}", &pox_info); - assert_eq!(pox_info.current_cycle.is_pox_active, true); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox-2") - ); + assert!(pox_info.current_cycle.is_pox_active); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox-2"); // re-stack let tx = make_contract_call( @@ -1677,7 +1657,7 @@ fn transition_removes_pox_sunset() { ); let pox_info = get_pox_info(&http_origin).unwrap(); - assert_eq!(pox_info.current_cycle.is_pox_active, true); + assert!(pox_info.current_cycle.is_pox_active); // get pox back online while sort_height <= epoch_21 + reward_cycle_len { @@ -1688,13 +1668,10 @@ fn transition_removes_pox_sunset() { let pox_info = get_pox_info(&http_origin).unwrap(); eprintln!("pox_info = {:?}", &pox_info); - assert_eq!(pox_info.current_cycle.is_pox_active, true); + assert!(pox_info.current_cycle.is_pox_active); // first full reward cycle with pox-2 - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox-2") - ); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox-2"); let burn_blocks = test_observer::get_burn_blocks(); let mut pox_out_opt = None; @@ -1719,9 +1696,9 @@ fn transition_removes_pox_sunset() { if (i as u64) < (sunset_start_rc * reward_cycle_len) { // before sunset - if recipients.len() >= 1 { + if !recipients.is_empty() { for (_, amt) in recipients.into_iter() { - pox_out_opt = if let Some(pox_out) = pox_out_opt.clone() { + pox_out_opt = if let Some(pox_out) = pox_out_opt { Some(std::cmp::max(amt, pox_out)) } else { Some(amt) @@ -1730,16 +1707,16 @@ fn transition_removes_pox_sunset() { } } else if (i as u64) >= (sunset_start_rc * reward_cycle_len) && (i as u64) + 1 < epoch_21 { // some sunset burn happened - let pox_out = pox_out_opt.clone().unwrap(); - if recipients.len() >= 1 { + let pox_out = pox_out_opt.unwrap(); + if !recipients.is_empty() { for (_, amt) in recipients.into_iter() { assert!(amt < pox_out); } } } else if (i as u64) + 1 >= epoch_21 { // no sunset burn happened - let pox_out = pox_out_opt.clone().unwrap(); - if recipients.len() >= 1 { + let pox_out = pox_out_opt.unwrap(); + if !recipients.is_empty() { for (_, amt) in recipients.into_iter() { // NOTE: odd number of reward cycles if !burnchain_config.is_in_prepare_phase((i + 2) as u64) { @@ -1875,7 +1852,7 @@ fn transition_empty_blocks() { ) .unwrap(); let res = StacksChainState::block_crosses_epoch_boundary( - &chainstate.db(), + chainstate.db(), &tip_info.stacks_tip_consensus_hash, &tip_info.stacks_tip, ) @@ -1987,7 +1964,7 @@ pub fn wait_pox_stragglers(confs: &[Config], max_stacks_tip: u64, block_time_ms: let mut stacks_tip_bhh = None; for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.stacks_tip_height < max_stacks_tip { @@ -2057,15 +2034,9 @@ fn test_pox_reorgs_three_flaps() { epochs[3].start_height = 151; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -2112,7 +2083,7 @@ fn test_pox_reorgs_three_flaps() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -2134,12 +2105,11 @@ fn test_pox_reorgs_three_flaps() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -2151,8 +2121,8 @@ fn test_pox_reorgs_three_flaps() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -2187,10 +2157,10 @@ fn test_pox_reorgs_three_flaps() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -2215,8 +2185,8 @@ fn test_pox_reorgs_three_flaps() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -2238,10 +2208,10 @@ fn test_pox_reorgs_three_flaps() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); if tip_info.stacks_tip_height > 0 { @@ -2250,11 +2220,7 @@ fn test_pox_reorgs_three_flaps() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -2264,19 +2230,14 @@ fn test_pox_reorgs_three_flaps() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -2311,11 +2272,9 @@ fn test_pox_reorgs_three_flaps() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -2325,7 +2284,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -2344,7 +2303,7 @@ fn test_pox_reorgs_three_flaps() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -2353,7 +2312,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); //assert_eq!(tip_info.affirmations.heaviest, AffirmationMap::decode("nnnnnnnnnnnnnnnnnnnnp").unwrap()); @@ -2374,7 +2333,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2386,7 +2345,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -2399,7 +2358,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2411,7 +2370,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history overtakes miner 0's. @@ -2428,7 +2387,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2440,7 +2399,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history continues to overtake miner 0's. @@ -2457,7 +2416,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2469,7 +2428,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 0 may have won here, but its affirmation map isn't yet the heaviest. @@ -2484,7 +2443,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2496,7 +2455,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 0's affirmation map now becomes the heaviest. @@ -2511,7 +2470,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2524,7 +2483,7 @@ fn test_pox_reorgs_three_flaps() { info!("####################### end of cycle ##############################"); let mut max_stacks_tip = 0; for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 0's affirmation map is now the heaviest, and there's no longer a tie. @@ -2538,7 +2497,7 @@ fn test_pox_reorgs_three_flaps() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2554,7 +2513,7 @@ fn test_pox_reorgs_three_flaps() { // nodes now agree on affirmation maps for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -2599,15 +2558,9 @@ fn test_pox_reorg_one_flap() { epochs[3].start_height = 151; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -2654,7 +2607,7 @@ fn test_pox_reorg_one_flap() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -2674,12 +2627,11 @@ fn test_pox_reorg_one_flap() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -2691,8 +2643,8 @@ fn test_pox_reorg_one_flap() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -2727,10 +2679,10 @@ fn test_pox_reorg_one_flap() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -2755,8 +2707,8 @@ fn test_pox_reorg_one_flap() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -2778,10 +2730,10 @@ fn test_pox_reorg_one_flap() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner {}: {:?}\n\n", i, &tip_info); if tip_info.stacks_tip_height > 0 { @@ -2790,11 +2742,7 @@ fn test_pox_reorg_one_flap() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -2804,19 +2752,14 @@ fn test_pox_reorg_one_flap() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -2851,11 +2794,9 @@ fn test_pox_reorg_one_flap() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -2865,7 +2806,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -2884,7 +2825,7 @@ fn test_pox_reorg_one_flap() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -2893,7 +2834,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -2912,7 +2853,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2924,7 +2865,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -2937,7 +2878,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2950,7 +2891,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); let mut max_stacks_tip = 0; for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history overtakes miner 0's. @@ -2966,7 +2907,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -2982,7 +2923,7 @@ fn test_pox_reorg_one_flap() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -3025,15 +2966,9 @@ fn test_pox_reorg_flap_duel() { epochs[3].start_height = 151; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -3080,7 +3015,7 @@ fn test_pox_reorg_flap_duel() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -3102,12 +3037,12 @@ fn test_pox_reorg_flap_duel() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); - confs[i].node.set_bootstrap_nodes( + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -3119,8 +3054,8 @@ fn test_pox_reorg_flap_duel() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -3155,10 +3090,10 @@ fn test_pox_reorg_flap_duel() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -3183,8 +3118,8 @@ fn test_pox_reorg_flap_duel() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -3206,10 +3141,10 @@ fn test_pox_reorg_flap_duel() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); if tip_info.stacks_tip_height > 0 { @@ -3218,11 +3153,7 @@ fn test_pox_reorg_flap_duel() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -3232,19 +3163,14 @@ fn test_pox_reorg_flap_duel() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -3279,11 +3205,9 @@ fn test_pox_reorg_flap_duel() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -3293,7 +3217,7 @@ fn test_pox_reorg_flap_duel() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -3312,7 +3236,7 @@ fn test_pox_reorg_flap_duel() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -3321,7 +3245,7 @@ fn test_pox_reorg_flap_duel() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); //assert_eq!(tip_info.affirmations.heaviest, AffirmationMap::decode("nnnnnnnnnnnnnnnnnnnnp").unwrap()); @@ -3349,7 +3273,7 @@ fn test_pox_reorg_flap_duel() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); max_stacks_tip = std::cmp::max(tip_info.stacks_tip_height, max_stacks_tip); } @@ -3362,7 +3286,7 @@ fn test_pox_reorg_flap_duel() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -3375,7 +3299,7 @@ fn test_pox_reorg_flap_duel() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -3387,7 +3311,7 @@ fn test_pox_reorg_flap_duel() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history overtakes miner 0's. @@ -3404,7 +3328,7 @@ fn test_pox_reorg_flap_duel() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -3423,7 +3347,7 @@ fn test_pox_reorg_flap_duel() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -3465,15 +3389,9 @@ fn test_pox_reorg_flap_reward_cycles() { epochs[3].start_height = 151; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -3520,7 +3438,7 @@ fn test_pox_reorg_flap_reward_cycles() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -3540,12 +3458,11 @@ fn test_pox_reorg_flap_reward_cycles() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -3557,8 +3474,8 @@ fn test_pox_reorg_flap_reward_cycles() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in confs.iter() { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -3593,10 +3510,10 @@ fn test_pox_reorg_flap_reward_cycles() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -3621,8 +3538,8 @@ fn test_pox_reorg_flap_reward_cycles() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -3644,10 +3561,10 @@ fn test_pox_reorg_flap_reward_cycles() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); if tip_info.stacks_tip_height > 0 { @@ -3656,11 +3573,7 @@ fn test_pox_reorg_flap_reward_cycles() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -3670,19 +3583,14 @@ fn test_pox_reorg_flap_reward_cycles() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -3717,11 +3625,9 @@ fn test_pox_reorg_flap_reward_cycles() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -3731,7 +3637,7 @@ fn test_pox_reorg_flap_reward_cycles() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -3750,7 +3656,7 @@ fn test_pox_reorg_flap_reward_cycles() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -3759,7 +3665,7 @@ fn test_pox_reorg_flap_reward_cycles() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -3785,7 +3691,7 @@ fn test_pox_reorg_flap_reward_cycles() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); max_stacks_tip = std::cmp::max(tip_info.stacks_tip_height, max_stacks_tip); } @@ -3794,7 +3700,7 @@ fn test_pox_reorg_flap_reward_cycles() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -3808,7 +3714,7 @@ fn test_pox_reorg_flap_reward_cycles() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } } @@ -3816,7 +3722,7 @@ fn test_pox_reorg_flap_reward_cycles() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history overtakes miner 0's. @@ -3833,7 +3739,7 @@ fn test_pox_reorg_flap_reward_cycles() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -3852,7 +3758,7 @@ fn test_pox_reorg_flap_reward_cycles() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -3897,15 +3803,9 @@ fn test_pox_missing_five_anchor_blocks() { epochs[3].start_height = 151; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -3952,7 +3852,7 @@ fn test_pox_missing_five_anchor_blocks() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -3972,12 +3872,11 @@ fn test_pox_missing_five_anchor_blocks() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -3989,8 +3888,8 @@ fn test_pox_missing_five_anchor_blocks() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -4025,10 +3924,10 @@ fn test_pox_missing_five_anchor_blocks() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -4053,8 +3952,8 @@ fn test_pox_missing_five_anchor_blocks() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -4076,10 +3975,10 @@ fn test_pox_missing_five_anchor_blocks() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); if tip_info.stacks_tip_height > 0 { @@ -4088,11 +3987,7 @@ fn test_pox_missing_five_anchor_blocks() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -4102,19 +3997,14 @@ fn test_pox_missing_five_anchor_blocks() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -4149,11 +4039,9 @@ fn test_pox_missing_five_anchor_blocks() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -4163,7 +4051,7 @@ fn test_pox_missing_five_anchor_blocks() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -4182,7 +4070,7 @@ fn test_pox_missing_five_anchor_blocks() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -4191,7 +4079,7 @@ fn test_pox_missing_five_anchor_blocks() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -4212,7 +4100,7 @@ fn test_pox_missing_five_anchor_blocks() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -4223,7 +4111,7 @@ fn test_pox_missing_five_anchor_blocks() { signal_mining_ready(miner_status[1].clone()); info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); max_stacks_tip = std::cmp::max(tip_info.stacks_tip_height, max_stacks_tip); } @@ -4236,7 +4124,7 @@ fn test_pox_missing_five_anchor_blocks() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -4253,7 +4141,7 @@ fn test_pox_missing_five_anchor_blocks() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -4297,15 +4185,9 @@ fn test_sortition_divergence_pre_21() { epochs[3].start_height = 241; conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -4352,7 +4234,7 @@ fn test_sortition_divergence_pre_21() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -4376,12 +4258,11 @@ fn test_sortition_divergence_pre_21() { } let node_privkey_1 = Secp256k1PrivateKey::from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -4393,8 +4274,8 @@ fn test_sortition_divergence_pre_21() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -4429,10 +4310,10 @@ fn test_sortition_divergence_pre_21() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -4457,8 +4338,8 @@ fn test_sortition_divergence_pre_21() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -4480,10 +4361,10 @@ fn test_sortition_divergence_pre_21() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); if tip_info.stacks_tip_height > 0 { @@ -4492,11 +4373,7 @@ fn test_sortition_divergence_pre_21() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -4506,19 +4383,14 @@ fn test_sortition_divergence_pre_21() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -4553,11 +4425,9 @@ fn test_sortition_divergence_pre_21() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { + for (cnt, tx) in stacking_txs.iter().enumerate() { eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + submit_tx(&http_origin, tx); } // run a reward cycle @@ -4567,7 +4437,7 @@ fn test_sortition_divergence_pre_21() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -4586,7 +4456,7 @@ fn test_sortition_divergence_pre_21() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -4595,7 +4465,7 @@ fn test_sortition_divergence_pre_21() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -4616,7 +4486,7 @@ fn test_sortition_divergence_pre_21() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -4645,7 +4515,7 @@ fn test_sortition_divergence_pre_21() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); max_stacks_tip = std::cmp::max(tip_info.stacks_tip_height, max_stacks_tip); } @@ -4657,14 +4527,14 @@ fn test_sortition_divergence_pre_21() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } } info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); max_stacks_tip = std::cmp::max(tip_info.stacks_tip_height, max_stacks_tip); } @@ -4678,7 +4548,7 @@ fn test_sortition_divergence_pre_21() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } } @@ -4690,7 +4560,7 @@ fn test_sortition_divergence_pre_21() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -4706,7 +4576,7 @@ fn test_sortition_divergence_pre_21() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } @@ -4722,7 +4592,7 @@ fn trait_invocation_cross_epoch() { let spender_sk = StacksPrivateKey::new(); let spender_addr = PrincipalData::from(to_addr(&spender_sk)); - let spender_addr_c32 = StacksAddress::from(to_addr(&spender_sk)); + let spender_addr_c32 = to_addr(&spender_sk); let trait_contract = "(define-trait simple-method ((foo (uint) (response uint uint)) ))"; let impl_contract = @@ -4907,7 +4777,7 @@ fn trait_invocation_cross_epoch() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); } - let interesting_txids = vec![ + let interesting_txids = [ invoke_txid.clone(), invoke_1_txid.clone(), invoke_2_txid.clone(), @@ -4988,21 +4858,13 @@ fn test_v1_unlock_height_with_current_stackers() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let (mut conf, _) = neon_integration_test_conf(); @@ -5200,12 +5062,10 @@ fn test_v1_unlock_height_with_current_stackers() { assert_eq!(addr_tuple, pox_addr_tuple_1); } } - } else { - if !burnchain_config.is_in_prepare_phase(height) { - assert_eq!(pox_addrs.len(), 2); - for addr_tuple in pox_addrs { - assert_eq!(addr_tuple, pox_addr_tuple_2); - } + } else if !burnchain_config.is_in_prepare_phase(height) { + assert_eq!(pox_addrs.len(), 2); + for addr_tuple in pox_addrs { + assert_eq!(addr_tuple, pox_addr_tuple_2); } } } @@ -5251,21 +5111,13 @@ fn test_v1_unlock_height_with_delay_and_current_stackers() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let (mut conf, _) = neon_integration_test_conf(); @@ -5475,7 +5327,7 @@ fn test_v1_unlock_height_with_delay_and_current_stackers() { if !burnchain_config.is_in_prepare_phase(height) { let mut have_expected_payout = false; if height < epoch_2_1 + (reward_cycle_len as u64) { - if pox_addrs.len() > 0 { + if !pox_addrs.is_empty() { assert_eq!(pox_addrs.len(), 2); for addr_tuple in pox_addrs { // can either pay to pox tuple 1, or burn @@ -5485,15 +5337,13 @@ fn test_v1_unlock_height_with_delay_and_current_stackers() { } } } - } else { - if pox_addrs.len() > 0 { - assert_eq!(pox_addrs.len(), 2); - for addr_tuple in pox_addrs { - // can either pay to pox tuple 2, or burn - assert_ne!(addr_tuple, pox_addr_tuple_1); - if addr_tuple == pox_addr_tuple_2 { - have_expected_payout = true; - } + } else if !pox_addrs.is_empty() { + assert_eq!(pox_addrs.len(), 2); + for addr_tuple in pox_addrs { + // can either pay to pox tuple 2, or burn + assert_ne!(addr_tuple, pox_addr_tuple_1); + if addr_tuple == pox_addr_tuple_2 { + have_expected_payout = true; } } } diff --git a/testnet/stacks-node/src/tests/epoch_22.rs b/testnet/stacks-node/src/tests/epoch_22.rs index 9bffca7c8a..774a83f712 100644 --- a/testnet/stacks-node/src/tests/epoch_22.rs +++ b/testnet/stacks-node/src/tests/epoch_22.rs @@ -58,7 +58,7 @@ fn disable_pox() { let epoch_2_2 = 255; // two blocks before next prepare phase. let stacked = 100_000_000_000 * (core::MICROSTACKS_PER_STACKS as u64); - let increase_by = 1_000_0000 * (core::MICROSTACKS_PER_STACKS as u64); + let increase_by = 10_000_000 * (core::MICROSTACKS_PER_STACKS as u64); let spender_sk = StacksPrivateKey::new(); let spender_addr: PrincipalData = to_addr(&spender_sk).into(); @@ -92,31 +92,19 @@ fn disable_pox() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let pox_pubkey_3 = Secp256k1PublicKey::from_hex( "0317782e663c77fb02ebf46a3720f41a70f5678ad185974a456d35848e275fe56b", ) .unwrap(); - let pox_pubkey_hash_3 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_3) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_3 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_3).to_bytes()); let (mut conf, _) = neon_integration_test_conf(); @@ -397,9 +385,9 @@ fn disable_pox() { .block_height_to_reward_cycle(burnchain_config.first_block_height, height) .unwrap(); - if !reward_cycle_pox_addrs.contains_key(&reward_cycle) { - reward_cycle_pox_addrs.insert(reward_cycle, HashMap::new()); - } + reward_cycle_pox_addrs + .entry(reward_cycle) + .or_insert_with(HashMap::new); let iconn = sortdb.index_handle_at_block(&chainstate, &tip).unwrap(); let pox_addrs = chainstate @@ -420,37 +408,35 @@ fn disable_pox() { .unwrap(); debug!("Test burnchain height {}", height); - if !burnchain_config.is_in_prepare_phase(height) { - if pox_addrs.len() > 0 { - assert_eq!(pox_addrs.len(), 2); - let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); - let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); - - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if !burnchain_config.is_in_prepare_phase(height) && !pox_addrs.is_empty() { + assert_eq!(pox_addrs.len(), 2); + let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); + let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); + + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_0) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_0) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_0, 1); - } + .insert(pox_addr_0, 1); + } - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_1) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_1) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_1, 1); - } + .insert(pox_addr_1, 1); } } } @@ -522,7 +508,7 @@ fn disable_pox() { for (pox_addr, slots) in cycle_counts.iter() { assert_eq!( *slots, - expected_slots[&reward_cycle][&pox_addr], + expected_slots[&reward_cycle][pox_addr], "The number of expected slots for PoX address {} in reward cycle {} is mismatched with the actual count.", &pox_addr, reward_cycle, @@ -544,8 +530,7 @@ fn disable_pox() { let parsed = StacksTransaction::consensus_deserialize(&mut tx_bytes.as_slice()).unwrap(); let tx_sender = PrincipalData::from(parsed.auth.origin().address_testnet()); - if &tx_sender == &spender_addr - && parsed.auth.get_origin_nonce() == aborted_increase_nonce + if tx_sender == spender_addr && parsed.auth.get_origin_nonce() == aborted_increase_nonce { let contract_call = match &parsed.payload { TransactionPayload::ContractCall(cc) => cc, @@ -626,31 +611,19 @@ fn pox_2_unlock_all() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let pox_pubkey_3 = Secp256k1PublicKey::from_hex( "0317782e663c77fb02ebf46a3720f41a70f5678ad185974a456d35848e275fe56b", ) .unwrap(); - let pox_pubkey_hash_3 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_3) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_3 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_3).to_bytes()); let (mut conf, _) = neon_integration_test_conf(); @@ -892,7 +865,7 @@ fn pox_2_unlock_all() { // in bitcoin block epoch_2_2 - 1, so `nonce_of_2_1_unlock_ht_call` // will be included in that bitcoin block. // this will build the last block before 2.2 activates - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let tx = make_contract_call( &spender_sk, @@ -913,19 +886,19 @@ fn pox_2_unlock_all() { // in bitcoin block epoch_2_2, so `nonce_of_2_2_unlock_ht_call` // will be included in that bitcoin block. // this block activates 2.2 - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // this *burn block* is when the unlock occurs - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // and this will mine the first block whose parent is the unlock block - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let spender_1_account = get_account(&http_origin, &spender_addr); let spender_2_account = get_account(&http_origin, &spender_2_addr); - info!("spender_1_account = {:?}", spender_1_account); - info!("spender_2_account = {:?}", spender_1_account); + info!("spender_1_account = {spender_1_account:?}"); + info!("spender_2_account = {spender_2_account:?}"); assert_eq!( spender_1_account.balance as u64, @@ -943,7 +916,7 @@ fn pox_2_unlock_all() { assert_eq!( spender_2_account.balance as u64, - spender_2_initial_balance - stacked - (1 * tx_fee), + spender_2_initial_balance - stacked - tx_fee, "Spender 2 should still be locked" ); assert_eq!( @@ -957,13 +930,13 @@ fn pox_2_unlock_all() { // and this will mice the bitcoin block containing the first block whose parent has >= unlock burn block // (which is the criterion for the unlock) - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let spender_1_account = get_account(&http_origin, &spender_addr); let spender_2_account = get_account(&http_origin, &spender_2_addr); - info!("spender_1_account = {:?}", spender_1_account); - info!("spender_2_account = {:?}", spender_1_account); + info!("spender_1_account = {spender_1_account:?}"); + info!("spender_2_account = {spender_2_account:?}"); assert_eq!( spender_1_account.balance, @@ -978,7 +951,7 @@ fn pox_2_unlock_all() { assert_eq!( spender_2_account.balance, - spender_2_initial_balance as u128 - (1 * tx_fee as u128), + spender_2_initial_balance as u128 - tx_fee as u128, "Spender 2 should be unlocked" ); assert_eq!(spender_2_account.locked, 0, "Spender 2 should be unlocked"); @@ -1001,16 +974,16 @@ fn pox_2_unlock_all() { submit_tx(&http_origin, &tx); // this wakes up the node to mine the transaction - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // this block selects the previously mined block - next_block_and_wait(&mut &mut btc_regtest_controller, &blocks_processed); + next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let spender_1_account = get_account(&http_origin, &spender_addr); let spender_2_account = get_account(&http_origin, &spender_2_addr); let spender_3_account = get_account(&http_origin, &spender_3_addr); - info!("spender_1_account = {:?}", spender_1_account); - info!("spender_2_account = {:?}", spender_1_account); + info!("spender_1_account = {spender_1_account:?}"); + info!("spender_2_account = {spender_2_account:?}"); assert_eq!( spender_3_account.balance, 1_000_000, @@ -1038,7 +1011,7 @@ fn pox_2_unlock_all() { assert_eq!( spender_2_account.balance, - spender_2_initial_balance as u128 - (1 * tx_fee as u128), + spender_2_initial_balance as u128 - tx_fee as u128, "Spender 2 should be unlocked" ); assert_eq!(spender_2_account.locked, 0, "Spender 2 should be unlocked"); @@ -1080,9 +1053,9 @@ fn pox_2_unlock_all() { .block_height_to_reward_cycle(burnchain_config.first_block_height, height) .unwrap(); - if !reward_cycle_pox_addrs.contains_key(&reward_cycle) { - reward_cycle_pox_addrs.insert(reward_cycle, HashMap::new()); - } + reward_cycle_pox_addrs + .entry(reward_cycle) + .or_insert_with(HashMap::new); let iconn = sortdb.index_handle_at_block(&chainstate, &tip).unwrap(); let pox_addrs = chainstate @@ -1103,37 +1076,35 @@ fn pox_2_unlock_all() { .unwrap(); debug!("Test burnchain height {}", height); - if !burnchain_config.is_in_prepare_phase(height) { - if pox_addrs.len() > 0 { - assert_eq!(pox_addrs.len(), 2); - let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); - let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); - - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if !burnchain_config.is_in_prepare_phase(height) && !pox_addrs.is_empty() { + assert_eq!(pox_addrs.len(), 2); + let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); + let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); + + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_0) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_0) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_0, 1); - } + .insert(pox_addr_0, 1); + } - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_1) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_1) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_1, 1); - } + .insert(pox_addr_1, 1); } } } @@ -1191,7 +1162,7 @@ fn pox_2_unlock_all() { for (pox_addr, slots) in cycle_counts.iter() { assert_eq!( *slots, - expected_slots[&reward_cycle][&pox_addr], + expected_slots[&reward_cycle][pox_addr], "The number of expected slots for PoX address {} in reward cycle {} is mismatched with the actual count.", &pox_addr, reward_cycle, @@ -1215,7 +1186,7 @@ fn pox_2_unlock_all() { let parsed = StacksTransaction::consensus_deserialize(&mut tx_bytes.as_slice()).unwrap(); let tx_sender = PrincipalData::from(parsed.auth.origin().address_testnet()); - if &tx_sender == &spender_addr + if tx_sender == spender_addr && parsed.auth.get_origin_nonce() == nonce_of_2_2_unlock_ht_call { let contract_call = match &parsed.payload { @@ -1231,7 +1202,7 @@ fn pox_2_unlock_all() { assert_eq!(result.to_string(), format!("(ok u{})", epoch_2_2 + 1)); unlock_ht_22_tested = true; } - if &tx_sender == &spender_addr + if tx_sender == spender_addr && parsed.auth.get_origin_nonce() == nonce_of_2_1_unlock_ht_call { let contract_call = match &parsed.payload { @@ -1303,15 +1274,9 @@ fn test_pox_reorg_one_flap() { epochs.truncate(5); conf_template.burnchain.epochs = Some(epochs); - let privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); - let stack_privks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let stack_privks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() @@ -1358,7 +1323,7 @@ fn test_pox_reorg_one_flap() { conf.node.wait_time_for_blocks = conf_template.node.wait_time_for_blocks; conf.burnchain.max_rbf = conf_template.burnchain.max_rbf; conf.burnchain.epochs = conf_template.burnchain.epochs.clone(); - conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation.clone(); + conf.burnchain.pox_2_activation = conf_template.burnchain.pox_2_activation; conf.node.require_affirmed_anchor_blocks = conf_template.node.require_affirmed_anchor_blocks; @@ -1379,12 +1344,11 @@ fn test_pox_reorg_one_flap() { let node_privkey_1 = StacksNode::make_node_private_key_from_seed(&confs[0].node.local_peer_seed); - for i in 1..num_miners { - let chain_id = confs[0].burnchain.chain_id; - let peer_version = confs[0].burnchain.peer_version; - let p2p_bind = confs[0].node.p2p_bind.clone(); - - confs[i].node.set_bootstrap_nodes( + let chain_id = confs[0].burnchain.chain_id; + let peer_version = confs[0].burnchain.peer_version; + let p2p_bind = confs[0].node.p2p_bind.clone(); + for conf in confs.iter_mut().skip(1) { + conf.node.set_bootstrap_nodes( format!( "{}@{}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), @@ -1396,8 +1360,8 @@ fn test_pox_reorg_one_flap() { } // use short reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let pox_constants = PoxConstants::new( reward_cycle_len, prepare_phase_len, @@ -1432,10 +1396,10 @@ fn test_pox_reorg_one_flap() { btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -1460,8 +1424,8 @@ fn test_pox_reorg_one_flap() { let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -1483,10 +1447,10 @@ fn test_pox_reorg_one_flap() { ); } - for i in 1..num_miners { + for (i, conf) in confs.iter().enumerate().skip(1) { eprintln!("\n\nBoot miner {}\n\n", i); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { eprintln!("\n\nMiner {}: {:?}\n\n", i, &tip_info); if tip_info.stacks_tip_height > 0 { @@ -1495,11 +1459,7 @@ fn test_pox_reorg_one_flap() { } else { eprintln!("\n\nWaiting for miner {}...\n\n", i); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -1509,19 +1469,14 @@ fn test_pox_reorg_one_flap() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let sort_height = channels[0].get_sortitions_processed(); // make everyone stack let stacking_txs: Vec<_> = stack_privks .iter() - .enumerate() - .map(|(_i, pk)| { + .map(|pk| { make_contract_call( pk, 0, @@ -1533,7 +1488,7 @@ fn test_pox_reorg_one_flap() { &[ Value::UInt(2_000_000_000_000_000 - 30_000_000), execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash), + &format!("{{ hashbytes: 0x{pox_pubkey_hash}, version: 0x00 }}"), ClarityVersion::Clarity1, ) .unwrap() @@ -1556,11 +1511,9 @@ fn test_pox_reorg_one_flap() { .collect(); // everyone locks up - let mut cnt = 0; - for tx in stacking_txs { - eprintln!("\n\nSubmit stacking tx {}\n\n", &cnt); - submit_tx(&http_origin, &tx); - cnt += 1; + for (cnt, tx) in stacking_txs.iter().enumerate() { + eprintln!("\n\nSubmit stacking tx {cnt}\n\n"); + submit_tx(&http_origin, tx); } // run a reward cycle @@ -1570,7 +1523,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); if tip_info.burn_block_height == 220 { at_220 = true; @@ -1589,7 +1542,7 @@ fn test_pox_reorg_one_flap() { } for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); assert!(tip_info.burn_block_height <= 220); } @@ -1598,7 +1551,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -1617,7 +1570,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -1629,7 +1582,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } info!("####################### end of cycle ##############################"); @@ -1642,7 +1595,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -1655,7 +1608,7 @@ fn test_pox_reorg_one_flap() { info!("####################### end of cycle ##############################"); let mut max_stacks_tip = 0; for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); // miner 1's history overtakes miner 0's. @@ -1671,7 +1624,7 @@ fn test_pox_reorg_one_flap() { sleep_ms(block_time_ms); for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Tip for miner {}: {:?}", i, &tip_info); } @@ -1687,7 +1640,7 @@ fn test_pox_reorg_one_flap() { // nodes now agree on stacks affirmation map for (i, c) in confs.iter().enumerate() { - let tip_info = get_chain_info(&c); + let tip_info = get_chain_info(c); info!("Final tip for miner {}: {:?}", i, &tip_info); } } diff --git a/testnet/stacks-node/src/tests/epoch_23.rs b/testnet/stacks-node/src/tests/epoch_23.rs index 2355f7521d..a0cbbfe876 100644 --- a/testnet/stacks-node/src/tests/epoch_23.rs +++ b/testnet/stacks-node/src/tests/epoch_23.rs @@ -52,7 +52,7 @@ fn trait_invocation_behavior() { let spender_addr: PrincipalData = to_addr(&spender_sk).into(); let impl_contract_id = - QualifiedContractIdentifier::new(contract_addr.clone().into(), "impl-simple".into()); + QualifiedContractIdentifier::new(contract_addr.into(), "impl-simple".into()); let mut spender_nonce = 0; let fee_amount = 10_000; @@ -526,7 +526,7 @@ fn trait_invocation_behavior() { let parsed = StacksTransaction::consensus_deserialize(&mut tx_bytes.as_slice()).unwrap(); let tx_sender = PrincipalData::from(parsed.auth.origin().address_testnet()); - if &tx_sender == &spender_addr { + if tx_sender == spender_addr { let contract_call = match &parsed.payload { TransactionPayload::ContractCall(cc) => cc, // only interested in contract calls @@ -583,29 +583,27 @@ fn trait_invocation_behavior() { assert_eq!(&transaction_receipts[&tx_nonce].1.to_string(), "(ok u0)"); } - for tx_nonce in [expected_good_23_3_nonce] { - assert_eq!( - transaction_receipts[&tx_nonce].0.contract_name.as_str(), - "wrap-simple" - ); - assert_eq!( - transaction_receipts[&tx_nonce].0.function_name.as_str(), - "invocation-1" - ); - assert_eq!(&transaction_receipts[&tx_nonce].1.to_string(), "(ok u0)"); - } + let tx_nonce = expected_good_23_3_nonce; + assert_eq!( + transaction_receipts[&tx_nonce].0.contract_name.as_str(), + "wrap-simple" + ); + assert_eq!( + transaction_receipts[&tx_nonce].0.function_name.as_str(), + "invocation-1" + ); + assert_eq!(&transaction_receipts[&tx_nonce].1.to_string(), "(ok u0)"); - for tx_nonce in [expected_good_23_4_nonce] { - assert_eq!( - transaction_receipts[&tx_nonce].0.contract_name.as_str(), - "wrap-simple" - ); - assert_eq!( - transaction_receipts[&tx_nonce].0.function_name.as_str(), - "invocation-2" - ); - assert_eq!(&transaction_receipts[&tx_nonce].1.to_string(), "(ok u0)"); - } + let tx_nonce = expected_good_23_4_nonce; + assert_eq!( + transaction_receipts[&tx_nonce].0.contract_name.as_str(), + "wrap-simple" + ); + assert_eq!( + transaction_receipts[&tx_nonce].0.function_name.as_str(), + "invocation-2" + ); + assert_eq!(&transaction_receipts[&tx_nonce].1.to_string(), "(ok u0)"); for tx_nonce in [expected_bad_22_1_nonce, expected_bad_22_3_nonce] { assert_eq!( diff --git a/testnet/stacks-node/src/tests/epoch_24.rs b/testnet/stacks-node/src/tests/epoch_24.rs index 26ad007ca7..e39255678d 100644 --- a/testnet/stacks-node/src/tests/epoch_24.rs +++ b/testnet/stacks-node/src/tests/epoch_24.rs @@ -55,9 +55,9 @@ pub fn get_reward_set_entries_at_block( ) -> Result, Error> { state .get_reward_addresses(burnchain, sortdb, burn_block_height, block_id) - .and_then(|mut addrs| { + .map(|mut addrs| { addrs.sort_by_key(|k| k.reward_address.bytes()); - Ok(addrs) + addrs }) } @@ -86,7 +86,7 @@ fn fix_to_pox_contract() { let pox_3_activation_height = epoch_2_4; let stacked = 100_000_000_000 * (core::MICROSTACKS_PER_STACKS as u64); - let increase_by = 1_000_0000 * (core::MICROSTACKS_PER_STACKS as u64); + let increase_by = 10_000_000 * (core::MICROSTACKS_PER_STACKS as u64); let spender_sk = StacksPrivateKey::new(); let spender_addr: PrincipalData = to_addr(&spender_sk).into(); @@ -110,31 +110,19 @@ fn fix_to_pox_contract() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let pox_pubkey_3 = Secp256k1PublicKey::from_hex( "0317782e663c77fb02ebf46a3720f41a70f5678ad185974a456d35848e275fe56b", ) .unwrap(); - let pox_pubkey_hash_3 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_3) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_3 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_3).to_bytes()); let (mut conf, _) = neon_integration_test_conf(); @@ -341,13 +329,13 @@ fn fix_to_pox_contract() { &[Value::UInt(5000)], ); - info!("Submit 2.2 stack-increase tx to {:?}", &http_origin); + info!("Submit 2.2 stack-increase tx to {http_origin:?}"); submit_tx(&http_origin, &tx); // transition to epoch 2.3 loop { let tip_info = get_chain_info(&conf); - if tip_info.burn_block_height >= epoch_2_3 + 1 { + if tip_info.burn_block_height > epoch_2_3 { break; } next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); @@ -367,7 +355,7 @@ fn fix_to_pox_contract() { &[Value::UInt(5000)], ); - info!("Submit 2.3 stack-increase tx to {:?}", &http_origin); + info!("Submit 2.3 stack-increase tx to {http_origin:?}"); submit_tx(&http_origin, &tx); // transition to 2 blocks before epoch 2.4 @@ -411,7 +399,7 @@ fn fix_to_pox_contract() { ], ); - info!("Submit 2.4 stacking tx to {:?}", &http_origin); + info!("Submit 2.4 stacking tx to {http_origin:?}"); sleep_ms(5_000); submit_tx(&http_origin, &tx); @@ -431,7 +419,7 @@ fn fix_to_pox_contract() { ], ); - info!("Submit second 2.4 stacking tx to {:?}", &http_origin); + info!("Submit second 2.4 stacking tx to {http_origin:?}"); submit_tx(&http_origin, &tx); // that it can mine _at all_ is a success criterion @@ -458,7 +446,7 @@ fn fix_to_pox_contract() { &[Value::UInt(increase_by.into())], ); - info!("Submit 2.4 stack-increase tx to {:?}", &http_origin); + info!("Submit 2.4 stack-increase tx to {http_origin:?}"); submit_tx(&http_origin, &tx); for _i in 0..19 { @@ -492,9 +480,9 @@ fn fix_to_pox_contract() { .block_height_to_reward_cycle(burnchain_config.first_block_height, height) .unwrap(); - if !reward_cycle_pox_addrs.contains_key(&reward_cycle) { - reward_cycle_pox_addrs.insert(reward_cycle, HashMap::new()); - } + reward_cycle_pox_addrs + .entry(reward_cycle) + .or_insert_with(HashMap::new); let iconn = sortdb.index_handle_at_block(&chainstate, &tip).unwrap(); let pox_addrs = chainstate @@ -502,7 +490,7 @@ fn fix_to_pox_contract() { &iconn, &tip, &boot_code_id("pox-2", false), - &format!("(get-burn-block-info? pox-addrs u{})", height), + &format!("(get-burn-block-info? pox-addrs u{height})"), ) .expect_optional() .unwrap() @@ -514,38 +502,36 @@ fn fix_to_pox_contract() { .expect_list() .unwrap(); - debug!("Test burnchain height {}", height); - if !burnchain_config.is_in_prepare_phase(height) { - if pox_addrs.len() > 0 { - assert_eq!(pox_addrs.len(), 2); - let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); - let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); + debug!("Test burnchain height {height}"); + if !burnchain_config.is_in_prepare_phase(height) && !pox_addrs.is_empty() { + assert_eq!(pox_addrs.len(), 2); + let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); + let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_0) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_0) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_0, 1); - } + .insert(pox_addr_0, 1); + } - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_1) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_1) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_1, 1); - } + .insert(pox_addr_1, 1); } } } @@ -624,14 +610,12 @@ fn fix_to_pox_contract() { for reward_cycle in reward_cycle_min..(reward_cycle_max + 1) { let cycle_counts = &reward_cycle_pox_addrs[&reward_cycle]; - assert_eq!(cycle_counts.len(), expected_slots[&reward_cycle].len(), "The number of expected PoX addresses in reward cycle {} is mismatched with the actual count.", reward_cycle); + assert_eq!(cycle_counts.len(), expected_slots[&reward_cycle].len(), "The number of expected PoX addresses in reward cycle {reward_cycle} is mismatched with the actual count."); for (pox_addr, slots) in cycle_counts.iter() { assert_eq!( *slots, - expected_slots[&reward_cycle][&pox_addr], - "The number of expected slots for PoX address {} in reward cycle {} is mismatched with the actual count.", - &pox_addr, - reward_cycle, + expected_slots[&reward_cycle][pox_addr], + "The number of expected slots for PoX address {pox_addr} in reward cycle {reward_cycle} is mismatched with the actual count." ); info!("PoX payment received"; "cycle" => reward_cycle, "pox_addr" => %pox_addr, "slots" => slots); } @@ -651,7 +635,7 @@ fn fix_to_pox_contract() { let parsed = StacksTransaction::consensus_deserialize(&mut tx_bytes.as_slice()).unwrap(); let tx_sender = PrincipalData::from(parsed.auth.origin().address_testnet()); - if &tx_sender == &spender_addr + if tx_sender == spender_addr && (parsed.auth.get_origin_nonce() == aborted_increase_nonce_2_2 || parsed.auth.get_origin_nonce() == aborted_increase_nonce_2_3) { @@ -738,21 +722,13 @@ fn verify_auto_unlock_behavior() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash_1 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_1) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_1 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_1).to_bytes()); let pox_pubkey_2 = Secp256k1PublicKey::from_hex( "03cd91307e16c10428dd0120d0a4d37f14d4e0097b3b2ea1651d7bd0fb109cd44b", ) .unwrap(); - let pox_pubkey_hash_2 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_2) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_2 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_2).to_bytes()); let pox_pubkey_2_stx_addr = StacksAddress::from_public_keys( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, &AddressHashMode::SerializeP2PKH, @@ -765,11 +741,7 @@ fn verify_auto_unlock_behavior() { "0317782e663c77fb02ebf46a3720f41a70f5678ad185974a456d35848e275fe56b", ) .unwrap(); - let pox_pubkey_hash_3 = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey_3) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash_3 = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey_3).to_bytes()); let pox_pubkey_3_stx_addr = StacksAddress::from_public_keys( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, &AddressHashMode::SerializeP2PKH, @@ -879,14 +851,14 @@ fn verify_auto_unlock_behavior() { // stack right away let sort_height = channel.get_sortitions_processed(); let pox_addr_tuple_1 = execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash_1,), + &format!("{{ hashbytes: 0x{pox_pubkey_hash_1}, version: 0x00 }}"), ClarityVersion::Clarity2, ) .unwrap() .unwrap(); let pox_addr_tuple_3 = execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash_3,), + &format!("{{ hashbytes: 0x{pox_pubkey_hash_3}, version: 0x00 }}"), ClarityVersion::Clarity2, ) .unwrap() @@ -908,7 +880,7 @@ fn verify_auto_unlock_behavior() { ], ); - info!("Submit 2.05 stacking tx to {:?}", &http_origin); + info!("Submit 2.05 stacking tx to {http_origin:?}"); submit_tx(&http_origin, &tx); // wait until just before epoch 2.1 @@ -937,7 +909,7 @@ fn verify_auto_unlock_behavior() { let sort_height = channel.get_sortitions_processed(); let pox_addr_tuple_2 = execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash_2,), + &format!("{{ hashbytes: 0x{pox_pubkey_hash_2}, version: 0x00 }}"), ClarityVersion::Clarity2, ) .unwrap() @@ -958,7 +930,7 @@ fn verify_auto_unlock_behavior() { ], ); - info!("Submit 2.1 stacking tx to {:?}", &http_origin); + info!("Submit 2.1 stacking tx to {http_origin:?}"); sleep_ms(5_000); submit_tx(&http_origin, &tx); @@ -979,7 +951,7 @@ fn verify_auto_unlock_behavior() { // transition to epoch 2.3 loop { let tip_info = get_chain_info(&conf); - if tip_info.burn_block_height >= epoch_2_3 + 1 { + if tip_info.burn_block_height > epoch_2_3 { break; } next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); @@ -1044,7 +1016,7 @@ fn verify_auto_unlock_behavior() { ], ); - info!("Submit 2.4 stacking tx to {:?}", &http_origin); + info!("Submit 2.4 stacking tx to {http_origin:?}"); sleep_ms(5_000); submit_tx(&http_origin, &tx); @@ -1064,7 +1036,7 @@ fn verify_auto_unlock_behavior() { ], ); - info!("Submit second 2.4 stacking tx to {:?}", &http_origin); + info!("Submit second 2.4 stacking tx to {http_origin:?}"); submit_tx(&http_origin, &tx); // that it can mine _at all_ is a success criterion @@ -1113,7 +1085,7 @@ fn verify_auto_unlock_behavior() { .unwrap(); assert_eq!(reward_set_entries.len(), 2); - info!("reward set entries: {:?}", reward_set_entries); + info!("reward set entries: {reward_set_entries:?}"); assert_eq!( reward_set_entries[0].reward_address.bytes(), pox_pubkey_2_stx_addr.bytes.0.to_vec() @@ -1141,7 +1113,7 @@ fn verify_auto_unlock_behavior() { &[Value::UInt(first_stacked_incr.into())], ); - info!("Submit 2.4 stack-increase tx to {:?}", &http_origin); + info!("Submit 2.4 stack-increase tx to {http_origin:?}"); submit_tx(&http_origin, &tx); for _i in 0..19 { @@ -1213,9 +1185,9 @@ fn verify_auto_unlock_behavior() { .block_height_to_reward_cycle(burnchain_config.first_block_height, height) .unwrap(); - if !reward_cycle_pox_addrs.contains_key(&reward_cycle) { - reward_cycle_pox_addrs.insert(reward_cycle, HashMap::new()); - } + reward_cycle_pox_addrs + .entry(reward_cycle) + .or_insert_with(HashMap::new); let iconn = sortdb.index_handle_at_block(&chainstate, &tip).unwrap(); let pox_addrs = chainstate @@ -1223,7 +1195,7 @@ fn verify_auto_unlock_behavior() { &iconn, &tip, &boot_code_id("pox-2", false), - &format!("(get-burn-block-info? pox-addrs u{})", height), + &format!("(get-burn-block-info? pox-addrs u{height})"), ) .expect_optional() .unwrap() @@ -1235,37 +1207,35 @@ fn verify_auto_unlock_behavior() { .expect_list() .unwrap(); - if !burnchain_config.is_in_prepare_phase(height) { - if pox_addrs.len() > 0 { - assert_eq!(pox_addrs.len(), 2); - let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); - let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); + if !burnchain_config.is_in_prepare_phase(height) && !pox_addrs.is_empty() { + assert_eq!(pox_addrs.len(), 2); + let pox_addr_0 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[0]).unwrap(); + let pox_addr_1 = PoxAddress::try_from_pox_tuple(false, &pox_addrs[1]).unwrap(); - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_0) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_0) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_0, 1); - } + .insert(pox_addr_0, 1); + } - if let Some(pox_slot_count) = reward_cycle_pox_addrs + if let Some(pox_slot_count) = reward_cycle_pox_addrs + .get_mut(&reward_cycle) + .unwrap() + .get_mut(&pox_addr_1) + { + *pox_slot_count += 1; + } else { + reward_cycle_pox_addrs .get_mut(&reward_cycle) .unwrap() - .get_mut(&pox_addr_1) - { - *pox_slot_count += 1; - } else { - reward_cycle_pox_addrs - .get_mut(&reward_cycle) - .unwrap() - .insert(pox_addr_1, 1); - } + .insert(pox_addr_1, 1); } } } @@ -1340,14 +1310,12 @@ fn verify_auto_unlock_behavior() { for reward_cycle in reward_cycle_min..(reward_cycle_max + 1) { let cycle_counts = &reward_cycle_pox_addrs[&reward_cycle]; - assert_eq!(cycle_counts.len(), expected_slots[&reward_cycle].len(), "The number of expected PoX addresses in reward cycle {} is mismatched with the actual count.", reward_cycle); + assert_eq!(cycle_counts.len(), expected_slots[&reward_cycle].len(), "The number of expected PoX addresses in reward cycle {reward_cycle} is mismatched with the actual count."); for (pox_addr, slots) in cycle_counts.iter() { assert_eq!( *slots, - expected_slots[&reward_cycle][&pox_addr], - "The number of expected slots for PoX address {} in reward cycle {} is mismatched with the actual count.", - &pox_addr, - reward_cycle, + expected_slots[&reward_cycle][pox_addr], + "The number of expected slots for PoX address {pox_addr} in reward cycle {reward_cycle} is mismatched with the actual count." ); info!("PoX payment received"; "cycle" => reward_cycle, "pox_addr" => %pox_addr, "slots" => slots); } diff --git a/testnet/stacks-node/src/tests/epoch_25.rs b/testnet/stacks-node/src/tests/epoch_25.rs index 6af1bee626..4a3e2a4095 100644 --- a/testnet/stacks-node/src/tests/epoch_25.rs +++ b/testnet/stacks-node/src/tests/epoch_25.rs @@ -79,8 +79,8 @@ fn microblocks_disabled() { conf.node.wait_time_for_blocks = 2_000; conf.miner.wait_for_block_download = false; - conf.miner.first_attempt_time_ms = i64::max_value() as u64; - conf.miner.subsequent_attempt_time_ms = i64::max_value() as u64; + conf.miner.first_attempt_time_ms = i64::MAX as u64; + conf.miner.subsequent_attempt_time_ms = i64::MAX as u64; test_observer::spawn(); test_observer::register_any(&mut conf); @@ -111,8 +111,8 @@ fn microblocks_disabled() { 4 * prepare_phase_len / 5, 5, 15, - u64::max_value() - 2, - u64::max_value() - 1, + u64::MAX - 2, + u64::MAX - 1, v1_unlock_height as u32, epoch_2_2 as u32 + 1, u32::MAX, diff --git a/testnet/stacks-node/src/tests/integrations.rs b/testnet/stacks-node/src/tests/integrations.rs index 236d76b000..5a8de4d3bd 100644 --- a/testnet/stacks-node/src/tests/integrations.rs +++ b/testnet/stacks-node/src/tests/integrations.rs @@ -1,3 +1,4 @@ +use std::cmp::Ordering; use std::collections::HashMap; use std::fmt::Write; use std::sync::Mutex; @@ -43,7 +44,7 @@ use crate::config::InitialBalance; use crate::helium::RunLoop; use crate::tests::make_sponsored_stacks_transfer_on_testnet; -const OTHER_CONTRACT: &'static str = " +const OTHER_CONTRACT: &str = " (define-data-var x uint u0) (define-public (f1) (ok (var-get x))) @@ -51,14 +52,14 @@ const OTHER_CONTRACT: &'static str = " (ok (var-set x val))) "; -const CALL_READ_CONTRACT: &'static str = " +const CALL_READ_CONTRACT: &str = " (define-public (public-no-write) (ok (contract-call? .other f1))) (define-public (public-write) (ok (contract-call? .other f2 u5))) "; -const GET_INFO_CONTRACT: &'static str = " +const GET_INFO_CONTRACT: &str = " (define-map block-data { height: uint } { stacks-hash: (buff 32), @@ -143,7 +144,7 @@ const GET_INFO_CONTRACT: &'static str = " (fn-2 (uint) (response uint uint)))) "; -const IMPL_TRAIT_CONTRACT: &'static str = " +const IMPL_TRAIT_CONTRACT: &str = " ;; explicit trait compliance for trait 1 (impl-trait .get-info.trait-1) (define-private (test-height) burn-block-height) @@ -193,7 +194,7 @@ fn integration_test_get_info() { { let mut http_opt = HTTP_BINDING.lock().unwrap(); - http_opt.replace(format!("http://{}", &rpc_bind)); + http_opt.replace(format!("http://{rpc_bind}")); } run_loop @@ -279,10 +280,10 @@ fn integration_test_get_info() { let old_tip = StacksBlockId::new(&consensus_hash, &header_hash); use std::fs; use std::io::Write; - if fs::metadata(&tmppath).is_ok() { - fs::remove_file(&tmppath).unwrap(); + if fs::metadata(tmppath).is_ok() { + fs::remove_file(tmppath).unwrap(); } - let mut f = fs::File::create(&tmppath).unwrap(); + let mut f = fs::File::create(tmppath).unwrap(); f.write_all(&old_tip.serialize_to_vec()).unwrap(); } else if round == 2 { // block-height = 3 @@ -311,7 +312,7 @@ fn integration_test_get_info() { // block-height > 3 let tx = make_contract_call( &principal_sk, - (round - 3).into(), + round - 3, 10, CHAIN_ID_TESTNET, &to_addr(&contract_sk), @@ -337,7 +338,7 @@ fn integration_test_get_info() { if round >= 1 { let tx_xfer = make_stacks_transfer( &spender_sk, - (round - 1).into(), + round - 1, 10, CHAIN_ID_TESTNET, &StacksAddress::from_string(ADDR_4).unwrap().into(), @@ -356,16 +357,14 @@ fn integration_test_get_info() { ) .unwrap(); } - - return; }); run_loop.callbacks.on_new_stacks_chain_state(|round, _burnchain_tip, chain_tip, chain_state, burn_dbconn| { let contract_addr = to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()); let contract_identifier = - QualifiedContractIdentifier::parse(&format!("{}.{}", &contract_addr, "get-info")).unwrap(); + QualifiedContractIdentifier::parse(&format!("{contract_addr}.get-info")).unwrap(); let impl_trait_contract_identifier = - QualifiedContractIdentifier::parse(&format!("{}.{}", &contract_addr, "impl-trait-contract")).unwrap(); + QualifiedContractIdentifier::parse(&format!("{contract_addr}.impl-trait-contract")).unwrap(); let http_origin = { HTTP_BINDING.lock().unwrap().clone().unwrap() @@ -374,7 +373,7 @@ fn integration_test_get_info() { match round { 1 => { // - Chain length should be 2. - let blocks = StacksChainState::list_blocks(&chain_state.db()).unwrap(); + let blocks = StacksChainState::list_blocks(chain_state.db()).unwrap(); assert!(chain_tip.metadata.stacks_block_height == 2); // Block #1 should have 5 txs @@ -382,14 +381,14 @@ fn integration_test_get_info() { let parent = chain_tip.block.header.parent_block; let bhh = &chain_tip.metadata.index_block_hash(); - eprintln!("Current Block: {} Parent Block: {}", bhh, parent); + eprintln!("Current Block: {bhh} Parent Block: {parent}"); let parent_val = Value::buff_from(parent.as_bytes().to_vec()).unwrap(); // find header metadata let mut headers = vec![]; for block in blocks.iter() { let header = StacksChainState::get_anchored_block_header_info(chain_state.db(), &block.0, &block.1).unwrap().unwrap(); - eprintln!("{}/{}: {:?}", &block.0, &block.1, &header); + eprintln!("{}/{}: {header:?}", &block.0, &block.1); headers.push(header); } @@ -500,13 +499,12 @@ fn integration_test_get_info() { burn_dbconn, bhh, &contract_identifier, "(exotic-data-checks u4)")); let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/map_entry/{}/{}/{}", - &http_origin, &contract_addr, "get-info", "block-data"); + let path = format!("{http_origin}/v2/map_entry/{contract_addr}/get-info/block-data"); let key: Value = TupleData::from_data(vec![("height".into(), Value::UInt(3))]) .unwrap().into(); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let res = client.post(&path) .json(&key.serialize_to_hex().unwrap()) .send() @@ -514,14 +512,14 @@ fn integration_test_get_info() { let result_data = Value::try_deserialize_hex_untyped(&res["data"][2..]).unwrap(); let expected_data = chain_state.clarity_eval_read_only(burn_dbconn, bhh, &contract_identifier, "(some (get-exotic-data-info u3))"); - assert!(res.get("proof").is_some()); + assert!(res.contains_key("proof")); assert_eq!(result_data, expected_data); let key: Value = TupleData::from_data(vec![("height".into(), Value::UInt(100))]) .unwrap().into(); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let res = client.post(&path) .json(&key.serialize_to_hex().unwrap()) .send() @@ -532,19 +530,18 @@ fn integration_test_get_info() { let sender_addr = to_addr(&StacksPrivateKey::from_hex(SK_3).unwrap()); // now, let's use a query string to get data without a proof - let path = format!("{}/v2/map_entry/{}/{}/{}?proof=0", - &http_origin, &contract_addr, "get-info", "block-data"); + let path = format!("{http_origin}/v2/map_entry/{contract_addr}/get-info/block-data?proof=0"); let key: Value = TupleData::from_data(vec![("height".into(), Value::UInt(3))]) .unwrap().into(); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let res = client.post(&path) .json(&key.serialize_to_hex().unwrap()) .send() .unwrap().json::>().unwrap(); - assert!(res.get("proof").is_none()); + assert!(!res.contains_key("proof")); let result_data = Value::try_deserialize_hex_untyped(&res["data"][2..]).unwrap(); let expected_data = chain_state.clarity_eval_read_only(burn_dbconn, bhh, &contract_identifier, "(some (get-exotic-data-info u3))"); @@ -553,19 +550,18 @@ fn integration_test_get_info() { assert_eq!(result_data, expected_data); // now, let's use a query string to get data _with_ a proof - let path = format!("{}/v2/map_entry/{}/{}/{}?proof=1", - &http_origin, &contract_addr, "get-info", "block-data"); + let path = format!("{http_origin}/v2/map_entry/{contract_addr}/get-info/block-data?proof=1"); let key: Value = TupleData::from_data(vec![("height".into(), Value::UInt(3))]) .unwrap().into(); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let res = client.post(&path) .json(&key.serialize_to_hex().unwrap()) .send() .unwrap().json::>().unwrap(); - assert!(res.get("proof").is_some()); + assert!(res.contains_key("proof")); let result_data = Value::try_deserialize_hex_untyped(&res["data"][2..]).unwrap(); let expected_data = chain_state.clarity_eval_read_only(burn_dbconn, bhh, &contract_identifier, "(some (get-exotic-data-info u3))"); @@ -574,9 +570,8 @@ fn integration_test_get_info() { assert_eq!(result_data, expected_data); // account with a nonce entry + a balance entry - let path = format!("{}/v2/accounts/{}", - &http_origin, &sender_addr); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{sender_addr}"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 99860); assert_eq!(res.nonce, 4); @@ -584,9 +579,8 @@ fn integration_test_get_info() { assert!(res.balance_proof.is_some()); // account with a nonce entry but not a balance entry - let path = format!("{}/v2/accounts/{}", - &http_origin, &contract_addr); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{contract_addr}"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 960); assert_eq!(res.nonce, 4); @@ -594,9 +588,8 @@ fn integration_test_get_info() { assert!(res.balance_proof.is_some()); // account with a balance entry but not a nonce entry - let path = format!("{}/v2/accounts/{}", - &http_origin, ADDR_4); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{ADDR_4}"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 400); assert_eq!(res.nonce, 0); @@ -604,27 +597,24 @@ fn integration_test_get_info() { assert!(res.balance_proof.is_some()); // account with neither! - let path = format!("{}/v2/accounts/{}.get-info", - &http_origin, &contract_addr); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{contract_addr}.get-info"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 0); assert_eq!(res.nonce, 0); assert!(res.nonce_proof.is_some()); assert!(res.balance_proof.is_some()); - let path = format!("{}/v2/accounts/{}?proof=0", - &http_origin, ADDR_4); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{ADDR_4}?proof=0"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 400); assert_eq!(res.nonce, 0); assert!(res.nonce_proof.is_none()); assert!(res.balance_proof.is_none()); - let path = format!("{}/v2/accounts/{}?proof=1", - &http_origin, ADDR_4); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/accounts/{ADDR_4}?proof=1"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 400); assert_eq!(res.nonce, 0); @@ -632,15 +622,15 @@ fn integration_test_get_info() { assert!(res.balance_proof.is_some()); // let's try getting the transfer cost - let path = format!("{}/v2/fees/transfer", &http_origin); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/fees/transfer"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert!(res > 0); // let's get a contract ABI - let path = format!("{}/v2/contracts/interface/{}/{}", &http_origin, &contract_addr, "get-info"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/contracts/interface/{contract_addr}/get-info"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); let contract_analysis = mem_type_check(GET_INFO_CONTRACT, ClarityVersion::Clarity2, StacksEpochId::Epoch21).unwrap().1; @@ -652,14 +642,14 @@ fn integration_test_get_info() { // a missing one? - let path = format!("{}/v2/contracts/interface/{}/{}", &http_origin, &contract_addr, "not-there"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/contracts/interface/{contract_addr}/not-there"); + eprintln!("Test: GET {path}"); assert_eq!(client.get(&path).send().unwrap().status(), 404); // let's get a contract SRC - let path = format!("{}/v2/contracts/source/{}/{}", &http_origin, &contract_addr, "get-info"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/contracts/source/{contract_addr}/get-info"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(res.source, GET_INFO_CONTRACT); @@ -667,8 +657,8 @@ fn integration_test_get_info() { assert!(res.marf_proof.is_some()); - let path = format!("{}/v2/contracts/source/{}/{}?proof=0", &http_origin, &contract_addr, "get-info"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/contracts/source/{contract_addr}/get-info?proof=0"); + eprintln!("Test: GET {path}"); let res = client.get(&path).send().unwrap().json::().unwrap(); assert_eq!(res.source, GET_INFO_CONTRACT); @@ -677,14 +667,14 @@ fn integration_test_get_info() { // a missing one? - let path = format!("{}/v2/contracts/source/{}/{}", &http_origin, &contract_addr, "not-there"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/contracts/source/{contract_addr}/not-there"); + eprintln!("Test: GET {path}"); assert_eq!(client.get(&path).send().unwrap().status(), 404); // how about a read-only function call! - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "get-info", "get-exotic-data-info"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/get-info/get-exotic-data-info"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -705,8 +695,8 @@ fn integration_test_get_info() { assert_eq!(result_data, expected_data); // how about a non read-only function call which does not modify anything - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "main", "public-no-write"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/main/public-no-write"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -732,8 +722,8 @@ fn integration_test_get_info() { assert_eq!(result_data, expected_data); // how about a non read-only function call which does modify something and should fail - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "main", "public-write"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/main/public-write"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -750,9 +740,8 @@ fn integration_test_get_info() { assert!(res["cause"].as_str().unwrap().contains("NotReadOnly")); // let's try a call with a url-encoded string. - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "get-info", - "get-exotic-data-info%3F"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/get-info/get-exotic-data-info%3F"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -774,8 +763,8 @@ fn integration_test_get_info() { assert_eq!(result_data, expected_data); // let's have a runtime error! - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "get-info", "get-exotic-data-info"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/get-info/get-exotic-data-info"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -793,8 +782,8 @@ fn integration_test_get_info() { assert!(res["cause"].as_str().unwrap().contains("UnwrapFailure")); // let's have a runtime error! - let path = format!("{}/v2/contracts/call-read/{}/{}/{}", &http_origin, &contract_addr, "get-info", "update-info"); - eprintln!("Test: POST {}", path); + let path = format!("{http_origin}/v2/contracts/call-read/{contract_addr}/get-info/update-info"); + eprintln!("Test: POST {path}"); let body = CallReadOnlyRequestBody { sender: "'SP139Q3N9RXCJCD1XVA4N5RYWQ5K9XQ0T9PKQ8EE5".into(), @@ -814,13 +803,13 @@ fn integration_test_get_info() { // let's submit a valid transaction! let spender_sk = StacksPrivateKey::from_hex(SK_3).unwrap(); - let path = format!("{}/v2/transactions", &http_origin); - eprintln!("Test: POST {} (valid)", path); + let path = format!("{http_origin}/v2/transactions"); + eprintln!("Test: POST {path} (valid)"); // tx_xfer is 180 bytes long let tx_xfer = make_stacks_transfer( &spender_sk, - round.into(), + round, 200, CHAIN_ID_TESTNET, &StacksAddress::from_string(ADDR_4).unwrap().into(), @@ -846,17 +835,17 @@ fn integration_test_get_info() { .send() .unwrap().json::().unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!(res.get("error").unwrap().as_str().unwrap(), "transaction rejected"); assert!(res.get("reason").is_some()); // let's submit an invalid transaction! - let path = format!("{}/v2/transactions", &http_origin); - eprintln!("Test: POST {} (invalid)", path); + let path = format!("{http_origin}/v2/transactions"); + eprintln!("Test: POST {path} (invalid)"); // tx_xfer_invalid is 180 bytes long // bad nonce - let tx_xfer_invalid = make_stacks_transfer(&spender_sk, (round + 30).into(), 200, CHAIN_ID_TESTNET, + let tx_xfer_invalid = make_stacks_transfer(&spender_sk, round + 30, 200, CHAIN_ID_TESTNET, &StacksAddress::from_string(ADDR_4).unwrap().into(), 456); let tx_xfer_invalid_tx = StacksTransaction::consensus_deserialize(&mut &tx_xfer_invalid[..]).unwrap(); @@ -869,39 +858,39 @@ fn integration_test_get_info() { .json::() .unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!(res.get("txid").unwrap().as_str().unwrap(), format!("{}", tx_xfer_invalid_tx.txid())); assert_eq!(res.get("error").unwrap().as_str().unwrap(), "transaction rejected"); assert!(res.get("reason").is_some()); // testing /v2/trait// // trait does not exist - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}", &http_origin, &contract_addr, "get-info", &contract_addr, "get-info", "dummy-trait"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/traits/{contract_addr}/get-info/{contract_addr}/get-info/dummy-trait"); + eprintln!("Test: GET {path}"); assert_eq!(client.get(&path).send().unwrap().status(), 404); // explicit trait compliance - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-1"); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-1"); let res = client.get(&path).send().unwrap().json::().unwrap(); eprintln!("Test: GET {}", path); assert!(res.is_implemented); // No trait found - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-4"); - eprintln!("Test: GET {}", path); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-4"); + eprintln!("Test: GET {path}"); assert_eq!(client.get(&path).send().unwrap().status(), 404); // implicit trait compliance - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-2"); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-2"); let res = client.get(&path).send().unwrap().json::().unwrap(); - eprintln!("Test: GET {}", path); + eprintln!("Test: GET {path}"); assert!(res.is_implemented); // invalid trait compliance - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-3"); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-3"); let res = client.get(&path).send().unwrap().json::().unwrap(); - eprintln!("Test: GET {}", path); + eprintln!("Test: GET {path}"); assert!(!res.is_implemented); // test query parameters for v2/trait endpoint @@ -911,33 +900,33 @@ fn integration_test_get_info() { let tmppath = "/tmp/integration_test_get_info-old-tip"; use std::fs; use std::io::Read; - let mut f = fs::File::open(&tmppath).unwrap(); + let mut f = fs::File::open(tmppath).unwrap(); let mut buf = vec![]; f.read_to_end(&mut buf).unwrap(); let old_tip = StacksBlockId::consensus_deserialize(&mut &buf[..]).unwrap(); - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}?tip={}", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-1", &old_tip); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-1?tip={old_tip}"); let res = client.get(&path).send().unwrap(); - eprintln!("Test: GET {}", path); + eprintln!("Test: GET {path}"); assert_eq!(res.text().unwrap(), "No contract analysis found or trait definition not found"); // evaluate check for explicit compliance where tip is the chain tip of the first block (contract DNE at that block), but tip is "latest" - let path = format!("{}/v2/traits/{}/{}/{}/{}/{}?tip=latest", &http_origin, &contract_addr, "impl-trait-contract", &contract_addr, "get-info", "trait-1"); + let path = format!("{http_origin}/v2/traits/{contract_addr}/impl-trait-contract/{contract_addr}/get-info/trait-1?tip=latest"); let res = client.get(&path).send().unwrap().json::().unwrap(); - eprintln!("Test: GET {}", path); + eprintln!("Test: GET {path}"); assert!(res.is_implemented); // perform some tests of the fee rate interface - let path = format!("{}/v2/fees/transaction", &http_origin); + let path = format!("{http_origin}/v2/fees/transaction"); let tx_payload = - TransactionPayload::TokenTransfer(contract_addr.clone().into(), 10_000_000, TokenTransferMemo([0; 34])); + TransactionPayload::TokenTransfer(contract_addr.into(), 10_000_000, TokenTransferMemo([0; 34])); let payload_data = tx_payload.serialize_to_vec(); let payload_hex = format!("0x{}", to_hex(&payload_data)); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let body = json!({ "transaction_payload": payload_hex.clone() }); @@ -948,7 +937,7 @@ fn integration_test_get_info() { .json::() .expect("Failed to parse result into JSON"); - eprintln!("{}", res); + eprintln!("{res}"); // destruct the json result // estimated_cost for transfers should be 0 -- their cost is just in their length @@ -975,11 +964,11 @@ fn integration_test_get_info() { .map(|x| x.get("fee").expect("Should have fee field")) .collect(); - assert!(estimated_fee_rates.len() == 3, "Fee rates should be length 3 array"); - assert!(estimated_fees.len() == 3, "Fees should be length 3 array"); + assert_eq!(estimated_fee_rates.len(), 3, "Fee rates should be length 3 array"); + assert_eq!(estimated_fees.len(), 3, "Fees should be length 3 array"); let tx_payload = TransactionPayload::from(TransactionContractCall { - address: contract_addr.clone(), + address: contract_addr, contract_name: "get-info".into(), function_name: "update-info".into(), function_args: vec![], @@ -988,7 +977,7 @@ fn integration_test_get_info() { let payload_data = tx_payload.serialize_to_vec(); let payload_hex = to_hex(&payload_data); - eprintln!("Test: POST {}", path); + eprintln!("Test: POST {path}"); let body = json!({ "transaction_payload": payload_hex.clone() }); @@ -999,7 +988,7 @@ fn integration_test_get_info() { .json::() .expect("Failed to parse result into JSON"); - eprintln!("{}", res); + eprintln!("{res}"); // destruct the json result // estimated_cost for transfers should be non-zero @@ -1026,11 +1015,11 @@ fn integration_test_get_info() { .map(|x| x.get("fee").expect("Should have fee field")) .collect(); - assert!(estimated_fee_rates.len() == 3, "Fee rates should be length 3 array"); - assert!(estimated_fees.len() == 3, "Fees should be length 3 array"); + assert_eq!(estimated_fee_rates.len(), 3, "Fee rates should be length 3 array"); + assert_eq!(estimated_fees.len(), 3, "Fees should be length 3 array"); let tx_payload = TransactionPayload::from(TransactionContractCall { - address: contract_addr.clone(), + address: contract_addr, contract_name: "get-info".into(), function_name: "update-info".into(), function_args: vec![], @@ -1041,7 +1030,7 @@ fn integration_test_get_info() { let estimated_len = 1550; let body = json!({ "transaction_payload": payload_hex.clone(), "estimated_len": estimated_len }); - info!("POST body\n {}", body); + info!("POST body\n {body}"); let res = client.post(&path) .json(&body) @@ -1050,7 +1039,7 @@ fn integration_test_get_info() { .json::() .expect("Failed to parse result into JSON"); - info!("{}", res); + info!("{res}"); // destruct the json result // estimated_cost for transfers should be non-zero @@ -1094,7 +1083,7 @@ fn integration_test_get_info() { run_loop.start(num_rounds).unwrap(); } -const FAUCET_CONTRACT: &'static str = " +const FAUCET_CONTRACT: &str = " (define-public (spout) (let ((recipient tx-sender)) (print (as-contract (stx-transfer? u1 .faucet recipient))))) @@ -1111,7 +1100,7 @@ fn contract_stx_transfer() { conf.burnchain.commit_anchor_block_within = 5000; conf.add_initial_balance(addr_3.to_string(), 100000); conf.add_initial_balance( - to_addr(&StacksPrivateKey::from_hex(&SK_2).unwrap()).to_string(), + to_addr(&StacksPrivateKey::from_hex(SK_2).unwrap()).to_string(), 1000, ); conf.add_initial_balance(to_addr(&contract_sk).to_string(), 1000); @@ -1133,9 +1122,8 @@ fn contract_stx_transfer() { let consensus_hash = chain_tip.metadata.consensus_hash; let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); @@ -1226,7 +1214,7 @@ fn contract_stx_transfer() { .submit_raw( &mut chainstate_copy, &sortdb, - &consensus_hash, + consensus_hash, &header_hash, tx, &ExecutionCost::max_value(), @@ -1287,30 +1275,27 @@ fn contract_stx_transfer() { .unwrap_err() { MemPoolRejection::ConflictingNonceInMempool => (), - e => panic!("{:?}", e), + e => panic!("{e:?}"), }; } - - return; }); run_loop.callbacks.on_new_stacks_chain_state( |round, _burnchain_tip, chain_tip, chain_state, burn_dbconn| { let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); match round { 1 => { - assert!(chain_tip.metadata.stacks_block_height == 2); + assert_eq!(chain_tip.metadata.stacks_block_height, 2); // Block #1 should have 2 txs -- coinbase + transfer assert_eq!(chain_tip.block.txs.len(), 2); let cur_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); // check that 1000 stx _was_ transfered to the contract principal @@ -1353,19 +1338,19 @@ fn contract_stx_transfer() { ); } 2 => { - assert!(chain_tip.metadata.stacks_block_height == 3); + assert_eq!(chain_tip.metadata.stacks_block_height, 3); // Block #2 should have 2 txs -- coinbase + publish assert_eq!(chain_tip.block.txs.len(), 2); } 3 => { - assert!(chain_tip.metadata.stacks_block_height == 4); + assert_eq!(chain_tip.metadata.stacks_block_height, 4); // Block #3 should have 2 txs -- coinbase + contract-call, // the second publish _should have been rejected_ assert_eq!(chain_tip.block.txs.len(), 2); // check that 1 stx was transfered to SK_2 via the contract-call let cur_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); @@ -1408,7 +1393,7 @@ fn contract_stx_transfer() { ); } 4 => { - assert!(chain_tip.metadata.stacks_block_height == 5); + assert_eq!(chain_tip.metadata.stacks_block_height, 5); assert_eq!( chain_tip.block.txs.len() as u64, MAXIMUM_MEMPOOL_TX_CHAINING + 1, @@ -1416,7 +1401,7 @@ fn contract_stx_transfer() { ); let cur_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); @@ -1491,9 +1476,8 @@ fn mine_transactions_out_of_order() { let consensus_hash = chain_tip.metadata.consensus_hash; let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); @@ -1578,16 +1562,13 @@ fn mine_transactions_out_of_order() { ) .unwrap(); } - - return; }); run_loop.callbacks.on_new_stacks_chain_state( |round, _burnchain_tip, chain_tip, chain_state, burn_dbconn| { let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); @@ -1610,7 +1591,7 @@ fn mine_transactions_out_of_order() { // check that 1000 stx _was_ transfered to the contract principal let curr_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); assert_eq!( @@ -1698,15 +1679,14 @@ fn mine_contract_twice() { run_loop.callbacks.on_new_stacks_chain_state( |round, _burnchain_tip, chain_tip, chain_state, burn_dbconn| { let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); if round == 2 { let cur_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); // check that the contract published! @@ -1761,9 +1741,8 @@ fn bad_contract_tx_rollback() { let addr_2 = to_addr(&sk_2); let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); @@ -1872,16 +1851,13 @@ fn bad_contract_tx_rollback() { ) .unwrap(); } - - return; }); run_loop.callbacks.on_new_stacks_chain_state( |round, _burnchain_tip, chain_tip, chain_state, burn_dbconn| { let contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()).to_string(), - "faucet" + "{}.faucet", + to_addr(&StacksPrivateKey::from_hex(SK_1).unwrap()) )) .unwrap(); @@ -1892,7 +1868,7 @@ fn bad_contract_tx_rollback() { assert_eq!(chain_tip.block.txs.len(), 2); let cur_tip = ( - chain_tip.metadata.consensus_hash.clone(), + chain_tip.metadata.consensus_hash, chain_tip.metadata.anchored_header.block_hash(), ); // check that 1000 stx _was_ transfered to the contract principal @@ -1967,10 +1943,8 @@ fn make_expensive_contract(inner_loop: &str, other_decl: &str) -> String { for i in 0..10 { contract.push('\n'); contract.push_str(&format!( - "(define-constant list-{} (concat list-{} list-{}))", + "(define-constant list-{} (concat list-{i} list-{i}))", i + 1, - i, - i )); } @@ -2083,7 +2057,7 @@ fn block_limit_runtime_test() { let seed = "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"; let spender_sks = make_keys(seed, 500); for sk in spender_sks.iter() { - conf.add_initial_balance(to_addr(&sk).to_string(), 1000); + conf.add_initial_balance(to_addr(sk).to_string(), 1000); } let num_rounds = 6; @@ -2097,9 +2071,8 @@ fn block_limit_runtime_test() { let contract_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let _contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&contract_sk), - "hello-contract" + "{}.hello-contract", + to_addr(&contract_sk) )) .unwrap(); let (consensus_hash, block_hash) = ( @@ -2107,45 +2080,15 @@ fn block_limit_runtime_test() { &tenure.parent_block.metadata.anchored_header.block_hash(), ); - if round == 1 { - let publish_tx = make_contract_publish( - &contract_sk, - 0, - 10, - CHAIN_ID_TESTNET, - "hello-contract", - EXPENSIVE_CONTRACT.as_str(), - ); - tenure - .mem_pool - .submit_raw( - &mut chainstate_copy, - &sortdb, - consensus_hash, - block_hash, - publish_tx, - &ExecutionCost::max_value(), - &StacksEpochId::Epoch21, - ) - .unwrap(); - } else if round > 1 { - eprintln!("Begin Round: {}", round); - let to_submit = 2 * (round - 1); - - let seed = "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"; - let spender_sks = make_keys(seed, 500); - - for i in 0..to_submit { - let sk = &spender_sks[(i + round * round) as usize]; - let tx = make_contract_call( - sk, + match round.cmp(&1) { + Ordering::Equal => { + let publish_tx = make_contract_publish( + &contract_sk, 0, 10, CHAIN_ID_TESTNET, - &to_addr(&contract_sk), "hello-contract", - "do-it", - &[], + EXPENSIVE_CONTRACT.as_str(), ); tenure .mem_pool @@ -2154,24 +2097,55 @@ fn block_limit_runtime_test() { &sortdb, consensus_hash, block_hash, - tx, + publish_tx, &ExecutionCost::max_value(), &StacksEpochId::Epoch21, ) .unwrap(); } - } - - return; + Ordering::Greater => { + eprintln!("Begin Round: {round}"); + let to_submit = 2 * (round - 1); + + let seed = "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"; + let spender_sks = make_keys(seed, 500); + + for i in 0..to_submit { + let sk = &spender_sks[(i + round * round) as usize]; + let tx = make_contract_call( + sk, + 0, + 10, + CHAIN_ID_TESTNET, + &to_addr(&contract_sk), + "hello-contract", + "do-it", + &[], + ); + tenure + .mem_pool + .submit_raw( + &mut chainstate_copy, + &sortdb, + consensus_hash, + block_hash, + tx, + &ExecutionCost::max_value(), + &StacksEpochId::Epoch21, + ) + .unwrap(); + } + } + Ordering::Less => {} + }; }); run_loop.callbacks.on_new_stacks_chain_state( |round, _chain_state, block, _chain_tip_info, _burn_dbconn| { let contract_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let _contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&contract_sk), - "hello-contract" + "{}.hello-contract", + to_addr(&contract_sk) )) .unwrap(); @@ -2180,7 +2154,7 @@ fn block_limit_runtime_test() { // Block #1 should have 3 txs -- coinbase + 2 contract calls... assert_eq!(block.block.txs.len(), 3); } - 3 | 4 | 5 => { + 3..=5 => { // Block >= 2 should have 4 txs -- coinbase + 3 contract calls // because the _subsequent_ transactions should never have been // included. @@ -2215,7 +2189,7 @@ fn mempool_errors() { { let mut http_opt = HTTP_BINDING.lock().unwrap(); - http_opt.replace(format!("http://{}", &rpc_bind)); + http_opt.replace(format!("http://{rpc_bind}")); } let mut run_loop = RunLoop::new(conf); @@ -2254,22 +2228,19 @@ fn mempool_errors() { ) .unwrap(); } - - return; }); run_loop.callbacks.on_new_stacks_chain_state( |round, _chain_state, _block, _chain_tip_info, _burn_dbconn| { let contract_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let _contract_identifier = QualifiedContractIdentifier::parse(&format!( - "{}.{}", - to_addr(&contract_sk), - "hello-contract" + "{}.hello-contract", + to_addr(&contract_sk) )) .unwrap(); let http_origin = { HTTP_BINDING.lock().unwrap().clone().unwrap() }; let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let spender_sk = StacksPrivateKey::from_hex(SK_3).unwrap(); let spender_addr = to_addr(&spender_sk); @@ -2277,7 +2248,7 @@ fn mempool_errors() { if round == 1 { // let's submit an invalid transaction! - eprintln!("Test: POST {} (invalid)", path); + eprintln!("Test: POST {path} (invalid)"); let tx_xfer_invalid = make_stacks_transfer( &spender_sk, 30, // bad nonce -- too much chaining @@ -2298,7 +2269,7 @@ fn mempool_errors() { .json::() .unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!( res.get("txid").unwrap().as_str().unwrap(), tx_xfer_invalid_tx.txid().to_string() @@ -2312,7 +2283,7 @@ fn mempool_errors() { "TooMuchChaining" ); let data = res.get("reason_data").unwrap(); - assert_eq!(data.get("is_origin").unwrap().as_bool().unwrap(), true); + assert!(data.get("is_origin").unwrap().as_bool().unwrap()); assert_eq!( data.get("principal").unwrap().as_str().unwrap(), &spender_addr.to_string() @@ -2340,7 +2311,7 @@ fn mempool_errors() { .json::() .unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!( res.get("txid").unwrap().as_str().unwrap(), tx_xfer_invalid_tx.txid().to_string() @@ -2374,7 +2345,7 @@ fn mempool_errors() { .json::() .unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!( res.get("txid").unwrap().as_str().unwrap(), tx_xfer_invalid_tx.txid().to_string() @@ -2419,7 +2390,7 @@ fn mempool_errors() { .json::() .unwrap(); - eprintln!("{}", res); + eprintln!("{res}"); assert_eq!( res.get("txid").unwrap().as_str().unwrap(), tx_xfer_invalid_tx.txid().to_string() diff --git a/testnet/stacks-node/src/tests/mempool.rs b/testnet/stacks-node/src/tests/mempool.rs index b701e70a15..58a526ba30 100644 --- a/testnet/stacks-node/src/tests/mempool.rs +++ b/testnet/stacks-node/src/tests/mempool.rs @@ -31,13 +31,13 @@ use super::{ use crate::helium::RunLoop; use crate::Keychain; -const FOO_CONTRACT: &'static str = "(define-public (foo) (ok 1)) +const FOO_CONTRACT: &str = "(define-public (foo) (ok 1)) (define-public (bar (x uint)) (ok x))"; -const TRAIT_CONTRACT: &'static str = "(define-trait tr ((value () (response uint uint))))"; -const USE_TRAIT_CONTRACT: &'static str = "(use-trait tr-trait .trait-contract.tr) +const TRAIT_CONTRACT: &str = "(define-trait tr ((value () (response uint uint))))"; +const USE_TRAIT_CONTRACT: &str = "(use-trait tr-trait .trait-contract.tr) (define-public (baz (abc )) (ok (contract-of abc)))"; -const IMPLEMENT_TRAIT_CONTRACT: &'static str = "(define-public (value) (ok u1))"; -const BAD_TRAIT_CONTRACT: &'static str = "(define-public (foo-bar) (ok u1))"; +const IMPLEMENT_TRAIT_CONTRACT: &str = "(define-public (value) (ok u1))"; +const BAD_TRAIT_CONTRACT: &str = "(define-public (foo-bar) (ok u1))"; pub fn make_bad_stacks_transfer( sender: &StacksPrivateKey, @@ -318,17 +318,13 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!( - if let MemPoolRejection::FailedToValidate(ChainstateError::NetError( - NetError::VerifyingError(_), - )) = e - { - true - } else { - false - } - ); + eprintln!("Err: {e:?}"); + assert!(matches!( + e, + MemPoolRejection::FailedToValidate(ChainstateError::NetError( + NetError::VerifyingError(_) + )) + )); // mismatched network on contract-call! let bad_addr = StacksAddress::from_public_keys( @@ -337,8 +333,7 @@ fn mempool_setup_chainstate() { 1, &vec![StacksPublicKey::from_private(&other_sk)], ) - .unwrap() - .into(); + .unwrap(); let tx_bytes = make_contract_call( &contract_sk, @@ -362,11 +357,7 @@ fn mempool_setup_chainstate() { ) .unwrap_err(); - assert!(if let MemPoolRejection::BadAddressVersionByte = e { - true - } else { - false - }); + assert!(matches!(e, MemPoolRejection::BadAddressVersionByte)); // mismatched network on transfer! let bad_addr = StacksAddress::from_public_keys( @@ -391,11 +382,7 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - assert!(if let MemPoolRejection::BadAddressVersionByte = e { - true - } else { - false - }); + assert!(matches!(e, MemPoolRejection::BadAddressVersionByte)); // bad fees let tx_bytes = @@ -411,12 +398,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::FeeTooLow(0, _) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::FeeTooLow(0, _))); // bad nonce let tx_bytes = @@ -432,12 +415,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::BadNonces(_) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::BadNonces(_))); // not enough funds let tx_bytes = make_stacks_transfer( @@ -459,15 +438,11 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NotEnoughFunds(111000, 99500) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NotEnoughFunds(111000, 99500))); // sender == recipient - let contract_princ = PrincipalData::from(contract_addr.clone()); + let contract_princ = PrincipalData::from(contract_addr); let tx_bytes = make_stacks_transfer( &contract_sk, 5, @@ -487,7 +462,7 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); + eprintln!("Err: {e:?}"); assert!(if let MemPoolRejection::TransferRecipientIsSender(r) = e { r == contract_princ } else { @@ -517,15 +492,11 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::BadAddressVersionByte = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::BadAddressVersionByte)); // tx version must be testnet - let contract_princ = PrincipalData::from(contract_addr.clone()); + let contract_princ = PrincipalData::from(contract_addr); let payload = TransactionPayload::TokenTransfer( contract_princ.clone(), 1000, @@ -551,12 +522,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::BadTransactionVersion = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::BadTransactionVersion)); // send amount must be positive let tx_bytes = @@ -572,12 +539,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::TransferAmountMustBePositive = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::TransferAmountMustBePositive)); // not enough funds let tx_bytes = make_stacks_transfer( @@ -599,12 +562,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NotEnoughFunds(111000, 99500) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NotEnoughFunds(111000, 99500))); let tx_bytes = make_stacks_transfer( &contract_sk, @@ -625,12 +584,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NotEnoughFunds(100700, 99500) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NotEnoughFunds(100700, 99500))); let tx_bytes = make_contract_call( &contract_sk, @@ -653,12 +608,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NoSuchContract = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NoSuchContract)); let tx_bytes = make_contract_call( &contract_sk, @@ -681,12 +632,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NoSuchPublicFunction = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NoSuchPublicFunction)); let tx_bytes = make_contract_call( &contract_sk, @@ -709,12 +656,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::BadFunctionArgument(_) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::BadFunctionArgument(_))); let tx_bytes = make_contract_publish( &contract_sk, @@ -735,12 +678,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::ContractAlreadyExists(_) = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::ContractAlreadyExists(_))); let microblock_1 = StacksMicroblockHeader { version: 0, @@ -777,13 +716,13 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); + eprintln!("Err: {e:?}"); assert!(matches!(e, MemPoolRejection::Other(_))); let microblock_1 = StacksMicroblockHeader { version: 0, sequence: 0, - prev_block: block_hash.clone(), + prev_block: *block_hash, tx_merkle_root: Sha512Trunc256Sum::from_data(&[]), signature: MessageSignature([0; 65]), }; @@ -791,7 +730,7 @@ fn mempool_setup_chainstate() { let microblock_2 = StacksMicroblockHeader { version: 0, sequence: 0, - prev_block: block_hash.clone(), + prev_block: *block_hash, tx_merkle_root: Sha512Trunc256Sum::from_data(&[1, 2, 3]), signature: MessageSignature([0; 65]), }; @@ -815,7 +754,7 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); + eprintln!("Err: {e:?}"); assert!(matches!(e, MemPoolRejection::Other(_))); let mut microblock_1 = StacksMicroblockHeader { @@ -856,7 +795,7 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); + eprintln!("Err: {e:?}"); assert!(matches!(e, MemPoolRejection::Other(_))); let tx_bytes = make_coinbase(&contract_sk, 5, 1000, CHAIN_ID_TESTNET); @@ -871,12 +810,8 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); - assert!(if let MemPoolRejection::NoCoinbaseViaMempool = e { - true - } else { - false - }); + eprintln!("Err: {e:?}"); + assert!(matches!(e, MemPoolRejection::NoCoinbaseViaMempool)); // find the correct priv-key let mut secret_key = None; @@ -936,12 +871,12 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - eprintln!("Err: {:?}", e); + eprintln!("Err: {e:?}"); assert!(matches!(e, MemPoolRejection::Other(_))); let contract_id = QualifiedContractIdentifier::new( - StandardPrincipalData::from(contract_addr.clone()), - ContractName::try_from("implement-trait-contract").unwrap(), + StandardPrincipalData::from(contract_addr), + ContractName::from("implement-trait-contract"), ); let contract_principal = PrincipalData::Contract(contract_id.clone()); @@ -968,8 +903,8 @@ fn mempool_setup_chainstate() { .unwrap(); let contract_id = QualifiedContractIdentifier::new( - StandardPrincipalData::from(contract_addr.clone()), - ContractName::try_from("bad-trait-contract").unwrap(), + StandardPrincipalData::from(contract_addr), + ContractName::from("bad-trait-contract"), ); let contract_principal = PrincipalData::Contract(contract_id.clone()); @@ -994,11 +929,7 @@ fn mempool_setup_chainstate() { tx_bytes.len() as u64, ) .unwrap_err(); - assert!(if let MemPoolRejection::BadFunctionArgument(_) = e { - true - } else { - false - }); + assert!(matches!(e, MemPoolRejection::BadFunctionArgument(_))); } }, ); diff --git a/testnet/stacks-node/src/tests/mod.rs b/testnet/stacks-node/src/tests/mod.rs index 2c555e7232..6f02ecf138 100644 --- a/testnet/stacks-node/src/tests/mod.rs +++ b/testnet/stacks-node/src/tests/mod.rs @@ -81,11 +81,11 @@ pub const STORE_CONTRACT: &str = r#"(define-map store { key: (string-ascii 32) } (ok true)))"#; // ./blockstack-cli --testnet publish 043ff5004e3d695060fa48ac94c96049b8c14ef441c50a184a6a3875d2a000f3 0 0 store /tmp/out.clar -pub const SK_1: &'static str = "a1289f6438855da7decf9b61b852c882c398cff1446b2a0f823538aa2ebef92e01"; -pub const SK_2: &'static str = "4ce9a8f7539ea93753a36405b16e8b57e15a552430410709c2b6d65dca5c02e201"; -pub const SK_3: &'static str = "cb95ddd0fe18ec57f4f3533b95ae564b3f1ae063dbf75b46334bd86245aef78501"; +pub const SK_1: &str = "a1289f6438855da7decf9b61b852c882c398cff1446b2a0f823538aa2ebef92e01"; +pub const SK_2: &str = "4ce9a8f7539ea93753a36405b16e8b57e15a552430410709c2b6d65dca5c02e201"; +pub const SK_3: &str = "cb95ddd0fe18ec57f4f3533b95ae564b3f1ae063dbf75b46334bd86245aef78501"; -pub const ADDR_4: &'static str = "ST31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZZ239N96"; +pub const ADDR_4: &str = "ST31DA6FTSJX2WGTZ69SFY11BH51NZMB0ZZ239N96"; lazy_static! { pub static ref PUBLISH_CONTRACT: Vec = make_contract_publish( @@ -133,6 +133,7 @@ pub fn insert_new_port(port: u16) -> bool { ports.insert(port) } +#[allow(clippy::too_many_arguments)] pub fn serialize_sign_sponsored_sig_tx_anchor_mode_version( payload: TransactionPayload, sender: &StacksPrivateKey, @@ -215,6 +216,7 @@ pub fn serialize_sign_standard_single_sig_tx_anchor_mode_version( ) } +#[allow(clippy::too_many_arguments)] pub fn serialize_sign_tx_anchor_mode_version( payload: TransactionPayload, sender: &StacksPrivateKey, @@ -401,10 +403,10 @@ pub fn set_random_binds(config: &mut Config) { let rpc_port = gen_random_port(); let p2p_port = gen_random_port(); let localhost = "127.0.0.1"; - config.node.rpc_bind = format!("{}:{}", localhost, rpc_port); - config.node.p2p_bind = format!("{}:{}", localhost, p2p_port); - config.node.data_url = format!("http://{}:{}", localhost, rpc_port); - config.node.p2p_address = format!("{}:{}", localhost, p2p_port); + config.node.rpc_bind = format!("{localhost}:{rpc_port}"); + config.node.p2p_bind = format!("{localhost}:{p2p_port}"); + config.node.data_url = format!("http://{localhost}:{rpc_port}"); + config.node.p2p_address = format!("{localhost}:{p2p_port}"); } pub fn to_addr(sk: &StacksPrivateKey) -> StacksAddress { @@ -427,9 +429,10 @@ pub fn make_stacks_transfer( ) -> Vec { let payload = TransactionPayload::TokenTransfer(recipient.clone(), amount, TokenTransferMemo([0; 34])); - serialize_sign_standard_single_sig_tx(payload.into(), sender, nonce, tx_fee, chain_id) + serialize_sign_standard_single_sig_tx(payload, sender, nonce, tx_fee, chain_id) } +#[allow(clippy::too_many_arguments)] pub fn make_sponsored_stacks_transfer_on_testnet( sender: &StacksPrivateKey, payer: &StacksPrivateKey, @@ -443,7 +446,7 @@ pub fn make_sponsored_stacks_transfer_on_testnet( let payload = TransactionPayload::TokenTransfer(recipient.clone(), amount, TokenTransferMemo([0; 34])); serialize_sign_sponsored_sig_tx_anchor_mode_version( - payload.into(), + payload, sender, payer, sender_nonce, @@ -466,7 +469,7 @@ pub fn make_stacks_transfer_mblock_only( let payload = TransactionPayload::TokenTransfer(recipient.clone(), amount, TokenTransferMemo([0; 34])); serialize_sign_standard_single_sig_tx_anchor_mode( - payload.into(), + payload, sender, nonce, tx_fee, @@ -484,14 +487,15 @@ pub fn make_poison( header_2: StacksMicroblockHeader, ) -> Vec { let payload = TransactionPayload::PoisonMicroblock(header_1, header_2); - serialize_sign_standard_single_sig_tx(payload.into(), sender, nonce, tx_fee, chain_id) + serialize_sign_standard_single_sig_tx(payload, sender, nonce, tx_fee, chain_id) } pub fn make_coinbase(sender: &StacksPrivateKey, nonce: u64, tx_fee: u64, chain_id: u32) -> Vec { let payload = TransactionPayload::Coinbase(CoinbasePayload([0; 32]), None, None); - serialize_sign_standard_single_sig_tx(payload.into(), sender, nonce, tx_fee, chain_id) + serialize_sign_standard_single_sig_tx(payload, sender, nonce, tx_fee, chain_id) } +#[allow(clippy::too_many_arguments)] pub fn make_contract_call( sender: &StacksPrivateKey, nonce: u64, @@ -506,15 +510,16 @@ pub fn make_contract_call( let function_name = ClarityName::from(function_name); let payload = TransactionContractCall { - address: contract_addr.clone(), + address: *contract_addr, contract_name, function_name, - function_args: function_args.iter().map(|x| x.clone()).collect(), + function_args: function_args.to_vec(), }; serialize_sign_standard_single_sig_tx(payload.into(), sender, nonce, tx_fee, chain_id) } +#[allow(clippy::too_many_arguments)] pub fn make_contract_call_mblock_only( sender: &StacksPrivateKey, nonce: u64, @@ -529,10 +534,10 @@ pub fn make_contract_call_mblock_only( let function_name = ClarityName::from(function_name); let payload = TransactionContractCall { - address: contract_addr.clone(), + address: *contract_addr, contract_name, function_name, - function_args: function_args.iter().map(|x| x.clone()).collect(), + function_args: function_args.to_vec(), }; serialize_sign_standard_single_sig_tx_anchor_mode( @@ -558,7 +563,7 @@ fn make_microblock( let mut microblock_builder = StacksMicroblockBuilder::new( block.block_hash(), - consensus_hash.clone(), + consensus_hash, chainstate, burn_dbconn, BlockBuilderSettings::max_value(), @@ -576,10 +581,9 @@ fn make_microblock( // NOTE: we intentionally do not check the block's microblock pubkey hash against the private // key, because we may need to test that microblocks get rejected due to bad signatures. - let microblock = microblock_builder + microblock_builder .mine_next_microblock_from_txs(mempool_txs, privk) - .unwrap(); - microblock + .unwrap() } /// Deserializes the `StacksTransaction` objects from `blocks` and returns all those that @@ -601,7 +605,7 @@ pub fn select_transactions_where( } } - return result; + result } /// This function will call `next_block_and_wait` until the burnchain height underlying `BitcoinRegtestController` @@ -614,20 +618,19 @@ pub fn run_until_burnchain_height( target_height: u64, conf: &Config, ) -> bool { - let tip_info = get_chain_info(&conf); + let tip_info = get_chain_info(conf); let mut current_height = tip_info.burn_block_height; while current_height < target_height { eprintln!( - "run_until_burnchain_height: Issuing block at {}, current_height burnchain height is ({})", - get_epoch_time_secs(), - current_height + "run_until_burnchain_height: Issuing block at {}, current_height burnchain height is ({current_height})", + get_epoch_time_secs() ); - let next_result = next_block_and_wait(btc_regtest_controller, &blocks_processed); + let next_result = next_block_and_wait(btc_regtest_controller, blocks_processed); if !next_result { return false; } - let tip_info = get_chain_info(&conf); + let tip_info = get_chain_info(conf); current_height = tip_info.burn_block_height; } @@ -717,7 +720,6 @@ fn should_succeed_mining_valid_txs() { }, _ => {} }; - return }); // Use block's hook for asserting expectations @@ -743,18 +745,18 @@ fn should_succeed_mining_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the smart contract published let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::SmartContract(..) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::SmartContract(..) + )); // 0 event should have been produced let events: Vec = chain_tip @@ -762,7 +764,7 @@ fn should_succeed_mining_valid_txs() { .iter() .flat_map(|a| a.events.clone()) .collect(); - assert!(events.len() == 0); + assert!(events.is_empty()); } 2 => { // Inspecting the chain at round 2. @@ -775,18 +777,18 @@ fn should_succeed_mining_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the get-value contract-call let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::ContractCall(_) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::ContractCall(_) + )); // 2 lockup events should have been produced let events: Vec = chain_tip @@ -807,18 +809,18 @@ fn should_succeed_mining_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the set-value contract-call let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::ContractCall(_) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::ContractCall(_) + )); // 2 lockup events + 1 contract event should have been produced let events: Vec = chain_tip @@ -832,7 +834,7 @@ fn should_succeed_mining_valid_txs() { format!("{}", data.key.0) == "STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.store" && data.key.1 == "print" - && format!("{}", data.value) == "\"Setting key foo\"".to_string() + && format!("{}", data.value) == "\"Setting key foo\"" } _ => false, }); @@ -848,18 +850,18 @@ fn should_succeed_mining_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the get-value contract-call let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::ContractCall(_) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::ContractCall(_) + )); // 1 event should have been produced let events: Vec = chain_tip @@ -873,7 +875,7 @@ fn should_succeed_mining_valid_txs() { format!("{}", data.key.0) == "STGT7GSMZG7EA0TS6MVSKT5JC1DCDFGZWJJZXN8A.store" && data.key.1 == "print" - && format!("{}", data.value) == "\"Getting key foo\"".to_string() + && format!("{}", data.value) == "\"Getting key foo\"" } _ => false, }); @@ -889,19 +891,19 @@ fn should_succeed_mining_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the STX transfer let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::TokenTransfer(_, _, _) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::TokenTransfer(_, _, _) + )); // 1 event should have been produced let events: Vec = chain_tip @@ -996,7 +998,6 @@ fn should_succeed_handling_malformed_and_valid_txs() { }, _ => {} }; - return }); // Use block's hook for asserting expectations @@ -1014,10 +1015,10 @@ fn should_succeed_handling_malformed_and_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); } 1 => { // Inspecting the chain at round 1. @@ -1030,18 +1031,18 @@ fn should_succeed_handling_malformed_and_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the smart contract published let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::SmartContract(..) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::SmartContract(..) + )); } 2 => { // Inspecting the chain at round 2. @@ -1054,10 +1055,10 @@ fn should_succeed_handling_malformed_and_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); } 3 => { // Inspecting the chain at round 3. @@ -1070,10 +1071,10 @@ fn should_succeed_handling_malformed_and_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); } 4 => { // Inspecting the chain at round 4. @@ -1086,18 +1087,18 @@ fn should_succeed_handling_malformed_and_valid_txs() { // Transaction #1 should be the coinbase from the leader let coinbase_tx = &chain_tip.block.txs[0]; assert!(coinbase_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match coinbase_tx.payload { - TransactionPayload::Coinbase(..) => true, - _ => false, - }); + assert!(matches!( + coinbase_tx.payload, + TransactionPayload::Coinbase(..) + )); // Transaction #2 should be the contract-call let contract_tx = &chain_tip.block.txs[1]; assert!(contract_tx.chain_id == CHAIN_ID_TESTNET); - assert!(match contract_tx.payload { - TransactionPayload::ContractCall(_) => true, - _ => false, - }); + assert!(matches!( + contract_tx.payload, + TransactionPayload::ContractCall(_) + )); } _ => {} } diff --git a/testnet/stacks-node/src/tests/nakamoto_integrations.rs b/testnet/stacks-node/src/tests/nakamoto_integrations.rs index b5140a06ee..3e9f235424 100644 --- a/testnet/stacks-node/src/tests/nakamoto_integrations.rs +++ b/testnet/stacks-node/src/tests/nakamoto_integrations.rs @@ -200,9 +200,7 @@ impl TestSigningChannel { /// TODO: update to use signatures vec pub fn get_signature() -> Option> { let mut signer = TEST_SIGNING.lock().unwrap(); - let Some(sign_channels) = signer.as_mut() else { - return None; - }; + let sign_channels = signer.as_mut()?; let recv = sign_channels.recv.take().unwrap(); drop(signer); // drop signer so we don't hold the lock while receiving. let signatures = recv.recv_timeout(Duration::from_secs(30)).unwrap(); @@ -362,7 +360,7 @@ pub fn blind_signer_multinode( thread::sleep(Duration::from_secs(2)); info!("Checking for a block proposal to sign..."); last_count = cur_count; - let configs: Vec<&Config> = configs.iter().map(|x| x).collect(); + let configs: Vec<&Config> = configs.iter().collect(); match read_and_sign_block_proposal(configs.as_slice(), &signers, &signed_blocks, &sender) { Ok(signed_block) => { if signed_blocks.contains(&signed_block) { @@ -427,10 +425,12 @@ pub fn get_latest_block_proposal( .collect(); proposed_blocks.sort_by(|(block_a, _, is_latest_a), (block_b, _, is_latest_b)| { - if block_a.header.chain_length > block_b.header.chain_length { - return std::cmp::Ordering::Greater; - } else if block_a.header.chain_length < block_b.header.chain_length { - return std::cmp::Ordering::Less; + let res = block_a + .header + .chain_length + .cmp(&block_b.header.chain_length); + if res != std::cmp::Ordering::Equal { + return res; } // the heights are tied, tie break with the latest miner if *is_latest_a { @@ -439,7 +439,7 @@ pub fn get_latest_block_proposal( if *is_latest_b { return std::cmp::Ordering::Less; } - return std::cmp::Ordering::Equal; + std::cmp::Ordering::Equal }); for (b, _, is_latest) in proposed_blocks.iter() { @@ -542,7 +542,7 @@ pub fn read_and_sign_block_proposal( channel .send(proposed_block.header.signer_signature) .unwrap(); - return Ok(signer_sig_hash); + Ok(signer_sig_hash) } /// Return a working nakamoto-neon config and the miner's bitcoin address to fund @@ -585,12 +585,12 @@ pub fn naka_neon_integration_conf(seed: Option<&[u8]>) -> (Config, StacksAddress burnchain.peer_host = Some("127.0.0.1".to_string()); } - conf.burnchain.magic_bytes = MagicBytes::from(['T' as u8, '3' as u8].as_ref()); + conf.burnchain.magic_bytes = MagicBytes::from([b'T', b'3'].as_ref()); conf.burnchain.poll_time_secs = 1; conf.node.pox_sync_sample_secs = 0; - conf.miner.first_attempt_time_ms = i64::max_value() as u64; - conf.miner.subsequent_attempt_time_ms = i64::max_value() as u64; + conf.miner.first_attempt_time_ms = i64::MAX as u64; + conf.miner.subsequent_attempt_time_ms = i64::MAX as u64; // if there's just one node, then this must be true for tests to pass conf.miner.wait_for_block_download = false; @@ -709,7 +709,7 @@ pub fn next_block_and_wait_for_commits( coord_channels: &[&Arc>], commits_submitted: &[&Arc], ) -> Result<(), String> { - let commits_submitted: Vec<_> = commits_submitted.iter().cloned().collect(); + let commits_submitted: Vec<_> = commits_submitted.to_vec(); let blocks_processed_before: Vec<_> = coord_channels .iter() .map(|x| { @@ -786,7 +786,7 @@ pub fn setup_stacker(naka_conf: &mut Config) -> Secp256k1PrivateKey { let stacker_sk = Secp256k1PrivateKey::new(); let stacker_address = tests::to_addr(&stacker_sk); naka_conf.add_initial_balance( - PrincipalData::from(stacker_address.clone()).to_string(), + PrincipalData::from(stacker_address).to_string(), POX_4_DEFAULT_STACKER_BALANCE, ); stacker_sk @@ -813,17 +813,17 @@ pub fn boot_to_epoch_3( "Epoch 3.0 Boundary" => (epoch_3.start_height - 1), ); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); - next_block_and_wait(btc_regtest_controller, &blocks_processed); - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); // first mined stacks block - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); let start_time = Instant::now(); loop { if start_time.elapsed() > Duration::from_secs(20) { panic!("Timed out waiting for the stacks height to increment") } - let stacks_height = get_chain_info(&naka_conf).stacks_tip_height; + let stacks_height = get_chain_info(naka_conf).stacks_tip_height; if stacks_height >= 1 { break; } @@ -840,13 +840,13 @@ pub fn boot_to_epoch_3( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( &pox_addr, - &signer_sk, + signer_sk, reward_cycle.into(), &Pox4SignatureTopic::StackStx, naka_conf.burnchain.chain_id, @@ -860,7 +860,7 @@ pub fn boot_to_epoch_3( let signer_pk = StacksPublicKey::from_private(signer_sk); let stacking_tx = tests::make_contract_call( - &stacker_sk, + stacker_sk, 0, 1000, naka_conf.burnchain.chain_id, @@ -900,9 +900,9 @@ pub fn boot_to_epoch_3( // Run until the prepare phase run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, reward_set_calculation, - &naka_conf, + naka_conf, ); // We need to vote on the aggregate public key if this test is self signing @@ -943,9 +943,9 @@ pub fn boot_to_epoch_3( run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, epoch_3.start_height - 1, - &naka_conf, + naka_conf, ); info!("Bootstrapped to Epoch-3.0 boundary, Epoch2x miner should stop"); @@ -975,17 +975,17 @@ pub fn boot_to_pre_epoch_3_boundary( "Epoch 3.0 Boundary" => (epoch_3.start_height - 1), ); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); - next_block_and_wait(btc_regtest_controller, &blocks_processed); - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); // first mined stacks block - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); let start_time = Instant::now(); loop { if start_time.elapsed() > Duration::from_secs(20) { panic!("Timed out waiting for the stacks height to increment") } - let stacks_height = get_chain_info(&naka_conf).stacks_tip_height; + let stacks_height = get_chain_info(naka_conf).stacks_tip_height; if stacks_height >= 1 { break; } @@ -1002,13 +1002,13 @@ pub fn boot_to_pre_epoch_3_boundary( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( &pox_addr, - &signer_sk, + signer_sk, reward_cycle.into(), &Pox4SignatureTopic::StackStx, naka_conf.burnchain.chain_id, @@ -1022,7 +1022,7 @@ pub fn boot_to_pre_epoch_3_boundary( let signer_pk = StacksPublicKey::from_private(signer_sk); let stacking_tx = tests::make_contract_call( - &stacker_sk, + stacker_sk, 0, 1000, naka_conf.burnchain.chain_id, @@ -1062,9 +1062,9 @@ pub fn boot_to_pre_epoch_3_boundary( // Run until the prepare phase run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, reward_set_calculation, - &naka_conf, + naka_conf, ); // We need to vote on the aggregate public key if this test is self signing @@ -1105,9 +1105,9 @@ pub fn boot_to_pre_epoch_3_boundary( run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, epoch_3.start_height - 2, - &naka_conf, + naka_conf, ); info!("Bootstrapped to one block before Epoch 3.0 boundary, Epoch 2.x miner should continue for one more block"); @@ -1191,7 +1191,7 @@ pub fn is_key_set_for_cycle( is_mainnet: bool, http_origin: &str, ) -> Result { - let key = get_key_for_cycle(reward_cycle, is_mainnet, &http_origin)?; + let key = get_key_for_cycle(reward_cycle, is_mainnet, http_origin)?; Ok(key.is_some()) } @@ -1218,10 +1218,10 @@ pub fn setup_epoch_3_reward_set( let epoch_3_reward_cycle_boundary = epoch_3_start_height.saturating_sub(epoch_3_start_height % reward_cycle_len); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); - next_block_and_wait(btc_regtest_controller, &blocks_processed); - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); // first mined stacks block - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); // stack enough to activate pox-4 let block_height = btc_regtest_controller.get_headers_height(); @@ -1241,13 +1241,13 @@ pub fn setup_epoch_3_reward_set( for (stacker_sk, signer_sk) in stacker_sks.iter().zip(signer_sks.iter()) { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( &pox_addr, - &signer_sk, + signer_sk, reward_cycle.into(), &Pox4SignatureTopic::StackStx, naka_conf.burnchain.chain_id, @@ -1260,7 +1260,7 @@ pub fn setup_epoch_3_reward_set( let signer_pk = StacksPublicKey::from_private(signer_sk); let stacking_tx = tests::make_contract_call( - &stacker_sk, + stacker_sk, 0, 1000, naka_conf.burnchain.chain_id, @@ -1322,9 +1322,9 @@ pub fn boot_to_epoch_3_reward_set_calculation_boundary( run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, epoch_3_reward_set_calculation_boundary, - &naka_conf, + naka_conf, ); info!("Bootstrapped to Epoch 3.0 reward set calculation boundary height: {epoch_3_reward_set_calculation_boundary}."); @@ -1364,9 +1364,9 @@ pub fn boot_to_epoch_25( ); run_until_burnchain_height( btc_regtest_controller, - &blocks_processed, + blocks_processed, epoch_25_start_height, - &naka_conf, + naka_conf, ); info!("Bootstrapped to Epoch 2.5: {epoch_25_start_height}."); } @@ -1391,7 +1391,7 @@ pub fn boot_to_epoch_3_reward_set( btc_regtest_controller, num_stacking_cycles, ); - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); info!( "Bootstrapped to Epoch 3.0 reward set calculation height: {}", get_chain_info(naka_conf).burn_block_height @@ -1426,7 +1426,7 @@ fn simple_neon_integration() { } let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(5); let sender_sk = Secp256k1PrivateKey::new(); @@ -1435,16 +1435,13 @@ fn simple_neon_integration() { let send_amt = 1000; let send_fee = 100; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), send_amt * 2 + send_fee, ); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + let mut signers = TestSigners::new(vec![sender_signer_sk]); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -1502,7 +1499,7 @@ fn simple_neon_integration() { #[cfg(feature = "monitoring_prom")] { wait_for(10, || { - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); let client = reqwest::blocking::Client::new(); let res = client .get(&prom_http_origin) @@ -1569,8 +1566,7 @@ fn simple_neon_integration() { .as_array() .unwrap() .iter() - .find(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) - .is_some() + .any(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) }); Ok(transfer_tx_included) }) @@ -1598,17 +1594,13 @@ fn simple_neon_integration() { ); // assert that the transfer tx was observed - let transfer_tx_included = test_observer::get_blocks() - .into_iter() - .find(|block_json| { - block_json["transactions"] - .as_array() - .unwrap() - .iter() - .find(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) - .is_some() - }) - .is_some(); + let transfer_tx_included = test_observer::get_blocks().into_iter().any(|block_json| { + block_json["transactions"] + .as_array() + .unwrap() + .iter() + .any(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) + }); assert!( transfer_tx_included, @@ -1626,7 +1618,7 @@ fn simple_neon_integration() { #[cfg(feature = "monitoring_prom")] { wait_for(10, || { - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); let client = reqwest::blocking::Client::new(); let res = client .get(&prom_http_origin) @@ -1676,7 +1668,7 @@ fn flash_blocks_on_epoch_3() { } let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1); let sender_sk = Secp256k1PrivateKey::new(); @@ -1685,16 +1677,13 @@ fn flash_blocks_on_epoch_3() { let send_amt = 1000; let send_fee = 100; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), send_amt * 2 + send_fee, ); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + let mut signers = TestSigners::new(vec![sender_signer_sk]); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -1852,17 +1841,13 @@ fn flash_blocks_on_epoch_3() { ); // assert that the transfer tx was observed - let transfer_tx_included = test_observer::get_blocks() - .into_iter() - .find(|block_json| { - block_json["transactions"] - .as_array() - .unwrap() - .iter() - .find(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) - .is_some() - }) - .is_some(); + let transfer_tx_included = test_observer::get_blocks().into_iter().any(|block_json| { + block_json["transactions"] + .as_array() + .unwrap() + .iter() + .any(|tx_json| tx_json["raw_tx"].as_str() == Some(&transfer_tx_hex)) + }); assert!( transfer_tx_included, @@ -1898,18 +1883,13 @@ fn flash_blocks_on_epoch_3() { // Verify that there's a gap of AT LEAST 3 blocks assert!( gap_end - gap_start + 1 >= 3, - "Expected a gap of AT LEAST 3 burn blocks due to flash blocks, found gap from {} to {}", - gap_start, - gap_end + "Expected a gap of AT LEAST 3 burn blocks due to flash blocks, found gap from {gap_start} to {gap_end}" ); // Verify that the gap includes the Epoch 3.0 activation height assert!( gap_start <= epoch_3_start_height && epoch_3_start_height <= gap_end, - "Expected the gap ({}..={}) to include the Epoch 3.0 activation height ({})", - gap_start, - gap_end, - epoch_3_start_height + "Expected the gap ({gap_start}..={gap_end}) to include the Epoch 3.0 activation height ({epoch_3_start_height})" ); // Verify blocks before and after the gap @@ -1918,7 +1898,7 @@ fn flash_blocks_on_epoch_3() { check_nakamoto_empty_block_heuristics(); info!("Verified burn block ranges, including expected gap for flash blocks"); - info!("Confirmed that the gap includes the Epoch 3.0 activation height (Bitcoin block height): {}", epoch_3_start_height); + info!("Confirmed that the gap includes the Epoch 3.0 activation height (Bitcoin block height): {epoch_3_start_height}"); coord_channel .lock() @@ -1957,13 +1937,10 @@ fn mine_multiple_per_tenure_integration() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -1993,7 +1970,7 @@ fn mine_multiple_per_tenure_integration() { .spawn(move || run_loop.start(None, 0)) .unwrap(); wait_for_runloop(&blocks_processed); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); boot_to_epoch_3( &naka_conf, &blocks_processed, @@ -2028,7 +2005,7 @@ fn mine_multiple_per_tenure_integration() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - debug!("Mining tenure {}", tenure_ix); + debug!("Mining tenure {tenure_ix}"); let commits_before = commits_submitted.load(Ordering::SeqCst); next_block_and_process_new_stacks_block(&mut btc_regtest_controller, 60, &coord_channel) .unwrap(); @@ -2145,22 +2122,19 @@ fn multiple_miners() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); let mut conf_node_2 = naka_conf.clone(); let localhost = "127.0.0.1"; - conf_node_2.node.rpc_bind = format!("{}:{}", localhost, node_2_rpc); - conf_node_2.node.p2p_bind = format!("{}:{}", localhost, node_2_p2p); - conf_node_2.node.data_url = format!("http://{}:{}", localhost, node_2_rpc); - conf_node_2.node.p2p_address = format!("{}:{}", localhost, node_2_p2p); + conf_node_2.node.rpc_bind = format!("{localhost}:{node_2_rpc}"); + conf_node_2.node.p2p_bind = format!("{localhost}:{node_2_p2p}"); + conf_node_2.node.data_url = format!("http://{localhost}:{node_2_rpc}"); + conf_node_2.node.p2p_address = format!("{localhost}:{node_2_p2p}"); conf_node_2.node.seed = vec![2, 2, 2, 2]; conf_node_2.burnchain.local_mining_public_key = Some( Keychain::default(conf_node_2.node.seed.clone()) @@ -2175,7 +2149,7 @@ fn multiple_miners() { let node_1_sk = Secp256k1PrivateKey::from_seed(&naka_conf.node.local_peer_seed); let node_1_pk = StacksPublicKey::from_private(&node_1_sk); - conf_node_2.node.working_dir = format!("{}-{}", conf_node_2.node.working_dir, "1"); + conf_node_2.node.working_dir = format!("{}-1", conf_node_2.node.working_dir); conf_node_2.node.set_bootstrap_nodes( format!("{}@{}", &node_1_pk.to_hex(), naka_conf.node.p2p_bind), @@ -2243,7 +2217,7 @@ fn multiple_miners() { .unwrap(); wait_for_runloop(&blocks_processed); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); boot_to_epoch_3( &naka_conf, &blocks_processed, @@ -2286,7 +2260,7 @@ fn multiple_miners() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - info!("Mining tenure {}", tenure_ix); + info!("Mining tenure {tenure_ix}"); let commits_before = commits_submitted.load(Ordering::SeqCst); next_block_and_process_new_stacks_block(&mut btc_regtest_controller, 60, &coord_channel) .unwrap(); @@ -2386,9 +2360,9 @@ fn correct_burn_outs() { { let epochs = naka_conf.burnchain.epochs.as_mut().unwrap(); - let epoch_24_ix = StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch24).unwrap(); - let epoch_25_ix = StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch25).unwrap(); - let epoch_30_ix = StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch30).unwrap(); + let epoch_24_ix = StacksEpoch::find_epoch_by_id(epochs, StacksEpochId::Epoch24).unwrap(); + let epoch_25_ix = StacksEpoch::find_epoch_by_id(epochs, StacksEpochId::Epoch25).unwrap(); + let epoch_30_ix = StacksEpoch::find_epoch_by_id(epochs, StacksEpochId::Epoch30).unwrap(); epochs[epoch_24_ix].end_height = 208; epochs[epoch_25_ix].start_height = 208; epochs[epoch_25_ix].end_height = 225; @@ -2411,10 +2385,7 @@ fn correct_burn_outs() { let stacker_accounts = accounts[0..3].to_vec(); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let signers = TestSigners::new(vec![sender_signer_sk]); @@ -2503,7 +2474,7 @@ fn correct_burn_outs() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&account.0).bytes, + tests::to_addr(account.0).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); @@ -2524,7 +2495,7 @@ fn correct_burn_outs() { .to_rsv(); let stacking_tx = tests::make_contract_call( - &account.0, + account.0, account.2.nonce, 1000, naka_conf.burnchain.chain_id, @@ -2586,7 +2557,7 @@ fn correct_burn_outs() { .block_height_to_reward_cycle(epoch_3.start_height) .unwrap(); - info!("first_epoch_3_cycle: {:?}", first_epoch_3_cycle); + info!("first_epoch_3_cycle: {first_epoch_3_cycle:?}"); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); let stacker_response = get_stacker_set(&http_origin, first_epoch_3_cycle).unwrap(); @@ -2732,10 +2703,7 @@ fn block_proposal_api_endpoint() { let stacker_sk = setup_stacker(&mut conf); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); // only subscribe to the block proposal events test_observer::spawn(); @@ -2760,7 +2728,7 @@ fn block_proposal_api_endpoint() { let coord_channel = run_loop.coordinator_channels(); let run_loop_thread = thread::spawn(move || run_loop.start(None, 0)); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); wait_for_runloop(&blocks_processed); boot_to_epoch_3( &conf, @@ -2814,7 +2782,7 @@ fn block_proposal_api_endpoint() { .unwrap() .unwrap(); - let privk = conf.miner.mining_key.unwrap().clone(); + let privk = conf.miner.mining_key.unwrap(); let sort_tip = SortitionDB::get_canonical_sortition_tip(sortdb.conn()) .expect("Failed to get sortition tip"); let db_handle = sortdb.index_handle(&sort_tip); @@ -2910,41 +2878,41 @@ fn block_proposal_api_endpoint() { ("Must wait", sign(&proposal), HTTP_TOO_MANY, None), ( "Non-canonical or absent tenure", - (|| { + { let mut sp = sign(&proposal); sp.block.header.consensus_hash.0[3] ^= 0x07; sp - })(), + }, HTTP_ACCEPTED, Some(Err(ValidateRejectCode::NonCanonicalTenure)), ), ( "Corrupted (bit flipped after signing)", - (|| { + { let mut sp = sign(&proposal); sp.block.header.timestamp ^= 0x07; sp - })(), + }, HTTP_ACCEPTED, Some(Err(ValidateRejectCode::ChainstateError)), ), ( "Invalid `chain_id`", - (|| { + { let mut p = proposal.clone(); p.chain_id ^= 0xFFFFFFFF; sign(&p) - })(), + }, HTTP_ACCEPTED, Some(Err(ValidateRejectCode::InvalidBlock)), ), ( "Invalid `miner_signature`", - (|| { + { let mut sp = sign(&proposal); sp.block.header.miner_signature.0[1] ^= 0x80; sp - })(), + }, HTTP_ACCEPTED, Some(Err(ValidateRejectCode::ChainstateError)), ), @@ -3042,10 +3010,7 @@ fn block_proposal_api_endpoint() { .iter() .zip(proposal_responses.iter()) { - info!( - "Received response {:?}, expecting {:?}", - &response, &expected_response - ); + info!("Received response {response:?}, expecting {expected_response:?}"); match expected_response { Ok(_) => { assert!(matches!(response, BlockValidateResponse::Ok(_))); @@ -3093,19 +3058,16 @@ fn miner_writes_proposed_block_to_stackerdb() { let send_amt = 1000; let send_fee = 100; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), send_amt + send_fee, ); let stacker_sk = setup_stacker(&mut naka_conf); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); test_observer::spawn(); test_observer::register( @@ -3216,9 +3178,9 @@ fn vote_for_aggregate_key_burn_op() { let signer_sk = Secp256k1PrivateKey::new(); let signer_addr = tests::to_addr(&signer_sk); - let mut signers = TestSigners::new(vec![signer_sk.clone()]); + let mut signers = TestSigners::new(vec![signer_sk]); - naka_conf.add_initial_balance(PrincipalData::from(signer_addr.clone()).to_string(), 100000); + naka_conf.add_initial_balance(PrincipalData::from(signer_addr).to_string(), 100000); let stacker_sk = setup_stacker(&mut naka_conf); test_observer::spawn(); @@ -3277,7 +3239,7 @@ fn vote_for_aggregate_key_burn_op() { let mut miner_signer = Keychain::default(naka_conf.node.seed.clone()).generate_op_signer(); info!("Submitting pre-stx op"); let pre_stx_op = PreStxOp { - output: signer_addr.clone(), + output: signer_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -3343,13 +3305,13 @@ fn vote_for_aggregate_key_burn_op() { let stacker_pk = StacksPublicKey::from_private(&stacker_sk); let signer_key: StacksPublicKeyBuffer = stacker_pk.to_bytes_compressed().as_slice().into(); - let aggregate_key = signer_key.clone(); + let aggregate_key = signer_key; let vote_for_aggregate_key_op = BlockstackOperationType::VoteForAggregateKey(VoteForAggregateKeyOp { signer_key, signer_index, - sender: signer_addr.clone(), + sender: signer_addr, round: 0, reward_cycle, aggregate_key, @@ -3360,7 +3322,7 @@ fn vote_for_aggregate_key_burn_op() { burn_header_hash: BurnchainHeaderHash::zero(), }); - let mut signer_burnop_signer = BurnchainOpSigner::new(signer_sk.clone(), false); + let mut signer_burnop_signer = BurnchainOpSigner::new(signer_sk, false); assert!( btc_regtest_controller .submit_operation( @@ -3393,10 +3355,10 @@ fn vote_for_aggregate_key_burn_op() { for tx in transactions.iter() { let raw_tx = tx.get("raw_tx").unwrap().as_str().unwrap(); if raw_tx == "0x00" { - info!("Found a burn op: {:?}", tx); + info!("Found a burn op: {tx:?}"); let burnchain_op = tx.get("burnchain_op").unwrap().as_object().unwrap(); if !burnchain_op.contains_key("vote_for_aggregate_key") { - warn!("Got unexpected burnchain op: {:?}", burnchain_op); + warn!("Got unexpected burnchain op: {burnchain_op:?}"); panic!("unexpected btc transaction type"); } let vote_obj = burnchain_op.get("vote_for_aggregate_key").unwrap(); @@ -3446,7 +3408,7 @@ fn follower_bootup() { let sender_sk = Secp256k1PrivateKey::new(); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); let tenure_count = 5; let inter_blocks_per_tenure = 9; // setup sender + recipient for some test stx transfers @@ -3455,13 +3417,10 @@ fn follower_bootup() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -3574,7 +3533,7 @@ fn follower_bootup() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - debug!("follower_bootup: Miner runs tenure {}", tenure_ix); + debug!("follower_bootup: Miner runs tenure {tenure_ix}"); let commits_before = commits_submitted.load(Ordering::SeqCst); next_block_and_process_new_stacks_block(&mut btc_regtest_controller, 60, &coord_channel) .unwrap(); @@ -3582,10 +3541,7 @@ fn follower_bootup() { let mut last_tip = BlockHeaderHash([0x00; 32]); let mut last_nonce = None; - debug!( - "follower_bootup: Miner mines interum blocks for tenure {}", - tenure_ix - ); + debug!("follower_bootup: Miner mines interum blocks for tenure {tenure_ix}"); // mine the interim blocks for _ in 0..inter_blocks_per_tenure { @@ -3621,8 +3577,8 @@ fn follower_bootup() { let tx = StacksTransaction::consensus_deserialize(&mut &transfer_tx[..]).unwrap(); - debug!("follower_bootup: Miner account: {:?}", &account); - debug!("follower_bootup: Miner sent {}: {:?}", &tx.txid(), &tx); + debug!("follower_bootup: Miner account: {account:?}"); + debug!("follower_bootup: Miner sent {}: {tx:?}", &tx.txid()); let now = get_epoch_time_secs(); while get_epoch_time_secs() < now + 10 { @@ -3773,7 +3729,7 @@ fn follower_bootup_across_multiple_cycles() { let sender_sk = Secp256k1PrivateKey::new(); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); let tenure_count = 5; let inter_blocks_per_tenure = 9; // setup sender + recipient for some test stx transfers @@ -3782,13 +3738,10 @@ fn follower_bootup_across_multiple_cycles() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let stacker_sk = setup_stacker(&mut naka_conf); test_observer::spawn(); @@ -3972,7 +3925,7 @@ fn follower_bootup_custom_chain_id() { let sender_sk = Secp256k1PrivateKey::new(); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); let tenure_count = 5; let inter_blocks_per_tenure = 9; // setup sender + recipient for some test stx transfers @@ -3981,13 +3934,10 @@ fn follower_bootup_custom_chain_id() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -4100,7 +4050,7 @@ fn follower_bootup_custom_chain_id() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - debug!("follower_bootup: Miner runs tenure {}", tenure_ix); + debug!("follower_bootup: Miner runs tenure {tenure_ix}"); let commits_before = commits_submitted.load(Ordering::SeqCst); next_block_and_process_new_stacks_block(&mut btc_regtest_controller, 60, &coord_channel) .unwrap(); @@ -4108,10 +4058,7 @@ fn follower_bootup_custom_chain_id() { let mut last_tip = BlockHeaderHash([0x00; 32]); let mut last_nonce = None; - debug!( - "follower_bootup: Miner mines interum blocks for tenure {}", - tenure_ix - ); + debug!("follower_bootup: Miner mines interum blocks for tenure {tenure_ix}"); // mine the interim blocks for _ in 0..inter_blocks_per_tenure { @@ -4147,8 +4094,8 @@ fn follower_bootup_custom_chain_id() { let tx = StacksTransaction::consensus_deserialize(&mut &transfer_tx[..]).unwrap(); - debug!("follower_bootup: Miner account: {:?}", &account); - debug!("follower_bootup: Miner sent {}: {:?}", &tx.txid(), &tx); + debug!("follower_bootup: Miner account: {account:?}"); + debug!("follower_bootup: Miner sent {}: {tx:?}", &tx.txid()); let now = get_epoch_time_secs(); while get_epoch_time_secs() < now + 10 { @@ -4326,23 +4273,14 @@ fn burn_ops_integration_test() { let sender_addr = tests::to_addr(&sender_sk); let mut sender_nonce = 0; - let mut signers = TestSigners::new(vec![signer_sk_1.clone()]); + let mut signers = TestSigners::new(vec![signer_sk_1]); let stacker_sk = setup_stacker(&mut naka_conf); // Add the initial balances to the other accounts - naka_conf.add_initial_balance( - PrincipalData::from(stacker_addr_1.clone()).to_string(), - 1000000, - ); - naka_conf.add_initial_balance( - PrincipalData::from(stacker_addr_2.clone()).to_string(), - 1000000, - ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), - 100_000_000, - ); + naka_conf.add_initial_balance(PrincipalData::from(stacker_addr_1).to_string(), 1000000); + naka_conf.add_initial_balance(PrincipalData::from(stacker_addr_2).to_string(), 1000000); + naka_conf.add_initial_balance(PrincipalData::from(sender_addr).to_string(), 100_000_000); test_observer::spawn(); test_observer::register_any(&mut naka_conf); @@ -4395,7 +4333,7 @@ fn burn_ops_integration_test() { info!("Submitting first pre-stx op"); let pre_stx_op = PreStxOp { - output: signer_addr_1.clone(), + output: signer_addr_1, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -4426,7 +4364,7 @@ fn burn_ops_integration_test() { let mut miner_signer_2 = Keychain::default(naka_conf.node.seed.clone()).generate_op_signer(); info!("Submitting second pre-stx op"); let pre_stx_op_2 = PreStxOp { - output: signer_addr_2.clone(), + output: signer_addr_2, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -4448,7 +4386,7 @@ fn burn_ops_integration_test() { let mut miner_signer_3 = Keychain::default(naka_conf.node.seed.clone()).generate_op_signer(); info!("Submitting third pre-stx op"); let pre_stx_op_3 = PreStxOp { - output: stacker_addr_1.clone(), + output: stacker_addr_1, txid: Txid([0u8; 32]), vtxindex: 0, block_height: 0, @@ -4469,7 +4407,7 @@ fn burn_ops_integration_test() { info!("Submitting fourth pre-stx op"); let mut miner_signer_4 = Keychain::default(naka_conf.node.seed.clone()).generate_op_signer(); let pre_stx_op_4 = PreStxOp { - output: stacker_addr_2.clone(), + output: stacker_addr_2, txid: Txid([0u8; 32]), vtxindex: 0, block_height: 0, @@ -4566,10 +4504,10 @@ fn burn_ops_integration_test() { "reward_cycle" => reward_cycle, ); - let mut signer_burnop_signer_1 = BurnchainOpSigner::new(signer_sk_1.clone(), false); - let mut signer_burnop_signer_2 = BurnchainOpSigner::new(signer_sk_2.clone(), false); - let mut stacker_burnop_signer_1 = BurnchainOpSigner::new(stacker_sk_1.clone(), false); - let mut stacker_burnop_signer_2 = BurnchainOpSigner::new(stacker_sk_2.clone(), false); + let mut signer_burnop_signer_1 = BurnchainOpSigner::new(signer_sk_1, false); + let mut signer_burnop_signer_2 = BurnchainOpSigner::new(signer_sk_2, false); + let mut stacker_burnop_signer_1 = BurnchainOpSigner::new(stacker_sk_1, false); + let mut stacker_burnop_signer_2 = BurnchainOpSigner::new(stacker_sk_2, false); info!( "Before stack-stx op, signer 1 total: {}", @@ -4603,8 +4541,8 @@ fn burn_ops_integration_test() { info!("Submitting transfer STX op"); let transfer_stx_op = TransferStxOp { - sender: stacker_addr_1.clone(), - recipient: stacker_addr_2.clone(), + sender: stacker_addr_1, + recipient: stacker_addr_2, transfered_ustx: 10000, memo: vec![], txid: Txid([0u8; 32]), @@ -4626,8 +4564,8 @@ fn burn_ops_integration_test() { info!("Submitting delegate STX op"); let del_stx_op = DelegateStxOp { - sender: stacker_addr_2.clone(), - delegate_to: stacker_addr_1.clone(), + sender: stacker_addr_2, + delegate_to: stacker_addr_1, reward_addr: None, delegated_ustx: 100_000, // to be filled in @@ -4654,7 +4592,7 @@ fn burn_ops_integration_test() { let min_stx = pox_info.next_cycle.min_threshold_ustx; let stack_stx_op_with_some_signer_key = StackStxOp { - sender: signer_addr_1.clone(), + sender: signer_addr_1, reward_addr: pox_addr, stacked_ustx: min_stx.into(), num_cycles: lock_period, @@ -4681,7 +4619,7 @@ fn burn_ops_integration_test() { ); let stack_stx_op_with_no_signer_key = StackStxOp { - sender: signer_addr_2.clone(), + sender: signer_addr_2, reward_addr: PoxAddress::Standard(signer_addr_2, None), stacked_ustx: 100000, num_cycles: 6, @@ -4766,7 +4704,7 @@ fn burn_ops_integration_test() { for tx in transactions.iter().rev() { let raw_tx = tx.get("raw_tx").unwrap().as_str().unwrap(); if raw_tx == "0x00" { - info!("Found a burn op: {:?}", tx); + info!("Found a burn op: {tx:?}"); assert!(block_has_tenure_change, "Block should have a tenure change"); let burnchain_op = tx.get("burnchain_op").unwrap().as_object().unwrap(); if burnchain_op.contains_key("transfer_stx") { @@ -4784,15 +4722,14 @@ fn burn_ops_integration_test() { assert_eq!(recipient, stacker_addr_2.to_string()); assert_eq!(transfered_ustx, 10000); info!( - "Transfer STX op: sender: {}, recipient: {}, transfered_ustx: {}", - sender, recipient, transfered_ustx + "Transfer STX op: sender: {sender}, recipient: {recipient}, transfered_ustx: {transfered_ustx}" ); assert!(!transfer_stx_found, "Transfer STX op should be unique"); transfer_stx_found = true; continue; } if burnchain_op.contains_key("delegate_stx") { - info!("Got delegate STX op: {:?}", burnchain_op); + info!("Got delegate STX op: {burnchain_op:?}"); let delegate_stx_obj = burnchain_op.get("delegate_stx").unwrap(); let sender_obj = delegate_stx_obj.get("sender").unwrap(); let sender = sender_obj.get("address").unwrap().as_str().unwrap(); @@ -4811,7 +4748,7 @@ fn burn_ops_integration_test() { continue; } if !burnchain_op.contains_key("stack_stx") { - warn!("Got unexpected burnchain op: {:?}", burnchain_op); + warn!("Got unexpected burnchain op: {burnchain_op:?}"); panic!("unexpected btc transaction type"); } let stack_stx_obj = burnchain_op.get("stack_stx").unwrap(); @@ -4882,7 +4819,7 @@ fn burn_ops_integration_test() { for ancestor_bhh in ancestor_burnchain_header_hashes.iter().rev() { let stacking_ops = SortitionDB::get_stack_stx_ops(sortdb_conn, ancestor_bhh).unwrap(); for stacking_op in stacking_ops.into_iter() { - debug!("Stacking op queried from sortdb: {:?}", stacking_op); + debug!("Stacking op queried from sortdb: {stacking_op:?}"); match stacking_op.signer_key { Some(_) => found_some = true, None => found_none = true, @@ -4937,17 +4874,14 @@ fn forked_tenure_is_ignored() { let send_amt = 100; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), send_amt + send_fee, ); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let stacker_sk = setup_stacker(&mut naka_conf); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); @@ -5075,7 +5009,7 @@ fn forked_tenure_is_ignored() { .nakamoto_blocks_db() .get_nakamoto_tenure_start_blocks(&tip_sn.consensus_hash) .unwrap() - .get(0) + .first() .cloned() .unwrap(); @@ -5304,13 +5238,10 @@ fn check_block_heights() { let send_fee = 180; let deploy_fee = 3000; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), 3 * deploy_fee + (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -5394,12 +5325,12 @@ fn check_block_heights() { vec![], ); let preheights = heights0_value.expect_tuple().unwrap(); - info!("Heights from pre-epoch 3.0: {}", preheights); + info!("Heights from pre-epoch 3.0: {preheights}"); wait_for_first_naka_block_commit(60, &commits_submitted); let info = get_chain_info_result(&naka_conf).unwrap(); - info!("Chain info: {:?}", info); + info!("Chain info: {info:?}"); // With the first Nakamoto block, the chain tip and the number of tenures // must be the same (before Nakamoto every block counts as a tenure) @@ -5417,7 +5348,7 @@ fn check_block_heights() { vec![], ); let heights0 = heights0_value.expect_tuple().unwrap(); - info!("Heights from epoch 3.0 start: {}", heights0); + info!("Heights from epoch 3.0 start: {heights0}"); assert_eq!( heights0.get("burn-block-height"), preheights.get("burn-block-height"), @@ -5466,7 +5397,7 @@ fn check_block_heights() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - info!("Mining tenure {}", tenure_ix); + info!("Mining tenure {tenure_ix}"); let commits_before = commits_submitted.load(Ordering::SeqCst); next_block_and_process_new_stacks_block(&mut btc_regtest_controller, 60, &coord_channel) .unwrap(); @@ -5488,7 +5419,7 @@ fn check_block_heights() { vec![], ); let heights1 = heights1_value.expect_tuple().unwrap(); - info!("Heights from Clarity 1: {}", heights1); + info!("Heights from Clarity 1: {heights1}"); let heights3_value = call_read_only( &naka_conf, @@ -5498,7 +5429,7 @@ fn check_block_heights() { vec![], ); let heights3 = heights3_value.expect_tuple().unwrap(); - info!("Heights from Clarity 3: {}", heights3); + info!("Heights from Clarity 3: {heights3}"); let bbh1 = heights1 .get("burn-block-height") @@ -5598,7 +5529,7 @@ fn check_block_heights() { vec![], ); let heights1 = heights1_value.expect_tuple().unwrap(); - info!("Heights from Clarity 1: {}", heights1); + info!("Heights from Clarity 1: {heights1}"); let heights3_value = call_read_only( &naka_conf, @@ -5608,7 +5539,7 @@ fn check_block_heights() { vec![], ); let heights3 = heights3_value.expect_tuple().unwrap(); - info!("Heights from Clarity 3: {}", heights3); + info!("Heights from Clarity 3: {heights3}"); let bbh1 = heights1 .get("burn-block-height") @@ -5723,17 +5654,11 @@ fn nakamoto_attempt_time() { let sender_sk = Secp256k1PrivateKey::new(); let sender_addr = tests::to_addr(&sender_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), - 1_000_000_000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_addr).to_string(), 1_000_000_000); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100_000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100_000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); @@ -5849,7 +5774,7 @@ fn nakamoto_attempt_time() { // mine the interim blocks for tenure_count in 0..inter_blocks_per_tenure { - debug!("nakamoto_attempt_time: begin tenure {}", tenure_count); + debug!("nakamoto_attempt_time: begin tenure {tenure_count}"); let blocks_processed_before = coord_channel .lock() @@ -5987,8 +5912,7 @@ fn nakamoto_attempt_time() { break 'submit_txs; } info!( - "nakamoto_times_ms: on account {}; sent {} txs so far (out of {})", - acct_idx, tx_count, tx_limit + "nakamoto_times_ms: on account {acct_idx}; sent {tx_count} txs so far (out of {tx_limit})" ); } acct_idx += 1; @@ -6056,13 +5980,10 @@ fn clarity_burn_state() { let tx_fee = 1000; let deploy_fee = 3000; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), deploy_fee + tx_fee * tenure_count + tx_fee * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let stacker_sk = setup_stacker(&mut naka_conf); test_observer::spawn(); @@ -6139,7 +6060,7 @@ fn clarity_burn_state() { // Mine `tenure_count` nakamoto tenures for tenure_ix in 0..tenure_count { - info!("Mining tenure {}", tenure_ix); + info!("Mining tenure {tenure_ix}"); // Don't submit this tx on the first iteration, because the contract is not published yet. if tenure_ix > 0 { @@ -6200,7 +6121,7 @@ fn clarity_burn_state() { let info = get_chain_info(&naka_conf); burn_block_height = info.burn_block_height as u128; - info!("Expecting burn block height to be {}", burn_block_height); + info!("Expecting burn block height to be {burn_block_height}"); // Assert that the contract call was successful test_observer::get_mined_nakamoto_blocks() @@ -6215,11 +6136,11 @@ fn clarity_burn_state() { return; } - info!("Contract call result: {}", result); + info!("Contract call result: {result}"); result.clone().expect_result_ok().expect("Ok result"); } _ => { - info!("Unsuccessful event: {:?}", event); + info!("Unsuccessful event: {event:?}"); panic!("Expected a successful transaction"); } }); @@ -6241,7 +6162,7 @@ fn clarity_burn_state() { "foo", vec![&expected_height], ); - info!("Read-only result: {:?}", result); + info!("Read-only result: {result:?}"); result.expect_result_ok().expect("Read-only call failed"); // Submit a tx to trigger the next block @@ -6277,11 +6198,11 @@ fn clarity_burn_state() { .iter() .for_each(|event| match event { TransactionEvent::Success(TransactionSuccessEvent { result, .. }) => { - info!("Contract call result: {}", result); + info!("Contract call result: {result}"); result.clone().expect_result_ok().expect("Ok result"); } _ => { - info!("Unsuccessful event: {:?}", event); + info!("Unsuccessful event: {event:?}"); panic!("Expected a successful transaction"); } }); @@ -6307,6 +6228,7 @@ fn clarity_burn_state() { #[test] #[ignore] +#[allow(clippy::drop_non_drop)] fn signer_chainstate() { if env::var("BITCOIND_TEST") != Ok("1".into()) { return; @@ -6314,7 +6236,7 @@ fn signer_chainstate() { let mut signers = TestSigners::default(); let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + let prom_bind = "127.0.0.1:6000".to_string(); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1); @@ -6324,15 +6246,12 @@ fn signer_chainstate() { let send_amt = 1000; let send_fee = 200; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * 20, ); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -6388,7 +6307,7 @@ fn signer_chainstate() { .unwrap() .unwrap() .stacks_block_height; - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); wait_for(10, || { let client = reqwest::blocking::Client::new(); let res = client @@ -6639,13 +6558,13 @@ fn signer_chainstate() { // Case: the block doesn't confirm the prior blocks that have been signed. let last_tenure = &last_tenures_proposals.as_ref().unwrap().1.clone(); let last_tenure_header = &last_tenure.header; - let miner_sk = naka_conf.miner.mining_key.clone().unwrap(); + let miner_sk = naka_conf.miner.mining_key.unwrap(); let miner_pk = StacksPublicKey::from_private(&miner_sk); let mut sibling_block_header = NakamotoBlockHeader { version: 1, chain_length: last_tenure_header.chain_length, burn_spent: last_tenure_header.burn_spent, - consensus_hash: last_tenure_header.consensus_hash.clone(), + consensus_hash: last_tenure_header.consensus_hash, parent_block_id: last_tenure_header.block_id(), tx_merkle_root: Sha512Trunc256Sum::from_data(&[0]), state_index_root: TrieHash([0; 32]), @@ -6693,8 +6612,8 @@ fn signer_chainstate() { version: 1, chain_length: last_tenure_header.chain_length, burn_spent: last_tenure_header.burn_spent, - consensus_hash: last_tenure_header.consensus_hash.clone(), - parent_block_id: last_tenure_header.parent_block_id.clone(), + consensus_hash: last_tenure_header.consensus_hash, + parent_block_id: last_tenure_header.parent_block_id, tx_merkle_root: Sha512Trunc256Sum::from_data(&[0]), state_index_root: TrieHash([0; 32]), timestamp: last_tenure_header.timestamp + 1, @@ -6751,7 +6670,7 @@ fn signer_chainstate() { version: 1, chain_length: reorg_to_block.header.chain_length + 1, burn_spent: reorg_to_block.header.burn_spent, - consensus_hash: last_tenure_header.consensus_hash.clone(), + consensus_hash: last_tenure_header.consensus_hash, parent_block_id: reorg_to_block.block_id(), tx_merkle_root: Sha512Trunc256Sum::from_data(&[0]), state_index_root: TrieHash([0; 32]), @@ -6782,9 +6701,9 @@ fn signer_chainstate() { post_condition_mode: TransactionPostConditionMode::Allow, post_conditions: vec![], payload: TransactionPayload::TenureChange(TenureChangePayload { - tenure_consensus_hash: sibling_block_header.consensus_hash.clone(), - prev_tenure_consensus_hash: reorg_to_block.header.consensus_hash.clone(), - burn_view_consensus_hash: sibling_block_header.consensus_hash.clone(), + tenure_consensus_hash: sibling_block_header.consensus_hash, + prev_tenure_consensus_hash: reorg_to_block.header.consensus_hash, + burn_view_consensus_hash: sibling_block_header.consensus_hash, previous_tenure_end: reorg_to_block.block_id(), previous_tenure_blocks: 1, cause: stacks::chainstate::stacks::TenureChangeCause::BlockFound, @@ -6812,12 +6731,12 @@ fn signer_chainstate() { // Case: the block contains a tenure change, but the parent tenure is a reorg let reorg_to_block = first_tenure_blocks.as_ref().unwrap().last().unwrap(); // make the sortition_view *think* that our block commit pointed at this old tenure - sortitions_view.cur_sortition.parent_tenure_id = reorg_to_block.header.consensus_hash.clone(); + sortitions_view.cur_sortition.parent_tenure_id = reorg_to_block.header.consensus_hash; let mut sibling_block_header = NakamotoBlockHeader { version: 1, chain_length: reorg_to_block.header.chain_length + 1, burn_spent: reorg_to_block.header.burn_spent, - consensus_hash: last_tenure_header.consensus_hash.clone(), + consensus_hash: last_tenure_header.consensus_hash, parent_block_id: reorg_to_block.block_id(), tx_merkle_root: Sha512Trunc256Sum::from_data(&[0]), state_index_root: TrieHash([0; 32]), @@ -6848,9 +6767,9 @@ fn signer_chainstate() { post_condition_mode: TransactionPostConditionMode::Allow, post_conditions: vec![], payload: TransactionPayload::TenureChange(TenureChangePayload { - tenure_consensus_hash: sibling_block_header.consensus_hash.clone(), - prev_tenure_consensus_hash: reorg_to_block.header.consensus_hash.clone(), - burn_view_consensus_hash: sibling_block_header.consensus_hash.clone(), + tenure_consensus_hash: sibling_block_header.consensus_hash, + prev_tenure_consensus_hash: reorg_to_block.header.consensus_hash, + burn_view_consensus_hash: sibling_block_header.consensus_hash, previous_tenure_end: reorg_to_block.block_id(), previous_tenure_blocks: 1, cause: stacks::chainstate::stacks::TenureChangeCause::BlockFound, @@ -6889,7 +6808,7 @@ fn signer_chainstate() { // every step of the return should be linked to the parent let mut prior: Option<&TenureForkingInfo> = None; for step in fork_info.iter().rev() { - if let Some(ref prior) = prior { + if let Some(prior) = prior { assert_eq!(prior.sortition_id, step.parent_sortition_id); } prior = Some(step); @@ -6928,7 +6847,7 @@ fn continue_tenure_extend() { let mut signers = TestSigners::default(); let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1); let http_origin = naka_conf.node.data_url.clone(); @@ -6938,15 +6857,12 @@ fn continue_tenure_extend() { let send_amt = 1000; let send_fee = 200; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * 20, ); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); let mut transfer_nonce = 0; @@ -7005,7 +6921,7 @@ fn continue_tenure_extend() { // query for prometheus metrics #[cfg(feature = "monitoring_prom")] { - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); wait_for(10, || { let client = reqwest::blocking::Client::new(); let res = client @@ -7194,7 +7110,7 @@ fn continue_tenure_extend() { let mut has_extend = false; for tx in block["transactions"].as_array().unwrap() { let raw_tx = tx["raw_tx"].as_str().unwrap(); - if raw_tx == &transfer_tx_hex { + if raw_tx == transfer_tx_hex { transfer_tx_included = true; continue; } @@ -7203,8 +7119,9 @@ fn continue_tenure_extend() { } let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); - match &parsed.payload { - TransactionPayload::TenureChange(payload) => match payload.cause { + + if let TransactionPayload::TenureChange(payload) = &parsed.payload { + match payload.cause { TenureChangeCause::Extended => { has_extend = true; tenure_extends.push(parsed); @@ -7215,9 +7132,8 @@ fn continue_tenure_extend() { } tenure_block_founds.push(parsed); } - }, - _ => {} - }; + }; + } } last_block_had_extend = has_extend; } @@ -7242,7 +7158,7 @@ fn continue_tenure_extend() { // make sure prometheus returns an updated height #[cfg(feature = "monitoring_prom")] { - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); wait_for(10, || { let client = reqwest::blocking::Client::new(); let res = client @@ -7280,8 +7196,8 @@ fn get_block_times( info!("Getting block times at block {block_height}, tenure {tenure_height}..."); let time0_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract0_name, "get-time", vec![&clarity::vm::Value::UInt(tenure_height)], @@ -7294,8 +7210,8 @@ fn get_block_times( .unwrap(); let time_now0_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract0_name, "get-last-time", vec![], @@ -7308,8 +7224,8 @@ fn get_block_times( .unwrap(); let time1_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract1_name, "get-time", vec![&clarity::vm::Value::UInt(tenure_height)], @@ -7322,8 +7238,8 @@ fn get_block_times( .unwrap(); let time1_now_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract1_name, "get-last-time", vec![], @@ -7336,8 +7252,8 @@ fn get_block_times( .unwrap(); let time3_tenure_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract3_name, "get-tenure-time", vec![&clarity::vm::Value::UInt(block_height)], @@ -7350,8 +7266,8 @@ fn get_block_times( .unwrap(); let time3_block_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract3_name, "get-block-time", vec![&clarity::vm::Value::UInt(block_height)], @@ -7364,8 +7280,8 @@ fn get_block_times( .unwrap(); let time3_now_tenure_value = call_read_only( - &naka_conf, - &sender_addr, + naka_conf, + sender_addr, contract3_name, "get-last-tenure-time", vec![], @@ -7432,13 +7348,10 @@ fn check_block_times() { let send_fee = 180; let deploy_fee = 3000; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), 3 * deploy_fee + (send_amt + send_fee) * 12, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -7528,7 +7441,7 @@ fn check_block_times() { .unwrap() .expect_u128() .unwrap(); - info!("Time from pre-epoch 3.0: {}", time0); + info!("Time from pre-epoch 3.0: {time0}"); // This version uses the Clarity 1 / 2 function let contract1_name = "test-contract-1"; @@ -7833,13 +7746,10 @@ fn check_block_info() { let send_fee = 180; let deploy_fee = 3000; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), 3 * deploy_fee + (send_amt + send_fee) * 2, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); let contract3_name = "test-contract-3"; @@ -7971,7 +7881,7 @@ fn check_block_info() { blind_signer(&naka_conf, &signers, proposals_submitted); let c0_block_ht_1_pre_3 = get_block_info(contract0_name, 1); - info!("Info from pre-epoch 3.0: {:?}", c0_block_ht_1_pre_3); + info!("Info from pre-epoch 3.0: {c0_block_ht_1_pre_3:?}"); wait_for_first_naka_block_commit(60, &commits_submitted); @@ -8039,7 +7949,7 @@ fn check_block_info() { // one in the tenure) let info = get_chain_info(&naka_conf); - info!("Chain info: {:?}", info); + info!("Chain info: {info:?}"); let last_stacks_block_height = info.stacks_tip_height as u128; let last_stacks_tip = StacksBlockId::new(&info.stacks_tip_consensus_hash, &info.stacks_tip); let last_tenure_height: u128 = @@ -8062,7 +7972,7 @@ fn check_block_info() { .unwrap(); let info = get_chain_info(&naka_conf); - info!("Chain info: {:?}", info); + info!("Chain info: {info:?}"); let cur_stacks_block_height = info.stacks_tip_height as u128; let cur_stacks_tip = StacksBlockId::new(&info.stacks_tip_consensus_hash, &info.stacks_tip); let cur_tenure_height: u128 = @@ -8381,7 +8291,7 @@ fn check_block_info() { run_loop_thread.join().unwrap(); } -fn get_expected_reward_for_height(blocks: &Vec, block_height: u128) -> u128 { +fn get_expected_reward_for_height(blocks: &[serde_json::Value], block_height: u128) -> u128 { // Find the target block let target_block = blocks .iter() @@ -8468,13 +8378,10 @@ fn check_block_info_rewards() { let send_fee = 180; let deploy_fee = 3000; naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), 3 * deploy_fee + (send_amt + send_fee) * 2, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -8560,7 +8467,7 @@ fn check_block_info_rewards() { blind_signer(&naka_conf, &signers, proposals_submitted); let tuple0 = get_block_info(contract0_name, 1); - info!("Info from pre-epoch 3.0: {:?}", tuple0); + info!("Info from pre-epoch 3.0: {tuple0:?}"); wait_for_first_naka_block_commit(60, &commits_submitted); @@ -8672,7 +8579,7 @@ fn check_block_info_rewards() { } let info = get_chain_info_result(&naka_conf).unwrap(); - info!("Chain info: {:?}", info); + info!("Chain info: {info:?}"); let (chainstate, _) = StacksChainState::open( naka_conf.is_mainnet(), naka_conf.burnchain.chain_id, @@ -8705,7 +8612,7 @@ fn check_block_info_rewards() { } let info = get_chain_info_result(&naka_conf).unwrap(); - info!("Chain info: {:?}", info); + info!("Chain info: {info:?}"); let last_stacks_block_height = info.stacks_tip_height as u128; let blocks = test_observer::get_blocks(); @@ -8797,7 +8704,7 @@ fn mock_mining() { let sender_sk = Secp256k1PrivateKey::new(); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); + let mut signers = TestSigners::new(vec![sender_signer_sk]); let tenure_count = 3; let inter_blocks_per_tenure = 3; // setup sender + recipient for some test stx transfers @@ -8819,13 +8726,10 @@ fn mock_mining() { let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); naka_conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), (send_amt + send_fee) * tenure_count * inter_blocks_per_tenure, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); @@ -9009,18 +8913,22 @@ fn mock_mining() { Ok(follower_naka_mined_blocks.load(Ordering::SeqCst) > follower_naka_mined_blocks_before) }) - .expect(&format!( - "Timed out waiting for mock miner block {}", - follower_naka_mined_blocks_before + 1 - )); + .unwrap_or_else(|_| { + panic!( + "Timed out waiting for mock miner block {}", + follower_naka_mined_blocks_before + 1 + ) + }); wait_for(20, || { Ok(commits_submitted.load(Ordering::SeqCst) > commits_before) }) - .expect(&format!( - "Timed out waiting for mock miner block {}", - follower_naka_mined_blocks_before + 1 - )); + .unwrap_or_else(|_| { + panic!( + "Timed out waiting for mock miner block {}", + follower_naka_mined_blocks_before + 1 + ) + }); } // load the chain tip, and assert that it is a nakamoto block and at least 30 blocks have advanced in epoch 3 @@ -9046,9 +8954,7 @@ fn mock_mining() { let blocks_mock_mined = mock_mining_blocks_end - mock_mining_blocks_start; assert!( blocks_mock_mined >= tenure_count, - "Should have mock mined at least `tenure_count` nakamoto blocks. Mined = {}. Expected = {}", - blocks_mock_mined, - tenure_count, + "Should have mock mined at least `tenure_count` nakamoto blocks. Mined = {blocks_mock_mined}. Expected = {tenure_count}" ); // wait for follower to reach the chain tip @@ -9093,8 +8999,8 @@ fn utxo_check_on_startup_panic() { } let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - println!("Nakamoto node started with config: {:?}", naka_conf); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + println!("Nakamoto node started with config: {naka_conf:?}"); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1000); @@ -9169,8 +9075,8 @@ fn utxo_check_on_startup_recover() { } let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - println!("Nakamoto node started with config: {:?}", naka_conf); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + println!("Nakamoto node started with config: {naka_conf:?}"); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1000); @@ -9244,10 +9150,10 @@ fn v3_signer_api_endpoint() { let send_amt = 100; let send_fee = 180; conf.add_initial_balance( - PrincipalData::from(sender_addr.clone()).to_string(), + PrincipalData::from(sender_addr).to_string(), send_amt + send_fee, ); - conf.add_initial_balance(PrincipalData::from(signer_addr.clone()).to_string(), 100000); + conf.add_initial_balance(PrincipalData::from(signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); // only subscribe to the block proposal events @@ -9273,7 +9179,7 @@ fn v3_signer_api_endpoint() { let coord_channel = run_loop.coordinator_channels(); let run_loop_thread = thread::spawn(move || run_loop.start(None, 0)); - let mut signers = TestSigners::new(vec![signer_sk.clone()]); + let mut signers = TestSigners::new(vec![signer_sk]); wait_for_runloop(&blocks_processed); boot_to_epoch_3( &conf, @@ -9407,7 +9313,7 @@ fn skip_mining_long_tx() { } let (mut naka_conf, _miner_account) = naka_neon_integration_conf(None); - let prom_bind = format!("{}:{}", "127.0.0.1", 6000); + let prom_bind = "127.0.0.1:6000".to_string(); naka_conf.node.prometheus_bind = Some(prom_bind.clone()); naka_conf.miner.wait_on_interim_blocks = Duration::from_secs(1); naka_conf.miner.nakamoto_attempt_time_ms = 5_000; @@ -9419,20 +9325,14 @@ fn skip_mining_long_tx() { let send_amt = 1000; let send_fee = 180; naka_conf.add_initial_balance( - PrincipalData::from(sender_1_addr.clone()).to_string(), + PrincipalData::from(sender_1_addr).to_string(), send_amt * 15 + send_fee * 15, ); - naka_conf.add_initial_balance( - PrincipalData::from(sender_2_addr.clone()).to_string(), - 10000, - ); + naka_conf.add_initial_balance(PrincipalData::from(sender_2_addr).to_string(), 10000); let sender_signer_sk = Secp256k1PrivateKey::new(); let sender_signer_addr = tests::to_addr(&sender_signer_sk); - let mut signers = TestSigners::new(vec![sender_signer_sk.clone()]); - naka_conf.add_initial_balance( - PrincipalData::from(sender_signer_addr.clone()).to_string(), - 100000, - ); + let mut signers = TestSigners::new(vec![sender_signer_sk]); + naka_conf.add_initial_balance(PrincipalData::from(sender_signer_addr).to_string(), 100000); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let stacker_sk = setup_stacker(&mut naka_conf); let http_origin = format!("http://{}", &naka_conf.node.rpc_bind); @@ -9488,7 +9388,7 @@ fn skip_mining_long_tx() { wait_for_first_naka_block_commit(60, &commits_submitted); // submit a long running TX and the transfer TX - let input_list: Vec<_> = (1..100u64).into_iter().map(|x| x.to_string()).collect(); + let input_list: Vec<_> = (1..100u64).map(|x| x.to_string()).collect(); let input_list = input_list.join(" "); // Mine a few nakamoto tenures with some interim blocks in them diff --git a/testnet/stacks-node/src/tests/neon_integrations.rs b/testnet/stacks-node/src/tests/neon_integrations.rs index d6373a3b44..1f7252ec5f 100644 --- a/testnet/stacks-node/src/tests/neon_integrations.rs +++ b/testnet/stacks-node/src/tests/neon_integrations.rs @@ -158,7 +158,7 @@ fn inner_neon_integration_test_conf(seed: Option>) -> (Config, StacksAdd .unwrap() .burnchain .magic_bytes; - assert_eq!(magic_bytes.as_bytes(), &['T' as u8, '2' as u8]); + assert_eq!(magic_bytes.as_bytes(), b"T2"); conf.burnchain.magic_bytes = magic_bytes; conf.burnchain.poll_time_secs = 1; conf.node.pox_sync_sample_secs = 0; @@ -391,7 +391,7 @@ pub mod test_observer { let new_rawtxs = txs .as_array() .unwrap() - .into_iter() + .iter() .map(|x| x.as_str().unwrap().to_string()); let mut memtxs = MEMTXS.lock().unwrap(); for new_tx in new_rawtxs { @@ -408,7 +408,7 @@ pub mod test_observer { .unwrap() .as_array() .unwrap() - .into_iter() + .iter() .map(|x| x.as_str().unwrap().to_string()); let reason = txs.get("reason").unwrap().as_str().unwrap().to_string(); @@ -622,8 +622,7 @@ pub mod test_observer { // Find indexes in range for which we don't have burn block in set let missing = (start..=end) - .into_iter() - .filter(|i| !burn_block_heights.contains(&i)) + .filter(|i| !burn_block_heights.contains(i)) .collect::>(); if missing.is_empty() { @@ -725,20 +724,19 @@ pub fn run_until_burnchain_height( target_height: u64, conf: &Config, ) -> bool { - let tip_info = get_chain_info(&conf); + let tip_info = get_chain_info(conf); let mut current_height = tip_info.burn_block_height; while current_height < target_height { eprintln!( - "run_until_burnchain_height: Issuing block at {}, current_height burnchain height is ({})", + "run_until_burnchain_height: Issuing block at {}, current_height burnchain height is ({current_height})", get_epoch_time_secs(), - current_height ); - let next_result = next_block_and_wait(btc_regtest_controller, &blocks_processed); + let next_result = next_block_and_wait(btc_regtest_controller, blocks_processed); if !next_result { return false; } - let Ok(tip_info) = get_chain_info_result(&conf) else { + let Ok(tip_info) = get_chain_info_result(conf) else { sleep_ms(1000); continue; }; @@ -764,15 +762,12 @@ pub fn wait_for_runloop(blocks_processed: &Arc) { pub fn wait_for_microblocks(microblocks_processed: &Arc, timeout: u64) -> bool { let mut current = microblocks_processed.load(Ordering::SeqCst); let start = Instant::now(); - info!("Waiting for next microblock (current = {})", ¤t); + info!("Waiting for next microblock (current = {current})"); loop { let now = microblocks_processed.load(Ordering::SeqCst); if now == 0 && current != 0 { // wrapped around -- a new epoch started - info!( - "New microblock epoch started while waiting (originally {})", - current - ); + info!("New microblock epoch started while waiting (originally {current})"); current = 0; } @@ -781,24 +776,24 @@ pub fn wait_for_microblocks(microblocks_processed: &Arc, timeout: u64 } if start.elapsed() > Duration::from_secs(timeout) { - warn!("Timed out waiting for microblocks to process ({})", timeout); + warn!("Timed out waiting for microblocks to process ({timeout})"); return false; } thread::sleep(Duration::from_millis(100)); } info!("Next microblock acknowledged"); - return true; + true } /// returns Txid string upon success -pub fn submit_tx_fallible(http_origin: &str, tx: &Vec) -> Result { +pub fn submit_tx_fallible(http_origin: &str, tx: &[u8]) -> Result { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/transactions", http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") - .body(tx.clone()) + .body(tx.to_vec()) .send() .unwrap(); if res.status().is_success() { @@ -817,16 +812,16 @@ pub fn submit_tx_fallible(http_origin: &str, tx: &Vec) -> Result) -> String { +pub fn submit_tx(http_origin: &str, tx: &[u8]) -> String { submit_tx_fallible(http_origin, tx).unwrap_or_else(|e| { - eprintln!("Submit tx error: {}", e); + eprintln!("Submit tx error: {e}"); panic!(""); }) } pub fn get_unconfirmed_tx(http_origin: &str, txid: &Txid) -> Option { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/transactions/unconfirmed/{}", http_origin, txid); + let path = format!("{http_origin}/v2/transactions/unconfirmed/{txid}"); let res = client.get(&path).send().unwrap(); if res.status().is_success() { @@ -840,14 +835,14 @@ pub fn get_unconfirmed_tx(http_origin: &str, txid: &Txid) -> Option { pub fn submit_block( http_origin: &str, consensus_hash: &ConsensusHash, - block: &Vec, + block: &[u8], ) -> StacksBlockAcceptedData { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/blocks/upload/{}", http_origin, consensus_hash); + let path = format!("{http_origin}/v2/blocks/upload/{consensus_hash}"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") - .body(block.clone()) + .body(block.to_owned()) .send() .unwrap(); @@ -862,21 +857,21 @@ pub fn submit_block( .block_hash() ) ); - return res; + res } else { eprintln!("{}", res.text().unwrap()); panic!(""); } } -pub fn submit_microblock(http_origin: &str, mblock: &Vec) -> BlockHeaderHash { +pub fn submit_microblock(http_origin: &str, mblock: &[u8]) -> BlockHeaderHash { let client = reqwest::blocking::Client::new(); let microblock = StacksMicroblock::consensus_deserialize(&mut &mblock[..]).unwrap(); - let path = format!("{}/v2/microblocks/{}", http_origin, microblock.block_hash()); + let path = format!("{http_origin}/v2/microblocks/{}", microblock.block_hash()); let res = client .post(&path) .header("Content-Type", "application/octet-stream") - .body(mblock.clone()) + .body(mblock.to_owned()) .send() .unwrap(); @@ -888,7 +883,7 @@ pub fn submit_microblock(http_origin: &str, mblock: &Vec) -> BlockHeaderHash .unwrap() .block_hash() ); - return res; + res } else { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -897,7 +892,7 @@ pub fn submit_microblock(http_origin: &str, mblock: &Vec) -> BlockHeaderHash pub fn get_block(http_origin: &str, block_id: &StacksBlockId) -> Option { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/blocks/{}", http_origin, block_id); + let path = format!("{http_origin}/v2/blocks/{block_id}"); let res = client.get(&path).send().unwrap(); if res.status().is_success() { @@ -939,7 +934,7 @@ pub fn get_tip_anchored_block(conf: &Config) -> (ConsensusHash, StacksBlock) { // get the associated anchored block let http_origin = format!("http://{}", &conf.node.rpc_bind); let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/blocks/{}", &http_origin, &stacks_id_tip); + let path = format!("{http_origin}/v2/blocks/{stacks_id_tip}"); let block_bytes = client.get(&path).send().unwrap().bytes().unwrap(); let block = StacksBlock::consensus_deserialize(&mut block_bytes.as_ref()).unwrap(); @@ -972,10 +967,7 @@ pub fn call_read_only( info!("Call read only: {contract}.{function}({args:?})"); - let path = format!( - "{http_origin}/v2/contracts/call-read/{}/{}/{}", - principal, contract, function - ); + let path = format!("{http_origin}/v2/contracts/call-read/{principal}/{contract}/{function}"); let serialized_args = args .iter() @@ -1005,14 +997,13 @@ fn find_microblock_privkey( let mut keychain = Keychain::default(conf.node.seed.clone()); for ix in 0..max_tries { // the first rotation occurs at 203. - let privk = - keychain.make_microblock_secret_key(203 + ix, &((203 + ix) as u64).to_be_bytes()); + let privk = keychain.make_microblock_secret_key(203 + ix, &(203 + ix).to_be_bytes()); let pubkh = Hash160::from_node_public_key(&StacksPublicKey::from_private(&privk)); if pubkh == *pubkey_hash { return Some(privk); } } - return None; + None } /// Returns true iff `b` is within `0.1%` of `a`. @@ -1088,7 +1079,7 @@ fn bitcoind_integration_test() { .filter(|block| block.get("burn_amount").unwrap().as_u64().unwrap() > 0) .collect(); assert!( - burn_blocks_with_burns.len() >= 1, + !burn_blocks_with_burns.is_empty(), "Burn block sortitions {} should be >= 1", burn_blocks_with_burns.len() ); @@ -1096,7 +1087,7 @@ fn bitcoind_integration_test() { // query for prometheus metrics #[cfg(feature = "monitoring_prom")] { - let prom_http_origin = format!("http://{}", prom_bind); + let prom_http_origin = format!("http://{prom_bind}"); let client = reqwest::blocking::Client::new(); let res = client .get(&prom_http_origin) @@ -1184,7 +1175,7 @@ fn confirm_unparsed_ongoing_ops() { bitcoin_regtest_controller::TEST_MAGIC_BYTES .lock() .unwrap() - .replace(['Z' as u8, 'Z' as u8]); + .replace([b'Z', b'Z']); // let's trigger another mining loop: this should create an invalid block commit. // this bitcoin block will contain the valid commit created before (so, a second stacks block) @@ -1209,7 +1200,7 @@ fn confirm_unparsed_ongoing_ops() { // query the miner's account nonce - eprintln!("Miner account: {}", miner_account); + eprintln!("Miner account: {miner_account}"); let account = get_account(&http_origin, &miner_account); assert_eq!(account.balance, 0); @@ -1305,9 +1296,9 @@ fn most_recent_utxo_integration_test() { let smallest_utxo = smallest_utxo.unwrap(); let mut biggest_utxo = biggest_utxo.unwrap(); - eprintln!("Last-spent UTXO is {:?}", &last_utxo); - eprintln!("Smallest UTXO is {:?}", &smallest_utxo); - eprintln!("Biggest UTXO is {:?}", &biggest_utxo); + eprintln!("Last-spent UTXO is {last_utxo:?}"); + eprintln!("Smallest UTXO is {smallest_utxo:?}"); + eprintln!("Biggest UTXO is {biggest_utxo:?}"); assert_eq!(last_utxo, smallest_utxo); assert_ne!(biggest_utxo, last_utxo); @@ -1354,9 +1345,9 @@ pub fn get_account_result( account: &F, ) -> Result { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/accounts/{}?proof=0", http_origin, account); + let path = format!("{http_origin}/v2/accounts/{account}?proof=0"); let res = client.get(&path).send()?.json::()?; - info!("Account response: {:#?}", res); + info!("Account response: {res:#?}"); Ok(Account { balance: u128::from_str_radix(&res.balance[2..], 16).unwrap(), locked: u128::from_str_radix(&res.locked[2..], 16).unwrap(), @@ -1371,19 +1362,19 @@ pub fn get_account(http_origin: &str, account: &F) -> Acco pub fn get_neighbors(conf: &Config) -> Option { let client = reqwest::blocking::Client::new(); let http_origin = format!("http://{}", &conf.node.rpc_bind); - let path = format!("{}/v2/neighbors", http_origin); + let path = format!("{http_origin}/v2/neighbors"); client.get(&path).send().ok()?.json().ok() } pub fn get_pox_info(http_origin: &str) -> Option { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/pox", http_origin); + let path = format!("{http_origin}/v2/pox"); client.get(&path).send().ok()?.json::().ok() } fn get_chain_tip(http_origin: &str) -> (ConsensusHash, BlockHeaderHash) { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/info", http_origin); + let path = format!("{http_origin}/v2/info"); let res = client .get(&path) .send() @@ -1404,7 +1395,7 @@ fn get_chain_tip(http_origin: &str) -> (ConsensusHash, BlockHeaderHash) { fn get_chain_tip_height(http_origin: &str) -> u64 { let client = reqwest::blocking::Client::new(); - let path = format!("{}/v2/info", http_origin); + let path = format!("{http_origin}/v2/info"); let res = client .get(&path) .send() @@ -1427,10 +1418,8 @@ pub fn get_contract_src( } else { "".to_string() }; - let path = format!( - "{}/v2/contracts/source/{}/{}{}", - http_origin, contract_addr, contract_name, query_string - ); + let path = + format!("{http_origin}/v2/contracts/source/{contract_addr}/{contract_name}{query_string}"); let res = client.get(&path).send().unwrap(); if res.status().is_success() { @@ -1848,7 +1837,7 @@ fn lockup_integration() { } } } - assert_eq!(found, true); + assert!(found); // block #2 won't unlock STX next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); @@ -1882,7 +1871,7 @@ fn stx_transfer_btc_integration_test() { let spender_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_stx_addr: StacksAddress = to_addr(&spender_sk); - let spender_addr: PrincipalData = spender_stx_addr.clone().into(); + let spender_addr: PrincipalData = spender_stx_addr.into(); let _spender_btc_addr = BitcoinAddress::from_bytes_legacy( BitcoinNetworkType::Regtest, LegacyBitcoinAddressType::PublicKeyHash, @@ -1892,7 +1881,7 @@ fn stx_transfer_btc_integration_test() { let spender_2_sk = StacksPrivateKey::from_hex(SK_2).unwrap(); let spender_2_stx_addr: StacksAddress = to_addr(&spender_2_sk); - let spender_2_addr: PrincipalData = spender_2_stx_addr.clone().into(); + let spender_2_addr: PrincipalData = spender_2_stx_addr.into(); let (mut conf, _miner_account) = neon_integration_test_conf(); @@ -1948,7 +1937,7 @@ fn stx_transfer_btc_integration_test() { // okay, let's send a pre-stx op. let pre_stx_op = PreStxOp { - output: spender_stx_addr.clone(), + output: spender_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -1975,8 +1964,8 @@ fn stx_transfer_btc_integration_test() { let recipient_sk = StacksPrivateKey::new(); let recipient_addr = to_addr(&recipient_sk); let transfer_stx_op = TransferStxOp { - sender: spender_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_stx_addr, + recipient: recipient_addr, transfered_ustx: 100_000, memo: vec![], // to be filled in @@ -1986,7 +1975,7 @@ fn stx_transfer_btc_integration_test() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_sk, false); assert!( btc_regtest_controller @@ -2017,7 +2006,7 @@ fn stx_transfer_btc_integration_test() { // okay, let's send a pre-stx op. let pre_stx_op = PreStxOp { - output: spender_2_stx_addr.clone(), + output: spender_2_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -2046,8 +2035,8 @@ fn stx_transfer_btc_integration_test() { // let's fire off our transfer op. let transfer_stx_op = TransferStxOp { - sender: spender_2_stx_addr.clone(), - recipient: recipient_addr.clone(), + sender: spender_2_stx_addr, + recipient: recipient_addr, transfered_ustx: 100_000, memo: vec![], // to be filled in @@ -2057,7 +2046,7 @@ fn stx_transfer_btc_integration_test() { burn_header_hash: BurnchainHeaderHash([0u8; 32]), }; - let mut spender_signer = BurnchainOpSigner::new(spender_2_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_2_sk, false); btc_regtest_controller .submit_manual( @@ -2111,7 +2100,7 @@ fn stx_delegate_btc_integration_test() { let spender_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_stx_addr: StacksAddress = to_addr(&spender_sk); - let spender_addr: PrincipalData = spender_stx_addr.clone().into(); + let spender_addr: PrincipalData = spender_stx_addr.into(); let recipient_sk = StacksPrivateKey::new(); let recipient_addr = to_addr(&recipient_sk); @@ -2119,11 +2108,7 @@ fn stx_delegate_btc_integration_test() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let (mut conf, _miner_account) = neon_integration_test_conf(); @@ -2132,7 +2117,7 @@ fn stx_delegate_btc_integration_test() { amount: 100300, }); conf.initial_balances.push(InitialBalance { - address: recipient_addr.clone().into(), + address: recipient_addr.into(), amount: 300, }); @@ -2226,7 +2211,7 @@ fn stx_delegate_btc_integration_test() { // okay, let's send a pre-stx op. let pre_stx_op = PreStxOp { - output: spender_stx_addr.clone(), + output: spender_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -2252,8 +2237,8 @@ fn stx_delegate_btc_integration_test() { // let's fire off our delegate op. let del_stx_op = DelegateStxOp { - sender: spender_stx_addr.clone(), - delegate_to: recipient_addr.clone(), + sender: spender_stx_addr, + delegate_to: recipient_addr, reward_addr: None, delegated_ustx: 100_000, // to be filled in @@ -2264,7 +2249,7 @@ fn stx_delegate_btc_integration_test() { until_burn_height: None, }; - let mut spender_signer = BurnchainOpSigner::new(spender_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(spender_sk, false); assert!( btc_regtest_controller .submit_operation( @@ -2298,7 +2283,7 @@ fn stx_delegate_btc_integration_test() { Value::Principal(spender_addr.clone()), Value::UInt(100_000), execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash), + &format!("{{ hashbytes: 0x{pox_pubkey_hash}, version: 0x00 }}"), ClarityVersion::Clarity2, ) .unwrap() @@ -2372,7 +2357,7 @@ fn stack_stx_burn_op_test() { let spender_sk_1 = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_stx_addr_1: StacksAddress = to_addr(&spender_sk_1); - let spender_addr_1: PrincipalData = spender_stx_addr_1.clone().into(); + let spender_addr_1: PrincipalData = spender_stx_addr_1.into(); let spender_sk_2 = StacksPrivateKey::from_hex(SK_2).unwrap(); let spender_stx_addr_2: StacksAddress = to_addr(&spender_sk_2); @@ -2390,7 +2375,7 @@ fn stack_stx_burn_op_test() { amount: first_bal, }); conf.initial_balances.push(InitialBalance { - address: recipient_addr.clone().into(), + address: recipient_addr.into(), amount: second_bal, }); @@ -2506,8 +2491,8 @@ fn stack_stx_burn_op_test() { info!("Bootstrapped to 2.5, submitting stack-stx and pre-stx op..."); - let signer_sk_1 = spender_sk_1.clone(); - let signer_sk_2 = spender_sk_2.clone(); + let signer_sk_1 = spender_sk_1; + let signer_sk_2 = spender_sk_2; let signer_pk_1 = StacksPublicKey::from_private(&signer_sk_1); let pox_addr = PoxAddress::Standard(spender_stx_addr_1, Some(AddressHashMode::SerializeP2PKH)); @@ -2540,7 +2525,7 @@ fn stack_stx_burn_op_test() { let mut miner_signer_2 = Keychain::default(conf.node.seed.clone()).generate_op_signer(); let pre_stx_op_2 = PreStxOp { - output: spender_stx_addr_2.clone(), + output: spender_stx_addr_2, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -2619,13 +2604,13 @@ fn stack_stx_burn_op_test() { // `stacked_ustx` should be large enough to avoid ERR_STACKING_THRESHOLD_NOT_MET from Clarity let stack_stx_op_with_some_signer_key = BlockstackOperationType::StackStx(StackStxOp { - sender: spender_stx_addr_1.clone(), + sender: spender_stx_addr_1, reward_addr: pox_addr.clone(), stacked_ustx: 10000000000000, num_cycles: 6, signer_key: Some(signer_key), max_amount: Some(u128::MAX), - auth_id: Some(auth_id.into()), + auth_id: Some(auth_id), // to be filled in vtxindex: 0, txid: Txid([0u8; 32]), @@ -2633,7 +2618,7 @@ fn stack_stx_burn_op_test() { burn_header_hash: BurnchainHeaderHash::zero(), }); - let mut spender_signer_1 = BurnchainOpSigner::new(signer_sk_1.clone(), false); + let mut spender_signer_1 = BurnchainOpSigner::new(signer_sk_1, false); assert!( btc_regtest_controller .submit_operation( @@ -2647,7 +2632,7 @@ fn stack_stx_burn_op_test() { ); let stack_stx_op_with_no_signer_key = BlockstackOperationType::StackStx(StackStxOp { - sender: spender_stx_addr_2.clone(), + sender: spender_stx_addr_2, reward_addr: pox_addr.clone(), stacked_ustx: 10000000000000, num_cycles: 6, @@ -2661,7 +2646,7 @@ fn stack_stx_burn_op_test() { burn_header_hash: BurnchainHeaderHash::zero(), }); - let mut spender_signer_2 = BurnchainOpSigner::new(signer_sk_2.clone(), false); + let mut spender_signer_2 = BurnchainOpSigner::new(signer_sk_2, false); assert!( btc_regtest_controller .submit_operation( @@ -2740,7 +2725,7 @@ fn stack_stx_burn_op_test() { for ancestor_bhh in ancestor_burnchain_header_hashes.iter().rev() { let stacking_ops = SortitionDB::get_stack_stx_ops(sortdb_conn, ancestor_bhh).unwrap(); for stacking_op in stacking_ops.into_iter() { - debug!("Stacking op queried from sortdb: {:?}", stacking_op); + debug!("Stacking op queried from sortdb: {stacking_op:?}"); match stacking_op.signer_key { Some(_) => found_some = true, None => found_none = true, @@ -2775,17 +2760,13 @@ fn vote_for_aggregate_key_burn_op_test() { let spender_sk = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_stx_addr: StacksAddress = to_addr(&spender_sk); - let spender_addr: PrincipalData = spender_stx_addr.clone().into(); + let spender_addr: PrincipalData = spender_stx_addr.into(); let pox_pubkey = Secp256k1PublicKey::from_hex( "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let _pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let _pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let (mut conf, _miner_account) = neon_integration_test_conf(); @@ -2912,7 +2893,7 @@ fn vote_for_aggregate_key_burn_op_test() { // setup stack-stx tx - let signer_sk = spender_sk.clone(); + let signer_sk = spender_sk; let signer_pk = StacksPublicKey::from_private(&signer_sk); let pox_addr = PoxAddress::Standard(spender_stx_addr, Some(AddressHashMode::SerializeP2PKH)); @@ -2959,7 +2940,7 @@ fn vote_for_aggregate_key_burn_op_test() { let mut miner_signer = Keychain::default(conf.node.seed.clone()).generate_op_signer(); let pre_stx_op = PreStxOp { - output: spender_stx_addr.clone(), + output: spender_stx_addr, // to be filled in txid: Txid([0u8; 32]), vtxindex: 0, @@ -3012,7 +2993,7 @@ fn vote_for_aggregate_key_burn_op_test() { BlockstackOperationType::VoteForAggregateKey(VoteForAggregateKeyOp { signer_key, signer_index, - sender: spender_stx_addr.clone(), + sender: spender_stx_addr, round: 0, reward_cycle, aggregate_key, @@ -3023,7 +3004,7 @@ fn vote_for_aggregate_key_burn_op_test() { burn_header_hash: BurnchainHeaderHash::zero(), }); - let mut spender_signer = BurnchainOpSigner::new(signer_sk.clone(), false); + let mut spender_signer = BurnchainOpSigner::new(signer_sk, false); assert!( btc_regtest_controller .submit_operation( @@ -3251,16 +3232,16 @@ fn bitcoind_forking_test() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let mut sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); while sort_height < 210 { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // let's query the miner's account nonce: - eprintln!("Miner account: {}", miner_account); + eprintln!("Miner account: {miner_account}"); let account = get_account(&http_origin, &miner_account); @@ -3355,17 +3336,17 @@ fn should_fix_2771() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let mut sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); while sort_height < 210 { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // okay, let's figure out the burn block we want to fork away. let reorg_height = 208; - warn!("Will trigger re-org at block {}", reorg_height); + warn!("Will trigger re-org at block {reorg_height}"); let burn_header_hash_to_fork = btc_regtest_controller.get_block_hash(reorg_height); btc_regtest_controller.invalidate_block(&burn_header_hash_to_fork); btc_regtest_controller.build_next_block(1); @@ -3407,10 +3388,10 @@ fn make_signed_microblock( version: rng.gen(), sequence: seq, prev_block: parent_block, - tx_merkle_root: tx_merkle_root, + tx_merkle_root, signature: MessageSignature([0u8; 65]), }, - txs: txs, + txs, }; mblock.sign(block_privk).unwrap(); mblock @@ -3585,9 +3566,8 @@ fn microblock_fork_poison_integration_test() { make_signed_microblock(&privk, vec![second_unconfirmed_tx], stacks_tip, 1); eprintln!( - "Created second conflicting microblock: {}: {:?}", - &second_microblock.block_hash(), - &second_microblock + "Created second conflicting microblock: {}: {second_microblock:?}", + &second_microblock.block_hash() ); (first_microblock, second_microblock) }; @@ -3598,7 +3578,7 @@ fn microblock_fork_poison_integration_test() { .unwrap(); // post the first microblock - let path = format!("{}/v2/microblocks", &http_origin); + let path = format!("{http_origin}/v2/microblocks"); let res: String = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -3616,7 +3596,7 @@ fn microblock_fork_poison_integration_test() { .unwrap(); // post the second microblock - let path = format!("{}/v2/microblocks", &http_origin); + let path = format!("{http_origin}/v2/microblocks"); let res: String = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -3737,7 +3717,7 @@ fn microblock_integration_test() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // let's query the miner's account nonce: - info!("Miner account: {}", miner_account); + info!("Miner account: {miner_account}"); let account = get_account(&http_origin, &miner_account); assert_eq!(account.balance, 0); assert_eq!(account.nonce, 1); @@ -3854,9 +3834,8 @@ fn microblock_integration_test() { ); eprintln!( - "Created first microblock: {}: {:?}", - &first_microblock.block_hash(), - &first_microblock + "Created first microblock: {}: {first_microblock:?}", + &first_microblock.block_hash() ); /* let second_microblock = @@ -3869,9 +3848,8 @@ fn microblock_integration_test() { 1, ); eprintln!( - "Created second microblock: {}: {:?}", - &second_microblock.block_hash(), - &second_microblock + "Created second microblock: {}: {second_microblock:?}", + &second_microblock.block_hash() ); (first_microblock, second_microblock) }; @@ -3882,7 +3860,7 @@ fn microblock_integration_test() { .unwrap(); // post the first microblock - let path = format!("{}/v2/microblocks", &http_origin); + let path = format!("{http_origin}/v2/microblocks"); let res: String = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -3894,7 +3872,7 @@ fn microblock_integration_test() { assert_eq!(res, format!("{}", &first_microblock.block_hash())); - eprintln!("\n\nBegin testing\nmicroblock: {:?}\n\n", &first_microblock); + eprintln!("\n\nBegin testing\nmicroblock: {first_microblock:?}\n\n"); let account = get_account(&http_origin, &spender_addr); assert_eq!(account.nonce, 1); @@ -3906,7 +3884,7 @@ fn microblock_integration_test() { .unwrap(); // post the second microblock - let path = format!("{}/v2/microblocks", &http_origin); + let path = format!("{http_origin}/v2/microblocks"); let res: String = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -4090,13 +4068,11 @@ fn microblock_integration_test() { // we can query unconfirmed state from the microblock we announced let path = format!( - "{}/v2/accounts/{}?proof=0&tip={}", - &http_origin, - &spender_addr, + "{http_origin}/v2/accounts/{spender_addr}?proof=0&tip={}", &tip_info.unanchored_tip.unwrap() ); - eprintln!("{:?}", &path); + eprintln!("{path:?}"); let mut iter_count = 0; let res = loop { @@ -4107,7 +4083,7 @@ fn microblock_integration_test() { match http_resp.json::() { Ok(x) => break x, Err(e) => { - warn!("Failed to query {}; will try again. Err = {:?}", &path, e); + warn!("Failed to query {path}; will try again. Err = {e:?}"); iter_count += 1; assert!(iter_count < 10, "Retry limit reached querying account"); sleep_ms(1000); @@ -4116,17 +4092,14 @@ fn microblock_integration_test() { }; }; - info!("Account Response = {:#?}", res); + info!("Account Response = {res:#?}"); assert_eq!(res.nonce, 2); assert_eq!(u128::from_str_radix(&res.balance[2..], 16).unwrap(), 96300); // limited by chaining for next_nonce in 2..5 { // verify that the microblock miner can automatically pick up transactions - debug!( - "Try to send unconfirmed tx from {} to {} nonce {}", - &spender_addr, &recipient, next_nonce - ); + debug!("Try to send unconfirmed tx from {spender_addr} to {recipient} nonce {next_nonce}"); let unconfirmed_tx_bytes = make_stacks_transfer_mblock_only( &spender_sk, next_nonce, @@ -4136,14 +4109,14 @@ fn microblock_integration_test() { 1000, ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") .body(unconfirmed_tx_bytes.clone()) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let res: String = res.json().unwrap(); assert_eq!( @@ -4153,7 +4126,7 @@ fn microblock_integration_test() { .txid() .to_string() ); - eprintln!("Sent {}", &res); + eprintln!("Sent {res}"); } else { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -4171,15 +4144,13 @@ fn microblock_integration_test() { // we can query _new_ unconfirmed state from the microblock we announced let path = format!( - "{}/v2/accounts/{}?proof=0&tip={}", - &http_origin, - &spender_addr, + "{http_origin}/v2/accounts/{spender_addr}?proof=0&tip={}", &tip_info.unanchored_tip.unwrap() ); let res_text = client.get(&path).send().unwrap().text().unwrap(); - eprintln!("text of {}\n{}", &path, &res_text); + eprintln!("text of {path}\n{res_text}"); let res = client .get(&path) @@ -4187,8 +4158,8 @@ fn microblock_integration_test() { .unwrap() .json::() .unwrap(); - eprintln!("{:?}", &path); - eprintln!("{:#?}", res); + eprintln!("{path:?}"); + eprintln!("{res:#?}"); // advanced! assert_eq!(res.nonce, next_nonce + 1); @@ -4209,10 +4180,7 @@ fn filter_low_fee_tx_integration_test() { return; } - let spender_sks: Vec<_> = (0..10) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..10).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, _) = neon_integration_test_conf(); @@ -4232,7 +4200,7 @@ fn filter_low_fee_tx_integration_test() { if ix < 5 { // low-fee make_stacks_transfer( - &spender_sk, + spender_sk, 0, 1000 + (ix as u64), conf.burnchain.chain_id, @@ -4242,7 +4210,7 @@ fn filter_low_fee_tx_integration_test() { } else { // high-fee make_stacks_transfer( - &spender_sk, + spender_sk, 0, 2000 + (ix as u64), conf.burnchain.chain_id, @@ -4296,14 +4264,9 @@ fn filter_low_fee_tx_integration_test() { // First five accounts have a transaction. The miner will consider low fee transactions, // but rank by estimated fee rate. - for i in 0..5 { - let account = get_account(&http_origin, &spender_addrs[i]); - assert_eq!(account.nonce, 1); - } - - // last five accounts have transaction - for i in 5..10 { - let account = get_account(&http_origin, &spender_addrs[i]); + // Last five accounts have transaction + for spender_addr in &spender_addrs { + let account = get_account(&http_origin, spender_addr); assert_eq!(account.nonce, 1); } @@ -4317,10 +4280,7 @@ fn filter_long_runtime_tx_integration_test() { return; } - let spender_sks: Vec<_> = (0..10) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..10).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, _) = neon_integration_test_conf(); @@ -4341,7 +4301,7 @@ fn filter_long_runtime_tx_integration_test() { .map(|(ix, spender_sk)| { let recipient = StacksAddress::from_string(ADDR_4).unwrap(); make_stacks_transfer( - &spender_sk, + spender_sk, 0, 1000 + (ix as u64), conf.burnchain.chain_id, @@ -4393,8 +4353,8 @@ fn filter_long_runtime_tx_integration_test() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // no transactions mined - for i in 0..10 { - let account = get_account(&http_origin, &spender_addrs[i]); + for spender_addr in &spender_addrs { + let account = get_account(&http_origin, &spender_addr); assert_eq!(account.nonce, 0); } @@ -4517,10 +4477,7 @@ fn size_check_integration_test() { giant_contract.push(' '); } - let spender_sks: Vec<_> = (0..10) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..10).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -4652,13 +4609,10 @@ fn size_check_integration_test() { panic!("Spender address nonce incremented past 1"); } - debug!("Spender {},{}: {:?}", ix, &spender_addr, &res); + debug!("Spender {ix},{spender_addr}: {res:?}"); } - eprintln!( - "anchor_block_txs: {}, micro_block_txs: {}", - anchor_block_txs, micro_block_txs - ); + eprintln!("anchor_block_txs: {anchor_block_txs}, micro_block_txs: {micro_block_txs}"); if anchor_block_txs >= 2 && micro_block_txs >= 2 { break; @@ -4693,10 +4647,7 @@ fn size_overflow_unconfirmed_microblocks_integration_test() { small_contract.push(' '); } - let spender_sks: Vec<_> = (0..5) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..5).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -4723,7 +4674,7 @@ fn size_overflow_unconfirmed_microblocks_integration_test() { i as u64, 1100000, conf.burnchain.chain_id, - &format!("small-{}", i), + &format!("small-{i}"), &small_contract, ); ret.push(tx); @@ -4849,10 +4800,10 @@ fn size_overflow_unconfirmed_microblocks_integration_test() { let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); if let TransactionPayload::SmartContract(tsc, ..) = parsed.payload { - if tsc.name.to_string().find("large-").is_some() { + if tsc.name.to_string().contains("large-") { num_big_anchored_txs += 1; total_big_txs_per_block += 1; - } else if tsc.name.to_string().find("small").is_some() { + } else if tsc.name.to_string().contains("small") { num_big_microblock_txs += 1; total_big_txs_per_microblock += 1; } @@ -4868,8 +4819,7 @@ fn size_overflow_unconfirmed_microblocks_integration_test() { } eprintln!( - "max_big_txs_per_microblock: {}, max_big_txs_per_block: {}, total_big_txs_per_block: {}, total_big_txs_per_microblock: {}", - max_big_txs_per_microblock, max_big_txs_per_block, total_big_txs_per_block, total_big_txs_per_microblock + "max_big_txs_per_microblock: {max_big_txs_per_microblock}, max_big_txs_per_block: {max_big_txs_per_block}, total_big_txs_per_block: {total_big_txs_per_block}, total_big_txs_per_microblock: {total_big_txs_per_microblock}" ); assert!(max_big_txs_per_block > 0); @@ -4902,10 +4852,7 @@ fn size_overflow_unconfirmed_stream_microblocks_integration_test() { small_contract.push(' '); } - let spender_sks: Vec<_> = (0..20) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..20).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -4930,15 +4877,14 @@ fn size_overflow_unconfirmed_stream_microblocks_integration_test() { let txs: Vec<_> = spender_sks .iter() .map(|spender_sk| { - let tx = make_contract_publish_microblock_only( + make_contract_publish_microblock_only( spender_sk, 0, 600000, conf.burnchain.chain_id, "small", &small_contract, - ); - tx + ) }) .collect(); @@ -5049,7 +4995,7 @@ fn size_overflow_unconfirmed_stream_microblocks_integration_test() { let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); if let TransactionPayload::SmartContract(tsc, ..) = parsed.payload { - if tsc.name.to_string().find("small").is_some() { + if tsc.name.to_string().contains("small") { num_big_microblock_txs += 1; total_big_txs_per_microblock += 1; } @@ -5061,8 +5007,7 @@ fn size_overflow_unconfirmed_stream_microblocks_integration_test() { } eprintln!( - "max_big_txs_per_microblock: {}, total_big_txs_per_microblock: {}", - max_big_txs_per_microblock, total_big_txs_per_microblock + "max_big_txs_per_microblock: {max_big_txs_per_microblock}, total_big_txs_per_microblock: {total_big_txs_per_microblock}" ); assert_eq!(max_big_txs_per_microblock, 5); @@ -5090,10 +5035,7 @@ fn size_overflow_unconfirmed_invalid_stream_microblocks_integration_test() { small_contract.push(' '); } - let spender_sks: Vec<_> = (0..25) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..25).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -5115,15 +5057,14 @@ fn size_overflow_unconfirmed_invalid_stream_microblocks_integration_test() { let txs: Vec> = spender_sks .iter() .map(|spender_sk| { - let tx = make_contract_publish_microblock_only( + make_contract_publish_microblock_only( spender_sk, 0, 1149230, conf.burnchain.chain_id, "small", &small_contract, - ); - tx + ) }) .collect(); @@ -5222,7 +5163,7 @@ fn size_overflow_unconfirmed_invalid_stream_microblocks_integration_test() { let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); if let TransactionPayload::SmartContract(tsc, ..) = parsed.payload { - if tsc.name.to_string().find("small").is_some() { + if tsc.name.to_string().contains("small") { num_big_microblock_txs += 1; total_big_txs_per_microblock += 1; } @@ -5234,8 +5175,7 @@ fn size_overflow_unconfirmed_invalid_stream_microblocks_integration_test() { } eprintln!( - "max_big_txs_per_microblock: {}, total_big_txs_per_microblock: {}", - max_big_txs_per_microblock, total_big_txs_per_microblock + "max_big_txs_per_microblock: {max_big_txs_per_microblock}, total_big_txs_per_microblock: {total_big_txs_per_microblock}" ); assert_eq!(max_big_txs_per_microblock, 3); @@ -5252,13 +5192,9 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { return; } - let spender_sks: Vec<_> = (0..4) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let spender_sks: Vec<_> = (0..4).map(|_| StacksPrivateKey::new()).collect(); let spender_addrs: Vec = spender_sks.iter().map(|x| to_addr(x).into()).collect(); - let spender_addrs_c32: Vec = - spender_sks.iter().map(|x| to_addr(x).into()).collect(); + let spender_addrs_c32: Vec = spender_sks.iter().map(to_addr).collect(); let (mut conf, miner_account) = neon_integration_test_conf(); @@ -5292,7 +5228,7 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { 0, 1049230, conf.burnchain.chain_id, - &format!("large-{}", ix), + &format!("large-{ix}"), &format!(" ;; a single one of these transactions consumes over half the runtime budget (define-constant BUFF_TO_BYTE (list @@ -5336,7 +5272,7 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { (begin (crash-me \"{}\")) ", - &format!("large-contract-{}-{}", &spender_addrs_c32[ix], &ix) + &format!("large-contract-{}-{ix}", &spender_addrs_c32[ix]) ) )] } else { @@ -5347,7 +5283,7 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { i as u64, 210000, conf.burnchain.chain_id, - &format!("small-{}-{}", ix, i), + &format!("small-{ix}-{i}"), &format!(" ;; a single one of these transactions consumes over half the runtime budget (define-constant BUFF_TO_BYTE (list @@ -5390,7 +5326,7 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { ) (begin (crash-me \"{}\")) - ", &format!("small-contract-{}-{}-{}", &spender_addrs_c32[ix], &ix, i)) + ", &format!("small-contract-{}-{ix}-{i}", &spender_addrs_c32[ix])) ); ret.push(tx); } @@ -5486,7 +5422,7 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { let mut total_big_txs_in_microblocks = 0; for block in blocks { - eprintln!("block {:?}", &block); + eprintln!("block {block:?}"); let transactions = block.get("transactions").unwrap().as_array().unwrap(); let mut num_big_anchored_txs = 0; @@ -5499,12 +5435,12 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { } let tx_bytes = hex_bytes(&raw_tx[2..]).unwrap(); let parsed = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).unwrap(); - eprintln!("tx: {:?}", &parsed); + eprintln!("tx: {parsed:?}"); if let TransactionPayload::SmartContract(tsc, ..) = parsed.payload { - if tsc.name.to_string().find("large-").is_some() { + if tsc.name.to_string().contains("large-") { num_big_anchored_txs += 1; total_big_txs_in_blocks += 1; - } else if tsc.name.to_string().find("small").is_some() { + } else if tsc.name.to_string().contains("small") { num_big_microblock_txs += 1; total_big_txs_in_microblocks += 1; } @@ -5520,12 +5456,10 @@ fn runtime_overflow_unconfirmed_microblocks_integration_test() { } info!( - "max_big_txs_per_microblock: {}, max_big_txs_per_block: {}", - max_big_txs_per_microblock, max_big_txs_per_block + "max_big_txs_per_microblock: {max_big_txs_per_microblock}, max_big_txs_per_block: {max_big_txs_per_block}" ); info!( - "total_big_txs_in_microblocks: {}, total_big_txs_in_blocks: {}", - total_big_txs_in_microblocks, total_big_txs_in_blocks + "total_big_txs_in_microblocks: {total_big_txs_in_microblocks}, total_big_txs_in_blocks: {total_big_txs_in_blocks}" ); // at most one big tx per block and at most one big tx per stream, always. @@ -5605,7 +5539,7 @@ fn block_replay_integration_test() { // let's query the miner's account nonce: - info!("Miner account: {}", miner_account); + info!("Miner account: {miner_account}"); let account = get_account(&http_origin, &miner_account); assert_eq!(account.balance, 0); assert_eq!(account.nonce, 1); @@ -5638,7 +5572,7 @@ fn block_replay_integration_test() { tip_block.consensus_serialize(&mut tip_block_bytes).unwrap(); for i in 0..1024 { - let path = format!("{}/v2/blocks/upload/{}", &http_origin, &tip_consensus_hash); + let path = format!("{http_origin}/v2/blocks/upload/{tip_consensus_hash}"); let res_text = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -5648,7 +5582,7 @@ fn block_replay_integration_test() { .text() .unwrap(); - eprintln!("{}: text of {}\n{}", i, &path, &res_text); + eprintln!("{i}: text of {path}\n{res_text}"); } test_observer::clear(); @@ -6022,11 +5956,11 @@ fn mining_events_integration_test() { let (mut conf, _) = neon_integration_test_conf(); conf.initial_balances.push(InitialBalance { - address: addr.clone().into(), + address: addr.into(), amount: 10000000, }); conf.initial_balances.push(InitialBalance { - address: addr_2.clone().into(), + address: addr_2.into(), amount: 10000000, }); @@ -6121,7 +6055,7 @@ fn mining_events_integration_test() { // check mined microblock events let mined_microblock_events = test_observer::get_mined_microblocks(); - assert!(mined_microblock_events.len() >= 1); + assert!(!mined_microblock_events.is_empty()); // check tx events in the first microblock // 1 success: 1 contract publish, 2 error (on chain transactions) @@ -6136,15 +6070,12 @@ fn mining_events_integration_test() { execution_cost, .. }) => { - assert_eq!( - result - .clone() - .expect_result_ok() - .unwrap() - .expect_bool() - .unwrap(), - true - ); + assert!(result + .clone() + .expect_result_ok() + .unwrap() + .expect_bool() + .unwrap()); assert_eq!(fee, &620000); assert_eq!( execution_cost, @@ -6176,15 +6107,12 @@ fn mining_events_integration_test() { txid.to_string(), "3e04ada5426332bfef446ba0a06d124aace4ade5c11840f541bf88e2e919faf6" ); - assert_eq!( - result - .clone() - .expect_result_ok() - .unwrap() - .expect_bool() - .unwrap(), - true - ); + assert!(result + .clone() + .expect_result_ok() + .unwrap() + .expect_bool() + .unwrap()); } _ => panic!("unexpected event type"), } @@ -6197,15 +6125,12 @@ fn mining_events_integration_test() { execution_cost, .. }) => { - assert_eq!( - result - .clone() - .expect_result_ok() - .unwrap() - .expect_bool() - .unwrap(), - true - ); + assert!(result + .clone() + .expect_result_ok() + .unwrap() + .expect_bool() + .unwrap()); assert_eq!(fee, &600000); assert_eq!( execution_cost, @@ -6304,7 +6229,7 @@ fn block_limit_hit_integration_test() { let (mut conf, _miner_account) = neon_integration_test_conf(); conf.initial_balances.push(InitialBalance { - address: addr.clone().into(), + address: addr.into(), amount: 10_000_000, }); conf.initial_balances.push(InitialBalance { @@ -6432,8 +6357,8 @@ fn block_limit_hit_integration_test() { assert_eq!(tx_third_block.len(), 3); let txid_1_exp = tx_third_block[1].get("txid").unwrap().as_str().unwrap(); let txid_4_exp = tx_third_block[2].get("txid").unwrap().as_str().unwrap(); - assert_eq!(format!("0x{}", txid_1), txid_1_exp); - assert_eq!(format!("0x{}", txid_4), txid_4_exp); + assert_eq!(format!("0x{txid_1}"), txid_1_exp); + assert_eq!(format!("0x{txid_4}"), txid_4_exp); let tx_fourth_block = mined_block_events[4] .get("transactions") @@ -6443,8 +6368,8 @@ fn block_limit_hit_integration_test() { assert_eq!(tx_fourth_block.len(), 3); let txid_2_exp = tx_fourth_block[1].get("txid").unwrap().as_str().unwrap(); let txid_3_exp = tx_fourth_block[2].get("txid").unwrap().as_str().unwrap(); - assert_eq!(format!("0x{}", txid_2), txid_2_exp); - assert_eq!(format!("0x{}", txid_3), txid_3_exp); + assert_eq!(format!("0x{txid_2}"), txid_2_exp); + assert_eq!(format!("0x{txid_3}"), txid_3_exp); test_observer::clear(); channel.stop_chains_coordinator(); @@ -6516,7 +6441,7 @@ fn microblock_limit_hit_integration_test() { let (mut conf, _) = neon_integration_test_conf(); conf.initial_balances.push(InitialBalance { - address: addr.clone().into(), + address: addr.into(), amount: 10_000_000, }); conf.initial_balances.push(InitialBalance { @@ -6656,10 +6581,7 @@ fn microblock_limit_hit_integration_test() { let txid_3 = submit_tx(&http_origin, &tx_3); let txid_4 = submit_tx(&http_origin, &tx_4); - eprintln!( - "transactions: {},{},{},{}", - &txid_1, &txid_2, &txid_3, &txid_4 - ); + eprintln!("transactions: {txid_1},{txid_2},{txid_3},{txid_4}"); sleep_ms(50_000); @@ -6702,8 +6624,8 @@ fn microblock_limit_hit_integration_test() { assert_eq!(tx_first_mblock.len(), 2); let txid_1_exp = tx_first_mblock[0].get("txid").unwrap().as_str().unwrap(); let txid_4_exp = tx_first_mblock[1].get("txid").unwrap().as_str().unwrap(); - assert_eq!(format!("0x{}", txid_1), txid_1_exp); - assert_eq!(format!("0x{}", txid_4), txid_4_exp); + assert_eq!(format!("0x{txid_1}"), txid_1_exp); + assert_eq!(format!("0x{txid_4}"), txid_4_exp); let tx_second_mblock = mined_mblock_events[1] .get("transactions") @@ -6713,8 +6635,8 @@ fn microblock_limit_hit_integration_test() { assert_eq!(tx_second_mblock.len(), 2); let txid_2_exp = tx_second_mblock[0].get("txid").unwrap().as_str().unwrap(); let txid_3_exp = tx_second_mblock[1].get("txid").unwrap().as_str().unwrap(); - assert_eq!(format!("0x{}", txid_2), txid_2_exp); - assert_eq!(format!("0x{}", txid_3), txid_3_exp); + assert_eq!(format!("0x{txid_2}"), txid_2_exp); + assert_eq!(format!("0x{txid_3}"), txid_3_exp); test_observer::clear(); channel.stop_chains_coordinator(); @@ -6761,7 +6683,7 @@ fn block_large_tx_integration_test() { test_observer::register_any(&mut conf); conf.initial_balances.push(InitialBalance { - address: spender_addr.clone().into(), + address: spender_addr.into(), amount: 10000000, }); @@ -6837,10 +6759,7 @@ fn block_large_tx_integration_test() { let normal_txid = submit_tx(&http_origin, &tx); let huge_txid = submit_tx(&http_origin, &tx_2); - eprintln!( - "Try to mine a too-big tx. Normal = {}, TooBig = {}", - &normal_txid, &huge_txid - ); + eprintln!("Try to mine a too-big tx. Normal = {normal_txid}, TooBig = {huge_txid}"); next_block_and_wait_with_timeout(&mut btc_regtest_controller, &blocks_processed, 1200); eprintln!("Finished trying to mine a too-big tx"); @@ -6848,7 +6767,7 @@ fn block_large_tx_integration_test() { let dropped_txs = test_observer::get_memtx_drops(); assert_eq!(dropped_txs.len(), 1); assert_eq!(&dropped_txs[0].1, "TooExpensive"); - assert_eq!(&dropped_txs[0].0, &format!("0x{}", huge_txid)); + assert_eq!(&dropped_txs[0].0, &format!("0x{huge_txid}")); test_observer::clear(); channel.stop_chains_coordinator(); @@ -6898,7 +6817,7 @@ fn microblock_large_tx_integration_test_FLAKY() { test_observer::register_any(&mut conf); conf.initial_balances.push(InitialBalance { - address: addr.clone().into(), + address: addr.into(), amount: 10000000, }); @@ -6981,7 +6900,7 @@ fn microblock_large_tx_integration_test_FLAKY() { // Check that the microblock contains the first tx. let microblock_events = test_observer::get_microblocks(); - assert!(microblock_events.len() >= 1); + assert!(!microblock_events.is_empty()); let microblock = microblock_events[0].clone(); let transactions = microblock.get("transactions").unwrap().as_array().unwrap(); @@ -6994,7 +6913,7 @@ fn microblock_large_tx_integration_test_FLAKY() { let dropped_txs = test_observer::get_memtx_drops(); assert_eq!(dropped_txs.len(), 1); assert_eq!(&dropped_txs[0].1, "TooExpensive"); - assert_eq!(&dropped_txs[0].0, &format!("0x{}", huge_txid)); + assert_eq!(&dropped_txs[0].0, &format!("0x{huge_txid}")); test_observer::clear(); channel.stop_chains_coordinator(); @@ -7020,18 +6939,10 @@ fn pox_integration_test() { "02f006a09b59979e2cb8449f58076152af6b124aa29b948a3714b8d5f15aa94ede", ) .unwrap(); - let pox_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_pubkey).to_bytes()); let pox_2_pubkey = Secp256k1PublicKey::from_private(&StacksPrivateKey::new()); - let pox_2_pubkey_hash = bytes_to_hex( - &Hash160::from_node_public_key(&pox_2_pubkey) - .to_bytes() - .to_vec(), - ); + let pox_2_pubkey_hash = bytes_to_hex(&Hash160::from_node_public_key(&pox_2_pubkey).to_bytes()); let pox_2_address = BitcoinAddress::from_bytes_legacy( BitcoinNetworkType::Testnet, @@ -7145,15 +7056,12 @@ fn pox_integration_test() { let pox_info = get_pox_info(&http_origin).unwrap(); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); assert_eq!(pox_info.first_burnchain_block_height, 0); assert_eq!(pox_info.next_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.stacked_ustx, 0); - assert_eq!(pox_info.current_cycle.is_pox_active, false); + assert!(!pox_info.current_cycle.is_pox_active); assert_eq!(pox_info.next_cycle.stacked_ustx, 0); assert_eq!(pox_info.reward_slots as u32, pox_constants.reward_slots()); assert_eq!(pox_info.next_cycle.reward_phase_start_block_height, 210); @@ -7191,7 +7099,7 @@ fn pox_integration_test() { &[ Value::UInt(stacked_bal), execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_pubkey_hash), + &format!("{{ hashbytes: 0x{pox_pubkey_hash}, version: 0x00 }}"), ClarityVersion::Clarity1, ) .unwrap() @@ -7205,14 +7113,14 @@ fn pox_integration_test() { submit_tx(&http_origin, &tx); let mut sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); test_observer::clear(); // now let's mine until the next reward cycle starts ... while sort_height < ((14 * pox_constants.reward_cycle_length) + 1).into() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } let pox_info = get_pox_info(&http_origin).unwrap(); @@ -7220,16 +7128,13 @@ fn pox_integration_test() { .block_height_to_reward_cycle(sort_height) .expect("Expected to be able to get reward cycle"); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); assert_eq!(pox_info.first_burnchain_block_height, 0); assert_eq!(pox_info.next_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.stacked_ustx, 1000000000000000); assert!(pox_info.pox_activation_threshold_ustx > 1500000000000000); - assert_eq!(pox_info.current_cycle.is_pox_active, false); + assert!(!pox_info.current_cycle.is_pox_active); assert_eq!(pox_info.next_cycle.stacked_ustx, 1000000000000000); assert_eq!(pox_info.reward_slots as u32, pox_constants.reward_slots()); assert_eq!(pox_info.next_cycle.reward_phase_start_block_height, 225); @@ -7281,8 +7186,7 @@ fn pox_integration_test() { // 14, and goes for 6 blocks, so we unlock in reward cycle 20, which with a reward // cycle length of 15 blocks, is a burnchain height of 300) assert_eq!(parsed.to_string(), - format!("(ok (tuple (lock-amount u1000000000000000) (stacker {}) (unlock-burn-height u300)))", - &spender_addr)); + format!("(ok (tuple (lock-amount u1000000000000000) (stacker {spender_addr}) (unlock-burn-height u300)))")); tested = true; } } @@ -7307,7 +7211,7 @@ fn pox_integration_test() { &[ Value::UInt(stacked_bal / 2), execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_2_pubkey_hash), + &format!("{{ hashbytes: 0x{pox_2_pubkey_hash}, version: 0x00 }}"), ClarityVersion::Clarity1, ) .unwrap() @@ -7331,7 +7235,7 @@ fn pox_integration_test() { &[ Value::UInt(stacked_bal / 2), execute( - &format!("{{ hashbytes: 0x{}, version: 0x00 }}", pox_2_pubkey_hash), + &format!("{{ hashbytes: 0x{pox_2_pubkey_hash}, version: 0x00 }}"), ClarityVersion::Clarity1, ) .unwrap() @@ -7348,20 +7252,17 @@ fn pox_integration_test() { while sort_height < ((15 * pox_constants.reward_cycle_length) - 1).into() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } let pox_info = get_pox_info(&http_origin).unwrap(); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); assert_eq!(pox_info.first_burnchain_block_height, 0); assert_eq!(pox_info.next_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.stacked_ustx, 1000000000000000); - assert_eq!(pox_info.current_cycle.is_pox_active, false); + assert!(!pox_info.current_cycle.is_pox_active); assert_eq!(pox_info.next_cycle.stacked_ustx, 2000000000000000); assert_eq!(pox_info.reward_slots as u32, pox_constants.reward_slots()); assert_eq!(pox_info.next_cycle.reward_phase_start_block_height, 225); @@ -7403,19 +7304,16 @@ fn pox_integration_test() { while sort_height < ((16 * pox_constants.reward_cycle_length) - 1).into() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } let pox_info = get_pox_info(&http_origin).unwrap(); - assert_eq!( - &pox_info.contract_id, - &format!("ST000000000000000000002AMW42H.pox") - ); + assert_eq!(&pox_info.contract_id, "ST000000000000000000002AMW42H.pox"); assert_eq!(pox_info.first_burnchain_block_height, 0); assert_eq!(pox_info.current_cycle.min_threshold_ustx, 125080000000000); assert_eq!(pox_info.current_cycle.stacked_ustx, 2000000000000000); - assert_eq!(pox_info.current_cycle.is_pox_active, true); + assert!(pox_info.current_cycle.is_pox_active); assert_eq!(pox_info.next_cycle.reward_phase_start_block_height, 240); assert_eq!(pox_info.next_cycle.prepare_phase_start_block_height, 235); assert_eq!(pox_info.next_cycle.blocks_until_prepare_phase, -4); @@ -7472,11 +7370,11 @@ fn pox_integration_test() { assert_eq!(recipient_slots.len(), 2); assert_eq!( - recipient_slots.get(&format!("{}", &pox_2_address)).cloned(), + recipient_slots.get(&format!("{pox_2_address}")).cloned(), Some(7u64) ); assert_eq!( - recipient_slots.get(&format!("{}", &pox_1_address)).cloned(), + recipient_slots.get(&format!("{pox_1_address}")).cloned(), Some(7u64) ); @@ -7490,7 +7388,7 @@ fn pox_integration_test() { while sort_height < ((17 * pox_constants.reward_cycle_length) - 1).into() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // get the canonical chain tip @@ -7513,7 +7411,7 @@ fn pox_integration_test() { while sort_height < ((18 * pox_constants.reward_cycle_length) - 1).into() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } let utxos = btc_regtest_controller.get_all_utxos(&pox_2_pubkey); @@ -7661,7 +7559,7 @@ fn atlas_integration_test() { // (stx-to-burn uint)) let namespace = "passport"; let salt = "some-salt"; - let salted_namespace = format!("{}{}", namespace, salt); + let salted_namespace = format!("{namespace}{salt}"); let hashed_namespace = Hash160::from_data(salted_namespace.as_bytes()); let tx_1 = make_contract_call( &user_1, @@ -7677,14 +7575,14 @@ fn atlas_integration_test() { ], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") .body(tx_1.clone()) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let res: String = res.json().unwrap(); assert_eq!( @@ -7759,14 +7657,14 @@ fn atlas_integration_test() { ], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") .body(tx_2.clone()) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let res: String = res.json().unwrap(); assert_eq!( @@ -7810,14 +7708,14 @@ fn atlas_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -7830,7 +7728,7 @@ fn atlas_integration_test() { while sort_height < few_blocks { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // Then check that the follower is correctly replicating the attachment @@ -7852,27 +7750,23 @@ fn atlas_integration_test() { while sort_height < few_blocks { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // Poll GET v2/attachments/ for i in 1..10 { let mut attachments_did_sync = false; let mut timeout = 60; - while attachments_did_sync != true { + while !attachments_did_sync { let zonefile_hex = hex_bytes(&format!("facade0{}", i)).unwrap(); let hashed_zonefile = Hash160::from_data(&zonefile_hex); - let path = format!( - "{}/v2/attachments/{}", - &http_origin, - hashed_zonefile.to_hex() - ); + let path = format!("{http_origin}/v2/attachments/{}", hashed_zonefile.to_hex()); let res = client .get(&path) .header("Content-Type", "application/json") .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let attachment_response: GetAttachmentResponse = res.json().unwrap(); assert_eq!(attachment_response.attachment.content, zonefile_hex); @@ -7944,20 +7838,16 @@ fn atlas_integration_test() { // Now wait for the node to sync the attachment let mut attachments_did_sync = false; let mut timeout = 60; - while attachments_did_sync != true { + while !attachments_did_sync { let zonefile_hex = "facade00"; let hashed_zonefile = Hash160::from_data(&hex_bytes(zonefile_hex).unwrap()); - let path = format!( - "{}/v2/attachments/{}", - &http_origin, - hashed_zonefile.to_hex() - ); + let path = format!("{http_origin}/v2/attachments/{}", hashed_zonefile.to_hex()); let res = client .get(&path) .header("Content-Type", "application/json") .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { eprintln!("Success syncing attachment - {}", res.text().unwrap()); attachments_did_sync = true; @@ -7966,7 +7856,7 @@ fn atlas_integration_test() { if timeout == 0 { panic!("Failed syncing 1 attachments between 2 neon runloops within 60s - Something is wrong"); } - eprintln!("Attachment {} not sync'd yet", zonefile_hex); + eprintln!("Attachment {zonefile_hex} not sync'd yet"); thread::sleep(Duration::from_millis(1000)); } } @@ -7980,7 +7870,7 @@ fn atlas_integration_test() { let namespace = "passport"; for i in 1..10 { let user = StacksPrivateKey::new(); - let zonefile_hex = format!("facade0{}", i); + let zonefile_hex = format!("facade0{i}"); let hashed_zonefile = Hash160::from_data(&hex_bytes(&zonefile_hex).unwrap()); let name = format!("johndoe{}", i); let tx = make_contract_call( @@ -8007,14 +7897,14 @@ fn atlas_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8040,20 +7930,16 @@ fn atlas_integration_test() { for i in 1..10 { let mut attachments_did_sync = false; let mut timeout = 60; - while attachments_did_sync != true { - let zonefile_hex = hex_bytes(&format!("facade0{}", i)).unwrap(); + while !attachments_did_sync { + let zonefile_hex = hex_bytes(&format!("facade0{i}")).unwrap(); let hashed_zonefile = Hash160::from_data(&zonefile_hex); - let path = format!( - "{}/v2/attachments/{}", - &http_origin, - hashed_zonefile.to_hex() - ); + let path = format!("{http_origin}/v2/attachments/{}", hashed_zonefile.to_hex()); let res = client .get(&path) .header("Content-Type", "application/json") .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let attachment_response: GetAttachmentResponse = res.json().unwrap(); assert_eq!(attachment_response.attachment.content, zonefile_hex); @@ -8072,7 +7958,7 @@ fn atlas_integration_test() { // Ensure that we the attached sidecar was able to receive a total of 10 attachments // This last assertion is flacky for some reason, it does not worth bullying the CI or disabling this whole test // We're using an inequality as a best effort, to make sure that **some** attachments were received. - assert!(test_observer::get_attachments().len() > 0); + assert!(!test_observer::get_attachments().is_empty()); test_observer::clear(); channel.stop_chains_coordinator(); @@ -8122,8 +8008,8 @@ fn antientropy_integration_test() { // Prepare the config of the follower node let (mut conf_follower_node, _) = neon_integration_test_conf(); let bootstrap_node_url = format!( - "{}@{}", - bootstrap_node_public_key, conf_bootstrap_node.node.p2p_bind + "{bootstrap_node_public_key}@{}", + conf_bootstrap_node.node.p2p_bind ); conf_follower_node.connection_options.disable_block_download = true; conf_follower_node.node.set_bootstrap_nodes( @@ -8195,10 +8081,10 @@ fn antientropy_integration_test() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); for i in 0..(target_height - 3) { - eprintln!("Mine block {}", i); + eprintln!("Mine block {i}"); next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // Let's setup the follower now. @@ -8214,11 +8100,11 @@ fn antientropy_integration_test() { println!("Follower has finished"); } Ok(x) => { - println!("Follower gave a bad signal: {:?}", &x); + println!("Follower gave a bad signal: {x:?}"); panic!(); } Err(e) => { - println!("Failed to recv: {:?}", &e); + println!("Failed to recv: {e:?}"); panic!(); } }; @@ -8255,8 +8141,7 @@ fn antientropy_integration_test() { let mut sort_height = channel.get_sortitions_processed(); while sort_height < (target_height + 200) as u64 { eprintln!( - "Follower sortition is {}, target is {}", - sort_height, + "Follower sortition is {sort_height}, target is {}", target_height + 200 ); wait_for_runloop(&blocks_processed); @@ -8269,8 +8154,7 @@ fn antientropy_integration_test() { // wait for block height to reach target let mut tip_height = get_chain_tip_height(&http_origin); eprintln!( - "Follower Stacks tip height is {}, wait until {} >= {} - 3", - tip_height, tip_height, target_height + "Follower Stacks tip height is {tip_height}, wait until {tip_height} >= {target_height} - 3" ); let btc_regtest_controller = BitcoinRegtestController::with_burnchain( @@ -8285,7 +8169,7 @@ fn antientropy_integration_test() { sleep_ms(1000); tip_height = get_chain_tip_height(&http_origin); - eprintln!("Follower Stacks tip height is {}", tip_height); + eprintln!("Follower Stacks tip height is {tip_height}"); if burnchain_deadline < get_epoch_time_secs() { burnchain_deadline = get_epoch_time_secs() + 60; @@ -8304,12 +8188,13 @@ fn antientropy_integration_test() { channel.stop_chains_coordinator(); } +#[allow(clippy::too_many_arguments)] fn wait_for_mined( btc_regtest_controller: &mut BitcoinRegtestController, blocks_processed: &Arc, http_origin: &str, users: &[StacksPrivateKey], - account_before_nonces: &Vec, + account_before_nonces: &[u64], batch_size: usize, batches: usize, index_block_hashes: &mut Vec, @@ -8318,7 +8203,7 @@ fn wait_for_mined( let mut account_after_nonces = vec![0; batches * batch_size]; let mut all_mined = false; for _k in 0..10 { - next_block_and_wait(btc_regtest_controller, &blocks_processed); + next_block_and_wait(btc_regtest_controller, blocks_processed); sleep_ms(10_000); let (ch, bhh) = get_chain_tip(http_origin); @@ -8327,29 +8212,28 @@ fn wait_for_mined( if let Some(last_ibh) = index_block_hashes.last() { if *last_ibh != ibh { index_block_hashes.push(ibh); - eprintln!("Tip is now {}", &ibh); + eprintln!("Tip is now {ibh}"); } } for j in 0..batches * batch_size { - let account_after = get_account(&http_origin, &to_addr(&users[j])); + let account_after = get_account(http_origin, &to_addr(&users[j])); let account_after_nonce = account_after.nonce; account_after_nonces[j] = account_after_nonce; - if account_before_nonces[j] + 1 <= account_after_nonce { + if account_before_nonces[j] < account_after_nonce { all_mined_vec[j] = true; } } - all_mined = all_mined_vec.iter().fold(true, |acc, elem| acc && *elem); + all_mined = all_mined_vec.iter().all(|elem| *elem); if all_mined { break; } } if !all_mined { eprintln!( - "Failed to mine all transactions: nonces = {:?}, expected {:?} + {}", - &account_after_nonces, account_before_nonces, batch_size + "Failed to mine all transactions: nonces = {account_after_nonces:?}, expected {account_before_nonces:?} + {batch_size}" ); panic!(); } @@ -8450,7 +8334,7 @@ fn atlas_stress_integration_test() { // (stx-to-burn uint)) let namespace = "passport"; let salt = "some-salt"; - let salted_namespace = format!("{}{}", namespace, salt); + let salted_namespace = format!("{namespace}{salt}"); let hashed_namespace = Hash160::from_data(salted_namespace.as_bytes()); let tx_1 = make_contract_call( &user_1, @@ -8466,14 +8350,14 @@ fn atlas_stress_integration_test() { ], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") .body(tx_1.clone()) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if res.status().is_success() { let res: String = res.json().unwrap(); assert_eq!( @@ -8548,7 +8432,7 @@ fn atlas_stress_integration_test() { ], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -8626,14 +8510,14 @@ fn atlas_stress_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8660,8 +8544,7 @@ fn atlas_stress_integration_test() { } if !all_mined { eprintln!( - "Failed to mine all transactions: nonce = {}, expected {}", - account_after_nonce, + "Failed to mine all transactions: nonce = {account_after_nonce}, expected {}", account_before.nonce + (batch_size as u64) ); panic!(); @@ -8682,14 +8565,14 @@ fn atlas_stress_integration_test() { &[Value::buff_from(namespace.as_bytes().to_vec()).unwrap()], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") .body(tx_4.clone()) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8723,7 +8606,7 @@ fn atlas_stress_integration_test() { get_account(&http_origin, &to_addr(&users[batches * batch_size + j])); account_before_nonces[j] = account_before.nonce; - let fqn = format!("janedoe{}.passport", j); + let fqn = format!("janedoe{j}.passport"); let fqn_bytes = fqn.as_bytes().to_vec(); let salt = format!("{:04x}", j); let salt_bytes = salt.as_bytes().to_vec(); @@ -8746,7 +8629,7 @@ fn atlas_stress_integration_test() { ], ); - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -8755,9 +8638,8 @@ fn atlas_stress_integration_test() { .unwrap(); eprintln!( - "sent preorder for {}:\n{:#?}", - &to_addr(&users[batches * batch_size + j]), - res + "sent preorder for {}:\n{res:#?}", + &to_addr(&users[batches * batch_size + j]) ); if !res.status().is_success() { panic!(""); @@ -8784,10 +8666,10 @@ fn atlas_stress_integration_test() { get_account(&http_origin, &to_addr(&users[batches * batch_size + j])); account_before_nonces[j] = account_before.nonce; - let name = format!("janedoe{}", j); - let salt = format!("{:04x}", j); + let name = format!("janedoe{j}"); + let salt = format!("{j:04x}"); - let zonefile_hex = format!("facade01{:04x}", j); + let zonefile_hex = format!("facade01{j:04x}"); let hashed_zonefile = Hash160::from_data(&hex_bytes(&zonefile_hex).unwrap()); all_zonefiles.push(zonefile_hex.clone()); @@ -8816,14 +8698,14 @@ fn atlas_stress_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8850,8 +8732,8 @@ fn atlas_stress_integration_test() { get_account(&http_origin, &to_addr(&users[batches * batch_size + j])); account_before_nonces[j] = account_before.nonce; - let name = format!("janedoe{}", j); - let zonefile_hex = format!("facade02{:04x}", j); + let name = format!("janedoe{j}"); + let zonefile_hex = format!("facade02{j:04x}"); let hashed_zonefile = Hash160::from_data(&hex_bytes(&zonefile_hex).unwrap()); all_zonefiles.push(zonefile_hex.clone()); @@ -8879,14 +8761,14 @@ fn atlas_stress_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8913,8 +8795,8 @@ fn atlas_stress_integration_test() { get_account(&http_origin, &to_addr(&users[batches * batch_size + j])); account_before_nonces[j] = account_before.nonce; - let name = format!("janedoe{}", j); - let zonefile_hex = format!("facade03{:04x}", j); + let name = format!("janedoe{j}"); + let zonefile_hex = format!("facade03{j:04x}"); let hashed_zonefile = Hash160::from_data(&hex_bytes(&zonefile_hex).unwrap()); all_zonefiles.push(zonefile_hex.clone()); @@ -8945,14 +8827,14 @@ fn atlas_stress_integration_test() { serde_json::to_vec(&json!(content)).unwrap() }; - let path = format!("{}/v2/transactions", &http_origin); + let path = format!("{http_origin}/v2/transactions"); let res = client .post(&path) .header("Content-Type", "application/json") .body(body) .send() .unwrap(); - eprintln!("{:#?}", res); + eprintln!("{res:#?}"); if !res.status().is_success() { eprintln!("{}", res.text().unwrap()); panic!(""); @@ -8984,8 +8866,8 @@ fn atlas_stress_integration_test() { &[ibh], ) .unwrap(); - if indexes.len() > 0 { - attachment_indexes.insert(ibh.clone(), indexes.clone()); + if !indexes.is_empty() { + attachment_indexes.insert(*ibh, indexes.clone()); } for index in indexes.iter() { @@ -8995,14 +8877,14 @@ fn atlas_stress_integration_test() { params![ibh, u64_to_sql(*index).unwrap()], "content_hash") .unwrap(); - if hashes.len() > 0 { + if !hashes.is_empty() { assert_eq!(hashes.len(), 1); - attachment_hashes.insert((ibh.clone(), *index), hashes.pop()); + attachment_hashes.insert((*ibh, *index), hashes.pop()); } } } } - eprintln!("attachment_indexes = {:?}", &attachment_indexes); + eprintln!("attachment_indexes = {attachment_indexes:?}"); let max_request_time_ms = 100; @@ -9017,12 +8899,10 @@ fn atlas_stress_integration_test() { ..cmp::min((i + 1) * MAX_ATTACHMENT_INV_PAGES_PER_REQUEST, l)] .to_vec(); let path = format!( - "{}/v2/attachments/inv?index_block_hash={}&pages_indexes={}", - &http_origin, - ibh, + "{http_origin}/v2/attachments/inv?index_block_hash={ibh}&pages_indexes={}", attachments_batch .iter() - .map(|a| format!("{}", &a)) + .map(|a| format!("{a}")) .collect::>() .join(",") ); @@ -9034,40 +8914,34 @@ fn atlas_stress_integration_test() { if res.status().is_success() { let attachment_inv_response: GetAttachmentsInvResponse = res.json().unwrap(); - eprintln!( - "attachment inv response for {}: {:?}", - &path, &attachment_inv_response - ); + eprintln!("attachment inv response for {path}: {attachment_inv_response:?}"); } else { - eprintln!("Bad response for `{}`: `{:?}`", &path, res.text().unwrap()); + eprintln!("Bad response for `{path}`: `{:?}`", res.text().unwrap()); panic!(); } } let ts_end = get_epoch_time_ms(); let total_time = ts_end.saturating_sub(ts_begin); - eprintln!("Requested {} {} times in {}ms", &path, attempts, total_time); + eprintln!("Requested {path} {attempts} times in {total_time}ms"); // requests should take no more than max_request_time_ms assert!( total_time < attempts * max_request_time_ms, - "Atlas inventory request is too slow: {} >= {} * {}", - total_time, - attempts, - max_request_time_ms + "Atlas inventory request is too slow: {total_time} >= {attempts} * {max_request_time_ms}" ); } - for i in 0..l { - if attachments[i] == 0 { + for attachment in attachments.iter().take(l) { + if *attachment == 0 { continue; } let content_hash = attachment_hashes - .get(&(*ibh, attachments[i])) + .get(&(*ibh, *attachment)) .cloned() .unwrap() .unwrap(); - let path = format!("{}/v2/attachments/{}", &http_origin, &content_hash); + let path = format!("{http_origin}/v2/attachments/{content_hash}"); let attempts = 10; let ts_begin = get_epoch_time_ms(); @@ -9076,26 +8950,20 @@ fn atlas_stress_integration_test() { if res.status().is_success() { let attachment_response: GetAttachmentResponse = res.json().unwrap(); - eprintln!( - "attachment response for {}: {:?}", - &path, &attachment_response - ); + eprintln!("attachment response for {path}: {attachment_response:?}"); } else { - eprintln!("Bad response for `{}`: `{:?}`", &path, res.text().unwrap()); + eprintln!("Bad response for `{path}`: `{:?}`", res.text().unwrap()); panic!(); } } let ts_end = get_epoch_time_ms(); let total_time = ts_end.saturating_sub(ts_begin); - eprintln!("Requested {} {} times in {}ms", &path, attempts, total_time); + eprintln!("Requested {path} {attempts} times in {total_time}ms"); // requests should take no more than max_request_time_ms assert!( total_time < attempts * max_request_time_ms, - "Atlas chunk request is too slow: {} >= {} * {}", - total_time, - attempts, - max_request_time_ms + "Atlas chunk request is too slow: {total_time} >= {attempts} * {max_request_time_ms}" ); } } @@ -9129,8 +8997,7 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value (unwrap! (increment) (err u1)) (unwrap! (increment) (err u1)) (ok (var-get counter)))) - "# - .to_string(); + "#; let spender_sk = StacksPrivateKey::new(); let spender_addr = to_addr(&spender_sk); @@ -9144,7 +9011,7 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value conf.estimation.fee_rate_window_size = window_size; conf.initial_balances.push(InitialBalance { - address: spender_addr.clone().into(), + address: spender_addr.into(), amount: 10000000000, }); test_observer::spawn(); @@ -9181,7 +9048,7 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value 110000, conf.burnchain.chain_id, "increment-contract", - &max_contract_src, + max_contract_src, ), ); run_until_burnchain_height(&mut btc_regtest_controller, &blocks_processed, 212, &conf); @@ -9198,7 +9065,7 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value i, // nonce i * 100000, // payment conf.burnchain.chain_id, - &spender_addr.into(), + &spender_addr, "increment-contract", "increment-many", &[], @@ -9213,12 +9080,12 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value { // Read from the fee estimation endpoin. - let path = format!("{}/v2/fees/transaction", &http_origin); + let path = format!("{http_origin}/v2/fees/transaction"); let tx_payload = TransactionPayload::ContractCall(TransactionContractCall { - address: spender_addr.clone().into(), - contract_name: ContractName::try_from("increment-contract").unwrap(), - function_name: ClarityName::try_from("increment-many").unwrap(), + address: spender_addr, + contract_name: ContractName::from("increment-contract"), + function_name: ClarityName::from("increment-many"), function_args: vec![], }); @@ -9255,8 +9122,8 @@ fn fuzzed_median_fee_rate_estimation_test(window_size: u64, expected_final_value let last_cost = response_estimated_costs[i - 1]; assert_eq!(curr_cost, last_cost); - let curr_rate = response_top_fee_rates[i] as f64; - let last_rate = response_top_fee_rates[i - 1] as f64; + let curr_rate = response_top_fee_rates[i]; + let last_rate = response_top_fee_rates[i - 1]; assert!(curr_rate >= last_rate); } @@ -9438,7 +9305,7 @@ fn use_latest_tip_integration_test() { let client = reqwest::blocking::Client::new(); // Post the microblock - let path = format!("{}/v2/microblocks", &http_origin); + let path = format!("{http_origin}/v2/microblocks"); let res: String = client .post(&path) .header("Content-Type", "application/octet-stream") @@ -9452,7 +9319,7 @@ fn use_latest_tip_integration_test() { // Wait for the microblock to be accepted sleep_ms(5_000); - let path = format!("{}/v2/info", &http_origin); + let path = format!("{http_origin}/v2/info"); let mut iter_count = 0; loop { let tip_info = client @@ -9594,26 +9461,26 @@ fn test_flash_block_skip_tenure() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); // fault injection: force tenures to take too long - std::env::set_var("STX_TEST_SLOW_TENURE".to_string(), "11000".to_string()); + std::env::set_var("STX_TEST_SLOW_TENURE", "11000"); for i in 0..10 { // build one bitcoin block every 10 seconds - eprintln!("Build bitcoin block +{}", i); + eprintln!("Build bitcoin block +{i}"); btc_regtest_controller.build_next_block(1); sleep_ms(10000); } // at least one tenure was skipped let num_skipped = missed_tenures.load(Ordering::SeqCst); - eprintln!("Skipped {} tenures", &num_skipped); + eprintln!("Skipped {num_skipped} tenures"); assert!(num_skipped > 1); // let's query the miner's account nonce: - eprintln!("Miner account: {}", miner_account); + eprintln!("Miner account: {miner_account}"); let account = get_account(&http_origin, &miner_account); - eprintln!("account = {:?}", &account); + eprintln!("account = {account:?}"); assert_eq!(account.balance, 0); assert_eq!(account.nonce, 2); @@ -9696,15 +9563,15 @@ fn test_problematic_txs_are_not_stored() { let (mut conf, _) = neon_integration_test_conf(); conf.initial_balances.push(InitialBalance { - address: spender_addr_1.clone(), + address: spender_addr_1, amount: 1_000_000_000_000, }); conf.initial_balances.push(InitialBalance { - address: spender_addr_2.clone(), + address: spender_addr_2, amount: 1_000_000_000_000, }); conf.initial_balances.push(InitialBalance { - address: spender_addr_3.clone(), + address: spender_addr_3, amount: 1_000_000_000_000, }); @@ -9772,7 +9639,7 @@ fn test_problematic_txs_are_not_stored() { let exceeds_repeat_factor = edge_repeat_factor + 1; let tx_exceeds_body_start = "{ a : ".repeat(exceeds_repeat_factor as usize); let tx_exceeds_body_end = "} ".repeat(exceeds_repeat_factor as usize); - let tx_exceeds_body = format!("{}u1 {}", tx_exceeds_body_start, tx_exceeds_body_end); + let tx_exceeds_body = format!("{tx_exceeds_body_start}u1 {tx_exceeds_body_end}"); let tx_exceeds = make_contract_publish( &spender_sk_2, @@ -9790,7 +9657,7 @@ fn test_problematic_txs_are_not_stored() { let high_repeat_factor = 128 * 1024; let tx_high_body_start = "{ a : ".repeat(high_repeat_factor as usize); let tx_high_body_end = "} ".repeat(high_repeat_factor as usize); - let tx_high_body = format!("{}u1 {}", tx_high_body_start, tx_high_body_end); + let tx_high_body = format!("{tx_high_body_start}u1 {tx_high_body_end}"); let tx_high = make_contract_publish( &spender_sk_3, @@ -9840,25 +9707,24 @@ fn test_problematic_txs_are_not_stored() { fn find_new_files(dirp: &str, prev_files: &HashSet) -> (Vec, HashSet) { let dirpp = Path::new(dirp); - debug!("readdir {}", dirp); + debug!("readdir {dirp}"); let cur_files = fs::read_dir(dirp).unwrap(); let mut new_files = vec![]; let mut cur_files_set = HashSet::new(); for cur_file in cur_files.into_iter() { let cur_file = cur_file.unwrap(); let cur_file_fullpath = dirpp.join(cur_file.path()).to_str().unwrap().to_string(); - test_debug!("file in {}: {}", dirp, &cur_file_fullpath); + test_debug!("file in {dirp}: {cur_file_fullpath}"); cur_files_set.insert(cur_file_fullpath.clone()); if prev_files.contains(&cur_file_fullpath) { - test_debug!("already contains {}", &cur_file_fullpath); + test_debug!("already contains {cur_file_fullpath}"); continue; } - test_debug!("new file {}", &cur_file_fullpath); + test_debug!("new file {cur_file_fullpath}"); new_files.push(cur_file_fullpath); } debug!( - "Checked {} for new files; found {} (all: {})", - dirp, + "Checked {dirp} for new files; found {} (all: {})", new_files.len(), cur_files_set.len() ); @@ -9894,8 +9760,7 @@ fn spawn_follower_node( conf.initial_balances = initial_conf.initial_balances.clone(); conf.burnchain.epochs = initial_conf.burnchain.epochs.clone(); - conf.burnchain.ast_precheck_size_height = - initial_conf.burnchain.ast_precheck_size_height.clone(); + conf.burnchain.ast_precheck_size_height = initial_conf.burnchain.ast_precheck_size_height; conf.connection_options.inv_sync_interval = 3; @@ -9923,12 +9788,12 @@ fn test_problematic_blocks_are_not_mined() { } let bad_blocks_dir = "/tmp/bad-blocks-test_problematic_blocks_are_not_mined"; - if fs::metadata(&bad_blocks_dir).is_ok() { - fs::remove_dir_all(&bad_blocks_dir).unwrap(); + if fs::metadata(bad_blocks_dir).is_ok() { + fs::remove_dir_all(bad_blocks_dir).unwrap(); } - fs::create_dir_all(&bad_blocks_dir).unwrap(); + fs::create_dir_all(bad_blocks_dir).unwrap(); - std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir.to_string()); + std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir); let spender_sk_1 = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_sk_2 = StacksPrivateKey::from_hex(SK_2).unwrap(); @@ -10000,7 +9865,7 @@ fn test_problematic_blocks_are_not_mined() { let exceeds_repeat_factor = 32; let tx_exceeds_body_start = "{ a : ".repeat(exceeds_repeat_factor as usize); let tx_exceeds_body_end = "} ".repeat(exceeds_repeat_factor as usize); - let tx_exceeds_body = format!("{}u1 {}", tx_exceeds_body_start, tx_exceeds_body_end); + let tx_exceeds_body = format!("{tx_exceeds_body_start}u1 {tx_exceeds_body_end}"); let tx_exceeds = make_contract_publish( &spender_sk_2, @@ -10018,7 +9883,7 @@ fn test_problematic_blocks_are_not_mined() { let high_repeat_factor = 3200; let tx_high_body_start = "{ a : ".repeat(high_repeat_factor as usize); let tx_high_body_end = "} ".repeat(high_repeat_factor as usize); - let tx_high_body = format!("{}u1 {}", tx_high_body_start, tx_high_body_end); + let tx_high_body = format!("{tx_high_body_start}u1 {tx_high_body_end}"); let tx_high = make_contract_publish( &spender_sk_3, @@ -10054,20 +9919,11 @@ fn test_problematic_blocks_are_not_mined() { // Third block will be the first mined Stacks block. next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); - debug!( - "Submit problematic tx_exceeds transaction {}", - &tx_exceeds_txid - ); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + debug!("Submit problematic tx_exceeds transaction {tx_exceeds_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_exceeds); assert!(get_unconfirmed_tx(&http_origin, &tx_exceeds_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); @@ -10116,7 +9972,7 @@ fn test_problematic_blocks_are_not_mined() { let (tip, cur_ast_rules) = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); (tip, cur_ast_rules) @@ -10125,31 +9981,25 @@ fn test_problematic_blocks_are_not_mined() { assert_eq!(cur_ast_rules, ASTRules::Typical); // add another bad tx to the mempool - debug!("Submit problematic tx_high transaction {}", &tx_high_txid); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + debug!("Submit problematic tx_high transaction {tx_high_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_high); assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); btc_regtest_controller.build_next_block(1); // wait for runloop to advance wait_for(30, || { let sortdb = btc_regtest_controller.sortdb_mut(); - let new_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let new_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); Ok(new_tip.block_height > tip.block_height) }) .expect("Failed waiting for blocks to be processed"); let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -10162,7 +10012,7 @@ fn test_problematic_blocks_are_not_mined() { let old_tip_info = get_chain_info(&conf); let mut all_new_files = vec![]; - eprintln!("old_tip_info = {:?}", &old_tip_info); + eprintln!("old_tip_info = {old_tip_info:?}"); // mine some blocks, and log problematic blocks for _i in 0..6 { @@ -10185,10 +10035,8 @@ fn test_problematic_blocks_are_not_mined() { // recently-submitted problematic transactions are not in the mempool // (but old ones that were already mined, and thus never considered, could still be present) - for txid in &[&tx_high_txid] { - test_debug!("Problematic tx {} should be dropped", txid); - assert!(get_unconfirmed_tx(&http_origin, txid).is_none()); - } + test_debug!("Problematic tx {tx_high_txid} should be dropped"); + assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_none()); // no block contained the tx_high bad transaction, ever let blocks = test_observer::get_blocks(); @@ -10233,8 +10081,7 @@ fn test_problematic_blocks_are_not_mined() { // make sure we aren't just slow -- wait for the follower to do a few download passes let num_download_passes = pox_sync_comms.get_download_passes(); eprintln!( - "\nFollower has performed {} download passes; wait for {}\n", - num_download_passes, + "\nFollower has performed {num_download_passes} download passes; wait for {}\n", num_download_passes + 5 ); @@ -10278,12 +10125,12 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { } let bad_blocks_dir = "/tmp/bad-blocks-test_problematic_blocks_are_not_relayed_or_stored"; - if fs::metadata(&bad_blocks_dir).is_ok() { - fs::remove_dir_all(&bad_blocks_dir).unwrap(); + if fs::metadata(bad_blocks_dir).is_ok() { + fs::remove_dir_all(bad_blocks_dir).unwrap(); } - fs::create_dir_all(&bad_blocks_dir).unwrap(); + fs::create_dir_all(bad_blocks_dir).unwrap(); - std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir.to_string()); + std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir); let spender_sk_1 = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_sk_2 = StacksPrivateKey::from_hex(SK_2).unwrap(); @@ -10355,7 +10202,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { let exceeds_repeat_factor = 32; let tx_exceeds_body_start = "{ a : ".repeat(exceeds_repeat_factor as usize); let tx_exceeds_body_end = "} ".repeat(exceeds_repeat_factor as usize); - let tx_exceeds_body = format!("{}u1 {}", tx_exceeds_body_start, tx_exceeds_body_end); + let tx_exceeds_body = format!("{tx_exceeds_body_start}u1 {tx_exceeds_body_end}"); let tx_exceeds = make_contract_publish( &spender_sk_2, @@ -10372,7 +10219,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { let high_repeat_factor = 70; let tx_high_body_start = "{ a : ".repeat(high_repeat_factor as usize); let tx_high_body_end = "} ".repeat(high_repeat_factor as usize); - let tx_high_body = format!("{}u1 {}", tx_high_body_start, tx_high_body_end); + let tx_high_body = format!("{tx_high_body_start}u1 {tx_high_body_end}"); let tx_high = make_contract_publish( &spender_sk_3, @@ -10408,20 +10255,11 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { // Third block will be the first mined Stacks block. next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); - debug!( - "Submit problematic tx_exceeds transaction {}", - &tx_exceeds_txid - ); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + debug!("Submit problematic tx_exceeds transaction {tx_exceeds_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_exceeds); assert!(get_unconfirmed_tx(&http_origin, &tx_exceeds_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); @@ -10470,7 +10308,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { let (tip, cur_ast_rules) = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); (tip, cur_ast_rules) @@ -10484,14 +10322,14 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { loop { sleep_ms(1_000); let sortdb = btc_regtest_controller.sortdb_mut(); - let new_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let new_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); if new_tip.block_height > tip.block_height { break; } } let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -10510,7 +10348,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { } let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -10521,23 +10359,17 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { // add another bad tx to the mempool. // because the miner is now non-conformant, it should mine this tx. - debug!("Submit problematic tx_high transaction {}", &tx_high_txid); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + debug!("Submit problematic tx_high transaction {tx_high_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_high); assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); let mut all_new_files = vec![]; - eprintln!("old_tip_info = {:?}", &old_tip_info); + eprintln!("old_tip_info = {old_tip_info:?}"); // mine some blocks, and log problematic blocks for _i in 0..6 { @@ -10549,7 +10381,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -10616,10 +10448,8 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { break; } eprintln!( - "\nFollower is at burn block {} stacks block {} (bad_block is {})\n", - follower_tip_info.burn_block_height, - follower_tip_info.stacks_tip_height, - bad_block_height + "\nFollower is at burn block {} stacks block {} (bad_block is {bad_block_height})\n", + follower_tip_info.burn_block_height, follower_tip_info.stacks_tip_height ); sleep_ms(1000); } @@ -10627,8 +10457,7 @@ fn test_problematic_blocks_are_not_relayed_or_stored() { // make sure we aren't just slow -- wait for the follower to do a few download passes let num_download_passes = pox_sync_comms.get_download_passes(); eprintln!( - "\nFollower has performed {} download passes; wait for {}\n", - num_download_passes, + "\nFollower has performed {num_download_passes} download passes; wait for {}\n", num_download_passes + 5 ); @@ -10669,12 +10498,12 @@ fn test_problematic_microblocks_are_not_mined() { } let bad_blocks_dir = "/tmp/bad-blocks-test_problematic_microblocks_are_not_mined"; - if fs::metadata(&bad_blocks_dir).is_ok() { - fs::remove_dir_all(&bad_blocks_dir).unwrap(); + if fs::metadata(bad_blocks_dir).is_ok() { + fs::remove_dir_all(bad_blocks_dir).unwrap(); } - fs::create_dir_all(&bad_blocks_dir).unwrap(); + fs::create_dir_all(bad_blocks_dir).unwrap(); - std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir.to_string()); + std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir); let spender_sk_1 = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_sk_2 = StacksPrivateKey::from_hex(SK_2).unwrap(); @@ -10752,7 +10581,7 @@ fn test_problematic_microblocks_are_not_mined() { let exceeds_repeat_factor = 32; let tx_exceeds_body_start = "{ a : ".repeat(exceeds_repeat_factor as usize); let tx_exceeds_body_end = "} ".repeat(exceeds_repeat_factor as usize); - let tx_exceeds_body = format!("{}u1 {}", tx_exceeds_body_start, tx_exceeds_body_end); + let tx_exceeds_body = format!("{tx_exceeds_body_start}u1 {tx_exceeds_body_end}"); let tx_exceeds = make_contract_publish_microblock_only( &spender_sk_2, @@ -10767,11 +10596,10 @@ fn test_problematic_microblocks_are_not_mined() { .txid(); // something stupidly high over the expression depth - let high_repeat_factor = - (AST_CALL_STACK_DEPTH_BUFFER as u64) + (MAX_CALL_STACK_DEPTH as u64) + 1; + let high_repeat_factor = AST_CALL_STACK_DEPTH_BUFFER + (MAX_CALL_STACK_DEPTH as u64) + 1; let tx_high_body_start = "{ a : ".repeat(high_repeat_factor as usize); let tx_high_body_end = "} ".repeat(high_repeat_factor as usize); - let tx_high_body = format!("{}u1 {}", tx_high_body_start, tx_high_body_end); + let tx_high_body = format!("{tx_high_body_start}u1 {tx_high_body_end}"); let tx_high = make_contract_publish_microblock_only( &spender_sk_3, @@ -10807,24 +10635,12 @@ fn test_problematic_microblocks_are_not_mined() { // Third block will be the first mined Stacks block. next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); - info!( - "Submit problematic tx_exceeds transaction {}", - &tx_exceeds_txid - ); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + info!("Submit problematic tx_exceeds transaction {tx_exceeds_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_exceeds); assert!(get_unconfirmed_tx(&http_origin, &tx_exceeds_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); - info!( - "Submitted problematic tx_exceeds transaction {}", - &tx_exceeds_txid - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); + info!("Submitted problematic tx_exceeds transaction {tx_exceeds_txid}"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); @@ -10876,7 +10692,7 @@ fn test_problematic_microblocks_are_not_mined() { let (tip, cur_ast_rules) = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); (tip, cur_ast_rules) @@ -10885,39 +10701,27 @@ fn test_problematic_microblocks_are_not_mined() { assert_eq!(cur_ast_rules, ASTRules::Typical); // add another bad tx to the mempool - info!("Submit problematic tx_high transaction {}", &tx_high_txid); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + info!("Submit problematic tx_high transaction {tx_high_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_high); assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); - info!( - "Submitted problematic tx_high transaction {}", - &tx_high_txid - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); + info!("Submitted problematic tx_high transaction {tx_high_txid}"); btc_regtest_controller.build_next_block(1); - info!( - "Mined block after submitting problematic tx_high transaction {}", - &tx_high_txid - ); + info!("Mined block after submitting problematic tx_high transaction {tx_high_txid}"); // wait for runloop to advance wait_for(30, || { let sortdb = btc_regtest_controller.sortdb_mut(); - let new_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let new_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); Ok(new_tip.block_height > tip.block_height) }) .expect("Failed waiting for runloop to advance"); let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -10930,7 +10734,7 @@ fn test_problematic_microblocks_are_not_mined() { let old_tip_info = get_chain_info(&conf); let mut all_new_files = vec![]; - eprintln!("old_tip_info = {:?}", &old_tip_info); + eprintln!("old_tip_info = {old_tip_info:?}"); // mine some microblocks, and log problematic microblocks for _i in 0..6 { @@ -10956,10 +10760,8 @@ fn test_problematic_microblocks_are_not_mined() { // recently-submitted problematic transactions are not in the mempool // (but old ones that were already mined, and thus never considered, could still be present) - for txid in &[&tx_high_txid] { - test_debug!("Problematic tx {} should be dropped", txid); - assert!(get_unconfirmed_tx(&http_origin, txid).is_none()); - } + test_debug!("Problematic tx {tx_high_txid} should be dropped"); + assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_none()); // no microblock contained the tx_high bad transaction, ever let microblocks = test_observer::get_microblocks(); @@ -11004,8 +10806,7 @@ fn test_problematic_microblocks_are_not_mined() { // make sure we aren't just slow -- wait for the follower to do a few download passes let num_download_passes = pox_sync_comms.get_download_passes(); eprintln!( - "\nFollower has performed {} download passes; wait for {}\n", - num_download_passes, + "\nFollower has performed {num_download_passes} download passes; wait for {}\n", num_download_passes + 5 ); @@ -11049,12 +10850,12 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { } let bad_blocks_dir = "/tmp/bad-blocks-test_problematic_microblocks_are_not_relayed_or_stored"; - if fs::metadata(&bad_blocks_dir).is_ok() { - fs::remove_dir_all(&bad_blocks_dir).unwrap(); + if fs::metadata(bad_blocks_dir).is_ok() { + fs::remove_dir_all(bad_blocks_dir).unwrap(); } - fs::create_dir_all(&bad_blocks_dir).unwrap(); + fs::create_dir_all(bad_blocks_dir).unwrap(); - std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir.to_string()); + std::env::set_var("STACKS_BAD_BLOCKS_DIR", bad_blocks_dir); let spender_sk_1 = StacksPrivateKey::from_hex(SK_1).unwrap(); let spender_sk_2 = StacksPrivateKey::from_hex(SK_2).unwrap(); @@ -11134,7 +10935,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { let exceeds_repeat_factor = 32; let tx_exceeds_body_start = "{ a : ".repeat(exceeds_repeat_factor as usize); let tx_exceeds_body_end = "} ".repeat(exceeds_repeat_factor as usize); - let tx_exceeds_body = format!("{}u1 {}", tx_exceeds_body_start, tx_exceeds_body_end); + let tx_exceeds_body = format!("{tx_exceeds_body_start}u1 {tx_exceeds_body_end}"); let tx_exceeds = make_contract_publish_microblock_only( &spender_sk_2, @@ -11149,11 +10950,10 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { .txid(); // greatly exceeds AST depth, but is still mineable without a stack overflow - let high_repeat_factor = - (AST_CALL_STACK_DEPTH_BUFFER as u64) + (MAX_CALL_STACK_DEPTH as u64) + 1; + let high_repeat_factor = AST_CALL_STACK_DEPTH_BUFFER + (MAX_CALL_STACK_DEPTH as u64) + 1; let tx_high_body_start = "{ a : ".repeat(high_repeat_factor as usize); let tx_high_body_end = "} ".repeat(high_repeat_factor as usize); - let tx_high_body = format!("{}u1 {}", tx_high_body_start, tx_high_body_end); + let tx_high_body = format!("{tx_high_body_start}u1 {tx_high_body_end}"); let tx_high = make_contract_publish_microblock_only( &spender_sk_3, @@ -11189,20 +10989,11 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { // Third block will be the first mined Stacks block. next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); - debug!( - "Submit problematic tx_exceeds transaction {}", - &tx_exceeds_txid - ); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + debug!("Submit problematic tx_exceeds transaction {tx_exceeds_txid}"); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_exceeds); assert!(get_unconfirmed_tx(&http_origin, &tx_exceeds_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); @@ -11254,7 +11045,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { let (tip, cur_ast_rules) = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); (tip, cur_ast_rules) @@ -11267,14 +11058,14 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { // wait for runloop to advance wait_for(30, || { let sortdb = btc_regtest_controller.sortdb_mut(); - let new_tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let new_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); Ok(new_tip.block_height > tip.block_height) }) .expect("Failed waiting for runloop to advance"); let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -11293,7 +11084,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { } let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); eprintln!("Sort db tip: {}", tip.block_height); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -11304,24 +11095,18 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { // add another bad tx to the mempool. // because the miner is now non-conformant, it should mine this tx. - debug!("Submit problematic tx_high transaction {}", &tx_high_txid); + debug!("Submit problematic tx_high transaction {tx_high_txid}"); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "1".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "1"); submit_tx(&http_origin, &tx_high); assert!(get_unconfirmed_tx(&http_origin, &tx_high_txid).is_some()); - std::env::set_var( - "STACKS_DISABLE_TX_PROBLEMATIC_CHECK".to_string(), - "0".to_string(), - ); + std::env::set_var("STACKS_DISABLE_TX_PROBLEMATIC_CHECK", "0"); let (_, mut cur_files) = find_new_files(bad_blocks_dir, &HashSet::new()); let old_tip_info = get_chain_info(&conf); let mut all_new_files = vec![]; - eprintln!("old_tip_info = {:?}", &old_tip_info); + eprintln!("old_tip_info = {old_tip_info:?}"); // mine some blocks, and log problematic microblocks for _i in 0..6 { @@ -11333,7 +11118,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { let cur_ast_rules = { let sortdb = btc_regtest_controller.sortdb_mut(); - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); let cur_ast_rules = SortitionDB::get_ast_rules(sortdb.conn(), tip.block_height).unwrap(); cur_ast_rules @@ -11356,7 +11141,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { // at least one was problematic. // the miner might make multiple microblocks (only some of which are confirmed), so also check // the event observer to see that we actually picked up tx_high - assert!(all_new_files.len() >= 1); + assert!(!all_new_files.is_empty()); // tx_high got mined by the miner let microblocks = test_observer::get_microblocks(); @@ -11381,8 +11166,8 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { .split("0x") .collect(); let bad_block_id_hex = parts[1]; - debug!("bad_block_id_hex = '{}'", &bad_block_id_hex); - Some(StacksBlockId::from_hex(&bad_block_id_hex).unwrap()) + debug!("bad_block_id_hex = '{bad_block_id_hex}'"); + Some(StacksBlockId::from_hex(bad_block_id_hex).unwrap()) }; } } @@ -11420,8 +11205,7 @@ fn test_problematic_microblocks_are_not_relayed_or_stored() { // make sure we aren't just slow -- wait for the follower to do a few download passes let num_download_passes = pox_sync_comms.get_download_passes(); eprintln!( - "\nFollower has performed {} download passes; wait for {}\n", - num_download_passes, + "\nFollower has performed {num_download_passes} download passes; wait for {}\n", num_download_passes + 5 ); @@ -11570,9 +11354,8 @@ fn make_runtime_sized_contract(num_index_of: usize, nonce: u64, addr_prefix: &st let full_iters_code = full_iters_code_parts.join("\n "); - let iters_mod_code_parts: Vec = (0..iters_mod) - .map(|cnt| format!("0x{:0>2x}", cnt)) - .collect(); + let iters_mod_code_parts: Vec = + (0..iters_mod).map(|cnt| format!("0x{cnt:0>2x}")).collect(); let iters_mod_code = format!("(list {})", iters_mod_code_parts.join(" ")); @@ -11599,7 +11382,7 @@ fn make_runtime_sized_contract(num_index_of: usize, nonce: u64, addr_prefix: &st (define-private (crash-me-folder (input (buff 1)) (ctr uint)) (begin ;; full_iters_code - {} + {full_iters_code} (+ u1 ctr) ) ) @@ -11608,20 +11391,17 @@ fn make_runtime_sized_contract(num_index_of: usize, nonce: u64, addr_prefix: &st ;; call index-of (iters_256 * 256) times (fold crash-me-folder BUFF_TO_BYTE u0) ;; call index-of iters_mod times - (fold crash-me-folder {} u0) + (fold crash-me-folder {iters_mod_code} u0) (print name) (ok u0) ) ) (begin - (crash-me \"{}\")) + (crash-me \"large-{nonce}-{addr_prefix}-{num_index_of}\")) ", - full_iters_code, - iters_mod_code, - &format!("large-{}-{}-{}", nonce, &addr_prefix, num_index_of) ); - eprintln!("{}", &code); + eprintln!("{code}"); code } @@ -11636,13 +11416,14 @@ pub fn make_expensive_tx_chain( chain_id: u32, mblock_only: bool, ) -> Vec> { - let addr = to_addr(&privk); + let addr = to_addr(privk); let mut chain = vec![]; + let num_index_of = 256; for nonce in 0..25 { let mut addr_prefix = addr.to_string(); let _ = addr_prefix.split_off(12); - let contract_name = format!("large-{}-{}-{}", nonce, &addr_prefix, 256); - eprintln!("Make tx {}", &contract_name); + let contract_name = format!("large-{nonce}-{addr_prefix}-{num_index_of}"); + eprintln!("Make tx {contract_name}"); let tx = if mblock_only { make_contract_publish_microblock_only( privk, @@ -11650,7 +11431,7 @@ pub fn make_expensive_tx_chain( 1049230 + nonce + fee_plus, chain_id, &contract_name, - &make_runtime_sized_contract(256, nonce, &addr_prefix), + &make_runtime_sized_contract(num_index_of, nonce, &addr_prefix), ) } else { make_contract_publish( @@ -11659,7 +11440,7 @@ pub fn make_expensive_tx_chain( 1049230 + nonce + fee_plus, chain_id, &contract_name, - &make_runtime_sized_contract(256, nonce, &addr_prefix), + &make_runtime_sized_contract(num_index_of, nonce, &addr_prefix), ) }; chain.push(tx); @@ -11673,7 +11454,7 @@ pub fn make_random_tx_chain( chain_id: u32, mblock_only: bool, ) -> Vec> { - let addr = to_addr(&privk); + let addr = to_addr(privk); let mut chain = vec![]; for nonce in 0..25 { @@ -11689,8 +11470,8 @@ pub fn make_random_tx_chain( let mut addr_prefix = addr.to_string(); let _ = addr_prefix.split_off(12); - let contract_name = format!("large-{}-{}-{}", nonce, &addr_prefix, random_iters); - eprintln!("Make tx {}", &contract_name); + let contract_name = format!("large-{nonce}-{addr_prefix}-{random_iters}"); + eprintln!("Make tx {contract_name}"); let tx = if mblock_only { make_contract_publish_microblock_only( privk, @@ -11716,7 +11497,7 @@ pub fn make_random_tx_chain( } fn make_mblock_tx_chain(privk: &StacksPrivateKey, fee_plus: u64, chain_id: u32) -> Vec> { - let addr = to_addr(&privk); + let addr = to_addr(privk); let mut chain = vec![]; for nonce in 0..25 { @@ -11732,7 +11513,7 @@ fn make_mblock_tx_chain(privk: &StacksPrivateKey, fee_plus: u64, chain_id: u32) let mut addr_prefix = addr.to_string(); let _ = addr_prefix.split_off(12); - let contract_name = format!("crct-{}-{}-{}", nonce, &addr_prefix, random_iters); + let contract_name = format!("crct-{nonce}-{addr_prefix}-{random_iters}"); eprintln!("Make tx {}", &contract_name); let tx = make_contract_publish_microblock_only( privk, @@ -11758,10 +11539,7 @@ fn test_competing_miners_build_on_same_chain( return; } - let privks: Vec<_> = (0..100) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..100).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() .map(|privk| { @@ -11808,9 +11586,8 @@ fn test_competing_miners_build_on_same_chain( confs[i].node.set_bootstrap_nodes( format!( - "{}@{}", + "{}@{p2p_bind}", &StacksPublicKey::from_private(&node_privkey_1).to_hex(), - p2p_bind ), chain_id, peer_version, @@ -11818,8 +11595,8 @@ fn test_competing_miners_build_on_same_chain( } // use long reward cycles - for i in 0..num_miners { - let mut burnchain_config = Burnchain::regtest(&confs[i].get_burn_db_path()); + for conf in &confs { + let mut burnchain_config = Burnchain::regtest(&conf.get_burn_db_path()); let reward_cycle_len = 100; let prepare_phase_len = 20; let pox_constants = PoxConstants::new( @@ -11856,10 +11633,10 @@ fn test_competing_miners_build_on_same_chain( btc_regtest_controller.bootstrap_chain(1); // make sure all miners have BTC - for i in 1..num_miners { + for conf in confs.iter().skip(1) { let old_mining_pubkey = btc_regtest_controller.get_mining_pubkey().unwrap(); btc_regtest_controller - .set_mining_pubkey(confs[i].burnchain.local_mining_public_key.clone().unwrap()); + .set_mining_pubkey(conf.burnchain.local_mining_public_key.clone().unwrap()); btc_regtest_controller.bootstrap_chain(1); btc_regtest_controller.set_mining_pubkey(old_mining_pubkey); } @@ -11879,8 +11656,8 @@ fn test_competing_miners_build_on_same_chain( let http_origin = format!("http://{}", &confs[0].node.rpc_bind); // give the run loops some time to start up! - for i in 0..num_miners { - wait_for_runloop(&blocks_processed[i as usize]); + for bp in &blocks_processed { + wait_for_runloop(bp); } // activate miners @@ -11888,7 +11665,7 @@ fn test_competing_miners_build_on_same_chain( loop { let tip_info_opt = get_chain_info_opt(&confs[0]); if let Some(tip_info) = tip_info_opt { - eprintln!("\n\nMiner 1: {:?}\n\n", &tip_info); + eprintln!("\n\nMiner 1: {tip_info:?}\n\n"); if tip_info.stacks_tip_height > 0 { break; } @@ -11898,23 +11675,19 @@ fn test_competing_miners_build_on_same_chain( next_block_and_wait(&mut btc_regtest_controller, &blocks_processed[0]); } - for i in 1..num_miners { - eprintln!("\n\nBoot miner {}\n\n", i); + for (i, conf) in confs.iter().enumerate().skip(1) { + eprintln!("\n\nBoot miner {i}\n\n"); loop { - let tip_info_opt = get_chain_info_opt(&confs[i]); + let tip_info_opt = get_chain_info_opt(conf); if let Some(tip_info) = tip_info_opt { - eprintln!("\n\nMiner 2: {:?}\n\n", &tip_info); + eprintln!("\n\nMiner {i}: {tip_info:?}\n\n"); if tip_info.stacks_tip_height > 0 { break; } } else { - eprintln!("\n\nWaiting for miner {}...\n\n", i); + eprintln!("\n\nWaiting for miner {i}...\n\n"); } - next_block_and_iterate( - &mut btc_regtest_controller, - &blocks_processed[i as usize], - 5_000, - ); + next_block_and_iterate(&mut btc_regtest_controller, &blocks_processed[i], 5_000); } } @@ -11938,7 +11711,7 @@ fn test_competing_miners_build_on_same_chain( let mut cnt = 0; for tx_chain in all_txs { for tx in tx_chain { - eprintln!("\n\nSubmit tx {}\n\n", &cnt); + eprintln!("\n\nSubmit tx {cnt}\n\n"); submit_tx(&http_origin, &tx); cnt += 1; } @@ -11948,7 +11721,7 @@ fn test_competing_miners_build_on_same_chain( // mine quickly -- see if we can induce flash blocks for i in 0..1000 { - eprintln!("\n\nBuild block {}\n\n", i); + eprintln!("\n\nBuild block {i}\n\n"); btc_regtest_controller.build_next_block(1); sleep_ms(block_time_ms); } @@ -12023,10 +11796,7 @@ fn microblock_miner_multiple_attempts() { conf.burnchain.max_rbf = 1000000; conf.node.wait_time_for_blocks = 1_000; - let privks: Vec<_> = (0..100) - .into_iter() - .map(|_| StacksPrivateKey::new()) - .collect(); + let privks: Vec<_> = (0..100).map(|_| StacksPrivateKey::new()).collect(); let balances: Vec<_> = privks .iter() .map(|privk| { @@ -12076,7 +11846,7 @@ fn microblock_miner_multiple_attempts() { // let's query the miner's account nonce: let account = get_account(&http_origin, &miner_account); - eprintln!("Miner account: {:?}", &account); + eprintln!("Miner account: {account:?}"); let all_txs: Vec<_> = privks .iter() @@ -12085,10 +11855,9 @@ fn microblock_miner_multiple_attempts() { .collect(); let _handle = thread::spawn(move || { - for txi in 0..all_txs.len() { - for j in 0..all_txs[txi].len() { - let tx = &all_txs[txi][j]; - eprintln!("\n\nSubmit tx {},{}\n\n", txi, j); + for (i, txi) in all_txs.iter().enumerate() { + for (j, tx) in txi.iter().enumerate() { + eprintln!("\n\nSubmit tx {i},{j}\n\n"); submit_tx(&http_origin, tx); sleep_ms(1_000); } @@ -12119,12 +11888,13 @@ fn min_txs() { test_observer::spawn(); test_observer::register_any(&mut conf); + let path = "/tmp/activate_vrf_key.min_txs.json"; conf.miner.min_tx_count = 4; conf.miner.first_attempt_time_ms = 0; - conf.miner.activated_vrf_key_path = Some("/tmp/activate_vrf_key.min_txs.json".to_string()); + conf.miner.activated_vrf_key_path = Some(path.to_string()); - if fs::metadata("/tmp/activate_vrf_key.min_txs.json").is_ok() { - fs::remove_file("/tmp/activate_vrf_key.min_txs.json").unwrap(); + if fs::metadata(path).is_ok() { + fs::remove_file(path).unwrap(); } let spender_bal = 10_000_000_000 * (core::MICROSTACKS_PER_STACKS as u64); @@ -12176,18 +11946,18 @@ fn min_txs() { let _sort_height = channel.get_sortitions_processed(); for i in 0..2 { - let code = format!("(print \"hello world {}\")", i); + let code = format!("(print \"hello world {i}\")"); let publish = make_contract_publish( &spender_sk, i as u64, 1000, conf.burnchain.chain_id, - &format!("test-publish-{}", &i), + &format!("test-publish-{i}"), &code, ); submit_tx(&http_origin, &publish); - debug!("Try to build too-small a block {}", &i); + debug!("Try to build too-small a block {i}"); next_block_and_wait_with_timeout(&mut btc_regtest_controller, &blocks_processed, 15); } @@ -12195,12 +11965,12 @@ fn min_txs() { for block in blocks { let transactions = block.get("transactions").unwrap().as_array().unwrap(); if transactions.len() > 1 { - debug!("Got block: {:?}", &block); + debug!("Got block: {block:?}"); assert!(transactions.len() >= 4); } } - let saved_vrf_key = RelayerThread::load_saved_vrf_key("/tmp/activate_vrf_key.min_txs.json"); + let saved_vrf_key = RelayerThread::load_saved_vrf_key(path); assert!(saved_vrf_key.is_some()); test_observer::clear(); @@ -12222,13 +11992,14 @@ fn filter_txs_by_type() { test_observer::spawn(); test_observer::register_any(&mut conf); + let path = "/tmp/activate_vrf_key.filter_txs.json"; conf.miner.min_tx_count = 4; conf.miner.first_attempt_time_ms = 0; - conf.miner.activated_vrf_key_path = Some("/tmp/activate_vrf_key.filter_txs.json".to_string()); + conf.miner.activated_vrf_key_path = Some(path.to_string()); conf.miner.txs_to_consider = [MemPoolWalkTxTypes::TokenTransfer].into_iter().collect(); - if fs::metadata("/tmp/activate_vrf_key.filter_txs.json").is_ok() { - fs::remove_file("/tmp/activate_vrf_key.filter_txs.json").unwrap(); + if fs::metadata(path).is_ok() { + fs::remove_file(path).unwrap(); } let spender_bal = 10_000_000_000 * (core::MICROSTACKS_PER_STACKS as u64); @@ -12280,13 +12051,13 @@ fn filter_txs_by_type() { let _sort_height = channel.get_sortitions_processed(); let mut sent_txids = HashSet::new(); for i in 0..2 { - let code = format!("(print \"hello world {}\")", i); + let code = format!("(print \"hello world {i}\")"); let publish = make_contract_publish( &spender_sk, i as u64, 1000, conf.burnchain.chain_id, - &format!("test-publish-{}", &i), + &format!("test-publish-{i}"), &code, ); let parsed = StacksTransaction::consensus_deserialize(&mut &publish[..]).unwrap(); @@ -12298,7 +12069,7 @@ fn filter_txs_by_type() { let blocks = test_observer::get_blocks(); for block in blocks { - info!("block: {:?}", &block); + info!("block: {block:?}"); let transactions = block.get("transactions").unwrap().as_array().unwrap(); for tx in transactions { let raw_tx = tx.get("raw_tx").unwrap().as_str().unwrap(); @@ -12313,7 +12084,7 @@ fn filter_txs_by_type() { } } - let saved_vrf_key = RelayerThread::load_saved_vrf_key("/tmp/activate_vrf_key.filter_txs.json"); + let saved_vrf_key = RelayerThread::load_saved_vrf_key(path); assert!(saved_vrf_key.is_some()); test_observer::clear(); @@ -12391,13 +12162,13 @@ fn filter_txs_by_origin() { let _sort_height = channel.get_sortitions_processed(); let mut sent_txids = HashSet::new(); for i in 0..2 { - let code = format!("(print \"hello world {}\")", i); + let code = format!("(print \"hello world {i}\")"); let publish = make_contract_publish( &spender_sk, i as u64, 1000, conf.burnchain.chain_id, - &format!("test-publish-{}", &i), + &format!("test-publish-{i}"), &code, ); let parsed = StacksTransaction::consensus_deserialize(&mut &publish[..]).unwrap(); @@ -12409,7 +12180,7 @@ fn filter_txs_by_origin() { let blocks = test_observer::get_blocks(); for block in blocks { - info!("block: {:?}", &block); + info!("block: {block:?}"); let transactions = block.get("transactions").unwrap().as_array().unwrap(); for tx in transactions { let raw_tx = tx.get("raw_tx").unwrap().as_str().unwrap(); @@ -12479,12 +12250,12 @@ fn bitcoin_reorg_flap() { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); let mut sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); while sort_height < 210 { next_block_and_wait(&mut btc_regtest_controller, &blocks_processed); sort_height = channel.get_sortitions_processed(); - eprintln!("Sort height: {}", sort_height); + eprintln!("Sort height: {sort_height}"); } // stop bitcoind and copy its DB to simulate a chain flap @@ -12496,7 +12267,7 @@ fn bitcoin_reorg_flap() { new_conf.node.working_dir = format!("{}.new", &conf.node.working_dir); fs::create_dir_all(&new_conf.node.working_dir).unwrap(); - copy_dir_all(&btcd_dir, &new_conf.get_burnchain_path_str()).unwrap(); + copy_dir_all(&btcd_dir, new_conf.get_burnchain_path_str()).unwrap(); // resume let mut btcd_controller = BitcoinCoreController::new(conf.clone()); @@ -12681,8 +12452,7 @@ fn bitcoin_reorg_flap_with_follower() { let mut miner_sort_height = miner_channel.get_sortitions_processed(); let mut follower_sort_height = follower_channel.get_sortitions_processed(); eprintln!( - "Miner sort height: {}, follower sort height: {}", - miner_sort_height, follower_sort_height + "Miner sort height: {miner_sort_height}, follower sort height: {follower_sort_height}" ); while miner_sort_height < 210 && follower_sort_height < 210 { @@ -12695,8 +12465,7 @@ fn bitcoin_reorg_flap_with_follower() { miner_sort_height = miner_channel.get_sortitions_processed(); follower_sort_height = miner_channel.get_sortitions_processed(); eprintln!( - "Miner sort height: {}, follower sort height: {}", - miner_sort_height, follower_sort_height + "Miner sort height: {miner_sort_height}, follower sort height: {follower_sort_height}" ); } @@ -12709,7 +12478,7 @@ fn bitcoin_reorg_flap_with_follower() { new_conf.node.working_dir = format!("{}.new", &conf.node.working_dir); fs::create_dir_all(&new_conf.node.working_dir).unwrap(); - copy_dir_all(&btcd_dir, &new_conf.get_burnchain_path_str()).unwrap(); + copy_dir_all(&btcd_dir, new_conf.get_burnchain_path_str()).unwrap(); // resume let mut btcd_controller = BitcoinCoreController::new(conf.clone()); diff --git a/testnet/stacks-node/src/tests/signer/mod.rs b/testnet/stacks-node/src/tests/signer/mod.rs index 42b894398d..622e31bdd6 100644 --- a/testnet/stacks-node/src/tests/signer/mod.rs +++ b/testnet/stacks-node/src/tests/signer/mod.rs @@ -123,10 +123,7 @@ impl + Send + 'static, T: SignerEventTrait + 'static> SignerTest (), - G: FnMut(&mut NeonConfig) -> (), - >( + fn new_with_config_modifications( num_signers: usize, initial_balances: Vec<(StacksAddress, u64)>, mut signer_config_modifier: F, @@ -151,8 +148,7 @@ impl + Send + 'static, T: SignerEventTrait + 'static> SignerTest + Send + 'static, T: SignerEventTrait + 'static> SignerTest>()); @@ -330,10 +326,7 @@ impl + Send + 'static, T: SignerEventTrait + 'static> SignerTest + Send + 'static, T: SignerEventTrait + 'static> SignerTest + Send + 'static, T: SignerEventTrait + 'static> SignerTest + Send + 'static, T: SignerEventTrait + 'static> SignerTest + Send + 'static, T: SignerEventTrait + 'static> SignerTest ()>( +fn setup_stx_btc_node( mut naka_conf: NeonConfig, signer_stacks_private_keys: &[StacksPrivateKey], signer_configs: &[SignerConfig], diff --git a/testnet/stacks-node/src/tests/signer/v0.rs b/testnet/stacks-node/src/tests/signer/v0.rs index 234b73684a..a704d2f2ee 100644 --- a/testnet/stacks-node/src/tests/signer/v0.rs +++ b/testnet/stacks-node/src/tests/signer/v0.rs @@ -118,13 +118,13 @@ impl SignerTest { for stacker_sk in self.signer_stacks_private_keys.iter() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( &pox_addr, - &stacker_sk, + stacker_sk, reward_cycle.into(), &Pox4SignatureTopic::StackStx, CHAIN_ID_TESTNET, @@ -137,7 +137,7 @@ impl SignerTest { let signer_pk = StacksPublicKey::from_private(stacker_sk); let stacking_tx = tests::make_contract_call( - &stacker_sk, + stacker_sk, 0, 1000, self.running_nodes.conf.burnchain.chain_id, @@ -246,7 +246,7 @@ impl SignerTest { .get_reward_set_signers(reward_cycle) .expect("Failed to check if reward set is calculated") .map(|reward_set| { - debug!("Signer set: {:?}", reward_set); + debug!("Signer set: {reward_set:?}"); }) .is_some()) }) @@ -304,10 +304,7 @@ impl SignerTest { // NOTE: signature.len() does not need to equal signers.len(); the stacks miner can finish the block // whenever it has crossed the threshold. assert!(signature.len() >= num_signers * 7 / 10); - info!( - "Verifying signatures against signers for reward cycle {:?}", - reward_cycle - ); + info!("Verifying signatures against signers for reward cycle {reward_cycle:?}"); let signers = self.get_reward_set_signers(reward_cycle); // Verify that the signers signed the proposed block @@ -789,7 +786,7 @@ fn reloads_signer_set_in() { let send_fee = 180; let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |_config| {}, |_| {}, None, @@ -848,7 +845,7 @@ fn reloads_signer_set_in() { } }; if let Some(ref set) = reward_set { - info!("Signer set: {:?}", set); + info!("Signer set: {set:?}"); } Ok(reward_set.is_some()) }) @@ -912,7 +909,7 @@ fn forked_tenure_testing( let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |config| { // make the duration long enough that the reorg attempt will definitely be accepted config.first_proposal_burn_block_timing = proposal_limit; @@ -1030,7 +1027,7 @@ fn forked_tenure_testing( .nakamoto_blocks_db() .get_nakamoto_tenure_start_blocks(&tip_sn.consensus_hash) .unwrap() - .get(0) + .first() .cloned() .unwrap(); @@ -1038,14 +1035,14 @@ fn forked_tenure_testing( let tip_b = StacksHeaderInfo { anchored_header: StacksBlockHeaderTypes::Nakamoto(tip_b_block.header.clone()), microblock_tail: None, - stacks_block_height: tip_b_block.header.chain_length.into(), + stacks_block_height: tip_b_block.header.chain_length, index_root: TrieHash([0x00; 32]), // we can't know this yet since the block hasn't been processed - consensus_hash: tip_b_block.header.consensus_hash.clone(), - burn_header_hash: tip_sn.burn_header_hash.clone(), + consensus_hash: tip_b_block.header.consensus_hash, + burn_header_hash: tip_sn.burn_header_hash, burn_header_height: tip_sn.block_height as u32, burn_header_timestamp: tip_sn.burn_header_timestamp, anchored_block_size: tip_b_block.serialize_to_vec().len() as u64, - burn_view: Some(tip_b_block.header.consensus_hash.clone()), + burn_view: Some(tip_b_block.header.consensus_hash), }; let blocks = test_observer::get_mined_nakamoto_blocks(); @@ -1227,10 +1224,8 @@ fn bitcoind_forking_test() { let sender_addr = tests::to_addr(&sender_sk); let send_amt = 100; let send_fee = 180; - let mut signer_test: SignerTest = SignerTest::new( - num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], - ); + let mut signer_test: SignerTest = + SignerTest::new(num_signers, vec![(sender_addr, send_amt + send_fee)]); let conf = signer_test.running_nodes.conf.clone(); let http_origin = format!("http://{}", &conf.node.rpc_bind); let miner_address = Keychain::default(conf.node.seed.clone()) @@ -1339,7 +1334,7 @@ fn bitcoind_forking_test() { let post_fork_1_nonce = get_account(&http_origin, &miner_address).nonce; - assert_eq!(post_fork_1_nonce, pre_fork_1_nonce - 1 * 2); + assert_eq!(post_fork_1_nonce, pre_fork_1_nonce - 2); for i in 0..5 { info!("Mining post-fork tenure {} of 5", i + 1); @@ -1466,7 +1461,7 @@ fn multiple_miners() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |signer_config| { let node_host = if signer_config.endpoint.port() % 2 == 0 { &node_1_rpc_bind @@ -1504,7 +1499,7 @@ fn multiple_miners() { false }) }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let conf = signer_test.running_nodes.conf.clone(); @@ -1583,10 +1578,7 @@ fn multiple_miners() { let info_1 = get_chain_info(&conf); let info_2 = get_chain_info(&conf_node_2); - info!( - "Issue next block-build request\ninfo 1: {:?}\ninfo 2: {:?}\n", - &info_1, &info_2 - ); + info!("Issue next block-build request\ninfo 1: {info_1:?}\ninfo 2: {info_2:?}\n"); signer_test.mine_block_wait_on_processing( &[&rl1_coord_channels, &rl2_coord_channels], @@ -1597,10 +1589,8 @@ fn multiple_miners() { btc_blocks_mined += 1; let blocks = get_nakamoto_headers(&conf); // for this test, there should be one block per tenure - let consensus_hash_set: HashSet<_> = blocks - .iter() - .map(|header| header.consensus_hash.clone()) - .collect(); + let consensus_hash_set: HashSet<_> = + blocks.iter().map(|header| header.consensus_hash).collect(); assert_eq!( consensus_hash_set.len(), blocks.len(), @@ -1667,14 +1657,7 @@ fn get_nakamoto_headers(config: &Config) -> Vec { let nakamoto_block_ids: HashSet<_> = test_observer::get_blocks() .into_iter() .filter_map(|block_json| { - if block_json - .as_object() - .unwrap() - .get("miner_signature") - .is_none() - { - return None; - } + block_json.as_object().unwrap().get("miner_signature")?; let block_id = StacksBlockId::from_hex( &block_json .as_object() @@ -1753,7 +1736,7 @@ fn miner_forking() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |signer_config| { let node_host = if signer_config.endpoint.port() % 2 == 0 { &node_1_rpc_bind @@ -1795,7 +1778,7 @@ fn miner_forking() { false }) }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let conf = signer_test.running_nodes.conf.clone(); @@ -1816,7 +1799,7 @@ fn miner_forking() { let node_1_sk = Secp256k1PrivateKey::from_seed(&conf.node.local_peer_seed); let node_1_pk = StacksPublicKey::from_private(&node_1_sk); - conf_node_2.node.working_dir = format!("{}-{}", conf_node_2.node.working_dir, "1"); + conf_node_2.node.working_dir = format!("{}-1", conf_node_2.node.working_dir); conf_node_2.node.set_bootstrap_nodes( format!("{}@{}", &node_1_pk.to_hex(), conf.node.p2p_bind), @@ -1904,7 +1887,7 @@ fn miner_forking() { TEST_BROADCAST_STALL.lock().unwrap().replace(false); // wait for a block to be processed (or timeout!) - if let Err(_) = wait_for(60, || Ok(test_observer::get_blocks().len() > blocks_len)) { + if wait_for(60, || Ok(test_observer::get_blocks().len() > blocks_len)).is_err() { info!("Timeout waiting for a block process: assuming this is because RL2 attempted to fork-- will check at end of test"); return (sort_tip, false); } @@ -1946,7 +1929,7 @@ fn miner_forking() { .into_iter() .map(|header| { info!("Nakamoto block"; "height" => header.stacks_block_height, "consensus_hash" => %header.consensus_hash, "last_sortition_hash" => %sortition_data.consensus_hash); - (header.consensus_hash.clone(), header) + (header.consensus_hash, header) }) .collect(); @@ -1985,9 +1968,7 @@ fn miner_forking() { expects_miner_2_to_be_valid = false; } else { info!("Sortition without tenure"; "expects_miner_2_to_be_valid?" => expects_miner_2_to_be_valid); - assert!(nakamoto_headers - .get(&sortition_data.consensus_hash) - .is_none()); + assert!(!nakamoto_headers.contains_key(&sortition_data.consensus_hash)); assert!(!expects_miner_2_to_be_valid, "If no blocks were produced in the tenure, it should be because miner 2 committed to a fork"); won_by_miner_2_but_no_tenure = true; expects_miner_2_to_be_valid = true; @@ -2034,10 +2015,8 @@ fn end_of_tenure() { let send_amt = 100; let send_fee = 180; let recipient = PrincipalData::from(StacksAddress::burn_address(false)); - let mut signer_test: SignerTest = SignerTest::new( - num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], - ); + let mut signer_test: SignerTest = + SignerTest::new(num_signers, vec![(sender_addr, send_amt + send_fee)]); let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind); let long_timeout = Duration::from_secs(200); let short_timeout = Duration::from_secs(20); @@ -2185,10 +2164,8 @@ fn retry_on_rejection() { let send_fee = 180; let short_timeout = Duration::from_secs(30); let recipient = PrincipalData::from(StacksAddress::burn_address(false)); - let mut signer_test: SignerTest = SignerTest::new( - num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * 3)], - ); + let mut signer_test: SignerTest = + SignerTest::new(num_signers, vec![(sender_addr, (send_amt + send_fee) * 3)]); let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind); signer_test.boot_to_epoch_3(); @@ -2198,7 +2175,7 @@ fn retry_on_rejection() { let sortdb = burnchain.open_sortition_db(true).unwrap(); wait_for(30, || { - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); Ok(tip.sortition) }) .expect("Timed out waiting for sortition"); @@ -2324,10 +2301,8 @@ fn signers_broadcast_signed_blocks() { let send_amt = 100; let send_fee = 180; let recipient = PrincipalData::from(StacksAddress::burn_address(false)); - let mut signer_test: SignerTest = SignerTest::new( - num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], - ); + let mut signer_test: SignerTest = + SignerTest::new(num_signers, vec![(sender_addr, send_amt + send_fee)]); let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind); signer_test.boot_to_epoch_3(); @@ -2345,8 +2320,8 @@ fn signers_broadcast_signed_blocks() { .load(Ordering::SeqCst); let info = get_chain_info(&signer_test.running_nodes.conf); debug!( - "blocks_mined: {},{}, stacks_tip_height: {},{}", - blocks_mined, blocks_before, info.stacks_tip_height, info_before.stacks_tip_height + "blocks_mined: {blocks_mined},{blocks_before}, stacks_tip_height: {},{}", + info.stacks_tip_height, info_before.stacks_tip_height ); Ok(blocks_mined > blocks_before && info.stacks_tip_height > info_before.stacks_tip_height) }) @@ -2388,11 +2363,7 @@ fn signers_broadcast_signed_blocks() { .load(Ordering::SeqCst); let info = get_chain_info(&signer_test.running_nodes.conf); debug!( - "blocks_mined: {},{}, signers_pushed: {},{}, stacks_tip_height: {},{}", - blocks_mined, - blocks_before, - signer_pushed, - signer_pushed_before, + "blocks_mined: {blocks_mined},{blocks_before}, signers_pushed: {signer_pushed},{signer_pushed_before}, stacks_tip_height: {},{}", info.stacks_tip_height, info_before.stacks_tip_height ); @@ -2432,7 +2403,7 @@ fn empty_sortition() { let block_proposal_timeout = Duration::from_secs(20); let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |config| { // make the duration long enough that the miner will be marked as malicious config.block_proposal_timeout = block_proposal_timeout; @@ -2613,7 +2584,7 @@ fn mock_sign_epoch_25() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |_| {}, |node_config| { node_config.miner.pre_nakamoto_mock_signing = true; @@ -2763,7 +2734,7 @@ fn multiple_miners_mock_sign_epoch_25() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), send_amt + send_fee)], + vec![(sender_addr, send_amt + send_fee)], |signer_config| { let node_host = if signer_config.endpoint.port() % 2 == 0 { &node_1_rpc_bind @@ -2807,16 +2778,16 @@ fn multiple_miners_mock_sign_epoch_25() { false }) }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let conf = signer_test.running_nodes.conf.clone(); let mut conf_node_2 = conf.clone(); let localhost = "127.0.0.1"; - conf_node_2.node.rpc_bind = format!("{}:{}", localhost, node_2_rpc); - conf_node_2.node.p2p_bind = format!("{}:{}", localhost, node_2_p2p); - conf_node_2.node.data_url = format!("http://{}:{}", localhost, node_2_rpc); - conf_node_2.node.p2p_address = format!("{}:{}", localhost, node_2_p2p); + conf_node_2.node.rpc_bind = format!("{localhost}:{node_2_rpc}"); + conf_node_2.node.p2p_bind = format!("{localhost}:{node_2_p2p}"); + conf_node_2.node.data_url = format!("http://{localhost}:{node_2_rpc}"); + conf_node_2.node.p2p_address = format!("{localhost}:{node_2_p2p}"); conf_node_2.node.seed = btc_miner_2_seed.clone(); conf_node_2.burnchain.local_mining_public_key = Some(btc_miner_2_pk.to_hex()); conf_node_2.node.local_peer_seed = btc_miner_2_seed.clone(); @@ -2829,7 +2800,7 @@ fn multiple_miners_mock_sign_epoch_25() { let node_1_sk = Secp256k1PrivateKey::from_seed(&conf.node.local_peer_seed); let node_1_pk = StacksPublicKey::from_private(&node_1_sk); - conf_node_2.node.working_dir = format!("{}-{}", conf_node_2.node.working_dir, "1"); + conf_node_2.node.working_dir = format!("{}-1", conf_node_2.node.working_dir); conf_node_2.node.set_bootstrap_nodes( format!("{}@{}", &node_1_pk.to_hex(), conf.node.p2p_bind), @@ -2953,17 +2924,13 @@ fn signer_set_rollover() { let new_num_signers = 4; let new_signer_private_keys: Vec<_> = (0..new_num_signers) - .into_iter() .map(|_| StacksPrivateKey::new()) .collect(); let new_signer_public_keys: Vec<_> = new_signer_private_keys .iter() .map(|sk| Secp256k1PublicKey::from_private(sk).to_bytes_compressed()) .collect(); - let new_signer_addresses: Vec<_> = new_signer_private_keys - .iter() - .map(|sk| tests::to_addr(sk)) - .collect(); + let new_signer_addresses: Vec<_> = new_signer_private_keys.iter().map(tests::to_addr).collect(); let sender_sk = Secp256k1PrivateKey::new(); let sender_addr = tests::to_addr(&sender_sk); let send_amt = 100; @@ -2972,15 +2939,15 @@ fn signer_set_rollover() { let mut initial_balances = new_signer_addresses .iter() - .map(|addr| (addr.clone(), POX_4_DEFAULT_STACKER_BALANCE)) + .map(|addr| (*addr, POX_4_DEFAULT_STACKER_BALANCE)) .collect::>(); - initial_balances.push((sender_addr.clone(), (send_amt + send_fee) * 4)); + initial_balances.push((sender_addr, (send_amt + send_fee) * 4)); let run_stamp = rand::random(); let rpc_port = 51024; - let rpc_bind = format!("127.0.0.1:{}", rpc_port); + let rpc_bind = format!("127.0.0.1:{rpc_port}"); // Setup the new signers that will take over let new_signer_configs = build_signer_config_tomls( @@ -2997,12 +2964,11 @@ fn signer_set_rollover() { None, ); - let new_spawned_signers: Vec<_> = (0..new_num_signers) - .into_iter() - .map(|i| { + let new_spawned_signers: Vec<_> = new_signer_configs + .iter() + .map(|conf| { info!("spawning signer"); - let signer_config = - SignerConfig::load_from_str(&new_signer_configs[i as usize]).unwrap(); + let signer_config = SignerConfig::load_from_str(conf).unwrap(); SpawnedSigner::new(signer_config) }) .collect(); @@ -3047,7 +3013,7 @@ fn signer_set_rollover() { // Verify that naka_conf has our new signer's event observers for toml in &new_signer_configs { - let signer_config = SignerConfig::load_from_str(&toml).unwrap(); + let signer_config = SignerConfig::load_from_str(toml).unwrap(); let endpoint = format!("{}", signer_config.endpoint); assert!(signer_test .running_nodes @@ -3072,7 +3038,7 @@ fn signer_set_rollover() { info!("---- Verifying that the current signers are the old signers ----"); let current_signers = signer_test.get_reward_set_signers(reward_cycle); - assert_eq!(current_signers.len(), num_signers as usize); + assert_eq!(current_signers.len(), num_signers); // Verify that the current signers are the same as the old signers for signer in current_signers.iter() { assert!(signer_test_public_keys.contains(&signer.signing_key.to_vec())); @@ -3117,13 +3083,13 @@ fn signer_set_rollover() { for stacker_sk in new_signer_private_keys.iter() { let pox_addr = PoxAddress::from_legacy( AddressHashMode::SerializeP2PKH, - tests::to_addr(&stacker_sk).bytes, + tests::to_addr(stacker_sk).bytes, ); let pox_addr_tuple: clarity::vm::Value = pox_addr.clone().as_clarity_tuple().unwrap().into(); let signature = make_pox_4_signer_key_signature( &pox_addr, - &stacker_sk, + stacker_sk, reward_cycle.into(), &Pox4SignatureTopic::StackStx, CHAIN_ID_TESTNET, @@ -3136,7 +3102,7 @@ fn signer_set_rollover() { let signer_pk = Secp256k1PublicKey::from_private(stacker_sk); let stacking_tx = tests::make_contract_call( - &stacker_sk, + stacker_sk, 0, 1000, signer_test.running_nodes.conf.burnchain.chain_id, @@ -3190,10 +3156,7 @@ fn signer_set_rollover() { assert!(new_signer_public_keys.contains(&signer.signing_key.to_vec())); } - info!( - "---- Mining to the next reward cycle (block {}) -----", - next_cycle_height - ); + info!("---- Mining to the next reward cycle (block {next_cycle_height}) -----",); signer_test.run_until_burnchain_height_nakamoto( Duration::from_secs(60), next_cycle_height, @@ -3204,7 +3167,7 @@ fn signer_set_rollover() { info!("---- Verifying that the current signers are the new signers ----"); let current_signers = signer_test.get_reward_set_signers(new_reward_cycle); - assert_eq!(current_signers.len(), new_num_signers as usize); + assert_eq!(current_signers.len(), new_num_signers); for signer in current_signers.iter() { assert!(!signer_test_public_keys.contains(&signer.signing_key.to_vec())); assert!(new_signer_public_keys.contains(&signer.signing_key.to_vec())); @@ -3262,13 +3225,12 @@ fn min_gap_between_blocks() { let send_amt = 100; let send_fee = 180; - let mut sender_nonce = 0; let interim_blocks = 5; let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let time_between_blocks_ms = 10_000; let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * interim_blocks)], + vec![(sender_addr, (send_amt + send_fee) * interim_blocks)], |_config| {}, |config| { config.miner.min_time_between_blocks_ms = time_between_blocks_ms; @@ -3294,13 +3256,12 @@ fn min_gap_between_blocks() { // submit a tx so that the miner will mine an extra block let transfer_tx = make_stacks_transfer( &sender_sk, - sender_nonce, + interim_block_ix, // same as the sender nonce send_fee, signer_test.running_nodes.conf.burnchain.chain_id, &recipient, send_amt, ); - sender_nonce += 1; submit_tx(&http_origin, &transfer_tx); info!("Submitted transfer tx and waiting for block to be processed"); @@ -3312,7 +3273,7 @@ fn min_gap_between_blocks() { Ok(blocks_processed > blocks_processed_before) }) .unwrap(); - info!("Mined interim block:{}", interim_block_ix); + info!("Mined interim block:{interim_block_ix}"); } wait_for(60, || { @@ -3426,7 +3387,7 @@ fn duplicate_signers() { }) .filter_map(|message| match message { SignerMessage::BlockResponse(BlockResponse::Accepted(m)) => { - info!("Message(accepted): {:?}", &m); + info!("Message(accepted): {m:?}"); Some(m) } _ => { @@ -3503,7 +3464,7 @@ fn multiple_miners_with_nakamoto_blocks() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, vec![( - sender_addr.clone(), + sender_addr, (send_amt + send_fee) * max_nakamoto_tenures * inter_blocks_per_tenure, )], |signer_config| { @@ -3542,7 +3503,7 @@ fn multiple_miners_with_nakamoto_blocks() { false }) }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let blocks_mined1 = signer_test.running_nodes.nakamoto_blocks_mined.clone(); @@ -3667,10 +3628,7 @@ fn multiple_miners_with_nakamoto_blocks() { Ok(blocks_processed > blocks_processed_before) }) .unwrap(); - info!( - "Mined interim block {}:{}", - btc_blocks_mined, interim_block_ix - ); + info!("Mined interim block {btc_blocks_mined}:{interim_block_ix}"); } let blocks = get_nakamoto_headers(&conf); @@ -3681,7 +3639,7 @@ fn multiple_miners_with_nakamoto_blocks() { if seen_burn_hashes.contains(&header.burn_header_hash) { continue; } - seen_burn_hashes.insert(header.burn_header_hash.clone()); + seen_burn_hashes.insert(header.burn_header_hash); let header = header.anchored_header.as_stacks_nakamoto().unwrap(); if miner_1_pk @@ -3703,10 +3661,7 @@ fn multiple_miners_with_nakamoto_blocks() { miner_2_tenures += 1; } } - info!( - "Miner 1 tenures: {}, Miner 2 tenures: {}", - miner_1_tenures, miner_2_tenures - ); + info!("Miner 1 tenures: {miner_1_tenures}, Miner 2 tenures: {miner_2_tenures}"); } info!( @@ -3724,10 +3679,7 @@ fn multiple_miners_with_nakamoto_blocks() { peer_1_height, pre_nakamoto_peer_1_height + (btc_blocks_mined - 1) * (inter_blocks_per_tenure + 1) ); - assert_eq!( - btc_blocks_mined, - u64::try_from(miner_1_tenures + miner_2_tenures).unwrap() - ); + assert_eq!(btc_blocks_mined, miner_1_tenures + miner_2_tenures); rl2_coord_channels .lock() .expect("Mutex poisoned") @@ -3777,7 +3729,7 @@ fn partial_tenure_fork() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, vec![( - sender_addr.clone(), + sender_addr, (send_amt + send_fee) * max_nakamoto_tenures * inter_blocks_per_tenure, )], |signer_config| { @@ -3812,7 +3764,7 @@ fn partial_tenure_fork() { panic!("Expected epochs to be set"); } }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let blocks_mined1 = signer_test.running_nodes.nakamoto_blocks_mined.clone(); @@ -3833,7 +3785,7 @@ fn partial_tenure_fork() { let node_1_sk = Secp256k1PrivateKey::from_seed(&conf.node.local_peer_seed); let node_1_pk = StacksPublicKey::from_private(&node_1_sk); - conf_node_2.node.working_dir = format!("{}-{}", conf_node_2.node.working_dir, "1"); + conf_node_2.node.working_dir = format!("{}-1", conf_node_2.node.working_dir); conf_node_2.node.set_bootstrap_nodes( format!("{}@{}", &node_1_pk.to_hex(), conf.node.p2p_bind), @@ -4057,14 +4009,11 @@ fn partial_tenure_fork() { blocks = interim_block_ix; break; } else { - panic!("Failed to submit tx: {}", e); + panic!("Failed to submit tx: {e}"); } } } - info!( - "Attempted to mine interim block {}:{}", - btc_blocks_mined, interim_block_ix - ); + info!("Attempted to mine interim block {btc_blocks_mined}:{interim_block_ix}"); } if miner == 1 { @@ -4084,13 +4033,11 @@ fn partial_tenure_fork() { if miner == 1 { assert_eq!(mined_1, mined_before_1 + blocks + 1); + } else if miner_2_tenures < min_miner_2_tenures { + assert_eq!(mined_2, mined_before_2 + blocks + 1); } else { - if miner_2_tenures < min_miner_2_tenures { - assert_eq!(mined_2, mined_before_2 + blocks + 1); - } else { - // Miner 2 should have mined 0 blocks after the fork - assert_eq!(mined_2, mined_before_2); - } + // Miner 2 should have mined 0 blocks after the fork + assert_eq!(mined_2, mined_before_2); } } @@ -4110,10 +4057,7 @@ fn partial_tenure_fork() { // Must be at least the number of blocks mined by miner 1 and the number of blocks mined by miner 2 // before the fork was initiated assert!(peer_1_height >= pre_nakamoto_peer_1_height + miner_1_blocks + min_miner_2_blocks); - assert_eq!( - btc_blocks_mined, - u64::try_from(miner_1_tenures + miner_2_tenures).unwrap() - ); + assert_eq!(btc_blocks_mined, miner_1_tenures + miner_2_tenures); let sortdb = SortitionDB::open( &conf_node_2.get_burn_db_file_path(), @@ -4179,7 +4123,7 @@ fn locally_accepted_blocks_overriden_by_global_rejection() { let short_timeout_secs = 20; let mut signer_test: SignerTest = SignerTest::new( num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * nmb_txs)], + vec![(sender_addr, (send_amt + send_fee) * nmb_txs)], ); let all_signers: Vec<_> = signer_test @@ -4366,7 +4310,7 @@ fn locally_rejected_blocks_overriden_by_global_acceptance() { let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let mut signer_test: SignerTest = SignerTest::new( num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * nmb_txs)], + vec![(sender_addr, (send_amt + send_fee) * nmb_txs)], ); let all_signers: Vec<_> = signer_test @@ -4589,7 +4533,7 @@ fn reorg_locally_accepted_blocks_across_tenures_succeeds() { let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let mut signer_test: SignerTest = SignerTest::new( num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * nmb_txs)], + vec![(sender_addr, (send_amt + send_fee) * nmb_txs)], ); let all_signers = signer_test .signer_stacks_private_keys @@ -4803,7 +4747,7 @@ fn miner_recovers_when_broadcast_block_delay_across_tenures_occurs() { let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let mut signer_test: SignerTest = SignerTest::new( num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * nmb_txs)], + vec![(sender_addr, (send_amt + send_fee) * nmb_txs)], ); let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind); signer_test.boot_to_epoch_3(); @@ -4817,7 +4761,7 @@ fn miner_recovers_when_broadcast_block_delay_across_tenures_occurs() { let sortdb = burnchain.open_sortition_db(true).unwrap(); wait_for(30, || { - let tip = SortitionDB::get_canonical_burn_chain_tip(&sortdb.conn()).unwrap(); + let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn()).unwrap(); Ok(tip.sortition) }) .expect("Timed out waiting for sortition"); @@ -5103,10 +5047,8 @@ fn continue_after_tenure_extend() { let recipient = PrincipalData::from(StacksAddress::burn_address(false)); let send_amt = 100; let send_fee = 180; - let mut signer_test: SignerTest = SignerTest::new( - num_signers, - vec![(sender_addr.clone(), (send_amt + send_fee) * 5)], - ); + let mut signer_test: SignerTest = + SignerTest::new(num_signers, vec![(sender_addr, (send_amt + send_fee) * 5)]); let timeout = Duration::from_secs(200); let coord_channel = signer_test.running_nodes.coord_channel.clone(); let http_origin = format!("http://{}", &signer_test.running_nodes.conf.node.rpc_bind); @@ -5178,17 +5120,16 @@ fn continue_after_tenure_extend() { match &parsed.payload { TransactionPayload::TenureChange(payload) if payload.cause == TenureChangeCause::Extended => {} - _ => panic!("Expected tenure extend transaction, got {:?}", parsed), + _ => panic!("Expected tenure extend transaction, got {parsed:?}"), }; // Verify that the miner can continue mining in the tenure with the tenure extend info!("------------------------- Mine After Tenure Extend -------------------------"); - let mut sender_nonce = 0; let mut blocks_processed_before = coord_channel .lock() .expect("Mutex poisoned") .get_stacks_blocks_processed(); - for _ in 0..5 { + for sender_nonce in 0..5 { // submit a tx so that the miner will mine an extra block let transfer_tx = make_stacks_transfer( &sender_sk, @@ -5198,7 +5139,6 @@ fn continue_after_tenure_extend() { &recipient, send_amt, ); - sender_nonce += 1; submit_tx(&http_origin, &transfer_tx); info!("Submitted transfer tx and waiting for block proposal"); @@ -5280,13 +5220,13 @@ fn signing_in_0th_tenure_of_reward_cycle() { assert_eq!(signer_test.get_current_reward_cycle(), curr_reward_cycle); for signer in &signer_public_keys { - let blocks_signed = get_v3_signer(&signer, next_reward_cycle); + let blocks_signed = get_v3_signer(signer, next_reward_cycle); assert_eq!(blocks_signed, 0); } info!("------------------------- Enter Reward Cycle {next_reward_cycle} -------------------------"); for signer in &signer_public_keys { - let blocks_signed = get_v3_signer(&signer, next_reward_cycle); + let blocks_signed = get_v3_signer(signer, next_reward_cycle); assert_eq!(blocks_signed, 0); } let blocks_before = signer_test @@ -5320,7 +5260,7 @@ fn signing_in_0th_tenure_of_reward_cycle() { .unwrap() }) .expect("Unknown signer signature"); - let blocks_signed = get_v3_signer(&signer, next_reward_cycle); + let blocks_signed = get_v3_signer(signer, next_reward_cycle); assert_eq!(blocks_signed, 1); } assert_eq!(signer_test.get_current_reward_cycle(), next_reward_cycle); @@ -5363,7 +5303,7 @@ fn multiple_miners_with_custom_chain_id() { let mut signer_test: SignerTest = SignerTest::new_with_config_modifications( num_signers, vec![( - sender_addr.clone(), + sender_addr, (send_amt + send_fee) * max_nakamoto_tenures * inter_blocks_per_tenure, )], |signer_config| { @@ -5404,7 +5344,7 @@ fn multiple_miners_with_custom_chain_id() { false }) }, - Some(vec![btc_miner_1_pk.clone(), btc_miner_2_pk.clone()]), + Some(vec![btc_miner_1_pk, btc_miner_2_pk]), None, ); let blocks_mined1 = signer_test.running_nodes.nakamoto_blocks_mined.clone(); @@ -5428,7 +5368,7 @@ fn multiple_miners_with_custom_chain_id() { let node_1_sk = Secp256k1PrivateKey::from_seed(&conf.node.local_peer_seed); let node_1_pk = StacksPublicKey::from_private(&node_1_sk); - conf_node_2.node.working_dir = format!("{}-{}", conf_node_2.node.working_dir, "1"); + conf_node_2.node.working_dir = format!("{}-1", conf_node_2.node.working_dir); conf_node_2.node.set_bootstrap_nodes( format!("{}@{}", &node_1_pk.to_hex(), conf.node.p2p_bind), @@ -5530,10 +5470,7 @@ fn multiple_miners_with_custom_chain_id() { Ok(blocks_processed > blocks_processed_before) }) .unwrap(); - info!( - "Mined interim block {}:{}", - btc_blocks_mined, interim_block_ix - ); + info!("Mined interim block {btc_blocks_mined}:{interim_block_ix}"); } let blocks = get_nakamoto_headers(&conf); @@ -5544,7 +5481,7 @@ fn multiple_miners_with_custom_chain_id() { if seen_burn_hashes.contains(&header.burn_header_hash) { continue; } - seen_burn_hashes.insert(header.burn_header_hash.clone()); + seen_burn_hashes.insert(header.burn_header_hash); let header = header.anchored_header.as_stacks_nakamoto().unwrap(); if miner_1_pk @@ -5566,10 +5503,7 @@ fn multiple_miners_with_custom_chain_id() { miner_2_tenures += 1; } } - info!( - "Miner 1 tenures: {}, Miner 2 tenures: {}", - miner_1_tenures, miner_2_tenures - ); + info!("Miner 1 tenures: {miner_1_tenures}, Miner 2 tenures: {miner_2_tenures}"); } info!( @@ -5587,10 +5521,7 @@ fn multiple_miners_with_custom_chain_id() { peer_1_height, pre_nakamoto_peer_1_height + (btc_blocks_mined - 1) * (inter_blocks_per_tenure + 1) ); - assert_eq!( - btc_blocks_mined, - u64::try_from(miner_1_tenures + miner_2_tenures).unwrap() - ); + assert_eq!(btc_blocks_mined, miner_1_tenures + miner_2_tenures); // Verify both nodes have the correct chain id let miner1_info = get_chain_info(&signer_test.running_nodes.conf); diff --git a/testnet/stacks-node/src/tests/stackerdb.rs b/testnet/stacks-node/src/tests/stackerdb.rs index aa620d349b..70d820fbb1 100644 --- a/testnet/stacks-node/src/tests/stackerdb.rs +++ b/testnet/stacks-node/src/tests/stackerdb.rs @@ -41,14 +41,13 @@ fn post_stackerdb_chunk( slot_version: u32, ) -> StackerDBChunkAckData { let mut chunk = StackerDBChunkData::new(slot_id, slot_version, data); - chunk.sign(&signer).unwrap(); + chunk.sign(signer).unwrap(); let chunk_body = serde_json::to_string(&chunk).unwrap(); let client = reqwest::blocking::Client::new(); let path = format!( - "{}/v2/stackerdb/{}/{}/chunks", - http_origin, + "{http_origin}/v2/stackerdb/{}/{}/chunks", &StacksAddress::from(stackerdb_contract_id.issuer.clone()), stackerdb_contract_id.name ); @@ -60,8 +59,8 @@ fn post_stackerdb_chunk( .unwrap(); if res.status().is_success() { let ack: StackerDBChunkAckData = res.json().unwrap(); - info!("Got stackerdb ack: {:?}", &ack); - return ack; + info!("Got stackerdb ack: {ack:?}"); + ack } else { eprintln!("StackerDB post error: {}", res.text().unwrap()); panic!(""); @@ -76,20 +75,15 @@ fn get_stackerdb_chunk( ) -> Vec { let path = if let Some(version) = slot_version { format!( - "{}/v2/stackerdb/{}/{}/{}/{}", - http_origin, + "{http_origin}/v2/stackerdb/{}/{}/{slot_id}/{version}", StacksAddress::from(stackerdb_contract_id.issuer.clone()), stackerdb_contract_id.name, - slot_id, - version ) } else { format!( - "{}/v2/stackerdb/{}/{}/{}", - http_origin, + "{http_origin}/v2/stackerdb/{}/{}/{slot_id}", StacksAddress::from(stackerdb_contract_id.issuer.clone()), - stackerdb_contract_id.name, - slot_id + stackerdb_contract_id.name ) }; @@ -97,8 +91,7 @@ fn get_stackerdb_chunk( let res = client.get(&path).send().unwrap(); if res.status().is_success() { - let chunk_data: Vec = res.bytes().unwrap().to_vec(); - return chunk_data; + res.bytes().unwrap().to_vec() } else { eprintln!("Get chunk error: {}", res.text().unwrap()); panic!(""); @@ -115,7 +108,7 @@ fn test_stackerdb_load_store() { let (mut conf, _) = neon_integration_test_conf(); test_observer::register_any(&mut conf); - let privks = vec![ + let privks = [ // ST2DS4MSWSGJ3W9FBC6BVT0Y92S345HY8N3T6AV7R StacksPrivateKey::from_hex( "9f1f85a512a96a244e4c0d762788500687feb97481639572e3bffbd6860e6ab001", @@ -223,18 +216,18 @@ fn test_stackerdb_load_store() { // write some chunks and read them back for i in 0..3 { - let chunk_str = format!("Hello chunks {}", &i); + let chunk_str = format!("Hello chunks {i}"); let ack = post_stackerdb_chunk( &http_origin, &contract_id, chunk_str.as_bytes().to_vec(), &privks[0], 0, - (i + 1) as u32, + i + 1, ); - debug!("ACK: {:?}", &ack); + debug!("ACK: {ack:?}"); - let data = get_stackerdb_chunk(&http_origin, &contract_id, 0, Some((i + 1) as u32)); + let data = get_stackerdb_chunk(&http_origin, &contract_id, 0, Some(i + 1)); assert_eq!(data, chunk_str.as_bytes().to_vec()); let data = get_stackerdb_chunk(&http_origin, &contract_id, 0, None); @@ -252,7 +245,7 @@ fn test_stackerdb_event_observer() { let (mut conf, _) = neon_integration_test_conf(); test_observer::register(&mut conf, &[EventKeyType::StackerDBChunks]); - let privks = vec![ + let privks = [ // ST2DS4MSWSGJ3W9FBC6BVT0Y92S345HY8N3T6AV7R StacksPrivateKey::from_hex( "9f1f85a512a96a244e4c0d762788500687feb97481639572e3bffbd6860e6ab001", @@ -383,11 +376,10 @@ fn test_stackerdb_event_observer() { // get events, verifying that they're all for the same contract (i.e. this one) let stackerdb_events: Vec<_> = test_observer::get_stackerdb_chunks() .into_iter() - .map(|stackerdb_event| { + .flat_map(|stackerdb_event| { assert_eq!(stackerdb_event.contract_id, contract_id); stackerdb_event.modified_slots }) - .flatten() .collect(); assert_eq!(stackerdb_events.len(), 6); @@ -396,7 +388,7 @@ fn test_stackerdb_event_observer() { assert_eq!(i as u32, event.slot_id); assert_eq!(event.slot_version, 1); - let expected_data = format!("Hello chunks {}", &i); + let expected_data = format!("Hello chunks {i}"); let expected_hash = Sha512Trunc256Sum::from_data(expected_data.as_bytes()); assert_eq!(event.data, expected_data.as_bytes().to_vec());