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

consensus/state: Optionally create proving keys for leadership proofs.

We don't need it if we don't participate in consensus.
parazyd 3 лет назад
Родитель
Сommit
349c1d7096

+ 9 - 3
bin/darkfid/src/main.rs

@@ -317,9 +317,15 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
     }
 
     // Initialize validator state
-    let state =
-        ValidatorState::new(&sled_db, genesis_ts, genesis_data, wallet.clone(), faucet_pubkeys)
-            .await?;
+    let state = ValidatorState::new(
+        &sled_db,
+        genesis_ts,
+        genesis_data,
+        wallet.clone(),
+        faucet_pubkeys,
+        args.consensus,
+    )
+    .await?;
 
     let sync_p2p = {
         info!("Registering block sync P2P protocols...");

+ 9 - 3
bin/faucetd/src/main.rs

@@ -591,9 +591,15 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
     }
 
     // Initialize validator state
-    let state =
-        ValidatorState::new(&sled_db, genesis_ts, genesis_data, wallet.clone(), faucet_pubkeys)
-            .await?;
+    let state = ValidatorState::new(
+        &sled_db,
+        genesis_ts,
+        genesis_data,
+        wallet.clone(),
+        faucet_pubkeys,
+        false,
+    )
+    .await?;
 
     // P2P network. The faucet doesn't participate in consensus, so we only
     // build the sync protocol.

+ 3 - 5
src/consensus/leadcoin.rs

@@ -27,19 +27,17 @@ use darkfi_sdk::{
 };
 use halo2_proofs::{arithmetic::Field, circuit::Value};
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
-use log::debug;
+use log::{debug, info};
 use rand::rngs::OsRng;
 
 use super::constants::EPOCH_LENGTH;
 use crate::{
-    consensus::{EncryptedTxRcpt, TransferStx, TxRcpt},
+    consensus::{TransferStx, TxRcpt},
     crypto::{proof::ProvingKey, Proof},
     zk::{vm::ZkCircuit, vm_stack::Witness},
     zkas::ZkBinary,
-    Error, Result,
+    Result,
 };
-use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
-use log::info;
 
 pub const MERKLE_DEPTH_LEADCOIN: usize = 32;
 pub const MERKLE_DEPTH: u8 = 32;

+ 0 - 1
src/consensus/metadata.rs

