github.com/ccm-chain/ccmchain@v1.0.0/core/rawdb/accessors_chain_test.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rawdb
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"math/big"
    25  	"os"
    26  	"reflect"
    27  	"testing"
    28  
    29  	"github.com/ccm-chain/ccmchain/common"
    30  	"github.com/ccm-chain/ccmchain/core/types"
    31  	"github.com/ccm-chain/ccmchain/params"
    32  	"github.com/ccm-chain/ccmchain/rlp"
    33  	"golang.org/x/crypto/sha3"
    34  )
    35  
    36  // Tests block header storage and retrieval operations.
    37  func TestHeaderStorage(t *testing.T) {
    38  	db := NewMemoryDatabase()
    39  
    40  	// Create a test header to move around the database and make sure it's really new
    41  	header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
    42  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    43  		t.Fatalf("Non existent header returned: %v", entry)
    44  	}
    45  	// Write and verify the header in the database
    46  	WriteHeader(db, header)
    47  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
    48  		t.Fatalf("Stored header not found")
    49  	} else if entry.Hash() != header.Hash() {
    50  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
    51  	}
    52  	if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
    53  		t.Fatalf("Stored header RLP not found")
    54  	} else {
    55  		hasher := sha3.NewLegacyKeccak256()
    56  		hasher.Write(entry)
    57  
    58  		if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
    59  			t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
    60  		}
    61  	}
    62  	// Delete the header and verify the execution
    63  	DeleteHeader(db, header.Hash(), header.Number.Uint64())
    64  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    65  		t.Fatalf("Deleted header returned: %v", entry)
    66  	}
    67  }
    68  
    69  // Tests block body storage and retrieval operations.
    70  func TestBodyStorage(t *testing.T) {
    71  	db := NewMemoryDatabase()
    72  
    73  	// Create a test body to move around the database and make sure it's really new
    74  	body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
    75  
    76  	hasher := sha3.NewLegacyKeccak256()
    77  	rlp.Encode(hasher, body)
    78  	hash := common.BytesToHash(hasher.Sum(nil))
    79  
    80  	if entry := ReadBody(db, hash, 0); entry != nil {
    81  		t.Fatalf("Non existent body returned: %v", entry)
    82  	}
    83  	// Write and verify the body in the database
    84  	WriteBody(db, hash, 0, body)
    85  	if entry := ReadBody(db, hash, 0); entry == nil {
    86  		t.Fatalf("Stored body not found")
    87  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
    88  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
    89  	}
    90  	if entry := ReadBodyRLP(db, hash, 0); entry == nil {
    91  		t.Fatalf("Stored body RLP not found")
    92  	} else {
    93  		hasher := sha3.NewLegacyKeccak256()
    94  		hasher.Write(entry)
    95  
    96  		if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
    97  			t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
    98  		}
    99  	}
   100  	// Delete the body and verify the execution
   101  	DeleteBody(db, hash, 0)
   102  	if entry := ReadBody(db, hash, 0); entry != nil {
   103  		t.Fatalf("Deleted body returned: %v", entry)
   104  	}
   105  }
   106  
   107  // Tests block storage and retrieval operations.
   108  func TestBlockStorage(t *testing.T) {
   109  	db := NewMemoryDatabase()
   110  
   111  	// Create a test block to move around the database and make sure it's really new
   112  	block := types.NewBlockWithHeader(&types.Header{
   113  		Extra:       []byte("test block"),
   114  		UncleHash:   types.EmptyUncleHash,
   115  		TxHash:      types.EmptyRootHash,
   116  		ReceiptHash: types.EmptyRootHash,
   117  	})
   118  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   119  		t.Fatalf("Non existent block returned: %v", entry)
   120  	}
   121  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   122  		t.Fatalf("Non existent header returned: %v", entry)
   123  	}
   124  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   125  		t.Fatalf("Non existent body returned: %v", entry)
   126  	}
   127  	// Write and verify the block in the database
   128  	WriteBlock(db, block)
   129  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   130  		t.Fatalf("Stored block not found")
   131  	} else if entry.Hash() != block.Hash() {
   132  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   133  	}
   134  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
   135  		t.Fatalf("Stored header not found")
   136  	} else if entry.Hash() != block.Header().Hash() {
   137  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
   138  	}
   139  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
   140  		t.Fatalf("Stored body not found")
   141  	} else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
   142  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
   143  	}
   144  	// Delete the block and verify the execution
   145  	DeleteBlock(db, block.Hash(), block.NumberU64())
   146  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   147  		t.Fatalf("Deleted block returned: %v", entry)
   148  	}
   149  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   150  		t.Fatalf("Deleted header returned: %v", entry)
   151  	}
   152  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   153  		t.Fatalf("Deleted body returned: %v", entry)
   154  	}
   155  }
   156  
   157  // Tests that partial block contents don't get reassembled into full blocks.
   158  func TestPartialBlockStorage(t *testing.T) {
   159  	db := NewMemoryDatabase()
   160  	block := types.NewBlockWithHeader(&types.Header{
   161  		Extra:       []byte("test block"),
   162  		UncleHash:   types.EmptyUncleHash,
   163  		TxHash:      types.EmptyRootHash,
   164  		ReceiptHash: types.EmptyRootHash,
   165  	})
   166  	// Store a header and check that it's not recognized as a block
   167  	WriteHeader(db, block.Header())
   168  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   169  		t.Fatalf("Non existent block returned: %v", entry)
   170  	}
   171  	DeleteHeader(db, block.Hash(), block.NumberU64())
   172  
   173  	// Store a body and check that it's not recognized as a block
   174  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   175  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   176  		t.Fatalf("Non existent block returned: %v", entry)
   177  	}
   178  	DeleteBody(db, block.Hash(), block.NumberU64())
   179  
   180  	// Store a header and a body separately and check reassembly
   181  	WriteHeader(db, block.Header())
   182  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   183  
   184  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   185  		t.Fatalf("Stored block not found")
   186  	} else if entry.Hash() != block.Hash() {
   187  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   188  	}
   189  }
   190  
   191  // Tests block total difficulty storage and retrieval operations.
   192  func TestTdStorage(t *testing.T) {
   193  	db := NewMemoryDatabase()
   194  
   195  	// Create a test TD to move around the database and make sure it's really new
   196  	hash, td := common.Hash{}, big.NewInt(314)
   197  	if entry := ReadTd(db, hash, 0); entry != nil {
   198  		t.Fatalf("Non existent TD returned: %v", entry)
   199  	}
   200  	// Write and verify the TD in the database
   201  	WriteTd(db, hash, 0, td)
   202  	if entry := ReadTd(db, hash, 0); entry == nil {
   203  		t.Fatalf("Stored TD not found")
   204  	} else if entry.Cmp(td) != 0 {
   205  		t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
   206  	}
   207  	// Delete the TD and verify the execution
   208  	DeleteTd(db, hash, 0)
   209  	if entry := ReadTd(db, hash, 0); entry != nil {
   210  		t.Fatalf("Deleted TD returned: %v", entry)
   211  	}
   212  }
   213  
   214  // Tests that canonical numbers can be mapped to hashes and retrieved.
   215  func TestCanonicalMappingStorage(t *testing.T) {
   216  	db := NewMemoryDatabase()
   217  
   218  	// Create a test canonical number and assinged hash to move around
   219  	hash, number := common.Hash{0: 0xff}, uint64(314)
   220  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   221  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   222  	}
   223  	// Write and verify the TD in the database
   224  	WriteCanonicalHash(db, hash, number)
   225  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   226  		t.Fatalf("Stored canonical mapping not found")
   227  	} else if entry != hash {
   228  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   229  	}
   230  	// Delete the TD and verify the execution
   231  	DeleteCanonicalHash(db, number)
   232  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   233  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   234  	}
   235  }
   236  
   237  // Tests that head headers and head blocks can be assigned, individually.
   238  func TestHeadStorage(t *testing.T) {
   239  	db := NewMemoryDatabase()
   240  
   241  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   242  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   243  	blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
   244  
   245  	// Check that no head entries are in a pristine database
   246  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   247  		t.Fatalf("Non head header entry returned: %v", entry)
   248  	}
   249  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   250  		t.Fatalf("Non head block entry returned: %v", entry)
   251  	}
   252  	if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
   253  		t.Fatalf("Non fast head block entry returned: %v", entry)
   254  	}
   255  	// Assign separate entries for the head header and block
   256  	WriteHeadHeaderHash(db, blockHead.Hash())
   257  	WriteHeadBlockHash(db, blockFull.Hash())
   258  	WriteHeadFastBlockHash(db, blockFast.Hash())
   259  
   260  	// Check that both heads are present, and different (i.e. two heads maintained)
   261  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   262  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   263  	}
   264  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   265  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   266  	}
   267  	if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
   268  		t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
   269  	}
   270  }
   271  
   272  // Tests that receipts associated with a single block can be stored and retrieved.
   273  func TestBlockReceiptStorage(t *testing.T) {
   274  	db := NewMemoryDatabase()
   275  
   276  	// Create a live block since we need metadata to reconstruct the receipt
   277  	tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   278  	tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   279  
   280  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   281  
   282  	// Create the two receipts to manage afterwards
   283  	receipt1 := &types.Receipt{
   284  		Status:            types.ReceiptStatusFailed,
   285  		CumulativeGasUsed: 1,
   286  		Logs: []*types.Log{
   287  			{Address: common.BytesToAddress([]byte{0x11})},
   288  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   289  		},
   290  		TxHash:          tx1.Hash(),
   291  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   292  		GasUsed:         111111,
   293  	}
   294  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   295  
   296  	receipt2 := &types.Receipt{
   297  		PostState:         common.Hash{2}.Bytes(),
   298  		CumulativeGasUsed: 2,
   299  		Logs: []*types.Log{
   300  			{Address: common.BytesToAddress([]byte{0x22})},
   301  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   302  		},
   303  		TxHash:          tx2.Hash(),
   304  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   305  		GasUsed:         222222,
   306  	}
   307  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   308  	receipts := []*types.Receipt{receipt1, receipt2}
   309  
   310  	// Check that no receipt entries are in a pristine database
   311  	hash := common.BytesToHash([]byte{0x03, 0x14})
   312  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   313  		t.Fatalf("non existent receipts returned: %v", rs)
   314  	}
   315  	// Insert the body that corresponds to the receipts
   316  	WriteBody(db, hash, 0, body)
   317  
   318  	// Insert the receipt slice into the database and check presence
   319  	WriteReceipts(db, hash, 0, receipts)
   320  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   321  		t.Fatalf("no receipts returned")
   322  	} else {
   323  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   324  			t.Fatalf(err.Error())
   325  		}
   326  	}
   327  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   328  	DeleteBody(db, hash, 0)
   329  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   330  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   331  	}
   332  	// Ensure that receipts without metadata can be returned without the block body too
   333  	if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
   334  		t.Fatalf(err.Error())
   335  	}
   336  	// Sanity check that body alone without the receipt is a full purge
   337  	WriteBody(db, hash, 0, body)
   338  
   339  	DeleteReceipts(db, hash, 0)
   340  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   341  		t.Fatalf("deleted receipts returned: %v", rs)
   342  	}
   343  }
   344  
   345  func checkReceiptsRLP(have, want types.Receipts) error {
   346  	if len(have) != len(want) {
   347  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   348  	}
   349  	for i := 0; i < len(want); i++ {
   350  		rlpHave, err := rlp.EncodeToBytes(have[i])
   351  		if err != nil {
   352  			return err
   353  		}
   354  		rlpWant, err := rlp.EncodeToBytes(want[i])
   355  		if err != nil {
   356  			return err
   357  		}
   358  		if !bytes.Equal(rlpHave, rlpWant) {
   359  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   360  		}
   361  	}
   362  	return nil
   363  }
   364  
   365  func TestAncientStorage(t *testing.T) {
   366  	// Freezer style fast import the chain.
   367  	frdir, err := ioutil.TempDir("", "")
   368  	if err != nil {
   369  		t.Fatalf("failed to create temp freezer dir: %v", err)
   370  	}
   371  	defer os.Remove(frdir)
   372  
   373  	db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "")
   374  	if err != nil {
   375  		t.Fatalf("failed to create database with ancient backend")
   376  	}
   377  	// Create a test block
   378  	block := types.NewBlockWithHeader(&types.Header{
   379  		Number:      big.NewInt(0),
   380  		Extra:       []byte("test block"),
   381  		UncleHash:   types.EmptyUncleHash,
   382  		TxHash:      types.EmptyRootHash,
   383  		ReceiptHash: types.EmptyRootHash,
   384  	})
   385  	// Ensure nothing non-existent will be read
   386  	hash, number := block.Hash(), block.NumberU64()
   387  	if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
   388  		t.Fatalf("non existent header returned")
   389  	}
   390  	if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
   391  		t.Fatalf("non existent body returned")
   392  	}
   393  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
   394  		t.Fatalf("non existent receipts returned")
   395  	}
   396  	if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
   397  		t.Fatalf("non existent td returned")
   398  	}
   399  	// Write and verify the header in the database
   400  	WriteAncientBlock(db, block, nil, big.NewInt(100))
   401  	if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
   402  		t.Fatalf("no header returned")
   403  	}
   404  	if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
   405  		t.Fatalf("no body returned")
   406  	}
   407  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
   408  		t.Fatalf("no receipts returned")
   409  	}
   410  	if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
   411  		t.Fatalf("no td returned")
   412  	}
   413  	// Use a fake hash for data retrieval, nothing should be returned.
   414  	fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
   415  	if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
   416  		t.Fatalf("invalid header returned")
   417  	}
   418  	if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
   419  		t.Fatalf("invalid body returned")
   420  	}
   421  	if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
   422  		t.Fatalf("invalid receipts returned")
   423  	}
   424  	if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
   425  		t.Fatalf("invalid td returned")
   426  	}
   427  }
   428  
   429  func TestCanonicalHashIteration(t *testing.T) {
   430  	var cases = []struct {
   431  		from, to uint64
   432  		limit    int
   433  		expect   []uint64
   434  	}{
   435  		{1, 8, 0, nil},
   436  		{1, 8, 1, []uint64{1}},
   437  		{1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
   438  		{1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
   439  		{2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
   440  		{9, 10, 10, nil},
   441  	}
   442  	// Test empty db iteration
   443  	db := NewMemoryDatabase()
   444  	numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
   445  	if len(numbers) != 0 {
   446  		t.Fatalf("No entry should be returned to iterate an empty db")
   447  	}
   448  	// Fill database with testing data.
   449  	for i := uint64(1); i <= 8; i++ {
   450  		WriteCanonicalHash(db, common.Hash{}, i)
   451  		WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
   452  	}
   453  	for i, c := range cases {
   454  		numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
   455  		if !reflect.DeepEqual(numbers, c.expect) {
   456  			t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
   457  		}
   458  	}
   459  }