OSDN Git Service

3f8f522c9005d6d9436cd46c0709645aec5e6cc8
[bytom/vapor.git] / protocol / validation / block.go
1 package validation
2
3 import (
4         "time"
5
6         log "github.com/sirupsen/logrus"
7
8         "github.com/vapor/chain"
9         "github.com/vapor/consensus"
10         engine "github.com/vapor/consensus/consensus"
11         "github.com/vapor/errors"
12         "github.com/vapor/protocol/bc"
13         "github.com/vapor/protocol/bc/types"
14         "github.com/vapor/protocol/state"
15 )
16
17 const logModule = "leveldb"
18
19 var (
20         errBadTimestamp          = errors.New("block timestamp is not in the valid range")
21         errBadBits               = errors.New("block bits is invalid")
22         errMismatchedBlock       = errors.New("mismatched block")
23         errMismatchedMerkleRoot  = errors.New("mismatched merkle root")
24         errMisorderedBlockHeight = errors.New("misordered block height")
25         errOverBlockLimit        = errors.New("block's gas is over the limit")
26         errWorkProof             = errors.New("invalid difficulty proof of work")
27         errVersionRegression     = errors.New("version regression")
28 )
29
30 func checkBlockTime(b *bc.Block, parent *state.BlockNode) error {
31         if b.Timestamp > uint64(time.Now().Unix())+consensus.MaxTimeOffsetSeconds {
32                 return errBadTimestamp
33         }
34
35         if b.Timestamp <= parent.CalcPastMedianTime() {
36                 return errBadTimestamp
37         }
38         return nil
39 }
40
41 func checkCoinbaseAmount(b *bc.Block, amount uint64) error {
42         if len(b.Transactions) == 0 {
43                 return errors.Wrap(ErrWrongCoinbaseTransaction, "block is empty")
44         }
45
46         tx := b.Transactions[0]
47         output, err := tx.Output(*tx.TxHeader.ResultIds[0])
48         if err != nil {
49                 return err
50         }
51
52         if output.Source.Value.Amount != amount {
53                 return errors.Wrap(ErrWrongCoinbaseTransaction, "dismatch output amount")
54         }
55         return nil
56 }
57
58 // ValidateBlockHeader check the block's header
59 func ValidateBlockHeader(b *bc.Block, block *types.Block, parent *state.BlockNode, c chain.Chain, engine engine.Engine) error {
60         if b.Version < parent.Version {
61                 return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", parent.Version, b.Version)
62         }
63         if b.Height != parent.Height+1 {
64                 return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", parent.Height, b.Height)
65         }
66         if parent.Hash != *b.PreviousBlockId {
67                 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", parent.Hash.Bytes(), b.PreviousBlockId.Bytes())
68         }
69         if err := checkBlockTime(b, parent); err != nil {
70                 return err
71         }
72         if err := engine.VerifySeal(c, &block.BlockHeader); err != nil {
73                 return err
74         }
75
76         return nil
77 }
78
79 // ValidateBlock validates a block and the transactions within.
80 func ValidateBlock(b *bc.Block, parent *state.BlockNode, block *types.Block, c chain.Chain, engine engine.Engine) error {
81         startTime := time.Now()
82         if err := ValidateBlockHeader(b, block, parent, c, engine); err != nil {
83                 return err
84         }
85
86         blockGasSum := uint64(0)
87         coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
88         b.TransactionStatus = bc.NewTransactionStatus()
89         for i, tx := range b.Transactions {
90                 gasStatus, err := ValidateTx(tx, b)
91                 if !gasStatus.GasValid {
92                         return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
93                 }
94
95                 if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
96                         return err
97                 }
98                 coinbaseAmount += gasStatus.BTMValue
99                 if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
100                         return errOverBlockLimit
101                 }
102         }
103
104         if err := checkCoinbaseAmount(b, coinbaseAmount); err != nil {
105                 return err
106         }
107
108         txMerkleRoot, err := types.TxMerkleRoot(b.Transactions)
109         if err != nil {
110                 return errors.Wrap(err, "computing transaction id merkle root")
111         }
112         if txMerkleRoot != *b.TransactionsRoot {
113                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction id merkle root")
114         }
115
116         txStatusHash, err := types.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
117         if err != nil {
118                 return errors.Wrap(err, "computing transaction status merkle root")
119         }
120         if txStatusHash != *b.TransactionStatusHash {
121                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction status merkle root")
122         }
123
124         log.WithFields(log.Fields{
125                 "module":   logModule,
126                 "height":   b.Height,
127                 "hash":     b.ID.String(),
128                 "duration": time.Since(startTime),
129         }).Debug("finish validate block")
130         return nil
131 }