@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,399 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ const exit_1 = require("../../src/exits/exit");
36
+ const ethUtils = __importStar(require("../../src/exits/ethUtils"));
37
+ const bls = __importStar(require("@chainsafe/bls"));
38
+ const discv5_1 = require("@chainsafe/discv5");
39
+ const elliptic = __importStar(require("elliptic"));
40
+ const constants_1 = require("../../src/constants");
41
+ const ssz_1 = require("@chainsafe/ssz");
42
+ const verificationHelpers = __importStar(require("../../src/exits/verificationHelpers"));
43
+ // --- Mocks ---
44
+ jest.mock('../../src/exits/ethUtils');
45
+ jest.mock('@chainsafe/bls', () => {
46
+ const actual = jest.requireActual('@chainsafe/bls');
47
+ return Object.assign(Object.assign({ __esModule: true }, actual), { init: jest.fn(), verify: jest.fn(), aggregateSignatures: jest.fn() });
48
+ });
49
+ // ENR and elliptic will be spied on, not fully mocked at module level for more flexibility
50
+ const mockedEthUtils = ethUtils;
51
+ const mockedBls = bls;
52
+ // --- Test Data ---
53
+ const MAINNET_BASE_FORK_VERSION = '0x00000000';
54
+ const MAINNET_CAPELLA_FORK_VERSION = constants_1.CAPELLA_FORK_MAPPING[MAINNET_BASE_FORK_VERSION];
55
+ const MOCK_GENESIS_ROOT = '0x0000000000000000000000000000000000000000000000000000000000000001';
56
+ const MOCK_BEACON_API_URL = 'http://localhost:5052';
57
+ const mockOperatorEnr = 'enr:-LK4QFo_n0dUm4PKejSOXf8JkSWq5EINV0XhG1zY00d22QpYdyxSAyQNsGkYQyKR5Ohe2kEkmS0nS31tuqVfXDNf_vEAhGV0aAgQD___2iXChwcEChAgAAAAADg__________g2V0aMfLCGgohEAcNlBpLdCgAAAQAdIaENsZS0CAAAABAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAAIAAAAAAAAAYAAAAAAAAAAAAAAAAAAAIQA___________gmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKwrO7sVJzX4B2vW1bTqWCpGA93R2aZqa2ZCrqSrh8CYN1ZHCCIyg';
58
+ const mockOperatorPublicKeyHex = '03ca0aceeec549cd7f8076bd6d5b4ea582a4603ddd1d9a66a6b6642aeaa4ae1f09';
59
+ const mockExitMessage = {
60
+ epoch: '1',
61
+ validator_index: '10',
62
+ };
63
+ const mockSignedExitMessage = {
64
+ message: mockExitMessage,
65
+ signature: '0x' + 'ab'.repeat(96),
66
+ };
67
+ const mockExitBlob = {
68
+ public_key: '0x' + 'cd'.repeat(48),
69
+ signed_exit_message: mockSignedExitMessage,
70
+ };
71
+ const mockExitPayload = {
72
+ partial_exits: [mockExitBlob],
73
+ share_idx: 1,
74
+ signature: '0x' + 'ef'.repeat(65),
75
+ };
76
+ // Make mockClusterConfig directly ExitClusterConfig for easier use in tests
77
+ const mockClusterConfig = {
78
+ definition: {
79
+ operators: [{ enr: mockOperatorEnr }],
80
+ fork_version: MAINNET_BASE_FORK_VERSION,
81
+ threshold: 1,
82
+ },
83
+ distributed_validators: [
84
+ {
85
+ distributed_public_key: mockExitBlob.public_key,
86
+ public_shares: ['0x' + 'aa'.repeat(48)],
87
+ },
88
+ ],
89
+ };
90
+ const mockExistingBlobData = {
91
+ public_key: mockExitBlob.public_key,
92
+ epoch: mockExitMessage.epoch,
93
+ validator_index: mockExitMessage.validator_index,
94
+ shares_exit_data: [],
95
+ };
96
+ describe('exit', () => {
97
+ let enrDecodeTxtSpy;
98
+ let ecVerifySpy;
99
+ let keyFromPublicSpy;
100
+ let exit;
101
+ beforeEach(() => {
102
+ jest.resetAllMocks();
103
+ exit = new exit_1.Exit(1, null);
104
+ mockedBls.init.mockResolvedValue(undefined);
105
+ mockedBls.verify.mockReturnValue(true);
106
+ mockedEthUtils.getCapellaFork.mockResolvedValue(MAINNET_CAPELLA_FORK_VERSION);
107
+ mockedEthUtils.getGenesisValidatorsRoot.mockResolvedValue(MOCK_GENESIS_ROOT);
108
+ const mockDecodedENR = {
109
+ publicKey: Buffer.from(mockOperatorPublicKeyHex, 'hex'),
110
+ };
111
+ enrDecodeTxtSpy = jest
112
+ .spyOn(discv5_1.ENR, 'decodeTxt')
113
+ .mockReturnValue(mockDecodedENR);
114
+ ecVerifySpy = jest.fn().mockReturnValue(true);
115
+ keyFromPublicSpy = jest.spyOn(elliptic.ec.prototype, 'keyFromPublic');
116
+ keyFromPublicSpy.mockImplementation(function () {
117
+ return { verify: ecVerifySpy };
118
+ });
119
+ });
120
+ afterEach(() => {
121
+ if (enrDecodeTxtSpy)
122
+ enrDecodeTxtSpy.mockRestore();
123
+ jest.restoreAllMocks();
124
+ });
125
+ describe('verifyPartialExitSignature', () => {
126
+ const publicShareKey = mockClusterConfig.distributed_validators[0].public_shares[0];
127
+ it('should return true for a valid signature', () => __awaiter(void 0, void 0, void 0, function* () {
128
+ const isValid = yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
129
+ expect(isValid).toBe(true);
130
+ expect(mockedBls.init).toHaveBeenCalledWith('herumi');
131
+ expect(mockedBls.verify).toHaveBeenCalled();
132
+ expect(mockedEthUtils.getCapellaFork).toHaveBeenCalledWith(MAINNET_BASE_FORK_VERSION);
133
+ }));
134
+ it('should return false if BLS verification fails', () => __awaiter(void 0, void 0, void 0, function* () {
135
+ mockedBls.verify.mockReturnValue(false);
136
+ const isValid = yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
137
+ expect(isValid).toBe(false);
138
+ }));
139
+ it('should throw if getCapellaFork returns null', () => __awaiter(void 0, void 0, void 0, function* () {
140
+ mockedEthUtils.getCapellaFork.mockResolvedValue(null);
141
+ yield expect(exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT)).rejects.toThrow('Could not determine Capella fork version');
142
+ }));
143
+ it('should call computeDomain and signingRoot with correct parameters', () => __awaiter(void 0, void 0, void 0, function* () {
144
+ const computeDomainSpy = jest.spyOn(verificationHelpers, 'computeDomain');
145
+ const signingRootSpy = jest.spyOn(verificationHelpers, 'signingRoot');
146
+ yield exit.verifyPartialExitSignature(publicShareKey, mockSignedExitMessage, MAINNET_BASE_FORK_VERSION, MOCK_GENESIS_ROOT);
147
+ expect(computeDomainSpy).toHaveBeenCalledWith((0, ssz_1.fromHexString)('04000000'), MAINNET_CAPELLA_FORK_VERSION, (0, ssz_1.fromHexString)(MOCK_GENESIS_ROOT.substring(2)));
148
+ expect(signingRootSpy).toHaveBeenCalled();
149
+ computeDomainSpy.mockRestore();
150
+ signingRootSpy.mockRestore();
151
+ }));
152
+ });
153
+ describe('verifyExitPayloadSignature', () => {
154
+ it('should return true for a valid ECDSA signature', () => __awaiter(void 0, void 0, void 0, function* () {
155
+ const isValid = yield exit.verifyExitPayloadSignature(mockOperatorEnr, mockExitPayload);
156
+ expect(isValid).toBe(true);
157
+ expect(enrDecodeTxtSpy).toHaveBeenCalledWith(mockOperatorEnr);
158
+ expect(ecVerifySpy).toHaveBeenCalled();
159
+ }));
160
+ it('should return false if ECDSA verification fails', () => __awaiter(void 0, void 0, void 0, function* () {
161
+ ecVerifySpy.mockReturnValue(false);
162
+ const isValid = yield exit.verifyExitPayloadSignature(mockOperatorEnr, mockExitPayload);
163
+ expect(isValid).toBe(false);
164
+ }));
165
+ it('should throw if ENR is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
166
+ enrDecodeTxtSpy.mockImplementation(() => {
167
+ throw new Error('Invalid ENR');
168
+ });
169
+ yield expect(exit.verifyExitPayloadSignature('invalid-enr', mockExitPayload)).rejects.toThrow('Invalid ENR string');
170
+ }));
171
+ it('should throw if signature hex is not 128 characters (excluding 0x)', () => __awaiter(void 0, void 0, void 0, function* () {
172
+ const payloadWithInvalidSig = Object.assign(Object.assign({}, mockExitPayload), { signature: '0x123456' });
173
+ yield expect(exit.verifyExitPayloadSignature(mockOperatorEnr, payloadWithInvalidSig)).rejects.toThrow('Invalid signature length');
174
+ }));
175
+ });
176
+ describe('validateExitBlobs', () => {
177
+ it('should successfully validate a new, valid exit blob', () => __awaiter(void 0, void 0, void 0, function* () {
178
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, null);
179
+ expect(result).toEqual([mockExitBlob]);
180
+ expect(ecVerifySpy).toHaveBeenCalled(); // Called by internal verifyExitPayloadSignature
181
+ expect(mockedBls.verify).toHaveBeenCalled(); // Called by internal verifyPartialExitSignature
182
+ }));
183
+ it('should throw if operatorIndex (from share_idx) is out of bounds', () => __awaiter(void 0, void 0, void 0, function* () {
184
+ const invalidPayload = Object.assign(Object.assign({}, mockExitPayload), { share_idx: 0 });
185
+ yield expect(exit.validateExitBlobs(mockClusterConfig, invalidPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Invalid share_idx');
186
+ const invalidPayload2 = Object.assign(Object.assign({}, mockExitPayload), { share_idx: mockClusterConfig.definition.operators.length + 1 });
187
+ yield expect(exit.validateExitBlobs(mockClusterConfig, invalidPayload2, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Invalid share_idx');
188
+ }));
189
+ it('should throw if payload signature is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
190
+ ecVerifySpy.mockReturnValue(false);
191
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Incorrect payload signature');
192
+ }));
193
+ it('should throw if getGenesisValidatorsRoot returns null', () => __awaiter(void 0, void 0, void 0, function* () {
194
+ mockedEthUtils.getGenesisValidatorsRoot.mockResolvedValue(null);
195
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Could not retrieve genesis validators root');
196
+ }));
197
+ it('should throw if getCapellaFork returns null (unsupported network)', () => __awaiter(void 0, void 0, void 0, function* () {
198
+ mockedEthUtils.getCapellaFork.mockResolvedValue(null);
199
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Unsupported network: Could not determine Capella fork');
200
+ }));
201
+ 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* () {
202
+ const blobWithUnknownKey = Object.assign(Object.assign({}, mockExitBlob), { public_key: '0x' + 'deadbeef'.repeat(12) });
203
+ const payloadWithUnknownKey = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithUnknownKey] });
204
+ yield expect(exit.validateExitBlobs(mockClusterConfig, payloadWithUnknownKey, MOCK_BEACON_API_URL, null)).rejects.toThrow("Public key 0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef not found in the cluster's distributed validators.");
205
+ }));
206
+ it('should throw if a partial exit signature is invalid', () => __awaiter(void 0, void 0, void 0, function* () {
207
+ mockedBls.verify.mockReturnValue(false);
208
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, null)).rejects.toThrow('Invalid partial exit signature for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd by operator index 0.');
209
+ }));
210
+ it('should return an empty array if an exit blob has already been processed (epoch match)', () => __awaiter(void 0, void 0, void 0, function* () {
211
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData);
212
+ expect(result).toEqual([]);
213
+ }));
214
+ it('should throw if an exit blob has been processed with a different validator index', () => __awaiter(void 0, void 0, void 0, function* () {
215
+ const existingBlobWithDifferentIndex = {
216
+ public_key: mockExitBlob.public_key,
217
+ epoch: mockExitMessage.epoch,
218
+ validator_index: (parseInt(mockExitMessage.validator_index, 10) + 1).toString(), // Different index
219
+ shares_exit_data: [],
220
+ };
221
+ 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.');
222
+ }));
223
+ it('should throw if an exit blob has been processed with a higher epoch', () => __awaiter(void 0, void 0, void 0, function* () {
224
+ const existingBlobWithHigherEpoch = {
225
+ public_key: mockExitBlob.public_key,
226
+ epoch: (parseInt(mockExitMessage.epoch, 10) + 1).toString(), // Existing epoch is HIGHER (e.g. 2)
227
+ validator_index: mockExitMessage.validator_index,
228
+ shares_exit_data: [],
229
+ };
230
+ // currentExitBlob (from mockExitPayload) has mockExitMessage.epoch (e.g. '1')
231
+ 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.');
232
+ }));
233
+ it('should successfully validate if an exit blob has been processed with a lower epoch', () => __awaiter(void 0, void 0, void 0, function* () {
234
+ const existingBlobWithLowerEpoch = {
235
+ public_key: mockExitBlob.public_key,
236
+ epoch: (parseInt(mockExitMessage.epoch, 10) - 1).toString(),
237
+ validator_index: mockExitMessage.validator_index,
238
+ shares_exit_data: [],
239
+ };
240
+ const result = yield exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithLowerEpoch);
241
+ expect(result).toEqual([mockExitBlob]);
242
+ }));
243
+ it('should throw on signature mismatch for existing blob with same epoch', () => __awaiter(void 0, void 0, void 0, function* () {
244
+ const operatorIndex = 0;
245
+ const operatorShareIndexString = String(operatorIndex);
246
+ const existingBlobWithDifferentSignature = {
247
+ public_key: mockExitBlob.public_key,
248
+ epoch: mockExitMessage.epoch,
249
+ validator_index: mockExitMessage.validator_index,
250
+ shares_exit_data: [
251
+ {
252
+ [operatorShareIndexString]: {
253
+ partial_exit_signature: '0x' + 'different'.repeat(16),
254
+ },
255
+ },
256
+ ],
257
+ };
258
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, existingBlobWithDifferentSignature)).rejects.toThrow('Signature mismatch for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd, operator index 0 at epoch 1.');
259
+ }));
260
+ it('should handle multiple blobs, some new, some already processed', () => __awaiter(void 0, void 0, void 0, function* () {
261
+ const anotherMockExitBlob = {
262
+ public_key: '0x' + '11'.repeat(48),
263
+ signed_exit_message: {
264
+ message: { epoch: '2', validator_index: '20' },
265
+ signature: '0x' + 'bb'.repeat(96),
266
+ },
267
+ };
268
+ const payloadWithTwoBlobs = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [mockExitBlob, anotherMockExitBlob] });
269
+ const clusterConfigWithTwoValidators = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
270
+ ...mockClusterConfig.distributed_validators,
271
+ {
272
+ distributed_public_key: anotherMockExitBlob.public_key,
273
+ public_shares: ['0x' + 'cc'.repeat(48)],
274
+ },
275
+ ] });
276
+ // Only the first blob has existing data, second is new
277
+ const existingBlobDataForFirstOnly = {
278
+ public_key: mockExitBlob.public_key,
279
+ epoch: mockExitMessage.epoch,
280
+ validator_index: mockExitMessage.validator_index,
281
+ shares_exit_data: [],
282
+ };
283
+ const result = yield exit.validateExitBlobs(clusterConfigWithTwoValidators, payloadWithTwoBlobs, MOCK_BEACON_API_URL, existingBlobDataForFirstOnly);
284
+ expect(result.length).toBe(1);
285
+ expect(result[0]).toEqual(anotherMockExitBlob);
286
+ }));
287
+ it('should throw if getGenesisValidatorsRoot itself throws an error', () => __awaiter(void 0, void 0, void 0, function* () {
288
+ mockedEthUtils.getGenesisValidatorsRoot.mockRejectedValue(new Error('Beacon node unavailable'));
289
+ yield expect(exit.validateExitBlobs(mockClusterConfig, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Beacon node unavailable');
290
+ }));
291
+ // Additional test cases to match API service coverage
292
+ it('should handle public key format differences (with and without 0x prefix)', () => __awaiter(void 0, void 0, void 0, function* () {
293
+ const blobWithoutPrefix = Object.assign(Object.assign({}, mockExitBlob), { public_key: 'cd'.repeat(48) });
294
+ const payloadWithoutPrefix = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithoutPrefix] });
295
+ const clusterConfigWithoutPrefix = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
296
+ {
297
+ distributed_public_key: '0x' + 'cd'.repeat(48), // With 0x prefix
298
+ public_shares: ['0x' + 'aa'.repeat(48)],
299
+ },
300
+ ] });
301
+ const result = yield exit.validateExitBlobs(clusterConfigWithoutPrefix, payloadWithoutPrefix, MOCK_BEACON_API_URL, null);
302
+ expect(result).toEqual([blobWithoutPrefix]);
303
+ }));
304
+ it('should handle public key case differences', () => __awaiter(void 0, void 0, void 0, function* () {
305
+ const blobWithUppercase = Object.assign(Object.assign({}, mockExitBlob), { public_key: '0x' + 'CD'.repeat(48) });
306
+ const payloadWithUppercase = Object.assign(Object.assign({}, mockExitPayload), { partial_exits: [blobWithUppercase] });
307
+ const clusterConfigWithLowercase = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
308
+ {
309
+ distributed_public_key: '0x' + 'cd'.repeat(48), // Lowercase
310
+ public_shares: ['0x' + 'aa'.repeat(48)],
311
+ },
312
+ ] });
313
+ const result = yield exit.validateExitBlobs(clusterConfigWithLowercase, payloadWithUppercase, MOCK_BEACON_API_URL, null);
314
+ expect(result).toEqual([blobWithUppercase]);
315
+ }));
316
+ it('should throw if public share for operator index is not found', () => __awaiter(void 0, void 0, void 0, function* () {
317
+ const clusterConfigWithMissingShare = Object.assign(Object.assign({}, mockClusterConfig), { distributed_validators: [
318
+ {
319
+ distributed_public_key: mockExitBlob.public_key,
320
+ public_shares: [], // Empty public shares array
321
+ },
322
+ ] });
323
+ yield expect(exit.validateExitBlobs(clusterConfigWithMissingShare, mockExitPayload, MOCK_BEACON_API_URL, mockExistingBlobData)).rejects.toThrow('Public share for operator index 0 not found for validator 0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd');
324
+ }));
325
+ });
326
+ describe('recombineExitBlobs', () => {
327
+ it('should successfully recombine signatures into a single exit blob', () => __awaiter(void 0, void 0, void 0, function* () {
328
+ const mockExistingBlob = {
329
+ public_key: '0x' + '1234'.repeat(24),
330
+ epoch: '100',
331
+ validator_index: '200',
332
+ shares_exit_data: [
333
+ {
334
+ 0: { partial_exit_signature: '0x' + 'a0'.repeat(96) },
335
+ 2: { partial_exit_signature: '0x' + 'a2'.repeat(96) }, // Note non-sequential indices
336
+ 1: { partial_exit_signature: '0x' + 'a1'.repeat(96) },
337
+ },
338
+ ],
339
+ };
340
+ const expectedAggregatedSig = '0x' + 'ff'.repeat(96);
341
+ const expectedAggregatedSigBytes = (0, ssz_1.fromHexString)(expectedAggregatedSig);
342
+ mockedBls.aggregateSignatures.mockReturnValue(expectedAggregatedSigBytes);
343
+ const result = yield exit.recombineExitBlobs(mockExistingBlob);
344
+ expect(mockedBls.init).toHaveBeenCalledWith('herumi');
345
+ expect(mockedBls.aggregateSignatures).toHaveBeenCalledTimes(1);
346
+ const calls = mockedBls.aggregateSignatures.mock.calls;
347
+ const rawSignatures = calls[0][0];
348
+ // Check if signatures were passed in sorted order of operator index
349
+ expect(rawSignatures[0]).toEqual((0, ssz_1.fromHexString)('a0'.repeat(96)));
350
+ expect(rawSignatures[1]).toEqual((0, ssz_1.fromHexString)('a1'.repeat(96)));
351
+ expect(rawSignatures[2]).toEqual((0, ssz_1.fromHexString)('a2'.repeat(96)));
352
+ expect(result).toEqual({
353
+ public_key: mockExistingBlob.public_key,
354
+ signed_exit_message: {
355
+ message: {
356
+ epoch: mockExistingBlob.epoch,
357
+ validator_index: mockExistingBlob.validator_index,
358
+ },
359
+ signature: expectedAggregatedSig,
360
+ },
361
+ });
362
+ }));
363
+ it('should throw if no valid signatures are found', () => __awaiter(void 0, void 0, void 0, function* () {
364
+ const mockExistingBlob = {
365
+ public_key: '0x' + '1234'.repeat(24),
366
+ epoch: '100',
367
+ validator_index: '200',
368
+ shares_exit_data: [
369
+ {
370
+ 0: { partial_exit_signature: '' }, // empty sig
371
+ },
372
+ ],
373
+ };
374
+ yield expect(exit.recombineExitBlobs(mockExistingBlob)).rejects.toThrow('No valid signatures found for aggregation');
375
+ }));
376
+ it('should throw on invalid signature length', () => __awaiter(void 0, void 0, void 0, function* () {
377
+ const mockExistingBlob = {
378
+ public_key: '0x' + '1234'.repeat(24),
379
+ epoch: '100',
380
+ validator_index: '200',
381
+ shares_exit_data: [
382
+ {
383
+ 0: { partial_exit_signature: '0x1234' },
384
+ },
385
+ ],
386
+ };
387
+ yield expect(exit.recombineExitBlobs(mockExistingBlob)).rejects.toThrow('Invalid signature length');
388
+ }));
389
+ it('should handle empty shares_exit_data', () => __awaiter(void 0, void 0, void 0, function* () {
390
+ const mockExistingBlob = {
391
+ public_key: '0x' + '1234'.repeat(24),
392
+ epoch: '100',
393
+ validator_index: '200',
394
+ shares_exit_data: [],
395
+ };
396
+ yield expect(exit.recombineExitBlobs(mockExistingBlob)).rejects.toThrow('No shares exit data available for aggregation');
397
+ }));
398
+ });
399
+ });
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const verificationHelpers_1 = require("../../src/exits/verificationHelpers");
4
+ const constants_1 = require("../../src/constants"); // Assuming this contains fork versions
5
+ const ssz_1 = require("@chainsafe/ssz");
6
+ // Mock data similar to what's used in obol-api tests or common scenarios
7
+ const DOMAIN_VOLUNTARY_EXIT_HEX = '0x04000000';
8
+ const MAINNET_BASE_FORK_VERSION = '0x00000000';
9
+ const MAINNET_CAPELLA_FORK_VERSION = constants_1.CAPELLA_FORK_MAPPING[MAINNET_BASE_FORK_VERSION]; // '0x03000000'
10
+ // Sample SSZ Object Root (32 bytes, replace with a realistic one if available from other tests)
11
+ const MOCK_SSZ_OBJECT_ROOT_HEX = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
12
+ describe('verificationHelpers', () => {
13
+ describe('computeDomain', () => {
14
+ it('should compute a domain with default genesis root', () => {
15
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
16
+ const domain = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION);
17
+ expect(domain).toBeInstanceOf(Uint8Array);
18
+ expect(domain.length).toBe(32);
19
+ // Add more specific expectation if a known domain value exists for these inputs
20
+ });
21
+ it('should compute a domain with a custom genesis root', () => {
22
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
23
+ const customGenesisRoot = (0, ssz_1.fromHexString)(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2)); // Using a mock root
24
+ const domain = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION, customGenesisRoot);
25
+ expect(domain).toBeInstanceOf(Uint8Array);
26
+ expect(domain.length).toBe(32);
27
+ // Add more specific expectation if a known domain value exists
28
+ });
29
+ it('should use GENESIS_VALIDATOR_ROOT_HEX_STRING when override is undefined', () => {
30
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
31
+ const domain1 = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION);
32
+ const domain2 = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION, (0, ssz_1.fromHexString)(verificationHelpers_1.GENESIS_VALIDATOR_ROOT_HEX_STRING.substring(2)));
33
+ expect(domain1).toEqual(domain2);
34
+ });
35
+ it('should throw an error for invalid fork version hex string (e.g. too short)', () => {
36
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
37
+ // Example of an invalid (too short) fork version string
38
+ const invalidForkVersion = '0x0300';
39
+ expect(() => (0, verificationHelpers_1.computeDomain)(domainType, invalidForkVersion)).toThrow();
40
+ });
41
+ it('should throw an error for invalid domainType (e.g. not 4 bytes)', () => {
42
+ const invalidDomainType = (0, ssz_1.fromHexString)('010203'); // 3 bytes
43
+ expect(() => (0, verificationHelpers_1.computeDomain)(invalidDomainType, MAINNET_CAPELLA_FORK_VERSION)).toThrow();
44
+ });
45
+ });
46
+ describe('signingRoot', () => {
47
+ it('should compute a signing root', () => {
48
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
49
+ const domain = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION);
50
+ const messageBuffer = Buffer.from(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2), 'hex');
51
+ const root = (0, verificationHelpers_1.signingRoot)(domain, messageBuffer);
52
+ expect(root).toBeInstanceOf(Uint8Array);
53
+ expect(root.length).toBe(32);
54
+ // Add more specific expectation if a known signing root value exists
55
+ });
56
+ it('should throw if domain is not 32 bytes', () => {
57
+ const invalidDomain = new Uint8Array(31); // Not 32 bytes
58
+ const messageBuffer = Buffer.from(MOCK_SSZ_OBJECT_ROOT_HEX.substring(2), 'hex');
59
+ expect(() => (0, verificationHelpers_1.signingRoot)(invalidDomain, messageBuffer)).toThrow();
60
+ });
61
+ it('should throw if messageBuffer is not 32 bytes', () => {
62
+ const domainType = (0, ssz_1.fromHexString)(DOMAIN_VOLUNTARY_EXIT_HEX.substring(2));
63
+ const domain = (0, verificationHelpers_1.computeDomain)(domainType, MAINNET_CAPELLA_FORK_VERSION);
64
+ const invalidMessageBuffer = Buffer.from('0102030405060708', 'hex'); // Not 32 bytes
65
+ expect(() => (0, verificationHelpers_1.signingRoot)(domain, invalidMessageBuffer)).toThrow();
66
+ });
67
+ });
68
+ });
@@ -34,10 +34,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
34
34
  var _a, _b;
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  const ethers_1 = require("ethers");
37
- const index_1 = require("../src/index");
38
- const utils = __importStar(require("../src/utils"));
39
- const incentivesHelpers = __importStar(require("../src/incentiveHelpers"));
40
- const constants_1 = require("../src/constants");
37
+ const index_1 = require("../../src/index");
38
+ const utils = __importStar(require("../../src/utils"));
39
+ const incentivesHelpers = __importStar(require("../../src/incentives/incentiveHelpers"));
40
+ const constants_1 = require("../../src/constants");
41
41
  const globals_1 = require("@jest/globals");
