@aztec/validator-client 0.0.1-commit.f504929 → 0.0.1-commit.f5d02921e
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 +41 -2
- package/dest/checkpoint_builder.d.ts +14 -4
- package/dest/checkpoint_builder.d.ts.map +1 -1
- package/dest/checkpoint_builder.js +97 -29
- package/dest/config.d.ts +1 -1
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +22 -6
- package/dest/duties/validation_service.d.ts +1 -1
- package/dest/duties/validation_service.d.ts.map +1 -1
- package/dest/duties/validation_service.js +3 -9
- package/dest/factory.d.ts +7 -4
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +5 -5
- package/dest/index.d.ts +2 -2
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +1 -1
- package/dest/key_store/ha_key_store.js +1 -1
- package/dest/metrics.d.ts +2 -2
- package/dest/metrics.d.ts.map +1 -1
- package/dest/proposal_handler.d.ts +107 -0
- package/dest/proposal_handler.d.ts.map +1 -0
- package/dest/proposal_handler.js +963 -0
- package/dest/validator.d.ts +9 -14
- package/dest/validator.d.ts.map +1 -1
- package/dest/validator.js +58 -218
- package/package.json +19 -19
- package/src/checkpoint_builder.ts +120 -34
- package/src/config.ts +22 -6
- package/src/duties/validation_service.ts +3 -9
- package/src/factory.ts +9 -4
- package/src/index.ts +1 -1
- package/src/key_store/ha_key_store.ts +1 -1
- package/src/metrics.ts +1 -1
- package/src/proposal_handler.ts +1027 -0
- package/src/validator.ts +78 -246
- package/dest/block_proposal_handler.d.ts +0 -63
- package/dest/block_proposal_handler.d.ts.map +0 -1
- package/dest/block_proposal_handler.js +0 -532
- package/src/block_proposal_handler.ts +0 -535
|
@@ -0,0 +1,963 @@
|
|
|
1
|
+
function _ts_add_disposable_resource(env, value, async) {
|
|
2
|
+
if (value !== null && value !== void 0) {
|
|
3
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
4
|
+
var dispose, inner;
|
|
5
|
+
if (async) {
|
|
6
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
7
|
+
dispose = value[Symbol.asyncDispose];
|
|
8
|
+
}
|
|
9
|
+
if (dispose === void 0) {
|
|
10
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
11
|
+
dispose = value[Symbol.dispose];
|
|
12
|
+
if (async) inner = dispose;
|
|
13
|
+
}
|
|
14
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
15
|
+
if (inner) dispose = function() {
|
|
16
|
+
try {
|
|
17
|
+
inner.call(this);
|
|
18
|
+
} catch (e) {
|
|
19
|
+
return Promise.reject(e);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
env.stack.push({
|
|
23
|
+
value: value,
|
|
24
|
+
dispose: dispose,
|
|
25
|
+
async: async
|
|
26
|
+
});
|
|
27
|
+
} else if (async) {
|
|
28
|
+
env.stack.push({
|
|
29
|
+
async: true
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function _ts_dispose_resources(env) {
|
|
35
|
+
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
36
|
+
var e = new Error(message);
|
|
37
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
38
|
+
};
|
|
39
|
+
return (_ts_dispose_resources = function _ts_dispose_resources(env) {
|
|
40
|
+
function fail(e) {
|
|
41
|
+
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
42
|
+
env.hasError = true;
|
|
43
|
+
}
|
|
44
|
+
var r, s = 0;
|
|
45
|
+
function next() {
|
|
46
|
+
while(r = env.stack.pop()){
|
|
47
|
+
try {
|
|
48
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
49
|
+
if (r.dispose) {
|
|
50
|
+
var result = r.dispose.call(r.value);
|
|
51
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
52
|
+
fail(e);
|
|
53
|
+
return next();
|
|
54
|
+
});
|
|
55
|
+
} else s |= 1;
|
|
56
|
+
} catch (e) {
|
|
57
|
+
fail(e);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
61
|
+
if (env.hasError) throw env.error;
|
|
62
|
+
}
|
|
63
|
+
return next();
|
|
64
|
+
})(env);
|
|
65
|
+
}
|
|
66
|
+
import { encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
|
|
67
|
+
import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
|
|
68
|
+
import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
|
|
69
|
+
import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
|
|
70
|
+
import { pick } from '@aztec/foundation/collection';
|
|
71
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
72
|
+
import { TimeoutError } from '@aztec/foundation/error';
|
|
73
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
74
|
+
import { retryUntil } from '@aztec/foundation/retry';
|
|
75
|
+
import { DateProvider, Timer } from '@aztec/foundation/timer';
|
|
76
|
+
import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
|
|
77
|
+
import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
|
|
78
|
+
import { Gas } from '@aztec/stdlib/gas';
|
|
79
|
+
import { accumulateCheckpointOutHashes, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
|
|
80
|
+
import { MerkleTreeId } from '@aztec/stdlib/trees';
|
|
81
|
+
import { ReExFailedTxsError, ReExInitialStateMismatchError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec/stdlib/validators';
|
|
82
|
+
import { getTelemetryClient } from '@aztec/telemetry-client';
|
|
83
|
+
/** Handles block and checkpoint proposals for both validator and non-validator nodes. */ export class ProposalHandler {
|
|
84
|
+
checkpointsBuilder;
|
|
85
|
+
worldState;
|
|
86
|
+
blockSource;
|
|
87
|
+
l1ToL2MessageSource;
|
|
88
|
+
txProvider;
|
|
89
|
+
blockProposalValidator;
|
|
90
|
+
epochCache;
|
|
91
|
+
config;
|
|
92
|
+
blobClient;
|
|
93
|
+
metrics;
|
|
94
|
+
dateProvider;
|
|
95
|
+
log;
|
|
96
|
+
tracer;
|
|
97
|
+
/** Cached last checkpoint validation result to avoid double-validation on validator nodes. */ lastCheckpointValidationResult;
|
|
98
|
+
/** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
|
|
99
|
+
/** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
|
|
100
|
+
constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
|
|
101
|
+
this.checkpointsBuilder = checkpointsBuilder;
|
|
102
|
+
this.worldState = worldState;
|
|
103
|
+
this.blockSource = blockSource;
|
|
104
|
+
this.l1ToL2MessageSource = l1ToL2MessageSource;
|
|
105
|
+
this.txProvider = txProvider;
|
|
106
|
+
this.blockProposalValidator = blockProposalValidator;
|
|
107
|
+
this.epochCache = epochCache;
|
|
108
|
+
this.config = config;
|
|
109
|
+
this.blobClient = blobClient;
|
|
110
|
+
this.metrics = metrics;
|
|
111
|
+
this.dateProvider = dateProvider;
|
|
112
|
+
this.log = log;
|
|
113
|
+
if (config.fishermanMode) {
|
|
114
|
+
this.log = this.log.createChild('[FISHERMAN]');
|
|
115
|
+
}
|
|
116
|
+
this.tracer = telemetry.getTracer('ProposalHandler');
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Registers handlers for block and checkpoint proposals on the p2p client.
|
|
120
|
+
* Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
|
|
121
|
+
* The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
|
|
122
|
+
* @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
|
|
123
|
+
* @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
|
|
124
|
+
*/ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
|
|
125
|
+
this.archiver = archiver;
|
|
126
|
+
this.getOwnValidatorAddresses = getOwnValidatorAddresses;
|
|
127
|
+
// Non-validator handler that processes or re-executes for monitoring but does not attest.
|
|
128
|
+
// Returns boolean indicating whether the proposal was valid.
|
|
129
|
+
const blockHandler = async (proposal, proposalSender)=>{
|
|
130
|
+
try {
|
|
131
|
+
const { slotNumber, blockNumber } = proposal;
|
|
132
|
+
const result = await this.handleBlockProposal(proposal, proposalSender, shouldReexecute);
|
|
133
|
+
if (result.isValid) {
|
|
134
|
+
this.log.info(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} handled`, {
|
|
135
|
+
blockNumber: result.blockNumber,
|
|
136
|
+
slotNumber,
|
|
137
|
+
reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
|
|
138
|
+
totalManaUsed: result.reexecutionResult?.totalManaUsed,
|
|
139
|
+
numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
|
|
140
|
+
reexecuted: shouldReexecute
|
|
141
|
+
});
|
|
142
|
+
return true;
|
|
143
|
+
} else {
|
|
144
|
+
this.log.warn(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`, {
|
|
145
|
+
blockNumber: result.blockNumber,
|
|
146
|
+
slotNumber,
|
|
147
|
+
reason: result.reason
|
|
148
|
+
});
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
this.log.error('Error processing block proposal in non-validator handler', error);
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
p2pClient.registerBlockProposalHandler(blockHandler);
|
|
157
|
+
// All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
|
|
158
|
+
// Runs for all nodes (validators and non-validators). Validators get the cached result in the
|
|
159
|
+
// validator-specific callback (attestToCheckpointProposal) which runs after this one.
|
|
160
|
+
const checkpointHandler = async (proposal, _sender)=>{
|
|
161
|
+
try {
|
|
162
|
+
const proposalInfo = {
|
|
163
|
+
slot: proposal.slotNumber,
|
|
164
|
+
archive: proposal.archive.toString(),
|
|
165
|
+
proposer: proposal.getSender()?.toString()
|
|
166
|
+
};
|
|
167
|
+
// For own proposals, skip validation — the proposer already built and validated the checkpoint
|
|
168
|
+
const proposer = proposal.getSender();
|
|
169
|
+
const ownAddresses = this.getOwnValidatorAddresses?.();
|
|
170
|
+
const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
|
|
171
|
+
if (isOwnProposal) {
|
|
172
|
+
this.log.debug(`Skipping validation for own checkpoint proposal at slot ${proposal.slotNumber}`);
|
|
173
|
+
if (this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
|
|
174
|
+
await this.setProposedCheckpointFromBlocks(proposal);
|
|
175
|
+
}
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
const result = await this.handleCheckpointProposal(proposal, proposalInfo);
|
|
179
|
+
if (result.isValid && this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
|
|
180
|
+
await this.setProposedCheckpointFromValidation(proposal);
|
|
181
|
+
}
|
|
182
|
+
} catch (err) {
|
|
183
|
+
this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, {
|
|
184
|
+
err
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
return undefined;
|
|
188
|
+
};
|
|
189
|
+
p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
|
|
190
|
+
return this;
|
|
191
|
+
}
|
|
192
|
+
async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
|
|
193
|
+
const slotNumber = proposal.slotNumber;
|
|
194
|
+
const proposer = proposal.getSender();
|
|
195
|
+
const config = this.checkpointsBuilder.getConfig();
|
|
196
|
+
// Reject proposals with invalid signatures
|
|
197
|
+
if (!proposer) {
|
|
198
|
+
this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
|
|
199
|
+
return {
|
|
200
|
+
isValid: false,
|
|
201
|
+
reason: 'invalid_proposal'
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const proposalInfo = {
|
|
205
|
+
...proposal.toBlockInfo(),
|
|
206
|
+
proposer: proposer.toString(),
|
|
207
|
+
blockNumber: undefined,
|
|
208
|
+
checkpointNumber: undefined
|
|
209
|
+
};
|
|
210
|
+
this.log.info(`Processing proposal for slot ${slotNumber}`, {
|
|
211
|
+
...proposalInfo,
|
|
212
|
+
txHashes: proposal.txHashes.map((t)=>t.toString())
|
|
213
|
+
});
|
|
214
|
+
// Check that the proposal is from the current proposer, or the next proposer
|
|
215
|
+
// This should have been handled by the p2p layer, but we double check here out of caution
|
|
216
|
+
const validationResult = await this.blockProposalValidator.validate(proposal);
|
|
217
|
+
if (validationResult.result !== 'accept') {
|
|
218
|
+
this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
|
|
219
|
+
return {
|
|
220
|
+
isValid: false,
|
|
221
|
+
reason: 'invalid_proposal'
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
// Ensure the block source is synced before checking for existing blocks,
|
|
225
|
+
// since a proposed checkpoint prune may remove blocks we'd otherwise find.
|
|
226
|
+
// This affects mostly the block_number_already_exists check, since a pending
|
|
227
|
+
// checkpoint prune could remove a block that would conflict with this proposal.
|
|
228
|
+
// When pipelining is enabled, the proposer builds ahead of L1 submission, so the
|
|
229
|
+
// block source won't have synced to the proposed slot yet. Skip the sync wait to
|
|
230
|
+
// avoid eating into the attestation window.
|
|
231
|
+
if (!this.epochCache.isProposerPipeliningEnabled()) {
|
|
232
|
+
const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
|
|
233
|
+
if (!blockSourceSync) {
|
|
234
|
+
this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
|
|
235
|
+
return {
|
|
236
|
+
isValid: false,
|
|
237
|
+
reason: 'block_source_not_synced'
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// Check that the parent proposal is a block we know, otherwise reexecution would fail.
|
|
242
|
+
// If we don't find it immediately, we keep retrying for a while; it may be we still
|
|
243
|
+
// need to process other block proposals to get to it.
|
|
244
|
+
const parentBlock = await this.getParentBlock(proposal);
|
|
245
|
+
if (parentBlock === undefined) {
|
|
246
|
+
this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
|
|
247
|
+
return {
|
|
248
|
+
isValid: false,
|
|
249
|
+
reason: 'parent_block_not_found'
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
// Check that the parent block's slot is not greater than the proposal's slot.
|
|
253
|
+
if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
|
|
254
|
+
this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
|
|
255
|
+
parentBlockSlot: parentBlock.header.getSlot().toString(),
|
|
256
|
+
proposalSlot: slotNumber.toString(),
|
|
257
|
+
...proposalInfo
|
|
258
|
+
});
|
|
259
|
+
return {
|
|
260
|
+
isValid: false,
|
|
261
|
+
reason: 'parent_block_wrong_slot'
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
// Compute the block number based on the parent block
|
|
265
|
+
const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
|
|
266
|
+
proposalInfo.blockNumber = blockNumber;
|
|
267
|
+
// Check that this block number does not exist already
|
|
268
|
+
const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
|
|
269
|
+
if (existingBlock) {
|
|
270
|
+
this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
|
|
271
|
+
return {
|
|
272
|
+
isValid: false,
|
|
273
|
+
blockNumber,
|
|
274
|
+
reason: 'block_number_already_exists'
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
// Collect txs from the proposal. We start doing this as early as possible,
|
|
278
|
+
// and we do it even if we don't plan to re-execute the txs, so that we have them if another node needs them.
|
|
279
|
+
const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
|
|
280
|
+
pinnedPeer: proposalSender,
|
|
281
|
+
deadline: this.getReexecutionDeadline(slotNumber, config)
|
|
282
|
+
});
|
|
283
|
+
// If reexecution is disabled, bail. We were just interested in triggering tx collection.
|
|
284
|
+
if (!shouldReexecute) {
|
|
285
|
+
this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
|
|
286
|
+
return {
|
|
287
|
+
isValid: true,
|
|
288
|
+
blockNumber
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
// Compute the checkpoint number for this block and validate checkpoint consistency
|
|
292
|
+
const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
|
|
293
|
+
if (checkpointResult.reason) {
|
|
294
|
+
return {
|
|
295
|
+
isValid: false,
|
|
296
|
+
blockNumber,
|
|
297
|
+
reason: checkpointResult.reason
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
const checkpointNumber = checkpointResult.checkpointNumber;
|
|
301
|
+
proposalInfo.checkpointNumber = checkpointNumber;
|
|
302
|
+
// Check that I have the same set of l1ToL2Messages as the proposal
|
|
303
|
+
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
|
|
304
|
+
const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
|
|
305
|
+
const proposalInHash = proposal.inHash;
|
|
306
|
+
if (!computedInHash.equals(proposalInHash)) {
|
|
307
|
+
this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
|
|
308
|
+
proposalInHash: proposalInHash.toString(),
|
|
309
|
+
computedInHash: computedInHash.toString(),
|
|
310
|
+
...proposalInfo
|
|
311
|
+
});
|
|
312
|
+
return {
|
|
313
|
+
isValid: false,
|
|
314
|
+
blockNumber,
|
|
315
|
+
reason: 'in_hash_mismatch'
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
// Check that all of the transactions in the proposal are available
|
|
319
|
+
if (missingTxs.length > 0) {
|
|
320
|
+
this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, {
|
|
321
|
+
...proposalInfo,
|
|
322
|
+
missingTxs
|
|
323
|
+
});
|
|
324
|
+
return {
|
|
325
|
+
isValid: false,
|
|
326
|
+
blockNumber,
|
|
327
|
+
reason: 'txs_not_available'
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
// Collect the out hashes of all the checkpoints before this one in the same epoch
|
|
331
|
+
const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
|
|
332
|
+
const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
|
|
333
|
+
// Try re-executing the transactions in the proposal if needed
|
|
334
|
+
let reexecutionResult;
|
|
335
|
+
try {
|
|
336
|
+
this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
|
|
337
|
+
reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
|
|
340
|
+
const reason = this.getReexecuteFailureReason(error);
|
|
341
|
+
return {
|
|
342
|
+
isValid: false,
|
|
343
|
+
blockNumber,
|
|
344
|
+
reason,
|
|
345
|
+
reexecutionResult
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
// If we succeeded, push this block into the archiver (unless disabled)
|
|
349
|
+
if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
|
|
350
|
+
await this.blockSource.addBlock(reexecutionResult.block);
|
|
351
|
+
}
|
|
352
|
+
this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
|
|
353
|
+
...proposalInfo,
|
|
354
|
+
...pick(reexecutionResult, 'reexecutionTimeMs', 'totalManaUsed')
|
|
355
|
+
});
|
|
356
|
+
return {
|
|
357
|
+
isValid: true,
|
|
358
|
+
blockNumber,
|
|
359
|
+
reexecutionResult
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
async getParentBlock(proposal) {
|
|
363
|
+
const parentArchive = proposal.blockHeader.lastArchive.root;
|
|
364
|
+
const slot = proposal.slotNumber;
|
|
365
|
+
const config = this.checkpointsBuilder.getConfig();
|
|
366
|
+
const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
|
|
367
|
+
if (parentArchive.equals(genesisArchiveRoot)) {
|
|
368
|
+
return 'genesis';
|
|
369
|
+
}
|
|
370
|
+
const deadline = this.getReexecutionDeadline(slot, config);
|
|
371
|
+
const currentTime = this.dateProvider.now();
|
|
372
|
+
const timeoutDurationMs = deadline.getTime() - currentTime;
|
|
373
|
+
try {
|
|
374
|
+
return await this.blockSource.getBlockDataByArchive(parentArchive) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockDataByArchive(parentArchive)), 'force archiver sync', timeoutDurationMs / 1000, 0.5));
|
|
375
|
+
} catch (err) {
|
|
376
|
+
if (err instanceof TimeoutError) {
|
|
377
|
+
this.log.debug(`Timed out getting parent block by archive root`, {
|
|
378
|
+
parentArchive
|
|
379
|
+
});
|
|
380
|
+
} else {
|
|
381
|
+
this.log.error('Error getting parent block by archive root', err, {
|
|
382
|
+
parentArchive
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
return undefined;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
computeCheckpointNumber(proposal, parentBlock, proposalInfo) {
|
|
389
|
+
if (parentBlock === 'genesis') {
|
|
390
|
+
// First block is in checkpoint 1
|
|
391
|
+
if (proposal.indexWithinCheckpoint !== 0) {
|
|
392
|
+
this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
|
|
393
|
+
return {
|
|
394
|
+
reason: 'invalid_proposal'
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
checkpointNumber: CheckpointNumber.INITIAL
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
if (proposal.indexWithinCheckpoint === 0) {
|
|
402
|
+
// If this is the first block in a new checkpoint, increment the checkpoint number
|
|
403
|
+
if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
|
|
404
|
+
this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
|
|
405
|
+
return {
|
|
406
|
+
reason: 'invalid_proposal'
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
return {
|
|
410
|
+
checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1)
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
// Otherwise it should follow the previous block in the same checkpoint
|
|
414
|
+
if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
|
|
415
|
+
this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
|
|
416
|
+
return {
|
|
417
|
+
reason: 'invalid_proposal'
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
|
|
421
|
+
this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
|
|
422
|
+
return {
|
|
423
|
+
reason: 'invalid_proposal'
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
// For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
|
|
427
|
+
const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
|
|
428
|
+
if (validationResult) {
|
|
429
|
+
return validationResult;
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
checkpointNumber: parentBlock.checkpointNumber
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Validates that a non-first block in a checkpoint has consistent global variables with its parent.
|
|
437
|
+
* For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
|
|
438
|
+
* @returns A failure result if validation fails, undefined if validation passes
|
|
439
|
+
*/ validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo) {
|
|
440
|
+
const proposalGlobals = proposal.blockHeader.globalVariables;
|
|
441
|
+
const parentGlobals = parentBlock.header.globalVariables;
|
|
442
|
+
// All global variables except blockNumber should match the parent
|
|
443
|
+
// blockNumber naturally increments between blocks
|
|
444
|
+
if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
|
|
445
|
+
this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
|
|
446
|
+
...proposalInfo,
|
|
447
|
+
proposalChainId: proposalGlobals.chainId.toString(),
|
|
448
|
+
parentChainId: parentGlobals.chainId.toString()
|
|
449
|
+
});
|
|
450
|
+
return {
|
|
451
|
+
reason: 'global_variables_mismatch'
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
if (!proposalGlobals.version.equals(parentGlobals.version)) {
|
|
455
|
+
this.log.warn(`Non-first block in checkpoint has mismatched version`, {
|
|
456
|
+
...proposalInfo,
|
|
457
|
+
proposalVersion: proposalGlobals.version.toString(),
|
|
458
|
+
parentVersion: parentGlobals.version.toString()
|
|
459
|
+
});
|
|
460
|
+
return {
|
|
461
|
+
reason: 'global_variables_mismatch'
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
|
|
465
|
+
this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
|
|
466
|
+
...proposalInfo,
|
|
467
|
+
proposalSlotNumber: proposalGlobals.slotNumber,
|
|
468
|
+
parentSlotNumber: parentGlobals.slotNumber
|
|
469
|
+
});
|
|
470
|
+
return {
|
|
471
|
+
reason: 'global_variables_mismatch'
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
|
|
475
|
+
this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
|
|
476
|
+
...proposalInfo,
|
|
477
|
+
proposalTimestamp: proposalGlobals.timestamp.toString(),
|
|
478
|
+
parentTimestamp: parentGlobals.timestamp.toString()
|
|
479
|
+
});
|
|
480
|
+
return {
|
|
481
|
+
reason: 'global_variables_mismatch'
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
|
|
485
|
+
this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
|
|
486
|
+
...proposalInfo,
|
|
487
|
+
proposalCoinbase: proposalGlobals.coinbase.toString(),
|
|
488
|
+
parentCoinbase: parentGlobals.coinbase.toString()
|
|
489
|
+
});
|
|
490
|
+
return {
|
|
491
|
+
reason: 'global_variables_mismatch'
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
|
|
495
|
+
this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
|
|
496
|
+
...proposalInfo,
|
|
497
|
+
proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
|
|
498
|
+
parentFeeRecipient: parentGlobals.feeRecipient.toString()
|
|
499
|
+
});
|
|
500
|
+
return {
|
|
501
|
+
reason: 'global_variables_mismatch'
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
|
|
505
|
+
this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
|
|
506
|
+
...proposalInfo,
|
|
507
|
+
proposalGasFees: proposalGlobals.gasFees.toInspect(),
|
|
508
|
+
parentGasFees: parentGlobals.gasFees.toInspect()
|
|
509
|
+
});
|
|
510
|
+
return {
|
|
511
|
+
reason: 'global_variables_mismatch'
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
getReexecutionDeadline(slot, config) {
|
|
517
|
+
const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
|
|
518
|
+
return new Date(nextSlotTimestampSeconds * 1000);
|
|
519
|
+
}
|
|
520
|
+
/** Waits for the block source to sync L1 data up to at least the slot before the given one. */ async waitForBlockSourceSync(slot) {
|
|
521
|
+
const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
|
|
522
|
+
const timeoutMs = deadline.getTime() - this.dateProvider.now();
|
|
523
|
+
if (slot === 0) {
|
|
524
|
+
return true;
|
|
525
|
+
}
|
|
526
|
+
// Make a quick check before triggering an archiver sync
|
|
527
|
+
const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
|
|
528
|
+
if (syncedSlot !== undefined && syncedSlot + 1 >= slot) {
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
531
|
+
try {
|
|
532
|
+
// Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
|
|
533
|
+
return await retryUntil(async ()=>{
|
|
534
|
+
await this.blockSource.syncImmediate();
|
|
535
|
+
const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
|
|
536
|
+
return syncedSlot !== undefined && syncedSlot + 1 >= slot;
|
|
537
|
+
}, 'wait for block source sync', timeoutMs / 1000, 0.5);
|
|
538
|
+
} catch (err) {
|
|
539
|
+
if (err instanceof TimeoutError) {
|
|
540
|
+
this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
|
|
541
|
+
return false;
|
|
542
|
+
} else {
|
|
543
|
+
throw err;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
getReexecuteFailureReason(err) {
|
|
548
|
+
if (err instanceof TransactionsNotAvailableError) {
|
|
549
|
+
return 'txs_not_available';
|
|
550
|
+
} else if (err instanceof ReExInitialStateMismatchError) {
|
|
551
|
+
return 'initial_state_mismatch';
|
|
552
|
+
} else if (err instanceof ReExStateMismatchError) {
|
|
553
|
+
return 'state_mismatch';
|
|
554
|
+
} else if (err instanceof ReExFailedTxsError) {
|
|
555
|
+
return 'failed_txs';
|
|
556
|
+
} else if (err instanceof ReExTimeoutError) {
|
|
557
|
+
return 'timeout';
|
|
558
|
+
} else {
|
|
559
|
+
return 'unknown_error';
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
async reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes) {
|
|
563
|
+
const env = {
|
|
564
|
+
stack: [],
|
|
565
|
+
error: void 0,
|
|
566
|
+
hasError: false
|
|
567
|
+
};
|
|
568
|
+
try {
|
|
569
|
+
const { blockHeader, txHashes } = proposal;
|
|
570
|
+
// If we do not have all of the transactions, then we should fail
|
|
571
|
+
if (txs.length !== txHashes.length) {
|
|
572
|
+
const foundTxHashes = txs.map((tx)=>tx.getTxHash());
|
|
573
|
+
const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
|
|
574
|
+
throw new TransactionsNotAvailableError(missingTxHashes);
|
|
575
|
+
}
|
|
576
|
+
const timer = new Timer();
|
|
577
|
+
const slot = proposal.slotNumber;
|
|
578
|
+
const config = this.checkpointsBuilder.getConfig();
|
|
579
|
+
// Get prior blocks in this checkpoint (same slot before current block)
|
|
580
|
+
const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
|
|
581
|
+
const priorBlocks = allBlocksInSlot.filter((b)=>b.number < blockNumber && b.header.getSlot() === slot);
|
|
582
|
+
// Fork before the block to be built
|
|
583
|
+
const parentBlockNumber = BlockNumber(blockNumber - 1);
|
|
584
|
+
await this.worldState.syncImmediate(parentBlockNumber);
|
|
585
|
+
const fork = _ts_add_disposable_resource(env, await this.worldState.fork(parentBlockNumber), true);
|
|
586
|
+
// Verify the fork's archive root matches the proposal's expected last archive.
|
|
587
|
+
// If they don't match, our world state synced to a different chain and reexecution would fail.
|
|
588
|
+
const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
|
|
589
|
+
if (!forkArchiveRoot.equals(proposal.blockHeader.lastArchive.root)) {
|
|
590
|
+
throw new ReExInitialStateMismatchError(proposal.blockHeader.lastArchive.root, forkArchiveRoot);
|
|
591
|
+
}
|
|
592
|
+
// Build checkpoint constants from proposal (excludes blockNumber which is per-block)
|
|
593
|
+
const constants = {
|
|
594
|
+
chainId: new Fr(config.l1ChainId),
|
|
595
|
+
version: new Fr(config.rollupVersion),
|
|
596
|
+
slotNumber: slot,
|
|
597
|
+
timestamp: blockHeader.globalVariables.timestamp,
|
|
598
|
+
coinbase: blockHeader.globalVariables.coinbase,
|
|
599
|
+
feeRecipient: blockHeader.globalVariables.feeRecipient,
|
|
600
|
+
gasFees: blockHeader.globalVariables.gasFees
|
|
601
|
+
};
|
|
602
|
+
// Create checkpoint builder with prior blocks
|
|
603
|
+
const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, 0n, l1ToL2Messages, previousCheckpointOutHashes, fork, priorBlocks, this.log.getBindings());
|
|
604
|
+
// Build the new block
|
|
605
|
+
const deadline = this.getReexecutionDeadline(slot, config);
|
|
606
|
+
const maxBlockGas = this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity) : undefined;
|
|
607
|
+
const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
|
|
608
|
+
isBuildingProposal: false,
|
|
609
|
+
minValidTxs: 0,
|
|
610
|
+
deadline,
|
|
611
|
+
expectedEndState: blockHeader.state,
|
|
612
|
+
maxTransactions: this.config.validateMaxTxsPerBlock,
|
|
613
|
+
maxBlockGas
|
|
614
|
+
});
|
|
615
|
+
const { block, failedTxs } = result;
|
|
616
|
+
const numFailedTxs = failedTxs.length;
|
|
617
|
+
this.log.verbose(`Block proposal ${blockNumber} at slot ${slot} transaction re-execution complete`, {
|
|
618
|
+
numFailedTxs,
|
|
619
|
+
numProposalTxs: txHashes.length,
|
|
620
|
+
numProcessedTxs: block.body.txEffects.length,
|
|
621
|
+
blockNumber,
|
|
622
|
+
slot
|
|
623
|
+
});
|
|
624
|
+
if (numFailedTxs > 0) {
|
|
625
|
+
this.metrics?.recordFailedReexecution(proposal);
|
|
626
|
+
throw new ReExFailedTxsError(numFailedTxs);
|
|
627
|
+
}
|
|
628
|
+
if (block.body.txEffects.length !== txHashes.length) {
|
|
629
|
+
this.metrics?.recordFailedReexecution(proposal);
|
|
630
|
+
throw new ReExTimeoutError();
|
|
631
|
+
}
|
|
632
|
+
// Throw a ReExStateMismatchError error if state updates do not match
|
|
633
|
+
// Compare the full block structure (archive and header) from the built block with the proposal
|
|
634
|
+
const archiveMatches = proposal.archive.equals(block.archive.root);
|
|
635
|
+
const headerMatches = proposal.blockHeader.equals(block.header);
|
|
636
|
+
if (!archiveMatches || !headerMatches) {
|
|
637
|
+
this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
|
|
638
|
+
expectedArchive: block.archive.root.toString(),
|
|
639
|
+
actualArchive: proposal.archive.toString(),
|
|
640
|
+
expectedHeader: block.header.toInspect(),
|
|
641
|
+
actualHeader: proposal.blockHeader.toInspect()
|
|
642
|
+
});
|
|
643
|
+
this.metrics?.recordFailedReexecution(proposal);
|
|
644
|
+
throw new ReExStateMismatchError(proposal.archive, block.archive.root);
|
|
645
|
+
}
|
|
646
|
+
const reexecutionTimeMs = timer.ms();
|
|
647
|
+
const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
|
|
648
|
+
this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
|
|
649
|
+
return {
|
|
650
|
+
block,
|
|
651
|
+
failedTxs,
|
|
652
|
+
reexecutionTimeMs,
|
|
653
|
+
totalManaUsed
|
|
654
|
+
};
|
|
655
|
+
} catch (e) {
|
|
656
|
+
env.error = e;
|
|
657
|
+
env.hasError = true;
|
|
658
|
+
} finally{
|
|
659
|
+
const result = _ts_dispose_resources(env);
|
|
660
|
+
if (result) await result;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
|
|
665
|
+
* Returns a cached result if the same proposal (archive + slot) was already validated.
|
|
666
|
+
* Used by both the all-nodes callback (via register) and the validator client (via delegation).
|
|
667
|
+
*/ async handleCheckpointProposal(proposal, proposalInfo) {
|
|
668
|
+
const slot = proposal.slotNumber;
|
|
669
|
+
// Check cache: same archive+slot means we already validated this proposal
|
|
670
|
+
if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.archive.equals(proposal.archive) && this.lastCheckpointValidationResult.slotNumber === slot) {
|
|
671
|
+
this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
|
|
672
|
+
return this.lastCheckpointValidationResult.result;
|
|
673
|
+
}
|
|
674
|
+
const proposer = proposal.getSender();
|
|
675
|
+
if (!proposer) {
|
|
676
|
+
this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
|
|
677
|
+
const result = {
|
|
678
|
+
isValid: false,
|
|
679
|
+
reason: 'invalid_signature'
|
|
680
|
+
};
|
|
681
|
+
this.lastCheckpointValidationResult = {
|
|
682
|
+
archive: proposal.archive,
|
|
683
|
+
slotNumber: slot,
|
|
684
|
+
result
|
|
685
|
+
};
|
|
686
|
+
return result;
|
|
687
|
+
}
|
|
688
|
+
if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
|
|
689
|
+
this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
|
|
690
|
+
const result = {
|
|
691
|
+
isValid: false,
|
|
692
|
+
reason: 'invalid_fee_asset_price_modifier'
|
|
693
|
+
};
|
|
694
|
+
this.lastCheckpointValidationResult = {
|
|
695
|
+
archive: proposal.archive,
|
|
696
|
+
slotNumber: slot,
|
|
697
|
+
result
|
|
698
|
+
};
|
|
699
|
+
return result;
|
|
700
|
+
}
|
|
701
|
+
const result = await this.validateCheckpointProposal(proposal, proposalInfo);
|
|
702
|
+
this.lastCheckpointValidationResult = {
|
|
703
|
+
archive: proposal.archive,
|
|
704
|
+
slotNumber: slot,
|
|
705
|
+
result
|
|
706
|
+
};
|
|
707
|
+
// Upload blobs to filestore if validation passed (fire and forget)
|
|
708
|
+
if (result.isValid) {
|
|
709
|
+
this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
|
|
710
|
+
}
|
|
711
|
+
return result;
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
|
|
715
|
+
* @returns Validation result with isValid flag and reason if invalid.
|
|
716
|
+
*/ async validateCheckpointProposal(proposal, proposalInfo) {
|
|
717
|
+
const env = {
|
|
718
|
+
stack: [],
|
|
719
|
+
error: void 0,
|
|
720
|
+
hasError: false
|
|
721
|
+
};
|
|
722
|
+
try {
|
|
723
|
+
const slot = proposal.slotNumber;
|
|
724
|
+
// Timeout block syncing at the start of the next slot
|
|
725
|
+
const config = this.checkpointsBuilder.getConfig();
|
|
726
|
+
const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
|
|
727
|
+
const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
|
|
728
|
+
// Wait for last block to sync by archive
|
|
729
|
+
let lastBlockHeader;
|
|
730
|
+
try {
|
|
731
|
+
lastBlockHeader = await retryUntil(async ()=>{
|
|
732
|
+
await this.blockSource.syncImmediate();
|
|
733
|
+
return this.blockSource.getBlockHeaderByArchive(proposal.archive);
|
|
734
|
+
}, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
|
|
735
|
+
} catch (err) {
|
|
736
|
+
if (err instanceof TimeoutError) {
|
|
737
|
+
this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
|
|
738
|
+
return {
|
|
739
|
+
isValid: false,
|
|
740
|
+
reason: 'last_block_not_found'
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
|
|
744
|
+
return {
|
|
745
|
+
isValid: false,
|
|
746
|
+
reason: 'block_fetch_error'
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
if (!lastBlockHeader) {
|
|
750
|
+
this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
|
|
751
|
+
return {
|
|
752
|
+
isValid: false,
|
|
753
|
+
reason: 'last_block_not_found'
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
// Get all full blocks for the slot and checkpoint
|
|
757
|
+
const blocks = await this.blockSource.getBlocksForSlot(slot);
|
|
758
|
+
if (blocks.length === 0) {
|
|
759
|
+
this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
|
|
760
|
+
return {
|
|
761
|
+
isValid: false,
|
|
762
|
+
reason: 'no_blocks_for_slot'
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
// Ensure the last block for this slot matches the archive in the checkpoint proposal
|
|
766
|
+
if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
|
|
767
|
+
this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
|
|
768
|
+
return {
|
|
769
|
+
isValid: false,
|
|
770
|
+
reason: 'last_block_archive_mismatch'
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
|
|
774
|
+
...proposalInfo,
|
|
775
|
+
blockNumbers: blocks.map((b)=>b.number)
|
|
776
|
+
});
|
|
777
|
+
// Get checkpoint constants from first block
|
|
778
|
+
const firstBlock = blocks[0];
|
|
779
|
+
const constants = this.extractCheckpointConstants(firstBlock);
|
|
780
|
+
const checkpointNumber = firstBlock.checkpointNumber;
|
|
781
|
+
// Get L1-to-L2 messages for this checkpoint
|
|
782
|
+
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
|
|
783
|
+
// Collect the out hashes of all the checkpoints before this one in the same epoch
|
|
784
|
+
const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
|
|
785
|
+
const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
|
|
786
|
+
// Fork world state at the block before the first block
|
|
787
|
+
const parentBlockNumber = BlockNumber(firstBlock.number - 1);
|
|
788
|
+
const fork = _ts_add_disposable_resource(env, await this.checkpointsBuilder.getFork(parentBlockNumber), true);
|
|
789
|
+
// Create checkpoint builder with all existing blocks
|
|
790
|
+
const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
|
|
791
|
+
// Complete the checkpoint to get computed values
|
|
792
|
+
const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
|
|
793
|
+
// Compare checkpoint header with proposal
|
|
794
|
+
if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
|
|
795
|
+
this.log.warn(`Checkpoint header mismatch`, {
|
|
796
|
+
...proposalInfo,
|
|
797
|
+
computed: computedCheckpoint.header.toInspect(),
|
|
798
|
+
proposal: proposal.checkpointHeader.toInspect()
|
|
799
|
+
});
|
|
800
|
+
return {
|
|
801
|
+
isValid: false,
|
|
802
|
+
reason: 'checkpoint_header_mismatch'
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
// Compare archive root with proposal
|
|
806
|
+
if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
|
|
807
|
+
this.log.warn(`Archive root mismatch`, {
|
|
808
|
+
...proposalInfo,
|
|
809
|
+
computed: computedCheckpoint.archive.root.toString(),
|
|
810
|
+
proposal: proposal.archive.toString()
|
|
811
|
+
});
|
|
812
|
+
return {
|
|
813
|
+
isValid: false,
|
|
814
|
+
reason: 'archive_mismatch'
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
// Check that the accumulated epoch out hash matches the value in the proposal.
|
|
818
|
+
// The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
|
|
819
|
+
const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
|
|
820
|
+
const computedEpochOutHash = accumulateCheckpointOutHashes([
|
|
821
|
+
...previousCheckpointOutHashes,
|
|
822
|
+
checkpointOutHash
|
|
823
|
+
]);
|
|
824
|
+
const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
|
|
825
|
+
if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
|
|
826
|
+
this.log.warn(`Epoch out hash mismatch`, {
|
|
827
|
+
proposalEpochOutHash: proposalEpochOutHash.toString(),
|
|
828
|
+
computedEpochOutHash: computedEpochOutHash.toString(),
|
|
829
|
+
checkpointOutHash: checkpointOutHash.toString(),
|
|
830
|
+
previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
|
|
831
|
+
...proposalInfo
|
|
832
|
+
});
|
|
833
|
+
return {
|
|
834
|
+
isValid: false,
|
|
835
|
+
reason: 'out_hash_mismatch'
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
// Final round of validations on the checkpoint, just in case.
|
|
839
|
+
try {
|
|
840
|
+
validateCheckpoint(computedCheckpoint, {
|
|
841
|
+
rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
|
|
842
|
+
maxDABlockGas: this.config.validateMaxDABlockGas,
|
|
843
|
+
maxL2BlockGas: this.config.validateMaxL2BlockGas,
|
|
844
|
+
maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
|
|
845
|
+
maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint
|
|
846
|
+
});
|
|
847
|
+
} catch (err) {
|
|
848
|
+
this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
|
|
849
|
+
return {
|
|
850
|
+
isValid: false,
|
|
851
|
+
reason: 'checkpoint_validation_failed'
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
|
|
855
|
+
return {
|
|
856
|
+
isValid: true
|
|
857
|
+
};
|
|
858
|
+
} catch (e) {
|
|
859
|
+
env.error = e;
|
|
860
|
+
env.hasError = true;
|
|
861
|
+
} finally{
|
|
862
|
+
const result = _ts_dispose_resources(env);
|
|
863
|
+
if (result) await result;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/** Extracts checkpoint global variables from a block. */ extractCheckpointConstants(block) {
|
|
867
|
+
const gv = block.header.globalVariables;
|
|
868
|
+
return {
|
|
869
|
+
chainId: gv.chainId,
|
|
870
|
+
version: gv.version,
|
|
871
|
+
slotNumber: gv.slotNumber,
|
|
872
|
+
timestamp: gv.timestamp,
|
|
873
|
+
coinbase: gv.coinbase,
|
|
874
|
+
feeRecipient: gv.feeRecipient,
|
|
875
|
+
gasFees: gv.gasFees
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
/** Triggers blob upload for a checkpoint if the blob client can upload (fire and forget). */ tryUploadBlobsForCheckpoint(proposal, proposalInfo) {
|
|
879
|
+
if (this.blobClient.canUpload()) {
|
|
880
|
+
void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
/** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
|
|
884
|
+
try {
|
|
885
|
+
const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
|
|
886
|
+
if (!lastBlockHeader) {
|
|
887
|
+
this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
|
|
891
|
+
if (blocks.length === 0) {
|
|
892
|
+
this.log.warn(`No blocks found for blob upload`, proposalInfo);
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
const blockBlobData = blocks.map((b)=>b.toBlockBlobData());
|
|
896
|
+
const blobFields = encodeCheckpointBlobDataFromBlocks(blockBlobData);
|
|
897
|
+
const blobs = await getBlobsPerL1Block(blobFields);
|
|
898
|
+
await this.blobClient.sendBlobsToFilestore(blobs);
|
|
899
|
+
this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
|
|
900
|
+
...proposalInfo,
|
|
901
|
+
numBlobs: blobs.length
|
|
902
|
+
});
|
|
903
|
+
} catch (err) {
|
|
904
|
+
this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Derives proposed checkpoint data from validated blocks and sets it on the archiver.
|
|
909
|
+
* Used after successful validation of a foreign proposal.
|
|
910
|
+
* Does not retry since we already waited for the block during validation.
|
|
911
|
+
*/ async setProposedCheckpointFromValidation(proposal) {
|
|
912
|
+
if (!this.archiver) {
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
const blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
|
|
916
|
+
if (!blockData) {
|
|
917
|
+
this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
|
|
918
|
+
archive: proposal.archive.toString()
|
|
919
|
+
});
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
await this.archiver.setProposedCheckpoint({
|
|
923
|
+
header: proposal.checkpointHeader,
|
|
924
|
+
checkpointNumber: blockData.checkpointNumber,
|
|
925
|
+
startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
|
|
926
|
+
blockCount: blockData.indexWithinCheckpoint + 1,
|
|
927
|
+
totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
|
|
928
|
+
feeAssetPriceModifier: proposal.feeAssetPriceModifier
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Sets proposed checkpoint from blocks for own proposals (skips full validation).
|
|
933
|
+
* Retries fetching block data since the checkpoint proposal often arrives before the last block
|
|
934
|
+
* finishes re-execution.
|
|
935
|
+
*/ async setProposedCheckpointFromBlocks(proposal) {
|
|
936
|
+
if (!this.archiver) {
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
let blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
|
|
940
|
+
if (!blockData) {
|
|
941
|
+
// The checkpoint proposal often arrives before the last block finishes re-execution.
|
|
942
|
+
// Retry until we find the data or give up at the end of the slot.
|
|
943
|
+
const nextSlot = this.epochCache.getSlotNow() + 1;
|
|
944
|
+
const timeOfNextSlot = getTimestampForSlot(SlotNumber(nextSlot), await this.archiver.getL1Constants());
|
|
945
|
+
const timeoutSeconds = Math.max(1, Number(timeOfNextSlot) - Math.floor(this.dateProvider.now() / 1000));
|
|
946
|
+
blockData = await retryUntil(()=>this.blockSource.getBlockDataByArchive(proposal.archive), 'block data for own checkpoint proposal', timeoutSeconds, 0.25).catch(()=>undefined);
|
|
947
|
+
}
|
|
948
|
+
if (blockData) {
|
|
949
|
+
await this.archiver.setProposedCheckpoint({
|
|
950
|
+
header: proposal.checkpointHeader,
|
|
951
|
+
checkpointNumber: blockData.checkpointNumber,
|
|
952
|
+
startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
|
|
953
|
+
blockCount: blockData.indexWithinCheckpoint + 1,
|
|
954
|
+
totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
|
|
955
|
+
feeAssetPriceModifier: proposal.feeAssetPriceModifier
|
|
956
|
+
});
|
|
957
|
+
} else {
|
|
958
|
+
this.log.debug(`Block data not found for own checkpoint proposal archive, cannot set proposed checkpoint`, {
|
|
959
|
+
archive: proposal.archive.toString()
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|