@waku/rln 0.1.5-76f86de.0 → 0.1.5-cad3e7a.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 (50) 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_contract.js +8 -8
  4. package/bundle/packages/rln/dist/contract/rln_light_contract.js +477 -0
  5. package/bundle/packages/rln/dist/identity.js +9 -0
  6. package/bundle/packages/rln/dist/keystore/keystore.js +15 -25
  7. package/bundle/packages/rln/dist/rln.js +5 -5
  8. package/bundle/packages/rln/dist/rln_light.js +149 -0
  9. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
  10. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
  11. package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
  12. package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
  13. package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
  14. package/dist/.tsbuildinfo +1 -1
  15. package/dist/contract/constants.d.ts +1 -1
  16. package/dist/contract/constants.js +1 -1
  17. package/dist/contract/constants.js.map +1 -1
  18. package/dist/contract/rln_contract.js +8 -8
  19. package/dist/contract/rln_contract.js.map +1 -1
  20. package/dist/contract/rln_light_contract.d.ts +124 -0
  21. package/dist/contract/rln_light_contract.js +460 -0
  22. package/dist/contract/rln_light_contract.js.map +1 -0
  23. package/dist/contract/test-utils.js +1 -1
  24. package/dist/contract/test-utils.js.map +1 -1
  25. package/dist/identity.d.ts +1 -0
  26. package/dist/identity.js +9 -0
  27. package/dist/identity.js.map +1 -1
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +3 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/keystore/keystore.d.ts +0 -1
  32. package/dist/keystore/keystore.js +15 -25
  33. package/dist/keystore/keystore.js.map +1 -1
  34. package/dist/keystore/types.d.ts +2 -2
  35. package/dist/rln.js +5 -5
  36. package/dist/rln.js.map +1 -1
  37. package/dist/rln_light.d.ts +64 -0
  38. package/dist/rln_light.js +144 -0
  39. package/dist/rln_light.js.map +1 -0
  40. package/package.json +1 -1
  41. package/src/contract/constants.ts +1 -1
  42. package/src/contract/rln_contract.ts +8 -8
  43. package/src/contract/rln_light_contract.ts +725 -0
  44. package/src/contract/test-utils.ts +1 -1
  45. package/src/identity.ts +10 -0
  46. package/src/index.ts +4 -0
  47. package/src/keystore/keystore.ts +27 -43
  48. package/src/keystore/types.ts +2 -2
  49. package/src/rln.ts +5 -5
  50. package/src/rln_light.ts +235 -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
  }
package/src/identity.ts CHANGED
@@ -28,4 +28,14 @@ export class IdentityCredential {
28
28
  idCommitmentBigInt
29
29
  );
30
30
  }
31
+
32
+ public toJSON(): [number[], number[], number[], number[], string] {
33
+ return [
34
+ Array.from(this.IDTrapdoor),
35
+ Array.from(this.IDNullifier),
36
+ Array.from(this.IDSecretHash),
37
+ Array.from(this.IDCommitment),
38
+ this.IDCommitmentBigInt.toString()
39
+ ];
40
+ }
31
41
  }
package/src/index.ts CHANGED
@@ -1,15 +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
5
  import { createRLN } from "./create.js";
5
6
  import { IdentityCredential } from "./identity.js";
6
7
  import { Keystore } from "./keystore/index.js";
7
8
  import { Proof } from "./proof.js";
8
9
  import { RLNInstance } from "./rln.js";
10
+ import { RLNLightInstance } from "./rln_light.js";
9
11
  import { MerkleRootTracker } from "./root_tracker.js";
10
12
  import { extractMetaMaskSigner } from "./utils/index.js";
11
13
 
