@cofhe/sdk 0.0.0-alpha-20260409113701

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 (132) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/adapters/ethers5.test.ts +174 -0
  3. package/adapters/ethers5.ts +36 -0
  4. package/adapters/ethers6.test.ts +169 -0
  5. package/adapters/ethers6.ts +36 -0
  6. package/adapters/hardhat-node.ts +167 -0
  7. package/adapters/hardhat.hh2.test.ts +159 -0
  8. package/adapters/hardhat.ts +36 -0
  9. package/adapters/index.test.ts +20 -0
  10. package/adapters/index.ts +5 -0
  11. package/adapters/smartWallet.ts +99 -0
  12. package/adapters/test-utils.ts +53 -0
  13. package/adapters/types.ts +6 -0
  14. package/adapters/wagmi.test.ts +156 -0
  15. package/adapters/wagmi.ts +17 -0
  16. package/chains/chains/arbSepolia.ts +14 -0
  17. package/chains/chains/baseSepolia.ts +14 -0
  18. package/chains/chains/hardhat.ts +15 -0
  19. package/chains/chains/localcofhe.ts +14 -0
  20. package/chains/chains/sepolia.ts +14 -0
  21. package/chains/chains.test.ts +50 -0
  22. package/chains/defineChain.ts +18 -0
  23. package/chains/index.ts +35 -0
  24. package/chains/types.ts +32 -0
  25. package/core/baseBuilder.ts +119 -0
  26. package/core/client.test.ts +429 -0
  27. package/core/client.ts +341 -0
  28. package/core/clientTypes.ts +119 -0
  29. package/core/config.test.ts +242 -0
  30. package/core/config.ts +225 -0
  31. package/core/consts.ts +22 -0
  32. package/core/decrypt/MockThresholdNetworkAbi.ts +179 -0
  33. package/core/decrypt/cofheMocksDecryptForTx.ts +84 -0
  34. package/core/decrypt/cofheMocksDecryptForView.ts +48 -0
  35. package/core/decrypt/decryptForTxBuilder.ts +359 -0
  36. package/core/decrypt/decryptForViewBuilder.ts +332 -0
  37. package/core/decrypt/decryptUtils.ts +28 -0
  38. package/core/decrypt/pollCallbacks.test.ts +194 -0
  39. package/core/decrypt/polling.ts +14 -0
  40. package/core/decrypt/tnDecryptUtils.ts +65 -0
  41. package/core/decrypt/tnDecryptV1.ts +171 -0
  42. package/core/decrypt/tnDecryptV2.ts +365 -0
  43. package/core/decrypt/tnSealOutputV1.ts +59 -0
  44. package/core/decrypt/tnSealOutputV2.ts +324 -0
  45. package/core/decrypt/verifyDecryptResult.ts +52 -0
  46. package/core/encrypt/MockZkVerifierAbi.ts +106 -0
  47. package/core/encrypt/cofheMocksZkVerifySign.ts +281 -0
  48. package/core/encrypt/encryptInputsBuilder.test.ts +747 -0
  49. package/core/encrypt/encryptInputsBuilder.ts +583 -0
  50. package/core/encrypt/encryptUtils.ts +67 -0
  51. package/core/encrypt/zkPackProveVerify.ts +335 -0
  52. package/core/error.ts +168 -0
  53. package/core/fetchKeys.test.ts +195 -0
  54. package/core/fetchKeys.ts +144 -0
  55. package/core/index.ts +106 -0
  56. package/core/keyStore.test.ts +226 -0
  57. package/core/keyStore.ts +154 -0
  58. package/core/permits.test.ts +493 -0
  59. package/core/permits.ts +201 -0
  60. package/core/types.ts +419 -0
  61. package/core/utils.ts +130 -0
  62. package/dist/adapters.cjs +88 -0
  63. package/dist/adapters.d.cts +14576 -0
  64. package/dist/adapters.d.ts +14576 -0
  65. package/dist/adapters.js +83 -0
  66. package/dist/chains.cjs +111 -0
  67. package/dist/chains.d.cts +121 -0
  68. package/dist/chains.d.ts +121 -0
  69. package/dist/chains.js +1 -0
  70. package/dist/chunk-36FBWLUS.js +3310 -0
  71. package/dist/chunk-7HLGHV67.js +990 -0
  72. package/dist/chunk-TBLR7NNE.js +102 -0
  73. package/dist/clientTypes-AVSCBet7.d.cts +998 -0
  74. package/dist/clientTypes-flH1ju82.d.ts +998 -0
  75. package/dist/core.cjs +4362 -0
  76. package/dist/core.d.cts +138 -0
  77. package/dist/core.d.ts +138 -0
  78. package/dist/core.js +3 -0
  79. package/dist/node.cjs +4225 -0
  80. package/dist/node.d.cts +22 -0
  81. package/dist/node.d.ts +22 -0
  82. package/dist/node.js +91 -0
  83. package/dist/permit-jRirYqFt.d.cts +376 -0
  84. package/dist/permit-jRirYqFt.d.ts +376 -0
  85. package/dist/permits.cjs +1025 -0
  86. package/dist/permits.d.cts +353 -0
  87. package/dist/permits.d.ts +353 -0
  88. package/dist/permits.js +1 -0
  89. package/dist/types-YiAC4gig.d.cts +33 -0
  90. package/dist/types-YiAC4gig.d.ts +33 -0
  91. package/dist/web.cjs +4434 -0
  92. package/dist/web.d.cts +42 -0
  93. package/dist/web.d.ts +42 -0
  94. package/dist/web.js +256 -0
  95. package/dist/zkProve.worker.cjs +93 -0
  96. package/dist/zkProve.worker.d.cts +2 -0
  97. package/dist/zkProve.worker.d.ts +2 -0
  98. package/dist/zkProve.worker.js +91 -0
  99. package/node/client.test.ts +159 -0
  100. package/node/config.test.ts +68 -0
  101. package/node/encryptInputs.test.ts +155 -0
  102. package/node/index.ts +97 -0
  103. package/node/storage.ts +51 -0
  104. package/package.json +121 -0
  105. package/permits/index.ts +68 -0
  106. package/permits/localstorage.test.ts +113 -0
  107. package/permits/onchain-utils.ts +221 -0
  108. package/permits/permit.test.ts +534 -0
  109. package/permits/permit.ts +386 -0
  110. package/permits/sealing.test.ts +84 -0
  111. package/permits/sealing.ts +131 -0
  112. package/permits/signature.ts +79 -0
  113. package/permits/store.test.ts +88 -0
  114. package/permits/store.ts +156 -0
  115. package/permits/test-utils.ts +28 -0
  116. package/permits/types.ts +204 -0
  117. package/permits/utils.ts +58 -0
  118. package/permits/validation.test.ts +361 -0
  119. package/permits/validation.ts +327 -0
  120. package/web/client.web.test.ts +159 -0
  121. package/web/config.web.test.ts +69 -0
  122. package/web/const.ts +2 -0
  123. package/web/encryptInputs.web.test.ts +172 -0
  124. package/web/index.ts +166 -0
  125. package/web/storage.ts +49 -0
  126. package/web/worker.builder.web.test.ts +148 -0
  127. package/web/worker.config.web.test.ts +329 -0
  128. package/web/worker.output.web.test.ts +84 -0
  129. package/web/workerManager.test.ts +80 -0
  130. package/web/workerManager.ts +214 -0
  131. package/web/workerManager.web.test.ts +114 -0
  132. package/web/zkProve.worker.ts +133 -0
