github.com/klaytn/klaytn@v1.12.1/blockchain/state/state_test.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2014 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from core/state/state_test.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package state
    22  
    23  import (
    24  	"bytes"
    25  	"math/big"
    26  	"testing"
    27  
    28  	"github.com/klaytn/klaytn/blockchain/types/account"
    29  	"github.com/klaytn/klaytn/common"
    30  	"github.com/klaytn/klaytn/crypto"
    31  	"github.com/klaytn/klaytn/params"
    32  	"github.com/klaytn/klaytn/storage/database"
    33  	checker "gopkg.in/check.v1"
    34  )
    35  
    36  type StateSuite struct {
    37  	db    database.DBManager
    38  	state *StateDB
    39  }
    40  
    41  var _ = checker.Suite(&StateSuite{})
    42  
    43  var toAddr = common.BytesToAddress
    44  
    45  func (s *StateSuite) TestDump(c *checker.C) {
    46  	// generate a few entries
    47  	obj1 := s.state.GetOrNewStateObject(toAddr([]byte{0x01}))
    48  	obj1.AddBalance(big.NewInt(22))
    49  	obj2 := s.state.GetOrNewSmartContract(toAddr([]byte{0x01, 0x02}))
    50  	obj2.SetCode(crypto.Keccak256Hash([]byte{3, 3, 3, 3, 3, 3, 3}), []byte{3, 3, 3, 3, 3, 3, 3})
    51  	obj3 := s.state.GetOrNewStateObject(toAddr([]byte{0x02}))
    52  	obj3.SetBalance(big.NewInt(44))
    53  
    54  	// write some of them to the trie
    55  	s.state.updateStateObject(obj1)
    56  	s.state.updateStateObject(obj2)
    57  	s.state.Commit(false)
    58  
    59  	// check that dump contains the state objects that are in trie
    60  	got := string(s.state.Dump())
    61  	want := `{
    62      "root": "e573e669d757892d7268beaaa75643d2a704ed207ef5f3007cf8bf72eb3624a4",
    63      "accounts": {
    64          "0000000000000000000000000000000000000001": {
    65              "balance": "22",
    66              "nonce": 0,
    67              "root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
    68              "codeHash": "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
    69              "code": "",
    70              "storage": {}
    71          },
    72          "0000000000000000000000000000000000000002": {
    73              "balance": "44",
    74              "nonce": 0,
    75              "root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
    76              "codeHash": "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
    77              "code": "",
    78              "storage": {}
    79          },
    80          "0000000000000000000000000000000000000102": {
    81              "balance": "0",
    82              "nonce": 0,
    83              "root": "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
    84              "codeHash": "87874902497a5bb968da31a2998d8f22e949d1ef6214bcdedd8bae24cca4b9e3",
    85              "code": "03030303030303",
    86              "storage": {}
    87          }
    88      }
    89  }`
    90  	if got != want {
    91  		c.Errorf("dump mismatch:\ngot: %s\nwant: %s\n", got, want)
    92  	}
    93  }
    94  
    95  func (s *StateSuite) SetUpTest(c *checker.C) {
    96  	s.db = database.NewMemoryDBManager()
    97  	s.state, _ = New(common.Hash{}, NewDatabase(s.db), nil, nil)
    98  }
    99  
   100  func (s *StateSuite) TestNull(c *checker.C) {
   101  	address := common.HexToAddress("0x823140710bf13990e4500136726d8b55")
   102  	s.state.CreateSmartContractAccount(address, params.CodeFormatEVM, params.Rules{IsIstanbul: true})
   103  	// value := common.FromHex("0x823140710bf13990e4500136726d8b55")
   104  	var value common.Hash
   105  
   106  	s.state.SetState(address, common.Hash{}, value)
   107  	s.state.Commit(false)
   108  	if value := s.state.GetState(address, common.Hash{}); value != (common.Hash{}) {
   109  		c.Errorf("expected empty current value, got %x", value)
   110  	}
   111  	if value := s.state.GetCommittedState(address, common.Hash{}); value != (common.Hash{}) {
   112  		c.Errorf("expected empty committed value, got %x", value)
   113  	}
   114  }
   115  
   116  // This test is to check if stateObject is restored back to the original
   117  // one after reverting to the state snapshot.
   118  func (s *StateSuite) TestSnapshot(c *checker.C) {
   119  	stateobjaddr := toAddr([]byte("aa"))
   120  	var storageaddr common.Hash
   121  	data1 := common.BytesToHash([]byte{42})
   122  	data2 := common.BytesToHash([]byte{43})
   123  
   124  	// snapshot the genesis state
   125  	genesis := s.state.Snapshot()
   126  
   127  	// set initial state object value
   128  	s.state.SetState(stateobjaddr, storageaddr, data1)
   129  	snapshot := s.state.Snapshot()
   130  
   131  	// set a new state object value, revert it and ensure correct content
   132  	s.state.SetState(stateobjaddr, storageaddr, data2)
   133  	s.state.RevertToSnapshot(snapshot)
   134  
   135  	c.Assert(s.state.GetState(stateobjaddr, storageaddr), checker.DeepEquals, data1)
   136  	c.Assert(s.state.GetCommittedState(stateobjaddr, storageaddr), checker.DeepEquals, common.Hash{})
   137  
   138  	// revert up to the genesis state and ensure correct content
   139  	s.state.RevertToSnapshot(genesis)
   140  	c.Assert(s.state.GetState(stateobjaddr, storageaddr), checker.DeepEquals, common.Hash{})
   141  	c.Assert(s.state.GetCommittedState(stateobjaddr, storageaddr), checker.DeepEquals, common.Hash{})
   142  }
   143  
   144  // This test is to check reverting to the empty snapshot.
   145  func (s *StateSuite) TestSnapshotEmpty(c *checker.C) {
   146  	s.state.RevertToSnapshot(s.state.Snapshot())
   147  }
   148  
   149  // use testing instead of checker because checker does not support
   150  // printing/logging in tests (-check.vv does not work)
   151  // This test is to compare deleted/non-deleted stateObject after restoring.
   152  func TestSnapshotForDeletedObject(t *testing.T) {
   153  	memDB := database.NewMemoryDBManager()
   154  	state, _ := New(common.Hash{}, NewDatabase(memDB), nil, nil)
   155  
   156  	stateObjAddr0 := toAddr([]byte("so0"))
   157  	stateObjAddr1 := toAddr([]byte("so1"))
   158  	var storageAddr common.Hash
   159  
   160  	data0 := common.BytesToHash([]byte{17})
   161  	data1 := common.BytesToHash([]byte{18})
   162  
   163  	state.SetState(stateObjAddr0, storageAddr, data0)
   164  	state.SetState(stateObjAddr1, storageAddr, data1)
   165  
   166  	// db, trie are already non-empty values
   167  	so0 := state.getStateObject(stateObjAddr0)
   168  	so0.SetBalance(big.NewInt(42))
   169  	so0.SetNonce(43)
   170  	so0.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e'}), []byte{'c', 'a', 'f', 'e'})
   171  	so0.selfDestructed = false
   172  	so0.deleted = false
   173  	state.setStateObject(so0)
   174  
   175  	root, _ := state.Commit(false)
   176  	state.Reset(root)
   177  
   178  	// and one with deleted == true
   179  	so1 := state.getStateObject(stateObjAddr1)
   180  	so1.SetBalance(big.NewInt(52))
   181  	so1.SetNonce(53)
   182  	so1.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e', '2'}), []byte{'c', 'a', 'f', 'e', '2'})
   183  	so1.selfDestructed = true
   184  	so1.deleted = true
   185  	state.setStateObject(so1)
   186  
   187  	// try to get deleted object before reverting to state snapshot = should be nil
   188  	so1 = state.getStateObject(stateObjAddr1)
   189  	if so1 != nil {
   190  		t.Fatalf("deleted object not nil when getting")
   191  	}
   192  
   193  	snapshot := state.Snapshot()
   194  	state.RevertToSnapshot(snapshot)
   195  
   196  	so0Restored := state.getStateObject(stateObjAddr0)
   197  	so0Restored.GetState(state.db, storageAddr) // Update lazily-loaded values before comparing.
   198  	so0Restored.Code(state.db)                  // Update lazily-loaded values before comparing.
   199  
   200  	// non-deleted stateObject should be equal before/after restoring.
   201  	compareStateObjects(so0Restored, so0, t)
   202  
   203  	// deleted should be nil, both before and after restore of state copy
   204  	// try to get deleted object after reverting to state snapshot = should be nil
   205  	so1Restored := state.getStateObject(stateObjAddr1)
   206  	if so1Restored != nil {
   207  		t.Fatalf("deleted object not nil after restoring snapshot: %+v", so1Restored)
   208  	}
   209  }
   210  
   211  func compareStateObjects(so0, so1 *stateObject, t *testing.T) {
   212  	if so0.Address() != so1.Address() {
   213  		t.Fatalf("Address mismatch: have %v, want %v", so0.address, so1.address)
   214  	}
   215  	if so0.Balance().Cmp(so1.Balance()) != 0 {
   216  		t.Fatalf("Balance mismatch: have %v, want %v", so0.Balance(), so1.Balance())
   217  	}
   218  	if so0.Nonce() != so1.Nonce() {
   219  		t.Fatalf("Nonce mismatch: have %v, want %v", so0.Nonce(), so1.Nonce())
   220  	}
   221  	so0ac := account.GetProgramAccount(so0.account)
   222  	so1ac := account.GetProgramAccount(so1.account)
   223  	if (so0ac == nil && so1ac != nil) ||
   224  		(so0ac != nil && so1ac == nil) {
   225  		t.Errorf("so0ok(%v) != so1ok(%v). Both should be smart contracts or not!", so0ac, so1ac)
   226  	}
   227  	if so0ac != nil && so0ac.GetStorageRoot() != so1ac.GetStorageRoot() {
   228  		// check the equivalence of storage root only if both are smart contract accounts.
   229  		t.Errorf("Root mismatch: have %x, want %x", so0ac.GetStorageRoot().Bytes(), so1ac.GetStorageRoot().Bytes())
   230  	}
   231  	if !bytes.Equal(so0.CodeHash(), so1.CodeHash()) {
   232  		t.Fatalf("CodeHash mismatch: have %v, want %v", so0.CodeHash(), so1.CodeHash())
   233  	}
   234  	if !bytes.Equal(so0.code, so1.code) {
   235  		t.Fatalf("Code mismatch: have %v, want %v", so0.code, so1.code)
   236  	}
   237  
   238  	if len(so1.dirtyStorage) != len(so0.dirtyStorage) {
   239  		t.Errorf("Dirty storage size mismatch: have %d, want %d", len(so1.dirtyStorage), len(so0.dirtyStorage))
   240  	}
   241  	for k, v := range so1.dirtyStorage {
   242  		if so0.dirtyStorage[k] != v {
   243  			t.Errorf("Dirty storage key %x mismatch: have %v, want %v", k, so0.dirtyStorage[k], v)
   244  		}
   245  	}
   246  	for k, v := range so0.dirtyStorage {
   247  		if so1.dirtyStorage[k] != v {
   248  			t.Errorf("Dirty storage key %x mismatch: have %v, want none.", k, v)
   249  		}
   250  	}
   251  
   252  	if len(so1.originStorage) != len(so0.originStorage) {
   253  		t.Errorf("Origin storage size mismatch: have %d, want %d", len(so1.originStorage), len(so0.originStorage))
   254  	}
   255  	for k, v := range so1.originStorage {
   256  		if so0.originStorage[k] != v {
   257  			t.Errorf("Origin storage key %x mismatch: have %v, want %v", k, so0.originStorage[k], v)
   258  		}
   259  	}
   260  	for k, v := range so0.originStorage {
   261  		if so1.originStorage[k] != v {
   262  			t.Errorf("Origin storage key %x mismatch: have %v, want none.", k, v)
   263  		}
   264  	}
   265  }