@aztec/p2p 0.0.1-commit.a072138 → 0.0.1-commit.aada20e3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dest/client/factory.d.ts +1 -1
- package/dest/client/factory.d.ts.map +1 -1
- package/dest/client/factory.js +3 -1
- package/dest/client/p2p_client.d.ts +4 -2
- package/dest/client/p2p_client.d.ts.map +1 -1
- package/dest/client/p2p_client.js +6 -2
- package/dest/config.d.ts +8 -2
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +3 -1
- package/dest/mem_pools/tx_pool_v2/archive/index.d.ts +2 -0
- package/dest/mem_pools/tx_pool_v2/archive/index.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/archive/index.js +1 -0
- package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts +43 -0
- package/dest/mem_pools/tx_pool_v2/archive/tx_archive.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/archive/tx_archive.js +103 -0
- package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts +47 -0
- package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/eviction_manager.js +119 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +17 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +90 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +19 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +89 -0
- package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts +10 -0
- package/dest/mem_pools/tx_pool_v2/eviction/index.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/index.js +11 -0
- package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +131 -0
- package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/interfaces.js +17 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts +15 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.js +63 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts +17 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +91 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +16 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +70 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +20 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +63 -0
- package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +15 -0
- package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +19 -0
- package/dest/mem_pools/tx_pool_v2/index.d.ts +5 -0
- package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/index.js +4 -0
- package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +193 -0
- package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/interfaces.js +6 -0
- package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +71 -0
- package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/tx_metadata.js +94 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts +26 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_bench_metrics.js +70 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +55 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +150 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +69 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -0
- package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +1041 -0
- package/dest/services/index.d.ts +2 -1
- package/dest/services/index.d.ts.map +1 -1
- package/dest/services/index.js +1 -0
- package/dest/services/tx_file_store/config.d.ts +18 -0
- package/dest/services/tx_file_store/config.d.ts.map +1 -0
- package/dest/services/tx_file_store/config.js +26 -0
- package/dest/services/tx_file_store/index.d.ts +4 -0
- package/dest/services/tx_file_store/index.d.ts.map +1 -0
- package/dest/services/tx_file_store/index.js +3 -0
- package/dest/services/tx_file_store/instrumentation.d.ts +15 -0
- package/dest/services/tx_file_store/instrumentation.d.ts.map +1 -0
- package/dest/services/tx_file_store/instrumentation.js +29 -0
- package/dest/services/tx_file_store/tx_file_store.d.ts +47 -0
- package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -0
- package/dest/services/tx_file_store/tx_file_store.js +149 -0
- package/package.json +14 -14
- package/src/client/factory.ts +4 -0
- package/src/client/p2p_client.ts +5 -0
- package/src/config.ts +8 -1
- package/src/mem_pools/tx_pool_v2/README.md +188 -0
- package/src/mem_pools/tx_pool_v2/archive/index.ts +1 -0
- package/src/mem_pools/tx_pool_v2/archive/tx_archive.ts +120 -0
- package/src/mem_pools/tx_pool_v2/eviction/eviction_manager.ts +147 -0
- package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +118 -0
- package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +111 -0
- package/src/mem_pools/tx_pool_v2/eviction/index.ts +23 -0
- package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +164 -0
- package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_mining_rule.ts +74 -0
- package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +101 -0
- package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +86 -0
- package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +72 -0
- package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +31 -0
- package/src/mem_pools/tx_pool_v2/index.ts +11 -0
- package/src/mem_pools/tx_pool_v2/interfaces.ts +225 -0
- package/src/mem_pools/tx_pool_v2/tx_metadata.ts +160 -0
- package/src/mem_pools/tx_pool_v2/tx_pool_bench_metrics.ts +77 -0
- package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +209 -0
- package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +1265 -0
- package/src/services/index.ts +1 -0
- package/src/services/tx_file_store/config.ts +43 -0
- package/src/services/tx_file_store/index.ts +3 -0
- package/src/services/tx_file_store/instrumentation.ts +36 -0
- package/src/services/tx_file_store/tx_file_store.ts +173 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# TxPoolV2
|
|
2
|
+
|
|
3
|
+
Transaction pool implementation with explicit state management and pluggable eviction rules.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
TxPoolV2 manages transactions through a state machine with clear transitions:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
addPendingTxs()
|
|
11
|
+
│
|
|
12
|
+
▼
|
|
13
|
+
┌─────────────────────────────────────┐
|
|
14
|
+
│ PENDING │◄──────────────────┐
|
|
15
|
+
│ (awaiting block inclusion) │ │
|
|
16
|
+
└─────────────────────────────────────┘ │
|
|
17
|
+
│ │
|
|
18
|
+
│ protectTxs() / addProtectedTxs() │
|
|
19
|
+
▼ │
|
|
20
|
+
┌─────────────────────────────────────┐ │
|
|
21
|
+
│ PROTECTED │───────────────────┘
|
|
22
|
+
│ (in a block proposal) │ prepareForSlot()
|
|
23
|
+
└─────────────────────────────────────┘ (slot passed without mining)
|
|
24
|
+
│ │
|
|
25
|
+
│ handleMinedBlock() │
|
|
26
|
+
▼ │
|
|
27
|
+
┌─────────────────────────────────────┐ │
|
|
28
|
+
│ MINED │───────────────────┘
|
|
29
|
+
│ (included in a block) │ handlePrunedBlocks()
|
|
30
|
+
└─────────────────────────────────────┘ (reorg)
|
|
31
|
+
│
|
|
32
|
+
│ handleFinalizedBlock()
|
|
33
|
+
▼
|
|
34
|
+
┌─────────────────────────────────────┐
|
|
35
|
+
│ DELETED │
|
|
36
|
+
│ (optionally archived) │
|
|
37
|
+
└─────────────────────────────────────┘
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Key Components
|
|
41
|
+
|
|
42
|
+
### TxPoolV2 (`tx_pool_v2.ts`)
|
|
43
|
+
|
|
44
|
+
The public API wrapper that serializes all operations through a queue to prevent race conditions. Delegates to `TxPoolV2Impl` for actual logic.
|
|
45
|
+
|
|
46
|
+
### TxPoolV2Impl (`tx_pool_v2_impl.ts`)
|
|
47
|
+
|
|
48
|
+
Core implementation containing:
|
|
49
|
+
- KV store persistence for transactions and metadata
|
|
50
|
+
- In-memory indices for fast lookups (by nullifier, fee payer, priority)
|
|
51
|
+
- State transition logic
|
|
52
|
+
- Pre-add rule execution
|
|
53
|
+
- Post-event eviction rule execution
|
|
54
|
+
|
|
55
|
+
### TxMetaData (`tx_metadata.ts`)
|
|
56
|
+
|
|
57
|
+
Lightweight metadata stored alongside each transaction:
|
|
58
|
+
- `txHash`: Transaction identifier
|
|
59
|
+
- `state`: Current state (pending, protected, mined)
|
|
60
|
+
- `priorityFee`: For priority ordering
|
|
61
|
+
- `feePayer`: For balance-based eviction
|
|
62
|
+
- `nullifiers`: For conflict detection
|
|
63
|
+
- `estimatedTxFee`: For balance calculations
|
|
64
|
+
- `blockId`: Block info when mined
|
|
65
|
+
- `protectedSlot`: Slot number when protected
|
|
66
|
+
|
|
67
|
+
## Eviction Rules
|
|
68
|
+
|
|
69
|
+
The pool uses a pluggable rule system for managing transactions.
|
|
70
|
+
|
|
71
|
+
### Pre-Add Rules
|
|
72
|
+
|
|
73
|
+
Checked before adding a transaction to the pending pool:
|
|
74
|
+
|
|
75
|
+
| Rule | Purpose |
|
|
76
|
+
|------|---------|
|
|
77
|
+
| `NullifierConflictRule` | Handles transactions with conflicting nullifiers. Higher priority tx wins. |
|
|
78
|
+
| `FeePayerBalancePreAddRule` | Ensures fee payer has sufficient balance for all their pending txs. |
|
|
79
|
+
| `LowPriorityPreAddRule` | Rejects txs when pool is full and new tx has lowest priority. |
|
|
80
|
+
|
|
81
|
+
### Post-Event Eviction Rules
|
|
82
|
+
|
|
83
|
+
Run after events to clean up the pool:
|
|
84
|
+
|
|
85
|
+
| Rule | Trigger | Purpose |
|
|
86
|
+
|------|---------|---------|
|
|
87
|
+
| `LowPriorityEvictionRule` | `txs_added` | Evicts lowest priority txs when pool exceeds limit. |
|
|
88
|
+
| `FeePayerBalanceEvictionRule` | `block_mined` | Evicts txs when fee payer balance decreases. |
|
|
89
|
+
| `InvalidTxsAfterMiningRule` | `block_mined` | Evicts pending txs with nullifiers that were just mined. |
|
|
90
|
+
| `InvalidTxsAfterReorgRule` | `chain_pruned` | Evicts txs with invalid anchor blocks after reorg. |
|
|
91
|
+
|
|
92
|
+
## Usage
|
|
93
|
+
|
|
94
|
+
### Creating a Pool
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
import { AztecKVTxPoolV2 } from './tx_pool_v2.js';
|
|
98
|
+
|
|
99
|
+
const pool = new AztecKVTxPoolV2(txStore, archiveStore, {
|
|
100
|
+
l2BlockSource: archiver,
|
|
101
|
+
worldStateSynchronizer: worldState,
|
|
102
|
+
pendingTxValidator: validator,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
await pool.start();
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### Adding Transactions
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
// Add to pending pool (validates and runs pre-add rules)
|
|
112
|
+
const result = await pool.addPendingTxs(txs, { source: 'gossip' });
|
|
113
|
+
// result: { accepted: TxHash[], ignored: TxHash[], rejected: TxHash[] }
|
|
114
|
+
|
|
115
|
+
// Check without modifying pool
|
|
116
|
+
const canAdd = await pool.canAddPendingTx(tx);
|
|
117
|
+
// canAdd: 'accepted' | 'ignored' | 'rejected'
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Block Building Flow
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
// 1. Proposer protects txs for their block
|
|
124
|
+
await pool.protectTxs(selectedTxHashes, blockHeader);
|
|
125
|
+
|
|
126
|
+
// 2. On successful mining
|
|
127
|
+
await pool.handleMinedBlock(minedTxHashes, blockHeader);
|
|
128
|
+
|
|
129
|
+
// 3. If slot passes without mining
|
|
130
|
+
await pool.prepareForSlot(nextSlotNumber);
|
|
131
|
+
|
|
132
|
+
// 4. On finalization
|
|
133
|
+
await pool.handleFinalizedBlock(finalizedBlockHeader);
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Handling Reorgs
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
// When blocks are pruned, un-mine affected transactions
|
|
140
|
+
await pool.handlePrunedBlocks(latestValidBlockId);
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Configuration
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
await pool.updateConfig({
|
|
147
|
+
maxPendingTxCount: 10000, // 0 = unlimited
|
|
148
|
+
archivedTxLimit: 1000, // 0 = disabled
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Return Values
|
|
153
|
+
|
|
154
|
+
### AddTxsResult
|
|
155
|
+
|
|
156
|
+
When adding pending transactions, each tx is categorized:
|
|
157
|
+
|
|
158
|
+
| Status | Meaning |
|
|
159
|
+
|--------|---------|
|
|
160
|
+
| `accepted` | Successfully added to the pool |
|
|
161
|
+
| `ignored` | Valid but not added (duplicate, lost nullifier conflict, insufficient balance) |
|
|
162
|
+
| `rejected` | Failed validation (invalid proof, expired, etc.) |
|
|
163
|
+
|
|
164
|
+
## Archive
|
|
165
|
+
|
|
166
|
+
Finalized transactions can optionally be archived for historical queries:
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
const archivedTx = await pool.getArchivedTxByHash(txHash);
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The archive uses FIFO eviction when `archivedTxLimit` is reached.
|
|
173
|
+
|
|
174
|
+
## Testing
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
# Unit tests (131 tests)
|
|
178
|
+
yarn test src/mem_pools/tx_pool_v2/tx_pool_v2.test.ts
|
|
179
|
+
|
|
180
|
+
# Compatibility tests (25 tests)
|
|
181
|
+
yarn test src/mem_pools/tx_pool_v2/tx_pool_v2.compat.test.ts
|
|
182
|
+
|
|
183
|
+
# Eviction rule tests
|
|
184
|
+
yarn test src/mem_pools/tx_pool_v2/eviction/
|
|
185
|
+
|
|
186
|
+
# Benchmarks
|
|
187
|
+
yarn test src/mem_pools/tx_pool_v2/tx_pool_v2_bench.test.ts
|
|
188
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { TxArchive } from './tx_archive.js';
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
2
|
+
import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
|
|
3
|
+
import { ChonkProof } from '@aztec/stdlib/proofs';
|
|
4
|
+
import { Tx, TxHash } from '@aztec/stdlib/tx';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Manages archived transactions with FIFO eviction.
|
|
8
|
+
* Archived transactions have their proofs stripped to save space.
|
|
9
|
+
*/
|
|
10
|
+
export class TxArchive {
|
|
11
|
+
#store: AztecAsyncKVStore;
|
|
12
|
+
#txs: AztecAsyncMap<string, Buffer>;
|
|
13
|
+
#indices: AztecAsyncMap<number, string>;
|
|
14
|
+
#limit: number;
|
|
15
|
+
#log: Logger;
|
|
16
|
+
|
|
17
|
+
constructor(store: AztecAsyncKVStore, limit: number, log?: Logger) {
|
|
18
|
+
this.#store = store;
|
|
19
|
+
this.#txs = store.openMap('archivedTxs');
|
|
20
|
+
this.#indices = store.openMap('archivedTxIndices');
|
|
21
|
+
this.#limit = limit;
|
|
22
|
+
this.#log = log ?? createLogger('p2p:tx_pool_v2:archive');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Updates the maximum number of archived transactions.
|
|
27
|
+
*/
|
|
28
|
+
updateLimit(limit: number): void {
|
|
29
|
+
this.#limit = limit;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Gets the current archive limit.
|
|
34
|
+
*/
|
|
35
|
+
getLimit(): number {
|
|
36
|
+
return this.#limit;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Checks if archiving is enabled.
|
|
41
|
+
*/
|
|
42
|
+
isEnabled(): boolean {
|
|
43
|
+
return this.#limit > 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Archives transactions, stripping their proofs.
|
|
48
|
+
* Evicts oldest transactions if the limit is exceeded.
|
|
49
|
+
*/
|
|
50
|
+
async archiveTxs(txs: Tx[]): Promise<void> {
|
|
51
|
+
if (!this.isEnabled() || txs.length === 0) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
await this.#store.transactionAsync(async () => {
|
|
57
|
+
// Get current head and tail indices
|
|
58
|
+
let headIdx = await this.getHeadIndex();
|
|
59
|
+
let tailIdx = await this.getTailIndex();
|
|
60
|
+
|
|
61
|
+
for (const tx of txs) {
|
|
62
|
+
// Evict oldest entries if at capacity
|
|
63
|
+
while (headIdx - tailIdx >= this.#limit) {
|
|
64
|
+
const txHashToEvict = await this.#indices.getAsync(tailIdx);
|
|
65
|
+
if (txHashToEvict) {
|
|
66
|
+
await this.#txs.delete(txHashToEvict);
|
|
67
|
+
await this.#indices.delete(tailIdx);
|
|
68
|
+
}
|
|
69
|
+
tailIdx++;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Archive the transaction with stripped proof
|
|
73
|
+
const archivedTx = this.stripProof(tx);
|
|
74
|
+
const txHash = tx.getTxHash().toString();
|
|
75
|
+
await this.#txs.set(txHash, archivedTx.toBuffer());
|
|
76
|
+
await this.#indices.set(headIdx, txHash);
|
|
77
|
+
headIdx++;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
this.#log.debug(`Archived ${txs.length} txs, total: ${headIdx - tailIdx}`);
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
this.#log.error('Error archiving transactions', { error });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Retrieves an archived transaction by its hash.
|
|
89
|
+
*/
|
|
90
|
+
async getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
|
|
91
|
+
const buffer = await this.#txs.getAsync(txHash.toString());
|
|
92
|
+
return buffer ? Tx.fromBuffer(buffer) : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Gets the current count of archived transactions.
|
|
97
|
+
*/
|
|
98
|
+
async getCount(): Promise<number> {
|
|
99
|
+
const head = await this.getHeadIndex();
|
|
100
|
+
const tail = await this.getTailIndex();
|
|
101
|
+
return head - tail;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Strips the proof from a transaction for archival.
|
|
106
|
+
*/
|
|
107
|
+
private stripProof(tx: Tx): Tx {
|
|
108
|
+
return new Tx(tx.txHash, tx.data, ChonkProof.empty(), tx.contractClassLogFields, tx.publicFunctionCalldata);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private async getHeadIndex(): Promise<number> {
|
|
112
|
+
const entry = await this.#indices.entriesAsync({ limit: 1, reverse: true }).next();
|
|
113
|
+
return (entry.value?.[0] ?? -1) + 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private async getTailIndex(): Promise<number> {
|
|
117
|
+
const entry = await this.#indices.entriesAsync({ limit: 1 }).next();
|
|
118
|
+
return entry.value?.[0] ?? 0;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { BlockNumber } from '@aztec/foundation/branded-types';
|
|
2
|
+
import type { Logger } from '@aztec/foundation/log';
|
|
3
|
+
import type { BlockHeader } from '@aztec/stdlib/tx';
|
|
4
|
+
|
|
5
|
+
import type { TxMetaData } from '../tx_metadata.js';
|
|
6
|
+
import {
|
|
7
|
+
type EvictionConfig,
|
|
8
|
+
type EvictionContext,
|
|
9
|
+
EvictionEvent,
|
|
10
|
+
type EvictionRule,
|
|
11
|
+
type PoolOperations,
|
|
12
|
+
type PreAddPoolAccess,
|
|
13
|
+
type PreAddResult,
|
|
14
|
+
type PreAddRule,
|
|
15
|
+
} from './interfaces.js';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Manages eviction rules for the transaction pool.
|
|
19
|
+
* Coordinates pre-add rules (run during addPendingTxs) and post-event rules (run after events).
|
|
20
|
+
*/
|
|
21
|
+
export class EvictionManager {
|
|
22
|
+
private preAddRules: PreAddRule[] = [];
|
|
23
|
+
private postEventRules: EvictionRule[] = [];
|
|
24
|
+
|
|
25
|
+
constructor(
|
|
26
|
+
private pool: PoolOperations,
|
|
27
|
+
private log: Logger,
|
|
28
|
+
) {}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Registers a pre-add rule that runs during transaction addition.
|
|
32
|
+
*/
|
|
33
|
+
registerPreAddRule(rule: PreAddRule): void {
|
|
34
|
+
this.preAddRules.push(rule);
|
|
35
|
+
this.log.debug(`Registered pre-add rule: ${rule.name}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Registers a post-event eviction rule that runs after events.
|
|
40
|
+
*/
|
|
41
|
+
registerRule(rule: EvictionRule): void {
|
|
42
|
+
this.postEventRules.push(rule);
|
|
43
|
+
this.log.debug(`Registered eviction rule: ${rule.name}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Runs all pre-add rules for an incoming transaction.
|
|
48
|
+
* Returns combined result of all rules.
|
|
49
|
+
*/
|
|
50
|
+
async runPreAddRules(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult> {
|
|
51
|
+
const allTxHashesToEvict: string[] = [];
|
|
52
|
+
|
|
53
|
+
for (const rule of this.preAddRules) {
|
|
54
|
+
try {
|
|
55
|
+
const result = await rule.check(incomingMeta, poolAccess);
|
|
56
|
+
|
|
57
|
+
if (result.shouldIgnore) {
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Collect txs to evict from all rules
|
|
62
|
+
for (const txHash of result.txHashesToEvict) {
|
|
63
|
+
if (!allTxHashesToEvict.includes(txHash)) {
|
|
64
|
+
allTxHashesToEvict.push(txHash);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
} catch (err) {
|
|
68
|
+
this.log.error(`Error running pre-add rule ${rule.name}`, { err, txHash: incomingMeta.txHash });
|
|
69
|
+
// On error, ignore the transaction to be safe
|
|
70
|
+
return {
|
|
71
|
+
shouldIgnore: true,
|
|
72
|
+
txHashesToEvict: [],
|
|
73
|
+
reason: `pre-add rule ${rule.name} error: ${err}`,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
shouldIgnore: false,
|
|
80
|
+
txHashesToEvict: allTxHashesToEvict,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Runs post-event eviction after new transactions are added.
|
|
86
|
+
*/
|
|
87
|
+
async evictAfterNewTxs(newTxHashes: string[], feePayers: string[]): Promise<void> {
|
|
88
|
+
const context: EvictionContext = {
|
|
89
|
+
event: EvictionEvent.TXS_ADDED,
|
|
90
|
+
newTxHashes,
|
|
91
|
+
feePayers,
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
await this.runPostEventRules(context);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Runs post-event eviction after a block is mined.
|
|
99
|
+
*/
|
|
100
|
+
async evictAfterNewBlock(block: BlockHeader, newNullifiers: string[], feePayers: string[]): Promise<void> {
|
|
101
|
+
const context: EvictionContext = {
|
|
102
|
+
event: EvictionEvent.BLOCK_MINED,
|
|
103
|
+
block,
|
|
104
|
+
newNullifiers,
|
|
105
|
+
feePayers,
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
await this.runPostEventRules(context);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Runs post-event eviction after a chain prune (reorg).
|
|
113
|
+
*/
|
|
114
|
+
async evictAfterChainPrune(blockNumber: BlockNumber): Promise<void> {
|
|
115
|
+
const context: EvictionContext = {
|
|
116
|
+
event: EvictionEvent.CHAIN_PRUNED,
|
|
117
|
+
blockNumber,
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
await this.runPostEventRules(context);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Updates configuration for all rules.
|
|
125
|
+
*/
|
|
126
|
+
updateConfig(config: EvictionConfig): void {
|
|
127
|
+
for (const rule of this.preAddRules) {
|
|
128
|
+
rule.updateConfig?.(config);
|
|
129
|
+
}
|
|
130
|
+
for (const rule of this.postEventRules) {
|
|
131
|
+
rule.updateConfig?.(config);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async runPostEventRules(context: EvictionContext): Promise<void> {
|
|
136
|
+
for (const rule of this.postEventRules) {
|
|
137
|
+
try {
|
|
138
|
+
const result = await rule.evict(context, this.pool);
|
|
139
|
+
if (!result.success) {
|
|
140
|
+
this.log.warn(`Eviction rule ${rule.name} failed`, { error: result.error });
|
|
141
|
+
}
|
|
142
|
+
} catch (err) {
|
|
143
|
+
this.log.error(`Error running eviction rule ${rule.name}`, { err });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
2
|
+
import { ProtocolContractAddress } from '@aztec/protocol-contracts';
|
|
3
|
+
import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice';
|
|
4
|
+
import { AztecAddress } from '@aztec/stdlib/aztec-address';
|
|
5
|
+
import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
|
|
6
|
+
import { DatabasePublicStateSource, type MerkleTreeReadOperations } from '@aztec/stdlib/trees';
|
|
7
|
+
|
|
8
|
+
import { type TxMetaData, comparePriority } from '../tx_metadata.js';
|
|
9
|
+
import type { EvictionContext, EvictionResult, EvictionRule, PoolOperations } from './interfaces.js';
|
|
10
|
+
import { EvictionEvent } from './interfaces.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Eviction rule that removes transactions when fee payers have insufficient balance.
|
|
14
|
+
* Triggers on TXS_ADDED, BLOCK_MINED, and CHAIN_PRUNED events.
|
|
15
|
+
*/
|
|
16
|
+
export class FeePayerBalanceEvictionRule implements EvictionRule {
|
|
17
|
+
public readonly name = 'FeePayerBalanceEviction';
|
|
18
|
+
public readonly reason = 'fee_payer_balance';
|
|
19
|
+
|
|
20
|
+
private log = createLogger('p2p:tx_pool_v2:fee_payer_balance_eviction_rule');
|
|
21
|
+
|
|
22
|
+
constructor(private worldState: WorldStateSynchronizer) {}
|
|
23
|
+
|
|
24
|
+
async evict(context: EvictionContext, pool: PoolOperations): Promise<EvictionResult> {
|
|
25
|
+
try {
|
|
26
|
+
if (context.event === EvictionEvent.TXS_ADDED) {
|
|
27
|
+
return await this.evictForFeePayers(context.feePayers, this.worldState.getCommitted(), pool);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (context.event === EvictionEvent.BLOCK_MINED) {
|
|
31
|
+
const blockNumber = context.block.getBlockNumber();
|
|
32
|
+
await this.worldState.syncImmediate(blockNumber);
|
|
33
|
+
return await this.evictForFeePayers(context.feePayers, this.worldState.getSnapshot(blockNumber), pool);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (context.event === EvictionEvent.CHAIN_PRUNED) {
|
|
37
|
+
await this.worldState.syncImmediate(context.blockNumber);
|
|
38
|
+
const feePayers = pool.getPendingFeePayers();
|
|
39
|
+
return await this.evictForFeePayers(feePayers, this.worldState.getSnapshot(context.blockNumber), pool);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
reason: this.reason,
|
|
44
|
+
success: true,
|
|
45
|
+
txsEvicted: [],
|
|
46
|
+
};
|
|
47
|
+
} catch (err) {
|
|
48
|
+
this.log.error('Failed to evict txs due to fee payer balance', { err });
|
|
49
|
+
return {
|
|
50
|
+
reason: this.reason,
|
|
51
|
+
success: false,
|
|
52
|
+
txsEvicted: [],
|
|
53
|
+
error: new Error('Failed to evict txs due to fee payer balance', { cause: err }),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private async evictForFeePayers(
|
|
59
|
+
feePayers: string[],
|
|
60
|
+
db: MerkleTreeReadOperations,
|
|
61
|
+
pool: PoolOperations,
|
|
62
|
+
): Promise<EvictionResult> {
|
|
63
|
+
const publicStateSource = new DatabasePublicStateSource(db);
|
|
64
|
+
|
|
65
|
+
const txsToEvict = (
|
|
66
|
+
await Promise.all(feePayers.map(feePayer => this.getEvictionsForFeePayer(feePayer, publicStateSource, pool)))
|
|
67
|
+
).flat();
|
|
68
|
+
|
|
69
|
+
if (txsToEvict.length > 0) {
|
|
70
|
+
await pool.deleteTxs(txsToEvict);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
reason: this.reason,
|
|
75
|
+
success: true,
|
|
76
|
+
txsEvicted: txsToEvict,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async getEvictionsForFeePayer(
|
|
81
|
+
feePayerStr: string,
|
|
82
|
+
publicStateSource: DatabasePublicStateSource,
|
|
83
|
+
pool: PoolOperations,
|
|
84
|
+
): Promise<string[]> {
|
|
85
|
+
const feePayer = AztecAddress.fromString(feePayerStr);
|
|
86
|
+
const initialBalance = (
|
|
87
|
+
await publicStateSource.storageRead(
|
|
88
|
+
ProtocolContractAddress.FeeJuice,
|
|
89
|
+
await computeFeePayerBalanceStorageSlot(feePayer),
|
|
90
|
+
)
|
|
91
|
+
).toBigInt();
|
|
92
|
+
|
|
93
|
+
const txs: TxMetaData[] = pool.getFeePayerPendingTxs(feePayerStr);
|
|
94
|
+
|
|
95
|
+
if (txs.length === 0) {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const txsToEvict: string[] = [];
|
|
100
|
+
let balance = initialBalance;
|
|
101
|
+
|
|
102
|
+
// Sort by priority descending (highest first), with hash as tiebreaker
|
|
103
|
+
txs.sort((a, b) => comparePriority(b, a));
|
|
104
|
+
|
|
105
|
+
for (const tx of txs) {
|
|
106
|
+
const available = balance + tx.claimAmount;
|
|
107
|
+
if (available >= tx.feeLimit) {
|
|
108
|
+
balance = available - tx.feeLimit;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// This tx cannot be covered - mark for eviction
|
|
113
|
+
txsToEvict.push(tx.txHash);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return txsToEvict;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
2
|
+
|
|
3
|
+
import { type TxMetaData, comparePriority } from '../tx_metadata.js';
|
|
4
|
+
import type { PreAddPoolAccess, PreAddResult, PreAddRule } from './interfaces.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Pre-add rule that checks if a fee payer has sufficient balance to cover the incoming transaction.
|
|
8
|
+
*
|
|
9
|
+
* When an incoming tx is added:
|
|
10
|
+
* - Get the fee payer's on-chain balance
|
|
11
|
+
* - Get all existing pending txs for this fee payer
|
|
12
|
+
* - Insert incoming tx in priority order
|
|
13
|
+
* - Walk through in priority order, tracking running balance
|
|
14
|
+
* - If incoming tx can be covered: accept, mark lower-priority txs for eviction if needed
|
|
15
|
+
* - If incoming tx cannot be covered: ignore it
|
|
16
|
+
*/
|
|
17
|
+
export class FeePayerBalancePreAddRule implements PreAddRule {
|
|
18
|
+
public readonly name = 'FeePayerBalancePreAdd';
|
|
19
|
+
|
|
20
|
+
private log = createLogger('p2p:tx_pool_v2:fee_payer_balance_pre_add_rule');
|
|
21
|
+
|
|
22
|
+
async check(incomingMeta: TxMetaData, poolAccess: PreAddPoolAccess): Promise<PreAddResult> {
|
|
23
|
+
// Get fee payer's on-chain balance
|
|
24
|
+
const initialBalance = await poolAccess.getFeePayerBalance(incomingMeta.feePayer);
|
|
25
|
+
|
|
26
|
+
// Get existing pending txs for this fee payer
|
|
27
|
+
const existingTxs = poolAccess.getFeePayerPendingTxs(incomingMeta.feePayer);
|
|
28
|
+
|
|
29
|
+
// Create combined list with incoming tx
|
|
30
|
+
const allTxs: Array<{
|
|
31
|
+
txHash: string;
|
|
32
|
+
priorityFee: bigint;
|
|
33
|
+
feeLimit: bigint;
|
|
34
|
+
claimAmount: bigint;
|
|
35
|
+
isIncoming: boolean;
|
|
36
|
+
}> = [
|
|
37
|
+
...existingTxs.map(t => ({
|
|
38
|
+
txHash: t.txHash,
|
|
39
|
+
priorityFee: t.priorityFee,
|
|
40
|
+
feeLimit: t.feeLimit,
|
|
41
|
+
claimAmount: t.claimAmount,
|
|
42
|
+
isIncoming: false,
|
|
43
|
+
})),
|
|
44
|
+
{
|
|
45
|
+
txHash: incomingMeta.txHash,
|
|
46
|
+
priorityFee: incomingMeta.priorityFee,
|
|
47
|
+
feeLimit: incomingMeta.feeLimit,
|
|
48
|
+
claimAmount: incomingMeta.claimAmount,
|
|
49
|
+
isIncoming: true,
|
|
50
|
+
},
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
// Sort by priority descending (highest first), with hash as tiebreaker
|
|
54
|
+
allTxs.sort((a, b) => comparePriority(b, a));
|
|
55
|
+
|
|
56
|
+
// Walk through in priority order, tracking balance
|
|
57
|
+
let balance = initialBalance;
|
|
58
|
+
let incomingTxCovered = false;
|
|
59
|
+
const txsToEvict: string[] = [];
|
|
60
|
+
|
|
61
|
+
for (const txInfo of allTxs) {
|
|
62
|
+
const available = balance + txInfo.claimAmount;
|
|
63
|
+
|
|
64
|
+
if (available >= txInfo.feeLimit) {
|
|
65
|
+
// This tx can be covered
|
|
66
|
+
balance = available - txInfo.feeLimit;
|
|
67
|
+
if (txInfo.isIncoming) {
|
|
68
|
+
incomingTxCovered = true;
|
|
69
|
+
}
|
|
70
|
+
} else {
|
|
71
|
+
// This tx cannot be covered
|
|
72
|
+
if (txInfo.isIncoming) {
|
|
73
|
+
// Incoming tx cannot be covered - ignore it
|
|
74
|
+
this.log.debug(
|
|
75
|
+
`Ignoring tx ${incomingMeta.txHash}: fee payer ${incomingMeta.feePayer} has insufficient balance`,
|
|
76
|
+
{ balance: initialBalance, feeLimit: incomingMeta.feeLimit, claimAmount: incomingMeta.claimAmount },
|
|
77
|
+
);
|
|
78
|
+
return {
|
|
79
|
+
shouldIgnore: true,
|
|
80
|
+
txHashesToEvict: [],
|
|
81
|
+
reason: `fee payer ${incomingMeta.feePayer} has insufficient balance`,
|
|
82
|
+
};
|
|
83
|
+
} else {
|
|
84
|
+
// Existing tx cannot be covered after adding incoming - mark for eviction
|
|
85
|
+
txsToEvict.push(txInfo.txHash);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!incomingTxCovered) {
|
|
91
|
+
// This shouldn't happen if the logic above is correct, but just in case
|
|
92
|
+
this.log.warn(`Incoming tx ${incomingMeta.txHash} was not covered but also not ignored - this is a bug`);
|
|
93
|
+
return {
|
|
94
|
+
shouldIgnore: true,
|
|
95
|
+
txHashesToEvict: [],
|
|
96
|
+
reason: 'internal error: tx coverage not determined',
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (txsToEvict.length > 0) {
|
|
101
|
+
this.log.debug(
|
|
102
|
+
`Accepting tx ${incomingMeta.txHash}, evicting ${txsToEvict.length} lower-priority txs due to fee payer balance`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
shouldIgnore: false,
|
|
108
|
+
txHashesToEvict: txsToEvict,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
}
|