rpc_blockchain.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // --> {"jsonrpc": "2.0", "method": "blockchain.get_slot", "params": [0], "id": 1}
  17. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  18. pub async fn get_slot(&self, id: Value, params: &[Value]) -> JsonResult {
  19. if params.len() != 1 || !params[0].is_u64() {
  20. return JsonError::new(InvalidParams, None, id).into()
  21. }
  22. let blocks = match self
  23. .validator_state
  24. .read()
  25. .await
  26. .blockchain
  27. .get_blocks_by_slot(&[params[0].as_u64().unwrap()])
  28. {
  29. Ok(v) => v,
  30. Err(e) => {
  31. error!("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)
  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. // --> {"jsonrpc": "2.0", "method": "blockchain.merkle_roots", "params": [], "id": 1}
  45. // <-- {"jsonrpc": "2.0", "result": [..., ..., ...], "id": 1}
  46. pub async fn merkle_roots(&self, id: Value, _params: &[Value]) -> JsonResult {
  47. let roots: Vec<MerkleNode> =
  48. match self.validator_state.read().await.blockchain.merkle_roots.get_all() {
  49. Ok(v) => v,
  50. Err(e) => {
  51. error!("Failed getting merkle roots from rootstore: {}", e);
  52. return JsonError::new(InternalError, None, id).into()
  53. }
  54. };
  55. JsonResponse::new(json!(roots), id).into()
  56. }
  57. }