Kaynağa Gözat

darkfid: replaced finalization term with confirmation

skoupidi 1 yıl önce
ebeveyn
işleme
9f490a09d3
37 değiştirilmiş dosya ile 235 ekleme ve 221 silme
  1. 3 3
      bin/darkfid/darkfid_config.toml
  2. 2 2
      bin/darkfid/src/main.rs
  3. 7 7
      bin/darkfid/src/proto/protocol_sync.rs
  4. 1 1
      bin/darkfid/src/rpc.rs
  5. 5 5
      bin/darkfid/src/rpc_blockchain.rs
  6. 6 6
      bin/darkfid/src/task/consensus.rs
  7. 16 16
      bin/darkfid/src/task/miner.rs
  8. 10 10
      bin/darkfid/src/task/sync.rs
  9. 6 6
      bin/darkfid/src/task/unknown_proposal.rs
  10. 5 5
      bin/darkfid/src/tests/harness.rs
  11. 7 7
      bin/darkfid/src/tests/mod.rs
  12. 1 1
      bin/darkfid/src/tests/sync_forks.rs
  13. 1 1
      bin/darkfid/src/tests/unproposed_txs.rs
  14. 16 16
      bin/drk/src/rpc.rs
  15. 1 1
      contrib/localnet/darkfid-five-nodes/darkfid0.toml
  16. 1 1
      contrib/localnet/darkfid-five-nodes/darkfid1.toml
  17. 1 1
      contrib/localnet/darkfid-five-nodes/darkfid2.toml
  18. 1 1
      contrib/localnet/darkfid-five-nodes/darkfid3.toml
  19. 1 1
      contrib/localnet/darkfid-five-nodes/darkfid4.toml
  20. 1 1
      contrib/localnet/darkfid-single-node/darkfid.toml
  21. 1 1
      contrib/localnet/darkfid-small/darkfid0.toml
  22. 1 1
      contrib/localnet/darkfid-small/darkfid1.toml
  23. 1 1
      contrib/localnet/darkfid-small/darkfid2.toml
  24. 1 1
      doc/src/arch/arch.md
  25. 30 16
      doc/src/arch/consensus.md
  26. 4 4
      doc/src/arch/overview.md
  27. 15 15
      doc/src/arch/tx_lifetime.md
  28. 1 1
      doc/src/spec/contract/dao/concepts.md
  29. 1 1
      doc/src/spec/contract/dao/dao.md
  30. 2 2
      doc/src/testnet/atomic-swap.md
  31. 6 6
      doc/src/testnet/dao.md
  32. 1 1
      doc/src/testnet/payment.md
  33. 3 3
      doc/src/testnet/token.md
  34. 12 12
      script/research/blockchain-explorer/src/rpc_blocks.rs
  35. 1 1
      src/contract/test-harness/src/lib.rs
  36. 29 29
      src/validator/consensus.rs
  37. 34 34
      src/validator/mod.rs

+ 3 - 3
bin/darkfid/darkfid_config.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:8240"
 # Path to the blockchain database directory
 database = "~/.local/darkfi/darkfid/localnet"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 3
 
 # minerd JSON-RPC endpoint
@@ -123,7 +123,7 @@ rpc_listen = "tcp://127.0.0.1:8340"
 # Path to the blockchain database directory
 database = "~/.local/darkfi/darkfid/testnet"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint
@@ -228,7 +228,7 @@ rpc_listen = "tcp://127.0.0.1:8440"
 # Path to the blockchain database directory
 database = "~/.local/darkfi/darkfid/mainnet"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 11
 
 # minerd JSON-RPC endpoint

+ 2 - 2
bin/darkfid/src/main.rs

