@waku/rln 0.1.5-76f86de.0 → 0.1.5-9901863.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 (65) hide show
  1. package/bundle/index.js +2 -0
  2. package/bundle/packages/rln/dist/contract/constants.js +1 -1
  3. package/bundle/packages/rln/dist/contract/rln_base_contract.js +477 -0
  4. package/bundle/packages/rln/dist/contract/rln_contract.js +9 -419
  5. package/bundle/packages/rln/dist/contract/types.js +9 -0
  6. package/bundle/packages/rln/dist/create.js +1 -1
  7. package/bundle/packages/rln/dist/credentials_manager.js +233 -0
  8. package/bundle/packages/rln/dist/identity.js +8 -0
  9. package/bundle/packages/rln/dist/keystore/keystore.js +19 -28
  10. package/bundle/packages/rln/dist/rln.js +56 -166
  11. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
  12. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
  13. package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
  14. package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
  15. package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
  16. package/dist/.tsbuildinfo +1 -1
  17. package/dist/contract/constants.d.ts +1 -1
  18. package/dist/contract/constants.js +1 -1
  19. package/dist/contract/constants.js.map +1 -1
  20. package/dist/contract/rln_base_contract.d.ts +96 -0
  21. package/dist/contract/rln_base_contract.js +460 -0
  22. package/dist/contract/rln_base_contract.js.map +1 -0
  23. package/dist/contract/rln_contract.d.ts +5 -122
  24. package/dist/contract/rln_contract.js +8 -417
  25. package/dist/contract/rln_contract.js.map +1 -1
  26. package/dist/contract/test-utils.js +1 -1
  27. package/dist/contract/test-utils.js.map +1 -1
  28. package/dist/contract/types.d.ts +40 -0
  29. package/dist/contract/types.js +8 -0
  30. package/dist/contract/types.js.map +1 -0
  31. package/dist/create.js +1 -1
  32. package/dist/create.js.map +1 -1
  33. package/dist/credentials_manager.d.ts +50 -0
  34. package/dist/credentials_manager.js +215 -0
  35. package/dist/credentials_manager.js.map +1 -0
  36. package/dist/identity.d.ts +1 -0
  37. package/dist/identity.js +8 -0
  38. package/dist/identity.js.map +1 -1
  39. package/dist/index.d.ts +3 -1
  40. package/dist/index.js +3 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/keystore/keystore.d.ts +0 -1
  43. package/dist/keystore/keystore.js +19 -28
  44. package/dist/keystore/keystore.js.map +1 -1
  45. package/dist/keystore/types.d.ts +1 -1
  46. package/dist/rln.d.ts +9 -52
  47. package/dist/rln.js +54 -163
  48. package/dist/rln.js.map +1 -1
  49. package/dist/types.d.ts +27 -0
  50. package/dist/types.js +2 -0
  51. package/dist/types.js.map +1 -0
  52. package/package.json +1 -1
  53. package/src/contract/constants.ts +1 -1
  54. package/src/contract/rln_base_contract.ts +707 -0
  55. package/src/contract/rln_contract.ts +9 -663
  56. package/src/contract/test-utils.ts +1 -1
  57. package/src/contract/types.ts +48 -0
  58. package/src/create.ts +1 -1
  59. package/src/credentials_manager.ts +306 -0
  60. package/src/identity.ts +9 -0
  61. package/src/index.ts +4 -0
  62. package/src/keystore/keystore.ts +31 -46
  63. package/src/keystore/types.ts +1 -1
  64. package/src/rln.ts +67 -259
  65. package/src/types.ts +31 -0
@@ -130,7 +130,7 @@ export function createRegisterStub(
130
130
  event: "MembershipRegistered",
131
131
  args: {
132
132
  idCommitment: formatIdCommitment(identity.IDCommitmentBigInt),
133
- rateLimit: DEFAULT_RATE_LIMIT,
133
+ membershipRateLimit: ethers.BigNumber.from(DEFAULT_RATE_LIMIT),
134
134
  index: ethers.BigNumber.from(1)
135
135
  }
136
136
  }
