/
modelx.go
1375 lines (1181 loc) · 39.1 KB
/
modelx.go
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
// (c) 2018 PoC Consortium ALL RIGHTS RESERVED
package modelx
import (
"database/sql"
"errors"
"fmt"
"math"
"strconv"
"sync"
"time"
"github.com/PoC-Consortium/Nogrod/pkg/burstmath"
. "github.com/PoC-Consortium/Nogrod/pkg/config"
. "github.com/PoC-Consortium/Nogrod/pkg/logger"
"github.com/PoC-Consortium/Nogrod/pkg/rsencoding"
"github.com/PoC-Consortium/Nogrod/pkg/wallet"
"github.com/PoC-Consortium/Nogrod/pkg/wallethandler"
_ "github.com/go-sql-driver/mysql"
"github.com/golang-migrate/migrate"
"github.com/golang-migrate/migrate/database/mysql"
_ "github.com/golang-migrate/migrate/source/file"
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
)
type Account struct {
ID uint64
Address string
Name string
Pending int64
}
type Miner struct {
ID uint64
Address string
Name string `db:"name"`
Pending int64
CurrentDeadlineParams *DeadlineParams
DeadlinesParams map[uint64]*DeadlineParams
WeightedDeadlineSum float64
PayoutDetail string `db:"account.payout_detail"`
UserAgent string
// this mutex ensures that there is only one concurrent write process
// to the db for each miner
dbMu sync.Mutex
// this mutex is used to protect the data
sync.Mutex
}
type DeadlineParams struct {
Deadline uint64
BaseTarget uint64
Height uint64
}
type Block struct {
Height uint64
BaseTarget uint64 `db:"base_target"`
Scoop uint32
GenerationSignature string `db:"generation_signature"`
GenerationSignatureBytes []byte
WinnerVerified bool `db:"winner_verified"`
WinnerID sql.NullInt64 `db:"winner_id"`
Reward sql.NullInt64
BestNonceSubmissionID sql.NullInt64 `db:"best_nonce_submission_id"`
Created time.Time
GenerationTime int32 `db:"generation_time"`
}
type Transaction struct {
ID uint64
Amount int64
RecipientID uint64 `db:"recipient_id"`
Created time.Time
}
type Modelx struct {
db *sqlx.DB
walletDB *sqlx.DB
walletHandler wallethandler.WalletHandler
newBlockMu sync.Mutex
}
type NonceSubmission struct {
Nonce uint64
Deadline uint64
MinerID uint64 `db:"miner.id"`
Height uint64 `db:"block.height"`
Name string `db:"account.name"`
Address string `db:"account.address"`
RoundStart time.Time `db:"block.created"`
}
type WonBlock struct {
WinnerName string `db:"account.name"`
WinnerAddress string `db:"account.address"`
WinnerID uint64 `db:"account.id"`
Deadline uint64 `db:"nonce_submission.deadline"`
BaseTarget uint64 `db:"base_target"`
Height uint64 `db:"height"`
Reward float64 `db:"reward"`
}
type PendingInfo struct {
ID uint64
PayoutInterval sql.NullString `db:"payout_interval"`
Pending int64
}
func NewModelX(walletHandler wallethandler.WalletHandler, migrateDB bool) *Modelx {
db, err := initializeDatabase(migrateDB)
if err != nil {
Logger.Fatal("failed to connect to database", zap.Error(err))
}
modelx := Modelx{
db: db,
walletHandler: walletHandler}
if Cfg.WalletDB.Name != "" {
walletDB, err := sqlx.Connect("mysql", Cfg.WalletDB.DataSourceName(true))
if err != nil {
Logger.Fatal("failed to connect to database", zap.Error(err))
}
modelx.walletDB = walletDB
}
if Cfg.FeeAccountID != 0 {
modelx.createFeeAccount()
}
loaded := modelx.loadCurrentBlock()
if loaded {
modelx.cacheMiners()
modelx.cacheRewardRecipients()
} else {
miningInfo, err := modelx.walletHandler.GetMiningInfo()
if err != nil {
Logger.Fatal("getting inital mining info failed", zap.Error(err))
}
err = modelx.NewBlock(miningInfo.BaseTarget, miningInfo.GenerationSignature, miningInfo.Height)
if err != nil {
Logger.Fatal("creating first block failed", zap.Error(err))
}
}
return &modelx
}
func initializeDatabase(migrateDB bool) (*sqlx.DB, error) {
tmpdb, err := sqlx.Connect("mysql", Cfg.DB.DataSourceName(false))
if err != nil {
Logger.Fatal("failed to connect to sql server", zap.Error(err))
}
_, err = tmpdb.Exec("CREATE SCHEMA IF NOT EXISTS `" + Cfg.DB.Name + "` DEFAULT CHARACTER SET utf8;")
if err != nil {
Logger.Fatal("failed to create the database", zap.Error(err))
}
tmpdb.Close()
db, err := sqlx.Connect("mysql", Cfg.DB.DataSourceName(true))
if err != nil {
Logger.Fatal("failed to connect to sql server", zap.Error(err))
}
if !migrateDB {
return db, err
}
driver, err := mysql.WithInstance(db.DB, &mysql.Config{})
if err != nil {
Logger.Fatal("failed to initialise migration driver", zap.Error(err))
}
m, err := migrate.NewWithDatabaseInstance("file://migrations", "mysql", driver)
if err != nil {
Logger.Fatal("failed to initialise migration instance", zap.Error(err))
}
version, dirty, versionErr := m.Version()
if versionErr != nil && versionErr != migrate.ErrNilVersion {
Logger.Fatal("failed to get migration version", zap.Error(err))
}
if dirty {
Logger.Warn("Forcing migration", zap.Uint("version", version))
err = m.Force(int(version))
if err != nil {
Logger.Fatal("failed to force execute migration", zap.Error(err))
}
}
migrateErr := m.Up()
if migrateErr != nil && migrateErr != migrate.ErrNoChange {
Logger.Fatal("failed to execute migrations", zap.Error(err))
}
return db, err
}
func (modelx *Modelx) loadCurrentBlock() bool {
var currentBlock Block
err := modelx.db.Get(¤tBlock, "SELECT * FROM block ORDER BY height desc LIMIT 1")
if err != nil {
Logger.Error("getting current block from db failed", zap.Error(err))
return false
}
genSigBytes, err := burstmath.DecodeGeneratorSignature(currentBlock.GenerationSignature)
if err != nil {
Logger.Fatal("deconding generationSignature to byte array failed", zap.Error(err))
}
currentBlock.GenerationSignatureBytes = genSigBytes
Cache.StoreCurrentBlock(currentBlock)
return true
}
func (modelx *Modelx) cacheMiners() {
type submissionData struct {
Miner
Deadline uint64 `db:"deadline"`
Height uint64 `db:"height"`
BaseTarget uint64 `db:"block.base_target"`
}
var slowBlockHeights []uint64
sql := "SELECT height FROM block WHERE generation_time >= ? ORDER BY height DESC LIMIT ?"
err := modelx.db.Select(&slowBlockHeights, sql, Cfg.TMin, Cfg.NAVG+1)
if err != nil {
Logger.Fatal("failed getting slowBlockHeights", zap.Error(err))
}
// nothing to cache
if len(slowBlockHeights) == 0 {
return
}
var fastBlockHeights []uint64
sql = `SELECT height FROM block WHERE
generation_time < ? AND
height > (SELECT height FROM block ORDER BY height DESC LIMIT 1) - ?`
err = modelx.db.Select(&fastBlockHeights, sql, Cfg.TMin, Cfg.NAVG)
if len(slowBlockHeights) > 1 {
for _, h := range slowBlockHeights[1:] {
Cache.AddBlock(h, Cfg.TMin+1)
}
}
for _, h := range fastBlockHeights {
Cache.AddBlock(h, 0)
}
query, args, err := sqlx.In(`SELECT
account.id "id",
account.address "address",
COALESCE(account.name, '') "name",
account.pending "pending",
deadline "deadline",
block_height "height",
block.base_target "block.base_target",
COALESCE(account.min_payout_value,
CONCAT(account.payout_interval, "|", account.next_payout_date),
"") "account.payout_detail"
FROM nonce_submission
JOIN account ON nonce_submission.miner_id = account.id
JOIN block ON block.height = nonce_submission.block_height
WHERE block.height IN (?)
ORDER BY block_height ASC`, slowBlockHeights)
if err != nil {
Logger.Fatal("failed to create IN query", zap.Error(err))
}
query = modelx.db.Rebind(query)
var sds []submissionData
// because of uints we actually should check if currentHeight is smaller
// than Cfg.NAVG, but we are at a sufficient block height already...
if err := modelx.db.Select(&sds, query, args...); err != nil {
Logger.Fatal("failed getting active miners from db", zap.Error(err))
}
currentHeight := slowBlockHeights[0]
heights := make(map[uint64]bool)
for i := range sds {
heights[sds[i].Height] = true
miner := Cache.GetMiner(sds[i].ID)
if miner == nil {
miner = &sds[i].Miner
miner.DeadlinesParams = make(map[uint64]*DeadlineParams)
Cache.LoadOrStoreMiner(miner)
}
dp := &DeadlineParams{
Height: sds[i].Height,
BaseTarget: sds[i].BaseTarget,
Deadline: sds[i].Deadline}
if sds[i].Height != currentHeight {
miner.DeadlinesParams[sds[i].Height] = dp
miner.WeightedDeadlineSum += weightDeadline(dp.Deadline, dp.BaseTarget)
}
if sds[i].Height > miner.CurrentBlockHeight() {
miner.CurrentDeadlineParams = dp
}
}
}
func (modelx *Modelx) createFeeAccount() {
modelx.db.MustExec(
"INSERT IGNORE INTO account (id, address) VALUES (?, ?)",
Cfg.FeeAccountID, rsencoding.Encode(Cfg.FeeAccountID))
}
func (modelx *Modelx) CleanDB() {
Logger.Info("starting to cleanup db")
currentBlock := Cache.CurrentBlock()
modelx.db.MustExec("DELETE FROM block WHERE height < ?", currentBlock.Height-5000)
modelx.db.MustExec(`DELETE FROM miner WHERE id NOT IN
(SELECT DISTINCT miner_id FROM nonce_submission)`)
tx, err := modelx.db.Begin()
if err != nil {
Logger.Error("begining cleanup transaction failed", zap.Error(err))
return
}
transferPendngSQL := `UPDATE account SET pending =
(SELECT * FROM ( SELECT SUM(pending) FROM account WHERE id NOT IN
(SELECT id FROM miner) ) bold ) WHERE id = ?`
_, err = tx.Exec(transferPendngSQL, Cfg.FeeAccountID)
if err != nil {
Logger.Error("transfering pending to fee account failed", zap.Error(err))
tx.Rollback()
return
}
deleteOldAccountsSQL := "DELETE FROM account WHERE id != ? AND id NOT IN (SELECT id FROM miner)"
_, err = tx.Exec(deleteOldAccountsSQL, Cfg.FeeAccountID)
if err != nil {
Logger.Error("deleteing old accounts failed", zap.Error(err))
tx.Rollback()
return
}
tx.Commit()
}
func (modelx *Modelx) RereadMinerNames() {
Cache.MinerRange(func(k, v interface{}) bool {
minerID := k.(uint64)
accountInfo, err := modelx.walletHandler.GetAccountInfo(minerID)
if err != nil {
return true
}
// only hold lock as long as necessary
miner := v.(*Miner)
miner.Lock()
if miner.Name == accountInfo.Name {
miner.Unlock()
return true
}
miner.Name = accountInfo.Name
miner.Unlock()
_, err = modelx.db.Exec("UPDATE account SET name = ? WHERE id = ?", accountInfo.Name, miner.ID)
if err != nil {
Logger.Error("updating miner name failed", zap.Error(err))
}
return true
})
}
func (modelx *Modelx) getMinerFromDB(accountID uint64) *Miner {
sql := `SELECT
id,
address,
COALESCE(name, '') "name",
pending
FROM account WHERE id = ?`
miner := Miner{}
err := modelx.db.Get(&miner, sql, accountID)
if err != nil {
return nil
}
miner.DeadlinesParams = make(map[uint64]*DeadlineParams)
return &miner
}
func (modelx *Modelx) GetBestNonceSubmissionOnBlock(height uint64) (*NonceSubmission, error) {
var ns NonceSubmission
sql := `SELECT
nonce_submission.deadline,
nonce_submission.nonce,
miner.id "miner.id",
COALESCE(account.name, '') "account.name",
account.address "account.address",
block.height "block.height",
block.created "block.created"
FROM block
JOIN nonce_submission ON block.best_nonce_submission_id = nonce_submission.id
JOIN miner ON miner.id = nonce_submission.miner_id
JOIN account ON account.id = nonce_submission.miner_id
WHERE block_height = ?`
err := modelx.db.Get(&ns, sql, height)
if err != nil {
return nil, err
}
return &ns, nil
}
func (modelx *Modelx) NewBlock(baseTarget uint64, genSig string, height uint64) error {
modelx.newBlockMu.Lock()
defer modelx.newBlockMu.Unlock()
if _, exists := Cache.WasSlowBlock(height); exists {
return nil
}
currentBlock := Cache.CurrentBlock()
if currentBlock.Height != uint64(0) && height < currentBlock.Height-uint64(Cfg.NAVG) {
return errors.New("bock too old")
}
genSigBytes, err := burstmath.DecodeGeneratorSignature(genSig)
if err != nil {
return err
}
var removedHeight uint64
var newBlock Block
var generationTime int32
if height > currentBlock.Height {
generationTime, err = modelx.getGenerationTime(currentBlock.Height)
if err != nil {
Logger.Error("could not get generation time", zap.Uint64("height", currentBlock.Height))
} else {
modelx.db.MustExec("UPDATE block SET generation_time = ? WHERE height = ?",
generationTime, currentBlock.Height)
removedHeight = Cache.AddBlock(currentBlock.Height, generationTime)
}
newBlock = Block{
Height: height,
BaseTarget: baseTarget,
Scoop: burstmath.CalcScoop(height, genSigBytes),
GenerationSignature: genSig,
GenerationSignatureBytes: genSigBytes,
Created: time.Now()}
} else {
generationTime, err = modelx.getGenerationTime(height)
if err != nil {
Logger.Error("could not get generation time", zap.Uint64("height", currentBlock.Height))
generationTime = 4 * 60 // fallback value of 4 minutes
}
removedHeight = Cache.AddBlock(height, generationTime)
}
modelx.db.MustExec(`INSERT
INTO block (height, base_target, scoop, generation_signature, created, generation_time)
VALUES (?, ?, ?, ?, ?, ?)`,
height, baseTarget, burstmath.CalcScoop(height, genSigBytes), genSig,
time.Now(), generationTime)
Cache.MinerRange(func(key, value interface{}) bool {
miner := value.(*Miner)
miner.Lock()
if slow, _ := Cache.WasSlowBlock(miner.CurrentBlockHeight()); slow {
miner.addDeadlineParams()
}
if removedHeight != 0 {
miner.removeDeadlineParams(removedHeight)
}
if miner.CurrentBlockHeight() < height-Cfg.InactiveAfterXBlocks {
Cache.DeleteMiner(key.(uint64))
}
miner.Unlock()
return true
})
if newBlock.Height != 0 {
modelx.cacheRewardRecipients()
Cache.StoreCurrentBlock(newBlock)
}
return nil
}
func (modelx *Modelx) createMiner(accountID uint64) (*Miner, error) {
if accountID == Cfg.FeeAccountID {
return nil, fmt.Errorf("not allowed to mine with fee account")
}
address := rsencoding.Encode(accountID)
var name string
accountInfo, err := modelx.walletHandler.GetAccountInfo(accountID)
if err == nil {
name = accountInfo.Name
}
tx, err := modelx.db.Begin()
if err != nil {
return nil, err
}
accountSQL := "INSERT IGNORE INTO account (id, address, name) VALUES (?, ?, ?)"
_, err = tx.Exec(accountSQL, accountID, address, name)
if err != nil {
tx.Rollback()
return nil, err
}
minerSQL := "INSERT IGNORE INTO miner (id) VALUES (?)"
_, err = tx.Exec(minerSQL, accountID)
if err != nil {
tx.Rollback()
return nil, err
}
err = tx.Commit()
if err != nil {
return nil, err
}
return &Miner{
ID: accountID,
Address: address,
Name: name,
DeadlinesParams: make(map[uint64]*DeadlineParams)}, nil
}
func (modelx *Modelx) FirstOrCreateMiner(accountID uint64) *Miner {
cachedMiner := Cache.GetMiner(accountID)
if cachedMiner != nil {
return cachedMiner
}
var miner *Miner
var err error
miner = modelx.getMinerFromDB(accountID)
if miner == nil {
miner, err = modelx.createMiner(accountID)
if err != nil {
Logger.Error("creating miner failed", zap.Error(err))
return nil
}
}
miner.DeadlinesParams = make(map[uint64]*DeadlineParams)
// if already exists at this point we rather use the existing
miner = Cache.LoadOrStoreMiner(miner)
return miner
}
func (miner *Miner) removeDeadlineParams(height uint64) {
if dp, exists := miner.DeadlinesParams[height]; exists {
miner.WeightedDeadlineSum -= weightDeadline(dp.Deadline, dp.BaseTarget)
delete(miner.DeadlinesParams, height)
}
}
func (miner *Miner) addDeadlineParams() {
if miner.CurrentDeadlineParams == nil {
return
}
// is this a new submission?
dp := miner.CurrentDeadlineParams
if _, exists := miner.DeadlinesParams[dp.Height]; !exists {
miner.DeadlinesParams[dp.Height] = miner.CurrentDeadlineParams
miner.WeightedDeadlineSum += weightDeadline(dp.Deadline, dp.BaseTarget)
}
}
func (miner *Miner) CurrentBlockHeight() uint64 {
if miner.CurrentDeadlineParams != nil {
return miner.CurrentDeadlineParams.Height
}
return 0
}
func (miner *Miner) CurrentDeadline() uint64 {
if miner.CurrentDeadlineParams == nil {
return ^uint64(0)
}
return miner.CurrentDeadlineParams.Deadline
}
func (miner *Miner) CalculateEEPS() float64 {
return eeps(len(miner.DeadlinesParams), miner.WeightedDeadlineSum)
}
func (modelx *Modelx) UpdateOrCreateNonceSubmission(miner *Miner, height, deadline, nonce, baseTarget uint64,
genSig string) error {
miner.dbMu.Lock()
defer miner.dbMu.Unlock()
if miner.CurrentBlockHeight() == height {
if miner.CurrentDeadline() <= deadline {
return nil
}
sql := "UPDATE nonce_submission SET deadline = ?, nonce = ? WHERE miner_id = ? AND block_height = ?"
_, err := modelx.db.Exec(sql, deadline, nonce, miner.ID, height)
if err != nil {
return err
}
miner.Lock()
miner.CurrentDeadlineParams.Deadline = deadline
miner.Unlock()
return nil
}
blockExists, slow := Cache.WasSlowBlock(height)
if blockExists && !slow {
return nil
}
if dp, exists := miner.DeadlinesParams[height]; exists {
if dp.Deadline <= deadline {
return nil
}
sql := "UPDATE nonce_submission SET deadline = ?, nonce = ? WHERE miner_id = ? AND block_height = ?"
_, err := modelx.db.Exec(sql, deadline, nonce, miner.ID, height)
if err != nil {
return err
}
miner.Lock()
miner.WeightedDeadlineSum += weightDeadline(deadline, baseTarget) -
weightDeadline(dp.Deadline, dp.BaseTarget)
dp.BaseTarget = baseTarget
dp.Deadline = deadline
dp.Height = height
miner.Unlock()
return nil
}
if !blockExists {
ri := Cache.GetRoundInfo()
if ri.Height != height {
err := modelx.NewBlock(baseTarget, genSig, height)
if err != nil {
return err
}
}
}
sql := "INSERT INTO nonce_submission (miner_id, block_height, deadline, nonce) VALUES (?, ?, ?, ?)"
_, err := modelx.db.Exec(sql, miner.ID, height, deadline, nonce)
if err != nil {
return err
}
miner.Lock()
dp := &DeadlineParams{
BaseTarget: baseTarget,
Deadline: deadline,
Height: height}
if height > miner.CurrentBlockHeight() {
miner.CurrentDeadlineParams = dp
} else {
miner.WeightedDeadlineSum += weightDeadline(deadline, baseTarget)
miner.DeadlinesParams[height] = dp
}
miner.Unlock()
return nil
}
func (modelx *Modelx) UpdateBestSubmission(minerID, height uint64) {
sql := `UPDATE block SET best_nonce_submission_id =
(SELECT id FROM nonce_submission WHERE block_height = block.height AND miner_id = ?)
WHERE height = ? `
modelx.db.MustExec(sql, minerID, height)
}
func (modelx *Modelx) RewardBlocks() {
currentBlock := Cache.CurrentBlock()
type BlockWonInfo struct {
Height uint64
Created time.Time
Nonce uint64 `db:"nonce_submission.nonce"`
MinerID uint64 `db:"nonce_submission.miner_id"`
}
payoutDelay := time.Now().Add(-time.Duration(Cfg.PayoutDelay) * time.Second)
payoutHeightDelay := currentBlock.Height - Cfg.BlockHeightPayoutDelay
modelx.db.MustExec(`UPDATE block SET best_nonce_submission_id =
(SELECT id FROM nonce_submission
WHERE nonce_submission.block_height = block.height ORDER BY deadline ASC LIMIT 1)
WHERE winner_verified = 0 AND height <= ? AND created <= ?`,
payoutHeightDelay,
payoutDelay)
modelx.db.MustExec(`UPDATE block SET winner_verified = 1
WHERE
best_nonce_submission_id IS NULL and
winner_verified = 0 AND
height <= ? AND
created <= ?`,
payoutHeightDelay,
payoutDelay)
var blockWonInfos []BlockWonInfo
sql := `SELECT
height,
created,
nonce_submission.miner_id "nonce_submission.miner_id",
nonce_submission.nonce "nonce_submission.nonce"
FROM block
JOIN nonce_submission ON nonce_submission.id = block.best_nonce_submission_id
WHERE
height <= ? AND
winner_verified = 0 AND
NOT block.best_nonce_submission_id IS NULL AND
created <= ?
ORDER BY height ASC`
err := modelx.db.Select(&blockWonInfos, sql, payoutHeightDelay, payoutDelay)
if err != nil {
Logger.Error("failed to fetch blocks without winner verified", zap.Error(err))
return
}
// set dynamic min payout
// for this we need to check transactions
// since the block that has not been checked
if len(blockWonInfos) > 0 {
earliestCreated := blockWonInfos[0].Created
msgOf, err := modelx.walletHandler.GetIncomingMsgsSince(earliestCreated.Add(-time.Second * 30))
if err != nil {
Logger.Error("failed to get messages", zap.Error(err))
} else {
modelx.SetMinPayout(msgOf)
}
}
for _, blockWonInfo := range blockWonInfos {
wonBlock, blockInfo, err := modelx.walletHandler.WonBlock(
blockWonInfo.Height, blockWonInfo.MinerID, blockWonInfo.Nonce)
if err != nil {
Logger.Error("failed to determine if block was won", zap.Error(err))
continue
}
if wonBlock {
modelx.rewardBlock(blockInfo)
} else {
modelx.db.MustExec("UPDATE block SET winner_verified = 1 WHERE height = ?",
blockWonInfo.Height)
}
}
}
func (modelx *Modelx) GetEEPSsOnBlock(height uint64, writeToDb bool) (map[uint64]float64, float64, error) {
type EEPSArgs struct {
MinerID uint64 `db:"miner_id"`
WeightedDeadlineSum float64 `db:"weighted_deadline_sum"`
NConf int `db:"confirmed_deadlines"`
}
eepsSQL := `SELECT
miner_id "miner_id",
CAST(SUM(deadline * block.base_target) AS DOUBLE) "weighted_deadline_sum",
COUNT(deadline) "confirmed_deadlines"
FROM nonce_submission
JOIN (SELECT base_target, height
FROM block WHERE height <= ? AND generation_time >= ? ORDER BY height DESC LIMIT ?)
AS block ON block.height = nonce_submission.block_height
GROUP BY miner_id;`
var eepsArgs []EEPSArgs
err := modelx.db.Select(&eepsArgs, eepsSQL, height, Cfg.TMin, Cfg.NAVG)
if err != nil {
return nil, 0.0, err
}
eepsOf := make(map[uint64]float64)
var eepsSum float64
for _, args := range eepsArgs {
eeps := eeps(args.NConf, args.WeightedDeadlineSum)
if writeToDb {
modelx.db.MustExec("UPDATE miner SET capacity = ? WHERE id = ?",
int32(eeps*1000.0), args.MinerID)
}
eepsSum += eeps
eepsOf[args.MinerID] = eeps
}
return eepsOf, eepsSum, nil
}
func (modelx *Modelx) GetSharesOnBlock(height uint64) (map[uint64]float64, error) {
eepsOf, eepsSum, err := modelx.GetEEPSsOnBlock(height, true)
if err != nil {
return nil, err
}
shareOf := make(map[uint64]float64)
if eepsSum != 0.0 {
for i := range eepsOf {
shareOf[i] = eepsOf[i] / eepsSum
}
}
return shareOf, nil
}
func (modelx *Modelx) rewardBlock(blockInfo *wallet.GetBlockReply) {
shareInPlanckOf := make(map[uint64]int64)
totalReward := blockInfo.BlockReward*100000000 + blockInfo.TotalFeeNQT
reward := totalReward
var poolFee int64
if Cfg.FeeAccountID != 0 {
poolFee = round(float64(reward) * Cfg.PoolFeeShare)
shareInPlanckOf[Cfg.FeeAccountID] = poolFee
reward -= poolFee
}
winnerReward := round(float64(reward) * Cfg.WinnerShare)
reward -= winnerReward
shareOf, err := modelx.GetSharesOnBlock(blockInfo.Height)
if err != nil {
Logger.Error("failed to calculate shares", zap.Error(err))
}
for accountID, share := range shareOf {
shareInPlanck := round(share * float64(reward))
if accountID == blockInfo.Generator {
shareInPlanck += winnerReward
}
shareInPlanckOf[accountID] = shareInPlanck
}
// write into db
tx, err := modelx.db.Begin()
if err != nil {
Logger.Error("beginning rewardBlock transaction failed", zap.Error(err))
return
}
stmt, err := tx.Prepare("UPDATE account SET pending = pending + ? WHERE id = ?")
if err != nil {
Logger.Error("failed to prepare update pending stmt", zap.Error(err))
tx.Rollback()
return
}
for accountID, shareInPlanck := range shareInPlanckOf {
_, err := stmt.Exec(shareInPlanck, accountID)
if err != nil {
Logger.Error("increasing pending failed", zap.Error(err))
tx.Rollback()
return
}
}
sql := "UPDATE block SET winner_verified = 1, reward = ?, winner_id = ? WHERE height = ?"
if _, err := tx.Exec(sql, totalReward, blockInfo.Generator, blockInfo.Height); err != nil {
Logger.Error("udpate won block failed", zap.Error(err))
tx.Rollback()
return
}
if err := tx.Commit(); err != nil {
Logger.Error("rewardBlock transaction failed", zap.Error(err))
return
}
// udpate cache, separate loop, because we don't want to lock inside the transaction
for accountID, shareInPlanck := range shareInPlanckOf {
if cachedMiner := Cache.GetMiner(accountID); cachedMiner != nil {
cachedMiner.Lock()
cachedMiner.Pending += shareInPlanck
cachedMiner.Unlock()
}
}
}
func (modelx *Modelx) validateTransactions() {
var txsToValidate []uint64
err := modelx.db.Select(&txsToValidate, `SELECT transaction_id FROM transaction WHERE
block_height IS NULL AND
created < NOW() - INTERVAL 1 DAY AND
transaction_id IS NOT NULL`)
if err != nil {
Logger.Error("get unconfirmed transactions")
return
}
for _, tx := range txsToValidate {
txInfo, querySuccessful, err := modelx.walletHandler.GetTransaction(tx)
if !querySuccessful {
// network or other error, can't be sure if the transaction made it into the chain
continue
}
if err != nil {
Logger.Warn("tx did not make it into blockchain", zap.Uint64("tx_id", tx))
modelx.db.MustExec("UPDATE transaction SET transaction_id = NULL WHERE transaction_id = ?",
tx)
continue
}
modelx.db.MustExec(`
IF EXISTS(SELECT 1 FROM block WHERE height = ?) THEN
UPDATE transaction SET block_height = ? WHERE transaction_id = ?;
ELSE
DELETE FROM transaction WHERE transaction_id = ?;
END IF;`, txInfo.Height, txInfo.Height, tx, tx)
}
}
func (modelx *Modelx) sendMoney() {
var txs []uint64
err := modelx.db.Select(&txs, `SELECT id FROM transaction WHERE
block_height IS NULL AND
transaction_id IS NULL`)
if err != nil {
Logger.Error("fetch transaction ids", zap.Error(err))
return
}
type recipToAmount struct {
Recip uint64 `db:"recipient_id"`
Amount int64
}
for _, tx := range txs {
var recipToAmounts []recipToAmount
err := modelx.db.Select(&recipToAmounts, `SELECT
recipient_id "recipient_id",
amount "amount"
FROM transaction_recipient WHERE transaction_id = ?`, tx)
if err != nil {
Logger.Error("fetch recips and amounts", zap.Error(err))
continue
}
var txID uint64
if len(recipToAmounts) == 1 {
txID, err = modelx.walletHandler.SendPayment(recipToAmounts[0].Recip,
recipToAmounts[0].Amount)
} else {
idToAmount := make(map[uint64]int64)
for _, ra := range recipToAmounts {
idToAmount[ra.Recip] = ra.Amount
}
txID, err = modelx.walletHandler.SendPayments(idToAmount)
}
if err != nil {
Logger.Error("send payment", zap.Error(err))
continue
}
// TODO: if this fails then there is the risk of a double payout
// the only way that I can think of avoiding this currently is:
// 1. update a new field (e.g. prepare) in a must exec statement before sending the money
// 2. check if there are transactions without transaction_ids but with the prepare field set
// 3. check for recent transactions of the account in the blockchain, where we did not save any
// transaction_ids
// 4. analyse those transactions and update the transation_id field if needed
modelx.db.MustExec(`UPDATE transaction SET transaction_id = ?,
created = NOW() WHERE id = ?`, txID, tx)
}