github.com/bcskill/bcschain/v3@v3.4.9-beta2/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  	"github.com/bcskill/bcschain/v3/params"
    24  	"math/big"
    25  	"testing"
    26  
    27  	"golang.org/x/crypto/sha3"
    28  
    29  	"github.com/bcskill/bcschain/v3/common"
    30  	"github.com/bcskill/bcschain/v3/core/types"
    31  	"github.com/bcskill/bcschain/v3/ethdb"
    32  	"github.com/bcskill/bcschain/v3/rlp"
    33  )
    34  
    35  // Tests block header storage and retrieval operations.
    36  func TestHeaderStorage(t *testing.T) {
    37  	db := ethdb.NewMemDatabase()
    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.HeaderTable(), 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.GlobalTable(), db.HeaderTable(), header)
    46  	if entry := ReadHeader(db.HeaderTable(), 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.HeaderTable(), 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.GlobalTable(), db.HeaderTable(), header.Hash(), header.Number.Uint64())
    63  	if entry := ReadHeader(db.HeaderTable(), 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 := ethdb.NewMemDatabase()
    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.BodyTable(), 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.BodyTable(), hash, 0, body)
    84  	if entry := ReadBody(db.BodyTable(), hash, 0); entry == nil {
    85  		t.Fatalf("Stored body not found")
    86  	} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || 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.BodyTable(), 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.BodyTable(), hash, 0)
   101  	if entry := ReadBody(db.BodyTable(), 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 := ethdb.NewMemDatabase()
   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.HeaderTable(), block.Hash(), block.NumberU64()); entry != nil {
   121  		t.Fatalf("Non existent header returned: %v", entry)
   122  	}
   123  	if entry := ReadBody(db.BodyTable(), 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.HeaderTable(), 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.BodyTable(), block.Hash(), block.NumberU64()); entry == nil {
   139  		t.Fatalf("Stored body not found")
   140  	} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || 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.HeaderTable(), block.Hash(), block.NumberU64()); entry != nil {
   149  		t.Fatalf("Deleted header returned: %v", entry)
   150  	}
   151  	if entry := ReadBody(db.BodyTable(), 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 := ethdb.NewMemDatabase()
   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.GlobalTable(), db.HeaderTable(), 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.GlobalTable(), db.HeaderTable(), block.Hash(), block.NumberU64())
   171  
   172  	// Store a body and check that it's not recognized as a block
   173  	WriteBody(db.BodyTable(), 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.BodyTable(), block.Hash(), block.NumberU64())
   178  
   179  	// Store a header and a body separately and check reassembly
   180  	WriteHeader(db.GlobalTable(), db.HeaderTable(), block.Header())
   181  	WriteBody(db.GlobalTable(), block.Hash(), block.NumberU64(), block.Body())
   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 := ethdb.NewMemDatabase()
   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.GlobalTable(), 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.GlobalTable(), hash, 0, td)
   200  	if entry := ReadTd(db.GlobalTable(), 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.GlobalTable(), hash, 0)
   207  	if entry := ReadTd(db.GlobalTable(), 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 := ethdb.NewMemDatabase()
   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 := ethdb.NewMemDatabase()
   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.GlobalTable()); entry != (common.Hash{}) {
   245  		t.Fatalf("Non head header entry returned: %v", entry)
   246  	}
   247  	if entry := ReadHeadBlockHash(db.GlobalTable()); entry != (common.Hash{}) {
   248  		t.Fatalf("Non head block entry returned: %v", entry)
   249  	}
   250  	if entry := ReadHeadFastBlockHash(db.GlobalTable()); 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.GlobalTable(), blockHead.Hash())
   255  	WriteHeadBlockHash(db.GlobalTable(), blockFull.Hash())
   256  	WriteHeadFastBlockHash(db.GlobalTable(), blockFast.Hash())
   257  
   258  	// Check that both heads are present, and different (i.e. two heads maintained)
   259  	if entry := ReadHeadHeaderHash(db.GlobalTable()); entry != blockHead.Hash() {
   260  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   261  	}
   262  	if entry := ReadHeadBlockHash(db.GlobalTable()); entry != blockFull.Hash() {
   263  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   264  	}
   265  	if entry := ReadHeadFastBlockHash(db.GlobalTable()); 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 := ethdb.NewMemDatabase()
   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  	hash := common.BytesToHash([]byte{0x03, 0x14})
   310  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   311  		t.Fatalf("non existent receipts returned: %v", rs)
   312  	}
   313  	// Insert the body that corresponds to the receipts
   314  	WriteBody(db.BodyTable(), hash, 0, body)
   315  
   316  	// Insert the receipt slice into the database and check presence
   317  	WriteReceipts(db.ReceiptTable(), hash, 0, receipts)
   318  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   319  		t.Fatalf("no receipts returned")
   320  	} else {
   321  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   322  			t.Fatal(err.Error())
   323  		}
   324  	}
   325  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   326  	DeleteBody(db.BodyTable(), hash, 0)
   327  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   328  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   329  	}
   330  	// Ensure that receipts without metadata can be returned without the block body too
   331  	if err := checkReceiptsRLP(ReadRawReceipts(db.ReceiptTable(), hash, 0), receipts); err != nil {
   332  		t.Fatal(err.Error())
   333  	}
   334  	// Sanity check that body alone without the receipt is a full purge
   335  	WriteBody(db.BodyTable(), hash, 0, body)
   336  
   337  	DeleteReceipts(db.ReceiptTable(), hash, 0)
   338  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   339  		t.Fatalf("deleted receipts returned: %v", rs)
   340  	}
   341  }
   342  
   343  func checkReceiptsRLP(have, want types.Receipts) error {
   344  	if len(have) != len(want) {
   345  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   346  	}
   347  	for i := 0; i < len(want); i++ {
   348  		rlpHave, err := rlp.EncodeToBytes(have[i])
   349  		if err != nil {
   350  			return err
   351  		}
   352  		rlpWant, err := rlp.EncodeToBytes(want[i])
   353  		if err != nil {
   354  			return err
   355  		}
   356  		if !bytes.Equal(rlpHave, rlpWant) {
   357  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   358  		}
   359  	}
   360  	return nil
   361  }