@@ -0,0 +1,48 @@
1
+ import { ethers } from "ethers";
2
+
3
+ export interface CustomQueryOptions extends FetchMembersOptions {
4
+ membersFilter: ethers.EventFilter;
5
+ }
6
+
7
+ export type Member = {
8
+ idCommitment: string;
9
+ index: ethers.BigNumber;
10
+ };
11
+
12
+ export interface RLNContractOptions {
13
+ signer: ethers.Signer;
14
+ address: string;
15
+ rateLimit?: number;
16
+ }
17
+
18
+ export interface RLNContractInitOptions extends RLNContractOptions {
19
+ contract?: ethers.Contract;
20
+ }
21
+
22
+ export interface MembershipRegisteredEvent {
23
+ idCommitment: string;
24
+ membershipRateLimit: ethers.BigNumber;
25
+ index: ethers.BigNumber;
26
+ }
27
+
28
+ export type FetchMembersOptions = {
29
+ fromBlock?: number;
30
+ fetchRange?: number;
31
+ fetchChunks?: number;
32
+ };
33
+
34
+ export interface MembershipInfo {
35
+ index: ethers.BigNumber;
36
+ idCommitment: string;
37
+ rateLimit: number;
38
+ startBlock: number;
39
+ endBlock: number;
40
+ state: MembershipState;
41
+ }
42
+
43
+ export enum MembershipState {
44
+ Active = "Active",
45
+ GracePeriod = "GracePeriod",
46
+ Expired = "Expired",
47
+ ErasedAwaitsWithdrawal = "ErasedAwaitsWithdrawal"
48
+ }
package/src/create.ts CHANGED
@@ -5,5 +5,5 @@ export async function createRLN(): Promise<RLNInstance> {
5
5
  // asynchronously. This file does the single async import, so
6
6
  // that no one else needs to worry about it again.
7
7
  const rlnModule = await import("./rln.js");
8
- return rlnModule.create();
8
+ return rlnModule.RLNInstance.create();
9
9
  }
