@waku/rln 0.1.5-cad3e7a.0 → 0.1.5-d0da8f8.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 (179) hide show
  1. package/bundle/_virtual/utils.js +2 -2
  2. package/bundle/_virtual/utils2.js +2 -2
  3. package/bundle/index.js +4 -3
  4. package/bundle/packages/rln/dist/contract/constants.js +2 -1
  5. package/bundle/packages/rln/dist/contract/{rln_light_contract.js → rln_base_contract.js} +189 -186
  6. package/bundle/packages/rln/dist/contract/rln_contract.js +10 -420
  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 +31 -17
  12. package/bundle/packages/rln/dist/rln.js +57 -167
  13. package/bundle/packages/rln/dist/utils/bytes.js +8 -2
  14. package/bundle/packages/rln/dist/utils/metamask.js +2 -2
  15. package/bundle/packages/rln/dist/zerokit.js +5 -5
  16. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/random.js +1 -1
  17. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/utils.js +2 -2
  18. package/bundle/packages/rln/node_modules/@noble/hashes/_sha2.js +1 -1
  19. package/bundle/packages/rln/node_modules/@noble/hashes/hmac.js +1 -1
  20. package/bundle/packages/rln/node_modules/@noble/hashes/pbkdf2.js +1 -1
  21. package/bundle/packages/rln/node_modules/@noble/hashes/scrypt.js +1 -1
  22. package/bundle/packages/rln/node_modules/@noble/hashes/sha256.js +1 -1
  23. package/bundle/packages/rln/node_modules/@noble/hashes/sha512.js +1 -1
  24. package/bundle/packages/rln/node_modules/@noble/hashes/utils.js +1 -1
  25. package/dist/.tsbuildinfo +1 -1
  26. package/dist/contract/constants.d.ts +1 -1
  27. package/dist/contract/constants.js +1 -1
  28. package/dist/contract/constants.js.map +1 -1
  29. package/dist/contract/index.d.ts +1 -0
  30. package/dist/contract/index.js +1 -0
  31. package/dist/contract/index.js.map +1 -1
  32. package/dist/contract/{rln_light_contract.d.ts → rln_base_contract.d.ts} +24 -58
  33. package/dist/contract/{rln_light_contract.js → rln_base_contract.js} +187 -184
  34. package/dist/contract/rln_base_contract.js.map +1 -0
  35. package/dist/contract/rln_contract.d.ts +5 -122
  36. package/dist/contract/rln_contract.js +8 -417
  37. package/dist/contract/rln_contract.js.map +1 -1
  38. package/dist/contract/types.d.ts +45 -0
  39. package/dist/contract/types.js +8 -0
  40. package/dist/contract/types.js.map +1 -0
  41. package/dist/create.js +1 -1
  42. package/dist/create.js.map +1 -1
  43. package/dist/credentials_manager.d.ts +44 -0
  44. package/dist/credentials_manager.js +197 -0
  45. package/dist/credentials_manager.js.map +1 -0
  46. package/dist/identity.d.ts +0 -1
  47. package/dist/identity.js +0 -9
  48. package/dist/identity.js.map +1 -1
  49. package/dist/index.d.ts +5 -4
  50. package/dist/index.js +4 -3
  51. package/dist/index.js.map +1 -1
  52. package/dist/keystore/keystore.d.ts +1 -0
  53. package/dist/keystore/keystore.js +31 -17
  54. package/dist/keystore/keystore.js.map +1 -1
  55. package/dist/keystore/types.d.ts +3 -3
  56. package/dist/rln.d.ts +9 -52
  57. package/dist/rln.js +55 -164
  58. package/dist/rln.js.map +1 -1
  59. package/dist/types.d.ts +27 -0
  60. package/dist/types.js +2 -0
  61. package/dist/types.js.map +1 -0
  62. package/dist/utils/bytes.js +8 -2
  63. package/dist/utils/bytes.js.map +1 -1
  64. package/dist/zerokit.d.ts +3 -3
  65. package/dist/zerokit.js +5 -5
  66. package/dist/zerokit.js.map +1 -1
  67. package/package.json +1 -1
  68. package/src/contract/constants.ts +1 -1
  69. package/src/contract/index.ts +1 -0
  70. package/src/contract/{rln_light_contract.ts → rln_base_contract.ts} +306 -323
  71. package/src/contract/rln_contract.ts +9 -663
  72. package/src/contract/types.ts +53 -0
  73. package/src/create.ts +1 -1
  74. package/src/credentials_manager.ts +282 -0
  75. package/src/identity.ts +0 -10
  76. package/src/index.ts +7 -5
  77. package/src/keystore/keystore.ts +57 -31
  78. package/src/keystore/types.ts +3 -3
  79. package/src/rln.ts +68 -259
  80. package/src/types.ts +31 -0
  81. package/src/utils/bytes.ts +10 -2
  82. package/src/zerokit.ts +3 -3
  83. package/bundle/_virtual/__node-resolve_empty.js +0 -6
  84. package/bundle/_virtual/_node-resolve_empty.js +0 -3
  85. package/bundle/_virtual/bn.js +0 -3
  86. package/bundle/_virtual/common.js +0 -3
  87. package/bundle/_virtual/common2.js +0 -3
  88. package/bundle/_virtual/hash.js +0 -3
  89. package/bundle/_virtual/inherits_browser.js +0 -3
  90. package/bundle/_virtual/ripemd.js +0 -3
  91. package/bundle/_virtual/sha.js +0 -3
  92. package/bundle/_virtual/sha3.js +0 -3
  93. package/bundle/_virtual/utils3.js +0 -3
  94. package/bundle/node_modules/@ethersproject/abi/lib.esm/_version.js +0 -3
  95. package/bundle/node_modules/@ethersproject/abi/lib.esm/abi-coder.js +0 -96
  96. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js +0 -148
  97. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/address.js +0 -26
  98. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/anonymous.js +0 -20
  99. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/array.js +0 -210
  100. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/boolean.js +0 -18
  101. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/bytes.js +0 -30
  102. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/fixed-bytes.js +0 -26
  103. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/null.js +0 -22
  104. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/number.js +0 -43
  105. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/string.js +0 -19
  106. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/tuple.js +0 -58
  107. package/bundle/node_modules/@ethersproject/abi/lib.esm/fragments.js +0 -854
  108. package/bundle/node_modules/@ethersproject/abi/lib.esm/interface.js +0 -609
  109. package/bundle/node_modules/@ethersproject/abstract-provider/lib.esm/_version.js +0 -3
  110. package/bundle/node_modules/@ethersproject/abstract-provider/lib.esm/index.js +0 -66
  111. package/bundle/node_modules/@ethersproject/abstract-signer/lib.esm/_version.js +0 -3
  112. package/bundle/node_modules/@ethersproject/abstract-signer/lib.esm/index.js +0 -302
  113. package/bundle/node_modules/@ethersproject/address/lib.esm/_version.js +0 -3
  114. package/bundle/node_modules/@ethersproject/address/lib.esm/index.js +0 -110
  115. package/bundle/node_modules/@ethersproject/base64/lib.esm/base64.js +0 -20
  116. package/bundle/node_modules/@ethersproject/basex/lib.esm/index.js +0 -120
  117. package/bundle/node_modules/@ethersproject/bignumber/lib.esm/_version.js +0 -3
  118. package/bundle/node_modules/@ethersproject/bignumber/lib.esm/bignumber.js +0 -287
  119. package/bundle/node_modules/@ethersproject/bytes/lib.esm/_version.js +0 -3
  120. package/bundle/node_modules/@ethersproject/bytes/lib.esm/index.js +0 -402
  121. package/bundle/node_modules/@ethersproject/constants/lib.esm/addresses.js +0 -3
  122. package/bundle/node_modules/@ethersproject/constants/lib.esm/bignumbers.js +0 -8
  123. package/bundle/node_modules/@ethersproject/constants/lib.esm/hashes.js +0 -3
  124. package/bundle/node_modules/@ethersproject/contracts/lib.esm/_version.js +0 -3
  125. package/bundle/node_modules/@ethersproject/contracts/lib.esm/index.js +0 -893
  126. package/bundle/node_modules/@ethersproject/hash/lib.esm/_version.js +0 -3
  127. package/bundle/node_modules/@ethersproject/hash/lib.esm/ens-normalize/decoder.js +0 -256
  128. package/bundle/node_modules/@ethersproject/hash/lib.esm/ens-normalize/include.js +0 -36
  129. package/bundle/node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js +0 -135
  130. package/bundle/node_modules/@ethersproject/hash/lib.esm/id.js +0 -8
  131. package/bundle/node_modules/@ethersproject/hash/lib.esm/namehash.js +0 -64
  132. package/bundle/node_modules/@ethersproject/hash/lib.esm/typed-data.js +0 -443
  133. package/bundle/node_modules/@ethersproject/keccak256/lib.esm/index.js +0 -8
  134. package/bundle/node_modules/@ethersproject/keccak256/node_modules/js-sha3/src/sha3.js +0 -660
  135. package/bundle/node_modules/@ethersproject/logger/lib.esm/_version.js +0 -3
  136. package/bundle/node_modules/@ethersproject/logger/lib.esm/index.js +0 -352
  137. package/bundle/node_modules/@ethersproject/networks/lib.esm/_version.js +0 -3
  138. package/bundle/node_modules/@ethersproject/networks/lib.esm/index.js +0 -248
  139. package/bundle/node_modules/@ethersproject/properties/lib.esm/_version.js +0 -3
  140. package/bundle/node_modules/@ethersproject/properties/lib.esm/index.js +0 -127
  141. package/bundle/node_modules/@ethersproject/providers/lib.esm/_version.js +0 -3
  142. package/bundle/node_modules/@ethersproject/providers/lib.esm/base-provider.js +0 -2007
  143. package/bundle/node_modules/@ethersproject/providers/lib.esm/formatter.js +0 -422
  144. package/bundle/node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js +0 -674
  145. package/bundle/node_modules/@ethersproject/providers/lib.esm/web3-provider.js +0 -132
  146. package/bundle/node_modules/@ethersproject/rlp/lib.esm/_version.js +0 -3
  147. package/bundle/node_modules/@ethersproject/rlp/lib.esm/index.js +0 -120
  148. package/bundle/node_modules/@ethersproject/sha2/lib.esm/sha2.js +0 -8
  149. package/bundle/node_modules/@ethersproject/signing-key/lib.esm/_version.js +0 -3
  150. package/bundle/node_modules/@ethersproject/signing-key/lib.esm/elliptic.js +0 -2430
  151. package/bundle/node_modules/@ethersproject/signing-key/lib.esm/index.js +0 -76
  152. package/bundle/node_modules/@ethersproject/strings/lib.esm/_version.js +0 -3
  153. package/bundle/node_modules/@ethersproject/strings/lib.esm/utf8.js +0 -219
  154. package/bundle/node_modules/@ethersproject/transactions/lib.esm/_version.js +0 -3
  155. package/bundle/node_modules/@ethersproject/transactions/lib.esm/index.js +0 -279
  156. package/bundle/node_modules/@ethersproject/web/lib.esm/_version.js +0 -3
  157. package/bundle/node_modules/@ethersproject/web/lib.esm/geturl.js +0 -69
  158. package/bundle/node_modules/@ethersproject/web/lib.esm/index.js +0 -404
  159. package/bundle/node_modules/bech32/index.js +0 -187
  160. package/bundle/node_modules/bn.js/lib/bn.js +0 -3361
  161. package/bundle/node_modules/hash.js/lib/hash/common.js +0 -97
  162. package/bundle/node_modules/hash.js/lib/hash/hmac.js +0 -51
  163. package/bundle/node_modules/hash.js/lib/hash/ripemd.js +0 -152
  164. package/bundle/node_modules/hash.js/lib/hash/sha/1.js +0 -81
  165. package/bundle/node_modules/hash.js/lib/hash/sha/224.js +0 -33
  166. package/bundle/node_modules/hash.js/lib/hash/sha/256.js +0 -113
  167. package/bundle/node_modules/hash.js/lib/hash/sha/384.js +0 -39
  168. package/bundle/node_modules/hash.js/lib/hash/sha/512.js +0 -336
  169. package/bundle/node_modules/hash.js/lib/hash/sha/common.js +0 -53
  170. package/bundle/node_modules/hash.js/lib/hash/sha.js +0 -14
  171. package/bundle/node_modules/hash.js/lib/hash/utils.js +0 -282
  172. package/bundle/node_modules/hash.js/lib/hash.js +0 -33
  173. package/bundle/node_modules/inherits/inherits_browser.js +0 -33
  174. package/bundle/node_modules/minimalistic-assert/index.js +0 -13
  175. package/dist/contract/rln_light_contract.js.map +0 -1
  176. package/dist/rln_light.d.ts +0 -64
  177. package/dist/rln_light.js +0 -144
  178. package/dist/rln_light.js.map +0 -1
  179. package/src/rln_light.ts +0 -235
