/
minorblock_validator.go
274 lines (246 loc) · 11.8 KB
/
minorblock_validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package core
import (
"errors"
"fmt"
"math/big"
"github.com/QuarkChain/goquarkchain/account"
"github.com/QuarkChain/goquarkchain/cluster/config"
"github.com/QuarkChain/goquarkchain/common"
"github.com/QuarkChain/goquarkchain/consensus"
"github.com/QuarkChain/goquarkchain/core/state"
"github.com/QuarkChain/goquarkchain/core/types"
"github.com/ethereum/go-ethereum/log"
)
// MinorBlockValidator is responsible for validating block Headers, uncles and
// processed state.
//
// MinorBlockValidator implements Validator.
type MinorBlockValidator struct {
quarkChainConfig *config.QuarkChainConfig // Chain configuration options
bc *MinorBlockChain // Canonical block chain
engine consensus.Engine // Consensus engine used for validating
branch account.Branch
logInfo string
}
// NewBlockValidator returns a new block validator which is safe for re-use
func NewBlockValidator(quarkChainConfig *config.QuarkChainConfig, blockchain *MinorBlockChain, engine consensus.Engine, branch account.Branch) *MinorBlockValidator {
validator := &MinorBlockValidator{
quarkChainConfig: quarkChainConfig,
engine: engine,
bc: blockchain,
branch: branch,
logInfo: fmt.Sprintf("minorBlock validate branch:%v", branch),
}
return validator
}
// ValidateBlock validates the given block's uncles and verifies the block
// header's transaction and uncle roots. The Headers are assumed to be already
// validated at this point.
func (v *MinorBlockValidator) ValidateBlock(mBlock types.IBlock) error {
if common.IsNil(mBlock) {
log.Error(v.logInfo, "check block err", ErrMinorBlockIsNil)
return ErrMinorBlockIsNil
}
block, ok := mBlock.(*types.MinorBlock)
if !ok {
log.Error(v.logInfo, "check block err", ErrInvalidMinorBlock)
return ErrInvalidMinorBlock
}
blockHeight := block.NumberU64()
if blockHeight < 1 {
errBlockHeight := errors.New("block.Number <1")
log.Error(v.logInfo, "err", errBlockHeight, "blockHeight", blockHeight)
return errBlockHeight
}
// Check whether the block's known, and if not, that it's linkable
if v.bc.HasBlockAndState(block.Hash()) {
log.Error(v.logInfo, "already have this block err", ErrKnownBlock, "height", block.NumberU64(), "hash", block.Hash().String())
return ErrKnownBlock
}
if !v.bc.HasBlockAndState(block.IHeader().GetParentHash()) {
if !v.bc.HasBlock(block.ParentHash()) {
log.Error(v.logInfo, "parent block do not have", consensus.ErrUnknownAncestor, "parent height", block.Header().Number-1, "hash", block.Header().ParentHash.String())
return consensus.ErrUnknownAncestor
}
log.Warn(v.logInfo, "will insert side chain", ErrPrunedAncestor, "parent height", block.Header().Number-1, "hash", block.Header().ParentHash.String(), "currHash", block.Hash().String())
return ErrPrunedAncestor
}
prevHeader := v.bc.GetHeader(block.IHeader().GetParentHash())
if common.IsNil(prevHeader) {
log.Error(v.logInfo, "parent header is not exist", ErrInvalidMinorBlock, "parent height", block.Header().Number-1, "parent hash", block.Header().ParentHash.String())
return ErrInvalidMinorBlock
}
if blockHeight != prevHeader.NumberU64()+1 {
log.Error(v.logInfo, "err", ErrHeightMismatch, "blockHeight", blockHeight, "prevHeader", prevHeader.NumberU64())
return ErrHeightMismatch
}
if block.Branch().Value != v.branch.Value {
log.Error(v.logInfo, "err", ErrBranch, "block.branch", block.Branch().Value, "current branch", v.branch.Value)
return ErrBranch
}
if block.IHeader().GetTime() <= prevHeader.GetTime() {
log.Error(v.logInfo, "err", ErrTime, "block.Time", block.IHeader().GetTime(), "prevHeader.Time", prevHeader.GetTime())
return ErrTime
}
if block.Header().MetaHash != block.GetMetaData().Hash() {
log.Error(v.logInfo, "err", ErrMetaHash, "block.Metahash", block.Header().MetaHash.String(), "block.meta.hash", block.GetMetaData().Hash().String())
return ErrMetaHash
}
if len(block.IHeader().GetExtra()) > int(v.quarkChainConfig.BlockExtraDataSizeLimit) {
log.Error(v.logInfo, "err", ErrExtraLimit, "len block's extra", len(block.IHeader().GetExtra()), "config's limit", v.quarkChainConfig.BlockExtraDataSizeLimit)
return ErrExtraLimit
}
if len(block.GetTrackingData()) > int(v.quarkChainConfig.BlockExtraDataSizeLimit) {
log.Error(v.logInfo, "err", ErrTrackLimit, "len block's tracking data", len(block.GetTrackingData()), "config's limit", v.quarkChainConfig.BlockExtraDataSizeLimit)
return ErrTrackLimit
}
if block.Header().GasLimit.Value.Cmp(v.bc.gasLimit) != 0 {
return errors.New("gasLimit is not match")
}
txHash := types.CalculateMerkleRoot(block.GetTransactions())
if txHash != block.GetMetaData().TxHash {
log.Error(v.logInfo, "txHash is not match err", ErrTxHash, "local", txHash.String(), "block.TxHash", block.GetMetaData().TxHash.String())
return ErrTxHash
}
if !v.branch.IsInBranch(block.IHeader().GetCoinbase().FullShardKey) {
log.Error(v.logInfo, "err", ErrMinerFullShardKey, "coinbase's fullshardkey", block.IHeader().GetCoinbase().FullShardKey, "current branch", v.branch.Value)
return ErrMinerFullShardKey
}
if !v.quarkChainConfig.SkipMinorDifficultyCheck {
diff, err := v.engine.CalcDifficulty(v.bc, block.IHeader().GetTime(), prevHeader)
if err != nil {
log.Error(v.logInfo, "check diff err", err)
return err
}
if diff.Cmp(block.IHeader().GetDifficulty()) != 0 {
log.Error(v.logInfo, "check diff err", err, "diff", diff, "block's", block.IHeader().GetDifficulty())
return ErrDifficulty
}
}
rootBlockHeader := v.bc.getRootBlockHeaderByHash(block.Header().GetPrevRootBlockHash())
if rootBlockHeader == nil {
log.Error(v.logInfo, "err", ErrRootBlockIsNil, "height", block.Header().Number, "parentRootBlockHash", block.Header().GetPrevRootBlockHash().String())
return ErrRootBlockIsNil
}
prevRootHeader := v.bc.getRootBlockHeaderByHash(prevHeader.(*types.MinorBlockHeader).GetPrevRootBlockHash())
if prevRootHeader == nil {
log.Error(v.logInfo, "err", ErrRootBlockIsNil, "prevHeader's height", prevHeader.NumberU64(), "preHeader's prevRootBlockHash", prevHeader.(*types.MinorBlockHeader).GetPrevRootBlockHash().String())
return ErrRootBlockIsNil
}
if rootBlockHeader.NumberU64() < prevRootHeader.NumberU64() {
errRootBlockOrder := errors.New("pre root block height must be non-decreasing")
log.Error(v.logInfo, "err", errRootBlockOrder, "rootBlockHeader's number", rootBlockHeader.Number, "preRootHeader.Number", prevHeader.NumberU64())
return errRootBlockOrder
}
prevConfirmedMinorHeader := v.bc.getLastConfirmedMinorBlockHeaderAtRootBlock(block.Header().PrevRootBlockHash)
if prevConfirmedMinorHeader != nil && !isSameChain(v.bc.db, prevHeader, prevConfirmedMinorHeader) {
errMustBeOneMinorChain := errors.New("prev root block's minor block is not in the same chain as the minor block")
log.Error(v.logInfo, "err", errMustBeOneMinorChain, "prevConfirmedMinor's height", prevConfirmedMinorHeader.Number, "prevConfirmedMinor's hash", prevConfirmedMinorHeader.Hash().String(),
"preHeader's height", prevHeader.NumberU64(), "preHeader's hash", prevHeader.Hash().String())
return errMustBeOneMinorChain
}
if !v.bc.isSameRootChain(v.bc.getRootBlockHeaderByHash(block.Header().GetPrevRootBlockHash()),
v.bc.getRootBlockHeaderByHash(prevHeader.(*types.MinorBlockHeader).GetPrevRootBlockHash())) {
errMustBeOneRootChain := errors.New("prev root blocks are not on the same chain")
log.Error(v.logInfo, "err", errMustBeOneRootChain, "long", block.Header().GetPrevRootBlockHash().String(), "short", prevHeader.(*types.MinorBlockHeader).GetPrevRootBlockHash().String())
return errMustBeOneRootChain
}
if err := v.ValidatorSeal(block.Header()); err != nil {
log.Error(v.logInfo, "ValidatorBlockSeal err", err)
return err
}
return nil
}
// ValidateHeader calls underlying engine's header verification method plus some sanity check.
func (v *MinorBlockValidator) ValidateHeader(header types.IHeader) error {
h, ok := header.(*types.MinorBlockHeader)
if !ok {
log.Crit("Failed to cast minor block header from validator, panic")
}
rh := v.bc.getRootBlockHeaderByHash(h.GetPrevRootBlockHash())
if rh == nil {
log.Error(v.logInfo, "err", ErrRootBlockIsNil, "height", h.Number, "parentRootBlockHash", h.GetPrevRootBlockHash().String())
return ErrRootBlockIsNil
}
return v.engine.VerifyHeader(v.bc, header, true)
}
// ValidatorBlockSeal validate minor block seal when validate block
func (v *MinorBlockValidator) ValidatorSeal(mHeader types.IHeader) error {
header, ok := mHeader.(*types.MinorBlockHeader)
if !ok {
return errors.New("validator minor seal failed , mBlock is nil")
}
if header.NumberU64() == 0 {
return nil
}
branch := header.GetBranch()
fullShardID := branch.GetFullShardID()
shardConfig := v.quarkChainConfig.GetShardConfigByFullShardID(fullShardID)
consensusType := shardConfig.ConsensusType
return v.validateSeal(header, consensusType, nil)
}
func (v *MinorBlockValidator) validateSeal(header types.IHeader, consensusType string, diff *uint64) error {
if diff == nil {
headerDifficult := header.GetDifficulty().Uint64()
diff = &headerDifficult
}
return v.engine.VerifySeal(v.bc, header, new(big.Int).SetUint64(*diff))
}
// ValidateState validates the various changes that happen after a state
// transition, such as amount of used gas, the receipt roots and the state root
// itself. ValidateState returns a database batch if the validation was a success
// otherwise nil and an error is returned.
func (v *MinorBlockValidator) ValidateState(mBlock, parent types.IBlock, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error {
if common.IsNil(mBlock) {
return ErrMinorBlockIsNil
}
block, ok := mBlock.(*types.MinorBlock)
if !ok {
return ErrInvalidMinorBlock
}
mHeader := block.Header()
if block.GetMetaData().GasUsed.Value.Cmp(statedb.GetGasUsed()) != 0 {
return fmt.Errorf("invalid gas used (statedb.GetGasUsed: %d usedGas: %d)", block.GetMetaData().GasUsed.Value.Uint64(), statedb.GetGasUsed())
}
// Validate the received block's bloom with the one derived from the generated receipts.
// For valid blocks this should always validate to true.
bloom := types.CreateBloom(receipts)
if bloom != mHeader.GetBloom() {
return fmt.Errorf("invalid bloom (remote: %x local: %x)", mHeader.GetBloom(), bloom)
}
receiptSha := types.DeriveSha(receipts)
if receiptSha != block.GetMetaData().ReceiptHash {
return fmt.Errorf("invalid receipt root hash (remote: %x local: %x)", block.GetMetaData().ReceiptHash, receiptSha)
}
if statedb.GetGasUsed().Cmp(block.GetMetaData().GasUsed.Value) != 0 {
return ErrGasUsed
}
coinbaseAmount := new(big.Int).Add(v.bc.getCoinbaseAmount(), statedb.GetBlockFee())
if coinbaseAmount.Cmp(block.CoinbaseAmount()) != 0 {
return ErrCoinbaseAmount
}
if statedb.GetXShardReceiveGasUsed().Cmp(block.GetMetaData().CrossShardGasUsed.Value) != 0 {
return ErrXShardList
}
// Validate the state root against the received state root and throw
// an error if they don't match.
if root := statedb.IntermediateRoot(true); block.GetMetaData().Root != root {
return fmt.Errorf("invalid merkle root (remote: %x local: %x)", block.GetMetaData().Root, root)
}
return nil
}