gitlab.com/flarenetwork/coreth@v0.1.1/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  	"reflect"
    25  	"testing"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/rlp"
    29  	"gitlab.com/flarenetwork/coreth/core/types"
    30  	"gitlab.com/flarenetwork/coreth/params"
    31  	"golang.org/x/crypto/sha3"
    32  )
    33  
    34  // Tests block header storage and retrieval operations.
    35  func TestHeaderStorage(t *testing.T) {
    36  	db := NewMemoryDatabase()
    37  
    38  	// Create a test header to move around the database and make sure it's really new
    39  	header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
    40  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    41  		t.Fatalf("Non existent header returned: %v", entry)
    42  	}
    43  	// Write and verify the header in the database
    44  	WriteHeader(db, header)
    45  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
    46  		t.Fatalf("Stored header not found")
    47  	} else if entry.Hash() != header.Hash() {
    48  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
    49  	}
    50  	if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
    51  		t.Fatalf("Stored header RLP not found")
    52  	} else {
    53  		hasher := sha3.NewLegacyKeccak256()
    54  		hasher.Write(entry)
    55  
    56  		if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
    57  			t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
    58  		}
    59  	}
    60  	// Delete the header and verify the execution
    61  	DeleteHeader(db, header.Hash(), header.Number.Uint64())
    62  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    63  		t.Fatalf("Deleted header returned: %v", entry)
    64  	}
    65  }
    66  
    67  // Tests block body storage and retrieval operations.
    68  func TestBodyStorage(t *testing.T) {
    69  	db := NewMemoryDatabase()
    70  
    71  	// Create a test body to move around the database and make sure it's really new
    72  	body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
    73  
    74  	hasher := sha3.NewLegacyKeccak256()
    75  	rlp.Encode(hasher, body)
    76  	hash := common.BytesToHash(hasher.Sum(nil))
    77  
    78  	if entry := ReadBody(db, hash, 0); entry != nil {
    79  		t.Fatalf("Non existent body returned: %v", entry)
    80  	}
    81  	// Write and verify the body in the database
    82  	WriteBody(db, hash, 0, body)
    83  	if entry := ReadBody(db, hash, 0); entry == nil {
    84  		t.Fatalf("Stored body not found")
    85  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
    86  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
    87  	}
    88  	if entry := ReadBodyRLP(db, hash, 0); entry == nil {
    89  		t.Fatalf("Stored body RLP not found")
    90  	} else {
    91  		hasher := sha3.NewLegacyKeccak256()
    92  		hasher.Write(entry)
    93  
    94  		if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
    95  			t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
    96  		}
    97  	}
    98  	// Delete the body and verify the execution
    99  	DeleteBody(db, hash, 0)
   100  	if entry := ReadBody(db, hash, 0); entry != nil {
   101  		t.Fatalf("Deleted body returned: %v", entry)
   102  	}
   103  }
   104  
   105  // Tests block storage and retrieval operations.
   106  func TestBlockStorage(t *testing.T) {
   107  	db := NewMemoryDatabase()
   108  
   109  	// Create a test block to move around the database and make sure it's really new
   110  	block := types.NewBlockWithHeader(&types.Header{
   111  		Extra:       []byte("test block"),
   112  		UncleHash:   types.EmptyUncleHash,
   113  		TxHash:      types.EmptyRootHash,
   114  		ReceiptHash: types.EmptyRootHash,
   115  	})
   116  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   117  		t.Fatalf("Non existent block returned: %v", entry)
   118  	}
   119  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   120  		t.Fatalf("Non existent header returned: %v", entry)
   121  	}
   122  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   123  		t.Fatalf("Non existent body returned: %v", entry)
   124  	}
   125  	// Write and verify the block in the database
   126  	WriteBlock(db, block)
   127  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   128  		t.Fatalf("Stored block not found")
   129  	} else if entry.Hash() != block.Hash() {
   130  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   131  	}
   132  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
   133  		t.Fatalf("Stored header not found")
   134  	} else if entry.Hash() != block.Header().Hash() {
   135  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
   136  	}
   137  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
   138  		t.Fatalf("Stored body not found")
   139  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
   140  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
   141  	}
   142  	// Delete the block and verify the execution
   143  	DeleteBlock(db, block.Hash(), block.NumberU64())
   144  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   145  		t.Fatalf("Deleted block returned: %v", entry)
   146  	}
   147  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   148  		t.Fatalf("Deleted header returned: %v", entry)
   149  	}
   150  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   151  		t.Fatalf("Deleted body returned: %v", entry)
   152  	}
   153  }
   154  
   155  // Tests that partial block contents don't get reassembled into full blocks.
   156  func TestPartialBlockStorage(t *testing.T) {
   157  	db := NewMemoryDatabase()
   158  	block := types.NewBlockWithHeader(&types.Header{
   159  		Extra:       []byte("test block"),
   160  		UncleHash:   types.EmptyUncleHash,
   161  		TxHash:      types.EmptyRootHash,
   162  		ReceiptHash: types.EmptyRootHash,
   163  	})
   164  	// Store a header and check that it's not recognized as a block
   165  	WriteHeader(db, block.Header())
   166  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   167  		t.Fatalf("Non existent block returned: %v", entry)
   168  	}
   169  	DeleteHeader(db, block.Hash(), block.NumberU64())
   170  
   171  	// Store a body and check that it's not recognized as a block
   172  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   173  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   174  		t.Fatalf("Non existent block returned: %v", entry)
   175  	}
   176  	DeleteBody(db, block.Hash(), block.NumberU64())
   177  
   178  	// Store a header and a body separately and check reassembly
   179  	WriteHeader(db, block.Header())
   180  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   181  
   182  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   183  		t.Fatalf("Stored block not found")
   184  	} else if entry.Hash() != block.Hash() {
   185  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   186  	}
   187  }
   188  
   189  // Tests block total difficulty storage and retrieval operations.
   190  func TestTdStorage(t *testing.T) {
   191  	db := NewMemoryDatabase()
   192  
   193  	// Create a test TD to move around the database and make sure it's really new
   194  	hash, td := common.Hash{}, big.NewInt(314)
   195  	if entry := ReadTd(db, hash, 0); entry != nil {
   196  		t.Fatalf("Non existent TD returned: %v", entry)
   197  	}
   198  	// Write and verify the TD in the database
   199  	WriteTd(db, hash, 0, td)
   200  	if entry := ReadTd(db, hash, 0); entry == nil {
   201  		t.Fatalf("Stored TD not found")
   202  	} else if entry.Cmp(td) != 0 {
   203  		t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
   204  	}
   205  	// Delete the TD and verify the execution
   206  	DeleteTd(db, hash, 0)
   207  	if entry := ReadTd(db, hash, 0); entry != nil {
   208  		t.Fatalf("Deleted TD returned: %v", entry)
   209  	}
   210  }
   211  
   212  // Tests that canonical numbers can be mapped to hashes and retrieved.
   213  func TestCanonicalMappingStorage(t *testing.T) {
   214  	db := NewMemoryDatabase()
   215  
   216  	// Create a test canonical number and assinged hash to move around
   217  	hash, number := common.Hash{0: 0xff}, uint64(314)
   218  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   219  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   220  	}
   221  	// Write and verify the TD in the database
   222  	WriteCanonicalHash(db, hash, number)
   223  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   224  		t.Fatalf("Stored canonical mapping not found")
   225  	} else if entry != hash {
   226  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   227  	}
   228  	// Delete the TD and verify the execution
   229  	DeleteCanonicalHash(db, number)
   230  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   231  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   232  	}
   233  }
   234  
   235  // Tests that head headers and head blocks can be assigned, individually.
   236  func TestHeadStorage(t *testing.T) {
   237  	db := NewMemoryDatabase()
   238  
   239  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   240  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   241  	blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
   242  
   243  	// Check that no head entries are in a pristine database
   244  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   245  		t.Fatalf("Non head header entry returned: %v", entry)
   246  	}
   247  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   248  		t.Fatalf("Non head block entry returned: %v", entry)
   249  	}
   250  	if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
   251  		t.Fatalf("Non fast head block entry returned: %v", entry)
   252  	}
   253  	// Assign separate entries for the head header and block
   254  	WriteHeadHeaderHash(db, blockHead.Hash())
   255  	WriteHeadBlockHash(db, blockFull.Hash())
   256  	WriteHeadFastBlockHash(db, blockFast.Hash())
   257  
   258  	// Check that both heads are present, and different (i.e. two heads maintained)
   259  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   260  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   261  	}
   262  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   263  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   264  	}
   265  	if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
   266  		t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
   267  	}
   268  }
   269  
   270  // Tests that receipts associated with a single block can be stored and retrieved.
   271  func TestBlockReceiptStorage(t *testing.T) {
   272  	db := NewMemoryDatabase()
   273  
   274  	// Create a live block since we need metadata to reconstruct the receipt
   275  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   276  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   277  
   278  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   279  
   280  	// Create the two receipts to manage afterwards
   281  	receipt1 := &types.Receipt{
   282  		Status:            types.ReceiptStatusFailed,
   283  		CumulativeGasUsed: 1,
   284  		Logs: []*types.Log{
   285  			{Address: common.BytesToAddress([]byte{0x11})},
   286  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   287  		},
   288  		TxHash:          tx1.Hash(),
   289  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   290  		GasUsed:         111111,
   291  	}
   292  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   293  
   294  	receipt2 := &types.Receipt{
   295  		PostState:         common.Hash{2}.Bytes(),
   296  		CumulativeGasUsed: 2,
   297  		Logs: []*types.Log{
   298  			{Address: common.BytesToAddress([]byte{0x22})},
   299  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   300  		},
   301  		TxHash:          tx2.Hash(),
   302  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   303  		GasUsed:         222222,
   304  	}
   305  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   306  	receipts := []*types.Receipt{receipt1, receipt2}
   307  
   308  	// Check that no receipt entries are in a pristine database
   309  	header := &types.Header{Number: big.NewInt(0), Extra: []byte("test header")}
   310  	hash := header.Hash()
   311  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   312  		t.Fatalf("non existent receipts returned: %v", rs)
   313  	}
   314  	// Insert the body that corresponds to the receipts
   315  	WriteHeader(db, header)
   316  	WriteBody(db, hash, 0, body)
   317  	if header := ReadHeader(db, hash, 0); header == nil {
   318  		t.Fatal("header is nil")
   319  	}
   320  
   321  	// Insert the receipt slice into the database and check presence
   322  	WriteReceipts(db, hash, 0, receipts)
   323  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   324  		t.Fatalf("no receipts returned")
   325  	} else {
   326  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   327  			t.Fatalf(err.Error())
   328  		}
   329  	}
   330  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   331  	DeleteHeader(db, hash, 0)
   332  	DeleteBody(db, hash, 0)
   333  	if header := ReadHeader(db, hash, 0); header != nil {
   334  		t.Fatal("header is not nil")
   335  	}
   336  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   337  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   338  	}
   339  	// Ensure that receipts without metadata can be returned without the block body too
   340  	if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
   341  		t.Fatalf(err.Error())
   342  	}
   343  	// Sanity check that body and header alone without the receipt is a full purge
   344  	WriteHeader(db, header)
   345  	WriteBody(db, hash, 0, body)
   346  
   347  	DeleteReceipts(db, hash, 0)
   348  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   349  		t.Fatalf("deleted receipts returned: %v", rs)
   350  	}
   351  }
   352  
   353  func checkReceiptsRLP(have, want types.Receipts) error {
   354  	if len(have) != len(want) {
   355  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   356  	}
   357  	for i := 0; i < len(want); i++ {
   358  		rlpHave, err := rlp.EncodeToBytes(have[i])
   359  		if err != nil {
   360  			return err
   361  		}
   362  		rlpWant, err := rlp.EncodeToBytes(want[i])
   363  		if err != nil {
   364  			return err
   365  		}
   366  		if !bytes.Equal(rlpHave, rlpWant) {
   367  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   368  		}
   369  	}
   370  	return nil
   371  }
   372  
   373  func TestCanonicalHashIteration(t *testing.T) {
   374  	var cases = []struct {
   375  		from, to uint64
   376  		limit    int
   377  		expect   []uint64
   378  	}{
   379  		{1, 8, 0, nil},
   380  		{1, 8, 1, []uint64{1}},
   381  		{1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
   382  		{1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
   383  		{2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
   384  		{9, 10, 10, nil},
   385  	}
   386  	// Test empty db iteration
   387  	db := NewMemoryDatabase()
   388  	numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
   389  	if len(numbers) != 0 {
   390  		t.Fatalf("No entry should be returned to iterate an empty db")
   391  	}
   392  	// Fill database with testing data.
   393  	for i := uint64(1); i <= 8; i++ {
   394  		WriteCanonicalHash(db, common.Hash{}, i)
   395  		WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
   396  	}
   397  	for i, c := range cases {
   398  		numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
   399  		if !reflect.DeepEqual(numbers, c.expect) {
   400  			t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
   401  		}
   402  	}
   403  }