OSDN Git Service

aa18b552bcb4e58b020c1197a6eddd3e4cc3b3c0
[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) 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
73         if err := engine.GDpos.CheckBlockHeader(block.BlockHeader); err != nil {
74                 return err
75         }
76
77         if err := engine.GDpos.IsValidBlockCheckIrreversibleBlock(block.Height, block.Hash()); err != nil {
78                 return err
79         }
80
81         return nil
82 }
83
84 // ValidateBlock validates a block and the transactions within.
85 func ValidateBlock(b *bc.Block, parent *state.BlockNode, block *types.Block, c chain.Chain) error {
86         startTime := time.Now()
87         if err := ValidateBlockHeader(b, block, parent, c); err != nil {
88                 return err
89         }
90
91         if err := engine.GDpos.CheckBlock(*block, true); err != nil {
92                 return err
93         }
94
95         blockGasSum := uint64(0)
96         coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
97         b.TransactionStatus = bc.NewTransactionStatus()
98         for i, tx := range b.Transactions {
99                 gasStatus, err := ValidateTx(tx, b)
100                 if !gasStatus.GasValid {
101                         return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
102                 }
103
104                 if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
105                         return err
106                 }
107                 coinbaseAmount += gasStatus.BTMValue
108                 if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
109                         return errOverBlockLimit
110                 }
111         }
112
113         if err := checkCoinbaseAmount(b, coinbaseAmount); err != nil {
114                 return err
115         }
116
117         txMerkleRoot, err := types.TxMerkleRoot(b.Transactions)
118         if err != nil {
119                 return errors.Wrap(err, "computing transaction id merkle root")
120         }
121         if txMerkleRoot != *b.TransactionsRoot {
122                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction id merkle root")
123         }
124
125         txStatusHash, err := types.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
126         if err != nil {
127                 return errors.Wrap(err, "computing transaction status merkle root")
128         }
129         if txStatusHash != *b.TransactionStatusHash {
130                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction status merkle root")
131         }
132
133         log.WithFields(log.Fields{
134                 "module":   logModule,
135                 "height":   b.Height,
136                 "hash":     b.ID.String(),
137                 "duration": time.Since(startTime),
138         }).Debug("finish validate block")
139         return nil
140 }