@aztec/p2p 0.0.1-commit.6d63667d → 0.0.1-commit.858058eac

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 (198) hide show
  1. package/dest/client/factory.d.ts +5 -5
  2. package/dest/client/factory.d.ts.map +1 -1
  3. package/dest/client/factory.js +40 -9
  4. package/dest/client/interface.d.ts +33 -15
  5. package/dest/client/interface.d.ts.map +1 -1
  6. package/dest/client/p2p_client.d.ts +33 -36
  7. package/dest/client/p2p_client.d.ts.map +1 -1
  8. package/dest/client/p2p_client.js +104 -139
  9. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +1 -1
  10. package/dest/config.d.ts +13 -4
  11. package/dest/config.d.ts.map +1 -1
  12. package/dest/config.js +11 -1
  13. package/dest/index.d.ts +2 -1
  14. package/dest/index.d.ts.map +1 -1
  15. package/dest/index.js +1 -0
  16. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts +102 -88
  17. package/dest/mem_pools/attestation_pool/attestation_pool.d.ts.map +1 -1
  18. package/dest/mem_pools/attestation_pool/attestation_pool.js +436 -3
  19. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts +2 -2
  20. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.d.ts.map +1 -1
  21. package/dest/mem_pools/attestation_pool/attestation_pool_test_suite.js +353 -87
  22. package/dest/mem_pools/attestation_pool/index.d.ts +2 -3
  23. package/dest/mem_pools/attestation_pool/index.d.ts.map +1 -1
  24. package/dest/mem_pools/attestation_pool/index.js +1 -2
  25. package/dest/mem_pools/index.d.ts +3 -2
  26. package/dest/mem_pools/index.d.ts.map +1 -1
  27. package/dest/mem_pools/index.js +1 -1
  28. package/dest/mem_pools/interface.d.ts +5 -5
  29. package/dest/mem_pools/interface.d.ts.map +1 -1
  30. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts +87 -0
  31. package/dest/mem_pools/tx_pool_v2/deleted_pool.d.ts.map +1 -0
  32. package/dest/mem_pools/tx_pool_v2/deleted_pool.js +180 -0
  33. package/dest/mem_pools/tx_pool_v2/index.d.ts +2 -1
  34. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -1
  35. package/dest/mem_pools/tx_pool_v2/index.js +1 -0
  36. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +3 -3
  37. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  38. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +25 -3
  39. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -1
  40. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +36 -4
  41. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +1 -1
  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 +77 -74
  44. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts +3 -3
  45. package/dest/msg_validators/attestation_validator/fisherman_attestation_validator.d.ts.map +1 -1
  46. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +3 -3
  47. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  48. package/dest/msg_validators/tx_validator/block_header_validator.d.ts +16 -3
  49. package/dest/msg_validators/tx_validator/block_header_validator.d.ts.map +1 -1
  50. package/dest/msg_validators/tx_validator/block_header_validator.js +1 -1
  51. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts +13 -3
  52. package/dest/msg_validators/tx_validator/double_spend_validator.d.ts.map +1 -1
  53. package/dest/msg_validators/tx_validator/double_spend_validator.js +4 -4
  54. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts +20 -4
  55. package/dest/msg_validators/tx_validator/timestamp_validator.d.ts.map +1 -1
  56. package/dest/msg_validators/tx_validator/timestamp_validator.js +2 -2
  57. package/dest/services/dummy_service.d.ts +10 -2
  58. package/dest/services/dummy_service.d.ts.map +1 -1
  59. package/dest/services/dummy_service.js +6 -0
  60. package/dest/services/encoding.d.ts +2 -2
  61. package/dest/services/encoding.d.ts.map +1 -1
  62. package/dest/services/encoding.js +2 -2
  63. package/dest/services/gossipsub/index.d.ts +3 -0
  64. package/dest/services/gossipsub/index.d.ts.map +1 -0
  65. package/dest/services/gossipsub/index.js +2 -0
  66. package/dest/services/gossipsub/scoring.d.ts +21 -3
  67. package/dest/services/gossipsub/scoring.d.ts.map +1 -1
  68. package/dest/services/gossipsub/scoring.js +24 -7
  69. package/dest/services/gossipsub/topic_score_params.d.ts +161 -0
  70. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -0
  71. package/dest/services/gossipsub/topic_score_params.js +324 -0
  72. package/dest/services/libp2p/libp2p_service.d.ts +84 -35
  73. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  74. package/dest/services/libp2p/libp2p_service.js +364 -265
  75. package/dest/services/peer-manager/peer_scoring.d.ts +1 -1
  76. package/dest/services/peer-manager/peer_scoring.d.ts.map +1 -1
  77. package/dest/services/peer-manager/peer_scoring.js +25 -2
  78. package/dest/services/reqresp/interface.d.ts +10 -1
  79. package/dest/services/reqresp/interface.d.ts.map +1 -1
  80. package/dest/services/reqresp/interface.js +15 -1
  81. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts +4 -3
  82. package/dest/services/reqresp/protocols/block_txs/block_txs_handler.d.ts.map +1 -1
  83. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts +7 -1
  84. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.d.ts.map +1 -1
  85. package/dest/services/reqresp/protocols/block_txs/block_txs_reqresp.js +15 -0
  86. package/dest/services/reqresp/protocols/tx.d.ts +7 -1
  87. package/dest/services/reqresp/protocols/tx.d.ts.map +1 -1
  88. package/dest/services/reqresp/protocols/tx.js +20 -0
  89. package/dest/services/reqresp/reqresp.d.ts +1 -1
  90. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  91. package/dest/services/reqresp/reqresp.js +11 -4
  92. package/dest/services/service.d.ts +35 -1
  93. package/dest/services/service.d.ts.map +1 -1
  94. package/dest/services/tx_collection/config.d.ts +7 -1
  95. package/dest/services/tx_collection/config.d.ts.map +1 -1
  96. package/dest/services/tx_collection/config.js +16 -0
  97. package/dest/services/tx_collection/fast_tx_collection.d.ts +3 -1
  98. package/dest/services/tx_collection/fast_tx_collection.d.ts.map +1 -1
  99. package/dest/services/tx_collection/fast_tx_collection.js +17 -3
  100. package/dest/services/tx_collection/file_store_tx_collection.d.ts +44 -0
  101. package/dest/services/tx_collection/file_store_tx_collection.d.ts.map +1 -0
  102. package/dest/services/tx_collection/file_store_tx_collection.js +118 -0
  103. package/dest/services/tx_collection/file_store_tx_source.d.ts +27 -0
  104. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -0
  105. package/dest/services/tx_collection/file_store_tx_source.js +57 -0
  106. package/dest/services/tx_collection/index.d.ts +2 -1
  107. package/dest/services/tx_collection/index.d.ts.map +1 -1
  108. package/dest/services/tx_collection/index.js +1 -0
  109. package/dest/services/tx_collection/slow_tx_collection.d.ts +3 -1
  110. package/dest/services/tx_collection/slow_tx_collection.d.ts.map +1 -1
  111. package/dest/services/tx_collection/slow_tx_collection.js +48 -19
  112. package/dest/services/tx_collection/tx_collection.d.ts +17 -7
  113. package/dest/services/tx_collection/tx_collection.d.ts.map +1 -1
  114. package/dest/services/tx_collection/tx_collection.js +58 -2
  115. package/dest/services/tx_collection/tx_collection_sink.d.ts +15 -6
  116. package/dest/services/tx_collection/tx_collection_sink.d.ts.map +1 -1
  117. package/dest/services/tx_collection/tx_collection_sink.js +13 -7
  118. package/dest/services/tx_file_store/config.d.ts +1 -3
  119. package/dest/services/tx_file_store/config.d.ts.map +1 -1
  120. package/dest/services/tx_file_store/config.js +0 -4
  121. package/dest/services/tx_file_store/tx_file_store.d.ts +3 -3
  122. package/dest/services/tx_file_store/tx_file_store.d.ts.map +1 -1
  123. package/dest/services/tx_provider.d.ts +3 -3
  124. package/dest/services/tx_provider.d.ts.map +1 -1
  125. package/dest/services/tx_provider.js +5 -4
  126. package/dest/test-helpers/make-test-p2p-clients.d.ts +3 -3
  127. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  128. package/dest/test-helpers/mock-pubsub.d.ts +27 -1
  129. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  130. package/dest/test-helpers/mock-pubsub.js +97 -2
  131. package/dest/test-helpers/reqresp-nodes.d.ts +1 -1
  132. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  133. package/dest/test-helpers/reqresp-nodes.js +2 -1
  134. package/dest/test-helpers/testbench-utils.d.ts +38 -38
  135. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  136. package/dest/test-helpers/testbench-utils.js +124 -61
  137. package/dest/testbench/p2p_client_testbench_worker.js +2 -2
  138. package/package.json +14 -14
  139. package/src/client/factory.ts +68 -12
  140. package/src/client/interface.ts +39 -14
  141. package/src/client/p2p_client.ts +139 -162
  142. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +1 -1
  143. package/src/config.ts +26 -2
  144. package/src/index.ts +1 -0
  145. package/src/mem_pools/attestation_pool/attestation_pool.ts +488 -91
  146. package/src/mem_pools/attestation_pool/attestation_pool_test_suite.ts +442 -102
  147. package/src/mem_pools/attestation_pool/index.ts +9 -2
  148. package/src/mem_pools/index.ts +4 -1
  149. package/src/mem_pools/interface.ts +4 -4
  150. package/src/mem_pools/tx_pool_v2/README.md +59 -9
  151. package/src/mem_pools/tx_pool_v2/deleted_pool.ts +234 -0
  152. package/src/mem_pools/tx_pool_v2/index.ts +1 -0
  153. package/src/mem_pools/tx_pool_v2/interfaces.ts +2 -2
  154. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +51 -5
  155. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +90 -77
  156. package/src/msg_validators/attestation_validator/fisherman_attestation_validator.ts +2 -2
  157. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +2 -2
  158. package/src/msg_validators/tx_validator/block_header_validator.ts +15 -3
  159. package/src/msg_validators/tx_validator/double_spend_validator.ts +11 -6
  160. package/src/msg_validators/tx_validator/timestamp_validator.ts +19 -14
  161. package/src/services/dummy_service.ts +12 -0
  162. package/src/services/encoding.ts +2 -2
  163. package/src/services/gossipsub/README.md +626 -0
  164. package/src/services/gossipsub/index.ts +2 -0
  165. package/src/services/gossipsub/scoring.ts +29 -5
  166. package/src/services/gossipsub/topic_score_params.ts +451 -0
  167. package/src/services/libp2p/libp2p_service.ts +360 -269
  168. package/src/services/peer-manager/peer_scoring.ts +25 -0
  169. package/src/services/reqresp/interface.ts +26 -1
  170. package/src/services/reqresp/protocols/block_txs/block_txs_handler.ts +4 -3
  171. package/src/services/reqresp/protocols/block_txs/block_txs_reqresp.ts +17 -0
  172. package/src/services/reqresp/protocols/tx.ts +22 -0
  173. package/src/services/reqresp/reqresp.ts +13 -3
  174. package/src/services/service.ts +40 -0
  175. package/src/services/tx_collection/config.ts +26 -0
  176. package/src/services/tx_collection/fast_tx_collection.ts +14 -2
  177. package/src/services/tx_collection/file_store_tx_collection.ts +152 -0
  178. package/src/services/tx_collection/file_store_tx_source.ts +70 -0
  179. package/src/services/tx_collection/index.ts +1 -0
  180. package/src/services/tx_collection/slow_tx_collection.ts +55 -26
  181. package/src/services/tx_collection/tx_collection.ts +78 -12
  182. package/src/services/tx_collection/tx_collection_sink.ts +17 -7
  183. package/src/services/tx_file_store/config.ts +0 -6
  184. package/src/services/tx_file_store/tx_file_store.ts +4 -4
  185. package/src/services/tx_provider.ts +8 -7
  186. package/src/test-helpers/make-test-p2p-clients.ts +3 -3
  187. package/src/test-helpers/mock-pubsub.ts +133 -3
  188. package/src/test-helpers/reqresp-nodes.ts +2 -1
  189. package/src/test-helpers/testbench-utils.ts +122 -74
  190. package/src/testbench/p2p_client_testbench_worker.ts +2 -2
  191. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts +0 -40
  192. package/dest/mem_pools/attestation_pool/kv_attestation_pool.d.ts.map +0 -1
  193. package/dest/mem_pools/attestation_pool/kv_attestation_pool.js +0 -218
  194. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts +0 -31
  195. package/dest/mem_pools/attestation_pool/memory_attestation_pool.d.ts.map +0 -1
  196. package/dest/mem_pools/attestation_pool/memory_attestation_pool.js +0 -180
  197. package/src/mem_pools/attestation_pool/kv_attestation_pool.ts +0 -320
  198. package/src/mem_pools/attestation_pool/memory_attestation_pool.ts +0 -264
