rpc_blockchain.rs 2.2 KB

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