rpc_blockchain.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use darkfi_sdk::crypto::MerkleNode;
  2. use log::{debug, error};
  3. use serde_json::{json, Value};
  4. use darkfi::rpc::jsonrpc::{
  5. ErrorCode::{InternalError, InvalidParams},
  6. JsonError, JsonResponse, JsonResult,
  7. };
  8. use super::Darkfid;
  9. use crate::{server_error, RpcError};
  10. impl Darkfid {
  11. // RPCAPI:
  12. // Queries the blockchain database for a block in the given slot.
  13. // Returns a readable block upon success.
  14. //
  15. // --> {"jsonrpc": "2.0", "method": "blockchain.get_slot", "params": [0], "id": 1}
  16. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  17. pub async fn blockchain_get_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  18. if params.len() != 1 || !params[0].is_u64() {
  19. return JsonError::new(InvalidParams, None, id).into()
  20. }
  21. let slot = params[0].as_u64().unwrap();
  22. let validator_state = self.validator_state.read().await;
  23. let blocks = match validator_state.blockchain.get_blocks_by_slot(&[slot]) {
  24. Ok(v) => {
  25. drop(validator_state);
  26. v
  27. }
  28. Err(e) => {
  29. error!("[RPC] blockchain.get_slot: Failed fetching block by slot: {}", e);
  30. return JsonError::new(InternalError, None, id).into()
  31. }
  32. };
  33. if blocks.is_empty() {
  34. return server_error(RpcError::UnknownSlot, id, None)
  35. }
  36. // TODO: Return block as JSON
  37. debug!("{:#?}", blocks[0]);
  38. JsonResponse::new(json!(true), id).into()
  39. }
  40. // RPCAPI:
  41. // Queries the blockchain database for all available merkle roots.
  42. //
  43. // --> {"jsonrpc": "2.0", "method": "blockchain.merkle_roots", "params": [], "id": 1}
  44. // <-- {"jsonrpc": "2.0", "result": [..., ..., ...], "id": 1}
  45. pub async fn blockchain_merkle_roots(&self, id: Value, params: &[Value]) -> JsonResult {
  46. if !params.is_empty() {
  47. return JsonError::new(InvalidParams, None, id).into()
  48. }
  49. let validator_state = self.validator_state.read().await;
  50. let roots: Vec<MerkleNode> = match validator_state.blockchain.merkle_roots.get_all() {
  51. Ok(v) => {
  52. drop(validator_state);
  53. v
  54. }
  55. Err(e) => {
  56. error!("[RPC] blockchain.merkle_roots: Failed fetching merkle roots from rootstore: {}", e);
  57. return JsonError::new(InternalError, None, id).into()
  58. }
  59. };
  60. let roots: Vec<String> = roots.iter().map(|x| x.to_string()).collect();
  61. JsonResponse::new(json!(roots), id).into()
  62. }
  63. }