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