@dorafactory/maci-sdk 0.1.3-pre.21 → 0.1.3-pre.22

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 (68) hide show
  1. package/dist/index.d.ts +5 -2
  2. package/dist/index.js +965 -44
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +954 -52
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/libs/account/crypto.d.ts +1 -0
  7. package/dist/libs/account/index.d.ts +35 -0
  8. package/dist/libs/account/keypair.d.ts +21 -0
  9. package/dist/libs/account/util.d.ts +25 -0
  10. package/dist/libs/crypto/adapter.d.ts +6 -0
  11. package/dist/libs/crypto/curve.d.ts +3 -0
  12. package/dist/libs/crypto/index.d.ts +3 -0
  13. package/dist/libs/crypto/keys.d.ts +8 -1
  14. package/dist/libs/crypto/rerandomize.d.ts +12 -0
  15. package/dist/libs/crypto/sign.d.ts +1 -1
  16. package/dist/libs/cryptography/index.d.ts +0 -0
  17. package/dist/libs/cryptography/keypair.d.ts +30 -0
  18. package/dist/libs/cryptography/mnemonics.d.ts +27 -0
  19. package/dist/libs/cryptography/publickey.d.ts +23 -0
  20. package/dist/libs/cryptography/signature-scheme.d.ts +1 -0
  21. package/dist/libs/keypairs/eddsa-poseidon/index.d.ts +2 -0
  22. package/dist/libs/keypairs/eddsa-poseidon/keypair.d.ts +187 -0
  23. package/dist/libs/keypairs/eddsa-poseidon/publickey.d.ts +48 -0
  24. package/dist/types/index.d.ts +13 -0
  25. package/dist/utils/account.d.ts +2 -0
  26. package/dist/utils/base64.d.ts +6 -0
  27. package/dist/utils/bech32.d.ts +2 -0
  28. package/dist/utils/decode-address.d.ts +10 -0
  29. package/dist/utils/fetch.d.ts +1 -0
  30. package/dist/utils/hex.d.ts +6 -0
  31. package/dist/utils/index.d.ts +5 -24
  32. package/dist/utils/validate-address.d.ts +24 -0
  33. package/dist/voter.d.ts +161 -0
  34. package/package.json +13 -61
  35. package/src/index.ts +7 -13
  36. package/src/libs/account/crypto.ts +7 -0
  37. package/src/libs/account/index.ts +70 -0
  38. package/src/libs/account/keypair.ts +29 -0
  39. package/src/libs/account/util.ts +55 -0
  40. package/src/libs/crypto/adapter.ts +41 -0
  41. package/src/libs/crypto/babyjub.ts +4 -7
  42. package/src/libs/crypto/constants.ts +2 -5
  43. package/src/libs/crypto/curve.ts +55 -0
  44. package/src/libs/crypto/hashing.ts +4 -6
  45. package/src/libs/crypto/index.ts +3 -0
  46. package/src/libs/crypto/keys.ts +15 -48
  47. package/src/libs/crypto/rerandomize.ts +77 -0
  48. package/src/libs/crypto/sign.ts +8 -17
  49. package/src/libs/crypto/tree.ts +1 -3
  50. package/src/libs/cryptography/index.ts +0 -0
  51. package/src/libs/cryptography/keypair.ts +44 -0
  52. package/src/libs/cryptography/mnemonics.ts +47 -0
  53. package/src/libs/cryptography/publickey.ts +44 -0
  54. package/src/libs/cryptography/signature-scheme.ts +1 -0
  55. package/src/libs/keypairs/eddsa-poseidon/index.ts +6 -0
  56. package/src/libs/keypairs/eddsa-poseidon/keypair.ts +452 -0
  57. package/src/libs/keypairs/eddsa-poseidon/publickey.ts +149 -0
  58. package/src/types/index.ts +16 -0
  59. package/src/types/lib.d.ts +7 -0
  60. package/src/utils/account.ts +5 -0
  61. package/src/utils/base64.ts +28 -0
  62. package/src/utils/bech32.ts +29 -0
  63. package/src/utils/decode-address.ts +35 -0
  64. package/src/utils/fetch.ts +28 -0
  65. package/src/utils/hex.ts +23 -0
  66. package/src/utils/index.ts +16 -79
  67. package/src/utils/validate-address.ts +82 -0
  68. package/src/voter.ts +430 -0
