@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
@@ -0,0 +1,233 @@
1
+ import { hmac } from '../node_modules/@noble/hashes/esm/hmac.js';
2
+ import { sha256 } from '../node_modules/@noble/hashes/esm/sha256.js';
3
+ import '../../interfaces/dist/protocols.js';
4
+ import '../../interfaces/dist/connection_manager.js';
5
+ import '../../interfaces/dist/health_indicator.js';
6
+ import '../../../node_modules/multiformats/dist/src/bases/base10.js';
7
+ import '../../../node_modules/multiformats/dist/src/bases/base16.js';
8
+ import '../../../node_modules/multiformats/dist/src/bases/base2.js';
9
+ import '../../../node_modules/multiformats/dist/src/bases/base256emoji.js';
10
+ import '../../../node_modules/multiformats/dist/src/bases/base32.js';
11
+ import '../../../node_modules/multiformats/dist/src/bases/base36.js';
12
+ import '../../../node_modules/multiformats/dist/src/bases/base58.js';
13
+ import '../../../node_modules/multiformats/dist/src/bases/base64.js';
14
+ import '../../../node_modules/multiformats/dist/src/bases/base8.js';
15
+ import '../../../node_modules/multiformats/dist/src/bases/identity.js';
16
+ import '../../../node_modules/multiformats/dist/src/codecs/json.js';
17
+ import { Logger } from '../../utils/dist/logger/index.js';
18
+ import { LINEA_CONTRACT } from './contract/constants.js';
19
+ import { RLNBaseContract } from './contract/rln_base_contract.js';
20
+ import { IdentityCredential } from './identity.js';
21
+ import { Keystore } from './keystore/keystore.js';
22
+ import { extractMetaMaskSigner } from './utils/metamask.js';
23
+ import { buildBigIntFromUint8Array } from './utils/bytes.js';
24
+ import './utils/epoch.js';
25
+
26
+ const log = new Logger("waku:credentials");
27
+ /**
28
+ * Manages credentials for RLN
29
+ * This is a lightweight implementation of the RLN contract that doesn't require Zerokit
30
+ * It is used to register membership and generate identity credentials
31
+ */
32
+ class RLNCredentialsManager {
33
+ started = false;
34
+ starting = false;
35
+ _contract;
36
+ _signer;
37
+ keystore = Keystore.create();
38
+ _credentials;
39
+ zerokit;
40
+ constructor(zerokit) {
41
+ log.info("RLNCredentialsManager initialized");
42
+ this.zerokit = zerokit;
43
+ }
44
+ get contract() {
45
+ return this._contract;
46
+ }
47
+ set contract(contract) {
48
+ this._contract = contract;
49
+ }
50
+ get signer() {
51
+ return this._signer;
52
+ }
53
+ set signer(signer) {
54
+ this._signer = signer;
55
+ }
56
+ get credentials() {
57
+ return this._credentials;
58
+ }
59
+ set credentials(credentials) {
60
+ this._credentials = credentials;
61
+ }
62
+ get provider() {
63
+ return this.contract?.provider;
64
+ }
65
+ async start(options = {}) {
66
+ if (this.started || this.starting) {
67
+ log.info("RLNCredentialsManager already started or starting");
68
+ return;
69
+ }
70
+ log.info("Starting RLNCredentialsManager");
71
+ this.starting = true;
72
+ try {
73
+ const { credentials, keystore } = await RLNCredentialsManager.decryptCredentialsIfNeeded(options.credentials);
74
+ if (credentials) {
75
+ log.info("Credentials successfully decrypted");
76
+ }
77
+ const { signer, address, rateLimit } = await this.determineStartOptions(options, credentials);
78
+ log.info(`Using contract address: ${address}`);
79
+ if (keystore) {
80
+ this.keystore = keystore;
81
+ log.info("Using provided keystore");
82
+ }
83
+ this._credentials = credentials;
84
+ this._signer = signer;
85
+ this._contract = new RLNBaseContract({
86
+ address: address,
87
+ signer: signer,
88
+ rateLimit: rateLimit ?? this.zerokit?.getRateLimit
89
+ });
90
+ log.info("RLNCredentialsManager successfully started");
91
+ this.started = true;
92
+ }
93
+ catch (error) {
94
+ log.error("Failed to start RLNCredentialsManager", error);
95
+ throw error;
96
+ }
97
+ finally {
98
+ this.starting = false;
99
+ }
100
+ }
101
+ async registerMembership(options) {
102
+ if (!this.contract) {
103
+ log.error("RLN Contract is not initialized");
104
+ throw Error("RLN Contract is not initialized.");
105
+ }
106
+ log.info("Registering membership");
107
+ let identity = "identity" in options && options.identity;
108
+ if ("signature" in options) {
109
+ log.info("Generating identity from signature");
110
+ if (this.zerokit) {
111
+ log.info("Using Zerokit to generate identity");
112
+ identity = this.zerokit.generateSeededIdentityCredential(options.signature);
113
+ }
114
+ else {
115
+ log.info("Using local implementation to generate identity");
116
+ identity = this.generateSeededIdentityCredential(options.signature);
117
+ }
118
+ }
119
+ if (!identity) {
120
+ log.error("Missing signature or identity to register membership");
121
+ throw Error("Missing signature or identity to register membership.");
122
+ }
123
+ log.info("Registering identity with contract");
124
+ return this.contract.registerWithIdentity(identity);
125
+ }
126
+ /**
127
+ * Changes credentials in use by relying on provided Keystore earlier in rln.start
128
+ * @param id: string, hash of credentials to select from Keystore
129
+ * @param password: string or bytes to use to decrypt credentials from Keystore
130
+ */
131
+ async useCredentials(id, password) {
132
+ log.info(`Attempting to use credentials with ID: ${id}`);
133
+ this._credentials = await this.keystore?.readCredential(id, password);
134
+ if (this._credentials) {
135
+ log.info("Successfully loaded credentials");
136
+ }
137
+ else {
138
+ log.warn("Failed to load credentials");
139
+ }
140
+ }
141
+ async determineStartOptions(options, credentials) {
142
+ let chainId = credentials?.membership.chainId;
143
+ const address = credentials?.membership.address ||
144
+ options.address ||
145
+ LINEA_CONTRACT.address;
146
+ if (address === LINEA_CONTRACT.address) {
147
+ chainId = LINEA_CONTRACT.chainId;
148
+ log.info(`Using Linea contract with chainId: ${chainId}`);
149
+ }
150
+ const signer = options.signer || (await extractMetaMaskSigner());
151
+ const currentChainId = await signer.getChainId();
152
+ log.info(`Current chain ID: ${currentChainId}`);
153
+ if (chainId && chainId !== currentChainId.toString()) {
154
+ log.error(`Chain ID mismatch: contract=${chainId}, current=${currentChainId}`);
155
+ throw Error(`Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`);
156
+ }
157
+ return {
158
+ signer,
159
+ address
160
+ };
161
+ }
162
+ static async decryptCredentialsIfNeeded(credentials) {
163
+ if (!credentials) {
164
+ log.info("No credentials provided");
165
+ return {};
166
+ }
167
+ if ("identity" in credentials) {
168
+ log.info("Using already decrypted credentials");
169
+ return { credentials };
170
+ }
171
+ log.info("Attempting to decrypt credentials");
172
+ const keystore = Keystore.fromString(credentials.keystore);
173
+ if (!keystore) {
174
+ log.warn("Failed to create keystore from string");
175
+ return {};
176
+ }
177
+ try {
178
+ const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
179
+ log.info(`Successfully decrypted credentials with ID: ${credentials.id}`);
180
+ return {
181
+ keystore,
182
+ credentials: decryptedCredentials
183
+ };
184
+ }
185
+ catch (error) {
186
+ log.error("Failed to decrypt credentials", error);
187
+ throw error;
188
+ }
189
+ }
190
+ async verifyCredentialsAgainstContract(credentials) {
191
+ if (!this.contract) {
192
+ throw Error("Failed to verify chain coordinates: no contract initialized.");
193
+ }
194
+ const registryAddress = credentials.membership.address;
195
+ const currentRegistryAddress = this.contract.address;
196
+ if (registryAddress !== currentRegistryAddress) {
197
+ throw Error(`Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`);
198
+ }
199
+ const chainId = credentials.membership.chainId;
200
+ const network = await this.contract.provider.getNetwork();
201
+ const currentChainId = network.chainId;
202
+ if (chainId !== currentChainId.toString()) {
203
+ throw Error(`Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`);
204
+ }
205
+ }
206
+ /**
207
+ * Generates an identity credential from a seed string
208
+ * This is a pure implementation that doesn't rely on Zerokit
209
+ * @param seed A string seed to generate the identity from
210
+ * @returns IdentityCredential
211
+ */
212
+ generateSeededIdentityCredential(seed) {
213
+ log.info("Generating seeded identity credential");
214
+ // Convert the seed to bytes
215
+ const encoder = new TextEncoder();
216
+ const seedBytes = encoder.encode(seed);
217
+ // Generate deterministic values using HMAC-SHA256
218
+ // We use different context strings for each component to ensure they're different
219
+ const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
220
+ const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
221
+ // Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
222
+ const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
223
+ const idSecretHash = sha256(combinedBytes);
224
+ // Generate IDCommitment as a hash of IDSecretHash
225
+ const idCommitment = sha256(idSecretHash);
226
+ // Convert IDCommitment to BigInt
227
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
228
+ log.info("Successfully generated identity credential");
229
+ return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
230
+ }
231
+ }
232
+
233
+ export { RLNCredentialsManager };
@@ -25,6 +25,14 @@ 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
+ }
28
36
  }
