@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.1142ef1
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 +256 -0
- package/dest/block_proposal_handler.d.ts +63 -0
- package/dest/block_proposal_handler.d.ts.map +1 -0
- package/dest/block_proposal_handler.js +551 -0
- package/dest/checkpoint_builder.d.ts +70 -0
- package/dest/checkpoint_builder.d.ts.map +1 -0
- package/dest/checkpoint_builder.js +155 -0
- package/dest/config.d.ts +3 -14
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +46 -7
- package/dest/duties/validation_service.d.ts +36 -12
- package/dest/duties/validation_service.d.ts.map +1 -1
- package/dest/duties/validation_service.js +69 -16
- package/dest/factory.d.ts +27 -5
- package/dest/factory.d.ts.map +1 -1
- package/dest/factory.js +13 -6
- package/dest/index.d.ts +6 -2
- package/dest/index.d.ts.map +1 -1
- package/dest/index.js +5 -1
- package/dest/key_store/index.d.ts +3 -1
- package/dest/key_store/index.d.ts.map +1 -1
- package/dest/key_store/index.js +2 -0
- package/dest/key_store/interface.d.ts +55 -6
- package/dest/key_store/interface.d.ts.map +1 -1
- package/dest/key_store/interface.js +3 -3
- package/dest/key_store/local_key_store.d.ts +41 -11
- package/dest/key_store/local_key_store.d.ts.map +1 -1
- package/dest/key_store/local_key_store.js +64 -17
- package/dest/key_store/node_keystore_adapter.d.ts +138 -0
- package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
- package/dest/key_store/node_keystore_adapter.js +316 -0
- package/dest/key_store/web3signer_key_store.d.ts +61 -0
- package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
- package/dest/key_store/web3signer_key_store.js +152 -0
- package/dest/metrics.d.ts +12 -5
- package/dest/metrics.d.ts.map +1 -1
- package/dest/metrics.js +36 -24
- package/dest/tx_validator/index.d.ts +3 -0
- package/dest/tx_validator/index.d.ts.map +1 -0
- package/dest/tx_validator/index.js +2 -0
- package/dest/tx_validator/nullifier_cache.d.ts +14 -0
- package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
- package/dest/tx_validator/nullifier_cache.js +24 -0
- package/dest/tx_validator/tx_validator_factory.d.ts +18 -0
- package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
- package/dest/tx_validator/tx_validator_factory.js +53 -0
- package/dest/validator.d.ts +73 -58
- package/dest/validator.d.ts.map +1 -1
- package/dest/validator.js +557 -166
- package/package.json +33 -21
- package/src/block_proposal_handler.ts +556 -0
- package/src/checkpoint_builder.ts +267 -0
- package/src/config.ts +58 -22
- package/src/duties/validation_service.ts +124 -18
- package/src/factory.ts +64 -11
- package/src/index.ts +5 -1
- package/src/key_store/index.ts +2 -0
- package/src/key_store/interface.ts +61 -5
- package/src/key_store/local_key_store.ts +68 -18
- package/src/key_store/node_keystore_adapter.ts +375 -0
- package/src/key_store/web3signer_key_store.ts +192 -0
- package/src/metrics.ts +48 -24
- package/src/tx_validator/index.ts +2 -0
- package/src/tx_validator/nullifier_cache.ts +30 -0
- package/src/tx_validator/tx_validator_factory.ts +133 -0
- package/src/validator.ts +749 -218
- package/dest/errors/index.d.ts +0 -2
- package/dest/errors/index.d.ts.map +0 -1
- package/dest/errors/index.js +0 -1
- package/dest/errors/validator.error.d.ts +0 -29
- package/dest/errors/validator.error.d.ts.map +0 -1
- package/dest/errors/validator.error.js +0 -45
- package/src/errors/index.ts +0 -1
- package/src/errors/validator.error.ts +0 -55
package/src/validator.ts
CHANGED
|
@@ -1,151 +1,265 @@
|
|
|
1
|
+
import type { BlobClientInterface } from '@aztec/blob-client/client';
|
|
2
|
+
import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
|
|
1
3
|
import type { EpochCache } from '@aztec/epoch-cache';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
4
|
+
import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
|
|
5
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
6
|
+
import { TimeoutError } from '@aztec/foundation/error';
|
|
7
|
+
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
8
|
+
import type { Signature } from '@aztec/foundation/eth-signature';
|
|
9
|
+
import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
|
|
10
|
+
import { retryUntil } from '@aztec/foundation/retry';
|
|
5
11
|
import { RunningPromise } from '@aztec/foundation/running-promise';
|
|
6
12
|
import { sleep } from '@aztec/foundation/sleep';
|
|
7
|
-
import { DateProvider
|
|
8
|
-
import type {
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import type {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
import { DateProvider } from '@aztec/foundation/timer';
|
|
14
|
+
import type { KeystoreManager } from '@aztec/node-keystore';
|
|
15
|
+
import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
|
|
16
|
+
import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
|
|
17
|
+
import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
|
|
18
|
+
import type { AztecAddress } from '@aztec/stdlib/aztec-address';
|
|
19
|
+
import type { CommitteeAttestationsAndSigners, L2BlockNew, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
|
|
20
|
+
import type {
|
|
21
|
+
CreateCheckpointProposalLastBlockData,
|
|
22
|
+
Validator,
|
|
23
|
+
ValidatorClientFullConfig,
|
|
24
|
+
WorldStateSynchronizer,
|
|
25
|
+
} from '@aztec/stdlib/interfaces/server';
|
|
26
|
+
import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
|
|
27
|
+
import type {
|
|
28
|
+
BlockProposal,
|
|
29
|
+
BlockProposalOptions,
|
|
30
|
+
CheckpointAttestation,
|
|
31
|
+
CheckpointProposalCore,
|
|
32
|
+
CheckpointProposalOptions,
|
|
33
|
+
} from '@aztec/stdlib/p2p';
|
|
34
|
+
import { CheckpointProposal } from '@aztec/stdlib/p2p';
|
|
35
|
+
import type { CheckpointHeader } from '@aztec/stdlib/rollup';
|
|
36
|
+
import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
|
|
37
|
+
import { AttestationTimeoutError } from '@aztec/stdlib/validators';
|
|
38
|
+
import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
|
|
39
|
+
|
|
40
|
+
import { EventEmitter } from 'events';
|
|
41
|
+
import type { TypedDataDefinition } from 'viem';
|
|
42
|
+
|
|
43
|
+
import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
|
|
44
|
+
import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
|
|
16
45
|
import { ValidationService } from './duties/validation_service.js';
|
|
17
|
-
import {
|
|
18
|
-
AttestationTimeoutError,
|
|
19
|
-
BlockBuilderNotProvidedError,
|
|
20
|
-
InvalidValidatorPrivateKeyError,
|
|
21
|
-
ReExFailedTxsError,
|
|
22
|
-
ReExStateMismatchError,
|
|
23
|
-
ReExTimeoutError,
|
|
24
|
-
TransactionsNotAvailableError,
|
|
25
|
-
} from './errors/validator.error.js';
|
|
26
|
-
import type { ValidatorKeyStore } from './key_store/interface.js';
|
|
27
|
-
import { LocalKeyStore } from './key_store/local_key_store.js';
|
|
46
|
+
import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
|
|
28
47
|
import { ValidatorMetrics } from './metrics.js';
|
|
29
48
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
) => Promise<{
|
|
40
|
-
block: L2Block;
|
|
41
|
-
publicProcessorDuration: number;
|
|
42
|
-
numTxs: number;
|
|
43
|
-
numFailedTxs: number;
|
|
44
|
-
blockBuildingTimer: Timer;
|
|
45
|
-
}>;
|
|
46
|
-
|
|
47
|
-
export interface Validator {
|
|
48
|
-
start(): Promise<void>;
|
|
49
|
-
registerBlockProposalHandler(): void;
|
|
50
|
-
registerBlockBuilder(blockBuilder: BlockBuilderCallback): void;
|
|
51
|
-
|
|
52
|
-
// Block validation responsibilities
|
|
53
|
-
createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal | undefined>;
|
|
54
|
-
attestToProposal(proposal: BlockProposal): void;
|
|
55
|
-
|
|
56
|
-
broadcastBlockProposal(proposal: BlockProposal): void;
|
|
57
|
-
collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]>;
|
|
58
|
-
}
|
|
49
|
+
// We maintain a set of proposers who have proposed invalid blocks.
|
|
50
|
+
// Just cap the set to avoid unbounded growth.
|
|
51
|
+
const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
|
|
52
|
+
|
|
53
|
+
// What errors from the block proposal handler result in slashing
|
|
54
|
+
const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT: BlockProposalValidationFailureReason[] = [
|
|
55
|
+
'state_mismatch',
|
|
56
|
+
'failed_txs',
|
|
57
|
+
];
|
|
59
58
|
|
|
60
59
|
/**
|
|
61
60
|
* Validator Client
|
|
62
61
|
*/
|
|
63
|
-
export class ValidatorClient extends
|
|
62
|
+
export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter) implements Validator, Watcher {
|
|
63
|
+
public readonly tracer: Tracer;
|
|
64
64
|
private validationService: ValidationService;
|
|
65
65
|
private metrics: ValidatorMetrics;
|
|
66
|
+
private log: Logger;
|
|
67
|
+
|
|
68
|
+
// Whether it has already registered handlers on the p2p client
|
|
69
|
+
private hasRegisteredHandlers = false;
|
|
66
70
|
|
|
67
71
|
// Used to check if we are sending the same proposal twice
|
|
68
72
|
private previousProposal?: BlockProposal;
|
|
69
73
|
|
|
70
|
-
|
|
71
|
-
private blockBuilder?: BlockBuilderCallback = undefined;
|
|
72
|
-
|
|
74
|
+
private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
|
|
73
75
|
private epochCacheUpdateLoop: RunningPromise;
|
|
74
76
|
|
|
75
|
-
private
|
|
77
|
+
private proposersOfInvalidBlocks: Set<string> = new Set();
|
|
78
|
+
|
|
79
|
+
// TODO(palla/mbps): Remove this once checkpoint validation is stable and we can validate all blocks properly.
|
|
80
|
+
// Tracks slots for which we have successfully validated a block proposal, so we can attest to checkpoint proposals for those slots.
|
|
81
|
+
// eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
|
|
82
|
+
private validatedBlockSlots: Set<SlotNumber> = new Set();
|
|
76
83
|
|
|
77
|
-
constructor(
|
|
78
|
-
private keyStore:
|
|
84
|
+
protected constructor(
|
|
85
|
+
private keyStore: NodeKeystoreAdapter,
|
|
79
86
|
private epochCache: EpochCache,
|
|
80
87
|
private p2pClient: P2P,
|
|
81
|
-
private
|
|
88
|
+
private blockProposalHandler: BlockProposalHandler,
|
|
89
|
+
private blockSource: L2BlockSource,
|
|
90
|
+
private checkpointsBuilder: FullNodeCheckpointsBuilder,
|
|
91
|
+
private worldState: WorldStateSynchronizer,
|
|
92
|
+
private l1ToL2MessageSource: L1ToL2MessageSource,
|
|
93
|
+
private config: ValidatorClientFullConfig,
|
|
94
|
+
private blobClient: BlobClientInterface,
|
|
82
95
|
private dateProvider: DateProvider = new DateProvider(),
|
|
83
96
|
telemetry: TelemetryClient = getTelemetryClient(),
|
|
84
|
-
|
|
97
|
+
log = createLogger('validator'),
|
|
85
98
|
) {
|
|
86
|
-
|
|
87
|
-
|
|
99
|
+
super();
|
|
100
|
+
|
|
101
|
+
// Create child logger with fisherman prefix if in fisherman mode
|
|
102
|
+
this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
|
|
103
|
+
|
|
104
|
+
this.tracer = telemetry.getTracer('Validator');
|
|
88
105
|
this.metrics = new ValidatorMetrics(telemetry);
|
|
89
106
|
|
|
90
|
-
this.validationService = new ValidationService(keyStore);
|
|
107
|
+
this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
|
|
91
108
|
|
|
92
|
-
|
|
109
|
+
// Refresh epoch cache every second to trigger alert if participation in committee changes
|
|
110
|
+
this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
|
|
93
111
|
|
|
94
|
-
|
|
95
|
-
this.
|
|
96
|
-
|
|
97
|
-
this.epochCache
|
|
98
|
-
.getCommittee()
|
|
99
|
-
.then(() => {})
|
|
100
|
-
.catch(err => log.error('Error updating validator committee', err)),
|
|
101
|
-
log,
|
|
102
|
-
1000,
|
|
103
|
-
);
|
|
112
|
+
const myAddresses = this.getValidatorAddresses();
|
|
113
|
+
this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
|
|
114
|
+
}
|
|
104
115
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
116
|
+
public static validateKeyStoreConfiguration(keyStoreManager: KeystoreManager, logger?: Logger) {
|
|
117
|
+
const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
|
|
118
|
+
const validatorAddresses = validatorKeyStore.getAddresses();
|
|
119
|
+
// Verify that we can retrieve all required data from the key store
|
|
120
|
+
for (const address of validatorAddresses) {
|
|
121
|
+
// Functions throw if required data is not available
|
|
122
|
+
let coinbase: EthAddress;
|
|
123
|
+
let feeRecipient: AztecAddress;
|
|
124
|
+
try {
|
|
125
|
+
coinbase = validatorKeyStore.getCoinbaseAddress(address);
|
|
126
|
+
feeRecipient = validatorKeyStore.getFeeRecipient(address);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
|
|
112
129
|
}
|
|
113
|
-
});
|
|
114
130
|
|
|
115
|
-
|
|
131
|
+
const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
|
|
132
|
+
if (!publisherAddresses.length) {
|
|
133
|
+
throw new Error(`No publisher addresses found for validator address ${address}`);
|
|
134
|
+
}
|
|
135
|
+
logger?.debug(
|
|
136
|
+
`Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map(x => x.toString()).join()}`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private async handleEpochCommitteeUpdate() {
|
|
142
|
+
try {
|
|
143
|
+
const { committee, epoch } = await this.epochCache.getCommittee('next');
|
|
144
|
+
if (!committee) {
|
|
145
|
+
this.log.trace(`No committee found for slot`);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
|
|
149
|
+
const me = this.getValidatorAddresses();
|
|
150
|
+
const committeeSet = new Set(committee.map(v => v.toString()));
|
|
151
|
+
const inCommittee = me.filter(a => committeeSet.has(a.toString()));
|
|
152
|
+
if (inCommittee.length > 0) {
|
|
153
|
+
this.log.info(
|
|
154
|
+
`Validators ${inCommittee.map(a => a.toString()).join(',')} are on the validator committee for epoch ${epoch}`,
|
|
155
|
+
);
|
|
156
|
+
} else {
|
|
157
|
+
this.log.verbose(
|
|
158
|
+
`Validators ${me.map(a => a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
this.lastEpochForCommitteeUpdateLoop = epoch;
|
|
162
|
+
}
|
|
163
|
+
} catch (err) {
|
|
164
|
+
this.log.error(`Error updating epoch committee`, err);
|
|
165
|
+
}
|
|
116
166
|
}
|
|
117
167
|
|
|
118
168
|
static new(
|
|
119
|
-
config:
|
|
169
|
+
config: ValidatorClientFullConfig,
|
|
170
|
+
checkpointsBuilder: FullNodeCheckpointsBuilder,
|
|
171
|
+
worldState: WorldStateSynchronizer,
|
|
120
172
|
epochCache: EpochCache,
|
|
121
173
|
p2pClient: P2P,
|
|
174
|
+
blockSource: L2BlockSource & L2BlockSink,
|
|
175
|
+
l1ToL2MessageSource: L1ToL2MessageSource,
|
|
176
|
+
txProvider: TxProvider,
|
|
177
|
+
keyStoreManager: KeystoreManager,
|
|
178
|
+
blobClient: BlobClientInterface,
|
|
122
179
|
dateProvider: DateProvider = new DateProvider(),
|
|
123
180
|
telemetry: TelemetryClient = getTelemetryClient(),
|
|
124
181
|
) {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
182
|
+
const metrics = new ValidatorMetrics(telemetry);
|
|
183
|
+
const blockProposalValidator = new BlockProposalValidator(epochCache, {
|
|
184
|
+
txsPermitted: !config.disableTransactions,
|
|
185
|
+
});
|
|
186
|
+
const blockProposalHandler = new BlockProposalHandler(
|
|
187
|
+
checkpointsBuilder,
|
|
188
|
+
worldState,
|
|
189
|
+
blockSource,
|
|
190
|
+
l1ToL2MessageSource,
|
|
191
|
+
txProvider,
|
|
192
|
+
blockProposalValidator,
|
|
193
|
+
config,
|
|
194
|
+
metrics,
|
|
195
|
+
dateProvider,
|
|
196
|
+
telemetry,
|
|
197
|
+
);
|
|
128
198
|
|
|
129
|
-
const
|
|
130
|
-
|
|
199
|
+
const validator = new ValidatorClient(
|
|
200
|
+
NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
|
|
201
|
+
epochCache,
|
|
202
|
+
p2pClient,
|
|
203
|
+
blockProposalHandler,
|
|
204
|
+
blockSource,
|
|
205
|
+
checkpointsBuilder,
|
|
206
|
+
worldState,
|
|
207
|
+
l1ToL2MessageSource,
|
|
208
|
+
config,
|
|
209
|
+
blobClient,
|
|
210
|
+
dateProvider,
|
|
211
|
+
telemetry,
|
|
212
|
+
);
|
|
131
213
|
|
|
132
|
-
const validator = new ValidatorClient(localKeyStore, epochCache, p2pClient, config, dateProvider, telemetry);
|
|
133
|
-
validator.registerBlockProposalHandler();
|
|
134
214
|
return validator;
|
|
135
215
|
}
|
|
136
216
|
|
|
217
|
+
public getValidatorAddresses() {
|
|
218
|
+
return this.keyStore
|
|
219
|
+
.getAddresses()
|
|
220
|
+
.filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
public getBlockProposalHandler() {
|
|
224
|
+
return this.blockProposalHandler;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
|
|
228
|
+
return this.keyStore.signTypedDataWithAddress(addr, msg);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
|
|
232
|
+
return this.keyStore.getCoinbaseAddress(attestor);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
public getFeeRecipientForAttestor(attestor: EthAddress): AztecAddress {
|
|
236
|
+
return this.keyStore.getFeeRecipient(attestor);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
public getConfig(): ValidatorClientFullConfig {
|
|
240
|
+
return this.config;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
public updateConfig(config: Partial<ValidatorClientFullConfig>) {
|
|
244
|
+
this.config = { ...this.config, ...config };
|
|
245
|
+
}
|
|
246
|
+
|
|
137
247
|
public async start() {
|
|
138
|
-
|
|
139
|
-
|
|
248
|
+
if (this.epochCacheUpdateLoop.isRunning()) {
|
|
249
|
+
this.log.warn(`Validator client already started`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
140
252
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
253
|
+
await this.registerHandlers();
|
|
254
|
+
|
|
255
|
+
const myAddresses = this.getValidatorAddresses();
|
|
256
|
+
const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
|
|
257
|
+
this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
|
|
258
|
+
if (inCommittee.length > 0) {
|
|
259
|
+
this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
|
|
147
260
|
}
|
|
148
261
|
this.epochCacheUpdateLoop.start();
|
|
262
|
+
|
|
149
263
|
return Promise.resolve();
|
|
150
264
|
}
|
|
151
265
|
|
|
@@ -153,185 +267,587 @@ export class ValidatorClient extends WithTracer implements Validator {
|
|
|
153
267
|
await this.epochCacheUpdateLoop.stop();
|
|
154
268
|
}
|
|
155
269
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
270
|
+
/** Register handlers on the p2p client */
|
|
271
|
+
public async registerHandlers() {
|
|
272
|
+
if (!this.hasRegisteredHandlers) {
|
|
273
|
+
this.hasRegisteredHandlers = true;
|
|
274
|
+
this.log.debug(`Registering validator handlers for p2p client`);
|
|
275
|
+
|
|
276
|
+
// Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
|
|
277
|
+
const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
|
|
278
|
+
this.validateBlockProposal(block, proposalSender);
|
|
279
|
+
this.p2pClient.registerBlockProposalHandler(blockHandler);
|
|
280
|
+
|
|
281
|
+
// Checkpoint proposal handler - validates and creates attestations
|
|
282
|
+
// The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
|
|
283
|
+
// and processed separately via the block handler above.
|
|
284
|
+
const checkpointHandler = (
|
|
285
|
+
checkpoint: CheckpointProposalCore,
|
|
286
|
+
proposalSender: PeerId,
|
|
287
|
+
): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
|
|
288
|
+
this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
|
|
289
|
+
|
|
290
|
+
const myAddresses = this.getValidatorAddresses();
|
|
291
|
+
this.p2pClient.registerThisValidatorAddresses(myAddresses);
|
|
292
|
+
|
|
293
|
+
await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
|
|
294
|
+
}
|
|
161
295
|
}
|
|
162
296
|
|
|
163
297
|
/**
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
298
|
+
* Validate a block proposal from a peer.
|
|
299
|
+
* Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
|
|
300
|
+
* @returns true if the proposal is valid, false otherwise
|
|
167
301
|
*/
|
|
168
|
-
|
|
169
|
-
|
|
302
|
+
async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
|
|
303
|
+
const slotNumber = proposal.slotNumber;
|
|
304
|
+
const proposer = proposal.getSender();
|
|
305
|
+
|
|
306
|
+
// Reject proposals with invalid signatures
|
|
307
|
+
if (!proposer) {
|
|
308
|
+
this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Check if we're in the committee (for metrics purposes)
|
|
313
|
+
const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
|
|
314
|
+
const partOfCommittee = inCommittee.length > 0;
|
|
315
|
+
|
|
316
|
+
const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
|
|
317
|
+
this.log.info(`Received block proposal for slot ${slotNumber}`, {
|
|
318
|
+
...proposalInfo,
|
|
319
|
+
txHashes: proposal.txHashes.map(t => t.toString()),
|
|
320
|
+
fishermanMode: this.config.fishermanMode || false,
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
|
|
324
|
+
// In fisherman mode, we always reexecute to validate proposals.
|
|
325
|
+
const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
|
|
326
|
+
this.config;
|
|
327
|
+
const shouldReexecute =
|
|
328
|
+
fishermanMode ||
|
|
329
|
+
(slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
|
|
330
|
+
(partOfCommittee && validatorReexecute) ||
|
|
331
|
+
alwaysReexecuteBlockProposals ||
|
|
332
|
+
this.blobClient.canUpload();
|
|
333
|
+
|
|
334
|
+
const validationResult = await this.blockProposalHandler.handleBlockProposal(
|
|
335
|
+
proposal,
|
|
336
|
+
proposalSender,
|
|
337
|
+
!!shouldReexecute,
|
|
338
|
+
);
|
|
339
|
+
|
|
340
|
+
if (!validationResult.isValid) {
|
|
341
|
+
this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
|
|
342
|
+
|
|
343
|
+
const reason = validationResult.reason || 'unknown';
|
|
344
|
+
// Classify failure reason: bad proposal vs node issue
|
|
345
|
+
const badProposalReasons: BlockProposalValidationFailureReason[] = [
|
|
346
|
+
'invalid_proposal',
|
|
347
|
+
'state_mismatch',
|
|
348
|
+
'failed_txs',
|
|
349
|
+
'in_hash_mismatch',
|
|
350
|
+
'parent_block_wrong_slot',
|
|
351
|
+
];
|
|
352
|
+
|
|
353
|
+
if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
|
|
354
|
+
this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
|
|
355
|
+
} else {
|
|
356
|
+
// Node issues so we can't validate
|
|
357
|
+
this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Slash invalid block proposals (can happen even when not in committee)
|
|
361
|
+
if (
|
|
362
|
+
validationResult.reason &&
|
|
363
|
+
SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
|
|
364
|
+
slashBroadcastedInvalidBlockPenalty > 0n
|
|
365
|
+
) {
|
|
366
|
+
this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
|
|
367
|
+
this.slashInvalidBlock(proposal);
|
|
368
|
+
}
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
this.log.info(`Validated block proposal for slot ${slotNumber}`, {
|
|
373
|
+
...proposalInfo,
|
|
374
|
+
inCommittee: partOfCommittee,
|
|
375
|
+
fishermanMode: this.config.fishermanMode || false,
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// TODO(palla/mbps): Remove this once checkpoint validation is stable.
|
|
379
|
+
// Track that we successfully validated a block for this slot, so we can attest to checkpoint proposals for it.
|
|
380
|
+
this.validatedBlockSlots.add(slotNumber);
|
|
381
|
+
|
|
382
|
+
return true;
|
|
170
383
|
}
|
|
171
384
|
|
|
172
|
-
|
|
173
|
-
|
|
385
|
+
/**
|
|
386
|
+
* Validate and attest to a checkpoint proposal from a peer.
|
|
387
|
+
* The proposal is received as CheckpointProposalCore (without lastBlock) since
|
|
388
|
+
* the lastBlock is extracted and processed separately via the block handler.
|
|
389
|
+
* @returns Checkpoint attestations if valid, undefined otherwise
|
|
390
|
+
*/
|
|
391
|
+
async attestToCheckpointProposal(
|
|
392
|
+
proposal: CheckpointProposalCore,
|
|
393
|
+
_proposalSender: PeerId,
|
|
394
|
+
): Promise<CheckpointAttestation[] | undefined> {
|
|
395
|
+
const slotNumber = proposal.slotNumber;
|
|
396
|
+
const proposer = proposal.getSender();
|
|
397
|
+
|
|
398
|
+
// Reject proposals with invalid signatures
|
|
399
|
+
if (!proposer) {
|
|
400
|
+
this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Check that I have any address in current committee before attesting
|
|
405
|
+
const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
|
|
406
|
+
const partOfCommittee = inCommittee.length > 0;
|
|
407
|
+
|
|
174
408
|
const proposalInfo = {
|
|
175
409
|
slotNumber,
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
txCount: proposal.
|
|
179
|
-
txHashes: proposal.payload.txHashes.map(txHash => txHash.toString()),
|
|
410
|
+
archive: proposal.archive.toString(),
|
|
411
|
+
proposer: proposer.toString(),
|
|
412
|
+
txCount: proposal.txHashes.length,
|
|
180
413
|
};
|
|
181
|
-
this.log.
|
|
414
|
+
this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
|
|
415
|
+
...proposalInfo,
|
|
416
|
+
txHashes: proposal.txHashes.map(t => t.toString()),
|
|
417
|
+
fishermanMode: this.config.fishermanMode || false,
|
|
418
|
+
});
|
|
182
419
|
|
|
183
|
-
//
|
|
184
|
-
|
|
185
|
-
|
|
420
|
+
// TODO(palla/mbps): Remove this once checkpoint validation is stable.
|
|
421
|
+
// Check that we have successfully validated a block for this slot before attesting to the checkpoint.
|
|
422
|
+
if (!this.validatedBlockSlots.has(slotNumber)) {
|
|
423
|
+
this.log.warn(`No validated block found for slot ${slotNumber}, refusing to attest to checkpoint`, proposalInfo);
|
|
186
424
|
return undefined;
|
|
187
425
|
}
|
|
188
426
|
|
|
189
|
-
//
|
|
190
|
-
|
|
191
|
-
if (
|
|
192
|
-
this.log.verbose(`
|
|
193
|
-
|
|
427
|
+
// Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
|
|
428
|
+
// TODO(palla/mbps): Change default to false once checkpoint validation is stable.
|
|
429
|
+
if (this.config.skipCheckpointProposalValidation !== false) {
|
|
430
|
+
this.log.verbose(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
|
|
431
|
+
} else {
|
|
432
|
+
const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
|
|
433
|
+
if (!validationResult.isValid) {
|
|
434
|
+
this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
|
|
435
|
+
return undefined;
|
|
436
|
+
}
|
|
194
437
|
}
|
|
195
438
|
|
|
196
|
-
//
|
|
197
|
-
this.
|
|
198
|
-
|
|
199
|
-
|
|
439
|
+
// Upload blobs to filestore if we can (fire and forget)
|
|
440
|
+
if (this.blobClient.canUpload()) {
|
|
441
|
+
void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
|
|
442
|
+
}
|
|
200
443
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
} catch (error: any) {
|
|
206
|
-
// If the transactions are not available, then we should not attempt to attest
|
|
207
|
-
if (error instanceof TransactionsNotAvailableError) {
|
|
208
|
-
this.log.error(`Transactions not available, skipping attestation`, error, proposalInfo);
|
|
209
|
-
} else {
|
|
210
|
-
// This branch most commonly be hit if the transactions are available, but the re-execution fails
|
|
211
|
-
// Catch all error handler
|
|
212
|
-
this.log.error(`Failed to attest to proposal`, error, proposalInfo);
|
|
213
|
-
}
|
|
444
|
+
// Check that I have any address in current committee before attesting
|
|
445
|
+
// In fisherman mode, we still create attestations for validation even if not in committee
|
|
446
|
+
if (!partOfCommittee && !this.config.fishermanMode) {
|
|
447
|
+
this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
|
|
214
448
|
return undefined;
|
|
215
449
|
}
|
|
216
450
|
|
|
217
451
|
// Provided all of the above checks pass, we can attest to the proposal
|
|
218
|
-
this.log.info(
|
|
452
|
+
this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
|
|
453
|
+
...proposalInfo,
|
|
454
|
+
inCommittee: partOfCommittee,
|
|
455
|
+
fishermanMode: this.config.fishermanMode || false,
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
this.metrics.incSuccessfulAttestations(inCommittee.length);
|
|
219
459
|
|
|
220
|
-
//
|
|
221
|
-
|
|
460
|
+
// Determine which validators should attest
|
|
461
|
+
let attestors: EthAddress[];
|
|
462
|
+
if (partOfCommittee) {
|
|
463
|
+
attestors = inCommittee;
|
|
464
|
+
} else if (this.config.fishermanMode) {
|
|
465
|
+
// In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
|
|
466
|
+
attestors = this.getValidatorAddresses();
|
|
467
|
+
} else {
|
|
468
|
+
attestors = [];
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Only create attestations if we have attestors
|
|
472
|
+
if (attestors.length === 0) {
|
|
473
|
+
return undefined;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
if (this.config.fishermanMode) {
|
|
477
|
+
// bail out early and don't save attestations to the pool in fisherman mode
|
|
478
|
+
this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
|
|
479
|
+
...proposalInfo,
|
|
480
|
+
attestors: attestors.map(a => a.toString()),
|
|
481
|
+
});
|
|
482
|
+
return undefined;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return this.createCheckpointAttestationsFromProposal(proposal, attestors);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private async createCheckpointAttestationsFromProposal(
|
|
489
|
+
proposal: CheckpointProposalCore,
|
|
490
|
+
attestors: EthAddress[] = [],
|
|
491
|
+
): Promise<CheckpointAttestation[]> {
|
|
492
|
+
const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
|
|
493
|
+
await this.p2pClient.addCheckpointAttestations(attestations);
|
|
494
|
+
return attestations;
|
|
222
495
|
}
|
|
223
496
|
|
|
224
497
|
/**
|
|
225
|
-
*
|
|
226
|
-
* @
|
|
498
|
+
* Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
|
|
499
|
+
* @returns Validation result with isValid flag and reason if invalid.
|
|
227
500
|
*/
|
|
228
|
-
async
|
|
229
|
-
|
|
501
|
+
private async validateCheckpointProposal(
|
|
502
|
+
proposal: CheckpointProposalCore,
|
|
503
|
+
proposalInfo: LogData,
|
|
504
|
+
): Promise<{ isValid: true } | { isValid: false; reason: string }> {
|
|
505
|
+
const slot = proposal.slotNumber;
|
|
506
|
+
const timeoutSeconds = 10;
|
|
507
|
+
|
|
508
|
+
// Wait for last block to sync by archive
|
|
509
|
+
let lastBlockHeader: BlockHeader | undefined;
|
|
510
|
+
try {
|
|
511
|
+
lastBlockHeader = await retryUntil(
|
|
512
|
+
async () => {
|
|
513
|
+
await this.blockSource.syncImmediate();
|
|
514
|
+
return this.blockSource.getBlockHeaderByArchive(proposal.archive);
|
|
515
|
+
},
|
|
516
|
+
`waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
|
|
517
|
+
timeoutSeconds,
|
|
518
|
+
0.5,
|
|
519
|
+
);
|
|
520
|
+
} catch (err) {
|
|
521
|
+
if (err instanceof TimeoutError) {
|
|
522
|
+
this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
|
|
523
|
+
return { isValid: false, reason: 'last_block_not_found' };
|
|
524
|
+
}
|
|
525
|
+
this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
|
|
526
|
+
return { isValid: false, reason: 'block_fetch_error' };
|
|
527
|
+
}
|
|
230
528
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
529
|
+
if (!lastBlockHeader) {
|
|
530
|
+
this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
|
|
531
|
+
return { isValid: false, reason: 'last_block_not_found' };
|
|
532
|
+
}
|
|
234
533
|
|
|
235
|
-
//
|
|
236
|
-
|
|
237
|
-
|
|
534
|
+
// Get the last full block to determine checkpoint number
|
|
535
|
+
const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
|
|
536
|
+
if (!lastBlock) {
|
|
537
|
+
this.log.warn(`Last block ${lastBlockHeader.getBlockNumber()} not found`, proposalInfo);
|
|
538
|
+
return { isValid: false, reason: 'last_block_not_found' };
|
|
238
539
|
}
|
|
540
|
+
const checkpointNumber = lastBlock.checkpointNumber;
|
|
239
541
|
|
|
240
|
-
//
|
|
241
|
-
|
|
242
|
-
|
|
542
|
+
// Get all full blocks for the slot and checkpoint
|
|
543
|
+
const blocks = await this.getBlocksForSlot(slot, lastBlockHeader, checkpointNumber);
|
|
544
|
+
if (blocks.length === 0) {
|
|
545
|
+
this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
|
|
546
|
+
return { isValid: false, reason: 'no_blocks_for_slot' };
|
|
243
547
|
}
|
|
244
548
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
validateOnly: true,
|
|
549
|
+
this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
|
|
550
|
+
...proposalInfo,
|
|
551
|
+
blockNumbers: blocks.map(b => b.number),
|
|
249
552
|
});
|
|
250
|
-
stopTimer();
|
|
251
553
|
|
|
252
|
-
|
|
554
|
+
// Get checkpoint constants from first block
|
|
555
|
+
const firstBlock = blocks[0];
|
|
556
|
+
const constants = this.extractCheckpointConstants(firstBlock);
|
|
253
557
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
throw new ReExFailedTxsError(numFailedTxs);
|
|
257
|
-
}
|
|
558
|
+
// Get L1-to-L2 messages for this checkpoint
|
|
559
|
+
const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
|
|
258
560
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
561
|
+
// Fork world state at the block before the first block
|
|
562
|
+
const parentBlockNumber = BlockNumber(firstBlock.number - 1);
|
|
563
|
+
const fork = await this.worldState.fork(parentBlockNumber);
|
|
564
|
+
|
|
565
|
+
try {
|
|
566
|
+
// Create checkpoint builder with all existing blocks
|
|
567
|
+
const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
|
|
568
|
+
checkpointNumber,
|
|
569
|
+
constants,
|
|
570
|
+
l1ToL2Messages,
|
|
571
|
+
fork,
|
|
572
|
+
blocks,
|
|
573
|
+
);
|
|
263
574
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
575
|
+
// Complete the checkpoint to get computed values
|
|
576
|
+
const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
|
|
577
|
+
|
|
578
|
+
// Compare checkpoint header with proposal
|
|
579
|
+
if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
|
|
580
|
+
this.log.warn(`Checkpoint header mismatch`, {
|
|
581
|
+
...proposalInfo,
|
|
582
|
+
computed: computedCheckpoint.header.toInspect(),
|
|
583
|
+
proposal: proposal.checkpointHeader.toInspect(),
|
|
584
|
+
});
|
|
585
|
+
return { isValid: false, reason: 'checkpoint_header_mismatch' };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// Compare archive root with proposal
|
|
589
|
+
if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
|
|
590
|
+
this.log.warn(`Archive root mismatch`, {
|
|
591
|
+
...proposalInfo,
|
|
592
|
+
computed: computedCheckpoint.archive.root.toString(),
|
|
593
|
+
proposal: proposal.archive.toString(),
|
|
594
|
+
});
|
|
595
|
+
return { isValid: false, reason: 'archive_mismatch' };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
|
|
599
|
+
return { isValid: true };
|
|
600
|
+
} finally {
|
|
601
|
+
await fork.close();
|
|
268
602
|
}
|
|
269
603
|
}
|
|
270
604
|
|
|
271
605
|
/**
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
* 2. If any transactions are not in the local tx pool, request them from the network
|
|
276
|
-
* 3. If we cannot retrieve them from the network, throw an error
|
|
277
|
-
* @param proposal - The proposal to attest to
|
|
606
|
+
* Get all full blocks for a given slot and checkpoint by walking backwards from the last block.
|
|
607
|
+
* Returns blocks in ascending order (earliest to latest).
|
|
608
|
+
* TODO(palla/mbps): Add getL2BlocksForSlot() to L2BlockSource interface for efficiency.
|
|
278
609
|
*/
|
|
279
|
-
async
|
|
280
|
-
|
|
281
|
-
|
|
610
|
+
private async getBlocksForSlot(
|
|
611
|
+
slot: SlotNumber,
|
|
612
|
+
lastBlockHeader: BlockHeader,
|
|
613
|
+
checkpointNumber: CheckpointNumber,
|
|
614
|
+
): Promise<L2BlockNew[]> {
|
|
615
|
+
const blocks: L2BlockNew[] = [];
|
|
616
|
+
let currentHeader = lastBlockHeader;
|
|
617
|
+
const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
|
|
618
|
+
|
|
619
|
+
while (currentHeader.getSlot() === slot) {
|
|
620
|
+
const block = await this.blockSource.getL2BlockNew(currentHeader.getBlockNumber());
|
|
621
|
+
if (!block) {
|
|
622
|
+
this.log.warn(`Block ${currentHeader.getBlockNumber()} not found while getting blocks for slot ${slot}`);
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
if (block.checkpointNumber !== checkpointNumber) {
|
|
626
|
+
break;
|
|
627
|
+
}
|
|
628
|
+
blocks.unshift(block);
|
|
282
629
|
|
|
283
|
-
|
|
630
|
+
const prevArchive = currentHeader.lastArchive.root;
|
|
631
|
+
if (prevArchive.equals(genesisArchiveRoot)) {
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
284
634
|
|
|
285
|
-
|
|
286
|
-
|
|
635
|
+
const prevHeader = await this.blockSource.getBlockHeaderByArchive(prevArchive);
|
|
636
|
+
if (!prevHeader || prevHeader.getSlot() !== slot) {
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
currentHeader = prevHeader;
|
|
287
640
|
}
|
|
288
641
|
|
|
289
|
-
|
|
642
|
+
return blocks;
|
|
643
|
+
}
|
|
290
644
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
645
|
+
/**
|
|
646
|
+
* Extract checkpoint global variables from a block.
|
|
647
|
+
*/
|
|
648
|
+
private extractCheckpointConstants(block: L2BlockNew): CheckpointGlobalVariables {
|
|
649
|
+
const gv = block.header.globalVariables;
|
|
650
|
+
return {
|
|
651
|
+
chainId: gv.chainId,
|
|
652
|
+
version: gv.version,
|
|
653
|
+
slotNumber: gv.slotNumber,
|
|
654
|
+
coinbase: gv.coinbase,
|
|
655
|
+
feeRecipient: gv.feeRecipient,
|
|
656
|
+
gasFees: gv.gasFees,
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Uploads blobs for a checkpoint to the filestore (fire and forget).
|
|
662
|
+
*/
|
|
663
|
+
private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
|
|
664
|
+
try {
|
|
665
|
+
const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
|
|
666
|
+
if (!lastBlockHeader) {
|
|
667
|
+
this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Get the last full block to determine checkpoint number
|
|
672
|
+
const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
|
|
673
|
+
if (!lastBlock) {
|
|
674
|
+
this.log.warn(`Failed to get last block for blob upload`, proposalInfo);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const blocks = await this.getBlocksForSlot(proposal.slotNumber, lastBlockHeader, lastBlock.checkpointNumber);
|
|
679
|
+
if (blocks.length === 0) {
|
|
680
|
+
this.log.warn(`No blocks found for blob upload`, proposalInfo);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const blobFields = blocks.flatMap(b => b.toBlobFields());
|
|
685
|
+
const blobs: Blob[] = getBlobsPerL1Block(blobFields);
|
|
686
|
+
await this.blobClient.sendBlobsToFilestore(blobs);
|
|
687
|
+
this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
|
|
688
|
+
...proposalInfo,
|
|
689
|
+
numBlobs: blobs.length,
|
|
690
|
+
});
|
|
691
|
+
} catch (err) {
|
|
692
|
+
this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
|
|
294
693
|
}
|
|
295
694
|
}
|
|
296
695
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
696
|
+
private slashInvalidBlock(proposal: BlockProposal) {
|
|
697
|
+
const proposer = proposal.getSender();
|
|
698
|
+
|
|
699
|
+
// Skip if signature is invalid (shouldn't happen since we validate earlier)
|
|
700
|
+
if (!proposer) {
|
|
701
|
+
this.log.warn(`Cannot slash proposal with invalid signature`);
|
|
702
|
+
return;
|
|
301
703
|
}
|
|
302
704
|
|
|
303
|
-
|
|
705
|
+
// Trim the set if it's too big.
|
|
706
|
+
if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
|
|
707
|
+
// remove oldest proposer. `values` is guaranteed to be in insertion order.
|
|
708
|
+
this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value!);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
this.proposersOfInvalidBlocks.add(proposer.toString());
|
|
712
|
+
|
|
713
|
+
this.emit(WANT_TO_SLASH_EVENT, [
|
|
714
|
+
{
|
|
715
|
+
validator: proposer,
|
|
716
|
+
amount: this.config.slashBroadcastedInvalidBlockPenalty,
|
|
717
|
+
offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
|
|
718
|
+
epochOrSlot: BigInt(proposal.slotNumber),
|
|
719
|
+
},
|
|
720
|
+
]);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async createBlockProposal(
|
|
724
|
+
blockHeader: BlockHeader,
|
|
725
|
+
indexWithinCheckpoint: number,
|
|
726
|
+
inHash: Fr,
|
|
727
|
+
archive: Fr,
|
|
728
|
+
txs: Tx[],
|
|
729
|
+
proposerAddress: EthAddress | undefined,
|
|
730
|
+
options: BlockProposalOptions,
|
|
731
|
+
): Promise<BlockProposal> {
|
|
732
|
+
// TODO(palla/mbps): Prevent double proposals properly
|
|
733
|
+
// if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
|
|
734
|
+
// this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
|
|
735
|
+
// return Promise.resolve(undefined);
|
|
736
|
+
// }
|
|
737
|
+
|
|
738
|
+
this.log.info(
|
|
739
|
+
`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
|
|
740
|
+
);
|
|
741
|
+
const newProposal = await this.validationService.createBlockProposal(
|
|
742
|
+
blockHeader,
|
|
743
|
+
indexWithinCheckpoint,
|
|
744
|
+
inHash,
|
|
745
|
+
archive,
|
|
746
|
+
txs,
|
|
747
|
+
proposerAddress,
|
|
748
|
+
{
|
|
749
|
+
...options,
|
|
750
|
+
broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
|
|
751
|
+
},
|
|
752
|
+
);
|
|
304
753
|
this.previousProposal = newProposal;
|
|
305
754
|
return newProposal;
|
|
306
755
|
}
|
|
307
756
|
|
|
308
|
-
|
|
309
|
-
|
|
757
|
+
async createCheckpointProposal(
|
|
758
|
+
checkpointHeader: CheckpointHeader,
|
|
759
|
+
archive: Fr,
|
|
760
|
+
lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
|
|
761
|
+
proposerAddress: EthAddress | undefined,
|
|
762
|
+
options: CheckpointProposalOptions,
|
|
763
|
+
): Promise<CheckpointProposal> {
|
|
764
|
+
this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
|
|
765
|
+
return await this.validationService.createCheckpointProposal(
|
|
766
|
+
checkpointHeader,
|
|
767
|
+
archive,
|
|
768
|
+
lastBlockInfo,
|
|
769
|
+
proposerAddress,
|
|
770
|
+
options,
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
|
|
775
|
+
await this.p2pClient.broadcastProposal(proposal);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async signAttestationsAndSigners(
|
|
779
|
+
attestationsAndSigners: CommitteeAttestationsAndSigners,
|
|
780
|
+
proposer: EthAddress,
|
|
781
|
+
): Promise<Signature> {
|
|
782
|
+
return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
|
|
310
783
|
}
|
|
311
784
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
785
|
+
async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
|
|
786
|
+
const slot = proposal.slotNumber;
|
|
787
|
+
const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
|
|
788
|
+
this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
|
|
789
|
+
const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
|
|
790
|
+
|
|
791
|
+
// We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
|
|
792
|
+
// other nodes can see that our validators did attest to this block proposal, and do not slash us
|
|
793
|
+
// due to inactivity for missed attestations.
|
|
794
|
+
void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
|
|
795
|
+
this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
|
|
796
|
+
});
|
|
797
|
+
return attestations;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async collectAttestations(
|
|
801
|
+
proposal: CheckpointProposal,
|
|
802
|
+
required: number,
|
|
803
|
+
deadline: Date,
|
|
804
|
+
): Promise<CheckpointAttestation[]> {
|
|
805
|
+
// Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
|
|
806
|
+
const slot = proposal.slotNumber;
|
|
316
807
|
this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
|
|
317
808
|
|
|
318
809
|
if (+deadline < this.dateProvider.now()) {
|
|
319
810
|
this.log.error(
|
|
320
811
|
`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`,
|
|
321
812
|
);
|
|
322
|
-
throw new AttestationTimeoutError(required, slot);
|
|
813
|
+
throw new AttestationTimeoutError(0, required, slot);
|
|
323
814
|
}
|
|
324
815
|
|
|
816
|
+
await this.collectOwnAttestations(proposal);
|
|
817
|
+
|
|
325
818
|
const proposalId = proposal.archive.toString();
|
|
326
|
-
const
|
|
819
|
+
const myAddresses = this.getValidatorAddresses();
|
|
327
820
|
|
|
328
|
-
let attestations:
|
|
821
|
+
let attestations: CheckpointAttestation[] = [];
|
|
329
822
|
while (true) {
|
|
330
|
-
|
|
331
|
-
|
|
823
|
+
// Filter out attestations with a mismatching archive. This should NOT happen since we have verified
|
|
824
|
+
// the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
|
|
825
|
+
const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
|
|
826
|
+
attestation => {
|
|
827
|
+
if (!attestation.archive.equals(proposal.archive)) {
|
|
828
|
+
this.log.warn(
|
|
829
|
+
`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
|
|
830
|
+
{ attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
|
|
831
|
+
);
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
return true;
|
|
835
|
+
},
|
|
836
|
+
);
|
|
837
|
+
|
|
838
|
+
// Log new attestations we collected
|
|
839
|
+
const oldSenders = attestations.map(attestation => attestation.getSender());
|
|
332
840
|
for (const collected of collectedAttestations) {
|
|
333
|
-
const collectedSender =
|
|
334
|
-
|
|
841
|
+
const collectedSender = collected.getSender();
|
|
842
|
+
// Skip attestations with invalid signatures
|
|
843
|
+
if (!collectedSender) {
|
|
844
|
+
this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
847
|
+
if (
|
|
848
|
+
!myAddresses.some(address => address.equals(collectedSender)) &&
|
|
849
|
+
!oldSenders.some(sender => sender?.equals(collectedSender))
|
|
850
|
+
) {
|
|
335
851
|
this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
|
|
336
852
|
}
|
|
337
853
|
}
|
|
@@ -344,19 +860,34 @@ export class ValidatorClient extends WithTracer implements Validator {
|
|
|
344
860
|
|
|
345
861
|
if (+deadline < this.dateProvider.now()) {
|
|
346
862
|
this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
|
|
347
|
-
throw new AttestationTimeoutError(required, slot);
|
|
863
|
+
throw new AttestationTimeoutError(attestations.length, required, slot);
|
|
348
864
|
}
|
|
349
865
|
|
|
350
|
-
this.log.debug(`Collected ${attestations.length} attestations so far`);
|
|
866
|
+
this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
|
|
351
867
|
await sleep(this.config.attestationPollingIntervalMs);
|
|
352
868
|
}
|
|
353
869
|
}
|
|
354
|
-
}
|
|
355
870
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
871
|
+
private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
|
|
872
|
+
const authRequest = AuthRequest.fromBuffer(msg);
|
|
873
|
+
const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
|
|
874
|
+
if (statusMessage === undefined) {
|
|
875
|
+
return Buffer.alloc(0);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// Find a validator address that is in the set
|
|
879
|
+
const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
|
|
880
|
+
const addressToUse = this.getValidatorAddresses().find(
|
|
881
|
+
address => allRegisteredValidators.find(v => v.equals(address)) !== undefined,
|
|
882
|
+
);
|
|
883
|
+
if (addressToUse === undefined) {
|
|
884
|
+
// We don't have a registered address
|
|
885
|
+
return Buffer.alloc(0);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
const payloadToSign = authRequest.getPayloadToSign();
|
|
889
|
+
const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
|
|
890
|
+
const authResponse = new AuthResponse(statusMessage, signature);
|
|
891
|
+
return authResponse.toBuffer();
|
|
361
892
|
}
|
|
362
893
|
}
|