@@ -0,0 +1,161 @@
1
+ import { ZKArtifact } from 'snarkjs';
2
+ import { MaciAccount } from './libs/account';
3
+ import { VoterClientParams, DerivePathParams, PubKey, PrivKey, DeactivateMessage } from './types';
4
+ /**
5
+ * @class Maci Voter Client
6
+ * @description This class is used to interact with Maci Voter Client.
7
+ */
8
+ export declare class VoterClient {
9
+ accountManager: MaciAccount;
10
+ /**
11
+ * @constructor
12
+ * @param {VoterClientParams} params - The parameters for the Maci Voter Client instance.
13
+ */
14
+ constructor({ mnemonic, secretKey }?: VoterClientParams);
15
+ /**
16
+ * else:
17
+ * it will generate signer from the mnemonic with the given derivePathParams.
18
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
19
+ */
20
+ getSigner(derivePathParams?: DerivePathParams): import(".").EdDSAPoseidonKeypair;
21
+ packMaciPubkey(pubkey?: PubKey): bigint;
22
+ unpackMaciPubkey(pubkey: bigint | string): PubKey;
23
+ getPubkey(derivePathParams?: DerivePathParams): import(".").EdDSAPoseidonPublicKey;
24
+ buildVotePayload({ stateIdx, operatorPubkey, selectedOptions, derivePathParams }: {
25
+ stateIdx: number;
26
+ operatorPubkey: bigint;
27
+ selectedOptions: {
28
+ idx: number;
29
+ vc: number;
30
+ }[];
31
+ derivePathParams?: DerivePathParams;
32
+ }): string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | {
33
+ [key: string]: string | /*elided*/ any | /*elided*/ any;
34
+ })[] | {
35
+ [key: string]: string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any;
36
+ })[] | {
37
+ [key: string]: string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
38
+ })[] | {
39
+ [key: string]: string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
40
+ })[] | {
41
+ [key: string]: string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
42
+ })[] | {
43
+ [key: string]: string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
44
+ })[] | {
45
+ [key: string]: string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
46
+ })[] | {
47
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
48
+ })[] | {
49
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
50
+ })[] | {
51
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
52
+ })[] | {
53
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
54
+ })[] | {
55
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
56
+ };
57
+ batchGenMessage(stateIdx: number, operatorPubkey: bigint, plan: [number, number][], derivePathParams?: DerivePathParams): {
58
+ msg: bigint[];
59
+ encPubkeys: PubKey<bigint>;
60
+ }[];
61
+ genMessageFactory(stateIdx: number, operatorPubkey: bigint, derivePathParams?: DerivePathParams): (encPriKey: PrivKey, nonce: number, voIdx: number, newVotes: number, isLastCmd: boolean, salt?: bigint) => bigint[];
62
+ buildAddNewKeyPayload({ stateTreeDepth, operatorPubkey, deactivates, wasmFile, zkeyFile, derivePathParams }: {
63
+ stateTreeDepth: number;
64
+ operatorPubkey: bigint;
65
+ deactivates: DeactivateMessage[];
66
+ wasmFile: ZKArtifact;
67
+ zkeyFile: ZKArtifact;
68
+ derivePathParams?: DerivePathParams;
69
+ }): Promise<{
70
+ proof: {
71
+ a: string;
72
+ b: string;
73
+ c: string;
74
+ };
75
+ d: string[];
76
+ nullifier: string;
77
+ }>;
78
+ buildPreAddNewKeyPayload({ stateTreeDepth, operatorPubkey, deactivates, wasmFile, zkeyFile, derivePathParams }: {
79
+ stateTreeDepth: number;
80
+ operatorPubkey: bigint;
81
+ deactivates: bigint[][];
82
+ wasmFile: ZKArtifact;
83
+ zkeyFile: ZKArtifact;
84
+ derivePathParams?: DerivePathParams;
85
+ }): Promise<{
86
+ proof: {
87
+ a: string;
88
+ b: string;
89
+ c: string;
90
+ };
91
+ d: string[];
92
+ nullifier: string;
93
+ }>;
94
+ genAddKeyInput(depth: number, { coordPubKey, deactivates, derivePathParams }: {
95
+ coordPubKey: PubKey;
96
+ deactivates: bigint[][];
97
+ derivePathParams?: DerivePathParams;
98
+ }): Promise<{
99
+ inputHash: bigint;
100
+ coordPubKey: PubKey;
101
+ deactivateRoot: bigint;
102
+ deactivateIndex: number;
103
+ deactivateLeaf: bigint;
104
+ c1: bigint[];
105
+ c2: bigint[];
106
+ randomVal: bigint;
107
+ d1: bigint[];
108
+ d2: bigint[];
109
+ deactivateLeafPathElements: bigint[][];
110
+ nullifier: bigint;
111
+ oldPrivateKey: bigint;
112
+ } | null>;
113
+ genPreAddKeyInput(depth: number, { coordPubKey, deactivates, derivePathParams }: {
114
+ coordPubKey: PubKey;
115
+ deactivates: bigint[][];
116
+ derivePathParams?: DerivePathParams;
117
+ }): Promise<{
118
+ inputHash: bigint;
119
+ coordPubKey: PubKey;
120
+ deactivateRoot: bigint;
121
+ deactivateIndex: number;
122
+ deactivateLeaf: bigint;
123
+ c1: [bigint, bigint];
124
+ c2: [bigint, bigint];
125
+ randomVal: bigint;
126
+ d1: bigint[];
127
+ d2: bigint[];
128
+ deactivateLeafPathElements: bigint[][];
129
+ nullifier: bigint;
130
+ oldPrivateKey: bigint;
131
+ } | null>;
132
+ buildDeactivatePayload({ stateIdx, operatorPubkey, derivePathParams }: {
133
+ stateIdx: number;
134
+ operatorPubkey: bigint;
135
+ derivePathParams?: DerivePathParams;
136
+ }): Promise<string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | {
137
+ [key: string]: string | /*elided*/ any | /*elided*/ any;
138
+ })[] | {
139
+ [key: string]: string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any;
140
+ })[] | {
141
+ [key: string]: string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
142
+ })[] | {
143
+ [key: string]: string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
144
+ })[] | {
145
+ [key: string]: string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
146
+ })[] | {
147
+ [key: string]: string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
148
+ })[] | {
149
+ [key: string]: string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
150
+ })[] | {
151
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
152
+ })[] | {
153
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
154
+ })[] | {
155
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
156
+ })[] | {
157
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
158
+ })[] | {
159
+ [key: string]: string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | (string | /*elided*/ any | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any)[] | /*elided*/ any;
160
+ }>;
161
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dorafactory/maci-sdk",
3
- "version": "0.1.3-pre.21",
3
+ "version": "0.1.3-pre.22",
4
4
  "description": "SDK for interacting with maci",
