@aztec/p2p 0.0.1-commit.b9865e97 → 0.0.1-commit.be03c316

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.
Files changed (153) hide show
  1. package/README.md +7 -6
  2. package/dest/bootstrap/bootstrap.d.ts +1 -1
  3. package/dest/bootstrap/bootstrap.d.ts.map +1 -1
  4. package/dest/bootstrap/bootstrap.js +20 -12
  5. package/dest/client/factory.d.ts +2 -2
  6. package/dest/client/factory.d.ts.map +1 -1
  7. package/dest/client/factory.js +10 -5
  8. package/dest/client/interface.d.ts +36 -8
  9. package/dest/client/interface.d.ts.map +1 -1
  10. package/dest/client/p2p_client.d.ts +23 -12
  11. package/dest/client/p2p_client.d.ts.map +1 -1
  12. package/dest/client/p2p_client.js +38 -35
  13. package/dest/config.d.ts +19 -13
  14. package/dest/config.d.ts.map +1 -1
  15. package/dest/config.js +27 -26
  16. package/dest/errors/reqresp.error.d.ts +13 -1
  17. package/dest/errors/reqresp.error.d.ts.map +1 -1
  18. package/dest/errors/reqresp.error.js +14 -0
  19. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +4 -2
  20. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  21. package/dest/mem_pools/attestation_pool/attestation_pool.js +9 -2
  22. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +1 -1
  23. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  24. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +43 -0
  25. package/dest/mem_pools/instrumentation.d.ts +9 -4
  26. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  27. package/dest/mem_pools/instrumentation.js +11 -8
  28. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +3 -3
  29. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -1
  30. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +6 -6
  31. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +1 -1
  32. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +30 -5
  33. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  34. package/dest/mem_pools/tx_pool_v2/interfaces.js +2 -1
  35. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +15 -1
  36. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -1
  37. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +31 -0
  38. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +9 -3
  39. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -1
  40. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +19 -8
  41. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +17 -4
  42. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -1
  43. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +133 -34
  44. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +6 -5
  45. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  46. package/dest/msg_validators/attestation_validator/attestation_validator.js +24 -26
  47. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +4 -4
  48. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  49. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +2 -2
  50. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +4 -3
  51. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -1
  52. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +2 -2
  53. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +4 -3
  54. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -1
  55. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +8 -2
  56. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +19 -5
  57. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -1
  58. package/dest/msg_validators/proposal_validator/proposal_validator.js +66 -30
  59. package/dest/msg_validators/tx_validator/factory.d.ts +9 -11
  60. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  61. package/dest/msg_validators/tx_validator/factory.js +15 -6
  62. package/dest/msg_validators/tx_validator/gas_validator.d.ts +12 -7
  63. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  64. package/dest/msg_validators/tx_validator/gas_validator.js +15 -15
  65. package/dest/msg_validators/tx_validator/phases_validator.js +2 -2
  66. package/dest/services/discv5/discV5_service.d.ts +12 -2
  67. package/dest/services/discv5/discV5_service.d.ts.map +1 -1
  68. package/dest/services/discv5/discV5_service.js +84 -15
  69. package/dest/services/discv5/persisted_enr_store.d.ts +38 -0
  70. package/dest/services/discv5/persisted_enr_store.d.ts.map +1 -0
  71. package/dest/services/discv5/persisted_enr_store.js +145 -0
  72. package/dest/services/dummy_service.d.ts +6 -2
  73. package/dest/services/dummy_service.d.ts.map +1 -1
  74. package/dest/services/dummy_service.js +3 -0
  75. package/dest/services/encoding.d.ts +19 -6
  76. package/dest/services/encoding.d.ts.map +1 -1
  77. package/dest/services/encoding.js +25 -15
  78. package/dest/services/gossipsub/topic_score_params.d.ts +6 -23
  79. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -1
  80. package/dest/services/gossipsub/topic_score_params.js +4 -31
  81. package/dest/services/libp2p/libp2p_service.d.ts +11 -3
  82. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  83. package/dest/services/libp2p/libp2p_service.js +135 -53
  84. package/dest/services/peer-manager/peer_manager.d.ts +15 -2
  85. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  86. package/dest/services/peer-manager/peer_manager.js +46 -18
  87. package/dest/services/peer-manager/peer_scoring.d.ts +28 -1
  88. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  89. package/dest/services/peer-manager/peer_scoring.js +70 -3
  90. package/dest/services/reqresp/config.d.ts +13 -1
  91. package/dest/services/reqresp/config.d.ts.map +1 -1
  92. package/dest/services/reqresp/config.js +11 -0
  93. package/dest/services/reqresp/rate-limiter/rate_limits.js +3 -3
  94. package/dest/services/reqresp/reqresp.d.ts +1 -1
  95. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  96. package/dest/services/reqresp/reqresp.js +34 -3
  97. package/dest/services/service.d.ts +17 -1
  98. package/dest/services/service.d.ts.map +1 -1
  99. package/dest/services/tx_collection/tx_source.d.ts +1 -1
  100. package/dest/services/tx_collection/tx_source.d.ts.map +1 -1
  101. package/dest/services/tx_collection/tx_source.js +4 -1
  102. package/dest/test-helpers/testbench-utils.d.ts +4 -1
  103. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  104. package/dest/test-helpers/testbench-utils.js +9 -0
  105. package/dest/testbench/p2p_client_testbench_worker.d.ts +1 -1
  106. package/dest/testbench/p2p_client_testbench_worker.d.ts.map +1 -1
  107. package/dest/testbench/p2p_client_testbench_worker.js +19 -2
  108. package/package.json +16 -17
  109. package/src/bootstrap/bootstrap.ts +15 -9
  110. package/src/client/factory.ts +9 -5
  111. package/src/client/interface.ts +29 -6
  112. package/src/client/p2p_client.ts +46 -48
  113. package/src/config.ts +50 -38
  114. package/src/errors/reqresp.error.ts +19 -0
  115. package/src/mem_pools/attestation_pool/attestation_pool.ts +12 -2
  116. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +40 -1
  117. package/src/mem_pools/instrumentation.ts +13 -11
  118. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +7 -7
  119. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +1 -1
  120. package/src/mem_pools/tx_pool_v2/interfaces.ts +28 -4
  121. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +35 -0
  122. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +22 -8
  123. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +158 -33
  124. package/src/msg_validators/attestation_validator/attestation_validator.ts +26 -26
  125. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +4 -3
  126. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +4 -2
  127. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +10 -2
  128. package/src/msg_validators/proposal_validator/proposal_validator.ts +69 -30
  129. package/src/msg_validators/tx_validator/README.md +2 -0
  130. package/src/msg_validators/tx_validator/factory.ts +19 -13
  131. package/src/msg_validators/tx_validator/gas_validator.ts +16 -20
  132. package/src/msg_validators/tx_validator/phases_validator.ts +2 -2
  133. package/src/services/discv5/discV5_service.ts +88 -9
  134. package/src/services/discv5/persisted_enr_store.ts +158 -0
  135. package/src/services/dummy_service.ts +6 -0
  136. package/src/services/encoding.ts +28 -20
  137. package/src/services/gossipsub/README.md +33 -11
  138. package/src/services/gossipsub/topic_score_params.ts +9 -50
  139. package/src/services/libp2p/libp2p_service.ts +159 -56
  140. package/src/services/peer-manager/peer_manager.ts +48 -17
  141. package/src/services/peer-manager/peer_scoring.ts +75 -3
  142. package/src/services/reqresp/README.md +2 -23
  143. package/src/services/reqresp/config.ts +17 -0
  144. package/src/services/reqresp/rate-limiter/rate_limits.ts +3 -3
  145. package/src/services/reqresp/reqresp.ts +42 -2
  146. package/src/services/service.ts +19 -0
  147. package/src/services/tx_collection/tx_source.ts +2 -1
  148. package/src/test-helpers/testbench-utils.ts +12 -0
  149. package/src/testbench/p2p_client_testbench_worker.ts +22 -2
  150. package/dest/msg_validators/clock_tolerance.d.ts +0 -32
  151. package/dest/msg_validators/clock_tolerance.d.ts.map +0 -1
  152. package/dest/msg_validators/clock_tolerance.js +0 -90
  153. package/src/msg_validators/clock_tolerance.ts +0 -121
