main.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 darkfi::{
  19. rpc::{
  20. client::RpcClient,
  21. jsonrpc::{JsonRequest, JsonResult},
  22. },
  23. system::{Subscriber, SubscriberPtr},
  24. Result,
  25. };
  26. use futures::join;
  27. use serde_json::json;
  28. use url::Url;
  29. async fn listen(subscriber: SubscriberPtr<JsonResult>) -> Result<()> {
  30. let subscription = subscriber.subscribe().await;
  31. loop {
  32. // Listen subscription for notifications
  33. let notification = subscription.receive().await;
  34. match notification {
  35. JsonResult::Notification(n) => {
  36. println!("Got notification: {:?}", n);
  37. }
  38. JsonResult::Error(e) => {
  39. println!("Client returned an error: {}", serde_json::to_string(&e)?);
  40. break
  41. }
  42. _ => {
  43. println!("Client returned an unexpected reply.");
  44. break
  45. }
  46. }
  47. }
  48. subscription.unsubscribe().await;
  49. Ok(())
  50. }
  51. #[async_std::main]
  52. async fn main() -> Result<()> {
  53. let endpoint = Url::parse("tcp://127.0.0.1:18927")?;
  54. let notif_channel = "blockchain.notify_blocks";
  55. println!("Creating subscriber for channel: {}", notif_channel);
  56. let subscriber: SubscriberPtr<JsonResult> = Subscriber::new();
  57. println!("Creating client for endpoint: {}", endpoint);
  58. let rpc_client = RpcClient::new(endpoint).await?;
  59. println!("Subscribing client");
  60. let req = JsonRequest::new("blockchain.notify_blocks", json!([]));
  61. println!("Starting listening");
  62. let result = join!(listen(subscriber.clone()), rpc_client.subscribe(req, subscriber));
  63. match result.0 {
  64. Ok(_) => {}
  65. Err(e) => println!("Listener failed: {}", e),
  66. }
  67. match result.1 {
  68. Ok(_) => {}
  69. Err(e) => println!("Subscriber failed: {}", e),
  70. }
  71. Ok(())
  72. }