@obolnetwork/obol-sdk 2.5.1 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/cjs/package.json +3 -3
  2. package/dist/cjs/src/constants.js +13 -1
  3. package/dist/cjs/src/exits/ethUtils.js +57 -0
  4. package/dist/cjs/src/exits/exit.js +502 -0
  5. package/dist/cjs/src/exits/verificationHelpers.js +86 -0
  6. package/dist/cjs/src/{incentiveHelpers.js → incentives/incentiveHelpers.js} +1 -1
  7. package/dist/cjs/src/{incentives.js → incentives/incentives.js} +3 -3
  8. package/dist/cjs/src/index.js +22 -4
  9. package/dist/cjs/src/splits/splitHelpers.js +327 -0
  10. package/dist/cjs/src/types.js +1 -0
  11. package/dist/cjs/test/exit/ethUtils.spec.js +83 -0
  12. package/dist/cjs/test/exit/exit.spec.js +399 -0
  13. package/dist/cjs/test/exit/verificationHelpers.spec.js +68 -0
  14. package/dist/cjs/test/{incentives.test.js → incentives/incentives.spec.js} +4 -4
  15. package/dist/esm/package.json +3 -3
  16. package/dist/esm/src/constants.js +12 -0
  17. package/dist/esm/src/exits/ethUtils.js +52 -0
  18. package/dist/esm/src/exits/exit.js +475 -0
  19. package/dist/esm/src/exits/verificationHelpers.js +81 -0
  20. package/dist/esm/src/{incentiveHelpers.js → incentives/incentiveHelpers.js} +1 -1
  21. package/dist/esm/src/{incentives.js → incentives/incentives.js} +3 -3
  22. package/dist/esm/src/index.js +20 -3
  23. package/dist/esm/src/splits/splitHelpers.js +317 -0
  24. package/dist/esm/src/types.js +1 -0
  25. package/dist/esm/test/exit/ethUtils.spec.js +81 -0
  26. package/dist/esm/test/exit/exit.spec.js +374 -0
  27. package/dist/esm/test/exit/verificationHelpers.spec.js +66 -0
  28. package/dist/esm/test/{incentives.test.js → incentives/incentives.spec.js} +4 -4
  29. package/dist/types/src/constants.d.ts +5 -0
  30. package/dist/types/src/exits/ethUtils.d.ts +13 -0
  31. package/dist/types/src/exits/exit.d.ts +200 -0
  32. package/dist/types/src/exits/verificationHelpers.d.ts +20 -0
  33. package/dist/types/src/{incentiveHelpers.d.ts → incentives/incentiveHelpers.d.ts} +1 -1
  34. package/dist/types/src/{incentives.d.ts → incentives/incentives.d.ts} +1 -1
  35. package/dist/types/src/index.d.ts +16 -2
  36. package/dist/types/src/{splitHelpers.d.ts → splits/splitHelpers.d.ts} +1 -1
  37. package/dist/types/src/types.d.ts +133 -0
  38. package/dist/types/test/exit/verificationHelpers.spec.d.ts +1 -0
  39. package/dist/types/test/incentives/incentives.spec.d.ts +1 -0
  40. package/package.json +3 -3
  41. package/src/constants.ts +13 -0
  42. package/src/exits/ethUtils.ts +49 -0
  43. package/src/exits/exit.ts +661 -0
  44. package/src/exits/verificationHelpers.ts +110 -0
  45. package/src/{incentiveHelpers.ts → incentives/incentiveHelpers.ts} +2 -2
  46. package/src/{incentives.ts → incentives/incentives.ts} +3 -3
  47. package/src/index.ts +29 -3
  48. package/src/splits/splitHelpers.ts +557 -0
  49. package/src/types.ts +158 -0
  50. package/dist/cjs/src/splitHelpers.js +0 -187
  51. package/dist/cjs/test/methods.test.js +0 -418
  52. package/dist/esm/src/splitHelpers.js +0 -177
  53. package/dist/esm/test/methods.test.js +0 -393
  54. package/src/splitHelpers.ts +0 -355
  55. /package/dist/types/test/{incentives.test.d.ts → exit/ethUtils.spec.d.ts} +0 -0
  56. /package/dist/types/test/{methods.test.d.ts → exit/exit.spec.d.ts} +0 -0
