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