@aztec/p2p 0.0.1-commit.d3ec352c → 0.0.1-commit.f295ac2

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 (263) hide show
  1. package/dest/client/factory.d.ts +2 -2
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +2 -3
  4. package/dest/client/interface.d.ts +18 -5
  5. package/dest/client/interface.d.ts.map +1 -1
  6. package/dest/client/p2p_client.d.ts +11 -14
  7. package/dest/client/p2p_client.d.ts.map +1 -1
  8. package/dest/client/p2p_client.js +456 -124
  9. package/dest/config.d.ts +4 -7
  10. package/dest/config.d.ts.map +1 -1
  11. package/dest/config.js +10 -13
  12. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +61 -42
  13. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  14. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +1 -1
  15. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  16. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +239 -265
  17. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +21 -18
  18. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +1 -1
  19. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +114 -109
  20. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +17 -16
  21. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +1 -1
  22. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +89 -128
  23. package/dest/mem_pools/attestation_pool/mocks.d.ts +11 -8
  24. package/dest/mem_pools/attestation_pool/mocks.d.ts.map +1 -1
  25. package/dest/mem_pools/attestation_pool/mocks.js +17 -13
  26. package/dest/mem_pools/instrumentation.d.ts +7 -1
  27. package/dest/mem_pools/instrumentation.d.ts.map +1 -1
  28. package/dest/mem_pools/instrumentation.js +30 -12
  29. package/dest/mem_pools/interface.d.ts +3 -4
  30. package/dest/mem_pools/interface.d.ts.map +1 -1
  31. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts +36 -27
  32. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.d.ts.map +1 -1
  33. package/dest/mem_pools/tx_pool/aztec_kv_tx_pool.js +314 -335
  34. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts +31 -0
  35. package/dest/mem_pools/tx_pool/eviction/eviction_manager.d.ts.map +1 -0
  36. package/dest/mem_pools/tx_pool/eviction/eviction_manager.js +112 -0
  37. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts +156 -0
  38. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.d.ts.map +1 -0
  39. package/dest/mem_pools/tx_pool/eviction/eviction_strategy.js +52 -0
  40. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts +16 -0
  41. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -0
  42. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.js +115 -0
  43. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts +17 -0
  44. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.d.ts.map +1 -0
  45. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.js +84 -0
  46. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts +19 -0
  47. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.d.ts.map +1 -0
  48. package/dest/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.js +76 -0
  49. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts +26 -0
  50. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.d.ts.map +1 -0
  51. package/dest/mem_pools/tx_pool/eviction/low_priority_eviction_rule.js +84 -0
  52. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts +25 -0
  53. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.d.ts.map +1 -0
  54. package/dest/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.js +57 -0
  55. package/dest/mem_pools/tx_pool/index.d.ts +1 -2
  56. package/dest/mem_pools/tx_pool/index.d.ts.map +1 -1
  57. package/dest/mem_pools/tx_pool/index.js +0 -1
  58. package/dest/mem_pools/tx_pool/priority.d.ts +5 -1
  59. package/dest/mem_pools/tx_pool/priority.d.ts.map +1 -1
  60. package/dest/mem_pools/tx_pool/priority.js +6 -1
  61. package/dest/mem_pools/tx_pool/tx_pool.d.ts +8 -4
  62. package/dest/mem_pools/tx_pool/tx_pool.d.ts.map +1 -1
  63. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +1 -1
  64. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +1 -1
  65. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +25 -20
  66. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts +4 -4
  67. package/dest/msg_validators/attestation_validator/attestation_validator.d.ts.map +1 -1
  68. package/dest/msg_validators/attestation_validator/attestation_validator.js +13 -11
  69. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +5 -5
  70. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  71. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.js +7 -10
  72. package/dest/msg_validators/index.d.ts +2 -2
  73. package/dest/msg_validators/index.d.ts.map +1 -1
  74. package/dest/msg_validators/index.js +1 -1
  75. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +9 -0
  76. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -0
  77. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +6 -0
  78. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +9 -0
  79. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -0
  80. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +6 -0
  81. package/dest/msg_validators/proposal_validator/index.d.ts +4 -0
  82. package/dest/msg_validators/proposal_validator/index.d.ts.map +1 -0
  83. package/dest/msg_validators/proposal_validator/index.js +3 -0
  84. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +13 -0
  85. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -0
  86. package/dest/msg_validators/{block_proposal_validator/block_proposal_validator.js → proposal_validator/proposal_validator.js} +20 -22
  87. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts +23 -0
  88. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts.map +1 -0
  89. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.js +183 -0
  90. package/dest/msg_validators/tx_validator/archive_cache.d.ts +2 -2
  91. package/dest/msg_validators/tx_validator/archive_cache.d.ts.map +1 -1
  92. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +2 -2
  93. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  94. package/dest/msg_validators/tx_validator/data_validator.d.ts +1 -1
  95. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  96. package/dest/msg_validators/tx_validator/factory.d.ts +2 -2
  97. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  98. package/dest/msg_validators/tx_validator/factory.js +1 -1
  99. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +10 -0
  100. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -0
  101. package/dest/msg_validators/tx_validator/fee_payer_balance.js +20 -0
  102. package/dest/msg_validators/tx_validator/gas_validator.d.ts +1 -1
  103. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  104. package/dest/msg_validators/tx_validator/gas_validator.js +8 -14
  105. package/dest/msg_validators/tx_validator/metadata_validator.d.ts +2 -2
  106. package/dest/msg_validators/tx_validator/metadata_validator.d.ts.map +1 -1
  107. package/dest/msg_validators/tx_validator/test_utils.d.ts +2 -2
  108. package/dest/msg_validators/tx_validator/test_utils.d.ts.map +1 -1
  109. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +1 -1
  110. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -1
  111. package/dest/services/dummy_service.d.ts +6 -2
  112. package/dest/services/dummy_service.d.ts.map +1 -1
  113. package/dest/services/dummy_service.js +3 -0
  114. package/dest/services/encoding.d.ts +1 -1
  115. package/dest/services/encoding.d.ts.map +1 -1
  116. package/dest/services/encoding.js +5 -3
  117. package/dest/services/libp2p/instrumentation.d.ts +1 -1
  118. package/dest/services/libp2p/instrumentation.d.ts.map +1 -1
  119. package/dest/services/libp2p/instrumentation.js +20 -73
  120. package/dest/services/libp2p/libp2p_service.d.ts +30 -13
  121. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  122. package/dest/services/libp2p/libp2p_service.js +703 -149
  123. package/dest/services/peer-manager/metrics.d.ts +6 -1
  124. package/dest/services/peer-manager/metrics.d.ts.map +1 -1
  125. package/dest/services/peer-manager/metrics.js +18 -21
  126. package/dest/services/peer-manager/peer_manager.d.ts +2 -2
  127. package/dest/services/peer-manager/peer_manager.d.ts.map +1 -1
  128. package/dest/services/peer-manager/peer_manager.js +4 -12
  129. package/dest/services/peer-manager/peer_scoring.d.ts +1 -1
  130. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  131. package/dest/services/peer-manager/peer_scoring.js +2 -5
  132. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts +1 -1
  133. package/dest/services/reqresp/connection-sampler/connection_sampler.d.ts.map +1 -1
  134. package/dest/services/reqresp/constants.d.ts +12 -0
  135. package/dest/services/reqresp/constants.d.ts.map +1 -0
  136. package/dest/services/reqresp/constants.js +7 -0
  137. package/dest/services/reqresp/interface.d.ts +4 -4
  138. package/dest/services/reqresp/interface.d.ts.map +1 -1
  139. package/dest/services/reqresp/interface.js +3 -3
  140. package/dest/services/reqresp/metrics.d.ts +1 -1
  141. package/dest/services/reqresp/metrics.d.ts.map +1 -1
  142. package/dest/services/reqresp/metrics.js +5 -21
  143. package/dest/services/reqresp/protocols/auth.d.ts +2 -2
  144. package/dest/services/reqresp/protocols/auth.d.ts.map +1 -1
  145. package/dest/services/reqresp/protocols/auth.js +2 -2
  146. package/dest/services/reqresp/protocols/block.js +1 -1
  147. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts +1 -1
  148. package/dest/services/reqresp/protocols/block_txs/bitvector.d.ts.map +1 -1
  149. package/dest/services/reqresp/protocols/block_txs/bitvector.js +7 -0
  150. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +2 -2
  151. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  152. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +1 -1
  153. package/dest/services/reqresp/protocols/status.d.ts +1 -1
  154. package/dest/services/reqresp/protocols/status.d.ts.map +1 -1
  155. package/dest/services/reqresp/protocols/status.js +4 -1
  156. package/dest/services/reqresp/protocols/tx.d.ts +2 -3
  157. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  158. package/dest/services/reqresp/reqresp.js +402 -24
  159. package/dest/services/service.d.ts +16 -3
  160. package/dest/services/service.d.ts.map +1 -1
  161. package/dest/services/tx_collection/config.js +1 -1
  162. package/dest/services/tx_collection/instrumentation.d.ts +1 -1
  163. package/dest/services/tx_collection/instrumentation.d.ts.map +1 -1
  164. package/dest/services/tx_collection/instrumentation.js +4 -14
  165. package/dest/services/tx_collection/slow_tx_collection.d.ts +3 -3
  166. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -1
  167. package/dest/services/tx_collection/tx_collection.d.ts +4 -4
  168. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  169. package/dest/services/tx_collection/tx_collection.js +1 -1
  170. package/dest/services/tx_provider.d.ts +2 -1
  171. package/dest/services/tx_provider.d.ts.map +1 -1
  172. package/dest/services/tx_provider.js +11 -2
  173. package/dest/services/tx_provider_instrumentation.d.ts +5 -2
  174. package/dest/services/tx_provider_instrumentation.d.ts.map +1 -1
  175. package/dest/services/tx_provider_instrumentation.js +13 -13
  176. package/dest/test-helpers/mock-tx-helpers.js +1 -1
  177. package/dest/test-helpers/reqresp-nodes.d.ts +2 -2
  178. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  179. package/dest/testbench/p2p_client_testbench_worker.js +28 -12
  180. package/dest/testbench/worker_client_manager.d.ts +1 -1
  181. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  182. package/dest/testbench/worker_client_manager.js +6 -1
  183. package/package.json +16 -16
  184. package/src/client/factory.ts +5 -10
  185. package/src/client/interface.ts +19 -4
  186. package/src/client/p2p_client.ts +92 -147
  187. package/src/config.ts +12 -18
  188. package/src/mem_pools/attestation_pool/attestation_pool.ts +68 -41
  189. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +241 -289
  190. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +163 -141
  191. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +141 -164
  192. package/src/mem_pools/attestation_pool/mocks.ts +21 -15
  193. package/src/mem_pools/instrumentation.ts +38 -14
  194. package/src/mem_pools/interface.ts +2 -4
  195. package/src/mem_pools/tx_pool/README.md +270 -0
  196. package/src/mem_pools/tx_pool/aztec_kv_tx_pool.ts +363 -368
  197. package/src/mem_pools/tx_pool/eviction/eviction_manager.ts +131 -0
  198. package/src/mem_pools/tx_pool/eviction/eviction_strategy.ts +207 -0
  199. package/src/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.ts +159 -0
  200. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_mining_rule.ts +104 -0
  201. package/src/mem_pools/tx_pool/eviction/invalid_txs_after_reorg_rule.ts +91 -0
  202. package/src/mem_pools/tx_pool/eviction/low_priority_eviction_rule.ts +106 -0
  203. package/src/mem_pools/tx_pool/eviction/nullifier_conflict_pre_add_rule.ts +75 -0
  204. package/src/mem_pools/tx_pool/index.ts +0 -1
  205. package/src/mem_pools/tx_pool/priority.ts +8 -1
  206. package/src/mem_pools/tx_pool/tx_pool.ts +8 -3
  207. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +18 -13
  208. package/src/msg_validators/attestation_validator/attestation_validator.ts +17 -14
  209. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +9 -12
  210. package/src/msg_validators/index.ts +1 -1
  211. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +10 -0
  212. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +13 -0
  213. package/src/msg_validators/proposal_validator/index.ts +3 -0
  214. package/src/msg_validators/{block_proposal_validator/block_proposal_validator.ts → proposal_validator/proposal_validator.ts} +24 -29
  215. package/src/msg_validators/proposal_validator/proposal_validator_test_suite.ts +206 -0
  216. package/src/msg_validators/tx_validator/archive_cache.ts +1 -1
  217. package/src/msg_validators/tx_validator/block_header_validator.ts +1 -1
  218. package/src/msg_validators/tx_validator/data_validator.ts +12 -4
  219. package/src/msg_validators/tx_validator/factory.ts +1 -1
  220. package/src/msg_validators/tx_validator/fee_payer_balance.ts +40 -0
  221. package/src/msg_validators/tx_validator/gas_validator.ts +8 -25
  222. package/src/msg_validators/tx_validator/metadata_validator.ts +13 -5
  223. package/src/msg_validators/tx_validator/test_utils.ts +1 -1
  224. package/src/msg_validators/tx_validator/timestamp_validator.ts +3 -1
  225. package/src/services/dummy_service.ts +6 -0
  226. package/src/services/encoding.ts +4 -2
  227. package/src/services/libp2p/instrumentation.ts +19 -73
  228. package/src/services/libp2p/libp2p_service.ts +336 -117
  229. package/src/services/peer-manager/metrics.ts +22 -21
  230. package/src/services/peer-manager/peer_manager.ts +5 -4
  231. package/src/services/peer-manager/peer_scoring.ts +1 -5
  232. package/src/services/reqresp/connection-sampler/connection_sampler.ts +3 -1
  233. package/src/services/reqresp/constants.ts +14 -0
  234. package/src/services/reqresp/interface.ts +3 -3
  235. package/src/services/reqresp/metrics.ts +7 -23
  236. package/src/services/reqresp/protocols/auth.ts +2 -2
  237. package/src/services/reqresp/protocols/block.ts +1 -1
  238. package/src/services/reqresp/protocols/block_txs/bitvector.ts +9 -0
  239. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +1 -1
  240. package/src/services/reqresp/protocols/status.ts +7 -4
  241. package/src/services/reqresp/protocols/tx.ts +1 -2
  242. package/src/services/service.ts +19 -4
  243. package/src/services/tx_collection/config.ts +1 -1
  244. package/src/services/tx_collection/instrumentation.ts +4 -21
  245. package/src/services/tx_collection/slow_tx_collection.ts +2 -2
  246. package/src/services/tx_collection/tx_collection.ts +4 -4
  247. package/src/services/tx_provider.ts +17 -2
  248. package/src/services/tx_provider_instrumentation.ts +18 -14
  249. package/src/test-helpers/mock-pubsub.ts +1 -1
  250. package/src/test-helpers/mock-tx-helpers.ts +1 -1
  251. package/src/test-helpers/reqresp-nodes.ts +1 -1
  252. package/src/testbench/p2p_client_testbench_worker.ts +37 -13
  253. package/src/testbench/worker_client_manager.ts +6 -1
  254. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts +0 -81
  255. package/dest/mem_pools/tx_pool/memory_tx_pool.d.ts.map +0 -1
  256. package/dest/mem_pools/tx_pool/memory_tx_pool.js +0 -239
  257. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts +0 -12
  258. package/dest/msg_validators/block_proposal_validator/block_proposal_validator.d.ts.map +0 -1
  259. package/dest/msg_validators/block_proposal_validator/index.d.ts +0 -2
  260. package/dest/msg_validators/block_proposal_validator/index.d.ts.map +0 -1
  261. package/dest/msg_validators/block_proposal_validator/index.js +0 -1
  262. package/src/mem_pools/tx_pool/memory_tx_pool.ts +0 -285
  263. package/src/msg_validators/block_proposal_validator/index.ts +0 -1