@@ -87,7 +87,7 @@ pub struct BlockchainNetwork {
     database: String,
 
     #[structopt(long, default_value = "3")]
-    /// Finalization threshold, denominated by number of blocks
+    /// Confirmation threshold, denominated by number of blocks
     threshold: usize,
 
     #[structopt(long)]
@@ -187,7 +187,7 @@ async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
     };
 
     let config = ValidatorConfig {
-        finalization_threshold: blockchain_config.threshold,
+        confirmation_threshold: blockchain_config.threshold,
         pow_target: blockchain_config.pow_target,
         pow_fixed_difficulty,
         genesis_block,

+ 7 - 7
bin/darkfid/src/proto/protocol_sync.rs

@@ -41,11 +41,11 @@ use darkfi_serial::{SerialDecodable, SerialEncodable};
 pub const BATCH: usize = 20;
 
 /// Structure represening a request to ask a node for their current
-/// canonical(finalized) tip block hash, if they are synced. We also
+/// canonical(confirmed) tip block hash, if they are synced. We also
 /// include our own tip, so they can verify we follow the same sequence.
 #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
 pub struct TipRequest {
-    /// Canonical(finalized) tip block hash
+    /// Canonical(confirmed) tip block hash
     pub tip: HeaderHash,
 }
 
@@ -53,14 +53,14 @@ impl_p2p_message!(TipRequest, "tiprequest");
 
 /// Structure representing the response to `TipRequest`,
 /// containing a boolean flag to indicate if we are synced,
-/// and our canonical(finalized) tip block height and hash.
+/// and our canonical(confirmed) tip block height and hash.
 #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
 pub struct TipResponse {
     /// Flag indicating the node is synced
     pub synced: bool,
-    /// Canonical(finalized) tip block height
+    /// Canonical(confirmed) tip block height
     pub height: Option<u32>,
-    /// Canonical(finalized) tip block hash
+    /// Canonical(confirmed) tip block hash
     pub hash: Option<HeaderHash>,
 }
 
@@ -109,11 +109,11 @@ impl_p2p_message!(SyncResponse, "syncresponse");
 /// Structure represening a request to ask a node a fork sequence.
 /// If we include a specific fork tip, they have to return its sequence,
 /// otherwise they respond with their best fork sequence.
-/// We also include our own canonical(finalized) tip, so they can verify
+/// We also include our own canonical(confirmed) tip, so they can verify
 /// we follow the same sequence.
 #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
 pub struct ForkSyncRequest {
-    /// Canonical(finalized) tip block hash
+    /// Canonical(confirmed) tip block hash
     pub tip: HeaderHash,
     /// Optional fork tip block hash
     pub fork_tip: Option<HeaderHash>,

+ 1 - 1
bin/darkfid/src/rpc.rs

@@ -64,7 +64,7 @@ impl RequestHandler for DarkfiNode {
             // ==================
             "blockchain.get_block" => self.blockchain_get_block(req.id, req.params).await,
             "blockchain.get_tx" => self.blockchain_get_tx(req.id, req.params).await,
-            "blockchain.last_finalized_block" => self.blockchain_last_finalized_block(req.id, req.params).await,
+            "blockchain.last_confirmed_block" => self.blockchain_last_confirmed_block(req.id, req.params).await,
             "blockchain.best_fork_next_block_height" => self.blockchain_best_fork_next_block_height(req.id, req.params).await,
             "blockchain.block_target" => self.blockchain_block_target(req.id, req.params).await,
             "blockchain.lookup_zkas" => self.blockchain_lookup_zkas(req.id, req.params).await,

+ 5 - 5
bin/darkfid/src/rpc_blockchain.rs

@@ -117,18 +117,18 @@ impl DarkfiNode {
     }
 
     // RPCAPI:
-    // Queries the blockchain database to find the last finalized block.
+    // Queries the blockchain database to find the last confirmed block.
     //
     // **Params:**
     // * `None`
     //
     // **Returns:**
-    // * `f64`   : Height of the last finalized block
-    // * `String`: Header hash of the last finalized block
+    // * `f64`   : Height of the last confirmed block
+    // * `String`: Header hash of the last confirmed block
     //
-    // --> {"jsonrpc": "2.0", "method": "blockchain.last_finalized_block", "params": [], "id": 1}
+    // --> {"jsonrpc": "2.0", "method": "blockchain.last_confirmed_block", "params": [], "id": 1}
     // <-- {"jsonrpc": "2.0", "result": [1234, "HeaderHash"], "id": 1}
-    pub async fn blockchain_last_finalized_block(&self, id: u16, params: JsonValue) -> JsonResult {
+    pub async fn blockchain_last_confirmed_block(&self, id: u16, params: JsonValue) -> JsonResult {
         let params = params.get::<Vec<JsonValue>>().unwrap();
         if !params.is_empty() {
             return JsonError::new(InvalidParams, None, id).into()

+ 6 - 6
bin/darkfid/src/task/consensus.rs

@@ -204,24 +204,24 @@ async fn consensus_task(
     loop {
         subscription.receive().await;
 
-        // Check if we can finalize anything and broadcast them
-        let finalized = match node.validator.finalization().await {
+        // Check if we can confirm anything and broadcast them
+        let confirmed = match node.validator.confirmation().await {
             Ok(f) => f,
             Err(e) => {
                 error!(
                     target: "darkfid::task::consensus_task",
-                    "Finalization failed: {e}"
+                    "Confirmation failed: {e}"
                 );
                 continue
             }
         };
 
-        if finalized.is_empty() {
+        if confirmed.is_empty() {
             continue
         }
 
-        let mut notif_blocks = Vec::with_capacity(finalized.len());
-        for block in finalized {
+        let mut notif_blocks = Vec::with_capacity(confirmed.len());
+        for block in confirmed {
             notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
         }
         block_sub.notify(JsonValue::Array(notif_blocks)).await;

+ 16 - 16
bin/darkfid/src/task/miner.rs

@@ -55,15 +55,15 @@ pub struct MinerRewardsRecipientConfig {
 
 /// Async task used for participating in the PoW block production.
 ///
-/// Miner initializes their setup and waits for next finalization,
+/// Miner initializes their setup and waits for next confirmation,
 /// by listenning for new proposals from the network, for optimal
-/// conditions. After finalization occurs, they start the actual
+/// conditions. After confirmation occurs, they start the actual
 /// miner loop, where they first grab the best ranking fork to extend,
 /// and start mining procedure for its next block. Additionally, they
 /// listen to the network for new proposals, and check if these
 /// proposals produce a new best ranking fork. If they do, the stop
 /// mining. These two tasks run in parallel, and after one of them
-/// finishes, node triggers finallization check.
+/// finishes, node triggers confirmation check.
 pub async fn miner_task(
     node: &DarkfiNodePtr,
     recipient_config: &MinerRewardsRecipientConfig,
@@ -97,21 +97,21 @@ pub async fn miner_task(
     let proposals_sub = node.subscribers.get("proposals").unwrap();
     let subscription = proposals_sub.publisher.clone().subscribe().await;
 
-    // Listen for blocks until next finalization, for optimal conditions
+    // Listen for blocks until next confirmation, for optimal conditions
     if !skip_sync {
-        info!(target: "darkfid::task::miner_task", "Waiting for next finalization...");
+        info!(target: "darkfid::task::miner_task", "Waiting for next confirmation...");
         loop {
             subscription.receive().await;
 
-            // Check if we can finalize anything and broadcast them
-            let finalized = node.validator.finalization().await?;
+            // Check if we can confirmation anything and broadcast them
+            let confirmed = node.validator.confirmation().await?;
 
-            if finalized.is_empty() {
+            if confirmed.is_empty() {
                 continue
             }
 
-            let mut notif_blocks = Vec::with_capacity(finalized.len());
-            for block in finalized {
+            let mut notif_blocks = Vec::with_capacity(confirmed.len());
+            for block in confirmed {
                 notif_blocks
                     .push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
             }
@@ -191,24 +191,24 @@ pub async fn miner_task(
             }
         }
 
-        // Check if we can finalize anything and broadcast them
-        let finalized = match node.validator.finalization().await {
+        // Check if we can confirm anything and broadcast them
+        let confirmed = match node.validator.confirmation().await {
             Ok(f) => f,
             Err(e) => {
                 error!(
                     target: "darkfid::task::miner_task",
-                    "Finalization failed: {e}"
+                    "Confirmation failed: {e}"
                 );
                 continue
             }
         };
 
-        if finalized.is_empty() {
+        if confirmed.is_empty() {
             continue
         }
 
-        let mut notif_blocks = Vec::with_capacity(finalized.len());
-        for block in finalized {
+        let mut notif_blocks = Vec::with_capacity(confirmed.len());
+        for block in confirmed {
             notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
         }
         block_sub.notify(JsonValue::Array(notif_blocks)).await;

+ 10 - 10
bin/darkfid/src/task/sync.rs

@@ -114,12 +114,12 @@ pub async fn sync_task(node: &DarkfiNodePtr, checkpoint: Option<(u32, HeaderHash
     // Sync best fork
     sync_best_fork(node, &common_tip_peers, &last.1).await;
 
-    // Perform finalization
-    let finalized = node.validator.finalization().await?;
-    if !finalized.is_empty() {
+    // Perform confirmation
+    let confirmed = node.validator.confirmation().await?;
+    if !confirmed.is_empty() {
         // Notify subscriber
-        let mut notif_blocks = Vec::with_capacity(finalized.len());
-        for block in finalized {
+        let mut notif_blocks = Vec::with_capacity(confirmed.len());
+        for block in confirmed {
             notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
         }
         block_sub.notify(JsonValue::Array(notif_blocks)).await;
@@ -462,12 +462,12 @@ async fn retrieve_blocks(
                 }
                 block_sub.notify(JsonValue::Array(notif_blocks)).await;
             } else {
-                // Perform finalization for received blocks
-                let finalized = node.validator.finalization().await?;
-                if !finalized.is_empty() {
+                // Perform confirmation for received blocks
+                let confirmed = node.validator.confirmation().await?;
+                if !confirmed.is_empty() {
                     // Notify subscriber
-                    let mut notif_blocks = Vec::with_capacity(finalized.len());
-                    for block in finalized {
+                    let mut notif_blocks = Vec::with_capacity(confirmed.len());
+                    for block in confirmed {
                         notif_blocks.push(JsonValue::String(base64::encode(
                             &serialize_async(&block).await,
                         )));

+ 6 - 6
bin/darkfid/src/task/unknown_proposal.rs

@@ -471,21 +471,21 @@ async fn handle_reorg(
     *forks = vec![peer_fork];
     drop(forks);
 
-    // Check if we can finalize anything and broadcast them
-    let finalized = match validator.finalization().await {
+    // Check if we can confirm anything and broadcast them
+    let confirmed = match validator.confirmation().await {
         Ok(f) => f,
         Err(e) => {
-            error!(target: "darkfid::task::handle_reorg", "Finalization failed: {e}");
+            error!(target: "darkfid::task::handle_reorg", "Confirmation failed: {e}");
             return Ok(())
         }
     };
 
-    if finalized.is_empty() {
+    if confirmed.is_empty() {
         return Ok(())
     }
 
-    let mut notif_blocks = Vec::with_capacity(finalized.len());
-    for block in finalized {
+    let mut notif_blocks = Vec::with_capacity(confirmed.len());
+    for block in confirmed {
         notif_blocks.push(JsonValue::String(base64::encode(&serialize_async(&block).await)));
     }
     subscriber.notify(JsonValue::Array(notif_blocks)).await;

+ 5 - 5
bin/darkfid/src/tests/harness.rs

@@ -50,7 +50,7 @@ use crate::{
 pub struct HarnessConfig {
     pub pow_target: u32,
     pub pow_fixed_difficulty: Option<BigUint>,
-    pub finalization_threshold: usize,
+    pub confirmation_threshold: usize,
     pub alice_url: String,
     pub bob_url: String,
 }
@@ -82,7 +82,7 @@ impl Harness {
         // NOTE: we are not using consensus constants here so we
         // don't get circular dependencies.
         let validator_config = ValidatorConfig {
-            finalization_threshold: config.finalization_threshold,
+            confirmation_threshold: config.confirmation_threshold,
             pow_target: config.pow_target,
             pow_fixed_difficulty: config.pow_fixed_difficulty.clone(),
             genesis_block,
@@ -158,10 +158,10 @@ impl Harness {
         }
 
         // Sleep a bit so blocks can be propagated and then
-        // trigger finalization check to Alice and Bob
+        // trigger confirmation check to Alice and Bob
         sleep(10).await;
-        self.alice.validator.finalization().await?;
-        self.bob.validator.finalization().await?;
+        self.alice.validator.confirmation().await?;
+        self.bob.validator.confirmation().await?;
 
         Ok(())
     }

+ 7 - 7
bin/darkfid/src/tests/mod.rs

@@ -43,7 +43,7 @@ async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
     let config = HarnessConfig {
         pow_target,
         pow_fixed_difficulty: pow_fixed_difficulty.clone(),
-        finalization_threshold: 3,
+        confirmation_threshold: 3,
         alice_url: "tcp+tls://127.0.0.1:18340".to_string(),
         bob_url: "tcp+tls://127.0.0.1:18341".to_string(),
     };
@@ -73,7 +73,7 @@ async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
 
     // Grab current best fork index
     let forks = th.alice.validator.consensus.forks.read().await;
-    // If index corresponds to the small fork, finalization
+    // If index corresponds to the small fork, confirmation
     // did not occur, as it's size is not over the threshold.
     let small_best = best_fork_index(&forks)? == 1;
     drop(forks);
@@ -142,20 +142,20 @@ async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
     drop(charlie_forks);
 
     // Since the don't know if the second fork was the best,
-    // we extend it until it becomes best and a finalization
+    // we extend it until it becomes best and a confirmation
     // occurred.
     let mut fork_sequence = vec![block6, block7];
     loop {
         let proposal = th.generate_next_block(fork_sequence.last().unwrap()).await?;
         th.add_blocks(&vec![proposal.clone()]).await?;
         fork_sequence.push(proposal);
-        // Check if finalization occured
+        // Check if confirmation occured
         if th.alice.validator.blockchain.len() > 4 {
             break
         }
     }
 
-    // Nodes must have executed finalization, so we validate their chains
+    // Nodes must have executed confirmation, so we validate their chains
     th.validate_chains(4 + (fork_sequence.len() - 2)).await?;
     let bob = &th.bob.validator;
     let last = alice.blockchain.last()?.1;
@@ -168,7 +168,7 @@ async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
     assert_eq!(last_proposal, bob.consensus.forks.read().await[0].proposals[1]);
 
     // Same for Charlie
-    charlie.finalization().await?;
+    charlie.confirmation().await?;
     charlie.validate_blockchain(pow_target, pow_fixed_difficulty).await?;
     assert_eq!(alice.blockchain.len(), charlie.blockchain.len());
     assert!(charlie.blockchain.headers.is_empty_sync());
@@ -230,7 +230,7 @@ fn darkfid_programmatic_control() -> Result<()> {
     genesis_block.append_txs(vec![producer_tx]);
     let bootstrap = genesis_block.header.timestamp.inner();
     let config = darkfi::validator::ValidatorConfig {
-        finalization_threshold: 1,
+        confirmation_threshold: 1,
         pow_target: 20,
         pow_fixed_difficulty: Some(BigUint::one()),
         genesis_block,

+ 1 - 1
bin/darkfid/src/tests/sync_forks.rs

@@ -36,7 +36,7 @@ async fn sync_forks_real(ex: Arc<Executor<'static>>) -> Result<()> {
     let config = HarnessConfig {
         pow_target,
         pow_fixed_difficulty: pow_fixed_difficulty.clone(),
-        finalization_threshold: 6,
+        confirmation_threshold: 6,
         alice_url: "tcp+tls://127.0.0.1:18440".to_string(),
         bob_url: "tcp+tls://127.0.0.1:18441".to_string(),
     };

+ 1 - 1
bin/darkfid/src/tests/unproposed_txs.rs

@@ -58,7 +58,7 @@ async fn simulate_unproposed_txs(
     let config = HarnessConfig {
         pow_target,
         pow_fixed_difficulty: pow_fixed_difficulty.clone(),
-        finalization_threshold: 6,
+        confirmation_threshold: 6,
         alice_url,
         bob_url,
     };

+ 16 - 16
bin/drk/src/rpc.rs

@@ -45,7 +45,7 @@ use crate::{
 
 impl Drk {
     /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
-    /// new finalized blocks. Upon receiving them, all the transactions are
+    /// new confirmed blocks. Upon receiving them, all the transactions are
     /// scanned and we check if any of them call the money contract, and if
     /// the payments are intended for us. If so, we decrypt them and append
     /// the metadata to our wallet. If a reorg block is received, we revert
@@ -57,11 +57,11 @@ impl Drk {
         endpoint: Url,
         ex: Arc<smol::Executor<'static>>,
     ) -> Result<()> {
-        // Grab last finalized block height
-        let (last_finalized_height, _) = self.get_last_finalized_block().await?;
+        // Grab last confirmed block height
+        let (last_confirmed_height, _) = self.get_last_confirmed_block().await?;
 
         // Handle genesis(0) block
-        if last_finalized_height == 0 {
+        if last_confirmed_height == 0 {
             if let Err(e) = self.scan_blocks().await {
                 return Err(Error::DatabaseError(format!(
                     "[subscribe_blocks] Scanning from genesis block failed: {e:?}"
@@ -69,8 +69,8 @@ impl Drk {
             }
         }
 
-        // Grab last finalized block again
-        let (last_finalized_height, last_finalized_hash) = self.get_last_finalized_block().await?;
+        // Grab last confirmed block again
+        let (last_confirmed_height, last_confirmed_hash) = self.get_last_confirmed_block().await?;
 
         // Grab last scanned block
         let (mut last_scanned_height, last_scanned_hash) = match self.get_last_scanned_block() {
@@ -83,9 +83,9 @@ impl Drk {
         };
 
         // Check if other blocks have been created
-        if last_finalized_height != last_scanned_height || last_finalized_hash != last_scanned_hash
+        if last_confirmed_height != last_scanned_height || last_confirmed_hash != last_scanned_hash
         {
-            eprintln!("Warning: Last scanned block is not the last finalized block.");
+            eprintln!("Warning: Last scanned block is not the last confirmed block.");
             eprintln!("You should first fully scan the blockchain, and then subscribe");
             return Err(Error::DatabaseError(
                 "[subscribe_blocks] Blockchain not fully scanned".to_string(),
@@ -256,7 +256,7 @@ impl Drk {
         }
 
         // Update wallet transactions records
-        if let Err(e) = self.put_tx_history_records(&wallet_txs, "Finalized").await {
+        if let Err(e) = self.put_tx_history_records(&wallet_txs, "Confirmed").await {
             return Err(Error::DatabaseError(format!(
                 "[scan_block] Inserting transaction history records failed: {e:?}"
             )))
@@ -328,18 +328,18 @@ impl Drk {
         }
 
         loop {
-            // Grab last finalized block
+            // Grab last confirmed block
             println!("Requested to scan from block number: {height}");
-            let (last_height, last_hash) = match self.get_last_finalized_block().await {
+            let (last_height, last_hash) = match self.get_last_confirmed_block().await {
                 Ok(last) => last,
                 Err(e) => {
                     eprintln!("[scan_blocks] RPC client request failed: {e:?}");
                     return Err(WalletDbError::GenericError)
                 }
             };
-            println!("Last finalized block reported by darkfid: {last_height} - {last_hash}");
+            println!("Last confirmed block reported by darkfid: {last_height} - {last_hash}");
 
-            // Already scanned last finalized block
+            // Already scanned last confirmed block
             if height > last_height {
                 return Ok(())
             }
@@ -363,10 +363,10 @@ impl Drk {
         }
     }
 
-    // Queries darkfid for last finalized block.
-    async fn get_last_finalized_block(&self) -> Result<(u32, String)> {
+    // Queries darkfid for last confirmed block.
+    async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
         let rep = self
-            .darkfid_daemon_request("blockchain.last_finalized_block", &JsonValue::Array(vec![]))
+            .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
             .await?;
         let params = rep.get::<Vec<JsonValue>>().unwrap();
         let height = *params[0].get::<f64>().unwrap() as u32;

+ 1 - 1
contrib/localnet/darkfid-five-nodes/darkfid0.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48240"
 # Path to the blockchain database directory
 database = "darkfid0"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-five-nodes/darkfid1.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48340"
 # Path to the blockchain database directory
 database = "darkfid1"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-five-nodes/darkfid2.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48440"
 # Path to the blockchain database directory
 database = "darkfid2"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-five-nodes/darkfid3.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48540"
 # Path to the blockchain database directory
 database = "darkfid3"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-five-nodes/darkfid4.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48640"
 # Path to the blockchain database directory
 database = "darkfid4"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-single-node/darkfid.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48240"
 # Path to the blockchain database directory
 database = "darkfid"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 1
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-small/darkfid0.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48240"
 # Path to the blockchain database directory
 database = "darkfid0"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-small/darkfid1.toml

@@ -25,7 +25,7 @@ rpc_listen = "tcp://127.0.0.1:48340"
 # Path to the blockchain database directory
 database = "darkfid1"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
contrib/localnet/darkfid-small/darkfid2.toml

@@ -17,7 +17,7 @@ rpc_listen = "tcp://127.0.0.1:48440"
 # Path to the blockchain database directory
 database = "darkfid2"
 
-# Finalization threshold, denominated by number of blocks
+# Confirmation threshold, denominated by number of blocks
 threshold = 6
 
 # minerd JSON-RPC endpoint

+ 1 - 1
doc/src/arch/arch.md

@@ -203,7 +203,7 @@ pass locally, the wallet should be updated to represent the state
 change but things should stay unconfirmed. The DAO SQL schema gives a
 nice way to do this, where there's a `tx_hash`, etc. which
 can be used to evaluate whether the transaction/coins/whatever was
-finalized.
+confirmed.
 
 We also discussed about having clients handle their own wallets,
 and not providing a sink through `darkfid` where there's a single API

+ 30 - 16
doc/src/arch/consensus.md

@@ -13,13 +13,13 @@ blockchain achieve consensus.
 | Unproposed Transaction | Transaction that exists in the memory pool but has not yet been included in a proposal |
 | Block proposal         | Block that has not yet been appended onto the canonical blockchain                     |
 | P2P network            | Peer-to-peer network on which nodes communicate with each other                        |
-| Finalization           | State achieved when a block and its contents are appended to the canonical blockchain  |
+| Confirmation           | State achieved when a block and its contents are appended to the canonical blockchain  |
 | Fork                   | Chain of block proposals that begins with the last block of the canonical blockchain   |
 | MAX_INT                | The maximum 32 bytes (256 bits) integer 2^256 − 1                                      |
 
 ## Miner main loop
 
-DarkFi uses RandomX Proof of Work algorithm with enforced finality.
+DarkFi uses RandomX Proof of Work algorithm.
 Therefore, block production involves the following steps:
 
 * First, a miner grabs its current best ranking fork and extends it with a
@@ -31,8 +31,8 @@ Therefore, block production involves the following steps:
   algorithm](https://github.com/tevador/RandomX).
 
 * Once the miner finds such a nonce, it broadcasts its block proposal to the
-  P2P network. Finally the miner triggers a finalization check to see if its
-  newly extended fork can be finalized.
+  P2P network. Finally the miner triggers a confirmation check to see if its
+  newly extended fork can be confirmed.
 
 Pseudocode:
 ```
@@ -47,7 +47,7 @@ loop {
 
     fork.append_proposal(block)
 
-    chain_finalization()
+    chain_confirmation()
 }
 ```
 
@@ -56,7 +56,7 @@ loop {
 Each node listens for new block proposals on the P2P network. Upon receiving
 block proposals, nodes try to extend the proposals onto a fork held in memory
 (this process is described in the next section). Then nodes trigger a
-finalization check to see if their newly extended fork can be finalized.
+confirmation check to see if their newly extended fork can be confirmed.
 
 Upon receiving a new block proposal, miners also check if the extended fork
 rank is better than the one they are currently trying to extend. If the fork
@@ -108,13 +108,13 @@ Upon receiving a block, one of the following cases may occur:
 | Block extends a known fork at its end         | Append block to fork                                                |
 | Block extends a known fork not at its end     | Create a new fork up to the extended block and append the new block |
 | Block extends canonical blockchain at its end | Create a new fork containing the new block                          |
-| Block doesn't extend any known chain          | Ignore block                                                        |
+| Block doesn't extend any known chain          | Check if a reorg should be executed                                 |
 
 ### Visual Examples
 
 | Symbol        | Description                            |
 |---------------|----------------------------------------|
-| [C]           | Canonical (finalized) blockchain block |
+| [C]           | Canonical (confirmed) blockchain block |
 | [C]--...--[C] | Sequence of canonical blocks           |
 | [Mn]          | Proposal produced by Miner n           |
 | Fn            | Fork name to identify them in examples |
@@ -159,8 +159,22 @@ Extending the canonical blockchain with a new block proposal:
                    |
                    |+--[M4]      <-- F3
 
+##### Case 4
 
-## Finalization
+Reorg happened and we rebuild the chain:
+
+                              |--[M0]--[M2] <-- F0
+    [C]--...--[C]/--...--[C]--|
+               |              |--[M1]       <-- F1
+               |              |
+               |              |--[M0]--[M3] <-- F2
+               |              |
+               |              |--[M4]       <-- F3
+               |
+               ...--...--[C]--|+--[M5]      <-- F4
+
+
+## Confirmation
 
 Based on the rank properties, each node will diverge to the highest ranking
 fork, and new fork will emerge extending that at its tips.
@@ -168,17 +182,17 @@ A security threshold is set, which refers to the height where the probability
 to produce a fork, able to reorg the current best ranking fork reaches zero,
 similar to the # of block confirmation used by other PoW based protocols.
 
-When the finalization check kicks in, each node will grab its best fork.
-If the fork's length exceeds the security threshold, the node will push (finalize)
+When the confirmation check kicks in, each node will grab its best fork.
+If the fork's length exceeds the security threshold, the node will push (confirm)
 its first proposal to the canonical blockchain. The fork acts as a queue (buffer)
-for the to-be-finalized proposals.
+for the to-be-confirmed proposals.
 
-Once a finalization occurs, all the fork chains not starting with the finalized
+Once a confirmation occurs, all the fork chains not starting with the confirmed
 block(s) are removed from the node's memory pool.
 
 We continue Case 3 from the previous section to visualize this logic.
 
-The finalization threshold used in this example is 3 blocks. A node observes 2
+The confirmation threshold used in this example is 3 blocks. A node observes 2
 proposals. One extends the F0 fork and the other extends the F2 fork:
 
                    |--[M0]--[M2]+--[M5] <-- F0
@@ -200,7 +214,7 @@ Later, the node only observes 1 proposal, extending the F2 fork:
                    |
                    |--[M4]                    <-- F3
 
-When the finalization sync period starts, the node finalizes block M0 and
+When the confirmation sync period starts, the node confirms block M0 and
 keeps the forks that extend that:
 
                    |--[M0]--[M2]--[M5]       <-- F0
@@ -275,7 +289,7 @@ the tx in Bitcoin with the most outputs has 2501.
 
 | Field       | Type              | Description                            |
 |-------------|-------------------|----------------------------------------|
-| `canonical` | `Blockchain`      | Canonical (finalized) blockchain       |
+| `canonical` | `Blockchain`      | Canonical (confirmed) blockchain       |
 | `forks`     | `Vec<Blockchain>` | Fork chains containing block proposals |
 
 # Appendix: Ranking Blocks

+ 4 - 4
doc/src/arch/overview.md

@@ -5,10 +5,10 @@ applications. It is currently under development. This overview will
 outline a few key terms that help explain DarkFi.
 
 **Blockchain:** The DarkFi blockchain is based off Proof of Work RandomX
-algorithm, paired with Delayed finality. Consensus participating nodes,
-called miners, produce and propose new blocks to the network, extending
-some fork chain, which once it reaches a finality security threshold,
-can be appended to canonical by all nodes in the network.
+algorithm. Consensus participating nodes, called miners, produce and propose
+new blocks to the network, extending some fork chain, which once it reaches
+a confirmation security threshold, can be appended to canonical by all nodes
+in the network.
 
 **Wallet:** A wallet is a portal to the DarkFi network. It provides
 the user with the ability to send and receive anonymous _darkened_

+ 15 - 15
doc/src/arch/tx_lifetime.md

@@ -15,10 +15,10 @@ that transactions reach `M`.
 To avoid spam attacks, `S` should keep $tx$ in their mempool for some
 period of time, and then prune it.
 
-## Ideal simulation with instant finality
+## Ideal simulation with instant confirmation
 
 The lifetime of a transaction $tx$ that passes verification and whose
-state transition can be applied on top of the finalized (canonical)
+state transition can be applied on top of the canonical (confirmed)
 chain:
 
 1. User creates a transaction $tx$
@@ -29,18 +29,18 @@ chain:
 6. `M` validates $tx$ state transition
 7. $tx$ enters `M` `mempool`
 8. `M` validates all transactions in its `mempool` in sequence
-9. `M` proposes a block finalization containing $tx$
+9. `M` proposes a block confirmation containing $tx$
 10. `M` writes the state transition update of $tx$ to their chain
 11. `M` removes $tx$ from their `mempool`
-12. `M` broadcasts the finalized proposal
+12. `M` broadcasts the confirmed proposal
 13. `S` receives the proposal and validates transactions
 14. `S` writes the state updates to their chain
 15. `S` removes $tx$ from their `mempool`
 
-## Real-world simulation with non-instant finality
+## Real-world simulation with non-instant confirmation
 
 The lifetime of a transaction $tx$ that passes verification and whose
-state transition is pending to be applied on top of the finalized (canonical)
+state transition is pending to be applied on top of the canonical (confirmed)
 chain:
 
 1. User creates a transaction $tx$
@@ -52,19 +52,19 @@ chain:
 7. $tx$ enters `M` `mempool`
 8. `M` proposes a block proposal containing $tx$
 9. `M` proposes more block proposals
-10. When proposals can be finalized, `M` validates all their transactions
+10. When proposals can be confirmed, `M` validates all their transactions
 in sequence
 11. `M` writes the state transition update of $tx$ to their chain
 12. `M` removes $tx$ from their `mempool`
-13. `M` broadcasts the finalized proposals sequence
+13. `M` broadcasts the confirmed proposals sequence
 14. `S` receives the proposals sequence and validates transactions
 15. `S` writes the state updates to their chain
 16. `S` removes $tx$ from their `mempool`
 
-## Real-world simulation with non-instant finality, forks and multiple `CP` nodes
+## Real-world simulation with non-instant confirmation, forks and multiple `CP` nodes
 
 The lifetime of a transaction $tx$ that passes verifications and whose
-state transition is pending to be applied on top of the finalized (canonical)
+state transition is pending to be applied on top of the canonical (confirmed)
 chain:
 
 1. User creates a transaction $tx$
@@ -82,22 +82,22 @@ against extended fork state, discarding invalid
 12. `M` receives block proposal and validates its transactions against
 the extended fork state
 13. `SM` proposes more block proposals extending a fork state
-14. When a fork can be finalized, `M` validates all its proposals
+14. When a fork can be confirmed, `M` validates all its proposals
 transactions in sequence, against canonical state
 15. `M` writes the state transition update of $tx$ to their chain
 16. `M` removes $tx$ from their `mempool`
-17. `M` drop rest forks and keeps only the finalized one
-18. `M` broadcasts the finalized proposals sequence
+17. `M` drop rest forks and keeps only the confirmed one
+18. `M` broadcasts the confirmed proposals sequence
 19. `S` receives the proposals sequence and validates transactions
 20. `S` writes the state updates to their chain
 21. `S` removes $tx$ from their `mempool`
 
 `M` will keep $tx$ in its `mempool` as long as it is a valid state transition
-for any fork(including canonical) or it get finalized.
+for any fork(including canonical) or it get confirmed.
 
 Unproposed transactions refers to all $tx$ not included in a proposal of any fork.
 
-If a fork that can be finalized fails to validate all its transactions(14), it should be dropped.
+If a fork that can be confirmed fails to validate all its transactions(14), it should be dropped.
 
 ## The `Transaction` object
 

+ 1 - 1
doc/src/spec/contract/dao/concepts.md

@@ -21,7 +21,7 @@ Once proposals are posted on chain, they are immediately active.
 * *Active*: the proposal is open to voting.
 * *Expired*: the proposal passed its duration and can no longer be voted on.
 * *Accepted*: the proposal gained sufficient votes but is not yet executed.
-* *Executed*: the proposal was accepted and has been finalized on chain.
+* *Executed*: the proposal was accepted and has been confirmed on chain.
 
 ## Vote
 

+ 1 - 1
doc/src/spec/contract/dao/dao.md

@@ -5,7 +5,7 @@
 This contract enables anonymous on chain DAOs which can make arbitrary contract calls.
 In this system, holders of the governance token specified by the DAO can
 make proposals which are then voted on. When proposals pass a specified
-threshold they are finalized, then the proposal can be executed.
+threshold they are confirmed, then the proposal can be executed.
 
 - [Concepts](concepts.md)
 - [Model](model.md)

+ 2 - 2
doc/src/testnet/atomic-swap.md

@@ -65,7 +65,7 @@ $ ./drk broadcast < swap_tx
 ```
 
 On success, you should see a transaction ID. This transaction will now
-also be in the mempool, so you should wait again until it's finalized.
+also be in the mempool, so you should wait again until it's confirmed.
 
 ![pablo-waiting2](pablo2.jpg)
 
@@ -77,4 +77,4 @@ $ ./drk wallet --balance
 
 If you see your counterparty's tokens, that means the swap was
 successful.  In case you still see your old tokens, that could mean
-that the swap transaction has not yet been finalized.
+that the swap transaction has not yet been confirmed.

+ 6 - 6
doc/src/testnet/dao.md

@@ -47,7 +47,7 @@ $ ./drk broadcast < dao_mldy_mint_tx
 ```
 
 Now the transaction is broadcasted to the network. Wait for it to
-finalize, and if your `drk` is subscribed, after finalization you
+confirm, and if your `drk` is subscribed, after confirmation you
 should see a leaf position and a transaction hash when running
 `dao list MiladyMakerDAO`.
 
@@ -66,7 +66,7 @@ $ ./drk transfer 10 WCKD {DAO_PUBLIC_KEY} \
 $ ./drk broadcast < dao_mldy_transfer_tx
 ```
 
-Wait for it to finalize, and if subscribed, you should see the DAO
+Wait for it to confirm, and if subscribed, you should see the DAO
 receive the funds:
 
 ```
@@ -109,7 +109,7 @@ $ ./drk broadcast < dao_mldy_transfer_proposal_mint_tx
 Members that didn't receive the encrypted file will receive the
 proposal when they scan the corresponding block, but its plaintext
 data will be missing, so they should ask the DAO for it.
-Once finalized and scanned, you should see a leaf position and a
+Once confirmed and scanned, you should see a leaf position and a
 transaction hash when running `dao proposal {PROPOSAL_BULLA}`.
 
 ## Voting on a proposal
@@ -141,14 +141,14 @@ $ ./drk dao vote {PROPOSAL_BULLA} 1 > dao_mldy_transfer_proposal_vote_tx
 $ ./drk broadcast < dao_mldy_transfer_proposal_vote_tx
 ```
 
-Once finalized and scanned, you should see votes information and
+Once confirmed and scanned, you should see votes information and
 current status when running `dao proposal {PROPOSAL_BULLA}`.
 
 ## Executing the proposal
 
 Once enough votes have been cast that meet the required minimum (quorum)
 and assuming the yes:no votes ratio is bigger than the approval ratio,
-then we are ready to finalize the vote. Any DAO member can perform this
+then we are ready to confirm the vote. Any DAO member can perform this
 action.
 
 Since in our tutorial the `MLDY` governance tokens we used surpass the
@@ -182,7 +182,7 @@ $ ./drk token mint MLDY 20 {DAO_PUBLIC_KEY} \
 $ ./drk broadcast < mint_dao_mldy_tx
 ```
 
-After finalization we will see the dao holding its own
+After confirmation we will see the dao holding its own
 governance tokens in its treasury:
 
 ```

+ 1 - 1
doc/src/testnet/payment.md

@@ -17,7 +17,7 @@ to the network:
 $ ./drk broadcast < payment_tx
 ```
 
-On success we'll see a transaction ID. Now again the same finalization
+On success we'll see a transaction ID. Now again the same confirmation
 process has to occur and `8sRwB7AwBTKEkyTW6oMyRoJWZhJwtqGTf7nyHwuJ74pj`
 will receive the tokens you've sent.
 

+ 3 - 3
doc/src/testnet/token.md

@@ -3,14 +3,14 @@
 Now that you have your wallet set up, you will need some native `DRK`
 tokens in order to be able to perform transactions, since that token
 is used to pay the transaction fees. You can obtain `DRK` either by
-successfully mining a block that gets finalized or by asking for some
+successfully mining a block that gets confirmed or by asking for some
 by the community on `darkirc` and/or your comrades. Don't forget to
 tell them to add the `--half-split` flag when they create the transfer
 transaction, so you get more than one coins to play with.
 
 After you request some `DRK` and the other party submitted a transaction
 to the network, it should be in the consensus' mempool, waiting for
-inclusion in the next block(s). Depending on the network, finalization
+inclusion in the next block(s). Depending on the network, confirmation
 of the blocks could take some time. You'll have to wait for this to happen.
 If your `drk subscribe` is running, then after some time your new balance
 should be in your wallet.
@@ -89,5 +89,5 @@ $ ./drk broadcast < mint_tx
 
 Now the transaction should be published to the network. If you have
 an active block subscription (which you can do with `drk subscribe`),
-then when the transaction is finalized, your wallet should have your
+then when the transaction is confirmed, your wallet should have your
 new tokens listed when you request to see the balance.

+ 12 - 12
script/research/blockchain-explorer/src/rpc_blocks.rs

@@ -79,13 +79,13 @@ impl Explorerd {
         };
 
         loop {
-            // Grab last finalized block
-            let (last_height, last_hash) = self.get_last_finalized_block().await?;
+            // Grab last confirmed block
+            let (last_height, last_hash) = self.get_last_confirmed_block().await?;
 
             info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Requested to sync from block number: {height}");
-            info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Last finalized block number reported by darkfid: {last_height} - {last_hash}");
+            info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Last confirmed block number reported by darkfid: {last_height} - {last_hash}");
 
-            // Already synced last finalized block
+            // Already synced last confirmed block
             if height > last_height {
                 return Ok(())
             }
@@ -248,10 +248,10 @@ impl Explorerd {
         }
     }
 
-    // Queries darkfid for last finalized block.
-    async fn get_last_finalized_block(&self) -> Result<(u32, String)> {
+    // Queries darkfid for last confirmed block.
+    async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
         let rep = self
-            .darkfid_daemon_request("blockchain.last_finalized_block", &JsonValue::Array(vec![]))
+            .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
             .await?;
         let params = rep.get::<Vec<JsonValue>>().unwrap();
         let height = *params[0].get::<f64>().unwrap() as u32;
@@ -262,14 +262,14 @@ impl Explorerd {
 }
 
 /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
-/// new finalized blocks. Upon receiving them, store them to the database.
+/// new confirmed blocks. Upon receiving them, store them to the database.
 pub async fn subscribe_blocks(
     explorer: Arc<Explorerd>,
     endpoint: Url,
     ex: Arc<smol::Executor<'static>>,
 ) -> Result<(StoppableTaskPtr, StoppableTaskPtr)> {
-    // Grab last finalized block
-    let (last_finalized, _) = explorer.get_last_finalized_block().await?;
+    // Grab last confirmed block
+    let (last_confirmed, _) = explorer.get_last_confirmed_block().await?;
 
     // Grab last synced block
     let last_synced = match explorer.db.last_block() {
@@ -282,8 +282,8 @@ pub async fn subscribe_blocks(
         }
     };
 
-    if last_finalized != last_synced {
-        warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Warning: Last synced block is not the last finalized block.");
+    if last_confirmed != last_synced {
+        warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Warning: Last synced block is not the last confirmed block.");
         warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "You should first fully sync the blockchain, and then subscribe");
         return Err(Error::DatabaseError(
             "[subscribe_blocks] Blockchain not fully synced".to_string(),

+ 1 - 1
src/contract/test-harness/src/lib.rs

@@ -164,7 +164,7 @@ impl Wallet {
 
         // Create the `Validator` instance
         let validator_config = ValidatorConfig {
-            finalization_threshold: 3,
+            confirmation_threshold: 3,
             pow_target: 90,
             pow_fixed_difficulty: Some(BigUint::from(1_u8)),
             genesis_block,

+ 29 - 29
src/validator/consensus.rs

@@ -52,10 +52,10 @@ pub const GAS_LIMIT_UNPROPOSED_TXS: u64 = GAS_TX_AVG * GAS_LIMIT_MULTIPLIER_UNPR
 
 /// This struct represents the information required by the consensus algorithm
 pub struct Consensus {
-    /// Canonical (finalized) blockchain
+    /// Canonical (confirmed) blockchain
     pub blockchain: Blockchain,
-    /// Fork size(length) after which it can be finalized
-    pub finalization_threshold: usize,
+    /// Fork size(length) after which it can be confirmed
+    pub confirmation_threshold: usize,
     /// Fork chains containing block proposals
     pub forks: RwLock<Vec<Fork>>,
     /// Canonical blockchain PoW module state
@@ -68,7 +68,7 @@ impl Consensus {
     /// Generate a new Consensus state.
     pub fn new(
         blockchain: Blockchain,
-        finalization_threshold: usize,
+        confirmation_threshold: usize,
         pow_target: u32,
         pow_fixed_difficulty: Option<BigUint>,
     ) -> Result<Self> {
@@ -80,7 +80,7 @@ impl Consensus {
             None,
         )?);
         let append_lock = RwLock::new(());
-        Ok(Self { blockchain, finalization_threshold, forks, module, append_lock })
+        Ok(Self { blockchain, confirmation_threshold, forks, module, append_lock })
     }
 
     /// Generate a new empty fork.
@@ -236,16 +236,16 @@ impl Consensus {
         Ok((fork, None))
     }
 
-    /// Check if best fork proposals can be finalized.
-    /// Consensus finalization logic:
+    /// Check if best fork proposals can be confirmed.
+    /// Consensus confirmation logic:
     /// - If the current best fork has reached greater length than the security threshold,
     ///   and no other fork exist with same rank, first proposal(s) in that fork can be
-    ///   appended to canonical blockchain (finalize).
+    ///   appended to canonical blockchain (confirme).
     ///
-    /// When best fork can be finalized, first block(s) should be appended to canonical,
+    /// When best fork can be confirmed, first block(s) should be appended to canonical,
     /// and forks should be rebuilt.
-    pub async fn finalization(&self) -> Result<Option<usize>> {
-        debug!(target: "validator::consensus::finalization", "Started finalization check");
+    pub async fn confirmation(&self) -> Result<Option<usize>> {
+        debug!(target: "validator::consensus::confirmation", "Started confirmation check");
 
         // Grab best fork
         let forks = self.forks.read().await;
@@ -254,8 +254,8 @@ impl Consensus {
 
         // Check its length
         let length = fork.proposals.len();
-        if length < self.finalization_threshold {
-            debug!(target: "validator::consensus::finalization", "Nothing to finalize yet, best fork size: {}", length);
+        if length < self.confirmation_threshold {
+            debug!(target: "validator::consensus::confirmation", "Nothing to confirme yet, best fork size: {}", length);
             drop(forks);
             return Ok(None)
         }
@@ -466,22 +466,22 @@ impl Consensus {
     }
 
     /// Auxiliary function to purge current forks and reset the ones starting
-    /// with the provided prefix, excluding provided finalized fork.
-    /// Additionally, remove finalized transactions from the forks mempools,
+    /// with the provided prefix, excluding provided confirmed fork.
+    /// Additionally, remove confirmed transactions from the forks mempools,
     /// along with the unporposed transactions sled trees.
     /// This function assumes that the prefix blocks have already been appended
-    /// to canonical chain from the finalized fork.
+    /// to canonical chain from the confirmed fork.
     pub async fn reset_forks(
         &self,
         prefix: &[HeaderHash],
-        finalized_fork_index: &usize,
-        finalized_txs: &[Transaction],
+        confirmed_fork_index: &usize,
+        confirmed_txs: &[Transaction],
     ) -> Result<()> {
         // Grab a lock over current forks
         let mut forks = self.forks.write().await;
 
         // Find all the forks that start with the provided prefix,
-        // excluding finalized fork index, and remove their prefixed
+        // excluding confirmed fork index, and remove their prefixed
         // proposals, and their corresponding diffs.
         // If the fork is not starting with the provided prefix,
         // drop it. Additionally, keep track of all the referenced
@@ -492,10 +492,10 @@ impl Consensus {
         let mut keep = vec![true; forks.len()];
         let mut referenced_trees = HashSet::new();
         let mut referenced_txs = HashSet::new();
-        let finalized_txs_hashes: Vec<TransactionHash> =
-            finalized_txs.iter().map(|tx| tx.hash()).collect();
+        let confirmed_txs_hashes: Vec<TransactionHash> =
+            confirmed_txs.iter().map(|tx| tx.hash()).collect();
         for (index, fork) in forks.iter_mut().enumerate() {
-            if &index == finalized_fork_index {
+            if &index == confirmed_fork_index {
                 // Store its tree references
                 let fork_overlay = fork.overlay.lock().unwrap();
                 let overlay = fork_overlay.overlay.lock().unwrap();
@@ -508,8 +508,8 @@ impl Consensus {
                 for tree in overlay.state.dropped_trees.keys() {
                     referenced_trees.insert(tree.clone());
                 }
-                // Remove finalized proposals txs from fork's mempool
-                fork.mempool.retain(|tx| !finalized_txs_hashes.contains(tx));
+                // Remove confirmed proposals txs from fork's mempool
+                fork.mempool.retain(|tx| !confirmed_txs_hashes.contains(tx));
                 // Store its txs references
                 for tx in &fork.mempool {
                     referenced_txs.insert(*tx);
@@ -527,8 +527,8 @@ impl Consensus {
                 continue
             }
 
-            // Remove finalized proposals txs from fork's mempool
-            fork.mempool.retain(|tx| !finalized_txs_hashes.contains(tx));
+            // Remove confirmed proposals txs from fork's mempool
+            fork.mempool.retain(|tx| !confirmed_txs_hashes.contains(tx));
             // Store its txs references
             for tx in &fork.mempool {
                 referenced_txs.insert(*tx);
@@ -602,8 +602,8 @@ impl Consensus {
         let mut iter = keep.iter();
         forks.retain(|_| *iter.next().unwrap());
 
-        // Remove finalized proposals txs from the unporposed txs sled tree
-        self.blockchain.remove_pending_txs_hashes(&finalized_txs_hashes)?;
+        // Remove confirmed proposals txs from the unporposed txs sled tree
+        self.blockchain.remove_pending_txs_hashes(&confirmed_txs_hashes)?;
 
         // Remove unreferenced txs from the unporposed txs sled tree
         self.blockchain.remove_pending_txs_hashes(&Vec::from_iter(dropped_txs))?;
@@ -669,7 +669,7 @@ impl From<Proposal> for BlockInfo {
 /// in order of receival, and the proposals hashes sequence, for validations.
 #[derive(Clone)]
 pub struct Fork {
-    /// Canonical (finalized) blockchain
+    /// Canonical (confirmed) blockchain
     pub blockchain: Blockchain,
     /// Overlay cache over canonical Blockchain
     pub overlay: BlockchainOverlayPtr,

+ 34 - 34
src/validator/mod.rs

@@ -61,8 +61,8 @@ use utils::{best_fork_index, block_rank, deploy_native_contracts};
 /// Configuration for initializing [`Validator`]
 #[derive(Clone)]
 pub struct ValidatorConfig {
-    /// Currently configured finalization security threshold
-    pub finalization_threshold: usize,
+    /// Currently configured confirmation security threshold
+    pub confirmation_threshold: usize,
     /// Currently configured PoW target
     pub pow_target: u32,
     /// Optional fixed difficulty, for testing purposes
@@ -78,7 +78,7 @@ pub type ValidatorPtr = Arc<Validator>;
 
 /// This struct represents a DarkFi validator node.
 pub struct Validator {
-    /// Canonical (finalized) blockchain
+    /// Canonical (confirmed) blockchain
     pub blockchain: Blockchain,
     /// Hot/Live data used by the consensus algorithm
     pub consensus: Consensus,
@@ -113,7 +113,7 @@ impl Validator {
         info!(target: "validator::new", "Initializing Consensus");
         let consensus = Consensus::new(
             blockchain.clone(),
-            config.finalization_threshold,
+            config.confirmation_threshold,
             config.pow_target,
             config.pow_fixed_difficulty.clone(),
         )?;
@@ -332,63 +332,63 @@ impl Validator {
         result
     }
 
-    /// The node checks if best fork can be finalized.
-    /// If proposals can be finalized, node appends them to canonical,
+    /// The node checks if best fork can be confirmed.
+    /// If proposals can be confirmed, node appends them to canonical,
     /// and resets the current forks.
-    pub async fn finalization(&self) -> Result<Vec<BlockInfo>> {
+    pub async fn confirmation(&self) -> Result<Vec<BlockInfo>> {
         // Grab append lock so no new proposals can be appended while
-        // we execute finalization
+        // we execute confirmation
         let append_lock = self.consensus.append_lock.write().await;
 
-        info!(target: "validator::finalization", "Performing finalization check");
+        info!(target: "validator::confirmation", "Performing confirmation check");
 
-        // Grab best fork index that can be finalized
-        let finalized_fork = match self.consensus.finalization().await {
+        // Grab best fork index that can be confirmed
+        let confirmed_fork = match self.consensus.confirmation().await {
             Ok(f) => f,
             Err(e) => {
                 drop(append_lock);
                 return Err(e)
             }
         };
-        if finalized_fork.is_none() {
-            info!(target: "validator::finalization", "No proposals can be finalized");
+        if confirmed_fork.is_none() {
+            info!(target: "validator::confirmation", "No proposals can be confirmed");
             drop(append_lock);
             return Ok(vec![])
         }
 
         // Grab the actual best fork
-        let finalized_fork = finalized_fork.unwrap();
+        let confirmed_fork = confirmed_fork.unwrap();
         let mut forks = self.consensus.forks.write().await;
-        let fork = &mut forks[finalized_fork];
+        let fork = &mut forks[confirmed_fork];
 
-        // Find the excess over finalization threshold
-        let excess = (fork.proposals.len() - self.consensus.finalization_threshold) + 1;
+        // Find the excess over confirmation threshold
+        let excess = (fork.proposals.len() - self.consensus.confirmation_threshold) + 1;
 
-        // Grab finalized proposals and update fork's sequences
+        // Grab confirmed proposals and update fork's sequences
         let rest_proposals = fork.proposals.split_off(excess);
         let rest_diffs = fork.diffs.split_off(excess);
-        let finalized_proposals = fork.proposals.clone();
+        let confirmed_proposals = fork.proposals.clone();
         let diffs = fork.diffs.clone();
         fork.proposals = rest_proposals;
         fork.diffs = rest_diffs;
 
-        // Grab finalized proposals blocks
-        let finalized_blocks =
-            fork.overlay.lock().unwrap().get_blocks_by_hash(&finalized_proposals)?;
+        // Grab confirmed proposals blocks
+        let confirmed_blocks =
+            fork.overlay.lock().unwrap().get_blocks_by_hash(&confirmed_proposals)?;
 
-        // Apply finalized proposals diffs and update PoW module
+        // Apply confirmed proposals diffs and update PoW module
         let mut module = self.consensus.module.write().await;
-        let mut finalized_txs = vec![];
+        let mut confirmed_txs = vec![];
         let mut state_diffs_heights = vec![];
         let mut state_diffs = vec![];
-        info!(target: "validator::finalization", "Finalizing proposals:");
-        for (index, proposal) in finalized_proposals.iter().enumerate() {
-            info!(target: "validator::finalization", "\t{} - {}", proposal, finalized_blocks[index].header.height);
+        info!(target: "validator::confirmation", "Confirming proposals:");
+        for (index, proposal) in confirmed_proposals.iter().enumerate() {
+            info!(target: "validator::confirmation", "\t{} - {}", proposal, confirmed_blocks[index].header.height);
             fork.overlay.lock().unwrap().overlay.lock().unwrap().apply_diff(&diffs[index])?;
             let next_difficulty = module.next_difficulty()?;
-            module.append(finalized_blocks[index].header.timestamp, &next_difficulty);
-            finalized_txs.extend_from_slice(&finalized_blocks[index].txs);
-            state_diffs_heights.push(finalized_blocks[index].header.height);
+            module.append(confirmed_blocks[index].header.timestamp, &next_difficulty);
+            confirmed_txs.extend_from_slice(&confirmed_blocks[index].txs);
+            state_diffs_heights.push(confirmed_blocks[index].header.height);
             state_diffs.push(diffs[index].clone());
         }
         drop(module);
@@ -397,14 +397,14 @@ impl Validator {
         // Store the block diffs
         self.blockchain.blocks.insert_state_diff(&state_diffs_heights, &state_diffs)?;
 
-        // Reset forks starting with the finalized blocks
-        self.consensus.reset_forks(&finalized_proposals, &finalized_fork, &finalized_txs).await?;
-        info!(target: "validator::finalization", "Finalization completed!");
+        // Reset forks starting with the confirmed blocks
+        self.consensus.reset_forks(&confirmed_proposals, &confirmed_fork, &confirmed_txs).await?;
+        info!(target: "validator::confirmation", "Confirmation completed!");
 
         // Release append lock
         drop(append_lock);
 
-        Ok(finalized_blocks)
+        Ok(confirmed_blocks)
     }
 
     /// Apply provided set of [`BlockInfo`] without doing formal verification.