@waku/rln 0.1.5-f39d215.0 → 0.1.5-f6b9809.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 (76) hide show
  1. package/bundle/_virtual/utils.js +2 -2
  2. package/bundle/_virtual/utils2.js +2 -2
  3. package/bundle/index.js +2 -2
  4. package/bundle/packages/rln/dist/contract/constants.js +2 -5
  5. package/bundle/packages/rln/dist/contract/{rln_light_contract.js → rln_base_contract.js} +165 -177
  6. package/bundle/packages/rln/dist/contract/rln_contract.js +9 -419
  7. package/bundle/packages/rln/dist/contract/types.js +9 -0
  8. package/bundle/packages/rln/dist/create.js +1 -1
  9. package/bundle/packages/rln/dist/{rln_light.js → credentials_manager.js} +114 -48
  10. package/bundle/packages/rln/dist/identity.js +0 -9
  11. package/bundle/packages/rln/dist/keystore/keystore.js +27 -13
  12. package/bundle/packages/rln/dist/rln.js +56 -166
  13. package/bundle/packages/rln/dist/zerokit.js +5 -5
  14. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/random.js +1 -1
  15. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/utils.js +2 -2
  16. package/bundle/packages/rln/node_modules/@noble/hashes/_sha2.js +1 -1
  17. package/bundle/packages/rln/node_modules/@noble/hashes/hmac.js +1 -1
  18. package/bundle/packages/rln/node_modules/@noble/hashes/pbkdf2.js +1 -1
  19. package/bundle/packages/rln/node_modules/@noble/hashes/scrypt.js +1 -1
  20. package/bundle/packages/rln/node_modules/@noble/hashes/sha256.js +1 -1
  21. package/bundle/packages/rln/node_modules/@noble/hashes/sha512.js +1 -1
  22. package/bundle/packages/rln/node_modules/@noble/hashes/utils.js +1 -1
  23. package/dist/.tsbuildinfo +1 -1
  24. package/dist/contract/constants.d.ts +1 -1
  25. package/dist/contract/constants.js +1 -1
  26. package/dist/contract/constants.js.map +1 -1
  27. package/dist/contract/{rln_light_contract.d.ts → rln_base_contract.d.ts} +24 -58
  28. package/dist/contract/{rln_light_contract.js → rln_base_contract.js} +165 -177
  29. package/dist/contract/rln_base_contract.js.map +1 -0
  30. package/dist/contract/rln_contract.d.ts +5 -122
  31. package/dist/contract/rln_contract.js +8 -417
  32. package/dist/contract/rln_contract.js.map +1 -1
  33. package/dist/contract/types.d.ts +45 -0
  34. package/dist/contract/types.js +8 -0
  35. package/dist/contract/types.js.map +1 -0
  36. package/dist/create.js +1 -1
  37. package/dist/create.js.map +1 -1
  38. package/dist/credentials_manager.d.ts +44 -0
  39. package/dist/credentials_manager.js +197 -0
  40. package/dist/credentials_manager.js.map +1 -0
  41. package/dist/identity.d.ts +0 -1
  42. package/dist/identity.js +0 -9
  43. package/dist/identity.js.map +1 -1
  44. package/dist/index.d.ts +3 -3
  45. package/dist/index.js +3 -3
  46. package/dist/index.js.map +1 -1
  47. package/dist/keystore/keystore.d.ts +1 -0
  48. package/dist/keystore/keystore.js +27 -13
  49. package/dist/keystore/keystore.js.map +1 -1
  50. package/dist/rln.d.ts +9 -52
  51. package/dist/rln.js +54 -163
  52. package/dist/rln.js.map +1 -1
  53. package/dist/types.d.ts +27 -0
  54. package/dist/types.js +2 -0
  55. package/dist/types.js.map +1 -0
  56. package/dist/zerokit.d.ts +3 -3
  57. package/dist/zerokit.js +5 -5
  58. package/dist/zerokit.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/contract/constants.ts +1 -1
  61. package/src/contract/{rln_light_contract.ts → rln_base_contract.ts} +271 -313
  62. package/src/contract/rln_contract.ts +9 -663
  63. package/src/contract/types.ts +53 -0
  64. package/src/create.ts +1 -1
  65. package/src/credentials_manager.ts +282 -0
  66. package/src/identity.ts +0 -10
  67. package/src/index.ts +4 -4
  68. package/src/keystore/keystore.ts +49 -25
  69. package/src/rln.ts +67 -258
  70. package/src/types.ts +31 -0
  71. package/src/zerokit.ts +3 -3
  72. package/dist/contract/rln_light_contract.js.map +0 -1
  73. package/dist/rln_light.d.ts +0 -64
  74. package/dist/rln_light.js +0 -144
  75. package/dist/rln_light.js.map +0 -1
  76. package/src/rln_light.ts +0 -235
