@zama-fhe/relayer-sdk 0.4.0-alpha.0 → 0.4.0-alpha.2

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.
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ import { parseCommonOptions } from '../utils.js';
4
+
5
+ // npx . config
6
+ // npx . config --name testnet
7
+ // npx . config --name devnet
8
+ // npx . config --contract-address 0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9 --user-address 0x37AC010c1c566696326813b840319B58Bb5840E4
9
+ export async function configCommand(options) {
10
+ const { config } = parseCommonOptions(options);
11
+
12
+ console.log(JSON.stringify(config, null, 2));
13
+ }
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ import { parseCommonOptions, parseHandles } from '../utils.js';
4
+
5
+ /*
6
+ "0x23dbf1687ffafbc15853416621ca14c09fea621d74000000000000aa36a70000"
7
+ "0xf96aab67148b26af2423a849f18114a39b8d8a7433000000000000aa36a70000"
8
+ "0x4b8cb305c234bc4a4b7de2fe3f5b121a72f249e1a6000000000000aa36a70000"
9
+ "0x646315ed2a2153795a011b8091bb1c4e6ae6d7fd4f000000000000aa36a70200"
10
+ "0xe49cb5d474bde768be1f68b4a144823885db839ffe000000000000aa36a70000"
11
+ "0x70cae442f5545bb892158b1dac9b036daac2481210000000000000aa36a70000"
12
+ "0x954859342a33ba51e8ab897f9e5f27e53e9975068f000000000000aa36a70000"
13
+ "0xb642793478114df3f6c2c04cd49d5ca092c41438b1ff0000000000aa36a70000"
14
+ "0xe41e81c8d93596bb3c8cbd813e683ab0f21c42a6ecff0000000000aa36a70400"
15
+ "0x7db07d2c2aed31571bbe4fe62ee84f1e8967c3869a000000000000aa36a70000"
16
+ */
17
+ // npx . handle "0x36a1f452f2c26d7cbf329d23220d92c342062fa7f7000000000000aa36a70000 0xce6f699529292547e11ad7635537997fef29519ecf010000000000aa36a70200 0x9162215c0789609fb2132615c76e80af78209797d9020000000000aa36a70600 0xa8225e1781cab16dedf1b9a5f5c0ed0f03b64d1fb3030000000000aa36a70700"
18
+ export async function handleCommand(args, options) {
19
+ const { config } = parseCommonOptions(options);
20
+ const fhevmHandles = parseHandles(args);
21
+ console.log(JSON.stringify(fhevmHandles, null, 2));
22
+ }
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+
3
+ import {
4
+ isFheTypeName,
5
+ encryptionBitsFromFheTypeName,
6
+ FhevmHandle,
7
+ bytesToHex,
8
+ safeJSONstringify,
9
+ } from '../../lib/internal.js';
10
+ import { getInstance } from '../instance.js';
11
+ import { loadFhevmPubKey } from '../pubkeyCache.js';
12
+ import {
13
+ fheTypedValuesToBuilderFunctionWithArg,
14
+ logCLI,
15
+ parseCommonOptions,
16
+ throwError,
17
+ valueColumnTypeListToFheTypedValues,
18
+ } from '../utils.js';
19
+
20
+ // npx . input-proof --values 123:euint32 true:ebool 1234567890123456789:euint256 0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9:eaddress
21
+ // npx . input-proof --contract-address 0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9 --user-address 0x37AC010c1c566696326813b840319B58Bb5840E4 --values 123:euint32
22
+ export async function inputProofCommand(options) {
23
+ const { config } = parseCommonOptions(options);
24
+
25
+ const fheTypedValues = valueColumnTypeListToFheTypedValues(options.values);
26
+ const arr = fheTypedValuesToBuilderFunctionWithArg(fheTypedValues);
27
+
28
+ const { publicKey, publicParams } = await loadFhevmPubKey(config, options);
29
+
30
+ try {
31
+ const instance = await getInstance(
32
+ {
33
+ ...config.fhevmInstanceConfig,
34
+ publicKey,
35
+ publicParams,
36
+ },
37
+ options,
38
+ );
39
+
40
+ const builder = instance.createEncryptedInput(
41
+ config.contractAddress,
42
+ config.userAddress,
43
+ );
44
+ for (let i = 0; i < arr.length; ++i) {
45
+ builder[arr[i].funcName](arr[i].arg);
46
+ }
47
+
48
+ logCLI(`🎲 generating zkproof...`, options);
49
+ const zkproof = builder.generateZKProof();
50
+
51
+ logCLI(`🎲 verifying zkproof...`, options);
52
+ const { handles, inputProof } = await instance.requestZKProofVerification(
53
+ zkproof,
54
+ {
55
+ onProgress: (args) => {
56
+ logCLI(`onProgress: ${args.type}`, options);
57
+ },
58
+ },
59
+ );
60
+
61
+ const o = {
62
+ values: fheTypedValues,
63
+ handles: handles.map((h) => FhevmHandle.fromBytes32(h).toBytes32Hex()),
64
+ inputProof: bytesToHex(inputProof),
65
+ };
66
+
67
+ console.log(safeJSONstringify(o, 2));
68
+ } catch (e) {
69
+ console.log(e.message);
70
+ console.log(e);
71
+ console.log(JSON.stringify(e.cause, null, 2));
72
+
73
+ process.exit(1);
74
+ }
75
+ }
@@ -0,0 +1,18 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { homedir } from 'os';
4
+ import { logCLI } from '../utils';
5
+
6
+ // npx . pubkey clear
7
+ export async function pubkeyClearCommand(options) {
8
+ const cacheDir = path.join(homedir(), '.fhevm');
9
+
10
+ logCLI(`🎃 FHEVM pubKey cache directory: ${cacheDir}`, options);
11
+
12
+ if (fs.existsSync(cacheDir)) {
13
+ fs.rmSync(cacheDir, { recursive: true });
14
+ logCLI(`✅ FHEVM pubKey cache cleared.`, options);
15
+ } else {
16
+ logCLI(`✅ FHEVM pubKey cache is empty.`, options);
17
+ }
18
+ }
@@ -0,0 +1,9 @@
1
+ import { parseCommonOptions } from '../utils.js';
2
+ import { loadFhevmPubKey } from '../pubkeyCache.js';
3
+
4
+ // npx . pubkey fetch
5
+ export async function pubkeyFetchCommand(options) {
6
+ const { config } = parseCommonOptions(options);
7
+
8
+ await loadFhevmPubKey(config, options);
9
+ }
@@ -0,0 +1,44 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { homedir } from 'os';
4
+ import { TFHECrs, TFHEPublicKey } from '../../lib/internal.js';
5
+ import { logCLI } from '../utils.js';
6
+
7
+ // npx . pubkey info
8
+ export async function pubkeyInfoCommand(options) {
9
+ const cacheDir = path.join(homedir(), '.fhevm');
10
+
11
+ const pubKeyFile = path.join(cacheDir, 'pubkey.json');
12
+ const pubKeyParams2048File = path.join(cacheDir, 'pubkey-params-2048.json');
13
+
14
+ logCLI(`cache directory : ${cacheDir}`, options);
15
+ logCLI(`pubKey file : ${pubKeyFile}`, options);
16
+ logCLI(`pubKeyParams2048 file : ${pubKeyParams2048File}`, options);
17
+
18
+ if (fs.existsSync(pubKeyFile)) {
19
+ logCLI(
20
+ `✅ pubKey file size : ${fs.statSync(pubKeyFile).size} bytes`,
21
+ options,
22
+ );
23
+ const pk = TFHEPublicKey.fromJSON(
24
+ JSON.parse(fs.readFileSync(pubKeyFile, 'utf-8')),
25
+ );
26
+ logCLI(`✅ pubKey id : ${pk.id}`, options);
27
+ } else {
28
+ logCLI(`❌ pubKey file size : file does not exist`, options);
29
+ }
30
+
31
+ if (fs.existsSync(pubKeyParams2048File)) {
32
+ logCLI(
33
+ `✅ pubKeyParams2048 file size : ${fs.statSync(pubKeyParams2048File).size} bytes`,
34
+ options,
35
+ );
36
+ const crs = TFHECrs.fromJSON(
37
+ JSON.parse(fs.readFileSync(pubKeyParams2048File, 'utf-8')),
38
+ );
39
+ logCLI(`✅ pubKeyParams2048 bits : ${crs.bits}`, options);
40
+ logCLI(`✅ pubKeyParams2048 id : ${crs.id}`, options);
41
+ } else {
42
+ logCLI(`❌ pubKeyParams2048 file size : file does not exist`, options);
43
+ }
44
+ }
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+
3
+ import { safeJSONstringify } from '../../lib/internal.js';
4
+ import { getInstance } from '../instance.js';
5
+ import { loadFhevmPubKey } from '../pubkeyCache.js';
6
+ import { logCLI, parseCommonOptions, parseHandles } from '../utils.js';
7
+
8
+ // Old devnet handles publicly decryptable
9
+ // =======================================
10
+ // 0xc49cf03ffa2768ee7ca49fb8b1fe930c6b43075ed0000000000000aa36a70000
11
+ // 0xfd82b3d4bc3318f57189a5841e248e24b59453a168ff0000000000aa36a70400
12
+
13
+ // npx . public-decrypt --handles 0xfd82b3d4bc3318f57189a5841e248e24b59453a168ff0000000000aa36a70400
14
+ // npx . public-decrypt --version 2 --handles 0xfd82b3d4bc3318f57189a5841e248e24b59453a168ff0000000000aa36a70400
15
+ // npx . public-decrypt --version 2 --handles 0xc49cf03ffa2768ee7ca49fb8b1fe930c6b43075ed0000000000000aa36a70000
16
+ export async function publicDecryptCommand(options) {
17
+ const { config } = parseCommonOptions(options);
18
+
19
+ const fhevmHandles = parseHandles(options.handles);
20
+ const handles = fhevmHandles.map((h) => {
21
+ return h.toBytes32Hex();
22
+ });
23
+
24
+ const { publicKey, publicParams } = await loadFhevmPubKey(config, options);
25
+
26
+ try {
27
+ const instance = await getInstance(
28
+ {
29
+ ...config.fhevmInstanceConfig,
30
+ publicKey,
31
+ publicParams,
32
+ },
33
+ options,
34
+ );
35
+
36
+ logCLI('Running public decrypt...', options);
37
+
38
+ // setTimeout(() => {
39
+ // abortController.abort();
40
+ // }, 3000);
41
+
42
+ const res = await instance.publicDecrypt(handles, {
43
+ timeout: 5000,
44
+ //signal: abortController.signal,
45
+ onProgress: (args) => {
46
+ logCLI('progress=' + args.type, options);
47
+ },
48
+ });
49
+
50
+ console.log(safeJSONstringify(res, 2));
51
+ } catch (e) {
52
+ console.log('');
53
+ console.log('===================== ❌ ERROR ❌ ========================');
54
+ console.log(`[Error message]: '${e.message}'`);
55
+ console.log('');
56
+ console.log(`[Error log]:`);
57
+ console.log(e);
58
+ if (e.cause) {
59
+ console.log('[ERROR cause]:');
60
+ console.log(JSON.stringify(e.cause, null, 2));
61
+ }
62
+ console.log('========================================================');
63
+ }
64
+ }
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ import {
4
+ isFheTypeName,
5
+ encryptionBitsFromFheTypeName,
6
+ FhevmHandle,
7
+ bytesToHex,
8
+ } from '../../lib/internal.js';
9
+ import { getInstance } from '../instance.js';
10
+ import { loadFhevmPubKey } from '../pubkeyCache.js';
11
+ import { logCLI, parseCommonOptions, throwError } from '../utils.js';
12
+ import { ethers } from 'ethers';
13
+
14
+ // npx . test fhecounter-get-count
15
+ export async function testFheCounterGetCountCommand(options) {
16
+ const { config, provider } = parseCommonOptions(options);
17
+
18
+ const contractAddress =
19
+ config.name === 'testnet'
20
+ ? '0x69c4511f85E9acBb9a3D4Be7098d1d2232Ed1F7f'
21
+ : '0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9';
22
+ // Devnet
23
+ // const FHE_COUNTER_PUBLIC_DECRYPT_ADDRESS =
24
+ // '0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9';
25
+ // const FHE_COUNTER_USER_DECRYPT_ADDRESS =
26
+ // '0xE4DdA6c4C007e24fcebF95073d8Cd7b2a3db1A40';
27
+ // const FHE_COUNTER_DEPLOYER_ADDRESS =
28
+ // '0x37AC010c1c566696326813b840319B58Bb5840E4';
29
+
30
+ // Testnet
31
+ // FHE_COUNTER_USER_DECRYPT_ADDRESS=0x9F3fd46B454D35cc4c661a97FB5e6FaBb70A18C2
32
+ // const FHE_COUNTER_PUBLIC_DECRYPT_ADDRESS =
33
+ // '0x69c4511f85E9acBb9a3D4Be7098d1d2232Ed1F7f';
34
+ // FHE_COUNTER_DEPLOYER_ADDRESS=0x37AC010c1c566696326813b840319B58Bb5840E4
35
+ // handle(testnet): 0x8f0e50f96fa55c3d7e4abe9db89ff72c0fb4f58c6a000000000000aa36a70400
36
+ const contract = new ethers.Contract(
37
+ contractAddress,
38
+ ['function getCount() view returns (bytes32)'],
39
+ provider,
40
+ );
41
+
42
+ const eCount = await contract.getCount();
43
+ const handle = FhevmHandle.fromBytes32Hex(eCount);
44
+
45
+ logCLI('🚚 network: ' + config.name, options);
46
+ logCLI('🤖 contractAddress: ' + contractAddress, options);
47
+
48
+ console.log(JSON.stringify(handle, null, 2));
49
+ }
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+
3
+ import {
4
+ isFheTypeName,
5
+ encryptionBitsFromFheTypeName,
6
+ FhevmHandle,
7
+ bytesToHex,
8
+ safeJSONstringify,
9
+ bytesToHexLarge,
10
+ } from '../../lib/internal.js';
11
+ import { getInstance } from '../instance.js';
12
+ import { loadFhevmPubKey } from '../pubkeyCache.js';
13
+ import {
14
+ fheTypedValuesToBuilderFunctionWithArg,
15
+ logCLI,
16
+ parseCommonOptions,
17
+ throwError,
18
+ valueColumnTypeListToFheTypedValues,
19
+ } from '../utils.js';
20
+
21
+ // npx . zkproof generate --values 123:euint32 true:ebool 1234567890123456789:euint256 0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9:eaddress
22
+ // npx . zkproof generate --contract-address 0xb2a8A265dD5A27026693Aa6cE87Fb21Ac197b6b9 --user-address 0x37AC010c1c566696326813b840319B58Bb5840E4 --values 123:euint32
23
+ export async function zkProofGenerateCommand(options) {
24
+ const { config } = parseCommonOptions(options);
25
+
26
+ const fheTypedValues = valueColumnTypeListToFheTypedValues(options.values);
27
+ const arr = fheTypedValuesToBuilderFunctionWithArg(fheTypedValues);
28
+
29
+ const { publicKey, publicParams } = await loadFhevmPubKey(config, options);
30
+
31
+ try {
32
+ const instance = await getInstance(
33
+ {
34
+ ...config.fhevmInstanceConfig,
35
+ publicKey,
36
+ publicParams,
37
+ },
38
+ options,
39
+ );
40
+
41
+ const builder = instance.createEncryptedInput(
42
+ config.contractAddress,
43
+ config.userAddress,
44
+ );
45
+ for (let i = 0; i < arr.length; ++i) {
46
+ builder[arr[i].funcName](arr[i].arg);
47
+ }
48
+
49
+ logCLI(`🎲 generating zkproof...`, options);
50
+ const zkProof = builder.generateZKProof();
51
+ zkProof.ciphertextWithZkProof = bytesToHexLarge(
52
+ zkProof.ciphertextWithZkProof,
53
+ );
54
+
55
+ const o = {
56
+ values: fheTypedValues,
57
+ zkProof,
58
+ };
59
+
60
+ console.log(safeJSONstringify(o, 2));
61
+ } catch (e) {
62
+ console.log(e.message);
63
+ console.log(e);
64
+ console.log(JSON.stringify(e.cause, null, 2));
65
+
66
+ process.exit(1);
67
+ }
68
+ }
@@ -0,0 +1,15 @@
1
+ import { createInstance } from '../lib/node.cjs';
2
+ import { logCLI } from './utils.js';
3
+
4
+ let __instance;
5
+
6
+ export async function getInstance(config, options) {
7
+ if (!__instance) {
8
+ if (!config) {
9
+ throw new Error('Missing FhevmInstanceConfig');
10
+ }
11
+ logCLI(`create FHEVM instance...`, options);
12
+ __instance = await createInstance(config);
13
+ }
14
+ return __instance;
15
+ }
@@ -0,0 +1,126 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { homedir } from 'os';
4
+ import { createRelayerFhevm, TFHECrs, TFHEPublicKey } from '../lib/internal.js';
5
+ import { logCLI } from './utils.js';
6
+
7
+ export function getFhevmPubKeyCacheInfo() {
8
+ const cacheDir = path.join(homedir(), '.fhevm');
9
+ const pubKeyFile = path.join(cacheDir, 'pubkey.json');
10
+ const pubKeyParams2048File = path.join(cacheDir, 'pubkey-params-2048.json');
11
+ return {
12
+ cacheDir,
13
+ pubKeyFile,
14
+ pubKeyParams2048File,
15
+ };
16
+ }
17
+
18
+ export async function loadFhevmPubKey(config, options) {
19
+ const res = loadFhevmPubKeyFromCache(options);
20
+ if (res) {
21
+ return {
22
+ publicKey: res.pk.toBytes(),
23
+ publicParams: res.crs.toPublicParams2048Bytes(),
24
+ };
25
+ }
26
+
27
+ const startTime = Date.now();
28
+
29
+ logCLI(
30
+ `Fetching pub keys from ${config.fhevmInstanceConfig.relayerUrl}...`,
31
+ options,
32
+ );
33
+
34
+ const fhevm = await createRelayerFhevm({
35
+ ...config.fhevmInstanceConfig,
36
+ defaultRelayerVersion: config.version,
37
+ });
38
+
39
+ logCLI(`Relayer url: ${fhevm.relayerVersionUrl}`, options);
40
+
41
+ const pubKeyBytes = fhevm.getPublicKeyBytes();
42
+ const publicParams2048Bytes = fhevm.getPublicParamsBytesForBits(2048);
43
+
44
+ const pk = TFHEPublicKey.fromPublicKeyBytes(pubKeyBytes);
45
+ const crs = TFHECrs.fromBitsPublicParamsBytes(2048, publicParams2048Bytes);
46
+
47
+ saveFhevmPubKeyToCache({ startTime, pk, crs });
48
+
49
+ return {
50
+ publicKey: pk.toBytes(),
51
+ publicParams: crs.toPublicParams2048Bytes(),
52
+ };
53
+ }
54
+
55
+ export function loadFhevmPubKeyFromCache({ clearCache, json, verbose }) {
56
+ const { pubKeyFile, pubKeyParams2048File } = getFhevmPubKeyCacheInfo();
57
+
58
+ const pubKeyFileExists = fs.existsSync(pubKeyFile);
59
+ const pubKeyParams2048FileExists = fs.existsSync(pubKeyParams2048File);
60
+
61
+ if (!pubKeyFileExists) {
62
+ logCLI(`❌ pubKey file does not exist.`, { json, verbose });
63
+ }
64
+ if (!pubKeyParams2048FileExists) {
65
+ logCLI(`❌ pubKeyParams2048 file does not exist.`, { json, verbose });
66
+ }
67
+
68
+ if (!pubKeyParams2048FileExists || !pubKeyFileExists) {
69
+ clearCache = true;
70
+ }
71
+
72
+ if (clearCache) {
73
+ if (pubKeyFileExists) {
74
+ logCLI(`delete ${pubKeyFile}.`, { json, verbose });
75
+ fs.rmSync(pubKeyFile);
76
+ }
77
+ if (pubKeyParams2048FileExists) {
78
+ logCLI(`delete ${pubKeyParams2048File}.`, { json, verbose });
79
+ fs.rmSync(pubKeyParams2048File);
80
+ }
81
+
82
+ return null;
83
+ }
84
+
85
+ logCLI(`✅ load pubKey from cache...`, { json, verbose });
86
+ const pk = TFHEPublicKey.fromJSON(
87
+ JSON.parse(fs.readFileSync(pubKeyFile, 'utf-8')),
88
+ );
89
+
90
+ logCLI(`✅ load pubKeyParams2048 from cache...`, { json, verbose });
91
+ const crs = TFHECrs.fromJSON(
92
+ JSON.parse(fs.readFileSync(pubKeyParams2048File, 'utf-8')),
93
+ );
94
+
95
+ return { pk, crs };
96
+ }
97
+
98
+ export function saveFhevmPubKeyToCache({ startTime, pk, crs, json, verbose }) {
99
+ const { cacheDir, pubKeyFile, pubKeyParams2048File } =
100
+ getFhevmPubKeyCacheInfo();
101
+
102
+ const pkJson = pk.toJSON();
103
+ const crsJson = crs.toJSON();
104
+
105
+ logCLI(`FHEVM pubKey cache directory: ${cacheDir}`, { json, verbose });
106
+
107
+ if (!fs.existsSync(cacheDir)) {
108
+ logCLI(`create directory ${cacheDir}...`, { json, verbose });
109
+ fs.mkdirSync(cacheDir);
110
+ }
111
+
112
+ fs.writeFileSync(pubKeyFile, JSON.stringify(pkJson), 'utf-8');
113
+ logCLI(
114
+ `🍟 TFHEPublicKey saved at ${pubKeyFile} (${Date.now() - startTime}ms)`,
115
+ {
116
+ json,
117
+ verbose,
118
+ },
119
+ );
120
+
121
+ fs.writeFileSync(pubKeyParams2048File, JSON.stringify(crsJson), 'utf-8');
122
+ logCLI(
123
+ `🥬 TFHECrs saved at ${pubKeyParams2048File} (${Date.now() - startTime}ms)`,
124
+ { json, verbose },
125
+ );
126
+ }