@aztec/p2p 0.0.1-commit.9d2bcf6d → 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/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/package.json +14 -14
- 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
|
@@ -0,0 +1,1041 @@
|
|
|
1
|
+
import { ProtocolContractAddress } from '@aztec/protocol-contracts';
|
|
2
|
+
import { computeFeePayerBalanceStorageSlot } from '@aztec/protocol-contracts/fee-juice';
|
|
3
|
+
import { AztecAddress } from '@aztec/stdlib/aztec-address';
|
|
4
|
+
import { DatabasePublicStateSource } from '@aztec/stdlib/trees';
|
|
5
|
+
import { Tx, TxHash } from '@aztec/stdlib/tx';
|
|
6
|
+
import { TxArchive } from './archive/index.js';
|
|
7
|
+
import { EvictionManager, FeePayerBalanceEvictionRule, FeePayerBalancePreAddRule, InvalidTxsAfterMiningRule, InvalidTxsAfterReorgRule, LowPriorityEvictionRule, LowPriorityPreAddRule, NullifierConflictRule } from './eviction/index.js';
|
|
8
|
+
import { DEFAULT_TX_POOL_V2_CONFIG } from './interfaces.js';
|
|
9
|
+
import { buildTxMetaData, checkNullifierConflict, compareFee, compareTxHash } from './tx_metadata.js';
|
|
10
|
+
/**
|
|
11
|
+
* Implementation of TxPoolV2 logic.
|
|
12
|
+
*
|
|
13
|
+
* This class contains all the actual transaction pool logic.
|
|
14
|
+
*/ export class TxPoolV2Impl {
|
|
15
|
+
// === Persistence ===
|
|
16
|
+
#store;
|
|
17
|
+
#txsDB;
|
|
18
|
+
// === Dependencies ===
|
|
19
|
+
#l2BlockSource;
|
|
20
|
+
#worldStateSynchronizer;
|
|
21
|
+
#pendingTxValidator;
|
|
22
|
+
// === In-Memory Indices ===
|
|
23
|
+
/** Primary metadata store: txHash -> TxMetaData */ #metadata = new Map();
|
|
24
|
+
/** Nullifier to txHash index (pending txs only) */ #nullifierToTxHash = new Map();
|
|
25
|
+
/** Fee payer to txHashes index (pending txs only) */ #feePayerToTxHashes = new Map();
|
|
26
|
+
/**
|
|
27
|
+
* Pending txHashes grouped by priority fee.
|
|
28
|
+
* Outer map: priorityFee -> Set of txHashes at that fee level.
|
|
29
|
+
*/ #pendingByPriority = new Map();
|
|
30
|
+
/** Protected transactions: txHash -> slotNumber. Includes txs we have and txs we expect to receive. */ #protectedTransactions = new Map();
|
|
31
|
+
// === Config & Services ===
|
|
32
|
+
#config;
|
|
33
|
+
#archive;
|
|
34
|
+
#evictionManager;
|
|
35
|
+
#log;
|
|
36
|
+
#callbacks;
|
|
37
|
+
constructor(store, archiveStore, deps, callbacks, config = {}, log){
|
|
38
|
+
this.#store = store;
|
|
39
|
+
this.#txsDB = store.openMap('txs');
|
|
40
|
+
this.#l2BlockSource = deps.l2BlockSource;
|
|
41
|
+
this.#worldStateSynchronizer = deps.worldStateSynchronizer;
|
|
42
|
+
this.#pendingTxValidator = deps.pendingTxValidator;
|
|
43
|
+
this.#config = {
|
|
44
|
+
...DEFAULT_TX_POOL_V2_CONFIG,
|
|
45
|
+
...config
|
|
46
|
+
};
|
|
47
|
+
this.#archive = new TxArchive(archiveStore, this.#config.archivedTxLimit, log);
|
|
48
|
+
this.#log = log;
|
|
49
|
+
this.#callbacks = callbacks;
|
|
50
|
+
// Setup eviction manager with rules
|
|
51
|
+
this.#evictionManager = new EvictionManager(this.#createPoolOperations(), log);
|
|
52
|
+
// Pre-add rules (run during addPendingTxs) - work with TxMetaData
|
|
53
|
+
this.#evictionManager.registerPreAddRule(new NullifierConflictRule());
|
|
54
|
+
this.#evictionManager.registerPreAddRule(new FeePayerBalancePreAddRule());
|
|
55
|
+
this.#evictionManager.registerPreAddRule(new LowPriorityPreAddRule({
|
|
56
|
+
maxPoolSize: this.#config.maxPendingTxCount
|
|
57
|
+
}));
|
|
58
|
+
// Post-event eviction rules (run after events to check ALL pending txs)
|
|
59
|
+
this.#evictionManager.registerRule(new InvalidTxsAfterMiningRule());
|
|
60
|
+
this.#evictionManager.registerRule(new InvalidTxsAfterReorgRule(deps.worldStateSynchronizer));
|
|
61
|
+
this.#evictionManager.registerRule(new FeePayerBalanceEvictionRule(deps.worldStateSynchronizer));
|
|
62
|
+
// LowPriorityEvictionRule handles cases where txs become pending via prepareForSlot (unprotect)
|
|
63
|
+
// The pre-add rule handles the addPendingTxs case, but post-event is needed for unprotect
|
|
64
|
+
this.#evictionManager.registerRule(new LowPriorityEvictionRule({
|
|
65
|
+
maxPoolSize: this.#config.maxPendingTxCount
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
// ============================================================================
|
|
69
|
+
// PUBLIC IMPLEMENTATION METHODS
|
|
70
|
+
// ============================================================================
|
|
71
|
+
/**
|
|
72
|
+
* Hydrates the in-memory state from the database on startup.
|
|
73
|
+
* Pipeline: Load → Check Mined Status → Partition → Validate Non-Mined → Rebuild Pending Pool → Delete Invalid
|
|
74
|
+
*
|
|
75
|
+
* Note: Protected status is lost on restart. All non-mined txs are rebuilt as pending
|
|
76
|
+
* by running pre-add rules to resolve nullifier conflicts, balance checks, and pool size limits.
|
|
77
|
+
*/ async hydrateFromDatabase() {
|
|
78
|
+
// Step 1: Load all transactions from DB
|
|
79
|
+
const { loaded, errors: deserializationErrors } = await this.#loadAllTxsFromDb();
|
|
80
|
+
// Step 2: Check mined status for each tx
|
|
81
|
+
await this.#markMinedStatusBatch(loaded.map((l)=>l.meta));
|
|
82
|
+
// Step 3: Partition by mined status
|
|
83
|
+
const { mined, nonMined } = this.#partitionByMinedStatus(loaded);
|
|
84
|
+
// Step 4: Validate non-mined transactions
|
|
85
|
+
const { valid, invalid } = await this.#validateNonMinedTxs(nonMined);
|
|
86
|
+
// Step 5: Populate mined indices (these don't need conflict resolution)
|
|
87
|
+
this.#populateMinedIndices(mined);
|
|
88
|
+
// Step 6: Rebuild pending pool by running pre-add rules for each tx
|
|
89
|
+
// This resolves nullifier conflicts, fee payer balance issues, and pool size limits
|
|
90
|
+
const { rejected } = await this.#rebuildPendingPool(valid);
|
|
91
|
+
// Step 7: Delete invalid and rejected txs from DB
|
|
92
|
+
const toDelete = [
|
|
93
|
+
...deserializationErrors,
|
|
94
|
+
...invalid,
|
|
95
|
+
...rejected
|
|
96
|
+
];
|
|
97
|
+
if (toDelete.length === 0) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
await this.#store.transactionAsync(async ()=>{
|
|
101
|
+
for (const txHashStr of toDelete){
|
|
102
|
+
await this.#txsDB.delete(txHashStr);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
this.#log.info(`Deleted ${toDelete.length} invalid/rejected transactions on startup`);
|
|
106
|
+
}
|
|
107
|
+
async addPendingTxs(txs, opts) {
|
|
108
|
+
const accepted = [];
|
|
109
|
+
const ignored = [];
|
|
110
|
+
const rejected = [];
|
|
111
|
+
const newlyAdded = [];
|
|
112
|
+
const acceptedPending = new Set();
|
|
113
|
+
const poolAccess = this.#createPreAddPoolAccess();
|
|
114
|
+
await this.#store.transactionAsync(async ()=>{
|
|
115
|
+
for (const tx of txs){
|
|
116
|
+
const txHash = tx.getTxHash();
|
|
117
|
+
const txHashStr = txHash.toString();
|
|
118
|
+
// Skip duplicates
|
|
119
|
+
if (this.#isDuplicateTx(txHashStr)) {
|
|
120
|
+
ignored.push(txHash);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
// Check mined status first (applies to all paths)
|
|
124
|
+
const minedBlockId = await this.#getMinedBlockId(txHash);
|
|
125
|
+
const preProtectedSlot = this.#protectedTransactions.get(txHashStr);
|
|
126
|
+
if (minedBlockId) {
|
|
127
|
+
// Already mined - add directly (protection already set if pre-protected)
|
|
128
|
+
await this.#addNewMinedTx(tx, minedBlockId);
|
|
129
|
+
accepted.push(txHash);
|
|
130
|
+
newlyAdded.push(tx);
|
|
131
|
+
} else if (preProtectedSlot !== undefined) {
|
|
132
|
+
// Pre-protected and not mined - add as protected (bypass validation)
|
|
133
|
+
await this.#addNewProtectedTx(tx, preProtectedSlot);
|
|
134
|
+
accepted.push(txHash);
|
|
135
|
+
newlyAdded.push(tx);
|
|
136
|
+
} else {
|
|
137
|
+
// Regular pending tx - validate and run pre-add rules
|
|
138
|
+
const result = await this.#tryAddRegularPendingTx(tx, poolAccess, acceptedPending, ignored);
|
|
139
|
+
if (result.status === 'accepted') {
|
|
140
|
+
acceptedPending.add(txHashStr);
|
|
141
|
+
newlyAdded.push(tx);
|
|
142
|
+
} else if (result.status === 'rejected') {
|
|
143
|
+
rejected.push(txHash);
|
|
144
|
+
} else {
|
|
145
|
+
ignored.push(txHash);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
// Build final accepted list for pending txs (excludes intra-batch evictions)
|
|
151
|
+
for (const txHashStr of acceptedPending){
|
|
152
|
+
accepted.push(TxHash.fromString(txHashStr));
|
|
153
|
+
}
|
|
154
|
+
// Run post-add eviction rules for pending txs
|
|
155
|
+
if (acceptedPending.size > 0) {
|
|
156
|
+
const feePayers = Array.from(acceptedPending).map((txHash)=>this.#metadata.get(txHash).feePayer);
|
|
157
|
+
const uniqueFeePayers = new Set(feePayers);
|
|
158
|
+
await this.#evictionManager.evictAfterNewTxs(Array.from(acceptedPending), [
|
|
159
|
+
...uniqueFeePayers
|
|
160
|
+
]);
|
|
161
|
+
}
|
|
162
|
+
// Emit events
|
|
163
|
+
if (newlyAdded.length > 0) {
|
|
164
|
+
this.#callbacks.onTxsAdded(newlyAdded, opts);
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
accepted,
|
|
168
|
+
ignored,
|
|
169
|
+
rejected
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/** Validates and adds a regular pending tx. Returns status. */ async #tryAddRegularPendingTx(tx, poolAccess, acceptedPending, ignored) {
|
|
173
|
+
const txHash = tx.getTxHash();
|
|
174
|
+
const txHashStr = txHash.toString();
|
|
175
|
+
// Validate transaction
|
|
176
|
+
const validationResult = await this.#pendingTxValidator.validateTx(tx);
|
|
177
|
+
if (validationResult.result !== 'valid') {
|
|
178
|
+
this.#log.info(`Rejecting tx ${txHashStr}: ${validationResult.reason?.join(', ')}`);
|
|
179
|
+
return {
|
|
180
|
+
status: 'rejected'
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
// Build metadata and run pre-add rules
|
|
184
|
+
const meta = await buildTxMetaData(tx);
|
|
185
|
+
const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
|
|
186
|
+
if (preAddResult.shouldIgnore) {
|
|
187
|
+
this.#log.debug(`Ignoring tx ${txHashStr}: ${preAddResult.reason}`);
|
|
188
|
+
return {
|
|
189
|
+
status: 'ignored'
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
// Evict conflicts (tracking intra-batch evictions)
|
|
193
|
+
for (const evictHashStr of preAddResult.txHashesToEvict){
|
|
194
|
+
await this.#deleteTx(evictHashStr);
|
|
195
|
+
this.#log.debug(`Evicted tx ${evictHashStr} due to higher-fee tx ${txHashStr}`);
|
|
196
|
+
if (acceptedPending.has(evictHashStr)) {
|
|
197
|
+
acceptedPending.delete(evictHashStr);
|
|
198
|
+
ignored.push(TxHash.fromString(evictHashStr));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Add the transaction
|
|
202
|
+
await this.#addNewPendingTx(tx);
|
|
203
|
+
return {
|
|
204
|
+
status: 'accepted'
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
async canAddPendingTx(tx) {
|
|
208
|
+
const txHashStr = tx.getTxHash().toString();
|
|
209
|
+
// Check if already in pool
|
|
210
|
+
if (this.#metadata.has(txHashStr)) {
|
|
211
|
+
return 'ignored';
|
|
212
|
+
}
|
|
213
|
+
// Validate transaction
|
|
214
|
+
const validationResult = await this.#pendingTxValidator.validateTx(tx);
|
|
215
|
+
if (validationResult.result !== 'valid') {
|
|
216
|
+
return 'rejected';
|
|
217
|
+
}
|
|
218
|
+
// Build metadata and use pre-add rules
|
|
219
|
+
const meta = await buildTxMetaData(tx);
|
|
220
|
+
const poolAccess = this.#createPreAddPoolAccess();
|
|
221
|
+
const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
|
|
222
|
+
return preAddResult.shouldIgnore ? 'ignored' : 'accepted';
|
|
223
|
+
}
|
|
224
|
+
async addProtectedTxs(txs, block, opts) {
|
|
225
|
+
const slotNumber = block.globalVariables.slotNumber;
|
|
226
|
+
const newlyAdded = [];
|
|
227
|
+
await this.#store.transactionAsync(async ()=>{
|
|
228
|
+
for (const tx of txs){
|
|
229
|
+
const txHash = tx.getTxHash();
|
|
230
|
+
const txHashStr = txHash.toString();
|
|
231
|
+
const isNew = !this.#metadata.has(txHashStr);
|
|
232
|
+
const minedBlockId = await this.#getMinedBlockId(txHash);
|
|
233
|
+
if (isNew) {
|
|
234
|
+
// New tx - add as mined or protected
|
|
235
|
+
if (minedBlockId) {
|
|
236
|
+
await this.#addNewMinedTx(tx, minedBlockId);
|
|
237
|
+
this.#protectedTransactions.set(txHashStr, slotNumber);
|
|
238
|
+
} else {
|
|
239
|
+
await this.#addNewProtectedTx(tx, slotNumber);
|
|
240
|
+
}
|
|
241
|
+
newlyAdded.push(tx);
|
|
242
|
+
} else {
|
|
243
|
+
// Existing tx - update protection and mined status
|
|
244
|
+
this.#updateProtection(txHashStr, slotNumber);
|
|
245
|
+
if (minedBlockId) {
|
|
246
|
+
this.#markAsMined(this.#metadata.get(txHashStr), minedBlockId);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
if (newlyAdded.length > 0) {
|
|
252
|
+
this.#callbacks.onTxsAdded(newlyAdded, opts);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
protectTxs(txHashes, block) {
|
|
256
|
+
const slotNumber = block.globalVariables.slotNumber;
|
|
257
|
+
const missing = [];
|
|
258
|
+
for (const txHash of txHashes){
|
|
259
|
+
const txHashStr = txHash.toString();
|
|
260
|
+
if (this.#metadata.has(txHashStr)) {
|
|
261
|
+
// Step 1a: Update protection for existing tx
|
|
262
|
+
this.#updateProtection(txHashStr, slotNumber);
|
|
263
|
+
} else {
|
|
264
|
+
// Step 1b: Pre-record protection for tx we don't have yet
|
|
265
|
+
this.#protectedTransactions.set(txHashStr, slotNumber);
|
|
266
|
+
missing.push(txHash);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return missing;
|
|
270
|
+
}
|
|
271
|
+
async addMinedTxs(txs, block, opts) {
|
|
272
|
+
// Step 1: Build block ID
|
|
273
|
+
const blockId = await this.#buildBlockId(block);
|
|
274
|
+
const newlyAdded = [];
|
|
275
|
+
await this.#store.transactionAsync(async ()=>{
|
|
276
|
+
for (const tx of txs){
|
|
277
|
+
const txHashStr = tx.getTxHash().toString();
|
|
278
|
+
const existingMeta = this.#metadata.get(txHashStr);
|
|
279
|
+
if (existingMeta) {
|
|
280
|
+
// Step 2a: Mark existing tx as mined
|
|
281
|
+
this.#markAsMined(existingMeta, blockId);
|
|
282
|
+
} else {
|
|
283
|
+
// Step 2b: Add new mined tx
|
|
284
|
+
await this.#addNewMinedTx(tx, blockId);
|
|
285
|
+
newlyAdded.push(tx);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
// Step 3: Emit events for newly added txs
|
|
290
|
+
if (newlyAdded.length > 0) {
|
|
291
|
+
this.#callbacks.onTxsAdded(newlyAdded, opts);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
async handleMinedBlock(block) {
|
|
295
|
+
// Step 1: Build block ID
|
|
296
|
+
const blockId = await this.#buildBlockId(block.header);
|
|
297
|
+
// Step 2: Extract tx hashes and nullifiers directly from the block
|
|
298
|
+
const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
|
|
299
|
+
const nullifiers = block.body.txEffects.flatMap((tx)=>tx.nullifiers.map((n)=>n.toString()));
|
|
300
|
+
// Step 3: Collect fee payers from txs we have in the pool (for balance-based eviction)
|
|
301
|
+
const feePayers = [];
|
|
302
|
+
const found = [];
|
|
303
|
+
for (const txHash of txHashes){
|
|
304
|
+
const meta = this.#metadata.get(txHash.toString());
|
|
305
|
+
if (meta) {
|
|
306
|
+
feePayers.push(meta.feePayer);
|
|
307
|
+
found.push(meta);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Step 4: Mark txs as mined (only those we have in the pool)
|
|
311
|
+
this.#markTxsAsMined(found, blockId);
|
|
312
|
+
// Step 5: Run eviction rules (remove pending txs with conflicting nullifiers/expired timestamps)
|
|
313
|
+
await this.#evictionManager.evictAfterNewBlock(block.header, nullifiers, feePayers);
|
|
314
|
+
this.#callbacks.onTxsRemoved(txHashes.map((h)=>h.toBigInt()));
|
|
315
|
+
this.#log.info(`Marked ${found.length} txs as mined in block ${blockId.number}`);
|
|
316
|
+
}
|
|
317
|
+
async prepareForSlot(slotNumber) {
|
|
318
|
+
// Step 1: Find expired protected txs
|
|
319
|
+
const expiredProtected = this.#findExpiredProtectedTxs(slotNumber);
|
|
320
|
+
// Step 2: Clear protection for all expired entries (including those without metadata)
|
|
321
|
+
this.#clearProtection(expiredProtected);
|
|
322
|
+
// Step 3: Filter to only txs that have metadata and are not mined
|
|
323
|
+
const txsToRestore = this.#filterRestorable(expiredProtected);
|
|
324
|
+
if (txsToRestore.length === 0) {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
this.#log.info(`Preparing for slot ${slotNumber}: unprotecting ${txsToRestore.length} txs`);
|
|
328
|
+
// Step 4: Validate for pending pool
|
|
329
|
+
const { valid, invalid } = await this.#validateForPending(txsToRestore);
|
|
330
|
+
// Step 5: Resolve nullifier conflicts and add winners to pending indices
|
|
331
|
+
const { added, toEvict } = this.#applyNullifierConflictResolution(valid);
|
|
332
|
+
// Step 6: Delete invalid and evicted txs
|
|
333
|
+
await this.#deleteTxsBatch([
|
|
334
|
+
...invalid,
|
|
335
|
+
...toEvict
|
|
336
|
+
]);
|
|
337
|
+
// Step 7: Run eviction rules (enforce pool size limit)
|
|
338
|
+
if (added.length > 0) {
|
|
339
|
+
const feePayers = added.map((meta)=>meta.feePayer);
|
|
340
|
+
const uniqueFeePayers = new Set(feePayers);
|
|
341
|
+
await this.#evictionManager.evictAfterNewTxs(added.map((m)=>m.txHash), [
|
|
342
|
+
...uniqueFeePayers
|
|
343
|
+
]);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
async handlePrunedBlocks(latestBlock) {
|
|
347
|
+
// Step 1: Find transactions mined after the prune point
|
|
348
|
+
const txsToUnmine = this.#findTxsMinedAfter(latestBlock.number);
|
|
349
|
+
if (txsToUnmine.length === 0) {
|
|
350
|
+
this.#log.debug(`No transactions to un-mine for prune to block ${latestBlock.number}`);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
this.#log.info(`Handling prune to block ${latestBlock.number}: un-mining ${txsToUnmine.length} txs`);
|
|
354
|
+
// Step 2: Unmine - clear mined status from metadata
|
|
355
|
+
this.#unmineTxs(txsToUnmine);
|
|
356
|
+
// Step 3: Filter out protected txs (they'll be handled by prepareForSlot)
|
|
357
|
+
const unprotectedTxs = this.#filterUnprotected(txsToUnmine);
|
|
358
|
+
// Step 4: Validate for pending pool
|
|
359
|
+
const { valid, invalid } = await this.#validateForPending(unprotectedTxs);
|
|
360
|
+
// Step 5: Resolve nullifier conflicts and add winners to pending indices
|
|
361
|
+
const { toEvict } = this.#applyNullifierConflictResolution(valid);
|
|
362
|
+
// Step 6: Delete invalid and evicted txs
|
|
363
|
+
await this.#deleteTxsBatch([
|
|
364
|
+
...invalid,
|
|
365
|
+
...toEvict
|
|
366
|
+
]);
|
|
367
|
+
// Step 7: Run eviction rules for ALL pending txs (not just restored ones)
|
|
368
|
+
// This handles cases like existing pending txs with invalid fee payer balances
|
|
369
|
+
await this.#evictionManager.evictAfterChainPrune(latestBlock.number);
|
|
370
|
+
}
|
|
371
|
+
async handleFailedExecution(txHashes) {
|
|
372
|
+
// Step 1: Delete failed txs
|
|
373
|
+
await this.#deleteTxsBatch(txHashes.map((h)=>h.toString()));
|
|
374
|
+
this.#log.info(`Deleted ${txHashes.length} failed txs`);
|
|
375
|
+
}
|
|
376
|
+
async handleFinalizedBlock(block) {
|
|
377
|
+
const blockNumber = block.globalVariables.blockNumber;
|
|
378
|
+
// Step 1: Find txs mined at or before finalized block
|
|
379
|
+
const txsToFinalize = this.#findTxsMinedAtOrBefore(blockNumber);
|
|
380
|
+
if (txsToFinalize.length === 0) {
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
// Step 2: Collect txs for archiving (before deletion)
|
|
384
|
+
const txsToArchive = [];
|
|
385
|
+
if (this.#archive.isEnabled()) {
|
|
386
|
+
for (const txHashStr of txsToFinalize){
|
|
387
|
+
const buffer = await this.#txsDB.getAsync(txHashStr);
|
|
388
|
+
if (buffer) {
|
|
389
|
+
txsToArchive.push(Tx.fromBuffer(buffer));
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// Step 3: Delete from active pool
|
|
394
|
+
await this.#deleteTxsBatch(txsToFinalize);
|
|
395
|
+
// Step 4: Archive
|
|
396
|
+
if (txsToArchive.length > 0) {
|
|
397
|
+
await this.#archive.archiveTxs(txsToArchive);
|
|
398
|
+
}
|
|
399
|
+
this.#log.info(`Finalized ${txsToFinalize.length} txs from blocks up to ${blockNumber}`);
|
|
400
|
+
}
|
|
401
|
+
// === Query Methods ===
|
|
402
|
+
async getTxByHash(txHash) {
|
|
403
|
+
const buffer = await this.#txsDB.getAsync(txHash.toString());
|
|
404
|
+
return buffer ? Tx.fromBuffer(buffer) : undefined;
|
|
405
|
+
}
|
|
406
|
+
async getTxsByHash(txHashes) {
|
|
407
|
+
const results = [];
|
|
408
|
+
for (const h of txHashes){
|
|
409
|
+
const buffer = await this.#txsDB.getAsync(h.toString());
|
|
410
|
+
results.push(buffer ? Tx.fromBuffer(buffer) : undefined);
|
|
411
|
+
}
|
|
412
|
+
return results;
|
|
413
|
+
}
|
|
414
|
+
hasTxs(txHashes) {
|
|
415
|
+
return txHashes.map((h)=>this.#metadata.has(h.toString()));
|
|
416
|
+
}
|
|
417
|
+
getTxStatus(txHash) {
|
|
418
|
+
const meta = this.#metadata.get(txHash.toString());
|
|
419
|
+
if (!meta) {
|
|
420
|
+
return undefined;
|
|
421
|
+
}
|
|
422
|
+
return this.#getTxState(meta);
|
|
423
|
+
}
|
|
424
|
+
getPendingTxHashes() {
|
|
425
|
+
return [
|
|
426
|
+
...this.#iteratePendingByPriority('desc')
|
|
427
|
+
].map((hash)=>TxHash.fromString(hash));
|
|
428
|
+
}
|
|
429
|
+
getPendingTxCount() {
|
|
430
|
+
let count = 0;
|
|
431
|
+
for (const hashes of this.#pendingByPriority.values()){
|
|
432
|
+
count += hashes.size;
|
|
433
|
+
}
|
|
434
|
+
return count;
|
|
435
|
+
}
|
|
436
|
+
getMinedTxHashes() {
|
|
437
|
+
const result = [];
|
|
438
|
+
for (const [txHash, meta] of this.#metadata){
|
|
439
|
+
if (meta.minedL2BlockId !== undefined) {
|
|
440
|
+
result.push([
|
|
441
|
+
TxHash.fromString(txHash),
|
|
442
|
+
meta.minedL2BlockId
|
|
443
|
+
]);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return result;
|
|
447
|
+
}
|
|
448
|
+
getMinedTxCount() {
|
|
449
|
+
let count = 0;
|
|
450
|
+
for (const meta of this.#metadata.values()){
|
|
451
|
+
if (meta.minedL2BlockId !== undefined) {
|
|
452
|
+
count++;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return count;
|
|
456
|
+
}
|
|
457
|
+
isEmpty() {
|
|
458
|
+
return this.#metadata.size === 0;
|
|
459
|
+
}
|
|
460
|
+
getTxCount() {
|
|
461
|
+
return this.#metadata.size;
|
|
462
|
+
}
|
|
463
|
+
getArchivedTxByHash(txHash) {
|
|
464
|
+
return this.#archive.getTxByHash(txHash);
|
|
465
|
+
}
|
|
466
|
+
getLowestPriorityPending(limit) {
|
|
467
|
+
if (limit <= 0) {
|
|
468
|
+
return [];
|
|
469
|
+
}
|
|
470
|
+
const result = [];
|
|
471
|
+
for (const hash of this.#iteratePendingByPriority('asc')){
|
|
472
|
+
result.push(TxHash.fromString(hash));
|
|
473
|
+
if (result.length >= limit) {
|
|
474
|
+
break;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return result;
|
|
478
|
+
}
|
|
479
|
+
// === Configuration ===
|
|
480
|
+
updateConfig(config) {
|
|
481
|
+
if (config.maxPendingTxCount !== undefined) {
|
|
482
|
+
this.#config.maxPendingTxCount = config.maxPendingTxCount;
|
|
483
|
+
}
|
|
484
|
+
if (config.archivedTxLimit !== undefined) {
|
|
485
|
+
this.#config.archivedTxLimit = config.archivedTxLimit;
|
|
486
|
+
this.#archive.updateLimit(config.archivedTxLimit);
|
|
487
|
+
}
|
|
488
|
+
// Update eviction rules with new config
|
|
489
|
+
this.#evictionManager.updateConfig(config);
|
|
490
|
+
}
|
|
491
|
+
// === Pool Read Access ===
|
|
492
|
+
getPoolReadAccess() {
|
|
493
|
+
return {
|
|
494
|
+
getMetadata: (txHash)=>this.#metadata.get(txHash),
|
|
495
|
+
getTxHashByNullifier: (nullifier)=>this.#nullifierToTxHash.get(nullifier),
|
|
496
|
+
getTxHashesByFeePayer: (feePayer)=>this.#feePayerToTxHashes.get(feePayer),
|
|
497
|
+
getPendingTxCount: ()=>this.getPendingTxCount()
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
// === Metrics ===
|
|
501
|
+
countTxs() {
|
|
502
|
+
let pending = 0;
|
|
503
|
+
let protected_ = 0;
|
|
504
|
+
let mined = 0;
|
|
505
|
+
for (const meta of this.#metadata.values()){
|
|
506
|
+
const state = this.#getTxState(meta);
|
|
507
|
+
if (state === 'pending') {
|
|
508
|
+
pending++;
|
|
509
|
+
} else if (state === 'protected') {
|
|
510
|
+
protected_++;
|
|
511
|
+
} else if (state === 'mined') {
|
|
512
|
+
mined++;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
pending,
|
|
517
|
+
protected: protected_,
|
|
518
|
+
mined
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
// ============================================================================
|
|
522
|
+
// PRIVATE QUERY IMPLEMENTATIONS
|
|
523
|
+
// ============================================================================
|
|
524
|
+
/**
|
|
525
|
+
* Derives the transaction state from its metadata and protection status.
|
|
526
|
+
* A transaction is:
|
|
527
|
+
* - 'mined' if it has a minedL2BlockId
|
|
528
|
+
* - 'protected' if it's in the protectedTransactions map (but not mined)
|
|
529
|
+
* - 'pending' otherwise
|
|
530
|
+
*/ #getTxState(meta) {
|
|
531
|
+
if (meta.minedL2BlockId !== undefined) {
|
|
532
|
+
return 'mined';
|
|
533
|
+
} else if (this.#protectedTransactions.has(meta.txHash)) {
|
|
534
|
+
return 'protected';
|
|
535
|
+
} else {
|
|
536
|
+
return 'pending';
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Iterates pending transaction hashes in priority order.
|
|
541
|
+
* @param order - 'desc' for highest priority first, 'asc' for lowest priority first
|
|
542
|
+
*/ *#iteratePendingByPriority(order) {
|
|
543
|
+
// Use shared comparators, negating for descending order
|
|
544
|
+
const feeCompareFn = order === 'desc' ? (a, b)=>compareFee(b, a) : (a, b)=>compareFee(a, b);
|
|
545
|
+
const hashCompareFn = order === 'desc' ? (a, b)=>compareTxHash(b, a) : (a, b)=>compareTxHash(a, b);
|
|
546
|
+
const sortedFees = [
|
|
547
|
+
...this.#pendingByPriority.keys()
|
|
548
|
+
].sort(feeCompareFn);
|
|
549
|
+
for (const fee of sortedFees){
|
|
550
|
+
const hashesAtFee = this.#pendingByPriority.get(fee);
|
|
551
|
+
const sortedHashes = [
|
|
552
|
+
...hashesAtFee
|
|
553
|
+
].sort(hashCompareFn);
|
|
554
|
+
for (const hash of sortedHashes){
|
|
555
|
+
yield hash;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
// ============================================================================
|
|
560
|
+
// HELPER FUNCTIONS - Pipeline Step Functions
|
|
561
|
+
// ============================================================================
|
|
562
|
+
// --- Finding & Filtering Steps ---
|
|
563
|
+
/** Finds all transactions mined in blocks after the given block number */ #findTxsMinedAfter(blockNumber) {
|
|
564
|
+
const result = [];
|
|
565
|
+
for (const meta of this.#metadata.values()){
|
|
566
|
+
if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number > blockNumber) {
|
|
567
|
+
result.push(meta);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return result;
|
|
571
|
+
}
|
|
572
|
+
/** Finds tx hashes mined at or before the given block number */ #findTxsMinedAtOrBefore(blockNumber) {
|
|
573
|
+
const result = [];
|
|
574
|
+
for (const [txHashStr, meta] of this.#metadata){
|
|
575
|
+
if (meta.minedL2BlockId !== undefined && meta.minedL2BlockId.number <= blockNumber) {
|
|
576
|
+
result.push(txHashStr);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return result;
|
|
580
|
+
}
|
|
581
|
+
/** Finds protected tx hashes from slots earlier than the given slot number */ #findExpiredProtectedTxs(slotNumber) {
|
|
582
|
+
const result = [];
|
|
583
|
+
for (const [txHashStr, protectedSlot] of this.#protectedTransactions){
|
|
584
|
+
if (protectedSlot < slotNumber) {
|
|
585
|
+
result.push(txHashStr);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return result;
|
|
589
|
+
}
|
|
590
|
+
/** Filters out transactions that are currently protected */ #filterUnprotected(txs) {
|
|
591
|
+
return txs.filter((meta)=>!this.#protectedTransactions.has(meta.txHash));
|
|
592
|
+
}
|
|
593
|
+
/** Filters to transactions that have metadata and are not mined */ #filterRestorable(txHashes) {
|
|
594
|
+
const result = [];
|
|
595
|
+
for (const txHashStr of txHashes){
|
|
596
|
+
const meta = this.#metadata.get(txHashStr);
|
|
597
|
+
if (meta && meta.minedL2BlockId === undefined) {
|
|
598
|
+
result.push(meta);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
return result;
|
|
602
|
+
}
|
|
603
|
+
// --- Validation & Conflict Resolution Steps ---
|
|
604
|
+
/** Validates transactions for pending pool, returning valid and invalid groups */ async #validateForPending(txs) {
|
|
605
|
+
const valid = [];
|
|
606
|
+
const invalid = [];
|
|
607
|
+
for (const meta of txs){
|
|
608
|
+
const buffer = await this.#txsDB.getAsync(meta.txHash);
|
|
609
|
+
if (!buffer) {
|
|
610
|
+
this.#log.warn(`Tx ${meta.txHash} not found in DB during validation`);
|
|
611
|
+
invalid.push(meta.txHash);
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
const tx = Tx.fromBuffer(buffer);
|
|
615
|
+
const result = await this.#pendingTxValidator.validateTx(tx);
|
|
616
|
+
if (result.result === 'valid') {
|
|
617
|
+
valid.push(meta);
|
|
618
|
+
} else {
|
|
619
|
+
this.#log.info(`Tx ${meta.txHash} failed validation: ${result.reason?.join(', ')}`);
|
|
620
|
+
invalid.push(meta.txHash);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return {
|
|
624
|
+
valid,
|
|
625
|
+
invalid
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Resolves nullifier conflicts between incoming txs and existing pending txs.
|
|
630
|
+
* Modifies the pending indices during iteration to maintain consistent state
|
|
631
|
+
* for subsequent conflict checks within the same batch.
|
|
632
|
+
*/ #applyNullifierConflictResolution(txs) {
|
|
633
|
+
const added = [];
|
|
634
|
+
const toEvict = [];
|
|
635
|
+
for (const meta of txs){
|
|
636
|
+
const conflict = checkNullifierConflict(meta, (nullifier)=>this.#nullifierToTxHash.get(nullifier), (txHash)=>this.#metadata.get(txHash));
|
|
637
|
+
if (conflict.shouldIgnore) {
|
|
638
|
+
// Lower priority than existing - don't add, mark for deletion
|
|
639
|
+
toEvict.push(meta.txHash);
|
|
640
|
+
} else {
|
|
641
|
+
// Higher priority - evict existing conflicts
|
|
642
|
+
toEvict.push(...conflict.txHashesToEvict);
|
|
643
|
+
// Remove evicted from indices immediately for subsequent checks
|
|
644
|
+
for (const evictHash of conflict.txHashesToEvict){
|
|
645
|
+
const evictMeta = this.#metadata.get(evictHash);
|
|
646
|
+
if (evictMeta) {
|
|
647
|
+
this.#removeFromPendingIndices(evictMeta);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
// Add to pending indices immediately so subsequent txs in the batch see this tx
|
|
651
|
+
this.#addToPendingIndices(meta);
|
|
652
|
+
added.push(meta);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return {
|
|
656
|
+
added,
|
|
657
|
+
toEvict
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
// --- State Transition Steps ---
|
|
661
|
+
/** Clears the mined status from transactions, returning them for further processing */ #unmineTxs(txs) {
|
|
662
|
+
for (const meta of txs){
|
|
663
|
+
meta.minedL2BlockId = undefined;
|
|
664
|
+
}
|
|
665
|
+
return txs;
|
|
666
|
+
}
|
|
667
|
+
/** Removes protection from tx hashes and clears them from the protected map */ #clearProtection(txHashes) {
|
|
668
|
+
for (const txHashStr of txHashes){
|
|
669
|
+
this.#protectedTransactions.delete(txHashStr);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
// --- Batch Operation Steps ---
|
|
673
|
+
/** Deletes a batch of transactions permanently */ async #deleteTxsBatch(txHashes) {
|
|
674
|
+
if (txHashes.length === 0) {
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
await this.#store.transactionAsync(async ()=>{
|
|
678
|
+
for (const txHashStr of txHashes){
|
|
679
|
+
await this.#deleteTx(txHashStr);
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
this.#callbacks.onTxsRemoved(txHashes);
|
|
683
|
+
}
|
|
684
|
+
// --- Block & Tx Info Steps ---
|
|
685
|
+
/** Builds a block ID from a block header */ async #buildBlockId(block) {
|
|
686
|
+
return {
|
|
687
|
+
number: block.globalVariables.blockNumber,
|
|
688
|
+
hash: (await block.hash()).toString()
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
/** Checks if a tx is already mined and returns its block ID if so */ async #getMinedBlockId(txHash) {
|
|
692
|
+
const txEffect = await this.#l2BlockSource.getTxEffect(txHash);
|
|
693
|
+
if (!txEffect) {
|
|
694
|
+
return undefined;
|
|
695
|
+
}
|
|
696
|
+
return {
|
|
697
|
+
number: txEffect.l2BlockNumber,
|
|
698
|
+
hash: txEffect.l2BlockHash.toString()
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
/** Marks a batch of transactions as mined */ #markTxsAsMined(metas, blockId) {
|
|
702
|
+
for (const meta of metas){
|
|
703
|
+
this.#markAsMined(meta, blockId);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
// --- Add Transaction Steps ---
|
|
707
|
+
/** Persists a transaction to the database */ async #persistTx(txHashStr, tx) {
|
|
708
|
+
await this.#txsDB.set(txHashStr, tx.toBuffer());
|
|
709
|
+
}
|
|
710
|
+
/** Adds a new transaction as protected, returning its metadata */ async #addNewProtectedTx(tx, slotNumber) {
|
|
711
|
+
const txHashStr = tx.getTxHash().toString();
|
|
712
|
+
const meta = await buildTxMetaData(tx);
|
|
713
|
+
this.#protectedTransactions.set(txHashStr, slotNumber);
|
|
714
|
+
await this.#persistTx(txHashStr, tx);
|
|
715
|
+
this.#metadata.set(txHashStr, meta);
|
|
716
|
+
// Don't add to pending indices since it's protected
|
|
717
|
+
this.#log.verbose(`Added protected tx ${txHashStr} for slot ${slotNumber}`);
|
|
718
|
+
return meta;
|
|
719
|
+
}
|
|
720
|
+
/** Adds a new transaction as mined, returning its metadata */ async #addNewMinedTx(tx, blockId) {
|
|
721
|
+
const txHashStr = tx.getTxHash().toString();
|
|
722
|
+
const meta = await buildTxMetaData(tx);
|
|
723
|
+
meta.minedL2BlockId = blockId;
|
|
724
|
+
await this.#persistTx(txHashStr, tx);
|
|
725
|
+
this.#metadata.set(txHashStr, meta);
|
|
726
|
+
// Don't add to pending indices since it's mined
|
|
727
|
+
this.#log.verbose(`Added mined tx ${txHashStr} from block ${blockId.number}`);
|
|
728
|
+
return meta;
|
|
729
|
+
}
|
|
730
|
+
// --- Hydration Steps ---
|
|
731
|
+
/** Loads all transactions from the database, returning loaded txs and deserialization errors */ async #loadAllTxsFromDb() {
|
|
732
|
+
const loaded = [];
|
|
733
|
+
const errors = [];
|
|
734
|
+
for await (const [txHashStr, buffer] of this.#txsDB.entriesAsync()){
|
|
735
|
+
try {
|
|
736
|
+
const tx = Tx.fromBuffer(buffer);
|
|
737
|
+
const meta = await buildTxMetaData(tx);
|
|
738
|
+
loaded.push({
|
|
739
|
+
tx,
|
|
740
|
+
meta
|
|
741
|
+
});
|
|
742
|
+
} catch (err) {
|
|
743
|
+
this.#log.warn(`Failed to deserialize tx ${txHashStr}, deleting`, {
|
|
744
|
+
err
|
|
745
|
+
});
|
|
746
|
+
errors.push(txHashStr);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
return {
|
|
750
|
+
loaded,
|
|
751
|
+
errors
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
/** Queries block source and marks mined status on transaction metadata */ async #markMinedStatusBatch(metas) {
|
|
755
|
+
for (const meta of metas){
|
|
756
|
+
try {
|
|
757
|
+
const txEffect = await this.#l2BlockSource.getTxEffect(TxHash.fromString(meta.txHash));
|
|
758
|
+
if (txEffect) {
|
|
759
|
+
meta.minedL2BlockId = {
|
|
760
|
+
number: txEffect.l2BlockNumber,
|
|
761
|
+
hash: txEffect.l2BlockHash.toString()
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
} catch (err) {
|
|
765
|
+
this.#log.warn(`Failed to check mined status for tx ${meta.txHash}`, {
|
|
766
|
+
err
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/** Partitions transactions by mined status */ #partitionByMinedStatus(txs) {
|
|
772
|
+
const mined = [];
|
|
773
|
+
const nonMined = [];
|
|
774
|
+
for (const entry of txs){
|
|
775
|
+
if (entry.meta.minedL2BlockId !== undefined) {
|
|
776
|
+
mined.push(entry.meta);
|
|
777
|
+
} else {
|
|
778
|
+
nonMined.push(entry);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return {
|
|
782
|
+
mined,
|
|
783
|
+
nonMined
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/** Validates non-mined transactions, returning valid metadata and invalid hashes */ async #validateNonMinedTxs(txs) {
|
|
787
|
+
const valid = [];
|
|
788
|
+
const invalid = [];
|
|
789
|
+
for (const { tx, meta } of txs){
|
|
790
|
+
const result = await this.#pendingTxValidator.validateTx(tx);
|
|
791
|
+
if (result.result === 'valid') {
|
|
792
|
+
valid.push(meta);
|
|
793
|
+
} else {
|
|
794
|
+
this.#log.info(`Removing invalid tx ${meta.txHash} on startup: ${result.reason?.join(', ')}`);
|
|
795
|
+
invalid.push(meta.txHash);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
return {
|
|
799
|
+
valid,
|
|
800
|
+
invalid
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
/** Populates metadata index for mined transactions */ #populateMinedIndices(metas) {
|
|
804
|
+
for (const meta of metas){
|
|
805
|
+
this.#metadata.set(meta.txHash, meta);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Rebuilds the pending pool by processing each tx through pre-add rules.
|
|
810
|
+
* Starts with an empty pending pool and adds txs one by one, resolving conflicts.
|
|
811
|
+
* Returns the list of accepted and rejected tx hashes.
|
|
812
|
+
*/ async #rebuildPendingPool(metas) {
|
|
813
|
+
const accepted = new Set();
|
|
814
|
+
const rejected = [];
|
|
815
|
+
const poolAccess = this.#createPreAddPoolAccess();
|
|
816
|
+
for (const meta of metas){
|
|
817
|
+
// Run pre-add rules against current pending pool state (metadata not yet in pool)
|
|
818
|
+
const preAddResult = await this.#evictionManager.runPreAddRules(meta, poolAccess);
|
|
819
|
+
if (preAddResult.shouldIgnore) {
|
|
820
|
+
// Transaction rejected - mark for deletion from DB
|
|
821
|
+
rejected.push(meta.txHash);
|
|
822
|
+
this.#log.debug(`Rejected tx ${meta.txHash} during rebuild: ${preAddResult.reason}`);
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
// Evict any conflicting txs identified by pre-add rules
|
|
826
|
+
for (const evictHashStr of preAddResult.txHashesToEvict){
|
|
827
|
+
const evictMeta = this.#metadata.get(evictHashStr);
|
|
828
|
+
if (evictMeta) {
|
|
829
|
+
this.#removeFromPendingIndices(evictMeta);
|
|
830
|
+
this.#metadata.delete(evictHashStr);
|
|
831
|
+
rejected.push(evictHashStr);
|
|
832
|
+
accepted.delete(evictHashStr);
|
|
833
|
+
this.#log.debug(`Evicted tx ${evictHashStr} during rebuild due to conflict with ${meta.txHash}`);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
// Add to metadata and pending indices
|
|
837
|
+
this.#addToIndices(meta);
|
|
838
|
+
accepted.add(meta.txHash);
|
|
839
|
+
}
|
|
840
|
+
this.#log.info(`Rebuilt pending pool: ${accepted.size} accepted, ${rejected.length} rejected`);
|
|
841
|
+
return {
|
|
842
|
+
accepted: [
|
|
843
|
+
...accepted
|
|
844
|
+
],
|
|
845
|
+
rejected
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
// --- Add Pending Tx Steps ---
|
|
849
|
+
/** Checks if a tx is a duplicate (already in pool) */ #isDuplicateTx(txHashStr) {
|
|
850
|
+
return this.#metadata.has(txHashStr);
|
|
851
|
+
}
|
|
852
|
+
/** Adds a new pending tx to the pool, returning its metadata */ async #addNewPendingTx(tx) {
|
|
853
|
+
const txHashStr = tx.getTxHash().toString();
|
|
854
|
+
const meta = await buildTxMetaData(tx);
|
|
855
|
+
await this.#persistTx(txHashStr, tx);
|
|
856
|
+
this.#addToIndices(meta);
|
|
857
|
+
this.#log.verbose(`Added tx ${txHashStr} to pool`, {
|
|
858
|
+
eventName: 'tx-added-to-pool',
|
|
859
|
+
state: this.#getTxState(meta)
|
|
860
|
+
});
|
|
861
|
+
return meta;
|
|
862
|
+
}
|
|
863
|
+
// ============================================================================
|
|
864
|
+
// HELPER FUNCTIONS - Index Management
|
|
865
|
+
// ============================================================================
|
|
866
|
+
#addToIndices(meta) {
|
|
867
|
+
this.#metadata.set(meta.txHash, meta);
|
|
868
|
+
if (this.#getTxState(meta) === 'pending') {
|
|
869
|
+
this.#addToPendingIndices(meta);
|
|
870
|
+
}
|
|
871
|
+
// Protected and mined txs don't go into pending indices
|
|
872
|
+
}
|
|
873
|
+
#addToPendingIndices(meta) {
|
|
874
|
+
// Add to nullifier index
|
|
875
|
+
for (const nullifier of meta.nullifiers){
|
|
876
|
+
this.#nullifierToTxHash.set(nullifier, meta.txHash);
|
|
877
|
+
}
|
|
878
|
+
// Add to fee payer index
|
|
879
|
+
let feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
|
|
880
|
+
if (!feePayerSet) {
|
|
881
|
+
feePayerSet = new Set();
|
|
882
|
+
this.#feePayerToTxHashes.set(meta.feePayer, feePayerSet);
|
|
883
|
+
}
|
|
884
|
+
feePayerSet.add(meta.txHash);
|
|
885
|
+
// Add to priority bucket
|
|
886
|
+
let prioritySet = this.#pendingByPriority.get(meta.priorityFee);
|
|
887
|
+
if (!prioritySet) {
|
|
888
|
+
prioritySet = new Set();
|
|
889
|
+
this.#pendingByPriority.set(meta.priorityFee, prioritySet);
|
|
890
|
+
}
|
|
891
|
+
prioritySet.add(meta.txHash);
|
|
892
|
+
}
|
|
893
|
+
#removeFromPendingIndices(meta) {
|
|
894
|
+
// Remove from nullifier index
|
|
895
|
+
for (const nullifier of meta.nullifiers){
|
|
896
|
+
this.#nullifierToTxHash.delete(nullifier);
|
|
897
|
+
}
|
|
898
|
+
// Remove from fee payer index
|
|
899
|
+
const feePayerSet = this.#feePayerToTxHashes.get(meta.feePayer);
|
|
900
|
+
if (feePayerSet) {
|
|
901
|
+
feePayerSet.delete(meta.txHash);
|
|
902
|
+
if (feePayerSet.size === 0) {
|
|
903
|
+
this.#feePayerToTxHashes.delete(meta.feePayer);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
// Remove from priority map
|
|
907
|
+
const hashSet = this.#pendingByPriority.get(meta.priorityFee);
|
|
908
|
+
if (hashSet) {
|
|
909
|
+
hashSet.delete(meta.txHash);
|
|
910
|
+
if (hashSet.size === 0) {
|
|
911
|
+
this.#pendingByPriority.delete(meta.priorityFee);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
#updateProtection(txHashStr, slotNumber) {
|
|
916
|
+
const currentSlot = this.#protectedTransactions.get(txHashStr);
|
|
917
|
+
// Only update if not already protected at an equal or later slot
|
|
918
|
+
if (currentSlot !== undefined && currentSlot >= slotNumber) {
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
// Remove from pending indices if transitioning from pending to protected
|
|
922
|
+
if (currentSlot === undefined) {
|
|
923
|
+
const meta = this.#metadata.get(txHashStr);
|
|
924
|
+
if (meta) {
|
|
925
|
+
this.#removeFromPendingIndices(meta);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
this.#protectedTransactions.set(txHashStr, slotNumber);
|
|
929
|
+
}
|
|
930
|
+
#markAsMined(meta, blockId) {
|
|
931
|
+
meta.minedL2BlockId = blockId;
|
|
932
|
+
// Safe to call unconditionally - removeFromPendingIndices is idempotent
|
|
933
|
+
this.#removeFromPendingIndices(meta);
|
|
934
|
+
}
|
|
935
|
+
async #deleteTx(txHashStr) {
|
|
936
|
+
const meta = this.#metadata.get(txHashStr);
|
|
937
|
+
if (!meta) {
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
// Remove from all indices
|
|
941
|
+
this.#metadata.delete(txHashStr);
|
|
942
|
+
this.#protectedTransactions.delete(txHashStr);
|
|
943
|
+
this.#removeFromPendingIndices(meta);
|
|
944
|
+
// Remove from persistence
|
|
945
|
+
await this.#txsDB.delete(txHashStr);
|
|
946
|
+
}
|
|
947
|
+
// ============================================================================
|
|
948
|
+
// HELPER FUNCTIONS - Adapters
|
|
949
|
+
// ============================================================================
|
|
950
|
+
/** Gets all pending transactions for a given fee payer. */ #getFeePayerPendingTxs(feePayer) {
|
|
951
|
+
const txHashes = this.#feePayerToTxHashes.get(feePayer);
|
|
952
|
+
if (!txHashes) {
|
|
953
|
+
return [];
|
|
954
|
+
}
|
|
955
|
+
const result = [];
|
|
956
|
+
for (const txHashStr of txHashes){
|
|
957
|
+
const meta = this.#metadata.get(txHashStr);
|
|
958
|
+
if (meta && this.#getTxState(meta) === 'pending') {
|
|
959
|
+
result.push(meta);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return result;
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Creates a PoolOperations adapter for use with the eviction manager.
|
|
966
|
+
*/ #createPoolOperations() {
|
|
967
|
+
return {
|
|
968
|
+
getPendingTxs: ()=>{
|
|
969
|
+
const result = [];
|
|
970
|
+
for (const hashSet of this.#pendingByPriority.values()){
|
|
971
|
+
for (const txHashStr of hashSet){
|
|
972
|
+
const meta = this.#metadata.get(txHashStr);
|
|
973
|
+
if (meta) {
|
|
974
|
+
result.push(meta);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return result;
|
|
979
|
+
},
|
|
980
|
+
getPendingFeePayers: ()=>{
|
|
981
|
+
return Array.from(this.#feePayerToTxHashes.keys());
|
|
982
|
+
},
|
|
983
|
+
getFeePayerPendingTxs: (feePayer)=>{
|
|
984
|
+
return this.#getFeePayerPendingTxs(feePayer);
|
|
985
|
+
},
|
|
986
|
+
getPendingTxCount: ()=>{
|
|
987
|
+
return this.getPendingTxCount();
|
|
988
|
+
},
|
|
989
|
+
getLowestPriorityPending: (limit)=>{
|
|
990
|
+
return this.getLowestPriorityPending(limit).map((h)=>h.toString());
|
|
991
|
+
},
|
|
992
|
+
deleteTxs: async (txHashes)=>{
|
|
993
|
+
await this.#store.transactionAsync(async ()=>{
|
|
994
|
+
for (const txHashStr of txHashes){
|
|
995
|
+
await this.#deleteTx(txHashStr);
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
this.#callbacks.onTxsRemoved(txHashes);
|
|
999
|
+
}
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Creates a PreAddPoolAccess adapter for use with pre-add eviction rules.
|
|
1004
|
+
* All methods work with strings and TxMetaData for efficiency.
|
|
1005
|
+
*/ #createPreAddPoolAccess() {
|
|
1006
|
+
return {
|
|
1007
|
+
getMetadata: (txHashStr)=>{
|
|
1008
|
+
const meta = this.#metadata.get(txHashStr);
|
|
1009
|
+
if (!meta || this.#getTxState(meta) !== 'pending') {
|
|
1010
|
+
return undefined;
|
|
1011
|
+
}
|
|
1012
|
+
return meta;
|
|
1013
|
+
},
|
|
1014
|
+
getTxHashByNullifier: (nullifier)=>{
|
|
1015
|
+
return this.#nullifierToTxHash.get(nullifier);
|
|
1016
|
+
},
|
|
1017
|
+
getFeePayerBalance: async (feePayer)=>{
|
|
1018
|
+
const db = this.#worldStateSynchronizer.getCommitted();
|
|
1019
|
+
const publicStateSource = new DatabasePublicStateSource(db);
|
|
1020
|
+
const balance = await publicStateSource.storageRead(ProtocolContractAddress.FeeJuice, await computeFeePayerBalanceStorageSlot(AztecAddress.fromString(feePayer)));
|
|
1021
|
+
return balance.toBigInt();
|
|
1022
|
+
},
|
|
1023
|
+
getFeePayerPendingTxs: (feePayer)=>{
|
|
1024
|
+
return this.#getFeePayerPendingTxs(feePayer);
|
|
1025
|
+
},
|
|
1026
|
+
getPendingTxCount: ()=>{
|
|
1027
|
+
return this.getPendingTxCount();
|
|
1028
|
+
},
|
|
1029
|
+
getLowestPriorityPendingTx: ()=>{
|
|
1030
|
+
// Iterate in ascending order to find the lowest priority
|
|
1031
|
+
for (const txHashStr of this.#iteratePendingByPriority('asc')){
|
|
1032
|
+
const meta = this.#metadata.get(txHashStr);
|
|
1033
|
+
if (meta) {
|
|
1034
|
+
return meta;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
return undefined;
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
}
|