@@ -1,6 +1,5 @@
1
1
  import type { EpochCacheInterface } from '@aztec/epoch-cache';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { randomInt } from '@aztec/foundation/crypto/random';
2
+ import { BlockNumber, type SlotNumber } from '@aztec/foundation/branded-types';
4
3
  import { Fr } from '@aztec/foundation/curves/bn254';
5
4
  import { type Logger, createLibp2pComponentLogger, createLogger } from '@aztec/foundation/log';
6
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
@@ -45,7 +44,7 @@ import {
45
44
  type GossipsubMessage,
46
45
  gossipsub,
47
46
  } from '@chainsafe/libp2p-gossipsub';
48
- import { createPeerScoreParams, createTopicScoreParams } from '@chainsafe/libp2p-gossipsub/score';
47
+ import { createPeerScoreParams } from '@chainsafe/libp2p-gossipsub/score';
49
48
  import { SignaturePolicy } from '@chainsafe/libp2p-gossipsub/types';
50
49
  import { noise } from '@chainsafe/libp2p-noise';
51
50
  import { yamux } from '@chainsafe/libp2p-yamux';
@@ -59,8 +58,7 @@ import { ENR } from '@nethermindeth/enr';
59
58
  import { createLibp2p } from 'libp2p';
60
59
 
61
60
  import type { P2PConfig } from '../../config.js';
