@waku/rln 0.1.6-a8ca168.0 → 0.1.6-ace7ca2.0

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.
@@ -13,6 +13,7 @@ import '../../../../node_modules/multiformats/dist/src/bases/base8.js';
13
13
  import '../../../../node_modules/multiformats/dist/src/bases/identity.js';
14
14
  import '../../../../node_modules/multiformats/dist/src/codecs/json.js';
15
15
  import { Logger } from '../../../utils/dist/logger/index.js';
16
+ import { buildBigIntFromUint8ArrayBE } from '../utils/bytes.js';
16
17
  import { RLN_ABI } from './abi.js';
17
18
  import { DEFAULT_Q, DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS } from './constants.js';
18
19
  import { MembershipState } from './types.js';
@@ -344,11 +345,28 @@ class RLNBaseContract {
344
345
  log.error(`Error in withdraw: ${error.message}`);
345
346
  }
346
347
  }
348
+ getIdCommitmentBigInt(bytes) {
349
+ let idCommitmentBigIntBE = buildBigIntFromUint8ArrayBE(bytes);
350
+ log.info("getIdCommitmentBigInt", {
351
+ idCommitmentBigIntBE,
352
+ idCommitmentBigIntLimit: this.idCommitmentBigIntLimit
353
+ });
354
+ if (!this.contract) {
355
+ throw Error("RLN contract is not initialized");
356
+ }
357
+ const idCommitmentBigIntLimit = this.contract.idCommitmentBigIntLimit;
358
+ if (idCommitmentBigIntBE >= idCommitmentBigIntLimit) {
359
+ log.warn(`ID commitment is greater than Q, reducing it by Q(idCommitmentBigIntLimit): ${idCommitmentBigIntBE} % ${idCommitmentBigIntLimit}`);
360
+ idCommitmentBigIntBE = idCommitmentBigIntBE % idCommitmentBigIntLimit;
361
+ }
362
+ return idCommitmentBigIntBE;
363
+ }
347
364
  async registerWithIdentity(identity) {
348
365
  try {
349
366
  log.info(`Registering identity with rate limit: ${this.rateLimit} messages/epoch`);
367
+ const idCommitmentBigInt = this.getIdCommitmentBigInt(identity.IDCommitment);
350
368
  // Check if the ID commitment is already registered
351
- const existingIndex = await this.getMemberIndex(identity.IDCommitmentBigInt);
369
+ const existingIndex = await this.getMemberIndex(idCommitmentBigInt);
352
370
  if (existingIndex) {
353
371
  throw new Error(`ID commitment is already registered with index ${existingIndex}`);
354
372
  }
@@ -357,9 +375,11 @@ class RLNBaseContract {
357
375
  if (remainingRateLimit < this.rateLimit) {
358
376
  throw new Error(`Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`);
359
377
  }
360
- const estimatedGas = await this.contract.estimateGas.register(identity.IDCommitmentBigInt, this.rateLimit, []);
378
+ const estimatedGas = await this.contract.estimateGas.register(idCommitmentBigInt, this.rateLimit, []);
361
379
  const gasLimit = estimatedGas.add(10000);
362
- const txRegisterResponse = await this.contract.register(identity.IDCommitmentBigInt, this.rateLimit, [], { gasLimit });
380
+ const txRegisterResponse = await this.contract.register(idCommitmentBigInt, this.rateLimit, [], {
381
+ gasLimit
382
+ });
363
383
  const txRegisterReceipt = await txRegisterResponse.wait();
364
384
  if (txRegisterReceipt.status === 0) {
365
385
  throw new Error("Transaction failed on-chain");
@@ -421,7 +441,7 @@ class RLNBaseContract {
421
441
  async registerWithPermitAndErase(identity, permit, idCommitmentsToErase) {
422
442
  try {
423
443
  log.info(`Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`);
424
- const txRegisterResponse = await this.contract.registerWithPermit(permit.owner, permit.deadline, permit.v, permit.r, permit.s, identity.IDCommitmentBigInt, this.rateLimit, idCommitmentsToErase.map((id) => BigNumber.from(id)));
444
+ const txRegisterResponse = await this.contract.registerWithPermit(permit.owner, permit.deadline, permit.v, permit.r, permit.s, this.getIdCommitmentBigInt(identity.IDCommitment), this.rateLimit, idCommitmentsToErase.map((id) => BigNumber.from(id)));
425
445
  const txRegisterReceipt = await txRegisterResponse.wait();
426
446
  const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
427
447
  if (!memberRegistered || !memberRegistered.args) {
@@ -20,7 +20,7 @@ import { RLNBaseContract } from './contract/rln_base_contract.js';
20
20
  import { IdentityCredential } from './identity.js';
21
21
  import { Keystore } from './keystore/keystore.js';
22
22
  import { extractMetaMaskSigner } from './utils/metamask.js';
23
- import { buildBigIntFromUint8ArrayLE } from './utils/bytes.js';
23
+ import { switchEndianness } from './utils/bytes.js';
24
24
  import './utils/epoch.js';
25
25
 
26
26
  const log = new Logger("waku:credentials");
@@ -198,22 +198,19 @@ class RLNCredentialsManager {
198
198
  const seedBytes = encoder.encode(seed);
199
199
  // Generate deterministic values using HMAC-SHA256
200
200
  // We use different context strings for each component to ensure they're different
201
- const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
202
- const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
203
- const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
204
- const idSecretHash = sha256(combinedBytes);
205
- const idCommitment = sha256(idSecretHash);
206
- let idCommitmentBigInt = buildBigIntFromUint8ArrayLE(idCommitment);
207
- if (!this.contract) {
208
- throw Error("RLN contract is not initialized");
209
- }
210
- const idCommitmentBigIntLimit = this.contract.idCommitmentBigIntLimit;
211
- if (idCommitmentBigInt >= idCommitmentBigIntLimit) {
212
- log.warn(`ID commitment is greater than Q, reducing it by Q(idCommitmentBigIntLimit): ${idCommitmentBigInt} % ${idCommitmentBigIntLimit}`);
213
- idCommitmentBigInt = idCommitmentBigInt % idCommitmentBigIntLimit;
214
- }
201
+ const idTrapdoorBE = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
202
+ const idNullifierBE = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
203
+ const combinedBytes = new Uint8Array([...idTrapdoorBE, ...idNullifierBE]);
204
+ const idSecretHashBE = sha256(combinedBytes);
205
+ const idCommitmentBE = sha256(idSecretHashBE);
206
+ // All hashing functions return big-endian bytes
207
+ // We need to switch to little-endian for the identity credential
208
+ const idTrapdoorLE = switchEndianness(idTrapdoorBE);
209
+ const idNullifierLE = switchEndianness(idNullifierBE);
210
+ const idSecretHashLE = switchEndianness(idSecretHashBE);
211
+ const idCommitmentLE = switchEndianness(idCommitmentBE);
215
212
  log.info("Successfully generated identity credential");
216
- return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
213
+ return new IdentityCredential(idTrapdoorLE, idNullifierLE, idSecretHashLE, idCommitmentLE);
217
214
  }
218
215
  }
219
216
 
@@ -1,18 +1,16 @@
1
- import { buildBigIntFromUint8ArrayLE } from './utils/bytes.js';
2
- import './utils/epoch.js';
3
-
4
1
  class IdentityCredential {
5
2
  IDTrapdoor;
6
3
  IDNullifier;
7
4
  IDSecretHash;
8
5
  IDCommitment;
9
- IDCommitmentBigInt;
10
- constructor(IDTrapdoor, IDNullifier, IDSecretHash, IDCommitment, IDCommitmentBigInt) {
6
+ /**
7
+ * All variables are in little-endian format
8
+ */
9
+ constructor(IDTrapdoor, IDNullifier, IDSecretHash, IDCommitment) {
11
10
  this.IDTrapdoor = IDTrapdoor;
12
11
  this.IDNullifier = IDNullifier;
13
12
  this.IDSecretHash = IDSecretHash;
14
13
  this.IDCommitment = IDCommitment;
15
- this.IDCommitmentBigInt = IDCommitmentBigInt;
16
14
  }
17
15
  static fromBytes(memKeys) {
18
16
  if (memKeys.length < 128) {
@@ -22,8 +20,7 @@ class IdentityCredential {
22
20
  const idNullifier = memKeys.subarray(32, 64);
23
21
  const idSecretHash = memKeys.subarray(64, 96);
24
22
  const idCommitment = memKeys.subarray(96, 128);
25
- const idCommitmentBigInt = buildBigIntFromUint8ArrayLE(idCommitment);
26
- return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
23
+ return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment);
27
24
  }
28
25
  }
29
26
 
@@ -17,7 +17,6 @@ import { Logger } from '../../../utils/dist/logger/index.js';
17
17
  import { sha256 } from '../../../../node_modules/ethereum-cryptography/esm/sha256.js';
18
18
  import { bytesToUtf8 } from '../../../../node_modules/ethereum-cryptography/esm/utils.js';
19
19
  import _ from '../../../../node_modules/lodash/lodash.js';
20
- import { buildBigIntFromUint8ArrayLE } from '../utils/bytes.js';
21
20
  import { keccak256Checksum, decryptEipKeystore } from './cipher.js';
22
21
  import { isKeystoreValid, isCredentialValid } from './schema_validator.js';
23
22
  import { __exports as lib } from '../../../../_virtual/index.js';
@@ -164,14 +163,16 @@ class Keystore {
164
163
  try {
165
164
  const str = bytesToUtf8(bytes);
166
165
  const obj = JSON.parse(str);
167
- // TODO: add runtime validation of nwaku credentials
166
+ const idCommitmentLE = Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idCommitment", []));
167
+ const idTrapdoorLE = Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idTrapdoor", []));
168
+ const idNullifierLE = Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idNullifier", []));
169
+ const idSecretHashLE = Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idSecretHash", []));
168
170
  return {
169
171
  identity: {
170
- IDCommitment: Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idCommitment", [])),
171
- IDTrapdoor: Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idTrapdoor", [])),
172
- IDNullifier: Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idNullifier", [])),
173
- IDCommitmentBigInt: buildBigIntFromUint8ArrayLE(Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idCommitment", []))),
174
- IDSecretHash: Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idSecretHash", []))
172
+ IDCommitment: idCommitmentLE,
173
+ IDTrapdoor: idTrapdoorLE,
174
+ IDNullifier: idNullifierLE,
175
+ IDSecretHash: idSecretHashLE
175
176
  },
176
177
  membership: {
177
178
  treeIndex: _.get(obj, "treeIndex"),
@@ -208,13 +209,16 @@ class Keystore {
208
209
  // follows nwaku implementation
209
210
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L98
210
211
  static fromIdentityToBytes(options) {
212
+ function toLittleEndian(bytes) {
213
+ return new Uint8Array(bytes).reverse();
214
+ }
211
215
  return utf8ToBytes(JSON.stringify({
212
216
  treeIndex: options.membership.treeIndex,
213
217
  identityCredential: {
214
- idCommitment: Array.from(options.identity.IDCommitment),
215
- idNullifier: Array.from(options.identity.IDNullifier),
216
- idSecretHash: Array.from(options.identity.IDSecretHash),
217
- idTrapdoor: Array.from(options.identity.IDTrapdoor)
218
+ idCommitment: Array.from(toLittleEndian(options.identity.IDCommitment)),
219
+ idNullifier: Array.from(toLittleEndian(options.identity.IDNullifier)),
220
+ idSecretHash: Array.from(toLittleEndian(options.identity.IDSecretHash)),
221
+ idTrapdoor: Array.from(toLittleEndian(options.identity.IDTrapdoor))
218
222
  },
219
223
  membershipContract: {
220
224
  chainId: options.membership.chainId,
@@ -16,12 +16,12 @@ function concatenate(...input) {
16
16
  }
17
17
  return result;
18
18
  }
19
- // Adapted from https://github.com/feross/buffer
20
- function checkInt(buf, value, offset, ext, max, min) {
21
- if (value > max || value < min)
22
- throw new RangeError('"value" argument is out of bounds');
23
- if (offset + ext > buf.length)
24
- throw new RangeError("Index out of range");
19
+ function switchEndianness(bytes) {
20
+ return new Uint8Array(bytes.reverse());
21
+ }
22
+ function buildBigIntFromUint8ArrayBE(bytes) {
23
+ // Interpret bytes as big-endian
24
+ return bytes.reduce((acc, byte) => (acc << 8n) + BigInt(byte), 0n);
25
25
  }
26
26
  function writeUIntLE(buf, value, offset, byteLength, noAssert) {
27
27
  value = +value;
@@ -39,9 +39,6 @@ function writeUIntLE(buf, value, offset, byteLength, noAssert) {
39
39
  }
40
40
  return buf;
41
41
  }
42
- function buildBigIntFromUint8ArrayLE(bytes) {
43
- return bytes.reduce((acc, byte, i) => acc + BigInt(byte) * (1n << (8n * BigInt(i))), 0n);
44
- }
45
42
  /**
46
43
  * Fills with zeros to set length
47
44
  * @param array little endian Uint8Array
@@ -55,5 +52,12 @@ function zeroPadLE(array, length) {
55
52
  }
56
53
  return result;
57
54
  }
55
+ // Adapted from https://github.com/feross/buffer
56
+ function checkInt(buf, value, offset, ext, max, min) {
57
+ if (value > max || value < min)
58
+ throw new RangeError('"value" argument is out of bounds');
59
+ if (offset + ext > buf.length)
60
+ throw new RangeError("Index out of range");
61
+ }
58
62
 
59
- export { buildBigIntFromUint8ArrayLE, concatenate, writeUIntLE, zeroPadLE };
63
+ export { buildBigIntFromUint8ArrayBE, concatenate, switchEndianness, writeUIntLE, zeroPadLE };