OSDN Git Service

add broadcast block signature (#139)
[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         now := uint64(time.Now().UnixNano() / 1e6)
30         if b.Timestamp < (parent.Timestamp + consensus.BlockTimeInterval) {
31                 return errBadTimestamp
32         }
33         if b.Timestamp > (now + consensus.MaxTimeOffsetMs) {
34                 return errBadTimestamp
35         }
36
37         return nil
38 }
39
40 func checkCoinbaseAmount(b *bc.Block, amount uint64) error {
41         if len(b.Transactions) == 0 {
42                 return errors.Wrap(ErrWrongCoinbaseTransaction, "block is empty")
43         }
44
45         tx := b.Transactions[0]
46         if len(tx.TxHeader.ResultIds) != 1 {
47                 return errors.Wrap(ErrWrongCoinbaseTransaction, "have more than 1 output")
48         }
49
50         var SourceAmount uint64
51         switch output := tx.Entries[*tx.TxHeader.ResultIds[0]].(type) {
52         case *bc.IntraChainOutput:
53                 SourceAmount = output.Source.Value.Amount
54         case *bc.VoteOutput:
55                 SourceAmount = output.Source.Value.Amount
56         default:
57                 return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", tx.TxHeader.ResultIds[0].Bytes(), output)
58         }
59
60         if SourceAmount != amount {
61                 return errors.Wrap(ErrWrongCoinbaseTransaction, "dismatch output amount")
62         }
63         return nil
64 }
65
66 // ValidateBlockHeader check the block's header
67 func ValidateBlockHeader(b *bc.Block, parent *state.BlockNode) error {
68         if b.Version != 1 {
69                 return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", parent.Version, b.Version)
70         }
71         if b.Height != parent.Height+1 {
72                 return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", parent.Height, b.Height)
73         }
74         if parent.Hash != *b.PreviousBlockId {
75                 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", parent.Hash.Bytes(), b.PreviousBlockId.Bytes())
76         }
77
78         return checkBlockTime(b, parent)
79 }
80
81 // ValidateBlock validates a block and the transactions within.
82 func ValidateBlock(b *bc.Block, parent *state.BlockNode) error {
83         startTime := time.Now()
84         if err := ValidateBlockHeader(b, parent); err != nil {
85                 return err
86         }
87
88         blockGasSum := uint64(0)
89         coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
90         b.TransactionStatus = bc.NewTransactionStatus()
91
92         for i, tx := range b.Transactions {
93                 gasStatus, err := ValidateTx(tx, b)
94                 if !gasStatus.GasValid {
95                         return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
96                 }
97
98                 if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
99                         return err
100                 }
101                 coinbaseAmount += gasStatus.BTMValue
102                 if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
103                         return errOverBlockLimit
104                 }
105         }
106
107         if err := checkCoinbaseAmount(b, coinbaseAmount); err != nil {
108                 return err
109         }
110
111         txMerkleRoot, err := types.TxMerkleRoot(b.Transactions)
112         if err != nil {
113                 return errors.Wrap(err, "computing transaction id merkle root")
114         }
115         if txMerkleRoot != *b.TransactionsRoot {
116                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction id merkle root. compute: %v, given: %v", txMerkleRoot, *b.TransactionsRoot)
117         }
118
119         txStatusHash, err := types.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
120         if err != nil {
121                 return errors.Wrap(err, "computing transaction status merkle root")
122         }
123         if txStatusHash != *b.TransactionStatusHash {
124                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction status merkle root")
125         }
126
127         log.WithFields(log.Fields{
128                 "module":   logModule,
129                 "height":   b.Height,
130                 "hash":     b.ID.String(),
131                 "duration": time.Since(startTime),
132         }).Debug("finish validate block")
133         return nil
134 }