-
Notifications
You must be signed in to change notification settings - Fork 13
/
webhook.rs
233 lines (204 loc) · 6.71 KB
/
webhook.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use {
relay_client::{
http::{Client, WatchRegisterRequest},
ConnectionOptions,
},
relay_rpc::{
auth::{ed25519_dalek::SigningKey, AuthToken},
domain::{DecodedClientId, Topic},
jwt::VerifyableClaims,
rpc,
},
std::{
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
time::Duration,
},
structopt::StructOpt,
tokio::{sync::mpsc, task::JoinHandle},
url::Url,
warp::Filter,
};
#[derive(StructOpt)]
struct Args {
/// Specify HTTP address.
#[structopt(short, long, default_value = "https://relay.walletconnect.com/rpc")]
address: String,
/// Specify WalletConnect project ID.
#[structopt(short, long, default_value = "3cbaa32f8fbf3cdcc87d27ca1fa68069")]
project_id: String,
/// Webhook server port.
#[structopt(short, long, default_value = "10100")]
webhook_server_port: u16,
}
fn create_conn_opts(key: &SigningKey, address: &str, project_id: &str) -> ConnectionOptions {
let aud = Url::parse(address)
.unwrap()
.origin()
.unicode_serialization();
let auth = AuthToken::new("http://example.com")
.aud(aud)
.ttl(Duration::from_secs(60 * 60))
.as_jwt(key)
.unwrap();
ConnectionOptions::new(project_id, auth).with_address(address)
}
#[derive(Debug)]
pub struct WebhookData {
pub url: String,
pub payload: rpc::WatchWebhookPayload,
}
pub struct WebhookServer {
addr: SocketAddr,
handle: JoinHandle<()>,
payload_rx: mpsc::UnboundedReceiver<WebhookData>,
}
impl WebhookServer {
pub fn new(port: u16) -> Self {
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into();
let (payload_tx, payload_rx) = mpsc::unbounded_channel();
let handle = tokio::spawn(mock_webhook_server(addr, payload_tx));
Self {
addr,
handle,
payload_rx,
}
}
pub fn url(&self) -> String {
format!("http://{}", self.addr)
}
pub async fn recv(&mut self) -> WebhookData {
self.payload_rx.recv().await.unwrap()
}
}
impl Drop for WebhookServer {
fn drop(&mut self) {
self.handle.abort();
}
}
async fn mock_webhook_server(addr: SocketAddr, payload_tx: mpsc::UnboundedSender<WebhookData>) {
let routes = warp::post()
.and(warp::path::tail())
.and(warp::body::json())
.and(warp::any().map(move || payload_tx.clone()))
.then(
move |path: warp::path::Tail,
payload: rpc::WatchWebhookPayload,
payload_tx: mpsc::UnboundedSender<WebhookData>| async move {
let url = format!("http://{addr}/{}", path.as_str());
payload_tx.send(WebhookData { url, payload }).unwrap();
warp::reply()
},
);
warp::serve(routes).run(addr).await;
}
/// Note: This example will only work with a locally running relay, since it
/// requires access to the local HTTP server.
#[tokio::main]
async fn main() -> anyhow::Result<()> {
const PUB_WH_PATH: &str = "/publisher_webhook";
const SUB_WH_PATH: &str = "/subscriber_webhook";
let args = Args::from_args();
let mut server = WebhookServer::new(args.webhook_server_port);
let server_url = server.url();
// Give time for the server to start up.
tokio::time::sleep(Duration::from_millis(500)).await;
let publisher_key = SigningKey::generate(&mut rand::thread_rng());
let publisher = Client::new(&create_conn_opts(
&publisher_key,
&args.address,
&args.project_id,
))?;
println!(
"[publisher] client id: {}",
DecodedClientId::from(publisher_key.verifying_key()).to_did_key()
);
let subscriber_key = SigningKey::generate(&mut rand::thread_rng());
let subscriber = Client::new(&create_conn_opts(
&subscriber_key,
&args.address,
&args.project_id,
))?;
println!(
"[subscriber] client id: {}",
DecodedClientId::from(subscriber_key.verifying_key()).to_did_key()
);
let topic = Topic::generate();
let message: Arc<str> = Arc::from("Hello WalletConnect!");
let sub_relay_id: DecodedClientId = subscriber
.watch_register(
WatchRegisterRequest {
service_url: server_url.clone(),
webhook_url: format!("{}{}", server_url, SUB_WH_PATH),
watch_type: rpc::WatchType::Subscriber,
tags: vec![1100],
statuses: vec![rpc::WatchStatus::Queued],
ttl: Duration::from_secs(600),
},
&subscriber_key,
)
.await
.unwrap()
.relay_id
.into();
subscriber.subscribe(topic.clone()).await.unwrap();
println!(
"[subscriber] watch registered: relay_id={}",
sub_relay_id.to_did_key()
);
let pub_relay_id: DecodedClientId = publisher
.watch_register(
WatchRegisterRequest {
service_url: server_url.clone(),
webhook_url: format!("{}{}", server_url, PUB_WH_PATH),
watch_type: rpc::WatchType::Publisher,
tags: vec![1100],
statuses: vec![rpc::WatchStatus::Accepted],
ttl: Duration::from_secs(600),
},
&publisher_key,
)
.await
.unwrap()
.relay_id
.into();
println!(
"[publisher] watch registered: relay_id={}",
pub_relay_id.to_did_key()
);
publisher
.publish(
topic.clone(),
message.clone(),
None,
1100,
Duration::from_secs(30),
false,
)
.await
.unwrap();
println!("[publisher] message published: topic={topic} message={message}");
tokio::time::sleep(Duration::from_secs(1)).await;
let messages = subscriber.fetch(topic).await?.messages;
let message = messages
.first()
.ok_or(anyhow::anyhow!("fetch did not return any messages"))?;
println!("[subscriber] received message: {}", message.message);
let pub_data = server.recv().await;
let decoded =
rpc::WatchEventClaims::try_from_str(pub_data.payload.event_auth.first().unwrap()).unwrap();
let decoded_json = serde_json::to_string_pretty(&decoded).unwrap();
println!(
"[webhook] publisher: url={} data={}",
pub_data.url, decoded_json
);
let sub_data = server.recv().await;
let decoded =
rpc::WatchEventClaims::try_from_str(sub_data.payload.event_auth.first().unwrap()).unwrap();
let decoded_json = serde_json::to_string_pretty(&decoded).unwrap();
println!(
"[webhook] subscriber: url={} data={}",
sub_data.url, decoded_json
);
Ok(())
}