forked from isabella232/fuel-canary-watchtower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathethereum_actions.rs
597 lines (524 loc) · 21 KB
/
ethereum_actions.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use serde::Deserialize;
use anyhow::Result;
use crate::alerter::{send_alert, AlertLevel, AlertParams};
use crate::ethereum_watcher::gateway_contract::GatewayContractTrait;
use crate::ethereum_watcher::portal_contract::PortalContractTrait;
use crate::ethereum_watcher::state_contract::StateContractTrait;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio::task::JoinHandle;
pub static THREAD_CONNECTIONS_ERR: &str = "Connections to the ethereum actions thread have all closed";
#[derive(Deserialize, Clone, PartialEq, Eq, Debug, Default)]
pub enum EthereumAction {
#[default]
None,
PauseState,
PauseGateway,
PausePortal,
PauseAll,
}
#[derive(Clone, Debug)]
pub struct ActionParams {
action: EthereumAction,
alert_level: AlertLevel,
}
impl ActionParams {
pub fn new(action: EthereumAction, alert_level: AlertLevel) -> Self {
ActionParams { action, alert_level }
}
#[cfg(test)]
pub fn is_action_equal(&self, action: EthereumAction) -> bool {
self.action == action
}
#[cfg(test)]
pub fn is_alert_level_equal(&self, alert_level: AlertLevel) -> bool {
self.alert_level == alert_level
}
}
#[derive(Clone)]
pub struct WatchtowerEthereumActions {
action_sender: UnboundedSender<ActionParams>,
action_receiver: Arc<Mutex<UnboundedReceiver<ActionParams>>>,
alert_sender: UnboundedSender<AlertParams>,
state_contract: Arc<dyn StateContractTrait>,
portal_contract: Arc<dyn PortalContractTrait>,
gateway_contract: Arc<dyn GatewayContractTrait>,
}
impl fmt::Debug for WatchtowerEthereumActions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WatchtowerEthereumActions")
.field("action_sender", &self.action_sender)
.field("action_receiver", &self.action_receiver)
.field("alert_sender", &self.alert_sender)
// You can't print `state_contract`, `portal_contract`, `gateway_contract` directly, but you can indicate its presence
.field("state_contract", &"Arc<dyn StateContractTrait>")
.field("portal_contract", &"Arc<dyn PortalContractTrait>")
.field("gateway_contract", &"Arc<dyn GatewayContractTrait>")
.finish()
}
}
impl WatchtowerEthereumActions {
pub fn new(
alert_sender: UnboundedSender<AlertParams>,
state_contract: Arc<dyn StateContractTrait>,
portal_contract: Arc<dyn PortalContractTrait>,
gateway_contract: Arc<dyn GatewayContractTrait>,
) -> Self {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
WatchtowerEthereumActions {
action_sender,
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender,
state_contract,
portal_contract,
gateway_contract,
}
}
pub async fn start_action_handling_thread(&self) -> Result<JoinHandle<()>> {
let action_receiver = Arc::clone(&self.action_receiver);
let alert_sender = self.alert_sender.clone();
let state_contract = Arc::clone(&self.state_contract);
let portal_contract = Arc::clone(&self.portal_contract);
let gateway_contract = Arc::clone(&self.gateway_contract);
let handle = tokio::spawn(async move {
let mut rx = action_receiver.lock().await;
while let Some(params) = rx.recv().await {
Self::handle_action(
params.action,
alert_sender.clone(),
Arc::clone(&state_contract),
Arc::clone(&portal_contract),
Arc::clone(&gateway_contract),
params.alert_level,
)
.await;
}
send_alert(
&alert_sender,
String::from(THREAD_CONNECTIONS_ERR),
String::from(THREAD_CONNECTIONS_ERR),
AlertLevel::Error,
);
});
Ok(handle)
}
async fn pause_contract<F>(
contract_name: &str,
pause_future: F,
alert_sender: UnboundedSender<AlertParams>,
alert_level: AlertLevel,
) where
F: Future<Output = Result<(), anyhow::Error>> + Send,
{
send_alert(
&alert_sender,
format!("Pausing {} contract", contract_name),
format!("Pausing {} contract", contract_name),
AlertLevel::Info,
);
// Set a duration for the timeout
let timeout_duration = Duration::from_secs(30);
match timeout(timeout_duration, pause_future).await {
Ok(Ok(_)) => {
send_alert(
&alert_sender,
format!("Successfully paused {} contract", contract_name),
format!("Successfully paused {} contract", contract_name),
AlertLevel::Info,
);
}
Ok(Err(e)) => {
// This is the case where pause_future completed, but resulted in an error.
send_alert(
&alert_sender,
format!("Failed to pause {} contract", contract_name),
e.to_string(),
alert_level,
);
}
Err(_) => {
// This is the timeout case
send_alert(
&alert_sender,
format!("Timeout while pausing {} contract", contract_name),
format!("Timeout while pausing {} contract", contract_name),
alert_level,
);
}
}
}
async fn handle_action(
action: EthereumAction,
alert_sender: UnboundedSender<AlertParams>,
state_contract: Arc<dyn StateContractTrait>,
portal_contract: Arc<dyn PortalContractTrait>,
gateway_contract: Arc<dyn GatewayContractTrait>,
alert_level: AlertLevel,
) {
match action {
EthereumAction::PauseState => {
Self::pause_contract("state", state_contract.pause(), alert_sender, alert_level).await;
}
EthereumAction::PauseGateway => {
Self::pause_contract("gateway", gateway_contract.pause(), alert_sender, alert_level).await;
}
EthereumAction::PausePortal => {
Self::pause_contract("portal", portal_contract.pause(), alert_sender, alert_level).await;
}
EthereumAction::PauseAll => {
Self::pause_contract(
"state",
state_contract.pause(),
alert_sender.clone(),
alert_level.clone(),
)
.await;
Self::pause_contract(
"gateway",
gateway_contract.pause(),
alert_sender.clone(),
alert_level.clone(),
)
.await;
Self::pause_contract("portal", portal_contract.pause(), alert_sender, alert_level).await;
}
EthereumAction::None => {}
}
}
pub fn get_action_sender(&self) -> UnboundedSender<ActionParams> {
self.action_sender.clone()
}
}
// Utility function to send actions
pub fn send_action(
action_sender: &UnboundedSender<ActionParams>,
action: EthereumAction,
alert_level: Option<AlertLevel>,
) {
let alert_level = alert_level.unwrap_or(AlertLevel::Info);
let params = ActionParams::new(action, alert_level);
if let Err(e) = action_sender.send(params) {
log::error!("Failed to send action: {}", e);
}
}
#[cfg(test)]
mod tests {
use std::pin::Pin;
use super::*;
use tokio::sync::mpsc;
use crate::ethereum_watcher::{
gateway_contract::MockGatewayContractTrait, portal_contract::MockPortalContractTrait,
state_contract::MockStateContractTrait,
};
// Util to help tests
async fn assert_alert_received(
alert_receiver: &mut UnboundedReceiver<AlertParams>,
expected_name: &str,
expected_description: &str,
expected_level: AlertLevel,
) {
// Create the expected alert we will compare the actual one too.
let expected_alert = AlertParams::new(
String::from(expected_name),
String::from(expected_description),
expected_level,
);
if let Some(alert) = alert_receiver.recv().await {
println!("{:?}", alert);
assert_eq!(alert, expected_alert);
} else {
panic!("Expected alert not received");
}
}
#[tokio::test]
async fn test_handle_pause_state_action() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract: MockStateContractTrait = MockStateContractTrait::new();
let mut mock_portal_contract: MockPortalContractTrait = MockPortalContractTrait::new();
let mut mock_gateway_contract: MockGatewayContractTrait = MockGatewayContractTrait::new();
// Mock the behavior of the pause function
mock_state_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
mock_portal_contract.expect_pause().times(0);
mock_gateway_contract.expect_pause().times(0);
// Create an instance of WatchtowerEthereumActions
let actions = WatchtowerEthereumActions {
action_sender: action_sender.clone(),
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender: alert_sender.clone(),
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
// Start the action handling thread
let _ = actions.start_action_handling_thread().await;
send_action(&action_sender, EthereumAction::PauseState, Some(AlertLevel::Info));
assert_alert_received(
&mut alert_receiver,
"Pausing state contract",
"Pausing state contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused state contract",
"Successfully paused state contract",
AlertLevel::Info,
)
.await;
}
#[tokio::test]
async fn test_pause_state_contract_timeout() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract: MockStateContractTrait = MockStateContractTrait::new();
let mut mock_portal_contract: MockPortalContractTrait = MockPortalContractTrait::new();
let mut mock_gateway_contract: MockGatewayContractTrait = MockGatewayContractTrait::new();
// Mock the behavior of the pause function to never complete
mock_state_contract.expect_pause().times(1).returning(|| {
Box::pin(async {
// Simulate a long-running future that does not resolve within the test
let pending_future: Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + Send>> = Box::pin(async {
tokio::time::sleep(Duration::from_secs(60)).await;
Ok(())
});
pending_future.await
})
});
mock_portal_contract.expect_pause().times(0);
mock_gateway_contract.expect_pause().times(0);
// Create an instance of WatchtowerEthereumActions
let actions = WatchtowerEthereumActions {
action_sender: action_sender.clone(),
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender: alert_sender.clone(),
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
// Start the action handling thread
let _ = actions.start_action_handling_thread().await;
// Send a PauseState action
send_action(&action_sender, EthereumAction::PauseState, Some(AlertLevel::Error));
assert_alert_received(
&mut alert_receiver,
"Pausing state contract",
"Pausing state contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Timeout while pausing state contract",
"Timeout while pausing state contract",
AlertLevel::Error,
)
.await;
}
#[tokio::test]
async fn test_pause_state_contract_with_error_response() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract = MockStateContractTrait::new();
let mock_portal_contract: MockPortalContractTrait = MockPortalContractTrait::new();
let mock_gateway_contract: MockGatewayContractTrait = MockGatewayContractTrait::new();
// Mock the pause function to return an error
// Mock the pause function to return an error
mock_state_contract.expect_pause().times(1).returning(|| {
Box::pin(async {
Err(anyhow::Error::msg("Mock pause error")) // Create a new error instance here
})
});
let actions = WatchtowerEthereumActions {
action_sender,
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender,
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
let _ = actions.start_action_handling_thread().await;
// Send a PauseState action
send_action(
&actions.action_sender,
EthereumAction::PauseState,
Some(AlertLevel::Error),
);
assert_alert_received(
&mut alert_receiver,
"Pausing state contract",
"Pausing state contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Failed to pause state contract",
"Mock pause error",
AlertLevel::Error,
)
.await;
}
#[tokio::test]
async fn test_handle_pause_gateway_action() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract: MockStateContractTrait = MockStateContractTrait::new();
let mut mock_portal_contract: MockPortalContractTrait = MockPortalContractTrait::new();
let mut mock_gateway_contract: MockGatewayContractTrait = MockGatewayContractTrait::new();
// Mock the behavior of the pause function
mock_state_contract.expect_pause().times(0);
mock_portal_contract.expect_pause().times(0);
mock_gateway_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
let actions = WatchtowerEthereumActions {
action_sender: action_sender.clone(),
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender: alert_sender.clone(),
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
let _ = actions.start_action_handling_thread().await;
send_action(&action_sender, EthereumAction::PauseGateway, Some(AlertLevel::Info));
assert_alert_received(
&mut alert_receiver,
"Pausing gateway contract",
"Pausing gateway contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused gateway contract",
"Successfully paused gateway contract",
AlertLevel::Info,
)
.await;
}
#[tokio::test]
async fn test_handle_pause_portal_action() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract: MockStateContractTrait = MockStateContractTrait::new();
let mut mock_portal_contract: MockPortalContractTrait = MockPortalContractTrait::new();
let mut mock_gateway_contract: MockGatewayContractTrait = MockGatewayContractTrait::new();
// Mock the behavior of the pause function
mock_state_contract.expect_pause().times(0);
mock_portal_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
mock_gateway_contract.expect_pause().times(0);
let actions = WatchtowerEthereumActions {
action_sender: action_sender.clone(),
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender: alert_sender.clone(),
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
let _ = actions.start_action_handling_thread().await;
send_action(&action_sender, EthereumAction::PausePortal, Some(AlertLevel::Info));
assert_alert_received(
&mut alert_receiver,
"Pausing portal contract",
"Pausing portal contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused portal contract",
"Successfully paused portal contract",
AlertLevel::Info,
)
.await;
}
#[tokio::test]
async fn test_handle_pause_all_action() {
let (action_sender, action_receiver) = mpsc::unbounded_channel::<ActionParams>();
let (alert_sender, mut alert_receiver) = mpsc::unbounded_channel::<AlertParams>();
let mut mock_state_contract = MockStateContractTrait::new();
let mut mock_portal_contract = MockPortalContractTrait::new();
let mut mock_gateway_contract = MockGatewayContractTrait::new();
// Mock the behavior of the pause function for all contracts
mock_state_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
mock_portal_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
mock_gateway_contract
.expect_pause()
.times(1)
.returning(|| Box::pin(async { Ok(()) }));
let actions = WatchtowerEthereumActions {
action_sender,
action_receiver: Arc::new(Mutex::new(action_receiver)),
alert_sender,
state_contract: Arc::new(mock_state_contract),
portal_contract: Arc::new(mock_portal_contract),
gateway_contract: Arc::new(mock_gateway_contract),
};
let _ = actions.start_action_handling_thread().await;
// Send a PauseAll action
send_action(&actions.action_sender, EthereumAction::PauseAll, Some(AlertLevel::Info));
// Verify alerts for pausing each contract
assert_alert_received(
&mut alert_receiver,
"Pausing state contract",
"Pausing state contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused state contract",
"Successfully paused state contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Pausing gateway contract",
"Pausing gateway contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused gateway contract",
"Successfully paused gateway contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Pausing portal contract",
"Pausing portal contract",
AlertLevel::Info,
)
.await;
assert_alert_received(
&mut alert_receiver,
"Successfully paused portal contract",
"Successfully paused portal contract",
AlertLevel::Info,
)
.await;
}
}