github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/core/rawdb/chain_iterator_test.go (about) 1 // Copyright 2019 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 17 package rawdb 18 19 import ( 20 "math/big" 21 "reflect" 22 "sort" 23 "testing" 24 25 "github.com/zhiqiangxu/go-ethereum/common" 26 "github.com/zhiqiangxu/go-ethereum/core/types" 27 ) 28 29 func TestChainIterator(t *testing.T) { 30 // Construct test chain db 31 chainDb := NewMemoryDatabase() 32 33 var block *types.Block 34 var txs []*types.Transaction 35 for i := uint64(0); i <= 10; i++ { 36 if i == 0 { 37 block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, nil, nil, nil) // Empty genesis block 38 } else { 39 tx := types.NewTransaction(i, common.BytesToAddress([]byte{0x11}), big.NewInt(111), 1111, big.NewInt(11111), []byte{0x11, 0x11, 0x11}) 40 txs = append(txs, tx) 41 block = types.NewBlock(&types.Header{Number: big.NewInt(int64(i))}, []*types.Transaction{tx}, nil, nil) 42 } 43 WriteBlock(chainDb, block) 44 WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64()) 45 } 46 47 var cases = []struct { 48 from, to uint64 49 reverse bool 50 expect []int 51 }{ 52 {0, 11, true, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}}, 53 {0, 0, true, nil}, 54 {0, 5, true, []int{4, 3, 2, 1, 0}}, 55 {10, 11, true, []int{10}}, 56 {0, 11, false, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}, 57 {0, 0, false, nil}, 58 {10, 11, false, []int{10}}, 59 } 60 for i, c := range cases { 61 var numbers []int 62 hashCh, _ := iterateTransactions(chainDb, c.from, c.to, c.reverse) 63 if hashCh != nil { 64 for h := range hashCh { 65 numbers = append(numbers, int(h.number)) 66 if len(h.hashes) > 0 { 67 if got, exp := h.hashes[0], txs[h.number-1].Hash(); got != exp { 68 t.Fatalf("hash wrong, got %x exp %x", got, exp) 69 } 70 } 71 } 72 } 73 if !c.reverse { 74 sort.Ints(numbers) 75 } else { 76 sort.Sort(sort.Reverse(sort.IntSlice(numbers))) 77 } 78 if !reflect.DeepEqual(numbers, c.expect) { 79 t.Fatalf("Case %d failed, visit element mismatch, want %v, got %v", i, c.expect, numbers) 80 } 81 } 82 }