Browse Source

remove crypsinous example

mohab metwally 3 years ago
parent
commit
c5a303931a

+ 0 - 182
example/crypsinous.rs

@@ -1,182 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-use std::sync::Arc;
-
-use clap::Parser;
-use easy_parallel::Parallel;
-use log::info;
-use smol::Executor;
-use url::Url;
-
-use darkfi::{
-    consensus::{
-        constants::{TESTNET_GENESIS_HASH_BYTES, TESTNET_GENESIS_TIMESTAMP},
-        ouroboros::{EpochConsensus, Stakeholder},
-        proto::{ProtocolSync, ProtocolTx},
-        ValidatorState,
-    },
-    net,
-    net::Settings,
-    util::{path::expand_path, time::Timestamp},
-    wallet::walletdb::init_wallet,
-    Result,
-};
-
-#[derive(Parser)]
-struct NetCli {
-    #[clap(long, value_parser)]
-    addr: Vec<String>,
-    #[clap(long, value_parser, default_value = "/tmp/db")]
-    path: String,
-    #[clap(long, value_parser)]
-    peers: Vec<String>,
-    #[clap(long, value_parser)]
-    seeds: Vec<String>,
-    #[clap(long, value_parser, default_value = "0")]
-    slots: u32,
-    #[clap(long, value_parser)]
-    wallet_path: String,
-    #[clap(long, value_parser)]
-    wallet_pass: String,
-}
-
-#[async_std::main]
-async fn main() -> Result<()> {
-    env_logger::init();
-    let args = NetCli::parse();
-
-    let (signal, shutdown) = smol::channel::unbounded::<()>();
-
-    let ex = Arc::new(Executor::new());
-    let ex2 = ex.clone();
-    let ex3 = ex2.clone();
-
-    let (_, result) = Parallel::new()
-        .each(0..4, |_| smol::future::block_on(ex2.run(shutdown.recv())))
-        .finish(|| {
-            smol::future::block_on(async move {
-                start(args, ex3).await?;
-                drop(signal);
-                Ok(())
-            })
-        });
-
-    result
-}
-
-async fn start(args: NetCli, ex: Arc<Executor<'_>>) -> Result<()> {
-    let mut addr = vec![];
-    for i in 0..args.addr.len() {
-        addr.push(Url::parse(args.addr[i].as_str()).unwrap());
-    }
-
-    let mut peers = vec![];
-    for i in 0..args.peers.len() {
-        peers.push(Url::parse(args.peers[i].as_str()).unwrap());
-    }
-
-    let mut seeds = vec![];
-    for i in 0..args.seeds.len() {
-        seeds.push(Url::parse(args.seeds[i].as_str()).unwrap());
-    }
-
-    // initialize n stakeholders
-    let settings = Settings {
-        inbound: addr.clone(),
-        outbound_connections: args.slots,
-        manual_attempt_limit: 0,
-        seed_query_timeout_seconds: 8,
-        connect_timeout_seconds: 10,
-        channel_handshake_seconds: 4,
-        channel_heartbeat_seconds: 10,
-        external_addr: addr,
-        peers,
-        seeds,
-        ..Default::default()
-    };
-
-    let p2p = net::P2p::new(settings.clone()).await;
-
-    //////////////////////////////
-
-    // Initialize or load wallet
-    let wallet = init_wallet(&args.wallet_path, &args.wallet_pass).await?;
-
-    // Initialize or open sled database
-    let db_path = format!("{}/{}", expand_path(&args.path)?.to_str().unwrap(), "testnet");
-    let sled_db = sled::open(&db_path)?;
-
-    // Initialize validator state
-    let (genesis_ts, genesis_data) = (*TESTNET_GENESIS_TIMESTAMP, *TESTNET_GENESIS_HASH_BYTES);
-
-    // Parse faucet addresses (not needed here probably)
-    let faucet_pubkeys = vec![];
-
-    // Initialize validator state
-    let state =
-        ValidatorState::new(&sled_db, genesis_ts, genesis_data, wallet.clone(), faucet_pubkeys)
-            .await?;
-
-    let registry = p2p.protocol_registry();
-
-    info!("Registering block sync P2P protocols...");
-    let _state = state.clone();
-    registry
-        .register(net::SESSION_ALL, move |channel, p2p| {
-            let state = _state.clone();
-            async move { ProtocolSync::init(channel, state, p2p, false).await.unwrap() }
-        })
-        .await;
-
-    let _state = state.clone();
-    registry
-        .register(net::SESSION_ALL, move |channel, p2p| {
-            let state = _state.clone();
-            async move { ProtocolTx::init(channel, state, p2p).await.unwrap() }
-        })
-        .await;
-
-    //////////////////////////////
-
-    let ex2 = ex.clone();
-
-    p2p.clone().start(ex.clone()).await?;
-    ex2.spawn(p2p.clone().run(ex.clone())).detach();
-
-    let slots = 3;
-    let epochs = 3;
-    let ticks = 3;
-    let reward = 1;
-    let epoch_consensus = EpochConsensus::new(Some(slots), Some(epochs), Some(ticks), Some(reward));
-
-    //proof's number of rows
-    let k: u32 = 11;
-    let path = args.path.clone();
-    let id = Timestamp::current_time().0;
-
-    let mut stakeholder =
-        Stakeholder::new(epoch_consensus, p2p.clone(), settings.to_owned(), &path, id, Some(k))
-            .await?;
-
-    stakeholder.background(Some(100)).await;
-
-    p2p.stop().await;
-
-    Ok(())
-}

