engine_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package backend
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "math/big"
  21. "reflect"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/consensus/istanbul"
  27. istanbulcommon "github.com/ethereum/go-ethereum/consensus/istanbul/common"
  28. "github.com/ethereum/go-ethereum/consensus/istanbul/testutils"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/core/vm"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. )
  35. func newBlockchainFromConfig(genesis *core.Genesis, nodeKeys []*ecdsa.PrivateKey, cfg *istanbul.Config) (*core.BlockChain, *Backend) {
  36. memDB := rawdb.NewMemoryDatabase()
  37. // Use the first key as private key
  38. backend := New(cfg, nodeKeys[0], memDB)
  39. backend.qbftConsensusEnabled = backend.IsQBFTConsensus()
  40. genesis.MustCommit(memDB)
  41. blockchain, err := core.NewBlockChain(memDB, nil, genesis.Config, backend, vm.Config{}, nil, nil, nil)
  42. if err != nil {
  43. panic(err)
  44. }
  45. backend.Start(blockchain, blockchain.CurrentBlock, rawdb.HasBadBlock)
  46. snap, err := backend.snapshot(blockchain, 0, common.Hash{}, nil)
  47. if err != nil {
  48. panic(err)
  49. }
  50. if snap == nil {
  51. panic("failed to get snapshot")
  52. }
  53. proposerAddr := snap.ValSet.GetProposer().Address()
  54. // find proposer key
  55. for _, key := range nodeKeys {
  56. addr := crypto.PubkeyToAddress(key.PublicKey)
  57. if addr.String() == proposerAddr.String() {
  58. backend.privateKey = key
  59. backend.address = addr
  60. }
  61. }
  62. return blockchain, backend
  63. }
  64. // in this test, we can set n to 1, and it means we can process Istanbul and commit a
  65. // block by one node. Otherwise, if n is larger than 1, we have to generate
  66. // other fake events to process Istanbul.
  67. func newBlockChain(n int, qbftBlock *big.Int) (*core.BlockChain, *Backend) {
  68. isQBFT := qbftBlock != nil && qbftBlock.Uint64() == 0
  69. genesis, nodeKeys := testutils.GenesisAndKeys(n, isQBFT)
  70. config := copyConfig(istanbul.DefaultConfig)
  71. config.TestQBFTBlock = qbftBlock
  72. return newBlockchainFromConfig(genesis, nodeKeys, config)
  73. }
  74. // copyConfig create a copy of istanbul.Config, so that changing it does not update the original
  75. func copyConfig(config *istanbul.Config) *istanbul.Config {
  76. cpy := *config
  77. return &cpy
  78. }
  79. func makeHeader(parent *types.Block, config *istanbul.Config) *types.Header {
  80. blockNumber := parent.Number().Add(parent.Number(), common.Big1)
  81. header := &types.Header{
  82. ParentHash: parent.Hash(),
  83. Number: blockNumber,
  84. GasLimit: core.CalcGasLimit(parent, parent.GasLimit(), parent.GasLimit(), parent.GasLimit()),
  85. GasUsed: 0,
  86. Time: parent.Time() + config.GetConfig(blockNumber).BlockPeriod,
  87. Difficulty: istanbulcommon.DefaultDifficulty,
  88. }
  89. return header
  90. }
  91. func makeBlock(chain *core.BlockChain, engine *Backend, parent *types.Block) *types.Block {
  92. block := makeBlockWithoutSeal(chain, engine, parent)
  93. stopCh := make(chan struct{})
  94. resultCh := make(chan *types.Block, 10)
  95. go engine.Seal(chain, block, resultCh, stopCh)
  96. blk := <-resultCh
  97. return blk
  98. }
  99. func makeBlockWithoutSeal(chain *core.BlockChain, engine *Backend, parent *types.Block) *types.Block {
  100. header := makeHeader(parent, engine.config)
  101. engine.Prepare(chain, header)
  102. state, _, _ := chain.StateAt(parent.Root())
  103. block, _ := engine.FinalizeAndAssemble(chain, header, state, nil, nil, nil)
  104. return block
  105. }
  106. func TestIBFTPrepare(t *testing.T) {
  107. chain, engine := newBlockChain(1, nil)
  108. defer engine.Stop()
  109. chain.Config().Istanbul.TestQBFTBlock = nil
  110. header := makeHeader(chain.Genesis(), engine.config)
  111. err := engine.Prepare(chain, header)
  112. if err != nil {
  113. t.Errorf("error mismatch: have %v, want nil", err)
  114. }
  115. header.ParentHash = common.StringToHash("1234567890")
  116. err = engine.Prepare(chain, header)
  117. if err != consensus.ErrUnknownAncestor {
  118. t.Errorf("error mismatch: have %v, want %v", err, consensus.ErrUnknownAncestor)
  119. }
  120. }
  121. func TestQBFTPrepare(t *testing.T) {
  122. chain, engine := newBlockChain(1, big.NewInt(0))
  123. defer engine.Stop()
  124. header := makeHeader(chain.Genesis(), engine.config)
  125. err := engine.Prepare(chain, header)
  126. if err != nil {
  127. t.Errorf("error mismatch: have %v, want nil", err)
  128. }
  129. header.ParentHash = common.StringToHash("1234567890")
  130. err = engine.Prepare(chain, header)
  131. if err != consensus.ErrUnknownAncestor {
  132. t.Errorf("error mismatch: have %v, want %v", err, consensus.ErrUnknownAncestor)
  133. }
  134. }
  135. func TestSealStopChannel(t *testing.T) {
  136. chain, engine := newBlockChain(1, big.NewInt(0))
  137. defer engine.Stop()
  138. block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
  139. stop := make(chan struct{}, 1)
  140. eventSub := engine.EventMux().Subscribe(istanbul.RequestEvent{})
  141. eventLoop := func() {
  142. ev := <-eventSub.Chan()
  143. _, ok := ev.Data.(istanbul.RequestEvent)
  144. if !ok {
  145. t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data))
  146. }
  147. stop <- struct{}{}
  148. eventSub.Unsubscribe()
  149. }
  150. resultCh := make(chan *types.Block, 10)
  151. go func() {
  152. err := engine.Seal(chain, block, resultCh, stop)
  153. if err != nil {
  154. t.Errorf("error mismatch: have %v, want nil", err)
  155. }
  156. }()
  157. go eventLoop()
  158. finalBlock := <-resultCh
  159. if finalBlock != nil {
  160. t.Errorf("block mismatch: have %v, want nil", finalBlock)
  161. }
  162. }
  163. func TestSealCommittedOtherHash(t *testing.T) {
  164. chain, engine := newBlockChain(1, big.NewInt(0))
  165. defer engine.Stop()
  166. block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
  167. otherBlock := makeBlockWithoutSeal(chain, engine, block)
  168. expectedCommittedSeal := append([]byte{1, 2, 3}, bytes.Repeat([]byte{0x00}, types.IstanbulExtraSeal-3)...)
  169. eventSub := engine.EventMux().Subscribe(istanbul.RequestEvent{})
  170. blockOutputChannel := make(chan *types.Block)
  171. stopChannel := make(chan struct{})
  172. go func() {
  173. ev := <-eventSub.Chan()
  174. if _, ok := ev.Data.(istanbul.RequestEvent); !ok {
  175. t.Errorf("unexpected event comes: %v", reflect.TypeOf(ev.Data))
  176. }
  177. if err := engine.Commit(otherBlock, [][]byte{expectedCommittedSeal}, big.NewInt(0)); err != nil {
  178. t.Error(err.Error())
  179. }
  180. eventSub.Unsubscribe()
  181. }()
  182. go func() {
  183. if err := engine.Seal(chain, block, blockOutputChannel, stopChannel); err != nil {
  184. t.Error(err.Error())
  185. }
  186. }()
  187. select {
  188. case <-blockOutputChannel:
  189. t.Error("Wrong block found!")
  190. default:
  191. //no block found, stop the sealing
  192. close(stopChannel)
  193. }
  194. output := <-blockOutputChannel
  195. if output != nil {
  196. t.Error("Block not nil!")
  197. }
  198. }
  199. func updateQBFTBlock(block *types.Block, addr common.Address) *types.Block {
  200. header := block.Header()
  201. header.Coinbase = addr
  202. return block.WithSeal(header)
  203. }
  204. func TestSealCommitted(t *testing.T) {
  205. chain, engine := newBlockChain(1, big.NewInt(0))
  206. defer engine.Stop()
  207. block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
  208. expectedBlock := updateQBFTBlock(block, engine.Address())
  209. resultCh := make(chan *types.Block, 10)
  210. go func() {
  211. err := engine.Seal(chain, block, resultCh, make(chan struct{}))
  212. if err != nil {
  213. t.Errorf("error mismatch: have %v, want %v", err, expectedBlock)
  214. }
  215. }()
  216. finalBlock := <-resultCh
  217. if finalBlock.Hash() != expectedBlock.Hash() {
  218. t.Errorf("hash mismatch: have %v, want %v", finalBlock.Hash(), expectedBlock.Hash())
  219. }
  220. }
  221. func TestVerifyHeader(t *testing.T) {
  222. chain, engine := newBlockChain(1, big.NewInt(0))
  223. defer engine.Stop()
  224. // istanbulcommon.ErrEmptyCommittedSeals case
  225. block := makeBlockWithoutSeal(chain, engine, chain.Genesis())
  226. header := engine.chain.GetHeader(block.ParentHash(), block.NumberU64()-1)
  227. block = updateQBFTBlock(block, engine.Address())
  228. err := engine.VerifyHeader(chain, block.Header(), false)
  229. if err != istanbulcommon.ErrEmptyCommittedSeals {
  230. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrEmptyCommittedSeals)
  231. }
  232. // short extra data
  233. header = block.Header()
  234. header.Extra = []byte{}
  235. err = engine.VerifyHeader(chain, header, false)
  236. if err != istanbulcommon.ErrInvalidExtraDataFormat {
  237. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidExtraDataFormat)
  238. }
  239. // incorrect extra format
  240. header.Extra = []byte("0000000000000000000000000000000012300000000000000000000000000000000000000000000000000000000000000000")
  241. err = engine.VerifyHeader(chain, header, false)
  242. if err != istanbulcommon.ErrInvalidExtraDataFormat {
  243. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidExtraDataFormat)
  244. }
  245. // non zero MixDigest
  246. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  247. header = block.Header()
  248. header.MixDigest = common.StringToHash("123456789")
  249. err = engine.VerifyHeader(chain, header, false)
  250. if err != istanbulcommon.ErrInvalidMixDigest {
  251. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidMixDigest)
  252. }
  253. // invalid uncles hash
  254. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  255. header = block.Header()
  256. header.UncleHash = common.StringToHash("123456789")
  257. err = engine.VerifyHeader(chain, header, false)
  258. if err != istanbulcommon.ErrInvalidUncleHash {
  259. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidUncleHash)
  260. }
  261. // invalid difficulty
  262. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  263. header = block.Header()
  264. header.Difficulty = big.NewInt(2)
  265. err = engine.VerifyHeader(chain, header, false)
  266. if err != istanbulcommon.ErrInvalidDifficulty {
  267. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidDifficulty)
  268. }
  269. // invalid timestamp
  270. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  271. header = block.Header()
  272. header.Time = chain.Genesis().Time() + (engine.config.GetConfig(block.Number()).BlockPeriod - 1)
  273. err = engine.VerifyHeader(chain, header, false)
  274. if err != istanbulcommon.ErrInvalidTimestamp {
  275. t.Errorf("error mismatch: have %v, want %v", err, istanbulcommon.ErrInvalidTimestamp)
  276. }
  277. // future block
  278. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  279. header = block.Header()
  280. header.Time = uint64(time.Now().Unix() + 10)
  281. err = engine.VerifyHeader(chain, header, false)
  282. if err != consensus.ErrFutureBlock {
  283. t.Errorf("error mismatch: have %v, want %v", err, consensus.ErrFutureBlock)
  284. }
  285. // future block which is within AllowedFutureBlockTime
  286. block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  287. header = block.Header()
  288. header.Time = new(big.Int).Add(big.NewInt(time.Now().Unix()), new(big.Int).SetUint64(10)).Uint64()
  289. priorValue := engine.config.AllowedFutureBlockTime
  290. engine.config.AllowedFutureBlockTime = 10
  291. err = engine.VerifyHeader(chain, header, false)
  292. engine.config.AllowedFutureBlockTime = priorValue //restore changed value
  293. if err == consensus.ErrFutureBlock {
  294. t.Errorf("error mismatch: have %v, want nil", err)
  295. }
  296. // TODO This test does not make sense anymore as validate vote type is not stored in nonce
  297. // invalid nonce
  298. /*block = makeBlockWithoutSeal(chain, engine, chain.Genesis())
  299. header = block.Header()
  300. copy(header.Nonce[:], hexutil.MustDecode("0x111111111111"))
  301. header.Number = big.NewInt(int64(engine.config.Epoch))
  302. err = engine.VerifyHeader(chain, header, false)
  303. if err != errInvalidNonce {
  304. t.Errorf("error mismatch: have %v, want %v", err, errInvalidNonce)
  305. }*/
  306. }
  307. func TestVerifyHeaders(t *testing.T) {
  308. chain, engine := newBlockChain(1, big.NewInt(0))
  309. defer engine.Stop()
  310. genesis := chain.Genesis()
  311. // success case
  312. headers := []*types.Header{}
  313. blocks := []*types.Block{}
  314. size := 100
  315. for i := 0; i < size; i++ {
  316. var b *types.Block
  317. if i == 0 {
  318. b = makeBlockWithoutSeal(chain, engine, genesis)
  319. b = updateQBFTBlock(b, engine.Address())
  320. } else {
  321. b = makeBlockWithoutSeal(chain, engine, blocks[i-1])
  322. b = updateQBFTBlock(b, engine.Address())
  323. }
  324. blocks = append(blocks, b)
  325. headers = append(headers, blocks[i].Header())
  326. }
  327. // now = func() time.Time {
  328. // return time.Unix(int64(headers[size-1].Time), 0)
  329. // }
  330. _, results := engine.VerifyHeaders(chain, headers, nil)
  331. const timeoutDura = 2 * time.Second
  332. timeout := time.NewTimer(timeoutDura)
  333. index := 0
  334. OUT1:
  335. for {
  336. select {
  337. case err := <-results:
  338. if err != nil {
  339. if err != istanbulcommon.ErrEmptyCommittedSeals && err != istanbulcommon.ErrInvalidCommittedSeals && err != consensus.ErrUnknownAncestor {
  340. t.Errorf("error mismatch: have %v, want istanbulcommon.ErrEmptyCommittedSeals|istanbulcommon.ErrInvalidCommittedSeals|ErrUnknownAncestor", err)
  341. break OUT1
  342. }
  343. }
  344. index++
  345. if index == size {
  346. break OUT1
  347. }
  348. case <-timeout.C:
  349. break OUT1
  350. }
  351. }
  352. _, results = engine.VerifyHeaders(chain, headers, nil)
  353. timeout = time.NewTimer(timeoutDura)
  354. OUT2:
  355. for {
  356. select {
  357. case err := <-results:
  358. if err != nil {
  359. if err != istanbulcommon.ErrEmptyCommittedSeals && err != istanbulcommon.ErrInvalidCommittedSeals && err != consensus.ErrUnknownAncestor {
  360. t.Errorf("error mismatch: have %v, want istanbulcommon.ErrEmptyCommittedSeals|istanbulcommon.ErrInvalidCommittedSeals|ErrUnknownAncestor", err)
  361. break OUT2
  362. }
  363. }
  364. case <-timeout.C:
  365. break OUT2
  366. }
  367. }
  368. // error header cases
  369. headers[2].Number = big.NewInt(100)
  370. _, results = engine.VerifyHeaders(chain, headers, nil)
  371. timeout = time.NewTimer(timeoutDura)
  372. index = 0
  373. errors := 0
  374. expectedErrors := 0
  375. OUT3:
  376. for {
  377. select {
  378. case err := <-results:
  379. if err != nil {
  380. if err != istanbulcommon.ErrEmptyCommittedSeals && err != istanbulcommon.ErrInvalidCommittedSeals && err != consensus.ErrUnknownAncestor {
  381. errors++
  382. }
  383. }
  384. index++
  385. if index == size {
  386. if errors != expectedErrors {
  387. t.Errorf("error mismatch: have %v, want %v", errors, expectedErrors)
  388. }
  389. break OUT3
  390. }
  391. case <-timeout.C:
  392. break OUT3
  393. }
  394. }
  395. }