OSDN Git Service

Add issue for claim
[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         output, err := tx.Output(*tx.TxHeader.ResultIds[0])
46         if err != nil {
47                 return err
48         }
49
50         if output.Source.Value.Amount != amount {
51                 return errors.Wrap(ErrWrongCoinbaseTransaction, "dismatch output amount")
52         }
53         return nil
54 }
55
56 // ValidateBlockHeader check the block's header
57 func ValidateBlockHeader(b *bc.Block, block *types.Block, parent *state.BlockNode) error {
58         if b.Version != 1 {
59                 return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", parent.Version, b.Version)
60         }
61         if b.Height != parent.Height+1 {
62                 return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", parent.Height, b.Height)
63         }
64         if parent.Hash != *b.PreviousBlockId {
65                 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", parent.Hash.Bytes(), b.PreviousBlockId.Bytes())
66         }
67         if err := checkBlockTime(b, parent); err != nil {
68                 return err
69         }
70
71         return nil
72 }
73
74 // ValidateBlock validates a block and the transactions within.
75 func ValidateBlock(b *bc.Block, parent *state.BlockNode, block *types.Block) error {
76         startTime := time.Now()
77         if err := ValidateBlockHeader(b, block, parent); err != nil {
78                 return err
79         }
80
81         blockGasSum := uint64(0)
82         coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
83         b.TransactionStatus = bc.NewTransactionStatus()
84         for i, tx := range b.Transactions {
85                 gasStatus, err := ValidateTx(tx, b)
86                 if !gasStatus.GasValid {
87                         return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
88                 }
89
90                 if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
91                         return err
92                 }
93                 coinbaseAmount += gasStatus.BTMValue
94                 if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
95                         return errOverBlockLimit
96                 }
97         }
98
99         if err := checkCoinbaseAmount(b, coinbaseAmount); err != nil {
100                 return err
101         }
102
103         txMerkleRoot, err := types.TxMerkleRoot(b.Transactions)
104         if err != nil {
105                 return errors.Wrap(err, "computing transaction id merkle root")
106         }
107         if txMerkleRoot != *b.TransactionsRoot {
108                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction id merkle root")
109         }
110
111         txStatusHash, err := types.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
112         if err != nil {
113                 return errors.Wrap(err, "computing transaction status merkle root")
114         }
115         if txStatusHash != *b.TransactionStatusHash {
116                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction status merkle root")
117         }
118
119         log.WithFields(log.Fields{
120                 "module":   logModule,
121                 "height":   b.Height,
122                 "hash":     b.ID.String(),
123                 "duration": time.Since(startTime),
124         }).Debug("finish validate block")
125         return nil
126 }