Просмотр исходного кода

[stakeholder/stakeholder] burn/mint lead coin

mohab metwally 3 лет назад
Родитель
Сommit
85096c5caa
7 измененных файлов с 74 добавлено и 22 удалено
  1. 20 0
      Cargo.lock
  2. 1 0
      Cargo.toml
  3. 1 0
      example/crypsinous.rs
  4. 7 4
      example/lead.rs
  5. 6 6
      src/blockchain/epoch.rs
  6. 2 2
      src/crypto/leadcoin.rs
  7. 37 10
      src/stakeholder/stakeholder.rs

+ 20 - 0
Cargo.lock

@@ -1199,6 +1199,7 @@ dependencies = [
  "dirs",
  "drk-sdk",
  "ed25519-compact",
+ "env_logger",
  "fast-socks5",
  "futures",
  "futures-rustls",
@@ -1715,6 +1716,19 @@ dependencies = [
  "syn",
 ]
 
+[[package]]
+name = "env_logger"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c90bf5f19754d10198ccb95b70664fc925bd1fc090a0fd9a6ebc54acc8cd6272"
+dependencies = [
+ "atty",
+ "humantime",
+ "log",
+ "regex",
+ "termcolor",
+]
+
 [[package]]
 name = "error-chain"
 version = "0.12.4"
@@ -2276,6 +2290,12 @@ version = "1.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
 
+[[package]]
+name = "humantime"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
+
 [[package]]
 name = "iana-time-zone"
 version = "0.1.50"

+ 1 - 0
Cargo.toml

@@ -48,6 +48,7 @@ members = [
 # Hard dependencies
 libc = "0.2.133"
 log = "0.4.17"
+env_logger = "0.9.0"
 thiserror = "1.0.35"
 
 # async-runtime

+ 1 - 0
example/crypsinous.rs

@@ -22,6 +22,7 @@ struct NetCli {
 
 #[async_std::main]
 async fn main() {
+    let _ = env_logger::init();
     let args = NetCli::parse();
     let addr = vec![Url::parse(args.addr.as_str()).unwrap()];
     let mut peers = vec![];

+ 7 - 4
example/lead.rs

@@ -2,6 +2,8 @@ use futures::executor::block_on;
 use halo2_proofs::dev::MockProver;
 use pasta_curves::pallas;
 use url::Url;
+use log::{debug, error, log_enabled, info, Level};
+use env_logger;
 
 use darkfi::{
     blockchain::{
@@ -14,6 +16,8 @@ use darkfi::{
 };
 
 fn main() {
+    debug!("..");
+    let _ = env_logger::init();
     let k: u32 = 13;
     //
 
@@ -45,12 +49,11 @@ fn main() {
         block_on(Stakeholder::new(consensus, settings, "db", 0, Some(k))).unwrap();
 
     let eta: pallas::Base = stakeholder.get_eta();
-    let mut epoch = Epoch { len: Some(LEN), value: Some(value), eta, coins: vec![] };
+    let mut epoch = Epoch::new(consensus,  eta);
     // sigma is nubmer of slots * reward (assuming reward is 1 for simplicity)
     let sigma = pallas::Base::from(10);
-    let coins: Vec<LeadCoin> = epoch.create_coins(sigma);
-    let coin_idx = 0;
-    let coin = coins[coin_idx];
+    let coins: Vec<Vec<LeadCoin>> = epoch.create_coins(sigma, vec!());
+    let coin = coins[0][0];
     let contract = coin.create_contract();
 
     let public_inputs: [pallas::Base; LEAD_PUBLIC_INPUT_LEN] = coin.public_inputs_as_array();

+ 6 - 6
src/blockchain/epoch.rs

@@ -191,14 +191,14 @@ impl Epoch {
             if owned.len()>0 {
                 let mut slot_coins = vec![];
                 for j in  0..owned.len() {
-                    let coin = self.create_leadcoin(sigma, owned[j].note.value, i, root_sks[i], path_sks[i], seeds[i]);
+                    let coin = self.create_leadcoin(sigma, pallas::Base::from(owned[j].note.value), i, root_sks[i], path_sks[i], seeds[i]);
                     slot_coins.push(coin.clone());
                 }
                 self.coins.push(slot_coins);
             }
             // otherwise compete with zero stake
             else {
-                let coin = self.create_leadcoin(sigma, 0, i, root_sks[i], path_sks[i], seeds[i]);
+                let coin = self.create_leadcoin(sigma, pallas::Base::zero(), i, root_sks[i], path_sks[i], seeds[i]);
                 self.coins.push(vec!(coin));
             }
         }
@@ -206,7 +206,7 @@ impl Epoch {
     }
 
     pub fn create_leadcoin(&self, sigma: pallas::Base,
-                           value : u64,
+                           value : pallas::Base,
                            i: usize,
                            c_root_sk: MerkleNode,
                            c_path_sk: [MerkleNode; MERKLE_DEPTH_ORCHARD],
@@ -216,7 +216,7 @@ impl Epoch {
         let c_cm1_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
         let c_cm2_blind: DrkValueBlind = pallas::Scalar::random(&mut rng);
         let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(self.len());
-        let c_v = pallas::Base::from(value);
+        let c_v = value;
         // coin relative slot index in the epoch
         let c_sl = pallas::Base::from(u64::try_from(i).unwrap());
         //
@@ -303,7 +303,7 @@ impl Epoch {
         assert!(slusize < self.coins.len());
         let competing_coins : &Vec<LeadCoin>= &self.coins.clone()[sl as usize];
         let mut am_leader = vec![];
-        let mut highest_stake = 0;
+        let mut highest_stake = pallas::Base::zero();
         let mut highest_stake_idx : usize= 0;
         for (idx, coin) in competing_coins.iter().enumerate() {
             let y_exp = [coin.root_sk.unwrap(), coin.nonce.unwrap()];
@@ -317,7 +317,7 @@ impl Epoch {
                 .unwrap()
                 .x();
             let ord = pallas::Base::from(10241024); //TODO fine tune this scalar.
-            let target = ord * pallas::Base::from(coin.value.unwrap());
+            let target = ord * coin.value.unwrap();
             debug!("y_x: {:?}, target: {:?}", y_x, target);
             //TODO (FIX) reversed for testin
             let iam_leader =  target < y_x;

+ 2 - 2
src/crypto/leadcoin.rs

@@ -21,7 +21,7 @@ pub const LEAD_PUBLIC_INPUT_LEN: usize = 10;
 
 #[derive(Debug, Default, Clone, Copy)]
 pub struct LeadCoin {
-    pub value: Option<u64>,                         // coin stake
+    pub value: Option<pallas::Base>,                         // coin stake
     pub cm: Option<pallas::Point>,                           // coin commitment
     pub cm2: Option<pallas::Point>,                          // poured coin commitment
     pub idx: u32,                                            // coin idex
@@ -118,7 +118,7 @@ impl LeadCoin {
             coin_timestamp: Value::known(self.tau.unwrap()), //
             coin_nonce: Value::known(self.nonce.unwrap()),
             coin1_blind: Value::known(self.c1_blind.unwrap()),
-            value: Value::known(pallas::Base::from(self.value.unwrap())),
+            value: Value::known(self.value.unwrap()),
             coin2_blind: Value::known(self.c2_blind.unwrap()),
             cm_pos: Value::known(self.idx),
             //sn_c1: Value::known(self.sn.unwrap()),

+ 37 - 10
src/stakeholder/stakeholder.rs

@@ -7,7 +7,7 @@ use halo2_proofs::arithmetic::Field;
 use rand::rngs::OsRng;
 use std::{thread, time::Duration};
 
-use crate::zk::circuit::LeadContract;
+use crate::zk::circuit::{LeadContract,BurnContract,MintContract};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 
 use crate::{
@@ -232,8 +232,10 @@ pub struct Stakeholder {
     pub ownedcoins: Vec<OwnCoin>,        // owned stakes
     pub epoch: Epoch,                    // current epoch
     pub epoch_consensus: EpochConsensus, // configuration for the epoch
+    pub lead_pk: ProvingKey,
     pub mint_pk: ProvingKey,
     pub burn_pk: ProvingKey,
+    pub lead_vk: VerifyingKey,
     pub mint_vk: VerifyingKey,
     pub burn_vk: VerifyingKey,
     pub playing: bool,
@@ -265,10 +267,12 @@ impl Stakeholder {
         let eta = pallas::Base::one();
         let epoch = Epoch::new(consensus, eta);
 
-        let mint_pk = ProvingKey::build(k.unwrap(), &LeadContract::default());
-        let burn_pk = ProvingKey::build(k.unwrap(), &LeadContract::default());
-        let mint_vk = VerifyingKey::build(k.unwrap(), &LeadContract::default());
-        let burn_vk = VerifyingKey::build(k.unwrap(), &LeadContract::default());
+        let lead_pk = ProvingKey::build(k.unwrap(), &LeadContract::default());
+        let mint_pk = ProvingKey::build(k.unwrap(), &MintContract::default());
+        let burn_pk = ProvingKey::build(k.unwrap(), &BurnContract::default());
+        let lead_vk = VerifyingKey::build(k.unwrap(), &LeadContract::default());
+        let mint_vk = VerifyingKey::build(k.unwrap(), &MintContract::default());
+        let burn_vk = VerifyingKey::build(k.unwrap(), &BurnContract::default());
         let p2p = P2p::new(settings.clone()).await;
         let workspace = SlotWorkspace::default();
         let clock = Clock::new(
@@ -292,8 +296,10 @@ impl Stakeholder {
             ownedcoins: vec![], //TODO should be read from wallet db.
             epoch,
             epoch_consensus: consensus,
+            lead_pk: lead_pk,
             mint_pk: mint_pk,
             burn_pk: burn_pk,
+            lead_vk: lead_vk,
             mint_vk: mint_vk,
             burn_vk: burn_vk,
             playing: true,
@@ -317,14 +323,30 @@ impl Stakeholder {
         self.keypair.public.verify(message, signature)
     }
 
-    pub fn get_provkingkey(&self) -> ProvingKey {
+    pub fn get_leadprovkingkey(&self) -> ProvingKey {
+        self.lead_pk.clone()
+    }
+
+    pub fn get_mintprovkingkey(&self) -> ProvingKey {
         self.mint_pk.clone()
     }
 
-    pub fn get_verifyingkey(&self) -> VerifyingKey {
+    pub fn get_burnprovkingkey(&self) -> ProvingKey {
+        self.burn_pk.clone()
+    }
+
+    pub fn get_leadverifyingkey(&self) -> VerifyingKey {
+        self.lead_vk.clone()
+    }
+
+    pub fn get_mintverifyingkey(&self) -> VerifyingKey {
         self.mint_vk.clone()
     }
 
+    pub fn get_burnverifyingkey(&self) -> VerifyingKey {
+        self.burn_vk.clone()
+    }
+
     /// get list stakeholder peers on the p2p network for synchronization
     pub fn get_peers(&self) -> Vec<Url> {
         let settings: SettingsPtr = self.net.settings();
@@ -512,7 +534,7 @@ impl Stakeholder {
         let mut winning_coin_idx :  usize = 0;
         let won = self.epoch.is_leader(sl, &mut winning_coin_idx);
         let proof = if won {
-            self.epoch.get_proof(sl, winning_coin_idx,  &self.mint_pk.clone())
+            self.epoch.get_proof(sl, winning_coin_idx,  &self.get_leadprovkingkey())
         } else {
             Proof::new(vec![])
         };
@@ -537,6 +559,7 @@ impl Stakeholder {
 
     //TODO (res) validate the owncoin is the same winning leadcoin
     pub fn finalize_coin (&self, coin : &LeadCoin) -> OwnCoin {
+
         let mut state = StakeholderState {
             tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(TREE_LEN),
             merkle_roots: vec![],
@@ -548,21 +571,25 @@ impl Stakeholder {
             faucet_signature_public: self.faucet_signature_public.clone(),
             secrets: vec![self.keypair.secret],
         };
+
         let token_id = pallas::Base::random(&mut OsRng);
         let builder = TransactionBuilder {
             clear_inputs: vec![TransactionBuilderClearInputInfo {
-                value: coin.value.unwrap(),
+                //value: coin.value.unwrap(),
+                value: 10,
                 token_id,
                 signature_secret: self.cashier_signature_secret,
             }],
             inputs: vec![],
             outputs: vec![TransactionBuilderOutputInfo {
-                value: coin.value.unwrap(),
+                //value: coin.value.unwrap(),
+                value: 10,
                 token_id,
                 public: self.keypair.public,
             }],
         };
         let tx = builder.build(&self.mint_pk, &self.burn_pk).unwrap();
+
         tx.verify(&state.mint_vk, &state.burn_vk);
         let _note = tx.outputs[0].enc_note.decrypt(&self.keypair.secret).unwrap();
         let update = state_transition(&state, tx).unwrap();