rpc.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 std::time::Instant;
  19. use darkfi::{
  20. rpc::{
  21. client::RpcClient,
  22. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  23. util::JsonValue,
  24. },
  25. system::{ExecutorPtr, Publisher, StoppableTask},
  26. Error, Result,
  27. };
  28. use url::Url;
  29. use crate::DamCli;
  30. impl DamCli {
  31. /// Auxiliary function to ping configured damd daemon for liveness.
  32. pub async fn ping(&self) -> Result<()> {
  33. println!("Executing ping request to damd...");
  34. let latency = Instant::now();
  35. let rep = self.damd_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  36. let latency = latency.elapsed();
  37. println!("Got reply: {rep:?}");
  38. println!("Latency: {latency:?}");
  39. Ok(())
  40. }
  41. /// Auxiliary function to execute a request towards the configured damd daemon JSON-RPC endpoint.
  42. pub async fn damd_daemon_request(&self, method: &str, params: &JsonValue) -> Result<JsonValue> {
  43. let req = JsonRequest::new(method, params.clone());
  44. let rep = self.rpc_client.request(req).await?;
  45. Ok(rep)
  46. }
  47. /// Subscribes to damd's JSON-RPC notification endpoints.
  48. pub async fn subscribe(&self, endpoint: &str, method: &str, ex: &ExecutorPtr) -> Result<()> {
  49. println!("Subscribing to receive notifications for: {method}");
  50. let endpoint = Url::parse(endpoint)?;
  51. let _method = String::from(method);
  52. let publisher = Publisher::new();
  53. let subscription = publisher.clone().subscribe().await;
  54. let _publisher = publisher.clone();
  55. let _ex = ex.clone();
  56. StoppableTask::new().start(
  57. // Weird hack to prevent lifetimes hell
  58. async move {
  59. let rpc_client = RpcClient::new(endpoint, _ex).await?;
  60. let req = JsonRequest::new(&_method, JsonValue::Array(vec![]));
  61. rpc_client.subscribe(req, _publisher).await
  62. },
  63. |res| async move {
  64. match res {
  65. Ok(()) => { /* Do nothing */ }
  66. Err(e) => {
  67. eprintln!("[subscribe] JSON-RPC server error: {e:?}");
  68. publisher
  69. .notify(JsonResult::Error(JsonError::new(
  70. ErrorCode::InternalError,
  71. None,
  72. 0,
  73. )))
  74. .await;
  75. }
  76. }
  77. },
  78. Error::RpcServerStopped,
  79. ex.clone(),
  80. );
  81. println!("Detached subscription to background");
  82. println!("All is good. Waiting for new notifications...");
  83. let e = loop {
  84. match subscription.receive().await {
  85. JsonResult::Notification(n) => {
  86. println!("Got notification from subscription");
  87. if n.method != method {
  88. break Error::UnexpectedJsonRpc(format!(
  89. "Got foreign notification from damd: {}",
  90. n.method
  91. ))
  92. }
  93. // Verify parameters
  94. if !n.params.is_array() {
  95. break Error::UnexpectedJsonRpc(
  96. "Received notification params are not an array".to_string(),
  97. )
  98. }
  99. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  100. if params.is_empty() {
  101. break Error::UnexpectedJsonRpc(
  102. "Notification parameters are empty".to_string(),
  103. )
  104. }
  105. for param in params {
  106. let param = param.get::<String>().unwrap();
  107. println!("Notification: {param}");
  108. }
  109. }
  110. JsonResult::Error(e) => {
  111. // Some error happened in the transmission
  112. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  113. }
  114. x => {
  115. // And this is weird
  116. break Error::UnexpectedJsonRpc(format!(
  117. "Got unexpected data from JSON-RPC: {x:?}"
  118. ))
  119. }
  120. }
  121. };
  122. Err(e)
  123. }
  124. }