@obolnetwork/obol-sdk 2.5.1 → 2.6.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 +420 -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 +328 -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 +393 -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 +303 -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 +180 -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 +98 -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 +564 -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 +123 -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,303 @@
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 { Exit } from '../../src/exits/exit';
11
+ import * as ethUtils from '../../src/exits/ethUtils';
12
+ import * as bls from '@chainsafe/bls';
13
+ import { ENR } from '@chainsafe/discv5';
14
+ import * as elliptic from 'elliptic';
15
+ import { CAPELLA_FORK_MAPPING } from '../../src/constants';
16
+ import { fromHexString } from '@chainsafe/ssz';
17
+ import * as verificationHelpers from '../../src/exits/verificationHelpers';
18
+ // --- Mocks ---
19
+ jest.mock('../../src/exits/ethUtils');
20
+ jest.mock('@chainsafe/bls', () => {
21
+ const actual = jest.requireActual('@chainsafe/bls');
22
+ return Object.assign(Object.assign({ __esModule: true }, actual), { init: jest.fn(), verify: jest.fn() });
23
+ });
24
+ // ENR and elliptic will be spied on, not fully mocked at module level for more flexibility
25
+ const mockedEthUtils = ethUtils;
26
+ const mockedBls = bls;
27
+ // --- Test Data ---
28
+ const MAINNET_BASE_FORK_VERSION = '0x00000000';
29
+ const MAINNET_CAPELLA_FORK_VERSION = CAPELLA_FORK_MAPPING[MAINNET_BASE_FORK_VERSION];
30
+ const MOCK_GENESIS_ROOT = '0x0000000000000000000000000000000000000000000000000000000000000001';
31
+ const MOCK_BEACON_API_URL = 'http://localhost:5052';
32
+ const mockOperatorEnr = 'enr:-LK4QFo_n0dUm4PKejSOXf8JkSWq5EINV0XhG1zY00d22QpYdyxSAyQNsGkYQyKR5Ohe2kEkmS0nS31tuqVfXDNf_vEAhGV0aAgQD___2iXChwcEChAgAAAAADg__________g2V0aMfLCGgohEAcNlBpLdCgAAAQAdIaENsZS0CAAAABAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAAIAAAAAAAAAYAAAAAAAAAAAAAAAAAAAIQA___________gmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKwrO7sVJzX4B2vW1bTqWCpGA93R2aZqa2ZCrqSrh8CYN1ZHCCIyg';
33
+ const mockOperatorPublicKeyHex = '03ca0aceeec549cd7f8076bd6d5b4ea582a4603ddd1d9a66a6b6642aeaa4ae1f09';
34
+ const mockExitMessage = {
35
+ epoch: '1',
36
+ validator_index: '10',
37
+ };
38
+ const mockSignedExitMessage = {
39
+ message: mockExitMessage,
40
+ signature: '0x' + 'ab'.repeat(96),
41
+ };
42
+ const mockExitBlob = {
43
+ public_key: '0x' + 'cd'.repeat(48),
44
+ signed_exit_message: mockSignedExitMessage,
45
+ };
46
+ const mockExitPayload = {
47
+ partial_exits: [mockExitBlob],
48
+ share_idx: 1,
49
+ signature: '0x' + 'ef'.repeat(65),
50
+ };
51
+ // Make mockClusterConfig directly ExitClusterConfig for easier use in tests
52
+ const mockClusterConfig = {
53
+ definition: {
54
+ operators: [{ enr: mockOperatorEnr }],
55
+ fork_version: MAINNET_BASE_FORK_VERSION,
56
+ threshold: 1,
57
+ },
58
+ distributed_validators: [
59
+ {
60
+ distributed_public_key: mockExitBlob.public_key,
61
+ public_shares: ['0x' + 'aa'.repeat(48)],
62
+ },
63
+ ],
64
+ };
65
+ const mockExistingBlobData = {
66
+ public_key: mockExitBlob.public_key,
67
+ epoch: mockExitMessage.epoch,
68
+ validator_index: mockExitMessage.validator_index,
69
+ shares_exit_data: [],
70
+ };
71
+ describe('exit', () => {
72
+ let enrDecodeTxtSpy;
73
+ let ecVerifySpy;
74
+ let keyFromPublicSpy;
75
+ let exit;
76
+ beforeEach(() => {
77
+ jest.resetAllMocks();
78
+ exit = new Exit(1, null);
79
+ mockedBls.init.mockResolvedValue(undefined);
80
+ mockedBls.verify.mockReturnValue(true);
81
+ mockedEthUtils.getCapellaFork.mockResolvedValue(MAINNET_CAPELLA_FORK_VERSION);
82
+ mockedEthUtils.getGenesisValidatorsRoot.mockResolvedValue(MOCK_GENESIS_ROOT);
83
+ const mockDecodedENR = {
84
+ publicKey: Buffer.from(mockOperatorPublicKeyHex, 'hex'),
85
+ };
86
+ enrDecodeTxtSpy = jest
87
+ .spyOn(ENR, 'decodeTxt')
88
+ .mockReturnValue(mockDecodedENR);
89
+ ecVerifySpy = jest.fn().mockReturnValue(true);
90
+ keyFromPublicSpy = jest.spyOn(elliptic.ec.prototype, 'keyFromPublic');
91
+ keyFromPublicSpy.mockImplementation(function () {
92
+ return { verify: ecVerifySpy };
93
+ });
94
+ });
95
+ afterEach(() => {
96
+ if (enrDecodeTxtSpy)
97
+ enrDecodeTxtSpy.mockRestore();
98
+ jest.restoreAllMocks();
99
+ });
100
+ describe('verifyPartialExitSignature', () => {
101
+ const publicShareKey = mockClusterConfig.distributed_validators[0].public_shares[0];
102
+ it('should return true for a valid signature', () => __awaiter(void 0, void 0, void 0, function* () {
103
+ const isValid = yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
104
+ expect(isValid).toBe(true);
105
+ expect(mockedBls.init).toHaveBeenCalledWith('herumi');
106
+ expect(mockedBls.verify).toHaveBeenCalled();
107
+ expect(mockedEthUtils.getCapellaFork).toHaveBeenCalledWith(MAINNET_BASE_FORK_VERSION);
108
+ }));
109
+ it('should return false if BLS verification fails', () => __awaiter(void 0, void 0, void 0, function* () {
110
+ mockedBls.verify.mockReturnValue(false);
111
+ const isValid = yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
112
+ expect(isValid).toBe(false);
113
+ }));
114
+ it('should throw if getCapellaFork returns null', () => __awaiter(void 0, void 0, void 0, function* () {
115
+ mockedEthUtils.getCapellaFork.mockResolvedValue(null);
116
+ yield expect(exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT)).rejects.toThrow('Could not determine Capella fork version');
117
+ }));
118
+ it('should call computeDomain and signingRoot with correct parameters', () => __awaiter(void 0, void 0, void 0, function* () {
119
+ const computeDomainSpy = jest.spyOn(verificationHelpers, 'computeDomain');
120
+ const signingRootSpy = jest.spyOn(verificationHelpers, 'signingRoot');
121
+ yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
122
+ expect(computeDomainSpy).toHaveBeenCalledWith(fromHexString('04000000'), MAINNET_CAPELLA_FORK_VERSION, fromHexString(MOCK_GENESIS_ROOT.substring(2)));
123
+ expect(signingRootSpy).toHaveBeenCalled();
124
+ computeDomainSpy.mockRestore();
125
+ signingRootSpy.mockRestore();
126
+ }));
127
+ });
128
+ describe('verifyExitPayloadSignature', () => {
129
+ it('should return true for a valid ECDSA signature', () => __awaiter(void 0, void 0, void 0, function* () {
130
+ const isValid = yield exit.verifyExitPayloadSignature(mockOperatorEnr, mockExitPayload);
131
+ expect(isValid).toBe(true);
132
+ expect(enrDecodeTxtSpy).toHaveBeenCalledWith(mockOperatorEnr);
133
+ expect(ecVerifySpy).toHaveBeenCalled();
134
+ }));
135
+ it('should return false if ECDSA verification fails', () => __awaiter(void 0, void 0, void 0, function* () {
136
+ ecVerifySpy.mockReturnValue(false);
137
+ const isValid = yield exit.verifyExitPayloadSignature(mockOperatorEnr, mockExitPayload);
138
+ expect(isValid).toBe(false);
139
+ }));
140
+ it('should throw if ENR is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
141
+ enrDecodeTxtSpy.mockImplementation(() => {
142
+ throw new Error('Invalid ENR');
143
+ });
144
+ yield expect(exit.verifyExitPayloadSignature('invalid-enr', mockExitPayload)).rejects.toThrow('Invalid ENR string');
145
+ }));
146
+ it('should throw if signature hex is not 128 characters (excluding 0x)', () => __awaiter(void 0, void 0, void 0, function* () {
147
+ const payloadWithInvalidSig = Object.assign(Object.assign({}, mockExitPayload), { signature: '0x123456' });
148
+ yield expect(exit.verifyExitPayloadSignature(mockOperatorEnr, payloadWithInvalidSig)).rejects.toThrow('Invalid signature length');
149
+ }));
150
+ });
151
+ describe('validateExitBlobs', () => {
152
+ it('should successfully validate a new, valid exit blob', () => __awaiter(void 0, void 0, void 0, function* () {
153
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, null);
154
+ expect(result).toEqual([mockExitBlob]);
155
+ expect(ecVerifySpy).toHaveBeenCalled(); // Called by internal verifyExitPayloadSignature
156
+ expect(mockedBls.verify).toHaveBeenCalled(); // Called by internal verifyPartialExitSignature
157
+ }));
158
+ it('should throw if operatorIndex (from share_idx) is out of bounds', () => __awaiter(void 0, void 0, void 0, function* () {
159
+ const invalidPayload = Object.assign(Object.assign({}, mockExitPayload), { share_idx: 0 });
160
+ yield expect(exit.validateExitBlobs(mockClusterConfig, invalidPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Invalid share_idx');
161
+ const invalidPayload2 = Object.assign(Object.assign({}, mockExitPayload), { share_idx: mockClusterConfig.definition.operators.length + 1 });
162
+ yield expect(exit.validateExitBlobs(mockClusterConfig, invalidPayload2, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Invalid share_idx');
163
+ }));
164
+ it('should throw if payload signature is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
165
+ ecVerifySpy.mockReturnValue(false);
166
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Incorrect payload signature');
167
+ }));
168
+ it('should throw if getGenesisValidatorsRoot returns null', () => __awaiter(void 0, void 0, void 0, function* () {
169
+ mockedEthUtils.getGenesisValidatorsRoot.mockResolvedValue(null);
170
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Could not retrieve genesis validators root');
171
+ }));
172
+ it('should throw if getCapellaFork returns null (unsupported network)', () => __awaiter(void 0, void 0, void 0, function* () {
173
+ mockedEthUtils.getCapellaFork.mockResolvedValue(null);
174
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Unsupported network: Could not determine Capella fork');
175
+ }));
176
+ it('should throw if a public key in an exit blob is not found in cluster config', () => __awaiter(void 0, void 0, void 0, function* () {
177
+ const blobWithUnknownKey = Object.assign(Object.assign({}, mockExitBlob), { public_key: '0x' + 'deadbeef'.repeat(12) });
178
+ const payloadWithUnknownKey = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithUnknownKey] });
179
+ yield expect(exit.validateExitBlobs(mockClusterConfig, payloadWithUnknownKey, MOCK_BEACON_API_URL, null)).rejects.toThrow("Public key 0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef not found in the cluster's distributed validators.");
180
+ }));
181
+ it('should throw if a partial exit signature is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
182
+ mockedBls.verify.mockReturnValue(false);
183
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, null)).rejects.toThrow('Invalid partial exit signature for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd by operator index 0.');
184
+ }));
185
+ it('should return an empty array if an exit blob has already been processed (epoch match)', () => __awaiter(void 0, void 0, void 0, function* () {
186
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData);
187
+ expect(result).toEqual([]);
188
+ }));
189
+ it('should throw if an exit blob has been processed with a different validator index', () => __awaiter(void 0, void 0, void 0, function* () {
190
+ const existingBlobWithDifferentIndex = {
191
+ public_key: mockExitBlob.public_key,
192
+ epoch: mockExitMessage.epoch,
193
+ validator_index: (parseInt(mockExitMessage.validator_index, 10) + 1).toString(), // Different index
194
+ shares_exit_data: [],
195
+ };
196
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithDifferentIndex)).rejects.toThrow('Validator index mismatch for already processed exit for public key 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd. Expected 11, got 10.');
197
+ }));
198
+ it('should throw if an exit blob has been processed with a higher epoch', () => __awaiter(void 0, void 0, void 0, function* () {
199
+ const existingBlobWithHigherEpoch = {
200
+ public_key: mockExitBlob.public_key,
201
+ epoch: (parseInt(mockExitMessage.epoch, 10) + 1).toString(), // Existing epoch is HIGHER (e.g. 2)
202
+ validator_index: mockExitMessage.validator_index,
203
+ shares_exit_data: [],
204
+ };
205
+ // currentExitBlob (from mockExitPayload) has mockExitMessage.epoch (e.g. '1')
206
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithHigherEpoch)).rejects.toThrow('New exit epoch 1 is not greater than existing exit epoch 2 for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd.');
207
+ }));
208
+ it('should successfully validate if an exit blob has been processed with a lower epoch', () => __awaiter(void 0, void 0, void 0, function* () {
209
+ const existingBlobWithLowerEpoch = {
210
+ public_key: mockExitBlob.public_key,
211
+ epoch: (parseInt(mockExitMessage.epoch, 10) - 1).toString(),
212
+ validator_index: mockExitMessage.validator_index,
213
+ shares_exit_data: [],
214
+ };
215
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithLowerEpoch);
216
+ expect(result).toEqual([mockExitBlob]);
217
+ }));
218
+ it('should throw on signature mismatch for existing blob with same epoch', () => __awaiter(void 0, void 0, void 0, function* () {
219
+ const operatorIndex = 0;
220
+ const operatorShareIndexString = String(operatorIndex);
221
+ const existingBlobWithDifferentSignature = {
222
+ public_key: mockExitBlob.public_key,
223
+ epoch: mockExitMessage.epoch,
224
+ validator_index: mockExitMessage.validator_index,
225
+ shares_exit_data: [
226
+ {
227
+ [operatorShareIndexString]: {
228
+ partial_exit_signature: '0x' + 'different'.repeat(16),
229
+ },
230
+ },
231
+ ],
232
+ };
233
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithDifferentSignature)).rejects.toThrow('Signature mismatch for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd, operator index 0 at epoch 1.');
234
+ }));
235
+ it('should handle multiple blobs, some new, some already processed', () => __awaiter(void 0, void 0, void 0, function* () {
236
+ const anotherMockExitBlob = {
237
+ public_key: '0x' + '11'.repeat(48),
238
+ signed_exit_message: {
239
+ message: { epoch: '2', validator_index: '20' },
240
+ signature: '0x' + 'bb'.repeat(96),
241
+ },
242
+ };
243
+ const payloadWithTwoBlobs = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [mockExitBlob, anotherMockExitBlob] });
244
+ const clusterConfigWithTwoValidators = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
245
+ ...mockClusterConfig.distributed_validators,
246
+ {
247
+ distributed_public_key: anotherMockExitBlob.public_key,
248
+ public_shares: ['0x' + 'cc'.repeat(48)],
249
+ },
250
+ ] });
251
+ // Only the first blob has existing data, second is new
252
+ const existingBlobDataForFirstOnly = {
253
+ public_key: mockExitBlob.public_key,
254
+ epoch: mockExitMessage.epoch,
255
+ validator_index: mockExitMessage.validator_index,
256
+ shares_exit_data: [],
257
+ };
258
+ const result = yield exit.validateExitBlobs(clusterConfigWithTwoValidators, payloadWithTwoBlobs, MOCK_BEACON_API_URL, existingBlobDataForFirstOnly);
259
+ expect(result.length).toBe(1);
260
+ expect(result[0]).toEqual(anotherMockExitBlob);
261
+ }));
262
+ it('should throw if getGenesisValidatorsRoot itself throws an error', () => __awaiter(void 0, void 0, void 0, function* () {
263
+ mockedEthUtils.getGenesisValidatorsRoot.mockRejectedValue(new Error('Beacon node unavailable'));
264
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Beacon node unavailable');
265
+ }));
266
+ // Additional test cases to match API service coverage
267
+ it('should handle public key format differences (with and without 0x prefix)', () => __awaiter(void 0, void 0, void 0, function* () {
268
+ const blobWithoutPrefix = Object.assign(Object.assign({}, mockExitBlob), { public_key: 'cd'.repeat(48) });
269
+ const payloadWithoutPrefix = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithoutPrefix] });
270
+ const clusterConfigWithoutPrefix = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
271
+ {
272
+ distributed_public_key: '0x' + 'cd'.repeat(48), // With 0x prefix
273
+ public_shares: ['0x' + 'aa'.repeat(48)],
274
+ },
275
+ ] });
276
+ const result = yield exit.validateExitBlobs(clusterConfigWithoutPrefix, payloadWithoutPrefix, MOCK_BEACON_API_URL, null);
277
+ expect(result).toEqual([blobWithoutPrefix]);
278
+ }));
279
+ it('should handle public key case differences', () => __awaiter(void 0, void 0, void 0, function* () {
280
+ const blobWithUppercase = Object.assign(Object.assign({}, mockExitBlob), { public_key: '0x' + 'CD'.repeat(48) });
281
+ const payloadWithUppercase = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithUppercase] });
282
+ const clusterConfigWithLowercase = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
283
+ {
284
+ distributed_public_key: '0x' + 'cd'.repeat(48), // Lowercase
285
+ public_shares: ['0x' + 'aa'.repeat(48)],
286
+ },
287
+ ] });
288
+ const result = yield exit.validateExitBlobs(clusterConfigWithLowercase, payloadWithUppercase, MOCK_BEACON_API_URL, null);
289
+ expect(result).toEqual([blobWithUppercase]);
290
+ }));
291
+ it('should throw if public share for operator index is not found', () => __awaiter(void 0, void 0, void 0, function* () {
292
+ const clusterConfigWithMissingShare = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
293
+ {
294
+ distributed_public_key: mockExitBlob.public_key,
295
+ public_shares: [], // Empty public shares array
296
+ },
297
+ ] });
298
+ yield expect(exit.validateExitBlobs(clusterConfigWithMissingShare, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Public share for operator index 0 not found for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd');
299
+ }));
300
+ });
301
+ // Add other tests for different scenarios: epoch mismatch, already exited, etc.
302
+ // Consider testing the case where getExistingBlobData throws an error
303
+ });
@@ -0,0 +1,66 @@
1
+ import { computeDomain, signingRoot, GENESIS_VALIDATOR_ROOT_HEX_STRING, } from '../../src/exits/verificationHelpers';
2
+ import { CAPELLA_FORK_MAPPING } from '../../src/constants'; // Assuming this contains fork versions
3
+ import { fromHexString } from '@chainsafe/ssz';
4
+ // Mock data similar to what's used in obol-api tests or common scenarios
5
+ const DOMAIN_VOLUNTARY_EXIT_HEX = '0x04000000';
6
+ const MAINNET_BASE_FORK_VERSION = '0x00000000';
7
+ const MAINNET_CAPELLA_FORK_VERSION = CAPELLA_FORK_MAPPING[MAINNET_BASE_FORK_VERSION]; // '0x03000000'
8
+ // Sample SSZ Object Root (32 bytes, replace with a realistic one if available from other tests)
9
+ const MOCK_SSZ_OBJECT_ROOT_HEX = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
10
+ describe('verificationHelpers', () => {
11
+ describe('computeDomain', () => {
12
+ it('should compute a domain with default genesis root', () => {
13
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
14
+ const domain = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION);
15
+ expect(domain).toBeInstanceOf(Uint8Array);
16
+ expect(domain.length).toBe(32);
17
+ // Add more specific expectation if a known domain value exists for these inputs
18
+ });
19
+ it('should compute a domain with a custom genesis root', () => {
20
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
21
+ const customGenesisRoot = fromHexString(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2)); // Using a mock root
22
+ const domain = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION, customGenesisRoot);
23
+ expect(domain).toBeInstanceOf(Uint8Array);
24
+ expect(domain.length).toBe(32);
25
+ // Add more specific expectation if a known domain value exists
26
+ });
27
+ it('should use GENESIS_VALIDATOR_ROOT_HEX_STRING when override is undefined', () => {
28
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
29
+ const domain1 = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION);
30
+ const domain2 = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION, fromHexString(GENESIS_VALIDATOR_ROOT_HEX_STRING.substring(2)));
31
+ expect(domain1).toEqual(domain2);
32
+ });
33
+ it('should throw an error for invalid fork version hex string (e.g. too short)', () => {
34
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
35
+ // Example of an invalid (too short) fork version string
36
+ const invalidForkVersion = '0x0300';
37
+ expect(() => computeDomain(domainType, invalidForkVersion)).toThrow();
38
+ });
39
+ it('should throw an error for invalid domainType (e.g. not 4 bytes)', () => {
40
+ const invalidDomainType = fromHexString('010203'); // 3 bytes
41
+ expect(() => computeDomain(invalidDomainType, MAINNET_CAPELLA_FORK_VERSION)).toThrow();
42
+ });
43
+ });
44
+ describe('signingRoot', () => {
45
+ it('should compute a signing root', () => {
46
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
47
+ const domain = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION);
48
+ const messageBuffer = Buffer.from(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2), 'hex');
49
+ const root = signingRoot(domain, messageBuffer);
50
+ expect(root).toBeInstanceOf(Uint8Array);
51
+ expect(root.length).toBe(32);
52
+ // Add more specific expectation if a known signing root value exists
53
+ });
54
+ it('should throw if domain is not 32 bytes', () => {
55
+ const invalidDomain = new Uint8Array(31); // Not 32 bytes
56
+ const messageBuffer = Buffer.from(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2), 'hex');
57
+ expect(() => signingRoot(invalidDomain, messageBuffer)).toThrow();
58
+ });
59
+ it('should throw if messageBuffer is not 32 bytes', () => {
60
+ const domainType = fromHexString(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
61
+ const domain = computeDomain(domainType, MAINNET_CAPELLA_FORK_VERSION);
62
+ const invalidMessageBuffer = Buffer.from('0102030405060708', 'hex'); // Not 32 bytes
63
+ expect(() => signingRoot(domain, invalidMessageBuffer)).toThrow();
64
+ });
65
+ });
66
+ });
@@ -9,10 +9,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  var _a, _b;
11
11
  import { ethers, JsonRpcProvider } from 'ethers';
