@waku/rln 0.1.5-9901863.0 → 0.1.5-a8ff776.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.
Files changed (62) hide show
  1. package/bundle/index.js +0 -2
  2. package/bundle/packages/rln/dist/contract/constants.js +1 -1
  3. package/bundle/packages/rln/dist/contract/rln_contract.js +419 -9
  4. package/bundle/packages/rln/dist/create.js +1 -1
  5. package/bundle/packages/rln/dist/identity.js +0 -8
  6. package/bundle/packages/rln/dist/keystore/keystore.js +28 -19
  7. package/bundle/packages/rln/dist/rln.js +166 -56
  8. package/dist/.tsbuildinfo +1 -1
  9. package/dist/contract/constants.d.ts +1 -1
  10. package/dist/contract/constants.js +1 -1
  11. package/dist/contract/constants.js.map +1 -1
  12. package/dist/contract/rln_contract.d.ts +122 -5
  13. package/dist/contract/rln_contract.js +417 -8
  14. package/dist/contract/rln_contract.js.map +1 -1
  15. package/dist/create.js +1 -1
  16. package/dist/create.js.map +1 -1
  17. package/dist/identity.d.ts +0 -1
  18. package/dist/identity.js +0 -8
  19. package/dist/identity.js.map +1 -1
  20. package/dist/index.d.ts +1 -3
  21. package/dist/index.js +1 -3
  22. package/dist/index.js.map +1 -1
  23. package/dist/keystore/keystore.d.ts +1 -0
  24. package/dist/keystore/keystore.js +28 -19
  25. package/dist/keystore/keystore.js.map +1 -1
  26. package/dist/keystore/types.d.ts +1 -1
  27. package/dist/rln.d.ts +52 -9
  28. package/dist/rln.js +163 -54
  29. package/dist/rln.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/contract/constants.ts +1 -1
  32. package/src/contract/rln_contract.ts +663 -9
  33. package/src/create.ts +1 -1
  34. package/src/identity.ts +0 -9
  35. package/src/index.ts +0 -4
  36. package/src/keystore/keystore.ts +46 -31
  37. package/src/keystore/types.ts +1 -1
  38. package/src/rln.ts +259 -67
  39. package/bundle/packages/rln/dist/contract/rln_base_contract.js +0 -477
  40. package/bundle/packages/rln/dist/contract/types.js +0 -9
  41. package/bundle/packages/rln/dist/credentials_manager.js +0 -233
  42. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +0 -43
  43. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +0 -116
  44. package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +0 -79
  45. package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +0 -126
  46. package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +0 -43
  47. package/dist/contract/rln_base_contract.d.ts +0 -96
  48. package/dist/contract/rln_base_contract.js +0 -460
  49. package/dist/contract/rln_base_contract.js.map +0 -1
  50. package/dist/contract/types.d.ts +0 -40
  51. package/dist/contract/types.js +0 -8
  52. package/dist/contract/types.js.map +0 -1
  53. package/dist/credentials_manager.d.ts +0 -50
  54. package/dist/credentials_manager.js +0 -215
  55. package/dist/credentials_manager.js.map +0 -1
  56. package/dist/types.d.ts +0 -27
  57. package/dist/types.js +0 -2
  58. package/dist/types.js.map +0 -1
  59. package/src/contract/rln_base_contract.ts +0 -707
  60. package/src/contract/types.ts +0 -48
  61. package/src/credentials_manager.ts +0 -306
  62. package/src/types.ts +0 -31
package/bundle/index.js CHANGED
@@ -2,9 +2,7 @@ export { RLNDecoder, RLNEncoder } from './packages/rln/dist/codec.js';
2
2
  export { RLN_ABI } from './packages/rln/dist/contract/abi.js';
3
3
  export { RLNContract } from './packages/rln/dist/contract/rln_contract.js';
4
4
  export { LINEA_CONTRACT } from './packages/rln/dist/contract/constants.js';
5
- export { RLNBaseContract } from './packages/rln/dist/contract/rln_base_contract.js';
6
5
  export { createRLN } from './packages/rln/dist/create.js';
