@waku/rln 0.1.5-76f86de.0 → 0.1.5-ad0e277.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.
- package/bundle/index.js +2 -0
- package/bundle/packages/rln/dist/contract/constants.js +1 -1
- package/bundle/packages/rln/dist/contract/rln_contract.js +8 -8
- package/bundle/packages/rln/dist/contract/rln_light_contract.js +477 -0
- package/bundle/packages/rln/dist/identity.js +8 -0
- package/bundle/packages/rln/dist/keystore/keystore.js +19 -28
- package/bundle/packages/rln/dist/rln.js +4 -4
- package/bundle/packages/rln/dist/rln_light.js +149 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/contract/constants.d.ts +1 -1
- package/dist/contract/constants.js +1 -1
- package/dist/contract/constants.js.map +1 -1
- package/dist/contract/rln_contract.js +8 -8
- package/dist/contract/rln_contract.js.map +1 -1
- package/dist/contract/rln_light_contract.d.ts +124 -0
- package/dist/contract/rln_light_contract.js +460 -0
- package/dist/contract/rln_light_contract.js.map +1 -0
- package/dist/contract/test-utils.js +1 -1
- package/dist/contract/test-utils.js.map +1 -1
- package/dist/identity.d.ts +1 -0
- package/dist/identity.js +8 -0
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/keystore/keystore.d.ts +0 -1
- package/dist/keystore/keystore.js +19 -28
- package/dist/keystore/keystore.js.map +1 -1
- package/dist/keystore/types.d.ts +1 -1
- package/dist/rln.js +4 -4
- package/dist/rln.js.map +1 -1
- package/dist/rln_light.d.ts +64 -0
- package/dist/rln_light.js +144 -0
- package/dist/rln_light.js.map +1 -0
- package/package.json +1 -1
- package/src/contract/constants.ts +1 -1
- package/src/contract/rln_contract.ts +8 -8
- package/src/contract/rln_light_contract.ts +725 -0
- package/src/contract/test-utils.ts +1 -1
- package/src/identity.ts +9 -0
- package/src/index.ts +4 -0
- package/src/keystore/keystore.ts +31 -46
- package/src/keystore/types.ts +1 -1
- package/src/rln.ts +4 -4
- package/src/rln_light.ts +235 -0
package/bundle/index.js
CHANGED
@@ -2,11 +2,13 @@ export { RLNDecoder, RLNEncoder } from './packages/rln/dist/codec.js';
|
|
2
2
|
export { RLN_ABI } from './packages/rln/dist/contract/abi.js';
|
3
3
|
export { RLNContract } from './packages/rln/dist/contract/rln_contract.js';
|
4
4
|
export { LINEA_CONTRACT } from './packages/rln/dist/contract/constants.js';
|
5
|
+
export { RLNLightContract } from './packages/rln/dist/contract/rln_light_contract.js';
|
5
6
|
export { createRLN } from './packages/rln/dist/create.js';
|
6
7
|
export { IdentityCredential } from './packages/rln/dist/identity.js';
|
7
8
|
export { Keystore } from './packages/rln/dist/keystore/keystore.js';
|
8
9
|
export { Proof } from './packages/rln/dist/proof.js';
|
9
10
|
export { RLNInstance } from './packages/rln/dist/rln.js';
|
11
|
+
export { RLNLightInstance } from './packages/rln/dist/rln_light.js';
|
10
12
|
export { MerkleRootTracker } from './packages/rln/dist/root_tracker.js';
|
11
13
|
export { extractMetaMaskSigner } from './packages/rln/dist/utils/metamask.js';
|
12
14
|
import './packages/rln/dist/utils/epoch.js';
|
@@ -84,7 +84,7 @@ class RLNContract {
|
|
84
84
|
*/
|
85
85
|
async getMinRateLimit() {
|
86
86
|
const minRate = await this.contract.minMembershipRateLimit();
|
87
|
-
return minRate.toNumber();
|
87
|
+
return BigNumber.from(minRate).toNumber();
|
88
88
|
}
|
89
89
|
/**
|
90
90
|
* Gets the maximum allowed rate limit from the contract
|
@@ -92,7 +92,7 @@ class RLNContract {
|
|
92
92
|
*/
|
93
93
|
async getMaxRateLimit() {
|
94
94
|
const maxRate = await this.contract.maxMembershipRateLimit();
|
95
|
-
return maxRate.toNumber();
|
95
|
+
return BigNumber.from(maxRate).toNumber();
|
96
96
|
}
|
97
97
|
/**
|
98
98
|
* Gets the maximum total rate limit across all memberships
|
@@ -300,13 +300,13 @@ class RLNContract {
|
|
300
300
|
`and rate limit ${decodedData.membershipRateLimit}`);
|
301
301
|
const network = await this.contract.provider.getNetwork();
|
302
302
|
const address = this.contract.address;
|
303
|
-
const membershipId =
|
303
|
+
const membershipId = decodedData.index.toString();
|
304
304
|
return {
|
305
305
|
identity,
|
306
306
|
membership: {
|
307
307
|
address,
|
308
|
-
treeIndex: membershipId,
|
309
|
-
chainId: network.chainId,
|
308
|
+
treeIndex: parseInt(membershipId),
|
309
|
+
chainId: network.chainId.toString(),
|
310
310
|
rateLimit: decodedData.membershipRateLimit.toNumber()
|
311
311
|
}
|
312
312
|
};
|
@@ -380,13 +380,13 @@ class RLNContract {
|
|
380
380
|
`Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`);
|
381
381
|
const network = await this.contract.provider.getNetwork();
|
382
382
|
const address = this.contract.address;
|
383
|
-
const membershipId =
|
383
|
+
const membershipId = decodedData.index.toString();
|
384
384
|
return {
|
385
385
|
identity,
|
386
386
|
membership: {
|
387
387
|
address,
|
388
|
-
treeIndex: membershipId,
|
389
|
-
chainId: network.chainId,
|
388
|
+
treeIndex: parseInt(membershipId),
|
389
|
+
chainId: network.chainId.toString(),
|
390
390
|
rateLimit: decodedData.membershipRateLimit.toNumber()
|
391
391
|
}
|
392
392
|
};
|
@@ -0,0 +1,477 @@
|
|
1
|
+
import '../../../interfaces/dist/protocols.js';
|
2
|
+
import '../../../interfaces/dist/connection_manager.js';
|
3
|
+
import '../../../interfaces/dist/health_indicator.js';
|
4
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base10.js';
|
5
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base16.js';
|
6
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base2.js';
|
7
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base256emoji.js';
|
8
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base32.js';
|
9
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base36.js';
|
10
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base58.js';
|
11
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base64.js';
|
12
|
+
import '../../../../node_modules/multiformats/dist/src/bases/base8.js';
|
13
|
+
import '../../../../node_modules/multiformats/dist/src/bases/identity.js';
|
14
|
+
import '../../../../node_modules/multiformats/dist/src/codecs/json.js';
|
15
|
+
import { Logger } from '../../../utils/dist/logger/index.js';
|
16
|
+
import { RLN_ABI } from './abi.js';
|
17
|
+
import { DEFAULT_RATE_LIMIT, RATE_LIMIT_PARAMS } from './constants.js';
|
18
|
+
import { Contract } from '../../../../node_modules/@ethersproject/contracts/lib.esm/index.js';
|
19
|
+
import { BigNumber } from '../../../../node_modules/@ethersproject/bignumber/lib.esm/bignumber.js';
|
20
|
+
|
21
|
+
const log = new Logger("waku:rln:contract");
|
22
|
+
var MembershipState;
|
23
|
+
(function (MembershipState) {
|
24
|
+
MembershipState["Active"] = "Active";
|
25
|
+
MembershipState["GracePeriod"] = "GracePeriod";
|
26
|
+
MembershipState["Expired"] = "Expired";
|
27
|
+
MembershipState["ErasedAwaitsWithdrawal"] = "ErasedAwaitsWithdrawal";
|
28
|
+
})(MembershipState || (MembershipState = {}));
|
29
|
+
class RLNLightContract {
|
30
|
+
contract;
|
31
|
+
deployBlock;
|
32
|
+
rateLimit;
|
33
|
+
_members = new Map();
|
34
|
+
_membersFilter;
|
35
|
+
_membershipErasedFilter;
|
36
|
+
_membersExpiredFilter;
|
37
|
+
/**
|
38
|
+
* Asynchronous initializer for RLNContract.
|
39
|
+
* Allows injecting a mocked contract for testing purposes.
|
40
|
+
*/
|
41
|
+
static async init(options) {
|
42
|
+
const rlnContract = new RLNLightContract(options);
|
43
|
+
await rlnContract.fetchMembers();
|
44
|
+
rlnContract.subscribeToMembers();
|
45
|
+
return rlnContract;
|
46
|
+
}
|
47
|
+
constructor(options) {
|
48
|
+
const { address, signer, rateLimit = DEFAULT_RATE_LIMIT, contract } = options;
|
49
|
+
if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
|
50
|
+
rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
|
51
|
+
throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE} messages per epoch`);
|
52
|
+
}
|
53
|
+
this.rateLimit = rateLimit;
|
54
|
+
// Use the injected contract if provided; otherwise, instantiate a new one.
|
55
|
+
this.contract = contract || new Contract(address, RLN_ABI, signer);
|
56
|
+
// Initialize event filters
|
57
|
+
this._membersFilter = this.contract.filters.MembershipRegistered();
|
58
|
+
this._membershipErasedFilter = this.contract.filters.MembershipErased();
|
59
|
+
this._membersExpiredFilter = this.contract.filters.MembershipExpired();
|
60
|
+
}
|
61
|
+
/**
|
62
|
+
* Gets the current rate limit for this contract instance
|
63
|
+
*/
|
64
|
+
getRateLimit() {
|
65
|
+
return this.rateLimit;
|
66
|
+
}
|
67
|
+
/**
|
68
|
+
* Gets the contract address
|
69
|
+
*/
|
70
|
+
get address() {
|
71
|
+
return this.contract.address;
|
72
|
+
}
|
73
|
+
/**
|
74
|
+
* Gets the contract provider
|
75
|
+
*/
|
76
|
+
get provider() {
|
77
|
+
return this.contract.provider;
|
78
|
+
}
|
79
|
+
/**
|
80
|
+
* Gets the minimum allowed rate limit from the contract
|
81
|
+
* @returns Promise<number> The minimum rate limit in messages per epoch
|
82
|
+
*/
|
83
|
+
async getMinRateLimit() {
|
84
|
+
const minRate = await this.contract.minMembershipRateLimit();
|
85
|
+
return BigNumber.from(minRate).toNumber();
|
86
|
+
}
|
87
|
+
/**
|
88
|
+
* Gets the maximum allowed rate limit from the contract
|
89
|
+
* @returns Promise<number> The maximum rate limit in messages per epoch
|
90
|
+
*/
|
91
|
+
async getMaxRateLimit() {
|
92
|
+
const maxRate = await this.contract.maxMembershipRateLimit();
|
93
|
+
return BigNumber.from(maxRate).toNumber();
|
94
|
+
}
|
95
|
+
/**
|
96
|
+
* Gets the maximum total rate limit across all memberships
|
97
|
+
* @returns Promise<number> The maximum total rate limit in messages per epoch
|
98
|
+
*/
|
99
|
+
async getMaxTotalRateLimit() {
|
100
|
+
const maxTotalRate = await this.contract.maxTotalRateLimit();
|
101
|
+
return BigNumber.from(maxTotalRate).toNumber();
|
102
|
+
}
|
103
|
+
/**
|
104
|
+
* Gets the current total rate limit usage across all memberships
|
105
|
+
* @returns Promise<number> The current total rate limit usage in messages per epoch
|
106
|
+
*/
|
107
|
+
async getCurrentTotalRateLimit() {
|
108
|
+
const currentTotal = await this.contract.currentTotalRateLimit();
|
109
|
+
return BigNumber.from(currentTotal).toNumber();
|
110
|
+
}
|
111
|
+
/**
|
112
|
+
* Gets the remaining available total rate limit that can be allocated
|
113
|
+
* @returns Promise<number> The remaining rate limit that can be allocated
|
114
|
+
*/
|
115
|
+
async getRemainingTotalRateLimit() {
|
116
|
+
const [maxTotal, currentTotal] = await Promise.all([
|
117
|
+
this.contract.maxTotalRateLimit(),
|
118
|
+
this.contract.currentTotalRateLimit()
|
119
|
+
]);
|
120
|
+
return BigNumber.from(maxTotal)
|
121
|
+
.sub(BigNumber.from(currentTotal))
|
122
|
+
.toNumber();
|
123
|
+
}
|
124
|
+
/**
|
125
|
+
* Updates the rate limit for future registrations
|
126
|
+
* @param newRateLimit The new rate limit to use
|
127
|
+
*/
|
128
|
+
async setRateLimit(newRateLimit) {
|
129
|
+
this.rateLimit = newRateLimit;
|
130
|
+
}
|
131
|
+
get members() {
|
132
|
+
const sortedMembers = Array.from(this._members.values()).sort((left, right) => left.index.toNumber() - right.index.toNumber());
|
133
|
+
return sortedMembers;
|
134
|
+
}
|
135
|
+
get membersFilter() {
|
136
|
+
if (!this._membersFilter) {
|
137
|
+
throw Error("Members filter was not initialized.");
|
138
|
+
}
|
139
|
+
return this._membersFilter;
|
140
|
+
}
|
141
|
+
get membershipErasedFilter() {
|
142
|
+
if (!this._membershipErasedFilter) {
|
143
|
+
throw Error("MembershipErased filter was not initialized.");
|
144
|
+
}
|
145
|
+
return this._membershipErasedFilter;
|
146
|
+
}
|
147
|
+
get membersExpiredFilter() {
|
148
|
+
if (!this._membersExpiredFilter) {
|
149
|
+
throw Error("MembersExpired filter was not initialized.");
|
150
|
+
}
|
151
|
+
return this._membersExpiredFilter;
|
152
|
+
}
|
153
|
+
async fetchMembers(options = {}) {
|
154
|
+
const registeredMemberEvents = await queryFilter(this.contract, {
|
155
|
+
fromBlock: this.deployBlock,
|
156
|
+
...options,
|
157
|
+
membersFilter: this.membersFilter
|
158
|
+
});
|
159
|
+
const removedMemberEvents = await queryFilter(this.contract, {
|
160
|
+
fromBlock: this.deployBlock,
|
161
|
+
...options,
|
162
|
+
membersFilter: this.membershipErasedFilter
|
163
|
+
});
|
164
|
+
const expiredMemberEvents = await queryFilter(this.contract, {
|
165
|
+
fromBlock: this.deployBlock,
|
166
|
+
...options,
|
167
|
+
membersFilter: this.membersExpiredFilter
|
168
|
+
});
|
169
|
+
const events = [
|
170
|
+
...registeredMemberEvents,
|
171
|
+
...removedMemberEvents,
|
172
|
+
...expiredMemberEvents
|
173
|
+
];
|
174
|
+
this.processEvents(events);
|
175
|
+
}
|
176
|
+
processEvents(events) {
|
177
|
+
const toRemoveTable = new Map();
|
178
|
+
const toInsertTable = new Map();
|
179
|
+
events.forEach((evt) => {
|
180
|
+
if (!evt.args) {
|
181
|
+
return;
|
182
|
+
}
|
183
|
+
if (evt.event === "MembershipErased" ||
|
184
|
+
evt.event === "MembershipExpired") {
|
185
|
+
let index = evt.args.index;
|
186
|
+
if (!index) {
|
187
|
+
return;
|
188
|
+
}
|
189
|
+
if (typeof index === "number" || typeof index === "string") {
|
190
|
+
index = BigNumber.from(index);
|
191
|
+
}
|
192
|
+
const toRemoveVal = toRemoveTable.get(evt.blockNumber);
|
193
|
+
if (toRemoveVal != undefined) {
|
194
|
+
toRemoveVal.push(index.toNumber());
|
195
|
+
toRemoveTable.set(evt.blockNumber, toRemoveVal);
|
196
|
+
}
|
197
|
+
else {
|
198
|
+
toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
|
199
|
+
}
|
200
|
+
}
|
201
|
+
else if (evt.event === "MembershipRegistered") {
|
202
|
+
let eventsPerBlock = toInsertTable.get(evt.blockNumber);
|
203
|
+
if (eventsPerBlock == undefined) {
|
204
|
+
eventsPerBlock = [];
|
205
|
+
}
|
206
|
+
eventsPerBlock.push(evt);
|
207
|
+
toInsertTable.set(evt.blockNumber, eventsPerBlock);
|
208
|
+
}
|
209
|
+
});
|
210
|
+
}
|
211
|
+
subscribeToMembers() {
|
212
|
+
this.contract.on(this.membersFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
213
|
+
this.processEvents([event]);
|
214
|
+
});
|
215
|
+
this.contract.on(this.membershipErasedFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
216
|
+
this.processEvents([event]);
|
217
|
+
});
|
218
|
+
this.contract.on(this.membersExpiredFilter, (_idCommitment, _membershipRateLimit, _index, event) => {
|
219
|
+
this.processEvents([event]);
|
220
|
+
});
|
221
|
+
}
|
222
|
+
async registerWithIdentity(identity) {
|
223
|
+
try {
|
224
|
+
log.info(`Registering identity with rate limit: ${this.rateLimit} messages/epoch`);
|
225
|
+
// Check if the ID commitment is already registered
|
226
|
+
const existingIndex = await this.getMemberIndex(identity.IDCommitmentBigInt.toString());
|
227
|
+
if (existingIndex) {
|
228
|
+
throw new Error(`ID commitment is already registered with index ${existingIndex}`);
|
229
|
+
}
|
230
|
+
// Check if there's enough remaining rate limit
|
231
|
+
const remainingRateLimit = await this.getRemainingTotalRateLimit();
|
232
|
+
if (remainingRateLimit < this.rateLimit) {
|
233
|
+
throw new Error(`Not enough remaining rate limit. Requested: ${this.rateLimit}, Available: ${remainingRateLimit}`);
|
234
|
+
}
|
235
|
+
const estimatedGas = await this.contract.estimateGas.register(identity.IDCommitmentBigInt, this.rateLimit, []);
|
236
|
+
const gasLimit = estimatedGas.add(10000);
|
237
|
+
const txRegisterResponse = await this.contract.register(identity.IDCommitmentBigInt, this.rateLimit, [], { gasLimit });
|
238
|
+
const txRegisterReceipt = await txRegisterResponse.wait();
|
239
|
+
if (txRegisterReceipt.status === 0) {
|
240
|
+
throw new Error("Transaction failed on-chain");
|
241
|
+
}
|
242
|
+
const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
|
243
|
+
if (!memberRegistered || !memberRegistered.args) {
|
244
|
+
log.error("Failed to register membership: No MembershipRegistered event found");
|
245
|
+
return undefined;
|
246
|
+
}
|
247
|
+
const decodedData = {
|
248
|
+
idCommitment: memberRegistered.args.idCommitment,
|
249
|
+
membershipRateLimit: memberRegistered.args.membershipRateLimit,
|
250
|
+
index: memberRegistered.args.index
|
251
|
+
};
|
252
|
+
log.info(`Successfully registered membership with index ${decodedData.index} ` +
|
253
|
+
`and rate limit ${decodedData.membershipRateLimit}`);
|
254
|
+
const network = await this.contract.provider.getNetwork();
|
255
|
+
const address = this.contract.address;
|
256
|
+
const membershipId = decodedData.index.toString();
|
257
|
+
return {
|
258
|
+
identity,
|
259
|
+
membership: {
|
260
|
+
address,
|
261
|
+
treeIndex: parseInt(membershipId),
|
262
|
+
chainId: network.chainId.toString(),
|
263
|
+
rateLimit: decodedData.membershipRateLimit.toNumber()
|
264
|
+
}
|
265
|
+
};
|
266
|
+
}
|
267
|
+
catch (error) {
|
268
|
+
if (error instanceof Error) {
|
269
|
+
const errorMessage = error.message;
|
270
|
+
log.error("registerWithIdentity - error message:", errorMessage);
|
271
|
+
log.error("registerWithIdentity - error stack:", error.stack);
|
272
|
+
// Try to extract more specific error information
|
273
|
+
if (errorMessage.includes("CannotExceedMaxTotalRateLimit")) {
|
274
|
+
throw new Error("Registration failed: Cannot exceed maximum total rate limit");
|
275
|
+
}
|
276
|
+
else if (errorMessage.includes("InvalidIdCommitment")) {
|
277
|
+
throw new Error("Registration failed: Invalid ID commitment");
|
278
|
+
}
|
279
|
+
else if (errorMessage.includes("InvalidMembershipRateLimit")) {
|
280
|
+
throw new Error("Registration failed: Invalid membership rate limit");
|
281
|
+
}
|
282
|
+
else if (errorMessage.includes("execution reverted")) {
|
283
|
+
throw new Error("Contract execution reverted. Check contract requirements.");
|
284
|
+
}
|
285
|
+
else {
|
286
|
+
throw new Error(`Error in registerWithIdentity: ${errorMessage}`);
|
287
|
+
}
|
288
|
+
}
|
289
|
+
else {
|
290
|
+
throw new Error("Unknown error in registerWithIdentity", {
|
291
|
+
cause: error
|
292
|
+
});
|
293
|
+
}
|
294
|
+
}
|
295
|
+
}
|
296
|
+
/**
|
297
|
+
* Helper method to get remaining messages in current epoch
|
298
|
+
* @param membershipId The ID of the membership to check
|
299
|
+
* @returns number of remaining messages allowed in current epoch
|
300
|
+
*/
|
301
|
+
async getRemainingMessages(membershipId) {
|
302
|
+
try {
|
303
|
+
const [startTime, , rateLimit] = await this.contract.getMembershipInfo(membershipId);
|
304
|
+
// Calculate current epoch
|
305
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
306
|
+
const epochsPassed = Math.floor((currentTime - startTime) / RATE_LIMIT_PARAMS.EPOCH_LENGTH);
|
307
|
+
const currentEpochStart = startTime + epochsPassed * RATE_LIMIT_PARAMS.EPOCH_LENGTH;
|
308
|
+
// Get message count in current epoch using contract's function
|
309
|
+
const messageCount = await this.contract.getMessageCount(membershipId, currentEpochStart);
|
310
|
+
return Math.max(0, BigNumber.from(rateLimit)
|
311
|
+
.sub(BigNumber.from(messageCount))
|
312
|
+
.toNumber());
|
313
|
+
}
|
314
|
+
catch (error) {
|
315
|
+
log.error(`Error getting remaining messages: ${error.message}`);
|
316
|
+
return 0; // Fail safe: assume no messages remaining on error
|
317
|
+
}
|
318
|
+
}
|
319
|
+
async registerWithPermitAndErase(identity, permit, idCommitmentsToErase) {
|
320
|
+
try {
|
321
|
+
log.info(`Registering identity with permit and rate limit: ${this.rateLimit} messages/epoch`);
|
322
|
+
const txRegisterResponse = await this.contract.registerWithPermit(permit.owner, permit.deadline, permit.v, permit.r, permit.s, identity.IDCommitmentBigInt, this.rateLimit, idCommitmentsToErase.map((id) => BigNumber.from(id)));
|
323
|
+
const txRegisterReceipt = await txRegisterResponse.wait();
|
324
|
+
const memberRegistered = txRegisterReceipt.events?.find((event) => event.event === "MembershipRegistered");
|
325
|
+
if (!memberRegistered || !memberRegistered.args) {
|
326
|
+
log.error("Failed to register membership with permit: No MembershipRegistered event found");
|
327
|
+
return undefined;
|
328
|
+
}
|
329
|
+
const decodedData = {
|
330
|
+
idCommitment: memberRegistered.args.idCommitment,
|
331
|
+
membershipRateLimit: memberRegistered.args.membershipRateLimit,
|
332
|
+
index: memberRegistered.args.index
|
333
|
+
};
|
334
|
+
log.info(`Successfully registered membership with permit. Index: ${decodedData.index}, ` +
|
335
|
+
`Rate limit: ${decodedData.membershipRateLimit}, Erased ${idCommitmentsToErase.length} commitments`);
|
336
|
+
const network = await this.contract.provider.getNetwork();
|
337
|
+
const address = this.contract.address;
|
338
|
+
const membershipId = decodedData.index.toString();
|
339
|
+
return {
|
340
|
+
identity,
|
341
|
+
membership: {
|
342
|
+
address,
|
343
|
+
treeIndex: parseInt(membershipId),
|
344
|
+
chainId: network.chainId.toString(),
|
345
|
+
rateLimit: decodedData.membershipRateLimit.toNumber()
|
346
|
+
}
|
347
|
+
};
|
348
|
+
}
|
349
|
+
catch (error) {
|
350
|
+
log.error(`Error in registerWithPermitAndErase: ${error.message}`);
|
351
|
+
return undefined;
|
352
|
+
}
|
353
|
+
}
|
354
|
+
async withdraw(token, holder) {
|
355
|
+
try {
|
356
|
+
const tx = await this.contract.withdraw(token, { from: holder });
|
357
|
+
await tx.wait();
|
358
|
+
}
|
359
|
+
catch (error) {
|
360
|
+
log.error(`Error in withdraw: ${error.message}`);
|
361
|
+
}
|
362
|
+
}
|
363
|
+
async getMembershipInfo(idCommitment) {
|
364
|
+
try {
|
365
|
+
const [startBlock, endBlock, rateLimit] = await this.contract.getMembershipInfo(idCommitment);
|
366
|
+
const currentBlock = await this.contract.provider.getBlockNumber();
|
367
|
+
let state;
|
368
|
+
if (currentBlock < startBlock) {
|
369
|
+
state = MembershipState.Active;
|
370
|
+
}
|
371
|
+
else if (currentBlock < endBlock) {
|
372
|
+
state = MembershipState.GracePeriod;
|
373
|
+
}
|
374
|
+
else {
|
375
|
+
state = MembershipState.Expired;
|
376
|
+
}
|
377
|
+
const index = await this.getMemberIndex(idCommitment);
|
378
|
+
if (!index)
|
379
|
+
return undefined;
|
380
|
+
return {
|
381
|
+
index,
|
382
|
+
idCommitment,
|
383
|
+
rateLimit: rateLimit.toNumber(),
|
384
|
+
startBlock: startBlock.toNumber(),
|
385
|
+
endBlock: endBlock.toNumber(),
|
386
|
+
state
|
387
|
+
};
|
388
|
+
}
|
389
|
+
catch (error) {
|
390
|
+
return undefined;
|
391
|
+
}
|
392
|
+
}
|
393
|
+
async extendMembership(idCommitment) {
|
394
|
+
return this.contract.extendMemberships([idCommitment]);
|
395
|
+
}
|
396
|
+
async eraseMembership(idCommitment, eraseFromMembershipSet = true) {
|
397
|
+
return this.contract.eraseMemberships([idCommitment], eraseFromMembershipSet);
|
398
|
+
}
|
399
|
+
async registerMembership(idCommitment, rateLimit = DEFAULT_RATE_LIMIT) {
|
400
|
+
if (rateLimit < RATE_LIMIT_PARAMS.MIN_RATE ||
|
401
|
+
rateLimit > RATE_LIMIT_PARAMS.MAX_RATE) {
|
402
|
+
throw new Error(`Rate limit must be between ${RATE_LIMIT_PARAMS.MIN_RATE} and ${RATE_LIMIT_PARAMS.MAX_RATE}`);
|
403
|
+
}
|
404
|
+
return this.contract.register(idCommitment, rateLimit, []);
|
405
|
+
}
|
406
|
+
async getMemberIndex(idCommitment) {
|
407
|
+
try {
|
408
|
+
const events = await this.contract.queryFilter(this.contract.filters.MembershipRegistered(idCommitment));
|
409
|
+
if (events.length === 0)
|
410
|
+
return undefined;
|
411
|
+
// Get the most recent registration event
|
412
|
+
const event = events[events.length - 1];
|
413
|
+
return event.args?.index;
|
414
|
+
}
|
415
|
+
catch (error) {
|
416
|
+
return undefined;
|
417
|
+
}
|
418
|
+
}
|
419
|
+
}
|
420
|
+
// These values should be tested on other networks
|
421
|
+
const FETCH_CHUNK = 5;
|
422
|
+
const BLOCK_RANGE = 3000;
|
423
|
+
async function queryFilter(contract, options) {
|
424
|
+
const { fromBlock, membersFilter, fetchRange = BLOCK_RANGE, fetchChunks = FETCH_CHUNK } = options;
|
425
|
+
if (fromBlock === undefined) {
|
426
|
+
return contract.queryFilter(membersFilter);
|
427
|
+
}
|
428
|
+
if (!contract.provider) {
|
429
|
+
throw Error("No provider found on the contract.");
|
430
|
+
}
|
431
|
+
const toBlock = await contract.provider.getBlockNumber();
|
432
|
+
if (toBlock - fromBlock < fetchRange) {
|
433
|
+
return contract.queryFilter(membersFilter, fromBlock, toBlock);
|
434
|
+
}
|
435
|
+
const events = [];
|
436
|
+
const chunks = splitToChunks(fromBlock, toBlock, fetchRange);
|
437
|
+
for (const portion of takeN(chunks, fetchChunks)) {
|
438
|
+
const promises = portion.map(([left, right]) => ignoreErrors(contract.queryFilter(membersFilter, left, right), []));
|
439
|
+
const fetchedEvents = await Promise.all(promises);
|
440
|
+
events.push(fetchedEvents.flatMap((v) => v));
|
441
|
+
}
|
442
|
+
return events.flatMap((v) => v);
|
443
|
+
}
|
444
|
+
function splitToChunks(from, to, step) {
|
445
|
+
const chunks = [];
|
446
|
+
let left = from;
|
447
|
+
while (left < to) {
|
448
|
+
const right = left + step < to ? left + step : to;
|
449
|
+
chunks.push([left, right]);
|
450
|
+
left = right;
|
451
|
+
}
|
452
|
+
return chunks;
|
453
|
+
}
|
454
|
+
function* takeN(array, size) {
|
455
|
+
let start = 0;
|
456
|
+
while (start < array.length) {
|
457
|
+
const portion = array.slice(start, start + size);
|
458
|
+
yield portion;
|
459
|
+
start += size;
|
460
|
+
}
|
461
|
+
}
|
462
|
+
async function ignoreErrors(promise, defaultValue) {
|
463
|
+
try {
|
464
|
+
return await promise;
|
465
|
+
}
|
466
|
+
catch (err) {
|
467
|
+
if (err instanceof Error) {
|
468
|
+
log.info(`Ignoring an error during query: ${err.message}`);
|
469
|
+
}
|
470
|
+
else {
|
471
|
+
log.info(`Ignoring an unknown error during query`);
|
472
|
+
}
|
473
|
+
return defaultValue;
|
474
|
+
}
|
475
|
+
}
|
476
|
+
|
477
|
+
export { MembershipState, RLNLightContract };
|
@@ -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
|
-
//
|
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, "
|
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
|
}
|