Skip to content

Commit

Permalink
Merge branch 'main' into ray/param-const-export
Browse files Browse the repository at this point in the history
  • Loading branch information
joe authored Aug 11, 2023
2 parents c882da8 + e83521d commit 628b1e2
Show file tree
Hide file tree
Showing 31 changed files with 1,041 additions and 459 deletions.
6 changes: 3 additions & 3 deletions masp_primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ sha2 = "0.9"
# - Metrics
memuse = "0.2.1"

# - Checked arithmetic
num-traits = "0.2.14"

# - Secret management
subtle = "2.2.3"

Expand All @@ -53,9 +56,6 @@ lazy_static = "1"
# - Test dependencies
proptest = { version = "1.0.0", optional = true }

# - Transparent inputs
secp256k1 = { version = "0.24.1", features = [ "rand" ] }

# - ZIP 339
bip0039 = { version = "0.9", features = ["std", "all-languages"] }

Expand Down
3 changes: 2 additions & 1 deletion masp_primitives/src/consensus.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Consensus logic and parameters.

use borsh::{BorshDeserialize, BorshSerialize};
use memuse::DynamicUsage;
use std::cmp::{Ord, Ordering};
use std::convert::TryFrom;
Expand All @@ -9,7 +10,7 @@ use std::ops::{Add, Bound, RangeBounds, Sub};
/// A wrapper type representing blockchain heights. Safe conversion from
/// various integer types, as well as addition and subtraction, are provided.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize)]
pub struct BlockHeight(u32);

memuse::impl_no_dynamic_usage!(BlockHeight);
Expand Down
33 changes: 17 additions & 16 deletions masp_primitives/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
pedersen_hash::{pedersen_hash, Personalization},
Node, ValueCommitment,
},
transaction::components::amount::Amount,
transaction::components::amount::{I32Sum, ValueSum},
};
use borsh::{BorshDeserialize, BorshSerialize};
use group::{Curve, GroupEncoding};
Expand All @@ -16,7 +16,7 @@ use std::{
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AllowedConversion {
/// The asset type that the note represents
assets: Amount,
assets: I32Sum,
/// Memorize generator because it's expensive to recompute
generator: jubjub::ExtendedPoint,
}
Expand Down Expand Up @@ -71,15 +71,15 @@ impl AllowedConversion {
}
}

