OSDN Git Service

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