OSDN Git Service

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