forked from PlatONnetwork/PlatON-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbft_mock.go
More file actions
403 lines (338 loc) · 12.5 KB
/
Copy pathbft_mock.go
File metadata and controls
403 lines (338 loc) · 12.5 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright 2021 The PlatON Network Authors
// This file is part of the PlatON-Go library.
//
// The PlatON-Go 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 PlatON-Go 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 PlatON-Go library. If not, see <http://www.gnu.org/licenses/>.
package consensus
import (
"bytes"
"errors"
"fmt"
"math/big"
"time"
"github.com/PlatONnetwork/PlatON-Go/core/rawdb"
"github.com/PlatONnetwork/PlatON-Go/core/snapshotdb"
"github.com/PlatONnetwork/PlatON-Go/params"
"github.com/PlatONnetwork/PlatON-Go/p2p/enode"
"github.com/PlatONnetwork/PlatON-Go/ethdb"
"github.com/PlatONnetwork/PlatON-Go/event"
"github.com/PlatONnetwork/PlatON-Go/trie"
"github.com/PlatONnetwork/PlatON-Go/common/consensus"
"github.com/PlatONnetwork/PlatON-Go/crypto"
"github.com/PlatONnetwork/PlatON-Go/common"
"github.com/PlatONnetwork/PlatON-Go/core/cbfttypes"
"github.com/PlatONnetwork/PlatON-Go/core/state"
"github.com/PlatONnetwork/PlatON-Go/core/types"
"github.com/PlatONnetwork/PlatON-Go/p2p"
"github.com/PlatONnetwork/PlatON-Go/rpc"
ctypes "github.com/PlatONnetwork/PlatON-Go/consensus/cbft/types"
"github.com/PlatONnetwork/PlatON-Go/x/gov"
)
type Chain interface {
StateAt(root common.Hash) (*state.StateDB, error)
ProcessDirectly(block *types.Block, state *state.StateDB, parent *types.Block) (types.Receipts, error)
WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool, cbftBridgeUpdateChainState func()) error
GetHeaderByNumber(number uint64) *types.Header
}
func NewFaker() *BftMock {
c := new(BftMock)
c.Blocks = make([]*types.Block, 0)
c.blockIndexs = make(map[common.Hash]int, 0)
return c
}
func NewFakerWithDataBase(database ethdb.Database, genesis *types.Block) *BftMock {
c := new(BftMock)
c.Blocks = make([]*types.Block, 0)
c.blockIndexs = make(map[common.Hash]int, 0)
c.database = database
c.genesis = genesis
return c
}
func NewFailFaker(number uint64) *BftMock {
c := NewFaker()
c.fakeFail = number
return c
}
// BftMock represents a simulated consensus structure.
type BftMock struct {
EventMux *event.TypeMux
Blocks []*types.Block
blockIndexs map[common.Hash]int
Next uint32
Current *types.Block
Base *types.Block
fakeFail uint64 // Block number which fails BFT check even in fake mode
database ethdb.Database // In memory database to store our testing data
chain Chain
genesis *types.Block
}
func (bm *BftMock) Reset() {
bm.Blocks = make([]*types.Block, 0)
bm.blockIndexs = make(map[common.Hash]int, 0)
}
func (bm *BftMock) SetChain(c Chain) {
bm.chain = c
}
// InsertChain is a fake interface, no need to implement.
func (bm *BftMock) InsertChain(block *types.Block) error {
if _, ok := bm.blockIndexs[block.Hash()]; ok {
return nil
}
if len(bm.Blocks) != 0 && bm.Blocks[len(bm.Blocks)-1].Hash() != block.ParentHash() {
return errors.New("insertChain fail,block not compare")
}
if bm.chain != nil {
var root common.Hash
if block.ParentHash() == bm.genesis.Hash() {
root = bm.genesis.Root()
} else if len(bm.Blocks) == 0 {
root = bm.chain.GetHeaderByNumber(block.NumberU64() - 1).Root
} else {
root = bm.Blocks[len(bm.Blocks)-1].Root()
}
statedb, err := bm.chain.StateAt(root)
gov.NewGovDB(snapshotdb.Instance()).AddActiveVersion(params.FORKVERSION_1_6_0, 1, statedb)
if err != nil {
return err
}
receipts, err := bm.chain.ProcessDirectly(block, statedb, nil)
if err != nil {
return err
}
if err := statedb.UpdateSnaps(); err != nil {
return err
}
if err := bm.chain.WriteBlockWithState(block, receipts, nil, statedb, false, nil); err != nil {
return err
}
}
bm.Blocks = append(bm.Blocks, block)
bm.blockIndexs[block.Hash()] = len(bm.Blocks) - 1
bm.Current = block
bm.Base = block
if bm.database != nil {
rawdb.WriteBlock(bm.database, block)
rawdb.WriteHeadBlockHash(bm.database, block.Hash())
rawdb.WriteCanonicalHash(bm.database, block.Hash(), block.NumberU64())
rawdb.WriteHeadHeaderHash(bm.database, block.Hash())
}
return nil
}
func (bm *BftMock) GetPrepareQC(number uint64) *ctypes.QuorumCert {
panic("implement me")
}
// FastSyncCommitHead is a fake interface, no need to implement.
func (bm *BftMock) FastSyncCommitHead(block *types.Block) error {
return nil
}
// Start is a fake interface, no need to implement.
func (bm *BftMock) Start(chain ChainReader, blockCacheWriter BlockCacheWriter, pool TxPoolReset, agency Agency) error {
return nil
}
// CalcBlockDeadline is a fake interface, no need to implement.
func (bm *BftMock) CalcBlockDeadline(timePoint time.Time) time.Time {
now := time.Now()
if timePoint.Equal(now) || timePoint.Before(now) {
return now.Add(now.Sub(timePoint)).Add(10 * time.Millisecond)
}
return timePoint.Add(10 * time.Millisecond)
}
// CalcNextBlockTime is a fake interface, no need to implement.
func (bm *BftMock) CalcNextBlockTime(timePoint time.Time) time.Time {
return time.Now()
}
// GetBlockWithoutLock is a fake interface, no need to implement.
func (bm *BftMock) GetBlockWithoutLock(hash common.Hash, number uint64) *types.Block {
return nil
}
// IsSignedBySelf is a fake interface, no need to implement.
func (bm *BftMock) IsSignedBySelf(sealHash common.Hash, header *types.Header) bool {
return true
}
// Evidences is a fake interface, no need to implement.
func (bm *BftMock) Evidences() string {
return ""
}
// UnmarshalEvidence is a fake interface, no need to implement.
func (bm *BftMock) UnmarshalEvidence(data []byte) (consensus.Evidences, error) {
return nil, nil
}
func (bm *BftMock) Node() *enode.Node {
privateKey, err := crypto.GenerateKey()
if nil != err {
panic(fmt.Sprintf("Failed to generate random NodeId private key: %v", err))
}
return enode.NewV4(&privateKey.PublicKey, nil, 0, 0)
}
// Author retrieves the Ethereum address of the account that minted the given
// block, which may be different from the header's coinbase if a consensus
// engine is based on signatures.
func (bm *BftMock) Author(header *types.Header) (common.Address, error) {
return common.Address{}, nil
}
// VerifyHeader checks whether a header conforms to the consensus rules of a
// given engine. Verifying the seal may be done optionally here, or explicitly
// via the VerifySeal method.
func (bm *BftMock) VerifyHeader(chain ChainReader, header *types.Header, async bool) error {
if bm.fakeFail == header.Number.Uint64() {
return fmt.Errorf("failed verifyHeader on bftMock")
}
return nil
}
// VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers
// concurrently. The method returns a quit channel to abort the operations and
// a results channel to retrieve the async verifications (the order is that of
// the input slice).
func (bm *BftMock) VerifyHeaders(chain ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) {
results := make(chan error, len(headers))
c := make(chan<- struct{})
//time.Sleep(bm.fakeDelay)
go func() {
for i := range headers {
if bm.fakeFail == headers[i].Number.Uint64() {
results <- fmt.Errorf("failed verifyHeader on bftMock")
} else {
results <- nil
}
}
}()
return c, results
}
// VerifySeal checks whether the crypto seal on a header is valid according to
// the consensus rules of the given engine.
func (bm *BftMock) VerifySeal(chain ChainReader, header *types.Header) error {
return nil
}
// Prepare initializes the consensus fields of a block header according to the
// rules of a particular engine. The changes are executed inline.
func (bm *BftMock) Prepare(chain ChainReader, header *types.Header) error {
//header.Extra[0:31] to store block's version info etc. and right pad with 0x00;
//header.Extra[32:] to store block's sign of producer, the length of sign is 65.
if len(header.Extra) < 32 {
header.Extra = append(header.Extra, bytes.Repeat([]byte{0x00}, 32-len(header.Extra))...)
}
header.Extra = header.Extra[:32]
//init header.Extra[32: 32+65]
header.Extra = append(header.Extra, make([]byte, ExtraSeal)...)
return nil
}
// Finalize runs any post-transaction state modifications (e.g. block rewards)
// and assembles the final block.
// Note: The block header and state database might be updated to reflect any
// consensus rules that happen at finalization (e.g. block rewards).
func (bm *BftMock) Finalize(chain ChainReader, header *types.Header, state *state.StateDB,
txs []*types.Transaction, receipts []*types.Receipt, withdrawals []*types.Withdrawal) (*types.Block, error) {
header.Root = state.IntermediateRoot(true)
// Header seems complete, assemble into a block and return
return types.NewBlock(header, txs, receipts, new(trie.Trie)), nil
}
// Seal generates a new sealing request for the given input block and pushes
// the result into the given channel.
//
// Note, the method returns immediately and will send the result async. More
// than one result may also be returned depending on the consensus algorithm.
func (bm *BftMock) Seal(chain ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}, complete chan<- struct{}) error {
header := block.Header()
if block.NumberU64() == 0 {
return fmt.Errorf("unknown block")
}
sign := header.SealHash().Bytes()
copy(header.Extra[len(header.Extra)-ExtraSeal:], sign[:])
sealBlock := block.WithSeal(header)
complete <- struct{}{}
results <- sealBlock
bm.EventMux.Post(cbfttypes.CbftResult{
Block: sealBlock,
//ExtraData: extra,
//SyncState: cbft.commitErrCh,
ChainStateUpdateCB: func() {
},
})
return nil
}
// SealHash returns the hash of a block prior to it being sealed.
func (bm *BftMock) SealHash(header *types.Header) common.Hash {
return header.SealHash()
}
// CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty
// that a new block should have.
func (bm *BftMock) CalcDifficulty(chain ChainReader, time uint64, parent *types.Header) *big.Int {
return nil
}
// APIs returns the RPC APIs this consensus engine provides.
func (bm *BftMock) APIs(chain ChainReader) []rpc.API {
return nil
}
// Protocols is a fake interface, no need to implement.
func (bm *BftMock) Protocols() []p2p.Protocol {
return []p2p.Protocol{}
}
// Close terminates any background threads maintained by the consensus engine.
func (bm *BftMock) Close() error {
return nil
}
func (bm *BftMock) Stop() error {
return nil
}
// ConsensusNodes returns the current consensus node address list.
func (bm *BftMock) ConsensusNodes() ([]enode.ID, error) {
return nil, nil
}
func (bm *BftMock) ConsensusValidators() []*cbfttypes.ValidateNode {
return nil
}
// ShouldSeal returns whether the current node is out of the block
func (bm *BftMock) ShouldSeal(curTime time.Time) (bool, error) {
return true, nil
}
// IsConsensusNode is a fake interface, no need to implement.
func (bm *BftMock) IsConsensusNode() bool {
return true
}
// GetBlock is a fake interface, no need to implement.
func (bm *BftMock) GetBlock(hash common.Hash, number uint64) *types.Block {
return nil
}
// NextBaseBlock is a fake interface, no need to implement.
func (bm *BftMock) NextBaseBlock() *types.Block {
return bm.Base
}
// HasBlock is a fake interface, no need to implement.
func (bm *BftMock) HasBlock(hash common.Hash, number uint64) bool {
return true
}
// GetBlockByHash is a fake interface, no need to implement.
func (bm *BftMock) GetBlockByHash(hash common.Hash) *types.Block {
if index, ok := bm.blockIndexs[hash]; ok {
return bm.Blocks[index]
}
return nil
}
// GetBlockByHash get the specified block by hash and number.
func (bm *BftMock) GetBlockByHashAndNum(hash common.Hash, number uint64) *types.Block {
return nil
}
// CurrentBlock is a fake interface, no need to implement.
func (bm *BftMock) CurrentBlock() *types.Block {
return bm.Current
}
// TracingSwitch is a fake interface, no need to implement.
func (bm *BftMock) TracingSwitch(flag int8) {}
func (bm *BftMock) Pause() {}
func (bm *BftMock) Resume() {}
func (bm *BftMock) Syncing() bool {
return false
}
func (bm *BftMock) DecodeExtra(extra []byte) (common.Hash, uint64, error) {
return common.Hash{}, 0, nil
}