+ 0 - 1
src/consensus/leadcoin.rs

@@ -312,7 +312,6 @@ impl LeadCoin {
         coin_commitment_tree: &mut BridgeTree<MerkleNode, MERKLE_DEPTH>,
     ) -> LeadCoin {
         info!("LeadCoin::derive_coin()");
-        let mut derived = self.clone();
         let rho = self.derived_rho();
         let blind = pallas::Scalar::random(&mut OsRng);
         let cm = self.derived_commitment(blind);

+ 0 - 20
src/consensus/ouroboros/consts.rs

@@ -1,20 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-pub(crate) const LOG_T: &str = "stakeholder";
-pub(crate) const TREE_LEN: usize = 100;

+ 0 - 90
src/consensus/ouroboros/epoch.rs

@@ -1,90 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-use crate::{
-    consensus::{coins, ouroboros::EpochConsensus},
-    crypto::{
-        coin::OwnCoin,
-        lead_proof,
-        leadcoin::LeadCoin,
-        proof::{Proof, ProvingKey},
-    },
-};
-use log::info;
-use pasta_curves::pallas;
-
-#[derive(Debug, Default, Clone)]
-pub struct Epoch {
-    pub consensus: EpochConsensus,
-    // should have ep, slot, current block, etc.
-    pub eta: pallas::Base,     // CRS for the leader selection.
-    coins: Vec<Vec<LeadCoin>>, // competing coins
-}
-
-impl Epoch {
-    pub fn new(consensus: EpochConsensus, true_random: pallas::Base) -> Self {
-        Self { consensus, eta: true_random, coins: vec![] }
-    }
-
-    /// retrive leadership lottary coins of static stake,
-    /// retrived for for commitment in the genesis data
-    pub fn get_coins(&self) -> Vec<Vec<LeadCoin>> {
-        self.coins.clone()
-    }
-
-    pub fn get_coin(&self, sl: usize, idx: usize) -> LeadCoin {
-        self.coins[sl][idx]
-    }
-
-    pub fn len(&self) -> usize {
-        self.consensus.get_epoch_len() as usize
-    }
-
-    pub fn is_empty(&self) -> bool {
-        self.len() == 0
-    }
-
-    pub fn col(&self) -> usize {
-        if self.coins.is_empty() {
-            0
-        } else {
-            self.coins[0].len()
-        }
-    }
-
-    /// Wrapper for coins::create_epoch_coins
-    pub fn create_coins(&mut self, e: u64, sl: u64, owned: &Vec<OwnCoin>) {
-        self.coins = coins::create_epoch_coins(self.eta, owned, e, sl);
-    }
-
-    /// Wrapper for coins::is_leader
-    pub fn is_leader(&self, sl: u64) -> (bool, usize) {
-        coins::is_leader(sl, &self.coins)
-    }
-
-    /// * `sl` - relative slot index (zero based)
-    /// * `idx` - idex of the highest winning coin
-    /// * `pk` - proving key
-    /// returns  the of proof of the winning coin of slot `sl` at index `idx` with
-    /// proving key `pk`
-    pub fn get_proof(&self, sl: usize, idx: usize, pk: &ProvingKey) -> Proof {
-        info!("get_proof");
-        let coin = self.get_coin(sl, idx);
-        lead_proof::create_lead_proof(pk, coin).unwrap()
-    }
-}

+ 0 - 69
src/consensus/ouroboros/epochconsensus.rs

@@ -1,69 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-/// epoch configuration
-/// this struct need be a singleton,
-/// TODO should be populated from configuration file.
-#[derive(Copy, Debug, Default, Clone)]
-pub struct EpochConsensus {
-    pub sl_len: u64, // length of slot in terms of ticks
-    // number of slots per epoch
-    pub e_len: u64,    // length of epoch in terms of slots
-    pub tick_len: u64, // length of tick in terms of seconds
-    pub reward: u64,   // constant reward value for the slot leader
-}
-
-impl EpochConsensus {
-    pub fn new(
-        sl_len: Option<u64>,
-        e_len: Option<u64>,
-        tick_len: Option<u64>,
-        reward: Option<u64>,
-    ) -> Self {
-        Self {
-            sl_len: sl_len.unwrap_or(22),
-            e_len: e_len.unwrap_or(3),
-            tick_len: tick_len.unwrap_or(22),
-            reward: reward.unwrap_or(1),
-        }
-    }
-
-    pub fn total_stake(&self, e: u64, sl: u64) -> u64 {
-        (e * self.e_len + sl + 1) * self.reward
-    }
-    /// getter for constant stakeholder reward
-    /// used for configuring the stakeholder reward value
-    pub fn get_reward(&self) -> u64 {
-        self.reward
-    }
-
-    /// getter for the slot length in terms of ticks
-    pub fn get_slot_len(&self) -> u64 {
-        self.sl_len
-    }
-
-    /// getter for the epoch length in terms of slots
-    pub fn get_epoch_len(&self) -> u64 {
-        self.e_len
-    }
-
-    /// getter for the ticks length in terms of seconds
-    pub fn get_tick_len(&self) -> u64 {
-        self.tick_len
-    }
-}

+ 0 - 29
src/consensus/ouroboros/mod.rs

@@ -1,29 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-pub mod consts;
-pub mod epochconsensus;
-pub use epochconsensus::EpochConsensus;
-pub mod epoch;
-pub use epoch::Epoch;
-pub(crate) mod workspace;
-pub(crate) use workspace::SlotWorkspace;
-pub(crate) mod state;
-pub(crate) use state::StakeholderState;
-pub mod stakeholder;
-pub use stakeholder::Stakeholder;

+ 0 - 442
src/consensus/ouroboros/stakeholder.rs

@@ -1,442 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-use std::{fmt, thread, time::Duration};
-
-use async_std::sync::Arc;
-use darkfi_sdk::{
-    crypto::{
-        constants::MERKLE_DEPTH, schnorr::SchnorrSecret, Address, MerkleNode, PublicKey, SecretKey,
-        TokenId,
-    },
-    incrementalmerkletree::bridgetree::BridgeTree,
-    pasta::{group::ff::PrimeField, pallas},
-};
-use halo2_proofs::arithmetic::Field;
-use log::{error, info};
-use rand::rngs::OsRng;
-use url::Url;
-
-use crate::{
-    blockchain::Blockchain,
-    consensus::{
-        clock::{Clock, Ticks},
-        ouroboros::{
-            consts::{LOG_T, TREE_LEN},
-            Epoch, EpochConsensus, SlotWorkspace, StakeholderState,
-        },
-        BlockInfo, LeadProof, Metadata,
-    },
-    crypto::{
-        coin::OwnCoin,
-        lead_proof,
-        leadcoin::LeadCoin,
-        proof::{ProvingKey, VerifyingKey},
-    },
-    zk::{vm::ZkCircuit, vm_stack::{empty_witnesses}},
-    zkas::ZkBinary,
-    net::{P2p, P2pPtr, Settings, SettingsPtr},
-    node::state::state_transition,
-    tx::{
-        builder::{
-            TransactionBuilder, TransactionBuilderClearInputInfo, TransactionBuilderOutputInfo,
-        },
-        Transaction,
-    },
-    util::{path::expand_path, time::Timestamp},
-    Result,
-};
-
-pub struct Stakeholder {
-    pub blockchain: Blockchain, // stakeholder view of the blockchain
-    pub net: Arc<P2p>,
-    pub clock: Clock,
-    pub ownedcoins: Vec<OwnCoin>,        // owned stakes
-    pub epoch: Epoch,                    // current epoch
-    pub epoch_consensus: EpochConsensus, // configuration for the epoch
-    pub lead_pk: ProvingKey,
-    pub lead_vk: VerifyingKey,
-    pub playing: bool,
-    pub workspace: SlotWorkspace,
-    pub id: i64,
-    pub cashier_signature_public: PublicKey,
-    pub faucet_signature_public: PublicKey,
-    pub cashier_signature_secret: SecretKey,
-    pub faucet_signature_secret: SecretKey,
-}
-
-impl Stakeholder {
-    pub async fn new(
-        consensus: EpochConsensus,
-        net: P2pPtr,
-        settings: Settings,
-        rel_path: &str,
-        id: i64,
-        k: Option<u32>,
-    ) -> Result<Self> {
-        let path = expand_path(rel_path).unwrap();
-        let db = sled::open(&path)?;
-        let ts = Timestamp::current_time();
-        let genesis_hash = blake3::hash(b"");
-        let bc = Blockchain::new(&db, ts, genesis_hash).unwrap();
-        let eta = pallas::Base::one();
-        let epoch = Epoch::new(consensus, eta);
-        let bincode = include_bytes!("../../../proof/lead.zk.bin");
-        let zkbin = ZkBinary::decode(bincode)?;
-        let void_witnesses = empty_witnesses(&zkbin);
-        let circuit = ZkCircuit::new(void_witnesses, zkbin);
-        let lead_pk = ProvingKey::build(LEADER_PROOF_K, &circuit);
-        let lead_vk = VerifyingKey::build(LEADER_PROOF_K, &circuit);
-        // let p2p = P2p::new(settings.clone()).await;
-        let workspace = SlotWorkspace::default();
-        let clock = Clock::new(
-            Some(consensus.get_epoch_len()),
-            Some(consensus.get_slot_len()),
-            Some(consensus.get_tick_len()),
-            settings.peers,
-        );
-        let cashier_signature_secret = SecretKey::random(&mut OsRng);
-        let cashier_signature_public = PublicKey::from_secret(cashier_signature_secret);
-
-        let faucet_signature_secret = SecretKey::random(&mut OsRng);
-        let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
-
-        info!(target: LOG_T, "stakeholder constructed");
-        Ok(Self {
-            blockchain: bc,
-            net,
-            clock,
-            ownedcoins: vec![], //TODO should be read from wallet db.
-            epoch,
-            epoch_consensus: consensus,
-            lead_pk,
-            lead_vk,
-            playing: true,
-            workspace,
-            id,
-            cashier_signature_public,
-            faucet_signature_public,
-            cashier_signature_secret,
-            faucet_signature_secret,
-        })
-    }
-
-    /*
-    /// wrapper on schnorr public verify
-    pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
-        info!(target: LOG_T, "verify()");
-        self.keypair.public.verify(message, signature)
-    }
-    */
-
-    pub fn get_leadprovkingkey(&self) -> ProvingKey {
-        info!(target: LOG_T, "get_leadprovkingkey()");
-        self.lead_pk.clone()
-    }
-
-    pub fn get_mintprovkingkey(&self) -> ProvingKey {
-        info!(target: LOG_T, "get_mintprovkingkey()");
-        self.mint_pk.clone()
-    }
-
-    pub fn get_burnprovkingkey(&self) -> ProvingKey {
-        info!(target: LOG_T, "get_burnprovkingkey()");
-        self.burn_pk.clone()
-    }
-
-    pub fn get_leadverifyingkey(&self) -> VerifyingKey {
-        info!(target: LOG_T, "get_leadverifyingkey()");
-        self.lead_vk.clone()
-    }
-
-    pub fn get_mintverifyingkey(&self) -> VerifyingKey {
-        info!(target: LOG_T, "get_mintverifyingkey()");
-        self.mint_vk.clone()
-    }
-
-    pub fn get_burnverifyingkey(&self) -> VerifyingKey {
-        info!(target: LOG_T, "get_burnverifyingkey()");
-        self.burn_vk.clone()
-    }
-
-    /// get list stakeholder peers on the p2p network for synchronization
-    pub fn get_peers(&self) -> Vec<Url> {
-        info!(target: LOG_T, "get_peers()");
-        let settings: SettingsPtr = self.net.settings();
-        settings.peers.clone()
-    }
-
-    // async fn init_network(&self) -> Result<()> {
-    //     info!(target: LOG_T, "init_network()");
-    //     let exec = Arc::new(Executor::new());
-    //     self.net.clone().start(exec.clone()).await?;
-    //     exec.spawn(self.net.clone().run(exec.clone())).detach();
-    //     info!(target: LOG_T, "net initialized");
-    //     Ok(())
-    // }
-
-    pub fn get_net(&self) -> Arc<P2p> {
-        info!(target: LOG_T, "get_net()");
-        self.net.clone()
-    }
-
-    /// add new blockinfo to the blockchain
-    pub fn add_block(&self, block: BlockInfo) {
-        info!(target: LOG_T, "add_block()");
-        let blocks = [block];
-        let _len = self.blockchain.add(&blocks);
-    }
-
-    pub fn add_tx(&mut self, tx: Transaction) {
-        info!(target: LOG_T, "add_tx()");
-        self.workspace.add_tx(tx);
-    }
-
-    /// extract leader selection lottery randomness \eta
-    /// it's the hash of the previous lead proof
-    /// converted to pallas base
-    pub fn get_eta(&self) -> pallas::Base {
-        info!(target: LOG_T, "get_eta()");
-
-        let proof_tx_hash = self.blockchain.get_last_proof_hash().unwrap();
-        let mut bytes: [u8; 32] = *proof_tx_hash.as_bytes();
-        // read first 254 bits
-        bytes[30] = 0;
-        bytes[31] = 0;
-        pallas::Base::from_repr(bytes).unwrap()
-    }
-
-    pub fn valid_block(&self, _blk: BlockInfo) -> bool {
-        info!(target: LOG_T, "valid_block()");
-
-        //TODO implement
-        true
-    }
-
-    /// listen to the network,
-    /// for new transactions.
-    pub fn sync_tx(&self) {
-        //TODO
-    }
-
-    /// listen to the network channels,
-    /// receive new messages, or blocks,
-    /// validate the block proof, and the transactions,
-    /// if so add the proof to metadata if stakeholder isn't the lead.
-    // pub async fn sync_block(&self) {
-    //     info!(target: LOG_T, "syncing blocks");
-    //     for chanptr in self.net.channels().lock().await.values() {
-    //         let message_subsytem = chanptr.get_message_subsystem();
-    //         message_subsytem.add_dispatch::<BlockInfo>().await;
-    //         //TODO start channel if isn't started yet
-    //         //let info = chanptr.get_info();
-    //         let msg_sub: MessageSubscription<BlockInfo> =
-    //             chanptr.subscribe_msg::<BlockInfo>().await.expect("missing blockinfo");
-
-    //         let res = msg_sub.receive().await.unwrap();
-    //         let blk: BlockInfo = (*res).to_owned();
-    //         //TODO validate the block proof, and transactions.
-    //         if self.valid_block(blk.clone()) {
-    //             let _len = self.blockchain.add(&[blk]);
-    //         } else {
-    //             error!(target: LOG_T, "received block is invalid!");
-    //         }
-    //     }
-    // }
-
-    pub async fn background(&mut self, hardlimit: Option<u8>) {
-        info!(target: LOG_T, "background");
-        // let _ = self.init_network().await;
-        let _ = self.clock.sync().await;
-        let mut c: u8 = 0;
-        let lim: u8 = hardlimit.unwrap_or(0);
-        let mut epoch_not_started = true;
-        while self.playing {
-            if c > lim && lim > 0 {
-                break
-            }
-            // clock ticks slot begins
-            // initialize the epoch if it's the time
-            // check for leadership
-            match self.clock.ticks().await {
-                Ticks::GENESIS { e, sl } => {
-                    self.new_epoch(e, sl);
-                    self.new_slot(e, sl);
-                    epoch_not_started = false;
-                }
-                Ticks::NEWEPOCH { e, sl } => {
-                    self.new_epoch(e, sl);
-                    //self.new_slot(e, sl);
-                    epoch_not_started = false;
-                }
-                Ticks::NEWSLOT { e, sl } => {
-                    if !epoch_not_started {
-                        self.new_slot(e, sl);
-                    }
-                }
-                Ticks::TOCKS => {
-                    info!(target: LOG_T, "tocks");
-                    // slot is about to end.
-                    // sync, and validate.
-                    // no more transactions to be received/send to the end of slot.
-                    if self.workspace.has_leader() {
-                        info!(target: LOG_T, "[leadership won]");
-                        //craete block
-                        let (block_info, _block_hash) = self.workspace.new_block();
-                        //add the block to the blockchain
-                        self.add_block(block_info.clone());
-                        // let block: Block = Block::from(block_info.clone());
-                        // publish the block
-                        //TODO (fix) before publishing the workspace tx root need to be set.
-                        self.net.broadcast(block_info.clone()).await.unwrap();
-                    }
-                }
-                Ticks::IDLE => continue,
-                Ticks::OUTOFSYNC => {
-                    error!(target: LOG_T, "clock/blockchain are out of sync");
-                    // clock, and blockchain are out of sync
-                    let _ = self.clock.sync().await;
-                    // self.sync_block().await;
-                }
-            }
-            thread::sleep(Duration::from_millis(1000));
-            c += 1;
-        }
-    }
-
-    /// on the onset of the epoch, layout the new the competing coins
-    /// assuming static stake during the epoch, enforced by the commitment to competing coins
-    /// in the epoch's gen2esis data.
-    fn new_epoch(&mut self, e: u64, sl: u64) {
-        info!(target: LOG_T, "[new epoch] {}", self);
-        let eta = self.get_eta();
-        let mut epoch = Epoch::new(self.epoch_consensus, eta);
-        epoch.create_coins(e, sl, &self.ownedcoins);
-        self.epoch = epoch.clone();
-    }
-
-    /// at the begining of the slot
-    /// stakeholder need to play the lottery for the slot.
-    /// FIXME if the stakeholder is not winning, staker can try different coins before,
-    /// commiting it's coins, to maximize success, thus,
-    /// the lottery proof need to be conditioned on the slot itself, and previous proof.
-    /// this will encourage each potential leader to play with honesty.
-    /// TODO this is fixed by commiting to the stakers at epoch genesis slot
-    /// * `e` - epoch index
-    /// * `sl` - slot relative index
-    fn new_slot(&mut self, e: u64, sl: u64) {
-        info!(target: LOG_T, "[new slot] {}, e:{}, rel sl:{}", self, e, sl);
-        let st: blake3::Hash = if e > 0 || (e == 0 && sl > 0) {
-            self.workspace.block.blockhash()
-        } else {
-            blake3::hash(b"")
-        };
-        // set workspace
-        self.workspace.set_sl(sl);
-        self.workspace.set_e(e);
-        self.workspace.set_st(st);
-
-        let (won, idx) = self.epoch.is_leader(sl);
-        info!("Lottery outcome: {}", won);
-        if !won {
-            return
-        }
-        // TODO: Generate rewards transaction
-        info!("Winning coin index: {}", idx);
-        // Generating leader proof
-        let coin = self.epoch.get_coin(sl as usize, idx);
-        // TODO: Generate new LeadCoin from newlly minted coin, will reuse original coin for now
-        //let coin2 = something();
-        let proof = self.epoch.get_proof(sl as usize, idx, &self.get_leadprovkingkey());
-        //Verifying generated proof against winning coin public inputs
-        info!("Leader proof generated successfully, veryfing...");
-        match lead_proof::verify_lead_proof(
-            &self.get_leadverifyingkey(),
-            &proof,
-            &coin.public_inputs(),
-        ) {
-            Ok(_) => info!("Proof veryfied succsessfully!"),
-            Err(e) => error!("Error during leader proof verification: {}", e),
-        }
-
-        self.workspace.add_leader(won);
-        self.workspace.set_idx(idx);
-        let keypair = coin.keypair.unwrap();
-        let addr = Address::from(keypair.public);
-        let sign = keypair.secret.sign(&mut OsRng, proof.as_ref());
-        let meta = Metadata::new(
-            sign,
-            addr,
-            coin.public_inputs(),
-            coin.public_inputs(),
-            idx,
-            coin.sn.unwrap(),
-            self.get_eta().to_repr(),
-            LeadProof::from(proof),
-            vec![],
-        );
-        self.workspace.add_metadata(meta);
-        let owned_coin = self.finalize_coin(&self.epoch.get_coin(sl as usize, idx as usize));
-        self.ownedcoins.push(owned_coin);
-    }
-
-    //TODO (res) validate the owncoin is the same winning leadcoin
-    pub fn finalize_coin(&self, coin: &LeadCoin) -> OwnCoin {
-        info!(target: LOG_T, "finalize coin");
-        let keypair = coin.keypair.unwrap();
-        let mut state = StakeholderState {
-            tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(TREE_LEN),
-            merkle_roots: vec![],
-            nullifiers: vec![],
-            own_coins: vec![],
-            mint_vk: self.mint_vk.clone(),
-            burn_vk: self.burn_vk.clone(),
-            cashier_signature_public: self.cashier_signature_public,
-            faucet_signature_public: self.faucet_signature_public,
-            secrets: vec![keypair.secret],
-        };
-
-        let token_id = TokenId::from(pallas::Base::random(&mut OsRng));
-        let builder = TransactionBuilder {
-            clear_inputs: vec![TransactionBuilderClearInputInfo {
-                value: coin.value.unwrap(),
-                token_id,
-                signature_secret: self.cashier_signature_secret,
-            }],
-            inputs: vec![],
-            outputs: vec![TransactionBuilderOutputInfo {
-                value: coin.value.unwrap(),
-                token_id,
-                public: keypair.public,
-            }],
-        };
-        let tx = builder.build(&self.mint_pk, &self.burn_pk).unwrap();
-
-        tx.verify(&state.mint_vk, &state.burn_vk).unwrap();
-        let _note = tx.outputs[0].enc_note.decrypt(&keypair.secret).unwrap();
-        let update = state_transition(&state, tx).unwrap();
-        state.apply(update);
-        state.own_coins[0].clone()
-    }
-}
-
-impl fmt::Display for Stakeholder {
-    fn fmt(&self, formater: &mut fmt::Formatter) -> fmt::Result {
-        formater.write_fmt(format_args!("stakeholder with id: {}", self.id))
-    }
-}

+ 0 - 131
src/consensus/ouroboros/state.rs

@@ -1,131 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-use darkfi_sdk::crypto::{
-    constants::MERKLE_DEPTH, poseidon_hash, MerkleNode, Nullifier, PublicKey, SecretKey,
-};
-use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
-
-use crate::{
-    crypto::{
-        coin::OwnCoin,
-        note::{EncryptedNote, Note},
-        proof::VerifyingKey,
-    },
-    node::state::{ProgramState, StateUpdate},
-};
-
-pub struct StakeholderState {
-    /// The entire Merkle tree state
-    pub tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
-    /// List of all previous and the current Merkle roots.
-    /// This is the hashed value of all the children.
-    pub merkle_roots: Vec<MerkleNode>,
-    /// Nullifiers prevent double spending
-    pub nullifiers: Vec<Nullifier>,
-    /// All received coins
-    // NOTE: We need maybe a flag to keep track of which ones are
-    // spent. Maybe the spend field links to a tx hash:input index.
-    // We should also keep track of the tx hash:output index where
-    // this coin was received.
-    pub own_coins: Vec<OwnCoin>,
-    /// Verifying key for the mint zk circuit.
-    pub mint_vk: VerifyingKey,
-    /// Verifying key for the burn zk circuit.
-    pub burn_vk: VerifyingKey,
-
-    /// Public key of the cashier
-    pub cashier_signature_public: PublicKey,
-
-    /// Public key of the faucet
-    pub faucet_signature_public: PublicKey,
-
-    /// List of all our secret keys
-    pub secrets: Vec<SecretKey>,
-}
-
-impl ProgramState for StakeholderState {
-    fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool {
-        public == &self.cashier_signature_public
-    }
-
-    fn is_valid_faucet_public_key(&self, public: &PublicKey) -> bool {
-        public == &self.faucet_signature_public
-    }
-
-    fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
-        self.merkle_roots.iter().any(|m| m == merkle_root)
-    }
-
-    fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
-        self.nullifiers.iter().any(|n| n == nullifier)
-    }
-
-    fn mint_vk(&self) -> &VerifyingKey {
-        &self.mint_vk
-    }
-
-    fn burn_vk(&self) -> &VerifyingKey {
-        &self.burn_vk
-    }
-}
-
-impl StakeholderState {
-    pub fn apply(&mut self, mut update: StateUpdate) {
-        // Extend our list of nullifiers with the ones from the update
-        self.nullifiers.append(&mut update.nullifiers);
-
-        // Update merkle tree and witnesses
-        for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.into_iter()) {
-            // Add the new coins to the Merkle tree
-            let node = MerkleNode::from(coin.0);
-            self.tree.append(&node);
-
-            // Keep track of all Merkle roots that have existed
-            self.merkle_roots.push(self.tree.root(0).unwrap());
-
-            // If it's our own coin, witness it and append to the vector.
-            if let Some((note, secret)) = self.try_decrypt_note(enc_note) {
-                let leaf_position = self.tree.witness().unwrap();
-                let nullifier = poseidon_hash::<2>([secret.inner(), note.serial]);
-                let own_coin = OwnCoin {
-                    coin,
-                    note,
-                    secret,
-                    nullifier: Nullifier::from(nullifier),
-                    leaf_position,
-                };
-                self.own_coins.push(own_coin);
-            }
-        }
-    }
-
-    fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, SecretKey)> {
-        // Loop through all our secret keys...
-        for secret in &self.secrets {
-            // .. attempt to decrypt the note ...
-            if let Ok(note) = ciphertext.decrypt(secret) {
-                // ... and return the decrypted note for this coin.
-                return Some((note, *secret))
-            }
-        }
-
-        // We weren't able to decrypt the note with any of our keys.
-        None
-    }
-}