29
37
 
30
38
  export { IdentityCredential };
@@ -17,6 +17,7 @@ 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';
20
21
  import { buildBigIntFromUint8Array } from '../utils/bytes.js';
21
22
  import { keccak256Checksum, decryptEipKeystore } from './cipher.js';
22
23
  import { isKeystoreValid, isCredentialValid } from './schema_validator.js';
@@ -164,20 +165,20 @@ class Keystore {
164
165
  try {
165
166
  const str = bytesToUtf8(bytes);
166
167
  const obj = JSON.parse(str);
167
- // TODO: add runtime validation of nwaku credentials
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);
168
175
  return {
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
- },
176
+ identity: new IdentityCredential(idTrapdoorArray, idNullifierArray, idSecretHashArray, idCommitmentArray, idCommitmentBigInt),
176
177
  membership: {
177
178
  treeIndex: _.get(obj, "treeIndex"),
178
179
  chainId: _.get(obj, "membershipContract.chainId"),
179
180
  address: _.get(obj, "membershipContract.address"),
180
- rateLimit: _.get(obj, "membershipContract.rateLimit")
181
+ rateLimit: _.get(obj, "userMessageLimit")
181
182
  }
182
183
  };
183
184
  }
@@ -186,17 +187,6 @@ class Keystore {
186
187
  return;
187
188
  }
