-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathtx.rs
More file actions
470 lines (407 loc) · 15.2 KB
/
tx.rs
File metadata and controls
470 lines (407 loc) · 15.2 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
use crate::TempoInvalidTransaction;
use alloy_consensus::{EthereumTxEnvelope, TxEip4844, Typed2718, crypto::secp256k1};
use alloy_evm::{FromRecoveredTx, FromTxWithEncoded, IntoTxEnv};
use alloy_primitives::{Address, B256, Bytes, TxKind, U256};
use reth_evm::TransactionEnv;
use revm::context::{
Transaction, TxEnv,
either::Either,
result::InvalidTransaction,
transaction::{
AccessList, AccessListItem, RecoveredAuthority, RecoveredAuthorization, SignedAuthorization,
},
};
use tempo_primitives::{
AASigned, TempoSignature, TempoTransaction, TempoTxEnvelope,
transaction::{
Call, RecoveredTempoAuthorization, SignedKeyAuthorization, calc_gas_balance_spending,
},
};
/// Tempo transaction environment for AA features.
#[derive(Debug, Clone, Default)]
pub struct TempoBatchCallEnv {
/// Signature bytes for Tempo transactions
pub signature: TempoSignature,
/// validBefore timestamp
pub valid_before: Option<u64>,
/// validAfter timestamp
pub valid_after: Option<u64>,
/// Multiple calls for Tempo transactions
pub aa_calls: Vec<Call>,
/// Authorization list (EIP-7702 with Tempo signatures)
///
/// Each authorization lazily recovers the authority on first access and caches the result.
/// The signature is preserved for gas calculation.
pub tempo_authorization_list: Vec<RecoveredTempoAuthorization>,
/// Nonce key for 2D nonce system
pub nonce_key: U256,
/// Whether the transaction is a subblock transaction.
pub subblock_transaction: bool,
/// Optional key authorization for provisioning access keys
pub key_authorization: Option<SignedKeyAuthorization>,
/// Transaction signature hash (for signature verification)
pub signature_hash: B256,
/// Optional access key ID override for gas estimation.
/// When provided in eth_call/eth_estimateGas, enables spending limits simulation
/// This is not used in actual transaction execution - the key_id is recovered from the signature.
pub override_key_id: Option<Address>,
}
/// Tempo transaction environment.
#[derive(Debug, Clone, Default, derive_more::Deref, derive_more::DerefMut)]
pub struct TempoTxEnv {
/// Inner Ethereum [`TxEnv`].
#[deref]
#[deref_mut]
pub inner: TxEnv,
/// Optional fee token preference specified for the transaction.
pub fee_token: Option<Address>,
/// Whether the transaction is a system transaction.
pub is_system_tx: bool,
/// Optional fee payer specified for the transaction.
///
/// - Some(Some(address)) corresponds to a successfully recovered fee payer
/// - Some(None) corresponds to a failed recovery and means that transaction is invalid
/// - None corresponds to a transaction without a fee payer
pub fee_payer: Option<Option<Address>>,
/// AA-specific transaction environment (boxed to keep TempoTxEnv lean for non-AA tx)
pub tempo_tx_env: Option<Box<TempoBatchCallEnv>>,
}
impl TempoTxEnv {
/// Resolves fee payer from the signature.
pub fn fee_payer(&self) -> Result<Address, TempoInvalidTransaction> {
if let Some(fee_payer) = self.fee_payer {
fee_payer.ok_or(TempoInvalidTransaction::InvalidFeePayerSignature)
} else {
Ok(self.caller())
}
}
/// Returns true if the transaction is a subblock transaction.
pub fn is_subblock_transaction(&self) -> bool {
self.tempo_tx_env
.as_ref()
.is_some_and(|aa| aa.subblock_transaction)
}
/// Returns the first top-level call in the transaction.
pub fn first_call(&self) -> Option<(&TxKind, &[u8])> {
if let Some(aa) = self.tempo_tx_env.as_ref() {
aa.aa_calls
.first()
.map(|call| (&call.to, call.input.as_ref()))
} else {
Some((&self.inner.kind, &self.inner.data))
}
}
/// Invokes the given closure for each top-level call in the transaction and
/// returns true if all calls returned true.
pub fn calls(&self) -> impl Iterator<Item = (&TxKind, &[u8])> {
if let Some(aa) = self.tempo_tx_env.as_ref() {
Either::Left(
aa.aa_calls
.iter()
.map(|call| (&call.to, call.input.as_ref())),
)
} else {
Either::Right(core::iter::once((
&self.inner.kind,
self.inner.input().as_ref(),
)))
}
}
}
impl From<TxEnv> for TempoTxEnv {
fn from(inner: TxEnv) -> Self {
Self {
inner,
..Default::default()
}
}
}
impl Transaction for TempoTxEnv {
type AccessListItem<'a> = &'a AccessListItem;
type Authorization<'a> = &'a Either<SignedAuthorization, RecoveredAuthorization>;
fn tx_type(&self) -> u8 {
self.inner.tx_type()
}
fn kind(&self) -> TxKind {
self.inner.kind()
}
fn caller(&self) -> Address {
self.inner.caller()
}
fn gas_limit(&self) -> u64 {
self.inner.gas_limit()
}
fn gas_price(&self) -> u128 {
self.inner.gas_price()
}
fn value(&self) -> U256 {
self.inner.value()
}
fn nonce(&self) -> u64 {
Transaction::nonce(&self.inner)
}
fn chain_id(&self) -> Option<u64> {
self.inner.chain_id()
}
fn access_list(&self) -> Option<impl Iterator<Item = Self::AccessListItem<'_>>> {
self.inner.access_list()
}
fn max_fee_per_gas(&self) -> u128 {
self.inner.max_fee_per_gas()
}
fn max_fee_per_blob_gas(&self) -> u128 {
self.inner.max_fee_per_blob_gas()
}
fn authorization_list_len(&self) -> usize {
self.inner.authorization_list_len()
}
fn authorization_list(&self) -> impl Iterator<Item = Self::Authorization<'_>> {
self.inner.authorization_list()
}
fn input(&self) -> &Bytes {
self.inner.input()
}
fn blob_versioned_hashes(&self) -> &[B256] {
self.inner.blob_versioned_hashes()
}
fn max_priority_fee_per_gas(&self) -> Option<u128> {
self.inner.max_priority_fee_per_gas()
}
fn max_balance_spending(&self) -> Result<U256, InvalidTransaction> {
calc_gas_balance_spending(self.gas_limit(), self.max_fee_per_gas())
.checked_add(self.value())
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)
}
fn effective_balance_spending(
&self,
base_fee: u128,
_blob_price: u128,
) -> Result<U256, InvalidTransaction> {
calc_gas_balance_spending(self.gas_limit(), self.effective_gas_price(base_fee))
.checked_add(self.value())
.ok_or(InvalidTransaction::OverflowPaymentInTransaction)
}
}
impl TransactionEnv for TempoTxEnv {
fn set_gas_limit(&mut self, gas_limit: u64) {
self.inner.set_gas_limit(gas_limit);
}
fn nonce(&self) -> u64 {
Transaction::nonce(&self.inner)
}
fn set_nonce(&mut self, nonce: u64) {
self.inner.set_nonce(nonce);
}
fn set_access_list(&mut self, access_list: AccessList) {
self.inner.set_access_list(access_list);
}
}
impl IntoTxEnv<Self> for TempoTxEnv {
fn into_tx_env(self) -> Self {
self
}
}
impl FromRecoveredTx<EthereumTxEnvelope<TxEip4844>> for TempoTxEnv {
fn from_recovered_tx(tx: &EthereumTxEnvelope<TxEip4844>, sender: Address) -> Self {
TxEnv::from_recovered_tx(tx, sender).into()
}
}
impl FromRecoveredTx<AASigned> for TempoTxEnv {
fn from_recovered_tx(aa_signed: &AASigned, caller: Address) -> Self {
let tx = aa_signed.tx();
let signature = aa_signed.signature();
// Populate the key_id cache for Keychain signatures before cloning
// This parallelizes recovery during Tx->TxEnv conversion, and the cache is preserved when cloned
if let Some(keychain_sig) = signature.as_keychain() {
let _ = keychain_sig.key_id(&aa_signed.signature_hash());
}
let TempoTransaction {
chain_id,
fee_token,
max_priority_fee_per_gas,
max_fee_per_gas,
gas_limit,
calls,
access_list,
nonce_key,
nonce,
fee_payer_signature,
valid_before,
valid_after,
key_authorization,
tempo_authorization_list,
} = tx;
// Extract to/value/input from calls (use first call or defaults)
let (to, value, input) = if let Some(first_call) = calls.first() {
(first_call.to, first_call.value, first_call.input.clone())
} else {
(
alloy_primitives::TxKind::Create,
alloy_primitives::U256::ZERO,
alloy_primitives::Bytes::new(),
)
};
Self {
inner: TxEnv {
tx_type: tx.ty(),
caller,
gas_limit: *gas_limit,
gas_price: *max_fee_per_gas,
kind: to,
value,
data: input,
nonce: *nonce, // AA: nonce maps to TxEnv.nonce
chain_id: Some(*chain_id),
gas_priority_fee: Some(*max_priority_fee_per_gas),
access_list: access_list.clone(),
// Convert Tempo authorization list to RecoveredAuthorization upfront
authorization_list: tempo_authorization_list
.iter()
.map(|auth| {
let authority = auth
.recover_authority()
.map_or(RecoveredAuthority::Invalid, RecoveredAuthority::Valid);
Either::Right(RecoveredAuthorization::new_unchecked(
auth.inner().clone(),
authority,
))
})
.collect(),
..Default::default()
},
fee_token: *fee_token,
is_system_tx: false,
fee_payer: fee_payer_signature.map(|sig| {
secp256k1::recover_signer(&sig, tx.fee_payer_signature_hash(caller)).ok()
}),
// Bundle AA-specific fields into TempoBatchCallEnv
tempo_tx_env: Some(Box::new(TempoBatchCallEnv {
signature: signature.clone(),
valid_before: *valid_before,
valid_after: *valid_after,
aa_calls: calls.clone(),
// Recover authorizations upfront to avoid recovery during execution
tempo_authorization_list: tempo_authorization_list
.iter()
.map(|auth| RecoveredTempoAuthorization::recover(auth.clone()))
.collect(),
nonce_key: *nonce_key,
subblock_transaction: aa_signed.tx().subblock_proposer().is_some(),
key_authorization: key_authorization.clone(),
signature_hash: aa_signed.signature_hash(),
// override_key_id is only used for gas estimation, not actual execution
override_key_id: None,
})),
}
}
}
impl FromRecoveredTx<TempoTxEnvelope> for TempoTxEnv {
fn from_recovered_tx(tx: &TempoTxEnvelope, sender: Address) -> Self {
match tx {
tx @ TempoTxEnvelope::Legacy(inner) => Self {
inner: TxEnv::from_recovered_tx(inner.tx(), sender),
fee_token: None,
is_system_tx: tx.is_system_tx(),
fee_payer: None,
tempo_tx_env: None, // Non-AA transaction
},
TempoTxEnvelope::Eip2930(tx) => TxEnv::from_recovered_tx(tx.tx(), sender).into(),
TempoTxEnvelope::Eip1559(tx) => TxEnv::from_recovered_tx(tx.tx(), sender).into(),
TempoTxEnvelope::Eip7702(tx) => TxEnv::from_recovered_tx(tx.tx(), sender).into(),
TempoTxEnvelope::AA(tx) => Self::from_recovered_tx(tx, sender),
}
}
}
impl FromTxWithEncoded<EthereumTxEnvelope<TxEip4844>> for TempoTxEnv {
fn from_encoded_tx(
tx: &EthereumTxEnvelope<TxEip4844>,
sender: Address,
_encoded: Bytes,
) -> Self {
Self::from_recovered_tx(tx, sender)
}
}
impl FromTxWithEncoded<AASigned> for TempoTxEnv {
fn from_encoded_tx(tx: &AASigned, sender: Address, _encoded: Bytes) -> Self {
Self::from_recovered_tx(tx, sender)
}
}
impl FromTxWithEncoded<TempoTxEnvelope> for TempoTxEnv {
fn from_encoded_tx(tx: &TempoTxEnvelope, sender: Address, _encoded: Bytes) -> Self {
Self::from_recovered_tx(tx, sender)
}
}
#[cfg(test)]
mod tests {
use alloy_primitives::TxKind;
use tempo_primitives::transaction::{Call, validate_calls};
fn create_call(to: TxKind) -> Call {
Call {
to,
value: alloy_primitives::U256::ZERO,
input: alloy_primitives::Bytes::new(),
}
}
#[test]
fn test_validate_empty_calls_list() {
let result = validate_calls(&[], false);
assert!(result.is_err());
assert!(result.unwrap_err().contains("empty"));
}
#[test]
fn test_validate_single_call_ok() {
let calls = vec![create_call(TxKind::Call(alloy_primitives::Address::ZERO))];
assert!(validate_calls(&calls, false).is_ok());
}
#[test]
fn test_validate_single_create_ok() {
let calls = vec![create_call(TxKind::Create)];
assert!(validate_calls(&calls, false).is_ok());
}
#[test]
fn test_validate_create_with_authorization_list_fails() {
let calls = vec![create_call(TxKind::Create)];
let result = validate_calls(&calls, true); // has_authorization_list = true
assert!(result.is_err());
assert!(result.unwrap_err().contains("CREATE"));
}
#[test]
fn test_validate_create_not_first_call_fails() {
let calls = vec![
create_call(TxKind::Call(alloy_primitives::Address::ZERO)),
create_call(TxKind::Create), // CREATE as second call - should fail
];
let result = validate_calls(&calls, false);
assert!(result.is_err());
assert!(result.unwrap_err().contains("first call"));
}
#[test]
fn test_validate_multiple_creates_fails() {
let calls = vec![
create_call(TxKind::Create),
create_call(TxKind::Create), // Second CREATE - should fail
];
let result = validate_calls(&calls, false);
assert!(result.is_err());
assert!(result.unwrap_err().contains("first call"));
}
#[test]
fn test_validate_create_first_then_calls_ok() {
let calls = vec![
create_call(TxKind::Create),
create_call(TxKind::Call(alloy_primitives::Address::ZERO)),
create_call(TxKind::Call(alloy_primitives::Address::random())),
];
// No auth list, so CREATE is allowed
assert!(validate_calls(&calls, false).is_ok());
}
#[test]
fn test_validate_multiple_calls_ok() {
let calls = vec![
create_call(TxKind::Call(alloy_primitives::Address::ZERO)),
create_call(TxKind::Call(alloy_primitives::Address::random())),
create_call(TxKind::Call(alloy_primitives::Address::random())),
];
assert!(validate_calls(&calls, false).is_ok());
}
}