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

darkfid: Add RPC endpoint to fetch block difficulty

x 6 месяцев назад
Родитель
Сommit
6d5aaff7df
2 измененных файлов с 40 добавлено и 0 удалено
  1. 39 0
      bin/darkfid/src/rpc/blockchain.rs
  2. 1 0
      bin/darkfid/src/rpc/mod.rs

+ 39 - 0
bin/darkfid/src/rpc/blockchain.rs

@@ -125,6 +125,45 @@ impl DarkfiNode {
         JsonResponse::new(JsonValue::String(tx_enc), id).into()
     }
 
+    // RPCAPI:
+    // Queries the blockchain database to fetch the difficulty and cumulative
+    // difficulty for a specific block height.
+    //
+    // **Params:**
+    // * `array[0]`: Block height
+    //
+    // **Returns:**
+    // * `difficulty`: Block difficulty as integer
+    // * `cumulative_difficulty`: Cumulative block difficulty as integer
+    //
+    // --> {"jsonrpc": "2.0", "method": "blockchain.get_difficulty", "params": [1], "id": 1}
+    // <-- {"jsonrpc": "2.0", "result": [123, 456], "id": 1}
+    pub async fn blockchain_get_difficulty(&self, id: u16, params: JsonValue) -> JsonResult {
+        let Some(params) = params.get::<Vec<JsonValue>>() else {
+            return JsonError::new(InvalidParams, None, id).into()
+        };
+        if params.len() != 1 || !params[0].is_number() {
+            return JsonError::new(InvalidParams, None, id).into()
+        }
+
+        let height = *params[0].get::<f64>().unwrap() as u32;
+
+        if height == 0 {
+            return JsonResponse::new(JsonValue::Array(vec![1_f64.into(), 1_f64.into()]), id).into()
+        }
+
+        let Ok(diff) = self.validator.blockchain.blocks.get_difficulty(&[height], true) else {
+            return server_error(RpcError::UnknownBlockHeight, id, None)
+        };
+
+        let block_diff = diff[0].clone().unwrap();
+
+        let difficulty: f64 = block_diff.difficulty.to_string().parse().unwrap();
+        let cumulative: f64 = block_diff.cumulative_difficulty.to_string().parse().unwrap();
+
+        JsonResponse::new(JsonValue::Array(vec![difficulty.into(), cumulative.into()]), id).into()
+    }
+
     // RPCAPI:
     // Queries the blockchain database to find the last confirmed block.
     //

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

@@ -71,6 +71,7 @@ impl RequestHandler<DefaultRpcHandler> 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.get_difficulty" => self.blockchain_get_difficulty(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,