rpc.rs 5.1 KB

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