rpc.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use serde_json::{json, Value};
  19. use url::Url;
  20. use darkfi::{
  21. error::Result,
  22. rpc::{client::RpcClient, jsonrpc::JsonRequest},
  23. };
  24. use crate::error::{DnetViewError, DnetViewResult};
  25. pub struct RpcConnect {
  26. pub name: String,
  27. pub rpc_client: RpcClient,
  28. }
  29. impl RpcConnect {
  30. pub async fn new(url: Url, name: String) -> Result<Self> {
  31. let rpc_client = RpcClient::new(url).await?;
  32. Ok(Self { name, rpc_client })
  33. }
  34. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  35. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  36. pub async fn ping(&self) -> Result<Value> {
  37. let req = JsonRequest::new("ping", json!([]));
  38. self.rpc_client.request(req).await
  39. }
  40. // --> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  41. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  42. pub async fn get_info(&self) -> DnetViewResult<Value> {
  43. let req = JsonRequest::new("get_info", json!([]));
  44. match self.rpc_client.request(req).await {
  45. Ok(req) => Ok(req),
  46. Err(e) => Err(DnetViewError::Darkfi(e)),
  47. }
  48. }
  49. // Returns all lilith node spawned networks names with their node addresses.
  50. // --> {"jsonrpc": "2.0", "method": "spawns", "params": [], "id": 42}
  51. // <-- {"jsonrpc": "2.0", "result": "{spawns}", "id": 42}
  52. pub async fn lilith_spawns(&self) -> DnetViewResult<Value> {
  53. let req = JsonRequest::new("spawns", json!([]));
  54. match self.rpc_client.request(req).await {
  55. Ok(req) => Ok(req),
  56. Err(e) => Err(DnetViewError::Darkfi(e)),
  57. }
  58. }
  59. }