@@ -0,0 +1,106 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+ import type { TxHash } from '@aztec/stdlib/tx';
3
+
4
+ import type { TxPoolOptions } from '../tx_pool.js';
5
+ import {
6
+ type EvictionContext,
7
+ EvictionEvent,
8
+ type EvictionResult,
9
+ type EvictionRule,
10
+ type TxPoolOperations,
11
+ } from './eviction_strategy.js';
12
+
13
+ export interface LowPriorityEvictionConfig {
14
+ /** Maximum number of pending transactions before eviction kicks in */
15
+ maxPoolSize: number;
16
+ }
17
+
18
+ /**
19
+ * Eviction rule that removes low-priority transactions when the number of pending transactions exceeds configured limits.
20
+ * Only triggers on TXS_ADDED events and respects non-evictable transactions.
21
+ */
22
+ export class LowPriorityEvictionRule implements EvictionRule {
23
+ public readonly name = 'LowPriorityEviction';
24
+
25
+ private log = createLogger('p2p:mempool:tx_pool:low_priority_eviction_rule');
26
+
27
+ constructor(private config: LowPriorityEvictionConfig) {}
28
+
29
+ public async evict(context: EvictionContext, txPool: TxPoolOperations): Promise<EvictionResult> {
30
+ if (context.event !== EvictionEvent.TXS_ADDED) {
31
+ return {
32
+ reason: 'low_priority',
33
+ success: true,
34
+ txsEvicted: [],
35
+ };
36
+ }
37
+
38
+ if (this.config.maxPoolSize === 0) {
39
+ return {
40
+ reason: 'low_priority',
41
+ success: true,
42
+ txsEvicted: [],
43
+ };
44
+ }
45
+
46
+ try {
47
+ const currentTxCount = await txPool.getPendingTxCount();
48
+ const maxCount = this.config.maxPoolSize;
49
+
50
+ if (currentTxCount <= maxCount) {
51
+ this.log.trace(`Not evicting low priority txs. Pending tx count below limit ${currentTxCount} <= ${maxCount}`);
52
+ return {
53
+ reason: 'low_priority',
54
+ success: true,
55
+ txsEvicted: [],
56
+ };
57
+ }
58
+
59
+ this.log.verbose(`Evicting low priority txs. Pending tx count above limit: ${currentTxCount} > ${maxCount}`);
60
+ const numberToEvict = currentTxCount - maxCount;
61
+ const txsToEvict: TxHash[] = await txPool.getLowestPriorityEvictable(numberToEvict);
62
+
63
+ if (txsToEvict.length > 0) {
64
+ await txPool.deleteTxs(txsToEvict);
65
+ }
66
+
67
+ const numNewTxsEvicted = context.newTxs.filter(newTxHash =>
68
+ txsToEvict.some(evictedTx => evictedTx.equals(newTxHash)),
69
+ ).length;
70
+
71
+ this.log.verbose(`Evicted ${txsToEvict.length} low priority txs, including ${numNewTxsEvicted} newly added txs`, {
72
+ txsEvicted: txsToEvict,
73
+ });
74
+
75
+ return {
76
+ reason: 'low_priority',
77
+ success: true,
78
+ txsEvicted: txsToEvict,
79
+ };
80
+ } catch (err) {
81
+ this.log.error('Failed to evict low priority transactions', { err });
82
+ return {
83
+ reason: 'low_priority',
84
+ success: false,
85
+ txsEvicted: [],
86
+ error: new Error('Failed to evict low priority txs', { cause: err }),
87
+ };
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Updates the configuration for this eviction rule
93
+ */
94
+ updateConfig(config: TxPoolOptions): void {
95
+ if (config.maxPendingTxCount !== undefined) {
96
+ this.config.maxPoolSize = config.maxPendingTxCount;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Gets the current configuration
102
+ */
103
+ getConfig(): LowPriorityEvictionConfig {
104
+ return { ...this.config };
105
+ }
106
+ }
@@ -0,0 +1,75 @@
1
+ import { findIndexInSortedArray, insertIntoSortedArray } from '@aztec/foundation/array';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import { type Tx, TxHash } from '@aztec/stdlib/tx';
5
+
6
+ import type { PreAddEvictionResult, PreAddEvictionRule, PreAddPoolAccess } from './eviction_strategy.js';
7
+
8
+ const cmpTxHash = (a: TxHash, b: TxHash) => Fr.cmp(a.hash, b.hash);
9
+
10
+ /**
11
+ * Pre-add eviction rule that checks for nullifier conflicts between incoming and existing transactions.
12
+ *
13
+ * When an incoming tx shares nullifiers with existing pending txs:
14
+ * - If the incoming tx has strictly higher priority fee, evict all conflicting txs
15
+ * - If any conflicting tx has equal or higher priority fee, reject the incoming tx
16
+ *
17
+ * This prevents nullifier spam attacks where an attacker floods the mempool with
18
+ * transactions spending the same nullifiers.
19
+ */
20
+ export class NullifierConflictPreAddRule implements PreAddEvictionRule {
21
+ public readonly name = 'NullifierConflictPreAdd';
22
+
23
+ private log = createLogger('p2p:mempool:tx_pool:nullifier_conflict_pre_add_rule');
24
+
25
+ /**
26
+ * Check if the incoming transaction conflicts with existing transactions via nullifiers.
27
+ *
28
+ * @param tx - The incoming transaction
29
+ * @param poolAccess - Read-only access to pool state
30
+ * @returns Result with rejection status and txs to evict
31
+ */
32
+ async check(tx: Tx, poolAccess: PreAddPoolAccess): Promise<PreAddEvictionResult> {
33
+ const txHash = tx.getTxHash();
34
+ const nullifiers = tx.data.getNonEmptyNullifiers();
35
+ const txHashesToEvict: TxHash[] = [];
36
+ const incomingPriority = poolAccess.getTxPriority(tx);
37
+
38
+ for (const nullifier of nullifiers) {
39
+ const conflictingHash = await poolAccess.getTxHashByNullifier(nullifier);
40
+
41
+ if (
42
+ !conflictingHash ||
43
+ conflictingHash.equals(txHash) ||
44
+ findIndexInSortedArray(txHashesToEvict, conflictingHash, cmpTxHash) !== -1
45
+ ) {
46
+ continue;
47
+ }
48
+
49
+ // Get the conflicting tx's priority
50
+ const conflictingTx = await poolAccess.getPendingTxByHash(conflictingHash);
51
+ if (!conflictingTx) {
52
+ continue;
53
+ }
54
+
55
+ const conflictingPriority = poolAccess.getTxPriority(conflictingTx);
56
+
57
+ // If incoming tx has strictly higher priority, mark for eviction
58
+ // Otherwise, reject incoming tx (ties go to existing tx)
59
+ if (incomingPriority > conflictingPriority) {
60
+ insertIntoSortedArray(txHashesToEvict, conflictingHash, cmpTxHash);
61
+ } else {
62
+ this.log.debug(
63
+ `Rejecting tx ${txHash.toString()}: nullifier conflict with ${conflictingHash.toString()} which has higher or equal fee`,
64
+ );
65
+ return {
66
+ shouldReject: true,
67
+ txHashesToEvict: [],
68
+ reason: `nullifier conflict with ${conflictingHash.toString()}`,
69
+ };
70
+ }
71
+ }
72
+
73
+ return { shouldReject: false, txHashesToEvict };
74
+ }
75
+ }
@@ -1,3 +1,2 @@
1
1
  export * from './tx_pool.js';
2
- export * from './memory_tx_pool.js';
3
2
  export * from './aztec_kv_tx_pool.js';
@@ -7,7 +7,14 @@ import type { Tx } from '@aztec/stdlib/tx';
7
7
  * We currently use the sum of the priority fees for the tx for this value, represented as hex.
8
8
  */
9
9
  export function getPendingTxPriority(tx: Tx): string {
10
+ return Buffer32.fromBigInt(getTxPriorityFee(tx)).toString();
11
+ }
12
+
13
+ /**
14
+ * Returns the priority of a tx.
15
+ */
16
+ export function getTxPriorityFee(tx: Tx): bigint {
10
17
  const priorityFees = tx.getGasSettings().maxPriorityFeesPerGas;
11
18
  const totalFees = priorityFees.feePerDaGas + priorityFees.feePerL2Gas;
12
- return Buffer32.fromBigInt(totalFees).toString();
19
+ return totalFees;
13
20
  }
@@ -3,8 +3,7 @@ import type { TypedEventEmitter } from '@aztec/foundation/types';
3
3
  import type { BlockHeader, Tx, TxHash } from '@aztec/stdlib/tx';
4
4
 
5
5
  export type TxPoolOptions = {
6
- maxTxPoolSize?: number;
7
- txPoolOverflowFactor?: number;
6
+ maxPendingTxCount?: number;
8
7
  archivedTxLimit?: number;
9
8
  };
10
9
 
@@ -69,8 +68,9 @@ export interface TxPool extends TypedEventEmitter<TxPoolEvents> {
69
68
  * Moves mined txs back to the pending set in the case of a reorg.
70
69
  * Note: txs not known by this peer will be ignored.
71
70
  * @param txHashes - Hashes of the txs to flag as pending.
71
+ * @param latestBlock - The block number the chain was pruned to.
72
72
  */
73
- markMinedAsPending(txHashes: TxHash[]): Promise<void>;
73
+ markMinedAsPending(txHashes: TxHash[], latestBlock: BlockNumber): Promise<void>;
74
74
 
75
75
  /**
76
76
  * Deletes transactions from the pool. Tx hashes that are not present are ignored.
@@ -127,6 +127,11 @@ export interface TxPool extends TypedEventEmitter<TxPoolEvents> {
127
127
  */
128
128
  markTxsAsNonEvictable(txHashes: TxHash[]): Promise<void>;
129
129
 
130
+ /**
131
+ * Clears collection of non-evictable transactions in the pool
132
+ */
133
+ clearNonEvictableTxs(): Promise<void>;
134
+
130
135
  /**
131
136
  * Permanently deletes deleted mined transactions from blocks up to and including the specified block number.
132
137
  * @param blockNumber - Block number threshold. Deleted mined txs from this block or earlier will be permanently deleted.
@@ -26,7 +26,7 @@ export function describeTxPool(getTxPool: () => TxPool) {
26
26
  });
27
27
 
28
28
  it('adds txs to the pool as pending', async () => {
29
- const tx1 = await mockTx();
29
+ const tx1 = await mockTx(1);
30
30
 
31
31
  await pool.addTxs([tx1]);
32
32
  const poolTx = await pool.getTxByHash(tx1.getTxHash());
@@ -37,9 +37,9 @@ export function describeTxPool(getTxPool: () => TxPool) {
37
37
  });
38
38
 
39
39
  it('emits txs-added event with new txs', async () => {
40
- const tx1 = await mockTx(); // existing and pending
41
- const tx2 = await mockTx(); // mined but not known
42
- const tx3 = await mockTx(); // brand new
40
+ const tx1 = await mockTx(1); // existing and pending
41
+ const tx2 = await mockTx(2); // mined but not known
42
+ const tx3 = await mockTx(3); // brand new
43
43
 
44
44
  await pool.addTxs([tx1]);
45
45
  await pool.markAsMined([tx2.getTxHash()], minedBlockHeader);
@@ -52,10 +52,11 @@ export function describeTxPool(getTxPool: () => TxPool) {
52
52
  await pool.addTxs([tx1, tx2, tx3]);
53
53
  expect(txsFromEvent).toBeDefined();
54
54
  expect(txsFromEvent).toHaveLength(2);
55
- expect(txsFromEvent).toEqual(expect.arrayContaining([tx2, tx3]));
55
+ const eventHashes = txsFromEvent!.map(tx => tx.getTxHash());
56
+ expect(eventHashes).toEqual(expect.arrayContaining([tx2.getTxHash(), tx3.getTxHash()]));
56
57
  });
57
58
 
58
- it('permanently deletes pending txs and soft-deletes mined txs', async () => {
59
+ it('removes txs from the pool', async () => {
59
60
  const pendingTx = await mockTx(1);
60
61
  const minedTx = await mockTx(2);
61
62
 
@@ -83,7 +84,8 @@ export function describeTxPool(getTxPool: () => TxPool) {
83
84
  await pool.addTxs([tx1, tx2]);
84
85
  await pool.markAsMined([tx1.getTxHash()], minedBlockHeader);
85
86
 
86
- await expect(pool.getTxByHash(tx1.getTxHash())).resolves.toEqual(tx1);
87
+ const retrievedTx = await pool.getTxByHash(tx1.getTxHash());
88
+ expect(retrievedTx?.getTxHash()).toEqual(tx1.getTxHash());
87
89
  await expect(pool.getTxStatus(tx1.getTxHash())).resolves.toEqual('mined');
88
90
  await expect(pool.getMinedTxHashes()).resolves.toEqual([[tx1.getTxHash(), 1]]);
89
91
  await expect(pool.getPendingTxHashes()).resolves.toEqual([tx2.getTxHash()]);
@@ -97,7 +99,7 @@ export function describeTxPool(getTxPool: () => TxPool) {
97
99
  await pool.addTxs([tx1, tx2]);
98
100
  await pool.markAsMined([tx1.getTxHash()], minedBlockHeader);
99
101
 
100
- await pool.markMinedAsPending([tx1.getTxHash()]);
102
+ await pool.markMinedAsPending([tx1.getTxHash()], BlockNumber(1));
101
103
  await expect(pool.getMinedTxHashes()).resolves.toEqual([]);
102
104
  const pending = await pool.getPendingTxHashes();
103
105
  expect(pending).toHaveLength(2);
@@ -121,7 +123,7 @@ export function describeTxPool(getTxPool: () => TxPool) {
121
123
  );
122
124
 
123
125
  // reorg: both txs should now become available again
124
- await pool.markMinedAsPending([tx1.getTxHash(), someTxHashThatThisPeerDidNotSee]);
126
+ await pool.markMinedAsPending([tx1.getTxHash(), someTxHashThatThisPeerDidNotSee], BlockNumber(1));
125
127
  await expect(pool.getMinedTxHashes()).resolves.toEqual([]);
126
128
  await expect(pool.getPendingTxHashes()).resolves.toEqual([tx1.getTxHash()]); // tx2 is not in the pool
127
129
  await expect(pool.getPendingTxCount()).resolves.toEqual(1);
@@ -136,7 +138,8 @@ export function describeTxPool(getTxPool: () => TxPool) {
136
138
 
137
139
  const poolTxs = await pool.getAllTxs();
138
140
  expect(poolTxs).toHaveLength(3);
139
- expect(poolTxs).toEqual(expect.arrayContaining([tx1, tx2, tx3]));
141
+ const poolHashes = poolTxs.map(tx => tx.getTxHash());
142
+ expect(poolHashes).toEqual(expect.arrayContaining([tx1.getTxHash(), tx2.getTxHash(), tx3.getTxHash()]));
140
143
  await expect(pool.getPendingTxCount()).resolves.toEqual(3);
141
144
  });
142
145
 
@@ -163,17 +166,19 @@ export function describeTxPool(getTxPool: () => TxPool) {
163
166
 
164
167
  const requestedTxs = await pool.getTxsByHash([tx1.getTxHash(), tx3.getTxHash()]);
165
168
  expect(requestedTxs).toHaveLength(2);
166
- expect(requestedTxs).toEqual(expect.arrayContaining([tx1, tx3]));
169
+ const requestedHashes = requestedTxs.map(tx => tx!.getTxHash());
170
+ expect(requestedHashes).toEqual(expect.arrayContaining([tx1.getTxHash(), tx3.getTxHash()]));
167
171
  });
168
172
 
169
173
  it('returns a large number of transactions by their hash', async () => {
170
- const numTxs = 1000;
174
+ const numTxs = 1_000;
171
175
  const txs = await Promise.all(Array.from({ length: numTxs }, (_, i) => mockTx(i)));
172
176
  const hashes = txs.map(tx => tx.getTxHash());
173
177
  await pool.addTxs(txs);
174
178
  const requestedTxs = await pool.getTxsByHash(hashes);
175
179
  expect(requestedTxs).toHaveLength(numTxs);
176
- expect(requestedTxs).toEqual(expect.arrayContaining(txs));
180
+ const requestedHashes = requestedTxs.map(tx => tx!.getTxHash());
181
+ expect(requestedHashes).toEqual(expect.arrayContaining(hashes));
177
182
  });
178
183
 
179
184
  it('returns whether or not txs exist', async () => {
@@ -1,33 +1,34 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
- import { NoCommitteeError } from '@aztec/ethereum';
2
+ import { NoCommitteeError } from '@aztec/ethereum/contracts';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
- import { type BlockAttestation, type P2PValidator, PeerErrorSeverity } from '@aztec/stdlib/p2p';
4
+ import { type CheckpointAttestation, type P2PValidator, PeerErrorSeverity } from '@aztec/stdlib/p2p';
5
5
 
6
- export class AttestationValidator implements P2PValidator<BlockAttestation> {
6
+ export class CheckpointAttestationValidator implements P2PValidator<CheckpointAttestation> {
7
7
  protected epochCache: EpochCacheInterface;
8
8
  protected logger: Logger;
9
9
 
10
10
  constructor(epochCache: EpochCacheInterface) {
11
11
  this.epochCache = epochCache;
12
- this.logger = createLogger('p2p:attestation-validator');
12
+ this.logger = createLogger('p2p:checkpoint-attestation-validator');
13
13
  }
14
14
 
15
- async validate(message: BlockAttestation): Promise<PeerErrorSeverity | undefined> {
15
+ async validate(message: CheckpointAttestation): Promise<PeerErrorSeverity | undefined> {
16
16
  const slotNumber = message.payload.header.slotNumber;
17
17
 
18
18
  try {
19
- const { currentProposer, nextProposer, currentSlot, nextSlot } =
20
- await this.epochCache.getProposerAttesterAddressInCurrentOrNextSlot();
19
+ const { currentSlot, nextSlot } = await this.epochCache.getProposerAttesterAddressInCurrentOrNextSlot();
21
20
 
22
21
  if (slotNumber !== currentSlot && slotNumber !== nextSlot) {
23
- this.logger.warn(`Attestation slot ${slotNumber} is not current (${currentSlot}) or next (${nextSlot}) slot`);
22
+ this.logger.warn(
23
+ `Checkpoint attestation slot ${slotNumber} is not current (${currentSlot}) or next (${nextSlot}) slot`,
24
+ );
24
25
  return PeerErrorSeverity.HighToleranceError;
25
26
  }
26
27
 
27
28
  // Verify the signature is valid
28
29
  const attester = message.getSender();
29
30
  if (attester === undefined) {
30
- this.logger.warn(`Invalid signature in attestation for slot ${slotNumber}`);
31
+ this.logger.warn(`Invalid signature in checkpoint attestation for slot ${slotNumber}`);
31
32
  return PeerErrorSeverity.LowToleranceError;
32
33
  }
33
34
 
@@ -37,20 +38,22 @@ export class AttestationValidator implements P2PValidator<BlockAttestation> {
37
38
  return PeerErrorSeverity.HighToleranceError;
38
39
  }
39
40
 
40
- // Verify the proposer signature matches the expected proposer for this slot
41
+ // Verify the proposer signature matches the expected proposer for the attestation's slot
42
+ // We look up the proposer for the specific slot rather than using currentSlot/nextSlot
43
+ // since timing differences could cause mismatches
41
44
  const proposer = message.getProposer();
42
- const expectedProposer = slotNumber === currentSlot ? currentProposer : nextProposer;
45
+ const expectedProposer = await this.epochCache.getProposerAttesterAddressInSlot(slotNumber);
43
46
  if (!expectedProposer) {
44
47
  this.logger.warn(`No proposer defined for slot ${slotNumber}`);
45
48
  return PeerErrorSeverity.HighToleranceError;
46
49
  }
47
50
  if (!proposer) {
48
- this.logger.warn(`Invalid proposer signature in attestation for slot ${slotNumber}`);
51
+ this.logger.warn(`Invalid proposer signature in checkpoint attestation for slot ${slotNumber}`);
49
52
  return PeerErrorSeverity.LowToleranceError;
50
53
  }
51
54
  if (!proposer.equals(expectedProposer)) {
52
55
  this.logger.warn(
53
- `Proposer signature mismatch in attestation. ` +
56
+ `Proposer signature mismatch in checkpoint attestation. ` +
54
57
  `Expected ${expectedProposer?.toString() ?? 'none'} but got ${proposer.toString()} for slot ${slotNumber}`,
55
58
  );
56
59
  return PeerErrorSeverity.HighToleranceError;
@@ -60,7 +63,7 @@ export class AttestationValidator implements P2PValidator<BlockAttestation> {
60
63
  } catch (e) {
61
64
  // People shouldn't be sending us attestations if the committee doesn't exist
62
65
  if (e instanceof NoCommitteeError) {
63
- this.logger.warn(`No committee exists for attestation for slot ${slotNumber}`);
66
+ this.logger.warn(`No committee exists for checkpoint attestation for slot ${slotNumber}`);
64
67
  return PeerErrorSeverity.LowToleranceError;
65
68
  }
66
69
  throw e;
@@ -1,9 +1,9 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
- import { type BlockAttestation, PeerErrorSeverity } from '@aztec/stdlib/p2p';
3
- import { Attributes, Metrics, type TelemetryClient, ValueType } from '@aztec/telemetry-client';
2
+ import { type CheckpointAttestation, PeerErrorSeverity } from '@aztec/stdlib/p2p';
3
+ import { Attributes, Metrics, type TelemetryClient } from '@aztec/telemetry-client';
4
4
 
5
5
  import type { AttestationPool } from '../../mem_pools/attestation_pool/attestation_pool.js';
6
- import { AttestationValidator } from './attestation_validator.js';
6
+ import { CheckpointAttestationValidator } from './attestation_validator.js';
7
7
 
8
8
  /**
9
9
  * FishermanAttestationValidator extends the base AttestationValidator to add
@@ -13,7 +13,7 @@ import { AttestationValidator } from './attestation_validator.js';
13
13
  * handled by LibP2PService based on the fishermanMode config to ensure a better
14
14
  * view of the network.
15
15
  */
16
- export class FishermanAttestationValidator extends AttestationValidator {
16
+ export class FishermanAttestationValidator extends CheckpointAttestationValidator {
17
17
  private invalidAttestationCounter;
18
18
 
19
19
  constructor(
@@ -25,13 +25,10 @@ export class FishermanAttestationValidator extends AttestationValidator {
25
25
  this.logger = this.logger.createChild('[FISHERMAN]');
26
26
 
27
27
  const meter = telemetryClient.getMeter('FishermanAttestationValidator');
28
- this.invalidAttestationCounter = meter.createUpDownCounter(Metrics.VALIDATOR_INVALID_ATTESTATION_RECEIVED_COUNT, {
29
- description: 'The number of invalid attestations received',
30
- valueType: ValueType.INT,
31
- });
28
+ this.invalidAttestationCounter = meter.createUpDownCounter(Metrics.VALIDATOR_INVALID_ATTESTATION_RECEIVED_COUNT);
32
29
  }
33
30
 
34
- override async validate(message: BlockAttestation): Promise<PeerErrorSeverity | undefined> {
31
+ override async validate(message: CheckpointAttestation): Promise<PeerErrorSeverity | undefined> {
35
32
  // First run the standard validation
36
33
  const baseValidationResult = await super.validate(message);
37
34
  if (baseValidationResult !== undefined) {
@@ -52,11 +49,11 @@ export class FishermanAttestationValidator extends AttestationValidator {
52
49
  }
53
50
 
54
51
  const proposalId = message.archive.toString();
55
- const proposal = await this.attestationPool.getBlockProposal(proposalId);
52
+ const proposal = await this.attestationPool.getCheckpointProposal(proposalId);
56
53
 
57
54
  if (proposal) {
58
55
  // Compare the attestation payload with the proposal payload
59
- if (!message.payload.equals(proposal.payload)) {
56
+ if (!message.payload.equals(proposal)) {
60
57
  this.logger.error(
61
58
  `Attestation payload mismatch for slot ${slotNumberBigInt}! ` +
62
59
  `Attester ${attester.toString()} signed different data than the proposal.`,
@@ -66,7 +63,7 @@ export class FishermanAttestationValidator extends AttestationValidator {
66
63
  proposer: proposer.toString(),
67
64
  proposalArchive: proposal.archive.toString(),
68
65
  attestationArchive: message.archive.toString(),
69
- proposalHeader: proposal.payload.header.hash().toString(),
66
+ proposalHeader: proposal.checkpointHeader.hash().toString(),
70
67
  attestationHeader: message.payload.header.hash().toString(),
71
68
  },
72
69
  );
@@ -1,3 +1,3 @@
1
1
  export * from './tx_validator/index.js';
2
- export * from './block_proposal_validator/index.js';
2
+ export * from './proposal_validator/index.js';
3
3
  export * from './attestation_validator/index.js';
@@ -0,0 +1,10 @@
1
+ import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
+ import type { BlockProposal, P2PValidator } from '@aztec/stdlib/p2p';
3
+
4
+ import { ProposalValidator } from '../proposal_validator/proposal_validator.js';
5
+
6
+ export class BlockProposalValidator extends ProposalValidator<BlockProposal> implements P2PValidator<BlockProposal> {
7
+ constructor(epochCache: EpochCacheInterface, opts: { txsPermitted: boolean }) {
8
+ super(epochCache, opts, 'p2p:block_proposal_validator');
9
+ }
10
+ }
@@ -0,0 +1,13 @@
1
+ import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
+ import type { CheckpointProposal, P2PValidator } from '@aztec/stdlib/p2p';
3
+
4
+ import { ProposalValidator } from '../proposal_validator/proposal_validator.js';
5
+
6
+ export class CheckpointProposalValidator
7
+ extends ProposalValidator<CheckpointProposal>
8
+ implements P2PValidator<CheckpointProposal>
9
+ {
10
+ constructor(epochCache: EpochCacheInterface, opts: { txsPermitted: boolean }) {
11
+ super(epochCache, opts, 'p2p:checkpoint_proposal_validator');
12
+ }
13
+ }
@@ -0,0 +1,3 @@
1
+ export * from './block_proposal_validator.js';
2
+ export * from './checkpoint_proposal_validator.js';
3
+ export * from './proposal_validator.js';
@@ -1,63 +1,60 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
- import { NoCommitteeError } from '@aztec/ethereum';
2
+ import { NoCommitteeError } from '@aztec/ethereum/contracts';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
- import { type BlockProposal, type P2PValidator, PeerErrorSeverity } from '@aztec/stdlib/p2p';
4
+ import { BlockProposal, CheckpointProposal, PeerErrorSeverity } from '@aztec/stdlib/p2p';
5
5
 
6
- export class BlockProposalValidator implements P2PValidator<BlockProposal> {
7
- private epochCache: EpochCacheInterface;
8
- private logger: Logger;
9
- private txsPermitted: boolean;
6
+ export abstract class ProposalValidator<TProposal extends BlockProposal | CheckpointProposal> {
7
+ protected epochCache: EpochCacheInterface;
8
+ protected logger: Logger;
9
+ protected txsPermitted: boolean;
10
10
 
11
- constructor(epochCache: EpochCacheInterface, opts: { txsPermitted: boolean }) {
11
+ constructor(epochCache: EpochCacheInterface, opts: { txsPermitted: boolean }, loggerName: string) {
12
12
  this.epochCache = epochCache;
13
13
  this.txsPermitted = opts.txsPermitted;
14
- this.logger = createLogger('p2p:block_proposal_validator');
14
+ this.logger = createLogger(loggerName);
15
15
  }
16
16
 
17
- async validate(block: BlockProposal): Promise<PeerErrorSeverity | undefined> {
17
+ public async validate(proposal: TProposal): Promise<PeerErrorSeverity | undefined> {
18
18
  try {
19
- // Check signature validity first - invalid signatures are a high-severity issue
20
- const proposer = block.getSender();
19
+ // Signature validity
20
+ const proposer = proposal.getSender();
21
21
  if (!proposer) {
22
- this.logger.debug(`Penalizing peer for block proposal with invalid signature`);
22
+ this.logger.debug(`Penalizing peer for proposal with invalid signature`);
23
23
  return PeerErrorSeverity.MidToleranceError;
24
24
  }
25
25
 
26
- // Check if transactions are permitted when the proposal contains transaction hashes
27
- const embeddedTxCount = block.txs?.length ?? 0;
28
- if (!this.txsPermitted && (block.txHashes.length > 0 || embeddedTxCount > 0)) {
26
+ // Transactions permitted check
27
+ const embeddedTxCount = proposal.txs?.length ?? 0;
28
+ if (!this.txsPermitted && (proposal.txHashes.length > 0 || embeddedTxCount > 0)) {
29
29
  this.logger.debug(
30
- `Penalizing peer for block proposal with ${block.txHashes.length} transaction(s) when transactions are not permitted`,
30
+ `Penalizing peer for proposal with ${proposal.txHashes.length} transaction(s) when transactions are not permitted`,
31
31
  );
32
32
  return PeerErrorSeverity.MidToleranceError;
33
33
  }
34
34
 
35
- // If there are embedded txs, they must be listed in txHashes; if there are no txHashes, there must be no txs
36
- const hashSet = new Set(block.txHashes.map(h => h.toString()));
35
+ // Embedded txs must be listed in txHashes
36
+ const hashSet = new Set(proposal.txHashes.map(h => h.toString()));
37
37
  const missingTxHashes =
38
38
  embeddedTxCount > 0
39
- ? block.txs!.filter(tx => !hashSet.has(tx.getTxHash().toString())).map(tx => tx.getTxHash().toString())
39
+ ? proposal.txs!.filter(tx => !hashSet.has(tx.getTxHash().toString())).map(tx => tx.getTxHash().toString())
40
40
  : [];
41
41
  if (embeddedTxCount > 0 && missingTxHashes.length > 0) {
42
42
  this.logger.warn('Penalizing peer for embedded transaction(s) not included in txHashes', {
43
43
  embeddedTxCount,
44
- txHashesLength: block.txHashes.length,
44
+ txHashesLength: proposal.txHashes.length,
45
45
  missingTxHashes,
46
46
  });
47
47
  return PeerErrorSeverity.MidToleranceError;
48
48
  }
49
49
 
50
+ // Slot and proposer checks
50
51
  const { currentProposer, nextProposer, currentSlot, nextSlot } =
51
52
  await this.epochCache.getProposerAttesterAddressInCurrentOrNextSlot();
52
-
53
- // Check that the attestation is for the current or next slot
54
- const slotNumber = block.payload.header.slotNumber;
53
+ const slotNumber = proposal.slotNumber;
55
54
  if (slotNumber !== currentSlot && slotNumber !== nextSlot) {
56
55
  this.logger.debug(`Penalizing peer for invalid slot number ${slotNumber}`, { currentSlot, nextSlot });
57
56
  return PeerErrorSeverity.HighToleranceError;
58
57
  }
59
-
60
- // Check that the block proposal is from the current or next proposer
61
58
  if (slotNumber === currentSlot && currentProposer !== undefined && !proposer.equals(currentProposer)) {
62
59
  this.logger.debug(`Penalizing peer for invalid proposer for current slot ${slotNumber}`, {
63
60
  currentProposer,
@@ -66,7 +63,6 @@ export class BlockProposalValidator implements P2PValidator<BlockProposal> {
66
63
  });
67
64
  return PeerErrorSeverity.MidToleranceError;
68
65
  }
69
-
70
66
  if (slotNumber === nextSlot && nextProposer !== undefined && !proposer.equals(nextProposer)) {
71
67
  this.logger.debug(`Penalizing peer for invalid proposer for next slot ${slotNumber}`, {
72
68
  currentProposer,
@@ -77,8 +73,8 @@ export class BlockProposalValidator implements P2PValidator<BlockProposal> {
77
73
  }
78
74
 
79
75
  // Validate tx hashes for all txs embedded in the proposal
80
- if (!(await Promise.all(block.txs?.map(tx => tx.validateTxHash()) ?? [])).every(v => v)) {
81
- this.logger.warn(`Penalizing peer for invalid tx hashes in block proposal`, {
76
+ if (!(await Promise.all(proposal.txs?.map(tx => tx.validateTxHash()) ?? [])).every(v => v)) {
77
+ this.logger.warn(`Penalizing peer for invalid tx hashes in proposal`, {
82
78
  proposer,
83
79
  slotNumber,
84
80
  });
@@ -87,7 +83,6 @@ export class BlockProposalValidator implements P2PValidator<BlockProposal> {
87
83
 
88
84
  return undefined;
89
85
  } catch (e) {
90
- // People shouldn't be sending us block proposals if the committee doesn't exist
91
86
  if (e instanceof NoCommitteeError) {
92
87
  return PeerErrorSeverity.LowToleranceError;
93
88
  }