-
Notifications
You must be signed in to change notification settings - Fork 10
/
registry.ts
277 lines (241 loc) · 10.6 KB
/
registry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { Group } from '@semaphore-protocol/group'
import { MerkleProof } from './types'
import { DEFAULT_MERKLE_TREE_DEPTH, calculateIdentityCommitment, calculateRateCommitment } from './common'
import { RLNContract } from './contract-wrapper'
import { ethers } from 'ethers'
import { WithdrawProver } from './circuit-wrapper'
export interface IRLNRegistry {
isRegistered(identityCommitment: bigint): Promise<boolean>
getMerkleRoot(): Promise<bigint>
getMessageLimit(identityCommitment: bigint): Promise<bigint>
getRateCommitment(identityCommitment: bigint): Promise<bigint>
getAllRateCommitments(): Promise<bigint[]>
generateMerkleProof(identityCommitment: bigint): Promise<MerkleProof>
register(identityCommitment: bigint, messageLimit: bigint): Promise<void>
withdraw(identitySecret: bigint): Promise<void>
releaseWithdrawal(identityCommitment: bigint): Promise<void>
slash(identitySecret: bigint, receiver?: string): Promise<void>
}
export class ContractRLNRegistry implements IRLNRegistry {
private rlnContract: RLNContract
// the withdrawProver allows user to generate withdraw proof, which is verified in the RLN contract
private withdrawProver?: WithdrawProver
private rlnIdentifier: bigint
private treeDepth: number
constructor(args: {
rlnIdentifier: bigint,
rlnContract: RLNContract,
treeDepth?: number,
withdrawWasmFilePath?: string | Uint8Array,
withdrawFinalZkeyPath?: string | Uint8Array,
}) {
this.treeDepth = args.treeDepth ? args.treeDepth : DEFAULT_MERKLE_TREE_DEPTH
this.rlnContract = args.rlnContract
this.rlnIdentifier = args.rlnIdentifier
if (args.withdrawWasmFilePath !== undefined && args.withdrawFinalZkeyPath !== undefined) {
this.withdrawProver = new WithdrawProver(args.withdrawWasmFilePath, args.withdrawFinalZkeyPath)
}
}
async getSignerAddress(): Promise<string> {
return this.rlnContract.getSignerAddress()
}
async isRegistered(identityCommitment: bigint): Promise<boolean> {
return this.rlnContract.isRegistered(identityCommitment)
}
async getMessageLimit(identityCommitment: bigint): Promise<bigint> {
const user = await this.rlnContract.getUser(identityCommitment)
if (user.userAddress === ethers.ZeroAddress) {
throw new Error('Identity commitment is not registered')
}
return user.messageLimit
}
async getRateCommitment(identityCommitment: bigint): Promise<bigint> {
const messageLimit = await this.getMessageLimit(identityCommitment)
return calculateRateCommitment(identityCommitment, messageLimit)
}
private async generateLatestGroup(): Promise<Group> {
const group = new Group(this.rlnIdentifier, this.treeDepth)
const events = await this.rlnContract.getLogs()
for (const event of events) {
if (event.name === 'MemberRegistered') {
const identityCommitment = BigInt(event.identityCommitment)
const messageLimit = BigInt(event.messageLimit)
const rateCommitment = calculateRateCommitment(identityCommitment, messageLimit)
group.addMember(rateCommitment)
} else if (event.name === 'MemberWithdrawn' || event.name === 'MemberSlashed') {
const index = event.index
group.removeMember(Number(index))
}
}
return group
}
async getAllRateCommitments(): Promise<bigint[]> {
const group = await this.generateLatestGroup()
return group.members.map((member) => BigInt(member))
}
async getMerkleRoot(): Promise<bigint> {
const group = await this.generateLatestGroup()
return BigInt(group.root)
}
/**
* Creates a Merkle Proof.
* @param identityCommitment The leaf for which Merkle proof should be created.
* @returns The Merkle proof.
*/
async generateMerkleProof(identityCommitment: bigint): Promise<MerkleProof> {
const group = await this.generateLatestGroup()
const user = await this.rlnContract.getUser(identityCommitment)
if (user.userAddress === ethers.ZeroAddress) {
throw new Error('Identity commitment is not registered')
}
const rateCommitment = calculateRateCommitment(identityCommitment, user.messageLimit)
const index = group.indexOf(rateCommitment)
if (index === -1) {
// Should only happen when a user was registered before `const user = ...` and then withdraw/slashed
// after `const user = ...`.
throw new Error('Rate commitment is not in the merkle tree')
}
return group.generateMerkleProof(index)
}
async register(identityCommitment: bigint, messageLimit: bigint): Promise<void> {
if (await this.isRegistered(identityCommitment)) {
throw new Error('Identity commitment is already registered')
}
await this.rlnContract.register(identityCommitment, messageLimit)
}
async withdraw(identitySecret: bigint): Promise<void> {
if (this.withdrawProver === undefined) {
throw new Error('Withdraw prover is not initialized')
}
const identityCommitment = calculateIdentityCommitment(identitySecret)
const user = await this.rlnContract.getUser(identityCommitment)
if (user.userAddress === ethers.ZeroAddress) {
throw new Error('Identity commitment is not registered')
}
const userAddressBigInt = BigInt(user.userAddress)
const proof = await this.withdrawProver.generateProof({
identitySecret,
address: userAddressBigInt,
})
if (identityCommitment != BigInt(proof.publicSignals[0]) || userAddressBigInt != BigInt(proof.publicSignals[1])) {
throw new Error('Withdraw proof public signals do not match')
}
await this.rlnContract.withdraw(identityCommitment, proof.proof)
}
async releaseWithdrawal(identityCommitment: bigint): Promise<void> {
if (!await this.isRegistered(identityCommitment)) {
throw new Error('Identity commitment is not registered')
}
const withdrawal = await this.rlnContract.getWithdrawal(identityCommitment)
if (withdrawal.blockNumber == BigInt(0)) {
throw new Error('Withdrawal is not initiated')
}
await this.rlnContract.release(identityCommitment)
}
async slash(identitySecret: bigint, receiver?: string): Promise<void> {
if (this.withdrawProver === undefined) {
throw new Error('Withdraw prover is not initialized')
}
const identityCommitment = calculateIdentityCommitment(identitySecret)
receiver = receiver ? receiver : await this.rlnContract.getSignerAddress()
const receiverBigInt = BigInt(receiver)
const proof = await this.withdrawProver.generateProof({
identitySecret,
address: receiverBigInt,
})
if (identityCommitment != BigInt(proof.publicSignals[0]) || receiverBigInt != BigInt(proof.publicSignals[1])) {
throw new Error('Withdraw proof public signals do not match')
}
await this.rlnContract.slash(identityCommitment, receiver, proof.proof)
}
}
export class MemoryRLNRegistry implements IRLNRegistry {
// map of identityCommitment -> messageLimit
private mapIsWithdrawing: Map<string, boolean>
private mapMessageLimit: Map<string, bigint>
private group: Group
constructor(
readonly rlnIdentifier: bigint,
readonly treeDepth: number = DEFAULT_MERKLE_TREE_DEPTH,
) {
this.mapIsWithdrawing = new Map<string, boolean>()
this.mapMessageLimit = new Map<string, bigint>()
this.group = new Group(this.rlnIdentifier, this.treeDepth)
}
async isRegistered(identityCommitment: bigint): Promise<boolean> {
const messageLimit = this.mapMessageLimit.get(identityCommitment.toString())
return messageLimit !== undefined
}
async getMerkleRoot(): Promise<bigint> {
return BigInt(this.group.root)
}
async getMessageLimit(identityCommitment: bigint): Promise<bigint> {
const messageLimit = this.mapMessageLimit.get(identityCommitment.toString())
if (messageLimit === undefined) {
throw new Error('Identity commitment is not registered')
}
return messageLimit
}
async getRateCommitment(identityCommitment: bigint): Promise<bigint> {
const messageLimit = await this.getMessageLimit(identityCommitment)
return calculateRateCommitment(identityCommitment, messageLimit)
}
async getAllRateCommitments(): Promise<bigint[]> {
return this.group.members.map((member) => BigInt(member))
}
async generateMerkleProof(identityCommitment: bigint): Promise<MerkleProof> {
const rateCommitment = await this.getRateCommitment(identityCommitment)
const index = this.group.indexOf(rateCommitment)
if (index === -1) {
// Sanity check
throw new Error('Rate commitment is not in the merkle tree. This should never happen.')
}
return this.group.generateMerkleProof(index)
}
async register(identityCommitment: bigint, messageLimit: bigint): Promise<void> {
if (await this.isRegistered(identityCommitment)) {
throw new Error('Identity commitment is already registered')
}
this.mapMessageLimit.set(identityCommitment.toString(), messageLimit)
const rateCommitment = await this.getRateCommitment(identityCommitment)
this.group.addMember(rateCommitment)
}
async withdraw(identitySecret: bigint): Promise<void> {
const identityCommitment = calculateIdentityCommitment(identitySecret)
if (!await this.isRegistered(identityCommitment)) {
throw new Error('Identity commitment is not registered')
}
const isWithdrawing = this.mapIsWithdrawing.get(identityCommitment.toString())
if (isWithdrawing !== undefined) {
throw new Error('Identity is already withdrawing')
}
this.mapIsWithdrawing.set(identityCommitment.toString(), true)
}
async releaseWithdrawal(identityCommitment: bigint): Promise<void> {
const rateCommitment = await this.getRateCommitment(identityCommitment)
const index = this.group.indexOf(rateCommitment)
if (index === -1) {
// Sanity check
throw new Error('Rate commitment is not in the merkle tree. This should never happen')
}
const isWithdrawing = this.mapIsWithdrawing.get(identityCommitment.toString())
if (isWithdrawing === undefined) {
throw new Error('Identity is not withdrawing')
}
this.mapIsWithdrawing.delete(identityCommitment.toString())
this.mapMessageLimit.delete(identityCommitment.toString())
this.group.removeMember(index)
}
async slash(identitySecret: bigint, _?: string): Promise<void> {
const identityCommitment = calculateIdentityCommitment(identitySecret)
const rateCommitment = await this.getRateCommitment(identityCommitment)
const index = this.group.indexOf(rateCommitment)
if (index === -1) {
// Sanity check
throw new Error('Rate commitment is not in the merkle tree. This should never happen')
}
this.mapIsWithdrawing.delete(identityCommitment.toString())
this.mapMessageLimit.delete(identityCommitment.toString())
this.group.removeMember(index)
}
}