@@ -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/identity.ts CHANGED
@@ -28,14 +28,4 @@ export class IdentityCredential {
28
28
  idCommitmentBigInt
29
29
  );
30
30
  }
31
-
32
- public toJSON(): Record<string, number[] | string> {
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
- idCommitmentBigInt: this.IDCommitmentBigInt.toString()
39
- };
40
- }
41
31
  }
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,
@@ -14,7 +14,6 @@ import {
14
14
  import _ from "lodash";
15
15
  import { v4 as uuidV4 } from "uuid";
16
16
 
17
- import { IdentityCredential } from "../identity.js";
18
17
  import { buildBigIntFromUint8Array } from "../utils/bytes.js";
19
18
 
20
19
  import { decryptEipKeystore, keccak256Checksum } from "./cipher.js";
@@ -251,32 +250,32 @@ export class Keystore {
251
250
  const str = bytesToUtf8(bytes);
252
251
  const obj = JSON.parse(str);
253
252
 
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
-
253
+ // TODO: add runtime validation of nwaku credentials
267
254
  return {
268
- identity: new IdentityCredential(
269
- idTrapdoorArray,
270
- idNullifierArray,
271
- idSecretHashArray,
272
- idCommitmentArray,
273
- idCommitmentBigInt
274
- ),
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
+ },
275
274
  membership: {
276
275
  treeIndex: _.get(obj, "treeIndex"),
277
276
  chainId: _.get(obj, "membershipContract.chainId"),
278
277
  address: _.get(obj, "membershipContract.address"),
279
- rateLimit: _.get(obj, "membershipContract.rateLimit")
278
+ rateLimit: _.get(obj, "userMessageLimit")
280
279
  }
281
280
  };
282
281
  } catch (err) {
@@ -285,6 +284,30 @@ export class Keystore {
285
284
  }
286
285
  }
287
286
 
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
+ }
297
+
298
+ const bytes = [];
299
+ let index = 0;
300
+ let lastElement = obj[index];
301
+
302
+ while (lastElement !== undefined) {
303
+ bytes.push(lastElement);
304
+ index += 1;
305
+ lastElement = obj[index];
306
+ }
307
+
308
+ return new Uint8Array(bytes);
309
+ }
310
+
288
311
  // follows nwaku implementation
289
312
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
290
313
  private static computeMembershipHash(info: MembershipInfo): MembershipHash {
@@ -300,15 +323,16 @@ export class Keystore {
300
323
  JSON.stringify({
301
324
  treeIndex: options.membership.treeIndex,
302
325
  identityCredential: {
303
- idTrapdoor: Array.from(options.identity.IDTrapdoor),
326
+ idCommitment: Array.from(options.identity.IDCommitment),
304
327
  idNullifier: Array.from(options.identity.IDNullifier),
305
328
  idSecretHash: Array.from(options.identity.IDSecretHash),
306
- idCommitment: Array.from(options.identity.IDCommitment)
329
+ idTrapdoor: Array.from(options.identity.IDTrapdoor)
307
330
  },
308
331
  membershipContract: {
309
332
  chainId: options.membership.chainId,
310
333
  address: options.membership.address
311
- }
334
+ },
335
+ userMessageLimit: options.membership.rateLimit
312
336
  })
313
337
  );
314
338
  }