소스 검색

contract/consensus: Minor cleanups.

parazyd 3 년 전
부모
커밋
f61aa41fac

+ 1 - 1
script/research/pallas_constants/src/main.rs

@@ -44,7 +44,7 @@ fn to_constant(name: &str, x: pallas::Base, public: bool) -> String {
 /// Generate constants for corresponding `pallas::Base`
 fn main() -> Result<()> {
     let mut source = String::new();
-    source.push_str(&to_constant("REWARD_PALLAS", pallas::Base::one(), true));
+    source.push_str(&to_constant("REWARD_PALLAS", pallas::Base::from(100_000_000), true));
     source.push_str(&to_constant("SERIAL_PREFIX", pallas::Base::from(2), true));
     source.push_str(&to_constant("SEED_PREFIX", pallas::Base::from(3), true));
     source.push_str(&to_constant("MU_Y_PREFIX", pallas::Base::from(22), true));

+ 1 - 0
src/contract/consensus/src/client/common.rs

@@ -67,6 +67,7 @@ impl ConsensusMintRevealed {
     }
 }
 
+/// Create a ZK proof for minting a coin in the Consensus coin state.
 pub fn create_consensus_mint_proof(
     zkbin: &ZkBinary,
     pk: &ProvingKey,

+ 28 - 10
src/contract/consensus/src/client/genesis_stake_v1.rs

@@ -46,8 +46,10 @@ pub struct ConsensusGenesisStakeCallDebris {
 
 /// Struct holding necessary information to build a `Consensus::GenesisStakeV1` contract call.
 pub struct ConsensusGenesisStakeCallBuilder {
-    /// Caller's keypair
+    /// Signer keypair, this pubkey is in the clear input, and used to sign the tx.
     pub keypair: Keypair,
+    /// Output pubkey, to whom the minted coin goes. The secret should be managed externally.
+    pub recipient: PublicKey,
     /// Amount of tokens we want to mint and stake
     pub amount: u64,
     /// `ConsensusMint_V1` zkas circuit ZkBinary
@@ -65,23 +67,39 @@ impl ConsensusGenesisStakeCallBuilder {
         // 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;
+
+        // With genesis, our epoch is 0.
         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
         // commitments.
+        let coin_blind = pallas::Base::random(&mut OsRng);
         let value_blind = pallas::Scalar::random(&mut OsRng);
         let token_blind = pallas::Scalar::random(&mut OsRng);
+        let reward_blind = pallas::Scalar::random(&mut OsRng);
+
+        // FIXME: The coin's serial number here is arbitrary, and allows grinding attacks.
         let serial = pallas::Base::random(&mut OsRng);
-        let coin_blind = pallas::Base::random(&mut OsRng);
 
-        let c_input =
-            ClearInput { value, token_id, value_blind, token_blind, signature_public: public_key };
+        // Parameters for the clear input
+        let c_input = ClearInput {
+            value,
+            token_id,
+            value_blind,
+            token_blind,
+            signature_public: self.keypair.public,
+        };
 
-        let output =
-            ConsensusMintOutputInfo { value, epoch, public_key, value_blind, serial, coin_blind };
+        // Parameters for the anonymous output
+        let output = ConsensusMintOutputInfo {
+            value,
+            epoch,
+            public_key: self.recipient,
+            value_blind,
+            serial,
+            coin_blind,
+        };
 
         info!("Creating genesis stake mint proof for output");
         let (proof, public_inputs) =
@@ -95,10 +113,10 @@ impl ConsensusGenesisStakeCallBuilder {
             coin_blind,
             value_blind,
             reward: 0,
-            reward_blind: value_blind,
+            reward_blind,
         };
 
-        let encrypted_note = AeadEncryptedNote::encrypt(&note, &output.public_key, &mut OsRng)?;
+        let encrypted_note = AeadEncryptedNote::encrypt(&note, &self.recipient, &mut OsRng)?;
 
         let output = ConsensusOutput {
             value_commit: public_inputs.value_commit,

+ 7 - 8
src/contract/consensus/src/model.rs

@@ -77,22 +77,21 @@ pub struct ConsensusUnstakeRequestParamsV1 {
     pub output: Output,
 }
 
-// ==================================
+// ======================================================================
 // Consensus parameters configuration
-// Note: Always verify `pallas::Base` are correct, in case of changes,
-// using pallas_constants tool.
-// ==================================
-
+// NOTE: In case of changes, always verify that the `pallas::Base` consts
+// are correct using the `pallas_constants` tool in `script/research/`.
+// ======================================================================
 /// Number of slots in one epoch
 pub const EPOCH_LENGTH: u64 = 10;
 /// Slot time in seconds
 pub const SLOT_TIME: u64 = 90;
 /// Grace period days target
 pub const GRACE_PERIOD_DAYS: u64 = 2;
-/// Configured block reward
-pub const REWARD: u64 = 1;
+/// Configured block reward (1 DRK == 1 * 10^8)
+pub const REWARD: u64 = 100_000_000;
 /// Reward `pallas::Base`, calculated by: pallas::Base::from(REWARD)
-pub const REWARD_PALLAS: pallas::Base = pallas::Base::from_raw([1, 0, 0, 0]);
+pub const REWARD_PALLAS: pallas::Base = pallas::Base::from_raw([100000000, 0, 0, 0]);
 /// Serial prefix, calculated by: pallas::Base::from(2)
 pub const SERIAL_PREFIX: pallas::Base = pallas::Base::from_raw([2, 0, 0, 0]);
 /// Seed prefix, calculated by: pallas::Base::from(3)

+ 19 - 10
src/contract/consensus/tests/harness.rs

@@ -153,7 +153,7 @@ impl TxActionBenchmarks {
 pub struct Wallet {
     pub keypair: Keypair,
     pub state: ValidatorStatePtr,
-    pub merkle_tree: MerkleTree,
+    pub money_merkle_tree: MerkleTree,
     pub consensus_merkle_tree: MerkleTree,
     pub wallet: WalletPtr,
     pub coins: Vec<OwnCoin>,
@@ -178,13 +178,21 @@ impl Wallet {
         )
         .await?;
 
-        let merkle_tree = MerkleTree::new(100);
+        let money_merkle_tree = MerkleTree::new(100);
         let consensus_merkle_tree = MerkleTree::new(100);
 
         let coins = vec![];
         let spent_coins = vec![];
 
-        Ok(Self { keypair, state, merkle_tree, consensus_merkle_tree, wallet, coins, spent_coins })
+        Ok(Self {
+            keypair,
+            state,
+            money_merkle_tree,
+            consensus_merkle_tree,
+            wallet,
+            coins,
+            spent_coins,
+        })
     }
 }
 
@@ -276,7 +284,7 @@ impl ConsensusTestHarness {
             change_user_data: pallas::Base::zero(),
             change_user_data_blind: pallas::Base::random(&mut OsRng),
             coins: vec![],
-            tree: faucet.merkle_tree.clone(),
+            tree: faucet.money_merkle_tree.clone(),
             mint_zkbin: mint_zkbin.clone(),
             mint_pk: mint_pk.clone(),
             burn_zkbin: burn_zkbin.clone(),
@@ -320,7 +328,7 @@ impl ConsensusTestHarness {
         let erroneous_txs =
             wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
         assert!(erroneous_txs.is_empty());
-        wallet.merkle_tree.append(&MerkleNode::from(params.outputs[0].coin.inner()));
+        wallet.money_merkle_tree.append(&MerkleNode::from(params.outputs[0].coin.inner()));
         tx_action_benchmark.verify_times.push(timer.elapsed());
 
         Ok(())
@@ -341,6 +349,7 @@ impl ConsensusTestHarness {
         // Building Consensus::GenesisStake params
         let genesis_stake_call_debris = ConsensusGenesisStakeCallBuilder {
             keypair: wallet.keypair,
+            recipient: wallet.keypair.public,
             amount,
             mint_zkbin: mint_zkbin.clone(),
             mint_pk: mint_pk.clone(),
@@ -429,7 +438,7 @@ impl ConsensusTestHarness {
         // Building Money::Stake params
         let money_stake_call_debris = MoneyStakeCallBuilder {
             coin: owncoin.clone(),
-            tree: wallet.merkle_tree.clone(),
+            tree: wallet.money_merkle_tree.clone(),
             burn_zkbin: burn_zkbin.clone(),
             burn_pk: burn_pk.clone(),
         }
@@ -787,7 +796,7 @@ impl ConsensusTestHarness {
         let erroneous_txs =
             wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
         assert!(erroneous_txs.is_empty());
-        wallet.merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
+        wallet.money_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
         tx_action_benchmark.verify_times.push(timer.elapsed());
 
         Ok(())
@@ -800,7 +809,7 @@ impl ConsensusTestHarness {
         secret_key: Option<SecretKey>,
     ) -> Result<OwnCoin> {
         let wallet = self.holders.get_mut(&holder).unwrap();
-        let leaf_position = wallet.merkle_tree.witness().unwrap();
+        let leaf_position = wallet.money_merkle_tree.witness().unwrap();
         let secret_key = match secret_key {
             Some(key) => key,
             None => wallet.keypair.secret,
@@ -875,11 +884,11 @@ impl ConsensusTestHarness {
 
     pub fn assert_trees(&self) {
         let faucet = self.holders.get(&Holder::Faucet).unwrap();
-        let money_root = faucet.merkle_tree.root(0).unwrap();
+        let money_root = faucet.money_merkle_tree.root(0).unwrap();
         let consensus_root = faucet.consensus_merkle_tree.root(0).unwrap();
         let consensus_unstake_root = faucet.consensus_merkle_tree.root(0).unwrap();
         for wallet in self.holders.values() {
-            assert!(money_root == wallet.merkle_tree.root(0).unwrap());
+            assert!(money_root == wallet.money_merkle_tree.root(0).unwrap());
             assert!(consensus_root == wallet.consensus_merkle_tree.root(0).unwrap());
             assert!(consensus_unstake_root == wallet.consensus_merkle_tree.root(0).unwrap());
         }