+ 0 - 112
src/consensus/ouroboros/workspace.rs

@@ -1,112 +0,0 @@
-/* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2022 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/>.
- */
-
-use darkfi_sdk::crypto::MerkleNode;
-use pasta_curves::pallas;
-
-use crate::{
-    consensus::{BlockInfo, Header, Metadata},
-    tx::Transaction,
-    util::time::Timestamp,
-};
-
-#[derive(Debug)]
-pub struct SlotWorkspace {
-    pub st: blake3::Hash,      // hash of the previous block
-    pub e: u64,                // epoch index
-    pub sl: u64,               // relative slot index
-    pub txs: Vec<Transaction>, // unpublished block transactions
-    pub root: MerkleNode,
-    /// merkle root of txs
-    pub m: Vec<Metadata>,
-    pub is_leader: Vec<bool>,
-    pub block: BlockInfo,
-    pub idx: usize, // index of the highest winning coin
-}
-
-impl Default for SlotWorkspace {
-    fn default() -> Self {
-        Self {
-            st: blake3::hash(b""),
-            e: 0,
-            sl: 0,
-            txs: vec![],
-            root: MerkleNode::from(pallas::Base::zero()),
-            is_leader: vec![],
-            m: vec![],
-            block: BlockInfo::default(),
-            idx: 0,
-        }
-    }
-}
-
-impl SlotWorkspace {
-    /// create new block from the workspace
-    /// if there are multiple winning coins (owned by the same stakeholder)
-    /// then pick the highest winning coin.
-    /// returns tuple of blockinfo, hash of that block
-    pub fn new_block(&self) -> (BlockInfo, blake3::Hash) {
-        let header = Header::new(self.st, self.e, self.sl, Timestamp::current_time(), self.root);
-        let block = BlockInfo::new(header, self.txs.clone(), self.m[self.idx].clone());
-        let hash = block.blockhash();
-        (block, hash)
-    }
-
-    // each opoch research the worksapce
-    fn reset(&mut self) {
-        self.is_leader = vec![];
-        self.m = vec![];
-    }
-
-    pub fn add_tx(&mut self, tx: Transaction) {
-        self.txs.push(tx);
-    }
-
-    pub fn set_root(&mut self, root: MerkleNode) {
-        self.root = root;
-    }
-
-    pub fn add_metadata(&mut self, meta: Metadata) {
-        self.m.push(meta);
-    }
-
-    pub fn set_sl(&mut self, sl: u64) {
-        self.sl = sl;
-        self.reset();
-    }
-
-    pub fn set_st(&mut self, st: blake3::Hash) {
-        self.st = st;
-    }
-
-    pub fn set_e(&mut self, e: u64) {
-        self.e = e;
-    }
-
-    pub fn add_leader(&mut self, alead: bool) {
-        self.is_leader.push(alead);
-    }
-
-    pub fn has_leader(&self) -> bool {
-        self.is_leader.iter().any(|&x| x)
-    }
-
-    pub fn set_idx(&mut self, idx: usize) {
-        self.idx = idx;
-    }
-}