@@ -0,0 +1,306 @@
1
+ import { hmac } from "@noble/hashes/hmac";
2
+ import { sha256 } from "@noble/hashes/sha256";
3
+ import { Logger } from "@waku/utils";
4
+ import { ethers } from "ethers";
5
+
6
+ import { LINEA_CONTRACT } from "./contract/constants.js";
7
+ import { RLNBaseContract } from "./contract/rln_base_contract.js";
8
+ import { IdentityCredential } from "./identity.js";
9
+ import { Keystore } from "./keystore/index.js";
10
+ import type {
11
+ DecryptedCredentials,
12
+ EncryptedCredentials
13
+ } from "./keystore/index.js";
14
+ import { KeystoreEntity, Password } from "./keystore/types.js";
15
+ import { RegisterMembershipOptions, StartRLNOptions } from "./types.js";
16
+ import {
17
+ buildBigIntFromUint8Array,
18
+ extractMetaMaskSigner
19
+ } from "./utils/index.js";
20
+ import { Zerokit } from "./zerokit.js";
21
+
22
+ const log = new Logger("waku:credentials");
23
+
24
+ /**
25
+ * Manages credentials for RLN
26
+ * This is a lightweight implementation of the RLN contract that doesn't require Zerokit
27
+ * It is used to register membership and generate identity credentials
28
+ */
29
+ export class RLNCredentialsManager {
30
+ protected started = false;
31
+ protected starting = false;
32
+
33
+ private _contract: undefined | RLNBaseContract;
34
+ private _signer: undefined | ethers.Signer;
35
+
36
+ protected keystore = Keystore.create();
37
+ private _credentials: undefined | DecryptedCredentials;
38
+
39
+ public zerokit: undefined | Zerokit;
40
+
41
+ public constructor(zerokit?: Zerokit) {
42
+ log.info("RLNCredentialsManager initialized");
43
+ this.zerokit = zerokit;
44
+ }
45
+
46
+ public get contract(): undefined | RLNBaseContract {
47
+ return this._contract;
48
+ }
49
+
50
+ public set contract(contract: RLNBaseContract | undefined) {
51
+ this._contract = contract;
52
+ }
53
+
54
+ public get signer(): undefined | ethers.Signer {
55
+ return this._signer;
56
+ }
57
+
58
+ public set signer(signer: ethers.Signer | undefined) {
59
+ this._signer = signer;
60
+ }
61
+
62
+ public get credentials(): undefined | DecryptedCredentials {
63
+ return this._credentials;
64
+ }
65
+
66
+ public set credentials(credentials: DecryptedCredentials | undefined) {
67
+ this._credentials = credentials;
68
+ }
69
+
70
+ public get provider(): undefined | ethers.providers.Provider {
71
+ return this.contract?.provider;
72
+ }
73
+
74
+ public async start(options: StartRLNOptions = {}): Promise<void> {
75
+ if (this.started || this.starting) {
76
+ log.info("RLNCredentialsManager already started or starting");
77
+ return;
78
+ }
79
+
80
+ log.info("Starting RLNCredentialsManager");
81
+ this.starting = true;
82
+
83
+ try {
84
+ const { credentials, keystore } =
85
+ await RLNCredentialsManager.decryptCredentialsIfNeeded(
86
+ options.credentials
87
+ );
88
+
89
+ if (credentials) {
90
+ log.info("Credentials successfully decrypted");
91
+ }
92
+
93
+ const { signer, address, rateLimit } = await this.determineStartOptions(
94
+ options,
95
+ credentials
96
+ );
97
+
98
+ log.info(`Using contract address: ${address}`);
99
+
100
+ if (keystore) {
101
+ this.keystore = keystore;
102
+ log.info("Using provided keystore");
103
+ }
104
+
105
+ this._credentials = credentials;
106
+ this._signer = signer!;
107
+ this._contract = new RLNBaseContract({
108
+ address: address!,
109
+ signer: signer!,
110
+ rateLimit: rateLimit ?? this.zerokit?.getRateLimit
111
+ });
112
+
113
+ log.info("RLNCredentialsManager successfully started");
114
+ this.started = true;
115
+ } catch (error) {
116
+ log.error("Failed to start RLNCredentialsManager", error);
117
+ throw error;
118
+ } finally {
119
+ this.starting = false;
120
+ }
121
+ }
122
+
123
+ public async registerMembership(
124
+ options: RegisterMembershipOptions
125
+ ): Promise<undefined | DecryptedCredentials> {
126
+ if (!this.contract) {
127
+ log.error("RLN Contract is not initialized");
128
+ throw Error("RLN Contract is not initialized.");
129
+ }
130
+
131
+ log.info("Registering membership");
132
+ let identity = "identity" in options && options.identity;
133
+
134
+ if ("signature" in options) {
135
+ log.info("Generating identity from signature");
136
+ if (this.zerokit) {
137
+ log.info("Using Zerokit to generate identity");
138
+ identity = this.zerokit.generateSeededIdentityCredential(
139
+ options.signature
140
+ );
141
+ } else {
142
+ log.info("Using local implementation to generate identity");
143
+ identity = this.generateSeededIdentityCredential(options.signature);
144
+ }
145
+ }
146
+
147
+ if (!identity) {
148
+ log.error("Missing signature or identity to register membership");
149
+ throw Error("Missing signature or identity to register membership.");
150
+ }
151
+
152
+ log.info("Registering identity with contract");
153
+ return this.contract.registerWithIdentity(identity);
154
+ }
155
+
156
+ /**
157
+ * Changes credentials in use by relying on provided Keystore earlier in rln.start
158
+ * @param id: string, hash of credentials to select from Keystore
159
+ * @param password: string or bytes to use to decrypt credentials from Keystore
160
+ */
161
+ public async useCredentials(id: string, password: Password): Promise<void> {
162
+ log.info(`Attempting to use credentials with ID: ${id}`);
163
+ this._credentials = await this.keystore?.readCredential(id, password);
164
+ if (this._credentials) {
165
+ log.info("Successfully loaded credentials");
166
+ } else {
167
+ log.warn("Failed to load credentials");
168
+ }
169
+ }
170
+
171
+ protected async determineStartOptions(
172
+ options: StartRLNOptions,
173
+ credentials: KeystoreEntity | undefined
174
+ ): Promise<StartRLNOptions> {
175
+ let chainId = credentials?.membership.chainId;
176
+ const address =
177
+ credentials?.membership.address ||
178
+ options.address ||
179
+ LINEA_CONTRACT.address;
180
+
181
+ if (address === LINEA_CONTRACT.address) {
182
+ chainId = LINEA_CONTRACT.chainId;
183
+ log.info(`Using Linea contract with chainId: ${chainId}`);
184
+ }
185
+
186
+ const signer = options.signer || (await extractMetaMaskSigner());
187
+ const currentChainId = await signer.getChainId();
188
+ log.info(`Current chain ID: ${currentChainId}`);
189
+
190
+ if (chainId && chainId !== currentChainId.toString()) {
191
+ log.error(
192
+ `Chain ID mismatch: contract=${chainId}, current=${currentChainId}`
193
+ );
194
+ throw Error(
195
+ `Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`
196
+ );
197
+ }
198
+
199
+ return {
200
+ signer,
201
+ address
202
+ };
203
+ }
204
+
205
+ protected static async decryptCredentialsIfNeeded(
206
+ credentials?: EncryptedCredentials | DecryptedCredentials
207
+ ): Promise<{ credentials?: DecryptedCredentials; keystore?: Keystore }> {
208
+ if (!credentials) {
209
+ log.info("No credentials provided");
210
+ return {};
211
+ }
212
+
213
+ if ("identity" in credentials) {
214
+ log.info("Using already decrypted credentials");
215
+ return { credentials };
216
+ }
217
+
218
+ log.info("Attempting to decrypt credentials");
219
+ const keystore = Keystore.fromString(credentials.keystore);
220
+
221
+ if (!keystore) {
222
+ log.warn("Failed to create keystore from string");
223
+ return {};
224
+ }
225
+
226
+ try {
227
+ const decryptedCredentials = await keystore.readCredential(
228
+ credentials.id,
229
+ credentials.password
230
+ );
231
+ log.info(`Successfully decrypted credentials with ID: ${credentials.id}`);
232
+
233
+ return {
234
+ keystore,
235
+ credentials: decryptedCredentials
236
+ };
237
+ } catch (error) {
238
+ log.error("Failed to decrypt credentials", error);
239
+ throw error;
240
+ }
241
+ }
242
+
243
+ protected async verifyCredentialsAgainstContract(
244
+ credentials: KeystoreEntity
245
+ ): Promise<void> {
246
+ if (!this.contract) {
247
+ throw Error(
248
+ "Failed to verify chain coordinates: no contract initialized."
249
+ );
250
+ }
251
+
252
+ const registryAddress = credentials.membership.address;
253
+ const currentRegistryAddress = this.contract.address;
254
+ if (registryAddress !== currentRegistryAddress) {
255
+ throw Error(
256
+ `Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`
257
+ );
258
+ }
259
+
260
+ const chainId = credentials.membership.chainId;
261
+ const network = await this.contract.provider.getNetwork();
262
+ const currentChainId = network.chainId;
263
+ if (chainId !== currentChainId.toString()) {
264
+ throw Error(
265
+ `Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`
266
+ );
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Generates an identity credential from a seed string
272
+ * This is a pure implementation that doesn't rely on Zerokit
273
+ * @param seed A string seed to generate the identity from
274
+ * @returns IdentityCredential
275
+ */
276
+ private generateSeededIdentityCredential(seed: string): IdentityCredential {
277
+ log.info("Generating seeded identity credential");
278
+ // Convert the seed to bytes
279
+ const encoder = new TextEncoder();
280
+ const seedBytes = encoder.encode(seed);
281
+
282
+ // Generate deterministic values using HMAC-SHA256
283
+ // We use different context strings for each component to ensure they're different
284
+ const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
285
+ const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
286
+
287
+ // Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
288
+ const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
289
+ const idSecretHash = sha256(combinedBytes);
290
+
291
+ // Generate IDCommitment as a hash of IDSecretHash
292
+ const idCommitment = sha256(idSecretHash);
293
+
294
+ // Convert IDCommitment to BigInt
295
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
296
+
297
+ log.info("Successfully generated identity credential");
298
+ return new IdentityCredential(
299
+ idTrapdoor,
300
+ idNullifier,
301
+ idSecretHash,
302
+ idCommitment,
303
+ idCommitmentBigInt
304
+ );
305
+ }
306
+ }
package/src/identity.ts CHANGED
@@ -28,4 +28,13 @@ export class IdentityCredential {
28
28
  idCommitmentBigInt
29
29
  );
30
30
  }
31
+
32
+ public toJSON(): Record<string, number[]> {
33
+ return {
34
+ idTrapdoor: Array.from(this.IDTrapdoor),
35
+ idNullifier: Array.from(this.IDNullifier),
36
+ idSecretHash: Array.from(this.IDSecretHash),
37
+ idCommitment: Array.from(this.IDCommitment)
38
+ };
39
+ }
31
40
  }
