@dorafactory/maci-sdk 0.0.6 → 0.0.7

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);
@@ -3713,8 +3734,8 @@ function getContractParams(type, circuitType, proofSystem, maxVoter, maxOption)
3713
3734
  case "2" /* ORACLE_MACI */:
3714
3735
  return {
3715
3736
  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,
3737
+ groth16ProcessVkey,
3738
+ groth16TallyVkey,
3718
3739
  plonkProcessVkey: null,
3719
3740
  plonkTallyVkey: null,
3720
3741
  maciVoteType,
@@ -3980,6 +4001,264 @@ var Contract = class {
3980
4001
  contractAddress
3981
4002
  });
3982
4003
  }
4004
+ async contractClient({ signer }) {
4005
+ return createContractClientByWallet(this.rpcEndpoint, signer);
4006
+ }
4007
+ };
4008
+
4009
+ // src/libs/circom/index.ts
4010
+ var import_proto_signing = require("@cosmjs/proto-signing");
4011
+
4012
+ // src/libs/circom/circomlib.ts
4013
+ var import_crypto = require("crypto");
4014
+ var import_circomlib = require("@dorafactory/circomlib");
4015
+ var import_ffjavascript = require("ffjavascript");
4016
+ var import_blake_hash = __toESM(require("blake-hash"));
4017
+ var import_ethers = require("ethers");
4018
+ var SNARK_FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
4019
+ var bigInt2Buffer = (i) => {
4020
+ let hex = i.toString(16);
4021
+ if (hex.length % 2 === 1) {
4022
+ hex = "0" + hex;
4023
+ }
4024
+ return Buffer.from(hex, "hex");
4025
+ };
4026
+ var genRandomKey = () => {
4027
+ const min = 6350874878119819312338956282401532410528162663560392320966563075034087161851n;
4028
+ let rand;
4029
+ while (true) {
4030
+ rand = BigInt("0x" + (0, import_crypto.randomBytes)(32).toString("hex"));
4031
+ if (rand >= min) {
4032
+ break;
4033
+ }
4034
+ }
4035
+ const privKey = rand % SNARK_FIELD_SIZE;
4036
+ return privKey;
4037
+ };
4038
+ var genPubKey = (privKey) => {
4039
+ return import_circomlib.eddsa.prv2pub(bigInt2Buffer(privKey));
4040
+ };
4041
+ var stringizing = (o, path = []) => {
4042
+ if (path.includes(o)) {
4043
+ throw new Error("loop nesting!");
4044
+ }
4045
+ const newPath = [...path, o];
4046
+ if (Array.isArray(o)) {
4047
+ return o.map((item) => stringizing(item, newPath));
4048
+ } else if (typeof o === "object") {
4049
+ const output = {};
4050
+ for (const key in o) {
4051
+ output[key] = stringizing(o[key], newPath);
4052
+ }
4053
+ return output;
4054
+ } else {
4055
+ return o.toString();
4056
+ }
4057
+ };
4058
+ var genKeypair = (pkey) => {
4059
+ const privKey = pkey ? pkey % SNARK_FIELD_SIZE : genRandomKey();
4060
+ const pubKey = genPubKey(privKey);
4061
+ const formatedPrivKey = formatPrivKeyForBabyJub(privKey);
4062
+ return { privKey, pubKey, formatedPrivKey };
4063
+ };
4064
+ var formatPrivKeyForBabyJub = (privKey) => {
4065
+ const sBuff = import_circomlib.eddsa.pruneBuffer(
4066
+ (0, import_blake_hash.default)("blake512").update(bigInt2Buffer(privKey)).digest().slice(0, 32)
4067
+ );
4068
+ const s = import_ffjavascript.utils.leBuff2int(sBuff);
4069
+ return import_ffjavascript.Scalar.shr(s, 3);
4070
+ };
4071
+ var genEcdhSharedKey = (privKey, pubKey) => {
4072
+ const sharedKey = import_circomlib.babyJub.mulPointEscalar(
4073
+ pubKey,
4074
+ formatPrivKeyForBabyJub(privKey)
4075
+ );
4076
+ if (sharedKey[0] === 0n) {
4077
+ return [0n, 1n];
4078
+ } else {
4079
+ return sharedKey;
4080
+ }
4081
+ };
4082
+ var genMessageFactory = (stateIdx, signPriKey, signPubKey, coordPubKey) => (encPriKey, nonce, voIdx, newVotes, isLastCmd, salt) => {
4083
+ if (!salt) {
4084
+ salt = BigInt("0x" + (0, import_crypto.randomBytes)(7).toString("hex"));
4085
+ }
4086
+ const packaged = BigInt(nonce) + (BigInt(stateIdx) << 32n) + (BigInt(voIdx) << 64n) + (BigInt(newVotes) << 96n) + (BigInt(salt) << 192n);
4087
+ let newPubKey = [...signPubKey];
4088
+ if (isLastCmd) {
4089
+ newPubKey = [0n, 0n];
4090
+ }
4091
+ const hash = (0, import_circomlib.poseidon)([packaged, ...newPubKey]);
4092
+ const signature = import_circomlib.eddsa.signPoseidon(bigInt2Buffer(signPriKey), hash);
4093
+ const command = [packaged, ...newPubKey, ...signature.R8, signature.S];
4094
+ const message = (0, import_circomlib.poseidonEncrypt)(
4095
+ command,
4096
+ genEcdhSharedKey(encPriKey, coordPubKey),
4097
+ 0n
4098
+ );
4099
+ return message;
4100
+ };
4101
+ var batchGenMessage = (stateIdx, account, coordPubKey, plan) => {
4102
+ const genMessage = genMessageFactory(
4103
+ stateIdx,
4104
+ account.privKey,
4105
+ account.pubKey,
4106
+ coordPubKey
4107
+ );
4108
+ const payload = [];
4109
+ for (let i = plan.length - 1; i >= 0; i--) {
4110
+ const p = plan[i];
4111
+ const encAccount = genKeypair();
4112
+ const msg = genMessage(
4113
+ encAccount.privKey,
4114
+ i + 1,
4115
+ p[0],
4116
+ p[1],
4117
+ i === plan.length - 1
4118
+ );
4119
+ payload.push({
4120
+ msg,
4121
+ encPubkeys: encAccount.pubKey
4122
+ });
4123
+ }
4124
+ return payload;
4125
+ };
4126
+ var privateKeyFromTxt = (txt) => {
4127
+ if (typeof txt !== "string") {
4128
+ return;
4129
+ }
4130
+ const key = txt.split("\n")[1] || "";
4131
+ if (key.length !== 512) {
4132
+ return;
4133
+ }
4134
+ const keys = key.match(/[0-9a-f]{128}/g);
4135
+ if (!keys || keys.length !== 4) {
4136
+ return;
4137
+ }
4138
+ const priKey = (0, import_circomlib.poseidon)(keys.map((k) => BigInt("0x" + k)));
4139
+ return genKeypair(priKey % SNARK_FIELD_SIZE);
4140
+ };
4141
+ var rerandomize = (pubKey, ciphertext, randomVal = genRandomKey()) => {
4142
+ const d1 = import_circomlib.babyJub.addPoint(
4143
+ import_circomlib.babyJub.mulPointEscalar(import_circomlib.babyJub.Base8, randomVal),
4144
+ ciphertext.c1
4145
+ );
4146
+ const d2 = import_circomlib.babyJub.addPoint(
4147
+ import_circomlib.babyJub.mulPointEscalar(pubKey, randomVal),
4148
+ ciphertext.c2
4149
+ );
4150
+ return {
4151
+ d1,
4152
+ d2
4153
+ };
4154
+ };
4155
+ var genAddKeyProof = async (depth, {
4156
+ coordPubKey,
4157
+ oldKey,
4158
+ deactivates
4159
+ }) => {
4160
+ const sharedKeyHash = (0, import_circomlib.poseidon)(genEcdhSharedKey(oldKey.privKey, coordPubKey));
4161
+ const randomVal = genRandomKey();
4162
+ const deactivateIdx = deactivates.findIndex((d) => d[4] === sharedKeyHash);
4163
+ if (deactivateIdx < 0) {
4164
+ return null;
4165
+ }
4166
+ const deactivateLeaf = deactivates[deactivateIdx];
4167
+ const c1 = [deactivateLeaf[0], deactivateLeaf[1]];
4168
+ const c2 = [deactivateLeaf[2], deactivateLeaf[3]];
4169
+ const { d1, d2 } = rerandomize(coordPubKey, { c1, c2 }, randomVal);
4170
+ const nullifier = (0, import_circomlib.poseidon)([oldKey.formatedPrivKey, 1444992409218394441042n]);
4171
+ const tree = new import_circomlib.Tree(5, depth, 0n);
4172
+ const leaves = deactivates.map((d) => (0, import_circomlib.poseidon)(d));
4173
+ tree.initLeaves(leaves);
4174
+ const deactivateRoot = tree.root;
4175
+ const deactivateLeafPathElements = tree.pathElementOf(deactivateIdx);
4176
+ const inputHash = BigInt(
4177
+ (0, import_ethers.solidityPackedSha256)(
4178
+ new Array(7).fill("uint256"),
4179
+ stringizing([
4180
+ deactivateRoot,
4181
+ (0, import_circomlib.poseidon)(coordPubKey),
4182
+ nullifier,
4183
+ d1[0],
4184
+ d1[1],
4185
+ d2[0],
4186
+ d2[1]
4187
+ ])
4188
+ )
4189
+ ) % SNARK_FIELD_SIZE;
4190
+ const input = {
4191
+ inputHash,
4192
+ coordPubKey,
4193
+ deactivateRoot,
4194
+ deactivateIndex: deactivateIdx,
4195
+ deactivateLeaf: (0, import_circomlib.poseidon)(deactivateLeaf),
4196
+ c1,
4197
+ c2,
4198
+ randomVal,
4199
+ d1,
4200
+ d2,
4201
+ deactivateLeafPathElements,
4202
+ nullifier,
4203
+ oldPrivateKey: oldKey.formatedPrivKey
4204
+ };
4205
+ return input;
4206
+ };
4207
+
4208
+ // src/libs/circom/index.ts
4209
+ var Circom = class {
4210
+ constructor({ network }) {
4211
+ this.network = network;
4212
+ this.chainId = getDefaultParams(network).chainId;
4213
+ }
4214
+ async signMessage(signer, address, message) {
4215
+ const accounts = await signer.getAccounts();
4216
+ const account = accounts.find((acc) => acc.address === address);
4217
+ if (!account) {
4218
+ throw new Error(`Address ${address} not found in wallet`);
4219
+ }
4220
+ if ((0, import_proto_signing.isOfflineDirectSigner)(signer)) {
4221
+ const signDoc = {
4222
+ bodyBytes: new TextEncoder().encode(message),
4223
+ authInfoBytes: new Uint8Array(),
4224
+ chainId: this.chainId,
4225
+ accountNumber: BigInt(0)
4226
+ };
4227
+ const { signature } = await signer.signDirect(address, signDoc);
4228
+ return {
4229
+ signature: signature.signature,
4230
+ pubkey: account.pubkey
4231
+ };
4232
+ } else {
4233
+ const signDoc = {
4234
+ chain_id: this.chainId,
4235
+ account_number: "0",
4236
+ sequence: "0",
4237
+ fee: {
4238
+ gas: "0",
4239
+ amount: []
4240
+ },
4241
+ msgs: [],
4242
+ memo: message
4243
+ };
4244
+ const { signature } = await signer.signAmino(address, signDoc);
4245
+ return {
4246
+ signature: signature.signature,
4247
+ pubkey: account.pubkey
4248
+ };
4249
+ }
4250
+ }
4251
+ async genKeypairFromSign(signer, address) {
4252
+ const sig = await this.signMessage(
4253
+ signer,
4254
+ address,
4255
+ "Generate_MACI_Private_Key"
4256
+ );
4257
+ const sign = BigInt(
4258
+ "0x" + Buffer.from(sig.signature, "base64").toString("hex")
4259
+ );
4260
+ return genKeypair(sign);
4261
+ }
3983
4262
  };
