diff --git a/coins/monero/src/ringct/bulletproofs/core.rs b/coins/monero/src/ringct/bulletproofs/core.rs index 04852ecc..e1ad6bf8 100644 --- a/coins/monero/src/ringct/bulletproofs/core.rs +++ b/coins/monero/src/ringct/bulletproofs/core.rs @@ -4,6 +4,8 @@ use lazy_static::lazy_static; use rand_core::{RngCore, CryptoRng}; +use curve25519_dalek::{scalar::Scalar as DalekScalar, edwards::EdwardsPoint as DalekPoint}; + use group::{ff::Field, Group}; use dalek_ff_group::{Scalar, EdwardsPoint}; @@ -11,18 +13,16 @@ use multiexp::multiexp; use crate::{ H as DALEK_H, Commitment, random_scalar as dalek_random, hash, hash_to_scalar as dalek_hash, - ringct::{ - hash_to_point::raw_hash_to_point, - bulletproofs::{scalar_vector::*, Bulletproofs}, - }, + ringct::{hash_to_point::raw_hash_to_point, bulletproofs::scalar_vector::*}, serialize::write_varint, }; -pub(crate) const MAX_M: usize = 16; -const N: usize = 64; -const MAX_MN: usize = MAX_M * N; +// Bring things into ff/group +lazy_static! { + static ref INV_EIGHT: Scalar = Scalar::from(8u8).invert().unwrap(); + static ref H: EdwardsPoint = EdwardsPoint(*DALEK_H); +} -// Wrap random_scalar and hash_to_scalar into dalek_ff_group fn random_scalar(rng: &mut R) -> Scalar { Scalar(dalek_random(rng)) } @@ -31,26 +31,42 @@ fn hash_to_scalar(data: &[u8]) -> Scalar { Scalar(dalek_hash(data)) } -fn generator(i: usize) -> EdwardsPoint { - let mut transcript = (*H).compress().to_bytes().to_vec(); - transcript.extend(b"bulletproof"); - write_varint(&i.try_into().unwrap(), &mut transcript).unwrap(); - EdwardsPoint(raw_hash_to_point(hash(&transcript))) -} +// Components common between variants +pub(crate) const MAX_M: usize = 16; +const N: usize = 64; +const MAX_MN: usize = MAX_M * N; lazy_static! { - static ref INV_EIGHT: Scalar = Scalar::from(8u8).invert().unwrap(); - static ref H: EdwardsPoint = EdwardsPoint(*DALEK_H); - pub(crate) static ref ONE_N: ScalarVector = ScalarVector(vec![Scalar::one(); MAX_N]); - pub(crate) static ref TWO_N: ScalarVector = ScalarVector::powers(Scalar::from(2u8), MAX_N); - pub(crate) static ref IP12: Scalar = inner_product(&ONE_N, &TWO_N); - static ref H_i: Vec = (0 .. MAX_MN).map(|g| generator(g * 2)).collect(); - static ref G_i: Vec = (0 .. MAX_MN).map(|g| generator((g * 2) + 1)).collect(); + static ref ONE_N: ScalarVector = ScalarVector(vec![Scalar::one(); N]); + static ref TWO_N: ScalarVector = ScalarVector::powers(Scalar::from(2u8), N); + static ref IP12: Scalar = inner_product(&ONE_N, &TWO_N); } -pub(crate) fn vector_exponent(a: &ScalarVector, b: &ScalarVector) -> EdwardsPoint { +struct Generators { + G: Vec, + H: Vec, +} + +fn generators_core(prefix: &'static [u8]) -> Generators { + let mut res = Generators { G: Vec::with_capacity(MAX_MN), H: Vec::with_capacity(MAX_MN) }; + for i in 0 .. MAX_MN { + let i = 2 * i; + + let mut even = (*H).compress().to_bytes().to_vec(); + even.extend(prefix); + let mut odd = even.clone(); + + write_varint(&i.try_into().unwrap(), &mut even).unwrap(); + write_varint(&(i + 1).try_into().unwrap(), &mut odd).unwrap(); + res.H.push(EdwardsPoint(raw_hash_to_point(hash(&even)))); + res.G.push(EdwardsPoint(raw_hash_to_point(hash(&odd)))); + } + res +} + +fn vector_exponent(generators: &Generators, a: &ScalarVector, b: &ScalarVector) -> EdwardsPoint { debug_assert_eq!(a.len(), b.len()); - (a * &G_i[.. a.len()]) + (b * &H_i[.. b.len()]) + (a * &generators.G[.. a.len()]) + (b * &generators.H[.. b.len()]) } fn hash_cache(cache: &mut Scalar, mash: &[[u8; 32]]) -> Scalar { @@ -61,13 +77,7 @@ fn hash_cache(cache: &mut Scalar, mash: &[[u8; 32]]) -> Scalar { *cache } -pub(crate) fn prove( - rng: &mut R, - commitments: &[Commitment], -) -> Bulletproofs { - let sv = ScalarVector(commitments.iter().cloned().map(|c| Scalar::from(c.amount)).collect()); - let gamma = ScalarVector(commitments.iter().cloned().map(|c| Scalar(c.mask)).collect()); - +fn MN(outputs: usize) -> (usize, usize, usize) { let logN = 6; debug_assert_eq!(N, 1 << logN); @@ -75,14 +85,18 @@ pub(crate) fn prove( let mut M; while { M = 1 << logM; - (M <= MAX_M) && (M < sv.len()) + (M <= MAX_M) && (M < outputs) } { logM += 1; } - let logMN = logM + logN; - let MN = M * N; + (logM + logN, M, M * N) +} +fn bit_decompose(commitments: &[Commitment]) -> (ScalarVector, ScalarVector) { + let (_, M, MN) = MN(commitments.len()); + + let sv = ScalarVector(commitments.iter().cloned().map(|c| Scalar::from(c.amount)).collect()); let mut aL = ScalarVector::new(MN); let mut aR = ScalarVector::new(MN); @@ -96,18 +110,85 @@ pub(crate) fn prove( } } - // Commitments * INV_EIGHT - let V = commitments.iter().map(|c| EdwardsPoint(c.calculate()) * *INV_EIGHT).collect::>(); - let mut cache = - hash_to_scalar(&V.iter().flat_map(|V| V.compress().to_bytes()).collect::>()); + (aL, aR) +} +fn hash_commitments(commitments: &[Commitment]) -> Scalar { + let V = commitments.iter().map(|c| EdwardsPoint(c.calculate()) * *INV_EIGHT).collect::>(); + hash_to_scalar(&V.iter().flat_map(|V| V.compress().to_bytes()).collect::>()) +} + +fn alpha( + rng: &mut R, + generators: &Generators, + aL: &ScalarVector, + aR: &ScalarVector, +) -> (Scalar, EdwardsPoint) { let alpha = random_scalar(&mut *rng); - let A = (vector_exponent(&aL, &aR) + (EdwardsPoint::generator() * alpha)) * *INV_EIGHT; + (alpha, (vector_exponent(generators, aL, aR) + (EdwardsPoint::generator() * alpha)) * *INV_EIGHT) +} + +// Bulletproofs-specific +lazy_static! { + static ref GENERATORS: Generators = generators_core(b"bulletproof"); +} + +// Bulletproofs+-specific +lazy_static! { + static ref GENERATORS_PLUS: Generators = generators_core(b"bulletproof_plus"); + static ref TRANSCRIPT_PLUS: EdwardsPoint = + EdwardsPoint(raw_hash_to_point(hash(b"bulletproof_plus_transcript"))); +} + +fn even_powers_sum(x: Scalar, pow: usize) -> Scalar { + debug_assert!(pow != 0); + // Verify pow is a power of two + debug_assert_eq!(((pow - 1) & pow), 0); + + let xsq = x * x; + let mut res = xsq; + + let mut prev = 2; + while prev < pow { + res += res * xsq; + prev += 2; + } + + res +} + +// Types for all Bulletproofs +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum Bulletproofs { + Original { + A: DalekPoint, + S: DalekPoint, + T1: DalekPoint, + T2: DalekPoint, + taux: DalekScalar, + mu: DalekScalar, + L: Vec, + R: Vec, + a: DalekScalar, + b: DalekScalar, + t: DalekScalar, + }, +} + +pub(crate) fn prove( + rng: &mut R, + commitments: &[Commitment], +) -> Bulletproofs { + let (logMN, M, MN) = MN(commitments.len()); + + let (aL, aR) = bit_decompose(commitments); + let mut cache = hash_commitments(commitments); + let (alpha, A) = alpha(rng, &GENERATORS, &aL, &aR); let (sL, sR) = ScalarVector((0 .. (MN * 2)).map(|_| random_scalar(&mut *rng)).collect::>()).split(); let rho = random_scalar(&mut *rng); - let S = (vector_exponent(&sL, &sR) + (EdwardsPoint::generator() * rho)) * *INV_EIGHT; + let S = (vector_exponent(&GENERATORS, &sL, &sR) + (EdwardsPoint::generator() * rho)) * *INV_EIGHT; let y = hash_cache(&mut cache, &[A.compress().to_bytes(), S.compress().to_bytes()]); let mut cache = hash_to_scalar(&y.to_bytes()); @@ -140,8 +221,9 @@ pub(crate) fn prove( let x = hash_cache(&mut cache, &[z.to_bytes(), T1.compress().to_bytes(), T2.compress().to_bytes()]); + let gamma = ScalarVector(commitments.iter().cloned().map(|c| Scalar(c.mask)).collect()); let mut taux = (tau2 * (x * x)) + (tau1 * x); - for i in 1 ..= sv.len() { + for i in 1 ..= gamma.len() { taux += zpow[i + 1] * gamma[i - 1]; } let mu = (x * rho) + alpha; @@ -159,8 +241,8 @@ pub(crate) fn prove( let yinv = y.invert().unwrap(); let yinvpow = ScalarVector::powers(yinv, MN); - let mut G_proof = G_i[.. a.len()].to_vec(); - let mut H_proof = H_i[.. a.len()].to_vec(); + let mut G_proof = GENERATORS.G[.. a.len()].to_vec(); + let mut H_proof = GENERATORS.H[.. a.len()].to_vec(); H_proof.iter_mut().zip(yinvpow.0.iter()).for_each(|(this_H, yinvpow)| *this_H *= yinvpow); let U = *H * x_ip; @@ -212,7 +294,7 @@ pub(crate) fn prove( } } - Bulletproofs { + Bulletproofs::Original { A: *A, S: *S, T1: *T1, diff --git a/coins/monero/src/ringct/bulletproofs/mod.rs b/coins/monero/src/ringct/bulletproofs/mod.rs index 388fdfd7..e1d1d815 100644 --- a/coins/monero/src/ringct/bulletproofs/mod.rs +++ b/coins/monero/src/ringct/bulletproofs/mod.rs @@ -2,33 +2,18 @@ use rand_core::{RngCore, CryptoRng}; -use curve25519_dalek::{scalar::Scalar, edwards::EdwardsPoint}; +use curve25519_dalek::edwards::EdwardsPoint; use crate::{Commitment, wallet::TransactionError, serialize::*}; pub(crate) mod scalar_vector; mod core; -pub(crate) use self::core::MAX_M; -use self::core::prove; +pub(crate) use self::core::Bulletproofs; +use self::core::{MAX_M, prove}; pub(crate) const MAX_OUTPUTS: usize = MAX_M; -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct Bulletproofs { - pub A: EdwardsPoint, - pub S: EdwardsPoint, - pub T1: EdwardsPoint, - pub T2: EdwardsPoint, - pub taux: Scalar, - pub mu: Scalar, - pub L: Vec, - pub R: Vec, - pub a: Scalar, - pub b: Scalar, - pub t: Scalar, -} - impl Bulletproofs { pub(crate) fn fee_weight(outputs: usize) -> usize { let proofs = 6 + usize::try_from(usize::BITS - (outputs - 1).leading_zeros()).unwrap(); @@ -44,7 +29,7 @@ impl Bulletproofs { len + clawback } - pub fn new( + pub fn prove( rng: &mut R, outputs: &[Commitment], ) -> Result { @@ -59,17 +44,21 @@ impl Bulletproofs { w: &mut W, specific_write_vec: F, ) -> std::io::Result<()> { - write_point(&self.A, w)?; - write_point(&self.S, w)?; - write_point(&self.T1, w)?; - write_point(&self.T2, w)?; - write_scalar(&self.taux, w)?; - write_scalar(&self.mu, w)?; - specific_write_vec(&self.L, w)?; - specific_write_vec(&self.R, w)?; - write_scalar(&self.a, w)?; - write_scalar(&self.b, w)?; - write_scalar(&self.t, w) + match self { + Bulletproofs::Original { A, S, T1, T2, taux, mu, L, R, a, b, t } => { + write_point(A, w)?; + write_point(S, w)?; + write_point(T1, w)?; + write_point(T2, w)?; + write_scalar(taux, w)?; + write_scalar(mu, w)?; + specific_write_vec(L, w)?; + specific_write_vec(R, w)?; + write_scalar(a, w)?; + write_scalar(b, w)?; + write_scalar(t, w) + } + } } pub fn signature_serialize(&self, w: &mut W) -> std::io::Result<()> { @@ -81,7 +70,7 @@ impl Bulletproofs { } pub fn deserialize(r: &mut R) -> std::io::Result { - let bp = Bulletproofs { + Ok(Bulletproofs::Original { A: read_point(r)?, S: read_point(r)?, T1: read_point(r)?, @@ -93,11 +82,6 @@ impl Bulletproofs { a: read_scalar(r)?, b: read_scalar(r)?, t: read_scalar(r)?, - }; - - if bp.L.len() != bp.R.len() { - Err(std::io::Error::new(std::io::ErrorKind::Other, "mismatched L/R len"))?; - } - Ok(bp) + }) } } diff --git a/coins/monero/src/ringct/bulletproofs/scalar_vector.rs b/coins/monero/src/ringct/bulletproofs/scalar_vector.rs index 53b1c73e..51fd6065 100644 --- a/coins/monero/src/ringct/bulletproofs/scalar_vector.rs +++ b/coins/monero/src/ringct/bulletproofs/scalar_vector.rs @@ -50,19 +50,20 @@ impl ScalarVector { } pub(crate) fn powers(x: Scalar, len: usize) -> ScalarVector { - let mut res = Vec::with_capacity(len); - if len == 0 { - return ScalarVector(res); - } + debug_assert!(len != 0); + let mut res = Vec::with_capacity(len); res.push(Scalar::one()); for i in 1 .. len { res.push(res[i - 1] * x); } - ScalarVector(res) } + pub(crate) fn sum(mut self) -> Scalar { + self.0.drain(..).sum() + } + pub(crate) fn len(&self) -> usize { self.0.len() } @@ -81,7 +82,11 @@ impl Index for ScalarVector { } pub(crate) fn inner_product(a: &ScalarVector, b: &ScalarVector) -> Scalar { - (a * b).0.drain(..).sum() + (a * b).sum() +} + +pub(crate) fn weighted_inner_product(a: &ScalarVector, b: &ScalarVector, y: Scalar) -> Scalar { + (a * b * ScalarVector::powers(y, a.len())).sum() } impl Mul<&[EdwardsPoint]> for &ScalarVector { diff --git a/coins/monero/src/wallet/send/mod.rs b/coins/monero/src/wallet/send/mod.rs index f1860c34..e994662f 100644 --- a/coins/monero/src/wallet/send/mod.rs +++ b/coins/monero/src/wallet/send/mod.rs @@ -329,7 +329,7 @@ impl SignableTransaction { ), ); - let mut tx = self.prepare_transaction(&commitments, Bulletproofs::new(rng, &commitments)?); + let mut tx = self.prepare_transaction(&commitments, Bulletproofs::prove(rng, &commitments)?); let signable = prepare_inputs(rng, rpc, &self.inputs, spend, &mut tx).await?; diff --git a/coins/monero/src/wallet/send/multisig.rs b/coins/monero/src/wallet/send/multisig.rs index 61285bbf..b5b58956 100644 --- a/coins/monero/src/wallet/send/multisig.rs +++ b/coins/monero/src/wallet/send/multisig.rs @@ -301,7 +301,7 @@ impl SignMachine for TransactionSignMachine { self.signable.prepare_transaction( &commitments, - Bulletproofs::new( + Bulletproofs::prove( &mut ChaCha12Rng::from_seed(self.transcript.rng_seed(b"bulletproofs")), &commitments, )