OSDN Git Service

rename (#465)
[bytom/vapor.git] / protocol / validation / block.go
1 package validation
2
3 import (
4         "bytes"
5         "encoding/hex"
6         "time"
7
8         log "github.com/sirupsen/logrus"
9
10         "github.com/bytom/vapor/consensus"
11         "github.com/bytom/vapor/errors"
12         "github.com/bytom/vapor/protocol/bc"
13         "github.com/bytom/vapor/protocol/bc/types"
14         "github.com/bytom/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 *types.BlockHeader) error {
31         now := uint64(time.Now().UnixNano() / 1e6)
32         if b.Timestamp < (parent.Timestamp + consensus.ActiveNetParams.BlockTimeInterval) {
33                 return errBadTimestamp
34         }
35         if b.Timestamp > (now + consensus.ActiveNetParams.MaxTimeOffsetMs) {
36                 return errBadTimestamp
37         }
38
39         return nil
40 }
41
42 func checkCoinbaseTx(b *bc.Block, rewards []state.CoinbaseReward) error {
43         if len(b.Transactions) == 0 {
44                 return errors.Wrap(ErrWrongCoinbaseTransaction, "block is empty")
45         }
46
47         tx := b.Transactions[0]
48         if len(tx.TxHeader.ResultIds) != len(rewards)+1 {
49                 return errors.Wrapf(ErrWrongCoinbaseTransaction, "dismatch number of outputs, got:%d, want:%d", len(tx.TxHeader.ResultIds), len(rewards))
50         }
51
52         rewards = append([]state.CoinbaseReward{state.CoinbaseReward{Amount: uint64(0)}}, rewards...)
53         for i, output := range tx.TxHeader.ResultIds {
54                 out, err := tx.IntraChainOutput(*output)
55                 if err != nil {
56                         return err
57                 }
58
59                 if rewards[i].Amount != out.Source.Value.Amount {
60                         return errors.Wrapf(ErrWrongCoinbaseTransaction, "dismatch output amount, got:%d, want:%d", out.Source.Value.Amount, rewards[i].Amount)
61                 }
62
63                 if i == 0 {
64                         continue
65                 }
66
67                 if res := bytes.Compare(rewards[i].ControlProgram, out.ControlProgram.Code); res != 0 {
68                         return errors.Wrapf(ErrWrongCoinbaseTransaction, "dismatch output control_program, got:%s, want:%s", hex.EncodeToString(out.ControlProgram.Code), hex.EncodeToString(rewards[i].ControlProgram))
69                 }
70         }
71         return nil
72 }
73
74 // ValidateBlockHeader check the block's header
75 func ValidateBlockHeader(b *bc.Block, parent *types.BlockHeader) error {
76         if b.Version != 1 {
77                 return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", parent.Version, b.Version)
78         }
79         if b.Height != parent.Height+1 {
80                 return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", parent.Height, b.Height)
81         }
82         if parent.Hash() != *b.PreviousBlockId {
83                 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", parent.Hash().Bytes(), b.PreviousBlockId.Bytes())
84         }
85
86         return checkBlockTime(b, parent)
87 }
88
89 // ValidateBlock validates a block and the transactions within.
90 func ValidateBlock(b *bc.Block, parent *types.BlockHeader, rewards []state.CoinbaseReward) error {
91         startTime := time.Now()
92         if err := ValidateBlockHeader(b, parent); err != nil {
93                 return err
94         }
95
96         blockGasSum := uint64(0)
97         b.TransactionStatus = bc.NewTransactionStatus()
98         validateResults := ValidateTxs(b.Transactions, b)
99         for i, validateResult := range validateResults {
100                 if !validateResult.gasStatus.GasValid {
101                         return errors.Wrapf(validateResult.err, "validate of transaction %d of %d", i, len(b.Transactions))
102                 }
103
104                 if err := b.TransactionStatus.SetStatus(i, validateResult.err != nil); err != nil {
105                         return err
106                 }
107
108                 if blockGasSum += uint64(validateResult.gasStatus.GasUsed); blockGasSum > consensus.ActiveNetParams.MaxBlockGas {
109                         return errOverBlockLimit
110                 }
111         }
112
113         if err := checkCoinbaseTx(b, rewards); 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. compute: %v, given: %v", txMerkleRoot, *b.TransactionsRoot)
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. compute: %v, given: %v", txStatusHash, *b.TransactionStatusHash)
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 }