taceo-nodes-common 0.7.0

Collection of common functions used by nodes in our MPC networks
Documentation
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
use std::{
    collections::VecDeque,
    pin::Pin,
    sync::{
        Arc, Mutex,
        atomic::{AtomicUsize, Ordering},
    },
    task::{Context, Poll},
    time::Duration,
};

use alloy::{
    node_bindings::{Anvil, AnvilInstance},
    providers::Provider,
    transports::{
        RpcError, TransportErrorKind,
        http::reqwest::{self, Url},
    },
};
use axum::{
    Router,
    body::{Body, Bytes, HttpBody},
    extract::State,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
};
use http_body::Frame;
use tokio::net::TcpListener;

use crate::{
    Environment,
    web3::{HttpRpcProvider, HttpRpcProviderBuilder, HttpRpcProviderConfig},
};

#[derive(Debug)]
enum HttpRpcAction {
    Respond {
        status: u16,
        response_body: &'static str,
        delay: Duration,
    },
    Timeout {
        delay: Duration,
    },
    CloseConnection,
}

#[derive(Debug)]
struct HttpRpcStep {
    expected_method: &'static str,
    action: HttpRpcAction,
}

impl HttpRpcStep {
    fn ok(expected_method: &'static str, response_body: &'static str) -> Self {
        Self {
            expected_method,
            action: HttpRpcAction::Respond {
                status: 200,
                response_body,
                delay: Duration::ZERO,
            },
        }
    }

    fn status(expected_method: &'static str, status: u16, response_body: &'static str) -> Self {
        Self {
            expected_method,
            action: HttpRpcAction::Respond {
                status,
                response_body,
                delay: Duration::ZERO,
            },
        }
    }

    fn close_connection(expected_method: &'static str) -> Self {
        Self {
            expected_method,
            action: HttpRpcAction::CloseConnection,
        }
    }

    fn timeout(expected_method: &'static str, delay: Duration) -> Self {
        Self {
            expected_method,
            action: HttpRpcAction::Timeout { delay },
        }
    }

