@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,281 @@
1
+ import { type EncryptableItem, FheTypes } from '../types.js';
2
+ import { MAX_ENCRYPTABLE_BITS, type VerifyResult } from './zkPackProveVerify.js';
3
+ import {
4
+ createWalletClient,
5
+ http,
6
+ encodePacked,
7
+ keccak256,
8
+ hashMessage,
9
+ toBytes,
10
+ type PublicClient,
11
+ type WalletClient,
12
+ } from 'viem';
13
+ import { MockZkVerifierAbi } from './MockZkVerifierAbi.js';
14
+ import { hardhat } from 'viem/chains';
15
+ import { CofheError, CofheErrorCode } from '../error.js';
16
+ import { privateKeyToAccount, sign } from 'viem/accounts';
17
+ import { MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_ADDRESS } from '../consts.js';
18
+
19
+ type EncryptableItemWithCtHash = EncryptableItem & {
20
+ ctHash: bigint;
21
+ };
22
+
23
+ function createMockZkVerifierSigner() {
24
+ return createWalletClient({
25
+ chain: hardhat,
26
+ transport: http(),
27
+ account: privateKeyToAccount(MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY),
28
+ });
29
+ }
30
+ /**
31
+ * The mocks don't use a tfhe builder, so we check the encryptable bits here to preserve parity
32
+ */
33
+ export async function cofheMocksCheckEncryptableBits(items: EncryptableItem[]): Promise<void> {
34
+ let totalBits = 0;
35
+ for (const item of items) {
36
+ switch (item.utype) {
37
+ case FheTypes.Bool: {
38
+ totalBits += 1;
39
+ break;
40
+ }
41
+ case FheTypes.Uint8: {
42
+ totalBits += 8;
43
+ break;
44
+ }
45
+ case FheTypes.Uint16: {
46
+ totalBits += 16;
47
+ break;
48
+ }
49
+ case FheTypes.Uint32: {
50
+ totalBits += 32;
51
+ break;
52
+ }
53
+ case FheTypes.Uint64: {
54
+ totalBits += 64;
55
+ break;
56
+ }
57
+ case FheTypes.Uint128: {
58
+ totalBits += 128;
59
+ break;
60
+ }
61
+ // [U256-DISABLED]
62
+ // case FheTypes.Uint256: {
63
+ // totalBits += 256;
64
+ // break;
65
+ // }
66
+ case FheTypes.Uint160: {
67
+ totalBits += 160;
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ if (totalBits > MAX_ENCRYPTABLE_BITS) {
73
+ throw new CofheError({
74
+ code: CofheErrorCode.ZkPackFailed,
75
+ message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
76
+ hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
77
+ context: {
78
+ totalBits,
79
+ maxBits: MAX_ENCRYPTABLE_BITS,
80
+ items,
81
+ },
82
+ });
83
+ }
84
+ }
85
+
86
+ /**
87
+ * In the mocks context, we use the MockZkVerifier contract to calculate the ctHashes.
88
+ */
89
+ async function calcCtHashes(
90
+ items: EncryptableItem[],
91
+ account: string,
92
+ securityZone: number,
93
+ publicClient: PublicClient
94
+ ): Promise<EncryptableItemWithCtHash[]> {
95
+ const calcCtHashesArgs = [
96
+ items.map(({ data }) => BigInt(data)),
97
+ items.map(({ utype }) => utype),
98
+ account as `0x${string}`,
99
+ securityZone,
100
+ BigInt(hardhat.id),
101
+ ] as const;
102
+
103
+ let ctHashes: bigint[];
104
+
105
+ try {
106
+ ctHashes = (await publicClient.readContract({
107
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
108
+ abi: MockZkVerifierAbi,
109
+ functionName: 'zkVerifyCalcCtHashesPacked',
110
+ args: calcCtHashesArgs,
111
+ })) as bigint[];
112
+ } catch (err) {
113
+ throw new CofheError({
114
+ code: CofheErrorCode.ZkMocksCalcCtHashesFailed,
115
+ message: `mockZkVerifySign calcCtHashes failed while calling zkVerifyCalcCtHashesPacked`,
116
+ cause: err instanceof Error ? err : undefined,
117
+ context: {
118
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
119
+ items,
120
+ account,
121
+ securityZone,
122
+ publicClient,
123
+ calcCtHashesArgs,
124
+ },
125
+ });
126
+ }
127
+
128
+ if (ctHashes.length !== items.length) {
129
+ throw new CofheError({
130
+ code: CofheErrorCode.ZkMocksCalcCtHashesFailed,
131
+ message: `mockZkVerifySign calcCtHashes returned incorrect number of ctHashes`,
132
+ context: {
133
+ items,
134
+ account,
135
+ securityZone,
136
+ publicClient,
137
+ calcCtHashesArgs,
138
+ ctHashes,
139
+ },
140
+ });
141
+ }
142
+
143
+ return items.map((item, index) => ({
144
+ ...item,
145
+ ctHash: ctHashes[index],
146
+ }));
147
+ }
148
+
149
+ /**
150
+ * Insert the calculated ctHashes into the MockZkVerifier contract along with the plaintext values.
151
+ * The plaintext values are used on chain to simulate the true FHE operations.
152
+ */
153
+ async function insertCtHashes(items: EncryptableItemWithCtHash[], walletClient: WalletClient): Promise<void> {
154
+ const insertPackedCtHashesArgs = [items.map(({ ctHash }) => ctHash), items.map(({ data }) => BigInt(data))] as const;
155
+ try {
156
+ const account = walletClient.account!;
157
+
158
+ await walletClient.writeContract({
159
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
160
+ abi: MockZkVerifierAbi,
161
+ functionName: 'insertPackedCtHashes',
162
+ args: insertPackedCtHashesArgs,
163
+ chain: hardhat,
164
+ account: account,
165
+ });
166
+ } catch (err) {
167
+ throw new CofheError({
168
+ code: CofheErrorCode.ZkMocksInsertCtHashesFailed,
169
+ message: `mockZkVerifySign insertPackedCtHashes failed while calling insertPackedCtHashes`,
170
+ cause: err instanceof Error ? err : undefined,
171
+ context: {
172
+ items,
173
+ walletClient,
174
+ insertPackedCtHashesArgs,
175
+ },
176
+ });
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The mocks verify the EncryptedInputs' signature against the known proof signer account.
182
+ * Locally, we create the proof signatures from the known proof signer account.
183
+ */
184
+ async function createProofSignatures(
185
+ items: EncryptableItemWithCtHash[],
186
+ securityZone: number,
187
+ account: string
188
+ ): Promise<string[]> {
189
+ let signatures: string[] = [];
190
+
191
+ // Create wallet client for the encrypted input signer
192
+ // This wallet won't send a transaction, so gas isn't needed
193
+ // This wallet doesn't need to be connected to the network
194
+ let encInputSignerClient: WalletClient | undefined;
195
+
196
+ try {
197
+ encInputSignerClient = createMockZkVerifierSigner();
198
+ } catch (err) {
199
+ throw new CofheError({
200
+ code: CofheErrorCode.ZkMocksCreateProofSignatureFailed,
201
+ message: `mockZkVerifySign createProofSignatures failed while creating wallet client`,
202
+ cause: err instanceof Error ? err : undefined,
203
+ context: {
204
+ MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY,
205
+ },
206
+ });
207
+ }
208
+
209
+ try {
210
+ for (const item of items) {
211
+ // Pack the data into bytes and hash it
212
+ const packedData = encodePacked(
213
+ ['uint256', 'uint8', 'uint8', 'address', 'uint256'],
214
+ [BigInt(item.ctHash), item.utype, securityZone, account as `0x${string}`, BigInt(hardhat.id)]
215
+ );
216
+ const messageHash = keccak256(packedData);
217
+
218
+ const signature = await sign({
219
+ hash: messageHash,
220
+ privateKey: MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY,
221
+ to: 'hex',
222
+ });
223
+
224
+ signatures.push(signature);
225
+ }
226
+ } catch (err) {
227
+ throw new CofheError({
228
+ code: CofheErrorCode.ZkMocksCreateProofSignatureFailed,
229
+ message: `mockZkVerifySign createProofSignatures failed while calling signMessage`,
230
+ cause: err instanceof Error ? err : undefined,
231
+ context: {
232
+ items,
233
+ securityZone,
234
+ },
235
+ });
236
+ }
237
+
238
+ if (signatures.length !== items.length) {
239
+ throw new CofheError({
240
+ code: CofheErrorCode.ZkMocksCreateProofSignatureFailed,
241
+ message: `mockZkVerifySign createProofSignatures returned incorrect number of signatures`,
242
+ context: {
243
+ items,
244
+ securityZone,
245
+ },
246
+ });
247
+ }
248
+
249
+ return signatures;
250
+ }
251
+
252
+ /**
253
+ * Transforms the encryptable items into EncryptedInputs ready to be used in a transaction on the hardhat chain.
254
+ * The EncryptedInputs are returned in the same format as from CoFHE, and include on-chain verifiable signatures.
255
+ */
256
+ export async function cofheMocksZkVerifySign(
257
+ items: EncryptableItem[],
258
+ account: string,
259
+ securityZone: number,
260
+ publicClient: PublicClient,
261
+ walletClient: WalletClient,
262
+ zkvWalletClient: WalletClient | undefined
263
+ ): Promise<VerifyResult[]> {
264
+ // Use config._internal?.zkvWalletClient if provided, otherwise use a mock zk verifier signer
265
+ const _walletClient = zkvWalletClient ?? createMockZkVerifierSigner();
266
+
267
+ // Call MockZkVerifier contract to calculate the ctHashes
268
+ const encryptableItems = await calcCtHashes(items, account, securityZone, publicClient);
269
+
270
+ // Insert the ctHashes into the MockZkVerifier contract
271
+ await insertCtHashes(encryptableItems, _walletClient);
272
+
273
+ // Locally create the proof signatures from the known proof signer account
274
+ const signatures = await createProofSignatures(encryptableItems, securityZone, account);
275
+
276
+ // Return the ctHashes and signatures in the same format as CoFHE
277
+ return encryptableItems.map((item, index) => ({
278
+ ct_hash: item.ctHash.toString(),
279
+ signature: signatures[index],
280
+ }));
281
+ }