Bladeren bron

validator/pow: simplyfied randomx keys usage in pow module

skoupidi 6 maanden geleden
bovenliggende
commit
1eebd74ff2
5 gewijzigde bestanden met toevoegingen van 37 en 29 verwijderingen
  1. 3 4
      bin/darkfid/src/registry/model.rs
  2. 16 16
      src/blockchain/mod.rs
  3. 2 1
      src/validator/consensus.rs
  4. 7 3
      src/validator/mod.rs
  5. 9 5
      src/validator/pow.rs

+ 3 - 4
bin/darkfid/src/registry/model.rs

@@ -265,11 +265,10 @@ pub async fn generate_next_block_template(
     let randomx_keys = if next_block_height > RANDOMX_KEY_CHANGING_HEIGHT &&
         next_block_height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
     {
-        (extended_fork.module.darkfi_rx_keys.1, None)
-    } else if extended_fork.module.darkfi_rx_keys.0 != extended_fork.module.darkfi_rx_keys.1 {
-        (extended_fork.module.darkfi_rx_keys.0, Some(extended_fork.module.darkfi_rx_keys.1))
+        // Its safe to unwrap here since we know the key has been set
+        (extended_fork.module.darkfi_rx_keys.1.unwrap(), None)
     } else {
-        (extended_fork.module.darkfi_rx_keys.0, None)
+        extended_fork.module.darkfi_rx_keys
     };
 
     // Grab forks' next mine target and difficulty

+ 16 - 16
src/blockchain/mod.rs

@@ -460,7 +460,7 @@ impl Blockchain {
         key_change_height: &u32,
         key_change_delay: &u32,
         height: Option<u32>,
-    ) -> Result<(HeaderHash, HeaderHash)> {
+    ) -> Result<(HeaderHash, Option<HeaderHash>)> {
         // Grab last known block header
         let last = match height {
             Some(h) => &self.get_headers_by_heights(&[if h != 0 { h - 1 } else { 0 }])?[0],
@@ -473,7 +473,7 @@ impl Blockchain {
             let current = self.genesis()?.1;
 
             // Check if last known block header is the next key
-            let next = if &last.height == key_change_height { last.hash() } else { current };
+            let next = if &last.height == key_change_height { Some(last.hash()) } else { None };
 
             return Ok((current, next))
         }
@@ -488,7 +488,7 @@ impl Blockchain {
         if distance == 0 {
             return Ok((
                 self.get_headers_by_heights(&[last.height - key_change_height])?[0].hash(),
-                last.hash(),
+                Some(last.hash()),
             ))
         }
 
@@ -500,7 +500,7 @@ impl Blockchain {
             return Ok((
                 self.get_headers_by_heights(&[last.height - (distance + key_change_height)])?[0]
                     .hash(),
-                self.get_headers_by_heights(&[last.height - distance])?[0].hash(),
+                Some(self.get_headers_by_heights(&[last.height - distance])?[0].hash()),
             ))
         }
 
@@ -508,7 +508,7 @@ impl Blockchain {
         // current key is the block header located at last_height - distance
         // height and we don't know the next key.
         let current = self.get_headers_by_heights(&[last.height - distance])?[0].hash();
-        Ok((current, current))
+        Ok((current, None))
     }
 }
 
@@ -779,14 +779,14 @@ mod tests {
 
     /// Compute the RandomX VM current and next key heights, based on
     /// provided key changing height and delay.
-    fn get_randomx_vm_keys_heights(last: u32) -> (u32, u32) {
+    fn get_randomx_vm_keys_heights(last: u32) -> (u32, Option<u32>) {
         // Check if we passed the first key change height
         if last <= RANDOMX_KEY_CHANGING_HEIGHT {
             // Genesis is our current
             let current = 0;
 
             // Check if last height is the next key height
-            let next = if last == RANDOMX_KEY_CHANGING_HEIGHT { last } else { current };
+            let next = if last == RANDOMX_KEY_CHANGING_HEIGHT { Some(last) } else { None };
 
             return (current, next)
         }
@@ -798,21 +798,21 @@ mod tests {
         // When distance is 0, current key is the last_height - RANDOMX_KEY_CHANGING_HEIGHT
         // height, while last is the next key.
         if distance == 0 {
-            return (last - RANDOMX_KEY_CHANGING_HEIGHT, last)
+            return (last - RANDOMX_KEY_CHANGING_HEIGHT, Some(last))
         }
 
         // When distance is less than key change delay, current key
         // is the last_height - (distance + RANDOMX_KEY_CHANGING_HEIGHT) height,
         // while the last_height - distance height is the next key.
         if distance < RANDOMX_KEY_CHANGE_DELAY {
-            return (last - (distance + RANDOMX_KEY_CHANGING_HEIGHT), last - distance)
+            return (last - (distance + RANDOMX_KEY_CHANGING_HEIGHT), Some(last - distance))
         }
 
         // When distance is greater or equal to key change delay,
         // current key is the last_height - distance height and we
         // don't know the next key height.
         let current = last - distance;
-        (current, current)
+        (current, None)
     }
 
     #[test]
@@ -820,32 +820,32 @@ mod tests {
         // last < RANDOMX_KEY_CHANGING_HEIGHT(2048)
         let (current, next) = get_randomx_vm_keys_heights(2047);
         assert_eq!(current, 0);
-        assert_eq!(next, 0);
+        assert!(next.is_none());
 
         // last == RANDOMX_KEY_CHANGING_HEIGHT(2048)
         let (current, next) = get_randomx_vm_keys_heights(2048);
         assert_eq!(current, 0);
-        assert_eq!(next, 2048);
+        assert_eq!(next, Some(2048));
 
         // last > RANDOMX_KEY_CHANGING_HEIGHT(2048)
         // last % RANDOMX_KEY_CHANGING_HEIGHT(2048) == 0
         let (current, next) = get_randomx_vm_keys_heights(4096);
         assert_eq!(current, 2048);
-        assert_eq!(next, 4096);
+        assert_eq!(next, Some(4096));
 
         // last % RANDOMX_KEY_CHANGING_HEIGHT(2048) < RANDOMX_KEY_CHANGE_DELAY(64)
         let (current, next) = get_randomx_vm_keys_heights(4097);
         assert_eq!(current, 2048);
-        assert_eq!(next, 4096);
+        assert_eq!(next, Some(4096));
 
         // last % RANDOMX_KEY_CHANGING_HEIGHT(2048) == RANDOMX_KEY_CHANGE_DELAY(64)
         let (current, next) = get_randomx_vm_keys_heights(4160);
         assert_eq!(current, 4096);
-        assert_eq!(next, 4096);
+        assert!(next.is_none());
 
         // last % RANDOMX_KEY_CHANGING_HEIGHT(2048) > RANDOMX_KEY_CHANGE_DELAY(64)
         let (current, next) = get_randomx_vm_keys_heights(4161);
         assert_eq!(current, 4096);
-        assert_eq!(next, 4096);
+        assert!(next.is_none());
     }
 }

+ 2 - 1
src/validator/consensus.rs

@@ -465,7 +465,8 @@ impl Consensus {
         if next_block_height > RANDOMX_KEY_CHANGING_HEIGHT &&
             next_block_height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
         {
-            Ok(rx_keys.1)
+            // Its safe to unwrap here since we know the key has been set
+            Ok(rx_keys.1.unwrap())
         } else {
             Ok(rx_keys.0)
         }

+ 7 - 3
src/validator/mod.rs

@@ -758,6 +758,10 @@ impl Validator {
         // Deploy native wasm contracts
         deploy_native_contracts(&overlay, pow_target).await?;
 
+        // Update the contracts states monotree
+        let diff = overlay.lock().unwrap().overlay.lock().unwrap().diff(&[])?;
+        overlay.lock().unwrap().contracts.update_state_monotree(&diff)?;
+
         // Validate genesis block
         verify_genesis_block(&overlay, &previous, pow_target).await?;
         info!(target: "validator::validate_blockchain", "Genesis block validated successfully!");
@@ -871,7 +875,7 @@ impl Validator {
         let mut blocks_count = self.blockchain.len() as u32;
         info!(target: "validator::rebuild_block_difficulties", "Rebuilding {blocks_count} block difficulties...");
         if blocks_count == 0 {
-            info!(target: "validator::reset_to_height", "Validator block difficulties rebuilt successfully!");
+            info!(target: "validator::rebuild_block_difficulties", "Validator block difficulties rebuilt successfully!");
             return Ok(())
         }
 
@@ -924,7 +928,7 @@ impl Validator {
             // Add difficulty to database
             self.blockchain.blocks.insert_difficulty(&[block_difficulty])?;
 
-            info!(target: "validator::validate_blockchain", "Block {index}/{blocks_count} difficulty added successfully!");
+            info!(target: "validator::rebuild_block_difficulties", "Block {index}/{blocks_count} difficulty added successfully!");
             index += 1;
         }
 
@@ -934,7 +938,7 @@ impl Validator {
         // Release append lock
         drop(append_lock);
 
-        info!(target: "validator::reset_to_height", "Validator block difficulties rebuilt successfully!");
+        info!(target: "validator::rebuild_block_difficulties", "Validator block difficulties rebuilt successfully!");
 
         Ok(())
     }

+ 9 - 5
src/validator/pow.rs

@@ -98,7 +98,7 @@ pub struct PoWModule {
     /// difficulties buffer last.
     pub cumulative_difficulty: BigUint,
     /// Native PoW RandomX VMs current and next keys pair
-    pub darkfi_rx_keys: (HeaderHash, HeaderHash),
+    pub darkfi_rx_keys: (HeaderHash, Option<HeaderHash>),
     /// RandomXFactory for native PoW (Arc from parent)
     pub darkfi_rx_factory: RandomXFactory,
     /// RandomXFactory for Monero PoW (Arc from parent)
@@ -305,7 +305,8 @@ impl PoWModule {
                 let randomx_key = if header.height > RANDOMX_KEY_CHANGING_HEIGHT &&
                     header.height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
                 {
-                    &self.darkfi_rx_keys.1
+                    // Its safe to unwrap here since we know the key has been set
+                    &self.darkfi_rx_keys.1.unwrap()
                 } else {
                     &self.darkfi_rx_keys.0
                 };
@@ -372,13 +373,15 @@ impl PoWModule {
         if header.height.is_multiple_of(RANDOMX_KEY_CHANGING_HEIGHT) {
             let next_key = header.hash();
             let _ = self.darkfi_rx_factory.create(&next_key.inner()[..])?;
-            self.darkfi_rx_keys.1 = next_key;
+            self.darkfi_rx_keys.1 = Some(next_key);
             return Ok(())
         }
 
         // Check if need to rotate keys
         if header.height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY {
-            self.darkfi_rx_keys.0 = self.darkfi_rx_keys.1;
+            // Its safe to unwrap here since we know the key has been set
+            self.darkfi_rx_keys.0 = self.darkfi_rx_keys.1.unwrap();
+            self.darkfi_rx_keys.1 = None;
         }
 
         Ok(())
@@ -410,7 +413,8 @@ impl PoWModule {
         let randomx_key = if header.height > RANDOMX_KEY_CHANGING_HEIGHT &&
             header.height % RANDOMX_KEY_CHANGING_HEIGHT == RANDOMX_KEY_CHANGE_DELAY
         {
-            &self.darkfi_rx_keys.1
+            // Its safe to unwrap here since we know the key has been set
+            &self.darkfi_rx_keys.1.unwrap()
         } else {
             &self.darkfi_rx_keys.0
         };