github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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  	"math/big"
    22  	"reflect"
    23  	"testing"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/consensus/istanbul"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/ethdb"
    29  	"github.com/ethereum/go-ethereum/rlp"
    30  	"golang.org/x/crypto/sha3"
    31  )
    32  
    33  // Tests block header storage and retrieval operations.
    34  func TestHeaderStorage(t *testing.T) {
    35  	db := ethdb.NewMemDatabase()
    36  
    37  	// Create a test header to move around the database and make sure it's really new
    38  	header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
    39  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    40  		t.Fatalf("Non existent header returned: %v", entry)
    41  	}
    42  	// Write and verify the header in the database
    43  	WriteHeader(db, header)
    44  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
    45  		t.Fatalf("Stored header not found")
    46  	} else if entry.Hash() != header.Hash() {
    47  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
    48  	}
    49  	if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
    50  		t.Fatalf("Stored header RLP not found")
    51  	} else {
    52  		hasher := sha3.NewLegacyKeccak256()
    53  		hasher.Write(entry)
    54  
    55  		if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
    56  			t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
    57  		}
    58  	}
    59  	// Delete the header and verify the execution
    60  	DeleteHeader(db, header.Hash(), header.Number.Uint64())
    61  	if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
    62  		t.Fatalf("Deleted header returned: %v", entry)
    63  	}
    64  }
    65  
    66  // Tests block body storage and retrieval operations.
    67  func TestBodyStorage(t *testing.T) {
    68  	db := ethdb.NewMemDatabase()
    69  
    70  	// Create a test body to move around the database and make sure it's really new
    71  	body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}, Randomness: &types.Randomness{}, EpochSnarkData: &types.EpochSnarkData{}}
    72  
    73  	hasher := sha3.NewLegacyKeccak256()
    74  	rlp.Encode(hasher, body)
    75  	hash := common.BytesToHash(hasher.Sum(nil))
    76  
    77  	if entry := ReadBody(db, hash, 0); entry != nil {
    78  		t.Fatalf("Non existent body returned: %v", entry)
    79  	}
    80  	// Write and verify the body in the database
    81  	WriteBody(db, hash, 0, body)
    82  	if entry := ReadBody(db, hash, 0); entry == nil {
    83  		t.Fatalf("Stored body not found")
    84  	} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
    85  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
    86  	}
    87  	if entry := ReadBodyRLP(db, hash, 0); entry == nil {
    88  		t.Fatalf("Stored body RLP not found")
    89  	} else {
    90  		hasher := sha3.NewLegacyKeccak256()
    91  		hasher.Write(entry)
    92  
    93  		if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
    94  			t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
    95  		}
    96  	}
    97  	// Delete the body and verify the execution
    98  	DeleteBody(db, hash, 0)
    99  	if entry := ReadBody(db, hash, 0); entry != nil {
   100  		t.Fatalf("Deleted body returned: %v", entry)
   101  	}
   102  }
   103  
   104  // Tests block storage and retrieval operations.
   105  func TestBlockStorage(t *testing.T) {
   106  	db := ethdb.NewMemDatabase()
   107  
   108  	// Create a test block to move around the database and make sure it's really new
   109  	block := types.NewBlockWithHeader(&types.Header{
   110  		Extra:       []byte("test block"),
   111  		UncleHash:   types.EmptyUncleHash,
   112  		TxHash:      types.EmptyRootHash,
   113  		ReceiptHash: types.EmptyRootHash,
   114  	})
   115  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   116  		t.Fatalf("Non existent block returned: %v", entry)
   117  	}
   118  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   119  		t.Fatalf("Non existent header returned: %v", entry)
   120  	}
   121  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   122  		t.Fatalf("Non existent body returned: %v", entry)
   123  	}
   124  	// Write and verify the block in the database
   125  	WriteBlock(db, block)
   126  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
   127  		t.Fatalf("Stored block not found")
   128  	} else if entry.Hash() != block.Hash() {
   129  		t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
   130  	}
   131  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
   132  		t.Fatalf("Stored header not found")
   133  	} else if entry.Hash() != block.Header().Hash() {
   134  		t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
   135  	}
   136  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
   137  		t.Fatalf("Stored body not found")
   138  	} else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
   139  		t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
   140  	}
   141  	// Delete the block and verify the execution
   142  	DeleteBlock(db, block.Hash(), block.NumberU64())
   143  	if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
   144  		t.Fatalf("Deleted block returned: %v", entry)
   145  	}
   146  	if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
   147  		t.Fatalf("Deleted header returned: %v", entry)
   148  	}
   149  	if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
   150  		t.Fatalf("Deleted body returned: %v", entry)
   151  	}
   152  }
   153  
   154  // Tests that partial block contents don't get reassembled into full blocks.
   155  func TestPartialBlockStorage(t *testing.T) {
   156  	db := ethdb.NewMemDatabase()
   157  	block := types.NewBlockWithHeader(&types.Header{
   158  		Extra:       []byte("test block"),
   159  		UncleHash:   types.EmptyUncleHash,
   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 uptime accumulator storage and retrieval operations.
   189  func TestUptimeStorage(t *testing.T) {
   190  	db := ethdb.NewMemDatabase()
   191  	epoch := uint64(0)
   192  
   193  	// Create a test uptime to move around the database and make sure it's really new
   194  	if entry := ReadAccumulatedEpochUptime(db, epoch); entry != nil {
   195  		t.Fatalf("Non existent uptime returned: %v", entry)
   196  	}
   197  	// Write and verify the uptime in the database
   198  	uptimeEntries := make([]istanbul.UptimeEntry, 3)
   199  	uptimeEntries[0] = istanbul.UptimeEntry{
   200  		ScoreTally:      0,
   201  		LastSignedBlock: 1,
   202  	}
   203  	uptimeEntries[1] = istanbul.UptimeEntry{
   204  		ScoreTally:      2,
   205  		LastSignedBlock: 2,
   206  	}
   207  	uptimeEntries[2] = istanbul.UptimeEntry{
   208  		ScoreTally:      8,
   209  		LastSignedBlock: 8,
   210  	}
   211  	uptime := &istanbul.Uptime{
   212  		Entries:     uptimeEntries,
   213  		LatestBlock: 5,
   214  	}
   215  	WriteAccumulatedEpochUptime(db, epoch, uptime)
   216  	if entry := ReadAccumulatedEpochUptime(db, epoch); entry == nil {
   217  		t.Fatalf("Stored uptime not found")
   218  	} else if !reflect.DeepEqual(entry, uptime) {
   219  		t.Fatalf("Retrieved uptime mismatch: have %v, want %v", entry, uptime)
   220  	}
   221  	// Delete the uptime and verify the execution
   222  	DeleteAccumulatedEpochUptime(db, epoch)
   223  	if entry := ReadAccumulatedEpochUptime(db, epoch); entry != nil {
   224  		t.Fatalf("Deleted uptime returned: %v", entry)
   225  	}
   226  }
   227  
   228  // Tests block total difficulty storage and retrieval operations.
   229  func TestTdStorage(t *testing.T) {
   230  	db := ethdb.NewMemDatabase()
   231  
   232  	// Create a test TD to move around the database and make sure it's really new
   233  	hash, td := common.Hash{}, big.NewInt(314)
   234  	if entry := ReadTd(db, hash, 0); entry != nil {
   235  		t.Fatalf("Non existent TD returned: %v", entry)
   236  	}
   237  	// Write and verify the TD in the database
   238  	WriteTd(db, hash, 0, td)
   239  	if entry := ReadTd(db, hash, 0); entry == nil {
   240  		t.Fatalf("Stored TD not found")
   241  	} else if entry.Cmp(td) != 0 {
   242  		t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
   243  	}
   244  	// Delete the TD and verify the execution
   245  	DeleteTd(db, hash, 0)
   246  	if entry := ReadTd(db, hash, 0); entry != nil {
   247  		t.Fatalf("Deleted TD returned: %v", entry)
   248  	}
   249  }
   250  
   251  // Tests that canonical numbers can be mapped to hashes and retrieved.
   252  func TestCanonicalMappingStorage(t *testing.T) {
   253  	db := ethdb.NewMemDatabase()
   254  
   255  	// Create a test canonical number and assinged hash to move around
   256  	hash, number := common.Hash{0: 0xff}, uint64(314)
   257  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   258  		t.Fatalf("Non existent canonical mapping returned: %v", entry)
   259  	}
   260  	// Write and verify the TD in the database
   261  	WriteCanonicalHash(db, hash, number)
   262  	if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
   263  		t.Fatalf("Stored canonical mapping not found")
   264  	} else if entry != hash {
   265  		t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
   266  	}
   267  	// Delete the TD and verify the execution
   268  	DeleteCanonicalHash(db, number)
   269  	if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
   270  		t.Fatalf("Deleted canonical mapping returned: %v", entry)
   271  	}
   272  }
   273  
   274  // Tests that head headers and head blocks can be assigned, individually.
   275  func TestHeadStorage(t *testing.T) {
   276  	db := ethdb.NewMemDatabase()
   277  
   278  	blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
   279  	blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
   280  	blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
   281  
   282  	// Check that no head entries are in a pristine database
   283  	if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
   284  		t.Fatalf("Non head header entry returned: %v", entry)
   285  	}
   286  	if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
   287  		t.Fatalf("Non head block entry returned: %v", entry)
   288  	}
   289  	if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
   290  		t.Fatalf("Non fast head block entry returned: %v", entry)
   291  	}
   292  	// Assign separate entries for the head header and block
   293  	WriteHeadHeaderHash(db, blockHead.Hash())
   294  	WriteHeadBlockHash(db, blockFull.Hash())
   295  	WriteHeadFastBlockHash(db, blockFast.Hash())
   296  
   297  	// Check that both heads are present, and different (i.e. two heads maintained)
   298  	if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
   299  		t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
   300  	}
   301  	if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
   302  		t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
   303  	}
   304  	if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
   305  		t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
   306  	}
   307  }
   308  
   309  // Tests that receipts associated with a single block can be stored and retrieved.
   310  func TestBlockReceiptStorage(t *testing.T) {
   311  	db := ethdb.NewMemDatabase()
   312  
   313  	receipt1 := &types.Receipt{
   314  		Status:            types.ReceiptStatusFailed,
   315  		CumulativeGasUsed: 1,
   316  		Logs: []*types.Log{
   317  			{Address: common.BytesToAddress([]byte{0x11})},
   318  			{Address: common.BytesToAddress([]byte{0x01, 0x11})},
   319  		},
   320  		TxHash:          common.BytesToHash([]byte{0x11, 0x11}),
   321  		ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
   322  		GasUsed:         111111,
   323  	}
   324  	receipt2 := &types.Receipt{
   325  		PostState:         common.Hash{2}.Bytes(),
   326  		CumulativeGasUsed: 2,
   327  		Logs: []*types.Log{
   328  			{Address: common.BytesToAddress([]byte{0x22})},
   329  			{Address: common.BytesToAddress([]byte{0x02, 0x22})},
   330  		},
   331  		TxHash:          common.BytesToHash([]byte{0x22, 0x22}),
   332  		ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
   333  		GasUsed:         222222,
   334  	}
   335  	receipts := []*types.Receipt{receipt1, receipt2}
   336  
   337  	// Check that no receipt entries are in a pristine database
   338  	hash := common.BytesToHash([]byte{0x03, 0x14})
   339  	if rs := ReadReceipts(db, hash, 0); len(rs) != 0 {
   340  		t.Fatalf("non existent receipts returned: %v", rs)
   341  	}
   342  	// Insert the receipt slice into the database and check presence
   343  	WriteReceipts(db, hash, 0, receipts)
   344  	if rs := ReadReceipts(db, hash, 0); len(rs) == 0 {
   345  		t.Fatalf("no receipts returned")
   346  	} else {
   347  		for i := 0; i < len(receipts); i++ {
   348  			rlpHave, _ := rlp.EncodeToBytes(rs[i])
   349  			rlpWant, _ := rlp.EncodeToBytes(receipts[i])
   350  
   351  			if !bytes.Equal(rlpHave, rlpWant) {
   352  				t.Fatalf("receipt #%d: receipt mismatch: have %v, want %v", i, rs[i], receipts[i])
   353  			}
   354  		}
   355  	}
   356  	// Delete the receipt slice and check purge
   357  	DeleteReceipts(db, hash, 0)
   358  	if rs := ReadReceipts(db, hash, 0); len(rs) != 0 {
   359  		t.Fatalf("deleted receipts returned: %v", rs)
   360  	}
   361  }