-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsync.go
More file actions
1574 lines (1384 loc) · 49.7 KB
/
sync.go
File metadata and controls
1574 lines (1384 loc) · 49.7 KB
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
package node
import (
"context"
"database/sql"
"fmt"
"github.com/pegnet/pegnet/modules/graderDelegateStake"
"math/big"
"sort"
"time"
"github.com/Factom-Asset-Tokens/factom"
"github.com/pegnet/pegnet/modules/grader"
"github.com/pegnet/pegnet/modules/graderStake"
"github.com/pegnet/pegnet/modules/opr"
"github.com/pegnet/pegnet/modules/transactionid"
"github.com/pegnet/pegnetd/config"
"github.com/pegnet/pegnetd/fat/fat2"
"github.com/pegnet/pegnetd/node/conversions"
"github.com/pegnet/pegnetd/node/pegnet"
log "github.com/sirupsen/logrus"
)
func (d *Pegnetd) GetCurrentSync() uint32 {
// Should be thread safe since we only have 1 routine writing to it
return d.Sync.Synced
}
// DBlockSync iterates through dblocks and syncs the various chains
func (d *Pegnetd) DBlockSync(ctx context.Context) {
retryPeriod := d.Config.GetDuration(config.DBlockSyncRetryPeriod)
isFirstSync := true
OuterSyncLoop:
for {
if isDone(ctx) {
return // If the user does ctl+c or something
}
// Fetch the current highest height
heights := new(factom.Heights)
err := heights.Get(nil, d.FactomClient)
if err != nil {
log.WithError(err).WithFields(log.Fields{}).Errorf("failed to fetch heights")
time.Sleep(retryPeriod)
continue // Loop will just keep retrying until factomd is reached
}
if d.Sync.Synced >= heights.DirectoryBlock {
// We are currently synced, nothing to do. If we are above it, the factomd could
// be rebooted
if d.Sync.Synced > heights.DirectoryBlock {
log.Debugf("Factom node behind. database height = %d, factom height = %d", d.Sync.Synced, heights.DirectoryBlock)
}
if isFirstSync {
isFirstSync = false
log.WithField("height", d.Sync.Synced).Info("Node is up to date")
}
time.Sleep(retryPeriod) // TODO: Should we have a separate polling period?
continue
}
var totalDur time.Duration
var iterations int
var longSync bool
if isFirstSync || heights.DirectoryBlock-d.Sync.Synced > 1 {
log.WithFields(log.Fields{
"height": d.Sync.Synced,
"syncing-to": heights.DirectoryBlock,
}).Infof("Starting sync job of %d blocks", heights.DirectoryBlock-d.Sync.Synced)
longSync = true
}
begin := time.Now()
lastReport := begin
for d.Sync.Synced < heights.DirectoryBlock {
start := time.Now()
hLog := log.WithFields(log.Fields{"height": d.Sync.Synced + 1})
if isDone(ctx) {
return
}
// start transaction for all block actions
tx, err := d.Pegnet.DB.BeginTx(ctx, nil)
if err != nil {
hLog.WithError(err).Errorf("failed to start transaction")
continue
}
////////////////////////
// Zeroing funds at Global Burn Address
// One time operation, Inserts negative balance for the burn address that used during the attack
// We need to do this before main logic because sqlite db will be locked
if d.Sync.Synced+1 == config.V20DevRewardsHeightActivation {
d.NullifyBurnAddress(ctx, tx, d.Sync.Synced+1)
}
if d.Sync.Synced+1 == config.V202EnhanceActivation {
d.NullifyBurnAddress(ctx, tx, d.Sync.Synced+1)
}
// We are not synced, so we need to iterate through the dblocks and sync them
// one by one. We can only sync our current synced height +1
// TODO: This skips the genesis block. I'm sure that is fine
if err := d.SyncBlock(ctx, tx, d.Sync.Synced+1); err != nil {
hLog.WithError(err).Errorf("failed to sync height")
time.Sleep(retryPeriod)
// If we fail, we backout to the outer loop. This allows error handling on factomd state to be a bit
// cleaner, such as a rebooted node with a different db. That node would have a new heights response.
err = tx.Rollback()
if err != nil {
// TODO evaluate if we can recover from this point or not
hLog.WithError(err).Fatal("unable to roll back transaction")
}
continue OuterSyncLoop
}
// Bump our sync, and march forward
d.Sync.Synced++
err = d.Pegnet.InsertSynced(tx, d.Sync)
if err != nil {
d.Sync.Synced--
hLog.WithError(err).Errorf("unable to update synced metadata")
err = tx.Rollback()
if err != nil {
// TODO evaluate if we can recover from this point or not
hLog.WithError(err).Fatal("unable to roll back transaction")
}
continue OuterSyncLoop
}
err = tx.Commit()
if err != nil {
d.Sync.Synced--
hLog.WithError(err).Errorf("unable to commit transaction")
err = tx.Rollback()
if err != nil {
// TODO evaluate if we can recover from this point or not
hLog.WithError(err).Fatal("unable to roll back transaction")
}
}
elapsed := time.Since(start)
hLog.WithFields(log.Fields{"took": elapsed}).Debugf("synced")
iterations++
totalDur += elapsed
// update every 15 seconds
if time.Since(lastReport) > time.Second*15 {
lastReport = time.Now()
toGo := heights.DirectoryBlock - d.Sync.Synced
avg := totalDur / time.Duration(iterations)
hLog.WithFields(log.Fields{
"avg": avg,
"left": time.Duration(toGo) * avg,
"syncing-to": heights.DirectoryBlock,
"elapsed": time.Since(begin),
}).Infof("sync stats")
}
}
isFirstSync = false
if longSync {
longSync = false
log.WithField("height", d.Sync.Synced).WithField("blocks-synced", iterations).Infof("Finished sync job")
} else if d.Sync.Synced%6 == 0 {
log.WithField("height", d.Sync.Synced).Infof("status report")
}
}
}
func (d *Pegnetd) MintTokensForBalance(ctx context.Context, tx *sql.Tx, height uint32) error {
fLog := log.WithFields(log.Fields{"height": height})
FAGlobalMintAddress, err := factom.NewFAAddress(GlobalMintAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Info("error getting mint address")
return err
}
for _, tokenSupply := range MintTotalSupplyMap {
_, err := d.Pegnet.AddToBalance(tx, &FAGlobalMintAddress, tokenSupply.Ticker, tokenSupply.Amount*1e8)
if err != nil {
fLog.WithFields(log.Fields{
"token": tokenSupply.Ticker,
"amount": tokenSupply.Amount,
"error": err,
}).Info("error minting token is failed")
return err
}
}
return nil
}
func (d *Pegnetd) NullifyMintedTokens(ctx context.Context, tx *sql.Tx, height uint32) error {
fLog := log.WithFields(log.Fields{"height": height})
FAGlobalMintAddress, err := factom.NewFAAddress(GlobalMintAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Info("error getting mint address")
return err
}
// Get all balances for the address
balances, err := d.Pegnet.SelectBalances(&FAGlobalMintAddress)
if err != nil {
fLog.WithFields(log.Fields{
"err": err,
}).Info("zeroing burn | balances retrieval failed")
}
for _, tokenSupply := range MintTotalSupplyMap {
// Substract from every issuance
ticker := tokenSupply.Ticker
value, _ := balances[ticker]
_, _, err := d.Pegnet.SubFromBalance(tx, &FAGlobalMintAddress, ticker, value) // lastInd, txErr, err
if err != nil {
fLog.WithFields(log.Fields{
"ticker": ticker,
"balance": value,
}).Info("zeroing burn | substract from balance failed")
return err
}
}
return nil
}
func (d *Pegnetd) NullifyBurnAddress(ctx context.Context, tx *sql.Tx, height uint32) error {
fLog := log.WithFields(log.Fields{"height": height})
var FAGlobalBurnAddress factom.FAAddress
var err error
if height < config.V202EnhanceActivation {
FAGlobalBurnAddress, err = factom.NewFAAddress(GlobalOldBurnAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Info("error getting burn address")
}
} else {
FAGlobalBurnAddress, err = factom.NewFAAddress(GlobalBurnAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Info("error getting burn address")
}
}
dblock := new(factom.DBlock)
dblock.Height = height
if err := dblock.Get(nil, d.FactomClient); err != nil {
return err
}
heightTimestamp := dblock.Timestamp
// We need to mock a TXID to record zeroing
txid := fmt.Sprintf("%064d", height)
// 1. check current balance
// 2. substract amounts for every ticker
// Get all balances for the address
balances, err := d.Pegnet.SelectBalances(&FAGlobalBurnAddress)
if err != nil {
fLog.WithFields(log.Fields{
"err": err,
}).Info("zeroing burn | balances retrieval failed")
}
i := 0 // value to keep witin 0-9 range for mock tx
j := 0 // value for uniqueness
if height >= config.V202EnhanceActivation {
j = 50
}
for ticker := fat2.PTickerInvalid + 1; ticker < fat2.PTickerMax; ticker++ {
// Substract from every issuance
value, _ := balances[ticker]
_, _, err := d.Pegnet.SubFromBalance(tx, &FAGlobalBurnAddress, ticker, value) // lastInd, txErr, err
if err != nil {
fLog.WithFields(log.Fields{
"time": heightTimestamp,
"ticker": ticker,
"balance": value,
}).Info("zeroing burn | substract from balance failed")
}
// We need to mock a TXID to record nullify recrods
// add more uniqness into hash value by reusing iterating j value in addtion to current height
// so it doesn't overlap with staking and rewards we have in place
txid = fmt.Sprintf("%064d", height-(uint32(j)))
if height >= config.V202EnhanceActivation {
txid = fmt.Sprintf("%03d%061d", j, height)
}
// Mock entry hash value
addTxid := fmt.Sprintf("%d-%s", i, txid)
j++ // iterate all the time
i++ // drop to zero to be within 0-9 range
if i > 9 {
i = 0
}
fLog.WithFields(log.Fields{
"txid": txid,
"addtxid": addTxid,
}).Info("burn nullify | prep")
if height < config.V202EnhanceActivation {
err = d.Pegnet.InsertZeroingCoinbase(tx, txid, addTxid, height, heightTimestamp, value, ticker.String(), FAGlobalBurnAddress)
if err != nil {
fLog.WithFields(log.Fields{
"error": err,
}).Info("zeroing burn | coinbase tx failed")
return err
}
}
}
return nil
}
// If SyncBlock returns no error, than that height was synced and saved. If any part of the sync fails,
// the whole sync should be rolled back and not applied. An error should then be returned.
// The context should be respected if it is cancelled
func (d *Pegnetd) SyncBlock(ctx context.Context, tx *sql.Tx, height uint32) error {
fLog := log.WithFields(log.Fields{"height": height})
if isDone(ctx) { // Just an example about how to handle it being cancelled
return context.Canceled
}
if height == config.V204EnhanceActivation {
if err := d.MintTokensForBalance(ctx, tx, d.Sync.Synced+1); err != nil {
return err
}
}
if height == config.V204BurnMintedTokenActivation {
if err := d.NullifyMintedTokens(ctx, tx, d.Sync.Synced+1); err != nil {
return err
}
}
dblock := new(factom.DBlock)
dblock.Height = height
if err := dblock.Get(nil, d.FactomClient); err != nil {
return err
}
// First, gather all entries we need from factomd
oprEBlock := dblock.EBlock(config.OPRChain)
if oprEBlock != nil {
if err := multiFetch(oprEBlock, d.FactomClient); err != nil {
return err
}
}
transactionsEBlock := dblock.EBlock(config.TransactionChain)
if transactionsEBlock != nil {
if err := multiFetch(transactionsEBlock, d.FactomClient); err != nil {
return err
}
}
sprEBlock := dblock.EBlock(config.SPRChain)
if sprEBlock != nil {
if err := multiFetch(sprEBlock, d.FactomClient); err != nil {
return err
}
}
// Then, grade the new OPR Block. The results of this will be used
// to execute conversions that are in holding.
gradedBlock, err := d.Grade(ctx, oprEBlock)
var gradedSPRBlock graderStake.GradedBlock
var gradedDelegatedSPRBlock graderDelegateStake.DelegatedGradedBlock
var err_s error
if sprEBlock != nil {
if height < config.PIP18DelegateStakingActivation {
gradedSPRBlock, err_s = d.GradeS(ctx, sprEBlock)
} else {
gradedDelegatedSPRBlock, err_s = d.GradeDelegatedS(ctx, sprEBlock)
}
}
isRatesAvailable := false
if height < config.V20HeightActivation {
if err != nil {
return err
}
isRatesAvailable = gradedBlock != nil && 0 < len(gradedBlock.Winners())
if gradedBlock != nil {
err = d.Pegnet.InsertGradeBlock(tx, oprEBlock, gradedBlock)
if err != nil {
return err
}
winners := gradedBlock.Winners()
if 0 < len(winners) {
// PEG has 3 current pricing phases
// 1: Price is 0
// 2: Price is determined by equation
// 3: Price is determine by miners
var phase pegnet.PEGPricingPhase
if height < config.PEGPricingActivation {
phase = pegnet.PEGPriceIsZero
}
if height >= config.PEGPricingActivation {
phase = pegnet.PEGPriceIsEquation
}
if height >= config.PEGFreeFloatingPriceActivation {
phase = pegnet.PEGPriceIsFloating
}
err = d.Pegnet.InsertRates(tx, height, winners[0].OPR.GetOrderedAssetsUint(), phase)
if err != nil {
return err
}
} else {
fLog.WithFields(log.Fields{"section": "grading", "reason": "no winners"}).Tracef("block not graded")
}
} else {
fLog.WithFields(log.Fields{"section": "grading", "reason": "no graded block"}).Tracef("block not graded")
}
} else {
if err != nil {
return err
}
if err_s != nil {
return err_s
}
// 1. Determine the rates from 2 OPRs (OPR, SPR)
// 2. Insert rates to DB
var oprWinners []opr.AssetUint
var sprWinners []opr.AssetUint
if gradedBlock != nil {
err = d.Pegnet.InsertGradeBlock(tx, oprEBlock, gradedBlock)
if err != nil {
return err
}
winnersOpr := gradedBlock.Winners()
if 0 < len(winnersOpr) {
oprWinners = winnersOpr[0].OPR.GetOrderedAssetsUint()
}
}
if height < config.PIP18DelegateStakingActivation {
if gradedSPRBlock != nil {
winnersSpr := gradedSPRBlock.Winners()
if 0 < len(winnersSpr) {
sprWinners = winnersSpr[0].SPR.GetOrderedAssetsUint()
}
}
} else {
if gradedDelegatedSPRBlock != nil {
winnersSpr := gradedDelegatedSPRBlock.Winners()
if 0 < len(winnersSpr) {
sprWinners = winnersSpr[0].SPR.GetOrderedAssetsUint()
}
}
}
if 0 < len(oprWinners) || 0 < len(sprWinners) {
var filteredRates []opr.AssetUint
var errRate error
if height < config.V20DevRewardsHeightActivation {
filteredRates, errRate = d.GetAssetRatesV0(oprWinners, sprWinners)
} else {
filteredRates, errRate = d.GetAssetRates(oprWinners, sprWinners, height)
}
if errRate != nil {
return err
}
isRatesAvailable = true
var phase pegnet.PEGPricingPhase
phase = pegnet.PEGPriceIsFloating
err = d.Pegnet.InsertRates(tx, height, filteredRates, phase)
if err != nil {
return err
}
} else {
fLog.WithFields(log.Fields{"section": "grading", "reason": "no winners from OPR & SPR"}).Tracef("block not graded")
fmt.Println("no winners from OPR & SPR", ": block not graded")
}
}
// Only apply transactions if we crossed the activation
if height >= config.TransactionConversionActivation {
rates, err := d.Pegnet.SelectPendingRates(ctx, tx, height)
if err != nil {
return err
}
// Before we apply any balance changes, we will snapshot the balances at the START of the block.
// This means the balances are the same as the end of the block n-1.
// This activation is nested in the activation that has the rates
if height >= config.V20HeightActivation && height%pegnet.SnapshotRate == 0 {
// check if the height has no rates, what do we do?
// check rates from previous height
if rates == nil && height < config.V202EnhanceActivation {
// We need to handle the no rates case. Miners could avoid mining this last block.
// use the last valid rates from last block
rates, err = d.Pegnet.SelectPendingRates(ctx, tx, height-1)
}
if (rates == nil || len(rates) == 0) && height >= config.V202EnhanceActivation {
rates, _, err = d.Pegnet.SelectMostRecentRatesBeforeHeight(ctx, tx, height)
}
// If no rates for second time, skip Snapshot logic
// otherwise proceed with payout
if rates != nil {
err := d.SnapshotPayouts(tx, fLog, rates, height, dblock.Timestamp)
if err != nil {
// something wrong happend during payout execution
return err
}
} else {
// We don't return error as it will stop synchronisation
// we continue execution but skiping payout for this time
fLog.WithFields(log.Fields{"section": "staking", "reason": "no rates"}).Tracef("2 last blocks does not contains rates")
}
}
// At this point, we start making updates to the database in a specific order:
// TODO: ensure we rollback the tx when needed
// 1) Apply transaction batches that are in holding (conversions are always applied here)
if isRatesAvailable {
// Before conversions can be run, we have to adjust and discover the bank's value.
// We also only sync the bank if the block is a pegnet block
if err := d.SyncBank(ctx, tx, height); err != nil {
return err
}
if err = d.ApplyTransactionBatchesInHolding(ctx, tx, height, rates); err != nil {
return err
}
}
//2) Sync transactions in current height and apply transactions
if transactionsEBlock != nil {
if err = d.ApplyTransactionBlock(tx, transactionsEBlock); err != nil {
return err
}
}
}
// Only apply burn transaction if height does not cross the activation
if height < config.V20HeightActivation {
// 3) Apply FCT --> pFCT burns that happened in this block
// These funds will be available for transactions and conversions executed in the next block
// TODO: Check the order of operations on this and what block to add burns from.
if err := d.ApplyFactoidBlock(ctx, tx, dblock); err != nil {
return err
}
}
// 4) Apply effects of graded OPR Block (PEG rewards, if any)
// These funds will be available for transactions and conversions executed in the next block
if gradedBlock != nil {
if err := d.ApplyGradedOPRBlock(tx, gradedBlock, dblock.Timestamp); err != nil {
return err
}
}
if height >= config.V20HeightActivation {
// 5) Apply effects of graded SPR Block (PEG rewards, if any)
// These funds will be available for transactions and conversions executed in the next block
if height < config.PIP18DelegateStakingActivation {
if gradedSPRBlock != nil {
if err := d.ApplyGradedSPRBlock(tx, gradedSPRBlock, dblock.Timestamp); err != nil {
return err
}
}
} else {
if gradedDelegatedSPRBlock != nil {
if err := d.ApplyGradedDelegatedSPRBlock(tx, gradedDelegatedSPRBlock, dblock.Timestamp); err != nil {
return err
}
}
}
}
// 6) Apply Developers Rewards
if height >= config.V20DevRewardsHeightActivation && height%pegnet.SnapshotRate == 0 {
// init developers list explicitely
// and forward to function
// we use hardcoded list of dev payouts
developersList := DeveloperRewardAddreses
// we want function to accepts dev list as parameter, so different corner cases
// can be assigned
err := d.DevelopersPayouts(tx, fLog, height, dblock.Timestamp, developersList)
if err != nil {
fLog.WithFields(log.Fields{"section": "devReward", "reason": "developer reward"}).Tracef("something wrong happend during dev payout execution")
}
}
return nil
}
// SnapshotPayouts moves the current shapshot to the "past", and updates the current snapshot. Then
// it proceeds to do the snapshot staking payouts.
func (d *Pegnetd) SnapshotPayouts(tx *sql.Tx, fLog *log.Entry, rates map[fat2.PTicker]uint64, height uint32, heightTimestamp time.Time) error {
// Snapshot
snapStart := time.Now()
err := d.Pegnet.SnapshotCurrent(tx)
if err != nil {
return err // Snapshot fails stop all progress and block syncing
}
// Payout snapshot
balances, err := d.Pegnet.SelectSnapshotBalances(tx)
if err != nil {
return err // Need to do staking payouts
}
staked := make(map[factom.FAAddress]*big.Int)
for _, bal := range balances {
// We want all balances in pUSD
total := new(big.Int)
for i := fat2.PTicker(1); i < fat2.PTickerMax; i++ {
if i == fat2.PTickerPEG {
continue // PEG does not count towards stake total
}
if bal.Balances[i] == 0 { // Ignore 0 balances
continue
}
if (rates[i] == 0 || rates[fat2.PTickerUSD] == 0) && height >= config.V202EnhanceActivation {
continue
}
// Convert from pXXX -> pUSD
c, err := conversions.Convert(height, int64(bal.Balances[i]), rates[i], rates[i], rates[fat2.PTickerUSD], rates[fat2.PTickerUSD])
if err != nil {
return err
}
// add c to running sum
total = total.Add(total, big.NewInt(c))
}
staked[*bal.Address] = total
}
// We need to mock a TXID for the staked payouts
txid := fmt.Sprintf("%064d", height)
// Sort the staked by highest PUSD
type StakedAmount struct {
Address factom.FAAddress
PUSD uint64
}
var list []StakedAmount
for add, amt := range staked {
if !amt.IsUint64() {
return fmt.Errorf("%s has balance that is not uint64: %s", add, amt)
}
uAmt := amt.Uint64()
if uAmt <= 0 { // Apply a minimum required amount in pUSD
continue
}
// TODO: Check uint64 is safe
list = append(list, StakedAmount{Address: add, PUSD: uAmt})
}
if len(list) == 0 {
// Abort early since there is no one to pay out
fLog.WithFields(log.Fields{
"duration": time.Since(snapStart),
"eligible": len(list),
}).Info("staking | balances snapshotted | not paid, there none eligible")
return nil
}
sort.Slice(list, func(i, j int) bool {
return list[i].PUSD < list[j].PUSD
})
// Calculate payouts
payoutindex := make(map[string]int)
addressMap := make(map[string]factom.FAAddress)
// 4.5K per block allowed
// as described in conversions
totalPayout := uint64(conversions.PerBlockAssetHolders) * pegnet.SnapshotRate
set := conversions.NewConversionSupply(totalPayout)
for i, stake := range list {
addTxid := fmt.Sprintf("%d-%s", i, txid)
payoutindex[addTxid] = i
addressMap[addTxid] = stake.Address
err := set.AddConversion(addTxid, stake.PUSD)
if err != nil {
return err
}
}
// ---- Database Payouts ----
// Inserts tx into the db
err = d.Pegnet.InsertStakingCoinbase(tx, txid, height, heightTimestamp, set.Payouts(), addressMap)
if err != nil {
return err
}
// Increase balances
for addTxid, payout := range set.Payouts() {
add := addressMap[addTxid] // The address to pay
_, err = d.Pegnet.AddToBalance(tx, &add, fat2.PTickerPEG, payout)
if err != nil {
return err
}
}
// -- End staking calculations
fLog.WithFields(log.Fields{
"duration": time.Since(snapStart),
"eligible": len(list),
"PEG": float64(totalPayout) / 1e8, // Float is good enough here,
"txid": txid,
}).Info("staking | balances snapshotted | paid to eligible")
return nil
}
// Developers Reward Payouts
// implementation of PIP16 - distributed rewards collected for developers every 24h
func (d *Pegnetd) DevelopersPayouts(tx *sql.Tx, fLog *log.Entry, height uint32, heightTimestamp time.Time, developers []DevReward) error {
totalPayout := uint64(conversions.PerBlockDevelopers) * pegnet.SnapshotRate // every day
payoutStart := time.Now()
txid := fmt.Sprintf("%064d", height)
log.Info("--------------------------------------------------")
i := 0
// we need more iterating values to construct unique mock hash
// should start from 1, because 0-hash reserved for staking mock tx
j := 1
for _, dev := range developers {
// We need to mock a TXID to record dev rewards
// add more uniqness into hash value by reusing iterating j value in addtion to current height
// so it doesn't repeat in 25+ blocks
txid = fmt.Sprintf("%02d%062d", j, height)
// we calculate developers reward from % pre-defined
rewardPayout := uint64((conversions.PerBlockDevelopers / 100) * dev.DevRewardPct)
if height >= config.V202EnhanceActivation {
rewardPayout = uint64((conversions.PerBlockDevelopers / 100) * dev.DevRewardPct * pegnet.SnapshotRate)
}
addr, err := factom.NewFAAddress(dev.DevAddress)
_, err = d.Pegnet.AddToBalance(tx, &addr, fat2.PTickerPEG, rewardPayout)
if err != nil {
return err
}
// Mock entry hash value
addTxid := fmt.Sprintf("%d-%s", i, txid)
j++ // iterate all the time to build unique hash
i++
if i > 9 {
i = 0
}
fLog.WithFields(log.Fields{
//"txid": txid,
"addtxid": addTxid,
"prct": dev.DevRewardPct,
}).Info("developer reward | prep")
// Get dev address as FAAdress
FADevAddress, err := factom.NewFAAddress(dev.DevAddress)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"addr": dev.DevAddress,
}).Info("error getting developer address")
return err
}
// ---- Database Payouts ----
// Inserts tx into the db
err = d.Pegnet.InsertDeveloperRewardCoinbase(tx, txid, addTxid, height, heightTimestamp, rewardPayout, FADevAddress)
if err != nil {
log.Info("dev insertion error")
return err
}
fLog.WithFields(log.Fields{
"total": float64(totalPayout) / 1e8,
"PEG": float64(rewardPayout) / 1e8, // Float is good enough here
"pct": dev.DevRewardPct,
"addr": FADevAddress,
}).Info("developer reward | paid out to")
fLog.Info("developer reward | for ", dev.DevGroup)
}
fLog.WithFields(log.Fields{
"total": float64(totalPayout) / 1e8,
"elapsed": time.Since(payoutStart),
}).Info("developer reward | paid out")
return nil
}
func multiFetch(eblock *factom.EBlock, c *factom.Client) error {
err := eblock.Get(nil, c)
if err != nil {
return err
}
work := make(chan int, len(eblock.Entries))
defer close(work)
errs := make(chan error)
defer close(errs)
for i := 0; i < 8; i++ {
go func() {
// TODO: Fix the channels such that a write on a closed channel never happens.
// For now, just kill the worker go routine
defer func() {
recover()
}()
for j := range work {
errs <- eblock.Entries[j].Get(nil, c)
}
}()
}
for i := range eblock.Entries {
work <- i
}
count := 0
for e := range errs {
count++
if e != nil {
// If we return, we close the errs channel, and the working go routine will
// still try to write to it.
return e
}
if count == len(eblock.Entries) {
break
}
}
return nil
}
// SyncBank will input the bank value for all heights >= V4OPRUpdate
// The bank table helps track the demand for peg at a given height.
// The bank is the total amount of PEG allowed to be issued for any given height.
func (d *Pegnetd) SyncBank(ctx context.Context, sqlTx *sql.Tx, currentHeight uint32) error {
if (currentHeight >= config.V4OPRUpdate) && (currentHeight < config.V20HeightActivation) { // V4 forward tracks this
err := d.Pegnet.InsertBankAmount(sqlTx, int32(currentHeight), int64(pegnet.BankBaseAmount))
if err != nil {
return err
}
}
return nil
}
// ApplyTransactionBatchesInHolding attempts to apply the transaction batches from previous
// blocks that were put into holding because they contained conversions.
// If an error is returned, the sql.Tx should be rolled back by the caller.
func (d *Pegnetd) ApplyTransactionBatchesInHolding(ctx context.Context, sqlTx *sql.Tx, currentHeight uint32, rates map[fat2.PTicker]uint64) error {
_, height, err := d.Pegnet.SelectMostRecentRatesBeforeHeight(ctx, sqlTx, currentHeight)
if err != nil {
return err
}
averages := d.GetPegNetRateAverages(ctx, height).(map[fat2.PTicker]uint64) // Get the averages for all the passets
// All batches with a PEG conversion
var pegConversions []*fat2.TransactionBatch
// Usually height is just currentHeight-1, but it can be farther back
// if the miners have skipped a block
for i := height; i < currentHeight; i++ {
txBatches, err := d.Pegnet.SelectTransactionBatchesInHoldingAtHeight(uint64(i))
if err != nil {
return err
}
// For all conversions, we need to apply the PEG conversion limit.
// This means, we need to find all valid conversions and pay them out
// on a proportional basis.
for i, txBatch := range txBatches {
// Re-validate transaction batch because timestamp might not be valid anymore
if currentHeight >= config.V20HeightActivation {
if err := txBatch.ValidatePegTx(int32(currentHeight)); err != nil {
d.Pegnet.SetTransactionHistoryExecuted(sqlTx, txBatch, -2)
continue
}
}
if err := txBatch.Validate(int32(currentHeight)); err != nil {
d.Pegnet.SetTransactionHistoryExecuted(sqlTx, txBatch, -2)
continue
}
isReplay, err := d.Pegnet.IsReplayTransaction(sqlTx, txBatch.Entry.Hash)
if err != nil {
return err
} else if isReplay {
continue
}
// This will apply all batche inputs, and all batch outputs except
// conversions to PEG if we are above the PegnetConversionLimit Act
err = d.applyTransactionBatch(sqlTx, txBatch, rates, averages, currentHeight)
// The err needs to be converted to a code. If the err is still
// not nil, then the code is 0 and the error is probably db related.
// If the code is < 0, the tx is rejected.
// If the code is > 0 and the err is nil, the tx is accepted.
rejectCode, err := pegnet.IsRejectedTx(err)
if err != nil { // Likely a db error
return err
} else if rejectCode < 0 { // Tx rejected
d.Pegnet.SetTransactionHistoryExecuted(sqlTx, txBatch, rejectCode)
} else if err == nil { // Tx accepted
if currentHeight < config.V20HeightActivation {
// If PegnetConversion limits are on, we process conversions to
// peg in a second pass.
if currentHeight >= config.PegnetConversionLimitActivation && txBatch.HasPEGRequest() {
// Batch applied, we need to do the PEG conversions at the end
pegConversions = append(pegConversions, txBatches[i])
}
}
}
}
// Apply all PEG Requests
// The `conversions.PerBlock` is the allowed amount of PEG to be
// converted. So when the bank is implemented, it should be passed in
// here.
//
// This is processing each height of conversions as its own block
// of conversions. After the v4 update, all pending conversions get
// processed together for peg conversions
if currentHeight >= config.PegnetConversionLimitActivation && currentHeight < config.V4OPRUpdate {
// All heights before v4 use the currentHeight-1 with a 5K PEG bank
bank := pegnet.BankBaseAmount
err = d.recordPegnetRequests(sqlTx, pegConversions, rates, averages, currentHeight, bank, int32(currentHeight-1))
if err != nil {
return err
}
pegConversions = []*fat2.TransactionBatch{}
}
}
// Process all pending using the same bank
if (currentHeight >= config.V4OPRUpdate) && (currentHeight < config.V20HeightActivation) {
// The bank entry should be here from the sync banks called before this function.
bentry, err := d.Pegnet.SelectBankEntry(sqlTx, int32(currentHeight))
if err != nil {
return err
}
err = d.recordPegnetRequests(sqlTx, pegConversions, rates, averages, currentHeight, uint64(bentry.BankAmount), int32(currentHeight))
if err != nil {
return err
}
}
return nil
}
// ApplyTransactionBlock puts conversion-containing transaction batches into holding,
// and applys the balance updates for all transaction batches able to be executed
// immediately. If an error is returned, the sql.Tx should be rolled back by the caller.
func (d *Pegnetd) ApplyTransactionBlock(sqlTx *sql.Tx, eblock *factom.EBlock) error {
for blockorder, entry := range eblock.Entries {
txBatch, err := fat2.NewTransactionBatch(entry, int32(eblock.Height))
if err != nil {
continue // Bad formatted entry
}
log.WithFields(log.Fields{
"height": eblock.Height,
"entryhash": entry.Hash.String(),
"conversions": txBatch.HasConversions(),
"txs": len(txBatch.Transactions)}).Tracef("tx found")
isReplay, err := d.Pegnet.IsReplayTransaction(sqlTx, txBatch.Entry.Hash)
if err != nil {
return err