rpc_blockchain.rs 2.5 KB

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