188
189
  }
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
- }
200
190
  // follows nwaku implementation
201
191
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
202
192
  static computeMembershipHash(info) {
@@ -206,17 +196,18 @@ class Keystore {
206
196
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L98
207
197
  static fromIdentityToBytes(options) {
208
198
  return utf8ToBytes(JSON.stringify({
209
- treeIndex: options.membership.treeIndex,
210
- identityCredential: {
211
- idCommitment: options.identity.IDCommitment,
212
- idNullifier: options.identity.IDNullifier,
213
- idSecretHash: options.identity.IDSecretHash,
214
- idTrapdoor: options.identity.IDTrapdoor
215
- },
216
199
  membershipContract: {
217
200
  chainId: options.membership.chainId,
218
201
  address: options.membership.address
219
- }
202
+ },
203
+ treeIndex: options.membership.treeIndex,
204
+ 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)
209
+ },
210
+ userMessageLimit: options.membership.rateLimit
220
211
  }));
221
212
  }
222
213
  }
@@ -21,167 +21,45 @@ import { Logger } from '../../utils/dist/logger/index.js';
21
21
  import '../../core/dist/lib/metadata/metadata.js';
22
22
  import __wbg_init, { init_panic_hook, newRLN } from '../../../node_modules/@waku/zerokit-rln-wasm/rln_wasm.js';