@@ -16,54 +16,109 @@ import '../../../node_modules/multiformats/dist/src/bases/identity.js';
16
16
  import '../../../node_modules/multiformats/dist/src/codecs/json.js';
17
17
  import { Logger } from '../../utils/dist/logger/index.js';
18
18
  import { LINEA_CONTRACT } from './contract/constants.js';
19
- import { RLNLightContract } from './contract/rln_light_contract.js';
19
+ import { RLNBaseContract } from './contract/rln_base_contract.js';
20
20
  import { IdentityCredential } from './identity.js';
21
21
  import { Keystore } from './keystore/keystore.js';
22
22
  import { extractMetaMaskSigner } from './utils/metamask.js';
23
23
  import { buildBigIntFromUint8Array } from './utils/bytes.js';
24
24
  import './utils/epoch.js';
25
25
 
26
- new Logger("waku:rln");
27
- class RLNLightInstance {
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 {
28
33
  started = false;
29
34
  starting = false;
30
- _contract;
31
- _signer;
35
+ contract;
36
+ signer;
32
37
  keystore = Keystore.create();
33
- _credentials;
34
- constructor() { }
35
- get contract() {
36
- return this._contract;
38
+ credentials;
39
+ zerokit;
40
+ constructor(zerokit) {
41
+ log.info("RLNCredentialsManager initialized");
42
+ this.zerokit = zerokit;
37
43
  }
38
- get signer() {
39
- return this._signer;
44
+ get provider() {
45
+ return this.contract?.provider;
40
46
  }
41
47
  async start(options = {}) {
42
48
  if (this.started || this.starting) {
49
+ log.info("RLNCredentialsManager already started or starting");
43
50
  return;
44
51
  }
52
+ log.info("Starting RLNCredentialsManager");
45
53
  this.starting = true;
46
54
  try {
47
- const { credentials, keystore } = await RLNLightInstance.decryptCredentialsIfNeeded(options.credentials);
55
+ const { credentials, keystore } = await RLNCredentialsManager.decryptCredentialsIfNeeded(options.credentials);
56
+ if (credentials) {
57
+ log.info("Credentials successfully decrypted");
58
+ }
48
59
  const { signer, address, rateLimit } = await this.determineStartOptions(options, credentials);
60
+ log.info(`Using contract address: ${address}`);
49
61
  if (keystore) {
50
62
  this.keystore = keystore;
63
+ log.info("Using provided keystore");
51
64
  }
52
- this._credentials = credentials;
53
- this._signer = signer;
54
- this._contract = await RLNLightContract.init({
65
+ this.credentials = credentials;
66
+ this.signer = signer;
67
+ this.contract = new RLNBaseContract({
55
68
  address: address,
56
69
  signer: signer,
57
- rateLimit: rateLimit
70
+ rateLimit: rateLimit ?? this.zerokit?.rateLimit
58
71
  });
72
+ log.info("RLNCredentialsManager successfully started");
59
73
  this.started = true;
60
74
  }
75
+ catch (error) {
76
+ log.error("Failed to start RLNCredentialsManager", error);
77
+ throw error;
78
+ }
61
79
  finally {
62
80
  this.starting = false;
63
81
  }
64
82
  }
65
- get credentials() {
66
- return this._credentials;
83
+ async registerMembership(options) {
84
+ if (!this.contract) {
85
+ log.error("RLN Contract is not initialized");
86
+ throw Error("RLN Contract is not initialized.");
87
+ }
88
+ log.info("Registering membership");
89
+ let identity = "identity" in options && options.identity;
90
+ if ("signature" in options) {
91
+ log.info("Generating identity from signature");
92
+ if (this.zerokit) {
93
+ log.info("Using Zerokit to generate identity");
94
+ identity = this.zerokit.generateSeededIdentityCredential(options.signature);
95
+ }
96
+ else {
97
+ log.info("Using local implementation to generate identity");
98
+ identity = this.generateSeededIdentityCredential(options.signature);
99
+ }
100
+ }
101
+ if (!identity) {
102
+ log.error("Missing signature or identity to register membership");
103
+ throw Error("Missing signature or identity to register membership.");
104
+ }
105
+ log.info("Registering identity with contract");
106
+ return this.contract.registerWithIdentity(identity);
107
+ }
108
+ /**
109
+ * Changes credentials in use by relying on provided Keystore earlier in rln.start
110
+ * @param id: string, hash of credentials to select from Keystore
111
+ * @param password: string or bytes to use to decrypt credentials from Keystore
112
+ */
113
+ async useCredentials(id, password) {
114
+ log.info(`Attempting to use credentials with ID: ${id}`);
115
+ this.credentials = await this.keystore?.readCredential(id, password);
116
+ if (this.credentials) {
117
+ log.info("Successfully loaded credentials");
118
+ }
119
+ else {
120
+ log.warn("Failed to load credentials");
121
+ }
67
122
  }
68
123
  async determineStartOptions(options, credentials) {
69
124
  let chainId = credentials?.membership.chainId;
@@ -71,11 +126,14 @@ class RLNLightInstance {
71
126
  options.address ||
72
127
  LINEA_CONTRACT.address;
73
128
  if (address === LINEA_CONTRACT.address) {
74
- chainId = LINEA_CONTRACT.chainId;
129
+ chainId = LINEA_CONTRACT.chainId.toString();
130
+ log.info(`Using Linea contract with chainId: ${chainId}`);
75
131
  }
76
132
  const signer = options.signer || (await extractMetaMaskSigner());
77
- const currentChainId = (await signer.getChainId()).toString();
78
- if (chainId && chainId !== currentChainId) {
133
+ const currentChainId = await signer.getChainId();
134
+ log.info(`Current chain ID: ${currentChainId}`);
135
+ if (chainId && chainId !== currentChainId.toString()) {
136
+ log.error(`Chain ID mismatch: contract=${chainId}, current=${currentChainId}`);
79
137
  throw Error(`Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`);
80
138
  }
81
139
  return {
@@ -85,20 +143,47 @@ class RLNLightInstance {
85
143
  }
86
144
  static async decryptCredentialsIfNeeded(credentials) {
87
145
  if (!credentials) {
146
+ log.info("No credentials provided");
88
147
  return {};
89
148
  }
90
149
  if ("identity" in credentials) {
150
+ log.info("Using already decrypted credentials");
91
151
  return { credentials };
92
152
  }
153
+ log.info("Attempting to decrypt credentials");
93
154
  const keystore = Keystore.fromString(credentials.keystore);
94
155
  if (!keystore) {
156
+ log.warn("Failed to create keystore from string");
95
157
  return {};
96
158
  }
97
- const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
98
- return {
99
- keystore,
100
- credentials: decryptedCredentials
101
- };
159
+ try {
160
+ const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
161
+ log.info(`Successfully decrypted credentials with ID: ${credentials.id}`);
162
+ return {
163
+ keystore,
164
+ credentials: decryptedCredentials
165
+ };
166
+ }
167
+ catch (error) {
168
+ log.error("Failed to decrypt credentials", error);
169
+ throw error;
170
+ }
171
+ }
172
+ async verifyCredentialsAgainstContract(credentials) {
173
+ if (!this.contract) {
174
+ throw Error("Failed to verify chain coordinates: no contract initialized.");
175
+ }
176
+ const registryAddress = credentials.membership.address;
177
+ const currentRegistryAddress = this.contract.address;
178
+ if (registryAddress !== currentRegistryAddress) {
179
+ throw Error(`Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`);
180
+ }
181
+ const chainId = credentials.membership.chainId;
182
+ const network = await this.contract.provider.getNetwork();
183
+ const currentChainId = network.chainId;
184
+ if (chainId !== currentChainId.toString()) {
185
+ throw Error(`Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`);
186
+ }
102
187
  }
103
188
  /**
104
189
  * Generates an identity credential from a seed string
@@ -107,6 +192,7 @@ class RLNLightInstance {
107
192
  * @returns IdentityCredential
108
193
  */
109
194
  generateSeededIdentityCredential(seed) {
195
+ log.info("Generating seeded identity credential");
110
196
  // Convert the seed to bytes
111
197
  const encoder = new TextEncoder();
112
198
  const seedBytes = encoder.encode(seed);
@@ -121,29 +207,9 @@ class RLNLightInstance {
121
207
  const idCommitment = sha256(idSecretHash);
122
208
  // Convert IDCommitment to BigInt
123
209
  const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
210
+ log.info("Successfully generated identity credential");
124
211
  return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
125
212
  }
126
- async registerMembership(options) {
127
- if (!this.contract) {
128
- throw Error("RLN Contract is not initialized.");
129
- }
130
- let identity = "identity" in options && options.identity;
131
- if ("signature" in options) {
132
- identity = this.generateSeededIdentityCredential(options.signature);
133
- }
134
- if (!identity) {
135
- throw Error("Missing signature or identity to register membership.");
136
- }
137
- return this.contract.registerWithIdentity(identity);
138
- }
139
- /**
140
- * Changes credentials in use by relying on provided Keystore earlier in rln.start
141
- * @param id: string, hash of credentials to select from Keystore
142
- * @param password: string or bytes to use to decrypt credentials from Keystore
143
- */
144
- async useCredentials(id, password) {
145
- this._credentials = await this.keystore?.readCredential(id, password);
146
- }
147
213
  }
148
214
 
149
- export { RLNLightInstance };
215
+ export { RLNCredentialsManager };
@@ -25,15 +25,6 @@ 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
- Array.from(this.IDTrapdoor),
31
- Array.from(this.IDNullifier),
32
- Array.from(this.IDSecretHash),
33
- Array.from(this.IDCommitment),
34
- this.IDCommitmentBigInt.toString()
35
- ];
36
- }
37
28
  }
38
29
 
39
30
  export { IdentityCredential };
@@ -17,7 +17,6 @@ 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';
21
20
  import { buildBigIntFromUint8Array } from '../utils/bytes.js';
22
21
  import { keccak256Checksum, decryptEipKeystore } from './cipher.js';
23
22
  import { isKeystoreValid, isCredentialValid } from './schema_validator.js';
@@ -165,20 +164,20 @@ class Keystore {
165
164
  try {
166
165
  const str = bytesToUtf8(bytes);
167
166
  const obj = JSON.parse(str);
168
- // Get identity arrays
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);
167
+ // TODO: add runtime validation of nwaku credentials
175
168
  return {
176
- identity: new IdentityCredential(idTrapdoorArray, idNullifierArray, idSecretHashArray, idCommitmentArray, idCommitmentBigInt),
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
+ },
177
176
  membership: {
178
177
  treeIndex: _.get(obj, "treeIndex"),
179
178
  chainId: _.get(obj, "membershipContract.chainId"),
180
179
  address: _.get(obj, "membershipContract.address"),
181
- rateLimit: _.get(obj, "membershipContract.rateLimit")
180
+ rateLimit: _.get(obj, "userMessageLimit")
182
181
  }
183
182
  };
184
183
  }
@@ -187,6 +186,20 @@ class Keystore {
187
186
  return;
188
187
  }
189
188
  }
189
+ static fromArraylikeToBytes(obj) {
190
+ if (Array.isArray(obj)) {
191
+ return new Uint8Array(obj);
192
+ }
193
+ const bytes = [];
194
+ let index = 0;
195
+ let lastElement = obj[index];
196
+ while (lastElement !== undefined) {
197
+ bytes.push(lastElement);
198
+ index += 1;
199
+ lastElement = obj[index];
200
+ }
201
+ return new Uint8Array(bytes);
202
+ }
190
203
  // follows nwaku implementation
191
204
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
192
205
  static computeMembershipHash(info) {
@@ -197,16 +210,17 @@ class Keystore {
197
210
  static fromIdentityToBytes(options) {
198
211
  return utf8ToBytes(JSON.stringify({
199
212
  treeIndex: options.membership.treeIndex,
200
- identityCredential: [
201
- Array.from(options.identity.IDTrapdoor),
202
- Array.from(options.identity.IDNullifier),
203
- Array.from(options.identity.IDSecretHash),
204
- Array.from(options.identity.IDCommitment)
205
- ],
213
+ identityCredential: {
214
+ idCommitment: Array.from(options.identity.IDCommitment),
215
+ idNullifier: Array.from(options.identity.IDNullifier),
216
+ idSecretHash: Array.from(options.identity.IDSecretHash),
217
+ idTrapdoor: Array.from(options.identity.IDTrapdoor)
218
+ },
206
219
  membershipContract: {
207
220
  chainId: options.membership.chainId,
208
221
  address: options.membership.address
209
- }
222
+ },
223
+ userMessageLimit: options.membership.rateLimit
210
224
  }));
211
225
  }
212
226
  }
@@ -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, rateLimit } = 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: 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()).toString();
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
  }
@@ -189,32 +67,44 @@ class RLNInstance {
189
67
  return createRLNEncoder({
190
68
  encoder: createEncoder(options),
191
69
  rlnInstance: this,
192
- index: parseInt(credentials.membership.treeIndex),
70
+ index: credentials.membership.treeIndex,
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.toString();
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 };
@@ -45,8 +45,14 @@ function writeUIntLE(buf, value, offset, byteLength, noAssert) {
45
45
  * @returns BigInt
46
46
  */
47
47
  function buildBigIntFromUint8Array(array, byteOffset = 0) {
48
- const dataView = new DataView(array.buffer);
49
- return dataView.getBigUint64(byteOffset, true);
48
+ // Convert byte array to BigInt in big-endian format (to match nwaku)
49
+ let result = 0n;
50
+ // Process all 32 bytes (or the available bytes if less)
51
+ const length = Math.min(array.length - byteOffset, 32);
52
+ for (let i = 0; i < length; i++) {
53
+ result = (result << 8n) | BigInt(array[byteOffset + i]);
54
+ }
55
+ return result;
50
56
  }
51
57
  /**
52
58
  * Fills with zeros to set length
@@ -1,4 +1,4 @@
1
- import { Web3Provider } from '../../../../node_modules/@ethersproject/providers/lib.esm/web3-provider.js';
1
+ import * as providers from '@ethersproject/providers';
2
2
 
3
3
  const extractMetaMaskSigner = async () => {
4
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -7,7 +7,7 @@ const extractMetaMaskSigner = async () => {
7
7
  throw Error("Missing or invalid Ethereum provider. Please install a Web3 wallet such as MetaMask.");
8
8
  }
9
9
  await ethereum.request({ method: "eth_requestAccounts" });
10
- const provider = new Web3Provider(ethereum, "any");
10
+ const provider = new providers.Web3Provider(ethereum, "any");
11
11
  return provider.getSigner();
12
12
  };
13
13
 
@@ -8,11 +8,11 @@ import { epochIntToBytes, dateToEpoch } from './utils/epoch.js';
8
8
  class Zerokit {
9
9
  zkRLN;
10
10
  witnessCalculator;
11
- rateLimit;
12
- constructor(zkRLN, witnessCalculator, rateLimit = DEFAULT_RATE_LIMIT) {
11
+ _rateLimit;
12
+ constructor(zkRLN, witnessCalculator, _rateLimit = DEFAULT_RATE_LIMIT) {
13
13
  this.zkRLN = zkRLN;
14
14
  this.witnessCalculator = witnessCalculator;
15
- this.rateLimit = rateLimit;
15
+ this._rateLimit = _rateLimit;
16
16
  }
17
17
  get getZkRLN() {
18
18
  return this.zkRLN;
@@ -20,8 +20,8 @@ class Zerokit {
20
20
  get getWitnessCalculator() {
21
21
  return this.witnessCalculator;
22
22
  }
23
- get getRateLimit() {
24
- return this.rateLimit;
23
+ get rateLimit() {
24
+ return this._rateLimit;
25
25
  }
26
26
  generateIdentityCredentials() {
27
27
  const memKeys = generateExtendedMembershipKey(this.zkRLN); // TODO: rename this function in zerokit rln-wasm
@@ -1,6 +1,6 @@
1
1
  import { __exports as random } from '../../../../../../../_virtual/random.js';
2
2
  import '../../../../@noble/hashes/utils.js';
3
- import { __exports as utils } from '../../../../../../../_virtual/utils.js';
3
+ import { __exports as utils } from '../../../../../../../_virtual/utils2.js';
4
4
 
5
5
  Object.defineProperty(random, "__esModule", { value: true });
6
6
  random.getRandomBytes = random.getRandomBytesSync = void 0;