5
5
  "keywords": [
6
6
  "maci",
@@ -28,16 +28,23 @@
28
28
  "src"
29
29
  ],
30
30
  "dependencies": {
31
+ "snarkjs": "0.7.5",
32
+ "ffjavascript": "0.3.1",
33
+ "@noble/curves": "^1.4.2",
34
+ "@noble/hashes": "^1.4.0",
35
+ "@scure/bip32": "^1.3.3",
36
+ "@scure/bip39": "^1.3.0",
37
+ "@zk-kit/baby-jubjub": "^1.0.3",
38
+ "@zk-kit/eddsa-poseidon": "^1.1.0",
39
+ "@zk-kit/poseidon-cipher": "^0.3.2",
40
+ "@zk-kit/utils": "^1.4.1",
31
41
  "@cosmjs/amino": "^0.32.1",
32
42
  "@cosmjs/cosmwasm-stargate": "^0.32.1",
33
43
  "@cosmjs/launchpad": "^0.27.1",
34
44
  "@cosmjs/proto-signing": "^0.32.1",
35
45
  "@cosmjs/stargate": "^0.32.1",
36
- "@zk-kit/baby-jubjub": "^1.0.3",
37
- "@zk-kit/eddsa-poseidon": "^1.1.0",
38
- "@zk-kit/poseidon-cipher": "^0.3.2",
39
46
  "assert": "^2.1.0",
40
- "bech32": "1.1.4",
47
+ "bech32": "^2.0.0",
41
48
  "cosmjs-types": "^0.9.0",
42
49
  "crypto-js": "^4.2.0",
43
50
  "ethers": "^6.13.4"
@@ -49,6 +56,7 @@
49
56
  "@types/crypto-js": "^4.2.2",
50
57
  "@types/node": "^20.8.7",
51
58
  "@types/tmp": "^0.2.5",
59
+ "@types/snarkjs": "^0.7.9",
52
60
  "@typescript-eslint/eslint-plugin": "^6.8.0",
53
61
  "@typescript-eslint/parser": "^6.8.0",
54
62
  "browserify-zlib": "^0.2.0",
@@ -73,62 +81,6 @@
73
81
  "typedoc": "^0.25.2",
74
82
  "typescript": "^5.2.2"
75
83
  },
