milestone 2

This commit is contained in:
scilio
2022-04-26 23:13:44 -04:00
parent 68929fd493
commit 115e0d2022
13 changed files with 760 additions and 1222 deletions
+63 -130
View File
@@ -5,27 +5,26 @@ pub use secp256k1zkp::pedersen::{Commitment, RangeProof};
pub use secp256k1zkp::key::{PublicKey, SecretKey, ZERO_KEY};
pub use secp256k1zkp::constants::{AGG_SIGNATURE_SIZE, COMPRESSED_PUBLIC_KEY_SIZE, MAX_PROOF_SIZE, PEDERSEN_COMMITMENT_SIZE, SECRET_KEY_SIZE};
use crate::ser::{self, Readable, Reader, Writeable, Writer};
use crate::error::{Error, ErrorKind, Result};
use blake2::blake2b::Blake2b;
use byteorder::{BigEndian, ByteOrder};
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use secp256k1zkp::rand::thread_rng;
use std::cmp;
/// A generalized Schnorr signature with a pedersen commitment value & blinding factors as the keys
pub struct ComSignature {
pub pub_nonce: Commitment,
pub s: SecretKey,
pub t: SecretKey,
pub_nonce: Commitment,
s: SecretKey,
t: SecretKey,
}
impl ComSignature {
pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature {
ComSignature {
pub_nonce: pub_nonce.clone(),
s: s.clone(),
t: t.clone(),
pub_nonce: pub_nonce.to_owned(),
s: s.to_owned(),
t: t.to_owned(),
}
}
@@ -34,7 +33,7 @@ impl ComSignature {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let mut amt_bytes = [0; 32];
BigEndian::write_u64(&mut amt_bytes[24..31], amount);
BigEndian::write_u64(&mut amt_bytes[24..32], amount);
let k_amt = SecretKey::from_slice(&secp, &amt_bytes)?;
let k_1 = SecretKey::new(&secp, &mut thread_rng());
@@ -71,7 +70,7 @@ impl ComSignature {
let commits = vec![Commitment::from_pubkey(&secp, &Ce)?, self.pub_nonce.clone()];
let S2 = secp.commit_sum(commits, Vec::new())?;
if S1 == S2 {
if S1 != S2 {
return Err(Error::new(ErrorKind::InvalidSigError));
}
@@ -94,9 +93,8 @@ impl ComSignature {
/// Serializes a ComSignature to and from hex
pub mod comsig_serde {
use super::ComSignature;
use super::ser::{self, BinReader, Readable};
use grin_core::ser::{self, ProtocolVersion};
use serde::{Deserialize, Serializer};
use std::io::Cursor;
use grin_util::ToHex;
/// Serializes a ComSignature as a hex string
@@ -105,7 +103,7 @@ pub mod comsig_serde {
S: Serializer,
{
use serde::ser::Error;
let bytes = ser::ser_vec(&comsig).map_err(Error::custom)?;
let bytes = ser::ser_vec(&comsig, ProtocolVersion::local()).map_err(Error::custom)?;
serializer.serialize_str(&bytes.to_hex())
}
@@ -117,18 +115,29 @@ pub mod comsig_serde {
use serde::de::Error;
let bytes = String::deserialize(deserializer)
.and_then(|string| grin_util::from_hex(&string).map_err(Error::custom))?;
let mut cursor = Cursor::new(&bytes);
let mut reader = BinReader::new(&mut cursor);
ComSignature::read(&mut reader).map_err(Error::custom)
let sig: ComSignature = grin_core::ser::deserialize_default(&mut &bytes[..])
.map_err(Error::custom)?;
Ok(sig)
}
}
/// Compute a PublicKey from a SecretKey
pub fn to_public_key(secret_key: &SecretKey) -> Result<PublicKey> {
let secp = Secp256k1::new();
let pubkey = PublicKey::from_secret_key(&secp, secret_key)?;
Ok(pubkey)
#[allow(non_snake_case)]
impl Readable for ComSignature {
fn read<R: Reader>(reader: &mut R) -> std::result::Result<Self, ser::Error> {
let R = Commitment::read(reader)?;
let s = read_secret_key(reader)?;
let t = read_secret_key(reader)?;
Ok(ComSignature::new(&R, &s, &t))
}
}
impl Writeable for ComSignature {
fn write<W: Writer>(&self, writer: &mut W) -> std::result::Result<(), ser::Error> {
writer.write_fixed_bytes(self.pub_nonce.0)?;
writer.write_fixed_bytes(self.s.0)?;
writer.write_fixed_bytes(self.t.0)?;
Ok(())
}
}
/// Generate a random SecretKey.
@@ -137,6 +146,14 @@ pub fn random_secret() -> SecretKey {
SecretKey::new(&secp, &mut thread_rng())
}
/// Deserialize a SecretKey from a Reader
pub fn read_secret_key<R: Reader>(reader: &mut R) -> std::result::Result<SecretKey, ser::Error> {
let buf = reader.read_fixed_bytes(SECRET_KEY_SIZE)?;
let secp = Secp256k1::with_caps(ContextFlag::None);
let pk = SecretKey::from_slice(&secp, &buf).map_err(|_| ser::Error::CorruptedData)?;
Ok(pk)
}
/// Build a Pedersen Commitment using the provided value and blinding factor
pub fn commit(value: u64, blind: &SecretKey) -> Result<Commitment> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
@@ -154,6 +171,7 @@ pub fn add_excess(commitment: &Commitment, excess: &SecretKey) -> Result<Commitm
Ok(sum)
}
/// Subtracts a value (v*H) from an existing commitment
pub fn sub_value(commitment: &Commitment, value: u64) -> Result<Commitment> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let neg_commit : Commitment = secp.commit(value, ZERO_KEY)?;
@@ -161,18 +179,7 @@ pub fn sub_value(commitment: &Commitment, value: u64) -> Result<Commitment> {
Ok(sum)
}
pub fn add_blinds(excesses: &Vec<SecretKey>) -> Result<SecretKey> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let sum = secp.blind_sum(excesses.clone(), Vec::new())?;
Ok(sum)
}
pub fn sub_blinds(minuend: &SecretKey, subtrahend: &SecretKey) -> Result<SecretKey> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let result = secp.blind_sum(vec![minuend.clone()], vec![subtrahend.clone()])?;
Ok(result)
}
/// Signs the message with the provided SecretKey
pub fn sign(sk: &SecretKey, msg: &Message) -> Result<Signature> {
let secp = Secp256k1::with_caps(ContextFlag::Full);
let pubkey = PublicKey::from_secret_key(&secp, &sk)?;
@@ -180,107 +187,33 @@ pub fn sign(sk: &SecretKey, msg: &Message) -> Result<Signature> {
Ok(sig)
}
/// secp256k1-zkp object serialization
#[cfg(test)]
mod tests {
use super::{ComSignature, ContextFlag, Secp256k1, SecretKey};
use crate::error::Result;
impl Readable for Commitment {
fn read<R: Reader>(reader: &mut R) -> Result<Commitment> {
let a = reader.read_fixed_bytes(PEDERSEN_COMMITMENT_SIZE)?;
let mut c = [0; PEDERSEN_COMMITMENT_SIZE];
c[..PEDERSEN_COMMITMENT_SIZE].clone_from_slice(&a[..PEDERSEN_COMMITMENT_SIZE]);
Ok(Commitment(c))
}
}
use secp256k1zkp::rand::{RngCore, thread_rng};
use rand::Rng;
/// Test signing and verification of ComSignatures
#[test]
fn verify_comsig() -> Result<()> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
impl Writeable for Commitment {
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
writer.write_fixed_bytes(self)
}
}
let amount = thread_rng().next_u64();
let blind = SecretKey::new(&secp, &mut thread_rng());
let msg: [u8; 16] = rand::thread_rng().gen();
let comsig = ComSignature::sign(amount, &blind, &msg.to_vec())?;
let commit = secp.commit(amount, blind.clone())?;
assert!(comsig.verify(&commit, &msg.to_vec()).is_ok());
impl Readable for RangeProof {
fn read<R: Reader>(reader: &mut R) -> Result<RangeProof> {
let len = reader.read_u64()?;
let max_len = cmp::min(len as usize, MAX_PROOF_SIZE);
let p = reader.read_fixed_bytes(max_len)?;
let mut proof = [0; MAX_PROOF_SIZE];
proof[..p.len()].clone_from_slice(&p[..]);
Ok(RangeProof {
plen: proof.len(),
proof,
})
}
}
let wrong_msg: [u8; 16] = rand::thread_rng().gen();
assert!(comsig.verify(&commit, &wrong_msg.to_vec()).is_err());
impl Writeable for RangeProof {
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
writer.write_bytes(self)
}
}
let wrong_commit = secp.commit(amount, SecretKey::new(&secp, &mut thread_rng()))?;
assert!(comsig.verify(&wrong_commit, &msg.to_vec()).is_err());
impl Readable for Signature {
fn read<R: Reader>(reader: &mut R) -> Result<Signature> {
let a = reader.read_fixed_bytes(AGG_SIGNATURE_SIZE)?;
let mut c = [0; AGG_SIGNATURE_SIZE];
c[..AGG_SIGNATURE_SIZE].clone_from_slice(&a[..AGG_SIGNATURE_SIZE]);
Ok(Signature::from_raw_data(&c).unwrap())
}
}
impl Writeable for Signature {
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
writer.write_fixed_bytes(self)
}
}
impl Readable for PublicKey {
// Read the public key in compressed form
fn read<R: Reader>(reader: &mut R) -> Result<Self> {
let buf = reader.read_fixed_bytes(COMPRESSED_PUBLIC_KEY_SIZE)?;
let secp = Secp256k1::with_caps(ContextFlag::None);
let pk = PublicKey::from_slice(&secp, &buf).map_err(|_| ErrorKind::CorruptedData)?;
Ok(pk)
}
}
impl Writeable for PublicKey {
// Write the public key in compressed form
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
let secp = Secp256k1::with_caps(ContextFlag::None);
writer.write_fixed_bytes(self.serialize_vec(&secp, true))?;
Ok(())
}
}
impl Readable for SecretKey {
fn read<R: Reader>(reader: &mut R) -> Result<Self> {
let buf = reader.read_fixed_bytes(SECRET_KEY_SIZE)?;
let secp = Secp256k1::with_caps(ContextFlag::None);
let pk = SecretKey::from_slice(&secp, &buf).map_err(|_| ErrorKind::CorruptedData)?;
Ok(pk)
}
}
impl Writeable for SecretKey {
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
writer.write_fixed_bytes(self.0)?;
Ok(())
}
}
#[allow(non_snake_case)]
impl Readable for ComSignature {
fn read<R: Reader>(reader: &mut R) -> Result<ComSignature> {
let R = Commitment::read(reader)?;
let s = SecretKey::read(reader)?;
let t = SecretKey::read(reader)?;
Ok(ComSignature::new(&R, &s, &t))
}
}
impl Writeable for ComSignature {
fn write<W: Writer>(&self, writer: &mut W) -> Result<()> {
writer.write_fixed_bytes(self.pub_nonce.0)?;
writer.write_fixed_bytes(self.s.0)?;
writer.write_fixed_bytes(self.t.0)
}
}