1
0
mirror of synced 2025-01-09 15:26:11 +00:00
* Add PoL crate

* promote cl crate to nomos-node repo

* add github action for risc0 proof

* fix actions scrupt

* add metal feature

* fix risc0 install

* remove check test
This commit is contained in:
Giacomo Pasini 2024-09-03 14:38:00 +02:00 committed by GitHub
parent c4c5eba642
commit 6f6bb61df4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
25 changed files with 1592 additions and 2 deletions

View File

@ -95,6 +95,27 @@ jobs:
with:
name: integration-test-artifacts
path: tests/.tmp*
risc0:
name: Risc0 tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: true
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install risc0
run: cargo install cargo-risczero && cargo risczero install
- name: Cargo test
uses: actions-rs/cargo@v1
with:
command: test
args: --manifest-path proof_of_leadership/risc0/prover/Cargo.toml
lints:
name: Rust lints

View File

@ -29,6 +29,8 @@ members = [
"consensus/carnot-engine",
"consensus/cryptarchia-engine",
"ledger/cryptarchia-ledger",
"tests"
"cl/cl",
"tests",
]
resolver = "2"
exclude = ["proof_of_leadership/risc0/risc0_proofs"]
resolver = "2"

13
cl/cl/Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
name = "cl"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = {version="1.0", features = ["derive"]}
rand = "0.8.5"
rand_core = "0.6.0"
hex = "0.4.3"
sha2 = "0.10"

149
cl/cl/src/balance.rs Normal file
View File