@@ -8,3 +8,22 @@ export class IndividualReqRespTimeoutError extends Error {
8
8
  super(`Request to peer timed out`);
9
9
  }
10
10
  }
11
+
12
+ /** Oversized reqresp request error
13
+ *
14
+ * Thrown locally (before dialing) when a request payload does not fit in a single muxer frame. Such a request would
15
+ * reach the responder split across multiple chunks, which are never reassembled into one request.
16
+ * @category Errors
17
+ */
18
+ export class OversizedReqRespRequestError extends Error {
19
+ constructor(
20
+ public readonly subProtocol: string,
21
+ public readonly payloadSizeBytes: number,
22
+ public readonly maxSizeBytes: number,
23
+ ) {
24
+ super(
25
+ `Request payload of ${payloadSizeBytes} bytes for ${subProtocol} exceeds the ${maxSizeBytes} byte limit of a single muxer frame`,
26
+ );
27
+ this.name = 'OversizedReqRespRequestError';
28
+ }
29
+ }
@@ -43,6 +43,7 @@ export type AttestationPoolApi = Pick<
43
43
  | 'getProposalsForSlot'
44
44
  | 'tryAddCheckpointProposal'
45
45
  | 'getCheckpointProposal'
46
+ | 'hasCheckpointProposalForSlot'
46
47
  | 'addOwnCheckpointAttestations'
