diff --git a/verkle-spec/src/code.rs b/verkle-spec/src/code.rs index 02508a0..b841864 100644 --- a/verkle-spec/src/code.rs +++ b/verkle-spec/src/code.rs @@ -54,14 +54,23 @@ pub fn chunkify_code(code: Vec) -> Vec { let mut leftover_push_data = 0usize; remaining_pushdata_bytes.push(leftover_push_data); - for chunk in chunked_code31.clone() { + let last_chunk_index = chunked_code31.len()-1; + // set this to true, if the last chunk had a push data instruction that + // needed another chunk + let mut last_chunk_push_data = false; + for (chunk_i, chunk) in chunked_code31.clone().enumerate() { // Case1: the left over push data is larger than the chunk size // // The left over push data can be larger than the chunk size // For example, if the last instruction was a PUSH32 and chunk size is 31 // We can compute the left over push data for this chunk as 31, the chunk size // and then the left over push data for the next chunk as 32-31=1 - if leftover_push_data > chunk.len() { + if leftover_push_data > chunk.len() { + if chunk_i == last_chunk_index { + last_chunk_push_data = true; + break + } + leftover_push_data = leftover_push_data - chunk.len(); remaining_pushdata_bytes.push(chunk.len()); continue; @@ -92,6 +101,12 @@ pub fn chunkify_code(code: Vec) -> Vec { chunked_code32.push(chunk32) } + if last_chunk_push_data { + // If the last chunk had remaining push data to be added + // we add a new chunk with 32 zeroes. This is fine + chunked_code32.push([0u8;32]) + } + chunked_code32 } // This functions returns a number which indicates how much PUSHDATA diff --git a/verkle-trie/Cargo.toml b/verkle-trie/Cargo.toml index 27967d6..cf12765 100644 --- a/verkle-trie/Cargo.toml +++ b/verkle-trie/Cargo.toml @@ -7,8 +7,9 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -bandersnatch = "0.1.1" -ipa-multipoint = { git = "https://github.com/crate-crypto/ipa_multipoint", branch = "develop" } +tempfile = "3.2.0" +ipa-multipoint = { git = "https://github.com/crate-crypto/ipa_multipoint", branch = "banderwagon_migration" } +banderwagon = { git = "https://github.com/crate-crypto/banderwagon" } ark-ff = { version = "^0.3.0", default-features = false } ark-ec = { version = "^0.3.0", default-features = false } ark-serialize = { version = "^0.3.0", default-features = false } @@ -40,9 +41,9 @@ debug-assertions = true incremental = true -[[bench]] -name = "benchmark_main" -harness = false +# [[bench]] +# name = "benchmark_main" +# harness = false [profile.test] diff --git a/verkle-trie/benches/benchmarks/precompute_scalar_mul.rs b/verkle-trie/benches/benchmarks/precompute_scalar_mul.rs index ae0689a..5a9b6e2 100644 --- a/verkle-trie/benches/benchmarks/precompute_scalar_mul.rs +++ b/verkle-trie/benches/benchmarks/precompute_scalar_mul.rs @@ -1,6 +1,6 @@ use crate::benchmarks::util::{generate_set_of_keys, KEYS_10K, PRECOMPUTED_TABLE}; use ark_ff::{Field, PrimeField}; -use bandersnatch::{EdwardsProjective, Fr}; +use banderwagon::Fr; use criterion::BenchmarkId; use criterion::{black_box, criterion_group, BatchSize, Criterion}; use verkle_db::BareMetalDiskDb; diff --git a/verkle-trie/src/committer.rs b/verkle-trie/src/committer.rs index 8cfa825..9988967 100644 --- a/verkle-trie/src/committer.rs +++ b/verkle-trie/src/committer.rs @@ -1,4 +1,4 @@ -use bandersnatch::{EdwardsProjective, Fr}; +use banderwagon::{Element, Fr}; pub mod precompute; pub mod test; @@ -10,12 +10,12 @@ pub trait Committer { // Commit to a lagrange polynomial, evaluations.len() must equal the size of the SRS at the moment //TODO: We can make this &[Fr;256] since we have committed to 256, this would force the caller // to handle the size of the slice - fn commit_lagrange(&self, evaluations: &[Fr]) -> EdwardsProjective; + fn commit_lagrange(&self, evaluations: &[Fr]) -> Element; // compute value * G for a specific generator in the SRS - fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> EdwardsProjective; + fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> Element; - fn commit_sparse(&self, val_indices: Vec<(Fr, usize)>) -> EdwardsProjective { - let mut result = EdwardsProjective::default(); + fn commit_sparse(&self, val_indices: Vec<(Fr, usize)>) -> Element { + let mut result = Element::zero(); for (value, lagrange_index) in val_indices { result += self.scalar_mul(value, lagrange_index) diff --git a/verkle-trie/src/committer/precompute.rs b/verkle-trie/src/committer/precompute.rs index 00759fd..446eb5a 100644 --- a/verkle-trie/src/committer/precompute.rs +++ b/verkle-trie/src/committer/precompute.rs @@ -1,8 +1,9 @@ use crate::committer::Committer; -use ark_ec::AffineCurve; use ark_ff::Zero; + +use banderwagon::{Element, Fr}; + use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Read, SerializationError, Write}; -use bandersnatch::{EdwardsAffine, EdwardsProjective, Fr}; #[derive(Debug, Clone, CanonicalSerialize, CanonicalDeserialize, PartialEq, Eq)] pub struct PrecomputeLagrange { @@ -13,12 +14,12 @@ pub struct PrecomputeLagrange { impl<'a> Committer for &'a PrecomputeLagrange { // If compute these points at compile time, we can // dictate that evaluations should be an array - fn commit_lagrange(&self, evaluations: &[Fr]) -> EdwardsProjective { + fn commit_lagrange(&self, evaluations: &[Fr]) -> Element { if evaluations.len() != self.num_points { panic!("wrong number of points") } - let mut result = EdwardsProjective::default(); + let mut result = Element::zero(); let scalar_table = evaluations .into_iter() @@ -29,12 +30,12 @@ impl<'a> Committer for &'a PrecomputeLagrange { // convert scalar to bytes in little endian let bytes = ark_ff::to_bytes!(scalar).unwrap(); - let partial_result: EdwardsProjective = bytes + let partial_result: Element = bytes .into_iter() .enumerate() .map(|(row, byte)| { let point = table.point(row, byte); - EdwardsProjective::from(*point) + Element::from(*point) }) .sum(); result += partial_result; @@ -42,33 +43,33 @@ impl<'a> Committer for &'a PrecomputeLagrange { result } - fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> EdwardsProjective { + fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> Element { let table = &self.inner[lagrange_index]; let bytes = ark_ff::to_bytes!(value).unwrap(); - let result: EdwardsProjective = bytes + let result: Element = bytes .into_iter() .enumerate() .map(|(row, byte)| { let point = table.point(row, byte); - EdwardsProjective::from(*point) + Element::from(*point) }) .sum(); result } } impl Committer for PrecomputeLagrange { - fn commit_lagrange(&self, evaluations: &[Fr]) -> EdwardsProjective { + fn commit_lagrange(&self, evaluations: &[Fr]) -> Element { (&self).commit_lagrange(evaluations) } - fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> EdwardsProjective { + fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> Element { (&self).scalar_mul(value, lagrange_index) } } impl PrecomputeLagrange { - pub fn precompute(points: &[EdwardsAffine]) -> Self { + pub fn precompute(points: &[Element]) -> Self { let lagrange_precomputed_points = PrecomputeLagrange::precompute_lagrange_points(points); Self { inner: lagrange_precomputed_points, @@ -76,7 +77,7 @@ impl PrecomputeLagrange { } } - fn precompute_lagrange_points(lagrange_points: &[EdwardsAffine]) -> Vec { + fn precompute_lagrange_points(lagrange_points: &[Element]) -> Vec { use rayon::prelude::*; lagrange_points .into_par_iter() @@ -86,12 +87,12 @@ impl PrecomputeLagrange { } #[derive(Debug, Clone, CanonicalSerialize, CanonicalDeserialize, PartialEq, Eq)] pub struct LagrangeTablePoints { - identity: EdwardsAffine, - matrix: Vec, + identity: Element, + matrix: Vec, } impl LagrangeTablePoints { - pub fn new(point: &EdwardsAffine) -> LagrangeTablePoints { + pub fn new(point: &Element) -> LagrangeTablePoints { let num_rows = 32u64; // We use base 256 let base_u128 = 256u128; @@ -111,11 +112,11 @@ impl LagrangeTablePoints { let flattened_rows: Vec<_> = rows.into_par_iter().flatten().collect(); LagrangeTablePoints { - identity: EdwardsAffine::default(), + identity: Element::zero(), matrix: flattened_rows, } } - pub fn point(&self, index: usize, value: u8) -> &EdwardsAffine { + pub fn point(&self, index: usize, value: u8) -> &Element { if value == 0 { return &self.identity; } @@ -123,7 +124,7 @@ impl LagrangeTablePoints { } // Computes [G_1, 2G_1, 3G_1, ... num_points * G_1] - fn compute_base_row(point: &EdwardsAffine, num_points: usize) -> Vec { + fn compute_base_row(point: &Element, num_points: usize) -> Vec { let mut row = Vec::with_capacity(num_points); row.push(*point); for i in 1..num_points { @@ -135,11 +136,8 @@ impl LagrangeTablePoints { // Given [G_1, 2G_1, 3G_1, ... num_points * G_1] and a scalar `k` // Returns [k * G_1, 2 * k * G_1, 3 * k * G_1, ... num_points * k * G_1] - fn scale_row(points: &[EdwardsAffine], scale: Fr) -> Vec { - let scaled_row: Vec = points - .into_iter() - .map(|element| element.mul(scale).into()) - .collect(); + fn scale_row(points: &[Element], scale: Fr) -> Vec { + let scaled_row: Vec = points.into_iter().map(|element| *element * scale).collect(); scaled_row } @@ -150,14 +148,13 @@ mod test { use crate::committer::precompute::LagrangeTablePoints; use crate::committer::Committer; - use ark_ec::AffineCurve; use ark_ff::{ToBytes, Zero}; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; - use bandersnatch::{EdwardsAffine, EdwardsProjective, Fr}; + use banderwagon::{Element, Fr}; #[test] fn read_write() { - let point: EdwardsAffine = EdwardsAffine::prime_subgroup_generator(); + let point = Element::prime_subgroup_generator(); let mut serialized_lagrange_table: Vec = Vec::new(); @@ -188,7 +185,7 @@ mod test { // let values: Vec<_> = (1..=degree + 1).map(|i| Fr::from(i as u128)).collect(); // let expected_comm = { -// let mut res = EdwardsProjective::zero(); +// let mut res = Element::zero(); // for (val, point) in values.iter().zip(SRS.iter()) { // res += point.mul(val.into_repr()) // } diff --git a/verkle-trie/src/committer/test.rs b/verkle-trie/src/committer/test.rs index d30b2ee..5627aab 100644 --- a/verkle-trie/src/committer/test.rs +++ b/verkle-trie/src/committer/test.rs @@ -2,22 +2,23 @@ use crate::{committer::Committer, constants::CRS}; use ark_ec::ProjectiveCurve; use ark_ff::PrimeField; use ark_ff::Zero; -use bandersnatch::{EdwardsProjective, Fr}; + +use banderwagon::{Element, Fr}; // A Basic Commit struct to be used in tests. // In production, we will use the Precomputed points #[derive(Debug, Clone, Copy)] pub struct TestCommitter; impl Committer for TestCommitter { - fn commit_lagrange(&self, evaluations: &[Fr]) -> EdwardsProjective { - let mut res = EdwardsProjective::zero(); + fn commit_lagrange(&self, evaluations: &[Fr]) -> Element { + let mut res = Element::zero(); for (val, point) in evaluations.iter().zip(CRS.G.iter()) { - res += point.mul(val.into_repr()) + res += point * val; } res } - fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> EdwardsProjective { - CRS[lagrange_index].mul(value.into_repr()) + fn scalar_mul(&self, value: Fr, lagrange_index: usize) -> Element { + CRS[lagrange_index] * value } } diff --git a/verkle-trie/src/config.rs b/verkle-trie/src/config.rs index b1028d2..db09665 100644 --- a/verkle-trie/src/config.rs +++ b/verkle-trie/src/config.rs @@ -31,8 +31,8 @@ impl VerkleConfig { // File is not already precomputed, so we pre-compute the points and store them let mut file = File::create(PRECOMPUTED_POINTS_PATH).unwrap(); - let g_aff: Vec<_> = CRS.G.iter().map(|point| point.into_affine()).collect(); - let committer = PrecomputeLagrange::precompute(&g_aff); + + let committer = PrecomputeLagrange::precompute(&CRS.G); committer.serialize_unchecked(&mut file).unwrap(); Ok(Config { db, committer }) } diff --git a/verkle-trie/src/constants.rs b/verkle-trie/src/constants.rs index 062dbff..97b381e 100644 --- a/verkle-trie/src/constants.rs +++ b/verkle-trie/src/constants.rs @@ -1,6 +1,7 @@ use ark_ff::BigInteger256; -pub use bandersnatch::Fr; -use ipa_multipoint::{lagrange_basis::PrecomputedWeights, multiproof::CRS}; +pub use banderwagon::Fr; +use ipa_multipoint::{crs::CRS, lagrange_basis::PrecomputedWeights}; +use once_cell::sync::Lazy; pub const FLUSH_BATCH: u32 = 20_000; // This library only works for a width of 256. It can be modified to work for other widths, but this is @@ -17,7 +18,6 @@ pub(crate) const TWO_POW_128: Fr = Fr::new(BigInteger256([ 1249884543737537366, ])); -use once_cell::sync::Lazy; pub static CRS: Lazy = Lazy::new(|| CRS::new(VERKLE_NODE_WIDTH, PEDERSEN_SEED)); pub static PRECOMPUTED_WEIGHTS: Lazy = @@ -27,7 +27,7 @@ pub static PRECOMPUTED_WEIGHTS: Lazy = mod tests { use super::TWO_POW_128; use ark_ff::PrimeField; - use bandersnatch::Fr; + use banderwagon::Fr; #[test] fn test_two_pow128_constant() { diff --git a/verkle-trie/src/database/meta.rs b/verkle-trie/src/database/meta.rs index f4f71cd..dfa9566 100644 --- a/verkle-trie/src/database/meta.rs +++ b/verkle-trie/src/database/meta.rs @@ -1,14 +1,14 @@ -use bandersnatch::{EdwardsProjective, Fr}; +use banderwagon::{Element, Fr}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct StemMeta { - pub C_1: EdwardsProjective, + pub C_1: Element, pub hash_c1: Fr, - pub C_2: EdwardsProjective, + pub C_2: Element, pub hash_c2: Fr, - pub stem_commitment: EdwardsProjective, + pub stem_commitment: Element, pub hash_stem_commitment: Fr, } @@ -31,13 +31,13 @@ impl std::fmt::Debug for StemMeta { } } -fn point_to_array(p: &EdwardsProjective) -> [u8; 64] { +fn point_to_array(p: &Element) -> [u8; 64] { let mut bytes = [0u8; 64]; use ark_serialize::CanonicalSerialize; p.serialize_uncompressed(&mut bytes[..]).unwrap(); bytes } -fn compress_point_to_array(p: &EdwardsProjective) -> [u8; 32] { +fn compress_point_to_array(p: &Element) -> [u8; 32] { let mut bytes = [0u8; 32]; use ark_serialize::CanonicalSerialize; p.serialize(&mut bytes[..]).unwrap(); @@ -59,12 +59,10 @@ impl StemMeta { use ark_serialize::CanonicalDeserialize; let point_bytes = &bytes[0..64 * 3]; - let C_1 = - EdwardsProjective::deserialize_uncompressed(&point_bytes[0 * 64..1 * 64]).unwrap(); - let C_2 = - EdwardsProjective::deserialize_uncompressed(&point_bytes[1 * 64..2 * 64]).unwrap(); + let C_1 = Element::deserialize_uncompressed(&point_bytes[0 * 64..1 * 64]).unwrap(); + let C_2 = Element::deserialize_uncompressed(&point_bytes[1 * 64..2 * 64]).unwrap(); let stem_commitment = - EdwardsProjective::deserialize_uncompressed(&point_bytes[2 * 64..3 * 64]).unwrap(); + Element::deserialize_uncompressed(&point_bytes[2 * 64..3 * 64]).unwrap(); let scalar_bytes = &bytes[64 * 3..]; let hash_c1 = Fr::deserialize_uncompressed(&scalar_bytes[0 * 32..1 * 32]).unwrap(); @@ -98,7 +96,7 @@ impl StemMeta { #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct BranchMeta { - pub commitment: EdwardsProjective, + pub commitment: Element, pub hash_commitment: Fr, } @@ -121,7 +119,7 @@ impl BranchMeta { pub fn zero() -> BranchMeta { use ark_ff::Zero; BranchMeta { - commitment: EdwardsProjective::zero(), + commitment: Element::zero(), hash_commitment: Fr::zero(), } } @@ -139,7 +137,7 @@ impl BranchMeta { let point_bytes = &bytes[0..64]; let scalar_bytes = &bytes[64..64 + 32]; - let commitment = EdwardsProjective::deserialize_uncompressed(point_bytes).unwrap(); + let commitment = Element::deserialize_uncompressed(point_bytes).unwrap(); let hash_commitment = Fr::deserialize_uncompressed(scalar_bytes).unwrap(); BranchMeta { diff --git a/verkle-trie/src/from_to_bytes.rs b/verkle-trie/src/from_to_bytes.rs index fd563e4..a47693e 100644 --- a/verkle-trie/src/from_to_bytes.rs +++ b/verkle-trie/src/from_to_bytes.rs @@ -1,5 +1,5 @@ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use bandersnatch::{EdwardsAffine, EdwardsProjective, Fr}; +use banderwagon::{Element, Fr}; // TODO: The only things that need to be converted to bytes are Points and scalars // so maybe we can return a [u8;32] and avoid allocating // Then use this instead of ark_serialize in the codebase @@ -10,14 +10,14 @@ pub trait FromBytes { fn from_bytes(bytes: &[u8]) -> Self; } -impl ToBytes for EdwardsProjective { +impl ToBytes for Element { fn to_bytes(&self) -> Vec { let mut bytes = [0u8; 32]; self.serialize(&mut bytes[..]).unwrap(); bytes.to_vec() } } -impl FromBytes for EdwardsProjective { +impl FromBytes for Element { fn from_bytes(bytes: &[u8]) -> Self { CanonicalDeserialize::deserialize(bytes).unwrap() } @@ -34,15 +34,3 @@ impl FromBytes for Fr { CanonicalDeserialize::deserialize(bytes).unwrap() } } -impl ToBytes for EdwardsAffine { - fn to_bytes(&self) -> Vec { - let mut bytes = [0u8; 32]; - self.serialize(&mut bytes[..]).unwrap(); - bytes.to_vec() - } -} -impl FromBytes for EdwardsAffine { - fn from_bytes(bytes: &[u8]) -> Self { - CanonicalDeserialize::deserialize(bytes).unwrap() - } -} diff --git a/verkle-trie/src/lib.rs b/verkle-trie/src/lib.rs index 69e54ed..2ec2fc5 100644 --- a/verkle-trie/src/lib.rs +++ b/verkle-trie/src/lib.rs @@ -11,7 +11,7 @@ mod trie_fuzzer; pub use config::*; pub use trie::Trie; -pub use bandersnatch::{EdwardsProjective, Fr}; +pub use banderwagon::{Element, Fr}; pub type Key = [u8; 32]; pub type Value = [u8; 32]; @@ -38,22 +38,23 @@ pub trait TrieTrait { fn root_hash(&self) -> Fr; /// Returns the root commitment of the trie - fn root_commitment(&self) -> EdwardsProjective; + fn root_commitment(&self) -> Element; /// Creates a verkle proof over many keys /// TODO: This will return a Result in the future fn create_verkle_proof(&self, key: impl Iterator) -> proof::VerkleProof; } -pub(crate) fn group_to_field(point: &EdwardsProjective) -> Fr { - use ark_ff::{PrimeField, Zero}; +// Note: This is a 2 to 1 map, but the two preimages are identified to be the same +// TODO: Create a document showing that this poses no problems +pub(crate) fn group_to_field(point: &Element) -> Fr { + use ark_ff::PrimeField; use ark_serialize::CanonicalSerialize; - if point.is_zero() { - return Fr::zero(); - } + let base_field = point.map_to_field(); + let mut bytes = [0u8; 32]; - point + base_field .serialize(&mut bytes[..]) .expect("could not serialise point into a 32 byte array"); Fr::from_le_bytes_mod_order(&bytes) @@ -72,10 +73,9 @@ mod tests { fn consistent_group_to_field() { // In python this is called commitment_to_field // print(commitment_to_field(Point(generator=True)).to_bytes(32, "little").hex()) - let expected = "37c6db79b111ea6cf47f80392239ea2bf2cc5579759b686773d5a361f7c8c50c"; - use ark_ec::ProjectiveCurve; + let expected = "d1e7de2aaea9603d5bc6c208d319596376556ecd8336671ba7670c2139772d14"; - let generator = EdwardsProjective::prime_subgroup_generator(); + let generator = Element::prime_subgroup_generator(); let mut bytes = [0u8; 32]; group_to_field(&generator) .serialize(&mut bytes[..]) diff --git a/verkle-trie/src/proof.rs b/verkle-trie/src/proof.rs index 7b5ad08..7fe7915 100644 --- a/verkle-trie/src/proof.rs +++ b/verkle-trie/src/proof.rs @@ -1,7 +1,8 @@ use crate::constants::CRS; use ark_ec::AffineCurve; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; -use bandersnatch::{EdwardsAffine, EdwardsProjective, Fr}; + +use banderwagon::Element; use ipa_multipoint::multiproof::MultiPointProof; use std::collections::{BTreeMap, BTreeSet}; @@ -164,7 +165,7 @@ pub struct UpdateHint { depths_and_ext_by_stem: BTreeMap<[u8; 31], (ExtPresent, u8)>, // This will be used to get the old commitment for a particular node // So that we can compute the delta between it and the new commitment - commitments_by_path: BTreeMap, EdwardsProjective>, + commitments_by_path: BTreeMap, Element>, other_stems_by_prefix: BTreeMap, [u8; 31]>, } @@ -173,7 +174,7 @@ pub struct VerkleProof { verification_hint: VerificationHint, // Commitments sorted by their paths and then their indices // The root is taken out when we serialise, so the verifier does not receive it - comms_sorted: Vec, + comms_sorted: Vec, // proof: MultiPointProof, } @@ -188,9 +189,9 @@ impl VerkleProof { let mut comms_sorted = Vec::new(); for _ in 0..num_comms { - let point: EdwardsAffine = CanonicalDeserialize::deserialize(&mut reader) + let point: Element = CanonicalDeserialize::deserialize(&mut reader) .map_err(|_| IOError::from(IOErrorKind::InvalidData))?; - comms_sorted.push(point.into_projective()); + comms_sorted.push(point); } let mut bytes = Vec::new(); @@ -227,7 +228,7 @@ impl VerkleProof { self, keys: Vec<[u8; 32]>, values: Vec>, - root: EdwardsProjective, + root: Element, ) -> (bool, Option) { // TODO: check the commitments are in the correct subgroup // TODO: possibly will be done with Decaf @@ -275,7 +276,7 @@ mod test { use crate::database::{memory_db::MemoryDb, ReadOnlyHigherDb}; use crate::proof::{prover, verifier}; use crate::{trie::Trie, TestConfig, TrieTrait}; - use bandersnatch::Fr; + use banderwagon::Fr; #[test] fn basic_proof_true() { diff --git a/verkle-trie/src/proof/opening_data.rs b/verkle-trie/src/proof/opening_data.rs index c70fe5d..7ad6172 100644 --- a/verkle-trie/src/proof/opening_data.rs +++ b/verkle-trie/src/proof/opening_data.rs @@ -5,7 +5,7 @@ use crate::{ proof::key_path_finder::{KeyNotFound, KeyPathFinder, KeyState}, }; use ark_ff::{One, PrimeField, Zero}; -use bandersnatch::Fr; +use banderwagon::Fr; use ipa_multipoint::lagrange_basis::LagrangeBasis; use ipa_multipoint::multiproof::{ProverQuery, VerifierQuery}; use std::{ diff --git a/verkle-trie/src/proof/stateless_updater.rs b/verkle-trie/src/proof/stateless_updater.rs index 290fcad..8878bcf 100644 --- a/verkle-trie/src/proof/stateless_updater.rs +++ b/verkle-trie/src/proof/stateless_updater.rs @@ -1,7 +1,7 @@ use crate::constants::TWO_POW_128; use crate::{committer::Committer, group_to_field, proof::ExtPresent}; use ark_ff::{One, PrimeField, Zero}; -use bandersnatch::{EdwardsProjective, Fr}; +use banderwagon::{Element, Fr}; use std::collections::{BTreeMap, HashSet}; use super::{UpdateHint, VerkleProof}; @@ -11,12 +11,12 @@ use super::{UpdateHint, VerkleProof}; // and to refactor panics into error variants pub fn verify_and_update( proof: VerkleProof, - root: EdwardsProjective, + root: Element, keys: Vec<[u8; 32]>, values: Vec>, updated_values: Vec>, commiter: C, -) -> Result { +) -> Result { // TODO: replace Clone with references if possible let (ok, update_hint) = proof.check(keys.clone(), values.clone(), root); if !ok { @@ -33,9 +33,9 @@ pub(crate) fn update_root( keys: Vec<[u8; 32]>, values: Vec>, updated_values: Vec>, - root: EdwardsProjective, + root: Element, committer: C, -) -> EdwardsProjective { +) -> Element { assert_eq!(values.len(), updated_values.len()); assert_eq!(keys.len(), updated_values.len()); @@ -86,8 +86,7 @@ pub(crate) fn update_root( // TODO: Prefix can be &'a [u8] instead of Vec which avoids unnecessary allocations... This may be unneeded when we switch to SmallVec32 let mut updated_stems_by_prefix: BTreeMap, HashSet<[u8; 31]>> = BTreeMap::new(); - let mut updated_commitents_by_stem: BTreeMap<[u8; 31], (EdwardsProjective, Fr)> = - BTreeMap::new(); + let mut updated_commitents_by_stem: BTreeMap<[u8; 31], (Element, Fr)> = BTreeMap::new(); for (stem, suffix_update) in updated_stems { let (ext_pres, depth) = hint.depths_and_ext_by_stem[&stem]; @@ -100,8 +99,8 @@ pub(crate) fn update_root( if ext_pres == ExtPresent::Present { let ext_path = stem[0..depth as usize].to_vec(); // It is the prefix - let mut C_1_delta_update = EdwardsProjective::default(); - let mut C_2_delta_update = EdwardsProjective::default(); + let mut C_1_delta_update = Element::zero(); + let mut C_2_delta_update = Element::zero(); // TODO abstract this into a function, since it's duplicated for (suffix, (old_value, new_value)) in suffix_update { @@ -164,7 +163,7 @@ pub(crate) fn update_root( hash_c2_delta = hash_c2_new - hash_c2_old; } - let mut stem_comm_update = EdwardsProjective::default(); + let mut stem_comm_update = Element::zero(); stem_comm_update += committer.scalar_mul(hash_c1_delta, 2); stem_comm_update += committer.scalar_mul(hash_c2_delta, 3); @@ -187,8 +186,8 @@ pub(crate) fn update_root( // // This is similar to the case of ExtPres::Present, except that the old_value is zero, so we can ignore it // TODO we could take this for loop out of the if statement and then use the if statement for the rest - let mut C_1 = EdwardsProjective::zero(); - let mut C_2 = EdwardsProjective::zero(); + let mut C_1 = Element::zero(); + let mut C_2 = Element::zero(); for (suffix, (old_value, new_value)) in suffix_update { assert!(old_value.is_none(), "since the extension was not present in the trie, the suffix cannot have any previous values"); @@ -306,27 +305,27 @@ pub(crate) fn update_root( // as if we were starting from a tree of depth=0 fn build_subtree( prefix: Vec, - elements: Vec<([u8; 31], EdwardsProjective)>, + elements: Vec<([u8; 31], Element)>, committer: &C, -) -> EdwardsProjective { +) -> Element { let mut tree: BTreeMap, Node> = BTreeMap::new(); // Insert the root tree.insert( vec![], Node::Inner(InnerNode { - commitment: EdwardsProjective::default(), + commitment: Element::zero(), }), ); #[derive(Debug, Clone)] struct InnerNode { - commitment: EdwardsProjective, + commitment: Element, } #[derive(Debug, Clone, Copy)] struct Stem { id: [u8; 31], - commitment: EdwardsProjective, + commitment: Element, } #[derive(Debug, Clone)] enum Node { @@ -353,7 +352,7 @@ fn build_subtree( Node::Stem(_) => panic!("found stem"), } } - fn commitment(&self) -> EdwardsProjective { + fn commitment(&self) -> Element { match self { Node::Inner(inner) => inner.commitment, Node::Stem(stem) => stem.commitment, @@ -405,7 +404,7 @@ fn build_subtree( // We now need to add a bunch of new inner nodes for each index that these two stems share // The current node which is a stem will be shifted down the tree, the node that was pointing to this stem will now point to an inner node let mut new_inner_node = InnerNode { - commitment: EdwardsProjective::default(), + commitment: Element::zero(), }; let stem_to_innernode_path = path.clone(); // Save the path of the node which was a stem and is now a inner node (currently an edge case) tree.insert(path.clone(), Node::Inner(new_inner_node)); // This inner node now replaces the old_stem @@ -415,7 +414,7 @@ fn build_subtree( depth += 1; path.push(index); new_inner_node = InnerNode { - commitment: EdwardsProjective::default(), + commitment: Element::zero(), }; tree.insert(path.clone(), Node::Inner(new_inner_node)); } @@ -498,12 +497,12 @@ fn build_subtree( } struct SparseVerkleTree { - root: EdwardsProjective, - updated_commitments_by_path: BTreeMap, EdwardsProjective>, + root: Element, + updated_commitments_by_path: BTreeMap, Element>, } impl SparseVerkleTree { - fn new(root: EdwardsProjective) -> SparseVerkleTree { + fn new(root: Element) -> SparseVerkleTree { SparseVerkleTree { root, updated_commitments_by_path: BTreeMap::default(), @@ -512,7 +511,7 @@ impl SparseVerkleTree { fn update_prefix( &mut self, - commitments_by_path: &BTreeMap, EdwardsProjective>, + commitments_by_path: &BTreeMap, Element>, committer: &C, mut prefix: Vec, old_value: Fr, diff --git a/verkle-trie/src/proof/verifier.rs b/verkle-trie/src/proof/verifier.rs index c3ded08..1c1c311 100644 --- a/verkle-trie/src/proof/verifier.rs +++ b/verkle-trie/src/proof/verifier.rs @@ -5,7 +5,7 @@ use crate::{ proof::{ExtPresent, UpdateHint}, }; use ark_ff::{One, PrimeField, Zero}; -use bandersnatch::{EdwardsProjective, Fr}; +use banderwagon::{Element, Fr}; use ipa_multipoint::multiproof::VerifierQuery; use std::{ collections::{BTreeMap, BTreeSet}, @@ -17,7 +17,7 @@ pub fn create_verifier_queries( proof: VerkleProof, keys: Vec<[u8; 32]>, values: Vec>, - root: EdwardsProjective, + root: Element, ) -> Option<(Vec, UpdateHint)> { let commitments_sorted_by_path: Vec<_> = std::iter::once(root).chain(proof.comms_sorted).collect(); @@ -185,7 +185,7 @@ pub fn create_verifier_queries( assert!(proof.verification_hint.diff_stem_no_proof == other_stems_used); assert!(commitments_sorted_by_path.len() == all_paths.len()); - let commitments_by_path: BTreeMap, EdwardsProjective> = all_paths + let commitments_by_path: BTreeMap, Element> = all_paths .into_iter() .zip(commitments_sorted_by_path) .map(|(path, comm)| (path, comm)) diff --git a/verkle-trie/src/trie.rs b/verkle-trie/src/trie.rs index 5d0bbda..09d0368 100644 --- a/verkle-trie/src/trie.rs +++ b/verkle-trie/src/trie.rs @@ -3,7 +3,8 @@ use crate::database::{BranchMeta, Flush, Meta, ReadWriteHigherDb, StemMeta}; use crate::{committer::Committer, Config}; use crate::{group_to_field, TrieTrait}; use ark_ff::{PrimeField, Zero}; -use bandersnatch::{EdwardsProjective, Fr}; + +use banderwagon::{Element, Fr}; #[derive(Debug, Clone)] // The trie implements the logic to insert values, fetch values, and create paths to said values @@ -43,7 +44,7 @@ impl TrieTrait for Trie { prover::create_verkle_proof(&self.storage, keys.collect()) } - fn root_commitment(&self) -> EdwardsProjective { + fn root_commitment(&self) -> Element { // TODO: This is needed for proofs, can we remove the root hash as the root? let root_node = self.storage.get_branch_meta(&vec![]).unwrap(); return root_node.commitment; @@ -604,10 +605,10 @@ impl Trie