-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathallow_handle.rs
More file actions
486 lines (446 loc) · 15.5 KB
/
allow_handle.rs
File metadata and controls
486 lines (446 loc) · 15.5 KB
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
use std::{
fmt::{Display, Formatter},
str::FromStr,
time::Duration,
};
use crate::{
metrics::{ALLOW_HANDLE_FAIL_COUNTER, ALLOW_HANDLE_SUCCESS_COUNTER},
nonce_managed_provider::NonceManagedProvider,
ops::common::try_into_array,
overprovision_gas_limit::try_overprovision_gas_limit,
REVIEW,
};
use super::TransactionOperation;
use alloy::{
network::{Ethereum, TransactionBuilder},
primitives::{Address, Bytes, FixedBytes},
providers::Provider,
rpc::types::TransactionRequest,
sol,
transports::{RpcError, TransportErrorKind},
};
use anyhow::bail;
use async_trait::async_trait;
use fhevm_engine_common::{tenant_keys::query_tenant_info, types::AllowEvents, utils::compact_hex};
use sqlx::{Pool, Postgres};
use tokio::task::JoinSet;
use tracing::{debug, error, info, warn};
use MultichainACL::MultichainACLErrors;
sol!(
#[sol(rpc)]
MultichainACL,
"artifacts/MultichainACL.sol/MultichainACL.json"
);
struct Key {
handle: Vec<u8>,
account_addr: String,
tenant_id: i32,
event_type: AllowEvents,
}
impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Key {{ handle: {}, account: {}, tenant_id: {}, event_type: {:?} }}",
compact_hex(&self.handle),
self.account_addr,
self.tenant_id,
self.event_type
)
}
}
#[derive(Clone)]
pub struct MultichainACLOperation<P: Provider<Ethereum> + Clone + 'static> {
multichain_acl_address: Address,
provider: NonceManagedProvider<P>,
conf: crate::ConfigSettings,
gas: Option<u64>,
db_pool: Pool<Postgres>,
}
impl<P: Provider<Ethereum> + Clone + 'static> MultichainACLOperation<P> {
/// Sends a transaction
///
/// TODO: Refactor: Avoid code duplication
async fn send_transaction(
&self,
key: &Key,
txn_request: impl Into<TransactionRequest>,
current_limited_retries_count: i32,
current_unlimited_retries_count: i32,
) -> anyhow::Result<()> {
let h = compact_hex(&key.handle);
info!(handle = h, "Processing transaction");
let overprovisioned_txn_req = try_overprovision_gas_limit(
txn_request,
self.provider.inner(),
self.conf.gas_limit_overprovision_percent,
)
.await;
let transaction = match self
.provider
.send_transaction(overprovisioned_txn_req.clone())
.await
{
Ok(txn) => txn,
Err(e) if self.already_allowed_error(&e).is_some() => {
warn!(
address = ?self.already_allowed_error(&e),
handle = h,
"Coprocessor has already added the ACL entry"
);
self.set_txn_is_sent(key, None, None).await?;
return Ok(());
}
// Consider transport retryable errors, BackendGone and local usage errors as something that must be retried infinitely.
// Local usage are included as they might be transient due to external AWS KMS signers.
Err(e)
if matches!(&e, RpcError::Transport(inner) if inner.is_retry_err() || matches!(inner, TransportErrorKind::BackendGone))
|| matches!(&e, RpcError::LocalUsageError(_)) =>
{
ALLOW_HANDLE_FAIL_COUNTER.inc();
warn!(
transaction_request = ?overprovisioned_txn_req,
error = %e,
handle = h,
"Transaction sending failed with unlimited retry error"
);
self.increment_txn_unlimited_retries_count(
key,
&e.to_string(),
current_unlimited_retries_count,
)
.await?;
bail!(e);
}
Err(e) => {
ALLOW_HANDLE_FAIL_COUNTER.inc();
warn!(
transaction_request = ?overprovisioned_txn_req,
error = %e,
handle = h,
"Transaction sending failed"
);
self.increment_txn_limited_retries_count(
key,
&e.to_string(),
current_limited_retries_count,
)
.await?;
bail!(e);
}
};
// We assume that if we were able to send the transaction, we will be able to get a receipt, eventually. If there is a transport
// error in-between, we rely on the retry logic to handle it.
let receipt = match transaction
.with_timeout(Some(Duration::from_secs(
self.conf.txn_receipt_timeout_secs as u64,
)))
.with_required_confirmations(self.conf.required_txn_confirmations as u64)
.get_receipt()
.await
{
Ok(receipt) => receipt,
Err(e) => {
ALLOW_HANDLE_FAIL_COUNTER.inc();
error!(error = %e, "Getting receipt failed");
self.increment_txn_limited_retries_count(
key,
&e.to_string(),
current_limited_retries_count,
)
.await?;
return Err(anyhow::Error::new(e));
}
};
if receipt.status() {
self.set_txn_is_sent(
key,
Some(receipt.transaction_hash.as_slice()),
receipt.block_number.map(|bn| bn as i64),
)
.await?;
info!(
transaction_hash = %receipt.transaction_hash,
key = %key,
"Allow txn succeeded"
);
ALLOW_HANDLE_SUCCESS_COUNTER.inc();
} else {
ALLOW_HANDLE_FAIL_COUNTER.inc();
error!(
transaction_hash = %receipt.transaction_hash,
status = receipt.status(),
handle = h,
"allowAccount txn failed"
);
self.increment_txn_limited_retries_count(
key,
"receipt status = false",
current_limited_retries_count,
)
.await?;
return Err(anyhow::anyhow!(
"Transaction {} failed with status {}, handle: {}",
receipt.transaction_hash,
receipt.status(),
h,
));
}
Ok(())
}
fn already_allowed_error(&self, err: &RpcError<TransportErrorKind>) -> Option<Address> {
err.as_error_resp()
.and_then(|payload| payload.as_decoded_interface_error::<MultichainACLErrors>())
.map(|error| match error {
MultichainACLErrors::CoprocessorAlreadyAllowedAccount(c) => c.txSender, /* coprocessor address */
MultichainACLErrors::CoprocessorAlreadyAllowedPublicDecrypt(c) => c.txSender,
})
}
async fn set_txn_is_sent(
&self,
key: &Key,
txn_hash: Option<&[u8]>,
txn_block_number: Option<i64>,
) -> anyhow::Result<()> {
sqlx::query!(
"UPDATE allowed_handles
SET
txn_is_sent = true,
txn_hash = $1,
txn_block_number = $2
WHERE handle = $3
AND account_address = $4
AND tenant_id = $5",
txn_hash,
txn_block_number,
key.handle,
key.account_addr,
key.tenant_id
)
.execute(&self.db_pool)
.await?;
Ok(())
}
}
impl<P: Provider<Ethereum> + Clone + 'static> MultichainACLOperation<P> {
pub fn new(
multichain_acl_address: Address,
provider: NonceManagedProvider<P>,
conf: crate::ConfigSettings,
gas: Option<u64>,
db_pool: Pool<Postgres>,
) -> Self {
info!(
gas = gas.unwrap_or(0),
multichain_acl_address = %multichain_acl_address,
"Creating MultichainACLOperation"
);
Self {
multichain_acl_address,
provider,
conf,
gas,
db_pool,
}
}
async fn increment_txn_limited_retries_count(
&self,
key: &Key,
err: &str,
current_limited_retries_count: i32,
) -> anyhow::Result<()> {
debug!("Updating retry count for key {}", key);
if current_limited_retries_count == (self.conf.allow_handle_max_retries as i32) - 1 {
error!(
action = REVIEW,
key = %key,
max_retries = self.conf.allow_handle_max_retries,
"Max limited retries reached"
);
} else {
warn!(
limited_reties_count = current_limited_retries_count + 1,
key = %key,
"Updating limited retry count"
);
}
sqlx::query!(
"UPDATE allowed_handles
SET
txn_limited_retries_count = txn_limited_retries_count + 1,
txn_last_error = $1,
txn_last_error_at = NOW()
WHERE handle = $2
AND account_address = $3
AND tenant_id = $4",
err,
key.handle,
key.account_addr,
key.tenant_id
)
.execute(&self.db_pool)
.await?;
Ok(())
}
async fn increment_txn_unlimited_retries_count(
&self,
key: &Key,
err: &str,
current_unlimited_retries_count: i32,
) -> anyhow::Result<()> {
debug!("Updating unlimited retries count, {}", key);
if current_unlimited_retries_count == (self.conf.review_after_unlimited_retries as i32) - 1
{
error!(
action = REVIEW,
unlimited_retries_count = current_unlimited_retries_count,
key = %key,
"Unlimited retries threshold reached"
);
} else {
warn!(
unlimited_retries_count = current_unlimited_retries_count + 1,
key = %key,
"Updating unlimited retries count"
);
}
sqlx::query!(
"UPDATE allowed_handles
SET
txn_unlimited_retries_count = txn_unlimited_retries_count + 1,
txn_last_error = $1,
txn_last_error_at = NOW()
WHERE handle = $2
AND account_address = $3
AND tenant_id = $4",
err,
key.handle,
key.account_addr,
key.tenant_id
)
.execute(&self.db_pool)
.await?;
Ok(())
}
}
#[async_trait]
impl<P> TransactionOperation<P> for MultichainACLOperation<P>
where
P: alloy::providers::Provider<Ethereum> + Clone + 'static,
{
fn channel(&self) -> &str {
&self.conf.allow_handle_db_channel
}
async fn execute(&self) -> anyhow::Result<bool> {
let rows = sqlx::query!(
"
SELECT handle, tenant_id, account_address, event_type, txn_limited_retries_count, txn_unlimited_retries_count
FROM allowed_handles
WHERE txn_is_sent = false
AND txn_limited_retries_count < $1
LIMIT $2;
",
self.conf.allow_handle_max_retries as i32,
self.conf.allow_handle_batch_limit as i32,
)
.fetch_all(&self.db_pool)
.await?;
let multichain_acl = MultichainACL::new(self.multichain_acl_address, self.provider.inner());
info!(rows_count = rows.len(), "Selected rows to process");
let maybe_has_more_work = rows.len() == self.conf.allow_handle_batch_limit as usize;
let mut join_set = JoinSet::new();
for row in rows.into_iter() {
let tenant = match query_tenant_info(&self.db_pool, row.tenant_id).await {
Ok(res) => res,
Err(_) => {
error!(
tenant_id = row.tenant_id,
"Failed to get chain_id for tenant"
);
continue;
}
};
let chain_id = tenant.chain_id;
let handle = row.handle.clone();
let h_as_hex = compact_hex(&handle);
let event_type = match AllowEvents::try_from(row.event_type) {
Ok(event_type) => event_type,
Err(_) => {
error!(
event_type = row.event_type,
tenant_id = row.tenant_id,
"Invalid event_type"
);
continue;
}
};
let account_addr = row.account_address;
info!(
handle = h_as_hex,
event_type = ?event_type,
account = ?account_addr,
chain_id = chain_id,
"Allow handle"
);
let handle_bytes32 = FixedBytes::from(try_into_array::<32>(handle)?);
let extra_data = Bytes::new();
let txn_request = match event_type {
AllowEvents::AllowedForDecryption => {
// Call allowPublicDecrypt when account_address is null
match &self.gas {
Some(gas_limit) => multichain_acl
.allowPublicDecrypt(handle_bytes32, extra_data)
.into_transaction_request()
.with_gas_limit(*gas_limit),
None => multichain_acl
.allowPublicDecrypt(handle_bytes32, extra_data)
.into_transaction_request(),
}
}
AllowEvents::AllowedAccount => {
let address = if let Ok(addr) = Address::from_str(&account_addr) {
addr
} else {
error!(
account_address = ?account_addr,
tenant_id = row.tenant_id,
"Invalid account address"
);
continue;
};
match &self.gas {
Some(gas_limit) => multichain_acl
.allowAccount(handle_bytes32, address, extra_data)
.into_transaction_request()
.with_gas_limit(*gas_limit),
None => multichain_acl
.allowAccount(handle_bytes32, address, extra_data)
.into_transaction_request(),
}
}
};
let handle = row.handle;
let key = Key {
handle,
account_addr: account_addr.to_string(),
tenant_id: row.tenant_id,
event_type,
};
let operation = self.clone();
join_set.spawn(async move {
operation
.send_transaction(
&key,
txn_request,
row.txn_limited_retries_count,
row.txn_unlimited_retries_count,
)
.await
});
}
while let Some(res) = join_set.join_next().await {
res??;
}
Ok(maybe_has_more_work)
}
}