From ffc92690c0b0edf35b8de5857532d5e3877b984e Mon Sep 17 00:00:00 2001 From: Kamal Ahmad Date: Sun, 1 Dec 2024 13:38:25 +0500 Subject: [PATCH] Optimize From, distinct_token_ids --- bindings/ergo-lib-wasm/src/transaction.rs | 2 +- ergo-chain-types/src/ec_point.rs | 4 ++-- ergo-lib/src/chain/transaction.rs | 18 ++++++------------ ergo-lib/src/chain/transaction/unsigned.rs | 2 +- .../src/eval/create_provedlog.rs | 2 +- .../src/eval/multiply_group.rs | 4 ++-- ergotree-interpreter/src/eval/sgroup_elem.rs | 6 +++--- .../src/sigma_protocol/dht_protocol.rs | 6 +++--- .../src/sigma_protocol/dlog_protocol.rs | 11 +++++------ .../src/sigma_protocol/prover.rs | 5 ++--- .../src/sigma_protocol/verifier.rs | 2 +- .../src/sigma_protocol/wscalar.rs | 11 +++++------ ergotree-ir/src/mir/constant.rs | 2 +- ergotree-ir/src/mir/value.rs | 2 +- 14 files changed, 34 insertions(+), 43 deletions(-) diff --git a/bindings/ergo-lib-wasm/src/transaction.rs b/bindings/ergo-lib-wasm/src/transaction.rs index 62f44ae72..da77f0b7d 100644 --- a/bindings/ergo-lib-wasm/src/transaction.rs +++ b/bindings/ergo-lib-wasm/src/transaction.rs @@ -401,7 +401,7 @@ impl UnsignedTransaction { /// Returns distinct token id from output_candidates as array of byte arrays pub fn distinct_token_ids(&self) -> Vec { - distinct_token_ids(self.0.output_candidates.clone()) + distinct_token_ids(&self.0.output_candidates) .iter() .map(|id| Uint8Array::from(id.as_ref())) .collect() diff --git a/ergo-chain-types/src/ec_point.rs b/ergo-chain-types/src/ec_point.rs index cf793fa65..a25bf1e1a 100644 --- a/ergo-chain-types/src/ec_point.rs +++ b/ergo-chain-types/src/ec_point.rs @@ -104,7 +104,7 @@ pub fn is_identity(ge: &EcPoint) -> bool { /// Calculates the inverse of the given group element pub fn inverse(ec: &EcPoint) -> EcPoint { - -ec.clone() + -*ec } /// Raises the base GroupElement to the exponent. The result is another GroupElement. @@ -113,7 +113,7 @@ pub fn exponentiate(base: &EcPoint, exponent: &Scalar) -> EcPoint { // we treat EC as a multiplicative group, therefore, exponentiate point is multiply. EcPoint(base.0 * exponent) } else { - base.clone() + *base } } diff --git a/ergo-lib/src/chain/transaction.rs b/ergo-lib/src/chain/transaction.rs index c9d9ec24f..a4150e9f5 100644 --- a/ergo-lib/src/chain/transaction.rs +++ b/ergo-lib/src/chain/transaction.rs @@ -231,20 +231,14 @@ pub enum TransactionSignatureVerificationError { } /// Returns distinct token ids from all given ErgoBoxCandidate's -pub fn distinct_token_ids(output_candidates: I) -> IndexSet +pub fn distinct_token_ids<'a, I>(output_candidates: I) -> IndexSet where - I: IntoIterator, + I: IntoIterator, { - let token_ids: Vec = output_candidates + let token_ids = output_candidates .into_iter() - .flat_map(|b| { - b.tokens - .into_iter() - .flatten() - .map(|t| t.token_id) - .collect::>() - }) - .collect(); + .flat_map(|b| b.tokens.iter().flatten().map(|t| t.token_id)); + IndexSet::<_>::from_iter(token_ids) } @@ -262,7 +256,7 @@ impl SigmaSerializable for Transaction { } // Serialize distinct ids of tokens in transaction outputs. - let distinct_token_ids = distinct_token_ids(self.output_candidates.clone()); + let distinct_token_ids = distinct_token_ids(&self.output_candidates); // Note that `self.output_candidates` is of type `TxIoVec` which has a max length of // `u16::MAX`. Therefore the following unwrap is safe. diff --git a/ergo-lib/src/chain/transaction/unsigned.rs b/ergo-lib/src/chain/transaction/unsigned.rs index 507287b57..d6817595c 100644 --- a/ergo-lib/src/chain/transaction/unsigned.rs +++ b/ergo-lib/src/chain/transaction/unsigned.rs @@ -123,7 +123,7 @@ impl UnsignedTransaction { /// Returns distinct token ids from all output_candidates pub fn distinct_token_ids(&self) -> IndexSet { - distinct_token_ids(self.output_candidates.clone()) + distinct_token_ids(&self.output_candidates) } } diff --git a/ergotree-interpreter/src/eval/create_provedlog.rs b/ergotree-interpreter/src/eval/create_provedlog.rs index 15838791d..ca85b4523 100644 --- a/ergotree-interpreter/src/eval/create_provedlog.rs +++ b/ergotree-interpreter/src/eval/create_provedlog.rs @@ -16,7 +16,7 @@ impl Evaluable for CreateProveDlog { let value_v = self.input.eval(env, ctx)?; match value_v { Value::GroupElement(ecpoint) => { - let prove_dlog = ProveDlog::new((*ecpoint).clone()); + let prove_dlog = ProveDlog::new(*ecpoint); Ok(prove_dlog.into()) } _ => Err(EvalError::UnexpectedValue(format!( diff --git a/ergotree-interpreter/src/eval/multiply_group.rs b/ergotree-interpreter/src/eval/multiply_group.rs index f79d54bb6..5475adbd4 100644 --- a/ergotree-interpreter/src/eval/multiply_group.rs +++ b/ergotree-interpreter/src/eval/multiply_group.rs @@ -17,7 +17,7 @@ impl Evaluable for MultiplyGroup { match (&left_v, &right_v) { (Value::GroupElement(left), Value::GroupElement(right)) => { - Ok(((**left).clone() * right).into()) + Ok(((**left) * right).into()) } _ => Err(EvalError::UnexpectedValue(format!( "Expected MultiplyGroup input to be GroupElement, got: {0:?}", @@ -45,7 +45,7 @@ mod tests { #[test] fn eval_any(left in any::(), right in any::()) { - let expected_mul = left.clone() * &right; + let expected_mul = left * &right; let expr: Expr = MultiplyGroup { left: Box::new(Expr::Const(left.into())), diff --git a/ergotree-interpreter/src/eval/sgroup_elem.rs b/ergotree-interpreter/src/eval/sgroup_elem.rs index e3181fb96..276b96fde 100644 --- a/ergotree-interpreter/src/eval/sgroup_elem.rs +++ b/ergotree-interpreter/src/eval/sgroup_elem.rs @@ -21,7 +21,7 @@ pub(crate) static GET_ENCODED_EVAL_FN: EvalFn = |_mc, _env, _ctx, obj, _args| { pub(crate) static NEGATE_EVAL_FN: EvalFn = |_mc, _env, _ctx, obj, _args| { let negated: EcPoint = match obj { - Value::GroupElement(ec_point) => Ok(-(*ec_point).clone()), + Value::GroupElement(ec_point) => Ok(-(*ec_point)), _ => Err(EvalError::UnexpectedValue(format!( "expected obj to be Value::GroupElement, got: {0:?}", obj @@ -47,7 +47,7 @@ mod tests { fn eval_get_encoded() { let input = force_any_val::(); let expr: Expr = MethodCall::new( - input.clone().into(), + input.into(), sgroup_elem::GET_ENCODED_METHOD.clone(), vec![], ) @@ -65,7 +65,7 @@ mod tests { fn eval_negate() { let input = force_any_val::(); let expr: Expr = MethodCall::new( - input.clone().into(), + input.into(), sgroup_elem::NEGATE_METHOD.clone(), vec![], ) diff --git a/ergotree-interpreter/src/sigma_protocol/dht_protocol.rs b/ergotree-interpreter/src/sigma_protocol/dht_protocol.rs index 637550bc7..f7bb65128 100644 --- a/ergotree-interpreter/src/sigma_protocol/dht_protocol.rs +++ b/ergotree-interpreter/src/sigma_protocol/dht_protocol.rs @@ -70,7 +70,7 @@ pub mod interactive_prover { let z = dlog_group::random_scalar_in_group_range(crypto_utils::secure_rng()); // COMPUTE a = g^z*u^(-e) and b = h^z*v^{-e} (where -e here means -e mod q) - let e: Scalar = challenge.clone().into(); + let e: Scalar = challenge.into(); let minus_e = e.negate(); let h_to_z = exponentiate(&public_input.h, &z); let g_to_z = exponentiate(&public_input.g, &z); @@ -106,7 +106,7 @@ pub mod interactive_prover { rnd: &Wscalar, challenge: &Challenge, ) -> SecondDhTupleProverMessage { - let e: Scalar = challenge.clone().into(); + let e: Scalar = challenge.into(); // modulo multiplication, no need to explicit mod op let ew = e.mul(private_input.w.as_scalar_ref()); // modulo addition, no need to explicit mod op @@ -133,7 +133,7 @@ pub mod interactive_prover { let z = second_message.z.clone(); - let e: Scalar = challenge.clone().into(); + let e: Scalar = challenge.into(); use ergo_chain_types::ec_point::{exponentiate, inverse}; diff --git a/ergotree-interpreter/src/sigma_protocol/dlog_protocol.rs b/ergotree-interpreter/src/sigma_protocol/dlog_protocol.rs index 2343d5689..fc044c1b1 100644 --- a/ergotree-interpreter/src/sigma_protocol/dlog_protocol.rs +++ b/ergotree-interpreter/src/sigma_protocol/dlog_protocol.rs @@ -46,7 +46,7 @@ pub mod interactive_prover { use crate::sigma_protocol::{private_input::DlogProverInput, Challenge}; use ergo_chain_types::ec_point::exponentiate_gen; use ergo_chain_types::{ - ec_point::{exponentiate, generator, inverse}, + ec_point::{exponentiate, inverse}, EcPoint, }; use ergotree_ir::sigma_protocol::dlog_group; @@ -65,7 +65,7 @@ pub mod interactive_prover { let z = dlog_group::random_scalar_in_group_range(crypto_utils::secure_rng()); //COMPUTE a = g^z*h^(-e) (where -e here means -e mod q) - let e: Scalar = challenge.clone().into(); + let e: Scalar = challenge.into(); let minus_e = e.negate(); let h_to_e = exponentiate(&public_input.h, &minus_e); let g_to_z = exponentiate_gen(&z); @@ -94,7 +94,7 @@ pub mod interactive_prover { rnd: Wscalar, challenge: &Challenge, ) -> SecondDlogProverMessage { - let e: Scalar = challenge.clone().into(); + let e: Scalar = challenge.into(); // modulo multiplication, no need to explicit mod op let ew = e.mul(private_input.w.as_scalar_ref()); // modulo addition, no need to explicit mod op @@ -112,9 +112,8 @@ pub mod interactive_prover { challenge: &Challenge, second_message: &SecondDlogProverMessage, ) -> EcPoint { - let g = generator(); - let h = *proposition.h.clone(); - let e: Scalar = challenge.clone().into(); + let h = *proposition.h; + let e: Scalar = challenge.into(); let g_z = exponentiate_gen(second_message.z.as_scalar_ref()); let h_e = exponentiate(&h, &e); g_z * &inverse(&h_e) diff --git a/ergotree-interpreter/src/sigma_protocol/prover.rs b/ergotree-interpreter/src/sigma_protocol/prover.rs index b00a2de87..cc3d10bf0 100644 --- a/ergotree-interpreter/src/sigma_protocol/prover.rs +++ b/ergotree-interpreter/src/sigma_protocol/prover.rs @@ -218,12 +218,11 @@ fn prove_to_unchecked( // Prover Steps 7: convert the relevant information in the tree (namely, tree structure, node types, // the statements being proven and commitments at the leaves) // to a string - let var_name = fiat_shamir_tree_to_bytes(&step6.clone().into())?; - let mut s = var_name; + let mut s = fiat_shamir_tree_to_bytes(&step6.clone().into())?; // Prover Step 8: compute the challenge for the root of the tree as the Fiat-Shamir hash of s // and the message being signed. - s.append(&mut message.to_vec()); + s.extend_from_slice(message); let root_challenge: Challenge = fiat_shamir_hash_fn(s.as_slice()).into(); let step8 = step6.with_challenge(root_challenge); // dbg!(&step8); diff --git a/ergotree-interpreter/src/sigma_protocol/verifier.rs b/ergotree-interpreter/src/sigma_protocol/verifier.rs index a08569369..22ebada55 100644 --- a/ergotree-interpreter/src/sigma_protocol/verifier.rs +++ b/ergotree-interpreter/src/sigma_protocol/verifier.rs @@ -115,7 +115,7 @@ fn check_commitments(sp: UncheckedTree, message: &[u8]) -> Result for Wscalar { } } -impl From for Scalar { - fn from(v: Challenge) -> Self { - let v: [u8; SOUNDNESS_BYTES] = v.0.into(); - // prepend zeroes to 32 bytes (big-endian) - let mut prefix = vec![0u8; 8]; - prefix.append(&mut v.to_vec()); +impl From<&Challenge> for Scalar { + fn from(v: &Challenge) -> Self { + let v: [u8; SOUNDNESS_BYTES] = *v.0 .0; + let mut prefix = [0u8; 32]; + prefix[32 - SOUNDNESS_BYTES..].copy_from_slice(&v); >::reduce_bytes(&GenericArray::clone_from_slice(&prefix)) } } diff --git a/ergotree-ir/src/mir/constant.rs b/ergotree-ir/src/mir/constant.rs index ae61153e9..847c2629b 100644 --- a/ergotree-ir/src/mir/constant.rs +++ b/ergotree-ir/src/mir/constant.rs @@ -700,7 +700,7 @@ impl TryExtractFrom for i64 { impl TryExtractFrom for EcPoint { fn try_extract_from(cv: Literal) -> Result { match cv { - Literal::GroupElement(v) => Ok((*v).clone()), + Literal::GroupElement(v) => Ok(*v), _ => Err(TryExtractFromError(format!( "expected EcPoint, found {:?}", cv diff --git a/ergotree-ir/src/mir/value.rs b/ergotree-ir/src/mir/value.rs index 3b3b33b75..aa06dc613 100644 --- a/ergotree-ir/src/mir/value.rs +++ b/ergotree-ir/src/mir/value.rs @@ -491,7 +491,7 @@ impl TryExtractFrom> for i64 { impl TryExtractFrom> for EcPoint { fn try_extract_from(cv: Value) -> Result { match cv { - Value::GroupElement(v) => Ok((*v).clone()), + Value::GroupElement(v) => Ok(*v), _ => Err(TryExtractFromError(format!( "expected EcPoint, found {:?}", cv