76
- "lint-staged": {
77
- "**/*.ts": [
78
- "pnpm run format:fix",
79
- "pnpm run lint:fix"
80
- ],
81
- "**/*.json|md": [
82
- "pnpm run format:fix"
83
- ]
84
- },
85
- "commitlint": {
86
- "extends": [
87
- "@commitlint/config-conventional"
88
- ]
89
- },
90
- "prettier": {
91
- "trailingComma": "es5",
92
- "tabWidth": 2,
93
- "semi": true,
94
- "singleQuote": true,
95
- "useTabs": false,
96
- "quoteProps": "as-needed",
97
- "bracketSpacing": true,
98
- "arrowParens": "always",
99
- "endOfLine": "lf"
100
- },
101
- "eslintConfig": {
102
- "root": true,
103
- "env": {
104
- "browser": true,
105
- "node": true,
106
- "es2022": true
107
- },
108
- "extends": [
109
- "eslint:recommended",
110
- "plugin:@typescript-eslint/eslint-recommended",
111
- "plugin:prettier/recommended"
112
- ],
113
- "plugins": [
114
- "@typescript-eslint",
115
- "prettier"
116
- ],
117
- "parser": "@typescript-eslint/parser",
118
- "rules": {
119
- "prettier/prettier": "warn",
120
- "@typescript-eslint/no-explicit-any": "off",
121
- "no-unused-vars": "off",
122
- "@typescript-eslint/no-unused-vars": [
123
- "error",
124
- {
125
- "argsIgnorePattern": "^_",
126
- "varsIgnorePattern": "^_",
127
- "caughtErrorsIgnorePattern": "^_"
128
- }
129
- ]
130
- }
131
- },
132
84
  "scripts": {
133
85
  "clean": "rm -rf tsconfig.tsbuildinfo ./dist",
134
86
  "build": "npm run build:types && npm run build:tsup",
package/src/index.ts CHANGED
@@ -1,16 +1,10 @@
1
1
  // Core
2
2
  export { MaciClient } from './maci';
3
+ export { VoterClient } from './voter';
3
4
  export { Http } from './libs/http';
4
5
 
5
6
  // Query Types
6
- export {
7
- Round,
8
- UserAccount,
9
- Circuit,
10
- Operator,
11
- Proof,
12
- Transaction,
13
- } from './libs/query';
7
+ export { Round, UserAccount, Circuit, Operator, Proof, Transaction } from './libs/query';
14
8
 
15
9
  // Crypto
16
10
  export * from './libs/crypto';
@@ -23,10 +17,10 @@ export type * from './types';
23
17
  export { circuits, getDefaultParams, type NetworkConfig } from './libs/const';
24
18
 
25
19
  // Utils
26
- export {
27
- stringizing,
28
- destringizing,
29
- bigInt2Buffer,
30
- } from './libs/crypto/bigintUtils';
20
+ export { stringizing, destringizing, bigInt2Buffer } from './libs/crypto/bigintUtils';
31
21
  export { isValidAddress } from './utils';
32
22
  export { getAMaciRoundCircuitFee } from './libs/contract/utils';
23
+
24
+ export { EdDSAPoseidonKeypair, EdDSAPoseidonPublicKey } from './libs/keypairs/eddsa-poseidon';
25
+
26
+ export * from './utils';
@@ -0,0 +1,7 @@
1
+ import { generateMnemonic as genMnemonic } from '@scure/bip39';
2
+ import { wordlist } from '@scure/bip39/wordlists/english';
3
+
4
+ export const generateMnemonic = (numberOfWords: 12 | 24 = 24) => {
5
+ const strength = numberOfWords === 12 ? 128 : 256;
6
+ return genMnemonic(wordlist, strength);
7
+ };
@@ -0,0 +1,70 @@
1
+ import {
2
+ EdDSAPoseidonKeypair,
3
+ EdDSAPoseidonPublicKey,
4
+ } from '../keypairs/eddsa-poseidon';
5
+ import { getKeyPair } from './keypair';
6
+ import { generateMnemonic } from './crypto';
7
+ import type { AccountMangerParams, DerivePathParams } from 'src/types';
8
+
9
+ export { generateMnemonic } from './crypto';
10
+ export { getKeyPair } from './keypair';
11
+
12
+ export class MaciAccount {
13
+ private mnemonic: string;
14
+ private secretKey: string | bigint;
15
+ public currentKeypair: EdDSAPoseidonKeypair;
16
+ public currentPubkey: EdDSAPoseidonPublicKey;
17
+
18
+ /**
19
+ * Support the following ways to init the SuiToolkit:
20
+ * 1. mnemonics
21
+ * 2. secretKey (base64 or hex)
22
+ * If none of them is provided, will generate a random mnemonics with 24 words.
23
+ *
24
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
25
+ * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
26
+ */
27
+ constructor({ mnemonic, secretKey }: AccountMangerParams = {}) {
28
+ // If the mnemonics or secretKey is provided, use it
29
+ // Otherwise, generate a random mnemonics with 24 words
30
+ this.mnemonic = mnemonic || '';
31
+ this.secretKey = secretKey || '';
32
+ if (!this.mnemonic && !this.secretKey) {
33
+ this.mnemonic = generateMnemonic(24);
34
+ }
35
+
36
+ // Init the current account
37
+ this.currentKeypair = this.secretKey
38
+ ? this.parseSecretKey(this.secretKey)
39
+ : getKeyPair(this.mnemonic);
40
+ this.currentPubkey = this.currentKeypair.getPublicKey();
41
+ }
42
+
43
+ /**
44
+ * Check if the secretKey starts with bench32 format
45
+ */
46
+ parseSecretKey(secretKey: string | bigint) {
47
+ return EdDSAPoseidonKeypair.fromSecretKey(secretKey);
48
+ }
49
+
50
+ /**
51
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
52
+ * else:
53
+ * it will generate keyPair from the mnemonic with the given derivePathParams.
54
+ */
55
+ getKeyPair(derivePathParams?: DerivePathParams) {
56
+ if (!derivePathParams || !this.mnemonic) return this.currentKeypair;
57
+ return getKeyPair(this.mnemonic, derivePathParams);
58
+ }
59
+
60
+ /**
61
+ * Switch the current account with the given derivePathParams.
62
+ * This is only useful when the mnemonic is provided. For secretKey mode, it will always use the same account.
63
+ */
64
+ switchAccount(derivePathParams: DerivePathParams) {
65
+ if (this.mnemonic) {
66
+ this.currentKeypair = getKeyPair(this.mnemonic, derivePathParams);
67
+ this.currentPubkey = this.currentKeypair.getPublicKey();
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,29 @@
1
+ import type { DerivePathParams } from '../../types';
2
+ import { EdDSAPoseidonKeypair } from '../keypairs/eddsa-poseidon';
3
+
4
+ /**
5
+ * @description Get eddsaposeidon derive path for MACI
6
+ * @param derivePathParams
7
+ */
8
+ export const getDerivePathForMACI = (derivePathParams: DerivePathParams = {}) => {
9
+ const { accountIndex = 0, isExternal = false, addressIndex = 0 } = derivePathParams;
10
+ return `m/44'/118'/${accountIndex}'/${isExternal ? 1 : 0}/${addressIndex}`;
11
+ };
12
+
13
+ /**
14
+ * the format is m/44'/118'/accountIndex'/${isExternal ? 1 : 0}/addressIndex
15
+ *
16
+ * accountIndex is the index of the account, default is 0.
17
+ *
18
+ * isExternal is the type of the address, default is false. Usually, the external address is used to receive coins. The internal address is used to change coins.
19
+ *
20
+ * addressIndex is the index of the address, default is 0. It's used to generate multiple addresses for one account.
21
+ *
22
+ * @description Get keypair from mnemonics and derive path
23
+ * @param mnemonics
24
+ * @param derivePathParams
25
+ */
26
+ export const getKeyPair = (mnemonics: string, derivePathParams: DerivePathParams = {}) => {
27
+ const derivePath = getDerivePathForMACI(derivePathParams);
28
+ return EdDSAPoseidonKeypair.deriveKeypair(mnemonics, derivePath);
29
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @description This regular expression matches any string that contains only hexadecimal digits (0-9, A-F, a-f).
3
+ * @param str
4
+ */
5
+ export const isHex = (str: string) =>
6
+ /^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(str);
7
+
8
+ /**
9
+ * @description This regular expression matches any string that contains only base64 digits (0-9, A-Z, a-z, +, /, =).
10
+ * Note that the "=" signs at the end are optional padding characters that may be present in some base64 encoded strings.
11
+ * @param str
12
+ */
13
+ export const isBase64 = (str: string) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);
14
+
15
+ /**
16
+ * Convert a hex string to Uint8Array
17
+ * @param hexStr
18
+ */
19
+ export const fromHEX = (hexStr: string): Uint8Array => {
20
+ if (!hexStr) {
21
+ throw new Error('cannot parse empty string to Uint8Array');
22
+ }
23
+ const intArr = hexStr
24
+ .replace('0x', '')
25
+ .match(/.{1,2}/g)
26
+ ?.map((byte) => parseInt(byte, 16));
27
+
28
+ if (!intArr || intArr.length === 0) {
29
+ throw new Error(`Unable to parse HEX: ${hexStr}`);
30
+ }
31
+ return Uint8Array.from(intArr);
32
+ };
33
+
34
+ const PRIVATE_KEY_SIZE = 32;
35
+ const LEGACY_PRIVATE_KEY_SIZE = 64;
36
+ /**
37
+ * normalize a private key
38
+ * A private key is a 32-byte array.
39
+ * But there are two different formats for private keys:
40
+ * 1. A 32-byte array
41
+ * 2. A 64-byte array with the first 32 bytes being the private key and the last 32 bytes being the public key
42
+ * 3. A 33-byte array with the first byte being 0x00 (sui.keystore key is a Base64 string with scheme flag 0x00 at the beginning)
43
+ */
44
+ export const normalizePrivateKey = (key: Uint8Array): Uint8Array => {
45
+ if (key.length === LEGACY_PRIVATE_KEY_SIZE) {
46
+ // This is a legacy secret key, we need to strip the public key bytes and only read the first 32 bytes
47
+ key = key.slice(0, PRIVATE_KEY_SIZE);
48
+ } else if (key.length === PRIVATE_KEY_SIZE + 1 && key[0] === 0) {
49
+ // sui.keystore key is a Base64 string with scheme flag 0x00 at the beginning
50
+ return key.slice(1);
51
+ } else if (key.length === PRIVATE_KEY_SIZE) {
52
+ return key;
53
+ }
54
+ throw new Error('invalid secret key');
55
+ };
@@ -0,0 +1,41 @@
1
+ import { Groth16Proof } from 'snarkjs';
2
+ import { utils } from 'ffjavascript';
3
+ const { unstringifyBigInts } = utils;
4
+
5
+ import * as curves from './curve';
6
+
7
+ const Bytes2Str = (arr: number[]) => {
8
+ let str = '';
9
+ for (let i = 0; i < arr.length; i++) {
10
+ let tmp = arr[i].toString(16);
11
+ if (tmp.length == 1) {
12
+ tmp = '0' + tmp;
13
+ }
14
+ str += tmp;
15
+ }
16
+ return str;
17
+ };
18
+
19
+ let BN128Curve: any = null;
20
+
21
+ export const adaptToUncompressed = async (proof: Groth16Proof) => {
22
+ const p = unstringifyBigInts(proof);
23
+
24
+ let curve = BN128Curve;
25
+ if (!curve) {
26
+ BN128Curve = await curves.getCurveFromName('BN128');
27
+ curve = BN128Curve;
28
+ }
29
+
30
+ // convert u8 array(little-endian order)to uncompressed type(big-endian order and on bls12_381 curve)
31
+ // which can be convert into Affine type in bellman
32
+ const pi_a = curve.G1.toUncompressed(curve.G1.fromObject(p.pi_a));
33
+ const pi_b = curve.G2.toUncompressed(curve.G2.fromObject(p.pi_b));
34
+ const pi_c = curve.G1.toUncompressed(curve.G1.fromObject(p.pi_c));
35
+
36
+ return {
37
+ a: Bytes2Str(Array.from(pi_a)),
38
+ b: Bytes2Str(Array.from(pi_b)),
39
+ c: Bytes2Str(Array.from(pi_c)),
40
+ };
41
+ };
@@ -42,7 +42,7 @@ export class G1Point {
42
42
  asContractParam(): { x: string; y: string } {
43
43
  return {
44
44
  x: this.x.toString(),
45
- y: this.y.toString(),
45
+ y: this.y.toString()
46
46
  };
47
47
  }
48
48
  }
@@ -91,7 +91,7 @@ export class G2Point {
91
91
  asContractParam(): { x: string[]; y: string[] } {
92
92
  return {
93
93
  x: this.x.map((n) => n.toString()),
94
- y: this.y.map((n) => n.toString()),
94
+ y: this.y.map((n) => n.toString())
95
95
  };
96
96
  }
97
97
 
@@ -144,14 +144,11 @@ export const genRandomBabyJubValue = () => {
144
144
  // Prevent modulo bias
145
145
  //const lim = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000')
146
146
  //const min = (lim - SNARK_FIELD_SIZE) % SNARK_FIELD_SIZE
147
- const min =
148
- 6350874878119819312338956282401532410528162663560392320966563075034087161851n;
147
+ const min = 6350874878119819312338956282401532410528162663560392320966563075034087161851n;
149
148
 
150
149
  let rand;
151
150
  while (true) {
152
- rand = BigInt(
153
- `0x${CryptoJS.lib.WordArray.random(32).toString(CryptoJS.enc.Hex)}`
154
- );
151
+ rand = BigInt(`0x${CryptoJS.lib.WordArray.random(32).toString(CryptoJS.enc.Hex)}`);
155
152
 
156
153
  if (rand >= min) {
157
154
  break;
@@ -7,14 +7,11 @@ export const SNARK_FIELD_SIZE = r;
7
7
 
8
8
  // A nothing-up-my-sleeve zero value
9
9
  // Should be equal to 8370432830353022751713833565135785980866757267633941821328460903436894336785
10
- export const NOTHING_UP_MY_SLEEVE =
11
- BigInt(keccak256(toUtf8Bytes('Maci'))) % SNARK_FIELD_SIZE;
10
+ export const NOTHING_UP_MY_SLEEVE = BigInt(keccak256(toUtf8Bytes('Maci'))) % SNARK_FIELD_SIZE;
12
11
 
13
12
  assert(
14
13
  NOTHING_UP_MY_SLEEVE ===
15
- BigInt(
16
- '8370432830353022751713833565135785980866757267633941821328460903436894336785'
17
- )
14
+ BigInt('8370432830353022751713833565135785980866757267633941821328460903436894336785')
18
15
  );
19
16
 
20
17
  export const PAD_KEY_HASH = BigInt(
@@ -0,0 +1,55 @@
1
+ import { Scalar, buildBn128, buildBls12381 } from 'ffjavascript';
2
+
3
+ const bls12381r = Scalar.e('73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001', 16);
4
+ const bn128r = Scalar.e(
5
+ '21888242871839275222246405745257275088548364400416034343698204186575808495617'
6
+ );
7
+
8
+ const bls12381q = Scalar.e(
9
+ '1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab',
10
+ 16
11
+ );
12
+ const bn128q = Scalar.e(
13
+ '21888242871839275222246405745257275088696311157297823662689037894645226208583'
14
+ );
15
+
16
+ export async function getCurveFromR(r: bigint) {
17
+ let curve;
18
+ if (Scalar.eq(r, bn128r)) {
19
+ curve = await buildBn128();
20
+ } else if (Scalar.eq(r, bls12381r)) {
21
+ curve = await buildBls12381();
22
+ } else {
23
+ throw new Error(`Curve not supported: ${Scalar.toString(r)}`);
24
+ }
25
+ return curve;
26
+ }
27
+
28
+ export async function getCurveFromQ(q: bigint) {
29
+ let curve;
30
+ if (Scalar.eq(q, bn128q)) {
31
+ curve = await buildBn128();
32
+ } else if (Scalar.eq(q, bls12381q)) {
33
+ curve = await buildBls12381();
34
+ } else {
35
+ throw new Error(`Curve not supported: ${Scalar.toString(q)}`);
36
+ }
37
+ return curve;
38
+ }
39
+
40
+ export async function getCurveFromName(name: string) {
41
+ let curve;
42
+ const normName = normalizeName(name);
43
+ if (['BN128', 'BN254', 'ALTBN128'].indexOf(normName) >= 0) {
44
+ curve = await buildBn128();
45
+ } else if (['BLS12381'].indexOf(normName) >= 0) {
46
+ curve = await buildBls12381();
47
+ } else {
48
+ throw new Error(`Curve not supported: ${name}`);
49
+ }
50
+ return curve;
51
+
52
+ function normalizeName(n: string) {
53
+ return (n.toUpperCase().match(/[A-Za-z0-9]+/g) || []).join('');
54
+ }
55
+ }
@@ -83,15 +83,14 @@ export const poseidonT6 = (inputs: bigint[]): bigint => {
83
83
  * @param right The right-hand element to hash
84
84
  * @returns The hash of the two elements
85
85
  */
86
- export const hashLeftRight = (left: bigint, right: bigint): bigint =>
87
- poseidonT3([left, right]);
86
+ export const hashLeftRight = (left: bigint, right: bigint): bigint => poseidonT3([left, right]);
88
87
 
89
88
  // hash functions
90
89
  const funcs: PoseidonFuncs = {
91
90
  2: poseidonT3,
92
91
  3: poseidonT4,
93
92
  4: poseidonT5,
94
- 5: poseidonT6,
93
+ 5: poseidonT6
95
94
  };
96
95
 
97
96
  /**
@@ -154,7 +153,7 @@ export const hash12 = (elements: Plaintext): bigint => {
154
153
  poseidonT6(elementsPadded.slice(0, 5)),
155
154
  poseidonT6(elementsPadded.slice(5, 10)),
156
155
  elementsPadded[10],
157
- elementsPadded[11],
156
+ elementsPadded[11]
158
157
  ]);
159
158
  };
160
159
 
@@ -163,5 +162,4 @@ export const hash12 = (elements: Plaintext): bigint => {
163
162
  * @param preImage The element to hash
164
163
  * @returns The hash of the element
165
164
  */
166
- export const hashOne = (preImage: bigint): bigint =>
167
- poseidonT3([preImage, BigInt(0)]);
165
+ export const hashOne = (preImage: bigint): bigint => poseidonT3([preImage, BigInt(0)]);
@@ -6,4 +6,7 @@ export * from './sign';
6
6
  export * from './types';
7
7
  export * from './tree';
8
8
  export * from './babyjub';
9
+ export * from './curve';
10
+ export * from './adapter';
11
+ export * from './rerandomize';
9
12
  export type { Keypair, PubKey, PrivKey } from './types';