github.com/MetalBlockchain/subnet-evm@v0.4.9/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  	"os"
    25  	"reflect"
    26  	"testing"
    27  
    28  	"github.com/MetalBlockchain/subnet-evm/core/types"
    29  	"github.com/MetalBlockchain/subnet-evm/params"
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/rlp"
    32  	"golang.org/x/crypto/sha3"
    33  )
    34  
    35  // Tests block header storage and retrieval operations.
    36  func TestHeaderStorage(t *testing.T) {
    37  	db := NewMemoryDatabase()
    38  
    39  	// Create a test header to move around the database and make sure it's really new
    40  	header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
    41  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    42  		t.Fatalf("Non existent header returned: %v", entry)
    43  	}
    44  	// Write and verify the header in the database
    45  	WriteHeader(db, header)
    46  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
    47  		t.Fatalf("Stored header not found")
    48  	} else if entry.Hash() != header.Hash() {
    49  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
    50  	}
    51  	if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
    52  		t.Fatalf("Stored header RLP not found")
    53  	} else {
    54  		hasher := sha3.NewLegacyKeccak256()
    55  		hasher.Write(entry)
    56  
    57  		if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
    58  			t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
    59  		}
    60  	}
    61  	// Delete the header and verify the execution
    62  	DeleteHeader(db, header.Hash(), header.Number.Uint64())
    63  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    64  		t.Fatalf("Deleted header returned: %v", entry)
    65  	}
    66  }
    67  
    68  // Tests block body storage and retrieval operations.
    69  func TestBodyStorage(t *testing.T) {
    70  	db := NewMemoryDatabase()
    71  
    72  	// Create a test body to move around the database and make sure it's really new
    73  	body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
    74  
    75  	hasher := sha3.NewLegacyKeccak256()
    76  	rlp.Encode(hasher, body)
    77  	hash := common.BytesToHash(hasher.Sum(nil))
    78  
    79  	if entry := ReadBody(db, hash, 0); entry != nil {
    80  		t.Fatalf("Non existent body returned: %v", entry)
    81  	}
    82  	// Write and verify the body in the database
    83  	WriteBody(db, hash, 0, body)
    84  	if entry := ReadBody(db, hash, 0); entry == nil {
    85  		t.Fatalf("Stored body not found")
    86  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
    87  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
    88  	}
    89  	if entry := ReadBodyRLP(db, hash, 0); entry == nil {
    90  		t.Fatalf("Stored body RLP not found")
    91  	} else {
    92  		hasher := sha3.NewLegacyKeccak256()
    93  		hasher.Write(entry)
    94  
    95  		if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
    96  			t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
    97  		}
    98  	}
    99  	// Delete the body and verify the execution
   100  	DeleteBody(db, hash, 0)
   101  	if entry := ReadBody(db, hash, 0); entry != nil {
   102  		t.Fatalf("Deleted body returned: %v", entry)
   103  	}
   104  }
   105  
   106  // Tests block storage and retrieval operations.
   107  func TestBlockStorage(t *testing.T) {
   108  	db := NewMemoryDatabase()
   109  
   110  	// Create a test block to move around the database and make sure it's really new
   111  	block := types.NewBlockWithHeader(&types.Header{
   112  		Extra:       []byte("test block"),
   113  		UncleHash:   types.EmptyUncleHash,
   114  		TxHash:      types.EmptyRootHash,
   115  		ReceiptHash: types.EmptyRootHash,
   116  	})
   117  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   118  		t.Fatalf("Non existent block returned: %v", entry)
   119  	}
   120  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   121  		t.Fatalf("Non existent header returned: %v", entry)
   122  	}
   123  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   124  		t.Fatalf("Non existent body returned: %v", entry)
   125  	}
   126  	// Write and verify the block in the database
   127  	WriteBlock(db, block)
   128  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   129  		t.Fatalf("Stored block not found")
   130  	} else if entry.Hash() != block.Hash() {
   131  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   132  	}
   133  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
   134  		t.Fatalf("Stored header not found")
   135  	} else if entry.Hash() != block.Header().Hash() {
   136  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
   137  	}
   138  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
   139  		t.Fatalf("Stored body not found")
   140  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
   141  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
   142  	}
   143  	// Delete the block and verify the execution
   144  	DeleteBlock(db, block.Hash(), block.NumberU64())
   145  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   146  		t.Fatalf("Deleted block returned: %v", entry)
   147  	}
   148  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   149  		t.Fatalf("Deleted header returned: %v", entry)
   150  	}
   151  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   152  		t.Fatalf("Deleted body returned: %v", entry)
   153  	}
   154  }
   155  
   156  // Tests that partial block contents don't get reassembled into full blocks.
   157  func TestPartialBlockStorage(t *testing.T) {
   158  	db := NewMemoryDatabase()
   159  	block := types.NewBlockWithHeader(&types.Header{
   160  		Extra:       []byte("test block"),
   161  		UncleHash:   types.EmptyUncleHash,
   162  		TxHash:      types.EmptyRootHash,
   163  		ReceiptHash: types.EmptyRootHash,
   164  	})
   165  	// Store a header and check that it's not recognized as a block
   166  	WriteHeader(db, block.Header())
   167  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   168  		t.Fatalf("Non existent block returned: %v", entry)
   169  	}
   170  	DeleteHeader(db, block.Hash(), block.NumberU64())
   171  
   172  	// Store a body and check that it's not recognized as a block
   173  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   174  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   175  		t.Fatalf("Non existent block returned: %v", entry)
   176  	}
   177  	DeleteBody(db, block.Hash(), block.NumberU64())
   178  
   179  	// Store a header and a body separately and check reassembly
   180  	WriteHeader(db, block.Header())
   181  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   182  
   183  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   184  		t.Fatalf("Stored block not found")
   185  	} else if entry.Hash() != block.Hash() {
   186  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   187  	}
   188  }
   189  
   190  // Tests that canonical numbers can be mapped to hashes and retrieved.
   191  func TestCanonicalMappingStorage(t *testing.T) {
   192  	db := NewMemoryDatabase()
   193  
   194  	// Create a test canonical number and assigned hash to move around
   195  	hash, number := common.Hash{0: 0xff}, uint64(314)
   196  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   197  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   198  	}
   199  	// Write and verify the TD in the database
   200  	WriteCanonicalHash(db, hash, number)
   201  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   202  		t.Fatalf("Stored canonical mapping not found")
   203  	} else if entry != hash {
   204  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   205  	}
   206  	// Delete the TD and verify the execution
   207  	DeleteCanonicalHash(db, number)
   208  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   209  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   210  	}
   211  }
   212  
   213  // Tests that head headers and head blocks can be assigned, individually.
   214  func TestHeadStorage(t *testing.T) {
   215  	db := NewMemoryDatabase()
   216  
   217  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   218  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   219  
   220  	// Check that no head entries are in a pristine database
   221  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   222  		t.Fatalf("Non head header entry returned: %v", entry)
   223  	}
   224  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   225  		t.Fatalf("Non head block entry returned: %v", entry)
   226  	}
   227  	// Assign separate entries for the head header and block
   228  	WriteHeadHeaderHash(db, blockHead.Hash())
   229  	WriteHeadBlockHash(db, blockFull.Hash())
   230  
   231  	// Check that both heads are present, and different (i.e. two heads maintained)
   232  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   233  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   234  	}
   235  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   236  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   237  	}
   238  }
   239  
   240  // Tests that receipts associated with a single block can be stored and retrieved.
   241  func TestBlockReceiptStorage(t *testing.T) {
   242  	db := NewMemoryDatabase()
   243  
   244  	// Create a live block since we need metadata to reconstruct the receipt
   245  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   246  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   247  
   248  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   249  
   250  	// Create the two receipts to manage afterwards
   251  	receipt1 := &types.Receipt{
   252  		Status:            types.ReceiptStatusFailed,
   253  		CumulativeGasUsed: 1,
   254  		Logs: []*types.Log{
   255  			{Address: common.BytesToAddress([]byte{0x11})},
   256  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   257  		},
   258  		TxHash:          tx1.Hash(),
   259  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   260  		GasUsed:         111111,
   261  	}
   262  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   263  
   264  	receipt2 := &types.Receipt{
   265  		PostState:         common.Hash{2}.Bytes(),
   266  		CumulativeGasUsed: 2,
   267  		Logs: []*types.Log{
   268  			{Address: common.BytesToAddress([]byte{0x22})},
   269  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   270  		},
   271  		TxHash:          tx2.Hash(),
   272  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   273  		GasUsed:         222222,
   274  	}
   275  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   276  	receipts := []*types.Receipt{receipt1, receipt2}
   277  
   278  	// Check that no receipt entries are in a pristine database
   279  	header := &types.Header{Number: big.NewInt(0), Extra: []byte("test header")}
   280  	hash := header.Hash()
   281  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   282  		t.Fatalf("non existent receipts returned: %v", rs)
   283  	}
   284  	// Insert the body that corresponds to the receipts
   285  	WriteHeader(db, header)
   286  	WriteBody(db, hash, 0, body)
   287  	if header := ReadHeader(db, hash, 0); header == nil {
   288  		t.Fatal("header is nil")
   289  	}
   290  
   291  	// Insert the receipt slice into the database and check presence
   292  	WriteReceipts(db, hash, 0, receipts)
   293  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   294  		t.Fatalf("no receipts returned")
   295  	} else {
   296  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   297  			t.Fatalf(err.Error())
   298  		}
   299  	}
   300  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   301  	DeleteHeader(db, hash, 0)
   302  	DeleteBody(db, hash, 0)
   303  	if header := ReadHeader(db, hash, 0); header != nil {
   304  		t.Fatal("header is not nil")
   305  	}
   306  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   307  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   308  	}
   309  	// Ensure that receipts without metadata can be returned without the block body too
   310  	if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
   311  		t.Fatalf(err.Error())
   312  	}
   313  	// Sanity check that body and header alone without the receipt is a full purge
   314  	WriteHeader(db, header)
   315  	WriteBody(db, hash, 0, body)
   316  
   317  	DeleteReceipts(db, hash, 0)
   318  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   319  		t.Fatalf("deleted receipts returned: %v", rs)
   320  	}
   321  }
   322  
   323  func checkReceiptsRLP(have, want types.Receipts) error {
   324  	if len(have) != len(want) {
   325  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   326  	}
   327  	for i := 0; i < len(want); i++ {
   328  		rlpHave, err := rlp.EncodeToBytes(have[i])
   329  		if err != nil {
   330  			return err
   331  		}
   332  		rlpWant, err := rlp.EncodeToBytes(want[i])
   333  		if err != nil {
   334  			return err
   335  		}
   336  		if !bytes.Equal(rlpHave, rlpWant) {
   337  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   338  		}
   339  	}
   340  	return nil
   341  }
   342  
   343  func TestCanonicalHashIteration(t *testing.T) {
   344  	var cases = []struct {
   345  		from, to uint64
   346  		limit    int
   347  		expect   []uint64
   348  	}{
   349  		{1, 8, 0, nil},
   350  		{1, 8, 1, []uint64{1}},
   351  		{1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
   352  		{1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
   353  		{2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
   354  		{9, 10, 10, nil},
   355  	}
   356  	// Test empty db iteration
   357  	db := NewMemoryDatabase()
   358  	numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
   359  	if len(numbers) != 0 {
   360  		t.Fatalf("No entry should be returned to iterate an empty db")
   361  	}
   362  	// Fill database with testing data.
   363  	for i := uint64(1); i <= 8; i++ {
   364  		WriteCanonicalHash(db, common.Hash{}, i)
   365  	}
   366  	for i, c := range cases {
   367  		numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
   368  		if !reflect.DeepEqual(numbers, c.expect) {
   369  			t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
   370  		}
   371  	}
   372  }
   373  
   374  func TestHashesInRange(t *testing.T) {
   375  	mkHeader := func(number, seq int) *types.Header {
   376  		h := types.Header{
   377  			Difficulty: new(big.Int),
   378  			Number:     big.NewInt(int64(number)),
   379  			GasLimit:   uint64(seq),
   380  		}
   381  		return &h
   382  	}
   383  	db := NewMemoryDatabase()
   384  	// For each number, write N versions of that particular number
   385  	total := 0
   386  	for i := 0; i < 15; i++ {
   387  		for ii := 0; ii < i; ii++ {
   388  			WriteHeader(db, mkHeader(i, ii))
   389  			total++
   390  		}
   391  	}
   392  	if have, want := len(ReadAllHashesInRange(db, 10, 10)), 10; have != want {
   393  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   394  	}
   395  	if have, want := len(ReadAllHashesInRange(db, 10, 9)), 0; have != want {
   396  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   397  	}
   398  	if have, want := len(ReadAllHashesInRange(db, 0, 100)), total; have != want {
   399  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   400  	}
   401  	if have, want := len(ReadAllHashesInRange(db, 9, 10)), 9+10; have != want {
   402  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   403  	}
   404  	if have, want := len(ReadAllHashes(db, 10)), 10; have != want {
   405  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   406  	}
   407  	if have, want := len(ReadAllHashes(db, 16)), 0; have != want {
   408  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   409  	}
   410  	if have, want := len(ReadAllHashes(db, 1)), 1; have != want {
   411  		t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
   412  	}
   413  }
   414  
   415  type fullLogRLP struct {
   416  	Address     common.Address
   417  	Topics      []common.Hash
   418  	Data        []byte
   419  	BlockNumber uint64
   420  	TxHash      common.Hash
   421  	TxIndex     uint
   422  	BlockHash   common.Hash
   423  	Index       uint
   424  }
   425  
   426  func newFullLogRLP(l *types.Log) *fullLogRLP {
   427  	return &fullLogRLP{
   428  		Address:     l.Address,
   429  		Topics:      l.Topics,
   430  		Data:        l.Data,
   431  		BlockNumber: l.BlockNumber,
   432  		TxHash:      l.TxHash,
   433  		TxIndex:     l.TxIndex,
   434  		BlockHash:   l.BlockHash,
   435  		Index:       l.Index,
   436  	}
   437  }
   438  
   439  // Tests that logs associated with a single block can be retrieved.
   440  func TestReadLogs(t *testing.T) {
   441  	db := NewMemoryDatabase()
   442  
   443  	// Create a live block since we need metadata to reconstruct the receipt
   444  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   445  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   446  
   447  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   448  
   449  	// Create the two receipts to manage afterwards
   450  	receipt1 := &types.Receipt{
   451  		Status:            types.ReceiptStatusFailed,
   452  		CumulativeGasUsed: 1,
   453  		Logs: []*types.Log{
   454  			{Address: common.BytesToAddress([]byte{0x11})},
   455  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   456  		},
   457  		TxHash:          tx1.Hash(),
   458  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   459  		GasUsed:         111111,
   460  	}
   461  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   462  
   463  	receipt2 := &types.Receipt{
   464  		PostState:         common.Hash{2}.Bytes(),
   465  		CumulativeGasUsed: 2,
   466  		Logs: []*types.Log{
   467  			{Address: common.BytesToAddress([]byte{0x22})},
   468  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   469  		},
   470  		TxHash:          tx2.Hash(),
   471  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   472  		GasUsed:         222222,
   473  	}
   474  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   475  	receipts := []*types.Receipt{receipt1, receipt2}
   476  
   477  	hash := common.BytesToHash([]byte{0x03, 0x14})
   478  	// Check that no receipt entries are in a pristine database
   479  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   480  		t.Fatalf("non existent receipts returned: %v", rs)
   481  	}
   482  	// Insert the body that corresponds to the receipts
   483  	WriteBody(db, hash, 0, body)
   484  
   485  	// Insert the receipt slice into the database and check presence
   486  	WriteReceipts(db, hash, 0, receipts)
   487  
   488  	logs := ReadLogs(db, hash, 0)
   489  	if len(logs) == 0 {
   490  		t.Fatalf("no logs returned")
   491  	}
   492  	if have, want := len(logs), 2; have != want {
   493  		t.Fatalf("unexpected number of logs returned, have %d want %d", have, want)
   494  	}
   495  	if have, want := len(logs[0]), 2; have != want {
   496  		t.Fatalf("unexpected number of logs[0] returned, have %d want %d", have, want)
   497  	}
   498  	if have, want := len(logs[1]), 2; have != want {
   499  		t.Fatalf("unexpected number of logs[1] returned, have %d want %d", have, want)
   500  	}
   501  
   502  	// Fill in log fields so we can compare their rlp encoding
   503  	if err := types.Receipts(receipts).DeriveFields(params.TestChainConfig, hash, 0, 0, body.Transactions); err != nil {
   504  		t.Fatal(err)
   505  	}
   506  	for i, pr := range receipts {
   507  		for j, pl := range pr.Logs {
   508  			rlpHave, err := rlp.EncodeToBytes(newFullLogRLP(logs[i][j]))
   509  			if err != nil {
   510  				t.Fatal(err)
   511  			}
   512  			rlpWant, err := rlp.EncodeToBytes(newFullLogRLP(pl))
   513  			if err != nil {
   514  				t.Fatal(err)
   515  			}
   516  			if !bytes.Equal(rlpHave, rlpWant) {
   517  				t.Fatalf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   518  			}
   519  		}
   520  	}
   521  }
   522  
   523  func TestDeriveLogFields(t *testing.T) {
   524  	// Create a few transactions to have receipts for
   525  	to2 := common.HexToAddress("0x2")
   526  	to3 := common.HexToAddress("0x3")
   527  	txs := types.Transactions{
   528  		types.NewTx(&types.LegacyTx{
   529  			Nonce:    1,
   530  			Value:    big.NewInt(1),
   531  			Gas:      1,
   532  			GasPrice: big.NewInt(1),
   533  		}),
   534  		types.NewTx(&types.LegacyTx{
   535  			To:       &to2,
   536  			Nonce:    2,
   537  			Value:    big.NewInt(2),
   538  			Gas:      2,
   539  			GasPrice: big.NewInt(2),
   540  		}),
   541  		types.NewTx(&types.AccessListTx{
   542  			To:       &to3,
   543  			Nonce:    3,
   544  			Value:    big.NewInt(3),
   545  			Gas:      3,
   546  			GasPrice: big.NewInt(3),
   547  		}),
   548  	}
   549  	// Create the corresponding receipts
   550  	receipts := []*receiptLogs{
   551  		{
   552  			Logs: []*types.Log{
   553  				{Address: common.BytesToAddress([]byte{0x11})},
   554  				{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   555  			},
   556  		},
   557  		{
   558  			Logs: []*types.Log{
   559  				{Address: common.BytesToAddress([]byte{0x22})},
   560  				{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   561  			},
   562  		},
   563  		{
   564  			Logs: []*types.Log{
   565  				{Address: common.BytesToAddress([]byte{0x33})},
   566  				{Address: common.BytesToAddress([]byte{0x03, 0x33})},
   567  			},
   568  		},
   569  	}
   570  
   571  	// Derive log metadata fields
   572  	number := big.NewInt(1)
   573  	hash := common.BytesToHash([]byte{0x03, 0x14})
   574  	if err := deriveLogFields(receipts, hash, number.Uint64(), txs); err != nil {
   575  		t.Fatal(err)
   576  	}
   577  
   578  	// Iterate over all the computed fields and check that they're correct
   579  	logIndex := uint(0)
   580  	for i := range receipts {
   581  		for j := range receipts[i].Logs {
   582  			if receipts[i].Logs[j].BlockNumber != number.Uint64() {
   583  				t.Errorf("receipts[%d].Logs[%d].BlockNumber = %d, want %d", i, j, receipts[i].Logs[j].BlockNumber, number.Uint64())
   584  			}
   585  			if receipts[i].Logs[j].BlockHash != hash {
   586  				t.Errorf("receipts[%d].Logs[%d].BlockHash = %s, want %s", i, j, receipts[i].Logs[j].BlockHash.String(), hash.String())
   587  			}
   588  			if receipts[i].Logs[j].TxHash != txs[i].Hash() {
   589  				t.Errorf("receipts[%d].Logs[%d].TxHash = %s, want %s", i, j, receipts[i].Logs[j].TxHash.String(), txs[i].Hash().String())
   590  			}
   591  			if receipts[i].Logs[j].TxIndex != uint(i) {
   592  				t.Errorf("receipts[%d].Logs[%d].TransactionIndex = %d, want %d", i, j, receipts[i].Logs[j].TxIndex, i)
   593  			}
   594  			if receipts[i].Logs[j].Index != logIndex {
   595  				t.Errorf("receipts[%d].Logs[%d].Index = %d, want %d", i, j, receipts[i].Logs[j].Index, logIndex)
   596  			}
   597  			logIndex++
   598  		}
   599  	}
   600  }
   601  
   602  func BenchmarkDecodeRLPLogs(b *testing.B) {
   603  	// Encoded receipts from block 0x14ee094309fbe8f70b65f45ebcc08fb33f126942d97464aad5eb91cfd1e2d269
   604  	buf, err := os.ReadFile("testdata/stored_receipts.bin")
   605  	if err != nil {
   606  		b.Fatal(err)
   607  	}
   608  	b.Run("ReceiptForStorage", func(b *testing.B) {
   609  		b.ReportAllocs()
   610  		var r []*types.ReceiptForStorage
   611  		for i := 0; i < b.N; i++ {
   612  			if err := rlp.DecodeBytes(buf, &r); err != nil {
   613  				b.Fatal(err)
   614  			}
   615  		}
   616  	})
   617  	b.Run("rlpLogs", func(b *testing.B) {
   618  		b.ReportAllocs()
   619  		var r []*receiptLogs
   620  		for i := 0; i < b.N; i++ {
   621  			if err := rlp.DecodeBytes(buf, &r); err != nil {
   622  				b.Fatal(err)
   623  			}
   624  		}
   625  	})
   626  }