12
- import { Client } from '../src/index';
13
- import * as utils from '../src/utils';
14
- import * as incentivesHelpers from '../src/incentiveHelpers';
15
- import { DEFAULT_BASE_VERSION } from '../src/constants';
12
+ import { Client } from '../../src/index';
13
+ import * as utils from '../../src/utils';
14
+ import * as incentivesHelpers from '../../src/incentives/incentiveHelpers';
15
+ import { DEFAULT_BASE_VERSION } from '../../src/constants';
16
16
  import { jest, describe, beforeEach, test, expect } from '@jest/globals';
17
17
  const mnemonic = (_b = (_a = ethers.Wallet.createRandom().mnemonic) === null || _a === void 0 ? void 0 : _a.phrase) !== null && _b !== void 0 ? _b : '';
18
18
  const privateKey = ethers.Wallet.fromPhrase(mnemonic).privateKey;
@@ -111,3 +111,8 @@ export declare const DEFAULT_RETROACTIVE_FUNDING_REWARDS_ONLY_SPLIT = 1;
111
111
  export declare const DEFAULT_RETROACTIVE_FUNDING_TOTAL_SPLIT = 0.1;
112
112
  export declare const OBOL_SDK_EMAIL = "sdk@dvlabs.tech";
113
113
  export declare const PROVIDER_MAP: Record<number, string>;
