OSDN Git Service

new repo
[bytom/vapor.git] / protocol / validation / block.go
1 package validation
2
3 import (
4         "encoding/hex"
5         "time"
6
7         log "github.com/sirupsen/logrus"
8
9         "github.com/vapor/consensus"
10         "github.com/vapor/crypto/ed25519/chainkd"
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, parent *state.BlockNode) 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 b.Bits != parent.CalcNextBits() {
67                 return errBadBits
68         }
69         if parent.Hash != *b.PreviousBlockId {
70                 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", parent.Hash.Bytes(), b.PreviousBlockId.Bytes())
71         }
72         if err := checkBlockTime(b, parent); err != nil {
73                 return err
74         }
75         return nil
76 }
77
78 // ValidateBlock validates a block and the transactions within.
79 func ValidateBlock(b *bc.Block, parent *state.BlockNode, block *types.Block, authoritys map[string]string, position uint64) error {
80         startTime := time.Now()
81         if err := ValidateBlockHeader(b, parent); err != nil {
82                 return err
83         }
84         time.Sleep(3 * time.Second)
85         // 验证出块人
86         controlProgram := hex.EncodeToString(block.Proof.ControlProgram)
87         xpub := &chainkd.XPub{}
88         xpub.UnmarshalText([]byte(authoritys[controlProgram]))
89
90         msg := block.BlockCommitment.TransactionsMerkleRoot.Bytes()
91         if !xpub.Verify(msg, block.Proof.Sign) {
92                 return errors.New("Verification signature failed")
93         }
94
95         blockGasSum := uint64(0)
96         coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
97         b.TransactionStatus = bc.NewTransactionStatus()
98
99         for i, tx := range b.Transactions {
100                 gasStatus, err := ValidateTx(tx, b)
101                 if !gasStatus.GasValid {
102                         return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
103                 }
104
105                 if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
106                         return err
107                 }
108                 coinbaseAmount += gasStatus.BTMValue
109                 if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
110                         return errOverBlockLimit
111                 }
112         }
113
114         if err := checkCoinbaseAmount(b, coinbaseAmount); err != nil {
115                 return err
116         }
117
118         txMerkleRoot, err := types.TxMerkleRoot(b.Transactions)
119         if err != nil {
120                 return errors.Wrap(err, "computing transaction id merkle root")
121         }
122         if txMerkleRoot != *b.TransactionsRoot {
123                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction id merkle root")
124         }
125
126         txStatusHash, err := types.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
127         if err != nil {
128                 return errors.Wrap(err, "computing transaction status merkle root")
129         }
130         if txStatusHash != *b.TransactionStatusHash {
131                 return errors.WithDetailf(errMismatchedMerkleRoot, "transaction status merkle root")
132         }
133
134         log.WithFields(log.Fields{
135                 "module":   logModule,
136                 "height":   b.Height,
137                 "hash":     b.ID.String(),
138                 "duration": time.Since(startTime),
139         }).Debug("finish validate block")
140         return nil
141 }