github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/core/rawdb/accessors_chain_test.go (about)

     1  // Copyright 2018 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  	"bytes"
    21  	"encoding/hex"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"math/big"
    25  	"math/rand"
    26  	"os"
    27  	"reflect"
    28  	"testing"
    29  
    30  	"golang.org/x/crypto/sha3"
    31  
    32  	"github.com/scroll-tech/go-ethereum/common"
    33  	"github.com/scroll-tech/go-ethereum/core/types"
    34  	"github.com/scroll-tech/go-ethereum/crypto"
    35  	"github.com/scroll-tech/go-ethereum/params"
    36  	"github.com/scroll-tech/go-ethereum/rlp"
    37  )
    38  
    39  // Tests block header storage and retrieval operations.
    40  func TestHeaderStorage(t *testing.T) {
    41  	db := NewMemoryDatabase()
    42  
    43  	// Create a test header to move around the database and make sure it's really new
    44  	header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
    45  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    46  		t.Fatalf("Non existent header returned: %v", entry)
    47  	}
    48  	// Write and verify the header in the database
    49  	WriteHeader(db, header)
    50  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
    51  		t.Fatalf("Stored header not found")
    52  	} else if entry.Hash() != header.Hash() {
    53  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
    54  	}
    55  	if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
    56  		t.Fatalf("Stored header RLP not found")
    57  	} else {
    58  		hasher := sha3.NewLegacyKeccak256()
    59  		hasher.Write(entry)
    60  
    61  		if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
    62  			t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
    63  		}
    64  	}
    65  	// Delete the header and verify the execution
    66  	DeleteHeader(db, header.Hash(), header.Number.Uint64())
    67  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    68  		t.Fatalf("Deleted header returned: %v", entry)
    69  	}
    70  }
    71  
    72  // Tests block body storage and retrieval operations.
    73  func TestBodyStorage(t *testing.T) {
    74  	db := NewMemoryDatabase()
    75  
    76  	// Create a test body to move around the database and make sure it's really new
    77  	body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
    78  
    79  	hasher := sha3.NewLegacyKeccak256()
    80  	rlp.Encode(hasher, body)
    81  	hash := common.BytesToHash(hasher.Sum(nil))
    82  
    83  	if entry := ReadBody(db, hash, 0); entry != nil {
    84  		t.Fatalf("Non existent body returned: %v", entry)
    85  	}
    86  	// Write and verify the body in the database
    87  	WriteBody(db, hash, 0, body)
    88  	if entry := ReadBody(db, hash, 0); entry == nil {
    89  		t.Fatalf("Stored body not found")
    90  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
    91  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
    92  	}
    93  	if entry := ReadBodyRLP(db, hash, 0); entry == nil {
    94  		t.Fatalf("Stored body RLP not found")
    95  	} else {
    96  		hasher := sha3.NewLegacyKeccak256()
    97  		hasher.Write(entry)
    98  
    99  		if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
   100  			t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
   101  		}
   102  	}
   103  	// Delete the body and verify the execution
   104  	DeleteBody(db, hash, 0)
   105  	if entry := ReadBody(db, hash, 0); entry != nil {
   106  		t.Fatalf("Deleted body returned: %v", entry)
   107  	}
   108  }
   109  
   110  // Tests block storage and retrieval operations.
   111  func TestBlockStorage(t *testing.T) {
   112  	db := NewMemoryDatabase()
   113  
   114  	// Create a test block to move around the database and make sure it's really new
   115  	block := types.NewBlockWithHeader(&types.Header{
   116  		Extra:       []byte("test block"),
   117  		UncleHash:   types.EmptyUncleHash,
   118  		TxHash:      types.EmptyRootHash,
   119  		ReceiptHash: types.EmptyRootHash,
   120  	})
   121  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   122  		t.Fatalf("Non existent block returned: %v", entry)
   123  	}
   124  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   125  		t.Fatalf("Non existent header returned: %v", entry)
   126  	}
   127  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   128  		t.Fatalf("Non existent body returned: %v", entry)
   129  	}
   130  	// Write and verify the block in the database
   131  	WriteBlock(db, block)
   132  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   133  		t.Fatalf("Stored block not found")
   134  	} else if entry.Hash() != block.Hash() {
   135  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   136  	}
   137  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
   138  		t.Fatalf("Stored header not found")
   139  	} else if entry.Hash() != block.Header().Hash() {
   140  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
   141  	}
   142  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
   143  		t.Fatalf("Stored body not found")
   144  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
   145  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
   146  	}
   147  	// Delete the block and verify the execution
   148  	DeleteBlock(db, block.Hash(), block.NumberU64())
   149  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   150  		t.Fatalf("Deleted block returned: %v", entry)
   151  	}
   152  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   153  		t.Fatalf("Deleted header returned: %v", entry)
   154  	}
   155  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   156  		t.Fatalf("Deleted body returned: %v", entry)
   157  	}
   158  }
   159  
   160  // Tests that partial block contents don't get reassembled into full blocks.
   161  func TestPartialBlockStorage(t *testing.T) {
   162  	db := NewMemoryDatabase()
   163  	block := types.NewBlockWithHeader(&types.Header{
   164  		Extra:       []byte("test block"),
   165  		UncleHash:   types.EmptyUncleHash,
   166  		TxHash:      types.EmptyRootHash,
   167  		ReceiptHash: types.EmptyRootHash,
   168  	})
   169  	// Store a header and check that it's not recognized as a block
   170  	WriteHeader(db, block.Header())
   171  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   172  		t.Fatalf("Non existent block returned: %v", entry)
   173  	}
   174  	DeleteHeader(db, block.Hash(), block.NumberU64())
   175  
   176  	// Store a body and check that it's not recognized as a block
   177  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   178  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   179  		t.Fatalf("Non existent block returned: %v", entry)
   180  	}
   181  	DeleteBody(db, block.Hash(), block.NumberU64())
   182  
   183  	// Store a header and a body separately and check reassembly
   184  	WriteHeader(db, block.Header())
   185  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   186  
   187  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   188  		t.Fatalf("Stored block not found")
   189  	} else if entry.Hash() != block.Hash() {
   190  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   191  	}
   192  }
   193  
   194  // Tests block storage and retrieval operations.
   195  func TestBadBlockStorage(t *testing.T) {
   196  	db := NewMemoryDatabase()
   197  
   198  	// Create a test block to move around the database and make sure it's really new
   199  	block := types.NewBlockWithHeader(&types.Header{
   200  		Number:      big.NewInt(1),
   201  		Extra:       []byte("bad block"),
   202  		UncleHash:   types.EmptyUncleHash,
   203  		TxHash:      types.EmptyRootHash,
   204  		ReceiptHash: types.EmptyRootHash,
   205  	})
   206  	if entry := ReadBadBlock(db, block.Hash()); entry != nil {
   207  		t.Fatalf("Non existent block returned: %v", entry)
   208  	}
   209  	// Write and verify the block in the database
   210  	WriteBadBlock(db, block)
   211  	if entry := ReadBadBlock(db, block.Hash()); entry == nil {
   212  		t.Fatalf("Stored block not found")
   213  	} else if entry.Hash() != block.Hash() {
   214  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   215  	}
   216  	// Write one more bad block
   217  	blockTwo := types.NewBlockWithHeader(&types.Header{
   218  		Number:      big.NewInt(2),
   219  		Extra:       []byte("bad block two"),
   220  		UncleHash:   types.EmptyUncleHash,
   221  		TxHash:      types.EmptyRootHash,
   222  		ReceiptHash: types.EmptyRootHash,
   223  	})
   224  	WriteBadBlock(db, blockTwo)
   225  
   226  	// Write the block one again, should be filtered out.
   227  	WriteBadBlock(db, block)
   228  	badBlocks := ReadAllBadBlocks(db)
   229  	if len(badBlocks) != 2 {
   230  		t.Fatalf("Failed to load all bad blocks")
   231  	}
   232  
   233  	// Write a bunch of bad blocks, all the blocks are should sorted
   234  	// in reverse order. The extra blocks should be truncated.
   235  	for _, n := range rand.Perm(100) {
   236  		block := types.NewBlockWithHeader(&types.Header{
   237  			Number:      big.NewInt(int64(n)),
   238  			Extra:       []byte("bad block"),
   239  			UncleHash:   types.EmptyUncleHash,
   240  			TxHash:      types.EmptyRootHash,
   241  			ReceiptHash: types.EmptyRootHash,
   242  		})
   243  		WriteBadBlock(db, block)
   244  	}
   245  	badBlocks = ReadAllBadBlocks(db)
   246  	if len(badBlocks) != badBlockToKeep {
   247  		t.Fatalf("The number of persised bad blocks in incorrect %d", len(badBlocks))
   248  	}
   249  	for i := 0; i < len(badBlocks)-1; i++ {
   250  		if badBlocks[i].NumberU64() < badBlocks[i+1].NumberU64() {
   251  			t.Fatalf("The bad blocks are not sorted #[%d](%d) < #[%d](%d)", i, i+1, badBlocks[i].NumberU64(), badBlocks[i+1].NumberU64())
   252  		}
   253  	}
   254  
   255  	// Delete all bad blocks
   256  	DeleteBadBlocks(db)
   257  	badBlocks = ReadAllBadBlocks(db)
   258  	if len(badBlocks) != 0 {
   259  		t.Fatalf("Failed to delete bad blocks")
   260  	}
   261  }
   262  
   263  // Tests block total difficulty storage and retrieval operations.
   264  func TestTdStorage(t *testing.T) {
   265  	db := NewMemoryDatabase()
   266  
   267  	// Create a test TD to move around the database and make sure it's really new
   268  	hash, td := common.Hash{}, big.NewInt(314)
   269  	if entry := ReadTd(db, hash, 0); entry != nil {
   270  		t.Fatalf("Non existent TD returned: %v", entry)
   271  	}
   272  	// Write and verify the TD in the database
   273  	WriteTd(db, hash, 0, td)
   274  	if entry := ReadTd(db, hash, 0); entry == nil {
   275  		t.Fatalf("Stored TD not found")
   276  	} else if entry.Cmp(td) != 0 {
   277  		t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
   278  	}
   279  	// Delete the TD and verify the execution
   280  	DeleteTd(db, hash, 0)
   281  	if entry := ReadTd(db, hash, 0); entry != nil {
   282  		t.Fatalf("Deleted TD returned: %v", entry)
   283  	}
   284  }
   285  
   286  // Tests that canonical numbers can be mapped to hashes and retrieved.
   287  func TestCanonicalMappingStorage(t *testing.T) {
   288  	db := NewMemoryDatabase()
   289  
   290  	// Create a test canonical number and assinged hash to move around
   291  	hash, number := common.Hash{0: 0xff}, uint64(314)
   292  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   293  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   294  	}
   295  	// Write and verify the TD in the database
   296  	WriteCanonicalHash(db, hash, number)
   297  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   298  		t.Fatalf("Stored canonical mapping not found")
   299  	} else if entry != hash {
   300  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   301  	}
   302  	// Delete the TD and verify the execution
   303  	DeleteCanonicalHash(db, number)
   304  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   305  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   306  	}
   307  }
   308  
   309  // Tests that head headers and head blocks can be assigned, individually.
   310  func TestHeadStorage(t *testing.T) {
   311  	db := NewMemoryDatabase()
   312  
   313  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   314  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   315  	blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
   316  
   317  	// Check that no head entries are in a pristine database
   318  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   319  		t.Fatalf("Non head header entry returned: %v", entry)
   320  	}
   321  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   322  		t.Fatalf("Non head block entry returned: %v", entry)
   323  	}
   324  	if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
   325  		t.Fatalf("Non fast head block entry returned: %v", entry)
   326  	}
   327  	// Assign separate entries for the head header and block
   328  	WriteHeadHeaderHash(db, blockHead.Hash())
   329  	WriteHeadBlockHash(db, blockFull.Hash())
   330  	WriteHeadFastBlockHash(db, blockFast.Hash())
   331  
   332  	// Check that both heads are present, and different (i.e. two heads maintained)
   333  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   334  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   335  	}
   336  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   337  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   338  	}
   339  	if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
   340  		t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
   341  	}
   342  }
   343  
   344  // Tests that receipts associated with a single block can be stored and retrieved.
   345  func TestBlockReceiptStorage(t *testing.T) {
   346  	db := NewMemoryDatabase()
   347  
   348  	// Create a live block since we need metadata to reconstruct the receipt
   349  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   350  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   351  
   352  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   353  
   354  	// Create the two receipts to manage afterwards
   355  	receipt1 := &types.Receipt{
   356  		Status:            types.ReceiptStatusFailed,
   357  		CumulativeGasUsed: 1,
   358  		Logs: []*types.Log{
   359  			{Address: common.BytesToAddress([]byte{0x11})},
   360  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   361  		},
   362  		TxHash:          tx1.Hash(),
   363  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   364  		GasUsed:         111111,
   365  	}
   366  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   367  
   368  	receipt2 := &types.Receipt{
   369  		PostState:         common.Hash{2}.Bytes(),
   370  		CumulativeGasUsed: 2,
   371  		Logs: []*types.Log{
   372  			{Address: common.BytesToAddress([]byte{0x22})},
   373  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   374  		},
   375  		TxHash:          tx2.Hash(),
   376  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   377  		GasUsed:         222222,
   378  	}
   379  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   380  	receipts := []*types.Receipt{receipt1, receipt2}
   381  
   382  	// Check that no receipt entries are in a pristine database
   383  	hash := common.BytesToHash([]byte{0x03, 0x14})
   384  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   385  		t.Fatalf("non existent receipts returned: %v", rs)
   386  	}
   387  	// Insert the body that corresponds to the receipts
   388  	WriteBody(db, hash, 0, body)
   389  
   390  	// Insert the receipt slice into the database and check presence
   391  	WriteReceipts(db, hash, 0, receipts)
   392  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   393  		t.Fatalf("no receipts returned")
   394  	} else {
   395  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   396  			t.Fatalf(err.Error())
   397  		}
   398  	}
   399  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   400  	DeleteBody(db, hash, 0)
   401  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   402  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   403  	}
   404  	// Ensure that receipts without metadata can be returned without the block body too
   405  	if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
   406  		t.Fatalf(err.Error())
   407  	}
   408  	// Sanity check that body alone without the receipt is a full purge
   409  	WriteBody(db, hash, 0, body)
   410  
   411  	DeleteReceipts(db, hash, 0)
   412  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   413  		t.Fatalf("deleted receipts returned: %v", rs)
   414  	}
   415  }
   416  
   417  func checkReceiptsRLP(have, want types.Receipts) error {
   418  	if len(have) != len(want) {
   419  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   420  	}
   421  	for i := 0; i < len(want); i++ {
   422  		rlpHave, err := rlp.EncodeToBytes(have[i])
   423  		if err != nil {
   424  			return err
   425  		}
   426  		rlpWant, err := rlp.EncodeToBytes(want[i])
   427  		if err != nil {
   428  			return err
   429  		}
   430  		if !bytes.Equal(rlpHave, rlpWant) {
   431  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   432  		}
   433  	}
   434  	return nil
   435  }
   436  
   437  func TestAncientStorage(t *testing.T) {
   438  	// Freezer style fast import the chain.
   439  	frdir, err := ioutil.TempDir("", "")
   440  	if err != nil {
   441  		t.Fatalf("failed to create temp freezer dir: %v", err)
   442  	}
   443  	defer os.RemoveAll(frdir)
   444  
   445  	db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
   446  	if err != nil {
   447  		t.Fatalf("failed to create database with ancient backend")
   448  	}
   449  	defer db.Close()
   450  	// Create a test block
   451  	block := types.NewBlockWithHeader(&types.Header{
   452  		Number:      big.NewInt(0),
   453  		Extra:       []byte("test block"),
   454  		UncleHash:   types.EmptyUncleHash,
   455  		TxHash:      types.EmptyRootHash,
   456  		ReceiptHash: types.EmptyRootHash,
   457  	})
   458  	// Ensure nothing non-existent will be read
   459  	hash, number := block.Hash(), block.NumberU64()
   460  	if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
   461  		t.Fatalf("non existent header returned")
   462  	}
   463  	if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
   464  		t.Fatalf("non existent body returned")
   465  	}
   466  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
   467  		t.Fatalf("non existent receipts returned")
   468  	}
   469  	if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
   470  		t.Fatalf("non existent td returned")
   471  	}
   472  
   473  	// Write and verify the header in the database
   474  	WriteAncientBlocks(db, []*types.Block{block}, []types.Receipts{nil}, big.NewInt(100))
   475  
   476  	if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
   477  		t.Fatalf("no header returned")
   478  	}
   479  	if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
   480  		t.Fatalf("no body returned")
   481  	}
   482  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
   483  		t.Fatalf("no receipts returned")
   484  	}
   485  	if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
   486  		t.Fatalf("no td returned")
   487  	}
   488  
   489  	// Use a fake hash for data retrieval, nothing should be returned.
   490  	fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
   491  	if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
   492  		t.Fatalf("invalid header returned")
   493  	}
   494  	if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
   495  		t.Fatalf("invalid body returned")
   496  	}
   497  	if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
   498  		t.Fatalf("invalid receipts returned")
   499  	}
   500  	if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
   501  		t.Fatalf("invalid td returned")
   502  	}
   503  }
   504  
   505  func TestCanonicalHashIteration(t *testing.T) {
   506  	var cases = []struct {
   507  		from, to uint64
   508  		limit    int
   509  		expect   []uint64
   510  	}{
   511  		{1, 8, 0, nil},
   512  		{1, 8, 1, []uint64{1}},
   513  		{1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
   514  		{1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
   515  		{2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
   516  		{9, 10, 10, nil},
   517  	}
   518  	// Test empty db iteration
   519  	db := NewMemoryDatabase()
   520  	numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
   521  	if len(numbers) != 0 {
   522  		t.Fatalf("No entry should be returned to iterate an empty db")
   523  	}
   524  	// Fill database with testing data.
   525  	for i := uint64(1); i <= 8; i++ {
   526  		WriteCanonicalHash(db, common.Hash{}, i)
   527  		WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
   528  	}
   529  	for i, c := range cases {
   530  		numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
   531  		if !reflect.DeepEqual(numbers, c.expect) {
   532  			t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
   533  		}
   534  	}
   535  }
   536  
   537  func TestHashesInRange(t *testing.T) {
   538  	mkHeader := func(number, seq int) *types.Header {
   539  		h := types.Header{
   540  			Difficulty: new(big.Int),
   541  			Number:     big.NewInt(int64(number)),
   542  			GasLimit:   uint64(seq),
   543  		}
   544  		return &h
   545  	}
   546  	db := NewMemoryDatabase()
   547  	// For each number, write N versions of that particular number
   548  	total := 0
   549  	for i := 0; i < 15; i++ {
   550  		for ii := 0; ii < i; ii++ {
   551  			WriteHeader(db, mkHeader(i, ii))
   552  			total++
   553  		}
   554  	}
   555  	if have, want := len(ReadAllHashesInRange(db, 10, 10)), 10; have != want {
   556  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   557  	}
   558  	if have, want := len(ReadAllHashesInRange(db, 10, 9)), 0; have != want {
   559  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   560  	}
   561  	if have, want := len(ReadAllHashesInRange(db, 0, 100)), total; have != want {
   562  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   563  	}
   564  	if have, want := len(ReadAllHashesInRange(db, 9, 10)), 9+10; have != want {
   565  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   566  	}
   567  	if have, want := len(ReadAllHashes(db, 10)), 10; have != want {
   568  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   569  	}
   570  	if have, want := len(ReadAllHashes(db, 16)), 0; have != want {
   571  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   572  	}
   573  	if have, want := len(ReadAllHashes(db, 1)), 1; have != want {
   574  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   575  	}
   576  }
   577  
   578  // This measures the write speed of the WriteAncientBlocks operation.
   579  func BenchmarkWriteAncientBlocks(b *testing.B) {
   580  	// Open freezer database.
   581  	frdir, err := ioutil.TempDir("", "")
   582  	if err != nil {
   583  		b.Fatalf("failed to create temp freezer dir: %v", err)
   584  	}
   585  	defer os.RemoveAll(frdir)
   586  	db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
   587  	if err != nil {
   588  		b.Fatalf("failed to create database with ancient backend")
   589  	}
   590  
   591  	// Create the data to insert. The blocks must have consecutive numbers, so we create
   592  	// all of them ahead of time. However, there is no need to create receipts
   593  	// individually for each block, just make one batch here and reuse it for all writes.
   594  	const batchSize = 128
   595  	const blockTxs = 20
   596  	allBlocks := makeTestBlocks(b.N, blockTxs)
   597  	batchReceipts := makeTestReceipts(batchSize, blockTxs)
   598  	b.ResetTimer()
   599  
   600  	// The benchmark loop writes batches of blocks, but note that the total block count is
   601  	// b.N. This means the resulting ns/op measurement is the time it takes to write a
   602  	// single block and its associated data.
   603  	var td = big.NewInt(55)
   604  	var totalSize int64
   605  	for i := 0; i < b.N; i += batchSize {
   606  		length := batchSize
   607  		if i+batchSize > b.N {
   608  			length = b.N - i
   609  		}
   610  
   611  		blocks := allBlocks[i : i+length]
   612  		receipts := batchReceipts[:length]
   613  		writeSize, err := WriteAncientBlocks(db, blocks, receipts, td)
   614  		if err != nil {
   615  			b.Fatal(err)
   616  		}
   617  		totalSize += writeSize
   618  	}
   619  
   620  	// Enable MB/s reporting.
   621  	b.SetBytes(totalSize / int64(b.N))
   622  }
   623  
   624  // makeTestBlocks creates fake blocks for the ancient write benchmark.
   625  func makeTestBlocks(nblock int, txsPerBlock int) []*types.Block {
   626  	key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   627  	signer := types.LatestSignerForChainID(big.NewInt(8))
   628  
   629  	// Create transactions.
   630  	txs := make([]*types.Transaction, txsPerBlock)
   631  	for i := 0; i < len(txs); i++ {
   632  		var err error
   633  		to := common.Address{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
   634  		txs[i], err = types.SignNewTx(key, signer, &types.LegacyTx{
   635  			Nonce:    2,
   636  			GasPrice: big.NewInt(30000),
   637  			Gas:      0x45454545,
   638  			To:       &to,
   639  		})
   640  		if err != nil {
   641  			panic(err)
   642  		}
   643  	}
   644  
   645  	// Create the blocks.
   646  	blocks := make([]*types.Block, nblock)
   647  	for i := 0; i < nblock; i++ {
   648  		header := &types.Header{
   649  			Number: big.NewInt(int64(i)),
   650  			Extra:  []byte("test block"),
   651  		}
   652  		blocks[i] = types.NewBlockWithHeader(header).WithBody(txs, nil)
   653  		blocks[i].Hash() // pre-cache the block hash
   654  	}
   655  	return blocks
   656  }
   657  
   658  // makeTestReceipts creates fake receipts for the ancient write benchmark.
   659  func makeTestReceipts(n int, nPerBlock int) []types.Receipts {
   660  	receipts := make([]*types.Receipt, nPerBlock)
   661  	for i := 0; i < len(receipts); i++ {
   662  		receipts[i] = &types.Receipt{
   663  			Status:            types.ReceiptStatusSuccessful,
   664  			CumulativeGasUsed: 0x888888888,
   665  			Logs:              make([]*types.Log, 5),
   666  		}
   667  	}
   668  	allReceipts := make([]types.Receipts, n)
   669  	for i := 0; i < n; i++ {
   670  		allReceipts[i] = receipts
   671  	}
   672  	return allReceipts
   673  }
   674  
   675  type fullLogRLP struct {
   676  	Address     common.Address
   677  	Topics      []common.Hash
   678  	Data        []byte
   679  	BlockNumber uint64
   680  	TxHash      common.Hash
   681  	TxIndex     uint
   682  	BlockHash   common.Hash
   683  	Index       uint
   684  }
   685  
   686  func newFullLogRLP(l *types.Log) *fullLogRLP {
   687  	return &fullLogRLP{
   688  		Address:     l.Address,
   689  		Topics:      l.Topics,
   690  		Data:        l.Data,
   691  		BlockNumber: l.BlockNumber,
   692  		TxHash:      l.TxHash,
   693  		TxIndex:     l.TxIndex,
   694  		BlockHash:   l.BlockHash,
   695  		Index:       l.Index,
   696  	}
   697  }
   698  
   699  // Tests that logs associated with a single block can be retrieved.
   700  func TestReadLogs(t *testing.T) {
   701  	db := NewMemoryDatabase()
   702  
   703  	// Create a live block since we need metadata to reconstruct the receipt
   704  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   705  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   706  
   707  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   708  
   709  	// Create the two receipts to manage afterwards
   710  	receipt1 := &types.Receipt{
   711  		Status:            types.ReceiptStatusFailed,
   712  		CumulativeGasUsed: 1,
   713  		Logs: []*types.Log{
   714  			{Address: common.BytesToAddress([]byte{0x11})},
   715  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   716  		},
   717  		TxHash:          tx1.Hash(),
   718  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   719  		GasUsed:         111111,
   720  	}
   721  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   722  
   723  	receipt2 := &types.Receipt{
   724  		PostState:         common.Hash{2}.Bytes(),
   725  		CumulativeGasUsed: 2,
   726  		Logs: []*types.Log{
   727  			{Address: common.BytesToAddress([]byte{0x22})},
   728  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   729  		},
   730  		TxHash:          tx2.Hash(),
   731  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   732  		GasUsed:         222222,
   733  	}
   734  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   735  	receipts := []*types.Receipt{receipt1, receipt2}
   736  
   737  	hash := common.BytesToHash([]byte{0x03, 0x14})
   738  	// Check that no receipt entries are in a pristine database
   739  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   740  		t.Fatalf("non existent receipts returned: %v", rs)
   741  	}
   742  	// Insert the body that corresponds to the receipts
   743  	WriteBody(db, hash, 0, body)
   744  
   745  	// Insert the receipt slice into the database and check presence
   746  	WriteReceipts(db, hash, 0, receipts)
   747  
   748  	logs := ReadLogs(db, hash, 0, params.TestChainConfig)
   749  	if len(logs) == 0 {
   750  		t.Fatalf("no logs returned")
   751  	}
   752  	if have, want := len(logs), 2; have != want {
   753  		t.Fatalf("unexpected number of logs returned, have %d want %d", have, want)
   754  	}
   755  	if have, want := len(logs[0]), 2; have != want {
   756  		t.Fatalf("unexpected number of logs[0] returned, have %d want %d", have, want)
   757  	}
   758  	if have, want := len(logs[1]), 2; have != want {
   759  		t.Fatalf("unexpected number of logs[1] returned, have %d want %d", have, want)
   760  	}
   761  
   762  	// Fill in log fields so we can compare their rlp encoding
   763  	if err := types.Receipts(receipts).DeriveFields(params.TestChainConfig, hash, 0, body.Transactions); err != nil {
   764  		t.Fatal(err)
   765  	}
   766  	for i, pr := range receipts {
   767  		for j, pl := range pr.Logs {
   768  			rlpHave, err := rlp.EncodeToBytes(newFullLogRLP(logs[i][j]))
   769  			if err != nil {
   770  				t.Fatal(err)
   771  			}
   772  			rlpWant, err := rlp.EncodeToBytes(newFullLogRLP(pl))
   773  			if err != nil {
   774  				t.Fatal(err)
   775  			}
   776  			if !bytes.Equal(rlpHave, rlpWant) {
   777  				t.Fatalf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   778  			}
   779  		}
   780  	}
   781  }
   782  
   783  func TestDeriveLogFields(t *testing.T) {
   784  	// Create a few transactions to have receipts for
   785  	to2 := common.HexToAddress("0x2")
   786  	to3 := common.HexToAddress("0x3")
   787  	txs := types.Transactions{
   788  		types.NewTx(&types.LegacyTx{
   789  			Nonce:    1,
   790  			Value:    big.NewInt(1),
   791  			Gas:      1,
   792  			GasPrice: big.NewInt(1),
   793  		}),
   794  		types.NewTx(&types.LegacyTx{
   795  			To:       &to2,
   796  			Nonce:    2,
   797  			Value:    big.NewInt(2),
   798  			Gas:      2,
   799  			GasPrice: big.NewInt(2),
   800  		}),
   801  		types.NewTx(&types.AccessListTx{
   802  			To:       &to3,
   803  			Nonce:    3,
   804  			Value:    big.NewInt(3),
   805  			Gas:      3,
   806  			GasPrice: big.NewInt(3),
   807  		}),
   808  	}
   809  	// Create the corresponding receipts
   810  	receipts := []*receiptLogs{
   811  		{
   812  			Logs: []*types.Log{
   813  				{Address: common.BytesToAddress([]byte{0x11})},
   814  				{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   815  			},
   816  		},
   817  		{
   818  			Logs: []*types.Log{
   819  				{Address: common.BytesToAddress([]byte{0x22})},
   820  				{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   821  			},
   822  		},
   823  		{
   824  			Logs: []*types.Log{
   825  				{Address: common.BytesToAddress([]byte{0x33})},
   826  				{Address: common.BytesToAddress([]byte{0x03, 0x33})},
   827  			},
   828  		},
   829  	}
   830  
   831  	// Derive log metadata fields
   832  	number := big.NewInt(1)
   833  	hash := common.BytesToHash([]byte{0x03, 0x14})
   834  	if err := deriveLogFields(receipts, hash, number.Uint64(), txs); err != nil {
   835  		t.Fatal(err)
   836  	}
   837  
   838  	// Iterate over all the computed fields and check that they're correct
   839  	logIndex := uint(0)
   840  	for i := range receipts {
   841  		for j := range receipts[i].Logs {
   842  			if receipts[i].Logs[j].BlockNumber != number.Uint64() {
   843  				t.Errorf("receipts[%d].Logs[%d].BlockNumber = %d, want %d", i, j, receipts[i].Logs[j].BlockNumber, number.Uint64())
   844  			}
   845  			if receipts[i].Logs[j].BlockHash != hash {
   846  				t.Errorf("receipts[%d].Logs[%d].BlockHash = %s, want %s", i, j, receipts[i].Logs[j].BlockHash.String(), hash.String())
   847  			}
   848  			if receipts[i].Logs[j].TxHash != txs[i].Hash() {
   849  				t.Errorf("receipts[%d].Logs[%d].TxHash = %s, want %s", i, j, receipts[i].Logs[j].TxHash.String(), txs[i].Hash().String())
   850  			}
   851  			if receipts[i].Logs[j].TxIndex != uint(i) {
   852  				t.Errorf("receipts[%d].Logs[%d].TransactionIndex = %d, want %d", i, j, receipts[i].Logs[j].TxIndex, i)
   853  			}
   854  			if receipts[i].Logs[j].Index != logIndex {
   855  				t.Errorf("receipts[%d].Logs[%d].Index = %d, want %d", i, j, receipts[i].Logs[j].Index, logIndex)
   856  			}
   857  			logIndex++
   858  		}
   859  	}
   860  }
   861  
   862  func BenchmarkDecodeRLPLogs(b *testing.B) {
   863  	// Encoded receipts from block 0x14ee094309fbe8f70b65f45ebcc08fb33f126942d97464aad5eb91cfd1e2d269
   864  	buf, err := ioutil.ReadFile("testdata/stored_receipts.bin")
   865  	if err != nil {
   866  		b.Fatal(err)
   867  	}
   868  	b.Run("ReceiptForStorage", func(b *testing.B) {
   869  		b.ReportAllocs()
   870  		var r []*types.ReceiptForStorage
   871  		for i := 0; i < b.N; i++ {
   872  			if err := rlp.DecodeBytes(buf, &r); err != nil {
   873  				b.Fatal(err)
   874  			}
   875  		}
   876  	})
   877  	b.Run("rlpLogs", func(b *testing.B) {
   878  		b.ReportAllocs()
   879  		var r []*receiptLogs
   880  		for i := 0; i < b.N; i++ {
   881  			if err := rlp.DecodeBytes(buf, &r); err != nil {
   882  				b.Fatal(err)
   883  			}
   884  		}
   885  	})
   886  }