42
42
  const mnemonic = (_b = (_a = ethers_1.ethers.Wallet.createRandom().mnemonic) === null || _a === void 0 ? void 0 : _a.phrase) !== null && _b !== void 0 ? _b : '';
43
43
  const privateKey = ethers_1.ethers.Wallet.fromPhrase(mnemonic).privateKey;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@obolnetwork/obol-sdk",
3
- "version": "2.5.1",
3
+ "version": "2.7.0",
4
4
  "description": "A package for creating Distributed Validators using the Obol API.",
5
5
  "bugs": {
6
6
  "url": "https://github.com/obolnetwork/obol-sdk/issues"
@@ -15,7 +15,7 @@
15
15
  "compile": "tsc -b ./tsconfig.cjs.json ./tsconfig.esm.json ./tsconfig.types.json",
16
16
  "build:clean": "rm -rf ./dist",
17
17
  "build": "npm-run-all build:clean compile",
18
- "test": "jest ./test/*.test.ts",
18
+ "test": "jest test/**/*.spec.ts --testPathIgnorePatterns=test/sdk-package/",
19
19
  "generate-typedoc": "typedoc",
20
20
  "npm:publish": "npm publish --tag latest",
21
21
  "release": "release-it",
@@ -130,7 +130,7 @@
130
130
  "^bn.js$": "<rootDir>/node_modules/bn.js",
131
131
  "^asn1.js$": "<rootDir>/node_modules/asn1.js",
132
132
  "^hash.js$": "<rootDir>/node_modules/hash.js",
133
- "(.+)\\.js": "$1"
133
+ "^(\\.\\.?\\/.+)\\.js$": "$1"
134
134
  },