package/src/index.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { RLNDecoder, RLNEncoder } from "./codec.js";
2
2
  import { RLN_ABI } from "./contract/abi.js";
3
3
  import { LINEA_CONTRACT, RLNContract } from "./contract/index.js";
4
+ import { RLNBaseContract } from "./contract/rln_base_contract.js";
4
5
  import { createRLN } from "./create.js";
6
+ import { RLNCredentialsManager } from "./credentials_manager.js";
5
7
  import { IdentityCredential } from "./identity.js";
6
8
  import { Keystore } from "./keystore/index.js";
7
9
  import { Proof } from "./proof.js";
@@ -10,6 +12,8 @@ import { MerkleRootTracker } from "./root_tracker.js";
10
12
  import { extractMetaMaskSigner } from "./utils/index.js";
11
13
 
12
14
  export {
15
+ RLNCredentialsManager,
16
+ RLNBaseContract,
13
17
  createRLN,
14
18
  Keystore,
15
19
  RLNInstance,
@@ -14,6 +14,7 @@ import {
14
14
  import _ from "lodash";
15
15
  import { v4 as uuidV4 } from "uuid";
16
16
 
17
+ import { IdentityCredential } from "../identity.js";
17
18
  import { buildBigIntFromUint8Array } from "../utils/bytes.js";
18
19
 
19
20
  import { decryptEipKeystore, keccak256Checksum } from "./cipher.js";
@@ -250,32 +251,32 @@ export class Keystore {
250
251
  const str = bytesToUtf8(bytes);
251
252
  const obj = JSON.parse(str);
252
253
 
253
- // TODO: add runtime validation of nwaku credentials
254
+ // Get identity fields from named object
255
+ const { idTrapdoor, idNullifier, idSecretHash, idCommitment } = _.get(
256
+ obj,
257
+ "identityCredential",
258
+ {}
259
+ );
260
+
261
+ const idTrapdoorArray = new Uint8Array(idTrapdoor || []);
262
+ const idNullifierArray = new Uint8Array(idNullifier || []);
263
+ const idSecretHashArray = new Uint8Array(idSecretHash || []);
264
+ const idCommitmentArray = new Uint8Array(idCommitment || []);
265
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitmentArray);
266
+
254
267
  return {
255
- identity: {
256
- IDCommitment: Keystore.fromArraylikeToBytes(
257
- _.get(obj, "identityCredential.idCommitment", [])
258
- ),
259
- IDTrapdoor: Keystore.fromArraylikeToBytes(
260
- _.get(obj, "identityCredential.idTrapdoor", [])
261
- ),
262
- IDNullifier: Keystore.fromArraylikeToBytes(
263
- _.get(obj, "identityCredential.idNullifier", [])
264
- ),
265
- IDCommitmentBigInt: buildBigIntFromUint8Array(
266
- Keystore.fromArraylikeToBytes(
267
- _.get(obj, "identityCredential.idCommitment", [])
268
- )
269
- ),
270
- IDSecretHash: Keystore.fromArraylikeToBytes(
271
- _.get(obj, "identityCredential.idSecretHash", [])
272
- )
273
- },
268
+ identity: new IdentityCredential(
269
+ idTrapdoorArray,
270
+ idNullifierArray,
271
+ idSecretHashArray,
272
+ idCommitmentArray,
273
+ idCommitmentBigInt
274
+ ),
274
275
  membership: {
275
276
  treeIndex: _.get(obj, "treeIndex"),
276
277
  chainId: _.get(obj, "membershipContract.chainId"),
277
278
  address: _.get(obj, "membershipContract.address"),
278
- rateLimit: _.get(obj, "membershipContract.rateLimit")
279
+ rateLimit: _.get(obj, "userMessageLimit")
279
280
  }
280
281
  };
281
282
  } catch (err) {
@@ -284,23 +285,6 @@ export class Keystore {
284
285
  }
285
286
  }
286
287
 
287
- private static fromArraylikeToBytes(obj: {
288
- [key: number]: number;
289
- }): Uint8Array {
290
- const bytes = [];
291
-
292
- let index = 0;
293
- let lastElement = obj[index];
294
-
295
- while (lastElement !== undefined) {
296
- bytes.push(lastElement);
297
- index += 1;
298
- lastElement = obj[index];
299
- }
300
-
301
- return new Uint8Array(bytes);
302
- }
303
-
304
288
  // follows nwaku implementation
305
289
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
306
290
  private static computeMembershipHash(info: MembershipInfo): MembershipHash {
@@ -314,17 +298,18 @@ export class Keystore {
314
298
  private static fromIdentityToBytes(options: KeystoreEntity): Uint8Array {
315
299
  return utf8ToBytes(
316
300
  JSON.stringify({
317
- treeIndex: options.membership.treeIndex,
318
- identityCredential: {
319
- idCommitment: options.identity.IDCommitment,
320
- idNullifier: options.identity.IDNullifier,
321
- idSecretHash: options.identity.IDSecretHash,
322
- idTrapdoor: options.identity.IDTrapdoor
323
- },
324
301
  membershipContract: {
325
302
  chainId: options.membership.chainId,
326
303
  address: options.membership.address
327
- }
304
+ },
305
+ treeIndex: options.membership.treeIndex,
306
+ identityCredential: {
307
+ idTrapdoor: Array.from(options.identity.IDTrapdoor),
308
+ idNullifier: Array.from(options.identity.IDNullifier),
309
+ idSecretHash: Array.from(options.identity.IDSecretHash),
310
+ idCommitment: Array.from(options.identity.IDCommitment)
311
+ },
312
+ userMessageLimit: options.membership.rateLimit
328
313
  })
329
314
  );
330
315
  }
@@ -8,7 +8,7 @@ export type Password = string | Uint8Array;
8
8
  // see reference
9
9
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
10
10
  export type MembershipInfo = {
11
- chainId: number;
11
+ chainId: string;
12
12
  address: string;
13
13
  treeIndex: number;
14
14
  rateLimit: number;