@@ -23,7 +23,6 @@ use darkfi_sdk::{
 use darkfi_serial::{SerialDecodable, SerialEncodable};
 use log::error;
 
-use super::leadcoin::LeadCoin;
 use crate::{
     crypto::proof::{Proof, ProvingKey, VerifyingKey},
     Result,

+ 5 - 17
src/consensus/rcpt.rs

@@ -16,31 +16,19 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
+use crypto_api_chachapoly::ChachaPolyIetf;
 use darkfi_sdk::{
     crypto::{
         diffie_hellman::{kdf_sapling, sapling_ka_agree},
         keypair::PublicKey,
-        pedersen::{pedersen_commitment_base, pedersen_commitment_u64},
-        poseidon_hash,
-        util::mod_r_p,
-        MerkleNode, SecretKey,
+        SecretKey,
     },
-    pasta::{arithmetic::CurveAffine, group::Curve, pallas},
+    pasta::pallas,
 };
-use halo2_proofs::{arithmetic::Field, circuit::Value};
-use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
-use log::debug;
+use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
 use rand::rngs::OsRng;
 
-use super::constants::EPOCH_LENGTH;
-use crate::{
-    crypto::{proof::ProvingKey, Proof},
-    zk::{vm::ZkCircuit, vm_stack::Witness},
-    zkas::ZkBinary,
-    Error, Result,
-};
-use crypto_api_chachapoly::ChachaPolyIetf;
-use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
+use crate::Error;
 
 /// transfered leadcoin is rcpt into two coins,
 /// first coin is transfered rcpt coin.

+ 16 - 9
src/consensus/state.rs

@@ -22,10 +22,7 @@ use async_std::sync::{Arc, RwLock};
 use chrono::{NaiveDateTime, Utc};
 use darkfi_sdk::crypto::{
     constants::MERKLE_DEPTH,
-    pedersen::pedersen_commitment_base,
-    poseidon_hash,
     schnorr::{SchnorrPublic, SchnorrSecret},
-    util::mod_r_p,
     ContractId, MerkleNode, PublicKey,
 };
 use darkfi_serial::{serialize, Decodable, Encodable, SerialDecodable, SerialEncodable, WriteExt};
@@ -124,7 +121,7 @@ pub type ValidatorStatePtr = Arc<RwLock<ValidatorState>>;
 /// This struct represents the state of a validator node.
 pub struct ValidatorState {
     /// Leader proof proving key
-    pub lead_proving_key: ProvingKey,
+    pub lead_proving_key: Option<ProvingKey>,
     /// Leader proof verifying key
     pub lead_verifying_key: VerifyingKey,
     /// Hot/Live data used by the consensus algorithm
@@ -160,6 +157,7 @@ impl ValidatorState {
         genesis_data: blake3::Hash,
         wallet: WalletPtr,
         faucet_pubkeys: Vec<PublicKey>,
+        enable_participation: bool,
     ) -> Result<ValidatorStatePtr> {
         info!("Initializing ValidatorState");
 
@@ -174,13 +172,20 @@ impl ValidatorState {
         info!("Generating leader proof keys with k: {}", LEADER_PROOF_K);
         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_proving_key = ProvingKey::build(LEADER_PROOF_K, &circuit);
+        let witnesses = empty_witnesses(&zkbin);
+        let circuit = ZkCircuit::new(witnesses, zkbin);
+
         let lead_verifying_key = VerifyingKey::build(LEADER_PROOF_K, &circuit);
+        // We only need this proving key if we're going to participate in the consensus.
+        let lead_proving_key = if enable_participation {
+            Some(ProvingKey::build(LEADER_PROOF_K, &circuit))
+        } else {
+            None
+        };
 
         let consensus = ConsensusState::new(genesis_ts, genesis_data)?;
         let blockchain = Blockchain::new(db, genesis_ts, genesis_data)?;
+
         let unconfirmed_txs = vec![];
         let participating = None;
 
@@ -212,6 +217,7 @@ impl ValidatorState {
         runtime.deploy(&payload)?;
         info!("Deployed Money Contract with ID: {}", cid);
         // -----END ARTIFACT-----
+
         let zero = Float10::from_str_native("0").unwrap().with_precision(RADIX_BITS).value();
         let one = Float10::from_str_native("1").unwrap().with_precision(RADIX_BITS).value();
         let ten = Float10::from_str_native("10").unwrap().with_precision(RADIX_BITS).value();
@@ -576,7 +582,8 @@ impl ValidatorState {
         // Generating leader proof
         let relative_slot = self.relative_slot(slot) as usize;
         let coin = self.consensus.coins[relative_slot][idx];
-        let proof = coin.create_lead_proof(sigma1, sigma2, &self.lead_proving_key)?;
+        let proof =
+            coin.create_lead_proof(sigma1, sigma2, self.lead_proving_key.as_ref().unwrap())?;
 
         // Signing using coin
         let secret_key = coin.secret_key;
@@ -597,7 +604,7 @@ impl ValidatorState {
         // how is this going to get reused?
         self.consensus.coins[relative_slot][idx] = coin.derive_coin(eta, relative_slot as u64);
 
-        /// lead,spend,nullifiers
+        // lead,spend,nullifiers
         self.nullifiers.push(coin.sn());
         let cm = coin.coin1_commitment.to_affine().coordinates().unwrap();
         self.spent.push((*cm.x(), *cm.y()));

+ 1 - 1
src/consensus/stx.rs

@@ -25,7 +25,7 @@ use crate::{
     crypto::{proof::VerifyingKey, Proof},
     Error, Result,
 };
-use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
+use darkfi_serial::{SerialDecodable, SerialEncodable};
 
 #[derive(Debug, Clone, SerialDecodable, SerialEncodable)]
 pub struct TransferStx {

+ 1 - 6
src/consensus/task/proposal.rs

@@ -21,12 +21,7 @@ use std::time::Duration;
 use log::{debug, error, info};
 
 use super::consensus_sync_task;
-use crate::{
-    consensus::{ValidatorState, ValidatorStatePtr},
-    net::P2pPtr,
-    util::async_util::sleep,
-};
-use std::sync::LockResult;
+use crate::{consensus::ValidatorStatePtr, net::P2pPtr, util::async_util::sleep};
 
 /// async task used for participating in the consensus protocol
 pub async fn proposal_task(consensus_p2p: P2pPtr, sync_p2p: P2pPtr, state: ValidatorStatePtr) {

+ 2 - 1
src/consensus/tx.rs

@@ -1,5 +1,6 @@
+use darkfi_serial::{SerialDecodable, SerialEncodable};
+
 use crate::consensus::{EncryptedTxRcpt, TransferStx};
-use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
 
 /// transfer transaction
 #[derive(Debug, Clone, SerialDecodable, SerialEncodable)]