62
- import { ProposalSlotCapExceededError } from '../../errors/attestation-pool.error.js';
63
- import type { MemPools } from '../../mem_pools/index.js';
61
+ import type { MemPools } from '../../mem_pools/interface.js';
64
62
  import {
65
63
  BlockProposalValidator,
66
64
  CheckpointAttestationValidator,
@@ -81,7 +79,8 @@ import { getVersions } from '../../versioning.js';
81
79
  import { AztecDatastore } from '../data_store.js';
82
80
  import { DiscV5Service } from '../discv5/discV5_service.js';
83
81
  import { SnappyTransform, fastMsgIdFn, getMsgIdFn, msgIdToStrFn } from '../encoding.js';
84
- import { gossipScoreThresholds } from '../gossipsub/scoring.js';
82
+ import { APP_SPECIFIC_WEIGHT, gossipScoreThresholds } from '../gossipsub/scoring.js';
83
+ import { createAllTopicScoreParams } from '../gossipsub/topic_score_params.js';
85
84
  import type { PeerManagerInterface } from '../peer-manager/interface.js';
86
85
  import { PeerManager } from '../peer-manager/peer_manager.js';
87
86
  import { PeerScoring } from '../peer-manager/peer_scoring.js';
@@ -114,6 +113,7 @@ import { ReqResp } from '../reqresp/reqresp.js';
114
113
  import type {
115
114
  P2PBlockReceivedCallback,
116
115
  P2PCheckpointReceivedCallback,
116
+ P2PDuplicateAttestationCallback,
117
117
  P2PService,
118
118
  PeerDiscoveryService,
119
119
  } from '../service.js';
@@ -128,9 +128,9 @@ interface ValidationResult {
128
128
  type ValidationOutcome = { allPassed: true } | { allPassed: false; failure: ValidationResult };
129
129
 
130
130
  // REFACTOR: Unify with the type above
131
- type ReceivedMessageValidationResult<T> =
132
- | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject> }
133
- | { obj?: undefined; result: TopicValidatorResult.Reject };
131
+ type ReceivedMessageValidationResult<T, M = undefined> =
132
+ | { obj: T; result: Exclude<TopicValidatorResult, TopicValidatorResult.Reject>; metadata?: M }
133
+ | { obj?: T; result: TopicValidatorResult.Reject; metadata?: M };
134
134
 
135
135
  /**
136
136
  * Lib P2P implementation of the P2PService interface.
@@ -149,6 +149,16 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
149
149
 
150
150
  private feesCache: { blockNumber: BlockNumber; gasFees: GasFees } | undefined;
151
151
 
152
+ /** Callback invoked when a duplicate proposal is detected (triggers slashing). */
153
+ private duplicateProposalCallback?: (info: {
154
+ slot: SlotNumber;
155
+ proposer: EthAddress;
156
+ type: 'checkpoint' | 'block';
157
+ }) => void;
158
+
159
+ /** Callback invoked when a duplicate attestation is detected (triggers slashing). */
160
+ private duplicateAttestationCallback?: P2PDuplicateAttestationCallback;
161
+
152
162
  /**
153
163
  * Callback for when a block is received from a peer.
154
164
  * @param block - The block received from the peer.
@@ -177,9 +187,9 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
177
187
  protected node: PubSubLibp2p,
178
188
  private peerDiscoveryService: PeerDiscoveryService,
179
189
  private reqresp: ReqRespInterface,
180
- private peerManager: PeerManagerInterface,
190
+ protected peerManager: PeerManagerInterface,
181
191
  protected mempools: MemPools,
182
- private archiver: L2BlockSource & ContractDataSource,
192
+ protected archiver: L2BlockSource & ContractDataSource,
183
193
  private epochCache: EpochCacheInterface,
184
194
  private proofVerifier: ClientProtocolCircuitVerifier,
185
195
  private worldStateSynchronizer: WorldStateSynchronizer,
@@ -305,11 +315,6 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
305
315
  const versions = getVersions(config);
306
316
  const protocolVersion = compressComponentVersions(versions);
307
317
 
308
- const txTopic = createTopicString(TopicType.tx, protocolVersion);
309
- const blockProposalTopic = createTopicString(TopicType.block_proposal, protocolVersion);
310
- const checkpointProposalTopic = createTopicString(TopicType.checkpoint_proposal, protocolVersion);
311
- const checkpointAttestationTopic = createTopicString(TopicType.checkpoint_attestation, protocolVersion);
312
-
313
318
  const preferredPeersEnrs: ENR[] = config.preferredPeers.map(enr => ENR.decodeTxt(enr));
314
319
  const directPeers = (
315
320
  await Promise.all(
@@ -329,6 +334,15 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
329
334
 
330
335
  const announceTcpMultiaddr = config.p2pIp ? [convertToMultiaddr(config.p2pIp, p2pPort, 'tcp')] : [];
331
336
 
337
+ // Create dynamic topic score params based on network configuration
338
+ const l1Constants = epochCache.getL1Constants();
339
+ const topicScoreParams = createAllTopicScoreParams(protocolVersion, {
340
+ slotDurationMs: l1Constants.slotDuration * 1000,
341
+ heartbeatIntervalMs: config.gossipsubInterval,
342
+ targetCommitteeSize: l1Constants.targetCommitteeSize,
343
+ blockDurationMs: config.blockDurationMs,
344
+ });
345
+
332
346
  const node = await createLibp2p({
333
347
  start: false,
334
348
  peerId,
@@ -424,28 +438,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
424
438
  scoreParams: createPeerScoreParams({
425
439
  // IPColocation factor can be disabled for local testing - default to -5
426
440
  IPColocationFactorWeight: config.debugDisableColocationPenalty ? 0 : -5.0,
427
- topics: {
428
- [txTopic]: createTopicScoreParams({
429
- topicWeight: 1,
430
- invalidMessageDeliveriesWeight: -20,
431
- invalidMessageDeliveriesDecay: 0.5,
432
- }),
433
- [blockProposalTopic]: createTopicScoreParams({
434
- topicWeight: 1,
435
- invalidMessageDeliveriesWeight: -20,
436
- invalidMessageDeliveriesDecay: 0.5,
437
- }),
438
- [checkpointProposalTopic]: createTopicScoreParams({
439
- topicWeight: 1,
440
- invalidMessageDeliveriesWeight: -20,
441
- invalidMessageDeliveriesDecay: 0.5,
442
- }),
443
- [checkpointAttestationTopic]: createTopicScoreParams({
444
- topicWeight: 1,
445
- invalidMessageDeliveriesWeight: -20,
446
- invalidMessageDeliveriesDecay: 0.5,
447
- }),
448
- },
441
+ topics: topicScoreParams,
449
442
  }),
450
443
  }) as (components: GossipSubComponents) => GossipSub,
451
444
  components: (components: { connectionManager: ConnectionManager }) => ({
@@ -471,8 +464,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
471
464
  epochCache,
472
465
  );
473
466
 
474
- // Update gossipsub score params
475
- node.services.pubsub.score.params.appSpecificWeight = 10;
467
+ // Configure application-specific scoring for gossipsub.
468
+ // The weight scales app score to align with gossipsub thresholds:
469
+ // - Disconnect (-50) × 10 = -500 = gossipThreshold (stops receiving gossip)
470
+ // - Ban (-100) × 10 = -1000 = publishThreshold (cannot publish)
471
+ // Note: positive topic scores can offset penalties, so alignment is best-effort.
472
+ node.services.pubsub.score.params.appSpecificWeight = APP_SPECIFIC_WEIGHT;
476
473
  node.services.pubsub.score.params.appSpecificScore = (peerId: string) =>
477
474
  peerManager.shouldDisableP2PGossip(peerId) ? -Infinity : peerManager.getPeerScore(peerId);
478
475
 
@@ -669,6 +666,25 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
669
666
  this.checkpointReceivedCallback = callback;
670
667
  }
671
668
 
669
+ /**
670
+ * Registers a callback to be invoked when a duplicate proposal is detected.
671
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
672
+ */
673
+ public registerDuplicateProposalCallback(
674
+ callback: (info: { slot: SlotNumber; proposer: EthAddress; type: 'checkpoint' | 'block' }) => void,
675
+ ): void {
676
+ this.duplicateProposalCallback = callback;
677
+ }
678
+
679
+ /**
680
+ * Registers a callback to be invoked when a duplicate attestation is detected.
681
+ * A validator signing attestations for different proposals at the same slot.
682
+ * This callback is triggered on the first duplicate (when count goes from 1 to 2).
683
+ */
684
+ public registerDuplicateAttestationCallback(callback: P2PDuplicateAttestationCallback): void {
685
+ this.duplicateAttestationCallback = callback;
686
+ }
687
+
672
688
  /**
673
689
  * Subscribes to a topic.
674
690
  * @param topic - The topic to subscribe to.
@@ -855,13 +871,13 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
855
871
  return;
856
872
  }
857
873
 
858
- protected async validateReceivedMessage<T>(
859
- validationFunc: () => Promise<ReceivedMessageValidationResult<T>>,
874
+ protected async validateReceivedMessage<T, M = undefined>(
875
+ validationFunc: () => Promise<ReceivedMessageValidationResult<T, M>>,
860
876
  msgId: string,
861
877
  source: PeerId,
862
878
  topicType: TopicType,
863
- ): Promise<ReceivedMessageValidationResult<T>> {
864
- let resultAndObj: ReceivedMessageValidationResult<T> = { result: TopicValidatorResult.Reject };
879
+ ): Promise<ReceivedMessageValidationResult<T, M>> {
880
+ let resultAndObj: ReceivedMessageValidationResult<T, M> = { result: TopicValidatorResult.Reject };
865
881
  const timer = new Timer();
866
882
  try {
867
883
  resultAndObj = await validationFunc();
@@ -886,20 +902,33 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
886
902
  const validationFunc: () => Promise<ReceivedMessageValidationResult<Tx>> = async () => {
887
903
  const tx = Tx.fromBuffer(payloadData);
888
904
  const isValid = await this.validatePropagatedTx(tx, source);
889
- const exists = isValid && (await this.mempools.txPool.hasTx(tx.getTxHash()));
905
+ if (!isValid) {
906
+ this.logger.trace(`Rejecting invalid propagated tx`, {
907
+ [Attributes.P2P_ID]: source.toString(),
908
+ });
909
+ return { result: TopicValidatorResult.Reject };
910
+ }
911
+
912
+ // Propagate only on pool acceptance
913
+ const txHash = tx.getTxHash();
914
+ const addResult = await this.mempools.txPool.addPendingTxs([tx], { source: 'gossip' });
915
+
916
+ const wasAccepted = addResult.accepted.some(h => h.equals(txHash));
917
+ const wasIgnored = addResult.ignored.some(h => h.equals(txHash));
890
918
 
891
919
  this.logger.trace(`Validate propagated tx`, {
892
920
  isValid,
893
- exists,
921
+ wasAccepted,
922
+ wasIgnored,
894
923
  [Attributes.P2P_ID]: source.toString(),
895
924
  });
896
925
 
897
- if (!isValid) {
898
- return { result: TopicValidatorResult.Reject };
899
- } else if (exists) {
926
+ if (wasAccepted) {
927
+ return { result: TopicValidatorResult.Accept, obj: tx };
928
+ } else if (wasIgnored) {
900
929
  return { result: TopicValidatorResult.Ignore, obj: tx };
901
930
  } else {
902
- return { result: TopicValidatorResult.Accept, obj: tx };
931
+ return { result: TopicValidatorResult.Reject };
903
932
  }
904
933
  };
905
934
 
@@ -908,6 +937,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
908
937
  return;
909
938
  }
910
939
 
940
+ // Tx was accepted into pool and will be propagated - just log and record metrics
911
941
  const txHash = tx.getTxHash();
912
942
  const txHashString = txHash.toString();
913
943
  this.logger.verbose(`Received tx ${txHashString} from external peer ${source.toString()} via gossip`, {
@@ -915,13 +945,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
915
945
  txHash: txHashString,
916
946
  });
917
947
 
918
- if (this.config.dropTransactions && randomInt(1000) < this.config.dropTransactionsProbability * 1000) {
919
- this.logger.warn(`Intentionally dropping tx ${txHashString} (probability rule)`);
920
- return;
921
- }
922
-
923
948
  this.instrumentation.incrementTxReceived(1);
924
- await this.mempools.txPool.addTxs([tx]);
925
949
  }
926
950
 
927
951
  /**
@@ -933,47 +957,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
933
957
  msgId: string,
934
958
  source: PeerId,
935
959
  ): Promise<void> {
936
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointAttestation>> = async () => {
937
- const attestation = CheckpointAttestation.fromBuffer(payloadData);
938
- const pool = this.mempools.attestationPool;
939
- const validationResult = await this.validateCheckpointAttestation(source, attestation);
940
- const isValid = validationResult.result === 'accept';
941
- const exists = isValid && (await pool.hasCheckpointAttestation(attestation));
942
-
943
- let canAdd = true;
944
- if (isValid && !exists) {
945
- const slot = attestation.payload.header.slotNumber;
946
- const { committee } = await this.epochCache.getCommittee(slot);
947
- const committeeSize = committee?.length ?? 0;
948
- canAdd = await pool.canAddCheckpointAttestation(attestation, committeeSize);
949
- }
950
-
951
- this.logger.trace(`Validate propagated checkpoint attestation`, {
952
- isValid,
953
- exists,
954
- canAdd,
955
- [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
956
- [Attributes.P2P_ID]: source.toString(),
957
- });
958
-
959
- if (validationResult.result === 'reject') {
960
- return { result: TopicValidatorResult.Reject };
961
- } else if (validationResult.result === 'ignore' || exists) {
962
- return { result: TopicValidatorResult.Ignore, obj: attestation };
963
- } else if (!canAdd) {
964
- this.logger.warn(`Dropping checkpoint attestation due to per-(slot, proposalId) attestation cap`, {
965
- slot: attestation.payload.header.slotNumber.toString(),
966
- archive: attestation.archive.toString(),
967
- source: source.toString(),
968
- });
969
- return { result: TopicValidatorResult.Ignore, obj: attestation };
970
- } else {
971
- return { result: TopicValidatorResult.Accept, obj: attestation };
972
- }
973
- };
974
-
975
960
  const { result, obj: attestation } = await this.validateReceivedMessage<CheckpointAttestation>(
976
- validationFunc,
961
+ () => this.validateAndStoreCheckpointAttestation(source, CheckpointAttestation.fromBuffer(payloadData)),
977
962
  msgId,
978
963
  source,
979
964
  TopicType.checkpoint_attestation,
@@ -983,8 +968,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
983
968
  return;
984
969
  }
985
970
 
986
- this.logger.debug(
987
- `Received checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
971
+ this.logger.verbose(
972
+ `Received valid checkpoint attestation for slot ${attestation.slotNumber} from external peer ${source.toString()}`,
988
973
  {
989
974
  p2pMessageIdentifier: await attestation.p2pMessageLoggingIdentifier(),
990
975
  slot: attestation.slotNumber,
@@ -992,60 +977,167 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
992
977
  source: source.toString(),
993
978
  },
994
979
  );
995
-
996
- await this.mempools.attestationPool.addCheckpointAttestations([attestation]);
997
980
  }
998
981
 
999
- private async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1000
- const validationFunc: () => Promise<ReceivedMessageValidationResult<BlockProposal>> = async () => {
1001
- const block = BlockProposal.fromBuffer(payloadData);
1002
- const validationResult = await this.validateBlockProposal(source, block);
1003
- const isValid = validationResult.result === 'accept';
1004
- const pool = this.mempools.attestationPool;
982
+ /** Validates a checkpoint attestation and adds it to the pool. Penalizes the peer if validation fails. */
983
+ @trackSpan('Libp2pService.validateAndStoreCheckpointAttestation', (_peerId, attestation) => ({
984
+ [Attributes.SLOT_NUMBER]: attestation.payload.header.slotNumber.toString(),
985
+ }))
986
+ protected async validateAndStoreCheckpointAttestation(
987
+ peerId: PeerId,
988
+ attestation: CheckpointAttestation,
989
+ ): Promise<ReceivedMessageValidationResult<CheckpointAttestation>> {
990
+ const validationResult = await this.checkpointAttestationValidator.validate(attestation);
1005
991
 
1006
- const exists = isValid && (await pool.hasBlockProposal(block));
1007
- const canAdd = isValid && (await pool.canAddProposal(block));
992
+ if (validationResult.result === 'reject') {
993
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
994
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
995
+ return { result: TopicValidatorResult.Reject };
996
+ }
1008
997
 
1009
- this.logger.trace(`Validate propagated block proposal`, {
1010
- isValid,
1011
- exists,
1012
- canAdd,
1013
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1014
- [Attributes.P2P_ID]: source.toString(),
998
+ if (validationResult.result === 'ignore') {
999
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1000
+ }
1001
+
1002
+ // Try to add the attestation: this handles existence check, cap check, and adding in one call
1003
+ // count is the number of attestations by this signer for this slot (for duplicate detection)
1004
+ const slot = attestation.payload.header.slotNumber;
1005
+ const { added, alreadyExists, count } =
1006
+ await this.mempools.attestationPool.tryAddCheckpointAttestation(attestation);
1007
+
1008
+ this.logger.trace(`Validate propagated checkpoint attestation`, {
1009
+ added,
1010
+ alreadyExists,
1011
+ count,
1012
+ [Attributes.SLOT_NUMBER]: slot.toString(),
1013
+ [Attributes.P2P_ID]: peerId.toString(),
1014
+ });
1015
+
1016
+ // Exact same attestation received, no need to re-broadcast
1017
+ if (alreadyExists) {
1018
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1019
+ }
1020
+
1021
+ // Could not add (cap reached for signer), no need to re-broadcast
1022
+ if (!added) {
1023
+ this.logger.warn(`Dropping checkpoint attestation due to cap`, {
1024
+ slot: slot.toString(),
1025
+ archive: attestation.archive.toString(),
1026
+ source: peerId.toString(),
1027
+ attester: attestation.getSender()?.toString(),
1028
+ count,
1015
1029
  });
1030
+ return { result: TopicValidatorResult.Ignore, obj: attestation };
1031
+ }
1016
1032
 
1017
- if (validationResult.result === 'reject') {
1018
- return { result: TopicValidatorResult.Reject };
1019
- } else if (validationResult.result === 'ignore' || exists) {
1020
- return { result: TopicValidatorResult.Ignore, obj: block };
1021
- } else if (!canAdd) {
1022
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1023
- this.logger.warn(`Penalizing peer for block proposal exceeding per-slot cap`, {
1024
- slot: block.slotNumber.toString(),
1025
- archive: block.archive.toString(),
1026
- source: source.toString(),
1033
+ // Check if this is a duplicate attestation (signer attested to a different proposal at the same slot)
1034
+ // count is the number of attestations by this signer for this slot
1035
+ if (count === 2) {
1036
+ const attester = attestation.getSender();
1037
+ if (attester) {
1038
+ this.logger.warn(`Detected duplicate attestation (equivocation) at slot ${slot}`, {
1039
+ slot: slot.toString(),
1040
+ archive: attestation.archive.toString(),
1041
+ source: peerId.toString(),
1042
+ attester: attester.toString(),
1027
1043
  });
1028
- return { result: TopicValidatorResult.Reject };
1029
- } else {
1030
- return { result: TopicValidatorResult.Accept, obj: block };
1044
+ this.duplicateAttestationCallback?.({ slot, attester });
1031
1045
  }
1032
- };
1046
+ }
1047
+
1048
+ // Attestation was added successfully - accept it so other nodes can also detect the equivocation
1049
+ return { result: TopicValidatorResult.Accept, obj: attestation };
1050
+ }
1033
1051
 
1034
- const { result, obj: block } = await this.validateReceivedMessage<BlockProposal>(
1035
- validationFunc,
1052
+ protected async processBlockFromPeer(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1053
+ const {
1054
+ result,
1055
+ obj: block,
1056
+ metadata: { isEquivocated } = {},
1057
+ } = await this.validateReceivedMessage<BlockProposal, { isEquivocated: boolean }>(
1058
+ () => this.validateAndStoreBlockProposal(source, BlockProposal.fromBuffer(payloadData)),
1036
1059
  msgId,
1037
1060
  source,
1038
1061
  TopicType.block_proposal,
1039
1062
  );
1040
1063
 
1041
- if (!result || !block) {
1064
+ // If not accepted or equivocated, return
1065
+ if (result !== TopicValidatorResult.Accept || !block || isEquivocated) {
1042
1066
  return;
1043
1067
  }
1044
1068
 
1045
1069
  await this.processValidBlockProposal(block, source);
1046
1070
  }
1047
1071
 
1048
- // REVIEW: callback pattern https://github.com/AztecProtocol/aztec-packages/issues/7963
1072
+ /** Validates a block proposal. Triggers a penalization to the peer that sent it if invalid. Adds to the mempool if valid. */
1073
+ @trackSpan('Libp2pService.validateAndStoreBlockProposal', (_peerId, block) => ({
1074
+ [Attributes.BLOCK_NUMBER]: block.blockNumber.toString(),
1075
+ [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1076
+ }))
1077
+ protected async validateAndStoreBlockProposal(
1078
+ peerId: PeerId,
1079
+ block: BlockProposal,
1080
+ ): Promise<ReceivedMessageValidationResult<BlockProposal, { isEquivocated: boolean }>> {
1081
+ const validationResult = await this.blockProposalValidator.validate(block);
1082
+
1083
+ if (validationResult.result === 'reject') {
1084
+ this.logger.warn(`Penalizing peer ${peerId} for block proposal validation failure`);
1085
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
1086
+ return { result: TopicValidatorResult.Reject };
1087
+ }
1088
+
1089
+ if (validationResult.result === 'ignore') {
1090
+ return { result: TopicValidatorResult.Ignore, obj: block };
1091
+ }
1092
+
1093
+ // Try to add the proposal: this handles existence check, cap check, and adding in one call
1094
+ const { added, alreadyExists, count } = await this.mempools.attestationPool.tryAddBlockProposal(block);
1095
+ const isEquivocated = count !== undefined && count > 1;
1096
+
1097
+ // Duplicate proposal received, no need to re-broadcast
1098
+ if (alreadyExists) {
1099
+ this.logger.debug(`Ignoring duplicate block proposal received`, {
1100
+ ...block.toBlockInfo(),
1101
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1102
+ proposer: block.getSender()?.toString(),
1103
+ source: peerId.toString(),
1104
+ });
1105
+ return { result: TopicValidatorResult.Ignore, obj: block, metadata: { isEquivocated } };
1106
+ }
1107
+
1108
+ // Too many blocks received for this slot and index, penalize peer and do not re-broadcast
1109
+ if (!added) {
1110
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1111
+ this.logger.warn(`Penalizing peer for block proposal exceeding per-position cap`, {
1112
+ ...block.toBlockInfo(),
1113
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1114
+ count,
1115
+ proposer: block.getSender()?.toString(),
1116
+ source: peerId.toString(),
1117
+ });
1118
+ return { result: TopicValidatorResult.Reject, metadata: { isEquivocated } };
1119
+ }
1120
+
1121
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1122
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1123
+ if (isEquivocated) {
1124
+ const proposer = block.getSender();
1125
+ this.logger.warn(`Detected duplicate block proposal (equivocation) at slot ${block.slotNumber}`, {
1126
+ ...block.toBlockInfo(),
1127
+ source: peerId.toString(),
1128
+ proposer: proposer?.toString(),
1129
+ });
1130
+ // Invoke the duplicate callback on the first duplicate spotted only
1131
+ if (proposer && count === 2) {
1132
+ this.duplicateProposalCallback?.({ slot: block.slotNumber, proposer, type: 'block' });
1133
+ }
1134
+ return { result: TopicValidatorResult.Accept, obj: block, metadata: { isEquivocated } };
1135
+ }
1136
+
1137
+ // Otherwise, we're good to go!
1138
+ return { result: TopicValidatorResult.Accept, obj: block };
1139
+ }
1140
+
1049
1141
  // REFACTOR(palla): This method should be moved to the p2p_client or to a separate component,
1050
1142
  // should not be here as it does not deal with p2p networking.
1051
1143
  @trackSpan('Libp2pService.processValidBlockProposal', async block => ({
@@ -1053,7 +1145,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1053
1145
  [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
1054
1146
  [Attributes.P2P_ID]: await block.p2pMessageLoggingIdentifier().then(i => i.toString()),
1055
1147
  }))
1056
- private async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1148
+ protected async processValidBlockProposal(block: BlockProposal, sender: PeerId) {
1057
1149
  const slot = block.slotNumber;
1058
1150
  this.logger.verbose(`Received block proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1059
1151
  p2pMessageIdentifier: await block.p2pMessageLoggingIdentifier(),
@@ -1061,24 +1153,8 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1061
1153
  ...block.toBlockInfo(),
1062
1154
  });
1063
1155
 
1064
- // Attempt to add proposal
1065
- try {
1066
- await this.mempools.attestationPool.addBlockProposal(block);
1067
- } catch (err: unknown) {
1068
- // Drop proposals if we hit per-slot cap in the attestation pool; rethrow unknown errors
1069
- if (err instanceof ProposalSlotCapExceededError) {
1070
- this.logger.warn(`Dropping block proposal due to per-slot proposal cap`, {
1071
- slot: String(slot),
1072
- archive: block.archive.toString(),
1073
- error: (err as Error).message,
1074
- });
1075
- return;
1076
- }
1077
- throw err;
1078
- }
1079
-
1080
- // Mark the txs in this proposal as non-evictable
1081
- await this.mempools.txPool.markTxsAsNonEvictable(block.txHashes);
1156
+ // Mark the txs in this proposal as protected
1157
+ await this.mempools.txPool.protectTxs(block.txHashes, block.blockHeader);
1082
1158
 
1083
1159
  // Call the block received callback to validate the proposal.
1084
1160
  // Note: Validators do NOT attest to individual blocks, only to checkpoint proposals.
@@ -1092,67 +1168,145 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1092
1168
  * Handle a gossiped checkpoint proposal.
1093
1169
  * Validates and processes the checkpoint proposal, then triggers the callback for attestation.
1094
1170
  */
1095
- private async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1096
- // TODO(palla/mbps): This pattern is repeated across multiple message handlers, consider abstracting it.
1097
- const validationFunc: () => Promise<ReceivedMessageValidationResult<CheckpointProposal>> = async () => {
1098
- const checkpoint = CheckpointProposal.fromBuffer(payloadData);
1099
- const validationResult = await this.validateCheckpointProposal(source, checkpoint);
1100
- const isValid = validationResult.result === 'accept';
1101
- const pool = this.mempools.attestationPool;
1102
-
1103
- const exists = isValid && (await pool.hasCheckpointProposal(checkpoint));
1104
- const canAdd = isValid && (await pool.canAddCheckpointProposal(checkpoint));
1105
-
1106
- this.logger.trace(`Validate propagated checkpoint proposal`, {
1107
- isValid,
1108
- exists,
1109
- canAdd,
1171
+ protected async handleGossipedCheckpointProposal(payloadData: Buffer, msgId: string, source: PeerId): Promise<void> {
1172
+ const {
1173
+ result,
1174
+ obj: checkpoint,
1175
+ metadata: { isEquivocated, processBlock } = {},
1176
+ } = await this.validateReceivedMessage<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>(
1177
+ () => this.validateAndStoreCheckpointProposal(source, CheckpointProposal.fromBuffer(payloadData)),
1178
+ msgId,
1179
+ source,
1180
+ TopicType.checkpoint_proposal,
1181
+ );
1182
+
1183
+ // If the checkpoint contained a valid last block, we process it even if the checkpoint itself is to be rejected
1184
+ // TODO(palla/mbps): Is this ok? Should we be considering a block from a checkpoint that was equivocated?
1185
+ if (processBlock && checkpoint?.getBlockProposal()) {
1186
+ await this.processValidBlockProposal(checkpoint.getBlockProposal()!, source);
1187
+ }
1188
+
1189
+ if (result !== TopicValidatorResult.Accept || !checkpoint || isEquivocated) {
1190
+ return;
1191
+ }
1192
+
1193
+ await this.processValidCheckpointProposal(checkpoint.toCore(), source);
1194
+ }
1195
+
1196
+ /**
1197
+ * Validates a checkpoint proposal. Penalizes peer if validation fails. Adds the checkpoint and
1198
+ * its last block (if present) to the mempool if valid. Triggers equivocation detection on both.
1199
+ */
1200
+ @trackSpan('Libp2pService.validateAndStoreCheckpointProposal', (_peerId, checkpoint) => ({
1201
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1202
+ }))
1203
+ protected async validateAndStoreCheckpointProposal(
1204
+ peerId: PeerId,
1205
+ checkpoint: CheckpointProposal,
1206
+ ): Promise<ReceivedMessageValidationResult<CheckpointProposal, { isEquivocated: boolean; processBlock: boolean }>> {
1207
+ const validationResult = await this.checkpointProposalValidator.validate(checkpoint);
1208
+
1209
+ if (validationResult.result === 'reject') {
1210
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1211
+ this.peerManager.penalizePeer(peerId, validationResult.severity);
1212
+ return { result: TopicValidatorResult.Reject };
1213
+ }
1214
+
1215
+ if (validationResult.result === 'ignore') {
1216
+ return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1217
+ }
1218
+
1219
+ // Extract and try to add the block proposal first if present
1220
+ const blockProposal = checkpoint.getBlockProposal();
1221
+ let processBlock = false;
1222
+ if (blockProposal) {
1223
+ this.logger.debug(`Validating block proposal from propagated checkpoint`, {
1110
1224
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1111
- [Attributes.P2P_ID]: source.toString(),
1225
+ [Attributes.P2P_ID]: peerId.toString(),
1112
1226
  });
1113
-
1114
- if (validationResult.result === 'reject') {
1115
- return { result: TopicValidatorResult.Reject };
1116
- } else if (validationResult.result === 'ignore' || exists) {
1117
- return { result: TopicValidatorResult.Ignore, obj: checkpoint };
1118
- } else if (!canAdd) {
1119
- this.peerManager.penalizePeer(source, PeerErrorSeverity.MidToleranceError);
1120
- this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1121
- slot: checkpoint.slotNumber.toString(),
1122
- archive: checkpoint.archive.toString(),
1123
- source: source.toString(),
1227
+ const {
1228
+ result,
1229
+ obj,
1230
+ metadata: { isEquivocated } = {},
1231
+ } = await this.validateAndStoreBlockProposal(peerId, blockProposal);
1232
+ if (result === TopicValidatorResult.Reject || !obj || isEquivocated) {
1233
+ this.logger.debug(`Rejecting checkpoint due to invalid last block proposal`, {
1234
+ [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1235
+ [Attributes.P2P_ID]: peerId.toString(),
1236
+ isEquivocated,
1237
+ result,
1124
1238
  });
1125
1239
  return { result: TopicValidatorResult.Reject };
1126
- } else {
1127
- return { result: TopicValidatorResult.Accept, obj: checkpoint };
1240
+ } else if (result === TopicValidatorResult.Accept && obj && !isEquivocated) {
1241
+ processBlock = true;
1128
1242
  }
1129
- };
1243
+ }
1130
1244
 
1131
- const { result, obj: checkpoint } = await this.validateReceivedMessage<CheckpointProposal>(
1132
- validationFunc,
1133
- msgId,
1134
- source,
1135
- TopicType.checkpoint_proposal,
1136
- );
1245
+ // Try to add the checkpoint proposal core: this handles existence check, cap check, and adding in one call
1246
+ const checkpointCore = checkpoint.toCore();
1247
+ const tryAddResult = await this.mempools.attestationPool.tryAddCheckpointProposal(checkpointCore);
1248
+ const { added, alreadyExists, count } = tryAddResult;
1249
+ const isEquivocated = count !== undefined && count > 1;
1250
+
1251
+ // Duplicate proposal received, do not re-broadcast
1252
+ if (alreadyExists) {
1253
+ this.logger.debug(`Ignoring duplicate checkpoint proposal received`, {
1254
+ ...checkpoint.toCheckpointInfo(),
1255
+ source: peerId.toString(),
1256
+ });
1257
+ return {
1258
+ result: TopicValidatorResult.Ignore,
1259
+ obj: checkpoint,
1260
+ metadata: { isEquivocated, processBlock },
1261
+ };
1262
+ }
1137
1263
 
1138
- if (result !== TopicValidatorResult.Accept || !checkpoint) {
1139
- return;
1264
+ // Too many checkpoint proposals received for this slot, penalize peer and do not re-broadcast
1265
+ // Note: We still return the checkpoint obj so the lastBlock can be processed if valid
1266
+ if (!added) {
1267
+ this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
1268
+ this.logger.warn(`Penalizing peer for checkpoint proposal exceeding per-slot cap`, {
1269
+ ...checkpoint.toCheckpointInfo(),
1270
+ count,
1271
+ source: peerId.toString(),
1272
+ });
1273
+ return { result: TopicValidatorResult.Reject, obj: checkpoint, metadata: { isEquivocated, processBlock } };
1140
1274
  }
1141
1275
 
1142
- await this.processValidCheckpointProposal(checkpoint, source);
1276
+ // If this was a duplicate proposal, do not process it, but do invoke the duplicate callback,
1277
+ // and do re-broadcast it so other nodes in the network know to slash the proposer
1278
+ if (isEquivocated) {
1279
+ const proposer = checkpoint.getSender();
1280
+ this.logger.warn(`Detected duplicate checkpoint proposal (equivocation) at slot ${checkpoint.slotNumber}`, {
1281
+ ...checkpoint.toCheckpointInfo(),
1282
+ source: peerId.toString(),
1283
+ proposer: proposer?.toString(),
1284
+ });
1285
+ // Invoke the duplicate callback on the first duplicate spotted only
1286
+ if (proposer && count === 2) {
1287
+ this.duplicateProposalCallback?.({ slot: checkpoint.slotNumber, proposer, type: 'checkpoint' });
1288
+ }
1289
+ return {
1290
+ result: TopicValidatorResult.Accept,
1291
+ obj: checkpoint,
1292
+ metadata: { isEquivocated, processBlock },
1293
+ };
1294
+ }
1295
+
1296
+ // Otherwise, we're good to go!
1297
+ return { result: TopicValidatorResult.Accept, obj: checkpoint, metadata: { processBlock, isEquivocated } };
1143
1298
  }
1144
1299
 
1145
1300
  /**
1146
1301
  * Process a validated checkpoint proposal.
1147
- * Extracts and processes the last block proposal (if present) first, then processes the checkpoint.
1148
- * The block callback is invoked before the checkpoint callback.
1302
+ * Note: The proposal was already added to the pool by tryAddCheckpointProposal in handleGossipedCheckpointProposal.
1149
1303
  */
1150
1304
  @trackSpan('Libp2pService.processValidCheckpointProposal', async checkpoint => ({
1151
1305
  [Attributes.SLOT_NUMBER]: checkpoint.slotNumber,
1152
1306
  [Attributes.BLOCK_ARCHIVE]: checkpoint.archive.toString(),
1153
1307
  [Attributes.P2P_ID]: await checkpoint.p2pMessageLoggingIdentifier().then(i => i.toString()),
1154
1308
  }))
1155
- private async processValidCheckpointProposal(checkpoint: CheckpointProposal, sender: PeerId) {
1309
+ protected async processValidCheckpointProposal(checkpoint: CheckpointProposalCore, sender: PeerId) {
1156
1310
  const slot = checkpoint.slotNumber;
1157
1311
  this.logger.verbose(`Received checkpoint proposal for slot ${slot} from external peer ${sender.toString()}.`, {
1158
1312
  p2pMessageIdentifier: await checkpoint.p2pMessageLoggingIdentifier(),
@@ -1161,37 +1315,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1161
1315
  source: sender.toString(),
1162
1316
  });
1163
1317
 
1164
- // Extract block proposal before adding to pool (pool stores them separately)
1165
- const blockProposal = checkpoint.getBlockProposal();
1166
-
1167
- // Add proposal to the pool (this extracts and stores block proposal separately)
1168
- await this.mempools.attestationPool.addCheckpointProposal(checkpoint);
1169
-
1170
- // Mark txs as non-evictable if present (from the last block)
1171
- if (checkpoint.txHashes.length > 0) {
1172
- await this.mempools.txPool.markTxsAsNonEvictable(checkpoint.txHashes);
1173
- }
1174
-
1175
- // If there was a last block proposal, invoke the block callback first for validation.
1176
- // Note: The block proposal is already stored in the pool by addCheckpointProposal.
1177
- if (blockProposal) {
1178
- const isValid = await this.blockReceivedCallback(blockProposal, sender);
1179
- if (!isValid) {
1180
- this.logger.warn(`Block proposal from checkpoint failed validation`, {
1181
- slot: slot.toString(),
1182
- archive: checkpoint.archive.toString(),
1183
- blockNumber: blockProposal.blockNumber.toString(),
1184
- });
1185
- return;
1186
- }
1187
- }
1188
-
1189
1318
  // Call the checkpoint received callback with the core version (without lastBlock)
1190
1319
  // to validate and potentially generate attestations
1191
- const attestations = await this.checkpointReceivedCallback(checkpoint.toCore(), sender);
1320
+ const attestations = await this.checkpointReceivedCallback(checkpoint, sender);
1192
1321
  if (attestations && attestations.length > 0) {
1193
1322
  // If the callback returned attestations, add them to the pool and propagate them
1194
- await this.mempools.attestationPool.addCheckpointAttestations(attestations);
1323
+ await this.mempools.attestationPool.addOwnCheckpointAttestations(attestations);
1195
1324
  for (const attestation of attestations) {
1196
1325
  await this.propagate(attestation);
1197
1326
  }
@@ -1220,7 +1349,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1220
1349
  @trackSpan('Libp2pService.validateRequestedBlockTxs', request => ({
1221
1350
  [Attributes.BLOCK_ARCHIVE]: request.archiveRoot.toString(),
1222
1351
  }))
1223
- private async validateRequestedBlockTxs(
1352
+ protected async validateRequestedBlockTxs(
1224
1353
  request: BlockTxsRequest,
1225
1354
  response: BlockTxsResponse,
1226
1355
  peerId: PeerId,
@@ -1350,7 +1479,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1350
1479
  @trackSpan('Libp2pService.validateRequestedBlock', (requestedBlockNumber, _responseBlock) => ({
1351
1480
  [Attributes.BLOCK_NUMBER]: requestedBlockNumber.toString(),
1352
1481
  }))
1353
- private async validateRequestedBlock(
1482
+ protected async validateRequestedBlock(
1354
1483
  requestedBlockNumber: Fr,
1355
1484
  responseBlock: L2Block,
1356
1485
  peerId: PeerId,
@@ -1383,7 +1512,12 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1383
1512
  }
1384
1513
  }
1385
1514
 
1386
- private async validateRequestedTx(tx: Tx, peerId: PeerId, txValidator: TxValidator, requested?: Set<`0x${string}`>) {
1515
+ protected async validateRequestedTx(
1516
+ tx: Tx,
1517
+ peerId: PeerId,
1518
+ txValidator: TxValidator,
1519
+ requested?: Set<`0x${string}`>,
1520
+ ) {
1387
1521
  const penalize = (severity: PeerErrorSeverity) => this.peerManager.penalizePeer(peerId, severity);
1388
1522
  if (requested && !requested.has(tx.getTxHash().toString())) {
1389
1523
  penalize(PeerErrorSeverity.MidToleranceError);
@@ -1397,7 +1531,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1397
1531
  }
1398
1532
  }
1399
1533
 
1400
- private createRequestedTxValidator(): TxValidator {
1534
+ protected createRequestedTxValidator(): TxValidator {
1401
1535
  return createTxReqRespValidator(this.proofVerifier, {
1402
1536
  l1ChainId: this.config.l1ChainId,
1403
1537
  rollupVersion: this.config.rollupVersion,
@@ -1407,7 +1541,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1407
1541
  @trackSpan('Libp2pService.validatePropagatedTx', tx => ({
1408
1542
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1409
1543
  }))
1410
- private async validatePropagatedTx(tx: Tx, peerId: PeerId): Promise<boolean> {
1544
+ protected async validatePropagatedTx(tx: Tx, peerId: PeerId): Promise<boolean> {
1411
1545
  const currentBlockNumber = await this.archiver.getBlockNumber();
1412
1546
 
1413
1547
  // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
@@ -1605,50 +1739,7 @@ export class LibP2PService<T extends P2PClientType = P2PClientType.Full> extends
1605
1739
  const result = await this.checkpointAttestationValidator.validate(attestation);
1606
1740
 
1607
1741
  if (result.result === 'reject') {
1608
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1609
- this.peerManager.penalizePeer(peerId, result.severity);
1610
- }
1611
-
1612
- return result;
1613
- }
1614
-
1615
- /**
1616
- * Validate a block proposal.
1617
- *
1618
- * @param block - The block proposal to validate.
1619
- * @returns True if the block proposal is valid, false otherwise.
1620
- */
1621
- @trackSpan('Libp2pService.validateBlockProposal', (_peerId, block) => ({
1622
- [Attributes.SLOT_NUMBER]: block.slotNumber.toString(),
1623
- }))
1624
- public async validateBlockProposal(peerId: PeerId, block: BlockProposal): Promise<P2PValidationResult> {
1625
- const result = await this.blockProposalValidator.validate(block);
1626
-
1627
- if (result.result === 'reject') {
1628
- this.logger.debug(`Penalizing peer ${peerId} for block proposal validation failure`);
1629
- this.peerManager.penalizePeer(peerId, result.severity);
1630
- }
1631
-
1632
- return result;
1633
- }
1634
-
1635
- /**
1636
- * Validate a checkpoint proposal.
1637
- *
1638
- * @param checkpoint - The checkpoint proposal to validate.
1639
- * @returns True if the checkpoint proposal is valid, false otherwise.
1640
- */
1641
- @trackSpan('Libp2pService.validateCheckpointProposal', (_peerId, checkpoint) => ({
1642
- [Attributes.SLOT_NUMBER]: checkpoint.slotNumber.toString(),
1643
- }))
1644
- public async validateCheckpointProposal(
1645
- peerId: PeerId,
1646
- checkpoint: CheckpointProposal,
1647
- ): Promise<P2PValidationResult> {
1648
- const result = await this.checkpointProposalValidator.validate(checkpoint);
1649
-
1650
- if (result.result === 'reject') {
1651
- this.logger.debug(`Penalizing peer ${peerId} for checkpoint proposal validation failure`);
1742
+ this.logger.warn(`Penalizing peer ${peerId} for checkpoint attestation validation failure`);
1652
1743
  this.peerManager.penalizePeer(peerId, result.severity);
1653
1744
  }
1654
1745