rpc_blockchain.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. use log::{debug, error};
  2. use serde_json::{json, Value};
  3. use darkfi::rpc::{
  4. jsonrpc,
  5. jsonrpc::{
  6. ErrorCode::{InternalError, InvalidParams},
  7. 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 jsonrpc::error(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 jsonrpc::error(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. jsonrpc::response(json!(true), id).into()
  41. }
  42. }