23
23
  import { createRLNEncoder, createRLNDecoder } from './codec.js';
24
- import { LINEA_CONTRACT, DEFAULT_RATE_LIMIT } from './contract/constants.js';
25
- import { RLNContract } from './contract/rln_contract.js';
26
- import { Keystore } from './keystore/keystore.js';
24
+ import { DEFAULT_RATE_LIMIT } from './contract/constants.js';
25
+ import { RLNCredentialsManager } from './credentials_manager.js';
27
26
  import verificationKey from './resources/verification_key.js';
28
27
  import { builder } from './resources/witness_calculator.js';
29
- import { extractMetaMaskSigner } from './utils/metamask.js';
30
- import './utils/epoch.js';
31
28
  import { Zerokit } from './zerokit.js';
32
29
 
33
30
  const log = new Logger("waku:rln");
34
- async function loadWitnessCalculator() {
35
- try {
36
- const url = new URL("./resources/rln.wasm", import.meta.url);
37
- const response = await fetch(url);
38
- if (!response.ok) {
39
- throw new Error(`Failed to fetch witness calculator: ${response.status} ${response.statusText}`);
40
- }
41
- return await builder(new Uint8Array(await response.arrayBuffer()), false);
42
- }
43
- catch (error) {
44
- log.error("Error loading witness calculator:", error);
45
- throw new Error(`Failed to load witness calculator: ${error instanceof Error ? error.message : String(error)}`);
46
- }
47
- }
48
- async function loadZkey() {
49
- try {
50
- const url = new URL("./resources/rln_final.zkey", import.meta.url);
51
- const response = await fetch(url);
52
- if (!response.ok) {
53
- throw new Error(`Failed to fetch zkey: ${response.status} ${response.statusText}`);
54
- }
55
- return new Uint8Array(await response.arrayBuffer());
56
- }
57
- catch (error) {
58
- log.error("Error loading zkey:", error);
59
- throw new Error(`Failed to load zkey: ${error instanceof Error ? error.message : String(error)}`);
60
- }
61
- }
62
- /**
63
- * Create an instance of RLN
64
- * @returns RLNInstance
65
- */
66
- async function create() {
67
- try {
68
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
- await __wbg_init?.();
70
- init_panic_hook();
71
- const witnessCalculator = await loadWitnessCalculator();
72
- const zkey = await loadZkey();
73
- const stringEncoder = new TextEncoder();
74
- const vkey = stringEncoder.encode(JSON.stringify(verificationKey));
75
- const DEPTH = 20;
76
- const zkRLN = newRLN(DEPTH, zkey, vkey);
77
- const zerokit = new Zerokit(zkRLN, witnessCalculator, DEFAULT_RATE_LIMIT);
78
- return new RLNInstance(zerokit);
79
- }
80
- catch (error) {
81
- log.error("Failed to initialize RLN:", error);
82
- throw error;
83
- }
84
- }
85
- class RLNInstance {
31
+ class RLNInstance extends RLNCredentialsManager {
86
32
  zerokit;
87
- started = false;
88
- starting = false;
89
- _contract;
90
- _signer;
91
- keystore = Keystore.create();
92
- _credentials;
93
- constructor(zerokit) {
94
- this.zerokit = zerokit;
95
- }
96
- get contract() {
97
- return this._contract;
98
- }
99
- get signer() {
100
- return this._signer;
101
- }
102
- async start(options = {}) {
103
- if (this.started || this.starting) {
104
- return;
105
- }
106
- this.starting = true;
33
+ /**
34
+ * Create an instance of RLN
35
+ * @returns RLNInstance
36
+ */
37
+ static async create() {
107
38
  try {
108
- const { credentials, keystore } = await RLNInstance.decryptCredentialsIfNeeded(options.credentials);
109
- const { signer, address } = await this.determineStartOptions(options, credentials);
110
- if (keystore) {
111
- this.keystore = keystore;
112
- }
113
- this._credentials = credentials;
114
- this._signer = signer;
115
- this._contract = await RLNContract.init(this, {
116
- address: address,
117
- signer: signer,
118
- rateLimit: options.rateLimit ?? this.zerokit.getRateLimit
119
- });
120
- this.started = true;
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ await __wbg_init?.();
41
+ init_panic_hook();
42
+ const witnessCalculator = await RLNInstance.loadWitnessCalculator();
43
+ const zkey = await RLNInstance.loadZkey();
44
+ const stringEncoder = new TextEncoder();
45
+ const vkey = stringEncoder.encode(JSON.stringify(verificationKey));
46
+ const DEPTH = 20;
47
+ const zkRLN = newRLN(DEPTH, zkey, vkey);
48
+ const zerokit = new Zerokit(zkRLN, witnessCalculator, DEFAULT_RATE_LIMIT);
49
+ return new RLNInstance(zerokit);
50
+ }
51
+ catch (error) {
52
+ log.error("Failed to initialize RLN:", error);
53
+ throw error;
121
54
  }
122
- finally {
123
- this.starting = false;
124
- }
125
- }
126
- async determineStartOptions(options, credentials) {
127
- let chainId = credentials?.membership.chainId;
128
- const address = credentials?.membership.address ||
129
- options.address ||
130
- LINEA_CONTRACT.address;
131
- if (address === LINEA_CONTRACT.address) {
132
- chainId = LINEA_CONTRACT.chainId;
133
- }
134
- const signer = options.signer || (await extractMetaMaskSigner());
135
- const currentChainId = await signer.getChainId();
136
- if (chainId && chainId !== currentChainId) {
137
- throw Error(`Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`);
138
- }
139
- return {
140
- signer,
141
- address
142
- };
143
55
  }
144
- static async decryptCredentialsIfNeeded(credentials) {
145
- if (!credentials) {
146
- return {};
147
- }
148
- if ("identity" in credentials) {
149
- return { credentials };
150
- }
151
- const keystore = Keystore.fromString(credentials.keystore);
152
- if (!keystore) {
153
- return {};
154
- }
155
- const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
156
- return {
157
- keystore,
158
- credentials: decryptedCredentials
159
- };
160
- }
161
- async registerMembership(options) {
162
- if (!this.contract) {
163
- throw Error("RLN Contract is not initialized.");
164
- }
165
- let identity = "identity" in options && options.identity;
166
- if ("signature" in options) {
167
- identity = this.zerokit.generateSeededIdentityCredential(options.signature);
168
- }
169
- if (!identity) {
170
- throw Error("Missing signature or identity to register membership.");
171
- }
172
- return this.contract.registerWithIdentity(identity);
173
- }
174
- /**
175
- * Changes credentials in use by relying on provided Keystore earlier in rln.start
176
- * @param id: string, hash of credentials to select from Keystore
177
- * @param password: string or bytes to use to decrypt credentials from Keystore
178
- */
179
- async useCredentials(id, password) {
180
- this._credentials = await this.keystore?.readCredential(id, password);
56
+ constructor(zerokit) {
57
+ super(zerokit);
58
+ this.zerokit = zerokit;
181
59
  }
182
60
  async createEncoder(options) {
183
61
  const { credentials: decryptedCredentials } = await RLNInstance.decryptCredentialsIfNeeded(options.credentials);
184
- const credentials = decryptedCredentials || this._credentials;
62
+ const credentials = decryptedCredentials || this.credentials;
185
63
  if (!credentials) {
186
64
  throw Error("Failed to create Encoder: missing RLN credentials. Use createRLNEncoder directly.");
187
65
  }
@@ -193,28 +71,40 @@ class RLNInstance {
193
71
  credential: credentials.identity
194
72
  });
195
73
  }
196
- async verifyCredentialsAgainstContract(credentials) {
197
- if (!this._contract) {
198
- throw Error("Failed to verify chain coordinates: no contract initialized.");
199
- }
200
- const registryAddress = credentials.membership.address;
201
- const currentRegistryAddress = this._contract.address;
202
- if (registryAddress !== currentRegistryAddress) {
203
- throw Error(`Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`);
204
- }
205
- const chainId = credentials.membership.chainId;
206
- const network = await this._contract.provider.getNetwork();
207
- const currentChainId = network.chainId;
208
- if (chainId !== currentChainId) {
209
- throw Error(`Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`);
210
- }
211
- }
212
74
  createDecoder(contentTopic) {
213
75
  return createRLNDecoder({
214
76
  rlnInstance: this,
215
77
  decoder: createDecoder(contentTopic)
216
78
  });
217
79
  }
80
+ static async loadWitnessCalculator() {
81
+ try {
82
+ const url = new URL("./resources/rln.wasm", import.meta.url);
83
+ const response = await fetch(url);
84
+ if (!response.ok) {
85
+ throw new Error(`Failed to fetch witness calculator: ${response.status} ${response.statusText}`);
86
+ }
87
+ return await builder(new Uint8Array(await response.arrayBuffer()), false);
88
+ }
89
+ catch (error) {
90
+ log.error("Error loading witness calculator:", error);
91
+ throw new Error(`Failed to load witness calculator: ${error instanceof Error ? error.message : String(error)}`);
92
+ }
93
+ }
94
+ static async loadZkey() {
95
+ try {
96
+ const url = new URL("./resources/rln_final.zkey", import.meta.url);
97
+ const response = await fetch(url);
98
+ if (!response.ok) {
99
+ throw new Error(`Failed to fetch zkey: ${response.status} ${response.statusText}`);
100
+ }
101
+ return new Uint8Array(await response.arrayBuffer());
102
+ }
103
+ catch (error) {
104
+ log.error("Error loading zkey:", error);
105
+ throw new Error(`Failed to load zkey: ${error instanceof Error ? error.message : String(error)}`);
106
+ }
107
+ }
218
108
  }
219
109
 
220
- export { RLNInstance, create };
110
+ export { RLNInstance };
@@ -0,0 +1,43 @@
1
+ function number(n) {
2
+ if (!Number.isSafeInteger(n) || n < 0)
3
+ throw new Error(`Wrong positive integer: ${n}`);
4
+ }
5
+ function bool(b) {
6
+ if (typeof b !== 'boolean')
7
+ throw new Error(`Expected boolean, not ${b}`);
8
+ }
9
+ function bytes(b, ...lengths) {
10
+ if (!(b instanceof Uint8Array))
11
+ throw new TypeError('Expected Uint8Array');
12
+ if (lengths.length > 0 && !lengths.includes(b.length))
13
+ throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
14
+ }
15
+ function hash(hash) {
16
+ if (typeof hash !== 'function' || typeof hash.create !== 'function')
17
+ throw new Error('Hash should be wrapped by utils.wrapConstructor');
18
+ number(hash.outputLen);
19
+ number(hash.blockLen);
20
+ }
21
+ function exists(instance, checkFinished = true) {
22
+ if (instance.destroyed)
23
+ throw new Error('Hash instance has been destroyed');
24
+ if (checkFinished && instance.finished)
25
+ throw new Error('Hash#digest() has already been called');
26
+ }
27
+ function output(out, instance) {
28
+ bytes(out);
29
+ const min = instance.outputLen;
30
+ if (out.length < min) {
31
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
32
+ }
33
+ }
34
+ const assert = {
35
+ number,
36
+ bool,
37
+ bytes,
38
+ hash,
39
+ exists,
40
+ output,
41
+ };
42
+
43
+ export { bool, bytes, assert as default, exists, hash, number, output };