7
- export { RLNCredentialsManager } from './packages/rln/dist/credentials_manager.js';
8
6
  export { IdentityCredential } from './packages/rln/dist/identity.js';
9
7
  export { Keystore } from './packages/rln/dist/keystore/keystore.js';
10
8
  export { Proof } from './packages/rln/dist/proof.js';
@@ -1,7 +1,7 @@
1
1
  import { RLN_ABI } from './abi.js';
2
2
 
3
3
  const LINEA_CONTRACT = {
4
- chainId: "59141",
4
+ chainId: 59141,
5
5
  address: "0xb9cd878c90e49f797b4431fbf4fb333108cb90e6",
6
6
  abi: RLN_ABI
7
7
  };
@@ -5,28 +5,176 @@ import { hexToBytes } from '../../../utils/dist/bytes/index.js';
5
5
  import { Logger } from '../../../utils/dist/logger/index.js';
6
6
  import { MerkleRootTracker } from '../root_tracker.js';
7
7
  import { zeroPadLE } from '../utils/bytes.js';
8
- import { RLNBaseContract } from './rln_base_contract.js';
8
+ import { RLN_ABI } from './abi.js';
9
+ import { DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS } from './constants.js';
10
+ import { Contract } from '../../../../node_modules/@ethersproject/contracts/lib.esm/index.js';
9
11
  import { BigNumber } from '../../../../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js';
10
12
 
11
13
  const log = new Logger("waku:rln:contract");
