@waku/rln 0.1.4-d27db21.0 → 0.1.5-053bb95.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 (138) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +5 -0
  3. package/bundle/_virtual/utils.js +2 -2
  4. package/bundle/_virtual/utils2.js +2 -2
  5. package/bundle/index.js +3 -1
  6. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js +1 -1
  7. package/bundle/node_modules/@ethersproject/abi/lib.esm/interface.js +1 -1
  8. package/bundle/node_modules/@ethersproject/abstract-provider/lib.esm/index.js +1 -1
  9. package/bundle/node_modules/@ethersproject/abstract-signer/lib.esm/index.js +11 -11
  10. package/bundle/node_modules/@ethersproject/bytes/lib.esm/_version.js +1 -1
  11. package/bundle/node_modules/@ethersproject/contracts/lib.esm/index.js +7 -7
  12. package/bundle/node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js +2 -2
  13. package/bundle/node_modules/@ethersproject/hash/lib.esm/typed-data.js +2 -2
  14. package/bundle/node_modules/@ethersproject/keccak256/node_modules/js-sha3/src/sha3.js +1 -1
  15. package/bundle/node_modules/@ethersproject/logger/lib.esm/_version.js +1 -1
  16. package/bundle/node_modules/@ethersproject/properties/lib.esm/index.js +1 -1
  17. package/bundle/node_modules/@ethersproject/providers/lib.esm/base-provider.js +44 -44
  18. package/bundle/node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js +8 -8
  19. package/bundle/node_modules/@ethersproject/rlp/lib.esm/_version.js +1 -1
  20. package/bundle/node_modules/@ethersproject/transactions/lib.esm/index.js +1 -1
  21. package/bundle/node_modules/@ethersproject/web/lib.esm/geturl.js +1 -1
  22. package/bundle/node_modules/@ethersproject/web/lib.esm/index.js +2 -2
  23. package/bundle/node_modules/@multiformats/multiaddr/dist/src/multiaddr.js +1 -0
  24. package/bundle/node_modules/@noble/hashes/esm/sha3.js +1 -1
  25. package/bundle/node_modules/bn.js/lib/bn.js +1 -1
  26. package/bundle/packages/core/dist/lib/connection_manager/connection_manager.js +6 -6
  27. package/bundle/packages/rln/dist/contract/abi.js +502 -248
  28. package/bundle/packages/rln/dist/contract/constants.js +5 -9
  29. package/bundle/packages/rln/dist/contract/errors.js +62 -0
  30. package/bundle/packages/rln/dist/contract/rln_base_contract.js +347 -0
  31. package/bundle/packages/rln/dist/contract/rln_contract.js +81 -392
  32. package/bundle/packages/rln/dist/contract/types.js +9 -0
  33. package/bundle/packages/rln/dist/create.js +1 -1
  34. package/bundle/packages/rln/dist/credentials_manager.js +215 -0
  35. package/bundle/packages/rln/dist/identity.js +8 -0
  36. package/bundle/packages/rln/dist/keystore/keystore.js +20 -28
  37. package/bundle/packages/rln/dist/rln.js +56 -166
  38. package/bundle/packages/rln/dist/zerokit.js +5 -5
  39. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/checksum.js +2 -2
  40. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/cipher.js +3 -3
  41. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/class.js +4 -4
  42. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/functional.js +4 -4
  43. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/kdf.js +4 -4
  44. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/password.js +1 -1
  45. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/schema-validation-generated.js +1 -1
  46. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/schema-validation.js +1 -1
  47. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/aes.js +1 -1
  48. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/pbkdf2.js +1 -1
  49. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/random.js +2 -2
  50. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/scrypt.js +1 -1
  51. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/sha256.js +1 -1
  52. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/utils.js +3 -3
  53. package/bundle/packages/rln/node_modules/@noble/hashes/_assert.js +1 -1
  54. package/bundle/packages/rln/node_modules/@noble/hashes/_sha2.js +2 -2
  55. package/bundle/packages/rln/node_modules/@noble/hashes/_u64.js +1 -1
  56. package/bundle/packages/rln/node_modules/@noble/hashes/cryptoBrowser.js +1 -1
  57. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
  58. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
  59. package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
  60. package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
  61. package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
  62. package/bundle/packages/rln/node_modules/@noble/hashes/hmac.js +2 -2
  63. package/bundle/packages/rln/node_modules/@noble/hashes/pbkdf2.js +2 -2
  64. package/bundle/packages/rln/node_modules/@noble/hashes/scrypt.js +3 -3
  65. package/bundle/packages/rln/node_modules/@noble/hashes/sha256.js +2 -2
  66. package/bundle/packages/rln/node_modules/@noble/hashes/sha512.js +3 -3
  67. package/bundle/packages/rln/node_modules/@noble/hashes/utils.js +2 -2
  68. package/dist/.tsbuildinfo +1 -1
  69. package/dist/codec.test-utils.d.ts +36 -0
  70. package/dist/codec.test-utils.js +56 -0
  71. package/dist/codec.test-utils.js.map +1 -0
  72. package/dist/contract/abi.d.ts +21 -17
  73. package/dist/contract/abi.js +502 -248
  74. package/dist/contract/abi.js.map +1 -1
  75. package/dist/contract/constants.d.ts +23 -19
  76. package/dist/contract/constants.js +3 -3
  77. package/dist/contract/constants.js.map +1 -1
  78. package/dist/contract/errors.d.ts +30 -0
  79. package/dist/contract/errors.js +61 -0
  80. package/dist/contract/errors.js.map +1 -0
  81. package/dist/contract/rln_base_contract.d.ts +88 -0
  82. package/dist/contract/rln_base_contract.js +330 -0
  83. package/dist/contract/rln_base_contract.js.map +1 -0
  84. package/dist/contract/rln_contract.d.ts +19 -109
  85. package/dist/contract/rln_contract.js +80 -390
  86. package/dist/contract/rln_contract.js.map +1 -1
  87. package/dist/contract/test-setup.d.ts +26 -0
  88. package/dist/contract/test-setup.js +56 -0
  89. package/dist/contract/test-setup.js.map +1 -0
  90. package/dist/contract/test-utils.d.ts +39 -0
  91. package/dist/contract/test-utils.js +118 -0
  92. package/dist/contract/test-utils.js.map +1 -0
  93. package/dist/contract/types.d.ts +40 -0
  94. package/dist/contract/types.js +8 -0
  95. package/dist/contract/types.js.map +1 -0
  96. package/dist/create.js +1 -1
  97. package/dist/create.js.map +1 -1
  98. package/dist/credentials_manager.d.ts +44 -0
  99. package/dist/credentials_manager.js +197 -0
  100. package/dist/credentials_manager.js.map +1 -0
  101. package/dist/identity.d.ts +1 -0
  102. package/dist/identity.js +8 -0
  103. package/dist/identity.js.map +1 -1
  104. package/dist/index.d.ts +5 -2
  105. package/dist/index.js +4 -2
  106. package/dist/index.js.map +1 -1
  107. package/dist/keystore/keystore.d.ts +0 -1
  108. package/dist/keystore/keystore.js +20 -28
  109. package/dist/keystore/keystore.js.map +1 -1
  110. package/dist/keystore/types.d.ts +2 -1
  111. package/dist/rln.d.ts +9 -52
  112. package/dist/rln.js +54 -163
  113. package/dist/rln.js.map +1 -1
  114. package/dist/types.d.ts +27 -0
  115. package/dist/types.js +2 -0
  116. package/dist/types.js.map +1 -0
  117. package/dist/zerokit.d.ts +3 -3
  118. package/dist/zerokit.js +5 -5
  119. package/dist/zerokit.js.map +1 -1
  120. package/package.json +1 -1
  121. package/src/codec.test-utils.ts +80 -0
  122. package/src/contract/abi.ts +502 -248
  123. package/src/contract/constants.ts +3 -3
  124. package/src/contract/errors.ts +75 -0
  125. package/src/contract/rln_base_contract.ts +500 -0
  126. package/src/contract/rln_contract.ts +102 -619
  127. package/src/contract/test-setup.ts +86 -0
  128. package/src/contract/test-utils.ts +179 -0
  129. package/src/contract/types.ts +48 -0
  130. package/src/create.ts +1 -1
  131. package/src/credentials_manager.ts +282 -0
  132. package/src/identity.ts +9 -0
  133. package/src/index.ts +17 -2
  134. package/src/keystore/keystore.ts +32 -46
  135. package/src/keystore/types.ts +2 -1
  136. package/src/rln.ts +67 -258
  137. package/src/types.ts +31 -0
  138. package/src/zerokit.ts +3 -3