@@ -0,0 +1,475 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { ENR } from '@chainsafe/discv5';
11
+ import * as elliptic from 'elliptic';
12
+ import { init, verify, aggregateSignatures } from '@chainsafe/bls';
13
+ import { ByteVectorType, ContainerType, fromHexString, ListCompositeType, UintNumberType, } from '@chainsafe/ssz';
14
+ import { getCapellaFork, getGenesisValidatorsRoot } from './ethUtils';
15
+ import { computeDomain, signingRoot } from './verificationHelpers';
16
+ // Constants from obol-api/src/verification/exit.ts (assuming these might be needed or were in the original context)
17
+ const DOMAIN_VOLUNTARY_EXIT = '0x04000000';
18
+ // SSZ Type Definitions (adapted from obol-api/src/verification/exit.ts)
19
+ const SSZExitMessageType = new ContainerType({
20
+ epoch: new UintNumberType(8),
21
+ validator_index: new UintNumberType(8),
22
+ });
23
+ const SSZPartialExitsPayloadType = new ContainerType({
24
+ partial_exits: new ListCompositeType(new ContainerType({
25
+ public_key: new ByteVectorType(48),
26
+ signed_exit_message: new ContainerType({
27
+ message: new ContainerType({
28
+ epoch: new UintNumberType(8),
29
+ validator_index: new UintNumberType(8),
30
+ }),
31
+ signature: new ByteVectorType(96),
32
+ }),
33
+ }), 65536),
34
+ share_idx: new UintNumberType(8),
35
+ });
36
+ /**
37
+ * Exit validation and verification class for Obol distributed validators.
38
+ *
39
+ * This class provides functionality to validate and verify voluntary exit signatures
40
+ * for distributed validators in an Obol cluster. It handles both partial exit signatures
41
+ * from individual operators and payload signatures that authorize exit operations.
42
+ *
43
+ * The class supports:
44
+ * - Verification of BLS signatures for partial exit messages
45
+ * - Verification of ECDSA signatures for exit payload authorization
46
+ * - Validation of exit blobs against cluster configuration
47
+ * - Duplicate detection and epoch validation
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const exit = new Exit(1, provider); // Mainnet with provider
52
+ *
53
+ * // Verify a partial exit signature
54
+ * const isValid = await exit.verifyPartialExitSignature(
55
+ * publicShareKey,
56
+ * signedExitMessage,
57
+ * forkVersion,
58
+ * genesisValidatorsRoot
59
+ * );
60
+ *
61
+ * // Validate exit blobs for a cluster
62
+ * const validBlobs = await exit.validateExitBlobs(
63
+ * clusterConfig,
64
+ * exitsPayload,
65
+ * beaconNodeApiUrl,
66
+ * existingBlobData
67
+ * );
68
+ * ```
69
+ */
70
+ export class Exit {
71
+ /**
72
+ * Creates a new Exit instance for validator exit operations.
73
+ *
74
+ * @param chainId - The Ethereum chain ID (e.g., 1 for mainnet, 5 for goerli)
75
+ * @param provider - Optional Ethereum provider for blockchain interactions
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * // For mainnet with a provider
80
+ * const exit = new Exit(1, provider);
81
+ *
82
+ * // For goerli testnet without provider
83
+ * const exit = new Exit(5, null);
84
+ * ```
85
+ */
86
+ constructor(chainId, provider) {
87
+ this.chainId = chainId;
88
+ this.provider = provider;
89
+ }
90
+ /**
91
+ * Safely parse a string integer to number, using BigInt to avoid precision loss
92
+ * for large values beyond JavaScript's safe integer limit (2^53 - 1).
93
+ * Throws an error if the value exceeds the safe range for a 64-bit unsigned integer.
94
+ */
95
+ static safeParseInt(value) {
96
+ const bigIntValue = BigInt(value);
97
+ // Check if value is within the range of a 64-bit unsigned integer
98
+ const MAX_UINT64 = BigInt('0xFFFFFFFFFFFFFFFF');
99
+ if (bigIntValue < 0 || bigIntValue > MAX_UINT64) {
100
+ throw new Error(`Value ${value} is outside the valid range for a 64-bit unsigned integer`);
101
+ }
102
+ // Convert to number - SSZ library should handle values even if they exceed JS safe integer limits
103
+ return Number(bigIntValue);
104
+ }
105
+ static computePartialExitMessageRoot(msg) {
106
+ const sszValue = SSZExitMessageType.defaultValue();
107
+ sszValue.epoch = Exit.safeParseInt(msg.epoch);
108
+ sszValue.validator_index = Exit.safeParseInt(msg.validator_index);
109
+ return Buffer.from(SSZExitMessageType.hashTreeRoot(sszValue).buffer);
110
+ }
111
+ static computeExitPayloadRoot(exits) {
112
+ // Remove sorting since SSZ list ordering guarantees order
113
+ // This eliminates the O(n log n) sort and improves performance
114
+ const sszValue = SSZPartialExitsPayloadType.defaultValue();
115
+ sszValue.partial_exits = exits.partial_exits.map(pe => ({
116
+ public_key: fromHexString(pe.public_key),
117
+ signed_exit_message: {
118
+ message: {
119
+ epoch: Exit.safeParseInt(pe.signed_exit_message.message.epoch),
120
+ validator_index: Exit.safeParseInt(pe.signed_exit_message.message.validator_index),
121
+ },
122
+ signature: fromHexString(pe.signed_exit_message.signature),
123
+ },
124
+ }));
125
+ sszValue.share_idx = exits.share_idx;
126
+ return Buffer.from(SSZPartialExitsPayloadType.hashTreeRoot(sszValue).buffer).toString('hex');
127
+ }
128
+ /**
129
+ * Verifies a partial exit signature from a distributed validator operator.
130
+ *
131
+ * This method validates that a partial exit signature was correctly signed by the
132
+ * operator's share of the distributed validator's private key. It performs BLS
133
+ * signature verification using the appropriate fork version and genesis validators root.
134
+ *
135
+ * @param publicShareKey - The operator's public share key (BLS public key, hex string with or without 0x prefix)
136
+ * @param signedExitMessage - The signed exit message containing the exit details and signature
137
+ * @param forkVersion - The Ethereum fork version (e.g., "0x00000000" for mainnet)
138
+ * @param genesisValidatorsRootString - The genesis validators root for the network (hex string)
139
+ *
140
+ * @returns Promise resolving to true if the signature is valid, false otherwise
141
+ *
142
+ * @throws {Error} When unable to determine the Capella fork version for the given network
143
+ * @throws {Error} When BLS library initialization or verification fails
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * const isValid = await exit.verifyPartialExitSignature(
148
+ * "0x1234...abcd", // operator's public share key
149
+ * {
150
+ * message: { epoch: "12345", validator_index: "67890" },
151
+ * signature: "0xabcd...1234"
152
+ * },
153
+ * "0x00000000", // mainnet fork version
154
+ * "0x4b363db94e286120d76eb905340fdd4e54bfe9f06bf33ff6cf5ad27f511bfe95"
155
+ * );
156
+ * ```
157
+ */
158
+ verifyPartialExitSignature(publicShareKey, signedExitMessage, forkVersion, genesisValidatorsRootString) {
159
+ return __awaiter(this, void 0, void 0, function* () {
160
+ yield init('herumi');
161
+ const capellaForkVersionString = yield getCapellaFork(forkVersion);
162
+ if (!capellaForkVersionString) {
163
+ throw new Error(`Could not determine Capella fork version for base fork: ${forkVersion}`);
164
+ }
165
+ const partialExitMessageBuffer = Exit.computePartialExitMessageRoot(signedExitMessage.message);
166
+ const exitDomain = computeDomain(fromHexString(DOMAIN_VOLUNTARY_EXIT), capellaForkVersionString, fromHexString(genesisValidatorsRootString));
167
+ const messageSigningRoot = signingRoot(exitDomain, partialExitMessageBuffer);
168
+ return verify(fromHexString(publicShareKey), messageSigningRoot, fromHexString(signedExitMessage.signature));
169
+ });
170
+ }
171
+ /**
172
+ * Verifies the exit payload signature using the operator's ENR.
173
+ *
174
+ * This method validates that an exit payload was signed by the correct operator
175
+ * using ECDSA signature verification. The signature is verified against the
176
+ * operator's public key extracted from their ENR (Ethereum Node Record).
177
+ *
178
+ * @param enrString - The operator's ENR string containing their identity and public key
179
+ * @param exitsPayload - The exit validation payload containing partial exits and operator signature
180
+ *
181
+ * @returns Promise resolving to true if the payload signature is valid, false otherwise
182
+ *
183
+ * @throws {Error} When the ENR string is invalid or cannot be decoded
184
+ * @throws {Error} When the signature format is invalid (must be 130 hex characters)
185
+ * @throws {Error} When signature verification encounters an error
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * const isValid = await exit.verifyExitPayloadSignature(
190
+ * "enr:-LK4QFo_n0dUm4PKejSOXf8JkSWq5EINV0XhG1zY00d...", // operator ENR
191
+ * {
192
+ * partial_exits: [exitBlob1, exitBlob2],
193
+ * share_idx: 1,
194
+ * signature: "0x1234...abcd" // ECDSA signature (130 hex chars)
195
+ * }
196
+ * );
197
+ * ```
198
+ */
199
+ verifyExitPayloadSignature(enrString, exitsPayload) {
200
+ var _a, _b;
201
+ return __awaiter(this, void 0, void 0, function* () {
202
+ const partialExitsDtoHashRoot = Exit.computeExitPayloadRoot(exitsPayload);
203
+ const ec = new elliptic.ec('secp256k1');
204
+ let pubKeyHex;
205
+ try {
206
+ pubKeyHex = ENR.decodeTxt(enrString).publicKey.toString('hex');
207
+ }
208
+ catch (e) {
209
+ throw new Error(`Invalid ENR string: ${enrString}. Error: ${(_a = e.message) !== null && _a !== void 0 ? _a : String(e)}`);
210
+ }
211
+ const sigHex = exitsPayload.signature.startsWith('0x')
212
+ ? exitsPayload.signature.substring(2)
213
+ : exitsPayload.signature;
214
+ if (sigHex.length !== 130) {
215
+ throw new Error(`Invalid signature length. Expected 130 hex chars (r + s), got ${sigHex.length}`);
216
+ }
217
+ const r = sigHex.slice(0, 64);
218
+ const s = sigHex.slice(64, 128);
219
+ const enrSignature = { r, s };
220
+ try {
221
+ return ec
222
+ .keyFromPublic(pubKeyHex, 'hex')
223
+ .verify(partialExitsDtoHashRoot, enrSignature);
224
+ }
225
+ catch (e) {
226
+ throw new Error(`Signature verification failed: ${(_b = e.message) !== null && _b !== void 0 ? _b : String(e)}`);
227
+ }
228
+ });
229
+ }
230
+ validateOperatorAndPayload(clusterConfig, exitsPayload) {
231
+ return __awaiter(this, void 0, void 0, function* () {
232
+ const operatorIndex = exitsPayload.share_idx - 1;
233
+ if (operatorIndex < 0 ||
234
+ operatorIndex >= clusterConfig.definition.operators.length) {
235
+ throw new Error(`Invalid share_idx ${exitsPayload.share_idx} for ${clusterConfig.definition.operators.length} operators.`);
236
+ }
237
+ const operatorEnr = clusterConfig.definition.operators[operatorIndex].enr;
238
+ const isPayloadSignatureValid = yield this.verifyExitPayloadSignature(operatorEnr, exitsPayload);
239
+ if (!isPayloadSignatureValid) {
240
+ throw new Error('Incorrect payload signature for partial exits.');
241
+ }
242
+ return operatorEnr;
243
+ });
244
+ }
245
+ getNetworkParameters(forkVersion, beaconNodeApiUrl) {
246
+ return __awaiter(this, void 0, void 0, function* () {
247
+ const genesisValidatorsRootString = yield getGenesisValidatorsRoot(beaconNodeApiUrl);
248
+ if (!genesisValidatorsRootString) {
249
+ throw new Error('Could not retrieve genesis validators root.');
250
+ }
251
+ const capellaForkVersionString = yield getCapellaFork(forkVersion);
252
+ if (!capellaForkVersionString) {
253
+ throw new Error(`Unsupported network: Could not determine Capella fork for ${forkVersion}`);
254
+ }
255
+ return {
256
+ genesisValidatorsRoot: genesisValidatorsRootString,
257
+ capellaForkVersion: capellaForkVersionString,
258
+ };
259
+ });
260
+ }
261
+ findValidatorInCluster(clusterConfig, publicKey, operatorIndex) {
262
+ const validatorInCluster = clusterConfig.distributed_validators.find(dv => (dv.distributed_public_key.startsWith('0x')
263
+ ? dv.distributed_public_key
264
+ : '0x' + dv.distributed_public_key).toLowerCase() ===
265
+ (publicKey.startsWith('0x')
266
+ ? publicKey
267
+ : '0x' + publicKey).toLowerCase());
268
+ if (!validatorInCluster) {
269
+ throw new Error(`Public key ${publicKey} not found in the cluster's distributed validators.`);
270
+ }
271
+ const publicShareForOperator = validatorInCluster.public_shares[operatorIndex];
272
+ if (!publicShareForOperator) {
273
+ throw new Error(`Public share for operator index ${operatorIndex} not found for validator ${publicKey}`);
274
+ }
275
+ return {
276
+ validator: validatorInCluster,
277
+ publicShare: publicShareForOperator,
278
+ };
279
+ }
280
+ validateExistingBlobData(exitBlob, existingBlob, operatorIndex) {
281
+ var _a, _b, _c;
282
+ return __awaiter(this, void 0, void 0, function* () {
283
+ if (!existingBlob) {
284
+ return false;
285
+ }
286
+ // Check if existing blob data is for this public key
287
+ const normalizeKey = (key) => (key.startsWith('0x') ? key : '0x' + key).toLowerCase();
288
+ if (normalizeKey(existingBlob.public_key) !==
289
+ normalizeKey(exitBlob.public_key)) {
290
+ return false; // Existing blob data is for a different validator
291
+ }
292
+ if (existingBlob.validator_index !==
293
+ exitBlob.signed_exit_message.message.validator_index) {
294
+ throw new Error(`Validator index mismatch for already processed exit for public key ${exitBlob.public_key}. Expected ${existingBlob.validator_index}, got ${exitBlob.signed_exit_message.message.validator_index}.`);
295
+ }
296
+ const currentEpoch = Exit.safeParseInt(exitBlob.signed_exit_message.message.epoch);
297
+ const existingEpoch = Exit.safeParseInt(existingBlob.epoch);
298
+ if (currentEpoch < existingEpoch) {
299
+ throw new Error(`New exit epoch ${currentEpoch} is not greater than existing exit epoch ${existingEpoch} for validator ${exitBlob.public_key}.`);
300
+ }
301
+ else if (currentEpoch === existingEpoch) {
302
+ const operatorShareIndexString = String(operatorIndex);
303
+ if (((_c = (_b = (_a = existingBlob.shares_exit_data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b[operatorShareIndexString]) === null || _c === void 0 ? void 0 : _c.partial_exit_signature) &&
304
+ existingBlob.shares_exit_data[0][operatorShareIndexString]
305
+ .partial_exit_signature !== exitBlob.signed_exit_message.signature) {
306
+ throw new Error(`Signature mismatch for validator ${exitBlob.public_key}, operator index ${operatorIndex} at epoch ${currentEpoch}. Received different signature than existing.`);
307
+ }
308
+ return true; // Already processed
309
+ }
310
+ return false;
311
+ });
312
+ }
313
+ processExitBlob(exitBlob, clusterConfig, operatorIndex, genesisValidatorsRoot, existingBlobData) {
314
+ return __awaiter(this, void 0, void 0, function* () {
315
+ const { publicShare } = this.findValidatorInCluster(clusterConfig, exitBlob.public_key, operatorIndex);
316
+ const alreadyProcessed = yield this.validateExistingBlobData(exitBlob, existingBlobData, operatorIndex);
317
+ if (alreadyProcessed) {
318
+ return null;
319
+ }
320
+ const isPartialSignatureValid = yield this.verifyPartialExitSignature(publicShare, exitBlob.signed_exit_message, clusterConfig.definition.fork_version, genesisValidatorsRoot);
321
+ if (!isPartialSignatureValid) {
322
+ throw new Error(`Invalid partial exit signature for validator ${exitBlob.public_key} by operator index ${operatorIndex}.`);
323
+ }
324
+ return exitBlob;
325
+ });
326
+ }
327
+ /**
328
+ * Validates exit blobs against cluster configuration and existing data.
329
+ *
330
+ * This method performs comprehensive validation of exit blobs including:
331
+ * - Operator authorization and payload signature verification
332
+ * - Network parameter validation (genesis root, fork version)
333
+ * - Public key validation against cluster configuration
334
+ * - Partial signature verification for each exit blob
335
+ * - Duplicate detection and epoch progression validation
336
+ * - Signature consistency checks for existing exits
337
+ *
338
+ * @param clusterConfig - The cluster configuration containing operators and distributed validators
339
+ * @param exitsPayload - The exit validation payload with partial exits and operator info
340
+ * @param beaconNodeApiUrl - The beacon node API URL for network parameter retrieval
341
+ * @param existingBlobData - Existing exit blob data for duplicate detection, or null if none exists
342
+ *
343
+ * @returns Promise resolving to an array of validated, non-duplicate exit blobs
344
+ *
345
+ * @throws {Error} When share_idx is invalid or out of bounds for the cluster operators
346
+ * @throws {Error} When payload signature verification fails
347
+ * @throws {Error} When network parameters cannot be retrieved or are invalid
348
+ * @throws {Error} When a public key is not found in the cluster's distributed validators
349
+ * @throws {Error} When a partial exit signature is invalid
350
+ * @throws {Error} When exit epoch validation fails (new epoch not greater than existing)
351
+ * @throws {Error} When validator index mismatches with existing data
352
+ * @throws {Error} When signature mismatches for the same epoch and operator
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * const validExitBlobs = await exit.validateExitBlobs(
357
+ * {
358
+ * definition: {
359
+ * operators: [{ enr: "enr:-LK4Q..." }],
360
+ * fork_version: "0x00000000",
361
+ * threshold: 1
362
+ * },
363
+ * distributed_validators: [{
364
+ * distributed_public_key: "0x1234...abcd",
365
+ * public_shares: ["0x5678...efgh"]
366
+ * }]
367
+ * },
368
+ * {
369
+ * partial_exits: [exitBlob],
370
+ * share_idx: 1,
371
+ * signature: "0x1234...abcd"
372
+ * },
373
+ * "http://localhost:5052",
374
+ * existingBlobData // or null for new exits
375
+ * );
376
+ * ```
377
+ */
378
+ validateExitBlobs(clusterConfig, exitsPayload, beaconNodeApiUrl, existingBlobData) {
379
+ return __awaiter(this, void 0, void 0, function* () {
380
+ yield this.validateOperatorAndPayload(clusterConfig, exitsPayload);
381
+ const { genesisValidatorsRoot } = yield this.getNetworkParameters(clusterConfig.definition.fork_version, beaconNodeApiUrl);
382
+ const operatorIndex = exitsPayload.share_idx - 1;
383
+ const validNonDuplicateBlobs = [];
384
+ for (const currentExitBlob of exitsPayload.partial_exits) {
385
+ const processedBlob = yield this.processExitBlob(currentExitBlob, clusterConfig, operatorIndex, genesisValidatorsRoot, existingBlobData);
386
+ if (processedBlob) {
387
+ validNonDuplicateBlobs.push(processedBlob);
388
+ }
389
+ }
390
+ return validNonDuplicateBlobs;
391
+ });
392
+ }
393
+ /**
394
+ * Recombines exit blobs into a single exit blob.
395
+ *
396
+ * This method aggregates partial exit signatures from multiple operators into a single exit blob.
397
+ * It ensures that the signatures are properly ordered and aggregated according to the operator indices.
398
+ *
399
+ * @param exitBlob - The existing exit blob data containing partial exit signatures
400
+ *
401
+ * @returns Promise resolving to a single exit blob with aggregated signatures
402
+ *
403
+ * @throws {Error} When no valid signatures are found for aggregation
404
+ * @throws {Error} When signature length is invalid
405
+ * @throws {Error} When signature parsing fails
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * const aggregatedExitBlob = await exit.recombineExitBlobs(existingBlobData);
410
+ * ```
411
+ */
412
+ recombineExitBlobs(exitBlob) {
413
+ return __awaiter(this, void 0, void 0, function* () {
414
+ yield init('herumi');
415
+ // Map to store signatures by their share index (matching Go's map[int]tbls.Signature)
416
+ const signaturesByIndex = new Map();
417
+ // Extract signatures from shares_exit_data (equivalent to er.Signatures in Go)
418
+ if (!exitBlob.shares_exit_data || exitBlob.shares_exit_data.length === 0) {
419
+ throw new Error('No shares exit data available for aggregation');
420
+ }
421
+ const signaturesMap = exitBlob.shares_exit_data[0] || {};
422
+ for (const [sigIdxStr, sigData] of Object.entries(signaturesMap)) {
423
+ const sigStr = sigData.partial_exit_signature;
424
+ if (!sigStr || sigStr.length === 0) {
425
+ // ignore, the associated share index didn't push a partial signature yet
426
+ continue;
427
+ }
428
+ if (sigStr.length < 2) {
429
+ throw new Error(`Signature string has invalid size: ${sigStr.length}`);
430
+ }
431
+ // Remove 0x prefix and ensure it's 96 bytes (192 hex chars)
432
+ const cleanSigStr = sigStr.startsWith('0x')
433
+ ? sigStr.substring(2)
434
+ : sigStr;
435
+ if (cleanSigStr.length !== 192) {
436
+ throw new Error(`Invalid signature length. Expected 192 hex chars (96 bytes), got ${cleanSigStr.length}`);
437
+ }
438
+ try {
439
+ const sigBytes = fromHexString(cleanSigStr);
440
+ // Convert string index to number and add 1 (matching Go's sigIdx+1)
441
+ const sigIdx = parseInt(sigIdxStr, 10);
442
+ signaturesByIndex.set(sigIdx + 1, sigBytes);
443
+ }
444
+ catch (err) {
445
+ throw new Error(`Invalid partial signature: ${String(err)}`);
446
+ }
447
+ }
448
+ if (signaturesByIndex.size === 0) {
449
+ throw new Error('No valid signatures found for aggregation');
450
+ }
451
+ // Sort by index and extract signatures in correct order
452
+ const sortedIndices = Array.from(signaturesByIndex.keys()).sort((a, b) => a - b);
453
+ const rawSignatures = sortedIndices.map(idx => {
454
+ const signature = signaturesByIndex.get(idx);
455
+ if (signature === undefined) {
456
+ throw new Error(`Missing signature for index ${idx}`);
457
+ }
458
+ return signature;
459
+ });
460
+ // Aggregate signatures (equivalent to tbls.ThresholdAggregate in Go)
461
+ // Note: @chainsafe/bls doesn't have explicit threshold aggregation, but ordering should be preserved
462
+ const fullSig = aggregateSignatures(rawSignatures);
463
+ return {
464
+ public_key: exitBlob.public_key,
465
+ signed_exit_message: {
466
+ message: {
467
+ epoch: exitBlob.epoch,
468
+ validator_index: exitBlob.validator_index,
469
+ },
470
+ signature: '0x' + Buffer.from(fullSig).toString('hex'),
471
+ },
472
+ };
473
+ });
474
+ }
475
+ }
@@ -0,0 +1,81 @@
1
+ import { ContainerType, ByteVectorType, fromHexString } from '@chainsafe/ssz';
2
+ // From obol-api/src/verification/common.ts
3
+ export const GENESIS_VALIDATOR_ROOT_HEX_STRING = '0x0000000000000000000000000000000000000000000000000000000000000000'; // Added 0x prefix
4
+ const ForkDataType = new ContainerType({
5
+ currentVersion: new ByteVectorType(4),
6
+ genesisValidatorsRoot: new ByteVectorType(32),
7
+ });
8
+ const SigningRootType = new ContainerType({
9
+ objectRoot: new ByteVectorType(32),
10
+ domain: new ByteVectorType(32),
11
+ });
12
+ /**
13
+ * https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_fork_data_root
14
+ * @param currentVersion - Uint8Array of the current fork version.
15
+ * @param genesisValidatorsRoot - Uint8Array of the genesis validators root.
16
+ * @returns Uint8Array - The 32-byte fork data root.
17
+ */
18
+ function computeForkDataRoot(currentVersion, genesisValidatorsRoot) {
19
+ const forkDataVal = ForkDataType.defaultValue();
20
+ forkDataVal.currentVersion = currentVersion;
21
+ forkDataVal.genesisValidatorsRoot = genesisValidatorsRoot;
22
+ return Buffer.from(ForkDataType.hashTreeRoot(forkDataVal).buffer);
23
+ }
24
+ /**
25
+ * Computes the domain for a given domain type, fork version, and genesis state.
26
+ * https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_domain
27
+ * @param domainType - Uint8Array representing the domain type (e.g., DOMAIN_VOLUNTARY_EXIT).
28
+ * @param forkVersionString - Hex string of the fork version (e.g., Capella fork version).
29
+ * @param genesisValidatorsRootOverride - Optional Uint8Array to override the default genesis validators root.
30
+ * @returns Uint8Array - The 32-byte domain.
31
+ */
32
+ export function computeDomain(domainType, // Should be 4 bytes
33
+ forkVersionString, // Hex string, e.g., '0x03000000'
34
+ genesisValidatorsRootOverride) {
35
+ const forkVersionBytes = fromHexString(forkVersionString.substring(2, forkVersionString.length));
36
+ if (forkVersionBytes.length !== 4) {
37
+ throw new Error('Fork version must be 4 bytes');
38
+ }
39
+ if (domainType.length !== 4) {
40
+ throw new Error('Domain type must be 4 bytes');
41
+ }
42
+ const actualGenesisValidatorsRoot = genesisValidatorsRootOverride !== null && genesisValidatorsRootOverride !== void 0 ? genesisValidatorsRootOverride : fromHexString(GENESIS_VALIDATOR_ROOT_HEX_STRING.substring(2));
43
+ if (actualGenesisValidatorsRoot.length !== 32) {
44
+ throw new Error('genesisValidatorsRoot must be 32 bytes');
45
+ }
46
+ const forkDataRoot = computeForkDataRoot(forkVersionBytes, actualGenesisValidatorsRoot);
47
+ const domain = new Uint8Array(32);
48
+ domain.set(domainType);
49
+ domain.set(forkDataRoot.subarray(0, 28), 4); // Set the remaining 28 bytes from forkDataRoot
50
+ return domain;
51
+ }
52
+ /**
53
+ * Computes the signing root for an SSZ object and a domain.
54
+ * https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_signing_root
55
+ * @param sszObjectRoot - Uint8Array of the hash tree root of the SSZ object.
56
+ * @param domain - Uint8Array of the domain.
57
+ * @returns Uint8Array - The 32-byte signing root.
58
+ */
59
+ function computeSigningRoot(sszObjectRoot, // Should be 32 bytes
60
+ domain) {
61
+ if (sszObjectRoot.length !== 32) {
62
+ throw new Error('SSZ object root must be 32 bytes');
63
+ }
64
+ if (domain.length !== 32) {
65
+ throw new Error('Domain must be 32 bytes');
66
+ }
67
+ const val = SigningRootType.defaultValue();
68
+ val.objectRoot = sszObjectRoot;
69
+ val.domain = domain;
70
+ return Buffer.from(SigningRootType.hashTreeRoot(val).buffer);
71
+ }
72
+ /**
73
+ * Convenience wrapper for computeSigningRoot.
74
+ * @param domain - Uint8Array of the domain.
75
+ * @param messageBuffer - Buffer of the message (SSZ object root).
76
+ * @returns Uint8Array - The signing root.
77
+ */
78
+ export function signingRoot(domain, messageBuffer) {
79
+ const sszObjectRootU8 = Uint8Array.from(messageBuffer);
80
+ return computeSigningRoot(sszObjectRootU8, domain);
81
+ }
@@ -8,7 +8,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { Contract } from 'ethers';
11
- import { MerkleDistributorABI } from './abi/MerkleDistributorWithDeadline';
11
+ import { MerkleDistributorABI } from '../abi/MerkleDistributorWithDeadline';
12
12
  export const claimIncentivesFromMerkleDistributor = (incentivesData) => __awaiter(void 0, void 0, void 0, function* () {
13
13
  try {
14
14
  const contract = new Contract(incentivesData.contractAddress, MerkleDistributorABI.abi, incentivesData.signer);
@@ -7,10 +7,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { isContractAvailable } from './utils';
11
- import { FORK_NAMES, } from './types';
10
+ import { isContractAvailable } from '../utils';
11
+ import { FORK_NAMES, } from '../types';
12
12
  import { claimIncentivesFromMerkleDistributor, isClaimedFromMerkleDistributor, } from './incentiveHelpers';
13
- import { DEFAULT_BASE_VERSION } from './constants';
13
+ import { DEFAULT_BASE_VERSION } from '../constants';
14
14
  /**
15
15
  * Incentives can be used for fetching and claiming Obol incentives.
16
16
  * @class
@@ -14,15 +14,17 @@ import { ConflictError } from './errors.js';
14
14
  import { clusterConfigOrDefinitionHash } from './verification/common.js';
15
15
  import { validatePayload } from './ajv.js';
16
16
  import { definitionSchema, operatorPayloadSchema, rewardsSplitterPayloadSchema, totalSplitterPayloadSchema, } from './schema.js';
17
- import { deploySplitterContract, formatSplitRecipients, handleDeployOWRAndSplitter, predictSplitterAddress, getOWRTranches, } from './splitHelpers.js';
17
+ import { deploySplitterContract, formatSplitRecipients, handleDeployOWRAndSplitter, predictSplitterAddress, getOWRTranches, } from './splits/splitHelpers.js';
18
18
  import { isContractAvailable } from './utils.js';
19
- import { Incentives } from './incentives.js';
19
+ import { Incentives } from './incentives/incentives.js';
20
+ import { Exit } from './exits/exit.js';
20
21
  export * from './types.js';
21
22
  export * from './services.js';
22
23
  export * from './verification/signature-validator.js';
23
24
  export * from './verification/common.js';
24
25
  export * from './constants.js';
25
- export { Incentives } from './incentives.js';
26
+ export { Incentives } from './incentives/incentives.js';
27
+ export { Exit } from './exits/exit.js';
26
28
  /**
27
29
  * Obol sdk Client can be used for creating, managing and activating distributed validators.
28
30
  */
@@ -44,6 +46,7 @@ export class Client extends Base {
44
46
  this.provider =
45
47
  provider !== null && provider !== void 0 ? provider : (signer && 'provider' in signer ? signer.provider : undefined);
46
48
  this.incentives = new Incentives(this.signer, this.chainId, this.request.bind(this), this.provider);
49
+ this.exit = new Exit(this.chainId, this.provider);
47
50
  }
48
51
  /**
49
52
  * Accepts Obol terms and conditions to be able to create or update data.
@@ -357,4 +360,18 @@ export class Client extends Base {
357
360
  return lock;
358
361
  });
359
362
  }
363
+ /**
364
+ * @param lockHash - The configuration hash in cluster-definition
365
+ * @returns {Promise<ClusterLock>} The matched cluster details (lock) from DB
366
+ * @throws On not found cluster definition or lock.
367
+ *
368
+ */
369
+ getClusterLockByHash(lockHash) {
370
+ return __awaiter(this, void 0, void 0, function* () {
371
+ const lock = yield this.request(`/${DEFAULT_BASE_VERSION}/lock/${lockHash}`, {
372
+ method: 'GET',
373
+ });
374
+ return lock;
375
+ });
376
+ }
360
377
  }