This repository has been archived by the owner on Jul 30, 2019. It is now read-only.
/
block.go
753 lines (665 loc) · 17.6 KB
/
block.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
// Copyright (C) 2018 MediBloc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
package core
import (
"github.com/medibloc/go-medibloc/common"
corestate "github.com/medibloc/go-medibloc/core/state"
"github.com/medibloc/go-medibloc/crypto/signature"
"github.com/medibloc/go-medibloc/storage"
"github.com/medibloc/go-medibloc/util"
"github.com/medibloc/go-medibloc/util/byteutils"
"github.com/medibloc/go-medibloc/util/logging"
"github.com/sirupsen/logrus"
)
// Block represents block with actual state tries
type Block struct {
*BlockData
state *BlockState
sealed bool
}
// FromBlockData converts block data to block.
func (b *Block) FromBlockData(bd *BlockData, consensus Consensus, storage storage.Storage) error {
var err error
b.BlockData = bd
b.state, err = NewBlockState(bd, consensus, storage)
if err != nil {
logging.Console().WithFields(logrus.Fields{
"block": bd,
"err": err,
}).Error("Failed to create new block state.")
return err
}
b.sealed = true
return nil
}
// InitChild return initial child block for verifying or making block
func (b *Block) InitChild(coinbase common.Address) (*Block, error) {
bs, err := b.state.Clone()
if err != nil {
return nil, err
}
bs.cpuUsage = 0
bs.netUsage = 0
newPrice, err := b.CalcChildPrice()
if err != nil {
return nil, err
}
bs.cpuPrice = newPrice.CPUPrice
bs.netPrice = newPrice.NetPrice
return &Block{
BlockData: &BlockData{
BlockHeader: &BlockHeader{
hash: nil,
parentHash: b.Hash(),
accStateRoot: nil,
txStateRoot: nil,
dposRoot: nil,
coinbase: coinbase,
reward: util.NewUint128(),
supply: b.supply.DeepCopy(),
timestamp: 0,
chainID: b.chainID,
sign: nil,
cpuPrice: util.NewUint128(),
cpuUsage: 0,
netPrice: util.NewUint128(),
netUsage: 0,
},
transactions: make([]*Transaction, 0),
height: b.height + 1,
},
state: bs,
sealed: false,
}, nil
}
// CreateChildWithBlockData returns child block by executing block data on parent block.
func (b *Block) CreateChildWithBlockData(bd *BlockData, consensus Consensus) (child *Block, err error) {
// Prepare Execution
child, err = b.InitChild(bd.coinbase)
if err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to make child block for execution on parent block")
return nil, err
}
child.BlockData = bd
child.State().SetTimestamp(bd.timestamp)
// TODO call block.Timestamp() instead
err = child.Prepare()
if err != nil {
return nil, err
}
if err := child.verifyExecution(b, consensus); err != nil {
return nil, err
}
err = child.Flush()
if err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to flush state")
return nil, err
}
return child, nil
}
// State returns block state
func (b *Block) State() *BlockState {
return b.state
}
// Sealed returns sealed
func (b *Block) Sealed() bool {
return b.sealed
}
// Seal writes state root hashes and block hash in block header
func (b *Block) Seal() error {
var err error
if b.sealed {
return ErrBlockAlreadySealed
}
b.timestamp = b.state.timestamp
b.reward = b.state.Reward()
b.supply = b.state.Supply()
b.cpuPrice = b.state.cpuPrice
b.cpuUsage = b.state.cpuUsage
b.netPrice = b.state.netPrice
b.netUsage = b.state.netUsage
b.accStateRoot, err = b.state.AccountsRoot()
if err != nil {
return err
}
b.txStateRoot, err = b.state.TxsRoot()
if err != nil {
return err
}
b.dposRoot, err = b.state.dposState.RootBytes()
if err != nil {
return err
}
blockHash, err := b.CalcHash()
if err != nil {
return err
}
b.hash = blockHash
b.sealed = true
return nil
}
// ExecuteTransaction on given block state
func (b *Block) ExecuteTransaction(tx *Transaction) (*Receipt, error) {
// Verify that transaction is executable
exeTx, err := TxConv(tx)
if err != nil {
return nil, err
}
if err := b.checkNonce(tx); err != nil {
return nil, err
}
if err := b.checkBandwidth(exeTx); err != nil {
return nil, err
}
usage, err := b.calcPointUsage(exeTx)
if err != nil {
return nil, err
}
if err := b.checkAvailablePoint(tx, exeTx, usage); err != nil {
return nil, err
}
execErr, err := b.Atomic(exeTx.Execute)
if err != nil {
return nil, ErrAtomicError
}
if execErr != nil {
return b.makeErrorReceipt(exeTx.Bandwidth(), usage, execErr), nil
}
return b.makeSuccessReceipt(exeTx.Bandwidth(), usage), nil
}
func (b *Block) receiptTemplate(bw *common.Bandwidth, point *util.Uint128) *Receipt {
receipt := new(Receipt)
receipt.SetTimestamp(b.state.timestamp)
receipt.SetHeight(b.Height())
receipt.SetCPUUsage(bw.CPUUsage())
receipt.SetNetUsage(bw.NetUsage())
receipt.SetPoints(point)
receipt.SetExecuted(false)
receipt.SetError(nil)
return receipt
}
func (b *Block) makeErrorReceipt(bw *common.Bandwidth, point *util.Uint128, err error) *Receipt {
receipt := b.receiptTemplate(bw, point)
receipt.SetError([]byte(err.Error()))
return receipt
}
func (b *Block) makeSuccessReceipt(bw *common.Bandwidth, point *util.Uint128) *Receipt {
receipt := b.receiptTemplate(bw, point)
receipt.SetExecuted(true)
return receipt
}
func (b *Block) checkNonce(tx *Transaction) error {
from, err := b.state.GetAccount(tx.From())
if err != nil {
return err
}
if tx.Nonce() != from.Nonce+1 {
return ErrNonceNotExecutable
}
return nil
}
func (b *Block) checkBandwidth(exeTx ExecutableTx) error {
if err := b.state.checkBandwidthLimit(exeTx.Bandwidth()); err != nil {
return err
}
return nil
}
func (b *Block) checkAvailablePoint(tx *Transaction, exeTx ExecutableTx, usage *util.Uint128) error {
if tx.HasPayer() {
payer, err := b.state.GetAccount(tx.Payer())
if err != nil {
return err
}
return checkPayerAccountPoint(payer, usage)
}
from, err := b.state.GetAccount(tx.From())
if err != nil {
return err
}
return checkFromAccountPoint(from, exeTx, usage)
}
func checkPayerAccountPoint(payer *corestate.Account, usage *util.Uint128) error {
if payer.Points.Cmp(usage) < 0 {
return ErrPointNotEnough
}
return nil
}
func checkFromAccountPoint(from *corestate.Account, exeTx ExecutableTx, usage *util.Uint128) (err error) {
avail := from.Points
neg, abs := exeTx.PointChange()
if neg {
avail, err = avail.Sub(abs)
} else {
avail, err = avail.Add(abs)
}
if err != nil && err != util.ErrUint128Underflow {
return err
}
if err == util.ErrUint128Underflow {
avail = util.Uint128Zero()
}
if avail.Cmp(usage) < 0 {
return ErrPointNotEnough
}
return nil
}
func (b *Block) calcPointUsage(exeTx ExecutableTx) (*util.Uint128, error) {
return exeTx.Bandwidth().CalcPoints(b.state.Price())
}
// verifyExecution executes txs in block and verify root hashes using block header
func (b *Block) verifyExecution(parent *Block, consensus Consensus) error {
if err := b.SetMintDynasty(parent, consensus); err != nil {
return err
}
if err := consensus.VerifyProposer(b); err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"blockData": b.BlockData,
"parent": parent,
}).Warn("Failed to verifyProposer")
return err
}
if err := b.executeAll(); err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"block": b,
}).Error("Failed to execute block transactions.")
return err
}
if err := b.PayReward(parent.Supply()); err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"block": b,
}).Error("Failed to pay block reward.")
return err
}
if err := b.verifyState(); err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"block": b,
}).Error("Failed to verify block state.")
return err
}
return nil
}
// executeAll executes all txs in block
func (b *Block) executeAll() error {
for _, transaction := range b.transactions {
err := b.execute(transaction)
if err != nil {
return err
}
}
return nil
}
// execute executes a transaction.
func (b *Block) execute(tx *Transaction) error {
receipt, err := b.ExecuteTransaction(tx)
if err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"transaction": tx,
"block": b,
}).Debug("Failed to execute transaction.")
return err
}
if !receipt.Equal(tx.Receipt()) {
logging.Console().WithFields(logrus.Fields{
"err": err,
"transaction": tx,
"block": b,
"receipt": receipt,
}).Warn("transaction receipt is wrong")
return ErrWrongReceipt
}
if err := b.AcceptTransaction(tx); err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
"transaction": tx,
"block": b,
}).Warn("Failed to accept a transaction.")
return err
}
return nil
}
// SetMintDynasty sets mint dynasty of block's timestamp.
func (b *Block) SetMintDynasty(parent *Block, consensus Consensus) error {
mintDynasty, err := consensus.MakeMintDynasty(b.state.timestamp, parent.State())
if err != nil && err == ErrSameDynasty {
return nil
}
if err != nil {
return err
}
execErr, err := b.Atomic(func(block *Block) error {
return block.state.DposState().SetDynasty(mintDynasty)
})
if err != nil {
return err
}
if execErr != nil {
return execErr
}
return nil
}
// AcceptTransaction accepts a transaction.
func (b *Block) AcceptTransaction(tx *Transaction) error {
if tx.Receipt() == nil {
return ErrNoTransactionReceipt
}
from, err := b.state.GetAccount(tx.From())
if err != nil {
return err
}
from.Nonce++
var payer *corestate.Account
if tx.HasPayer() {
payer, err = b.state.GetAccount(tx.Payer())
if err != nil {
return err
}
} else {
payer = from
}
payer.Points, err = payer.Points.Sub(tx.Receipt().Points())
if err != nil {
logging.Console().WithFields(logrus.Fields{
"tx": tx,
"payer": payer,
"err": err,
}).Error("Failed to subtract point.")
return err
}
execErr, err := b.Atomic(func(block *Block) error {
if err := block.state.PutAccount(from); err != nil {
return err
}
if tx.HasPayer() {
if err := block.state.PutAccount(payer); err != nil {
return err
}
}
return block.state.PutTx(tx)
})
if err != nil {
return err
}
if execErr != nil {
return err
}
b.state.cpuUsage += tx.Receipt().CPUUsage()
b.state.netUsage += tx.Receipt().NetUsage()
return nil
}
// PayReward add reward to coinbase and update reward and supply
func (b *Block) PayReward(parentSupply *util.Uint128) error {
if b.coinbase.Equals(common.Address{}) {
return ErrCoinbaseNotSet
}
reward, err := calcMintReward(parentSupply)
if err != nil {
return err
}
supply, err := parentSupply.Add(reward)
if err != nil {
return err
}
acc, err := b.state.GetAccount(b.coinbase)
if err != nil {
return err
}
acc.Balance, err = acc.Balance.Add(reward)
if err != nil {
return err
}
execErr, err := b.Atomic(func(block *Block) error {
return block.state.PutAccount(acc)
})
if err != nil {
return err
}
if execErr != nil {
return execErr
}
b.state.SetReward(reward)
b.state.SetSupply(supply)
return nil
}
// calcMintReward returns calculated block produce reward
func calcMintReward(parentSupply *util.Uint128) (*util.Uint128, error) {
reward, err := parentSupply.MulWithRat(InflationRate)
if err != nil {
return nil, err
}
roundDownDecimal := util.NewUint128FromUint(InflationRoundDown)
reward, err = reward.Div(roundDownDecimal)
if err != nil {
return nil, err
}
reward, err = reward.Mul(roundDownDecimal)
if err != nil {
return nil, err
}
return reward, nil
}
// verifyState verifies block states comparing with root hashes in header
func (b *Block) verifyState() error {
if b.state.CPUPrice().Cmp(b.CPUPrice()) != 0 {
logging.Console().WithFields(logrus.Fields{
"state": b.state.CPUPrice(),
"header": b.CPUPrice(),
}).Warn("Failed to verify CPU price.")
return ErrInvalidCPUPrice
}
if b.state.NetPrice().Cmp(b.NetPrice()) != 0 {
logging.Console().WithFields(logrus.Fields{
"state": b.state.NetPrice(),
"header": b.NetPrice(),
}).Warn("Failed to verify Net price.")
return ErrInvalidNetPrice
}
if b.state.Reward().Cmp(b.Reward()) != 0 {
logging.Console().WithFields(logrus.Fields{
"state": b.state.Reward(),
"header": b.Reward(),
}).Warn("Failed to verify reward.")
return ErrInvalidBlockReward
}
if b.state.Supply().Cmp(b.Supply()) != 0 {
logging.Console().WithFields(logrus.Fields{
"state": b.state.Supply(),
"header": b.Supply(),
}).Warn("Failed to verify supply.")
return ErrInvalidBlockSupply
}
accRoot, err := b.state.AccountsRoot()
if err != nil {
return err
}
if !byteutils.Equal(accRoot, b.AccStateRoot()) {
logging.Console().WithFields(logrus.Fields{
"state": byteutils.Bytes2Hex(accRoot),
"header": byteutils.Bytes2Hex(b.AccStateRoot()),
}).Warn("Failed to verify accounts root.")
return ErrInvalidBlockAccountsRoot
}
txsRoot, err := b.state.TxsRoot()
if err != nil {
return err
}
if !byteutils.Equal(txsRoot, b.TxStateRoot()) {
logging.WithFields(logrus.Fields{
"state": byteutils.Bytes2Hex(txsRoot),
"header": byteutils.Bytes2Hex(b.TxStateRoot()),
}).Warn("Failed to verify transactions root.")
return ErrInvalidBlockTxsRoot
}
dposRoot, err := b.state.DposState().RootBytes()
if err != nil {
logging.Console().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to get dpos state's root bytes.")
return err
}
if !byteutils.Equal(dposRoot, b.DposRoot()) {
logging.WithFields(logrus.Fields{
"state": byteutils.Bytes2Hex(dposRoot),
"header": byteutils.Bytes2Hex(b.DposRoot()),
}).Warn("Failed to get state of candidate root.")
return ErrInvalidBlockDposRoot
}
return nil
}
// SignThis sets signature info in block
func (b *Block) SignThis(signer signature.Signature) error {
if !b.Sealed() {
return ErrBlockNotSealed
}
return b.BlockData.SignThis(signer)
}
// Prepare prepare block state
func (b *Block) Prepare() error {
return b.state.prepare()
}
// BeginBatch makes block state update possible
func (b *Block) BeginBatch() error {
return b.state.beginBatch()
}
// RollBack rolls back block state batch updates
func (b *Block) RollBack() error {
return b.state.rollBack()
}
// Commit commit changes of block state
func (b *Block) Commit() error {
return b.state.commit()
}
// Flush saves batch updates to storage
func (b *Block) Flush() error {
return b.state.flush()
}
// Atomic executes a given function in atomic way. execErr is an return error of
// a given function. err is an error of atomic processing.
func (b *Block) Atomic(batch func(block *Block) error) (execErr error, err error) {
if err := b.BeginBatch(); err != nil {
return nil, ErrAtomicError
}
if execErr := batch(b); execErr != nil {
if err := b.RollBack(); err != nil {
return nil, ErrAtomicError
}
return execErr, nil
}
if err := b.Commit(); err != nil {
return nil, ErrAtomicError
}
return nil, nil
}
// GetBlockData returns data part of block
func (b *Block) GetBlockData() *BlockData {
return b.BlockData
}
// CalcChildPrice calculate child block's price
func (b *Block) CalcChildPrice() (common.Price, error) {
cpu, err := b.calcChildCPUPrice()
if err != nil {
return common.Price{}, err
}
net, err := b.calcChildNetPrice()
if err != nil {
return common.Price{}, err
}
return common.Price{
CPUPrice: cpu,
NetPrice: net,
}, nil
}
type calcPriceParam struct {
threshold uint64
limit uint64
usage uint64
price *util.Uint128
supply *util.Uint128
}
func (b *Block) calcChildCPUPrice() (*util.Uint128, error) {
return calcPrice(&calcPriceParam{
threshold: cpuThreshold(),
limit: CPULimit,
usage: b.cpuUsage,
price: b.cpuPrice,
supply: b.supply,
})
}
func (b *Block) calcChildNetPrice() (*util.Uint128, error) {
return calcPrice(&calcPriceParam{
threshold: netThreshold(),
limit: NetLimit,
usage: b.netUsage,
price: b.netPrice,
supply: b.supply,
})
}
func calcPrice(param *calcPriceParam) (*util.Uint128, error) {
var (
newPrice *util.Uint128
err error
)
if param.usage <= param.threshold {
newPrice, err = decreasePrice(param.price)
} else {
newPrice, err = increasePrice(param.price)
}
if err != nil {
return nil, err
}
minPrice, err := minPricePerBandwidth(param.supply, param.limit)
if err != nil {
return nil, err
}
if minPrice.Cmp(newPrice) > 0 {
return minPrice, nil
}
return newPrice, nil
}
func minPricePerBandwidth(supply *util.Uint128, limit uint64) (*util.Uint128, error) {
supplyPerBlock, err := supply.Div(util.NewUint128FromUint(NumberOfBlocksInSingleTimeWindow))
if err != nil {
return nil, err
}
supplyPerBandwidth, err := supplyPerBlock.Div(util.NewUint128FromUint(limit))
if err != nil {
return nil, err
}
minPricePerBandwidth, err := supplyPerBandwidth.MulWithRat(PriceMinimumRate)
if err != nil {
return nil, err
}
return minPricePerBandwidth, err
}
func increasePrice(prev *util.Uint128) (*util.Uint128, error) {
return prev.MulWithRat(PriceIncreaseRate)
}
func decreasePrice(prev *util.Uint128) (*util.Uint128, error) {
return prev.MulWithRat(PriceDecreaseRate)
}
func cpuThreshold() uint64 {
return CPULimit * ThresholdRatioNum / ThresholdRatioDenom
}
func netThreshold() uint64 {
return NetLimit * ThresholdRatioNum / ThresholdRatioDenom
}