@@ -0,0 +1,386 @@
1
+ import { keccak256, toHex, zeroAddress, parseAbi, type PublicClient, type WalletClient } from 'viem';
2
+ import {
3
+ type Permit,
4
+ type SelfPermit,
5
+ type SharingPermit,
6
+ type RecipientPermit,
7
+ type CreateSelfPermitOptions,
8
+ type CreateSharingPermitOptions,
9
+ type ImportSharedPermitOptions,
10
+ type SerializedPermit,
11
+ type EIP712Domain,
12
+ type Permission,
13
+ type EthEncryptedData,
14
+ type PermitHashFields,
15
+ } from './types.js';
16
+ import {
17
+ validateSelfPermitOptions,
18
+ validateSharingPermitOptions,
19
+ validateImportPermitOptions,
20
+ validateSelfPermit,
21
+ validateSharingPermit,
22
+ validateImportPermit,
23
+ ValidationUtils,
24
+ } from './validation.js';
25
+ import * as z from 'zod';
26
+ import { SignatureUtils } from './signature.js';
27
+ import { GenerateSealingKey, SealingKey } from './sealing.js';
28
+ import { checkPermitValidityOnChain, getAclEIP712Domain } from './onchain-utils.js';
29
+
30
+ /**
31
+ * Main Permit utilities - functional approach for React compatibility
32
+ */
33
+ export const PermitUtils = {
34
+ /**
35
+ * Create a self permit for personal use
36
+ */
37
+ createSelf: (options: CreateSelfPermitOptions): SelfPermit => {
38
+ const validation = validateSelfPermitOptions(options);
39
+
40
+ // Always generate a new sealing key - users cannot provide their own
41
+ const sealingPair = GenerateSealingKey();
42
+
43
+ const permit = {
44
+ hash: PermitUtils.getHash(validation),
45
+ ...validation,
46
+ sealingPair,
47
+ _signedDomain: undefined,
48
+ } satisfies SelfPermit;
49
+
50
+ return permit;
51
+ },
52
+
53
+ /**
54
+ * Create a sharing permit to be shared with another user
55
+ */
56
+ createSharing: (options: CreateSharingPermitOptions): SharingPermit => {
57
+ const validation = validateSharingPermitOptions(options);
58
+
59
+ // Always generate a new sealing key - users cannot provide their own
60
+ const sealingPair = GenerateSealingKey();
61
+
62
+ const permit = {
63
+ hash: PermitUtils.getHash(validation),
64
+ ...validation,
65
+ sealingPair,
66
+ _signedDomain: undefined,
67
+ } satisfies SharingPermit;
68
+
69
+ return permit;
70
+ },
71
+
72
+ /**
73
+ * Import a shared permit from various input formats
74
+ */
75
+ importShared: (options: ImportSharedPermitOptions | string): RecipientPermit => {
76
+ let parsedOptions: ImportSharedPermitOptions;
77
+
78
+ // Handle different input types
79
+ if (typeof options === 'string') {
80
+ // Parse JSON string
81
+ try {
82
+ parsedOptions = JSON.parse(options);
83
+ } catch (error) {
84
+ throw new Error(`Failed to parse JSON string: ${error}`);
85
+ }
86
+ } else if (typeof options === 'object' && options !== null) {
87
+ // Handle both ImportSharedPermitOptions and any object
88
+ parsedOptions = options;
89
+ } else {
90
+ throw new Error('Invalid input type, expected ImportSharedPermitOptions, object, or string');
91
+ }
92
+
93
+ // Validate type if provided
94
+ if (parsedOptions.type != null && parsedOptions.type !== 'sharing') {
95
+ throw new Error(`Invalid permit type <${parsedOptions.type}>, must be "sharing"`);
96
+ }
97
+
98
+ const validation = validateImportPermitOptions({ ...parsedOptions, type: 'recipient' });
99
+
100
+ // Always generate a new sealing key - users cannot provide their own
101
+ const sealingPair = GenerateSealingKey();
102
+
103
+ const permit = {
104
+ hash: PermitUtils.getHash(validation),
105
+ ...validation,
106
+ sealingPair,
107
+ _signedDomain: undefined,
108
+ } satisfies RecipientPermit;
109
+
110
+ return permit;
111
+ },
112
+
113
+ /**
114
+ * Sign a permit with the provided wallet client
115
+ */
116
+ sign: async <T extends Permit>(permit: T, publicClient: PublicClient, walletClient: WalletClient): Promise<T> => {
117
+ if (walletClient == null || walletClient.account == null) {
118
+ throw new Error(
119
+ 'Missing walletClient, you must pass in a `walletClient` for the connected user to create a permit signature'
120
+ );
121
+ }
122
+
123
+ const primaryType = SignatureUtils.getPrimaryType(permit.type);
124
+ const domain = await getAclEIP712Domain(publicClient);
125
+ const { types, message } = SignatureUtils.getSignatureParams(PermitUtils.getPermission(permit, true), primaryType);
126
+
127
+ const signature = await walletClient.signTypedData({
128
+ domain,
129
+ types,
130
+ primaryType,
131
+ message,
132
+ account: walletClient.account,
133
+ });
134
+
135
+ let updatedPermit: Permit;
136
+ if (permit.type === 'self' || permit.type === 'sharing') {
137
+ updatedPermit = {
138
+ ...permit,
139
+ issuerSignature: signature,
140
+ _signedDomain: domain,
141
+ };
142
+ } else {
143
+ updatedPermit = {
144
+ ...permit,
145
+ recipientSignature: signature,
146
+ _signedDomain: domain,
147
+ };
148
+ }
149
+
150
+ return updatedPermit as T;
151
+ },
152
+
153
+ /**
154
+ * Create and sign a self permit in one operation
155
+ */
156
+ createSelfAndSign: async (
157
+ options: CreateSelfPermitOptions,
158
+ publicClient: PublicClient,
159
+ walletClient: WalletClient
160
+ ): Promise<SelfPermit> => {
161
+ const permit = PermitUtils.createSelf(options);
162
+ return PermitUtils.sign(permit, publicClient, walletClient);
163
+ },
164
+
165
+ /**
166
+ * Create and sign a sharing permit in one operation
167
+ */
168
+ createSharingAndSign: async (
169
+ options: CreateSharingPermitOptions,
170
+ publicClient: PublicClient,
171
+ walletClient: WalletClient
172
+ ): Promise<SharingPermit> => {
173
+ const permit = PermitUtils.createSharing(options);
174
+ return PermitUtils.sign(permit, publicClient, walletClient);
175
+ },
176
+
177
+ /**
178
+ * Import and sign a shared permit in one operation from various input formats
179
+ */
180
+ importSharedAndSign: async (
181
+ options: ImportSharedPermitOptions | string,
182
+ publicClient: PublicClient,
183
+ walletClient: WalletClient
184
+ ): Promise<RecipientPermit> => {
185
+ const permit = PermitUtils.importShared(options);
186
+ return PermitUtils.sign(permit, publicClient, walletClient);
187
+ },
188
+
189
+ /**
190
+ * Deserialize a permit from serialized data
191
+ */
192
+ deserialize: (data: SerializedPermit): Permit => {
193
+ return {
194
+ ...data,
195
+ sealingPair: SealingKey.deserialize(data.sealingPair.privateKey, data.sealingPair.publicKey),
196
+ };
197
+ },
198
+
199
+ /**
200
+ * Serialize a permit for storage
201
+ */
202
+ serialize: (permit: Permit): SerializedPermit => {
203
+ return {
204
+ hash: permit.hash,
205
+ name: permit.name,
206
+ type: permit.type,
207
+ issuer: permit.issuer,
208
+ expiration: permit.expiration,
209
+ recipient: permit.recipient,
210
+ validatorId: permit.validatorId,
211
+ validatorContract: permit.validatorContract,
212
+ issuerSignature: permit.issuerSignature,
213
+ recipientSignature: permit.recipientSignature,
214
+ _signedDomain: permit._signedDomain,
215
+ sealingPair: permit.sealingPair.serialize(),
216
+ };
217
+ },
218
+
219
+ /**
220
+ * Validate a permit (schema-level validation)
221
+ */
222
+ validateSchema: (permit: Permit) => {
223
+ if (permit.type === 'self') {
224
+ return validateSelfPermit(permit);
225
+ } else if (permit.type === 'sharing') {
226
+ return validateSharingPermit(permit);
227
+ } else if (permit.type === 'recipient') {
228
+ return validateImportPermit(permit);
229
+ } else {
230
+ throw new Error('Invalid permit type');
231
+ }
232
+ },
233
+
234
+ /**
235
+ * Validate a permit (holistic validation).
236
+ *
237
+ * This validates:
238
+ * - Permit schema (shape + invariants)
239
+ * - Permit is signed
240
+ * - Permit is not expired
241
+ *
242
+ * For schema-only validation, use `validateSchema(permit)`.
243
+ */
244
+ validate: (permit: Permit) => {
245
+ const validated = PermitUtils.validateSchema(permit);
246
+ ValidationUtils.assertSignedAndNotExpired(validated as Permit);
247
+ return validated;
248
+ },
249
+
250
+ /**
251
+ * Get the permission object from a permit (for use in contracts)
252
+ */
253
+ getPermission: (permit: Permit, skipValidation = false): Permission => {
254
+ if (!skipValidation) {
255
+ PermitUtils.validateSchema(permit);
256
+ }
257
+
258
+ return {
259
+ issuer: permit.issuer,
260
+ expiration: permit.expiration,
261
+ recipient: permit.recipient,
262
+ validatorId: permit.validatorId,
263
+ validatorContract: permit.validatorContract,
264
+ sealingKey: `0x${permit.sealingPair.publicKey}`,
265
+ issuerSignature: permit.issuerSignature,
266
+ recipientSignature: permit.recipientSignature,
267
+ };
268
+ },
269
+
270
+ /**
271
+ * Get a stable hash for the permit (used as key in storage)
272
+ */
273
+ getHash: (permit: PermitHashFields): string => {
274
+ const data = JSON.stringify({
275
+ type: permit.type,
276
+ issuer: permit.issuer,
277
+ expiration: permit.expiration,
278
+ recipient: permit.recipient,
279
+ validatorId: permit.validatorId,
280
+ validatorContract: permit.validatorContract,
281
+ });
282
+ return keccak256(toHex(data));
283
+ },
284
+
285
+ /**
286
+ * Export permit data for sharing (removes sensitive fields)
287
+ */
288
+ export: (permit: Permit): string => {
289
+ const cleanedPermit: Record<string, unknown> = {
290
+ name: permit.name,
291
+ type: permit.type,
292
+ issuer: permit.issuer,
293
+ expiration: permit.expiration,
294
+ };
295
+
296
+ if (permit.recipient !== zeroAddress) cleanedPermit.recipient = permit.recipient;
297
+ if (permit.validatorId !== 0) cleanedPermit.validatorId = permit.validatorId;
298
+ if (permit.validatorContract !== zeroAddress) cleanedPermit.validatorContract = permit.validatorContract;
299
+ if (permit.type === 'sharing' && permit.issuerSignature !== '0x')
300
+ cleanedPermit.issuerSignature = permit.issuerSignature;
301
+
302
+ return JSON.stringify(cleanedPermit, undefined, 2);
303
+ },
304
+
305
+ /**
306
+ * Unseal encrypted data using the permit's sealing key
307
+ */
308
+ unseal: (permit: Permit, ciphertext: EthEncryptedData): bigint => {
309
+ return permit.sealingPair.unseal(ciphertext);
310
+ },
311
+
312
+ /**
313
+ * Check if permit is expired
314
+ */
315
+ isExpired: (permit: Permit): boolean => {
316
+ return ValidationUtils.isExpired(permit);
317
+ },
318
+
319
+ /**
320
+ * Check if permit is signed
321
+ */
322
+ isSigned: (permit: Permit): boolean => {
323
+ return ValidationUtils.isSigned(permit);
324
+ },
325
+
326
+ /**
327
+ * Check if permit is signed and not expired
328
+ */
329
+ isSignedAndNotExpired: (permit: Permit) => {
330
+ return ValidationUtils.isSignedAndNotExpired(permit);
331
+ },
332
+
333
+ /**
334
+ * Assert that permit is signed and not expired
335
+ */
336
+ assertSignedAndNotExpired: (permit: Permit): void => {
337
+ return ValidationUtils.assertSignedAndNotExpired(permit);
338
+ },
339
+
340
+ isValid: (permit: Permit) => {
341
+ return ValidationUtils.isValid(permit);
342
+ },
343
+
344
+ /**
345
+ * Update permit name (returns new permit instance)
346
+ */
347
+ updateName: (permit: Permit, name: string): Permit => {
348
+ return { ...permit, name };
349
+ },
350
+
351
+ /**
352
+ * Fetch EIP712 domain from the blockchain
353
+ */
354
+ fetchEIP712Domain: async (publicClient: PublicClient): Promise<EIP712Domain> => {
355
+ return getAclEIP712Domain(publicClient);
356
+ },
357
+
358
+ /**
359
+ * Check if permit's signed domain matches the provided domain
360
+ */
361
+ matchesDomain: (permit: Permit, domain: EIP712Domain): boolean => {
362
+ return (
363
+ permit._signedDomain?.name === domain.name &&
364
+ permit._signedDomain?.version === domain.version &&
365
+ permit._signedDomain?.verifyingContract === domain.verifyingContract &&
366
+ permit._signedDomain?.chainId === domain.chainId
367
+ );
368
+ },
369
+
370
+ /**
371
+ * Check if permit's signed domain is valid for the current chain
372
+ */
373
+ checkSignedDomainValid: async (permit: Permit, publicClient: PublicClient): Promise<boolean> => {
374
+ if (permit._signedDomain == null) return false;
375
+ const domain = await getAclEIP712Domain(publicClient);
376
+ return PermitUtils.matchesDomain(permit, domain);
377
+ },
378
+
379
+ /**
380
+ * Check if permit passes the on-chain validation
381
+ */
382
+ checkValidityOnChain: async (permit: Permit, publicClient: PublicClient): Promise<boolean> => {
383
+ const permission = PermitUtils.getPermission(permit);
384
+ return checkPermitValidityOnChain(permission, publicClient);
385
+ },
386
+ };
@@ -0,0 +1,84 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { SealingKey, GenerateSealingKey } from './index.js';
3
+
4
+ describe('SealingKey', () => {
5
+ it('should create a SealingKey with valid keys', () => {
6
+ const privateKey = 'a'.repeat(64);
7
+ const publicKey = 'b'.repeat(64);
8
+
9
+ const sealingKey = new SealingKey(privateKey, publicKey);
10
+
11
+ expect(sealingKey.privateKey).toBe(privateKey);
12
+ expect(sealingKey.publicKey).toBe(publicKey);
13
+ });
14
+
15
+ it('should throw error for invalid private key length', () => {
16
+ const privateKey = 'a'.repeat(32); // Too short
17
+ const publicKey = 'b'.repeat(64);
18
+
19
+ expect(() => {
20
+ new SealingKey(privateKey, publicKey);
21
+ }).toThrow('Private key must be of length 64');
22
+ });
23
+
24
+ it('should throw error for invalid public key length', () => {
25
+ const privateKey = 'a'.repeat(64);
26
+ const publicKey = 'b'.repeat(32); // Too short
27
+
28
+ expect(() => {
29
+ new SealingKey(privateKey, publicKey);
30
+ }).toThrow('Public key must be of length 64');
31
+ });
32
+
33
+ it('should seal and unseal data correctly', () => {
34
+ const publicKey = 'b'.repeat(64);
35
+ const value = BigInt(12345);
36
+
37
+ // Seal the data
38
+ const encryptedData = SealingKey.seal(value, publicKey);
39
+
40
+ expect(encryptedData).toHaveProperty('data');
41
+ expect(encryptedData).toHaveProperty('public_key');
42
+ expect(encryptedData).toHaveProperty('nonce');
43
+ expect(encryptedData.data).toBeInstanceOf(Uint8Array);
44
+ expect(encryptedData.public_key).toBeInstanceOf(Uint8Array);
45
+ expect(encryptedData.nonce).toBeInstanceOf(Uint8Array);
46
+ });
47
+
48
+ it('should throw error for invalid public key in seal', () => {
49
+ const value = BigInt(12345);
50
+ const invalidPublicKey = 'invalid';
51
+
52
+ expect(() => {
53
+ SealingKey.seal(value, invalidPublicKey);
54
+ }).toThrow('bad public key size');
55
+ });
56
+
57
+ it('should throw error for invalid value in seal', () => {
58
+ const publicKey = 'b'.repeat(64);
59
+ const invalidValue = 'not a number';
60
+
61
+ expect(() => {
62
+ // @ts-expect-error - invalid value
63
+ SealingKey.seal(invalidValue, publicKey);
64
+ }).toThrow('Value not a number is not a number or bigint: string');
65
+ });
66
+ });
67
+
68
+ describe('GenerateSealingKey', () => {
69
+ it('should generate a valid SealingKey', async () => {
70
+ const sealingKey = GenerateSealingKey();
71
+
72
+ expect(sealingKey).toBeInstanceOf(SealingKey);
73
+ expect(sealingKey.privateKey).toHaveLength(64);
74
+ expect(sealingKey.publicKey).toHaveLength(64);
75
+ });
76
+
77
+ it('should generate different keys on each call', async () => {
78
+ const key1 = GenerateSealingKey();
79
+ const key2 = GenerateSealingKey();
80
+
81
+ expect(key1.privateKey).not.toBe(key2.privateKey);
82
+ expect(key1.publicKey).not.toBe(key2.publicKey);
83
+ });
84
+ });
@@ -0,0 +1,131 @@
1
+ import nacl from 'tweetnacl';
2
+ import { fromHexString, toBeArray, toBigInt, toHexString, isBigIntOrNumber, isString } from './utils.js';
3
+
4
+ const PRIVATE_KEY_LENGTH = 64;
5
+ const PUBLIC_KEY_LENGTH = 64;
6
+
7
+ export type EthEncryptedData = {
8
+ data: Uint8Array;
9
+ public_key: Uint8Array;
10
+ nonce: Uint8Array;
11
+ };
12
+
13
+ /**
14
+ * A class representing a SealingKey which provides cryptographic sealing (encryption)
15
+ * and unsealing (decryption) capabilities.
16
+ */
17
+ export class SealingKey {
18
+ /**
19
+ * The private key used for decryption.
20
+ */
21
+ privateKey: string;
22
+ /**
23
+ * The public key used for encryption.
24
+ */
25
+ publicKey: string;
26
+
27
+ /**
28
+ * Constructs a SealingKey instance with the given private and public keys.
29
+ *
30
+ * @param {string} privateKey - The private key used for decryption.
31
+ * @param {string} publicKey - The public key used for encryption.
32
+ * @throws Will throw an error if the provided keys lengths do not match
33
+ * the required lengths for private and public keys.
34
+ */
35
+ constructor(privateKey: string, publicKey: string) {
36
+ if (privateKey.length !== PRIVATE_KEY_LENGTH) {
37
+ throw new Error(`Private key must be of length ${PRIVATE_KEY_LENGTH}`);
38
+ }
39
+
40
+ if (publicKey.length !== PUBLIC_KEY_LENGTH) {
41
+ throw new Error(`Public key must be of length ${PUBLIC_KEY_LENGTH}`);
42
+ }
43
+
44
+ this.privateKey = privateKey;
45
+ this.publicKey = publicKey;
46
+ }
47
+
48
+ unseal = (parsedData: EthEncryptedData): bigint => {
49
+ // Ensure all parameters are Uint8Array
50
+ const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
51
+
52
+ const ephemPublicKey =
53
+ parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
54
+
55
+ const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
56
+
57
+ // Make sure the private key is also a Uint8Array
58
+ const privateKeyBytes = fromHexString(this.privateKey);
59
+
60
+ // Debug information
61
+ // console.log("nonce length:", nonce.length);
62
+ // console.log("ephemPublicKey length:", ephemPublicKey.length);
63
+ // console.log("privateKeyBytes length:", privateKeyBytes.length);
64
+ // console.log("dataToDecrypt length:", dataToDecrypt.length);
65
+
66
+ // call the nacl box function to decrypt the data
67
+ const decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, privateKeyBytes);
68
+
69
+ if (!decryptedMessage) {
70
+ throw new Error('Failed to decrypt message');
71
+ }
72
+
73
+ return toBigInt(decryptedMessage);
74
+ };
75
+
76
+ /**
77
+ * Serializes the SealingKey to a JSON object.
78
+ */
79
+ serialize = () => {
80
+ return {
81
+ privateKey: this.privateKey,
82
+ publicKey: this.publicKey,
83
+ };
84
+ };
85
+
86
+ /**
87
+ * Deserializes the SealingKey from a JSON object.
88
+ */
89
+ static deserialize = (privateKey: string, publicKey: string): SealingKey => {
90
+ return new SealingKey(privateKey, publicKey);
91
+ };
92
+
93
+ /**
94
+ * Seals (encrypts) the provided message for a receiver with the specified public key.
95
+ *
96
+ * @param {bigint | number} value - The message to be encrypted.
97
+ * @param {string} publicKey - The public key of the intended recipient.
98
+ * @returns string - The encrypted message in hexadecimal format.
99
+ * @static
100
+ * @throws Will throw if the provided publicKey or value do not meet defined preconditions.
101
+ */
102
+ static seal = (value: bigint | number, publicKey: string): EthEncryptedData => {
103
+ isString(publicKey);
104
+ isBigIntOrNumber(value);
105
+
106
+ // generate ephemeral keypair
107
+ const ephemeralKeyPair = nacl.box.keyPair();
108
+
109
+ const nonce = nacl.randomBytes(nacl.box.nonceLength);
110
+
111
+ const encryptedMessage = nacl.box(toBeArray(value), nonce, fromHexString(publicKey), ephemeralKeyPair.secretKey);
112
+
113
+ return {
114
+ data: encryptedMessage,
115
+ public_key: ephemeralKeyPair.publicKey,
116
+ nonce: nonce,
117
+ };
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Asynchronously generates a new SealingKey.
123
+ * This function uses the 'nacl' library to create a new public/private key pair for sealing purposes.
124
+ * A sealing key is used to encrypt data such that it can only be unsealed (decrypted) by the owner of the corresponding private key.
125
+ * @returns {SealingKey} - A new SealingKey object containing the hexadecimal strings of the public and private keys.
126
+ */
127
+ export const GenerateSealingKey = (): SealingKey => {
128
+ const sodiumKeypair = nacl.box.keyPair();
129
+
130
+ return new SealingKey(toHexString(sodiumKeypair.secretKey), toHexString(sodiumKeypair.publicKey));
131
+ };
@@ -0,0 +1,79 @@
1
+ import { type EIP712Message, type EIP712Types, type Permission, type PermitSignaturePrimaryType } from './types.js';
2
+
3
+ const PermitSignatureAllFields = [
4
+ { name: 'issuer', type: 'address' },
5
+ { name: 'expiration', type: 'uint64' },
6
+ { name: 'recipient', type: 'address' },
7
+ { name: 'validatorId', type: 'uint256' },
8
+ { name: 'validatorContract', type: 'address' },
9
+ { name: 'sealingKey', type: 'bytes32' },
10
+ { name: 'issuerSignature', type: 'bytes' },
11
+ ] as const;
12
+
13
+ type PermitSignatureFieldOption = (typeof PermitSignatureAllFields)[number]['name'];
14
+
15
+ export const SignatureTypes = {
16
+ PermissionedV2IssuerSelf: [
17
+ 'issuer',
18
+ 'expiration',
19
+ 'recipient',
20
+ 'validatorId',
21
+ 'validatorContract',
22
+ 'sealingKey',
23
+ ] satisfies PermitSignatureFieldOption[],
24
+ PermissionedV2IssuerShared: [
25
+ 'issuer',
26
+ 'expiration',
27
+ 'recipient',
28
+ 'validatorId',
29
+ 'validatorContract',
30
+ ] satisfies PermitSignatureFieldOption[],
31
+ PermissionedV2Recipient: ['sealingKey', 'issuerSignature'] satisfies PermitSignatureFieldOption[],
32
+ } as const;
33
+
34
+ /**
35
+ * Get signature types and message for EIP712 signing
36
+ */
37
+ export const getSignatureTypesAndMessage = <T extends PermitSignatureFieldOption>(
38
+ primaryType: PermitSignaturePrimaryType,
39
+ fields: T[] | readonly T[],
40
+ values: Pick<Permission, T> & Partial<Permission>
41
+ ): { types: EIP712Types; primaryType: string; message: EIP712Message } => {
42
+ const types = {
43
+ [primaryType]: PermitSignatureAllFields.filter((fieldType) => fields.includes(fieldType.name as T)),
44
+ };
45
+
46
+ const message: Record<T, string | string[] | number | number[]> = {} as Record<
47
+ T,
48
+ string | string[] | number | number[]
49
+ >;
50
+ fields.forEach((field) => {
51
+ if (field in values) {
52
+ message[field] = values[field];
53
+ }
54
+ });
55
+
56
+ return { types, primaryType, message: message as EIP712Message };
57
+ };
58
+
59
+ /**
60
+ * Signature utilities for permit operations
61
+ */
62
+ export const SignatureUtils = {
63
+ /**
64
+ * Get signature parameters for a permit
65
+ */
66
+ getSignatureParams: (permit: Permission, primaryType: PermitSignaturePrimaryType) => {
67
+ return getSignatureTypesAndMessage(primaryType, SignatureTypes[primaryType], permit);
68
+ },
69
+
70
+ /**
71
+ * Determine the required signature type based on permit type
72
+ */
73
+ getPrimaryType: (permitType: 'self' | 'sharing' | 'recipient'): PermitSignaturePrimaryType => {
74
+ if (permitType === 'self') return 'PermissionedV2IssuerSelf';
75
+ if (permitType === 'sharing') return 'PermissionedV2IssuerShared';
76
+ if (permitType === 'recipient') return 'PermissionedV2Recipient';
77
+ throw new Error(`Unknown permit type: ${permitType}`);
78
+ },
79
+ };