rpc.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. use async_std::sync::{Arc, Mutex};
  2. use async_trait::async_trait;
  3. use log::debug;
  4. use serde_json::{json, Value};
  5. use darkfi::{
  6. event_graph::{
  7. get_current_time,
  8. model::{Event, EventId, ModelPtr},
  9. protocol_event::{SeenPtr, UnreadEvents},
  10. },
  11. net,
  12. rpc::{
  13. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  14. server::RequestHandler,
  15. },
  16. };
  17. use crate::genevent::GenEvent;
  18. pub struct JsonRpcInterface {
  19. _nickname: String,
  20. unread_events: Arc<Mutex<UnreadEvents<GenEvent>>>,
  21. missed_events: Arc<Mutex<Vec<Event<GenEvent>>>>,
  22. model: ModelPtr<GenEvent>,
  23. seen: SeenPtr<EventId>,
  24. p2p: net::P2pPtr,
  25. }
  26. #[async_trait]
  27. impl RequestHandler for JsonRpcInterface {
  28. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  29. if !req.params.is_array() {
  30. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  31. }
  32. match req.method.as_str() {
  33. Some("add") => self.add(req.id, req.params).await,
  34. Some("list") => self.list(req.id, req.params).await,
  35. Some("ping") => self.pong(req.id, req.params).await,
  36. Some("get_info") => self.get_info(req.id, req.params).await,
  37. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  38. }
  39. }
  40. }
  41. impl JsonRpcInterface {
  42. pub fn new(
  43. _nickname: String,
  44. unread_events: Arc<Mutex<UnreadEvents<GenEvent>>>,
  45. missed_events: Arc<Mutex<Vec<Event<GenEvent>>>>,
  46. model: ModelPtr<GenEvent>,
  47. seen: SeenPtr<EventId>,
  48. p2p: net::P2pPtr,
  49. ) -> Self {
  50. Self { _nickname, unread_events, missed_events, model, seen, p2p }
  51. }
  52. // RPCAPI:
  53. // Replies to a ping method.
  54. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  55. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  56. async fn pong(&self, id: Value, _params: Value) -> JsonResult {
  57. JsonResponse::new(json!("pong"), id).into()
  58. }
  59. // RPCAPI:
  60. // Retrieves P2P network information.
  61. // --> {"jsonrpc": "2.0", "method": "get_info", "params": [], "id": 42}
  62. // <-- {"jsonrpc": "2.0", result": {"nodeID": [], "nodeinfo": [], "id": 42}
  63. async fn get_info(&self, id: Value, _params: Value) -> JsonResult {
  64. let resp = self.p2p.get_info().await;
  65. JsonResponse::new(resp, id).into()
  66. }
  67. // RPCAPI:
  68. // Add a new event
  69. // --> {"jsonrpc": "2.0", "method": "add", "params": [], "id": 1}
  70. // <-- {"jsonrpc": "2.0", "result": [nickname, ...], "id": 1}
  71. async fn add(&self, id: Value, params: Value) -> JsonResult {
  72. let genevent = GenEvent {
  73. nick: params[0].get("nick").unwrap().to_string(),
  74. title: params[0].get("title").unwrap().to_string(),
  75. text: params[0].get("text").unwrap().to_string(),
  76. };
  77. let event = Event {
  78. previous_event_hash: self.model.lock().await.get_head_hash(),
  79. action: genevent,
  80. timestamp: get_current_time(),
  81. read_confirms: 0,
  82. };
  83. if !self.seen.push(&event.hash()).await {
  84. let json = json!(false);
  85. return JsonResponse::new(json, id).into()
  86. }
  87. self.unread_events.lock().await.insert(&event);
  88. self.p2p.broadcast(event).await.unwrap();
  89. let json = json!(true);
  90. JsonResponse::new(json, id).into()
  91. }
  92. // RPCAPI:
  93. // List events
  94. // --> {"jsonrpc": "2.0", "method": "list", "params": [], "id": 1}
  95. // <-- {"jsonrpc": "2.0", "result": [task_id, ...], "id": 1}
  96. async fn list(&self, id: Value, _params: Value) -> JsonResult {
  97. debug!("fetching all events");
  98. let msd = self.missed_events.lock().await.clone();
  99. let ser = darkfi_serial::serialize(&msd);
  100. let json = json!(ser);
  101. JsonResponse::new(json, id).into()
  102. }
  103. }