@@ -0,0 +1,215 @@
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 provider() {
45
+ return this.contract?.provider;
46
+ }
47
+ async start(options = {}) {
48
+ if (this.started || this.starting) {
49
+ log.info("RLNCredentialsManager already started or starting");
50
+ return;
51
+ }
52
+ log.info("Starting RLNCredentialsManager");
53
+ this.starting = true;
54
+ try {
55
+ const { credentials, keystore } = await RLNCredentialsManager.decryptCredentialsIfNeeded(options.credentials);
56
+ if (credentials) {
57
+ log.info("Credentials successfully decrypted");
58
+ }
59
+ const { signer, address, rateLimit } = await this.determineStartOptions(options, credentials);
60
+ log.info(`Using contract address: ${address}`);
61
+ if (keystore) {
62
+ this.keystore = keystore;
63
+ log.info("Using provided keystore");
64
+ }
65
+ this.credentials = credentials;
66
+ this.signer = signer;
67
+ this.contract = new RLNBaseContract({
68
+ address: address,
69
+ signer: signer,
70
+ rateLimit: rateLimit ?? this.zerokit?.rateLimit
71
+ });
72
+ log.info("RLNCredentialsManager successfully started");
73
+ this.started = true;
74
+ }
75
+ catch (error) {
76
+ log.error("Failed to start RLNCredentialsManager", error);
77
+ throw error;
78
+ }
79
+ finally {
80
+ this.starting = false;
81
+ }
82
+ }
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
+ }
122
+ }
123
+ async determineStartOptions(options, credentials) {
124
+ let chainId = credentials?.membership.chainId;
125
+ const address = credentials?.membership.address ||
126
+ options.address ||
127
+ LINEA_CONTRACT.address;
128
+ if (address === LINEA_CONTRACT.address) {
129
+ chainId = LINEA_CONTRACT.chainId;
130
+ log.info(`Using Linea contract with chainId: ${chainId}`);
131
+ }
132
+ const signer = options.signer || (await extractMetaMaskSigner());
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}`);
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
+ }
144
+ static async decryptCredentialsIfNeeded(credentials) {
145
+ if (!credentials) {
146
+ log.info("No credentials provided");
147
+ return {};
148
+ }
149
+ if ("identity" in credentials) {
150
+ log.info("Using already decrypted credentials");
151
+ return { credentials };
152
+ }
153
+ log.info("Attempting to decrypt credentials");
154
+ const keystore = Keystore.fromString(credentials.keystore);
155
+ if (!keystore) {
156
+ log.warn("Failed to create keystore from string");
157
+ return {};
158
+ }
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
+ }
187
+ }
188
+ /**
189
+ * Generates an identity credential from a seed string
190
+ * This is a pure implementation that doesn't rely on Zerokit
191
+ * @param seed A string seed to generate the identity from
192
+ * @returns IdentityCredential
193
+ */
194
+ generateSeededIdentityCredential(seed) {
195
+ log.info("Generating seeded identity credential");
196
+ // Convert the seed to bytes
197
+ const encoder = new TextEncoder();
198
+ const seedBytes = encoder.encode(seed);
199
+ // Generate deterministic values using HMAC-SHA256
200
+ // We use different context strings for each component to ensure they're different
201
+ const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
202
+ const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
203
+ // Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
204
+ const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
205
+ const idSecretHash = sha256(combinedBytes);
206
+ // Generate IDCommitment as a hash of IDSecretHash
207
+ const idCommitment = sha256(idSecretHash);
208
+ // Convert IDCommitment to BigInt
209
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
210
+ log.info("Successfully generated identity credential");
211
+ return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
212
+ }
213
+ }
214
+
215
+ 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,19 +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
- address: _.get(obj, "membershipContract.address")
180
+ address: _.get(obj, "membershipContract.address"),
181
+ rateLimit: _.get(obj, "userMessageLimit")
180
182
  }
181
183
  };
182
184
  }
@@ -185,17 +187,6 @@ class Keystore {
185
187
  return;
186
188
  }
187
189
  }
188
- static fromArraylikeToBytes(obj) {
189
- const bytes = [];
190
- let index = 0;
191
- let lastElement = obj[index];
192
- while (lastElement !== undefined) {
193
- bytes.push(lastElement);
194
- index += 1;
195
- lastElement = obj[index];
196
- }
197
- return new Uint8Array(bytes);
198
- }
199
190
  // follows nwaku implementation
200
191
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L111
201
192
  static computeMembershipHash(info) {
@@ -205,17 +196,18 @@ class Keystore {
205
196
  // https://github.com/waku-org/nwaku/blob/f05528d4be3d3c876a8b07f9bb7dfaae8aa8ec6e/waku/waku_keystore/protocol_types.nim#L98
206
197
  static fromIdentityToBytes(options) {
207
198
  return utf8ToBytes(JSON.stringify({
208
- treeIndex: options.membership.treeIndex,
209
- identityCredential: {
210
- idCommitment: options.identity.IDCommitment,
211
- idNullifier: options.identity.IDNullifier,
212
- idSecretHash: options.identity.IDSecretHash,
213
- idTrapdoor: options.identity.IDTrapdoor
214
- },
215
199
  membershipContract: {
216
200
  chainId: options.membership.chainId,
217
201
  address: options.membership.address
218
- }
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
219
211
  }));
220
212
  }
221
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 { DEFAULT_RATE_LIMIT, SEPOLIA_CONTRACT } 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
- SEPOLIA_CONTRACT.address;
131
- if (address === SEPOLIA_CONTRACT.address) {
132
- chainId = SEPOLIA_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 };
@@ -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
@@ -14,7 +14,7 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr
14
14
  });
15
15
  };
16
16
  Object.defineProperty(checksum$1, "__esModule", { value: true });
17
- checksum$1.verifyChecksum = checksum$1.checksum = checksum$1.defaultSha256Module = undefined;
17
+ checksum$1.verifyChecksum = checksum$1.checksum = checksum$1.defaultSha256Module = void 0;
18
18
  const sha256_1 = sha256;
19
19
  const utils_1 = utilsExports;
20
20
  // default checksum configuration
@@ -38,7 +38,7 @@ function checksum(mod, key, ciphertext) {
38
38
  }
39
39
  checksum$1.checksum = checksum;
40
40
  function verifyChecksum(mod, key, ciphertext) {
41
- return __awaiter(this, undefined, undefined, function* () {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
42
  if (mod.function === "sha256") {
43
43
  return utils_1.equalsBytes(utils_1.hexToBytes(mod.message), sha256_1.sha256(checksumData(key, ciphertext)));
44
44
  }
@@ -16,7 +16,7 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr
16
16
  });
17
17
  };
18
18
  Object.defineProperty(cipher, "__esModule", { value: true });
19
- var cipherDecrypt_1 = cipher.cipherDecrypt = cipher.cipherEncrypt = cipher.defaultAes128CtrModule = undefined;
19
+ var cipherDecrypt_1 = cipher.cipherDecrypt = cipher.cipherEncrypt = cipher.defaultAes128CtrModule = void 0;
20
20
  const random_1 = random;
21
21
  const aes_1 = aes;
22
22
  const utils_1 = utilsExports;
@@ -30,7 +30,7 @@ function defaultAes128CtrModule() {
30
30
  }
31
31
  cipher.defaultAes128CtrModule = defaultAes128CtrModule;
32
32
  function cipherEncrypt(mod, key, data) {
33
- return __awaiter(this, undefined, undefined, function* () {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
34
  if (mod.function === "aes-128-ctr") {
35
35
  try {
36
36
  return yield aes_1.encrypt(data, key, utils_1.hexToBytes(mod.params.iv), mod.function, false);
@@ -46,7 +46,7 @@ function cipherEncrypt(mod, key, data) {
46
46
  }
47
47
  cipher.cipherEncrypt = cipherEncrypt;
48
48
  function cipherDecrypt(mod, key) {
49
- return __awaiter(this, undefined, undefined, function* () {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
50
  if (mod.function === "aes-128-ctr") {
51
51
  try {
52
52
  return yield aes_1.decrypt(utils_1.hexToBytes(mod.message), key, utils_1.hexToBytes(mod.params.iv), mod.function, false);
@@ -21,7 +21,7 @@ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisAr
21
21
  });
22
22
  };
23
23
  Object.defineProperty(_class, "__esModule", { value: true });
24
- _class.Keystore = undefined;
24
+ _class.Keystore = void 0;
25
25
  const kdf_1 = kdf;
26
26
  const checksum_1 = checksum;
27
27
  const cipher_1 = cipher;
@@ -47,7 +47,7 @@ class Keystore {
47
47
  * Create a new Keystore object
48
48
  */
49
49
  static create(password, secret, pubkey, path, description = null, kdfMod = kdf_1.defaultPbkdfModule(), checksumMod = checksum_1.defaultSha256Module(), cipherMod = cipher_1.defaultAes128CtrModule()) {
50
- return __awaiter(this, undefined, undefined, function* () {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
51
  const obj = yield functional_1.create(password, secret, pubkey, path, description, kdfMod, checksumMod, cipherMod);
52
52
  return new Keystore(obj);
53
53
  });
@@ -69,7 +69,7 @@ class Keystore {
69
69
  * Decrypt a keystore, returns the secret key or throws on invalid password
70
70
  */
71
71
  decrypt(password) {
72
- return __awaiter(this, undefined, undefined, function* () {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
73
  return functional_1.decrypt(this, password);
74
74
  });
75
75
  }
@@ -77,7 +77,7 @@ class Keystore {
77
77
  * Verify the password as correct or not
78
78
  */
79
79
  verifyPassword(password) {
80
- return __awaiter(this, undefined, undefined, function* () {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
81
  return functional_1.verifyPassword(this, password);
82
82
  });
83
83
  }