/
Synchronizer.ts
1360 lines (1285 loc) · 43.2 KB
/
Synchronizer.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EventEmitter } from 'events'
import { DB, TransactionDB } from 'anondb'
import { ethers } from 'ethers'
import { IncrementalMerkleTree, MAX_EPOCH } from '@unirep/utils'
import UNIREP_ABI from '@unirep/contracts/abi/Unirep.json'
import { schema } from './schema'
import { nanoid } from 'nanoid'
// TODO: consolidate these into 'anondb' index
import { constructSchema } from 'anondb/types'
import { MemoryConnector } from 'anondb/web'
import AsyncLock from 'async-lock'
/**
* The type of data to be processed in an event handler.
*/
type EventHandlerArgs = {
event: ethers.Event
decodedData: { [key: string]: any }
db: TransactionDB
}
/**
* The settings of an attester.
*/
type AttesterSetting = {
startTimestamp: number
epochLength: number
}
/**
* Turn either a decimal or hex string to a decimal string.
* @param content A `bigint`, `string` or `number` type data.
* @returns A decimal string.
*/
export function toDecString(content: bigint | string | number) {
return BigInt(content).toString()
}
/**
* The synchronizer is used to construct the Unirep state. After events are emitted from the Unirep contract,
* the synchronizer will verify the events and then save the states.
* @example
* ```ts
* import { Synchronizer } from '@unirep/core'
*
* const state = new Synchronizer({
* unirepAddress: '0xaabbccaabbccaabbccaabbccaabbccaabbccaaaa',
* provider, // an ethers.js provider
* })
*
* // start the synchronizer deamon
* await state.start()
* await state.waitForSync()
*
* // stop the synchronizer deamon
* state.stop()
* ```
*/
export class Synchronizer extends EventEmitter {
/**
* @private
* The database object.
*/
private _db: DB
/**
* @private
* The provider which is connected in the synchronizer.
*/
private _provider: ethers.providers.Provider
/**
* @private
* The UniRep smart contract object which is connected in the synchronizer.
*/
private _unirepContract: ethers.Contract
/**
* @private
* The array of attester IDs which are synchronized in the synchronizer.
*/
private _attesterId: bigint[] = []
/**
* @private
* The circuits settings.
*/
private _settings: any
/**
* @private
* The settings of attesters. There are `startTimestamp` and `epochLength` of each attester.
*/
private _attesterSettings: { [key: string]: AttesterSetting } = {}
/**
* @protected
* The default zero [state tree](https://developer.unirep.io/docs/protocol/trees#state-tree) leaf.
*/
protected defaultStateTreeLeaf: bigint = BigInt(0)
/**
* @protected
* The default zero [epoch tree](https://developer.unirep.io/docs/protocol/trees#epoch-tree) leaf.
*/
protected defaultEpochTreeLeaf: bigint = BigInt(0)
/**
* @private
* Indicates if the synchronizer is to sync with all Unirep attesters.
*/
private _syncAll = false
/**
* @private
* The mapping of the event name and its handler
*/
private _eventHandlers: any
/**
* @private
* The mapping of a contract address and its event filters.
*/
private _eventFilters: any
/**
* @private
* The id of the poll event.
*/
private pollId: string | null = null
/**
* How frequently the synchronizer will poll the blockchain for new events (specified in milliseconds). Default: `5000`
*/
public pollRate: number = 5000
/**
* How many blocks the synchronizer will query on each poll. Default: `100000`
*/
public blockRate: number = 10000
/**
* Allow passing the genesis block as the starting block for querying events
*/
private _genesisBlock: number = 0
/**
* @private
* Check if a setup is completed or not.
*/
private setupComplete = false
/**
* @private
* If a setup is not completed, there will be a setup promise.
*/
private setupPromise: any
/**
* @private
* Lock on poll event.
*/
private lock = new AsyncLock()
/**
* @private
* Load events promises.
*/
private promises: any[] = []
/**
* @private
* Unprocessed events.
*/
private _blocks: any[] = []
/**
* @private
* The latest completed block number.
*/
private _blockEnd: Number = 0
constructor(config: {
db?: DB
attesterId?: bigint | bigint[]
provider: ethers.providers.Provider
unirepAddress: string
genesisBlock?: number
}) {
super()
const { db, unirepAddress, provider, attesterId, genesisBlock } = config
if (Array.isArray(attesterId)) {
// multiple attesters
this._attesterId = attesterId.map((a) => BigInt(a))
} else if (!!attesterId) {
// single attester
this._attesterId = [BigInt(attesterId)]
} else if (!attesterId) {
this._syncAll = true
}
this._db = db ?? new MemoryConnector(constructSchema(schema))
this._unirepContract = new ethers.Contract(
unirepAddress,
UNIREP_ABI,
provider
)
this._provider = provider
this._genesisBlock = genesisBlock ?? 0
this._settings = {
stateTreeDepth: 0,
epochTreeDepth: 0,
historyTreeDepth: 0,
numEpochKeyNoncePerEpoch: 0,
epochLength: 0,
fieldCount: 0,
sumFieldCount: 0,
replNonceBits: 0,
replFieldBits: 0,
}
this.setup().then(() => (this.setupComplete = true))
}
private buildEventHandlers() {
const allEventNames = {} as any
this._eventHandlers = Object.keys(this.contracts).reduce(
(acc, address) => {
// build _eventHandlers and decodeData functions
const { contract, eventNames } = this.contracts[address]
const handlers = {}
for (const name of eventNames) {
if (allEventNames[name]) {
throw new Error(
`duplicate event name registered "${name}"`
)
}
allEventNames[name] = true
const topic = (contract.filters[name] as any)().topics[0]
const handlerName = `handle${name}`
if (typeof this[handlerName] !== 'function') {
throw new Error(
`No handler for event ${name} expected property "${handlerName}" to exist and be a function`
)
}
// set this up here to avoid re-binding on every call
const handler = this[`handle${name}`].bind(this)
handlers[topic] = ({ event, ...args }: any) => {
const decodedData = contract.interface.decodeEventLog(
name,
event.data,
event.topics
)
// call the handler with the event and decodedData
return handler({ decodedData, event, ...args })
.then((r) => {
if (r) {
this.emit(name, { decodedData, event })
}
return r
})
.catch((err) => {
console.log(`${name} handler error`)
throw err
})
// uncomment this to debug
// console.log(name, decodedData)
}
}
return {
...acc,
...handlers,
}
},
{}
)
this._eventFilters = Object.keys(this.contracts).reduce(
(acc, address) => {
const { contract, eventNames } = this.contracts[address]
const filter = {
address,
topics: [
// don't spread here, it should be a nested array
eventNames.map(
(name) =>
(contract.filters[name] as any)().topics[0]
),
],
}
return {
...acc,
[address]: filter,
}
},
{}
)
}
/**
* Read the database object.
*/
get db(): DB {
return this._db
}
/**
* Read the provider which is connected in the synchronizer.
*/
get provider(): ethers.providers.Provider {
return this._provider
}
/**
* Read the UniRep smart contract object which is connected in the synchronizer.
*/
get unirepContract(): ethers.Contract {
return this._unirepContract
}
/**
* Read the settings of the UniRep smart contract.
*/
get settings() {
return this._settings
}
/**
* Read the genesis block of the provider environment.
*/
get genesisBlock() {
return this._genesisBlock
}
/**
* The default attester ID that is set when constructed.
* If there is a list of attester IDs, then the first one will be the default attester ID.
* If no attester ID is given during construction, all attesters will be synchronized and the default `attesterId` will be `BigInt(0)`.
*
* :::caution
* The default attester ID should be checked carefully while synchronizing more than one attester.
* The default attester ID can be changed with [setAttesterId](#setattesterid).
* :::
*/
get attesterId() {
if (this._attesterId.length === 0) return BigInt(0)
return this._attesterId[0]
}
get attestersOrClauses() {
const orClauses = [] as any[]
for (let id = 0; id < this._attesterId.length; id++) {
orClauses.push({
attesterId: toDecString(this._attesterId[id]),
})
}
return orClauses
}
/**
* Change default [attesterId](#attesterid) to another attester ID.
* It will fail if an `attesterId` is not synchronized during construction.
* @param attesterId The default attester Id to be set.
*/
setAttesterId(attesterId: string | bigint) {
const index = this._attesterId.indexOf(BigInt(attesterId))
if (index === -1) {
throw new Error(
`@unirep/core:Synchronizer: attester ID ${attesterId.toString()} is not synchronized`
)
}
;[this._attesterId[0], this._attesterId[index]] = [
this._attesterId[index],
this._attesterId[0],
]
}
/**
* Check if attester events are synchronized in this synchronizer.
* @param attesterId The queried attester ID.
* @returns True if the attester events are synced, false otherwise.
*/
attesterExist(attesterId: string | bigint) {
return this._attesterId.indexOf(BigInt(attesterId)) !== -1
}
/**
* Check if attester events are synchronized in this synchronizer. It will throw an error if the attester is not synchronized.
* @param attesterId The queried attester ID.
*/
checkAttesterId(attesterId: string | bigint) {
if (this._attesterId.length === 0) {
throw new Error(
`@unirep/core:Synchronizer: no attester ID is synchronized`
)
}
if (!this.attesterExist(attesterId)) {
throw new Error(
`@unirep/core:Synchronizer: attester ID ${attesterId.toString()} is not synchronized`
)
}
}
/**
* Run setup promises.
* @returns Setup promises.
*/
async setup() {
if (!this.setupPromise) {
this.setupPromise = this._setup().catch((err) => {
this.setupPromise = undefined
this.setupComplete = false
throw err
})
}
return this.setupPromise
}
/**
* Query settings from smart contract and setup event handlers.
*/
async _setup() {
if (this.setupComplete) return
const config = await this.unirepContract.config()
this.settings.stateTreeDepth = config.stateTreeDepth
this.settings.epochTreeDepth = config.epochTreeDepth
this.settings.historyTreeDepth = config.historyTreeDepth
this.settings.numEpochKeyNoncePerEpoch = config.numEpochKeyNoncePerEpoch
this.settings.fieldCount = config.fieldCount
this.settings.sumFieldCount = config.sumFieldCount
this.settings.replNonceBits = config.replNonceBits
this.settings.replFieldBits = config.replFieldBits
this.buildEventHandlers()
await this._findStartBlock()
this.setupComplete = true
}
/**
* Find the attester's genesis block in the Unirep smart contract.
* Then store the `startTimestamp` and `epochLength` in database and in the memory.
*/
private async _findStartBlock() {
// look for the first attesterSignUp event
// no events could be emitted before this
const filter = this.unirepContract.filters.AttesterSignedUp()
if (!this._syncAll && this._attesterId.length) {
filter.topics?.push([
...this._attesterId.map(
(n) => '0x' + n.toString(16).padStart(64, '0')
),
])
}
const events = await this.unirepContract.queryFilter(
filter,
this._genesisBlock
)
if (events.length === 0) {
throw new Error(
`@unirep/core:Synchronizer: failed to fetch genesis event`
)
}
await this._db.transaction(async (db) => {
for (let event of events) {
const decodedData =
this.unirepContract.interface.decodeEventLog(
'AttesterSignedUp',
event.data,
event.topics
)
const { timestamp, epochLength, attesterId } = decodedData
this._attesterSettings[toDecString(attesterId)] = {
startTimestamp: Number(timestamp),
epochLength: Number(epochLength),
}
if (
this._syncAll &&
!this.attesterExist(attesterId) &&
BigInt(attesterId) !== BigInt(0)
) {
this._attesterId.push(BigInt(attesterId))
}
const syncStartBlock = event.blockNumber - 1
db.upsert('SynchronizerState', {
where: {
attesterId: toDecString(attesterId),
},
create: {
attesterId: toDecString(attesterId),
latestCompleteBlock: syncStartBlock,
},
update: {},
})
}
})
}
/**
* Start the synchronizer daemon.
* Start polling the blockchain for new events. If we're behind the HEAD block we'll poll many times quickly
*/
async start() {
await this.setup()
;(async () => {
const pollId = nanoid()
this.pollId = pollId
const minBackoff = 128
let backoff = minBackoff
for (;;) {
// poll repeatedly until we're up to date
try {
await this.loadBlocks(this.blockRate)
} catch (err) {
console.error(`--- unable to load blocks`)
console.error(err)
console.error(`---`)
}
try {
const { complete } = await this.poll()
if (complete) break
backoff = Math.max(backoff / 2, minBackoff)
} catch (err) {
backoff *= 2
console.error(`--- unirep poll failed`)
console.error(err)
console.error(`---`)
}
await new Promise((r) => setTimeout(r, backoff))
if (pollId != this.pollId) break
}
for (;;) {
await this.loadBlocks(this.blockRate)
await new Promise((r) => setTimeout(r, this.pollRate))
if (pollId != this.pollId) break
await this.poll().catch((err) => {
console.error(`--- unirep poll failed`)
console.error(err)
console.error(`---`)
})
}
})()
}
/**
* Stop synchronizing with Unirep contract.
*/
stop() {
this.pollId = null
}
/**
* Manually poll for new events.
* Returns a boolean indicating whether the synchronizer has synced to the head of the blockchain.
*/
async poll(): Promise<{ complete: boolean }> {
return this.lock.acquire('poll', () => this._poll())
}
/**
* @private
* Execute polling events and processing events.
*/
private async _poll(): Promise<{ complete: boolean }> {
if (!this.setupComplete) {
console.warn(
'@unirep/core:Synchronizer: polled before setup, nooping'
)
return { complete: false }
}
this.emit('pollStart')
const state = await this._db.findOne('SynchronizerState', {
where: {
OR: this.attestersOrClauses,
},
orderBy: {
latestCompleteBlock: 'asc',
},
})
const latestBlock = await this.provider.getBlockNumber()
const newEvents = this._blocks
this._blocks = []
// filter out the events that have already been seen
const unprocessedEvents = newEvents.filter((e) => {
if (e.blockNumber === state.latestProcessedBlock) {
if (
e.transactionIndex === state.latestProcessedTransactionIndex
) {
return e.logIndex > state.latestProcessedEventIndex
}
return (
e.transactionIndex > state.latestProcessedTransactionIndex
)
}
return e.blockNumber > state.latestProcessedBlock
})
await this.processEvents(unprocessedEvents)
await this._db.update('SynchronizerState', {
where: {
OR: this.attestersOrClauses,
},
update: {
latestCompleteBlock: this._blockEnd,
},
})
return {
complete: latestBlock === this._blockEnd,
}
}
/**
* Load more events from the smart contract.
* @param n How many blocks will be loaded.
*/
async loadBlocks(n: number) {
const state = await this._db.findOne('SynchronizerState', {
where: {
OR: this.attestersOrClauses,
},
orderBy: {
latestCompleteBlock: 'asc',
},
})
const latestProcessed = state.latestCompleteBlock
const latestBlock = await this.provider.getBlockNumber()
const blockStart = latestProcessed + 1
const count = Math.ceil((latestBlock - blockStart + 1) / n)
this._blockEnd = latestBlock
if (count <= 0) return
const promises = Array.from(Array(count).keys()).map(async (_, i) => {
return this.loadNewEvents(
blockStart + n * i,
Math.min(blockStart + n * (i + 1) - 1, latestBlock)
)
})
await Promise.all(promises)
this.promises.sort((a, b) => {
return a.blockNumber - b.blockNumber
})
const tmp: any[] = []
for (const chunk of this.promises) {
if (chunk === undefined || chunk.length === 0) {
continue
}
for (const block of chunk) {
this._blocks.splice(0, 0, block)
}
}
this.promises = tmp
}
/**
* Load new event from smart contract.
* @param fromBlock From which block number.
* @param toBlock To which block number.
* @returns All events in the block range.
*/
async loadNewEvents(fromBlock: number, toBlock: number) {
const promises = [] as any[]
const minBackOff = 128
for (const address of Object.keys(this.contracts)) {
const { contract } = this.contracts[address]
const filter = this._eventFilters[address]
let backoff = minBackOff
for (;;) {
try {
const request = contract.queryFilter(
filter,
fromBlock,
toBlock
)
promises.push(request)
request.then((r) => {
this.promises.push(r)
})
break
} catch (err) {
console.error(`--- unable to load new events`)
console.error(err)
console.error(`---`)
backoff *= 2
}
await new Promise((r) => setTimeout(r, backoff))
}
}
return Promise.all(promises)
}
/**
* Overwrite this to query events in different attester addresses.
* @example
* ```ts
* export class AppSynchronizer extends Synchronizer {
* ...
* get contracts(){
* return {
* ...super.contracts,
* [this.appContract.address]: {
* contract: this.appContract,
* eventNames: [
* 'Event1',
* 'Event2',
* 'Event3',
* ...
* ]
* }
* }
* }
* ```
*/
get contracts() {
return {
[this.unirepContract.address]: {
contract: this.unirepContract,
eventNames: [
'UserSignedUp',
'UserStateTransitioned',
'Attestation',
'EpochEnded',
'StateTreeLeaf',
'EpochTreeLeaf',
'AttesterSignedUp',
'HistoryTreeLeaf',
],
},
}
}
/**
* Process events with each event handler.
* @param events The array of events will be proccessed.
*/
private async processEvents(events: ethers.Event[]) {
if (events.length === 0) return
events.sort((a: any, b: any) => {
if (a.blockNumber !== b.blockNumber) {
return a.blockNumber - b.blockNumber
}
if (a.transactionIndex !== b.transactionIndex) {
return a.transactionIndex - b.transactionIndex
}
return a.logIndex - b.logIndex
})
for (const event of events) {
try {
let success: boolean | undefined
await this._db.transaction(async (db) => {
const handler = this._eventHandlers[event.topics[0]]
if (!handler) {
throw new Error(
`@unirep/core:Synchronizer: Unrecognized event topic "${event.topics[0]}"`
)
}
success = await handler({
event,
db,
})
db.update('SynchronizerState', {
where: {
OR: this.attestersOrClauses,
},
update: {
latestProcessedBlock: +event.blockNumber,
latestProcessedTransactionIndex:
+event.transactionIndex,
latestProcessedEventIndex: +event.logIndex,
},
})
})
if (success) this.emit(event.topics[0], event)
this.emit('processedEvent', event)
} catch (err) {
console.log(
`@unirep/core:Synchronizer: Error processing event:`,
err
)
console.log(event)
throw err
}
}
}
/**
* Wait for the synchronizer to sync up to a certain block.
* By default this will wait until the current latest known block (according to the provider).
* @param blockNumber The block number to be synced to.
*/
async waitForSync(blockNumber?: number) {
const latestBlock =
blockNumber ?? (await this.unirepContract.provider.getBlockNumber())
for (;;) {
const state = await this._db.findOne('SynchronizerState', {
where: {
OR: this.attestersOrClauses,
},
orderBy: {
latestCompleteBlock: 'asc',
},
})
if (state && state.latestCompleteBlock >= latestBlock) return
await new Promise((r) => setTimeout(r, 250))
}
}
/**
* Get the latest processed epoch from the database.
*
* :::caution
* This value may mismatch the onchain value depending on synchronization status.
* :::
* @param attesterId The queried attester Id.
* @returns `{number: number, sealed: boolean}`
*/
async readCurrentEpoch(attesterId: bigint | string = this.attesterId) {
const currentEpoch = await this._db.findOne('Epoch', {
where: {
attesterId: attesterId.toString(),
},
orderBy: {
number: 'desc',
},
})
return (
currentEpoch || {
number: 0,
sealed: false,
}
)
}
/**
* Calculate the current epoch determining the amount of time since the attester registration timestamp.
* This operation is **synchronous** and does not involve any database operations.
* @param attesterId The queried attester Id.
* @returns The number of current calculated epoch.
*/
calcCurrentEpoch(attesterId: bigint | string = this.attesterId) {
this.checkAttesterId(attesterId)
const decAttesterId = toDecString(attesterId)
const timestamp = Math.floor(+new Date() / 1000)
const { startTimestamp, epochLength } =
this._attesterSettings[decAttesterId]
return Math.max(
0,
Math.floor((timestamp - startTimestamp) / epochLength)
)
}
/**
* Calculate the amount of time remaining in the current epoch. This operation is **synchronous** and does not involve any database operations.
* @param attesterId The queried attester Id.
* @returns Current calculated time to the next epoch.
*/
calcEpochRemainingTime(attesterId: bigint | string = this.attesterId) {
const timestamp = Math.floor(+new Date() / 1000)
const currentEpoch = this.calcCurrentEpoch(attesterId)
const decAttesterId = toDecString(attesterId)
const { startTimestamp, epochLength } =
this._attesterSettings[decAttesterId]
const epochEnd = startTimestamp + (currentEpoch + 1) * epochLength
return Math.max(0, epochEnd - timestamp)
}
/**
* Load the current epoch number from the blockchain.
*
* :::tip
* Use this function in test environments where the blockchain timestamp may not match the real timestamp (e.g. due to snapshot/revert patterns).
* :::
* @param attesterId The queried attester Id.
* @returns The number of current epoch on-chain.
*/
async loadCurrentEpoch(attesterId: bigint | string = this.attesterId) {
const epoch = await this.unirepContract.attesterCurrentEpoch(attesterId)
return Number(epoch)
}
/**
* Get the epoch tree root for a certain epoch.
* @param epoch The epoch to be queried.
* @param attesterId The attester to be queried.
* @returns The epoch tree root.
*/
async epochTreeRoot(
epoch: number,
attesterId: bigint | string = this.attesterId
) {
return this.unirepContract.attesterEpochRoot(attesterId, epoch)
}
/**
* Build a merkle inclusion proof for the tree from a certain epoch.
* @param epoch The epoch to be queried.
* @param leafIndex The leaf index to be queried.
* @param attesterId The attester to be queried.
* @returns The merkle proof of the epoch tree index.
*/
async epochTreeProof(
epoch: number,
leafIndex: any,
attesterId: bigint | string = this.attesterId
) {
const tree = await this.genEpochTree(epoch, attesterId)
const proof = tree.createProof(leafIndex)
return proof
}
/**
* Determine if a [nullifier](https://developer.unirep.io/docs/protocol/nullifiers) exists. All nullifiers are stored in a single mapping and expected to be globally unique.
* @param nullifier A nullifier to be queried.
* @returns True if the nullifier exists on-chain before, false otherwise.
*/
async nullifierExist(nullifier: any) {
const epochEmitted = await this.unirepContract.usedNullifiers(nullifier)
return epochEmitted
}
/**
* Build the latest state tree for a certain epoch.
* @param epoch The epoch to be queried.
* @param attesterId The attester to be queried.
* @returns The state tree.
*/
async genStateTree(
epoch: number | bigint,
attesterId: bigint | string = this.attesterId
): Promise<IncrementalMerkleTree> {
this.checkAttesterId(attesterId)
const _epoch = Number(epoch.toString())
const tree = new IncrementalMerkleTree(
this.settings.stateTreeDepth,
this.defaultStateTreeLeaf
)
const leaves = await this._db.findMany('StateTreeLeaf', {
where: {
epoch: _epoch,
attesterId: toDecString(attesterId),
},
orderBy: {
index: 'asc',
},
})
for (const leaf of leaves) {
tree.insert(leaf.hash)
}
return tree
}
/**
* Build the latest history tree for the current attester.
* @param attesterId The attester to be queried.
* @returns The history tree.
*/
async genHistoryTree(
attesterId: bigint | string = this.attesterId
): Promise<IncrementalMerkleTree> {
const tree = new IncrementalMerkleTree(this.settings.historyTreeDepth)
const _attesterId = toDecString(attesterId)
this.checkAttesterId(_attesterId)
const leaves = await this._db.findMany('HistoryTreeLeaf', {
where: {
attesterId: _attesterId,
},
orderBy: {
index: 'asc',
},
})
for (const { leaf } of leaves) {
tree.insert(leaf)
}
return tree
}
/**
* Build the latest epoch tree for a certain epoch.
* @param epoch The epoch to be queried.
* @param attesterId The attester to be queried.
* @returns The epoch tree.
*/
async genEpochTree(
epoch: number | bigint,
attesterId: bigint | string = this.attesterId
): Promise<IncrementalMerkleTree> {
this.checkAttesterId(attesterId)
const _epoch = Number(epoch.toString())
const tree = new IncrementalMerkleTree(
this.settings.epochTreeDepth,
this.defaultEpochTreeLeaf
)
const leaves = await this._db.findMany('EpochTreeLeaf', {
where: {
epoch: _epoch,
attesterId: toDecString(attesterId),
},
orderBy: {
index: 'asc',
},
})
for (const { hash } of leaves) {
tree.insert(hash)
}
return tree
}