contract/consensus: use new ConsensusBurn proof in GenesisStake

This commit is contained in:
aggstam
2023-05-27 16:10:23 +03:00
parent 7ebe829caf
commit b9c817fce8
9 changed files with 169 additions and 76 deletions

View File

@@ -0,0 +1,92 @@
/* This file is part of DarkFi (https://dark.fi)
*
* Copyright (C) 2020-2023 Dyne.org foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! This API is crufty. Please rework it into something nice to read and nice to use.
use darkfi::{
zk::{halo2::Value, Proof, ProvingKey, Witness, ZkCircuit},
zkas::ZkBinary,
Result,
};
use darkfi_sdk::{
crypto::{
pasta_prelude::*, pedersen_commitment_u64, poseidon_hash, Coin, PublicKey, TokenId,
CONSENSUS_CONTRACT_ID,
},
pasta::pallas,
};
use rand::rngs::OsRng;
use crate::model::ZERO;
pub struct TransactionBuilderOutputInfo {
pub value: u64,
pub token_id: TokenId,
pub public_key: PublicKey,
}
pub struct ConsensusMintRevealed {
pub epoch: pallas::Base,
pub coin: Coin,
pub value_commit: pallas::Point,
}
impl ConsensusMintRevealed {
pub fn to_vec(&self) -> Vec<pallas::Base> {
let valcom_coords = self.value_commit.to_affine().coordinates().unwrap();
// NOTE: It's important to keep these in the same order
// as the `constrain_instance` calls in the zkas code.
vec![self.epoch, self.coin.inner(), *valcom_coords.x(), *valcom_coords.y()]
}
}
pub fn create_consensus_mint_proof(
zkbin: &ZkBinary,
pk: &ProvingKey,
epoch: u64,
output: &TransactionBuilderOutputInfo,
value_blind: pallas::Scalar,
serial: pallas::Base,
coin_blind: pallas::Base,
) -> Result<(Proof, ConsensusMintRevealed)> {
let epoch_pallas = pallas::Base::from(epoch);
let value_pallas = pallas::Base::from(output.value);
let value_commit = pedersen_commitment_u64(output.value, value_blind);
let (pub_x, pub_y) = output.public_key.xy();
let coin =
Coin::from(poseidon_hash([pub_x, pub_y, value_pallas, epoch_pallas, serial, coin_blind]));
let public_inputs = ConsensusMintRevealed { epoch: epoch_pallas, coin, value_commit };
let prover_witnesses = vec![
Witness::Base(Value::known(pub_x)),
Witness::Base(Value::known(pub_y)),
Witness::Base(Value::known(value_pallas)),
Witness::Base(Value::known(epoch_pallas)),
Witness::Base(Value::known(serial)),
Witness::Base(Value::known(coin_blind)),
Witness::Scalar(Value::known(value_blind)),
];
let circuit = ZkCircuit::new(prover_witnesses, zkbin.clone());
let proof = Proof::create(pk, &[circuit], &public_inputs.to_vec(), &mut OsRng)?;
Ok((proof, public_inputs))
}

View File

@@ -23,10 +23,7 @@ use darkfi::{
zkas::ZkBinary,
Result,
};
use darkfi_money_contract::{
client::{transfer_v1::TransactionBuilderClearInputInfo, MoneyNote},
model::{ClearInput, Output},
};
use darkfi_money_contract::{client::MoneyNote, model::ClearInput};
use darkfi_sdk::{
crypto::{
note::AeadEncryptedNote, pasta_prelude::*, Keypair, PublicKey, CONSENSUS_CONTRACT_ID,
@@ -38,8 +35,8 @@ use log::{debug, info};
use rand::rngs::OsRng;
use crate::{
client::stake_v1::{create_stake_mint_proof, TransactionBuilderOutputInfo},
model::ConsensusGenesisStakeParamsV1,
client::common::{create_consensus_mint_proof, TransactionBuilderOutputInfo},
model::{ConsensusGenesisStakeParamsV1, ConsensusOutput, ZERO},
};
pub struct ConsensusGenesisStakeCallDebris {
@@ -53,32 +50,24 @@ pub struct ConsensusGenesisStakeCallBuilder {
pub keypair: Keypair,
/// Amount of tokens we want to mint and stake
pub amount: u64,
/// `Mint_V1` zkas circuit ZkBinary
/// `ConsensusMint_V1` zkas circuit ZkBinary
pub mint_zkbin: ZkBinary,
/// Proving key for the `Mint_V1` zk circuit
/// Proving key for the `ConsensusMint_V1` zk circuit
pub mint_pk: ProvingKey,
}
impl ConsensusGenesisStakeCallBuilder {
pub fn build(&self) -> Result<ConsensusGenesisStakeCallDebris> {
debug!("Building Consensus::GenesisStakeV1 contract call");
assert!(self.amount != 0);
let value = self.amount;
assert!(value != 0);
// In this call, we will build one clear input and one anonymous output.
// Only DARK_TOKEN_ID can be minted and staked on genesis slot.
let token_id = *DARK_TOKEN_ID;
let input = TransactionBuilderClearInputInfo {
value: self.amount,
token_id,
signature_secret: self.keypair.secret,
};
let output = TransactionBuilderOutputInfo {
value: self.amount,
token_id,
public_key: self.keypair.public,
};
let epoch = 0;
let secret_key = self.keypair.secret;
let public_key = PublicKey::from_secret(secret_key);
// We just create the pedersen commitment blinds here. We simply
// enforce that the clear input and the anon output have the same
@@ -87,29 +76,22 @@ impl ConsensusGenesisStakeCallBuilder {
let value_blind = pallas::Scalar::random(&mut OsRng);
let token_blind = pallas::Scalar::random(&mut OsRng);
let c_input = ClearInput {
value: input.value,
token_id: input.token_id,
value_blind,
token_blind,
signature_public: PublicKey::from_secret(input.signature_secret),
};
let c_input =
ClearInput { value, token_id, value_blind, token_blind, signature_public: public_key };
let output = TransactionBuilderOutputInfo { value, token_id, public_key };
let serial = pallas::Base::random(&mut OsRng);
let spend_hook = CONSENSUS_CONTRACT_ID.inner();
let user_data = pallas::Base::random(&mut OsRng);
let coin_blind = pallas::Base::random(&mut OsRng);
info!("Creating genesis stake mint proof for output");
let (proof, public_inputs) = create_stake_mint_proof(
let (proof, public_inputs) = create_consensus_mint_proof(
&self.mint_zkbin,
&self.mint_pk,
epoch,
&output,
value_blind,
token_blind,
serial,
spend_hook,
user_data,
coin_blind,
)?;
@@ -118,8 +100,8 @@ impl ConsensusGenesisStakeCallBuilder {
serial,
value: output.value,
token_id: output.token_id,
spend_hook,
user_data,
spend_hook: CONSENSUS_CONTRACT_ID.inner(),
user_data: ZERO,
coin_blind,
value_blind,
token_blind,
@@ -128,9 +110,8 @@ impl ConsensusGenesisStakeCallBuilder {
let encrypted_note = AeadEncryptedNote::encrypt(&note, &output.public_key, &mut OsRng)?;
let output = Output {
let output = ConsensusOutput {
value_commit: public_inputs.value_commit,
token_commit: public_inputs.token_commit,
coin: public_inputs.coin,
note: encrypted_note,
};

View File

@@ -25,6 +25,9 @@
//! the necessary objects provided by the caller. This is intentional, so we
//! are able to abstract away any wallet interfaces to client implementations.
/// Common functions
pub(crate) mod common;
/// `Consensus::GenesisStakeV1` API
pub mod genesis_stake_v1;

View File

@@ -92,12 +92,14 @@ fn init_contract(cid: ContractId, _ix: &[u8]) -> ContractResult {
// order to be able to verify the circuits being bundled and enforcing
// a specific tree inside sled, and also creation of VerifyingKey.
let money_mint_v1_bincode = include_bytes!("../../money/proof/mint_v1.zk.bin");
let consensus_mint_v1_bincode = include_bytes!("../proof/consensus_mint_v1.zk.bin");
let money_burn_v1_bincode = include_bytes!("../../money/proof/burn_v1.zk.bin");
let proposal_reward_v1_bincode = include_bytes!("../proof/proposal_reward_v1.zk.bin");
let proposal_mint_v1_bincode = include_bytes!("../proof/proposal_mint_v1.zk.bin");
// For that, we use `zkas_db_set` and pass in the bincode.
zkas_db_set(&money_mint_v1_bincode[..])?;
zkas_db_set(&consensus_mint_v1_bincode[..])?;
zkas_db_set(&money_burn_v1_bincode[..])?;
zkas_db_set(&proposal_reward_v1_bincode[..])?;
zkas_db_set(&proposal_mint_v1_bincode[..])?;

View File

@@ -18,13 +18,10 @@
use darkfi_money_contract::{
error::MoneyError, model::ConsensusStakeUpdateV1, CONSENSUS_CONTRACT_COINS_TREE,
MONEY_CONTRACT_ZKAS_MINT_NS_V1,
CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1,
};
use darkfi_sdk::{
crypto::{
pasta_prelude::*, pedersen_commitment_base, pedersen_commitment_u64, ContractId,
DARK_TOKEN_ID,
},
crypto::{pasta_prelude::*, pedersen_commitment_u64, ContractId, DARK_TOKEN_ID},
db::{db_contains_key, db_lookup},
error::ContractError,
msg,
@@ -34,7 +31,10 @@ use darkfi_sdk::{
};
use darkfi_serial::{deserialize, serialize, Encodable, WriteExt};
use crate::{model::ConsensusGenesisStakeParamsV1, ConsensusFunction};
use crate::{
model::{ConsensusGenesisStakeParamsV1, ZERO},
ConsensusFunction,
};
/// `get_metadata` function for `Consensus::GenesisStakeV1`
pub(crate) fn consensus_genesis_stake_get_metadata_v1(
@@ -50,20 +50,16 @@ pub(crate) fn consensus_genesis_stake_get_metadata_v1(
// Public keys for the transaction signatures we have to verify
let signature_pubkeys = vec![params.input.signature_public];
// Genesis stake only happens on epoch 0
let epoch = ZERO;
// Grab the pedersen commitment from the anonymous output
let output = &params.output;
let value_coords = output.value_commit.to_affine().coordinates().unwrap();
let token_coords = output.token_commit.to_affine().coordinates().unwrap();
zk_public_inputs.push((
MONEY_CONTRACT_ZKAS_MINT_NS_V1.to_string(),
vec![
output.coin.inner(),
*value_coords.x(),
*value_coords.y(),
*token_coords.x(),
*token_coords.y(),
],
CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1.to_string(),
vec![epoch, output.coin.inner(), *value_coords.x(), *value_coords.y()],
));
// Serialize everything gathered and return it
@@ -106,9 +102,9 @@ pub(crate) fn consensus_genesis_stake_process_instruction_v1(
return Err(MoneyError::DuplicateCoin.into())
}
// Verify that the value and token commitments match. In here we just
// Verify that the value commitment match. In here we just
// confirm that the clear input and the anon output have the same
// commitments.
// commitment.
if pedersen_commitment_u64(params.input.value, params.input.value_blind) !=
params.output.value_commit
{
@@ -116,13 +112,6 @@ pub(crate) fn consensus_genesis_stake_process_instruction_v1(
return Err(MoneyError::ValueMismatch.into())
}
if pedersen_commitment_base(params.input.token_id.inner(), params.input.token_blind) !=
params.output.token_commit
{
msg!("[GenesisStakeV1] Error: Token commitment mismatch");
return Err(MoneyError::TokenMismatch.into())
}
// Create a state update.
let update = ConsensusStakeUpdateV1 { coin: params.output.coin };
let mut update_data = vec![];

View File

@@ -18,18 +18,29 @@
use darkfi_money_contract::model::{ClearInput, Input, Output, StakeInput};
use darkfi_sdk::{
crypto::{ecvrf::VrfProof, PublicKey},
crypto::{ecvrf::VrfProof, note::AeadEncryptedNote, Coin, PublicKey},
pasta::pallas,
};
use darkfi_serial::{SerialDecodable, SerialEncodable};
/// A consensus contract call's anonymous output
#[derive(Clone, Debug, PartialEq, SerialEncodable, SerialDecodable)]
pub struct ConsensusOutput {
/// Pedersen commitment for the output's value
pub value_commit: pallas::Point,
/// Minted coin
pub coin: Coin,
/// AEAD encrypted note
pub note: AeadEncryptedNote,
}
/// Parameters for `Consensus::GenesisStake`
#[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
pub struct ConsensusGenesisStakeParamsV1 {
/// Clear input
pub input: ClearInput,
/// Anonymous output
pub output: Output,
pub output: ConsensusOutput,
}
/// Parameters for `Consensus::ProposalBurn`

View File

@@ -105,7 +105,8 @@ async fn consensus_contract_genesis_stake_unstake() -> Result<()> {
th.assert_trees();
// Gather new staked owncoin
let alice_staked_oc = th.gather_owncoin(Holder::Alice, genesis_stake_params.output, true)?;
let alice_staked_oc =
th.gather_consensus_owncoin(Holder::Alice, genesis_stake_params.output)?;
// Verify values match
assert!(ALICE_INITIAL == alice_staked_oc.note.value);

View File

@@ -50,7 +50,7 @@ use darkfi_consensus_contract::{
proposal_v1::ConsensusProposalCallBuilder, stake_v1::ConsensusStakeCallBuilder,
unstake_v1::ConsensusUnstakeCallBuilder,
},
model::{ConsensusGenesisStakeParamsV1, ConsensusProposalMintParamsV1},
model::{ConsensusGenesisStakeParamsV1, ConsensusOutput, ConsensusProposalMintParamsV1},
ConsensusFunction,
};
use darkfi_money_contract::{
@@ -59,7 +59,7 @@ use darkfi_money_contract::{
unstake_v1::MoneyUnstakeCallBuilder, MoneyNote, OwnCoin,
},
model::{ConsensusStakeParamsV1, MoneyTransferParamsV1, MoneyUnstakeParamsV1, Output},
MoneyFunction, CONSENSUS_CONTRACT_ZKAS_PROPOSAL_MINT_NS_V1,
MoneyFunction, CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1, CONSENSUS_CONTRACT_ZKAS_PROPOSAL_MINT_NS_V1,
CONSENSUS_CONTRACT_ZKAS_PROPOSAL_REWARD_NS_V1, MONEY_CONTRACT_ZKAS_BURN_NS_V1,
MONEY_CONTRACT_ZKAS_MINT_NS_V1,
};
@@ -230,6 +230,7 @@ impl ConsensusTestHarness {
SMART_CONTRACT_ZKAS_DB_NAME,
)?;
mkpk!(MONEY_CONTRACT_ZKAS_MINT_NS_V1);
mkpk!(CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1);
mkpk!(MONEY_CONTRACT_ZKAS_BURN_NS_V1);
mkpk!(CONSENSUS_CONTRACT_ZKAS_PROPOSAL_REWARD_NS_V1);
mkpk!(CONSENSUS_CONTRACT_ZKAS_PROPOSAL_MINT_NS_V1);
@@ -327,7 +328,8 @@ impl ConsensusTestHarness {
amount: u64,
) -> Result<(Transaction, ConsensusGenesisStakeParamsV1)> {
let wallet = self.holders.get_mut(&holder).unwrap();
let (mint_pk, mint_zkbin) = self.proving_keys.get(&MONEY_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
let (mint_pk, mint_zkbin) =
self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
let tx_action_benchmark =
self.tx_action_benchmarks.get_mut(&TxAction::GenesisStake).unwrap();
let timer = Instant::now();
@@ -696,18 +698,28 @@ impl ConsensusTestHarness {
Ok(())
}
pub fn gather_owncoin(
pub fn gather_owncoin(&mut self, holder: Holder, output: Output) -> Result<OwnCoin> {
let wallet = self.holders.get_mut(&holder).unwrap();
let leaf_position = wallet.merkle_tree.witness().unwrap();
let note: MoneyNote = output.note.decrypt(&wallet.keypair.secret)?;
let oc = OwnCoin {
coin: Coin::from(output.coin),
note: note.clone(),
secret: wallet.keypair.secret,
nullifier: Nullifier::from(poseidon_hash([wallet.keypair.secret.inner(), note.serial])),
leaf_position,
};
Ok(oc)
}
pub fn gather_consensus_owncoin(
&mut self,
holder: Holder,
output: Output,
consensus: bool,
output: ConsensusOutput,
) -> Result<OwnCoin> {
let wallet = self.holders.get_mut(&holder).unwrap();
let leaf_position = if consensus {
wallet.consensus_merkle_tree.witness().unwrap()
} else {
wallet.merkle_tree.witness().unwrap()
};
let leaf_position = wallet.consensus_merkle_tree.witness().unwrap();
let note: MoneyNote = output.note.decrypt(&wallet.keypair.secret)?;
let oc = OwnCoin {
coin: Coin::from(output.coin),

View File

@@ -100,6 +100,8 @@ pub const CONSENSUS_CONTRACT_NULLIFIERS_TREE: &str = "consensus_nullifiers";
pub const CONSENSUS_CONTRACT_DB_VERSION: &str = "db_version";
pub const CONSENSUS_CONTRACT_COIN_MERKLE_TREE: &str = "consensus_coin_tree";
/// zkas consensus mint circuit namespace
pub const CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1: &str = "ConsensusMint_V1";
/// zkas proposal reward circuit namespace
pub const CONSENSUS_CONTRACT_ZKAS_PROPOSAL_REWARD_NS_V1: &str = "ProposalReward_V1";
/// zkas proposal mint circuit namespace