    fn with_delay(mut self, delay: Duration) -> Self {
        if let HttpRpcAction::Respond {
            delay: step_delay, ..
        } = &mut self.action
        {
            *step_delay = delay;
        } else {
            panic!("only response steps can be delayed");
        }
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WithWallet {
    Yes,
    No,
}

pub(crate) fn http_fixture(with_wallet: WithWallet) -> (AnvilInstance, HttpRpcProvider) {
    let anvil = Anvil::new().spawn();
    let mut http_provider_builder = HttpRpcProviderBuilder::with_config(
        &HttpRpcProviderConfig::with_default_values([anvil.endpoint_url()])
            .expect("anvil endpoint URL is always valid"),
    )
    .environment(Environment::Dev);
    if with_wallet == WithWallet::Yes {
        http_provider_builder =
            http_provider_builder.wallet(anvil.wallet().expect("anvil should have a wallet"));
    }
    let http_provider = http_provider_builder
        .chain_id(31_337)
        .build()
        .expect("Should be able to configure HTTP provider for local anvil");
    (anvil, http_provider)
}

fn retry_policy_config(max_times: usize) -> super::RetryPolicyConfig {
    super::RetryPolicyConfig {
        min_delay: Duration::from_millis(1),
        max_delay: Duration::from_millis(1),
        max_times,
    }
}

fn build_test_http_provider(
    http_urls: Vec<Url>,
    timeout: Duration,
    retry_policy_config: super::RetryPolicyConfig,
) -> HttpRpcProvider {
    let mut config =
        HttpRpcProviderConfig::with_default_values(http_urls).expect("test URLs are always valid");
    config.timeout = timeout;
    config.retry_policy_config = retry_policy_config;
    HttpRpcProviderBuilder::with_config(&config)
        .environment(Environment::Dev)
        .build()
        .expect("HTTP provider should build")
}

async fn wait_for_count(counter: &AtomicUsize, expected: usize) {
    tokio::time::timeout(Duration::from_secs(1), async {
        while counter.load(Ordering::SeqCst) < expected {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("timed out waiting for expected count");
}

#[derive(Debug)]
struct ErrorBody {
    has_failed: bool,
}

impl HttpBody for ErrorBody {
    type Data = Bytes;
    type Error = std::io::Error;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        if self.has_failed {
            Poll::Ready(None)
        } else {
            self.has_failed = true;
            Poll::Ready(Some(Err(std::io::Error::other(
                "simulated transport abort",
            ))))
        }
    }
}

#[derive(Debug)]
struct HttpRpcServerState {
    steps: Mutex<VecDeque<HttpRpcStep>>,
    request_count: Arc<AtomicUsize>,
}

#[derive(Debug)]
struct HttpRpcServer {
    url: Url,
    request_count: Arc<AtomicUsize>,
    task: tokio::task::JoinHandle<()>,
}

impl HttpRpcServer {
    fn url(&self) -> Url {
        self.url.clone()
    }

    fn request_count(&self) -> &Arc<AtomicUsize> {
        &self.request_count
    }
}

impl Drop for HttpRpcServer {
    fn drop(&mut self) {
        self.task.abort();
    }
}

async fn handle_http_rpc(State(state): State<Arc<HttpRpcServerState>>, request: Bytes) -> Response {
    let request = String::from_utf8(request.to_vec()).expect("request should be valid UTF-8");
    let step = {
        let mut steps = state
            .steps
            .lock()
            .expect("server state should not be poisoned");
        steps
            .pop_front()
            .expect("server received more requests than configured")
    };

    state.request_count.fetch_add(1, Ordering::SeqCst);
    assert!(
        request.contains(step.expected_method),
        "expected method {} in request {request}",
        step.expected_method
    );

    match step.action {
        HttpRpcAction::Respond {
            status,
            response_body,
            delay,
        } => {
            if !delay.is_zero() {
                tokio::time::sleep(delay).await;
            }
            (
                StatusCode::from_u16(status).expect("status should be valid"),
                response_body,
            )
                .into_response()
        }
        HttpRpcAction::Timeout { delay } => {
            tokio::time::sleep(delay).await;
            StatusCode::NO_CONTENT.into_response()
        }
        HttpRpcAction::CloseConnection => Response::new(Body::new(ErrorBody { has_failed: false })),
    }
}

async fn spawn_http_rpc_server(steps: impl IntoIterator<Item = HttpRpcStep>) -> HttpRpcServer {
    let listener = TcpListener::bind(("127.0.0.1", 0))
        .await
        .expect("listener should bind");
    let url = Url::parse(&format!(
        "http://{}",
        listener
            .local_addr()
            .expect("listener should have a local address")
    ))
    .expect("listener URL should parse");
    let request_count = Arc::new(AtomicUsize::new(0));
    let state = Arc::new(HttpRpcServerState {
        steps: Mutex::new(steps.into_iter().collect::<VecDeque<_>>()),
        request_count: Arc::clone(&request_count),
    });
    let app = Router::new()
        .route("/", post(handle_http_rpc))
        .with_state(state);
    let task = tokio::spawn(async move {
        axum::serve(listener, app)
            .await
            .expect("server should serve requests");
    });

    HttpRpcServer {
        url,
        request_count,
        task,
    }
}

#[tokio::test]
async fn http_provider_retries_json_rpc_error_then_succeeds() {
    let server = spawn_http_rpc_server([
        HttpRpcStep::ok(
            "eth_blockNumber",
            r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32007,"message":"100/second request limit reached - reduce calls per second"}}"#,
        ),
        HttpRpcStep::ok("eth_blockNumber", r#"{"jsonrpc":"2.0","id":1,"result":"0x1"}"#),
    ])
    .await;
    let provider = build_test_http_provider(
        vec![server.url()],
        Duration::from_secs(1),
        retry_policy_config(1),
    );

    let block_number = provider
        .get_block_number()
        .await
        .expect("retryable JSON-RPC error should be retried");

    assert_eq!(block_number, 1);
    assert_eq!(server.request_count().load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn http_provider_does_not_retry_non_retryable_json_rpc_error() {
    let server = spawn_http_rpc_server([HttpRpcStep::ok(
        "eth_blockNumber",
        r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params"}}"#,
    )])
    .await;
    let provider = build_test_http_provider(
        vec![server.url()],
        Duration::from_secs(1),
        retry_policy_config(1),
    );

    let error = provider
        .get_block_number()
        .await
        .expect_err("non-retryable JSON-RPC error should fail immediately");

    assert!(matches!(error, RpcError::ErrorResp(err) if err.code == -32602));
    assert_eq!(server.request_count().load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn http_provider_retries_408_502_504() {
    for status in [408, 502, 504] {
        let server = spawn_http_rpc_server([
            HttpRpcStep::status("eth_blockNumber", status, ""),
            HttpRpcStep::ok(
                "eth_blockNumber",
                r#"{"jsonrpc":"2.0","id":1,"result":"0x1"}"#,
            ),
        ])
        .await;
        let provider = build_test_http_provider(
            vec![server.url()],
            Duration::from_secs(1),
            retry_policy_config(1),
        );

        let block_number = provider
            .get_block_number()
            .await
            .unwrap_or_else(|error| panic!("status {status} should be retried: {error:?}"));

        assert_eq!(block_number, 1);
        assert_eq!(server.request_count().load(Ordering::SeqCst), 2);
    }
}

#[tokio::test]
async fn http_provider_does_not_retry_500() {
    let server = spawn_http_rpc_server([HttpRpcStep::status(
        "eth_blockNumber",
        500,
        "internal error",
    )])
    .await;
    let provider = build_test_http_provider(
        vec![server.url()],
        Duration::from_secs(1),
        retry_policy_config(1),
    );

    let error = provider
        .get_block_number()
        .await
        .expect_err("HTTP 500 should not be retried");

    assert!(matches!(
        error,
        RpcError::Transport(TransportErrorKind::HttpError(http_error)) if http_error.status == 500
    ));
    assert_eq!(server.request_count().load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn http_provider_prefers_slower_success_over_fast_json_rpc_error() {
    let fast_error_server = spawn_http_rpc_server([HttpRpcStep::ok(
        "eth_blockNumber",
        r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params"}}"#,
    )
    .with_delay(Duration::from_millis(1))])
    .await;
    let slow_success_server = spawn_http_rpc_server([HttpRpcStep::ok(
        "eth_blockNumber",
        r#"{"jsonrpc":"2.0","id":1,"result":"0x2"}"#,
    )
    .with_delay(Duration::from_millis(25))])
    .await;
    let provider = build_test_http_provider(
        vec![fast_error_server.url(), slow_success_server.url()],
        Duration::from_secs(1),
        retry_policy_config(1),
    );

    let block_number = provider
        .get_block_number()
        .await
        .expect("fallback should ignore JSON-RPC error responses and wait for success");

    assert_eq!(block_number, 2);
    assert_eq!(fast_error_server.request_count().load(Ordering::SeqCst), 1);
    assert_eq!(
        slow_success_server.request_count().load(Ordering::SeqCst),
        1
    );
}

#[tokio::test]
async fn http_provider_retries_timeout_custom_error() {
    let server = spawn_http_rpc_server([
        HttpRpcStep::timeout("eth_blockNumber", Duration::from_secs(1)),
        HttpRpcStep::timeout("eth_blockNumber", Duration::from_secs(1)),
    ])
    .await;
    let provider = build_test_http_provider(
        vec![server.url()],
        Duration::from_millis(50),
        retry_policy_config(1),
    );

    let error = provider
        .get_block_number()
        .await
        .expect_err("request should time out after the configured retries");

    assert!(matches!(
        error,
        RpcError::Transport(kind)
            if kind
                .as_custom()
                .and_then(|error| error.downcast_ref::<reqwest::Error>())
                .is_some_and(reqwest::Error::is_timeout)
    ));
    wait_for_count(server.request_count().as_ref(), 2).await;
}

#[tokio::test]
async fn http_provider_does_not_retry_non_timeout_custom_error() {
    let server = spawn_http_rpc_server([HttpRpcStep::close_connection("eth_blockNumber")]).await;
    let provider = build_test_http_provider(
        vec![server.url()],
        Duration::from_secs(1),
        retry_policy_config(1),
    );

    let error = provider
        .get_block_number()
        .await
        .expect_err("non-timeout custom errors should not be retried");

    assert!(matches!(
        error,
        RpcError::Transport(kind)
            if kind
                .as_custom()
                .and_then(|error| error.downcast_ref::<reqwest::Error>())
                .is_some_and(|error| !error.is_timeout())
    ));
    assert_eq!(server.request_count().load(Ordering::SeqCst), 1);
}