47
48
  | 'tryAddCheckpointAttestation'
48
49
  | 'deleteOlderThan'
@@ -403,6 +404,11 @@ export class AttestationPool {
403
404
  return undefined;
404
405
  }
405
406
 
407
+ /** Returns whether any checkpoint proposal is retained for the given slot. */
408
+ public async hasCheckpointProposalForSlot(slot: SlotNumber): Promise<boolean> {
409
+ return (await this.getCheckpointProposal(slot)) !== undefined;
410
+ }
411
+
406
412
  /**
407
413
  * Adds own checkpoint attestations to the pool.
408
414
  * Skips per-signer cap and equivocation tracking; the caller is trusted.
@@ -428,7 +434,8 @@ export class AttestationPool {
428
434
  const ownKey = this.getSlotSignerKey(slotNumber, address);
429
435
  const payloadHash = attestation.getPayloadHash();
430
436
 
431
- await this.attestationPerSlotAndSigner.set(ownKey, attestation.toBuffer());
437
+ // Store the signature in canonical (v ∈ {27, 28}) form; see tryAddCheckpointAttestation.
438
+ await this.attestationPerSlotAndSigner.set(ownKey, attestation.withNormalizedSignature().toBuffer());
432
439
  this.metrics.trackMempoolItemAdded(ownKey);
433
440
 
434
441
  // Track our own payload hash so that an equivocating attestation from another
@@ -608,7 +615,10 @@ export class AttestationPool {
608
615
  // equivocations are detected via the multimap but their bytes are not retained.
609
616
  const alreadyHasStored = await this.attestationPerSlotAndSigner.hasAsync(slotSignerKey);
610
617
  if (!alreadyHasStored) {
611
- await this.attestationPerSlotAndSigner.set(slotSignerKey, attestation.toBuffer());
618
+ // Store the signature in canonical (v ∈ {27, 28}) form. `sender` recovered above, so the
619
+ // signature is non-empty and safe to normalize; this keeps a yParity-encoded (v = 0/1) variant
620
+ // from a malicious peer or an in-flight byte mutation out of the L1 bundle downstream.
621
+ await this.attestationPerSlotAndSigner.set(slotSignerKey, attestation.withNormalizedSignature().toBuffer());
612
622
  this.metrics.trackMempoolItemAdded(slotSignerKey);
613
623
  }
614
624
 
@@ -1,7 +1,9 @@
1
1
  import { IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
2
  import { Secp256k1Signer } from '@aztec/foundation/crypto/secp256k1-signer';
3
3
  import { Fr } from '@aztec/foundation/curves/bn254';
4
- import type { BlockProposal, CheckpointAttestation, CheckpointProposalCore } from '@aztec/stdlib/p2p';
4
+ import { Signature } from '@aztec/foundation/eth-signature';
5
+ import type { BlockProposal, CheckpointProposalCore } from '@aztec/stdlib/p2p';
6
+ import { CheckpointAttestation } from '@aztec/stdlib/p2p';
5
7
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
6
8
  import {
7
9
  makeBlockHeader,
@@ -62,7 +64,44 @@ export function describeAttestationPool(getAttestationPool: () => AttestationPoo
62
64
  expect(a1Buffer).toEqual(expect.arrayContaining(a2Buffer));
63
65
  };
64
66
 
67
+ /**
68
+ * Rewrites the attester signature into yParity form (27 -> 0, 28 -> 1), keeping (r, s). The recovery
69
+ * bit is unchanged so it still recovers to the same signer, mimicking a peer that gossips (or mutates
70
+ * in flight) a signature with a non-canonical recovery byte.
71
+ */
72
+ const toYParityForm = (attestation: CheckpointAttestation): CheckpointAttestation => {
73
+ const sig = attestation.signature;
74
+ const yParityV = sig.v === 27 ? 0 : sig.v === 28 ? 1 : sig.v;
75
+ return new CheckpointAttestation(
76
+ attestation.payload,
77
+ new Signature(sig.r, sig.s, yParityV),
78
+ attestation.proposerSignature,
79
+ );
80
+ };
81
+
65
82
  describe('CheckpointAttestation', () => {
83
+ it('normalizes yParity (v=0/v=1) attester signatures on ingress from both gossip and own keys', async () => {
84
+ const slotNumber = 421;
85
+ const canonical = createCheckpointAttestationsForSlot(slotNumber);
86
+ const payloadHash = canonical[0].getPayloadHash();
87
+ const expectedSenders = new Set([canonical[0].getSender()!.toString(), canonical[1].getSender()!.toString()]);
88
+
89
+ const gossiped = toYParityForm(canonical[0]);
90
+ expect([0, 1]).toContain(gossiped.signature.v);
91
+ await ap.tryAddCheckpointAttestation(gossiped);
92
+
93
+ const own = toYParityForm(canonical[1]);
94
+ expect([0, 1]).toContain(own.signature.v);
95
+ await ap.addOwnCheckpointAttestations([own]);
96
+
97
+ const retrieved = await ap.getCheckpointAttestationsForSlotAndProposal(SlotNumber(slotNumber), payloadHash);
98
+ expect(retrieved.length).toBe(2);
99
+ for (const attestation of retrieved) {
100
+ expect([27, 28]).toContain(attestation.signature.v);
101
+ expect(expectedSenders.has(attestation.getSender()!.toString())).toBe(true);
102
+ }
103
+ });
104
+
66
105
  it('should add attestations to pool', async () => {
67
106
  const slotNumber = 420;
68
107
  const archive = Fr.random();
@@ -1,5 +1,4 @@
1
1
  import type { Gossipable } from '@aztec/stdlib/p2p';
2
- import type { Tx } from '@aztec/stdlib/tx';
3
2
  import {
4
3
  Attributes,
5
4
  type BatchObservableResult,
@@ -117,16 +116,6 @@ export class PoolInstrumentation<PoolObject extends Gossipable> {
117
116
  this.addObjectCounter.add(count);
118
117
  }
119
118
 
120
- public transactionsAdded(transactions: Tx[]) {
121
- transactions.forEach(tx => this.trackMempoolItemAdded(tx.txHash.toBigInt()));
122
- }
123
-
124
- public transactionsRemoved(hashes: Iterable<bigint> | Iterable<string>) {
125
- for (const hash of hashes) {
126
- this.trackMempoolItemRemoved(BigInt(hash));
127
- }
128
- }
129
-
130
119
  public trackMempoolItemAdded(key: bigint | string): void {
131
120
  this.mempoolItemAddedTimestamp.set(key, Date.now());
132
121
  }
@@ -142,6 +131,19 @@ export class PoolInstrumentation<PoolObject extends Gossipable> {
142
131
  }
143
132
  }
144
133
 
134
+ /**
135
+ * Records a pre-computed pending-to-mined delay directly, bypassing the
136
+ * `mempoolItemAddedTimestamp` map. Used by the tx pool, which derives the
137
+ * delay from the persisted `receivedAt` on tx metadata at the mined
138
+ * transition — more accurate than the add/remove map (which also fires on
139
+ * eviction) and resilient to the caller not having tracked the add.
140
+ */
141
+ public recordMinedDelay(delayMs: number): void {
142
+ if (delayMs > 0) {
143
+ this.minedDelay.record(delayMs);
144
+ }
145
+ }
146
+
145
147
  private observeStats = async (observer: BatchObservableResult) => {
146
148
  const { itemCount } = await this.poolStats();
147
149
  if (typeof itemCount === 'number') {
@@ -52,8 +52,8 @@ export class DeletedPool {
52
52
  /** Persisted map: txHash -> DeletedTxState (serialized) - for prune-based soft deletions */
53
53
  #deletedTxsDB: AztecAsyncMap<string, Buffer>;
54
54
 
55
- /** Reference to the main txs database for hard deletion */
56
- #txsDB: AztecAsyncMap<string, Buffer>;
55
+ /** Hard-deletes a tx's stored data (tx blob and proof) from the pool's stores. */
56
+ #deleteTxData: (txHash: string) => Promise<void>;
57
57
 
58
58
  /** In-memory state for transactions from pruned blocks */
59
59
  #state: Map<string, DeletedTxState> = new Map();
@@ -69,10 +69,10 @@ export class DeletedPool {
69
69
 
70
70
  #log: Logger;
71
71
 
72
- constructor(store: AztecAsyncKVStore, txsDB: AztecAsyncMap<string, Buffer>, log: Logger) {
72
+ constructor(store: AztecAsyncKVStore, deleteTxData: (txHash: string) => Promise<void>, log: Logger) {
73
73
  this.#deletedTxsDB = store.openMap('deleted_txs');
74
74
  this.#slotDeletedDB = store.openSet('slot_deleted_txs');
75
- this.#txsDB = txsDB;
75
+ this.#deleteTxData = deleteTxData;
76
76
  this.#log = log;
77
77
  }
78
78
 
@@ -100,7 +100,7 @@ export class DeletedPool {
100
100
  // Slot-deleted txs are stale after restart - hard-delete them all
101
101
  let slotDeletedCount = 0;
102
102
  for await (const txHash of this.#slotDeletedDB.entriesAsync()) {
103
- await this.#txsDB.delete(txHash);
103
+ await this.#deleteTxData(txHash);
104
104
  await this.#slotDeletedDB.delete(txHash);
105
105
  slotDeletedCount++;
106
106
  }
@@ -234,7 +234,7 @@ export class DeletedPool {
234
234
  for (const txHash of toHardDelete) {
235
235
  this.#state.delete(txHash);
236
236
  await this.#deletedTxsDB.delete(txHash);
237
- await this.#txsDB.delete(txHash);
237
+ await this.#deleteTxData(txHash);
238
238
  }
239
239
 
240
240
  this.#log.debug(`Finalized ${toHardDelete.length} txs from pruned blocks at block ${finalizedBlockNumber}`, {
@@ -266,7 +266,7 @@ export class DeletedPool {
266
266
  for (const txHash of toHardDelete) {
267
267
  this.#slotDeletedTxs.delete(txHash);
268
268
  await this.#slotDeletedDB.delete(txHash);
269
- await this.#txsDB.delete(txHash);
269
+ await this.#deleteTxData(txHash);
270
270
  }
271
271
 
272
272
  this.#log.debug(
@@ -86,7 +86,7 @@ export class FeePayerBalanceEvictionRule implements EvictionRule {
86
86
  publicStateSource: DatabasePublicStateSource,
87
87
  pool: PoolOperations,
88
88
  ): Promise<string[]> {
89
- const feePayer = AztecAddress.fromString(feePayerStr);
89
+ const feePayer = AztecAddress.fromStringUnsafe(feePayerStr);
90
90
  const initialBalance = (
91
91
  await publicStateSource.storageRead(
92
92
  ProtocolContractAddress.FeeJuice,
@@ -49,6 +49,11 @@ export type TxPoolV2Config = {
49
49
  dropTransactionsProbability: number;
50
50
  /** Minimum percentage fee increase required to replace an existing tx via RPC (0 = no bump). */
51
51
  priceBumpPercentage: bigint;
52
+ /**
53
+ * Number of slots behind the finalized tip to keep finalized txs for before deleting them. 0 deletes
54
+ * at the finalized tip (default).
55
+ */
56
+ keepFinalizedTxsForSlots: number;
52
57
  };
53
58
 
54
59
  /**
@@ -61,6 +66,7 @@ export const DEFAULT_TX_POOL_V2_CONFIG: TxPoolV2Config = {
61
66
  evictedTxCacheSize: 10_000,
62
67
  dropTransactionsProbability: 0,
63
68
  priceBumpPercentage: 10n,
69
+ keepFinalizedTxsForSlots: 0,
64
70
  };
65
71
 
66
72
  /**
@@ -170,6 +176,17 @@ export interface TxPoolV2 extends TypedEventEmitter<TxPoolV2Events> {
170
176
  */
171
177
  prepareForSlot(slotNumber: SlotNumber): Promise<void>;
172
178
 
179
+ /**
180
+ * Releases the protections a failed block proposal created and restores the txs to pending.
181
+ * Only clears protection entries still recorded at exactly the given slot: a tx that another,
182
+ * still-live proposal raised to a higher slot via {@link protectTxs} keeps its protection, and
183
+ * mined txs (which carry no protection entry) are left untouched. Restored txs are re-validated
184
+ * and resolved against nullifier conflicts before re-entering the pending indices.
185
+ * @param txHashes - Hashes of the proposal's txs to release.
186
+ * @param slotNumber - The slot the failed proposal targeted; protection is released only for this slot.
187
+ */
188
+ unprotectTxs(txHashes: TxHash[], slotNumber: SlotNumber): Promise<void>;
189
+
173
190
  /**
174
191
  * Handles pruned blocks during a reorg.
175
192
  * Un-mines all transactions mined in blocks beyond the given latest block
@@ -192,11 +209,11 @@ export interface TxPoolV2 extends TypedEventEmitter<TxPoolV2Events> {
192
209
  */
193
210
  handleFinalizedBlock(block: BlockHeader): Promise<void>;
194
211
 
195
- /** Gets a transaction by its hash */
196
- getTxByHash(txHash: TxHash): Promise<Tx | undefined>;
212
+ /** Gets a transaction by its hash. Set `includeProof: false` to skip loading the proof from the DB. */
213
+ getTxByHash(txHash: TxHash, opts?: { includeProof?: boolean }): Promise<Tx | undefined>;
197
214
 
198
- /** Gets multiple transactions by their hashes */
199
- getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]>;
215
+ /** Gets multiple transactions by their hashes. Set `includeProof: false` to skip loading proofs from the DB. */
216
+ getTxsByHash(txHashes: TxHash[], opts?: { includeProof?: boolean }): Promise<(Tx | undefined)[]>;
200
217
 
201
218
  /** Checks if transactions exist in the pool */
202
219
  hasTxs(txHashes: TxHash[]): Promise<boolean[]>;
@@ -213,6 +230,13 @@ export interface TxPoolV2 extends TypedEventEmitter<TxPoolV2Events> {
213
230
  /** Gets the count of pending transactions */
214
231
  getPendingTxCount(): Promise<number>;
215
232
 
233
+ /**
234
+ * Returns whether at least `minCount` pending transactions are old enough per minTxPoolAgeMs to be eligible
235
+ * for block building. Stops scanning once the threshold is reached, so it is cheaper than counting all
236
+ * eligible txs when only a few are needed.
237
+ */
238
+ hasEligiblePendingTxs(minCount: number): Promise<boolean>;
239
+
216
240
  /** Gets mined transaction hashes with their block IDs */
217
241
  getMinedTxHashes(): Promise<[TxHash, L2BlockId][]>;
218
242
 
@@ -131,6 +131,9 @@ export class TxPoolIndices {
131
131
  meta.minedL2BlockId = blockId;
132
132
  // Safe to call unconditionally - removeFromPendingIndices is idempotent
133
133
  this.#removeFromPendingIndices(meta);
134
+ // A mined tx supersedes any protection: drop the stale entry so it can't linger in the map and
135
+ // be matched by later protection scans.
136
+ this.#protectedTransactions.delete(meta.txHash);
134
137
  }
135
138
 
136
139
  /** Clears the mined status from a transaction */
@@ -225,6 +228,29 @@ export class TxPoolIndices {
225
228
  return this.#pendingByPriority.length;
226
229
  }
227
230
 
231
+ /**
232
+ * Returns whether at least `minCount` pending transactions were received at or before maxReceivedAt,
233
+ * i.e. are old enough to be eligible for block building. Stops as soon as the threshold is met, so it
234
+ * does not scan the whole pool when only a handful of eligible txs are needed. The total pending count
235
+ * is an upper bound on the eligible count, so a pool with fewer than `minCount` pending can never
236
+ * satisfy the threshold and short-circuits without scanning.
237
+ */
238
+ hasEligiblePendingTxs(maxReceivedAt: number, minCount: number): boolean {
239
+ if (minCount <= 0) {
240
+ return true;
241
+ }
242
+ if (this.#pendingByPriority.length < minCount) {
243
+ return false;
244
+ }
245
+ let count = 0;
246
+ for (const _ of this.iterateEligiblePendingByPriority('desc', maxReceivedAt)) {
247
+ if (++count >= minCount) {
248
+ return true;
249
+ }
250
+ }
251
+ return false;
252
+ }
253
+
228
254
  /** Gets the lowest priority pending transaction hashes (up to limit) */
229
255
  getLowestPriorityPending(limit: number): string[] {
230
256
  if (limit <= 0) {
@@ -316,6 +342,15 @@ export class TxPoolIndices {
316
342
  return result;
317
343
  }
318
344
 
345
+ /**
346
+ * From the given hashes, returns those whose protection is recorded at exactly the given slot.
347
+ * Used to release the protections a single block proposal created without disturbing entries a
348
+ * later proposal raised to a higher slot via updateProtection.
349
+ */
350
+ findProtectedTxsAtSlot(txHashes: string[], slotNumber: SlotNumber): string[] {
351
+ return txHashes.filter(txHash => this.#protectedTransactions.get(txHash) === slotNumber);
352
+ }
353
+
319
354
  /** Filters out transactions that are currently protected */
320
355
  filterUnprotected(txs: TxMetaData[]): TxMetaData[] {
321
356
  return txs.filter(meta => !this.#protectedTransactions.has(meta.txHash));
@@ -20,6 +20,7 @@ import type {
20
20
  TxPoolV2Events,
21
21
  } from './interfaces.js';
22
22
  import type { TxState } from './tx_metadata.js';
23
+ import type { MinedTxInfo } from './tx_pool_v2_impl.js';
23
24
  import { TxPoolV2Impl } from './tx_pool_v2_impl.js';
24
25
 
25
26
  /**
@@ -56,17 +57,22 @@ export class AztecKVTxPoolV2 extends (EventEmitter as new () => TypedEventEmitte
56
57
  // Create callbacks that the impl uses to notify us about events and metrics
57
58
  const callbacks = {
58
59
  onTxsAdded: (txs: Tx[], opts: { source?: string }) => {
59
- this.#metrics?.transactionsAdded(txs);
60
60
  this.emit('txs-added', { txs, ...opts });
61
61
  },
62
62
  onTxsRemoved: (txHashes: string[] | bigint[]) => {
63
- this.#metrics?.transactionsRemoved(txHashes);
64
63
  // Convert to TxHash objects for the event
65
64
  const hashes = txHashes.map(h => (typeof h === 'string' ? TxHash.fromString(h) : TxHash.fromBigInt(h)));
66
65
  this.emit('txs-removed', { txHashes: hashes });
67
66
  },
68
- onTxsMined: (txHashes: string[]) => {
69
- this.#metrics?.transactionsRemoved(txHashes);
67
+ onTxsMined: (minedTxs: MinedTxInfo[]) => {
68
+ // Pending-to-mined delay is derived from the tx's persisted receivedAt at the mined
69
+ // transition (see TxPoolV2Impl.handleMinedBlock), not the add/remove timestamp map —
70
+ // so eviction no longer pollutes MEMPOOL_TX_MINED_DELAY.
71
+ for (const { minedDelayMs } of minedTxs) {
72
+ if (minedDelayMs !== undefined) {
73
+ this.#metrics?.recordMinedDelay(minedDelayMs);
74
+ }
75
+ }
70
76
  },
71
77
  };
72
78
 
@@ -110,6 +116,10 @@ export class AztecKVTxPoolV2 extends (EventEmitter as new () => TypedEventEmitte
110
116
  return this.#queue.put(() => this.#impl.prepareForSlot(slotNumber));
111
117
  }
112
118
 
119
+ unprotectTxs(txHashes: TxHash[], slotNumber: SlotNumber): Promise<void> {
120
+ return this.#queue.put(() => this.#impl.unprotectTxs(txHashes, slotNumber));
121
+ }
122
+
113
123
  handlePrunedBlocks(latestBlock: L2BlockId, options?: { deleteAllTxs?: boolean }): Promise<void> {
114
124
  return this.#queue.put(() => this.#impl.handlePrunedBlocks(latestBlock, options));
115
125
  }
@@ -124,12 +134,12 @@ export class AztecKVTxPoolV2 extends (EventEmitter as new () => TypedEventEmitte
124
134
 
125
135
  // === Queries ===
126
136
 
127
- getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
128
- return this.#queue.put(() => this.#impl.getTxByHash(txHash));
137
+ getTxByHash(txHash: TxHash, opts?: { includeProof?: boolean }): Promise<Tx | undefined> {
138
+ return this.#queue.put(() => this.#impl.getTxByHash(txHash, opts));
129
139
  }
130
140
 
131
- getTxsByHash(txHashes: TxHash[]): Promise<(Tx | undefined)[]> {
132
- return this.#queue.put(() => this.#impl.getTxsByHash(txHashes));
141
+ getTxsByHash(txHashes: TxHash[], opts?: { includeProof?: boolean }): Promise<(Tx | undefined)[]> {
142
+ return this.#queue.put(() => this.#impl.getTxsByHash(txHashes, opts));
133
143
  }
134
144
 
135
145
  hasTxs(txHashes: TxHash[]): Promise<boolean[]> {
@@ -152,6 +162,10 @@ export class AztecKVTxPoolV2 extends (EventEmitter as new () => TypedEventEmitte
152
162
  return this.#queue.put(() => Promise.resolve(this.#impl.getPendingTxCount()));
153
163
  }
154
164
 
165
+ hasEligiblePendingTxs(minCount: number): Promise<boolean> {
166
+ return this.#queue.put(() => Promise.resolve(this.#impl.hasEligiblePendingTxs(minCount)));
167
+ }
168
+
155
169
  getMinedTxHashes(): Promise<[TxHash, L2BlockId][]> {
156
170
  return this.#queue.put(() => Promise.resolve(this.#impl.getMinedTxHashes()));
157
171
  }