3984
4263
 
3985
4264
  // src/maci.ts
@@ -4030,6 +4309,7 @@ var MaciClient2 = class {
4030
4309
  feegrantOperator: this.feegrantOperator,
4031
4310
  whitelistBackendPubkey: this.whitelistBackendPubkey
4032
4311
  });
4312
+ this.circom = new Circom({ network });
4033
4313
  }
4034
4314
  async oracleMaciClient({
4035
4315
  signer,
@@ -4208,9 +4488,13 @@ var MaciClient2 = class {
4208
4488
  return await this.indexer.proof.getProofByContractAddress(address);
4209
4489
  }
4210
4490
  };
4491
+
4492
+ // src/index.ts
4493
+ var import_ffjavascript2 = require("ffjavascript");
4494
+ var import_blake_hash2 = __toESM(require("blake-hash"));
4211
4495
  // Annotate the CommonJS export names for ESM import in node:
4212
4496
  0 && (module.exports = {
4213
- Account,
4497
+ Circom,
4214
4498
  Circuit,
4215
4499
  Contract,
4216
4500
  Http,
@@ -4222,13 +4506,24 @@ var MaciClient2 = class {
4222
4506
  Operator,
4223
4507
  Proof,
4224
4508
  Round,
4509
+ Scalar,
4225
4510
  Transaction,
4511
+ UserAccount,
4512
+ batchGenMessage,
4226
4513
  circuits,
4227
4514
  compressPublicKey,
4515
+ createBlakeHash,
4228
4516
  decompressPublicKey,
4517
+ genAddKeyProof,
4518
+ genEcdhSharedKey,
4519
+ genKeypair,
4520
+ genMessageFactory,
4229
4521
  getDefaultParams,
4230
4522
  hexToDecimalString,
4231
4523
  isValidAddress,
4524
+ privateKeyFromTxt,
4525
+ stringizing,
4526
+ utils,
4232
4527
  validator_operator_set
4233
4528
  });
4234
4529
  //# sourceMappingURL=index.js.map