@dorafactory/maci-sdk 0.0.6 → 0.0.8

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.
package/dist/index.d.ts CHANGED
@@ -5,9 +5,12 @@ export * from './libs/const';
5
5
  export { MaciClient } from './maci';
6
6
  export { Http } from './libs/http';
7
7
  export { Round } from './libs/query';
8
- export { Account } from './libs/query';
8
+ export { UserAccount } from './libs/query';
9
9
  export { Circuit } from './libs/query';
10
10
  export { Operator } from './libs/query';
11
11
  export { Proof } from './libs/query';
12
12
  export { Transaction } from './libs/query';
13
+ export * from './libs/circom';
13
14
  export * from './utils';
15
+ export { Scalar, utils } from 'ffjavascript';
16
+ export { default as createBlakeHash } from 'blake-hash';
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,12 +17,20 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var src_exports = {};
22
32
  __export(src_exports, {
23
- Account: () => Account,
33
+ Circom: () => Circom,
24
34
  Circuit: () => Circuit,
25
35
  Contract: () => Contract,
26
36
  Http: () => Http,
@@ -32,13 +42,24 @@ __export(src_exports, {
32
42
  Operator: () => Operator,
33
43
  Proof: () => Proof,
34
44
  Round: () => Round,
45
+ Scalar: () => import_ffjavascript2.Scalar,
35
46
  Transaction: () => Transaction,
47
+ UserAccount: () => UserAccount,
48
+ batchGenMessage: () => batchGenMessage,
36
49
  circuits: () => circuits,
37
50
  compressPublicKey: () => compressPublicKey,
51
+ createBlakeHash: () => import_blake_hash2.default,
38
52
  decompressPublicKey: () => decompressPublicKey,
53
+ genAddKeyProof: () => genAddKeyProof,
54
+ genEcdhSharedKey: () => genEcdhSharedKey,
55
+ genKeypair: () => genKeypair,
56
+ genMessageFactory: () => genMessageFactory,
39
57
  getDefaultParams: () => getDefaultParams,
40
58
  hexToDecimalString: () => hexToDecimalString,
41
59
  isValidAddress: () => isValidAddress,
60
+ privateKeyFromTxt: () => privateKeyFromTxt,
61
+ stringizing: () => stringizing,
62
+ utils: () => import_ffjavascript2.utils,
42
63
  validator_operator_set: () => validator_operator_set
43
64
  });
44
65
  module.exports = __toCommonJS(src_exports);
@@ -277,7 +298,7 @@ var ERROR = {
277
298
  };
278
299
 
279
300
  // src/libs/query/account.ts
280
- var Account = class {
301
+ var UserAccount = class {
281
302
  constructor(http) {
282
303
  this.http = http;
283
304
  }
@@ -1483,7 +1504,7 @@ var Indexer = class {
1483
1504
  this.apiEndpoint = apiEndpoint;
1484
1505
  this.registryAddress = registryAddress;
1485
1506
  this.round = new Round(this.http);
1486
- this.account = new Account(this.http);
1507
+ this.account = new UserAccount(this.http);
1487
1508
  this.circuit = new Circuit(this.http);
1488
1509
  this.operator = new Operator(this.http, this.registryAddress);
1489
1510
  this.proof = new Proof(this.http);
@@ -3711,10 +3732,17 @@ function getContractParams(type, circuitType, proofSystem, maxVoter, maxOption)
3711
3732
  // plonkTallyVkey,
3712
3733
  };
3713
3734
  case "2" /* ORACLE_MACI */:
3735
+ if (circuitType === "0" /* IP1V */) {
3736
+ groth16ProcessVkey = CIRCUIT_INFO["9-4-3-625"]["groth16"].process_1p1v_vkey;
3737
+ groth16TallyVkey = CIRCUIT_INFO["9-4-3-625"]["groth16"].tally_1p1v_vkey;
3738
+ } else if (circuitType === "1" /* QV */) {
3739
+ groth16ProcessVkey = CIRCUIT_INFO["9-4-3-625"]["groth16"].process_qv_vkey;
3740
+ groth16TallyVkey = CIRCUIT_INFO["9-4-3-625"]["groth16"].tally_qv_vkey;
3741
+ }
3714
3742
  return {
3715
3743
  parameters: CIRCUIT_INFO["9-4-3-625"].parameter,
3716
- groth16ProcessVkey: CIRCUIT_INFO["9-4-3-625"]["groth16"].process_vkey,
3717
- groth16TallyVkey: CIRCUIT_INFO["9-4-3-625"]["groth16"].tally_vkey,
3744
+ groth16ProcessVkey,
3745
+ groth16TallyVkey,
3718
3746
  plonkProcessVkey: null,
3719
3747
  plonkTallyVkey: null,
3720
3748
  maciVoteType,
@@ -3980,6 +4008,264 @@ var Contract = class {
3980
4008
  contractAddress
3981
4009
  });
3982
4010
  }
4011
+ async contractClient({ signer }) {
4012
+ return createContractClientByWallet(this.rpcEndpoint, signer);
4013
+ }
4014
+ };
4015
+
4016
+ // src/libs/circom/index.ts
4017
+ var import_proto_signing = require("@cosmjs/proto-signing");
4018
+
4019
+ // src/libs/circom/circomlib.ts
4020
+ var import_crypto = require("crypto");
4021
+ var import_circomlib = require("@dorafactory/circomlib");
4022
+ var import_ffjavascript = require("ffjavascript");
4023
+ var import_blake_hash = __toESM(require("blake-hash"));
4024
+ var import_ethers = require("ethers");
4025
+ var SNARK_FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
4026
+ var bigInt2Buffer = (i) => {
4027
+ let hex = i.toString(16);
4028
+ if (hex.length % 2 === 1) {
4029
+ hex = "0" + hex;
4030
+ }
4031
+ return Buffer.from(hex, "hex");
4032
+ };
4033
+ var genRandomKey = () => {
4034
+ const min = 6350874878119819312338956282401532410528162663560392320966563075034087161851n;
4035
+ let rand;
4036
+ while (true) {
4037
+ rand = BigInt("0x" + (0, import_crypto.randomBytes)(32).toString("hex"));
4038
+ if (rand >= min) {
4039
+ break;
4040
+ }
4041
+ }
4042
+ const privKey = rand % SNARK_FIELD_SIZE;
4043
+ return privKey;
4044
+ };
4045
+ var genPubKey = (privKey) => {
4046
+ return import_circomlib.eddsa.prv2pub(bigInt2Buffer(privKey));
4047
+ };
4048
+ var stringizing = (o, path = []) => {
4049
+ if (path.includes(o)) {
4050
+ throw new Error("loop nesting!");
4051
+ }
4052
+ const newPath = [...path, o];
4053
+ if (Array.isArray(o)) {
4054
+ return o.map((item) => stringizing(item, newPath));
4055
+ } else if (typeof o === "object") {
4056
+ const output = {};
4057
+ for (const key in o) {
4058
+ output[key] = stringizing(o[key], newPath);
4059
+ }
4060
+ return output;
4061
+ } else {
4062
+ return o.toString();
4063
+ }
4064
+ };
4065
+ var genKeypair = (pkey) => {
4066
+ const privKey = pkey ? pkey % SNARK_FIELD_SIZE : genRandomKey();
4067
+ const pubKey = genPubKey(privKey);
4068
+ const formatedPrivKey = formatPrivKeyForBabyJub(privKey);
4069
+ return { privKey, pubKey, formatedPrivKey };
4070
+ };
4071
+ var formatPrivKeyForBabyJub = (privKey) => {
4072
+ const sBuff = import_circomlib.eddsa.pruneBuffer(
4073
+ (0, import_blake_hash.default)("blake512").update(bigInt2Buffer(privKey)).digest().slice(0, 32)
4074
+ );
4075
+ const s = import_ffjavascript.utils.leBuff2int(sBuff);
4076
+ return import_ffjavascript.Scalar.shr(s, 3);
4077
+ };
4078
+ var genEcdhSharedKey = (privKey, pubKey) => {
4079
+ const sharedKey = import_circomlib.babyJub.mulPointEscalar(
4080
+ pubKey,
4081
+ formatPrivKeyForBabyJub(privKey)
4082
+ );
4083
+ if (sharedKey[0] === 0n) {
4084
+ return [0n, 1n];
4085
+ } else {
4086
+ return sharedKey;
4087
+ }
4088
+ };
4089
+ var genMessageFactory = (stateIdx, signPriKey, signPubKey, coordPubKey) => (encPriKey, nonce, voIdx, newVotes, isLastCmd, salt) => {
4090
+ if (!salt) {
4091
+ salt = BigInt("0x" + (0, import_crypto.randomBytes)(7).toString("hex"));
4092
+ }
4093
+ const packaged = BigInt(nonce) + (BigInt(stateIdx) << 32n) + (BigInt(voIdx) << 64n) + (BigInt(newVotes) << 96n) + (BigInt(salt) << 192n);
4094
+ let newPubKey = [...signPubKey];
4095
+ if (isLastCmd) {
4096
+ newPubKey = [0n, 0n];
4097
+ }
4098
+ const hash = (0, import_circomlib.poseidon)([packaged, ...newPubKey]);
4099
+ const signature = import_circomlib.eddsa.signPoseidon(bigInt2Buffer(signPriKey), hash);
4100
+ const command = [packaged, ...newPubKey, ...signature.R8, signature.S];
4101
+ const message = (0, import_circomlib.poseidonEncrypt)(
4102
+ command,
4103
+ genEcdhSharedKey(encPriKey, coordPubKey),
4104
+ 0n
4105
+ );
4106
+ return message;
4107
+ };
4108
+ var batchGenMessage = (stateIdx, account, coordPubKey, plan) => {
4109
+ const genMessage = genMessageFactory(
4110
+ stateIdx,
4111
+ account.privKey,
4112
+ account.pubKey,
4113
+ coordPubKey
4114
+ );
4115
+ const payload = [];
4116
+ for (let i = plan.length - 1; i >= 0; i--) {
4117
+ const p = plan[i];
4118
+ const encAccount = genKeypair();
4119
+ const msg = genMessage(
4120
+ encAccount.privKey,
4121
+ i + 1,
4122
+ p[0],
4123
+ p[1],
4124
+ i === plan.length - 1
4125
+ );
4126
+ payload.push({
4127
+ msg,
4128
+ encPubkeys: encAccount.pubKey
4129
+ });
4130
+ }
4131
+ return payload;
4132
+ };
4133
+ var privateKeyFromTxt = (txt) => {
4134
+ if (typeof txt !== "string") {
4135
+ return;
4136
+ }
4137
+ const key = txt.split("\n")[1] || "";
4138
+ if (key.length !== 512) {
4139
+ return;
4140
+ }
4141
+ const keys = key.match(/[0-9a-f]{128}/g);
4142
+ if (!keys || keys.length !== 4) {
4143
+ return;
4144
+ }
4145
+ const priKey = (0, import_circomlib.poseidon)(keys.map((k) => BigInt("0x" + k)));
4146
+ return genKeypair(priKey % SNARK_FIELD_SIZE);
4147
+ };
4148
+ var rerandomize = (pubKey, ciphertext, randomVal = genRandomKey()) => {
4149
+ const d1 = import_circomlib.babyJub.addPoint(
4150
+ import_circomlib.babyJub.mulPointEscalar(import_circomlib.babyJub.Base8, randomVal),
4151
+ ciphertext.c1
4152
+ );
4153
+ const d2 = import_circomlib.babyJub.addPoint(
4154
+ import_circomlib.babyJub.mulPointEscalar(pubKey, randomVal),
4155
+ ciphertext.c2
4156
+ );
4157
+ return {
4158
+ d1,
4159
+ d2
4160
+ };
4161
+ };
4162
+ var genAddKeyProof = async (depth, {
4163
+ coordPubKey,
4164
+ oldKey,
4165
+ deactivates
4166
+ }) => {
4167
+ const sharedKeyHash = (0, import_circomlib.poseidon)(genEcdhSharedKey(oldKey.privKey, coordPubKey));
4168
+ const randomVal = genRandomKey();
4169
+ const deactivateIdx = deactivates.findIndex((d) => d[4] === sharedKeyHash);
4170
+ if (deactivateIdx < 0) {
4171
+ return null;
4172
+ }
4173
+ const deactivateLeaf = deactivates[deactivateIdx];
4174
+ const c1 = [deactivateLeaf[0], deactivateLeaf[1]];
4175
+ const c2 = [deactivateLeaf[2], deactivateLeaf[3]];
4176
+ const { d1, d2 } = rerandomize(coordPubKey, { c1, c2 }, randomVal);
4177
+ const nullifier = (0, import_circomlib.poseidon)([oldKey.formatedPrivKey, 1444992409218394441042n]);
4178
+ const tree = new import_circomlib.Tree(5, depth, 0n);
4179
+ const leaves = deactivates.map((d) => (0, import_circomlib.poseidon)(d));
4180
+ tree.initLeaves(leaves);
4181
+ const deactivateRoot = tree.root;
4182
+ const deactivateLeafPathElements = tree.pathElementOf(deactivateIdx);
4183
+ const inputHash = BigInt(
4184
+ (0, import_ethers.solidityPackedSha256)(
4185
+ new Array(7).fill("uint256"),
4186
+ stringizing([
4187
+ deactivateRoot,
4188
+ (0, import_circomlib.poseidon)(coordPubKey),
4189
+ nullifier,
4190
+ d1[0],
4191
+ d1[1],
4192
+ d2[0],
4193
+ d2[1]
4194
+ ])
4195
+ )
4196
+ ) % SNARK_FIELD_SIZE;
4197
+ const input = {
4198
+ inputHash,
4199
+ coordPubKey,
4200
+ deactivateRoot,
4201
+ deactivateIndex: deactivateIdx,
4202
+ deactivateLeaf: (0, import_circomlib.poseidon)(deactivateLeaf),
4203
+ c1,
4204
+ c2,
4205
+ randomVal,
4206
+ d1,
4207
+ d2,
4208
+ deactivateLeafPathElements,
4209
+ nullifier,
4210
+ oldPrivateKey: oldKey.formatedPrivKey
4211
+ };
4212
+ return input;
4213
+ };
4214
+
4215
+ // src/libs/circom/index.ts
4216
+ var Circom = class {
4217
+ constructor({ network }) {
4218
+ this.network = network;
4219
+ this.chainId = getDefaultParams(network).chainId;
4220
+ }
4221
+ async signMessage(signer, address, message) {
4222
+ const accounts = await signer.getAccounts();
4223
+ const account = accounts.find((acc) => acc.address === address);
4224
+ if (!account) {
4225
+ throw new Error(`Address ${address} not found in wallet`);
4226
+ }
4227
+ if ((0, import_proto_signing.isOfflineDirectSigner)(signer)) {
4228
+ const signDoc = {
4229
+ bodyBytes: new TextEncoder().encode(message),
4230
+ authInfoBytes: new Uint8Array(),
4231
+ chainId: this.chainId,
4232
+ accountNumber: BigInt(0)
4233
+ };
4234
+ const { signature } = await signer.signDirect(address, signDoc);
4235
+ return {
4236
+ signature: signature.signature,
4237
+ pubkey: account.pubkey
4238
+ };
4239
+ } else {
4240
+ const signDoc = {
4241
+ chain_id: this.chainId,
4242
+ account_number: "0",
4243
+ sequence: "0",
4244
+ fee: {
4245
+ gas: "0",
4246
+ amount: []
4247
+ },
4248
+ msgs: [],
4249
+ memo: message
4250
+ };
4251
+ const { signature } = await signer.signAmino(address, signDoc);
4252
+ return {
4253
+ signature: signature.signature,
4254
+ pubkey: account.pubkey
4255
+ };
4256
+ }
4257
+ }
4258
+ async genKeypairFromSign(signer, address) {
4259
+ const sig = await this.signMessage(
4260
+ signer,
4261
+ address,
4262
+ "Generate_MACI_Private_Key"
4263
+ );
4264
+ const sign = BigInt(
4265
+ "0x" + Buffer.from(sig.signature, "base64").toString("hex")
4266
+ );
4267
+ return genKeypair(sign);
4268
+ }
3983
4269
  };
3984
4270
 
3985
4271
  // src/maci.ts
@@ -4030,6 +4316,7 @@ var MaciClient2 = class {
4030
4316
  feegrantOperator: this.feegrantOperator,
4031
4317
  whitelistBackendPubkey: this.whitelistBackendPubkey
4032
4318
  });
4319
+ this.circom = new Circom({ network });
4033
4320
  }
