Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MSM with chunks and HashMapPippenger #397

Merged
merged 18 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ lto = "thin"
incremental = true
debug-assertions = true
debug = true

# To be removed in the new release.
[patch.crates-io]
ark-std = { git = "https://github.com/arkworks-rs/std"}
1 change: 1 addition & 0 deletions ec/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ digest = { version = "0.10", default-features = false }
num-traits = { version = "0.2", default-features = false }
rayon = { version = "1", optional = true }
zeroize = { version = "1", default-features = false, features = ["zeroize_derive"] }
hashbrown = "0.11.2"

[dev-dependencies]
hashbrown = { version = "0.11.1" }
Pratyush marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
4 changes: 2 additions & 2 deletions ec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ pub trait AffineCurve:
{
type Parameters: ModelParameters<ScalarField = Self::ScalarField, BaseField = Self::BaseField>;

/// The group defined by this curve has order `h * r` where `r` is a large prime.
/// `Self::ScalarField` is the prime field defined by `r`
/// The group defined by this curve has order `h * r` where `r` is a large
/// prime. `Self::ScalarField` is the prime field defined by `r`
type ScalarField: PrimeField + SquareRootField + Into<<Self::ScalarField as PrimeField>::BigInt>;

/// The finite field over which this curve is defined.
Expand Down
44 changes: 42 additions & 2 deletions ec/src/msm/variable_base/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use ark_ff::prelude::*;
use ark_std::vec::Vec;
use ark_ff::{prelude::*, PrimeField};
use ark_std::{borrow::Borrow, iterable::Iterable, vec::Vec};
use core::ops::AddAssign;

use crate::{AffineCurve, ProjectiveCurve};

Expand Down Expand Up @@ -127,4 +128,43 @@ impl VariableBase {
total
})
}
/// Steaming multi-scalar multiplication algorithm with hard-coded chunk
/// size.
pub fn msm_chunks<G, F, I: ?Sized, J>(bases_stream: &J, scalars_stream: &I) -> G::Projective
where
G: AffineCurve<ScalarField = F>,
I: Iterable,
F: PrimeField,
I::Item: Borrow<F>,
J: Iterable,
J::Item: Borrow<G>,
{
assert!(scalars_stream.len() <= bases_stream.len());

// remove offset
let bases_init = bases_stream.iter();
let mut scalars = scalars_stream.iter();

// align the streams
// NOTE: Change skip() to iter_advance_by() when it becomes stable.
Pratyush marked this conversation as resolved.
Show resolved Hide resolved
let mut bases = bases_init.skip(bases_stream.len() - scalars_stream.len());
// .expect("bases not long enough");
Pratyush marked this conversation as resolved.
Show resolved Hide resolved
let step: usize = 1 << 20;
let mut result = G::Projective::zero();
for _ in 0..(scalars_stream.len() + step - 1) / step {
let bases_step = (&mut bases)
.take(step)
.map(|b| *b.borrow())
.collect::<Vec<_>>();
let scalars_step = (&mut scalars)
.take(step)
.map(|s| s.borrow().into_bigint())
.collect::<Vec<_>>();
result.add_assign(crate::msm::VariableBase::msm(
bases_step.as_slice(),
scalars_step.as_slice(),
));
}
result
}
}
65 changes: 64 additions & 1 deletion ec/src/msm/variable_base/stream_pippenger.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! A space-efficient implementation of Pippenger's algorithm.
//!
use crate::AffineCurve;
use ark_ff::{PrimeField, Zero};

use ark_std::{borrow::Borrow, ops::AddAssign, vec::Vec};
use hashbrown::HashMap;

/// Struct for the chunked Pippenger algorithm.
pub struct ChunkedPippenger<G: AffineCurve> {
Expand Down Expand Up @@ -65,3 +65,66 @@ impl<G: AffineCurve> ChunkedPippenger<G> {
self.result
}
}

/// Hash map struct for Pippenger algorithm.
pub struct HashMapPippenger<G: AffineCurve> {
pub buffer: HashMap<G, G::ScalarField>,
Pratyush marked this conversation as resolved.
Show resolved Hide resolved
pub result: G::Projective,
}

impl<G: AffineCurve> HashMapPippenger<G> {
/// Produce a new hash map with the maximum msm buffer size.
pub fn new(max_msm_buffer: usize) -> Self {
Self {
buffer: HashMap::with_capacity(max_msm_buffer),
result: G::Projective::zero(),
}
}

/// Add a new (base, scalar) pair into the hash map.
#[inline(always)]
pub fn add<B, S>(&mut self, base: B, scalar: S)
where
B: Borrow<G>,
S: Borrow<G::ScalarField>,
{
// update the entry, guarding the possibility that it has been already set.
let entry = self
.buffer
.entry(*base.borrow())
.or_insert(G::ScalarField::zero());
*entry += *scalar.borrow();
if self.buffer.len() == self.buffer.capacity() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@huyuncong @mmaker I have a concern about whether capacity() will run in the expected way. Rust did not promise that the capacity of the map would not grow on its own, and Rust did not promise that it will allocate exactly the capacity as specified during with_capacity.

Note: Rust's hashmap is often constructed through the RawTable here, which may specify a slightly different capacity compared with the one from with_capacity.
https://docs.rs/hashbrown/latest/src/hashbrown/raw/mod.rs.html#191

let bases = self.buffer.keys().cloned().collect::<Vec<_>>();
let scalars = self
.buffer
.values()
.map(|s| s.into_bigint())
.collect::<Vec<_>>();
self.result
.add_assign(crate::msm::variable_base::VariableBase::msm(
&bases, &scalars,
));
self.buffer.clear();
}
}

/// Update the final result with (base, scalar) pairs in the hash map.
#[inline(always)]
pub fn finalize(mut self) -> G::Projective {
if !self.buffer.is_empty() {
let bases = self.buffer.keys().cloned().collect::<Vec<_>>();
let scalars = self
.buffer
.values()
.map(|s| s.into_bigint())
.collect::<Vec<_>>();

self.result
.add_assign(crate::msm::variable_base::VariableBase::msm(
&bases, &scalars,
));
}
self.result
}
}