github.com/gnc-project/gnc@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  	"testing"
    27  
    28  	"github.com/gnc-project/gnc/common"
    29  	"github.com/gnc-project/gnc/core/types"
    30  	"github.com/gnc-project/gnc/params"
    31  	"github.com/gnc-project/gnc/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)) != types.DeriveSha(types.Transactions(body.Transactions)){
    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  		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)) != types.DeriveSha(block.Transactions())) {
   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  		TxHash:      types.EmptyRootHash,
   161  		ReceiptHash: types.EmptyRootHash,
   162  	})
   163  	// Store a header and check that it's not recognized as a block
   164  	WriteHeader(db, block.Header())
   165  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   166  		t.Fatalf("Non existent block returned: %v", entry)
   167  	}
   168  	DeleteHeader(db, block.Hash(), block.NumberU64())
   169  
   170  	// Store a body and check that it's not recognized as a block
   171  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   172  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   173  		t.Fatalf("Non existent block returned: %v", entry)
   174  	}
   175  	DeleteBody(db, block.Hash(), block.NumberU64())
   176  
   177  	// Store a header and a body separately and check reassembly
   178  	WriteHeader(db, block.Header())
   179  	WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
   180  
   181  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   182  		t.Fatalf("Stored block not found")
   183  	} else if entry.Hash() != block.Hash() {
   184  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   185  	}
   186  }
   187  
   188  // Tests block total difficulty storage and retrieval operations.
   189  func TestTdStorage(t *testing.T) {
   190  	db := NewMemoryDatabase()
   191  
   192  	// Create a test TD to move around the database and make sure it's really new
   193  	hash, td := common.Hash{}, big.NewInt(314)
   194  	if entry := ReadTd(db, hash, 0); entry != nil {
   195  		t.Fatalf("Non existent TD returned: %v", entry)
   196  	}
   197  	// Write and verify the TD in the database
   198  	WriteTd(db, hash, 0, td)
   199  	if entry := ReadTd(db, hash, 0); entry == nil {
   200  		t.Fatalf("Stored TD not found")
   201  	} else if entry.Cmp(td) != 0 {
   202  		t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
   203  	}
   204  	// Delete the TD and verify the execution
   205  	DeleteTd(db, hash, 0)
   206  	if entry := ReadTd(db, hash, 0); entry != nil {
   207  		t.Fatalf("Deleted TD returned: %v", entry)
   208  	}
   209  }
   210  
   211  // Tests that canonical numbers can be mapped to hashes and retrieved.
   212  func TestCanonicalMappingStorage(t *testing.T) {
   213  	db := NewMemoryDatabase()
   214  
   215  	// Create a test canonical number and assinged hash to move around
   216  	hash, number := common.Hash{0: 0xff}, uint64(314)
   217  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   218  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   219  	}
   220  	// Write and verify the TD in the database
   221  	WriteCanonicalHash(db, hash, number)
   222  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   223  		t.Fatalf("Stored canonical mapping not found")
   224  	} else if entry != hash {
   225  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   226  	}
   227  	// Delete the TD and verify the execution
   228  	DeleteCanonicalHash(db, number)
   229  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   230  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   231  	}
   232  }
   233  
   234  // Tests that head headers and head blocks can be assigned, individually.
   235  func TestHeadStorage(t *testing.T) {
   236  	db := NewMemoryDatabase()
   237  
   238  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   239  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   240  	blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
   241  
   242  	// Check that no head entries are in a pristine database
   243  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   244  		t.Fatalf("Non head header entry returned: %v", entry)
   245  	}
   246  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   247  		t.Fatalf("Non head block entry returned: %v", entry)
   248  	}
   249  	if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
   250  		t.Fatalf("Non fast head block entry returned: %v", entry)
   251  	}
   252  	// Assign separate entries for the head header and block
   253  	WriteHeadHeaderHash(db, blockHead.Hash())
   254  	WriteHeadBlockHash(db, blockFull.Hash())
   255  	WriteHeadFastBlockHash(db, blockFast.Hash())
   256  
   257  	// Check that both heads are present, and different (i.e. two heads maintained)
   258  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   259  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   260  	}
   261  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   262  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   263  	}
   264  	if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
   265  		t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
   266  	}
   267  }
   268  
   269  // Tests that receipts associated with a single block can be stored and retrieved.
   270  func TestBlockReceiptStorage(t *testing.T) {
   271  	db := NewMemoryDatabase()
   272  
   273  	// Create a live block since we need metadata to reconstruct the receipt
   274  	tx1 := types.NewTransaction(types.Binary,1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
   275  	tx2 := types.NewTransaction(types.Binary,2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
   276  
   277  	body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
   278  
   279  	// Create the two receipts to manage afterwards
   280  	receipt1 := &types.Receipt{
   281  		Status:            types.ReceiptStatusFailed,
   282  		CumulativeGasUsed: 1,
   283  		Logs: []*types.Log{
   284  			{Address: common.BytesToAddress([]byte{0x11})},
   285  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   286  		},
   287  		TxHash:          tx1.Hash(),
   288  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   289  		GasUsed:         111111,
   290  	}
   291  	receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
   292  
   293  	receipt2 := &types.Receipt{
   294  		PostState:         common.Hash{2}.Bytes(),
   295  		CumulativeGasUsed: 2,
   296  		Logs: []*types.Log{
   297  			{Address: common.BytesToAddress([]byte{0x22})},
   298  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   299  		},
   300  		TxHash:          tx2.Hash(),
   301  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   302  		GasUsed:         222222,
   303  	}
   304  	receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
   305  	receipts := []*types.Receipt{receipt1, receipt2}
   306  
   307  	// Check that no receipt entries are in a pristine database
   308  	hash := common.BytesToHash([]byte{0x03, 0x14})
   309  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   310  		t.Fatalf("non existent receipts returned: %v", rs)
   311  	}
   312  	// Insert the body that corresponds to the receipts
   313  	WriteBody(db, hash, 0, body)
   314  
   315  	// Insert the receipt slice into the database and check presence
   316  	WriteReceipts(db, hash, 0, receipts)
   317  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
   318  		t.Fatalf("no receipts returned")
   319  	} else {
   320  		if err := checkReceiptsRLP(rs, receipts); err != nil {
   321  			t.Fatalf(err.Error())
   322  		}
   323  	}
   324  	// Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
   325  	DeleteBody(db, hash, 0)
   326  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
   327  		t.Fatalf("receipts returned when body was deleted: %v", rs)
   328  	}
   329  	// Ensure that receipts without metadata can be returned without the block body too
   330  	if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
   331  		t.Fatalf(err.Error())
   332  	}
   333  	// Sanity check that body alone without the receipt is a full purge
   334  	WriteBody(db, hash, 0, body)
   335  
   336  	DeleteReceipts(db, hash, 0)
   337  	if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
   338  		t.Fatalf("deleted receipts returned: %v", rs)
   339  	}
   340  }
   341  
   342  func checkReceiptsRLP(have, want types.Receipts) error {
   343  	if len(have) != len(want) {
   344  		return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
   345  	}
   346  	for i := 0; i < len(want); i++ {
   347  		rlpHave, err := rlp.EncodeToBytes(have[i])
   348  		if err != nil {
   349  			return err
   350  		}
   351  		rlpWant, err := rlp.EncodeToBytes(want[i])
   352  		if err != nil {
   353  			return err
   354  		}
   355  		if !bytes.Equal(rlpHave, rlpWant) {
   356  			return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
   357  		}
   358  	}
   359  	return nil
   360  }
   361  
   362  func TestAncientStorage(t *testing.T) {
   363  	// Freezer style fast import the chain.
   364  	frdir, err := ioutil.TempDir("", "")
   365  	if err != nil {
   366  		t.Fatalf("failed to create temp freezer dir: %v", err)
   367  	}
   368  	defer os.Remove(frdir)
   369  
   370  	db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "")
   371  	if err != nil {
   372  		t.Fatalf("failed to create database with ancient backend")
   373  	}
   374  	// Create a test block
   375  	block := types.NewBlockWithHeader(&types.Header{
   376  		Number:      big.NewInt(0),
   377  		Extra:       []byte("test block"),
   378  		TxHash:      types.EmptyRootHash,
   379  		ReceiptHash: types.EmptyRootHash,
   380  	})
   381  	// Ensure nothing non-existent will be read
   382  	hash, number := block.Hash(), block.NumberU64()
   383  	if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
   384  		t.Fatalf("non existent header returned")
   385  	}
   386  	if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
   387  		t.Fatalf("non existent body returned")
   388  	}
   389  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
   390  		t.Fatalf("non existent receipts returned")
   391  	}
   392  	if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
   393  		t.Fatalf("non existent td returned")
   394  	}
   395  	// Write and verify the header in the database
   396  	WriteAncientBlock(db, block, nil, big.NewInt(100))
   397  	if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
   398  		t.Fatalf("no header returned")
   399  	}
   400  	if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
   401  		t.Fatalf("no body returned")
   402  	}
   403  	if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
   404  		t.Fatalf("no receipts returned")
   405  	}
   406  	if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
   407  		t.Fatalf("no td returned")
   408  	}
   409  	// Use a fake hash for data retrieval, nothing should be returned.
   410  	fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
   411  	if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
   412  		t.Fatalf("invalid header returned")
   413  	}
   414  	if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
   415  		t.Fatalf("invalid body returned")
   416  	}
   417  	if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
   418  		t.Fatalf("invalid receipts returned")
   419  	}
   420  	if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
   421  		t.Fatalf("invalid td returned")
   422  	}
   423  }