4034
4321
  async oracleMaciClient({
4035
4322
  signer,
@@ -4208,9 +4495,13 @@ var MaciClient2 = class {
4208
4495
  return await this.indexer.proof.getProofByContractAddress(address);
4209
4496
  }
4210
4497
  };
4498
+
4499
+ // src/index.ts
4500
+ var import_ffjavascript2 = require("ffjavascript");
4501
+ var import_blake_hash2 = __toESM(require("blake-hash"));
4211
4502
  // Annotate the CommonJS export names for ESM import in node:
4212
4503
  0 && (module.exports = {
4213
- Account,
4504
+ Circom,
4214
4505
  Circuit,
4215
4506
  Contract,
4216
4507
  Http,
@@ -4222,13 +4513,24 @@ var MaciClient2 = class {
4222
4513
  Operator,
4223
4514
  Proof,
4224
4515
  Round,
4516
+ Scalar,
4225
4517
  Transaction,
4518
+ UserAccount,
4519
+ batchGenMessage,
4226
4520
  circuits,
4227
4521
  compressPublicKey,
4522
+ createBlakeHash,
4228
4523
  decompressPublicKey,
4524
+ genAddKeyProof,
4525
+ genEcdhSharedKey,
4526
+ genKeypair,
4527
+ genMessageFactory,
4229
4528
  getDefaultParams,
4230
4529
  hexToDecimalString,
4231
4530
  isValidAddress,
4531
+ privateKeyFromTxt,
4532
+ stringizing,
4533
+ utils,
4232
4534
  validator_operator_set
4233
4535
  });
4234
4536
  //# sourceMappingURL=index.js.map