12
14
  export {
15
+ RLNLightInstance,
16
+ RLNLightContract,
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,27 +251,27 @@ 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 arrays
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"),
@@ -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 {
@@ -315,12 +299,12 @@ export class Keystore {
315
299
  return utf8ToBytes(
316
300
  JSON.stringify({
317
301
  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
- },
302
+ identityCredential: [
303
+ Array.from(options.identity.IDTrapdoor),
304
+ Array.from(options.identity.IDNullifier),
305
+ Array.from(options.identity.IDSecretHash),
306
+ Array.from(options.identity.IDCommitment)
307
+ ],
324
308
  membershipContract: {
325
309
  chainId: options.membership.chainId,
326
310
  address: options.membership.address
@@ -8,9 +8,9 @@ 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
- treeIndex: number;
13
+ treeIndex: `0x${string}`; // hexadecimal string
14
14
  rateLimit: number;
15
15
  };
16
16
 
package/src/rln.ts CHANGED
@@ -160,7 +160,7 @@ export class RLNInstance {
160
160
  try {
161
161
  const { credentials, keystore } =
162
162
  await RLNInstance.decryptCredentialsIfNeeded(options.credentials);
163
- const { signer, address } = await this.determineStartOptions(
163
+ const { signer, address, rateLimit } = await this.determineStartOptions(
164
164
  options,
165
165
  credentials
166
166
  );
@@ -174,7 +174,7 @@ export class RLNInstance {
174
174
  this._contract = await RLNContract.init(this, {
175
175
  address: address!,
176
176
  signer: signer!,
177
- rateLimit: options.rateLimit ?? this.zerokit.getRateLimit
177
+ rateLimit: rateLimit ?? this.zerokit.getRateLimit
178
178
  });
179
179
  this.started = true;
180
180
  } finally {
@@ -197,7 +197,7 @@ export class RLNInstance {
197
197
  }
198
198
 
199
199
  const signer = options.signer || (await extractMetaMaskSigner());
200
- const currentChainId = await signer.getChainId();
200
+ const currentChainId = (await signer.getChainId()).toString();
201
201
 
202
202
  if (chainId && chainId !== currentChainId) {
203
203
  throw Error(
@@ -288,7 +288,7 @@ export class RLNInstance {
288
288
  return createRLNEncoder({
289
289
  encoder: createEncoder(options),
290
290
  rlnInstance: this,
291
- index: credentials.membership.treeIndex,
291
+ index: parseInt(credentials.membership.treeIndex),
292
292
  credential: credentials.identity
293
293
  });
294
294
  }
@@ -312,7 +312,7 @@ export class RLNInstance {
312
312
 
313
313
  const chainId = credentials.membership.chainId;
314
314
  const network = await this._contract.provider.getNetwork();
315
- const currentChainId = network.chainId;
315
+ const currentChainId = network.chainId.toString();
316
316
  if (chainId !== currentChainId) {
317
317
  throw Error(
318
318
  `Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`
@@ -0,0 +1,235 @@
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 { RLNLightContract } from "./contract/rln_light_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 {
16
+ buildBigIntFromUint8Array,
17
+ extractMetaMaskSigner
18
+ } from "./utils/index.js";
19
+
20
+ const log = new Logger("waku:rln");
21
+
22
+ /**
23
+ * Create an instance of RLN
24
+ * @returns RLNInstance
25
+ */
26
+ export async function create(): Promise<RLNLightInstance> {
27
+ try {
28
+ return new RLNLightInstance();
29
+ } catch (error) {
30
+ log.error("Failed to initialize RLN:", error);
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ type StartRLNOptions = {
36
+ /**
37
+ * If not set - will extract MetaMask account and get signer from it.
38
+ */
39
+ signer?: ethers.Signer;
40
+ /**
41
+ * If not set - will use default SEPOLIA_CONTRACT address.
42
+ */
43
+ address?: string;
44
+ /**
45
+ * Credentials to use for generating proofs and connecting to the contract and network.
46
+ * If provided used for validating the network chainId and connecting to registry contract.
47
+ */
48
+ credentials?: EncryptedCredentials | DecryptedCredentials;
49
+ /**
50
+ * Rate limit for the member.
51
+ */
52
+ rateLimit?: number;
53
+ };
54
+
55
+ type RegisterMembershipOptions =
56
+ | { signature: string }
57
+ | { identity: IdentityCredential };
58
+
59
+ export class RLNLightInstance {
60
+ private started = false;
61
+ private starting = false;
62
+
63
+ private _contract: undefined | RLNLightContract;
64
+ private _signer: undefined | ethers.Signer;
65
+
66
+ private keystore = Keystore.create();
67
+ private _credentials: undefined | DecryptedCredentials;
68
+
69
+ public constructor() {}
70
+
71
+ public get contract(): undefined | RLNLightContract {
72
+ return this._contract;
73
+ }
74
+
75
+ public get signer(): undefined | ethers.Signer {
76
+ return this._signer;
77
+ }
78
+
79
+ public async start(options: StartRLNOptions = {}): Promise<void> {
80
+ if (this.started || this.starting) {
81
+ return;
82
+ }
83
+
84
+ this.starting = true;
85
+
86
+ try {
87
+ const { credentials, keystore } =
88
+ await RLNLightInstance.decryptCredentialsIfNeeded(options.credentials);
89
+ const { signer, address, rateLimit } = await this.determineStartOptions(
90
+ options,
91
+ credentials
92
+ );
93
+
94
+ if (keystore) {
95
+ this.keystore = keystore;
96
+ }
97
+
98
+ this._credentials = credentials;
99
+ this._signer = signer!;
100
+ this._contract = await RLNLightContract.init({
101
+ address: address!,
102
+ signer: signer!,
103
+ rateLimit: rateLimit
104
+ });
105
+ this.started = true;
106
+ } finally {
107
+ this.starting = false;
108
+ }
109
+ }
110
+
111
+ public get credentials(): DecryptedCredentials | undefined {
112
+ return this._credentials;
113
+ }
114
+
115
+ private async determineStartOptions(
116
+ options: StartRLNOptions,
117
+ credentials: KeystoreEntity | undefined
118
+ ): Promise<StartRLNOptions> {
119
+ let chainId = credentials?.membership.chainId;
120
+ const address =
121
+ credentials?.membership.address ||
122
+ options.address ||
123
+ LINEA_CONTRACT.address;
124
+
125
+ if (address === LINEA_CONTRACT.address) {
126
+ chainId = LINEA_CONTRACT.chainId;
127
+ }
128
+
129
+ const signer = options.signer || (await extractMetaMaskSigner());
130
+ const currentChainId = (await signer.getChainId()).toString();
131
+
132
+ if (chainId && chainId !== currentChainId) {
133
+ throw Error(
134
+ `Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`
135
+ );
136
+ }
137
+
138
+ return {
139
+ signer,
140
+ address
141
+ };
142
+ }
143
+
144
+ private static async decryptCredentialsIfNeeded(
145
+ credentials?: EncryptedCredentials | DecryptedCredentials
146
+ ): Promise<{ credentials?: DecryptedCredentials; keystore?: Keystore }> {
147
+ if (!credentials) {
148
+ return {};
149
+ }
150
+
151
+ if ("identity" in credentials) {
152
+ return { credentials };
153
+ }
154
+
155
+ const keystore = Keystore.fromString(credentials.keystore);
156
+
157
+ if (!keystore) {
158
+ return {};
159
+ }
160
+
161
+ const decryptedCredentials = await keystore.readCredential(
162
+ credentials.id,
163
+ credentials.password
164
+ );
165
+
166
+ return {
167
+ keystore,
168
+ credentials: decryptedCredentials
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Generates an identity credential from a seed string
174
+ * This is a pure implementation that doesn't rely on Zerokit
175
+ * @param seed A string seed to generate the identity from
176
+ * @returns IdentityCredential
177
+ */
178
+ private generateSeededIdentityCredential(seed: string): IdentityCredential {
179
+ // Convert the seed to bytes
180
+ const encoder = new TextEncoder();
181
+ const seedBytes = encoder.encode(seed);
182
+
183
+ // Generate deterministic values using HMAC-SHA256
184
+ // We use different context strings for each component to ensure they're different
185
+ const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
186
+ const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
187
+
188
+ // Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
189
+ const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
190
+ const idSecretHash = sha256(combinedBytes);
191
+
192
+ // Generate IDCommitment as a hash of IDSecretHash
193
+ const idCommitment = sha256(idSecretHash);
194
+
195
+ // Convert IDCommitment to BigInt
196
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
197
+
198
+ return new IdentityCredential(
199
+ idTrapdoor,
200
+ idNullifier,
201
+ idSecretHash,
202
+ idCommitment,
203
+ idCommitmentBigInt
204
+ );
205
+ }
206
+
207
+ public async registerMembership(
208
+ options: RegisterMembershipOptions
209
+ ): Promise<undefined | DecryptedCredentials> {
210
+ if (!this.contract) {
211
+ throw Error("RLN Contract is not initialized.");
212
+ }
213
+
214
+ let identity = "identity" in options && options.identity;
215
+
216
+ if ("signature" in options) {
217
+ identity = this.generateSeededIdentityCredential(options.signature);
218
+ }
219
+
220
+ if (!identity) {
221
+ throw Error("Missing signature or identity to register membership.");
222
+ }
223
+
224
+ return this.contract.registerWithIdentity(identity);
225
+ }
226
+
227
+ /**
228
+ * Changes credentials in use by relying on provided Keystore earlier in rln.start
229
+ * @param id: string, hash of credentials to select from Keystore
230
+ * @param password: string or bytes to use to decrypt credentials from Keystore
231
+ */
232
+ public async useCredentials(id: string, password: Password): Promise<void> {
233
+ this._credentials = await this.keystore?.readCredential(id, password);
234
+ }
235
+ }