diff --git a/build.rs b/build.rs index 2e475e90..504b6cd1 100644 --- a/build.rs +++ b/build.rs @@ -5,26 +5,35 @@ use clvmr::Allocator; use toml::{Table, Value}; use clvm_tools_rs::classic::clvm_tools::clvmc::CompileError; -use clvm_tools_rs::classic::platform::argparse::ArgumentValue; use clvm_tools_rs::classic::clvm_tools::comp_input::RunAndCompileInputData; +use clvm_tools_rs::classic::platform::argparse::ArgumentValue; use clvm_tools_rs::compiler::comptypes::CompileErr; use clvm_tools_rs::compiler::srcloc::Srcloc; fn do_compile(title: &str, filename: &str) -> Result<(), CompileError> { let mut allocator = Allocator::new(); let mut arguments: HashMap = HashMap::new(); - arguments.insert("include".to_string(), ArgumentValue::ArgArray(vec![ArgumentValue::ArgString(None, ".".to_string())])); + arguments.insert( + "include".to_string(), + ArgumentValue::ArgArray(vec![ArgumentValue::ArgString(None, ".".to_string())]), + ); let file_content = fs::read_to_string(filename).map_err(|e| { - CompileErr(Srcloc::start(filename), format!("failed to read {filename}: {e:?}")) + CompileErr( + Srcloc::start(filename), + format!("failed to read {filename}: {e:?}"), + ) })?; - arguments.insert("path_or_code".to_string(), ArgumentValue::ArgString(Some(filename.to_string()), file_content)); + arguments.insert( + "path_or_code".to_string(), + ArgumentValue::ArgString(Some(filename.to_string()), file_content), + ); let parsed = RunAndCompileInputData::new(&mut allocator, &arguments).map_err(|e| { CompileError::Modern( Srcloc::start("*error*"), - format!("error building chialisp {title}: {e}") + format!("error building chialisp {title}: {e}"), ) })?; let mut symbol_table = HashMap::new(); @@ -37,19 +46,20 @@ fn do_compile(title: &str, filename: &str) -> Result<(), CompileError> { fn compile_chialisp() -> Result<(), CompileError> { let srcloc = Srcloc::start("chialisp.toml"); let chialisp_toml_text = fs::read_to_string("chialisp.toml").map_err(|e| { - CompileError::Modern(srcloc.clone(), format!("Error reading chialisp.toml: {e:?}")) + CompileError::Modern( + srcloc.clone(), + format!("Error reading chialisp.toml: {e:?}"), + ) })?; - let chialisp_toml = chialisp_toml_text.parse::().map_err(|e| { - CompileError::Modern(srcloc, format!("Error parsing chialisp.toml: {e:?}")) - })?; + let chialisp_toml = chialisp_toml_text + .parse::
() + .map_err(|e| CompileError::Modern(srcloc, format!("Error parsing chialisp.toml: {e:?}")))?; - if let Some(compiles) = chialisp_toml.get("compile") { - if let Value::Table(t) = compiles { - for (k,v) in t.iter() { - if let Value::String(s) = v { - do_compile(k, &s)?; - } + if let Some(Value::Table(t)) = chialisp_toml.get("compile") { + for (k, v) in t.iter() { + if let Value::String(s) = v { + do_compile(k, s)?; } } } diff --git a/src/channel_handler/game.rs b/src/channel_handler/game.rs index ab7fe7c4..a71a82c1 100644 --- a/src/channel_handler/game.rs +++ b/src/channel_handler/game.rs @@ -1,5 +1,5 @@ use clvm_traits::{ClvmEncoder, ToClvm}; -use clvmr::{NodePtr, run_program}; +use clvmr::{run_program, NodePtr}; use clvm_tools_rs::classic::clvm::sexp::proper_list; @@ -65,11 +65,11 @@ impl Game { .expect("should be an atom"); let required_size_factor = Amount::new( atom_from_clvm(allocator, template_list[3]) - .and_then(|a| u64_from_atom(a)) + .and_then(u64_from_atom) .expect("should be an atom"), ); let initial_max_move_size = atom_from_clvm(allocator, template_list[4]) - .and_then(|a| usize_from_atom(a)) + .and_then(usize_from_atom) .expect("should be an atom"); let initial_validation_program = ValidationProgram::new(allocator, template_list[5]); let initial_validation_program_hash = @@ -82,7 +82,7 @@ impl Game { }; let initial_state = template_list[7]; let initial_mover_share_proportion = atom_from_clvm(allocator, template_list[8]) - .and_then(|a| usize_from_atom(a)) + .and_then(usize_from_atom) .expect("should be an atom"); Ok(Game { id: game_id, diff --git a/src/channel_handler/game_handler.rs b/src/channel_handler/game_handler.rs index 02d84a98..3c9052ee 100644 --- a/src/channel_handler/game_handler.rs +++ b/src/channel_handler/game_handler.rs @@ -155,7 +155,7 @@ fn run_code( pub enum TheirTurnResult { FinalMove(NodePtr), MakeMove(NodePtr, GameHandler, Vec), - Slash(Evidence, Aggsig), + Slash(Evidence, Box), } impl GameHandler { @@ -206,10 +206,7 @@ impl GameHandler { inputs.amount.clone(), ( inputs.last_mover_share.clone(), - ( - inputs.last_max_move_size.clone(), - (inputs.entropy.clone(), ()), - ), + (inputs.last_max_move_size, (inputs.entropy.clone(), ())), ), ), ) @@ -249,27 +246,27 @@ impl GameHandler { } let max_move_size = - if let Some(mm) = atom_from_clvm(allocator, pl[4]).and_then(|a| usize_from_atom(a)) { + if let Some(mm) = atom_from_clvm(allocator, pl[4]).and_then(usize_from_atom) { mm } else { return Err(Error::StrErr("bad max move size".to_string())); }; - let mover_share = - if let Some(ms) = atom_from_clvm(allocator, pl[5]).and_then(|a| u64_from_atom(a)) { - Amount::new(ms) - } else { - return Err(Error::StrErr(format!( - "bad share {}", - disassemble(allocator.allocator(), pl[5], None) - ))); - }; + let mover_share = if let Some(ms) = atom_from_clvm(allocator, pl[5]).and_then(u64_from_atom) + { + Amount::new(ms) + } else { + return Err(Error::StrErr(format!( + "bad share {}", + disassemble(allocator.allocator(), pl[5], None) + ))); + }; let message_parser = if pl[7] == allocator.allocator().null() { None } else { Some(MessageHandler::from_nodeptr(pl[7])) }; let validation_program_hash = - if let Some(h) = atom_from_clvm(allocator, pl[2]).map(|a| Hash::from_slice(a)) { + if let Some(h) = atom_from_clvm(allocator, pl[2]).map(Hash::from_slice) { h } else { return Err(Error::StrErr("bad hash".to_string())); @@ -312,7 +309,7 @@ impl GameHandler { let driver_args = ( inputs.amount.clone(), ( - Node(inputs.last_state.clone()), + Node(inputs.last_state), ( Node( allocator @@ -322,7 +319,7 @@ impl GameHandler { ( inputs.new_move.validation_info_hash.clone(), ( - inputs.new_move.basic.max_move_size.clone(), + inputs.new_move.basic.max_move_size, (inputs.new_move.basic.mover_share.clone(), ()), ), ), @@ -362,10 +359,10 @@ impl GameHandler { if move_type == 0 { if pl.len() < 2 { - return Err(Error::StrErr(format!( + Err(Error::StrErr(format!( "bad length for move result {}", disassemble(allocator.allocator(), run_result, None) - ))); + ))) } else if pl.len() < 3 { Ok(TheirTurnResult::FinalMove(pl[1])) } else { @@ -390,7 +387,7 @@ impl GameHandler { let sig_bytes = allocator.allocator().atom(pl[2]).to_vec(); Ok(TheirTurnResult::Slash( Evidence::from_nodeptr(pl[1]), - Aggsig::from_slice(&sig_bytes)?, + Box::new(Aggsig::from_slice(&sig_bytes)?), )) } else { Err(Error::StrErr("unknown move result type".to_string())) diff --git a/src/channel_handler/mod.rs b/src/channel_handler/mod.rs index 3d4ff1c4..2cc01665 100644 --- a/src/channel_handler/mod.rs +++ b/src/channel_handler/mod.rs @@ -4,6 +4,7 @@ pub mod runner; pub mod types; use std::borrow::BorrowMut; +use std::cmp::Ordering; use rand::prelude::*; @@ -133,7 +134,7 @@ impl ChannelHandler { pub fn get_finished_unroll_coin(&self) -> &ChannelHandlerUnrollSpendInfo { if let Some(t) = self.timeout.as_ref() { - &t + t } else { &self.unroll } @@ -319,7 +320,7 @@ impl ChannelHandler { &env.standard_puzzle, &aggregate_public_key, )?, - solution: Program::from_nodeptr(&mut env.allocator, channel_coin_spend.solution)?, + solution: Program::from_nodeptr(env.allocator, channel_coin_spend.solution)?, signature: channel_coin_spend.signature.clone(), }; @@ -574,12 +575,12 @@ impl ChannelHandler { self.next_nonce_number += 1; let referee_identity = ChiaIdentity::new( - &mut env.allocator, + env.allocator, self.private_keys.my_referee_private_key.clone(), )?; let (referee_maker, puzzle_hash) = RefereeMaker::new( - &mut env.allocator, + env.allocator, env.referee_coin_puzzle.clone(), env.referee_coin_puzzle_hash.clone(), g, @@ -902,7 +903,7 @@ impl ChannelHandler { )?; Ok(TransactionBundle { - solution: Program::from_nodeptr(&mut env.allocator, channel_coin_spend.solution)?, + solution: Program::from_nodeptr(env.allocator, channel_coin_spend.solution)?, signature: channel_coin_spend.signature, puzzle: puzzle_for_pk(env.allocator, &aggregate_public_key)?, }) @@ -936,12 +937,12 @@ impl ChannelHandler { assert!(!self.have_potato); let channel_spend = self.verify_channel_coin_from_peer_signatures( env, - &their_channel_half_signature, + their_channel_half_signature, conditions, )?; Ok(TransactionBundle { - solution: Program::from_nodeptr(&mut env.allocator, channel_spend.solution)?, + solution: Program::from_nodeptr(env.allocator, channel_spend.solution)?, signature: channel_spend.signature, puzzle: puzzle_for_pk(env.allocator, &aggregate_public_key)?, }) @@ -966,7 +967,7 @@ impl ChannelHandler { }) .collect(); - if rem_conditions.len() < 1 { + if rem_conditions.is_empty() { return Err(Error::StrErr( "Wrong number of rems in conditions".to_string(), )); @@ -999,8 +1000,8 @@ impl ChannelHandler { Ok(ChannelCoinSpentResult { transaction: TransactionBundle { - puzzle: Puzzle::from_nodeptr(&mut env.allocator, curried_unroll_puzzle)?, - solution: Program::from_nodeptr(&mut env.allocator, unroll_puzzle_solution)?, + puzzle: Puzzle::from_nodeptr(env.allocator, curried_unroll_puzzle)?, + solution: Program::from_nodeptr(env.allocator, unroll_puzzle_solution)?, signature: use_unroll.coin.get_unroll_coin_signature()? + use_unroll.signatures.my_unroll_half_signature_peer.clone(), }, @@ -1067,44 +1068,41 @@ impl ChannelHandler { self.current_state_number, full_coin.coin.state_number ); - if state_number > self.current_state_number { - return Err(Error::StrErr(format!( + match state_number.cmp(&self.current_state_number) { + Ordering::Greater => Err(Error::StrErr(format!( "Reply from the future onchain {} (me {}) vs {}", state_number, self.current_state_number, self.unroll.coin.state_number - ))); - } else if state_number < self.current_state_number { - if our_parity == their_parity { - return Err(Error::StrErr( - "We're superceding ourselves from the past?".to_string(), - )); - } + ))), + Ordering::Less => { + if our_parity == their_parity { + return Err(Error::StrErr( + "We're superceding ourselves from the past?".to_string(), + )); + } - self.get_unroll_coin_transaction(env) - } else if state_number == self.current_state_number { - // Timeout - let curried_unroll_puzzle = self - .unroll - .coin - .make_curried_unroll_puzzle(env, &self.get_aggregate_unroll_public_key())?; - let unroll_puzzle_solution = self - .unroll - .coin - .make_unroll_puzzle_solution(env, &self.get_aggregate_unroll_public_key())?; - - Ok(ChannelCoinSpentResult { - transaction: TransactionBundle { - puzzle: Puzzle::from_nodeptr(&mut env.allocator, curried_unroll_puzzle)?, - solution: Program::from_nodeptr(&mut env.allocator, unroll_puzzle_solution)?, - signature: self.unroll.coin.get_unroll_coin_signature()?, - }, - timeout: true, - games_canceled: self.get_just_created_games(), - }) - } else { - Err(Error::StrErr(format!( - "Unhandled relationship between state numbers {state_number} {}", - self.unroll.coin.state_number - ))) + self.get_unroll_coin_transaction(env) + } + _ => { + // Timeout + let curried_unroll_puzzle = self + .unroll + .coin + .make_curried_unroll_puzzle(env, &self.get_aggregate_unroll_public_key())?; + let unroll_puzzle_solution = self + .unroll + .coin + .make_unroll_puzzle_solution(env, &self.get_aggregate_unroll_public_key())?; + + Ok(ChannelCoinSpentResult { + transaction: TransactionBundle { + puzzle: Puzzle::from_nodeptr(env.allocator, curried_unroll_puzzle)?, + solution: Program::from_nodeptr(env.allocator, unroll_puzzle_solution)?, + signature: self.unroll.coin.get_unroll_coin_signature()?, + }, + timeout: true, + games_canceled: self.get_just_created_games(), + }) + } } } @@ -1148,7 +1146,7 @@ impl ChannelHandler { // Add amount contributed to vanilla balance // Skip game when generating result. Ok(Some(DispositionResult { - disposition: CoinSpentDisposition::CancelledUX(ids.iter().cloned().collect()), + disposition: CoinSpentDisposition::CancelledUX(ids.to_vec()), skip_game: ids.clone(), skip_coin_id: None, our_contribution_adjustment: our_contrib.clone(), @@ -1267,8 +1265,8 @@ impl ChannelHandler { // balances. // // If we have the potato at state 0 and they start an unroll, we don't - pub fn unroll_coin_spent<'a, R: Rng>( - &'a self, + pub fn unroll_coin_spent( + &self, env: &mut ChannelHandlerEnv, unroll_coin: &CoinString, conditions: NodePtr, @@ -1300,7 +1298,7 @@ impl ChannelHandler { let adjusted_amount = disposition .as_ref() .map(|d| d.our_contribution_adjustment.clone()) - .unwrap_or_else(|| Amount::default()); + .unwrap_or_default(); Ok(CoinSpentResult { my_clean_reward_coin_string_up: CoinString::from_parts( @@ -1368,19 +1366,16 @@ impl ChannelHandler { let quoted_program_hash = quoted_program.sha256tree(env.allocator); let signature = sign_agg_sig_me( &self.referee_private_key(), - "ed_program_hash.bytes(), + quoted_program_hash.bytes(), &parent_id, &env.agg_sig_me_additional_data, ); - let standard_solution = standard_solution_unsafe( - &mut env.allocator, - &self.referee_private_key(), - conditions, - )?; + let standard_solution = + standard_solution_unsafe(env.allocator, &self.referee_private_key(), conditions)?; coins_with_solutions.push(TransactionBundle { puzzle: spend_coin_puzzle.clone(), - solution: Program::from_nodeptr(&mut env.allocator, standard_solution.solution)?, + solution: Program::from_nodeptr(env.allocator, standard_solution.solution)?, signature, }); } diff --git a/src/channel_handler/runner.rs b/src/channel_handler/runner.rs index 2ef96a7c..92c1fc69 100644 --- a/src/channel_handler/runner.rs +++ b/src/channel_handler/runner.rs @@ -170,6 +170,6 @@ pub fn channel_handler_env<'a, R: Rng>( unroll_metapuzzle, unroll_puzzle, standard_puzzle, - agg_sig_me_additional_data: Hash::from_bytes(AGG_SIG_ME_ADDITIONAL_DATA.clone()), + agg_sig_me_additional_data: Hash::from_bytes(AGG_SIG_ME_ADDITIONAL_DATA), } } diff --git a/src/channel_handler/types.rs b/src/channel_handler/types.rs index 1b73b24f..61179ef4 100644 --- a/src/channel_handler/types.rs +++ b/src/channel_handler/types.rs @@ -309,7 +309,7 @@ impl ValidationProgram { } pub fn to_nodeptr(&self) -> NodePtr { - self.validation_program.clone() + self.validation_program } pub fn hash(&self) -> &Hash { @@ -343,7 +343,7 @@ impl ValidationInfo { ) -> Self { let hash = Sha256Input::Array(vec![ Sha256Input::Hash(validation_program.hash()), - Sha256Input::Hash(&Node(game_state).sha256tree(allocator).hash()), + Sha256Input::Hash(Node(game_state).sha256tree(allocator).hash()), ]) .hash(); ValidationInfo::FromProgram { @@ -362,7 +362,7 @@ impl ValidationInfo { ) -> Self { let hash = Sha256Input::Array(vec![ Sha256Input::Hash(&validation_program_hash), - Sha256Input::Hash(&Node(game_state).sha256tree(allocator).hash()), + Sha256Input::Hash(Node(game_state).sha256tree(allocator).hash()), ]) .hash(); ValidationInfo::FromProgramHash { @@ -375,7 +375,7 @@ impl ValidationInfo { match self { ValidationInfo::FromProgramHash { hash, .. } | ValidationInfo::FromProgram { hash, .. } - | ValidationInfo::FromHash { hash } => &hash, + | ValidationInfo::FromHash { hash } => hash, } } } @@ -412,10 +412,10 @@ impl ChannelCoin { ); let spend = standard_solution_partial( env.allocator, - &private_key, + private_key, &self.state_channel_coin.to_coin_id(), conditions, - &aggregate_public_key, + aggregate_public_key, &env.agg_sig_me_additional_data, true, )?; @@ -683,7 +683,7 @@ impl UnrollCoin { ) -> Result { let unroll_conditions = self.compute_unroll_coin_conditions(env, inputs)?; let conditions_hash = Node(unroll_conditions).sha256tree(env.allocator); - let unroll_public_key = private_to_public_key(&unroll_private_key); + let unroll_public_key = private_to_public_key(unroll_private_key); let unroll_aggregate_key = unroll_public_key.clone() + their_unroll_coin_public_key.clone(); eprintln!( "conditions {}", @@ -691,9 +691,9 @@ impl UnrollCoin { ); eprintln!("conditions_hash {conditions_hash:?}"); let unroll_signature = unsafe_sign_partial( - &unroll_private_key, + unroll_private_key, &unroll_aggregate_key, - &conditions_hash.bytes().to_vec(), + conditions_hash.bytes(), ); self.outcome = Some(UnrollCoinOutcome { conditions: unroll_conditions, @@ -730,8 +730,8 @@ impl UnrollCoin { let aggregate_unroll_signature = signature.clone() + self.get_unroll_coin_signature()?; Ok(aggregate_unroll_signature.verify( - &aggregate_unroll_public_key, - &unroll_puzzle_solution_hash.bytes(), + aggregate_unroll_public_key, + unroll_puzzle_solution_hash.bytes(), )) } } diff --git a/src/common/standard_coin.rs b/src/common/standard_coin.rs index b1a119fe..bd247785 100644 --- a/src/common/standard_coin.rs +++ b/src/common/standard_coin.rs @@ -6,8 +6,8 @@ use chia_bls; use clvm_traits::{clvm_curried_args, ToClvm}; -use clvmr::NodePtr; use clvmr::serde::node_from_bytes; +use clvmr::NodePtr; use clvm_tools_rs::util::{number_from_u8, u8_from_number}; @@ -36,7 +36,7 @@ pub fn hex_to_sexp( let hex_stream = Stream::new(Some( Bytes::new_validated(Some(UnvalidatedBytesFromType::Hex(hex_data))).into_gen()?, )); - node_from_bytes(allocator.allocator(), &hex_stream.get_value().data()).into_gen() + node_from_bytes(allocator.allocator(), hex_stream.get_value().data()).into_gen() } pub fn read_hex_puzzle(allocator: &mut AllocEncoder, name: &str) -> Result { @@ -58,7 +58,7 @@ fn group_order_int() -> BigInt { fn calculate_synthetic_offset(public_key: &PublicKey, hidden_puzzle_hash: &PuzzleHash) -> BigInt { let mut blob_input = public_key.bytes().to_vec(); - blob_input.extend_from_slice(&mut hidden_puzzle_hash.bytes()); + blob_input.extend_from_slice(hidden_puzzle_hash.bytes()); let blob = Sha256Input::Bytes(&blob_input).hash(); BigInt::from_bytes_be(Sign::Plus, blob.bytes()) % group_order_int() } @@ -168,11 +168,11 @@ fn hash_of_consed_parameter_hash(environment: &Hash, parameter: &Hash) -> Hash { Sha256Input::Hashed(vec![ Sha256Input::Bytes(&TWO), Sha256Input::Hashed(vec![Sha256Input::Bytes(&ONE), Sha256Input::Bytes(&Q_KW)]), - Sha256Input::Hash(¶meter), + Sha256Input::Hash(parameter), ]), Sha256Input::Hashed(vec![ Sha256Input::Bytes(&TWO), - Sha256Input::Hash(&environment), + Sha256Input::Hash(environment), Sha256Input::Hashed(vec![Sha256Input::Bytes(&ONE)]), ]), ]), @@ -212,7 +212,7 @@ pub fn calculate_hash_of_quoted_mod_hash(mod_hash: &PuzzleHash) -> Hash { Sha256Input::Array(vec![ Sha256Input::Bytes(&TWO), Sha256Input::Hash(&Q_KW_TREEHASH), - Sha256Input::Hash(&mod_hash.hash()), + Sha256Input::Hash(mod_hash.hash()), ]) .hash() } @@ -222,7 +222,7 @@ pub fn puzzle_hash_for_synthetic_public_key( synthetic_public_key: &PublicKey, ) -> Result { let quoted_mod_hash = PuzzleHash::from_hash(calculate_hash_of_quoted_mod_hash( - &PuzzleHash::from_bytes(DEFAULT_PUZZLE_HASH.clone()), + &PuzzleHash::from_bytes(DEFAULT_PUZZLE_HASH), )); let public_key_hash = Node(synthetic_public_key.to_clvm(allocator).into_gen()?).sha256tree(allocator); @@ -265,14 +265,10 @@ pub fn puzzle_for_pk( ) -> Result { let standard_puzzle = get_standard_coin_puzzle(allocator)?; let synthetic_public_key = calculate_synthetic_public_key( - &public_key, - &PuzzleHash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH.clone()), + public_key, + &PuzzleHash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH), )?; - Ok(puzzle_for_synthetic_public_key( - allocator, - &standard_puzzle, - &synthetic_public_key, - )?) + puzzle_for_synthetic_public_key(allocator, &standard_puzzle, &synthetic_public_key) } pub fn puzzle_hash_for_pk( @@ -280,13 +276,10 @@ pub fn puzzle_hash_for_pk( public_key: &PublicKey, ) -> Result { let synthetic_public_key = calculate_synthetic_public_key( - &public_key, - &PuzzleHash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH.clone()), + public_key, + &PuzzleHash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH), )?; - Ok(puzzle_hash_for_synthetic_public_key( - allocator, - &synthetic_public_key, - )?) + puzzle_hash_for_synthetic_public_key(allocator, &synthetic_public_key) } #[test] @@ -368,7 +361,7 @@ pub fn private_to_public_key(private_key: &types::PrivateKey) -> types::PublicKe pub fn unsafe_sign_partial>(sk: &PrivateKey, pk: &PublicKey, msg: Msg) -> Aggsig { let mut aug_msg = pk.bytes().to_vec(); aug_msg.extend_from_slice(msg.as_ref()); - Aggsig::from_bls(chia_bls::sign_raw(&sk.to_bls(), aug_msg)) + Aggsig::from_bls(chia_bls::sign_raw(sk.to_bls(), aug_msg)) } // From: https://github.com/Chia-Network/chia_rs/blob/2334c842f694444da317fa7432f308f159f62d70/chia-wallet/src/wallet.rs#L1166 @@ -438,7 +431,7 @@ pub fn standard_solution_partial( let quoted_conds_hash = quoted_conds.sha256tree(allocator); let solution = solution_for_conditions(allocator, conditions)?; let coin_agg_sig_me_message = agg_sig_me_message( - "ed_conds_hash.bytes(), + quoted_conds_hash.bytes(), parent_coin, agg_sig_me_additional_data, ); @@ -464,7 +457,7 @@ pub fn standard_solution_partial( add_signature( &mut aggregated_signature, if partial { - partial_signer(private_key, &aggregate_public_key, &coin_agg_sig_me_message) + partial_signer(private_key, aggregate_public_key, &coin_agg_sig_me_message) } else { private_key.sign(&coin_agg_sig_me_message) }, @@ -472,19 +465,19 @@ pub fn standard_solution_partial( } CoinCondition::AggSigMe(pubkey, data) => { let mut message = pubkey.bytes().to_vec(); - message.extend_from_slice(&data); + message.extend_from_slice(data); let extra_agg_sig_me_message = agg_sig_me_message(&message, parent_coin, agg_sig_me_additional_data); add_signature( &mut aggregated_signature, - partial_signer(private_key, &pubkey, &extra_agg_sig_me_message), + partial_signer(private_key, pubkey, &extra_agg_sig_me_message), ); } CoinCondition::AggSigUnsafe(pubkey, data) => { // It's "unsafe" because it's just a hash of the data. add_signature( &mut aggregated_signature, - partial_signer(private_key, &pubkey, &data), + partial_signer(private_key, pubkey, data), ); } _ => {} @@ -519,7 +512,7 @@ impl ChiaIdentity { allocator: &mut AllocEncoder, private_key: PrivateKey, ) -> Result { - let default_hidden_puzzle_hash = Hash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH.clone()); + let default_hidden_puzzle_hash = Hash::from_bytes(DEFAULT_HIDDEN_PUZZLE_HASH); let synthetic_private_key = calculate_synthetic_secret_key(&private_key, &default_hidden_puzzle_hash)?; let public_key = private_to_public_key(&private_key); diff --git a/src/common/types.rs b/src/common/types.rs index ae792871..e75708ad 100644 --- a/src/common/types.rs +++ b/src/common/types.rs @@ -41,7 +41,7 @@ impl CoinID { pub fn new(h: Hash) -> CoinID { CoinID(h) } - pub fn bytes<'a>(&'a self) -> &'a [u8] { + pub fn bytes(&self) -> &[u8] { self.0.bytes() } } @@ -140,8 +140,8 @@ impl PrivateKey { impl Distribution for Standard { fn sample(&self, rng: &mut R) -> Hash { let mut pk = [0; 32]; - for i in 0..32 { - pk[i] = rng.gen(); + for item in &mut pk { + *item = rng.gen(); } Hash::from_bytes(pk) } @@ -167,15 +167,9 @@ impl<'de> Visitor<'de> for SerdeByteConsumer { } /// Public key -#[derive(Clone, Eq, PartialEq, Debug)] +#[derive(Clone, Eq, PartialEq, Debug, Default)] pub struct PublicKey(chia_bls::PublicKey); -impl Default for PublicKey { - fn default() -> Self { - PublicKey(chia_bls::PublicKey::default()) - } -} - impl Serialize for PublicKey { fn serialize(&self, serializer: S) -> Result where @@ -199,8 +193,8 @@ impl<'de> Deserialize<'de> for PublicKey { fixed_bytes[i] = b; } } - Ok(PublicKey::from_bytes(fixed_bytes) - .map_err(|e| serde::de::Error::custom(format!("couldn't make pubkey: {e:?}")))?) + PublicKey::from_bytes(fixed_bytes) + .map_err(|e| serde::de::Error::custom(format!("couldn't make pubkey: {e:?}"))) } } @@ -249,16 +243,9 @@ impl ToClvm for PublicKey { } /// Aggsig -#[derive(Clone, Eq, PartialEq, Debug)] +#[derive(Clone, Eq, PartialEq, Debug, Default)] pub struct Aggsig(chia_bls::Signature); -impl Default for Aggsig { - // Revisit for empty aggsig. - fn default() -> Self { - Aggsig(chia_bls::Signature::default()) - } -} - impl Serialize for Aggsig { fn serialize(&self, serializer: S) -> Result where @@ -282,8 +269,8 @@ impl<'de> Deserialize<'de> for Aggsig { fixed_bytes[i] = b; } } - Ok(Aggsig::from_bytes(fixed_bytes) - .map_err(|e| serde::de::Error::custom(format!("couldn't make aggsig: {e:?}")))?) + Aggsig::from_bytes(fixed_bytes) + .map_err(|e| serde::de::Error::custom(format!("couldn't make aggsig: {e:?}"))) } } @@ -429,15 +416,9 @@ impl From for u64 { } } -#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize, Hash)] +#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize, Hash, Default)] pub struct Hash([u8; 32]); -impl Default for Hash { - fn default() -> Self { - Hash([0; 32]) - } -} - impl ToClvm for Hash { fn to_clvm( &self, @@ -461,7 +442,7 @@ impl Hash { } Hash::from_bytes(fixed) } - pub fn bytes<'a>(&'a self) -> &'a [u8; 32] { + pub fn bytes(&self) -> &[u8; 32] { &self.0 } } @@ -481,7 +462,7 @@ impl<'a> Sha256Input<'a> { hasher.update(b); } Sha256Input::Hash(hash) => { - hasher.update(&hash.bytes()); + hasher.update(hash.bytes()); } Sha256Input::Hashed(input) => { let mut new_hasher = Sha256::new(); @@ -518,10 +499,10 @@ impl PuzzleHash { pub fn from_hash(h: Hash) -> PuzzleHash { PuzzleHash(h) } - pub fn bytes<'a>(&'a self) -> &'a [u8] { + pub fn bytes(&self) -> &[u8] { self.0.bytes() } - pub fn hash<'a>(&'a self) -> &'a Hash { + pub fn hash(&self) -> &Hash { &self.0 } } @@ -546,12 +527,12 @@ impl ToClvm for PuzzleHash { pub enum Error { ClvmErr(EvalErr), IoErr(io::Error), - BasicError, + BasicErr, SyntaxErr(SyntaxErr), EncodeErr(ToClvmError), StrErr(String), BlsErr(chia_bls::Error), - BsonError(bson::de::Error), + BsonErr(bson::de::Error), Channel(String), } @@ -590,7 +571,7 @@ pub trait ToQuotedProgram { impl ToQuotedProgram for NodePtr { fn to_quoted_program(&self, allocator: &mut AllocEncoder) -> Result { let pair = allocator.0.new_pair(allocator.0.one(), *self).into_gen()?; - Ok(Program::from_nodeptr(allocator, pair)?) + Program::from_nodeptr(allocator, pair) } } @@ -661,7 +642,7 @@ fn clone_to_encoder( match source_allocator.sexp(node) { SExp::Atom => { let buf = source_allocator.atom(node); - encoder.encode_atom(&buf) + encoder.encode_atom(buf) } SExp::Pair(a, b) => { let ac = clone_to_encoder(encoder, source_allocator, a)?; @@ -731,12 +712,18 @@ impl ToClvm for Timeout { pub struct AllocEncoder(Allocator); +impl Default for AllocEncoder { + fn default() -> Self { + AllocEncoder(Allocator::new()) + } +} + impl AllocEncoder { pub fn new() -> Self { - AllocEncoder(Allocator::new()) + Self::default() } - pub fn allocator<'a>(&'a mut self) -> &'a mut Allocator { + pub fn allocator(&mut self) -> &mut Allocator { &mut self.0 } } @@ -810,7 +797,7 @@ impl ErrToError for ToClvmError { impl ErrToError for bson::de::Error { fn into_gen(self) -> Error { - Error::BsonError(self) + Error::BsonErr(self) } } @@ -837,12 +824,7 @@ pub enum CoinCondition { } fn parse_condition(allocator: &mut AllocEncoder, condition: NodePtr) -> Option { - let exploded = if let Some(pl) = proper_list(allocator.allocator(), condition, true) { - pl - } else { - return None; - }; - + let exploded = proper_list(allocator.allocator(), condition, true)?; let public_key_from_bytes = |b: &[u8]| -> Result { let mut fixed: [u8; 48] = [0; 48]; for (i, b) in b.iter().enumerate() { @@ -960,7 +942,7 @@ pub fn u64_from_atom(a: &[u8]) -> Option { bi.to_u64() } -pub fn atom_from_clvm<'a>(allocator: &'a mut AllocEncoder, n: NodePtr) -> Option<&'a [u8]> { +pub fn atom_from_clvm(allocator: &mut AllocEncoder, n: NodePtr) -> Option<&[u8]> { if matches!(allocator.allocator().sexp(n), SExp::Atom) { Some(allocator.allocator().atom(n)) } else { diff --git a/src/outside.rs b/src/outside.rs index 402e3cae..ec00b68c 100644 --- a/src/outside.rs +++ b/src/outside.rs @@ -484,7 +484,7 @@ impl Peer { their_contribution: self.their_contribution.clone(), }; let (channel_handler, _init_result) = - ChannelHandler::new(&mut penv.env, self.private_keys.clone(), &init_data)?; + ChannelHandler::new(penv.env, self.private_keys.clone(), &init_data)?; // init_result // pub channel_puzzle_hash_up: PuzzleHash, @@ -561,7 +561,7 @@ impl Peer { their_contribution: self.their_contribution.clone(), }; let (mut channel_handler, _init_result) = - ChannelHandler::new(&mut penv.env, self.private_keys.clone(), &init_data)?; + ChannelHandler::new(penv.env, self.private_keys.clone(), &init_data)?; let nil_sigs = channel_handler.send_empty_potato(penv.env)?; diff --git a/src/referee.rs b/src/referee.rs index 6b7d4304..be7cccbd 100644 --- a/src/referee.rs +++ b/src/referee.rs @@ -58,7 +58,7 @@ pub struct TheirTurnMoveResult { pub enum SlashOutcome { NoReward, Reward { - transaction: SpecificTransactionBundle, + transaction: Box, my_reward_coin_string: CoinString, }, } @@ -78,7 +78,7 @@ pub enum TheirTurnCoinSpentResult { new_coin_string: CoinString, readable: NodePtr, }, - Slash(SlashOutcome), + Slash(Box), } /// Adjudicates a two player turn based game @@ -169,7 +169,7 @@ impl RefereePuzzleArgs { }, ] .into_iter() - .map(|n| Node(n)) + .map(Node) .collect()) } } @@ -276,7 +276,7 @@ impl ValidatorMoveArgs { self.mover_puzzle.to_clvm(allocator).into_gen()?, self.solution, ]; - let argvec: Vec = args.into_iter().map(|v| Node(*v)).collect(); + let argvec: Vec = args.iter().map(|v| Node(*v)).collect(); argvec.to_clvm(allocator).into_gen() } } @@ -425,10 +425,7 @@ impl ToClvm for OnChainRefereeSolution { refmove.details.basic.max_move_size, ( refmove.mover_coin.mover_coin_puzzle.clone(), - ( - Node(refmove.mover_coin.mover_coin_spend_solution.clone()), - (), - ), + (Node(refmove.mover_coin.mover_coin_spend_solution), ()), ), ), ), @@ -820,7 +817,7 @@ impl RefereeMaker { RefereeMakerGameState::Initial { initial_move, .. } => ( initial_move.move_made.clone(), initial_move.mover_share.clone(), - initial_move.max_move_size.clone(), + initial_move.max_move_size, None, ), RefereeMakerGameState::AfterOurTurn { .. } => { @@ -864,7 +861,7 @@ impl RefereeMaker { self.accept_this_move( &result.waiting_driver, &result.validation_program, - result.state.clone(), + result.state, &result.game_move, )?; @@ -939,7 +936,7 @@ impl RefereeMaker { &MessageInputs { message: message.to_vec(), amount: self.amount.clone(), - state: state.clone(), + state: *state, move_data, mover_share, }, @@ -1037,11 +1034,7 @@ impl RefereeMaker { let my_mover_share = self.get_our_current_share(); if always_produce_transaction || my_mover_share != Amount::default() { - let signature = if let Some(sig) = args.get_signature() { - sig - } else { - Aggsig::default() - }; + let signature = args.get_signature().unwrap_or_default(); // The transaction solution is not the same as the solution for the // inner puzzle as we take additional move or slash data. @@ -1226,7 +1219,7 @@ impl RefereeMaker { details: self.get_our_most_recent_game_move()?, mover_coin: IdentityCoinAndSolution { mover_coin_puzzle: self.my_identity.puzzle.clone(), - mover_coin_spend_solution: referee_spend.solution.clone(), + mover_coin_spend_solution: referee_spend.solution, mover_coin_spend_signature: referee_spend.signature.clone(), }, }); @@ -1315,7 +1308,7 @@ impl RefereeMaker { let (readable_move, message) = match result { TheirTurnResult::FinalMove(readable_move) => { - self.accept_their_move(allocator, None, &details)?; + self.accept_their_move(allocator, None, details)?; (readable_move, vec![]) } @@ -1332,7 +1325,7 @@ impl RefereeMaker { // In case this succeeds, we'll direct the result to our mover // puzzle, which sets our identity for the game and is a value- // holding coin spendable by us. - self.accept_their_move(allocator, Some(handler), &details)?; + self.accept_their_move(allocator, Some(handler), details)?; (readable_move, message) } @@ -1364,7 +1357,7 @@ impl RefereeMaker { // Coin calculated off the new new state. Ok(TheirTurnMoveResult { puzzle_hash_for_unroll, - readable_move: readable_move.clone(), + readable_move, message: message.clone(), }) } @@ -1383,7 +1376,7 @@ impl RefereeMaker { evidence: Evidence, ) -> Result { ( - Node(state.clone()), + Node(state), ( Node(validation_program_clvm), ( @@ -1396,6 +1389,7 @@ impl RefereeMaker { .into_gen() } + #[allow(clippy::too_many_arguments)] fn make_slash_for_their_turn( &self, allocator: &mut AllocEncoder, @@ -1416,7 +1410,9 @@ impl RefereeMaker { let (state, validation_program) = self.get_validation_program_for_their_move()?; let reward_amount = self.amount.clone() - current_mover_share; if reward_amount == Amount::default() { - return Ok(TheirTurnCoinSpentResult::Slash(SlashOutcome::NoReward)); + return Ok(TheirTurnCoinSpentResult::Slash(Box::new( + SlashOutcome::NoReward, + ))); } let slashing_coin_solution = self.slashing_coin_solution( @@ -1428,20 +1424,22 @@ impl RefereeMaker { )?; let coin_string_of_output_coin = - CoinString::from_parts(&coin_string.to_coin_id(), &new_puzzle_hash, &reward_amount); - - Ok(TheirTurnCoinSpentResult::Slash(SlashOutcome::Reward { - transaction: SpecificTransactionBundle { - // Ultimate parent of these coins. - coin: coin_string.clone(), - bundle: TransactionBundle { - puzzle: new_puzzle.clone(), - solution: Program::from_nodeptr(allocator, slashing_coin_solution)?, - signature: sig.clone(), - }, + CoinString::from_parts(&coin_string.to_coin_id(), new_puzzle_hash, &reward_amount); + + Ok(TheirTurnCoinSpentResult::Slash(Box::new( + SlashOutcome::Reward { + transaction: Box::new(SpecificTransactionBundle { + // Ultimate parent of these coins. + coin: coin_string.clone(), + bundle: TransactionBundle { + puzzle: new_puzzle.clone(), + solution: Program::from_nodeptr(allocator, slashing_coin_solution)?, + signature: sig.clone(), + }, + }), + my_reward_coin_string: coin_string_of_output_coin, }, - my_reward_coin_string: coin_string_of_output_coin, - })) + ))) } pub fn their_turn_coin_spent( @@ -1454,8 +1452,7 @@ impl RefereeMaker { let rem_condition = if let Some(CoinCondition::Rem(rem_condition)) = CoinCondition::from_nodeptr(allocator, *conditions) .iter() - .filter(|cond| matches!(cond, CoinCondition::Rem(_))) - .next() + .find(|cond| matches!(cond, CoinCondition::Rem(_))) { // Got rem condition rem_condition.to_vec() @@ -1572,7 +1569,7 @@ impl RefereeMaker { ); let full_slash_solution = ( - Node(state.clone()), + Node(state), ( Node(validation_program.to_nodeptr()), // No evidence here. @@ -1637,7 +1634,7 @@ impl RefereeMaker { &new_puzzle_hash, full_slash_solution, evidence, - &(slash_spend.signature + sig), + &(slash_spend.signature + *sig), ); } TheirTurnResult::FinalMove(readable_move) => (readable_move, None), diff --git a/src/tests/game.rs b/src/tests/game.rs index d3980424..1bb1a9fc 100644 --- a/src/tests/game.rs +++ b/src/tests/game.rs @@ -1,6 +1,6 @@ -#[cfg(feature="sim-tests")] +#[cfg(feature = "sim-tests")] use crate::channel_handler::game::Game; -#[cfg(feature="sim-tests")] +#[cfg(feature = "sim-tests")] use crate::channel_handler::types::ChannelHandlerEnv; use crate::common::standard_coin::{ private_to_public_key, puzzle_hash_for_synthetic_public_key, ChiaIdentity,