iguana_ws/
lib.rs

1use bitcoin_cash::{UnhashedTx, tx_to_json, error::Error};
2
3use tokio::runtime::Runtime;
4use futures::{StreamExt, SinkExt};
5use warp::{Filter, filters::ws::Message};
6use std::sync::RwLock;
7use std::time::Instant;
8use lazy_static::lazy_static;
9
10lazy_static! {
11    static ref JSON: RwLock<String> = RwLock::new("".to_string());
12}
13
14pub fn run_iguana_ws(make_tx: impl Fn() -> Result<UnhashedTx, Error>) {
15    pretty_env_logger::init();
16
17    let t0 = Instant::now();
18    let tx = make_tx().expect("Failed building transaction:");
19    let dt_build_tx = t0.elapsed().as_micros();
20    let t1 = Instant::now();
21    *JSON.write().unwrap() = tx_to_json(&tx).unwrap();
22    let dt_json_tx = t1.elapsed().as_micros();
23
24    println!("dt build: {}ms", dt_build_tx as f64 / 1000.0);
25    println!("dt json: {}ms", dt_json_tx as f64 / 1000.0);
26
27    let mut rt = Runtime::new().expect("Failed setting up runtime");
28
29    rt.block_on(async {
30        let routes = warp::path("tx")
31            .and(warp::ws())
32            .map(|ws: warp::ws::Ws| {
33                ws.on_upgrade(|websocket| {
34                    async {
35                        println!("Sending tx.");
36                        let (mut outgoing, mut incoming) = websocket.split();
37                        let json_text = JSON.read().unwrap().clone();
38                        if let Err(err) = outgoing.send(Message::text(json_text)).await {
39                            eprintln!("Error sending tx: {}", err);
40                        }
41                        while let Some(msg) = incoming.next().await {
42                            println!("got msg: {:?}", msg);
43                        }
44                    }
45                })
46            });
47
48        let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
49        println!("Serving websocket at {}", addr);
50
51        warp::serve(routes).run(addr).await;
52    })
53}