impl From<AllowedConversion> for Amount {
fn from(allowed_conversion: AllowedConversion) -> Amount {
impl From<AllowedConversion> for I32Sum {
fn from(allowed_conversion: AllowedConversion) -> I32Sum {
allowed_conversion.assets
}
}

impl From<Amount> for AllowedConversion {
impl From<I32Sum> for AllowedConversion {
/// Produces an asset generator without cofactor cleared
fn from(assets: Amount) -> Self {
fn from(assets: I32Sum) -> Self {
let mut asset_generator = jubjub::ExtendedPoint::identity();
for (asset, value) in assets.components() {
// Compute the absolute value (failing if -i64::MAX is
Expand Down Expand Up @@ -123,7 +123,7 @@ impl BorshDeserialize for AllowedConversion {
/// computation of checking whether the asset generator corresponds to the
/// deserialized amount.
fn deserialize(buf: &mut &[u8]) -> borsh::maybestd::io::Result<Self> {
let assets = Amount::read(buf)?;
let assets = I32Sum::read(buf)?;
let gen_bytes =
<<jubjub::ExtendedPoint as GroupEncoding>::Repr as BorshDeserialize>::deserialize(buf)?;
let generator = Option::from(jubjub::ExtendedPoint::from_bytes(&gen_bytes))
Expand Down Expand Up @@ -174,15 +174,15 @@ impl SubAssign for AllowedConversion {

impl Sum for AllowedConversion {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(AllowedConversion::from(Amount::zero()), Add::add)
iter.fold(AllowedConversion::from(ValueSum::zero()), Add::add)
}
}

#[cfg(test)]
mod tests {
use crate::asset_type::AssetType;
use crate::convert::AllowedConversion;
use crate::transaction::components::amount::Amount;
use crate::transaction::components::amount::ValueSum;

/// Generate ZEC asset type
fn zec() -> AssetType {
Expand All @@ -199,11 +199,12 @@ mod tests {
#[test]
fn test_homomorphism() {
// Left operand
let a = Amount::from_pair(zec(), 5).unwrap()
+ Amount::from_pair(btc(), 6).unwrap()
+ Amount::from_pair(xan(), 7).unwrap();
let a = ValueSum::from_pair(zec(), 5i32).unwrap()
+ ValueSum::from_pair(btc(), 6i32).unwrap()
+ ValueSum::from_pair(xan(), 7i32).unwrap();
// Right operand
let b = Amount::from_pair(zec(), 2).unwrap() + Amount::from_pair(xan(), 10).unwrap();
let b =
ValueSum::from_pair(zec(), 2i32).unwrap() + ValueSum::from_pair(xan(), 10i32).unwrap();
// Test homomorphism
assert_eq!(
AllowedConversion::from(a.clone() + b.clone()),
Expand All @@ -213,9 +214,9 @@ mod tests {
#[test]
fn test_serialization() {
// Make conversion
let a: AllowedConversion = (Amount::from_pair(zec(), 5).unwrap()
+ Amount::from_pair(btc(), 6).unwrap()
+ Amount::from_pair(xan(), 7).unwrap())
let a: AllowedConversion = (ValueSum::from_pair(zec(), 5i32).unwrap()
+ ValueSum::from_pair(btc(), 6i32).unwrap()
+ ValueSum::from_pair(xan(), 7i32).unwrap())
.into();
// Serialize conversion
let mut data = Vec::new();
Expand Down
5 changes: 5 additions & 0 deletions masp_primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,10 @@ pub mod sapling;
pub mod transaction;
pub mod zip32;

pub use bls12_381;
pub use ff;
pub use group;
pub use jubjub;

#[cfg(test)]
mod test_vectors;
8 changes: 4 additions & 4 deletions masp_primitives/src/merkle_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,10 @@ impl<Node: Hashable> BorshDeserialize for MerklePath<Node> {
// Begin to construct the authentication path
// Do not use any data in the witness after the expected depth
let iter = witness[..33 * depth + 8].chunks_exact(33);
*witness = iter.remainder();
// Update the witness to its final position
*witness = &witness[33 * depth + 8..];
// Read the position from the witness
let position = iter.remainder().read_u64::<LittleEndian>()?;

// The vector works in reverse
let mut auth_path = iter
Expand All @@ -798,9 +801,6 @@ impl<Node: Hashable> BorshDeserialize for MerklePath<Node> {
return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));
}

// Read the position from the witness
let position = witness.read_u64::<LittleEndian>()?;

// Given the position, let's finish constructing the authentication
// path
let mut tmp = position;
Expand Down
9 changes: 5 additions & 4 deletions masp_primitives/src/sapling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ pub struct Node {
}

impl Node {
#[cfg(test)]
pub(crate) fn new(repr: [u8; 32]) -> Self {
pub fn new(repr: [u8; 32]) -> Self {
Node { repr }
}

Expand Down Expand Up @@ -506,7 +505,9 @@ pub enum Rseed {
}

/// Typesafe wrapper for nullifier values.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[derive(
Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, BorshSerialize, BorshDeserialize,
)]
pub struct Nullifier(pub [u8; 32]);

impl Nullifier {
Expand Down Expand Up @@ -551,7 +552,7 @@ impl From<NoteValue> for u64 {
}
}

#[derive(Clone, Debug)]
#[derive(Clone, Debug, Copy)]
pub struct Note {
/// The asset type that the note represents
pub asset_type: AssetType,
Expand Down
3 changes: 2 additions & 1 deletion masp_primitives/src/sapling/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
constants::{PROOF_GENERATION_KEY_GENERATOR, SPENDING_KEY_GENERATOR},
keys::prf_expand,
};
use borsh::{BorshDeserialize, BorshSerialize};
use ff::PrimeField;
use group::{Group, GroupEncoding};
use std::{
Expand All @@ -31,7 +32,7 @@ pub enum DecodingError {
}

/// An outgoing viewing key
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize)]
pub struct OutgoingViewingKey(pub [u8; 32]);

/// A Sapling expanded spending key
Expand Down
8 changes: 4 additions & 4 deletions masp_primitives/src/sapling/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
redjubjub::{PublicKey, Signature},
Node,
},
transaction::components::{Amount, GROTH_PROOF_SIZE},
transaction::components::{I128Sum, GROTH_PROOF_SIZE},
};

use super::{Diversifier, PaymentAddress, ProofGenerationKey, Rseed};
Expand Down Expand Up @@ -73,7 +73,7 @@ pub trait TxProver {
fn binding_sig(
&self,
ctx: &mut Self::SaplingProvingContext,
amount: &Amount,
amount: &I128Sum,
sighash: &[u8; 32],
) -> Result<Signature, ()>;
}
Expand All @@ -92,7 +92,7 @@ pub mod mock {
redjubjub::{PublicKey, Signature},
Diversifier, Node, PaymentAddress, ProofGenerationKey, Rseed,
},
transaction::components::{Amount, GROTH_PROOF_SIZE},
transaction::components::{I128Sum, GROTH_PROOF_SIZE},
};

use super::TxProver;
Expand Down Expand Up @@ -169,7 +169,7 @@ pub mod mock {
fn binding_sig(
&self,
_ctx: &mut Self::SaplingProvingContext,
_value: &Amount,
_value: &I128Sum,
_sighash: &[u8; 32],
) -> Result<Signature, ()> {
Err(())
Expand Down
50 changes: 39 additions & 11 deletions masp_primitives/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use blake2b_simd::Hash as Blake2bHash;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use ff::PrimeField;
use memuse::DynamicUsage;
pub use secp256k1::PublicKey as TransparentAddress;
use std::{
fmt::{self, Debug},
hash::Hash,
Expand All @@ -26,7 +25,7 @@ use crate::{

use self::{
components::{
amount::Amount,
amount::{I128Sum, ValueSum},
sapling::{
self, ConvertDescriptionV5, OutputDescriptionV5, SpendDescription, SpendDescriptionV5,
},
Expand All @@ -35,6 +34,9 @@ use self::{
txid::{to_txid, BlockTxCommitmentDigester, TxIdDigester},
};

#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
pub struct TransparentAddress(pub [u8; 20]);

pub const GROTH_PROOF_SIZE: usize = 48 + 96 + 48;
pub type GrothProofBytes = [u8; GROTH_PROOF_SIZE];

Expand Down Expand Up @@ -147,7 +149,7 @@ pub trait Authorization {
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Unproven;
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Authorized;

impl Authorization for Authorized {
Expand All @@ -163,7 +165,7 @@ impl Authorization for Unauthorized {
}

/// A MASP transaction.
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Transaction {
txid: TxId,
data: TransactionData<Authorized>,
Expand All @@ -183,7 +185,7 @@ impl PartialEq for Transaction {
}
}

#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Clone)]
pub struct TransactionData<A: Authorization> {
version: TxVersion,
consensus_branch_id: BranchId,
Expand Down Expand Up @@ -267,10 +269,10 @@ impl<A: Authorization> TransactionData<A> {
}

impl<A: Authorization> TransactionData<A> {
pub fn sapling_value_balance(&self) -> Amount {
pub fn sapling_value_balance(&self) -> I128Sum {
self.sapling_bundle
.as_ref()
.map_or(Amount::zero(), |b| b.value_balance.clone())
.map_or(ValueSum::zero(), |b| b.value_balance.clone())
}
}

Expand All @@ -280,6 +282,32 @@ impl TransactionData<Authorized> {
}
}

impl BorshSerialize for Transaction {
fn serialize<W: Write>(&self, writer: &mut W) -> borsh::maybestd::io::Result<()> {
self.write(writer)
}
}

impl BorshDeserialize for Transaction {
fn deserialize(buf: &mut &[u8]) -> borsh::maybestd::io::Result<Self> {
Self::read(buf, BranchId::MASP)
}
}

impl borsh::BorshSchema for Transaction {
fn add_definitions_recursively(
_definitions: &mut std::collections::HashMap<
borsh::schema::Declaration,
borsh::schema::Definition,
>,
) {
}

fn declaration() -> borsh::schema::Declaration {
"Transaction".into()
}
}

impl Transaction {
fn from_data(data: TransactionData<Authorized>) -> io::Result<Self> {
match data.version {
Expand Down Expand Up @@ -327,8 +355,8 @@ impl Transaction {
})
}

fn read_amount<R: Read>(mut reader: R) -> io::Result<Amount> {
Amount::read(&mut reader).map_err(|_| {
fn read_i128_sum<R: Read>(mut reader: R) -> io::Result<I128Sum> {
I128Sum::read(&mut reader).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"Amount valueBalance out of range",
Expand Down Expand Up @@ -379,9 +407,9 @@ impl Transaction {
let n_converts = cd_v5s.len();
let n_outputs = od_v5s.len();
let value_balance = if n_spends > 0 || n_outputs > 0 {
Self::read_amount(&mut reader)?
Self::read_i128_sum(&mut reader)?
} else {
Amount::zero()
ValueSum::zero()
};

let spend_anchor = if n_spends > 0 {
Expand Down
Loading

0 comments on commit 628b1e2

Please sign in to comment.