114
+ /**
115
+ * Maps base fork versions to their corresponding Capella fork versions.
116
+ * Example: Mainnet Capella fork version.
117
+ */
118
+ export declare const CAPELLA_FORK_MAPPING: Record<string, string>;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Retrieves the Capella fork version for a given base fork version.
3
+ * @param fork_version - The base fork version string (e.g., '0x00000000' for mainnet).
4
+ * @returns A promise that resolves to the Capella fork version string, or null if not found.
5
+ */
6
+ export declare function getCapellaFork(fork_version: string): Promise<string | null>;
7
+ /**
8
+ * Fetches the genesis validators root from a beacon node.
9
+ * @param beaconNodeApiUrl - The base URL of the beacon node API (e.g., http://localhost:5052).
10
+ * @returns A promise that resolves to the genesis_validators_root string, or null on error.
11
+ * @throws Will throw an error if the network corresponding to the fork_version is not supported or if the HTTP request fails.
12
+ */
13
+ export declare function getGenesisValidatorsRoot(beaconNodeApiUrl: string): Promise<string | null>;
@@ -0,0 +1,180 @@
1
+ import type { ProviderType, ExitClusterConfig, ExitValidationPayload, ExitValidationBlob, SignedExitValidationMessage, ExistingExitValidationBlobData } from '../types';
2
+ /**
3
+ * Exit validation and verification class for Obol distributed validators.
4
+ *
5
+ * This class provides functionality to validate and verify voluntary exit signatures
6
+ * for distributed validators in an Obol cluster. It handles both partial exit signatures
7
+ * from individual operators and payload signatures that authorize exit operations.
8
+ *
9
+ * The class supports:
10
+ * - Verification of BLS signatures for partial exit messages
11
+ * - Verification of ECDSA signatures for exit payload authorization
12
+ * - Validation of exit blobs against cluster configuration
13
+ * - Duplicate detection and epoch validation
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const exit = new Exit(1, provider); // Mainnet with provider
18
+ *
19
+ * // Verify a partial exit signature
20
+ * const isValid = await exit.verifyPartialExitSignature(
21
+ * publicShareKey,
22
+ * signedExitMessage,
23
+ * forkVersion,
24
+ * genesisValidatorsRoot
25
+ * );
26
+ *
27
+ * // Validate exit blobs for a cluster
28
+ * const validBlobs = await exit.validateExitBlobs(
29
+ * clusterConfig,
30
+ * exitsPayload,
31
+ * beaconNodeApiUrl,
32
+ * existingBlobData
33
+ * );
34
+ * ```
35
+ */
36
+ export declare class Exit {
37
+ readonly chainId: number;
38
+ readonly provider: ProviderType | undefined | null;
39
+ /**
40
+ * Creates a new Exit instance for validator exit operations.
41
+ *
42
+ * @param chainId - The Ethereum chain ID (e.g., 1 for mainnet, 5 for goerli)
43
+ * @param provider - Optional Ethereum provider for blockchain interactions
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * // For mainnet with a provider
48
+ * const exit = new Exit(1, provider);
49
+ *
50
+ * // For goerli testnet without provider
51
+ * const exit = new Exit(5, null);
52
+ * ```
53
+ */
54
+ constructor(chainId: number, provider: ProviderType | undefined | null);
55
+ /**
56
+ * Safely parse a string integer to number, using BigInt to avoid precision loss
57
+ * for large values beyond JavaScript's safe integer limit (2^53 - 1).
58
+ * Throws an error if the value exceeds the safe range for a 64-bit unsigned integer.
59
+ */
60
+ private static safeParseInt;
61
+ private static computePartialExitMessageRoot;
62
+ private static computeExitPayloadRoot;
63
+ /**
64
+ * Verifies a partial exit signature from a distributed validator operator.
65
+ *
66
+ * This method validates that a partial exit signature was correctly signed by the
67
+ * operator's share of the distributed validator's private key. It performs BLS
68
+ * signature verification using the appropriate fork version and genesis validators root.
69
+ *
70
+ * @param publicShareKey - The operator's public share key (BLS public key, hex string with or without 0x prefix)
71
+ * @param signedExitMessage - The signed exit message containing the exit details and signature
72
+ * @param forkVersion - The Ethereum fork version (e.g., "0x00000000" for mainnet)
73
+ * @param genesisValidatorsRootString - The genesis validators root for the network (hex string)
74
+ *
75
+ * @returns Promise resolving to true if the signature is valid, false otherwise
76
+ *
77
+ * @throws {Error} When unable to determine the Capella fork version for the given network
78
+ * @throws {Error} When BLS library initialization or verification fails
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const isValid = await exit.verifyPartialExitSignature(
83
+ * "0x1234...abcd", // operator's public share key
84
+ * {
85
+ * message: { epoch: "12345", validator_index: "67890" },
86
+ * signature: "0xabcd...1234"
87
+ * },
88
+ * "0x00000000", // mainnet fork version
89
+ * "0x4b363db94e286120d76eb905340fdd4e54bfe9f06bf33ff6cf5ad27f511bfe95"
90
+ * );
91
+ * ```
92
+ */
93
+ verifyPartialExitSignature(publicShareKey: string, signedExitMessage: SignedExitValidationMessage, forkVersion: string, genesisValidatorsRootString: string): Promise<boolean>;
94
+ /**
95
+ * Verifies the exit payload signature using the operator's ENR.
96
+ *
97
+ * This method validates that an exit payload was signed by the correct operator
98
+ * using ECDSA signature verification. The signature is verified against the
99
+ * operator's public key extracted from their ENR (Ethereum Node Record).
100
+ *
101
+ * @param enrString - The operator's ENR string containing their identity and public key
102
+ * @param exitsPayload - The exit validation payload containing partial exits and operator signature
103
+ *
104
+ * @returns Promise resolving to true if the payload signature is valid, false otherwise
105
+ *
106
+ * @throws {Error} When the ENR string is invalid or cannot be decoded
107
+ * @throws {Error} When the signature format is invalid (must be 130 hex characters)
108
+ * @throws {Error} When signature verification encounters an error
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const isValid = await exit.verifyExitPayloadSignature(
113
+ * "enr:-LK4QFo_n0dUm4PKejSOXf8JkSWq5EINV0XhG1zY00d...", // operator ENR
114
+ * {
115
+ * partial_exits: [exitBlob1, exitBlob2],
116
+ * share_idx: 1,
117
+ * signature: "0x1234...abcd" // ECDSA signature (130 hex chars)
118
+ * }
119
+ * );
120
+ * ```
121
+ */
122
+ verifyExitPayloadSignature(enrString: string, exitsPayload: ExitValidationPayload): Promise<boolean>;
123
+ private validateOperatorAndPayload;
124
+ private getNetworkParameters;
125
+ private findValidatorInCluster;
126
+ private validateExistingBlobData;
127
+ private processExitBlob;
128
+ /**
129
+ * Validates exit blobs against cluster configuration and existing data.
130
+ *
131
+ * This method performs comprehensive validation of exit blobs including:
132
+ * - Operator authorization and payload signature verification
133
+ * - Network parameter validation (genesis root, fork version)
134
+ * - Public key validation against cluster configuration
135
+ * - Partial signature verification for each exit blob
136
+ * - Duplicate detection and epoch progression validation
137
+ * - Signature consistency checks for existing exits
138
+ *
139
+ * @param clusterConfig - The cluster configuration containing operators and distributed validators
140
+ * @param exitsPayload - The exit validation payload with partial exits and operator info
141
+ * @param beaconNodeApiUrl - The beacon node API URL for network parameter retrieval
142
+ * @param existingBlobData - Existing exit blob data for duplicate detection, or null if none exists
143
+ *
144
+ * @returns Promise resolving to an array of validated, non-duplicate exit blobs
145
+ *
146
+ * @throws {Error} When share_idx is invalid or out of bounds for the cluster operators
147
+ * @throws {Error} When payload signature verification fails
148
+ * @throws {Error} When network parameters cannot be retrieved or are invalid
149
+ * @throws {Error} When a public key is not found in the cluster's distributed validators
150
+ * @throws {Error} When a partial exit signature is invalid
151
+ * @throws {Error} When exit epoch validation fails (new epoch not greater than existing)
152
+ * @throws {Error} When validator index mismatches with existing data
153
+ * @throws {Error} When signature mismatches for the same epoch and operator
154
+ *
155
+ * @example
156
+ * ```typescript
157
+ * const validExitBlobs = await exit.validateExitBlobs(
158
+ * {
159
+ * definition: {
160
+ * operators: [{ enr: "enr:-LK4Q..." }],
161
+ * fork_version: "0x00000000",
162
+ * threshold: 1
163
+ * },
164
+ * distributed_validators: [{
165
+ * distributed_public_key: "0x1234...abcd",
166
+ * public_shares: ["0x5678...efgh"]
167
+ * }]
168
+ * },
169
+ * {
170
+ * partial_exits: [exitBlob],
171
+ * share_idx: 1,
172
+ * signature: "0x1234...abcd"
173
+ * },
174
+ * "http://localhost:5052",
175
+ * existingBlobData // or null for new exits
176
+ * );
177
+ * ```
178
+ */
179
+ validateExitBlobs(clusterConfig: ExitClusterConfig, exitsPayload: ExitValidationPayload, beaconNodeApiUrl: string, existingBlobData: ExistingExitValidationBlobData | null): Promise<ExitValidationBlob[]>;
180
+ }
@@ -0,0 +1,20 @@
1
+ /// <reference types="node" />
2
+ export declare const GENESIS_VALIDATOR_ROOT_HEX_STRING = "0x0000000000000000000000000000000000000000000000000000000000000000";
3
+ /**
4
+ * Computes the domain for a given domain type, fork version, and genesis state.
5
+ * https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#compute_domain
6
+ * @param domainType - Uint8Array representing the domain type (e.g., DOMAIN_VOLUNTARY_EXIT).
7
+ * @param forkVersionString - Hex string of the fork version (e.g., Capella fork version).
8
+ * @param genesisValidatorsRootOverride - Optional Uint8Array to override the default genesis validators root.
9
+ * @returns Uint8Array - The 32-byte domain.
10
+ */
11
+ export declare function computeDomain(domainType: Uint8Array, // Should be 4 bytes
12
+ forkVersionString: string, // Hex string, e.g., '0x03000000'
13
+ genesisValidatorsRootOverride?: Uint8Array): Uint8Array;
14
+ /**
15
+ * Convenience wrapper for computeSigningRoot.
16
+ * @param domain - Uint8Array of the domain.
17
+ * @param messageBuffer - Buffer of the message (SSZ object root).
18
+ * @returns Uint8Array - The signing root.
19
+ */
20
+ export declare function signingRoot(domain: Uint8Array, messageBuffer: Buffer): Uint8Array;
@@ -1,4 +1,4 @@
1
- import { type ProviderType, type SignerType, type ETH_ADDRESS } from './types';
1
+ import { type ProviderType, type SignerType, type ETH_ADDRESS } from '../types';
2
2
  export declare const claimIncentivesFromMerkleDistributor: (incentivesData: {
3
3
  signer: SignerType;
4
4
  contractAddress: ETH_ADDRESS;
@@ -1,4 +1,4 @@
1
- import { type ClaimableIncentives, type ETH_ADDRESS, type ProviderType, type SignerType, type ClaimIncentivesResponse } from './types';
1
+ import { type ClaimableIncentives, type ETH_ADDRESS, type ProviderType, type SignerType, type ClaimIncentivesResponse } from '../types';
2
2
  /**
3
3
  * Incentives can be used for fetching and claiming Obol incentives.
4
4
  * @class