mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-09 12:49:23 +00:00
Utilize zeroize (#76)
* Apply Zeroize to nonces used in Bulletproofs Also makes bit decomposition constant time for a given amount of outputs. * Fix nonce reuse for single-signer CLSAG * Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data * Zeroize private keys and nonces * Merge prepare_outputs and prepare_transactions * Ensure CLSAG is constant time * Pass by borrow where needed, bug fixes The past few commitments have been one in-progress chunk which I've broken up as best read. * Add Zeroize to FROST structs Still needs to zeroize internally, yet next step. Not quite as aggressive as Monero, partially due to the limitations of HashMaps, partially due to less concern about metadata, yet does still delete a few smaller items of metadata (group key, context string...). * Remove Zeroize from most Monero multisig structs These structs largely didn't have private data, just fields with private data, yet those fields implemented ZeroizeOnDrop making them already covered. While there is still traces of the transaction left in RAM, fully purging that was never the intent. * Use Zeroize within dleq bitvec doesn't offer Zeroize, so a manual zeroing has been implemented. * Use Zeroize for random_nonce It isn't perfect, due to the inability to zeroize the digest, and due to kp256 requiring a few transformations. It does the best it can though. Does move the per-curve random_nonce to a provided one, which is allowed as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231. * Use Zeroize on FROST keygen/signing * Zeroize constant time multiexp. * Correct when FROST keygen zeroizes * Move the FROST keys Arc into FrostKeys Reduces amount of instances in memory. * Manually implement Debug for FrostCore to not leak the secret share * Misc bug fixes * clippy + multiexp test bug fixes * Correct FROST key gen share summation It leaked our own share for ourself. * Fix cross-group DLEq tests
This commit is contained in:
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -1376,6 +1376,7 @@ dependencies = [
|
|||||||
"group",
|
"group",
|
||||||
"rand_core 0.6.3",
|
"rand_core 0.6.3",
|
||||||
"subtle",
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1538,6 +1539,7 @@ dependencies = [
|
|||||||
"multiexp",
|
"multiexp",
|
||||||
"rand_core 0.6.3",
|
"rand_core 0.6.3",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4534,6 +4536,7 @@ dependencies = [
|
|||||||
"rand_core 0.6.3",
|
"rand_core 0.6.3",
|
||||||
"sha2 0.10.2",
|
"sha2 0.10.2",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4592,6 +4595,7 @@ dependencies = [
|
|||||||
"thiserror",
|
"thiserror",
|
||||||
"tiny-keccak",
|
"tiny-keccak",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4638,6 +4642,7 @@ dependencies = [
|
|||||||
"group",
|
"group",
|
||||||
"k256",
|
"k256",
|
||||||
"rand_core 0.6.3",
|
"rand_core 0.6.3",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ rand_chacha = { version = "0.3", optional = true }
|
|||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
rand_distr = "0.4"
|
rand_distr = "0.4"
|
||||||
|
|
||||||
|
zeroize = { version = "1.3", features = ["zeroize_derive"] }
|
||||||
subtle = "2.4"
|
subtle = "2.4"
|
||||||
|
|
||||||
tiny-keccak = { version = "2", features = ["keccak"] }
|
tiny-keccak = { version = "2", features = ["keccak"] }
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ use std::io::Read;
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::{scalar::Scalar, edwards::EdwardsPoint};
|
use curve25519_dalek::{scalar::Scalar, edwards::EdwardsPoint};
|
||||||
|
|
||||||
use group::{Group, GroupEncoding};
|
use group::{Group, GroupEncoding};
|
||||||
@@ -29,7 +31,7 @@ fn transcript() -> RecommendedTranscript {
|
|||||||
pub(crate) fn write_dleq<R: RngCore + CryptoRng>(
|
pub(crate) fn write_dleq<R: RngCore + CryptoRng>(
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
H: EdwardsPoint,
|
H: EdwardsPoint,
|
||||||
x: Scalar,
|
mut x: Scalar,
|
||||||
) -> Vec<u8> {
|
) -> Vec<u8> {
|
||||||
let mut res = Vec::with_capacity(64);
|
let mut res = Vec::with_capacity(64);
|
||||||
DLEqProof::prove(
|
DLEqProof::prove(
|
||||||
@@ -45,6 +47,7 @@ pub(crate) fn write_dleq<R: RngCore + CryptoRng>(
|
|||||||
)
|
)
|
||||||
.serialize(&mut res)
|
.serialize(&mut res)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
x.zeroize();
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use tiny_keccak::{Hasher, Keccak};
|
use tiny_keccak::{Hasher, Keccak};
|
||||||
|
|
||||||
use curve25519_dalek::{
|
use curve25519_dalek::{
|
||||||
@@ -25,7 +27,7 @@ pub mod wallet;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
#[allow(non_camel_case_types)]
|
#[allow(non_camel_case_types)]
|
||||||
pub enum Protocol {
|
pub enum Protocol {
|
||||||
Unsupported,
|
Unsupported,
|
||||||
@@ -61,7 +63,7 @@ lazy_static! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct Commitment {
|
pub struct Commitment {
|
||||||
pub mask: Scalar,
|
pub mask: Scalar,
|
||||||
pub amount: u64,
|
pub amount: u64,
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use subtle::{Choice, ConditionallySelectable};
|
||||||
|
|
||||||
use curve25519_dalek::edwards::EdwardsPoint as DalekPoint;
|
use curve25519_dalek::edwards::EdwardsPoint as DalekPoint;
|
||||||
|
|
||||||
use group::{ff::Field, Group};
|
use group::{ff::Field, Group};
|
||||||
@@ -99,11 +101,12 @@ pub(crate) fn bit_decompose(commitments: &[Commitment]) -> (ScalarVector, Scalar
|
|||||||
|
|
||||||
for j in 0 .. M {
|
for j in 0 .. M {
|
||||||
for i in (0 .. N).rev() {
|
for i in (0 .. N).rev() {
|
||||||
if (j < sv.len()) && ((sv[j][i / 8] & (1u8 << (i % 8))) != 0) {
|
let mut bit = Choice::from(0);
|
||||||
aL.0[(j * N) + i] = Scalar::one();
|
if j < sv.len() {
|
||||||
} else {
|
bit = Choice::from((sv[j][i / 8] >> (i % 8)) & 1);
|
||||||
aR.0[(j * N) + i] = -Scalar::one();
|
|
||||||
}
|
}
|
||||||
|
aL.0[(j * N) + i] = Scalar::conditional_select(&Scalar::zero(), &Scalar::one(), bit);
|
||||||
|
aR.0[(j * N) + i] = Scalar::conditional_select(&-Scalar::one(), &Scalar::zero(), bit);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::edwards::EdwardsPoint;
|
use curve25519_dalek::edwards::EdwardsPoint;
|
||||||
use multiexp::BatchVerifier;
|
use multiexp::BatchVerifier;
|
||||||
|
|
||||||
@@ -73,7 +75,7 @@ impl Bulletproofs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn batch_verify<ID: Copy, R: RngCore + CryptoRng>(
|
pub fn batch_verify<ID: Copy + Zeroize, R: RngCore + CryptoRng>(
|
||||||
&self,
|
&self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
verifier: &mut BatchVerifier<ID, dalek_ff_group::EdwardsPoint>,
|
verifier: &mut BatchVerifier<ID, dalek_ff_group::EdwardsPoint>,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::{scalar::Scalar as DalekScalar, edwards::EdwardsPoint as DalekPoint};
|
use curve25519_dalek::{scalar::Scalar as DalekScalar, edwards::EdwardsPoint as DalekPoint};
|
||||||
|
|
||||||
use group::{ff::Field, Group};
|
use group::{ff::Field, Group};
|
||||||
@@ -47,11 +49,12 @@ impl OriginalStruct {
|
|||||||
|
|
||||||
let (aL, aR) = bit_decompose(commitments);
|
let (aL, aR) = bit_decompose(commitments);
|
||||||
let (mut cache, _) = hash_commitments(commitments.iter().map(Commitment::calculate));
|
let (mut cache, _) = hash_commitments(commitments.iter().map(Commitment::calculate));
|
||||||
let (alpha, A) = alpha_rho(&mut *rng, &GENERATORS, &aL, &aR);
|
|
||||||
|
|
||||||
let (sL, sR) =
|
let (sL, sR) =
|
||||||
ScalarVector((0 .. (MN * 2)).map(|_| Scalar::random(&mut *rng)).collect::<Vec<_>>()).split();
|
ScalarVector((0 .. (MN * 2)).map(|_| Scalar::random(&mut *rng)).collect::<Vec<_>>()).split();
|
||||||
let (rho, S) = alpha_rho(&mut *rng, &GENERATORS, &sL, &sR);
|
|
||||||
|
let (mut alpha, A) = alpha_rho(&mut *rng, &GENERATORS, &aL, &aR);
|
||||||
|
let (mut rho, S) = alpha_rho(&mut *rng, &GENERATORS, &sL, &sR);
|
||||||
|
|
||||||
let y = hash_cache(&mut cache, &[A.compress().to_bytes(), S.compress().to_bytes()]);
|
let y = hash_cache(&mut cache, &[A.compress().to_bytes(), S.compress().to_bytes()]);
|
||||||
let mut cache = hash_to_scalar(&y.to_bytes());
|
let mut cache = hash_to_scalar(&y.to_bytes());
|
||||||
@@ -72,23 +75,33 @@ impl OriginalStruct {
|
|||||||
let r0 = (&(aR + z) * &yMN) + ScalarVector(zero_twos);
|
let r0 = (&(aR + z) * &yMN) + ScalarVector(zero_twos);
|
||||||
let r1 = yMN * sR;
|
let r1 = yMN * sR;
|
||||||
|
|
||||||
let t1 = inner_product(&l0, &r1) + inner_product(&l1, &r0);
|
let (T1, T2, x, mut taux) = {
|
||||||
let t2 = inner_product(&l1, &r1);
|
let t1 = inner_product(&l0, &r1) + inner_product(&l1, &r0);
|
||||||
|
let t2 = inner_product(&l1, &r1);
|
||||||
|
|
||||||
let tau1 = Scalar::random(&mut *rng);
|
let mut tau1 = Scalar::random(&mut *rng);
|
||||||
let tau2 = Scalar::random(rng);
|
let mut tau2 = Scalar::random(rng);
|
||||||
|
|
||||||
let T1 = prove_multiexp(&[(t1, *H), (tau1, EdwardsPoint::generator())]);
|
let T1 = prove_multiexp(&[(t1, *H), (tau1, EdwardsPoint::generator())]);
|
||||||
let T2 = prove_multiexp(&[(t2, *H), (tau2, EdwardsPoint::generator())]);
|
let T2 = prove_multiexp(&[(t2, *H), (tau2, EdwardsPoint::generator())]);
|
||||||
|
|
||||||
let x =
|
let x =
|
||||||
hash_cache(&mut cache, &[z.to_bytes(), T1.compress().to_bytes(), T2.compress().to_bytes()]);
|
hash_cache(&mut cache, &[z.to_bytes(), T1.compress().to_bytes(), T2.compress().to_bytes()]);
|
||||||
|
|
||||||
|
let taux = (tau2 * (x * x)) + (tau1 * x);
|
||||||
|
|
||||||
|
tau1.zeroize();
|
||||||
|
tau2.zeroize();
|
||||||
|
(T1, T2, x, taux)
|
||||||
|
};
|
||||||
|
|
||||||
|
let mu = (x * rho) + alpha;
|
||||||
|
alpha.zeroize();
|
||||||
|
rho.zeroize();
|
||||||
|
|
||||||
let mut taux = (tau2 * (x * x)) + (tau1 * x);
|
|
||||||
for (i, gamma) in commitments.iter().map(|c| Scalar(c.mask)).enumerate() {
|
for (i, gamma) in commitments.iter().map(|c| Scalar(c.mask)).enumerate() {
|
||||||
taux += zpow[i + 2] * gamma;
|
taux += zpow[i + 2] * gamma;
|
||||||
}
|
}
|
||||||
let mu = (x * rho) + alpha;
|
|
||||||
|
|
||||||
let l = &l0 + &(l1 * x);
|
let l = &l0 + &(l1 * x);
|
||||||
let r = &r0 + &(r1 * x);
|
let r = &r0 + &(r1 * x);
|
||||||
@@ -155,7 +168,7 @@ impl OriginalStruct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn verify_core<ID: Copy, R: RngCore + CryptoRng>(
|
fn verify_core<ID: Copy + Zeroize, R: RngCore + CryptoRng>(
|
||||||
&self,
|
&self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
||||||
@@ -284,7 +297,7 @@ impl OriginalStruct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn batch_verify<ID: Copy, R: RngCore + CryptoRng>(
|
pub(crate) fn batch_verify<ID: Copy + Zeroize, R: RngCore + CryptoRng>(
|
||||||
&self,
|
&self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::{scalar::Scalar as DalekScalar, edwards::EdwardsPoint as DalekPoint};
|
use curve25519_dalek::{scalar::Scalar as DalekScalar, edwards::EdwardsPoint as DalekPoint};
|
||||||
|
|
||||||
use group::ff::Field;
|
use group::ff::Field;
|
||||||
@@ -109,7 +111,7 @@ impl PlusStruct {
|
|||||||
let cL = weighted_inner_product(&aL, &bR, y);
|
let cL = weighted_inner_product(&aL, &bR, y);
|
||||||
let cR = weighted_inner_product(&(&aR * ypow[aR.len()]), &bL, y);
|
let cR = weighted_inner_product(&(&aR * ypow[aR.len()]), &bL, y);
|
||||||
|
|
||||||
let (dL, dR) = (Scalar::random(&mut *rng), Scalar::random(&mut *rng));
|
let (mut dL, mut dR) = (Scalar::random(&mut *rng), Scalar::random(&mut *rng));
|
||||||
|
|
||||||
let (G_L, G_R) = G_proof.split_at(aL.len());
|
let (G_L, G_R) = G_proof.split_at(aL.len());
|
||||||
let (H_L, H_R) = H_proof.split_at(aL.len());
|
let (H_L, H_R) = H_proof.split_at(aL.len());
|
||||||
@@ -134,12 +136,15 @@ impl PlusStruct {
|
|||||||
b = (bL * winv) + (bR * w);
|
b = (bL * winv) + (bR * w);
|
||||||
|
|
||||||
alpha1 += (dL * (w * w)) + (dR * (winv * winv));
|
alpha1 += (dL * (w * w)) + (dR * (winv * winv));
|
||||||
|
|
||||||
|
dL.zeroize();
|
||||||
|
dR.zeroize();
|
||||||
}
|
}
|
||||||
|
|
||||||
let r = Scalar::random(&mut *rng);
|
let mut r = Scalar::random(&mut *rng);
|
||||||
let s = Scalar::random(&mut *rng);
|
let mut s = Scalar::random(&mut *rng);
|
||||||
let d = Scalar::random(&mut *rng);
|
let mut d = Scalar::random(&mut *rng);
|
||||||
let eta = Scalar::random(rng);
|
let mut eta = Scalar::random(rng);
|
||||||
|
|
||||||
let A1 = prove_multiexp(&[
|
let A1 = prove_multiexp(&[
|
||||||
(r, G_proof[0]),
|
(r, G_proof[0]),
|
||||||
@@ -151,8 +156,13 @@ impl PlusStruct {
|
|||||||
let e = hash_cache(&mut cache, &[A1.compress().to_bytes(), B.compress().to_bytes()]);
|
let e = hash_cache(&mut cache, &[A1.compress().to_bytes(), B.compress().to_bytes()]);
|
||||||
|
|
||||||
let r1 = (a[0] * e) + r;
|
let r1 = (a[0] * e) + r;
|
||||||
|
r.zeroize();
|
||||||
let s1 = (b[0] * e) + s;
|
let s1 = (b[0] * e) + s;
|
||||||
|
s.zeroize();
|
||||||
let d1 = ((d * e) + eta) + (alpha1 * (e * e));
|
let d1 = ((d * e) + eta) + (alpha1 * (e * e));
|
||||||
|
d.zeroize();
|
||||||
|
eta.zeroize();
|
||||||
|
alpha1.zeroize();
|
||||||
|
|
||||||
PlusStruct {
|
PlusStruct {
|
||||||
A: *A,
|
A: *A,
|
||||||
@@ -167,7 +177,7 @@ impl PlusStruct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
fn verify_core<ID: Copy, R: RngCore + CryptoRng>(
|
fn verify_core<ID: Copy + Zeroize, R: RngCore + CryptoRng>(
|
||||||
&self,
|
&self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
||||||
@@ -293,7 +303,7 @@ impl PlusStruct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn batch_verify<ID: Copy, R: RngCore + CryptoRng>(
|
pub(crate) fn batch_verify<ID: Copy + Zeroize, R: RngCore + CryptoRng>(
|
||||||
&self,
|
&self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
verifier: &mut BatchVerifier<ID, EdwardsPoint>,
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
use core::ops::{Add, Sub, Mul, Index};
|
use core::ops::{Add, Sub, Mul, Index};
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use group::ff::Field;
|
use group::ff::Field;
|
||||||
use dalek_ff_group::{Scalar, EdwardsPoint};
|
use dalek_ff_group::{Scalar, EdwardsPoint};
|
||||||
|
|
||||||
use multiexp::multiexp;
|
use multiexp::multiexp;
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub(crate) struct ScalarVector(pub(crate) Vec<Scalar>);
|
pub(crate) struct ScalarVector(pub(crate) Vec<Scalar>);
|
||||||
macro_rules! math_op {
|
macro_rules! math_op {
|
||||||
($Op: ident, $op: ident, $f: expr) => {
|
($Op: ident, $op: ident, $f: expr) => {
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ use lazy_static::lazy_static;
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
use subtle::{ConstantTimeEq, Choice, CtOption};
|
||||||
|
|
||||||
use curve25519_dalek::{
|
use curve25519_dalek::{
|
||||||
constants::ED25519_BASEPOINT_TABLE,
|
constants::ED25519_BASEPOINT_TABLE,
|
||||||
scalar::Scalar,
|
scalar::Scalar,
|
||||||
@@ -45,7 +48,7 @@ pub enum ClsagError {
|
|||||||
InvalidC1,
|
InvalidC1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct ClsagInput {
|
pub struct ClsagInput {
|
||||||
// The actual commitment for the true spend
|
// The actual commitment for the true spend
|
||||||
pub commitment: Commitment,
|
pub commitment: Commitment,
|
||||||
@@ -161,11 +164,12 @@ fn core(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Perform the core loop
|
// Perform the core loop
|
||||||
let mut c1 = None;
|
let mut c1 = CtOption::new(Scalar::zero(), Choice::from(0));
|
||||||
for i in (start .. end).map(|i| i % n) {
|
for i in (start .. end).map(|i| i % n) {
|
||||||
if i == 0 {
|
// This will only execute once and shouldn't need to be constant time. Making it constant time
|
||||||
c1 = Some(c);
|
// removes the risk of branch prediction creating timing differences depending on ring index
|
||||||
}
|
// however
|
||||||
|
c1 = c1.or_else(|| CtOption::new(c, i.ct_eq(&0)));
|
||||||
|
|
||||||
let c_p = mu_P * c;
|
let c_p = mu_P * c;
|
||||||
let c_c = mu_C * c;
|
let c_c = mu_C * c;
|
||||||
@@ -224,14 +228,10 @@ impl Clsag {
|
|||||||
// Single signer CLSAG
|
// Single signer CLSAG
|
||||||
pub fn sign<R: RngCore + CryptoRng>(
|
pub fn sign<R: RngCore + CryptoRng>(
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
inputs: &[(Scalar, EdwardsPoint, ClsagInput)],
|
mut inputs: Vec<(Scalar, EdwardsPoint, ClsagInput)>,
|
||||||
sum_outputs: Scalar,
|
sum_outputs: Scalar,
|
||||||
msg: [u8; 32],
|
msg: [u8; 32],
|
||||||
) -> Vec<(Clsag, EdwardsPoint)> {
|
) -> Vec<(Clsag, EdwardsPoint)> {
|
||||||
let nonce = random_scalar(rng);
|
|
||||||
let mut rand_source = [0; 64];
|
|
||||||
rng.fill_bytes(&mut rand_source);
|
|
||||||
|
|
||||||
let mut res = Vec::with_capacity(inputs.len());
|
let mut res = Vec::with_capacity(inputs.len());
|
||||||
let mut sum_pseudo_outs = Scalar::zero();
|
let mut sum_pseudo_outs = Scalar::zero();
|
||||||
for i in 0 .. inputs.len() {
|
for i in 0 .. inputs.len() {
|
||||||
@@ -242,8 +242,7 @@ impl Clsag {
|
|||||||
sum_pseudo_outs += mask;
|
sum_pseudo_outs += mask;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut rand_source = [0; 64];
|
let mut nonce = random_scalar(rng);
|
||||||
rng.fill_bytes(&mut rand_source);
|
|
||||||
let (mut clsag, pseudo_out, p, c) = Clsag::sign_core(
|
let (mut clsag, pseudo_out, p, c) = Clsag::sign_core(
|
||||||
rng,
|
rng,
|
||||||
&inputs[i].1,
|
&inputs[i].1,
|
||||||
@@ -254,6 +253,8 @@ impl Clsag {
|
|||||||
nonce * hash_to_point(inputs[i].2.decoys.ring[usize::from(inputs[i].2.decoys.i)][0]),
|
nonce * hash_to_point(inputs[i].2.decoys.ring[usize::from(inputs[i].2.decoys.i)][0]),
|
||||||
);
|
);
|
||||||
clsag.s[usize::from(inputs[i].2.decoys.i)] = nonce - ((p * inputs[i].0) + c);
|
clsag.s[usize::from(inputs[i].2.decoys.i)] = nonce - ((p * inputs[i].0) + c);
|
||||||
|
inputs[i].0.zeroize();
|
||||||
|
nonce.zeroize();
|
||||||
|
|
||||||
res.push((clsag, pseudo_out));
|
res.push((clsag, pseudo_out));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ use std::{
|
|||||||
use rand_core::{RngCore, CryptoRng, SeedableRng};
|
use rand_core::{RngCore, CryptoRng, SeedableRng};
|
||||||
use rand_chacha::ChaCha12Rng;
|
use rand_chacha::ChaCha12Rng;
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use curve25519_dalek::{
|
use curve25519_dalek::{
|
||||||
constants::ED25519_BASEPOINT_TABLE,
|
constants::ED25519_BASEPOINT_TABLE,
|
||||||
traits::{Identity, IsIdentity},
|
traits::{Identity, IsIdentity},
|
||||||
@@ -52,7 +54,7 @@ impl ClsagInput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct ClsagDetails {
|
pub struct ClsagDetails {
|
||||||
input: ClsagInput,
|
input: ClsagInput,
|
||||||
mask: Scalar,
|
mask: Scalar,
|
||||||
@@ -195,7 +197,7 @@ impl Algorithm<Ed25519> for ClsagMultisig {
|
|||||||
);
|
);
|
||||||
self.interim = Some(Interim { p, c, clsag, pseudo_out });
|
self.interim = Some(Interim { p, c, clsag, pseudo_out });
|
||||||
|
|
||||||
dfg::Scalar(nonces[0].0 - (p * view.secret_share().0))
|
nonces[0] - (dfg::Scalar(p) * view.secret_share())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
||||||
|
|
||||||
pub(crate) mod hash_to_point;
|
pub(crate) mod hash_to_point;
|
||||||
@@ -11,8 +13,10 @@ use crate::{
|
|||||||
ringct::{clsag::Clsag, bulletproofs::Bulletproofs},
|
ringct::{clsag::Clsag, bulletproofs::Bulletproofs},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn generate_key_image(secret: Scalar) -> EdwardsPoint {
|
pub fn generate_key_image(mut secret: Scalar) -> EdwardsPoint {
|
||||||
secret * hash_to_point(&secret * &ED25519_BASEPOINT_TABLE)
|
let res = secret * hash_to_point(&secret * &ED25519_BASEPOINT_TABLE);
|
||||||
|
secret.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
|
|||||||
@@ -84,9 +84,11 @@ macro_rules! bulletproofs_tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn $max() {
|
fn $max() {
|
||||||
// Check Bulletproofs errors if we try to prove for too many outputs
|
// Check Bulletproofs errors if we try to prove for too many outputs
|
||||||
assert!(
|
let mut commitments = vec![];
|
||||||
Bulletproofs::prove(&mut OsRng, &[Commitment::new(Scalar::zero(), 0); 17], $plus).is_err()
|
for _ in 0 .. 17 {
|
||||||
);
|
commitments.push(Commitment::new(Scalar::zero(), 0));
|
||||||
|
}
|
||||||
|
assert!(Bulletproofs::prove(&mut OsRng, &commitments, $plus).is_err());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ fn clsag() {
|
|||||||
let image = generate_key_image(secrets[0]);
|
let image = generate_key_image(secrets[0]);
|
||||||
let (clsag, pseudo_out) = Clsag::sign(
|
let (clsag, pseudo_out) = Clsag::sign(
|
||||||
&mut OsRng,
|
&mut OsRng,
|
||||||
&vec![(
|
vec![(
|
||||||
secrets[0],
|
secrets[0],
|
||||||
image,
|
image,
|
||||||
ClsagInput::new(
|
ClsagInput::new(
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use core::cmp::Ordering;
|
use core::cmp::Ordering;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::edwards::EdwardsPoint;
|
use curve25519_dalek::edwards::EdwardsPoint;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -11,7 +13,6 @@ use crate::{
|
|||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
pub enum Input {
|
pub enum Input {
|
||||||
Gen(u64),
|
Gen(u64),
|
||||||
|
|
||||||
ToKey { amount: u64, key_offsets: Vec<u64>, key_image: EdwardsPoint },
|
ToKey { amount: u64, key_offsets: Vec<u64>, key_image: EdwardsPoint },
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,7 +108,7 @@ impl Output {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub enum Timelock {
|
pub enum Timelock {
|
||||||
None,
|
None,
|
||||||
Block(usize),
|
Block(usize),
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ use std::string::ToString;
|
|||||||
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use curve25519_dalek::{
|
use curve25519_dalek::{
|
||||||
constants::ED25519_BASEPOINT_TABLE,
|
constants::ED25519_BASEPOINT_TABLE,
|
||||||
edwards::{EdwardsPoint, CompressedEdwardsY},
|
edwards::{EdwardsPoint, CompressedEdwardsY},
|
||||||
@@ -11,14 +13,14 @@ use base58_monero::base58::{encode_check, decode_check};
|
|||||||
|
|
||||||
use crate::wallet::ViewPair;
|
use crate::wallet::ViewPair;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub enum Network {
|
pub enum Network {
|
||||||
Mainnet,
|
Mainnet,
|
||||||
Testnet,
|
Testnet,
|
||||||
Stagenet,
|
Stagenet,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub enum AddressType {
|
pub enum AddressType {
|
||||||
Standard,
|
Standard,
|
||||||
Integrated([u8; 8]),
|
Integrated([u8; 8]),
|
||||||
@@ -35,7 +37,7 @@ impl AddressType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub struct AddressMeta {
|
pub struct AddressMeta {
|
||||||
pub network: Network,
|
pub network: Network,
|
||||||
pub kind: AddressType,
|
pub kind: AddressType,
|
||||||
@@ -91,7 +93,7 @@ impl AddressMeta {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub struct Address {
|
pub struct Address {
|
||||||
pub meta: AddressMeta,
|
pub meta: AddressMeta,
|
||||||
pub spend: EdwardsPoint,
|
pub spend: EdwardsPoint,
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ use lazy_static::lazy_static;
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
use rand_distr::{Distribution, Gamma};
|
use rand_distr::{Distribution, Gamma};
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use curve25519_dalek::edwards::EdwardsPoint;
|
use curve25519_dalek::edwards::EdwardsPoint;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -91,7 +93,7 @@ fn offset(ring: &[u64]) -> Vec<u64> {
|
|||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct Decoys {
|
pub struct Decoys {
|
||||||
pub i: u8,
|
pub i: u8,
|
||||||
pub offsets: Vec<u64>,
|
pub offsets: Vec<u64>,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use curve25519_dalek::{scalar::Scalar, edwards::EdwardsPoint};
|
use curve25519_dalek::{scalar::Scalar, edwards::EdwardsPoint};
|
||||||
|
|
||||||
use crate::{hash, hash_to_scalar, serialize::write_varint, transaction::Input};
|
use crate::{hash, hash_to_scalar, serialize::write_varint, transaction::Input};
|
||||||
@@ -39,7 +41,7 @@ pub(crate) fn uniqueness(inputs: &[Input]) -> [u8; 32] {
|
|||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
pub(crate) fn shared_key(
|
pub(crate) fn shared_key(
|
||||||
uniqueness: Option<[u8; 32]>,
|
uniqueness: Option<[u8; 32]>,
|
||||||
s: Scalar,
|
s: &Scalar,
|
||||||
P: &EdwardsPoint,
|
P: &EdwardsPoint,
|
||||||
o: usize,
|
o: usize,
|
||||||
) -> (u8, Scalar) {
|
) -> (u8, Scalar) {
|
||||||
@@ -76,7 +78,7 @@ pub(crate) fn commitment_mask(shared_key: Scalar) -> Scalar {
|
|||||||
hash_to_scalar(&mask)
|
hash_to_scalar(&mask)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct ViewPair {
|
pub struct ViewPair {
|
||||||
pub spend: EdwardsPoint,
|
pub spend: EdwardsPoint,
|
||||||
pub view: Scalar,
|
pub view: Scalar,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
||||||
|
|
||||||
use monero::{consensus::deserialize, blockdata::transaction::ExtraField};
|
use monero::{consensus::deserialize, blockdata::transaction::ExtraField};
|
||||||
@@ -11,7 +13,7 @@ use crate::{
|
|||||||
wallet::{ViewPair, uniqueness, shared_key, amount_decryption, commitment_mask},
|
wallet::{ViewPair, uniqueness, shared_key, amount_decryption, commitment_mask},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct SpendableOutput {
|
pub struct SpendableOutput {
|
||||||
pub tx: [u8; 32],
|
pub tx: [u8; 32],
|
||||||
pub o: u8,
|
pub o: u8,
|
||||||
@@ -20,6 +22,7 @@ pub struct SpendableOutput {
|
|||||||
pub commitment: Commitment,
|
pub commitment: Commitment,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct Timelocked(Timelock, Vec<SpendableOutput>);
|
pub struct Timelocked(Timelock, Vec<SpendableOutput>);
|
||||||
impl Timelocked {
|
impl Timelocked {
|
||||||
pub fn timelock(&self) -> Timelock {
|
pub fn timelock(&self) -> Timelock {
|
||||||
@@ -76,7 +79,7 @@ impl SpendableOutput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Transaction {
|
impl Transaction {
|
||||||
pub fn scan(&self, view: ViewPair, guaranteed: bool) -> Timelocked {
|
pub fn scan(&self, view: &ViewPair, guaranteed: bool) -> Timelocked {
|
||||||
let mut extra = vec![];
|
let mut extra = vec![];
|
||||||
write_varint(&u64::try_from(self.prefix.extra.len()).unwrap(), &mut extra).unwrap();
|
write_varint(&u64::try_from(self.prefix.extra.len()).unwrap(), &mut extra).unwrap();
|
||||||
extra.extend(&self.prefix.extra);
|
extra.extend(&self.prefix.extra);
|
||||||
@@ -103,7 +106,7 @@ impl Transaction {
|
|||||||
for pubkey in &pubkeys {
|
for pubkey in &pubkeys {
|
||||||
let (view_tag, key_offset) = shared_key(
|
let (view_tag, key_offset) = shared_key(
|
||||||
Some(uniqueness(&self.prefix.inputs)).filter(|_| guaranteed),
|
Some(uniqueness(&self.prefix.inputs)).filter(|_| guaranteed),
|
||||||
view.view,
|
&view.view,
|
||||||
pubkey,
|
pubkey,
|
||||||
o,
|
o,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ use thiserror::Error;
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
use rand::seq::SliceRandom;
|
use rand::seq::SliceRandom;
|
||||||
|
|
||||||
|
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||||
|
|
||||||
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar, edwards::EdwardsPoint};
|
||||||
|
|
||||||
use monero::{consensus::Encodable, PublicKey, blockdata::transaction::SubField};
|
use monero::{consensus::Encodable, PublicKey, blockdata::transaction::SubField};
|
||||||
@@ -35,7 +37,7 @@ mod multisig;
|
|||||||
pub use multisig::TransactionMachine;
|
pub use multisig::TransactionMachine;
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
struct SendOutput {
|
struct SendOutput {
|
||||||
R: EdwardsPoint,
|
R: EdwardsPoint,
|
||||||
view_tag: u8,
|
view_tag: u8,
|
||||||
@@ -53,7 +55,7 @@ impl SendOutput {
|
|||||||
) -> SendOutput {
|
) -> SendOutput {
|
||||||
let r = random_scalar(rng);
|
let r = random_scalar(rng);
|
||||||
let (view_tag, shared_key) =
|
let (view_tag, shared_key) =
|
||||||
shared_key(Some(unique).filter(|_| output.0.meta.guaranteed), r, &output.0.view, o);
|
shared_key(Some(unique).filter(|_| output.0.meta.guaranteed), &r, &output.0.view, o);
|
||||||
|
|
||||||
let spend = output.0.spend;
|
let spend = output.0.spend;
|
||||||
SendOutput {
|
SendOutput {
|
||||||
@@ -127,7 +129,8 @@ async fn prepare_inputs<R: RngCore + CryptoRng>(
|
|||||||
signable.push((
|
signable.push((
|
||||||
spend + input.key_offset,
|
spend + input.key_offset,
|
||||||
generate_key_image(spend + input.key_offset),
|
generate_key_image(spend + input.key_offset),
|
||||||
ClsagInput::new(input.commitment, decoys[i].clone()).map_err(TransactionError::ClsagError)?,
|
ClsagInput::new(input.commitment.clone(), decoys[i].clone())
|
||||||
|
.map_err(TransactionError::ClsagError)?,
|
||||||
));
|
));
|
||||||
|
|
||||||
tx.prefix.inputs.push(Input::ToKey {
|
tx.prefix.inputs.push(Input::ToKey {
|
||||||
@@ -161,12 +164,11 @@ impl Fee {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
|
||||||
pub struct SignableTransaction {
|
pub struct SignableTransaction {
|
||||||
protocol: Protocol,
|
protocol: Protocol,
|
||||||
inputs: Vec<SpendableOutput>,
|
inputs: Vec<SpendableOutput>,
|
||||||
payments: Vec<(Address, u64)>,
|
payments: Vec<(Address, u64)>,
|
||||||
outputs: Vec<SendOutput>,
|
|
||||||
fee: u64,
|
fee: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,80 +253,78 @@ impl SignableTransaction {
|
|||||||
Err(TransactionError::TooManyOutputs)?;
|
Err(TransactionError::TooManyOutputs)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(SignableTransaction { protocol, inputs, payments, outputs: vec![], fee })
|
Ok(SignableTransaction { protocol, inputs, payments, fee })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare_outputs<R: RngCore + CryptoRng>(
|
fn prepare_transaction<R: RngCore + CryptoRng>(
|
||||||
&mut self,
|
&mut self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
uniqueness: [u8; 32],
|
uniqueness: [u8; 32],
|
||||||
) -> (Vec<Commitment>, Scalar) {
|
) -> (Transaction, Scalar) {
|
||||||
// Shuffle the payments
|
// Shuffle the payments
|
||||||
self.payments.shuffle(rng);
|
self.payments.shuffle(rng);
|
||||||
|
|
||||||
// Actually create the outputs
|
// Actually create the outputs
|
||||||
self.outputs = Vec::with_capacity(self.payments.len() + 1);
|
let outputs = self
|
||||||
for (o, output) in self.payments.iter().enumerate() {
|
.payments
|
||||||
self.outputs.push(SendOutput::new(rng, uniqueness, *output, o));
|
.drain(..)
|
||||||
}
|
.enumerate()
|
||||||
|
.map(|(o, output)| SendOutput::new(rng, uniqueness, output, o))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let commitments = self.outputs.iter().map(|output| output.commitment).collect::<Vec<_>>();
|
let commitments = outputs.iter().map(|output| output.commitment.clone()).collect::<Vec<_>>();
|
||||||
let sum = commitments.iter().map(|commitment| commitment.mask).sum();
|
let sum = commitments.iter().map(|commitment| commitment.mask).sum();
|
||||||
(commitments, sum)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_transaction<R: RngCore + CryptoRng>(
|
|
||||||
&self,
|
|
||||||
rng: &mut R,
|
|
||||||
commitments: &[Commitment],
|
|
||||||
) -> Transaction {
|
|
||||||
// Safe due to the constructor checking MAX_OUTPUTS
|
// Safe due to the constructor checking MAX_OUTPUTS
|
||||||
let bp = Bulletproofs::prove(rng, commitments, self.protocol.bp_plus()).unwrap();
|
let bp = Bulletproofs::prove(rng, &commitments, self.protocol.bp_plus()).unwrap();
|
||||||
|
|
||||||
// Create the TX extra
|
// Create the TX extra
|
||||||
// TODO: Review this for canonicity with Monero
|
// TODO: Review this for canonicity with Monero
|
||||||
let mut extra = vec![];
|
let mut extra = vec![];
|
||||||
SubField::TxPublicKey(PublicKey { point: self.outputs[0].R.compress() })
|
SubField::TxPublicKey(PublicKey { point: outputs[0].R.compress() })
|
||||||
.consensus_encode(&mut extra)
|
.consensus_encode(&mut extra)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
SubField::AdditionalPublickKey(
|
SubField::AdditionalPublickKey(
|
||||||
self.outputs[1 ..].iter().map(|output| PublicKey { point: output.R.compress() }).collect(),
|
outputs[1 ..].iter().map(|output| PublicKey { point: output.R.compress() }).collect(),
|
||||||
)
|
)
|
||||||
.consensus_encode(&mut extra)
|
.consensus_encode(&mut extra)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut tx_outputs = Vec::with_capacity(self.outputs.len());
|
let mut tx_outputs = Vec::with_capacity(outputs.len());
|
||||||
let mut ecdh_info = Vec::with_capacity(self.outputs.len());
|
let mut ecdh_info = Vec::with_capacity(outputs.len());
|
||||||
for o in 0 .. self.outputs.len() {
|
for output in &outputs {
|
||||||
tx_outputs.push(Output {
|
tx_outputs.push(Output {
|
||||||
amount: 0,
|
amount: 0,
|
||||||
key: self.outputs[o].dest,
|
key: output.dest,
|
||||||
view_tag: Some(self.outputs[o].view_tag).filter(|_| matches!(self.protocol, Protocol::v16)),
|
view_tag: Some(output.view_tag).filter(|_| matches!(self.protocol, Protocol::v16)),
|
||||||
});
|
});
|
||||||
ecdh_info.push(self.outputs[o].amount);
|
ecdh_info.push(output.amount);
|
||||||
}
|
}
|
||||||
|
|
||||||
Transaction {
|
(
|
||||||
prefix: TransactionPrefix {
|
Transaction {
|
||||||
version: 2,
|
prefix: TransactionPrefix {
|
||||||
timelock: Timelock::None,
|
version: 2,
|
||||||
inputs: vec![],
|
timelock: Timelock::None,
|
||||||
outputs: tx_outputs,
|
inputs: vec![],
|
||||||
extra,
|
outputs: tx_outputs,
|
||||||
},
|
extra,
|
||||||
rct_signatures: RctSignatures {
|
|
||||||
base: RctBase {
|
|
||||||
fee: self.fee,
|
|
||||||
ecdh_info,
|
|
||||||
commitments: commitments.iter().map(|commitment| commitment.calculate()).collect(),
|
|
||||||
},
|
},
|
||||||
prunable: RctPrunable::Clsag {
|
rct_signatures: RctSignatures {
|
||||||
bulletproofs: vec![bp],
|
base: RctBase {
|
||||||
clsags: vec![],
|
fee: self.fee,
|
||||||
pseudo_outs: vec![],
|
ecdh_info,
|
||||||
|
commitments: commitments.iter().map(|commitment| commitment.calculate()).collect(),
|
||||||
|
},
|
||||||
|
prunable: RctPrunable::Clsag {
|
||||||
|
bulletproofs: vec![bp],
|
||||||
|
clsags: vec![],
|
||||||
|
pseudo_outs: vec![],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
sum,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn sign<R: RngCore + CryptoRng>(
|
pub async fn sign<R: RngCore + CryptoRng>(
|
||||||
@@ -335,16 +335,17 @@ impl SignableTransaction {
|
|||||||
) -> Result<Transaction, TransactionError> {
|
) -> Result<Transaction, TransactionError> {
|
||||||
let mut images = Vec::with_capacity(self.inputs.len());
|
let mut images = Vec::with_capacity(self.inputs.len());
|
||||||
for input in &self.inputs {
|
for input in &self.inputs {
|
||||||
let offset = spend + input.key_offset;
|
let mut offset = spend + input.key_offset;
|
||||||
if (&offset * &ED25519_BASEPOINT_TABLE) != input.key {
|
if (&offset * &ED25519_BASEPOINT_TABLE) != input.key {
|
||||||
Err(TransactionError::WrongPrivateKey)?;
|
Err(TransactionError::WrongPrivateKey)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
images.push(generate_key_image(offset));
|
images.push(generate_key_image(offset));
|
||||||
|
offset.zeroize();
|
||||||
}
|
}
|
||||||
images.sort_by(key_image_sort);
|
images.sort_by(key_image_sort);
|
||||||
|
|
||||||
let (commitments, mask_sum) = self.prepare_outputs(
|
let (mut tx, mask_sum) = self.prepare_transaction(
|
||||||
rng,
|
rng,
|
||||||
uniqueness(
|
uniqueness(
|
||||||
&images
|
&images
|
||||||
@@ -354,12 +355,10 @@ impl SignableTransaction {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut tx = self.prepare_transaction(rng, &commitments);
|
|
||||||
|
|
||||||
let signable =
|
let signable =
|
||||||
prepare_inputs(rng, rpc, self.protocol.ring_len(), &self.inputs, spend, &mut tx).await?;
|
prepare_inputs(rng, rpc, self.protocol.ring_len(), &self.inputs, spend, &mut tx).await?;
|
||||||
|
|
||||||
let clsag_pairs = Clsag::sign(rng, &signable, mask_sum, tx.signature_hash());
|
let clsag_pairs = Clsag::sign(rng, signable, mask_sum, tx.signature_hash());
|
||||||
match tx.rct_signatures.prunable {
|
match tx.rct_signatures.prunable {
|
||||||
RctPrunable::Null => panic!("Signing for RctPrunable::Null"),
|
RctPrunable::Null => panic!("Signing for RctPrunable::Null"),
|
||||||
RctPrunable::Clsag { ref mut clsags, ref mut pseudo_outs, .. } => {
|
RctPrunable::Clsag { ref mut clsags, ref mut pseudo_outs, .. } => {
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ impl SignableTransaction {
|
|||||||
AlgorithmMachine::new(
|
AlgorithmMachine::new(
|
||||||
ClsagMultisig::new(transcript.clone(), input.key, inputs[i].clone())
|
ClsagMultisig::new(transcript.clone(), input.key, inputs[i].clone())
|
||||||
.map_err(TransactionError::MultisigError)?,
|
.map_err(TransactionError::MultisigError)?,
|
||||||
Arc::new(offset),
|
offset,
|
||||||
&included,
|
&included,
|
||||||
)
|
)
|
||||||
.map_err(TransactionError::FrostError)?,
|
.map_err(TransactionError::FrostError)?,
|
||||||
@@ -283,25 +283,18 @@ impl SignMachine<Transaction> for TransactionSignMachine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create the actual transaction
|
// Create the actual transaction
|
||||||
let output_masks;
|
let (mut tx, output_masks) = {
|
||||||
let mut tx = {
|
|
||||||
let mut sorted_images = images.clone();
|
let mut sorted_images = images.clone();
|
||||||
sorted_images.sort_by(key_image_sort);
|
sorted_images.sort_by(key_image_sort);
|
||||||
|
|
||||||
let commitments;
|
self.signable.prepare_transaction(
|
||||||
(commitments, output_masks) = self.signable.prepare_outputs(
|
&mut ChaCha12Rng::from_seed(self.transcript.rng_seed(b"transaction_keys_bulletproofs")),
|
||||||
&mut ChaCha12Rng::from_seed(self.transcript.rng_seed(b"tx_keys")),
|
|
||||||
uniqueness(
|
uniqueness(
|
||||||
&images
|
&sorted_images
|
||||||
.iter()
|
.iter()
|
||||||
.map(|image| Input::ToKey { amount: 0, key_offsets: vec![], key_image: *image })
|
.map(|image| Input::ToKey { amount: 0, key_offsets: vec![], key_image: *image })
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
),
|
),
|
||||||
);
|
|
||||||
|
|
||||||
self.signable.prepare_transaction(
|
|
||||||
&mut ChaCha12Rng::from_seed(self.transcript.rng_seed(b"bulletproofs")),
|
|
||||||
&commitments,
|
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -338,7 +331,7 @@ impl SignMachine<Transaction> for TransactionSignMachine {
|
|||||||
});
|
});
|
||||||
|
|
||||||
*value.3.write().unwrap() = Some(ClsagDetails::new(
|
*value.3.write().unwrap() = Some(ClsagDetails::new(
|
||||||
ClsagInput::new(value.1.commitment, value.2).map_err(|_| {
|
ClsagInput::new(value.1.commitment.clone(), value.2).map_err(|_| {
|
||||||
panic!("Signing an input which isn't present in the ring we created for it")
|
panic!("Signing an input which isn't present in the ring we created for it")
|
||||||
})?,
|
})?,
|
||||||
mask,
|
mask,
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ async fn send_core(test: usize, multisig: bool) {
|
|||||||
|
|
||||||
// Grab the largest output available
|
// Grab the largest output available
|
||||||
let output = {
|
let output = {
|
||||||
let mut outputs = tx.as_ref().unwrap().scan(view_pair, false).ignore_timelock();
|
let mut outputs = tx.as_ref().unwrap().scan(&view_pair, false).ignore_timelock();
|
||||||
outputs.sort_by(|x, y| x.commitment.amount.cmp(&y.commitment.amount).reverse());
|
outputs.sort_by(|x, y| x.commitment.amount.cmp(&y.commitment.amount).reverse());
|
||||||
outputs.swap_remove(0)
|
outputs.swap_remove(0)
|
||||||
};
|
};
|
||||||
@@ -126,7 +126,7 @@ async fn send_core(test: usize, multisig: bool) {
|
|||||||
|
|
||||||
for i in (start + 1) .. (start + 9) {
|
for i in (start + 1) .. (start + 9) {
|
||||||
let tx = rpc.get_block_transactions(i).await.unwrap().swap_remove(0);
|
let tx = rpc.get_block_transactions(i).await.unwrap().swap_remove(0);
|
||||||
let output = tx.scan(view_pair, false).ignore_timelock().swap_remove(0);
|
let output = tx.scan(&view_pair, false).ignore_timelock().swap_remove(0);
|
||||||
amount += output.commitment.amount;
|
amount += output.commitment.amount;
|
||||||
outputs.push(output);
|
outputs.push(output);
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ async fn send_core(test: usize, multisig: bool) {
|
|||||||
.clone()
|
.clone()
|
||||||
.multisig(
|
.multisig(
|
||||||
&rpc,
|
&rpc,
|
||||||
(*keys[&i]).clone(),
|
keys[&i].clone(),
|
||||||
RecommendedTranscript::new(b"Monero Serai Test Transaction"),
|
RecommendedTranscript::new(b"Monero Serai Test Transaction"),
|
||||||
rpc.get_height().await.unwrap() - 10,
|
rpc.get_height().await.unwrap() - 10,
|
||||||
(1 ..= THRESHOLD).collect::<Vec<_>>(),
|
(1 ..= THRESHOLD).collect::<Vec<_>>(),
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ edition = "2021"
|
|||||||
rand_core = "0.6"
|
rand_core = "0.6"
|
||||||
digest = "0.10"
|
digest = "0.10"
|
||||||
|
|
||||||
|
zeroize = { version = "1.3", features = ["zeroize_derive"] }
|
||||||
subtle = "2.4"
|
subtle = "2.4"
|
||||||
|
|
||||||
ff = "0.12"
|
ff = "0.12"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ use core::ops::{Add, AddAssign, Sub, SubAssign, Neg, Mul, MulAssign};
|
|||||||
use rand_core::RngCore;
|
use rand_core::RngCore;
|
||||||
|
|
||||||
use subtle::{Choice, CtOption, ConstantTimeEq, ConditionallySelectable};
|
use subtle::{Choice, CtOption, ConstantTimeEq, ConditionallySelectable};
|
||||||
|
|
||||||
use crypto_bigint::{Encoding, U256, U512};
|
use crypto_bigint::{Encoding, U256, U512};
|
||||||
|
|
||||||
use ff::{Field, PrimeField, FieldBits, PrimeFieldBits};
|
use ff::{Field, PrimeField, FieldBits, PrimeFieldBits};
|
||||||
@@ -12,7 +13,7 @@ use crate::{choice, constant_time, math_op, math, from_wrapper, from_uint};
|
|||||||
const FIELD_MODULUS: U256 =
|
const FIELD_MODULUS: U256 =
|
||||||
U256::from_be_hex("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
|
U256::from_be_hex("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||||
pub struct FieldElement(U256);
|
pub struct FieldElement(U256);
|
||||||
|
|
||||||
pub const SQRT_M1: FieldElement = FieldElement(U256::from_be_hex(
|
pub const SQRT_M1: FieldElement = FieldElement(U256::from_be_hex(
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use core::{
|
|||||||
iter::{Iterator, Sum},
|
iter::{Iterator, Sum},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
use subtle::{ConstantTimeEq, ConditionallySelectable};
|
use subtle::{ConstantTimeEq, ConditionallySelectable};
|
||||||
|
|
||||||
use rand_core::RngCore;
|
use rand_core::RngCore;
|
||||||
@@ -167,7 +168,7 @@ macro_rules! from_uint {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Wrapper around the dalek Scalar type
|
/// Wrapper around the dalek Scalar type
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Zeroize)]
|
||||||
pub struct Scalar(pub DScalar);
|
pub struct Scalar(pub DScalar);
|
||||||
deref_borrow!(Scalar, DScalar);
|
deref_borrow!(Scalar, DScalar);
|
||||||
constant_time!(Scalar, DScalar);
|
constant_time!(Scalar, DScalar);
|
||||||
@@ -285,7 +286,7 @@ macro_rules! dalek_group {
|
|||||||
$BASEPOINT_TABLE: ident
|
$BASEPOINT_TABLE: ident
|
||||||
) => {
|
) => {
|
||||||
/// Wrapper around the dalek Point type. For Ed25519, this is restricted to the prime subgroup
|
/// Wrapper around the dalek Point type. For Ed25519, this is restricted to the prime subgroup
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub struct $Point(pub $DPoint);
|
pub struct $Point(pub $DPoint);
|
||||||
deref_borrow!($Point, $DPoint);
|
deref_borrow!($Point, $DPoint);
|
||||||
constant_time!($Point, $DPoint);
|
constant_time!($Point, $DPoint);
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ edition = "2021"
|
|||||||
thiserror = "1"
|
thiserror = "1"
|
||||||
rand_core = "0.6"
|
rand_core = "0.6"
|
||||||
|
|
||||||
|
zeroize = "1.3"
|
||||||
|
|
||||||
digest = "0.10"
|
digest = "0.10"
|
||||||
|
|
||||||
transcript = { package = "flexible-transcript", path = "../transcript", version = "0.1" }
|
transcript = { package = "flexible-transcript", path = "../transcript", version = "0.1" }
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
@@ -46,15 +48,16 @@ impl<G0: PrimeGroup, G1: PrimeGroup> Re<G0, G1> {
|
|||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
pub(crate) struct Aos<G0: PrimeGroup, G1: PrimeGroup, const RING_LEN: usize> {
|
pub(crate) struct Aos<G0: PrimeGroup + Zeroize, G1: PrimeGroup + Zeroize, const RING_LEN: usize> {
|
||||||
Re_0: Re<G0, G1>,
|
Re_0: Re<G0, G1>,
|
||||||
s: [(G0::Scalar, G1::Scalar); RING_LEN],
|
s: [(G0::Scalar, G1::Scalar); RING_LEN],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<G0: PrimeGroup, G1: PrimeGroup, const RING_LEN: usize> Aos<G0, G1, RING_LEN>
|
impl<G0: PrimeGroup + Zeroize, G1: PrimeGroup + Zeroize, const RING_LEN: usize>
|
||||||
|
Aos<G0, G1, RING_LEN>
|
||||||
where
|
where
|
||||||
G0::Scalar: PrimeFieldBits,
|
G0::Scalar: PrimeFieldBits + Zeroize,
|
||||||
G1::Scalar: PrimeFieldBits,
|
G1::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
fn nonces<T: Transcript>(mut transcript: T, nonces: (G0, G1)) -> (G0::Scalar, G1::Scalar) {
|
fn nonces<T: Transcript>(mut transcript: T, nonces: (G0, G1)) -> (G0::Scalar, G1::Scalar) {
|
||||||
@@ -102,8 +105,8 @@ where
|
|||||||
transcript: T,
|
transcript: T,
|
||||||
generators: (Generators<G0>, Generators<G1>),
|
generators: (Generators<G0>, Generators<G1>),
|
||||||
ring: &[(G0, G1)],
|
ring: &[(G0, G1)],
|
||||||
actual: usize,
|
mut actual: usize,
|
||||||
blinding_key: (G0::Scalar, G1::Scalar),
|
blinding_key: &mut (G0::Scalar, G1::Scalar),
|
||||||
mut Re_0: Re<G0, G1>,
|
mut Re_0: Re<G0, G1>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
// While it is possible to use larger values, it's not efficient to do so
|
// While it is possible to use larger values, it's not efficient to do so
|
||||||
@@ -113,7 +116,7 @@ where
|
|||||||
|
|
||||||
let mut s = [(G0::Scalar::zero(), G1::Scalar::zero()); RING_LEN];
|
let mut s = [(G0::Scalar::zero(), G1::Scalar::zero()); RING_LEN];
|
||||||
|
|
||||||
let r = (G0::Scalar::random(&mut *rng), G1::Scalar::random(&mut *rng));
|
let mut r = (G0::Scalar::random(&mut *rng), G1::Scalar::random(&mut *rng));
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
let original_R = (generators.0.alt * r.0, generators.1.alt * r.1);
|
let original_R = (generators.0.alt * r.0, generators.1.alt * r.1);
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
@@ -135,6 +138,11 @@ where
|
|||||||
if i == actual {
|
if i == actual {
|
||||||
s[i] = (r.0 + (e.0 * blinding_key.0), r.1 + (e.1 * blinding_key.1));
|
s[i] = (r.0 + (e.0 * blinding_key.0), r.1 + (e.1 * blinding_key.1));
|
||||||
debug_assert_eq!(Self::R(generators, s[i], ring[actual], e), original_R);
|
debug_assert_eq!(Self::R(generators, s[i], ring[actual], e), original_R);
|
||||||
|
actual.zeroize();
|
||||||
|
blinding_key.0.zeroize();
|
||||||
|
blinding_key.1.zeroize();
|
||||||
|
r.0.zeroize();
|
||||||
|
r.1.zeroize();
|
||||||
break;
|
break;
|
||||||
// Generate a decoy response
|
// Generate a decoy response
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
|
|
||||||
use group::{ff::PrimeFieldBits, prime::PrimeGroup};
|
use group::{ff::PrimeFieldBits, prime::PrimeGroup};
|
||||||
@@ -67,16 +69,25 @@ impl BitSignature {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
pub(crate) struct Bits<G0: PrimeGroup, G1: PrimeGroup, const SIGNATURE: u8, const RING_LEN: usize> {
|
pub(crate) struct Bits<
|
||||||
|
G0: PrimeGroup + Zeroize,
|
||||||
|
G1: PrimeGroup + Zeroize,
|
||||||
|
const SIGNATURE: u8,
|
||||||
|
const RING_LEN: usize,
|
||||||
|
> {
|
||||||
pub(crate) commitments: (G0, G1),
|
pub(crate) commitments: (G0, G1),
|
||||||
signature: Aos<G0, G1, RING_LEN>,
|
signature: Aos<G0, G1, RING_LEN>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<G0: PrimeGroup, G1: PrimeGroup, const SIGNATURE: u8, const RING_LEN: usize>
|
impl<
|
||||||
Bits<G0, G1, SIGNATURE, RING_LEN>
|
G0: PrimeGroup + Zeroize,
|
||||||
|
G1: PrimeGroup + Zeroize,
|
||||||
|
const SIGNATURE: u8,
|
||||||
|
const RING_LEN: usize,
|
||||||
|
> Bits<G0, G1, SIGNATURE, RING_LEN>
|
||||||
where
|
where
|
||||||
G0::Scalar: PrimeFieldBits,
|
G0::Scalar: PrimeFieldBits + Zeroize,
|
||||||
G1::Scalar: PrimeFieldBits,
|
G1::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
fn transcript<T: Transcript>(transcript: &mut T, i: usize, commitments: (G0, G1)) {
|
fn transcript<T: Transcript>(transcript: &mut T, i: usize, commitments: (G0, G1)) {
|
||||||
transcript.domain_separate(b"bits");
|
transcript.domain_separate(b"bits");
|
||||||
@@ -106,8 +117,8 @@ where
|
|||||||
generators: (Generators<G0>, Generators<G1>),
|
generators: (Generators<G0>, Generators<G1>),
|
||||||
i: usize,
|
i: usize,
|
||||||
pow_2: &mut (G0, G1),
|
pow_2: &mut (G0, G1),
|
||||||
bits: u8,
|
mut bits: u8,
|
||||||
blinding_key: (G0::Scalar, G1::Scalar),
|
blinding_key: &mut (G0::Scalar, G1::Scalar),
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut commitments =
|
let mut commitments =
|
||||||
((generators.0.alt * blinding_key.0), (generators.1.alt * blinding_key.1));
|
((generators.0.alt * blinding_key.0), (generators.1.alt * blinding_key.1));
|
||||||
@@ -125,6 +136,7 @@ where
|
|||||||
blinding_key,
|
blinding_key,
|
||||||
BitSignature::from(SIGNATURE).aos_form(),
|
BitSignature::from(SIGNATURE).aos_form(),
|
||||||
);
|
);
|
||||||
|
bits.zeroize();
|
||||||
|
|
||||||
Self::shift(pow_2);
|
Self::shift(pow_2);
|
||||||
Bits { commitments, signature }
|
Bits { commitments, signature }
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use digest::Digest;
|
use digest::Digest;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
@@ -73,8 +76,8 @@ pub enum DLEqError {
|
|||||||
// anyone who wants it
|
// anyone who wants it
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
pub struct __DLEqProof<
|
pub struct __DLEqProof<
|
||||||
G0: PrimeGroup,
|
G0: PrimeGroup + Zeroize,
|
||||||
G1: PrimeGroup,
|
G1: PrimeGroup + Zeroize,
|
||||||
const SIGNATURE: u8,
|
const SIGNATURE: u8,
|
||||||
const RING_LEN: usize,
|
const RING_LEN: usize,
|
||||||
const REMAINDER_RING_LEN: usize,
|
const REMAINDER_RING_LEN: usize,
|
||||||
@@ -131,15 +134,15 @@ dleq!(EfficientLinearDLEq, BitSignature::EfficientLinear, false);
|
|||||||
dleq!(CompromiseLinearDLEq, BitSignature::CompromiseLinear, true);
|
dleq!(CompromiseLinearDLEq, BitSignature::CompromiseLinear, true);
|
||||||
|
|
||||||
impl<
|
impl<
|
||||||
G0: PrimeGroup,
|
G0: PrimeGroup + Zeroize,
|
||||||
G1: PrimeGroup,
|
G1: PrimeGroup + Zeroize,
|
||||||
const SIGNATURE: u8,
|
const SIGNATURE: u8,
|
||||||
const RING_LEN: usize,
|
const RING_LEN: usize,
|
||||||
const REMAINDER_RING_LEN: usize,
|
const REMAINDER_RING_LEN: usize,
|
||||||
> __DLEqProof<G0, G1, SIGNATURE, RING_LEN, REMAINDER_RING_LEN>
|
> __DLEqProof<G0, G1, SIGNATURE, RING_LEN, REMAINDER_RING_LEN>
|
||||||
where
|
where
|
||||||
G0::Scalar: PrimeFieldBits,
|
G0::Scalar: PrimeFieldBits + Zeroize,
|
||||||
G1::Scalar: PrimeFieldBits,
|
G1::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
pub(crate) fn transcript<T: Transcript>(
|
pub(crate) fn transcript<T: Transcript>(
|
||||||
transcript: &mut T,
|
transcript: &mut T,
|
||||||
@@ -213,22 +216,27 @@ where
|
|||||||
|
|
||||||
let mut pow_2 = (generators.0.primary, generators.1.primary);
|
let mut pow_2 = (generators.0.primary, generators.1.primary);
|
||||||
|
|
||||||
let raw_bits = f.0.to_le_bits();
|
let mut raw_bits = f.0.to_le_bits();
|
||||||
let mut bits = Vec::with_capacity(capacity);
|
let mut bits = Vec::with_capacity(capacity);
|
||||||
let mut these_bits: u8 = 0;
|
let mut these_bits: u8 = 0;
|
||||||
for (i, bit) in raw_bits.iter().enumerate() {
|
// Needed to zero out the bits
|
||||||
|
#[allow(unused_assignments)]
|
||||||
|
for (i, mut raw_bit) in raw_bits.iter_mut().enumerate() {
|
||||||
if i == capacity {
|
if i == capacity {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let bit = *bit as u8;
|
let mut bit = *raw_bit as u8;
|
||||||
debug_assert_eq!(bit | 1, 1);
|
debug_assert_eq!(bit | 1, 1);
|
||||||
|
*raw_bit = false;
|
||||||
|
|
||||||
// Accumulate this bit
|
// Accumulate this bit
|
||||||
these_bits |= bit << (i % bits_per_group);
|
these_bits |= bit << (i % bits_per_group);
|
||||||
|
bit = 0;
|
||||||
|
|
||||||
if (i % bits_per_group) == (bits_per_group - 1) {
|
if (i % bits_per_group) == (bits_per_group - 1) {
|
||||||
let last = i == (capacity - 1);
|
let last = i == (capacity - 1);
|
||||||
let blinding_key = blinding_key(&mut *rng, last);
|
let mut blinding_key = blinding_key(&mut *rng, last);
|
||||||
bits.push(Bits::prove(
|
bits.push(Bits::prove(
|
||||||
&mut *rng,
|
&mut *rng,
|
||||||
transcript,
|
transcript,
|
||||||
@@ -236,7 +244,7 @@ where
|
|||||||
i / bits_per_group,
|
i / bits_per_group,
|
||||||
&mut pow_2,
|
&mut pow_2,
|
||||||
these_bits,
|
these_bits,
|
||||||
blinding_key,
|
&mut blinding_key,
|
||||||
));
|
));
|
||||||
these_bits = 0;
|
these_bits = 0;
|
||||||
}
|
}
|
||||||
@@ -245,7 +253,7 @@ where
|
|||||||
|
|
||||||
let mut remainder = None;
|
let mut remainder = None;
|
||||||
if capacity != ((capacity / bits_per_group) * bits_per_group) {
|
if capacity != ((capacity / bits_per_group) * bits_per_group) {
|
||||||
let blinding_key = blinding_key(&mut *rng, true);
|
let mut blinding_key = blinding_key(&mut *rng, true);
|
||||||
remainder = Some(Bits::prove(
|
remainder = Some(Bits::prove(
|
||||||
&mut *rng,
|
&mut *rng,
|
||||||
transcript,
|
transcript,
|
||||||
@@ -253,10 +261,12 @@ where
|
|||||||
capacity / bits_per_group,
|
capacity / bits_per_group,
|
||||||
&mut pow_2,
|
&mut pow_2,
|
||||||
these_bits,
|
these_bits,
|
||||||
blinding_key,
|
&mut blinding_key,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
these_bits.zeroize();
|
||||||
|
|
||||||
let proof = __DLEqProof { bits, remainder, poks };
|
let proof = __DLEqProof { bits, remainder, poks };
|
||||||
debug_assert_eq!(
|
debug_assert_eq!(
|
||||||
proof.reconstruct_keys(),
|
proof.reconstruct_keys(),
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
use ff::PrimeFieldBits;
|
use ff::PrimeFieldBits;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
/// Convert a uniform scalar into one usable on both fields, clearing the top bits as needed
|
/// Convert a uniform scalar into one usable on both fields, clearing the top bits as needed
|
||||||
pub fn scalar_normalize<F0: PrimeFieldBits, F1: PrimeFieldBits>(scalar: F0) -> (F0, F1) {
|
pub fn scalar_normalize<F0: PrimeFieldBits + Zeroize, F1: PrimeFieldBits>(
|
||||||
|
mut scalar: F0,
|
||||||
|
) -> (F0, F1) {
|
||||||
let mutual_capacity = F0::CAPACITY.min(F1::CAPACITY);
|
let mutual_capacity = F0::CAPACITY.min(F1::CAPACITY);
|
||||||
|
|
||||||
// The security of a mutual key is the security of the lower field. Accordingly, this bans a
|
// The security of a mutual key is the security of the lower field. Accordingly, this bans a
|
||||||
@@ -13,30 +17,50 @@ pub fn scalar_normalize<F0: PrimeFieldBits, F1: PrimeFieldBits>(scalar: F0) -> (
|
|||||||
let mut res2 = F1::zero();
|
let mut res2 = F1::zero();
|
||||||
// Uses the bit view API to ensure a consistent endianess
|
// Uses the bit view API to ensure a consistent endianess
|
||||||
let mut bits = scalar.to_le_bits();
|
let mut bits = scalar.to_le_bits();
|
||||||
|
scalar.zeroize();
|
||||||
// Convert it to big endian
|
// Convert it to big endian
|
||||||
bits.reverse();
|
bits.reverse();
|
||||||
for bit in bits.iter().skip(bits.len() - usize::try_from(mutual_capacity).unwrap()) {
|
|
||||||
|
let mut skip = bits.len() - usize::try_from(mutual_capacity).unwrap();
|
||||||
|
// Needed to zero out the bits
|
||||||
|
#[allow(unused_assignments)]
|
||||||
|
for mut raw_bit in bits.iter_mut() {
|
||||||
|
if skip > 0 {
|
||||||
|
*raw_bit = false;
|
||||||
|
skip -= 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
res1 = res1.double();
|
res1 = res1.double();
|
||||||
res2 = res2.double();
|
res2 = res2.double();
|
||||||
|
|
||||||
let bit = *bit as u8;
|
let mut bit = *raw_bit as u8;
|
||||||
debug_assert_eq!(bit | 1, 1);
|
debug_assert_eq!(bit | 1, 1);
|
||||||
|
*raw_bit = false;
|
||||||
|
|
||||||
res1 += F0::from(bit.into());
|
res1 += F0::from(bit.into());
|
||||||
res2 += F1::from(bit.into());
|
res2 += F1::from(bit.into());
|
||||||
|
bit = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
(res1, res2)
|
(res1, res2)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper to convert a scalar between fields. Returns None if the scalar isn't mutually valid
|
/// Helper to convert a scalar between fields. Returns None if the scalar isn't mutually valid
|
||||||
pub fn scalar_convert<F0: PrimeFieldBits, F1: PrimeFieldBits>(scalar: F0) -> Option<F1> {
|
pub fn scalar_convert<F0: PrimeFieldBits + Zeroize, F1: PrimeFieldBits>(
|
||||||
let (valid, converted) = scalar_normalize(scalar);
|
mut scalar: F0,
|
||||||
Some(converted).filter(|_| scalar == valid)
|
) -> Option<F1> {
|
||||||
|
let (mut valid, converted) = scalar_normalize(scalar);
|
||||||
|
let res = Some(converted).filter(|_| scalar == valid);
|
||||||
|
scalar.zeroize();
|
||||||
|
valid.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a mutually valid scalar from bytes via bit truncation to not introduce bias
|
/// Create a mutually valid scalar from bytes via bit truncation to not introduce bias
|
||||||
pub fn mutual_scalar_from_bytes<F0: PrimeFieldBits, F1: PrimeFieldBits>(bytes: &[u8]) -> (F0, F1) {
|
pub fn mutual_scalar_from_bytes<F0: PrimeFieldBits + Zeroize, F1: PrimeFieldBits>(
|
||||||
|
bytes: &[u8],
|
||||||
|
) -> (F0, F1) {
|
||||||
let capacity = usize::try_from(F0::CAPACITY.min(F1::CAPACITY)).unwrap();
|
let capacity = usize::try_from(F0::CAPACITY.min(F1::CAPACITY)).unwrap();
|
||||||
debug_assert!((bytes.len() * 8) >= capacity);
|
debug_assert!((bytes.len() * 8) >= capacity);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
@@ -19,14 +21,14 @@ use crate::{read_scalar, cross_group::read_point};
|
|||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||||
pub(crate) struct SchnorrPoK<G: PrimeGroup> {
|
pub(crate) struct SchnorrPoK<G: PrimeGroup + Zeroize> {
|
||||||
R: G,
|
R: G,
|
||||||
s: G::Scalar,
|
s: G::Scalar,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<G: PrimeGroup> SchnorrPoK<G>
|
impl<G: PrimeGroup + Zeroize> SchnorrPoK<G>
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
// Not hram due to the lack of m
|
// Not hram due to the lack of m
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
@@ -42,15 +44,18 @@ where
|
|||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
transcript: &mut T,
|
transcript: &mut T,
|
||||||
generator: G,
|
generator: G,
|
||||||
private_key: G::Scalar,
|
mut private_key: G::Scalar,
|
||||||
) -> SchnorrPoK<G> {
|
) -> SchnorrPoK<G> {
|
||||||
let nonce = G::Scalar::random(rng);
|
let mut nonce = G::Scalar::random(rng);
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
let R = generator * nonce;
|
let R = generator * nonce;
|
||||||
SchnorrPoK {
|
let res = SchnorrPoK {
|
||||||
R,
|
R,
|
||||||
s: nonce + (private_key * SchnorrPoK::hra(transcript, generator, R, generator * private_key)),
|
s: nonce + (private_key * SchnorrPoK::hra(transcript, generator, R, generator * private_key)),
|
||||||
}
|
};
|
||||||
|
private_key.zeroize();
|
||||||
|
nonce.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn verify<R: RngCore + CryptoRng, T: Transcript>(
|
pub(crate) fn verify<R: RngCore + CryptoRng, T: Transcript>(
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
|
|
||||||
use ff::{Field, PrimeField};
|
use ff::{Field, PrimeField};
|
||||||
@@ -76,9 +78,12 @@ impl<G: PrimeGroup> DLEqProof<G> {
|
|||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
transcript: &mut T,
|
transcript: &mut T,
|
||||||
generators: &[G],
|
generators: &[G],
|
||||||
scalar: G::Scalar,
|
mut scalar: G::Scalar,
|
||||||
) -> DLEqProof<G> {
|
) -> DLEqProof<G>
|
||||||
let r = G::Scalar::random(rng);
|
where
|
||||||
|
G::Scalar: Zeroize,
|
||||||
|
{
|
||||||
|
let mut r = G::Scalar::random(rng);
|
||||||
|
|
||||||
transcript.domain_separate(b"dleq");
|
transcript.domain_separate(b"dleq");
|
||||||
for generator in generators {
|
for generator in generators {
|
||||||
@@ -88,6 +93,9 @@ impl<G: PrimeGroup> DLEqProof<G> {
|
|||||||
let c = challenge(transcript);
|
let c = challenge(transcript);
|
||||||
let s = r + (c * scalar);
|
let s = r + (c * scalar);
|
||||||
|
|
||||||
|
scalar.zeroize();
|
||||||
|
r.zeroize();
|
||||||
|
|
||||||
DLEqProof { c, s }
|
DLEqProof { c, s }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ fn test_aos<const RING_LEN: usize>(default: Re<G0, G1>) {
|
|||||||
generators,
|
generators,
|
||||||
&ring,
|
&ring,
|
||||||
actual,
|
actual,
|
||||||
ring_keys[actual],
|
&mut ring_keys[actual],
|
||||||
default.clone(),
|
default.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use rand_core::OsRng;
|
use rand_core::OsRng;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
ff::{Field, PrimeFieldBits},
|
ff::{Field, PrimeFieldBits},
|
||||||
prime::PrimeGroup,
|
prime::PrimeGroup,
|
||||||
@@ -10,9 +12,9 @@ use transcript::{Transcript, RecommendedTranscript};
|
|||||||
|
|
||||||
use crate::cross_group::schnorr::SchnorrPoK;
|
use crate::cross_group::schnorr::SchnorrPoK;
|
||||||
|
|
||||||
fn test_schnorr<G: PrimeGroup>()
|
fn test_schnorr<G: PrimeGroup + Zeroize>()
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
let private = G::Scalar::random(&mut OsRng);
|
let private = G::Scalar::random(&mut OsRng);
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ edition = "2021"
|
|||||||
thiserror = "1"
|
thiserror = "1"
|
||||||
|
|
||||||
rand_core = "0.6"
|
rand_core = "0.6"
|
||||||
|
|
||||||
|
zeroize = { version = "1.3", features = ["zeroize_derive"] }
|
||||||
|
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
|
|
||||||
sha2 = { version = "0.10", optional = true }
|
sha2 = { version = "0.10", optional = true }
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use sha2::{Digest, Sha512};
|
use sha2::{Digest, Sha512};
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ macro_rules! dalek_curve {
|
|||||||
) => {
|
) => {
|
||||||
use dalek_ff_group::{$Point, $POINT};
|
use dalek_ff_group::{$Point, $POINT};
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub struct $Curve;
|
pub struct $Curve;
|
||||||
impl Curve for $Curve {
|
impl Curve for $Curve {
|
||||||
type F = Scalar;
|
type F = Scalar;
|
||||||
@@ -30,13 +30,6 @@ macro_rules! dalek_curve {
|
|||||||
const ID: &'static [u8] = $ID;
|
const ID: &'static [u8] = $ID;
|
||||||
const GENERATOR: Self::G = $POINT;
|
const GENERATOR: Self::G = $POINT;
|
||||||
|
|
||||||
fn random_nonce<R: RngCore + CryptoRng>(secret: Self::F, rng: &mut R) -> Self::F {
|
|
||||||
let mut seed = vec![0; 32];
|
|
||||||
rng.fill_bytes(&mut seed);
|
|
||||||
seed.extend(&secret.to_bytes());
|
|
||||||
Self::hash_to_F(b"nonce", &seed)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hash_msg(msg: &[u8]) -> Vec<u8> {
|
fn hash_msg(msg: &[u8]) -> Vec<u8> {
|
||||||
Sha512::new()
|
Sha512::new()
|
||||||
.chain_update($CONTEXT)
|
.chain_update($CONTEXT)
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
use std::io::Cursor;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
|
||||||
|
|
||||||
use sha2::{digest::Update, Digest, Sha256};
|
use sha2::{digest::Update, Digest, Sha256};
|
||||||
|
|
||||||
use group::{ff::Field, GroupEncoding};
|
use group::{
|
||||||
|
ff::{Field, PrimeField},
|
||||||
|
GroupEncoding,
|
||||||
|
};
|
||||||
|
|
||||||
use elliptic_curve::{
|
use elliptic_curve::{
|
||||||
|
generic_array::GenericArray,
|
||||||
bigint::{Encoding, U384},
|
bigint::{Encoding, U384},
|
||||||
hash2curve::{Expander, ExpandMsg, ExpandMsgXmd},
|
hash2curve::{Expander, ExpandMsg, ExpandMsgXmd},
|
||||||
};
|
};
|
||||||
@@ -22,7 +24,7 @@ macro_rules! kp_curve {
|
|||||||
$ID: literal,
|
$ID: literal,
|
||||||
$CONTEXT: literal
|
$CONTEXT: literal
|
||||||
) => {
|
) => {
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Zeroize)]
|
||||||
pub struct $Curve;
|
pub struct $Curve;
|
||||||
impl Curve for $Curve {
|
impl Curve for $Curve {
|
||||||
type F = $lib::Scalar;
|
type F = $lib::Scalar;
|
||||||
@@ -31,13 +33,6 @@ macro_rules! kp_curve {
|
|||||||
const ID: &'static [u8] = $ID;
|
const ID: &'static [u8] = $ID;
|
||||||
const GENERATOR: Self::G = $lib::ProjectivePoint::GENERATOR;
|
const GENERATOR: Self::G = $lib::ProjectivePoint::GENERATOR;
|
||||||
|
|
||||||
fn random_nonce<R: RngCore + CryptoRng>(secret: Self::F, rng: &mut R) -> Self::F {
|
|
||||||
let mut seed = vec![0; 32];
|
|
||||||
rng.fill_bytes(&mut seed);
|
|
||||||
seed.extend(secret.to_bytes());
|
|
||||||
Self::hash_to_F(&[$CONTEXT as &[u8], b"nonce"].concat(), &seed)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hash_msg(msg: &[u8]) -> Vec<u8> {
|
fn hash_msg(msg: &[u8]) -> Vec<u8> {
|
||||||
(&Sha256::new().chain($CONTEXT).chain(b"digest").chain(msg).finalize()).to_vec()
|
(&Sha256::new().chain($CONTEXT).chain(b"digest").chain(msg).finalize()).to_vec()
|
||||||
}
|
}
|
||||||
@@ -58,17 +53,21 @@ macro_rules! kp_curve {
|
|||||||
let mut modulus = vec![0; 16];
|
let mut modulus = vec![0; 16];
|
||||||
modulus.extend((Self::F::zero() - Self::F::one()).to_bytes());
|
modulus.extend((Self::F::zero() - Self::F::one()).to_bytes());
|
||||||
let modulus = U384::from_be_slice(&modulus).wrapping_add(&U384::ONE);
|
let modulus = U384::from_be_slice(&modulus).wrapping_add(&U384::ONE);
|
||||||
Self::read_F(&mut Cursor::new(
|
|
||||||
&U384::from_be_slice(&{
|
let mut unreduced = U384::from_be_bytes({
|
||||||
let mut bytes = [0; 48];
|
let mut bytes = [0; 48];
|
||||||
ExpandMsgXmd::<Sha256>::expand_message(&[msg], dst, 48).unwrap().fill_bytes(&mut bytes);
|
ExpandMsgXmd::<Sha256>::expand_message(&[msg], dst, 48).unwrap().fill_bytes(&mut bytes);
|
||||||
bytes
|
bytes
|
||||||
})
|
})
|
||||||
.reduce(&modulus)
|
.reduce(&modulus)
|
||||||
.unwrap()
|
|
||||||
.to_be_bytes()[16 ..],
|
|
||||||
))
|
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
.to_be_bytes();
|
||||||
|
|
||||||
|
let mut array = *GenericArray::from_slice(&unreduced[16 ..]);
|
||||||
|
let res = $lib::Scalar::from_repr(array).unwrap();
|
||||||
|
unreduced.zeroize();
|
||||||
|
array.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ use thiserror::Error;
|
|||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::{PrimeField, PrimeFieldBits};
|
use ff::{PrimeField, PrimeFieldBits};
|
||||||
use group::{Group, GroupOps, GroupEncoding, prime::PrimeGroup};
|
use group::{Group, GroupOps, GroupEncoding, prime::PrimeGroup};
|
||||||
|
|
||||||
@@ -39,12 +41,12 @@ pub enum CurveError {
|
|||||||
// elliptic-curve exists, yet it doesn't really serve the same role, nor does it use &[u8]/Vec<u8>
|
// elliptic-curve exists, yet it doesn't really serve the same role, nor does it use &[u8]/Vec<u8>
|
||||||
// It uses GenericArray which will hopefully be deprecated as Rust evolves and doesn't offer enough
|
// It uses GenericArray which will hopefully be deprecated as Rust evolves and doesn't offer enough
|
||||||
// advantages in the modern day to be worth the hassle -- Kayaba
|
// advantages in the modern day to be worth the hassle -- Kayaba
|
||||||
pub trait Curve: Clone + Copy + PartialEq + Eq + Debug {
|
pub trait Curve: Clone + Copy + PartialEq + Eq + Debug + Zeroize {
|
||||||
/// Scalar field element type
|
/// Scalar field element type
|
||||||
// This is available via G::Scalar yet `C::G::Scalar` is ambiguous, forcing horrific accesses
|
// This is available via G::Scalar yet `C::G::Scalar` is ambiguous, forcing horrific accesses
|
||||||
type F: PrimeField + PrimeFieldBits;
|
type F: PrimeField + PrimeFieldBits + Zeroize;
|
||||||
/// Group element type
|
/// Group element type
|
||||||
type G: Group<Scalar = Self::F> + GroupOps + PrimeGroup;
|
type G: Group<Scalar = Self::F> + GroupOps + PrimeGroup + Zeroize;
|
||||||
|
|
||||||
/// ID for this curve
|
/// ID for this curve
|
||||||
const ID: &'static [u8];
|
const ID: &'static [u8];
|
||||||
@@ -53,9 +55,6 @@ pub trait Curve: Clone + Copy + PartialEq + Eq + Debug {
|
|||||||
// While group does provide this in its API, privacy coins may want to use a custom basepoint
|
// While group does provide this in its API, privacy coins may want to use a custom basepoint
|
||||||
const GENERATOR: Self::G;
|
const GENERATOR: Self::G;
|
||||||
|
|
||||||
/// Securely generate a random nonce. H4 from the IETF draft
|
|
||||||
fn random_nonce<R: RngCore + CryptoRng>(secret: Self::F, rng: &mut R) -> Self::F;
|
|
||||||
|
|
||||||
/// Hash the message for the binding factor. H3 from the IETF draft
|
/// Hash the message for the binding factor. H3 from the IETF draft
|
||||||
// This doesn't actually need to be part of Curve as it does nothing with the curve
|
// This doesn't actually need to be part of Curve as it does nothing with the curve
|
||||||
// This also solely relates to FROST and with a proper Algorithm/HRAM, all projects using
|
// This also solely relates to FROST and with a proper Algorithm/HRAM, all projects using
|
||||||
@@ -69,8 +68,23 @@ pub trait Curve: Clone + Copy + PartialEq + Eq + Debug {
|
|||||||
/// Hash the commitments and message to calculate the binding factor. H1 from the IETF draft
|
/// Hash the commitments and message to calculate the binding factor. H1 from the IETF draft
|
||||||
fn hash_binding_factor(binding: &[u8]) -> Self::F;
|
fn hash_binding_factor(binding: &[u8]) -> Self::F;
|
||||||
|
|
||||||
// The following methods would optimally be F:: and G:: yet developers can't control F/G
|
/// Securely generate a random nonce. H4 from the IETF draft
|
||||||
// They can control a trait they pass into this library
|
fn random_nonce<R: RngCore + CryptoRng>(mut secret: Self::F, rng: &mut R) -> Self::F {
|
||||||
|
let mut seed = vec![0; 32];
|
||||||
|
rng.fill_bytes(&mut seed);
|
||||||
|
|
||||||
|
let mut repr = secret.to_repr();
|
||||||
|
secret.zeroize();
|
||||||
|
|
||||||
|
seed.extend(repr.as_ref());
|
||||||
|
for i in repr.as_mut() {
|
||||||
|
*i = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = Self::hash_to_F(b"nonce", &seed);
|
||||||
|
seed.zeroize();
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
/// Field element from hash. Used during key gen and by other crates under Serai as a general
|
/// Field element from hash. Used during key gen and by other crates under Serai as a general
|
||||||
/// utility
|
/// utility
|
||||||
@@ -93,8 +107,14 @@ pub trait Curve: Clone + Copy + PartialEq + Eq + Debug {
|
|||||||
fn read_F<R: Read>(r: &mut R) -> Result<Self::F, CurveError> {
|
fn read_F<R: Read>(r: &mut R) -> Result<Self::F, CurveError> {
|
||||||
let mut encoding = <Self::F as PrimeField>::Repr::default();
|
let mut encoding = <Self::F as PrimeField>::Repr::default();
|
||||||
r.read_exact(encoding.as_mut()).map_err(|_| CurveError::InvalidScalar)?;
|
r.read_exact(encoding.as_mut()).map_err(|_| CurveError::InvalidScalar)?;
|
||||||
|
|
||||||
// ff mandates this is canonical
|
// ff mandates this is canonical
|
||||||
Option::<Self::F>::from(Self::F::from_repr(encoding)).ok_or(CurveError::InvalidScalar)
|
let res =
|
||||||
|
Option::<Self::F>::from(Self::F::from_repr(encoding)).ok_or(CurveError::InvalidScalar);
|
||||||
|
for b in encoding.as_mut() {
|
||||||
|
*b = 0;
|
||||||
|
}
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ use std::{
|
|||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
ff::{Field, PrimeField},
|
ff::{Field, PrimeField},
|
||||||
GroupEncoding,
|
GroupEncoding,
|
||||||
@@ -15,7 +17,7 @@ use multiexp::{multiexp_vartime, BatchVerifier};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
curve::Curve,
|
curve::Curve,
|
||||||
FrostError, FrostParams, FrostKeys,
|
FrostError, FrostParams, FrostCore,
|
||||||
schnorr::{self, SchnorrSignature},
|
schnorr::{self, SchnorrSignature},
|
||||||
validate_map,
|
validate_map,
|
||||||
};
|
};
|
||||||
@@ -54,7 +56,7 @@ fn generate_key_r1<R: RngCore + CryptoRng, C: Curve>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 2: Provide a proof of knowledge
|
// Step 2: Provide a proof of knowledge
|
||||||
let r = C::F::random(rng);
|
let mut r = C::F::random(rng);
|
||||||
serialized.extend(
|
serialized.extend(
|
||||||
schnorr::sign::<C>(
|
schnorr::sign::<C>(
|
||||||
coefficients[0],
|
coefficients[0],
|
||||||
@@ -67,6 +69,7 @@ fn generate_key_r1<R: RngCore + CryptoRng, C: Curve>(
|
|||||||
)
|
)
|
||||||
.serialize(),
|
.serialize(),
|
||||||
);
|
);
|
||||||
|
r.zeroize();
|
||||||
|
|
||||||
// Step 4: Broadcast
|
// Step 4: Broadcast
|
||||||
(coefficients, commitments, serialized)
|
(coefficients, commitments, serialized)
|
||||||
@@ -148,7 +151,7 @@ fn generate_key_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
params: &FrostParams,
|
params: &FrostParams,
|
||||||
context: &str,
|
context: &str,
|
||||||
coefficients: Vec<C::F>,
|
coefficients: &mut Vec<C::F>,
|
||||||
our_commitments: Vec<C::G>,
|
our_commitments: Vec<C::G>,
|
||||||
commitments: HashMap<u16, Re>,
|
commitments: HashMap<u16, Re>,
|
||||||
) -> Result<(C::F, HashMap<u16, Vec<C::G>>, HashMap<u16, Vec<u8>>), FrostError> {
|
) -> Result<(C::F, HashMap<u16, Vec<C::G>>, HashMap<u16, Vec<u8>>), FrostError> {
|
||||||
@@ -163,19 +166,13 @@ fn generate_key_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.insert(l, polynomial(&coefficients, l).to_repr().as_ref().to_vec());
|
res.insert(l, polynomial(coefficients, l).to_repr().as_ref().to_vec());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate our own share
|
// Calculate our own share
|
||||||
let share = polynomial(&coefficients, params.i());
|
let share = polynomial(coefficients, params.i());
|
||||||
|
|
||||||
// The secret shares are discarded here, not cleared. While any system which leaves its memory
|
coefficients.zeroize();
|
||||||
// accessible is likely totally lost already, making the distinction meaningless when the key gen
|
|
||||||
// system acts as the signer system and therefore actively holds the signing key anyways, it
|
|
||||||
// should be overwritten with /dev/urandom in the name of security (which still doesn't meet
|
|
||||||
// requirements for secure data deletion yet those requirements expect hardware access which is
|
|
||||||
// far past what this library can reasonably counter)
|
|
||||||
// TODO: Zero out the coefficients
|
|
||||||
|
|
||||||
Ok((share, commitments, res))
|
Ok((share, commitments, res))
|
||||||
}
|
}
|
||||||
@@ -189,17 +186,17 @@ fn complete_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
params: FrostParams,
|
params: FrostParams,
|
||||||
mut secret_share: C::F,
|
mut secret_share: C::F,
|
||||||
commitments: HashMap<u16, Vec<C::G>>,
|
commitments: &mut HashMap<u16, Vec<C::G>>,
|
||||||
mut serialized: HashMap<u16, Re>,
|
mut serialized: HashMap<u16, Re>,
|
||||||
) -> Result<FrostKeys<C>, FrostError> {
|
) -> Result<FrostCore<C>, FrostError> {
|
||||||
validate_map(&mut serialized, &(1 ..= params.n()).collect::<Vec<_>>(), params.i())?;
|
validate_map(&mut serialized, &(1 ..= params.n()).collect::<Vec<_>>(), params.i())?;
|
||||||
|
|
||||||
// Step 2. Verify each share
|
// Step 2. Verify each share
|
||||||
let mut shares = HashMap::new();
|
let mut shares = HashMap::new();
|
||||||
|
// TODO: Clear serialized
|
||||||
for (l, share) in serialized.iter_mut() {
|
for (l, share) in serialized.iter_mut() {
|
||||||
shares.insert(*l, C::read_F(share).map_err(|_| FrostError::InvalidShare(*l))?);
|
shares.insert(*l, C::read_F(share).map_err(|_| FrostError::InvalidShare(*l))?);
|
||||||
}
|
}
|
||||||
shares.insert(params.i(), secret_share);
|
|
||||||
|
|
||||||
// Calculate the exponent for a given participant and apply it to a series of commitments
|
// Calculate the exponent for a given participant and apply it to a series of commitments
|
||||||
// Initially used with the actual commitments to verify the secret share, later used with stripes
|
// Initially used with the actual commitments to verify the secret share, later used with stripes
|
||||||
@@ -215,12 +212,12 @@ fn complete_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut batch = BatchVerifier::new(shares.len());
|
let mut batch = BatchVerifier::new(shares.len());
|
||||||
for (l, share) in &shares {
|
for (l, share) in shares.iter_mut() {
|
||||||
if *l == params.i() {
|
if *l == params.i() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
secret_share += share;
|
secret_share += *share;
|
||||||
|
|
||||||
// This can be insecurely linearized from n * t to just n using the below sums for a given
|
// This can be insecurely linearized from n * t to just n using the below sums for a given
|
||||||
// stripe. Doing so uses naive addition which is subject to malleability. The only way to
|
// stripe. Doing so uses naive addition which is subject to malleability. The only way to
|
||||||
@@ -228,6 +225,8 @@ fn complete_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
// per sender and not as an aggregate of all senders, which also enables blame
|
// per sender and not as an aggregate of all senders, which also enables blame
|
||||||
let mut values = exponential(params.i, &commitments[l]);
|
let mut values = exponential(params.i, &commitments[l]);
|
||||||
values.push((-*share, C::GENERATOR));
|
values.push((-*share, C::GENERATOR));
|
||||||
|
share.zeroize();
|
||||||
|
|
||||||
batch.queue(rng, *l, values);
|
batch.queue(rng, *l, values);
|
||||||
}
|
}
|
||||||
batch.verify_with_vartime_blame().map_err(FrostError::InvalidCommitment)?;
|
batch.verify_with_vartime_blame().map_err(FrostError::InvalidCommitment)?;
|
||||||
@@ -249,9 +248,7 @@ fn complete_r2<Re: Read, R: RngCore + CryptoRng, C: Curve>(
|
|||||||
// Removing this check would enable optimizing the above from t + (n * t) to t + ((n - 1) * t)
|
// Removing this check would enable optimizing the above from t + (n * t) to t + ((n - 1) * t)
|
||||||
debug_assert_eq!(C::GENERATOR * secret_share, verification_shares[¶ms.i()]);
|
debug_assert_eq!(C::GENERATOR * secret_share, verification_shares[¶ms.i()]);
|
||||||
|
|
||||||
// TODO: Clear serialized and shares
|
Ok(FrostCore { params, secret_share, group_key: stripes[0], verification_shares })
|
||||||
|
|
||||||
Ok(FrostKeys { params, secret_share, group_key: stripes[0], verification_shares, offset: None })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct KeyGenMachine<C: Curve> {
|
pub struct KeyGenMachine<C: Curve> {
|
||||||
@@ -260,19 +257,37 @@ pub struct KeyGenMachine<C: Curve> {
|
|||||||
_curve: PhantomData<C>,
|
_curve: PhantomData<C>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Zeroize)]
|
||||||
pub struct SecretShareMachine<C: Curve> {
|
pub struct SecretShareMachine<C: Curve> {
|
||||||
|
#[zeroize(skip)]
|
||||||
params: FrostParams,
|
params: FrostParams,
|
||||||
context: String,
|
context: String,
|
||||||
coefficients: Vec<C::F>,
|
coefficients: Vec<C::F>,
|
||||||
|
#[zeroize(skip)]
|
||||||
our_commitments: Vec<C::G>,
|
our_commitments: Vec<C::G>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> Drop for SecretShareMachine<C> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.zeroize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Zeroize)]
|
||||||
pub struct KeyMachine<C: Curve> {
|
pub struct KeyMachine<C: Curve> {
|
||||||
|
#[zeroize(skip)]
|
||||||
params: FrostParams,
|
params: FrostParams,
|
||||||
secret: C::F,
|
secret: C::F,
|
||||||
|
#[zeroize(skip)]
|
||||||
commitments: HashMap<u16, Vec<C::G>>,
|
commitments: HashMap<u16, Vec<C::G>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> Drop for KeyMachine<C> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.zeroize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<C: Curve> KeyGenMachine<C> {
|
impl<C: Curve> KeyGenMachine<C> {
|
||||||
/// Creates a new machine to generate a key for the specified curve in the specified multisig
|
/// Creates a new machine to generate a key for the specified curve in the specified multisig
|
||||||
// The context string must be unique among multisigs
|
// The context string must be unique among multisigs
|
||||||
@@ -309,7 +324,7 @@ impl<C: Curve> SecretShareMachine<C> {
|
|||||||
/// is also expected at index i which is locally handled. Returns a byte vector representing a
|
/// is also expected at index i which is locally handled. Returns a byte vector representing a
|
||||||
/// secret share for each other participant which should be encrypted before sending
|
/// secret share for each other participant which should be encrypted before sending
|
||||||
pub fn generate_secret_shares<Re: Read, R: RngCore + CryptoRng>(
|
pub fn generate_secret_shares<Re: Read, R: RngCore + CryptoRng>(
|
||||||
self,
|
mut self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
commitments: HashMap<u16, Re>,
|
commitments: HashMap<u16, Re>,
|
||||||
) -> Result<(KeyMachine<C>, HashMap<u16, Vec<u8>>), FrostError> {
|
) -> Result<(KeyMachine<C>, HashMap<u16, Vec<u8>>), FrostError> {
|
||||||
@@ -317,8 +332,8 @@ impl<C: Curve> SecretShareMachine<C> {
|
|||||||
rng,
|
rng,
|
||||||
&self.params,
|
&self.params,
|
||||||
&self.context,
|
&self.context,
|
||||||
self.coefficients,
|
&mut self.coefficients,
|
||||||
self.our_commitments,
|
self.our_commitments.clone(),
|
||||||
commitments,
|
commitments,
|
||||||
)?;
|
)?;
|
||||||
Ok((KeyMachine { params: self.params, secret, commitments }, shares))
|
Ok((KeyMachine { params: self.params, secret, commitments }, shares))
|
||||||
@@ -333,10 +348,10 @@ impl<C: Curve> KeyMachine<C> {
|
|||||||
/// must report completion without issue before this key can be considered usable, yet you should
|
/// must report completion without issue before this key can be considered usable, yet you should
|
||||||
/// wait for all participants to report as such
|
/// wait for all participants to report as such
|
||||||
pub fn complete<Re: Read, R: RngCore + CryptoRng>(
|
pub fn complete<Re: Read, R: RngCore + CryptoRng>(
|
||||||
self,
|
mut self,
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
shares: HashMap<u16, Re>,
|
shares: HashMap<u16, Re>,
|
||||||
) -> Result<FrostKeys<C>, FrostError> {
|
) -> Result<FrostCore<C>, FrostError> {
|
||||||
complete_r2(rng, self.params, self.secret, self.commitments, shares)
|
complete_r2(rng, self.params, self.secret, &mut self.commitments, shares)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
use core::fmt::Debug;
|
use core::fmt::{self, Debug};
|
||||||
use std::{io::Read, collections::HashMap};
|
use std::{io::Read, sync::Arc, collections::HashMap};
|
||||||
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
ff::{Field, PrimeField},
|
ff::{Field, PrimeField},
|
||||||
GroupEncoding,
|
GroupEncoding,
|
||||||
@@ -18,6 +20,32 @@ pub mod sign;
|
|||||||
|
|
||||||
pub mod tests;
|
pub mod tests;
|
||||||
|
|
||||||
|
// Validate a map of serialized values to have the expected included participants
|
||||||
|
pub(crate) fn validate_map<T>(
|
||||||
|
map: &mut HashMap<u16, T>,
|
||||||
|
included: &[u16],
|
||||||
|
ours: u16,
|
||||||
|
) -> Result<(), FrostError> {
|
||||||
|
if (map.len() + 1) != included.len() {
|
||||||
|
Err(FrostError::InvalidParticipantQuantity(included.len(), map.len() + 1))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
for included in included {
|
||||||
|
if *included == ours {
|
||||||
|
if map.contains_key(included) {
|
||||||
|
Err(FrostError::DuplicatedIndex(*included))?;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !map.contains_key(included) {
|
||||||
|
Err(FrostError::MissingParticipant(*included))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Parameters for a multisig
|
/// Parameters for a multisig
|
||||||
// These fields can not be made public as they should be static
|
// These fields can not be made public as they should be static
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
@@ -89,33 +117,6 @@ pub enum FrostError {
|
|||||||
InternalError(&'static str),
|
InternalError(&'static str),
|
||||||
}
|
}
|
||||||
|
|
||||||
// View of keys passable to algorithm implementations
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct FrostView<C: Curve> {
|
|
||||||
group_key: C::G,
|
|
||||||
included: Vec<u16>,
|
|
||||||
secret_share: C::F,
|
|
||||||
verification_shares: HashMap<u16, C::G>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: Curve> FrostView<C> {
|
|
||||||
pub fn group_key(&self) -> C::G {
|
|
||||||
self.group_key
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn included(&self) -> Vec<u16> {
|
|
||||||
self.included.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn secret_share(&self) -> C::F {
|
|
||||||
self.secret_share
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn verification_share(&self, l: u16) -> C::G {
|
|
||||||
self.verification_shares[&l]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Calculate the lagrange coefficient for a signing set
|
/// Calculate the lagrange coefficient for a signing set
|
||||||
pub fn lagrange<F: PrimeField>(i: u16, included: &[u16]) -> F {
|
pub fn lagrange<F: PrimeField>(i: u16, included: &[u16]) -> F {
|
||||||
let mut num = F::one();
|
let mut num = F::one();
|
||||||
@@ -135,9 +136,11 @@ pub fn lagrange<F: PrimeField>(i: u16, included: &[u16]) -> F {
|
|||||||
num * denom.invert().unwrap()
|
num * denom.invert().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
/// Core keys generated by performing a FROST keygen protocol
|
||||||
pub struct FrostKeys<C: Curve> {
|
#[derive(Clone, PartialEq, Eq, Zeroize)]
|
||||||
|
pub struct FrostCore<C: Curve> {
|
||||||
/// FROST Parameters
|
/// FROST Parameters
|
||||||
|
#[zeroize(skip)]
|
||||||
params: FrostParams,
|
params: FrostParams,
|
||||||
|
|
||||||
/// Secret share key
|
/// Secret share key
|
||||||
@@ -145,32 +148,32 @@ pub struct FrostKeys<C: Curve> {
|
|||||||
/// Group key
|
/// Group key
|
||||||
group_key: C::G,
|
group_key: C::G,
|
||||||
/// Verification shares
|
/// Verification shares
|
||||||
|
#[zeroize(skip)]
|
||||||
verification_shares: HashMap<u16, C::G>,
|
verification_shares: HashMap<u16, C::G>,
|
||||||
|
|
||||||
/// Offset applied to these keys
|
|
||||||
offset: Option<C::F>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C: Curve> FrostKeys<C> {
|
impl<C: Curve> Drop for FrostCore<C> {
|
||||||
/// Offset the keys by a given scalar to allow for account and privacy schemes
|
fn drop(&mut self) {
|
||||||
/// This offset is ephemeral and will not be included when these keys are serialized
|
self.zeroize()
|
||||||
/// Keys offset multiple times will form a new offset of their sum
|
|
||||||
/// Not IETF compliant
|
|
||||||
pub fn offset(&self, offset: C::F) -> FrostKeys<C> {
|
|
||||||
let mut res = self.clone();
|
|
||||||
// Carry any existing offset
|
|
||||||
// Enables schemes like Monero's subaddresses which have a per-subaddress offset and then a
|
|
||||||
// one-time-key offset
|
|
||||||
res.offset = Some(offset + res.offset.unwrap_or_else(C::F::zero));
|
|
||||||
res.group_key += C::GENERATOR * offset;
|
|
||||||
res
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> Debug for FrostCore<C> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("FrostCore")
|
||||||
|
.field("params", &self.params)
|
||||||
|
.field("group_key", &self.group_key)
|
||||||
|
.field("verification_shares", &self.verification_shares)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> FrostCore<C> {
|
||||||
pub fn params(&self) -> FrostParams {
|
pub fn params(&self) -> FrostParams {
|
||||||
self.params
|
self.params
|
||||||
}
|
}
|
||||||
|
|
||||||
fn secret_share(&self) -> C::F {
|
pub(crate) fn secret_share(&self) -> C::F {
|
||||||
self.secret_share
|
self.secret_share
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,39 +181,16 @@ impl<C: Curve> FrostKeys<C> {
|
|||||||
self.group_key
|
self.group_key
|
||||||
}
|
}
|
||||||
|
|
||||||
fn verification_shares(&self) -> HashMap<u16, C::G> {
|
pub(crate) fn verification_shares(&self) -> HashMap<u16, C::G> {
|
||||||
self.verification_shares.clone()
|
self.verification_shares.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view(&self, included: &[u16]) -> Result<FrostView<C>, FrostError> {
|
|
||||||
if (included.len() < self.params.t.into()) || (usize::from(self.params.n) < included.len()) {
|
|
||||||
Err(FrostError::InvalidSigningSet("invalid amount of participants included"))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let secret_share = self.secret_share * lagrange::<C::F>(self.params.i, included);
|
|
||||||
let offset = self.offset.unwrap_or_else(C::F::zero);
|
|
||||||
let offset_share = offset * C::F::from(included.len().try_into().unwrap()).invert().unwrap();
|
|
||||||
|
|
||||||
Ok(FrostView {
|
|
||||||
group_key: self.group_key,
|
|
||||||
secret_share: secret_share + offset_share,
|
|
||||||
verification_shares: self
|
|
||||||
.verification_shares
|
|
||||||
.iter()
|
|
||||||
.map(|(l, share)| {
|
|
||||||
(*l, (*share * lagrange::<C::F>(*l, included)) + (C::GENERATOR * offset_share))
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
included: included.to_vec(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn serialized_len(n: u16) -> usize {
|
pub fn serialized_len(n: u16) -> usize {
|
||||||
8 + C::ID.len() + (3 * 2) + C::F_len() + C::G_len() + (usize::from(n) * C::G_len())
|
8 + C::ID.len() + (3 * 2) + C::F_len() + C::G_len() + (usize::from(n) * C::G_len())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn serialize(&self) -> Vec<u8> {
|
pub fn serialize(&self) -> Vec<u8> {
|
||||||
let mut serialized = Vec::with_capacity(FrostKeys::<C>::serialized_len(self.params.n));
|
let mut serialized = Vec::with_capacity(FrostCore::<C>::serialized_len(self.params.n));
|
||||||
serialized.extend(u32::try_from(C::ID.len()).unwrap().to_be_bytes());
|
serialized.extend(u32::try_from(C::ID.len()).unwrap().to_be_bytes());
|
||||||
serialized.extend(C::ID);
|
serialized.extend(C::ID);
|
||||||
serialized.extend(&self.params.t.to_be_bytes());
|
serialized.extend(&self.params.t.to_be_bytes());
|
||||||
@@ -224,10 +204,10 @@ impl<C: Curve> FrostKeys<C> {
|
|||||||
serialized
|
serialized
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deserialize<R: Read>(cursor: &mut R) -> Result<FrostKeys<C>, FrostError> {
|
pub fn deserialize<R: Read>(cursor: &mut R) -> Result<FrostCore<C>, FrostError> {
|
||||||
{
|
{
|
||||||
let missing = FrostError::InternalError("FrostKeys serialization is missing its curve");
|
let missing = FrostError::InternalError("FrostCore serialization is missing its curve");
|
||||||
let different = FrostError::InternalError("deserializing FrostKeys for another curve");
|
let different = FrostError::InternalError("deserializing FrostCore for another curve");
|
||||||
|
|
||||||
let mut id_len = [0; 4];
|
let mut id_len = [0; 4];
|
||||||
cursor.read_exact(&mut id_len).map_err(|_| missing)?;
|
cursor.read_exact(&mut id_len).map_err(|_| missing)?;
|
||||||
@@ -266,39 +246,133 @@ impl<C: Curve> FrostKeys<C> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(FrostKeys {
|
Ok(FrostCore {
|
||||||
params: FrostParams::new(t, n, i)
|
params: FrostParams::new(t, n, i)
|
||||||
.map_err(|_| FrostError::InternalError("invalid parameters"))?,
|
.map_err(|_| FrostError::InternalError("invalid parameters"))?,
|
||||||
secret_share,
|
secret_share,
|
||||||
group_key,
|
group_key,
|
||||||
verification_shares,
|
verification_shares,
|
||||||
offset: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate a map of serialized values to have the expected included participants
|
/// FROST keys usable for signing
|
||||||
pub(crate) fn validate_map<T>(
|
#[derive(Clone, Debug, Zeroize)]
|
||||||
map: &mut HashMap<u16, T>,
|
pub struct FrostKeys<C: Curve> {
|
||||||
included: &[u16],
|
/// Core keys
|
||||||
ours: u16,
|
#[zeroize(skip)]
|
||||||
) -> Result<(), FrostError> {
|
core: Arc<FrostCore<C>>,
|
||||||
if (map.len() + 1) != included.len() {
|
|
||||||
Err(FrostError::InvalidParticipantQuantity(included.len(), map.len() + 1))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
for included in included {
|
/// Offset applied to these keys
|
||||||
if *included == ours {
|
pub(crate) offset: Option<C::F>,
|
||||||
if map.contains_key(included) {
|
}
|
||||||
Err(FrostError::DuplicatedIndex(*included))?;
|
|
||||||
}
|
// Manually implement Drop due to https://github.com/RustCrypto/utils/issues/786
|
||||||
continue;
|
impl<C: Curve> Drop for FrostKeys<C> {
|
||||||
}
|
fn drop(&mut self) {
|
||||||
|
self.zeroize()
|
||||||
if !map.contains_key(included) {
|
}
|
||||||
Err(FrostError::MissingParticipant(*included))?;
|
}
|
||||||
}
|
|
||||||
}
|
// View of keys passable to algorithm implementations
|
||||||
|
#[derive(Clone, Zeroize)]
|
||||||
Ok(())
|
pub struct FrostView<C: Curve> {
|
||||||
|
group_key: C::G,
|
||||||
|
#[zeroize(skip)]
|
||||||
|
included: Vec<u16>,
|
||||||
|
secret_share: C::F,
|
||||||
|
#[zeroize(skip)]
|
||||||
|
verification_shares: HashMap<u16, C::G>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> Drop for FrostView<C> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.zeroize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> FrostKeys<C> {
|
||||||
|
pub fn new(core: FrostCore<C>) -> FrostKeys<C> {
|
||||||
|
FrostKeys { core: Arc::new(core), offset: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Offset the keys by a given scalar to allow for account and privacy schemes
|
||||||
|
/// This offset is ephemeral and will not be included when these keys are serialized
|
||||||
|
/// Keys offset multiple times will form a new offset of their sum
|
||||||
|
/// Not IETF compliant
|
||||||
|
pub fn offset(&self, offset: C::F) -> FrostKeys<C> {
|
||||||
|
let mut res = self.clone();
|
||||||
|
// Carry any existing offset
|
||||||
|
// Enables schemes like Monero's subaddresses which have a per-subaddress offset and then a
|
||||||
|
// one-time-key offset
|
||||||
|
res.offset = Some(offset + res.offset.unwrap_or_else(C::F::zero));
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn params(&self) -> FrostParams {
|
||||||
|
self.core.params
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn secret_share(&self) -> C::F {
|
||||||
|
self.core.secret_share
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn group_key(&self) -> C::G {
|
||||||
|
self.core.group_key + (C::GENERATOR * self.offset.unwrap_or_else(C::F::zero))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn verification_shares(&self) -> HashMap<u16, C::G> {
|
||||||
|
self.core.verification_shares.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn serialized_len(n: u16) -> usize {
|
||||||
|
FrostCore::<C>::serialized_len(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn serialize(&self) -> Vec<u8> {
|
||||||
|
self.core.serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(&self, included: &[u16]) -> Result<FrostView<C>, FrostError> {
|
||||||
|
if (included.len() < self.params().t.into()) || (usize::from(self.params().n) < included.len())
|
||||||
|
{
|
||||||
|
Err(FrostError::InvalidSigningSet("invalid amount of participants included"))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let offset_share = self.offset.unwrap_or_else(C::F::zero) *
|
||||||
|
C::F::from(included.len().try_into().unwrap()).invert().unwrap();
|
||||||
|
let offset_verification_share = C::GENERATOR * offset_share;
|
||||||
|
|
||||||
|
Ok(FrostView {
|
||||||
|
group_key: self.group_key(),
|
||||||
|
secret_share: (self.secret_share() * lagrange::<C::F>(self.params().i, included)) +
|
||||||
|
offset_share,
|
||||||
|
verification_shares: self
|
||||||
|
.verification_shares()
|
||||||
|
.iter()
|
||||||
|
.map(|(l, share)| {
|
||||||
|
(*l, (*share * lagrange::<C::F>(*l, included)) + offset_verification_share)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
included: included.to_vec(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> FrostView<C> {
|
||||||
|
pub fn group_key(&self) -> C::G {
|
||||||
|
self.group_key
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn included(&self) -> Vec<u16> {
|
||||||
|
self.included.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn secret_share(&self) -> C::F {
|
||||||
|
self.secret_share
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verification_share(&self, l: u16) -> C::G {
|
||||||
|
self.verification_shares[&l]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
ff::{Field, PrimeField},
|
ff::{Field, PrimeField},
|
||||||
GroupEncoding,
|
GroupEncoding,
|
||||||
@@ -26,11 +28,14 @@ impl<C: Curve> SchnorrSignature<C> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn sign<C: Curve>(
|
pub(crate) fn sign<C: Curve>(
|
||||||
private_key: C::F,
|
mut private_key: C::F,
|
||||||
nonce: C::F,
|
mut nonce: C::F,
|
||||||
challenge: C::F,
|
challenge: C::F,
|
||||||
) -> SchnorrSignature<C> {
|
) -> SchnorrSignature<C> {
|
||||||
SchnorrSignature { R: C::GENERATOR * nonce, s: nonce + (private_key * challenge) }
|
let res = SchnorrSignature { R: C::GENERATOR * nonce, s: nonce + (private_key * challenge) };
|
||||||
|
private_key.zeroize();
|
||||||
|
nonce.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
use core::fmt;
|
use core::fmt;
|
||||||
use std::{
|
use std::{
|
||||||
io::{Read, Cursor},
|
io::{Read, Cursor},
|
||||||
sync::Arc,
|
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
};
|
};
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use transcript::Transcript;
|
use transcript::Transcript;
|
||||||
|
|
||||||
use group::{
|
use group::{
|
||||||
@@ -25,7 +26,7 @@ use crate::{
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Params<C: Curve, A: Algorithm<C>> {
|
pub struct Params<C: Curve, A: Algorithm<C>> {
|
||||||
algorithm: A,
|
algorithm: A,
|
||||||
keys: Arc<FrostKeys<C>>,
|
keys: FrostKeys<C>,
|
||||||
view: FrostView<C>,
|
view: FrostView<C>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,23 +34,25 @@ pub struct Params<C: Curve, A: Algorithm<C>> {
|
|||||||
impl<C: Curve, A: Algorithm<C>> Params<C, A> {
|
impl<C: Curve, A: Algorithm<C>> Params<C, A> {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
algorithm: A,
|
algorithm: A,
|
||||||
keys: Arc<FrostKeys<C>>,
|
keys: FrostKeys<C>,
|
||||||
included: &[u16],
|
included: &[u16],
|
||||||
) -> Result<Params<C, A>, FrostError> {
|
) -> Result<Params<C, A>, FrostError> {
|
||||||
|
let params = keys.params();
|
||||||
|
|
||||||
let mut included = included.to_vec();
|
let mut included = included.to_vec();
|
||||||
included.sort_unstable();
|
included.sort_unstable();
|
||||||
|
|
||||||
// Included < threshold
|
// Included < threshold
|
||||||
if included.len() < usize::from(keys.params.t) {
|
if included.len() < usize::from(params.t) {
|
||||||
Err(FrostError::InvalidSigningSet("not enough signers"))?;
|
Err(FrostError::InvalidSigningSet("not enough signers"))?;
|
||||||
}
|
}
|
||||||
// Invalid index
|
// Invalid index
|
||||||
if included[0] == 0 {
|
if included[0] == 0 {
|
||||||
Err(FrostError::InvalidParticipantIndex(included[0], keys.params.n))?;
|
Err(FrostError::InvalidParticipantIndex(included[0], params.n))?;
|
||||||
}
|
}
|
||||||
// OOB index
|
// OOB index
|
||||||
if included[included.len() - 1] > keys.params.n {
|
if included[included.len() - 1] > params.n {
|
||||||
Err(FrostError::InvalidParticipantIndex(included[included.len() - 1], keys.params.n))?;
|
Err(FrostError::InvalidParticipantIndex(included[included.len() - 1], params.n))?;
|
||||||
}
|
}
|
||||||
// Same signer included multiple times
|
// Same signer included multiple times
|
||||||
for i in 0 .. included.len() - 1 {
|
for i in 0 .. included.len() - 1 {
|
||||||
@@ -58,7 +61,7 @@ impl<C: Curve, A: Algorithm<C>> Params<C, A> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Not included
|
// Not included
|
||||||
if !included.contains(&keys.params.i) {
|
if !included.contains(¶ms.i) {
|
||||||
Err(FrostError::InvalidSigningSet("signing despite not being included"))?;
|
Err(FrostError::InvalidSigningSet("signing despite not being included"))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,7 +70,7 @@ impl<C: Curve, A: Algorithm<C>> Params<C, A> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn multisig_params(&self) -> FrostParams {
|
pub fn multisig_params(&self) -> FrostParams {
|
||||||
self.keys.params
|
self.keys.params()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn view(&self) -> FrostView<C> {
|
pub fn view(&self) -> FrostView<C> {
|
||||||
@@ -79,12 +82,20 @@ fn nonce_transcript<T: Transcript>() -> T {
|
|||||||
T::new(b"FROST_nonce_dleq")
|
T::new(b"FROST_nonce_dleq")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Zeroize)]
|
||||||
pub(crate) struct PreprocessPackage<C: Curve> {
|
pub(crate) struct PreprocessPackage<C: Curve> {
|
||||||
pub(crate) nonces: Vec<[C::F; 2]>,
|
pub(crate) nonces: Vec<[C::F; 2]>,
|
||||||
|
#[zeroize(skip)]
|
||||||
pub(crate) commitments: Vec<Vec<[C::G; 2]>>,
|
pub(crate) commitments: Vec<Vec<[C::G; 2]>>,
|
||||||
pub(crate) addendum: Vec<u8>,
|
pub(crate) addendum: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<C: Curve> Drop for PreprocessPackage<C> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.zeroize()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// This library unifies the preprocessing step with signing due to security concerns and to provide
|
// This library unifies the preprocessing step with signing due to security concerns and to provide
|
||||||
// a simpler UX
|
// a simpler UX
|
||||||
fn preprocess<R: RngCore + CryptoRng, C: Curve, A: Algorithm<C>>(
|
fn preprocess<R: RngCore + CryptoRng, C: Curve, A: Algorithm<C>>(
|
||||||
@@ -122,10 +133,11 @@ fn preprocess<R: RngCore + CryptoRng, C: Curve, A: Algorithm<C>>(
|
|||||||
|
|
||||||
// This could be further optimized with a multi-nonce proof.
|
// This could be further optimized with a multi-nonce proof.
|
||||||
// See https://github.com/serai-dex/serai/issues/38
|
// See https://github.com/serai-dex/serai/issues/38
|
||||||
for nonce in nonces {
|
for mut nonce in nonces {
|
||||||
DLEqProof::prove(&mut *rng, &mut transcript, generators, nonce)
|
DLEqProof::prove(&mut *rng, &mut transcript, generators, nonce)
|
||||||
.serialize(&mut serialized)
|
.serialize(&mut serialized)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
nonce.zeroize();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,7 +202,7 @@ fn sign_with_share<Re: Read, C: Curve, A: Algorithm<C>>(
|
|||||||
t.append_message(b"commitment_E", commitments[1].to_bytes().as_ref());
|
t.append_message(b"commitment_E", commitments[1].to_bytes().as_ref());
|
||||||
};
|
};
|
||||||
|
|
||||||
if *l == params.keys.params.i {
|
if *l == params.keys.params().i {
|
||||||
for nonce_commitments in &our_preprocess.commitments {
|
for nonce_commitments in &our_preprocess.commitments {
|
||||||
for commitments in nonce_commitments {
|
for commitments in nonce_commitments {
|
||||||
transcript(params.algorithm.transcript(), *commitments);
|
transcript(params.algorithm.transcript(), *commitments);
|
||||||
@@ -282,16 +294,15 @@ fn sign_with_share<Re: Read, C: Curve, A: Algorithm<C>>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let share = params.algorithm.sign_share(
|
let mut nonces = our_preprocess
|
||||||
¶ms.view,
|
.nonces
|
||||||
&Rs,
|
.iter()
|
||||||
&our_preprocess
|
.map(|nonces| nonces[0] + (nonces[1] * B[¶ms.keys.params().i()].1))
|
||||||
.nonces
|
.collect::<Vec<_>>();
|
||||||
.iter()
|
|
||||||
.map(|nonces| nonces[0] + (nonces[1] * B[¶ms.keys.params.i()].1))
|
let share = params.algorithm.sign_share(¶ms.view, &Rs, &nonces, msg);
|
||||||
.collect::<Vec<_>>(),
|
nonces.zeroize();
|
||||||
msg,
|
|
||||||
);
|
|
||||||
Ok((Package { B, Rs, share }, share.to_repr().as_ref().to_vec()))
|
Ok((Package { B, Rs, share }, share.to_repr().as_ref().to_vec()))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,7 +408,7 @@ impl<C: Curve, A: Algorithm<C>> AlgorithmMachine<C, A> {
|
|||||||
/// Creates a new machine to generate a key for the specified curve in the specified multisig
|
/// Creates a new machine to generate a key for the specified curve in the specified multisig
|
||||||
pub fn new(
|
pub fn new(
|
||||||
algorithm: A,
|
algorithm: A,
|
||||||
keys: Arc<FrostKeys<C>>,
|
keys: FrostKeys<C>,
|
||||||
included: &[u16],
|
included: &[u16],
|
||||||
) -> Result<AlgorithmMachine<C, A>, FrostError> {
|
) -> Result<AlgorithmMachine<C, A>, FrostError> {
|
||||||
Ok(AlgorithmMachine { params: Params::new(algorithm, keys, included)? })
|
Ok(AlgorithmMachine { params: Params::new(algorithm, keys, included)? })
|
||||||
|
|||||||
@@ -4,18 +4,18 @@ use rand_core::{RngCore, CryptoRng};
|
|||||||
|
|
||||||
use group::{ff::Field, Group};
|
use group::{ff::Field, Group};
|
||||||
|
|
||||||
use crate::{Curve, FrostKeys, tests::key_gen};
|
use crate::{Curve, FrostCore, tests::core_gen};
|
||||||
|
|
||||||
// Test generation of FROST keys
|
// Test generation of FROST keys
|
||||||
fn key_generation<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
fn key_generation<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
||||||
// This alone verifies the verification shares and group key are agreed upon as expected
|
// This alone verifies the verification shares and group key are agreed upon as expected
|
||||||
key_gen::<_, C>(rng);
|
core_gen::<_, C>(rng);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test serialization of generated keys
|
// Test serialization of generated keys
|
||||||
fn keys_serialization<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
fn keys_serialization<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
||||||
for (_, keys) in key_gen::<_, C>(rng) {
|
for (_, keys) in core_gen::<_, C>(rng) {
|
||||||
assert_eq!(&FrostKeys::<C>::deserialize(&mut Cursor::new(keys.serialize())).unwrap(), &*keys);
|
assert_eq!(&FrostCore::<C>::deserialize(&mut Cursor::new(keys.serialize())).unwrap(), &keys);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ pub fn test_curve<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test FROST key generation and serialization of FrostKeys works as expected
|
// Test FROST key generation and serialization of FrostCore works as expected
|
||||||
key_generation::<_, C>(rng);
|
key_generation::<_, C>(rng);
|
||||||
keys_serialization::<_, C>(rng);
|
keys_serialization::<_, C>(rng);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use std::{io::Cursor, sync::Arc, collections::HashMap};
|
use std::{io::Cursor, collections::HashMap};
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
use group::ff::Field;
|
use group::ff::Field;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Curve, FrostParams, FrostKeys, lagrange,
|
Curve, FrostParams, FrostCore, FrostKeys, lagrange,
|
||||||
key_gen::KeyGenMachine,
|
key_gen::KeyGenMachine,
|
||||||
algorithm::Algorithm,
|
algorithm::Algorithm,
|
||||||
sign::{PreprocessMachine, SignMachine, SignatureMachine, AlgorithmMachine},
|
sign::{PreprocessMachine, SignMachine, SignatureMachine, AlgorithmMachine},
|
||||||
@@ -32,7 +32,7 @@ pub fn clone_without<K: Clone + std::cmp::Eq + std::hash::Hash, V: Clone>(
|
|||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn key_gen<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) -> HashMap<u16, Arc<FrostKeys<C>>> {
|
pub fn core_gen<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) -> HashMap<u16, FrostCore<C>> {
|
||||||
let mut machines = HashMap::new();
|
let mut machines = HashMap::new();
|
||||||
let mut commitments = HashMap::new();
|
let mut commitments = HashMap::new();
|
||||||
for i in 1 ..= PARTICIPANTS {
|
for i in 1 ..= PARTICIPANTS {
|
||||||
@@ -82,11 +82,15 @@ pub fn key_gen<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) -> HashMap<u16, Ar
|
|||||||
}
|
}
|
||||||
assert_eq!(group_key.unwrap(), these_keys.group_key());
|
assert_eq!(group_key.unwrap(), these_keys.group_key());
|
||||||
|
|
||||||
(i, Arc::new(these_keys))
|
(i, these_keys)
|
||||||
})
|
})
|
||||||
.collect::<HashMap<_, _>>()
|
.collect::<HashMap<_, _>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn key_gen<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) -> HashMap<u16, FrostKeys<C>> {
|
||||||
|
core_gen(rng).drain().map(|(i, core)| (i, FrostKeys::new(core))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn recover<C: Curve>(keys: &HashMap<u16, FrostKeys<C>>) -> C::F {
|
pub fn recover<C: Curve>(keys: &HashMap<u16, FrostKeys<C>>) -> C::F {
|
||||||
let first = keys.values().next().expect("no keys provided");
|
let first = keys.values().next().expect("no keys provided");
|
||||||
assert!(keys.len() >= first.params().t().into(), "not enough keys provided");
|
assert!(keys.len() >= first.params().t().into(), "not enough keys provided");
|
||||||
@@ -102,7 +106,7 @@ pub fn recover<C: Curve>(keys: &HashMap<u16, FrostKeys<C>>) -> C::F {
|
|||||||
pub fn algorithm_machines<R: RngCore, C: Curve, A: Algorithm<C>>(
|
pub fn algorithm_machines<R: RngCore, C: Curve, A: Algorithm<C>>(
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
algorithm: A,
|
algorithm: A,
|
||||||
keys: &HashMap<u16, Arc<FrostKeys<C>>>,
|
keys: &HashMap<u16, FrostKeys<C>>,
|
||||||
) -> HashMap<u16, AlgorithmMachine<C, A>> {
|
) -> HashMap<u16, AlgorithmMachine<C, A>> {
|
||||||
let mut included = vec![];
|
let mut included = vec![];
|
||||||
while included.len() < usize::from(keys[&1].params().t()) {
|
while included.len() < usize::from(keys[&1].params().t()) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::{marker::PhantomData, sync::Arc, collections::HashMap};
|
use std::{marker::PhantomData, collections::HashMap};
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
@@ -78,7 +78,7 @@ pub(crate) fn core_batch_verify<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
|||||||
fn sign_core<R: RngCore + CryptoRng, C: Curve>(
|
fn sign_core<R: RngCore + CryptoRng, C: Curve>(
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
group_key: C::G,
|
group_key: C::G,
|
||||||
keys: &HashMap<u16, Arc<FrostKeys<C>>>,
|
keys: &HashMap<u16, FrostKeys<C>>,
|
||||||
) {
|
) {
|
||||||
const MESSAGE: &[u8] = b"Hello, World!";
|
const MESSAGE: &[u8] = b"Hello, World!";
|
||||||
|
|
||||||
@@ -109,7 +109,7 @@ fn sign_with_offset<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
|
|||||||
|
|
||||||
let offset = C::hash_to_F(b"FROST Test sign_with_offset", b"offset");
|
let offset = C::hash_to_F(b"FROST Test sign_with_offset", b"offset");
|
||||||
for i in 1 ..= u16::try_from(keys.len()).unwrap() {
|
for i in 1 ..= u16::try_from(keys.len()).unwrap() {
|
||||||
keys.insert(i, Arc::new(keys[&i].offset(offset)));
|
keys.insert(i, keys[&i].offset(offset));
|
||||||
}
|
}
|
||||||
let offset_key = group_key + (C::GENERATOR * offset);
|
let offset_key = group_key + (C::GENERATOR * offset);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::{io::Cursor, sync::Arc, collections::HashMap};
|
use std::{io::Cursor, collections::HashMap};
|
||||||
|
|
||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@ use group::{ff::PrimeField, GroupEncoding};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
curve::Curve,
|
curve::Curve,
|
||||||
FrostKeys,
|
FrostCore, FrostKeys,
|
||||||
algorithm::{Schnorr, Hram},
|
algorithm::{Schnorr, Hram},
|
||||||
sign::{PreprocessPackage, SignMachine, SignatureMachine, AlgorithmMachine},
|
sign::{PreprocessPackage, SignMachine, SignatureMachine, AlgorithmMachine},
|
||||||
tests::{clone_without, curve::test_curve, schnorr::test_schnorr, recover},
|
tests::{clone_without, curve::test_curve, schnorr::test_schnorr, recover},
|
||||||
@@ -48,13 +48,13 @@ fn vectors_to_multisig_keys<C: Curve>(vectors: &Vectors) -> HashMap<u16, FrostKe
|
|||||||
serialized.extend(share.to_bytes().as_ref());
|
serialized.extend(share.to_bytes().as_ref());
|
||||||
}
|
}
|
||||||
|
|
||||||
let these_keys = FrostKeys::<C>::deserialize(&mut Cursor::new(serialized)).unwrap();
|
let these_keys = FrostCore::<C>::deserialize(&mut Cursor::new(serialized)).unwrap();
|
||||||
assert_eq!(these_keys.params().t(), vectors.threshold);
|
assert_eq!(these_keys.params().t(), vectors.threshold);
|
||||||
assert_eq!(usize::from(these_keys.params().n()), shares.len());
|
assert_eq!(usize::from(these_keys.params().n()), shares.len());
|
||||||
assert_eq!(these_keys.params().i(), i);
|
assert_eq!(these_keys.params().i(), i);
|
||||||
assert_eq!(these_keys.secret_share(), shares[usize::from(i - 1)]);
|
assert_eq!(these_keys.secret_share(), shares[usize::from(i - 1)]);
|
||||||
assert_eq!(&hex::encode(these_keys.group_key().to_bytes().as_ref()), vectors.group_key);
|
assert_eq!(&hex::encode(these_keys.group_key().to_bytes().as_ref()), vectors.group_key);
|
||||||
keys.insert(i, these_keys);
|
keys.insert(i, FrostKeys::new(these_keys));
|
||||||
}
|
}
|
||||||
|
|
||||||
keys
|
keys
|
||||||
@@ -86,7 +86,7 @@ pub fn test_with_vectors<R: RngCore + CryptoRng, C: Curve, H: Hram<C>>(
|
|||||||
*i,
|
*i,
|
||||||
AlgorithmMachine::new(
|
AlgorithmMachine::new(
|
||||||
Schnorr::<C, H>::new(),
|
Schnorr::<C, H>::new(),
|
||||||
Arc::new(keys[i].clone()),
|
keys[i].clone(),
|
||||||
&vectors.included.to_vec().clone(),
|
&vectors.included.to_vec().clone(),
|
||||||
)
|
)
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ keywords = ["multiexp", "ff", "group"]
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
zeroize = { version = "1.3", features = ["zeroize_derive"] }
|
||||||
|
|
||||||
ff = "0.12"
|
ff = "0.12"
|
||||||
group = "0.12"
|
group = "0.12"
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
use rand_core::{RngCore, CryptoRng};
|
use rand_core::{RngCore, CryptoRng};
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::{Field, PrimeFieldBits};
|
use ff::{Field, PrimeFieldBits};
|
||||||
use group::Group;
|
use group::Group;
|
||||||
|
|
||||||
use crate::{multiexp, multiexp_vartime};
|
use crate::{multiexp, multiexp_vartime};
|
||||||
|
|
||||||
#[cfg(feature = "batch")]
|
#[cfg(feature = "batch")]
|
||||||
pub struct BatchVerifier<Id: Copy, G: Group>(Vec<(Id, Vec<(G::Scalar, G)>)>);
|
#[derive(Clone, Zeroize)]
|
||||||
|
pub struct BatchVerifier<Id: Copy + Zeroize, G: Group + Zeroize>(Vec<(Id, Vec<(G::Scalar, G)>)>);
|
||||||
|
|
||||||
#[cfg(feature = "batch")]
|
#[cfg(feature = "batch")]
|
||||||
impl<Id: Copy, G: Group> BatchVerifier<Id, G>
|
impl<Id: Copy + Zeroize, G: Group + Zeroize> BatchVerifier<Id, G>
|
||||||
where
|
where
|
||||||
<G as Group>::Scalar: PrimeFieldBits,
|
<G as Group>::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
|
pub fn new(capacity: usize) -> BatchVerifier<Id, G> {
|
||||||
BatchVerifier(Vec::with_capacity(capacity))
|
BatchVerifier(Vec::with_capacity(capacity))
|
||||||
@@ -39,10 +42,17 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn verify(&self) -> bool {
|
pub fn verify_core(&self) -> bool {
|
||||||
multiexp(&self.0.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>())
|
let mut flat = self.0.iter().flat_map(|pairs| pairs.1.iter()).cloned().collect::<Vec<_>>();
|
||||||
.is_identity()
|
let res = multiexp(&flat).is_identity().into();
|
||||||
.into()
|
flat.zeroize();
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(mut self) -> bool {
|
||||||
|
let res = self.verify_core();
|
||||||
|
self.zeroize();
|
||||||
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@@ -75,12 +85,10 @@ where
|
|||||||
.map(|(id, _)| *id)
|
.map(|(id, _)| *id)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify_with_vartime_blame(&self) -> Result<(), Id> {
|
pub fn verify_with_vartime_blame(mut self) -> Result<(), Id> {
|
||||||
if self.verify() {
|
let res = if self.verify_core() { Ok(()) } else { Err(self.blame_vartime().unwrap()) };
|
||||||
Ok(())
|
self.zeroize();
|
||||||
} else {
|
res
|
||||||
Err(self.blame_vartime().unwrap())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn verify_vartime_with_vartime_blame(&self) -> Result<(), Id> {
|
pub fn verify_vartime_with_vartime_blame(&self) -> Result<(), Id> {
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::PrimeFieldBits;
|
use ff::PrimeFieldBits;
|
||||||
use group::Group;
|
use group::Group;
|
||||||
|
|
||||||
@@ -24,13 +26,17 @@ where
|
|||||||
let mut groupings = vec![];
|
let mut groupings = vec![];
|
||||||
for pair in pairs {
|
for pair in pairs {
|
||||||
let p = groupings.len();
|
let p = groupings.len();
|
||||||
let bits = pair.0.to_le_bits();
|
let mut bits = pair.0.to_le_bits();
|
||||||
groupings.push(vec![0; (bits.len() + (w_usize - 1)) / w_usize]);
|
groupings.push(vec![0; (bits.len() + (w_usize - 1)) / w_usize]);
|
||||||
|
|
||||||
for (i, bit) in bits.into_iter().enumerate() {
|
#[allow(unused_assignments)]
|
||||||
let bit = bit as u8;
|
for (i, mut raw_bit) in bits.iter_mut().enumerate() {
|
||||||
|
let mut bit = *raw_bit as u8;
|
||||||
debug_assert_eq!(bit | 1, 1);
|
debug_assert_eq!(bit | 1, 1);
|
||||||
|
*raw_bit = false;
|
||||||
|
|
||||||
groupings[p][i / w_usize] |= bit << (i % w_usize);
|
groupings[p][i / w_usize] |= bit << (i % w_usize);
|
||||||
|
bit = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +162,7 @@ fn algorithm(len: usize) -> Algorithm {
|
|||||||
// Performs a multiexp, automatically selecting the optimal algorithm based on amount of pairs
|
// Performs a multiexp, automatically selecting the optimal algorithm based on amount of pairs
|
||||||
pub fn multiexp<G: Group>(pairs: &[(G::Scalar, G)]) -> G
|
pub fn multiexp<G: Group>(pairs: &[(G::Scalar, G)]) -> G
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
match algorithm(pairs.len()) {
|
match algorithm(pairs.len()) {
|
||||||
Algorithm::Null => Group::identity(),
|
Algorithm::Null => Group::identity(),
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::PrimeFieldBits;
|
use ff::PrimeFieldBits;
|
||||||
use group::Group;
|
use group::Group;
|
||||||
|
|
||||||
@@ -7,7 +9,7 @@ pub(crate) fn pippenger<G: Group>(pairs: &[(G::Scalar, G)], window: u8) -> G
|
|||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits,
|
||||||
{
|
{
|
||||||
let bits = prep_bits(pairs, window);
|
let mut bits = prep_bits(pairs, window);
|
||||||
|
|
||||||
let mut res = G::identity();
|
let mut res = G::identity();
|
||||||
for n in (0 .. bits[0].len()).rev() {
|
for n in (0 .. bits[0].len()).rev() {
|
||||||
@@ -27,6 +29,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bits.zeroize();
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::PrimeFieldBits;
|
use ff::PrimeFieldBits;
|
||||||
use group::Group;
|
use group::Group;
|
||||||
|
|
||||||
@@ -5,9 +7,9 @@ use crate::{prep_bits, prep_tables};
|
|||||||
|
|
||||||
pub(crate) fn straus<G: Group>(pairs: &[(G::Scalar, G)], window: u8) -> G
|
pub(crate) fn straus<G: Group>(pairs: &[(G::Scalar, G)], window: u8) -> G
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
let groupings = prep_bits(pairs, window);
|
let mut groupings = prep_bits(pairs, window);
|
||||||
let tables = prep_tables(pairs, window);
|
let tables = prep_tables(pairs, window);
|
||||||
|
|
||||||
let mut res = G::identity();
|
let mut res = G::identity();
|
||||||
@@ -20,6 +22,8 @@ where
|
|||||||
res += tables[s][usize::from(groupings[s][b])];
|
res += tables[s][usize::from(groupings[s][b])];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
groupings.zeroize();
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ use std::time::Instant;
|
|||||||
|
|
||||||
use rand_core::OsRng;
|
use rand_core::OsRng;
|
||||||
|
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use ff::{Field, PrimeFieldBits};
|
use ff::{Field, PrimeFieldBits};
|
||||||
use group::Group;
|
use group::Group;
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ use crate::{straus, pippenger, multiexp, multiexp_vartime};
|
|||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
fn benchmark_internal<G: Group>(straus_bool: bool)
|
fn benchmark_internal<G: Group>(straus_bool: bool)
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
let runs: usize = 20;
|
let runs: usize = 20;
|
||||||
|
|
||||||
@@ -81,7 +83,7 @@ where
|
|||||||
|
|
||||||
fn test_multiexp<G: Group>()
|
fn test_multiexp<G: Group>()
|
||||||
where
|
where
|
||||||
G::Scalar: PrimeFieldBits,
|
G::Scalar: PrimeFieldBits + Zeroize,
|
||||||
{
|
{
|
||||||
let mut pairs = Vec::with_capacity(1000);
|
let mut pairs = Vec::with_capacity(1000);
|
||||||
let mut sum = G::identity();
|
let mut sum = G::identity();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::{marker::Send, sync::Arc};
|
use std::marker::Send;
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
@@ -57,7 +57,7 @@ pub trait Coin {
|
|||||||
|
|
||||||
async fn prepare_send(
|
async fn prepare_send(
|
||||||
&self,
|
&self,
|
||||||
keys: Arc<FrostKeys<Self::Curve>>,
|
keys: FrostKeys<Self::Curve>,
|
||||||
transcript: RecommendedTranscript,
|
transcript: RecommendedTranscript,
|
||||||
height: usize,
|
height: usize,
|
||||||
inputs: Vec<Self::Output>,
|
inputs: Vec<Self::Output>,
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use curve25519_dalek::scalar::Scalar;
|
use curve25519_dalek::scalar::Scalar;
|
||||||
@@ -57,7 +55,7 @@ impl OutputTrait for Output {
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct SignableTransaction(
|
pub struct SignableTransaction(
|
||||||
Arc<FrostKeys<Ed25519>>,
|
FrostKeys<Ed25519>,
|
||||||
RecommendedTranscript,
|
RecommendedTranscript,
|
||||||
usize,
|
usize,
|
||||||
MSignableTransaction,
|
MSignableTransaction,
|
||||||
@@ -137,14 +135,14 @@ impl Coin for Monero {
|
|||||||
async fn get_outputs(&self, block: &Self::Block, key: dfg::EdwardsPoint) -> Vec<Self::Output> {
|
async fn get_outputs(&self, block: &Self::Block, key: dfg::EdwardsPoint) -> Vec<Self::Output> {
|
||||||
block
|
block
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|tx| tx.scan(self.view_pair(key), true).not_locked())
|
.flat_map(|tx| tx.scan(&self.view_pair(key), true).not_locked())
|
||||||
.map(Output::from)
|
.map(Output::from)
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare_send(
|
async fn prepare_send(
|
||||||
&self,
|
&self,
|
||||||
keys: Arc<FrostKeys<Ed25519>>,
|
keys: FrostKeys<Ed25519>,
|
||||||
transcript: RecommendedTranscript,
|
transcript: RecommendedTranscript,
|
||||||
height: usize,
|
height: usize,
|
||||||
mut inputs: Vec<Output>,
|
mut inputs: Vec<Output>,
|
||||||
@@ -177,7 +175,7 @@ impl Coin for Monero {
|
|||||||
.clone()
|
.clone()
|
||||||
.multisig(
|
.multisig(
|
||||||
&self.rpc,
|
&self.rpc,
|
||||||
(*transaction.0).clone(),
|
transaction.0.clone(),
|
||||||
transaction.1.clone(),
|
transaction.1.clone(),
|
||||||
transaction.2,
|
transaction.2,
|
||||||
included.to_vec(),
|
included.to_vec(),
|
||||||
@@ -235,7 +233,7 @@ impl Coin for Monero {
|
|||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.swap_remove(0)
|
.swap_remove(0)
|
||||||
.scan(self.empty_view_pair(), false)
|
.scan(&self.empty_view_pair(), false)
|
||||||
.ignore_timelock();
|
.ignore_timelock();
|
||||||
|
|
||||||
let amount = outputs[0].commitment.amount;
|
let amount = outputs[0].commitment.amount;
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ async fn test_send<C: Coin + Clone>(coin: C, fee: C::Fee) {
|
|||||||
for i in 1 ..= threshold {
|
for i in 1 ..= threshold {
|
||||||
let mut wallet = Wallet::new(MemCoinDb::new(), coin.clone());
|
let mut wallet = Wallet::new(MemCoinDb::new(), coin.clone());
|
||||||
wallet.acknowledge_height(0, height);
|
wallet.acknowledge_height(0, height);
|
||||||
wallet.add_keys(&WalletKeys::new(Arc::try_unwrap(keys.remove(&i).take().unwrap()).unwrap(), 0));
|
wallet.add_keys(&WalletKeys::new(keys.remove(&i).unwrap(), 0));
|
||||||
wallets.push(wallet);
|
wallets.push(wallet);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::{sync::Arc, collections::HashMap};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use rand_core::OsRng;
|
use rand_core::OsRng;
|
||||||
|
|
||||||
@@ -203,7 +203,7 @@ fn select_inputs_outputs<C: Coin>(
|
|||||||
pub struct Wallet<D: CoinDb, C: Coin> {
|
pub struct Wallet<D: CoinDb, C: Coin> {
|
||||||
db: D,
|
db: D,
|
||||||
coin: C,
|
coin: C,
|
||||||
keys: Vec<(Arc<FrostKeys<C::Curve>>, Vec<C::Output>)>,
|
keys: Vec<(FrostKeys<C::Curve>, Vec<C::Output>)>,
|
||||||
pending: Vec<(usize, FrostKeys<C::Curve>)>,
|
pending: Vec<(usize, FrostKeys<C::Curve>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,7 +249,7 @@ impl<D: CoinDb, C: Coin> Wallet<D, C> {
|
|||||||
//if b < self.pending[k].0 {
|
//if b < self.pending[k].0 {
|
||||||
//} else if b == self.pending[k].0 {
|
//} else if b == self.pending[k].0 {
|
||||||
if b <= self.pending[k].0 {
|
if b <= self.pending[k].0 {
|
||||||
self.keys.push((Arc::new(self.pending.swap_remove(k).1), vec![]));
|
self.keys.push((self.pending.swap_remove(k).1, vec![]));
|
||||||
} else {
|
} else {
|
||||||
k += 1;
|
k += 1;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user