135
135
  "extensionsToTreatAsEsm": [
136
136
  ".ts"
@@ -149,3 +149,15 @@ export const PROVIDER_MAP = {
149
149
  11155111: `${process.env.RPC_SEPOLIA}`, // Sepolia
150
150
  100: `${process.env.RPC_GNOSIS}`, // Gnosis
151
151
  };
152
+ /**
153
+ * Maps base fork versions to their corresponding Capella fork versions.
154
+ * Example: Mainnet Capella fork version.
155
+ */
156
+ export const CAPELLA_FORK_MAPPING = {
157
+ '0x00000000': '0x03000000', // Mainnet
158
+ '0x00001020': '0x03001020', // Goerli
159
+ '0x00000064': '0x03000064', // Gnosis
160
+ '0x90000069': '0x90000072', // Sepolia
161
+ '0x01017000': '0x04017000', // Holesky
162
+ '0x10000910': '0x40000910', // Hoodi
163
+ };
@@ -0,0 +1,52 @@
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 { CAPELLA_FORK_MAPPING } from '../constants';
11
+ /**
12
+ * Retrieves the Capella fork version for a given base fork version.
13
+ * @param fork_version - The base fork version string (e.g., '0x00000000' for mainnet).
14
+ * @returns A promise that resolves to the Capella fork version string, or null if not found.
15
+ */
16
+ export function getCapellaFork(fork_version) {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ // Ensure the CAPELLA_FORK_MAPPING uses the base fork_version as key
19
+ if (CAPELLA_FORK_MAPPING[fork_version]) {
20
+ return CAPELLA_FORK_MAPPING[fork_version];
21
+ }
22
+ return null;
23
+ });
24
+ }
25
+ /**
26
+ * Fetches the genesis validators root from a beacon node.
27
+ * @param beaconNodeApiUrl - The base URL of the beacon node API (e.g., http://localhost:5052).
28
+ * @returns A promise that resolves to the genesis_validators_root string, or null on error.
29
+ * @throws Will throw an error if the network corresponding to the fork_version is not supported or if the HTTP request fails.
30
+ */
31
+ export function getGenesisValidatorsRoot(beaconNodeApiUrl) {
32
+ var _a;
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ const genesisEndpoint = `${beaconNodeApiUrl}/eth/v1/beacon/genesis`;
35
+ try {
36
+ const response = yield fetch(genesisEndpoint, {
37
+ method: 'GET',
38
+ });
39
+ const json = yield response.json();
40
+ if ((_a = json.data) === null || _a === void 0 ? void 0 : _a.genesis_validators_root) {
41
+ return json.data.genesis_validators_root;
42
+ }
43
+ console.error('Invalid response structure from genesis endpoint', json);
44
+ return null;
45
+ }
46
+ catch (e) {
47
+ console.error(`Error fetching genesis validators root from ${genesisEndpoint}:`, e);
48
+ const errorMessage = e instanceof Error ? e.message : String(e);
49
+ throw new Error(`Failed to fetch genesis validators root: ${errorMessage}`);
50
+ }
51
+ });
52
+ }