Skip to content

Commit

Permalink
Optimize From<Challenge>, distinct_token_ids
Browse files Browse the repository at this point in the history
  • Loading branch information
SethDusek committed Dec 1, 2024
1 parent 98654ba commit ffc9269
Show file tree
Hide file tree
Showing 14 changed files with 34 additions and 43 deletions.
2 changes: 1 addition & 1 deletion bindings/ergo-lib-wasm/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8Array> {
distinct_token_ids(self.0.output_candidates.clone())
distinct_token_ids(&self.0.output_candidates)
.iter()
.map(|id| Uint8Array::from(id.as_ref()))
.collect()
Expand Down
4 changes: 2 additions & 2 deletions ergo-chain-types/src/ec_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
}

Expand Down
18 changes: 6 additions & 12 deletions ergo-lib/src/chain/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,20 +231,14 @@ pub enum TransactionSignatureVerificationError {
}

/// Returns distinct token ids from all given ErgoBoxCandidate's
pub fn distinct_token_ids<I>(output_candidates: I) -> IndexSet<TokenId>
pub fn distinct_token_ids<'a, I>(output_candidates: I) -> IndexSet<TokenId>
where
I: IntoIterator<Item = ErgoBoxCandidate>,
I: IntoIterator<Item = &'a ErgoBoxCandidate>,
{
let token_ids: Vec<TokenId> = output_candidates
let token_ids = output_candidates
.into_iter()
.flat_map(|b| {
b.tokens
.into_iter()
.flatten()
.map(|t| t.token_id)
.collect::<Vec<TokenId>>()
})
.collect();
.flat_map(|b| b.tokens.iter().flatten().map(|t| t.token_id));

IndexSet::<_>::from_iter(token_ids)
}

Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ergo-lib/src/chain/transaction/unsigned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl UnsignedTransaction {

/// Returns distinct token ids from all output_candidates
pub fn distinct_token_ids(&self) -> IndexSet<TokenId> {
distinct_token_ids(self.output_candidates.clone())
distinct_token_ids(&self.output_candidates)
}
}

Expand Down
2 changes: 1 addition & 1 deletion ergotree-interpreter/src/eval/create_provedlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand Down
4 changes: 2 additions & 2 deletions ergotree-interpreter/src/eval/multiply_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:?}",
Expand Down Expand Up @@ -45,7 +45,7 @@ mod tests {
#[test]
fn eval_any(left in any::<EcPoint>(), right in any::<EcPoint>()) {

let expected_mul = left.clone() * &right;
let expected_mul = left * &right;

let expr: Expr = MultiplyGroup {
left: Box::new(Expr::Const(left.into())),
Expand Down
6 changes: 3 additions & 3 deletions ergotree-interpreter/src/eval/sgroup_elem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -47,7 +47,7 @@ mod tests {
fn eval_get_encoded() {
let input = force_any_val::<EcPoint>();
let expr: Expr = MethodCall::new(
input.clone().into(),
input.into(),
sgroup_elem::GET_ENCODED_METHOD.clone(),
vec![],
)
Expand All @@ -65,7 +65,7 @@ mod tests {
fn eval_negate() {
let input = force_any_val::<EcPoint>();
let expr: Expr = MethodCall::new(
input.clone().into(),
input.into(),
sgroup_elem::NEGATE_METHOD.clone(),
vec![],
)
Expand Down
6 changes: 3 additions & 3 deletions ergotree-interpreter/src/sigma_protocol/dht_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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};

Expand Down
11 changes: 5 additions & 6 deletions ergotree-interpreter/src/sigma_protocol/dlog_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions ergotree-interpreter/src/sigma_protocol/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,11 @@ fn prove_to_unchecked<P: Prover + ?Sized>(
// 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);
Expand Down
2 changes: 1 addition & 1 deletion ergotree-interpreter/src/sigma_protocol/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn check_commitments(sp: UncheckedTree, message: &[u8]) -> Result<bool, Verifier
// Perform Verifier Step 4
let new_root = compute_commitments(sp);
let mut s = fiat_shamir_tree_to_bytes(&new_root.clone().into())?;
s.append(&mut message.to_vec());
s.extend_from_slice(message);
// Verifier Steps 5-6: Convert the tree to a string `s` for input to the Fiat-Shamir hash function,
// using the same conversion as the prover in 7
// Accept the proof if the challenge at the root of the tree is equal to the Fiat-Shamir hash of `s`
Expand Down
11 changes: 5 additions & 6 deletions ergotree-interpreter/src/sigma_protocol/wscalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,11 @@ impl From<GroupSizedBytes> for Wscalar {
}
}

impl From<Challenge> 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);
<Scalar as Reduce<U256>>::reduce_bytes(&GenericArray::clone_from_slice(&prefix))
}
}
Expand Down
2 changes: 1 addition & 1 deletion ergotree-ir/src/mir/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ impl TryExtractFrom<Literal> for i64 {
impl TryExtractFrom<Literal> for EcPoint {
fn try_extract_from(cv: Literal) -> Result<EcPoint, TryExtractFromError> {
match cv {
Literal::GroupElement(v) => Ok((*v).clone()),
Literal::GroupElement(v) => Ok(*v),
_ => Err(TryExtractFromError(format!(
"expected EcPoint, found {:?}",
cv
Expand Down
2 changes: 1 addition & 1 deletion ergotree-ir/src/mir/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ impl TryExtractFrom<Value<'_>> for i64 {
impl TryExtractFrom<Value<'_>> for EcPoint {
fn try_extract_from(cv: Value) -> Result<EcPoint, TryExtractFromError> {
match cv {
Value::GroupElement(v) => Ok((*v).clone()),
Value::GroupElement(v) => Ok(*v),
_ => Err(TryExtractFromError(format!(
"expected EcPoint, found {:?}",
cv
Expand Down

0 comments on commit ffc9269

Please sign in to comment.