12
- class RLNContract extends RLNBaseContract {
13
- instance;
14
+ var MembershipState;
15
+ (function (MembershipState) {
16
+ MembershipState["Active"] = "Active";
17
+ MembershipState["GracePeriod"] = "GracePeriod";
18
+ MembershipState["Expired"] = "Expired";
19
+ MembershipState["ErasedAwaitsWithdrawal"] = "ErasedAwaitsWithdrawal";
20
+ })(MembershipState || (MembershipState = {}));
21
+ class RLNContract {
22
+ contract;
14
23
  merkleRootTracker;
24
+ deployBlock;
25
+ rateLimit;
26
+ _members = new Map();
27
+ _membersFilter;
28
+ _membershipErasedFilter;
29
+ _membersExpiredFilter;
15
30
  /**
16
31
  * Asynchronous initializer for RLNContract.
17
32
  * Allows injecting a mocked contract for testing purposes.
18
33
  */
19
34
  static async init(rlnInstance, options) {
20
35
  const rlnContract = new RLNContract(rlnInstance, options);
36
+ await rlnContract.fetchMembers(rlnInstance);
37
+ rlnContract.subscribeToMembers(rlnInstance);
21
38
  return rlnContract;
22
39
  }
23
40
  constructor(rlnInstance, options) {
24
- super(options);
25
- this.instance = rlnInstance;
41
+ const { address, signer, rateLimit = DEFAULT_RATE_LIMIT, contract } = options;
42
+ this.validateRateLimit(rateLimit);
43
+ this.rateLimit = rateLimit;
26
44
  const initialRoot = rlnInstance.zerokit.getMerkleRoot();
45
+ // Use the injected contract if provided; otherwise, instantiate a new one.
46
+ this.contract = contract || new Contract(address, RLN_ABI, signer);
27
47
  this.merkleRootTracker = new MerkleRootTracker(5, initialRoot);
48
+ // Initialize event filters
49
+ this._membersFilter = this.contract.filters.MembershipRegistered();
50
+ this._membershipErasedFilter = this.contract.filters.MembershipErased();
51
+ this._membersExpiredFilter = this.contract.filters.MembershipExpired();
28
52
  }
29
- processEvents(events) {
53
+ /**
54
+ * Validates that the rate limit is within the allowed range
55
+ * @throws Error if the rate limit is outside the allowed range
56
+ */
57
+ validateRateLimit(rateLimit) {
58
+ if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
59
+ rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
60
+ throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE} messages per epoch`);
61
+ }
62
+ }
63
+ /**
64
+ * Gets the current rate limit for this contract instance
65
+ */
66
+ getRateLimit() {
67
+ return this.rateLimit;
68
+ }
69
+ /**
70
+ * Gets the contract address
71
+ */
72
+ get address() {
73
+ return this.contract.address;
74
+ }
75
+ /**
76
+ * Gets the contract provider
77
+ */
78
+ get provider() {
79
+ return this.contract.provider;
80
+ }
81
+ /**
82
+ * Gets the minimum allowed rate limit from the contract
83
+ * @returns Promise<number> The minimum rate limit in messages per epoch
84
+ */
85
+ async getMinRateLimit() {
86
+ const minRate = await this.contract.minMembershipRateLimit();
87
+ return minRate.toNumber();
88
+ }
89
+ /**
90
+ * Gets the maximum allowed rate limit from the contract
91
+ * @returns Promise<number> The maximum rate limit in messages per epoch
92
+ */
93
+ async getMaxRateLimit() {
94
+ const maxRate = await this.contract.maxMembershipRateLimit();
95
+ return maxRate.toNumber();
96
+ }
97
+ /**
98
+ * Gets the maximum total rate limit across all memberships
99
+ * @returns Promise<number> The maximum total rate limit in messages per epoch
100
+ */
101
+ async getMaxTotalRateLimit() {
102
+ const maxTotalRate = await this.contract.maxTotalRateLimit();
103
+ return maxTotalRate.toNumber();
104
+ }
105
+ /**
106
+ * Gets the current total rate limit usage across all memberships
107
+ * @returns Promise<number> The current total rate limit usage in messages per epoch
108
+ */
109
+ async getCurrentTotalRateLimit() {
110
+ const currentTotal = await this.contract.currentTotalRateLimit();
111
+ return currentTotal.toNumber();
112
+ }
113
+ /**
114
+ * Gets the remaining available total rate limit that can be allocated
115
+ * @returns Promise<number> The remaining rate limit that can be allocated
116
+ */
117
+ async getRemainingTotalRateLimit() {
118
+ const [maxTotal, currentTotal] = await Promise.all([
119
+ this.contract.maxTotalRateLimit(),
120
+ this.contract.currentTotalRateLimit()
121
+ ]);
122
+ return Number(maxTotal) - Number(currentTotal);
123
+ }
124
+ /**
125
+ * Updates the rate limit for future registrations
126
+ * @param newRateLimit The new rate limit to use
127
+ */
128
+ async setRateLimit(newRateLimit) {
129
+ this.validateRateLimit(newRateLimit);
130
+ this.rateLimit = newRateLimit;
131
+ }
132
+ get members() {
133
+ const sortedMembers = Array.from(this._members.values()).sort((left, right) => left.index.toNumber() - right.index.toNumber());
134
+ return sortedMembers;
135
+ }
136
+ get membersFilter() {
137
+ if (!this._membersFilter) {
138
+ throw Error("Members filter was not initialized.");
139
+ }
140
+ return this._membersFilter;
141
+ }
142
+ get membershipErasedFilter() {
143
+ if (!this._membershipErasedFilter) {
144
+ throw Error("MembershipErased filter was not initialized.");
145
+ }
146
+ return this._membershipErasedFilter;
147
+ }
148
+ get membersExpiredFilter() {
149
+ if (!this._membersExpiredFilter) {
150
+ throw Error("MembersExpired filter was not initialized.");
151
+ }
152
+ return this._membersExpiredFilter;
153
+ }
154
+ async fetchMembers(rlnInstance, options = {}) {
155
+ const registeredMemberEvents = await queryFilter(this.contract, {
156
+ fromBlock: this.deployBlock,
157
+ ...options,
158
+ membersFilter: this.membersFilter
159
+ });
160
+ const removedMemberEvents = await queryFilter(this.contract, {
161
+ fromBlock: this.deployBlock,
162
+ ...options,
163
+ membersFilter: this.membershipErasedFilter
164
+ });
165
+ const expiredMemberEvents = await queryFilter(this.contract, {
166
+ fromBlock: this.deployBlock,
167
+ ...options,
168
+ membersFilter: this.membersExpiredFilter
169
+ });
170
+ const events = [
171
+ ...registeredMemberEvents,
172
+ ...removedMemberEvents,
173
+ ...expiredMemberEvents
174
+ ];
175
+ this.processEvents(rlnInstance, events);
176
+ }
177
+ processEvents(rlnInstance, events) {
30
178
  const toRemoveTable = new Map();
31
179
  const toInsertTable = new Map();
32
180
  events.forEach((evt) => {
@@ -67,8 +215,8 @@ class RLNContract extends RLNBaseContract {
67
215
  toInsertTable.set(evt.blockNumber, eventsPerBlock);
68
216
  }
69
217
  });
70
- this.removeMembers(this.instance, toRemoveTable);
71
- this.insertMembers(this.instance, toInsertTable);
218
+ this.removeMembers(rlnInstance, toRemoveTable);
219
+ this.insertMembers(rlnInstance, toInsertTable);
72
220
  }
73
221
  insertMembers(rlnInstance, toInsert) {
74
222
  toInsert.forEach((events, blockNumber) => {
@@ -107,6 +255,268 @@ class RLNContract extends RLNBaseContract {
107
255
  this.merkleRootTracker.backFill(blockNumber);
108
256
  });
109
257
  }
258
+ subscribeToMembers(rlnInstance) {
259
+ this.contract.on(this.membersFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
260
+ this.processEvents(rlnInstance, [event]);
261
+ });
262
+ this.contract.on(this.membershipErasedFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
263
+ this.processEvents(rlnInstance, [event]);
264
+ });
265
+ this.contract.on(this.membersExpiredFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
266
+ this.processEvents(rlnInstance, [event]);
267
+ });
268
+ }
269
+ async registerWithIdentity(identity) {
270
+ try {
271
+ log.info(`Registering identity with rate limit: ${this.rateLimit} messages/epoch`);
272
+ // Check if the ID commitment is already registered
273
+ const existingIndex = await this.getMemberIndex(identity.IDCommitmentBigInt.toString());
274
+ if (existingIndex) {
275
+ throw new Error(`ID commitment is already registered with index ${existingIndex}`);
276
+ }
277
+ // Check if there's enough remaining rate limit
278
+ const remainingRateLimit = await this.getRemainingTotalRateLimit();
279
+ if (remainingRateLimit < this.rateLimit) {
280
+ throw new Error(`Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`);
281
+ }
282
+ const estimatedGas = await this.contract.estimateGas.register(identity.IDCommitmentBigInt, this.rateLimit, []);
283
+ const gasLimit = estimatedGas.add(10000);
284
+ const txRegisterResponse = await this.contract.register(identity.IDCommitmentBigInt, this.rateLimit, [], { gasLimit });
285
+ const txRegisterReceipt = await txRegisterResponse.wait();
286
+ if (txRegisterReceipt.status === 0) {
287
+ throw new Error("Transaction failed on-chain");
288
+ }
289
+ const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
290
+ if (!memberRegistered || !memberRegistered.args) {
291
+ log.error("Failed to register membership: No MembershipRegistered event found");
292
+ return undefined;
293
+ }
294
+ const decodedData = {
295
+ idCommitment: memberRegistered.args.idCommitment,
296
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
297
+ index: memberRegistered.args.index
298
+ };
299
+ log.info(`Successfully registered membership with index ${decodedData.index} ` +
300
+ `and rate limit ${decodedData.membershipRateLimit}`);
301
+ const network = await this.contract.provider.getNetwork();
302
+ const address = this.contract.address;
303
+ const membershipId = Number(decodedData.index);
304
+ return {
305
+ identity,
306
+ membership: {
307
+ address,
308
+ treeIndex: membershipId,
309
+ chainId: network.chainId,
310
+ rateLimit: decodedData.membershipRateLimit.toNumber()
311
+ }
312
+ };
313
+ }
314
+ catch (error) {
315
+ if (error instanceof Error) {
316
+ const errorMessage = error.message;
317
+ log.error("registerWithIdentity - error message:", errorMessage);
318
+ log.error("registerWithIdentity - error stack:", error.stack);
319
+ // Try to extract more specific error information
320
+ if (errorMessage.includes("CannotExceedMaxTotalRateLimit")) {
321
+ throw new Error("Registration failed: Cannot exceed maximum total rate limit");
322
+ }
323
+ else if (errorMessage.includes("InvalidIdCommitment")) {
324
+ throw new Error("Registration failed: Invalid ID commitment");
325
+ }
326
+ else if (errorMessage.includes("InvalidMembershipRateLimit")) {
327
+ throw new Error("Registration failed: Invalid membership rate limit");
328
+ }
329
+ else if (errorMessage.includes("execution reverted")) {
330
+ throw new Error("Contract execution reverted. Check contract requirements.");
331
+ }
332
+ else {
333
+ throw new Error(`Error in registerWithIdentity: ${errorMessage}`);
334
+ }
335
+ }
336
+ else {
337
+ throw new Error("Unknown error in registerWithIdentity", {
338
+ cause: error
339
+ });
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Helper method to get remaining messages in current epoch
345
+ * @param membershipId The ID of the membership to check
346
+ * @returns number of remaining messages allowed in current epoch
347
+ */
348
+ async getRemainingMessages(membershipId) {
349
+ try {
350
+ const [startTime, , rateLimit] = await this.contract.getMembershipInfo(membershipId);
351
+ // Calculate current epoch
352
+ const currentTime = Math.floor(Date.now() / 1000);
353
+ const epochsPassed = Math.floor((currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH);
354
+ const currentEpochStart = startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
355
+ // Get message count in current epoch using contract's function
356
+ const messageCount = await this.contract.getMessageCount(membershipId, currentEpochStart);
357
+ return Math.max(0, rateLimit.sub(messageCount).toNumber());
358
+ }
359
+ catch (error) {
360
+ log.error(`Error getting remaining messages: ${error.message}`);
361
+ return 0; // Fail safe: assume no messages remaining on error
362
+ }
363
+ }
364
+ async registerWithPermitAndErase(identity, permit, idCommitmentsToErase) {
365
+ try {
366
+ log.info(`Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`);
367
+ 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)));
368
+ const txRegisterReceipt = await txRegisterResponse.wait();
369
+ const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
370
+ if (!memberRegistered || !memberRegistered.args) {
371
+ log.error("Failed to register membership with permit: No MembershipRegistered event found");
372
+ return undefined;
373
+ }
374
+ const decodedData = {
375
+ idCommitment: memberRegistered.args.idCommitment,
376
+ membershipRateLimit: memberRegistered.args.membershipRateLimit,
377
+ index: memberRegistered.args.index
378
+ };
379
+ log.info(`Successfully registered membership with permit. Index: ${decodedData.index}, ` +
380
+ `Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`);
381
+ const network = await this.contract.provider.getNetwork();
382
+ const address = this.contract.address;
383
+ const membershipId = BigNumber.from(decodedData.index).toNumber();
384
+ return {
385
+ identity,
386
+ membership: {
387
+ address,
388
+ treeIndex: membershipId,
389
+ chainId: network.chainId,
390
+ rateLimit: decodedData.membershipRateLimit.toNumber()
391
+ }
392
+ };
393
+ }
394
+ catch (error) {
395
+ log.error(`Error in registerWithPermitAndErase: ${error.message}`);
396
+ return undefined;
397
+ }
398
+ }
399
+ roots() {
400
+ return this.merkleRootTracker.roots();
401
+ }
402
+ async withdraw(token, holder) {
403
+ try {
404
+ const tx = await this.contract.withdraw(token, { from: holder });
405
+ await tx.wait();
406
+ }
407
+ catch (error) {
408
+ log.error(`Error in withdraw: ${error.message}`);
409
+ }
410
+ }
411
+ async getMembershipInfo(idCommitment) {
412
+ try {
413
+ const [startBlock, endBlock, rateLimit] = await this.contract.getMembershipInfo(idCommitment);
414
+ const currentBlock = await this.contract.provider.getBlockNumber();
415
+ let state;
416
+ if (currentBlock < startBlock) {
417
+ state = MembershipState.Active;
418
+ }
419
+ else if (currentBlock < endBlock) {
420
+ state = MembershipState.GracePeriod;
421
+ }
422
+ else {
423
+ state = MembershipState.Expired;
424
+ }
425
+ const index = await this.getMemberIndex(idCommitment);
426
+ if (!index)
427
+ return undefined;
428
+ return {
429
+ index,
430
+ idCommitment,
431
+ rateLimit: rateLimit.toNumber(),
432
+ startBlock: startBlock.toNumber(),
433
+ endBlock: endBlock.toNumber(),
434
+ state
435
+ };
436
+ }
437
+ catch (error) {
438
+ return undefined;
439
+ }
440
+ }
441
+ async extendMembership(idCommitment) {
442
+ return this.contract.extendMemberships([idCommitment]);
443
+ }
444
+ async eraseMembership(idCommitment, eraseFromMembershipSet = true) {
445
+ return this.contract.eraseMemberships([idCommitment], eraseFromMembershipSet);
446
+ }
447
+ async registerMembership(idCommitment, rateLimit = this.rateLimit) {
448
+ this.validateRateLimit(rateLimit);
449
+ return this.contract.register(idCommitment, rateLimit, []);
450
+ }
451
+ async getMemberIndex(idCommitment) {
452
+ try {
453
+ const events = await this.contract.queryFilter(this.contract.filters.MembershipRegistered(idCommitment));
454
+ if (events.length === 0)
455
+ return undefined;
456
+ // Get the most recent registration event
457
+ const event = events[events.length - 1];
458
+ return event.args?.index;
459
+ }
460
+ catch (error) {
461
+ return undefined;
462
+ }
463
+ }
464
+ }
465
+ // These values should be tested on other networks
466
+ const FETCH_CHUNK = 5;
467
+ const BLOCK_RANGE = 3000;
468
+ async function queryFilter(contract, options) {
469
+ const { fromBlock, membersFilter, fetchRange = BLOCK_RANGE, fetchChunks = FETCH_CHUNK } = options;
470
+ if (fromBlock === undefined) {
471
+ return contract.queryFilter(membersFilter);
472
+ }
473
+ if (!contract.provider) {
474
+ throw Error("No provider found on the contract.");
475
+ }
476
+ const toBlock = await contract.provider.getBlockNumber();
477
+ if (toBlock - fromBlock < fetchRange) {
478
+ return contract.queryFilter(membersFilter, fromBlock, toBlock);
479
+ }
480
+ const events = [];
481
+ const chunks = splitToChunks(fromBlock, toBlock, fetchRange);
482
+ for (const portion of takeN(chunks, fetchChunks)) {
483
+ const promises = portion.map(([left, right]) => ignoreErrors(contract.queryFilter(membersFilter, left, right), []));
484
+ const fetchedEvents = await Promise.all(promises);
485
+ events.push(fetchedEvents.flatMap((v) => v));
486
+ }
487
+ return events.flatMap((v) => v);
488
+ }
489
+ function splitToChunks(from, to, step) {
490
+ const chunks = [];
491
+ let left = from;
492
+ while (left < to) {
493
+ const right = left + step < to ? left + step : to;
494
+ chunks.push([left, right]);
495
+ left = right;
496
+ }
497
+ return chunks;
498
+ }
499
+ function* takeN(array, size) {
500
+ let start = 0;
501
+ while (start < array.length) {
502
+ const portion = array.slice(start, start + size);
503
+ yield portion;
504
+ start += size;
505
+ }
506
+ }
507
+ async function ignoreErrors(promise, defaultValue) {
508
+ try {
509
+ return await promise;
510
+ }
511
+ catch (err) {
512
+ if (err instanceof Error) {
513
+ log.info(`Ignoring an error during query: ${err.message}`);
514
+ }
515
+ else {
516
+ log.info(`Ignoring an unknown error during query`);
517
+ }
518
+ return defaultValue;
519
+ }
110
520
  }
111
521
 
112
- export { RLNContract };
522
+ export { MembershipState, RLNContract };
@@ -3,7 +3,7 @@ async function createRLN() {
3
3
  // asynchronously. This file does the single async import, so
4
4
  // that no one else needs to worry about it again.
5
5
  const rlnModule = await import('./rln.js');
6
- return rlnModule.RLNInstance.create();
6
+ return rlnModule.create();
7
7
  }
8
8
 
9
9
  export { createRLN };
@@ -25,14 +25,6 @@ class IdentityCredential {
25
25
  const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment, 32);
26
26
  return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
27
27
  }
28
- toJSON() {
29
- return {
30
- idTrapdoor: Array.from(this.IDTrapdoor),
31
- idNullifier: Array.from(this.IDNullifier),
32
- idSecretHash: Array.from(this.IDSecretHash),
33
- idCommitment: Array.from(this.IDCommitment)
34
- };
35
- }
36
28
  }
37
29
 
38
30
  export { IdentityCredential };
@@ -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 { IdentityCredential } from '../identity.js';
21
20
  import { buildBigIntFromUint8Array } from '../utils/bytes.js';
22
21
  import { keccak256Checksum, decryptEipKeystore } from './cipher.js';
23
22
  import { isKeystoreValid, isCredentialValid } from './schema_validator.js';
@@ -165,20 +164,20 @@ class Keystore {
165
164
  try {
166
165
  const str = bytesToUtf8(bytes);
167
166
  const obj = JSON.parse(str);
168
- // Get identity fields from named object
169
- const { idTrapdoor, idNullifier, idSecretHash, idCommitment } = _.get(obj, "identityCredential", {});
170
- const idTrapdoorArray = new Uint8Array(idTrapdoor || []);
171
- const idNullifierArray = new Uint8Array(idNullifier || []);
172
- const idSecretHashArray = new Uint8Array(idSecretHash || []);
173
- const idCommitmentArray = new Uint8Array(idCommitment || []);
174
- const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitmentArray);
167
+ // TODO: add runtime validation of nwaku credentials
175
168
  return {
176
- identity: new IdentityCredential(idTrapdoorArray, idNullifierArray, idSecretHashArray, idCommitmentArray, idCommitmentBigInt),
169
+ 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: buildBigIntFromUint8Array(Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idCommitment", []))),
174
+ IDSecretHash: Keystore.fromArraylikeToBytes(_.get(obj, "identityCredential.idSecretHash", []))
175
+ },
177
176
  membership: {
178
177
  treeIndex: _.get(obj, "treeIndex"),
179
178
  chainId: _.get(obj, "membershipContract.chainId"),
180
179
  address: _.get(obj, "membershipContract.address"),
181
- rateLimit: _.get(obj, "userMessageLimit")
180
+ rateLimit: _.get(obj, "membershipContract.rateLimit")
182
181
  }
183
182
  };
184
183
  }
@@ -187,6 +186,17 @@ class Keystore {
187
186
  return;
188
187
  }
189
188
  }
189
+ static fromArraylikeToBytes(obj) {
190
+ const bytes = [];
191
+ let index = 0;
192
+ let lastElement = obj[index];
193
+ while (lastElement !== undefined) {
194
+ bytes.push(lastElement);
195
+ index += 1;
196
+ lastElement = obj[index];
197
+ }
198
+ return new Uint8Array(bytes);
199
+ }
190
200
  // follows nwaku implementation
191
201
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
192
202
  static computeMembershipHash(info) {
@@ -196,18 +206,17 @@ class Keystore {
196
206
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L98
197
207
  static fromIdentityToBytes(options) {
198
208
  return utf8ToBytes(JSON.stringify({
199
- membershipContract: {
200
- chainId: options.membership.chainId,
201
- address: options.membership.address
202
- },
203
209
  treeIndex: options.membership.treeIndex,
204
210
  identityCredential: {
205
- idTrapdoor: Array.from(options.identity.IDTrapdoor),
206
- idNullifier: Array.from(options.identity.IDNullifier),
207
- idSecretHash: Array.from(options.identity.IDSecretHash),
208
- idCommitment: Array.from(options.identity.IDCommitment)
211
+ idCommitment: options.identity.IDCommitment,
212
+ idNullifier: options.identity.IDNullifier,
213
+ idSecretHash: options.identity.IDSecretHash,
214
+ idTrapdoor: options.identity.IDTrapdoor
209
215
  },
210
- userMessageLimit: options.membership.rateLimit
216
+ membershipContract: {
217
+ chainId: options.membership.chainId,
218
+ address: options.membership.address
219
+ }
211
220
  }));
212
221
  }
213
222
  }