+ 14 - 11
src/consensus/state.rs

@@ -893,8 +893,9 @@ impl ValidatorState {
         info!("offset: {}", offset);
         //TODO: subtract eta slot index from empty slots since restarting the network.
         //let mut slot_eta = self.get_eta_by_slot(proposed_slot.clone()-offset-1);
-        let slot_eta = self.get_eta();
+
         /*
+        let slot_eta = self.get_eta();
         // Verify proposal public values
         let (mu_y, mu_rho) =
             LeadCoin::election_seeds_u64(slot_eta, proposed_slot);
@@ -915,7 +916,8 @@ impl ValidatorState {
                 mu_rho, prop_mu_rho
             );
             return Err(Error::ProposalPublicValuesMismatched)
-        }
+    }
+        */
 
         // sigma1
         let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
@@ -931,11 +933,11 @@ impl ValidatorState {
             error!(
                 "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
                 self.consensus.prev_sigma2, prop_sigma2
-    );
-    }
-        */
+            );
+        }
+
         // sn
-        //let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
+        let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
         /*
         for sn in &self.consensus.leaders_nullifiers {
             if *sn == prop_sn {
@@ -946,10 +948,10 @@ impl ValidatorState {
         */
         // cm
 
-        /*
+
         let prop_cm_x: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_X_INDEX];
         let prop_cm_y: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_Y_INDEX];
-
+        /*
         for cm in &self.consensus.leaders_spent_coins {
             if *cm == (prop_cm_x, prop_cm_y) {
                 error!("receive_proposal(): Proposal coin already spent.");
@@ -986,8 +988,8 @@ impl ValidatorState {
         };
 
         // Store proposal coin info
-        //self.consensus.leaders_nullifiers.push(prop_sn);
-        //self.consensus.leaders_spent_coins.push((prop_cm_x, prop_cm_y));
+        self.consensus.leaders_nullifiers.push(prop_sn);
+        self.consensus.leaders_spent_coins.push((prop_cm_x, prop_cm_y));
 
         Ok(())
     }
@@ -1221,6 +1223,7 @@ impl ValidatorState {
         pallas::Base::from_repr(bytes).unwrap()
     }
 
+    /*
     fn get_eta_by_slot(&self, slot: u64) -> pallas::Base {
         let mut proof_tx_hash = self.blockchain.get_proof_hash_by_slot(slot);
         proof_tx_hash = match proof_tx_hash {
@@ -1236,7 +1239,7 @@ impl ValidatorState {
         bytes[31] = 0;
         pallas::Base::from_repr(bytes).unwrap()
     }
-
+    */
     // ==========================
     // State transition functions
     // ==========================