@aztec-labs/validator-client 6.0.0-nightly.20260829
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +327 -0
- package/dest/checkpoint_builder.d.ts +92 -0
- package/dest/checkpoint_builder.d.ts.map +1 -0
- package/dest/checkpoint_builder.js +272 -0
- package/dest/config.d.ts +17 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/config.js +102 -0
- package/dest/duties/validation_service.d.ts +65 -0
- package/dest/duties/validation_service.d.ts.map +1 -0
- package/dest/duties/validation_service.js +128 -0
- package/dest/factory.d.ts +41 -0
- package/dest/factory.d.ts.map +1 -0
- package/dest/factory.js +19 -0
- package/dest/index.d.ts +7 -0
- package/dest/index.d.ts.map +1 -0
- package/dest/index.js +6 -0
- package/dest/key_store/ha_key_store.d.ts +99 -0
- package/dest/key_store/ha_key_store.d.ts.map +1 -0
- package/dest/key_store/ha_key_store.js +208 -0
- package/dest/key_store/index.d.ts +6 -0
- package/dest/key_store/index.d.ts.map +1 -0
- package/dest/key_store/index.js +5 -0
- package/dest/key_store/interface.d.ts +104 -0
- package/dest/key_store/interface.d.ts.map +1 -0
- package/dest/key_store/interface.js +4 -0
- package/dest/key_store/local_key_store.d.ts +63 -0
- package/dest/key_store/local_key_store.d.ts.map +1 -0
- package/dest/key_store/local_key_store.js +83 -0
- package/dest/key_store/node_keystore_adapter.d.ts +151 -0
- package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
- package/dest/key_store/node_keystore_adapter.js +330 -0
- package/dest/key_store/web3signer_key_store.d.ts +74 -0
- package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
- package/dest/key_store/web3signer_key_store.js +147 -0
- package/dest/metrics.d.ts +31 -0
- package/dest/metrics.d.ts.map +1 -0
- package/dest/metrics.js +101 -0
- package/dest/proposal_handler.d.ts +188 -0
- package/dest/proposal_handler.d.ts.map +1 -0
- package/dest/proposal_handler.js +1438 -0
- package/dest/streaming_inbox_checks.d.ts +103 -0
- package/dest/streaming_inbox_checks.d.ts.map +1 -0
- package/dest/streaming_inbox_checks.js +112 -0
- package/dest/validator.d.ts +137 -0
- package/dest/validator.d.ts.map +1 -0
- package/dest/validator.js +771 -0
- package/package.json +110 -0
- package/src/checkpoint_builder.ts +449 -0
- package/src/config.ts +130 -0
- package/src/duties/validation_service.ts +224 -0
- package/src/factory.ts +95 -0
- package/src/index.ts +6 -0
- package/src/key_store/ha_key_store.ts +268 -0
- package/src/key_store/index.ts +5 -0
- package/src/key_store/interface.ts +120 -0
- package/src/key_store/local_key_store.ts +104 -0
- package/src/key_store/node_keystore_adapter.ts +397 -0
- package/src/key_store/web3signer_key_store.ts +188 -0
- package/src/metrics.ts +150 -0
- package/src/proposal_handler.ts +1598 -0
- package/src/streaming_inbox_checks.ts +198 -0
- package/src/validator.ts +1125 -0
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
import { getBlobsPerL1Block } from '@aztec-labs/blob-lib';
|
|
2
|
+
import { CheckpointNumber } from '@aztec-labs/foundation/branded-types';
|
|
3
|
+
import { FifoSet } from '@aztec-labs/foundation/fifo-set';
|
|
4
|
+
import { createLogger } from '@aztec-labs/foundation/log';
|
|
5
|
+
import { RunningPromise } from '@aztec-labs/foundation/running-promise';
|
|
6
|
+
import { sleep } from '@aztec-labs/foundation/sleep';
|
|
7
|
+
import { DateProvider } from '@aztec-labs/foundation/timer';
|
|
8
|
+
import { AuthRequest, AuthResponse, ReqRespSubProtocol } from '@aztec-labs/p2p';
|
|
9
|
+
import { OffenseType, WANT_TO_CLEAR_SLASH_EVENT, WANT_TO_SLASH_EVENT, getOffenseTypeName } from '@aztec-labs/slasher';
|
|
10
|
+
import { getEpochAtSlot } from '@aztec-labs/stdlib/epoch-helpers';
|
|
11
|
+
import { ConsensusTimetable } from '@aztec-labs/stdlib/timetable';
|
|
12
|
+
import { AttestationTimeoutError } from '@aztec-labs/stdlib/validators';
|
|
13
|
+
import { getTelemetryClient } from '@aztec-labs/telemetry-client';
|
|
14
|
+
import { createHASigner, createLocalSignerWithProtection, createSignerFromSharedDb } from '@aztec-labs/validator-ha-signer/factory';
|
|
15
|
+
import { DutyType } from '@aztec-labs/validator-ha-signer/types';
|
|
16
|
+
import { EventEmitter } from 'events';
|
|
17
|
+
import { ValidationService } from './duties/validation_service.js';
|
|
18
|
+
import { HAKeyStore } from './key_store/ha_key_store.js';
|
|
19
|
+
import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
|
|
20
|
+
import { ValidatorMetrics } from './metrics.js';
|
|
21
|
+
import { ProposalHandler, SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT, SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT } from './proposal_handler.js';
|
|
22
|
+
// We maintain a set of proposers who have proposed invalid blocks.
|
|
23
|
+
// Just cap the set to avoid unbounded growth.
|
|
24
|
+
const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
|
|
25
|
+
const MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS = 1000;
|
|
26
|
+
const MAX_TRACKED_BAD_ATTESTATIONS = 10_000;
|
|
27
|
+
/**
|
|
28
|
+
* Validator Client
|
|
29
|
+
*/ export class ValidatorClient extends EventEmitter {
|
|
30
|
+
keyStore;
|
|
31
|
+
epochCache;
|
|
32
|
+
p2pClient;
|
|
33
|
+
proposalHandler;
|
|
34
|
+
blockSource;
|
|
35
|
+
checkpointsBuilder;
|
|
36
|
+
worldState;
|
|
37
|
+
l1ToL2MessageSource;
|
|
38
|
+
config;
|
|
39
|
+
blobClient;
|
|
40
|
+
slashingProtectionSigner;
|
|
41
|
+
dateProvider;
|
|
42
|
+
tracer;
|
|
43
|
+
validationService;
|
|
44
|
+
metrics;
|
|
45
|
+
log;
|
|
46
|
+
// Whether it has already registered handlers on the p2p client
|
|
47
|
+
hasRegisteredHandlers;
|
|
48
|
+
/** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
|
|
49
|
+
/** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
|
|
50
|
+
lastEpochForCommitteeUpdateLoop;
|
|
51
|
+
epochCacheUpdateLoop;
|
|
52
|
+
/** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
|
|
53
|
+
proposersOfInvalidBlocks;
|
|
54
|
+
invalidCheckpointProposalOffenseKeys;
|
|
55
|
+
oversizedProposalOffenseKeys;
|
|
56
|
+
badAttestationOffenseKeys;
|
|
57
|
+
/** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
|
|
58
|
+
constructor(keyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
|
|
59
|
+
super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.proposalHandler = proposalHandler, this.blockSource = blockSource, this.checkpointsBuilder = checkpointsBuilder, this.worldState = worldState, this.l1ToL2MessageSource = l1ToL2MessageSource, this.config = config, this.blobClient = blobClient, this.slashingProtectionSigner = slashingProtectionSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.lastAttestedEpochByAttester = new Map(), this.proposersOfInvalidBlocks = FifoSet.withLimit(MAX_PROPOSERS_OF_INVALID_BLOCKS), this.invalidCheckpointProposalOffenseKeys = FifoSet.withLimit(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS), this.oversizedProposalOffenseKeys = FifoSet.withLimit(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS), this.badAttestationOffenseKeys = FifoSet.withLimit(MAX_TRACKED_BAD_ATTESTATIONS);
|
|
60
|
+
// Create child logger with fisherman prefix if in fisherman mode
|
|
61
|
+
this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
|
|
62
|
+
this.tracer = telemetry.getTracer('Validator');
|
|
63
|
+
this.metrics = new ValidatorMetrics(telemetry);
|
|
64
|
+
this.validationService = new ValidationService(keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
|
|
65
|
+
this.proposalHandler.setCheckpointProposalValidationFailureCallback((proposal, result, proposalInfo)=>this.handleInvalidCheckpointProposal(proposal, result, proposalInfo));
|
|
66
|
+
// Refresh epoch cache every second to trigger alert if participation in committee changes
|
|
67
|
+
this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
|
|
68
|
+
const myAddresses = this.getValidatorAddresses();
|
|
69
|
+
this.log.verbose(`Initialized validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
|
|
70
|
+
}
|
|
71
|
+
static validateKeyStoreConfiguration(keyStoreManager, logger) {
|
|
72
|
+
const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
|
|
73
|
+
const validatorAddresses = validatorKeyStore.getAddresses();
|
|
74
|
+
// Verify that we can retrieve all required data from the key store
|
|
75
|
+
for (const address of validatorAddresses){
|
|
76
|
+
// Functions throw if required data is not available
|
|
77
|
+
let coinbase;
|
|
78
|
+
let feeRecipient;
|
|
79
|
+
try {
|
|
80
|
+
coinbase = validatorKeyStore.getCoinbaseAddress(address);
|
|
81
|
+
feeRecipient = validatorKeyStore.getFeeRecipient(address);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
|
|
84
|
+
}
|
|
85
|
+
const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
|
|
86
|
+
if (!publisherAddresses.length) {
|
|
87
|
+
throw new Error(`No publisher addresses found for validator address ${address}`);
|
|
88
|
+
}
|
|
89
|
+
logger?.debug(`Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map((x)=>x.toString()).join()}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async handleEpochCommitteeUpdate() {
|
|
93
|
+
try {
|
|
94
|
+
const { committee, epoch } = await this.epochCache.getCommittee('next');
|
|
95
|
+
if (!committee) {
|
|
96
|
+
this.log.trace(`No committee found for slot`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
this.metrics.setCurrentEpoch(epoch);
|
|
100
|
+
if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
|
|
101
|
+
const me = this.getValidatorAddresses();
|
|
102
|
+
const committeeSet = new Set(committee.map((v)=>v.toString()));
|
|
103
|
+
const inCommittee = me.filter((a)=>committeeSet.has(a.toString()));
|
|
104
|
+
if (inCommittee.length > 0) {
|
|
105
|
+
this.log.info(`Validators ${inCommittee.map((a)=>a.toString()).join(',')} are on the validator committee for epoch ${epoch}`);
|
|
106
|
+
} else {
|
|
107
|
+
this.log.verbose(`Validators ${me.map((a)=>a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`);
|
|
108
|
+
}
|
|
109
|
+
this.lastEpochForCommitteeUpdateLoop = epoch;
|
|
110
|
+
}
|
|
111
|
+
} catch (err) {
|
|
112
|
+
this.log.error(`Error updating epoch committee`, err);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, reexecutionTracker, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), slashingProtectionDb) {
|
|
116
|
+
const metrics = new ValidatorMetrics(telemetry);
|
|
117
|
+
const consensusTimetable = new ConsensusTimetable({
|
|
118
|
+
l1Constants: epochCache.getL1Constants(),
|
|
119
|
+
blockDuration: config.blockDurationMs / 1000
|
|
120
|
+
});
|
|
121
|
+
const proposalHandler = new ProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, epochCache, consensusTimetable, config, blobClient, reexecutionTracker, metrics, dateProvider, telemetry, undefined);
|
|
122
|
+
const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
|
|
123
|
+
let slashingProtectionSigner;
|
|
124
|
+
if (slashingProtectionDb) {
|
|
125
|
+
// Shared database mode: use a pre-existing database (e.g. for testing HA setups).
|
|
126
|
+
({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
|
|
127
|
+
telemetryClient: telemetry,
|
|
128
|
+
dateProvider
|
|
129
|
+
}));
|
|
130
|
+
} else if (config.haSigningEnabled) {
|
|
131
|
+
// Multi-node HA mode: use PostgreSQL-backed distributed locking.
|
|
132
|
+
// If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
|
|
133
|
+
const haConfig = {
|
|
134
|
+
...config,
|
|
135
|
+
maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
|
|
136
|
+
};
|
|
137
|
+
({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
|
|
138
|
+
telemetryClient: telemetry,
|
|
139
|
+
dateProvider
|
|
140
|
+
}));
|
|
141
|
+
} else {
|
|
142
|
+
// Single-node mode: use LMDB-backed local signing protection.
|
|
143
|
+
// This prevents double-signing if the node crashes and restarts mid-proposal.
|
|
144
|
+
({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
|
|
145
|
+
telemetryClient: telemetry,
|
|
146
|
+
dateProvider
|
|
147
|
+
}));
|
|
148
|
+
}
|
|
149
|
+
const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
|
|
150
|
+
const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
|
|
151
|
+
return validator;
|
|
152
|
+
}
|
|
153
|
+
getValidatorAddresses() {
|
|
154
|
+
return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
|
|
155
|
+
}
|
|
156
|
+
getProposalHandler() {
|
|
157
|
+
return this.proposalHandler;
|
|
158
|
+
}
|
|
159
|
+
signWithAddress(addr, msg, context) {
|
|
160
|
+
return this.keyStore.signTypedDataWithAddress(addr, msg, context);
|
|
161
|
+
}
|
|
162
|
+
getSignatureContext() {
|
|
163
|
+
return {
|
|
164
|
+
chainId: this.config.l1ChainId,
|
|
165
|
+
rollupAddress: this.config.rollupAddress
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
getCoinbaseForAttestor(attestor) {
|
|
169
|
+
return this.keyStore.getCoinbaseAddress(attestor);
|
|
170
|
+
}
|
|
171
|
+
getFeeRecipientForAttestor(attestor) {
|
|
172
|
+
return this.keyStore.getFeeRecipient(attestor);
|
|
173
|
+
}
|
|
174
|
+
getConfig() {
|
|
175
|
+
return this.config;
|
|
176
|
+
}
|
|
177
|
+
hasProposalEquivocation(slotNumber) {
|
|
178
|
+
return this.proposalHandler.hasProposalEquivocation(slotNumber);
|
|
179
|
+
}
|
|
180
|
+
hasInvalidProposals(slotNumber) {
|
|
181
|
+
return this.proposalHandler.hasInvalidProposals(slotNumber);
|
|
182
|
+
}
|
|
183
|
+
updateConfig(config) {
|
|
184
|
+
this.config = {
|
|
185
|
+
...this.config,
|
|
186
|
+
...config
|
|
187
|
+
};
|
|
188
|
+
this.proposalHandler.updateConfig(config);
|
|
189
|
+
}
|
|
190
|
+
reloadKeystore(newManager) {
|
|
191
|
+
const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
|
|
192
|
+
this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
|
|
193
|
+
this.validationService = new ValidationService(this.keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
|
|
194
|
+
}
|
|
195
|
+
async start() {
|
|
196
|
+
if (this.epochCacheUpdateLoop.isRunning()) {
|
|
197
|
+
this.log.warn(`Validator client already started`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
await this.keyStore.start();
|
|
201
|
+
await this.registerHandlers();
|
|
202
|
+
const myAddresses = this.getValidatorAddresses();
|
|
203
|
+
const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
|
|
204
|
+
this.log.info(`Started validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
|
|
205
|
+
if (inCommittee.length > 0) {
|
|
206
|
+
this.log.info(`Addresses in current validator committee: ${inCommittee.map((a)=>a.toString()).join(', ')}`);
|
|
207
|
+
}
|
|
208
|
+
this.epochCacheUpdateLoop.start();
|
|
209
|
+
return Promise.resolve();
|
|
210
|
+
}
|
|
211
|
+
async stop() {
|
|
212
|
+
await this.epochCacheUpdateLoop.stop();
|
|
213
|
+
await this.keyStore.stop();
|
|
214
|
+
}
|
|
215
|
+
/** Register handlers on the p2p client */ async registerHandlers() {
|
|
216
|
+
if (!this.hasRegisteredHandlers) {
|
|
217
|
+
this.hasRegisteredHandlers = true;
|
|
218
|
+
this.log.debug(`Registering validator handlers for p2p client`);
|
|
219
|
+
// Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
|
|
220
|
+
const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
|
|
221
|
+
this.p2pClient.registerBlockProposalHandler(blockHandler);
|
|
222
|
+
// Checkpoint proposal handler - validates and creates attestations
|
|
223
|
+
// The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
|
|
224
|
+
// and processed separately via the block handler above.
|
|
225
|
+
const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
|
|
226
|
+
this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
|
|
227
|
+
// Duplicate proposal handler - triggers slashing for equivocation
|
|
228
|
+
this.p2pClient.registerDuplicateProposalCallback((info)=>{
|
|
229
|
+
this.handleDuplicateProposal(info);
|
|
230
|
+
});
|
|
231
|
+
// Oversized proposal handler - triggers slashing for proposals beyond the per-checkpoint block limit
|
|
232
|
+
this.p2pClient.registerOversizedProposalCallback((info)=>{
|
|
233
|
+
this.handleOversizedProposal(info);
|
|
234
|
+
});
|
|
235
|
+
// Duplicate attestation handler - triggers slashing for attestation equivocation
|
|
236
|
+
this.p2pClient.registerDuplicateAttestationCallback((info)=>{
|
|
237
|
+
this.handleDuplicateAttestation(info);
|
|
238
|
+
});
|
|
239
|
+
this.p2pClient.registerCheckpointAttestationCallback((attestation)=>{
|
|
240
|
+
this.handleCheckpointAttestation(attestation);
|
|
241
|
+
});
|
|
242
|
+
const myAddresses = this.getValidatorAddresses();
|
|
243
|
+
this.p2pClient.registerThisValidatorAddresses(myAddresses);
|
|
244
|
+
await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Validate a block proposal from a peer.
|
|
249
|
+
* Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
|
|
250
|
+
* @returns true if the proposal is valid, false otherwise
|
|
251
|
+
*/ async validateBlockProposal(proposal, proposalSender) {
|
|
252
|
+
const slotNumber = proposal.slotNumber;
|
|
253
|
+
// Note: During escape hatch, we still want to "validate" proposals for observability,
|
|
254
|
+
// but we intentionally reject them and disable slashing invalid block and attestation flow.
|
|
255
|
+
const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
|
|
256
|
+
const proposer = proposal.getSender();
|
|
257
|
+
// Reject proposals with invalid signatures
|
|
258
|
+
if (!proposer) {
|
|
259
|
+
this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
// Log self-proposals from HA peers (same validator key on different nodes)
|
|
263
|
+
if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
|
|
264
|
+
this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
|
|
265
|
+
proposer: proposer.toString(),
|
|
266
|
+
slotNumber
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
// Check if we're in the committee (for metrics purposes)
|
|
270
|
+
const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
|
|
271
|
+
const partOfCommittee = inCommittee.length > 0;
|
|
272
|
+
const proposalInfo = {
|
|
273
|
+
...proposal.toBlockInfo(),
|
|
274
|
+
proposer: proposer.toString()
|
|
275
|
+
};
|
|
276
|
+
this.log.info(`Received block proposal for slot ${slotNumber}`, {
|
|
277
|
+
...proposalInfo,
|
|
278
|
+
txHashes: proposal.txHashes.map((t)=>t.toString()),
|
|
279
|
+
fishermanMode: this.config.fishermanMode || false
|
|
280
|
+
});
|
|
281
|
+
// Reexecute outside the escape hatch so slashing observers can detect invalid proposals even when penalties are 0.
|
|
282
|
+
const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !escapeHatchOpen);
|
|
283
|
+
if (!validationResult.isValid) {
|
|
284
|
+
const reason = validationResult.reason || 'unknown';
|
|
285
|
+
this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
|
|
286
|
+
// Classify failure reason: bad proposal vs node issue
|
|
287
|
+
const badProposalReasons = [
|
|
288
|
+
'invalid_proposal',
|
|
289
|
+
'state_mismatch',
|
|
290
|
+
'failed_txs',
|
|
291
|
+
'parent_block_wrong_slot',
|
|
292
|
+
'duplicate_txs',
|
|
293
|
+
'invalid_embedded_txs'
|
|
294
|
+
];
|
|
295
|
+
if (badProposalReasons.includes(reason)) {
|
|
296
|
+
this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
|
|
297
|
+
} else {
|
|
298
|
+
// Node issues so we can't validate
|
|
299
|
+
this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
|
|
300
|
+
}
|
|
301
|
+
if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason)) {
|
|
302
|
+
this.log.info(`Detected invalid block proposal offense`, {
|
|
303
|
+
...proposalInfo,
|
|
304
|
+
amount: this.config.slashBroadcastedInvalidBlockPenalty,
|
|
305
|
+
offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL)
|
|
306
|
+
});
|
|
307
|
+
this.slashInvalidBlock(proposal);
|
|
308
|
+
this.markInvalidProposalSlot(proposal.slotNumber);
|
|
309
|
+
}
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
this.log.info(`Validated block proposal for slot ${slotNumber}`, {
|
|
313
|
+
...proposalInfo,
|
|
314
|
+
inCommittee: partOfCommittee,
|
|
315
|
+
fishermanMode: this.config.fishermanMode || false,
|
|
316
|
+
escapeHatchOpen
|
|
317
|
+
});
|
|
318
|
+
if (escapeHatchOpen) {
|
|
319
|
+
this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
|
|
320
|
+
return false;
|
|
321
|
+
}
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Validate and attest to a checkpoint proposal from a peer.
|
|
326
|
+
* The proposal is received as CheckpointProposalCore (without lastBlock) since
|
|
327
|
+
* the lastBlock is extracted and processed separately via the block handler.
|
|
328
|
+
* @returns Checkpoint attestations if valid, undefined otherwise
|
|
329
|
+
*/ async attestToCheckpointProposal(proposal, _proposalSender) {
|
|
330
|
+
const proposalSlotNumber = proposal.slotNumber;
|
|
331
|
+
const proposer = proposal.getSender();
|
|
332
|
+
// If escape hatch is open for this slot's epoch, do not attest.
|
|
333
|
+
if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
|
|
334
|
+
this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
// Early-out for equivocation: refuses if we've already attested to a higher slot.
|
|
338
|
+
if (!this.shouldAttestToSlot(proposalSlotNumber)) {
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
// Ignore proposals from ourselves (may happen in HA setups)
|
|
342
|
+
if (proposer && this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
|
|
343
|
+
this.log.debug(`Not attesting to block proposal from self for slot ${proposalSlotNumber}`, {
|
|
344
|
+
proposer: proposer.toString(),
|
|
345
|
+
proposalSlotNumber
|
|
346
|
+
});
|
|
347
|
+
return undefined;
|
|
348
|
+
}
|
|
349
|
+
// Check that I have any address in the committee where this checkpoint will land before attesting
|
|
350
|
+
const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
|
|
351
|
+
const partOfCommittee = inCommittee.length > 0;
|
|
352
|
+
const proposalInfo = {
|
|
353
|
+
proposalSlotNumber,
|
|
354
|
+
archive: proposal.archive.toString(),
|
|
355
|
+
proposer: proposer?.toString()
|
|
356
|
+
};
|
|
357
|
+
this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
|
|
358
|
+
...proposalInfo,
|
|
359
|
+
fishermanMode: this.config.fishermanMode || false
|
|
360
|
+
});
|
|
361
|
+
// Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
|
|
362
|
+
// Uses the cached result from the all-nodes callback if available (avoids double validation).
|
|
363
|
+
let checkpointNumber;
|
|
364
|
+
if (this.config.skipCheckpointProposalValidation) {
|
|
365
|
+
this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
|
|
366
|
+
checkpointNumber = CheckpointNumber(0);
|
|
367
|
+
} else {
|
|
368
|
+
const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
|
|
369
|
+
if (!validationResult.isValid) {
|
|
370
|
+
this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
|
|
371
|
+
return undefined;
|
|
372
|
+
}
|
|
373
|
+
checkpointNumber = validationResult.checkpointNumber;
|
|
374
|
+
}
|
|
375
|
+
// Check that I have any address in current committee before attesting
|
|
376
|
+
// In fisherman mode, we still create attestations for validation even if not in committee
|
|
377
|
+
if (!partOfCommittee && !this.config.fishermanMode) {
|
|
378
|
+
this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
// Provided all of the above checks pass, we can attest to the proposal
|
|
382
|
+
this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`, {
|
|
383
|
+
...proposalInfo,
|
|
384
|
+
inCommittee: partOfCommittee,
|
|
385
|
+
fishermanMode: this.config.fishermanMode || false
|
|
386
|
+
});
|
|
387
|
+
this.metrics.incSuccessfulAttestations(inCommittee.length);
|
|
388
|
+
// Track epoch participation per attester: count each (attester, epoch) pair at most once
|
|
389
|
+
const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
|
|
390
|
+
for (const attester of inCommittee){
|
|
391
|
+
const key = attester.toString();
|
|
392
|
+
const lastEpoch = this.lastAttestedEpochByAttester.get(key);
|
|
393
|
+
if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
|
|
394
|
+
this.lastAttestedEpochByAttester.set(key, proposalEpoch);
|
|
395
|
+
this.metrics.incAttestedEpochCount(attester);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// Determine which validators should attest
|
|
399
|
+
let attestors;
|
|
400
|
+
if (partOfCommittee) {
|
|
401
|
+
attestors = inCommittee;
|
|
402
|
+
} else if (this.config.fishermanMode) {
|
|
403
|
+
// In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
|
|
404
|
+
attestors = this.getValidatorAddresses();
|
|
405
|
+
} else {
|
|
406
|
+
attestors = [];
|
|
407
|
+
}
|
|
408
|
+
// Only create attestations if we have attestors
|
|
409
|
+
if (attestors.length === 0) {
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
if (this.config.fishermanMode) {
|
|
413
|
+
// bail out early and don't save attestations to the pool in fisherman mode
|
|
414
|
+
this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
|
|
415
|
+
...proposalInfo,
|
|
416
|
+
attestors: attestors.map((a)=>a.toString())
|
|
417
|
+
});
|
|
418
|
+
return undefined;
|
|
419
|
+
}
|
|
420
|
+
return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Checks if we should attest to a slot based on equivocation prevention rules.
|
|
424
|
+
* @returns true if we should attest, false if we should skip
|
|
425
|
+
*/ shouldAttestToSlot(slotNumber) {
|
|
426
|
+
// If attestToEquivocatedProposals is true, always allow
|
|
427
|
+
if (this.config.attestToEquivocatedProposals) {
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
// Check if incoming slot is strictly greater than last attested
|
|
431
|
+
if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
|
|
432
|
+
this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
return true;
|
|
436
|
+
}
|
|
437
|
+
async createCheckpointAttestationsFromProposal(proposal, attestors = [], checkpointNumber) {
|
|
438
|
+
// Equivocation check: must happen right before signing to minimize the race window
|
|
439
|
+
if (!this.shouldAttestToSlot(proposal.slotNumber)) {
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
442
|
+
const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
|
|
443
|
+
// Track the proposal we attested to (to prevent equivocation)
|
|
444
|
+
this.lastAttestedProposal = proposal;
|
|
445
|
+
await this.p2pClient.addOwnCheckpointAttestations(attestations);
|
|
446
|
+
return attestations;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Uploads blobs for a checkpoint to the filestore (fire and forget).
|
|
450
|
+
*/ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
|
|
451
|
+
try {
|
|
452
|
+
const lastBlockHeader = (await this.blockSource.getBlockData({
|
|
453
|
+
archive: proposal.archive
|
|
454
|
+
}))?.header;
|
|
455
|
+
if (!lastBlockHeader) {
|
|
456
|
+
this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
|
|
460
|
+
if (blocks.length === 0) {
|
|
461
|
+
this.log.warn(`No blocks found for blob upload`, proposalInfo);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
const blobFields = blocks.flatMap((b)=>b.toBlobFields());
|
|
465
|
+
const blobs = await getBlobsPerL1Block(blobFields);
|
|
466
|
+
await this.blobClient.sendBlobsToFilestore(blobs);
|
|
467
|
+
this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
|
|
468
|
+
...proposalInfo,
|
|
469
|
+
numBlobs: blobs.length
|
|
470
|
+
});
|
|
471
|
+
} catch (err) {
|
|
472
|
+
this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
slashInvalidBlock(proposal) {
|
|
476
|
+
const proposer = proposal.getSender();
|
|
477
|
+
// Skip if signature is invalid (shouldn't happen since we validate earlier)
|
|
478
|
+
if (!proposer) {
|
|
479
|
+
this.log.warn(`Cannot slash proposal with invalid signature`);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
this.proposersOfInvalidBlocks.add(proposer.toString());
|
|
483
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
484
|
+
{
|
|
485
|
+
validator: proposer,
|
|
486
|
+
amount: this.config.slashBroadcastedInvalidBlockPenalty,
|
|
487
|
+
offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
|
|
488
|
+
epochOrSlot: BigInt(proposal.slotNumber)
|
|
489
|
+
}
|
|
490
|
+
]);
|
|
491
|
+
}
|
|
492
|
+
handleInvalidCheckpointProposal(proposal, result, proposalInfo) {
|
|
493
|
+
if (!SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
// The slot is already marked invalid by the all-nodes checkpoint handler that invokes this callback,
|
|
497
|
+
// so we only emit the proposer slash event here.
|
|
498
|
+
if (this.slashInvalidCheckpointProposal(proposal)) {
|
|
499
|
+
this.log.info(`Detected invalid checkpoint proposal offense`, {
|
|
500
|
+
...proposalInfo,
|
|
501
|
+
reason: result.reason,
|
|
502
|
+
amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
|
|
503
|
+
offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL)
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
slashInvalidCheckpointProposal(proposal) {
|
|
508
|
+
const proposer = proposal.getSender();
|
|
509
|
+
if (!proposer) {
|
|
510
|
+
this.log.warn(`Cannot slash checkpoint proposal with invalid signature`, {
|
|
511
|
+
slotNumber: proposal.slotNumber,
|
|
512
|
+
archive: proposal.archive.toString()
|
|
513
|
+
});
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
const offenseType = OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL;
|
|
517
|
+
const offenseKey = `${proposer.toString()}:${offenseType}:${proposal.slotNumber}`;
|
|
518
|
+
if (!this.invalidCheckpointProposalOffenseKeys.addIfAbsent(offenseKey)) {
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
522
|
+
{
|
|
523
|
+
validator: proposer,
|
|
524
|
+
amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
|
|
525
|
+
offenseType,
|
|
526
|
+
epochOrSlot: BigInt(proposal.slotNumber)
|
|
527
|
+
}
|
|
528
|
+
]);
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
531
|
+
markInvalidProposalSlot(slotNumber) {
|
|
532
|
+
this.proposalHandler.markInvalidProposalSlot(slotNumber);
|
|
533
|
+
}
|
|
534
|
+
handleCheckpointAttestation(attestation) {
|
|
535
|
+
const slotNumber = attestation.slotNumber;
|
|
536
|
+
if (!this.proposalHandler.hasInvalidProposals(slotNumber) || this.proposalHandler.hasProposalEquivocation(slotNumber)) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const attester = attestation.getSender();
|
|
540
|
+
if (!attester) {
|
|
541
|
+
this.log.warn(`Cannot slash checkpoint attestation with invalid signature`, {
|
|
542
|
+
slotNumber,
|
|
543
|
+
archive: attestation.archive.toString()
|
|
544
|
+
});
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
this.slashAttestedToInvalidCheckpointProposal(slotNumber, attester);
|
|
548
|
+
}
|
|
549
|
+
slashAttestedToInvalidCheckpointProposal(slotNumber, attester) {
|
|
550
|
+
const offenseKey = `${attester.toString()}:${OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL}:${slotNumber}`;
|
|
551
|
+
if (!this.badAttestationOffenseKeys.addIfAbsent(offenseKey)) {
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
this.log.info(`Detected attestation to invalid checkpoint proposal offense`, {
|
|
555
|
+
attester: attester.toString(),
|
|
556
|
+
slotNumber,
|
|
557
|
+
amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
|
|
558
|
+
offenseType: getOffenseTypeName(OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL)
|
|
559
|
+
});
|
|
560
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
561
|
+
{
|
|
562
|
+
validator: attester,
|
|
563
|
+
amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
|
|
564
|
+
offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
|
|
565
|
+
epochOrSlot: BigInt(slotNumber)
|
|
566
|
+
}
|
|
567
|
+
]);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Handle detection of an oversized block proposal: one whose index within its checkpoint lands at or
|
|
571
|
+
* beyond the consensus per-checkpoint block limit. A single signed proposal at an illegal index is
|
|
572
|
+
* self-contained evidence, so emit an invalid-block-proposal slash event for the proposer, deduped per
|
|
573
|
+
* (proposer, slot) since the p2p layer reports every oversized proposal it stores.
|
|
574
|
+
*/ handleOversizedProposal(info) {
|
|
575
|
+
const { slot, proposer } = info;
|
|
576
|
+
const offenseType = OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL;
|
|
577
|
+
if (!this.oversizedProposalOffenseKeys.addIfAbsent(`${proposer.toString()}:${offenseType}:${slot}`)) {
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
this.log.info(`Detected oversized block proposal offense from ${proposer.toString()} at slot ${slot}`, {
|
|
581
|
+
proposer: proposer.toString(),
|
|
582
|
+
slot,
|
|
583
|
+
amount: this.config.slashBroadcastedInvalidBlockPenalty,
|
|
584
|
+
offenseType: getOffenseTypeName(offenseType)
|
|
585
|
+
});
|
|
586
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
587
|
+
{
|
|
588
|
+
validator: proposer,
|
|
589
|
+
amount: this.config.slashBroadcastedInvalidBlockPenalty,
|
|
590
|
+
offenseType,
|
|
591
|
+
epochOrSlot: BigInt(slot)
|
|
592
|
+
}
|
|
593
|
+
]);
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Handle detection of a duplicate proposal (equivocation).
|
|
597
|
+
* Emits a slash event when a proposer sends multiple proposals for the same position.
|
|
598
|
+
*/ handleDuplicateProposal(info) {
|
|
599
|
+
const { slot, proposer, type } = info;
|
|
600
|
+
this.proposalHandler.markProposalEquivocation(slot);
|
|
601
|
+
this.log.info(`Detected duplicate ${type} proposal offense from ${proposer.toString()} at slot ${slot}`, {
|
|
602
|
+
proposer: proposer.toString(),
|
|
603
|
+
slot,
|
|
604
|
+
type,
|
|
605
|
+
amount: this.config.slashDuplicateProposalPenalty,
|
|
606
|
+
offenseType: getOffenseTypeName(OffenseType.DUPLICATE_PROPOSAL)
|
|
607
|
+
});
|
|
608
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
609
|
+
{
|
|
610
|
+
validator: proposer,
|
|
611
|
+
amount: this.config.slashDuplicateProposalPenalty,
|
|
612
|
+
offenseType: OffenseType.DUPLICATE_PROPOSAL,
|
|
613
|
+
epochOrSlot: BigInt(slot)
|
|
614
|
+
}
|
|
615
|
+
]);
|
|
616
|
+
this.emit(WANT_TO_CLEAR_SLASH_EVENT, [
|
|
617
|
+
{
|
|
618
|
+
offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
|
|
619
|
+
epochOrSlot: BigInt(slot)
|
|
620
|
+
}
|
|
621
|
+
]);
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Handle detection of a duplicate attestation (equivocation).
|
|
625
|
+
* Emits a slash event when an attester signs attestations for different proposals at the same slot.
|
|
626
|
+
*/ handleDuplicateAttestation(info) {
|
|
627
|
+
const { slot, attester } = info;
|
|
628
|
+
this.log.info(`Detected duplicate attestation offense from ${attester.toString()} at slot ${slot}`, {
|
|
629
|
+
attester: attester.toString(),
|
|
630
|
+
slot,
|
|
631
|
+
amount: this.config.slashDuplicateAttestationPenalty,
|
|
632
|
+
offenseType: getOffenseTypeName(OffenseType.DUPLICATE_ATTESTATION)
|
|
633
|
+
});
|
|
634
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
635
|
+
{
|
|
636
|
+
validator: attester,
|
|
637
|
+
amount: this.config.slashDuplicateAttestationPenalty,
|
|
638
|
+
offenseType: OffenseType.DUPLICATE_ATTESTATION,
|
|
639
|
+
epochOrSlot: BigInt(slot)
|
|
640
|
+
}
|
|
641
|
+
]);
|
|
642
|
+
}
|
|
643
|
+
async createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, archive, txs, proposerAddress, options = {}, bucketRef) {
|
|
644
|
+
// Validate that we're not creating a proposal for an older or equal position
|
|
645
|
+
if (this.lastProposedBlock) {
|
|
646
|
+
const lastSlot = this.lastProposedBlock.slotNumber;
|
|
647
|
+
const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
|
|
648
|
+
const newSlot = blockHeader.globalVariables.slotNumber;
|
|
649
|
+
if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
|
|
650
|
+
throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
|
|
654
|
+
const newProposal = await this.validationService.createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, archive, txs, proposerAddress, {
|
|
655
|
+
...options,
|
|
656
|
+
broadcastInvalidBlockProposal: options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal
|
|
657
|
+
}, bucketRef);
|
|
658
|
+
this.lastProposedBlock = newProposal;
|
|
659
|
+
return newProposal;
|
|
660
|
+
}
|
|
661
|
+
async createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options = {}) {
|
|
662
|
+
// Validate that we're not creating a proposal for an older or equal slot
|
|
663
|
+
if (this.lastProposedCheckpoint) {
|
|
664
|
+
const lastSlot = this.lastProposedCheckpoint.slotNumber;
|
|
665
|
+
const newSlot = checkpointHeader.slotNumber;
|
|
666
|
+
if (newSlot <= lastSlot) {
|
|
667
|
+
throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
|
|
671
|
+
const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options);
|
|
672
|
+
this.lastProposedCheckpoint = newProposal;
|
|
673
|
+
// Self-record this slot's outcome on the re-execution tracker. Proposers don't run their
|
|
674
|
+
// own proposals through `handleCheckpointProposal`, so without this call the proposer's
|
|
675
|
+
// sentinel would see no outcome for slots it proposed and would mis-attribute itself as
|
|
676
|
+
// inactive. We pass the locally-computed `archive` (not `newProposal.archive`, which may
|
|
677
|
+
// be intentionally corrupted under test-only flags); from the proposer's local-view
|
|
678
|
+
// perspective the work it just completed is valid by definition.
|
|
679
|
+
this.proposalHandler.recordOwnCheckpointProposalAsValid(checkpointHeader.slotNumber, archive, checkpointNumber);
|
|
680
|
+
return newProposal;
|
|
681
|
+
}
|
|
682
|
+
async broadcastBlockProposal(proposal) {
|
|
683
|
+
await this.p2pClient.broadcastProposal(proposal);
|
|
684
|
+
}
|
|
685
|
+
async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber) {
|
|
686
|
+
return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber);
|
|
687
|
+
}
|
|
688
|
+
async collectOwnAttestations(proposal, checkpointNumber) {
|
|
689
|
+
const slot = proposal.slotNumber;
|
|
690
|
+
const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
|
|
691
|
+
this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
|
|
692
|
+
inCommittee
|
|
693
|
+
});
|
|
694
|
+
const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
|
|
695
|
+
if (!attestations) {
|
|
696
|
+
return [];
|
|
697
|
+
}
|
|
698
|
+
// We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
|
|
699
|
+
// other nodes can see that our validators did attest to this block proposal, and do not slash us
|
|
700
|
+
// due to inactivity for missed attestations.
|
|
701
|
+
void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
|
|
702
|
+
this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
|
|
703
|
+
});
|
|
704
|
+
return attestations;
|
|
705
|
+
}
|
|
706
|
+
async collectAttestations(proposal, required, deadline, checkpointNumber) {
|
|
707
|
+
// Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
|
|
708
|
+
const slot = proposal.slotNumber;
|
|
709
|
+
this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
|
|
710
|
+
if (+deadline < this.dateProvider.now()) {
|
|
711
|
+
this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
|
|
712
|
+
throw new AttestationTimeoutError(0, required, slot);
|
|
713
|
+
}
|
|
714
|
+
await this.collectOwnAttestations(proposal, checkpointNumber);
|
|
715
|
+
const proposalPayloadHash = proposal.getPayloadHash();
|
|
716
|
+
const myAddresses = this.getValidatorAddresses();
|
|
717
|
+
let attestations = [];
|
|
718
|
+
while(true){
|
|
719
|
+
// The pool already filters by proposal payload hash; if any attestation slips through with a
|
|
720
|
+
// mismatched payload hash, drop it defensively. Equivocations are emitted as separate slash
|
|
721
|
+
// events from libp2p_service.
|
|
722
|
+
const collectedAttestations = await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
|
|
723
|
+
// Log new attestations we collected
|
|
724
|
+
const oldSenders = attestations.map((attestation)=>attestation.getSender());
|
|
725
|
+
for (const collected of collectedAttestations){
|
|
726
|
+
const collectedSender = collected.getSender();
|
|
727
|
+
// Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
|
|
728
|
+
if (!collectedSender) {
|
|
729
|
+
this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
if (!myAddresses.some((address)=>address.equals(collectedSender)) && !oldSenders.some((sender)=>sender?.equals(collectedSender))) {
|
|
733
|
+
this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
attestations = collectedAttestations;
|
|
737
|
+
if (attestations.length >= required) {
|
|
738
|
+
this.log.verbose(`Collected all ${required} attestations for slot ${slot}`);
|
|
739
|
+
return attestations;
|
|
740
|
+
}
|
|
741
|
+
if (+deadline < this.dateProvider.now()) {
|
|
742
|
+
this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
|
|
743
|
+
throw new AttestationTimeoutError(attestations.length, required, slot);
|
|
744
|
+
}
|
|
745
|
+
this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
|
|
746
|
+
await sleep(this.config.attestationPollingIntervalMs);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
async handleAuthRequest(peer, msg) {
|
|
750
|
+
const authRequest = AuthRequest.fromBuffer(msg);
|
|
751
|
+
const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
|
|
752
|
+
if (statusMessage === undefined) {
|
|
753
|
+
return Buffer.alloc(0);
|
|
754
|
+
}
|
|
755
|
+
// Find a validator address that is in the set
|
|
756
|
+
const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
|
|
757
|
+
const addressToUse = this.getValidatorAddresses().find((address)=>allRegisteredValidators.find((v)=>v.equals(address)) !== undefined);
|
|
758
|
+
if (addressToUse === undefined) {
|
|
759
|
+
// We don't have a registered address
|
|
760
|
+
return Buffer.alloc(0);
|
|
761
|
+
}
|
|
762
|
+
const payloadToSign = authRequest.getPayloadToSign();
|
|
763
|
+
// AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
|
|
764
|
+
const context = {
|
|
765
|
+
dutyType: DutyType.AUTH_REQUEST
|
|
766
|
+
};
|
|
767
|
+
const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
|
|
768
|
+
const authResponse = new AuthResponse(statusMessage, signature);
|
|
769
|
+
return authResponse.toBuffer();
|
|
770
|
+
}
|
|
771
|
+
}
|