@ -0,0 +1,149 @@
use rand_core::CryptoRngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::PartialTxWitness;
pub type Value = u64;
pub type Unit = [u8; 32];
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct Balance([u8; 32]);
impl Balance {
pub fn to_bytes(&self) -> [u8; 32] {
self.0
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct UnitBalance {
pub unit: Unit,
pub pos: u64,
pub neg: u64,
}
impl UnitBalance {
pub fn is_zero(&self) -> bool {
self.pos == self.neg
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct BalanceWitness {
pub balances: Vec<UnitBalance>,
pub blinding: [u8; 16],
}
impl BalanceWitness {
pub fn random_blinding(mut rng: impl CryptoRngCore) -> [u8; 16] {
let mut blinding = [0u8; 16];
rng.fill_bytes(&mut blinding);
blinding
}
pub fn zero(blinding: [u8; 16]) -> Self {
Self {
balances: Default::default(),
blinding,
}
}
pub fn from_ptx(ptx: &PartialTxWitness, blinding: [u8; 16]) -> Self {
let mut balance = Self::zero(blinding);
for input in ptx.inputs.iter() {
balance.insert_negative(input.note.unit, input.note.value);
}
for output in ptx.outputs.iter() {
balance.insert_positive(output.note.unit, output.note.value);
}
balance.clear_zeros();
balance
}
pub fn insert_positive(&mut self, unit: Unit, value: Value) {
for unit_bal in self.balances.iter_mut() {
if unit_bal.unit == unit {
unit_bal.pos += value;
return;
}
}
// Unit was not found, so we must create one.
self.balances.push(UnitBalance {
unit,
pos: value,
neg: 0,
});
}
pub fn insert_negative(&mut self, unit: Unit, value: Value) {
for unit_bal in self.balances.iter_mut() {
if unit_bal.unit == unit {
unit_bal.neg += value;
return;
}
}
self.balances.push(UnitBalance {
unit,
pos: 0,
neg: value,
});
}
pub fn clear_zeros(&mut self) {
let mut i = 0usize;
while i < self.balances.len() {
if self.balances[i].is_zero() {
self.balances.swap_remove(i);
// don't increment `i` since the last element has been swapped into the
// `i`'th place
} else {
i += 1;
}
}
}
pub fn combine(balances: impl IntoIterator<Item = Self>, blinding: [u8; 16]) -> Self {
let mut combined = BalanceWitness::zero(blinding);
for balance in balances {
for unit_bal in balance.balances.iter() {
if unit_bal.pos > unit_bal.neg {
combined.insert_positive(unit_bal.unit, unit_bal.pos - unit_bal.neg);
} else {
combined.insert_negative(unit_bal.unit, unit_bal.neg - unit_bal.pos);
}
}
}
combined.clear_zeros();
combined
}
pub fn is_zero(&self) -> bool {
self.balances.is_empty()
}
pub fn commit(&self) -> Balance {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_BAL_COMMIT");
for unit_balance in self.balances.iter() {
hasher.update(unit_balance.unit);
hasher.update(unit_balance.pos.to_le_bytes());
hasher.update(unit_balance.neg.to_le_bytes());
}
hasher.update(self.blinding);
let commit_bytes: [u8; 32] = hasher.finalize().into();
Balance(commit_bytes)
}
}

117
cl/cl/src/bundle.rs Normal file
View File

@ -0,0 +1,117 @@
use serde::{Deserialize, Serialize};
use crate::{partial_tx::PartialTx, BalanceWitness, PartialTxWitness};
/// The transaction bundle is a collection of partial transactions.
/// The goal in bundling transactions is to produce a set of partial transactions
/// that balance each other.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bundle {
pub partials: Vec<PartialTx>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleWitness {
pub partials: Vec<PartialTxWitness>,
}
impl BundleWitness {
pub fn balance(&self) -> BalanceWitness {
BalanceWitness::combine(self.partials.iter().map(|ptx| ptx.balance()), [0u8; 16])
}
pub fn commit(&self) -> Bundle {
Bundle {
partials: Vec::from_iter(self.partials.iter().map(|ptx| ptx.commit())),
}
}
}
#[cfg(test)]
mod test {
use crate::{
balance::UnitBalance,
input::InputWitness,
note::{derive_unit, NoteWitness},
nullifier::NullifierSecret,
output::OutputWitness,
partial_tx::PartialTxWitness,
};
use super::*;
#[test]
fn test_bundle_balance() {
let mut rng = rand::thread_rng();
let (nmo, eth, crv) = (derive_unit("NMO"), derive_unit("ETH"), derive_unit("CRV"));
let nf_a = NullifierSecret::random(&mut rng);
let nf_b = NullifierSecret::random(&mut rng);
let nf_c = NullifierSecret::random(&mut rng);
let nmo_10_utxo = OutputWitness::new(NoteWitness::basic(10, nmo, &mut rng), nf_a.commit());
let nmo_10_in = InputWitness::from_output(nmo_10_utxo, nf_a);
let eth_23_utxo = OutputWitness::new(NoteWitness::basic(23, eth, &mut rng), nf_b.commit());
let eth_23_in = InputWitness::from_output(eth_23_utxo, nf_b);
let crv_4840_out =
OutputWitness::new(NoteWitness::basic(4840, crv, &mut rng), nf_c.commit());
let ptx_unbalanced = PartialTxWitness {
inputs: vec![nmo_10_in, eth_23_in],
outputs: vec![crv_4840_out],
balance_blinding: BalanceWitness::random_blinding(&mut rng),
};
let bundle_witness = BundleWitness {
partials: vec![ptx_unbalanced.clone()],
};
assert!(!bundle_witness.balance().is_zero());
assert_eq!(
bundle_witness.balance().balances,
vec![
UnitBalance {
unit: nmo,
pos: 0,
neg: 10
},
UnitBalance {
unit: eth,
pos: 0,
neg: 23
},
UnitBalance {
unit: crv,
pos: 4840,
neg: 0
},
]
);
let crv_4840_in = InputWitness::from_output(crv_4840_out, nf_c);
let nmo_10_out = OutputWitness::new(
NoteWitness::basic(10, nmo, &mut rng),
NullifierSecret::random(&mut rng).commit(), // transferring to a random owner
);
let eth_23_out = OutputWitness::new(
NoteWitness::basic(23, eth, &mut rng),
NullifierSecret::random(&mut rng).commit(), // transferring to a random owner
);
let ptx_solved = PartialTxWitness {
inputs: vec![crv_4840_in],
outputs: vec![nmo_10_out, eth_23_out],
balance_blinding: BalanceWitness::random_blinding(&mut rng),
};
let witness = BundleWitness {
partials: vec![ptx_unbalanced, ptx_solved],
};
assert!(witness.balance().is_zero());
assert_eq!(witness.balance().balances, vec![]);
}
}

4
cl/cl/src/error.rs Normal file
View File

@ -0,0 +1,4 @@
#[derive(Debug)]
pub enum Error {
ProofFailed,
}

85
cl/cl/src/input.rs Normal file
View File

@ -0,0 +1,85 @@
/// This module defines the partial transaction structure.
///
/// Partial transactions, as the name suggests, are transactions
/// which on their own may not balance (i.e. \sum inputs != \sum outputs)
use crate::{
note::{Constraint, NoteWitness},
nullifier::{Nullifier, NullifierSecret},
Nonce,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Input {
pub nullifier: Nullifier,
pub constraint: Constraint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputWitness {
pub note: NoteWitness,
pub nf_sk: NullifierSecret,
}
impl InputWitness {
pub fn new(note: NoteWitness, nf_sk: NullifierSecret) -> Self {
Self { note, nf_sk }
}
pub fn from_output(output: crate::OutputWitness, nf_sk: NullifierSecret) -> Self {
assert_eq!(nf_sk.commit(), output.nf_pk);
Self::new(output.note, nf_sk)
}
pub fn public(output: crate::OutputWitness) -> Self {
let nf_sk = NullifierSecret::zero();
assert_eq!(nf_sk.commit(), output.nf_pk); // ensure the output was a public UTXO
Self::new(output.note, nf_sk)
}
pub fn evolved_nonce(&self, domain: &[u8]) -> Nonce {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_COIN_EVOLVE");
hasher.update(domain);
hasher.update(self.nf_sk.0);
hasher.update(self.note.commit(self.nf_sk.commit()).0);
let nonce_bytes: [u8; 32] = hasher.finalize().into();
Nonce::from_bytes(nonce_bytes)
}
pub fn evolve_output(&self, domain: &[u8]) -> crate::OutputWitness {
crate::OutputWitness {
note: NoteWitness {
nonce: self.evolved_nonce(domain),
..self.note
},
nf_pk: self.nf_sk.commit(),
}
}
pub fn nullifier(&self) -> Nullifier {
Nullifier::new(self.nf_sk, self.note_commitment())
}
pub fn commit(&self) -> Input {
Input {
nullifier: self.nullifier(),
constraint: self.note.constraint,
}
}
pub fn note_commitment(&self) -> crate::NoteCommitment {
self.note.commit(self.nf_sk.commit())
}
}
impl Input {
pub fn to_bytes(&self) -> [u8; 64] {
let mut bytes = [0u8; 64];
bytes[..32].copy_from_slice(self.nullifier.as_bytes());
bytes[32..64].copy_from_slice(&self.constraint.0);
bytes
}
}

19
cl/cl/src/lib.rs Normal file
View File

@ -0,0 +1,19 @@
pub mod balance;
pub mod bundle;
pub mod error;
pub mod input;
pub mod merkle;
pub mod note;
pub mod nullifier;
pub mod output;
pub mod partial_tx;
pub use balance::{Balance, BalanceWitness};
pub use bundle::{Bundle, BundleWitness};
pub use input::{Input, InputWitness};
pub use note::{Constraint, Nonce, NoteCommitment, NoteWitness};
pub use nullifier::{Nullifier, NullifierCommitment, NullifierSecret};
pub use output::{Output, OutputWitness};
pub use partial_tx::{
PartialTx, PartialTxInputWitness, PartialTxOutputWitness, PartialTxWitness, PtxRoot,
};

239
cl/cl/src/merkle.rs Normal file
View File

@ -0,0 +1,239 @@
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub fn padded_leaves<const N: usize>(elements: &[Vec<u8>]) -> [[u8; 32]; N] {
let mut leaves = [[0u8; 32]; N];
for (i, element) in elements.iter().enumerate() {
assert!(i < N);
leaves[i] = leaf(element);
}
leaves
}
pub fn leaf(data: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_MERKLE_LEAF");
hasher.update(data);
hasher.finalize().into()
}
pub fn node(a: [u8; 32], b: [u8; 32]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_MERKLE_NODE");
hasher.update(a);
hasher.update(b);
hasher.finalize().into()
}
pub fn root<const N: usize>(elements: [[u8; 32]; N]) -> [u8; 32] {
let n = elements.len();
assert!(n.is_power_of_two());
let mut nodes = elements;
for h in (1..=n.ilog2()).rev() {
for i in 0..2usize.pow(h - 1) {
nodes[i] = node(nodes[i * 2], nodes[i * 2 + 1]);
}
}
nodes[0]
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PathNode {
Left([u8; 32]),
Right([u8; 32]),
}
pub fn path_root(leaf: [u8; 32], path: &[PathNode]) -> [u8; 32] {
let mut computed_hash = leaf;
for path_node in path {
match path_node {
PathNode::Left(sibling_hash) => {
computed_hash = node(*sibling_hash, computed_hash);
}
PathNode::Right(sibling_hash) => {
computed_hash = node(computed_hash, *sibling_hash);
}
}
}
computed_hash
}
pub fn path<const N: usize>(leaves: [[u8; 32]; N], idx: usize) -> Vec<PathNode> {
assert!(N.is_power_of_two());
assert!(idx < N);
let mut nodes = leaves;
let mut path = Vec::new();
let mut idx = idx;
for h in (1..=N.ilog2()).rev() {
if idx % 2 == 0 {
path.push(PathNode::Right(nodes[idx + 1]));
} else {
path.push(PathNode::Left(nodes[idx - 1]));
}
idx /= 2;
for i in 0..2usize.pow(h - 1) {
nodes[i] = node(nodes[i * 2], nodes[i * 2 + 1]);
}
}
path
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_root_height_1() {
let r = root::<1>(padded_leaves(&[b"sand".into()]));
let expected = leaf(b"sand");
assert_eq!(r, expected);
}
#[test]
fn test_root_height_2() {
let r = root::<2>(padded_leaves(&[b"desert".into(), b"sand".into()]));
let expected = node(leaf(b"desert"), leaf(b"sand"));
assert_eq!(r, expected);
}
#[test]
fn test_root_height_3() {
let r = root::<4>(padded_leaves(&[
b"desert".into(),
b"sand".into(),
b"feels".into(),
b"warm".into(),
]));
let expected = node(
node(leaf(b"desert"), leaf(b"sand")),
node(leaf(b"feels"), leaf(b"warm")),
);
assert_eq!(r, expected);
}
#[test]
fn test_root_height_4() {
let r = root::<8>(padded_leaves(&[
b"desert".into(),
b"sand".into(),
b"feels".into(),
b"warm".into(),
b"at".into(),
b"night".into(),
]));
let expected = node(
node(
node(leaf(b"desert"), leaf(b"sand")),
node(leaf(b"feels"), leaf(b"warm")),
),
node(
node(leaf(b"at"), leaf(b"night")),
node([0u8; 32], [0u8; 32]),
),
);
assert_eq!(r, expected);
}
#[test]
fn test_path_height_1() {
let leaves = padded_leaves(&[b"desert".into()]);
let r = root::<1>(leaves);
let p = path::<1>(leaves, 0);
let expected = vec![];
assert_eq!(p, expected);
assert_eq!(path_root(leaf(b"desert"), &p), r);
}
#[test]
fn test_path_height_2() {
let leaves = padded_leaves(&[b"desert".into(), b"sand".into()]);
let r = root::<2>(leaves);
// --- proof for element at idx 0
let p0 = path(leaves, 0);
let expected0 = vec![PathNode::Right(leaf(b"sand"))];
assert_eq!(p0, expected0);
assert_eq!(path_root(leaf(b"desert"), &p0), r);
// --- proof for element at idx 1
let p1 = path(leaves, 1);
let expected1 = vec![PathNode::Left(leaf(b"desert"))];
assert_eq!(p1, expected1);
assert_eq!(path_root(leaf(b"sand"), &p1), r);
}
#[test]
fn test_path_height_3() {
let leaves = padded_leaves(&[
b"desert".into(),
b"sand".into(),
b"feels".into(),
b"warm".into(),
]);
let r = root::<4>(leaves);
// --- proof for element at idx 0
let p0 = path(leaves, 0);
let expected0 = vec![
PathNode::Right(leaf(b"sand")),
PathNode::Right(node(leaf(b"feels"), leaf(b"warm"))),
];
assert_eq!(p0, expected0);
assert_eq!(path_root(leaf(b"desert"), &p0), r);
// --- proof for element at idx 1
let p1 = path(leaves, 1);
let expected1 = vec![
PathNode::Left(leaf(b"desert")),
PathNode::Right(node(leaf(b"feels"), leaf(b"warm"))),
];
assert_eq!(p1, expected1);
assert_eq!(path_root(leaf(b"sand"), &p1), r);
// --- proof for element at idx 2
let p2 = path(leaves, 2);
let expected2 = vec![
PathNode::Right(leaf(b"warm")),
PathNode::Left(node(leaf(b"desert"), leaf(b"sand"))),
];
assert_eq!(p2, expected2);
assert_eq!(path_root(leaf(b"feels"), &p2), r);
// --- proof for element at idx 3
let p3 = path(leaves, 3);
let expected3 = vec![
PathNode::Left(leaf(b"feels")),
PathNode::Left(node(leaf(b"desert"), leaf(b"sand"))),
];
assert_eq!(p3, expected3);
assert_eq!(path_root(leaf(b"warm"), &p3), r);
}
}

171
cl/cl/src/note.rs Normal file
View File

@ -0,0 +1,171 @@
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::{balance::Unit, nullifier::NullifierCommitment};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Constraint(pub [u8; 32]);
impl Constraint {
pub fn from_vk(constraint_vk: &[u8]) -> Self {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_CONSTRAINT_COMMIT");
hasher.update(constraint_vk);
let constraint_cm: [u8; 32] = hasher.finalize().into();
Self(constraint_cm)
}
}
pub fn derive_unit(unit: &str) -> Unit {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_UNIT");
hasher.update(unit.as_bytes());
let unit: Unit = hasher.finalize().into();
unit
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NoteCommitment(pub [u8; 32]);
impl NoteCommitment {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct NoteWitness {
pub value: u64,
pub unit: Unit,
pub constraint: Constraint,
pub state: [u8; 32],
pub nonce: Nonce,
}
impl NoteWitness {
pub fn new(
value: u64,
unit: Unit,
constraint: Constraint,
state: [u8; 32],
nonce: Nonce,
) -> Self {
Self {
value,
unit,
constraint,
state,
nonce,
}
}
pub fn basic(value: u64, unit: Unit, rng: impl RngCore) -> Self {
let constraint = Constraint([0u8; 32]);
let nonce = Nonce::random(rng);
Self::new(value, unit, constraint, [0u8; 32], nonce)
}
pub fn stateless(value: u64, unit: Unit, constraint: Constraint, rng: impl RngCore) -> Self {
Self::new(value, unit, constraint, [0u8; 32], Nonce::random(rng))
}
pub fn commit(&self, nf_pk: NullifierCommitment) -> NoteCommitment {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_NOTE_COMMIT");
// COMMIT TO BALANCE
hasher.update(self.value.to_le_bytes());
hasher.update(self.unit);
// Important! we don't commit to the balance blinding factor as that may make the notes linkable.
// COMMIT TO STATE
hasher.update(self.state);
// COMMIT TO CONSTRAINT
hasher.update(self.constraint.0);
// COMMIT TO NONCE
hasher.update(self.nonce.as_bytes());
// COMMIT TO NULLIFIER
hasher.update(nf_pk.as_bytes());
let commit_bytes: [u8; 32] = hasher.finalize().into();
NoteCommitment(commit_bytes)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Nonce([u8; 32]);
impl Nonce {
pub fn random(mut rng: impl RngCore) -> Self {
let mut nonce = [0u8; 32];
rng.fill_bytes(&mut nonce);
Self(nonce)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::nullifier::NullifierSecret;
#[test]
fn test_note_commit_permutations() {
let (nmo, eth) = (derive_unit("NMO"), derive_unit("ETH"));
let mut rng = rand::thread_rng();
let nf_pk = NullifierSecret::random(&mut rng).commit();
let reference_note = NoteWitness::basic(32, nmo, &mut rng);
// different notes under same nullifier produce different commitments
let mutation_tests = [
NoteWitness {
value: 12,
..reference_note
},
NoteWitness {
unit: eth,
..reference_note
},
NoteWitness {
constraint: Constraint::from_vk(&[1u8; 32]),
..reference_note
},
NoteWitness {
state: [1u8; 32],
..reference_note
},
NoteWitness {
nonce: Nonce::random(&mut rng),
..reference_note
},
];
for n in mutation_tests {
assert_ne!(n.commit(nf_pk), reference_note.commit(nf_pk));
}
// commitment to same note with different nullifiers produce different commitments
let other_nf_pk = NullifierSecret::random(&mut rng).commit();
assert_ne!(
reference_note.commit(nf_pk),
reference_note.commit(other_nf_pk)
);
}
}

161
cl/cl/src/nullifier.rs Normal file
View File

@ -0,0 +1,161 @@
// The Nullifier is used to detect if a note has
// already been consumed.
// The same nullifier secret may be used across multiple
// notes to allow users to hold fewer secrets. A note
// nonce is used to disambiguate when the same nullifier
// secret is used for multiple notes.
use rand_core::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::NoteCommitment;
// Maintained privately by note holder
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct NullifierSecret(pub [u8; 16]);
// Nullifier commitment is public information that
// can be provided to anyone wishing to transfer
// you a note
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct NullifierCommitment([u8; 32]);
// The nullifier attached to input notes to prove an input has not
// already been spent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Nullifier([u8; 32]);
impl NullifierSecret {
pub fn random(mut rng: impl RngCore) -> Self {
let mut sk = [0u8; 16];
rng.fill_bytes(&mut sk);
Self(sk)
}
pub const fn zero() -> Self {
Self([0u8; 16])
}
pub fn commit(&self) -> NullifierCommitment {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_NULL_COMMIT");
hasher.update(self.0);
let commit_bytes: [u8; 32] = hasher.finalize().into();
NullifierCommitment(commit_bytes)
}
pub fn from_bytes(bytes: [u8; 16]) -> Self {
Self(bytes)
}
}
impl NullifierCommitment {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn hex(&self) -> String {
hex::encode(self.0)
}
pub const fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
}
impl Nullifier {
pub fn new(sk: NullifierSecret, note_cm: NoteCommitment) -> Self {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_CL_NULLIFIER");
hasher.update(sk.0);
hasher.update(note_cm.0);
let nf_bytes: [u8; 32] = hasher.finalize().into();
Self(nf_bytes)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
#[cfg(test)]
mod test {
use crate::{note::derive_unit, Constraint, Nonce, NoteWitness};
use super::*;
#[ignore = "nullifier test vectors not stable yet"]
#[test]
fn test_nullifier_commitment_vectors() {
assert_eq!(
NullifierSecret([0u8; 16]).commit().hex(),
"384318f9864fe57647bac344e2afdc500a672dedb29d2dc63b004e940e4b382a"
);
assert_eq!(
NullifierSecret([1u8; 16]).commit().hex(),
"0fd667e6bb39fbdc35d6265726154b839638ea90bcf4e736953ccf27ca5f870b"
);
assert_eq!(
NullifierSecret([u8::MAX; 16]).commit().hex(),
"1cb78e487eb0b3116389311fdde84cd3f619a4d7f487b29bf5a002eed3784d75"
);
}
#[test]
fn test_nullifier_same_sk_different_nonce() {
let mut rng = rand::thread_rng();
let sk = NullifierSecret::random(&mut rng);
let note_1 = NoteWitness {
value: 1,
unit: derive_unit("NMO"),
constraint: Constraint::from_vk(&[]),
state: [0u8; 32],
nonce: Nonce::random(&mut rng),
};
let note_2 = NoteWitness {
nonce: Nonce::random(&mut rng),
..note_1
};
let note_cm_1 = note_1.commit(sk.commit());
let note_cm_2 = note_2.commit(sk.commit());
let nf_1 = Nullifier::new(sk, note_cm_1);
let nf_2 = Nullifier::new(sk, note_cm_2);
assert_ne!(nf_1, nf_2);
}
#[test]
fn test_same_sk_same_nonce_different_note() {
let mut rng = rand::thread_rng();
let sk = NullifierSecret::random(&mut rng);
let nonce = Nonce::random(&mut rng);
let note_1 = NoteWitness {
value: 1,
unit: derive_unit("NMO"),
constraint: Constraint::from_vk(&[]),
state: [0u8; 32],
nonce,
};
let note_2 = NoteWitness {
unit: derive_unit("ETH"),
..note_1
};
let note_cm_1 = note_1.commit(sk.commit());
let note_cm_2 = note_2.commit(sk.commit());
let nf_1 = Nullifier::new(sk, note_cm_1);
let nf_2 = Nullifier::new(sk, note_cm_2);
assert_ne!(nf_1, nf_2);
}
}

45
cl/cl/src/output.rs Normal file
View File

@ -0,0 +1,45 @@
use serde::{Deserialize, Serialize};
use crate::{
note::{NoteCommitment, NoteWitness},
nullifier::NullifierCommitment,
NullifierSecret,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Output {
pub note_comm: NoteCommitment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputWitness {
pub note: NoteWitness,
pub nf_pk: NullifierCommitment,
}
impl OutputWitness {
pub fn new(note: NoteWitness, nf_pk: NullifierCommitment) -> Self {
Self { note, nf_pk }
}
pub fn public(note: NoteWitness) -> Self {
let nf_pk = NullifierSecret::zero().commit();
Self { note, nf_pk }
}
pub fn commit_note(&self) -> NoteCommitment {
self.note.commit(self.nf_pk)
}
pub fn commit(&self) -> Output {
Output {
note_comm: self.commit_note(),
}
}
}
impl Output {
pub fn to_bytes(&self) -> [u8; 32] {
self.note_comm.0
}
}

211
cl/cl/src/partial_tx.rs Normal file
View File

@ -0,0 +1,211 @@
use rand_core::{CryptoRngCore, RngCore};
use serde::{Deserialize, Serialize};
use crate::balance::{Balance, BalanceWitness};
use crate::input::{Input, InputWitness};
use crate::merkle;
use crate::output::{Output, OutputWitness};
pub const MAX_INPUTS: usize = 8;
pub const MAX_OUTPUTS: usize = 8;
/// The partial transaction commitment couples an input to a partial transaction.
/// Prevents partial tx unbundling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PtxRoot(pub [u8; 32]);
impl From<[u8; 32]> for PtxRoot {
fn from(bytes: [u8; 32]) -> Self {
Self(bytes)
}
}
impl PtxRoot {
pub fn random(mut rng: impl RngCore) -> Self {
let mut sk = [0u8; 32];
rng.fill_bytes(&mut sk);
Self(sk)
}
pub fn hex(&self) -> String {
hex::encode(self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartialTx {
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub balance: Balance,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartialTxWitness {
pub inputs: Vec<InputWitness>,
pub outputs: Vec<OutputWitness>,
pub balance_blinding: [u8; 16],
}
impl PartialTxWitness {
pub fn random(
inputs: Vec<InputWitness>,
outputs: Vec<OutputWitness>,
mut rng: impl CryptoRngCore,
) -> Self {
Self {
inputs,
outputs,
balance_blinding: BalanceWitness::random_blinding(&mut rng),
}
}
pub fn balance(&self) -> BalanceWitness {
BalanceWitness::from_ptx(self, self.balance_blinding)
}
pub fn commit(&self) -> PartialTx {
PartialTx {
inputs: Vec::from_iter(self.inputs.iter().map(InputWitness::commit)),
outputs: Vec::from_iter(self.outputs.iter().map(OutputWitness::commit)),
balance: self.balance().commit(),
}
}
pub fn input_witness(&self, idx: usize) -> PartialTxInputWitness {
let input_bytes =
Vec::from_iter(self.inputs.iter().map(|i| i.commit().to_bytes().to_vec()));
let input_merkle_leaves = merkle::padded_leaves::<MAX_INPUTS>(&input_bytes);
let path = merkle::path(input_merkle_leaves, idx);
let input = self.inputs[idx];
PartialTxInputWitness { input, path }
}
pub fn output_witness(&self, idx: usize) -> PartialTxOutputWitness {
let output_bytes =
Vec::from_iter(self.outputs.iter().map(|o| o.commit().to_bytes().to_vec()));
let output_merkle_leaves = merkle::padded_leaves::<MAX_OUTPUTS>(&output_bytes);
let path = merkle::path(output_merkle_leaves, idx);
let output = self.outputs[idx];
PartialTxOutputWitness { output, path }
}
}
impl PartialTx {
pub fn input_root(&self) -> [u8; 32] {
let input_bytes =
Vec::from_iter(self.inputs.iter().map(Input::to_bytes).map(Vec::from_iter));
let input_merkle_leaves = merkle::padded_leaves(&input_bytes);
merkle::root::<MAX_INPUTS>(input_merkle_leaves)
}
pub fn output_root(&self) -> [u8; 32] {
let output_bytes = Vec::from_iter(
self.outputs
.iter()
.map(Output::to_bytes)
.map(Vec::from_iter),
);
let output_merkle_leaves = merkle::padded_leaves(&output_bytes);
merkle::root::<MAX_OUTPUTS>(output_merkle_leaves)
}
pub fn root(&self) -> PtxRoot {
let input_root = self.input_root();
let output_root = self.output_root();
let root = merkle::node(input_root, output_root);
PtxRoot(root)
}
}
/// An input to a partial transaction
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartialTxInputWitness {
pub input: InputWitness,
pub path: Vec<merkle::PathNode>,
}
impl PartialTxInputWitness {
pub fn input_root(&self) -> [u8; 32] {
let leaf = merkle::leaf(&self.input.commit().to_bytes());
merkle::path_root(leaf, &self.path)
}
}
/// An output to a partial transaction
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PartialTxOutputWitness {
pub output: OutputWitness,
pub path: Vec<merkle::PathNode>,
}
impl PartialTxOutputWitness {
pub fn output_root(&self) -> [u8; 32] {
let leaf = merkle::leaf(&self.output.commit().to_bytes());
merkle::path_root(leaf, &self.path)
}
}
#[cfg(test)]
mod test {
use crate::{
balance::UnitBalance,
note::{derive_unit, NoteWitness},
nullifier::NullifierSecret,
};
use super::*;
#[test]
fn test_partial_tx_balance() {
let (nmo, eth, crv) = (derive_unit("NMO"), derive_unit("ETH"), derive_unit("CRV"));
let mut rng = rand::thread_rng();
let nf_a = NullifierSecret::random(&mut rng);
let nf_b = NullifierSecret::random(&mut rng);
let nf_c = NullifierSecret::random(&mut rng);
let nmo_10_utxo = OutputWitness::new(NoteWitness::basic(10, nmo, &mut rng), nf_a.commit());
let nmo_10 = InputWitness::from_output(nmo_10_utxo, nf_a);
let eth_23_utxo = OutputWitness::new(NoteWitness::basic(23, eth, &mut rng), nf_b.commit());
let eth_23 = InputWitness::from_output(eth_23_utxo, nf_b);
let crv_4840 = OutputWitness::new(NoteWitness::basic(4840, crv, &mut rng), nf_c.commit());
let ptx_witness = PartialTxWitness {
inputs: vec![nmo_10, eth_23],
outputs: vec![crv_4840],
balance_blinding: BalanceWitness::random_blinding(&mut rng),
};
let ptx = ptx_witness.commit();
assert_eq!(
ptx.balance,
BalanceWitness {
balances: vec![
UnitBalance {
unit: nmo,
pos: 0,
neg: 10
},
UnitBalance {
unit: eth,
pos: 0,
neg: 23
},
UnitBalance {
unit: crv,
pos: 4840,
neg: 0
},
],
blinding: ptx_witness.balance_blinding
}
.commit()
);
}
}

View File

@ -0,0 +1,37 @@
use cl::{note::derive_unit, BalanceWitness};
fn receive_utxo(note: cl::NoteWitness, nf_pk: cl::NullifierCommitment) -> cl::OutputWitness {
cl::OutputWitness::new(note, nf_pk)
}
#[test]
fn test_simple_transfer() {
let nmo = derive_unit("NMO");
let mut rng = rand::thread_rng();
let sender_nf_sk = cl::NullifierSecret::random(&mut rng);
let sender_nf_pk = sender_nf_sk.commit();
let recipient_nf_pk = cl::NullifierSecret::random(&mut rng).commit();
// Assume the sender has received an unspent output from somewhere
let utxo = receive_utxo(cl::NoteWitness::basic(10, nmo, &mut rng), sender_nf_pk);
// and wants to send 8 NMO to some recipient and return 2 NMO to itself.
let recipient_output =
cl::OutputWitness::new(cl::NoteWitness::basic(8, nmo, &mut rng), recipient_nf_pk);
let change_output =
cl::OutputWitness::new(cl::NoteWitness::basic(2, nmo, &mut rng), sender_nf_pk);
let ptx_witness = cl::PartialTxWitness {
inputs: vec![cl::InputWitness::from_output(utxo, sender_nf_sk)],
outputs: vec![recipient_output, change_output],
balance_blinding: BalanceWitness::random_blinding(&mut rng),
};
let bundle = cl::BundleWitness {
partials: vec![ptx_witness],
};
assert!(bundle.balance().is_zero())
}

View File

@ -0,0 +1,10 @@
[package]
name = "leader_proof_statements"
version = "0.1.0"
edition = "2021"
[dependencies]
cl = { path = "../../cl/cl" }
serde = { version = "1.0", features = ["derive"] }
crypto-bigint = { version = "0.5.5", features = ["serde"] }
sha2 = "0.10"

View File

@ -0,0 +1,94 @@
use crypto_bigint::{CheckedMul, CheckedSub, Encoding, U256};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaderPublic {
pub cm_root: [u8; 32],
pub epoch_nonce: [u8; 32],
pub slot: u64,
pub scaled_phi_approx: (U256, U256),
pub nullifier: cl::Nullifier,
pub evolved_commitment: cl::NoteCommitment,
}
impl LeaderPublic {
pub fn new(
cm_root: [u8; 32],
epoch_nonce: [u8; 32],
slot: u64,
active_slot_coefficient: f64,
total_stake: u64,
nullifier: cl::Nullifier,
evolved_commitment: cl::NoteCommitment,
) -> Self {
let total_stake_big = U256::from_u64(total_stake);
let total_stake_sq_big = total_stake_big.checked_mul(&total_stake_big).unwrap();
let double_total_stake_sq_big = total_stake_sq_big.checked_mul(&U256::from_u64(2)).unwrap();
let precision_u64 = u64::MAX;
let precision_big = U256::from_u64(u64::MAX);
let precision_f64 = precision_u64 as f64;
let order: U256 = U256::MAX;
let order_div_precision = order.checked_div(&precision_big).unwrap();
let order_div_precision_sq = order_div_precision.checked_div(&precision_big).unwrap();
let neg_f_ln: U256 =
U256::from_u64(((-f64::ln(1f64 - active_slot_coefficient)) * precision_f64) as u64);
let neg_f_ln_sq = neg_f_ln.checked_mul(&neg_f_ln).unwrap();
let neg_f_ln_order: U256 = order_div_precision.checked_mul(&neg_f_ln).unwrap();
let t0 = neg_f_ln_order.checked_div(&total_stake_big).unwrap();
let t1 = order_div_precision_sq
.checked_mul(&neg_f_ln_sq)
.unwrap()
.checked_div(&double_total_stake_sq_big)
.unwrap();
Self {
cm_root,
epoch_nonce,
slot,
nullifier,
evolved_commitment,
scaled_phi_approx: (t0, t1),
}
}
pub fn check_winning(&self, input: &cl::InputWitness) -> bool {
let threshold = phi_approx(U256::from_u64(input.note.value), self.scaled_phi_approx);
let ticket = ticket(input, self.epoch_nonce, self.slot);
ticket < threshold
}
}
fn phi_approx(stake: U256, approx: (U256, U256)) -> U256 {
// stake * (t0 - t1 * stake)
stake
.checked_mul(
&approx
.0
.checked_sub(&approx.1.checked_mul(&stake).unwrap())
.unwrap(),
)
.unwrap()
}
fn ticket(input: &cl::InputWitness, epoch_nonce: [u8; 32], slot: u64) -> U256 {
let mut hasher = Sha256::new();
hasher.update(b"NOMOS_LEAD");
hasher.update(epoch_nonce);
hasher.update(slot.to_be_bytes());
hasher.update(input.note_commitment().as_bytes());
hasher.update(input.nf_sk.0);
let ticket_bytes: [u8; 32] = hasher.finalize().into();
U256::from_be_bytes(ticket_bytes)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaderPrivate {
pub input: cl::InputWitness,
pub input_cm_path: Vec<cl::merkle::PathNode>,
}

2
proof_of_leadership/risc0/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
Cargo.lock
target/

View File

@ -0,0 +1,11 @@
[workspace]
resolver = "2"
members = [ "prover", "risc0_proofs"]
# Always optimize; building and running the risc0_proofs takes much longer without optimization.
[profile.dev]
opt-level = 3
[profile.release]
debug = 1
lto = true

View File

@ -0,0 +1,19 @@
[package]
name = "nomos_pol_prover"
version = "0.1.0"
edition = "2021"
[dependencies]
cl = { path = "../../../cl/cl" }
leader_proof_statements = { path = "../../proof_statements" }
nomos_pol_risc0_proofs = { path = "../risc0_proofs" }
risc0-zkvm = { version = "1.0", features = ["prove"] }
risc0-groth16 = { version = "1.0" }
tracing = "0.1"
rand = "0.8.5"
rand_core = "0.6.0"
thiserror = "1.0.62"
anyhow = "1"
[features]
metal = ["risc0-zkvm/metal"]

View File

@ -0,0 +1,106 @@
use leader_proof_statements::{LeaderPrivate, LeaderPublic};
use risc0_zkvm::Receipt;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("failed to produce proof")]
ProofError(#[from] anyhow::Error),
}
pub fn prove(leader_public: LeaderPublic, leader_private: LeaderPrivate) -> Result<Receipt, Error> {
let env = risc0_zkvm::ExecutorEnv::builder()
.write(&leader_public)
.unwrap()
.write(&leader_private)
.unwrap()
.build()
.unwrap();
// Obtain the default prover.
let prover = risc0_zkvm::default_prover();
let start_t = std::time::Instant::now();
// Proof information by proving the specified ELF binary.
// This struct contains the receipt along with statistics about execution of the guest
let opts = risc0_zkvm::ProverOpts::succinct();
let prove_info =
prover.prove_with_opts(env, nomos_pol_risc0_proofs::PROOF_OF_LEADERSHIP_ELF, &opts)?;
tracing::debug!(
"STARK prover time: {:.2?}, total_cycles: {}",
start_t.elapsed(),
prove_info.stats.total_cycles
);
// extract the receipt.
Ok(prove_info.receipt)
}
#[cfg(test)]
mod test {
use super::*;
use cl::{note::NoteWitness, nullifier::NullifierSecret};
use rand::thread_rng;
const MAX_NOTE_COMMS: usize = 1 << 8;
// derive-unit(NOMOS_NMO)
pub const NMO_UNIT: [u8; 32] = [
67, 50, 140, 228, 181, 204, 226, 242, 254, 193, 239, 51, 237, 68, 36, 126, 124, 227, 60,
112, 223, 195, 146, 236, 5, 21, 42, 215, 48, 122, 25, 195,
];
fn note_commitment_leaves(
note_commitments: &[cl::NoteCommitment],
) -> [[u8; 32]; MAX_NOTE_COMMS] {
let note_comm_bytes =
Vec::from_iter(note_commitments.iter().map(|c| c.as_bytes().to_vec()));
let cm_leaves = cl::merkle::padded_leaves::<MAX_NOTE_COMMS>(&note_comm_bytes);
cm_leaves
}
#[test]
fn test_leader_prover() {
let mut rng = thread_rng();
let input = cl::InputWitness {
note: NoteWitness::basic(32, NMO_UNIT, &mut rng),
nf_sk: NullifierSecret::random(&mut rng),
};
let notes = vec![input.note_commitment()];
let epoch_nonce = [0u8; 32];
let slot = 0;
let active_slot_coefficient = 0.05;
let total_stake = 1000;
let leaves = note_commitment_leaves(&notes);
let mut expected_public_inputs = LeaderPublic::new(
cl::merkle::root(leaves),
epoch_nonce,
slot,
active_slot_coefficient,
total_stake,
input.nullifier(),
input.evolve_output(b"NOMOS_POL").commit_note(),
);
while !expected_public_inputs.check_winning(&input) {
expected_public_inputs.slot += 1;
}
println!("slot={}", expected_public_inputs.slot);
let private_inputs = LeaderPrivate {
input: input.clone(),
input_cm_path: cl::merkle::path(leaves, 0),
};
let proof = prove(expected_public_inputs, private_inputs).unwrap();
assert!(proof
.verify(nomos_pol_risc0_proofs::PROOF_OF_LEADERSHIP_ID)
.is_ok());
assert_eq!(expected_public_inputs, proof.journal.decode().unwrap());
}
}

View File

@ -0,0 +1,10 @@
[package]
name = "nomos_pol_risc0_proofs"
version = "0.1.0"
edition = "2021"
[build-dependencies]
risc0-build = { version = "1.0" }
[package.metadata.risc0]
methods = ["proof_of_leadership"]

View File

@ -0,0 +1,3 @@
fn main() {
risc0_build::embed_methods();
}

View File

@ -0,0 +1,19 @@
[package]
name = "proof_of_leadership"
version = "0.1.0"
edition = "2021"
[workspace]
[dependencies]
risc0-zkvm = { version = "1.0", default-features = false, features = ['std'] }
serde = { version = "1.0", features = ["derive"] }
cl = { path = "../../../../cl/cl" }
leader_proof_statements = { path = "../../../proof_statements" }
sha2 = "0.10"
crypto-bigint = "0.5.5"
[patch.crates-io]
# add RISC Zero accelerator support for all downstream usages of the following crates.
sha2 = { git = "https://github.com/risc0/RustCrypto-hashes", tag = "sha2-v0.10.8-risczero.0" }
crypto-bigint = { git = "https://github.com/risc0/RustCrypto-crypto-bigint", tag = "v0.5.5-risczero.0" }

View File

@ -0,0 +1,41 @@
use cl::balance::Unit;
/// Proof of Leadership
use cl::merkle;
use leader_proof_statements::{LeaderPrivate, LeaderPublic};
use risc0_zkvm::guest::env;
// derive-unit(NOMOS_NMO)
pub const NMO_UNIT: Unit = [
67, 50, 140, 228, 181, 204, 226, 242, 254, 193, 239, 51, 237, 68, 36, 126, 124, 227, 60, 112,
223, 195, 146, 236, 5, 21, 42, 215, 48, 122, 25, 195,
];
fn main() {
let public_inputs: LeaderPublic = env::read();
let LeaderPrivate {
input,
input_cm_path,
} = env::read();
// Lottery checks
assert!(public_inputs.check_winning(&input));
// Ensure note is valid
assert_eq!(input.note.unit, NMO_UNIT);
let note_cm = input.note_commitment();
let note_cm_leaf = merkle::leaf(note_cm.as_bytes());
let note_cm_root = merkle::path_root(note_cm_leaf, &input_cm_path);
assert_eq!(note_cm_root, public_inputs.cm_root);
// Public input constraints
assert_eq!(input.nullifier(), public_inputs.nullifier);
let evolved_output = input.evolve_output(b"NOMOS_POL");
assert_eq!(
evolved_output.commit_note(),
public_inputs.evolved_commitment
);
env::commit(&public_inputs);
}

View File

@ -0,0 +1 @@
include!(concat!(env!("OUT_DIR"), "/methods.rs"));