github.com/benorgera/go-ethereum@v1.10.18-0.20220401011646-b3f57b1a73ba/accounts/abi/bind/backends/simulated_test.go (about)

     1  // Copyright 2019 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 backends
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"math/big"
    24  	"math/rand"
    25  	"reflect"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  
    30  	"github.com/ethereum/go-ethereum"
    31  	"github.com/ethereum/go-ethereum/accounts/abi"
    32  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/core"
    35  	"github.com/ethereum/go-ethereum/core/types"
    36  	"github.com/ethereum/go-ethereum/crypto"
    37  	"github.com/ethereum/go-ethereum/params"
    38  )
    39  
    40  func TestSimulatedBackend(t *testing.T) {
    41  	var gasLimit uint64 = 8000029
    42  	key, _ := crypto.GenerateKey() // nolint: gosec
    43  	auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
    44  	genAlloc := make(core.GenesisAlloc)
    45  	genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)}
    46  
    47  	sim := NewSimulatedBackend(genAlloc, gasLimit)
    48  	defer sim.Close()
    49  
    50  	// should return an error if the tx is not found
    51  	txHash := common.HexToHash("2")
    52  	_, isPending, err := sim.TransactionByHash(context.Background(), txHash)
    53  
    54  	if isPending {
    55  		t.Fatal("transaction should not be pending")
    56  	}
    57  	if err != ethereum.NotFound {
    58  		t.Fatalf("err should be `ethereum.NotFound` but received %v", err)
    59  	}
    60  
    61  	// generate a transaction and confirm you can retrieve it
    62  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
    63  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
    64  
    65  	code := `6060604052600a8060106000396000f360606040526008565b00`
    66  	var gas uint64 = 3000000
    67  	tx := types.NewContractCreation(0, big.NewInt(0), gas, gasPrice, common.FromHex(code))
    68  	tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key)
    69  
    70  	err = sim.SendTransaction(context.Background(), tx)
    71  	if err != nil {
    72  		t.Fatal("error sending transaction")
    73  	}
    74  
    75  	txHash = tx.Hash()
    76  	_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
    77  	if err != nil {
    78  		t.Fatalf("error getting transaction with hash: %v", txHash.String())
    79  	}
    80  	if !isPending {
    81  		t.Fatal("transaction should have pending status")
    82  	}
    83  
    84  	sim.Commit()
    85  	_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
    86  	if err != nil {
    87  		t.Fatalf("error getting transaction with hash: %v", txHash.String())
    88  	}
    89  	if isPending {
    90  		t.Fatal("transaction should not have pending status")
    91  	}
    92  }
    93  
    94  var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    95  
    96  //  the following is based on this contract:
    97  //  contract T {
    98  //  	event received(address sender, uint amount, bytes memo);
    99  //  	event receivedAddr(address sender);
   100  //
   101  //  	function receive(bytes calldata memo) external payable returns (string memory res) {
   102  //  		emit received(msg.sender, msg.value, memo);
   103  //  		emit receivedAddr(msg.sender);
   104  //		    return "hello world";
   105  //  	}
   106  //  }
   107  const abiJSON = `[ { "constant": false, "inputs": [ { "name": "memo", "type": "bytes" } ], "name": "receive", "outputs": [ { "name": "res", "type": "string" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "memo", "type": "bytes" } ], "name": "received", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "sender", "type": "address" } ], "name": "receivedAddr", "type": "event" } ]`
   108  const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
   109  const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
   110  
   111  // expected return value contains "hello world"
   112  var expectedReturn = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
   113  
   114  func simTestBackend(testAddr common.Address) *SimulatedBackend {
   115  	return NewSimulatedBackend(
   116  		core.GenesisAlloc{
   117  			testAddr: {Balance: big.NewInt(10000000000000000)},
   118  		}, 10000000,
   119  	)
   120  }
   121  
   122  func TestNewSimulatedBackend(t *testing.T) {
   123  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   124  	expectedBal := big.NewInt(10000000000000000)
   125  	sim := simTestBackend(testAddr)
   126  	defer sim.Close()
   127  
   128  	if sim.config != params.AllEthashProtocolChanges {
   129  		t.Errorf("expected sim config to equal params.AllEthashProtocolChanges, got %v", sim.config)
   130  	}
   131  
   132  	if sim.blockchain.Config() != params.AllEthashProtocolChanges {
   133  		t.Errorf("expected sim blockchain config to equal params.AllEthashProtocolChanges, got %v", sim.config)
   134  	}
   135  
   136  	stateDB, _ := sim.blockchain.State()
   137  	bal := stateDB.GetBalance(testAddr)
   138  	if bal.Cmp(expectedBal) != 0 {
   139  		t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
   140  	}
   141  }
   142  
   143  func TestAdjustTime(t *testing.T) {
   144  	sim := NewSimulatedBackend(
   145  		core.GenesisAlloc{}, 10000000,
   146  	)
   147  	defer sim.Close()
   148  
   149  	prevTime := sim.pendingBlock.Time()
   150  	if err := sim.AdjustTime(time.Second); err != nil {
   151  		t.Error(err)
   152  	}
   153  	newTime := sim.pendingBlock.Time()
   154  
   155  	if newTime-prevTime != uint64(time.Second.Seconds()) {
   156  		t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime)
   157  	}
   158  }
   159  
   160  func TestNewAdjustTimeFail(t *testing.T) {
   161  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   162  	sim := simTestBackend(testAddr)
   163  
   164  	// Create tx and send
   165  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   166  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   167  
   168  	tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   169  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   170  	if err != nil {
   171  		t.Errorf("could not sign tx: %v", err)
   172  	}
   173  	sim.SendTransaction(context.Background(), signedTx)
   174  	// AdjustTime should fail on non-empty block
   175  	if err := sim.AdjustTime(time.Second); err == nil {
   176  		t.Error("Expected adjust time to error on non-empty block")
   177  	}
   178  	sim.Commit()
   179  
   180  	prevTime := sim.pendingBlock.Time()
   181  	if err := sim.AdjustTime(time.Minute); err != nil {
   182  		t.Error(err)
   183  	}
   184  	newTime := sim.pendingBlock.Time()
   185  	if newTime-prevTime != uint64(time.Minute.Seconds()) {
   186  		t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime)
   187  	}
   188  	// Put a transaction after adjusting time
   189  	tx2 := types.NewTransaction(1, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   190  	signedTx2, err := types.SignTx(tx2, types.HomesteadSigner{}, testKey)
   191  	if err != nil {
   192  		t.Errorf("could not sign tx: %v", err)
   193  	}
   194  	sim.SendTransaction(context.Background(), signedTx2)
   195  	sim.Commit()
   196  	newTime = sim.pendingBlock.Time()
   197  	if newTime-prevTime >= uint64(time.Minute.Seconds()) {
   198  		t.Errorf("time adjusted, but shouldn't be: prev: %v, new: %v", prevTime, newTime)
   199  	}
   200  }
   201  
   202  func TestBalanceAt(t *testing.T) {
   203  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   204  	expectedBal := big.NewInt(10000000000000000)
   205  	sim := simTestBackend(testAddr)
   206  	defer sim.Close()
   207  	bgCtx := context.Background()
   208  
   209  	bal, err := sim.BalanceAt(bgCtx, testAddr, nil)
   210  	if err != nil {
   211  		t.Error(err)
   212  	}
   213  
   214  	if bal.Cmp(expectedBal) != 0 {
   215  		t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
   216  	}
   217  }
   218  
   219  func TestBlockByHash(t *testing.T) {
   220  	sim := NewSimulatedBackend(
   221  		core.GenesisAlloc{}, 10000000,
   222  	)
   223  	defer sim.Close()
   224  	bgCtx := context.Background()
   225  
   226  	block, err := sim.BlockByNumber(bgCtx, nil)
   227  	if err != nil {
   228  		t.Errorf("could not get recent block: %v", err)
   229  	}
   230  	blockByHash, err := sim.BlockByHash(bgCtx, block.Hash())
   231  	if err != nil {
   232  		t.Errorf("could not get recent block: %v", err)
   233  	}
   234  
   235  	if block.Hash() != blockByHash.Hash() {
   236  		t.Errorf("did not get expected block")
   237  	}
   238  }
   239  
   240  func TestBlockByNumber(t *testing.T) {
   241  	sim := NewSimulatedBackend(
   242  		core.GenesisAlloc{}, 10000000,
   243  	)
   244  	defer sim.Close()
   245  	bgCtx := context.Background()
   246  
   247  	block, err := sim.BlockByNumber(bgCtx, nil)
   248  	if err != nil {
   249  		t.Errorf("could not get recent block: %v", err)
   250  	}
   251  	if block.NumberU64() != 0 {
   252  		t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
   253  	}
   254  
   255  	// create one block
   256  	sim.Commit()
   257  
   258  	block, err = sim.BlockByNumber(bgCtx, nil)
   259  	if err != nil {
   260  		t.Errorf("could not get recent block: %v", err)
   261  	}
   262  	if block.NumberU64() != 1 {
   263  		t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
   264  	}
   265  
   266  	blockByNumber, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   267  	if err != nil {
   268  		t.Errorf("could not get block by number: %v", err)
   269  	}
   270  	if blockByNumber.Hash() != block.Hash() {
   271  		t.Errorf("did not get the same block with height of 1 as before")
   272  	}
   273  }
   274  
   275  func TestNonceAt(t *testing.T) {
   276  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   277  
   278  	sim := simTestBackend(testAddr)
   279  	defer sim.Close()
   280  	bgCtx := context.Background()
   281  
   282  	nonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(0))
   283  	if err != nil {
   284  		t.Errorf("could not get nonce for test addr: %v", err)
   285  	}
   286  
   287  	if nonce != uint64(0) {
   288  		t.Errorf("received incorrect nonce. expected 0, got %v", nonce)
   289  	}
   290  
   291  	// create a signed transaction to send
   292  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   293  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   294  
   295  	tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   296  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   297  	if err != nil {
   298  		t.Errorf("could not sign tx: %v", err)
   299  	}
   300  
   301  	// send tx to simulated backend
   302  	err = sim.SendTransaction(bgCtx, signedTx)
   303  	if err != nil {
   304  		t.Errorf("could not add tx to pending block: %v", err)
   305  	}
   306  	sim.Commit()
   307  
   308  	newNonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
   309  	if err != nil {
   310  		t.Errorf("could not get nonce for test addr: %v", err)
   311  	}
   312  
   313  	if newNonce != nonce+uint64(1) {
   314  		t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
   315  	}
   316  	// create some more blocks
   317  	sim.Commit()
   318  	// Check that we can get data for an older block/state
   319  	newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
   320  	if err != nil {
   321  		t.Fatalf("could not get nonce for test addr: %v", err)
   322  	}
   323  	if newNonce != nonce+uint64(1) {
   324  		t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
   325  	}
   326  }
   327  
   328  func TestSendTransaction(t *testing.T) {
   329  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   330  
   331  	sim := simTestBackend(testAddr)
   332  	defer sim.Close()
   333  	bgCtx := context.Background()
   334  
   335  	// create a signed transaction to send
   336  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   337  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   338  
   339  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   340  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   341  	if err != nil {
   342  		t.Errorf("could not sign tx: %v", err)
   343  	}
   344  
   345  	// send tx to simulated backend
   346  	err = sim.SendTransaction(bgCtx, signedTx)
   347  	if err != nil {
   348  		t.Errorf("could not add tx to pending block: %v", err)
   349  	}
   350  	sim.Commit()
   351  
   352  	block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   353  	if err != nil {
   354  		t.Errorf("could not get block at height 1: %v", err)
   355  	}
   356  
   357  	if signedTx.Hash() != block.Transactions()[0].Hash() {
   358  		t.Errorf("did not commit sent transaction. expected hash %v got hash %v", block.Transactions()[0].Hash(), signedTx.Hash())
   359  	}
   360  }
   361  
   362  func TestTransactionByHash(t *testing.T) {
   363  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   364  
   365  	sim := NewSimulatedBackend(
   366  		core.GenesisAlloc{
   367  			testAddr: {Balance: big.NewInt(10000000000000000)},
   368  		}, 10000000,
   369  	)
   370  	defer sim.Close()
   371  	bgCtx := context.Background()
   372  
   373  	// create a signed transaction to send
   374  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   375  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   376  
   377  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   378  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   379  	if err != nil {
   380  		t.Errorf("could not sign tx: %v", err)
   381  	}
   382  
   383  	// send tx to simulated backend
   384  	err = sim.SendTransaction(bgCtx, signedTx)
   385  	if err != nil {
   386  		t.Errorf("could not add tx to pending block: %v", err)
   387  	}
   388  
   389  	// ensure tx is committed pending
   390  	receivedTx, pending, err := sim.TransactionByHash(bgCtx, signedTx.Hash())
   391  	if err != nil {
   392  		t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
   393  	}
   394  	if !pending {
   395  		t.Errorf("expected transaction to be in pending state")
   396  	}
   397  	if receivedTx.Hash() != signedTx.Hash() {
   398  		t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
   399  	}
   400  
   401  	sim.Commit()
   402  
   403  	// ensure tx is not and committed pending
   404  	receivedTx, pending, err = sim.TransactionByHash(bgCtx, signedTx.Hash())
   405  	if err != nil {
   406  		t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
   407  	}
   408  	if pending {
   409  		t.Errorf("expected transaction to not be in pending state")
   410  	}
   411  	if receivedTx.Hash() != signedTx.Hash() {
   412  		t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
   413  	}
   414  }
   415  
   416  func TestEstimateGas(t *testing.T) {
   417  	/*
   418  		pragma solidity ^0.6.4;
   419  		contract GasEstimation {
   420  		    function PureRevert() public { revert(); }
   421  		    function Revert() public { revert("revert reason");}
   422  		    function OOG() public { for (uint i = 0; ; i++) {}}
   423  		    function Assert() public { assert(false);}
   424  		    function Valid() public {}
   425  		}*/
   426  	const contractAbi = "[{\"inputs\":[],\"name\":\"Assert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OOG\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PureRevert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Revert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Valid\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
   427  	const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
   428  
   429  	key, _ := crypto.GenerateKey()
   430  	addr := crypto.PubkeyToAddress(key.PublicKey)
   431  	opts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
   432  
   433  	sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000)
   434  	defer sim.Close()
   435  
   436  	parsed, _ := abi.JSON(strings.NewReader(contractAbi))
   437  	contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim)
   438  	sim.Commit()
   439  
   440  	var cases = []struct {
   441  		name        string
   442  		message     ethereum.CallMsg
   443  		expect      uint64
   444  		expectError error
   445  		expectData  interface{}
   446  	}{
   447  		{"plain transfer(valid)", ethereum.CallMsg{
   448  			From:     addr,
   449  			To:       &addr,
   450  			Gas:      0,
   451  			GasPrice: big.NewInt(0),
   452  			Value:    big.NewInt(1),
   453  			Data:     nil,
   454  		}, params.TxGas, nil, nil},
   455  
   456  		{"plain transfer(invalid)", ethereum.CallMsg{
   457  			From:     addr,
   458  			To:       &contractAddr,
   459  			Gas:      0,
   460  			GasPrice: big.NewInt(0),
   461  			Value:    big.NewInt(1),
   462  			Data:     nil,
   463  		}, 0, errors.New("execution reverted"), nil},
   464  
   465  		{"Revert", ethereum.CallMsg{
   466  			From:     addr,
   467  			To:       &contractAddr,
   468  			Gas:      0,
   469  			GasPrice: big.NewInt(0),
   470  			Value:    nil,
   471  			Data:     common.Hex2Bytes("d8b98391"),
   472  		}, 0, errors.New("execution reverted: revert reason"), "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000"},
   473  
   474  		{"PureRevert", ethereum.CallMsg{
   475  			From:     addr,
   476  			To:       &contractAddr,
   477  			Gas:      0,
   478  			GasPrice: big.NewInt(0),
   479  			Value:    nil,
   480  			Data:     common.Hex2Bytes("aa8b1d30"),
   481  		}, 0, errors.New("execution reverted"), nil},
   482  
   483  		{"OOG", ethereum.CallMsg{
   484  			From:     addr,
   485  			To:       &contractAddr,
   486  			Gas:      100000,
   487  			GasPrice: big.NewInt(0),
   488  			Value:    nil,
   489  			Data:     common.Hex2Bytes("50f6fe34"),
   490  		}, 0, errors.New("gas required exceeds allowance (100000)"), nil},
   491  
   492  		{"Assert", ethereum.CallMsg{
   493  			From:     addr,
   494  			To:       &contractAddr,
   495  			Gas:      100000,
   496  			GasPrice: big.NewInt(0),
   497  			Value:    nil,
   498  			Data:     common.Hex2Bytes("b9b046f9"),
   499  		}, 0, errors.New("invalid opcode: INVALID"), nil},
   500  
   501  		{"Valid", ethereum.CallMsg{
   502  			From:     addr,
   503  			To:       &contractAddr,
   504  			Gas:      100000,
   505  			GasPrice: big.NewInt(0),
   506  			Value:    nil,
   507  			Data:     common.Hex2Bytes("e09fface"),
   508  		}, 21275, nil, nil},
   509  	}
   510  	for _, c := range cases {
   511  		got, err := sim.EstimateGas(context.Background(), c.message)
   512  		if c.expectError != nil {
   513  			if err == nil {
   514  				t.Fatalf("Expect error, got nil")
   515  			}
   516  			if c.expectError.Error() != err.Error() {
   517  				t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
   518  			}
   519  			if c.expectData != nil {
   520  				if err, ok := err.(*revertError); !ok {
   521  					t.Fatalf("Expect revert error, got %T", err)
   522  				} else if !reflect.DeepEqual(err.ErrorData(), c.expectData) {
   523  					t.Fatalf("Error data mismatch, want %v, got %v", c.expectData, err.ErrorData())
   524  				}
   525  			}
   526  			continue
   527  		}
   528  		if got != c.expect {
   529  			t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
   530  		}
   531  	}
   532  }
   533  
   534  func TestEstimateGasWithPrice(t *testing.T) {
   535  	key, _ := crypto.GenerateKey()
   536  	addr := crypto.PubkeyToAddress(key.PublicKey)
   537  
   538  	sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000)
   539  	defer sim.Close()
   540  
   541  	recipient := common.HexToAddress("deadbeef")
   542  	var cases = []struct {
   543  		name        string
   544  		message     ethereum.CallMsg
   545  		expect      uint64
   546  		expectError error
   547  	}{
   548  		{"EstimateWithoutPrice", ethereum.CallMsg{
   549  			From:     addr,
   550  			To:       &recipient,
   551  			Gas:      0,
   552  			GasPrice: big.NewInt(0),
   553  			Value:    big.NewInt(100000000000),
   554  			Data:     nil,
   555  		}, 21000, nil},
   556  
   557  		{"EstimateWithPrice", ethereum.CallMsg{
   558  			From:     addr,
   559  			To:       &recipient,
   560  			Gas:      0,
   561  			GasPrice: big.NewInt(100000000000),
   562  			Value:    big.NewInt(100000000000),
   563  			Data:     nil,
   564  		}, 21000, nil},
   565  
   566  		{"EstimateWithVeryHighPrice", ethereum.CallMsg{
   567  			From:     addr,
   568  			To:       &recipient,
   569  			Gas:      0,
   570  			GasPrice: big.NewInt(1e14), // gascost = 2.1ether
   571  			Value:    big.NewInt(1e17), // the remaining balance for fee is 2.1ether
   572  			Data:     nil,
   573  		}, 21000, nil},
   574  
   575  		{"EstimateWithSuperhighPrice", ethereum.CallMsg{
   576  			From:     addr,
   577  			To:       &recipient,
   578  			Gas:      0,
   579  			GasPrice: big.NewInt(2e14), // gascost = 4.2ether
   580  			Value:    big.NewInt(100000000000),
   581  			Data:     nil,
   582  		}, 21000, errors.New("gas required exceeds allowance (10999)")}, // 10999=(2.2ether-1000wei)/(2e14)
   583  
   584  		{"EstimateEIP1559WithHighFees", ethereum.CallMsg{
   585  			From:      addr,
   586  			To:        &addr,
   587  			Gas:       0,
   588  			GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
   589  			GasTipCap: big.NewInt(1),
   590  			Value:     big.NewInt(1e17), // the remaining balance for fee is 2.1ether
   591  			Data:      nil,
   592  		}, params.TxGas, nil},
   593  
   594  		{"EstimateEIP1559WithSuperHighFees", ethereum.CallMsg{
   595  			From:      addr,
   596  			To:        &addr,
   597  			Gas:       0,
   598  			GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
   599  			GasTipCap: big.NewInt(1),
   600  			Value:     big.NewInt(1e17 + 1), // the remaining balance for fee is 2.1ether
   601  			Data:      nil,
   602  		}, params.TxGas, errors.New("gas required exceeds allowance (20999)")}, // 20999=(2.2ether-0.1ether-1wei)/(1e14)
   603  	}
   604  	for i, c := range cases {
   605  		got, err := sim.EstimateGas(context.Background(), c.message)
   606  		if c.expectError != nil {
   607  			if err == nil {
   608  				t.Fatalf("test %d: expect error, got nil", i)
   609  			}
   610  			if c.expectError.Error() != err.Error() {
   611  				t.Fatalf("test %d: expect error, want %v, got %v", i, c.expectError, err)
   612  			}
   613  			continue
   614  		}
   615  		if c.expectError == nil && err != nil {
   616  			t.Fatalf("test %d: didn't expect error, got %v", i, err)
   617  		}
   618  		if got != c.expect {
   619  			t.Fatalf("test %d: gas estimation mismatch, want %d, got %d", i, c.expect, got)
   620  		}
   621  	}
   622  }
   623  
   624  func TestHeaderByHash(t *testing.T) {
   625  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   626  
   627  	sim := simTestBackend(testAddr)
   628  	defer sim.Close()
   629  	bgCtx := context.Background()
   630  
   631  	header, err := sim.HeaderByNumber(bgCtx, nil)
   632  	if err != nil {
   633  		t.Errorf("could not get recent block: %v", err)
   634  	}
   635  	headerByHash, err := sim.HeaderByHash(bgCtx, header.Hash())
   636  	if err != nil {
   637  		t.Errorf("could not get recent block: %v", err)
   638  	}
   639  
   640  	if header.Hash() != headerByHash.Hash() {
   641  		t.Errorf("did not get expected block")
   642  	}
   643  }
   644  
   645  func TestHeaderByNumber(t *testing.T) {
   646  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   647  
   648  	sim := simTestBackend(testAddr)
   649  	defer sim.Close()
   650  	bgCtx := context.Background()
   651  
   652  	latestBlockHeader, err := sim.HeaderByNumber(bgCtx, nil)
   653  	if err != nil {
   654  		t.Errorf("could not get header for tip of chain: %v", err)
   655  	}
   656  	if latestBlockHeader == nil {
   657  		t.Errorf("received a nil block header")
   658  	}
   659  	if latestBlockHeader.Number.Uint64() != uint64(0) {
   660  		t.Errorf("expected block header number 0, instead got %v", latestBlockHeader.Number.Uint64())
   661  	}
   662  
   663  	sim.Commit()
   664  
   665  	latestBlockHeader, err = sim.HeaderByNumber(bgCtx, nil)
   666  	if err != nil {
   667  		t.Errorf("could not get header for blockheight of 1: %v", err)
   668  	}
   669  
   670  	blockHeader, err := sim.HeaderByNumber(bgCtx, big.NewInt(1))
   671  	if err != nil {
   672  		t.Errorf("could not get header for blockheight of 1: %v", err)
   673  	}
   674  
   675  	if blockHeader.Hash() != latestBlockHeader.Hash() {
   676  		t.Errorf("block header and latest block header are not the same")
   677  	}
   678  	if blockHeader.Number.Int64() != int64(1) {
   679  		t.Errorf("did not get blockheader for block 1. instead got block %v", blockHeader.Number.Int64())
   680  	}
   681  
   682  	block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   683  	if err != nil {
   684  		t.Errorf("could not get block for blockheight of 1: %v", err)
   685  	}
   686  
   687  	if block.Hash() != blockHeader.Hash() {
   688  		t.Errorf("block hash and block header hash do not match. expected %v, got %v", block.Hash(), blockHeader.Hash())
   689  	}
   690  }
   691  
   692  func TestTransactionCount(t *testing.T) {
   693  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   694  
   695  	sim := simTestBackend(testAddr)
   696  	defer sim.Close()
   697  	bgCtx := context.Background()
   698  	currentBlock, err := sim.BlockByNumber(bgCtx, nil)
   699  	if err != nil || currentBlock == nil {
   700  		t.Error("could not get current block")
   701  	}
   702  
   703  	count, err := sim.TransactionCount(bgCtx, currentBlock.Hash())
   704  	if err != nil {
   705  		t.Error("could not get current block's transaction count")
   706  	}
   707  
   708  	if count != 0 {
   709  		t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count)
   710  	}
   711  	// create a signed transaction to send
   712  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   713  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   714  
   715  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   716  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   717  	if err != nil {
   718  		t.Errorf("could not sign tx: %v", err)
   719  	}
   720  
   721  	// send tx to simulated backend
   722  	err = sim.SendTransaction(bgCtx, signedTx)
   723  	if err != nil {
   724  		t.Errorf("could not add tx to pending block: %v", err)
   725  	}
   726  
   727  	sim.Commit()
   728  
   729  	lastBlock, err := sim.BlockByNumber(bgCtx, nil)
   730  	if err != nil {
   731  		t.Errorf("could not get header for tip of chain: %v", err)
   732  	}
   733  
   734  	count, err = sim.TransactionCount(bgCtx, lastBlock.Hash())
   735  	if err != nil {
   736  		t.Error("could not get current block's transaction count")
   737  	}
   738  
   739  	if count != 1 {
   740  		t.Errorf("expected transaction count of %v does not match actual count of %v", 1, count)
   741  	}
   742  }
   743  
   744  func TestTransactionInBlock(t *testing.T) {
   745  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   746  
   747  	sim := simTestBackend(testAddr)
   748  	defer sim.Close()
   749  	bgCtx := context.Background()
   750  
   751  	transaction, err := sim.TransactionInBlock(bgCtx, sim.pendingBlock.Hash(), uint(0))
   752  	if err == nil && err != errTransactionDoesNotExist {
   753  		t.Errorf("expected a transaction does not exist error to be received but received %v", err)
   754  	}
   755  	if transaction != nil {
   756  		t.Errorf("expected transaction to be nil but received %v", transaction)
   757  	}
   758  
   759  	// expect pending nonce to be 0 since account has not been used
   760  	pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
   761  	if err != nil {
   762  		t.Errorf("did not get the pending nonce: %v", err)
   763  	}
   764  
   765  	if pendingNonce != uint64(0) {
   766  		t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
   767  	}
   768  	// create a signed transaction to send
   769  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   770  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   771  
   772  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   773  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   774  	if err != nil {
   775  		t.Errorf("could not sign tx: %v", err)
   776  	}
   777  
   778  	// send tx to simulated backend
   779  	err = sim.SendTransaction(bgCtx, signedTx)
   780  	if err != nil {
   781  		t.Errorf("could not add tx to pending block: %v", err)
   782  	}
   783  
   784  	sim.Commit()
   785  
   786  	lastBlock, err := sim.BlockByNumber(bgCtx, nil)
   787  	if err != nil {
   788  		t.Errorf("could not get header for tip of chain: %v", err)
   789  	}
   790  
   791  	transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(1))
   792  	if err == nil && err != errTransactionDoesNotExist {
   793  		t.Errorf("expected a transaction does not exist error to be received but received %v", err)
   794  	}
   795  	if transaction != nil {
   796  		t.Errorf("expected transaction to be nil but received %v", transaction)
   797  	}
   798  
   799  	transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(0))
   800  	if err != nil {
   801  		t.Errorf("could not get transaction in the lastest block with hash %v: %v", lastBlock.Hash().String(), err)
   802  	}
   803  
   804  	if signedTx.Hash().String() != transaction.Hash().String() {
   805  		t.Errorf("received transaction that did not match the sent transaction. expected hash %v, got hash %v", signedTx.Hash().String(), transaction.Hash().String())
   806  	}
   807  }
   808  
   809  func TestPendingNonceAt(t *testing.T) {
   810  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   811  
   812  	sim := simTestBackend(testAddr)
   813  	defer sim.Close()
   814  	bgCtx := context.Background()
   815  
   816  	// expect pending nonce to be 0 since account has not been used
   817  	pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
   818  	if err != nil {
   819  		t.Errorf("did not get the pending nonce: %v", err)
   820  	}
   821  
   822  	if pendingNonce != uint64(0) {
   823  		t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
   824  	}
   825  
   826  	// create a signed transaction to send
   827  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   828  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   829  
   830  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   831  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   832  	if err != nil {
   833  		t.Errorf("could not sign tx: %v", err)
   834  	}
   835  
   836  	// send tx to simulated backend
   837  	err = sim.SendTransaction(bgCtx, signedTx)
   838  	if err != nil {
   839  		t.Errorf("could not add tx to pending block: %v", err)
   840  	}
   841  
   842  	// expect pending nonce to be 1 since account has submitted one transaction
   843  	pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
   844  	if err != nil {
   845  		t.Errorf("did not get the pending nonce: %v", err)
   846  	}
   847  
   848  	if pendingNonce != uint64(1) {
   849  		t.Errorf("expected pending nonce of 1 got %v", pendingNonce)
   850  	}
   851  
   852  	// make a new transaction with a nonce of 1
   853  	tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   854  	signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey)
   855  	if err != nil {
   856  		t.Errorf("could not sign tx: %v", err)
   857  	}
   858  	err = sim.SendTransaction(bgCtx, signedTx)
   859  	if err != nil {
   860  		t.Errorf("could not send tx: %v", err)
   861  	}
   862  
   863  	// expect pending nonce to be 2 since account now has two transactions
   864  	pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
   865  	if err != nil {
   866  		t.Errorf("did not get the pending nonce: %v", err)
   867  	}
   868  
   869  	if pendingNonce != uint64(2) {
   870  		t.Errorf("expected pending nonce of 2 got %v", pendingNonce)
   871  	}
   872  }
   873  
   874  func TestTransactionReceipt(t *testing.T) {
   875  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   876  
   877  	sim := simTestBackend(testAddr)
   878  	defer sim.Close()
   879  	bgCtx := context.Background()
   880  
   881  	// create a signed transaction to send
   882  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
   883  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
   884  
   885  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
   886  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   887  	if err != nil {
   888  		t.Errorf("could not sign tx: %v", err)
   889  	}
   890  
   891  	// send tx to simulated backend
   892  	err = sim.SendTransaction(bgCtx, signedTx)
   893  	if err != nil {
   894  		t.Errorf("could not add tx to pending block: %v", err)
   895  	}
   896  	sim.Commit()
   897  
   898  	receipt, err := sim.TransactionReceipt(bgCtx, signedTx.Hash())
   899  	if err != nil {
   900  		t.Errorf("could not get transaction receipt: %v", err)
   901  	}
   902  
   903  	if receipt.ContractAddress != testAddr && receipt.TxHash != signedTx.Hash() {
   904  		t.Errorf("received receipt is not correct: %v", receipt)
   905  	}
   906  }
   907  
   908  func TestSuggestGasPrice(t *testing.T) {
   909  	sim := NewSimulatedBackend(
   910  		core.GenesisAlloc{},
   911  		10000000,
   912  	)
   913  	defer sim.Close()
   914  	bgCtx := context.Background()
   915  	gasPrice, err := sim.SuggestGasPrice(bgCtx)
   916  	if err != nil {
   917  		t.Errorf("could not get gas price: %v", err)
   918  	}
   919  	if gasPrice.Uint64() != sim.pendingBlock.Header().BaseFee.Uint64() {
   920  		t.Errorf("gas price was not expected value of %v. actual: %v", sim.pendingBlock.Header().BaseFee.Uint64(), gasPrice.Uint64())
   921  	}
   922  }
   923  
   924  func TestPendingCodeAt(t *testing.T) {
   925  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   926  	sim := simTestBackend(testAddr)
   927  	defer sim.Close()
   928  	bgCtx := context.Background()
   929  	code, err := sim.CodeAt(bgCtx, testAddr, nil)
   930  	if err != nil {
   931  		t.Errorf("could not get code at test addr: %v", err)
   932  	}
   933  	if len(code) != 0 {
   934  		t.Errorf("got code for account that does not have contract code")
   935  	}
   936  
   937  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
   938  	if err != nil {
   939  		t.Errorf("could not get code at test addr: %v", err)
   940  	}
   941  	auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
   942  	contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
   943  	if err != nil {
   944  		t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
   945  	}
   946  
   947  	code, err = sim.PendingCodeAt(bgCtx, contractAddr)
   948  	if err != nil {
   949  		t.Errorf("could not get code at test addr: %v", err)
   950  	}
   951  	if len(code) == 0 {
   952  		t.Errorf("did not get code for account that has contract code")
   953  	}
   954  	// ensure code received equals code deployed
   955  	if !bytes.Equal(code, common.FromHex(deployedCode)) {
   956  		t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
   957  	}
   958  }
   959  
   960  func TestCodeAt(t *testing.T) {
   961  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   962  	sim := simTestBackend(testAddr)
   963  	defer sim.Close()
   964  	bgCtx := context.Background()
   965  	code, err := sim.CodeAt(bgCtx, testAddr, nil)
   966  	if err != nil {
   967  		t.Errorf("could not get code at test addr: %v", err)
   968  	}
   969  	if len(code) != 0 {
   970  		t.Errorf("got code for account that does not have contract code")
   971  	}
   972  
   973  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
   974  	if err != nil {
   975  		t.Errorf("could not get code at test addr: %v", err)
   976  	}
   977  	auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
   978  	contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
   979  	if err != nil {
   980  		t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
   981  	}
   982  
   983  	sim.Commit()
   984  	code, err = sim.CodeAt(bgCtx, contractAddr, nil)
   985  	if err != nil {
   986  		t.Errorf("could not get code at test addr: %v", err)
   987  	}
   988  	if len(code) == 0 {
   989  		t.Errorf("did not get code for account that has contract code")
   990  	}
   991  	// ensure code received equals code deployed
   992  	if !bytes.Equal(code, common.FromHex(deployedCode)) {
   993  		t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
   994  	}
   995  }
   996  
   997  // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
   998  //   receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
   999  func TestPendingAndCallContract(t *testing.T) {
  1000  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1001  	sim := simTestBackend(testAddr)
  1002  	defer sim.Close()
  1003  	bgCtx := context.Background()
  1004  
  1005  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
  1006  	if err != nil {
  1007  		t.Errorf("could not get code at test addr: %v", err)
  1008  	}
  1009  	contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
  1010  	addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(abiBin), sim)
  1011  	if err != nil {
  1012  		t.Errorf("could not deploy contract: %v", err)
  1013  	}
  1014  
  1015  	input, err := parsed.Pack("receive", []byte("X"))
  1016  	if err != nil {
  1017  		t.Errorf("could not pack receive function on contract: %v", err)
  1018  	}
  1019  
  1020  	// make sure you can call the contract in pending state
  1021  	res, err := sim.PendingCallContract(bgCtx, ethereum.CallMsg{
  1022  		From: testAddr,
  1023  		To:   &addr,
  1024  		Data: input,
  1025  	})
  1026  	if err != nil {
  1027  		t.Errorf("could not call receive method on contract: %v", err)
  1028  	}
  1029  	if len(res) == 0 {
  1030  		t.Errorf("result of contract call was empty: %v", res)
  1031  	}
  1032  
  1033  	// while comparing against the byte array is more exact, also compare against the human readable string for readability
  1034  	if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
  1035  		t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
  1036  	}
  1037  
  1038  	sim.Commit()
  1039  
  1040  	// make sure you can call the contract
  1041  	res, err = sim.CallContract(bgCtx, ethereum.CallMsg{
  1042  		From: testAddr,
  1043  		To:   &addr,
  1044  		Data: input,
  1045  	}, nil)
  1046  	if err != nil {
  1047  		t.Errorf("could not call receive method on contract: %v", err)
  1048  	}
  1049  	if len(res) == 0 {
  1050  		t.Errorf("result of contract call was empty: %v", res)
  1051  	}
  1052  
  1053  	if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
  1054  		t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
  1055  	}
  1056  }
  1057  
  1058  // This test is based on the following contract:
  1059  /*
  1060  contract Reverter {
  1061      function revertString() public pure{
  1062          require(false, "some error");
  1063      }
  1064      function revertNoString() public pure {
  1065          require(false, "");
  1066      }
  1067      function revertASM() public pure {
  1068          assembly {
  1069              revert(0x0, 0x0)
  1070          }
  1071      }
  1072      function noRevert() public pure {
  1073          assembly {
  1074              // Assembles something that looks like require(false, "some error") but is not reverted
  1075              mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
  1076              mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020)
  1077              mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a)
  1078              mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000)
  1079              return(0x0, 0x64)
  1080          }
  1081      }
  1082  }*/
  1083  func TestCallContractRevert(t *testing.T) {
  1084  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1085  	sim := simTestBackend(testAddr)
  1086  	defer sim.Close()
  1087  	bgCtx := context.Background()
  1088  
  1089  	reverterABI := `[{"inputs": [],"name": "noRevert","outputs": [],"stateMutability": "pure","type": "function"},{"inputs": [],"name": "revertASM","outputs": [],"stateMutability": "pure","type": "function"},{"inputs": [],"name": "revertNoString","outputs": [],"stateMutability": "pure","type": "function"},{"inputs": [],"name": "revertString","outputs": [],"stateMutability": "pure","type": "function"}]`
  1090  	reverterBin := "608060405234801561001057600080fd5b506101d3806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80634b409e01146100515780639b340e361461005b5780639bd6103714610065578063b7246fc11461006f575b600080fd5b610059610079565b005b6100636100ca565b005b61006d6100cf565b005b610077610145565b005b60006100c8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526000815260200160200191505060405180910390fd5b565b600080fd5b6000610143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f736f6d65206572726f720000000000000000000000000000000000000000000081525060200191505060405180910390fd5b565b7f08c379a0000000000000000000000000000000000000000000000000000000006000526020600452600a6024527f736f6d65206572726f720000000000000000000000000000000000000000000060445260646000f3fea2646970667358221220cdd8af0609ec4996b7360c7c780bad5c735740c64b1fffc3445aa12d37f07cb164736f6c63430006070033"
  1091  
  1092  	parsed, err := abi.JSON(strings.NewReader(reverterABI))
  1093  	if err != nil {
  1094  		t.Errorf("could not get code at test addr: %v", err)
  1095  	}
  1096  	contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
  1097  	addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(reverterBin), sim)
  1098  	if err != nil {
  1099  		t.Errorf("could not deploy contract: %v", err)
  1100  	}
  1101  
  1102  	inputs := make(map[string]interface{}, 3)
  1103  	inputs["revertASM"] = nil
  1104  	inputs["revertNoString"] = ""
  1105  	inputs["revertString"] = "some error"
  1106  
  1107  	call := make([]func([]byte) ([]byte, error), 2)
  1108  	call[0] = func(input []byte) ([]byte, error) {
  1109  		return sim.PendingCallContract(bgCtx, ethereum.CallMsg{
  1110  			From: testAddr,
  1111  			To:   &addr,
  1112  			Data: input,
  1113  		})
  1114  	}
  1115  	call[1] = func(input []byte) ([]byte, error) {
  1116  		return sim.CallContract(bgCtx, ethereum.CallMsg{
  1117  			From: testAddr,
  1118  			To:   &addr,
  1119  			Data: input,
  1120  		}, nil)
  1121  	}
  1122  
  1123  	// Run pending calls then commit
  1124  	for _, cl := range call {
  1125  		for key, val := range inputs {
  1126  			input, err := parsed.Pack(key)
  1127  			if err != nil {
  1128  				t.Errorf("could not pack %v function on contract: %v", key, err)
  1129  			}
  1130  
  1131  			res, err := cl(input)
  1132  			if err == nil {
  1133  				t.Errorf("call to %v was not reverted", key)
  1134  			}
  1135  			if res != nil {
  1136  				t.Errorf("result from %v was not nil: %v", key, res)
  1137  			}
  1138  			if val != nil {
  1139  				rerr, ok := err.(*revertError)
  1140  				if !ok {
  1141  					t.Errorf("expect revert error")
  1142  				}
  1143  				if rerr.Error() != "execution reverted: "+val.(string) {
  1144  					t.Errorf("error was malformed: got %v want %v", rerr.Error(), val)
  1145  				}
  1146  			} else {
  1147  				// revert(0x0,0x0)
  1148  				if err.Error() != "execution reverted" {
  1149  					t.Errorf("error was malformed: got %v want %v", err, "execution reverted")
  1150  				}
  1151  			}
  1152  		}
  1153  		input, err := parsed.Pack("noRevert")
  1154  		if err != nil {
  1155  			t.Errorf("could not pack noRevert function on contract: %v", err)
  1156  		}
  1157  		res, err := cl(input)
  1158  		if err != nil {
  1159  			t.Error("call to noRevert was reverted")
  1160  		}
  1161  		if res == nil {
  1162  			t.Errorf("result from noRevert was nil")
  1163  		}
  1164  		sim.Commit()
  1165  	}
  1166  }
  1167  
  1168  // TestFork check that the chain length after a reorg is correct.
  1169  // Steps:
  1170  //  1. Save the current block which will serve as parent for the fork.
  1171  //  2. Mine n blocks with n ∈ [0, 20].
  1172  //  3. Assert that the chain length is n.
  1173  //  4. Fork by using the parent block as ancestor.
  1174  //  5. Mine n+1 blocks which should trigger a reorg.
  1175  //  6. Assert that the chain length is n+1.
  1176  //     Since Commit() was called 2n+1 times in total,
  1177  //     having a chain length of just n+1 means that a reorg occurred.
  1178  func TestFork(t *testing.T) {
  1179  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1180  	sim := simTestBackend(testAddr)
  1181  	defer sim.Close()
  1182  	// 1.
  1183  	parent := sim.blockchain.CurrentBlock()
  1184  	// 2.
  1185  	n := int(rand.Int31n(21))
  1186  	for i := 0; i < n; i++ {
  1187  		sim.Commit()
  1188  	}
  1189  	// 3.
  1190  	if sim.blockchain.CurrentBlock().NumberU64() != uint64(n) {
  1191  		t.Error("wrong chain length")
  1192  	}
  1193  	// 4.
  1194  	sim.Fork(context.Background(), parent.Hash())
  1195  	// 5.
  1196  	for i := 0; i < n+1; i++ {
  1197  		sim.Commit()
  1198  	}
  1199  	// 6.
  1200  	if sim.blockchain.CurrentBlock().NumberU64() != uint64(n+1) {
  1201  		t.Error("wrong chain length")
  1202  	}
  1203  }
  1204  
  1205  /*
  1206  Example contract to test event emission:
  1207  
  1208  pragma solidity >=0.7.0 <0.9.0;
  1209  contract Callable {
  1210      event Called();
  1211      function Call() public { emit Called(); }
  1212  }
  1213  */
  1214  const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
  1215  
  1216  const callableBin = "6080604052348015600f57600080fd5b5060998061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806334e2292114602d575b600080fd5b60336035565b005b7f81fab7a4a0aa961db47eefc81f143a5220e8c8495260dd65b1356f1d19d3c7b860405160405180910390a156fea2646970667358221220029436d24f3ac598ceca41d4d712e13ced6d70727f4cdc580667de66d2f51d8b64736f6c63430008010033"
  1217  
  1218  // TestForkLogsReborn check that the simulated reorgs
  1219  // correctly remove and reborn logs.
  1220  // Steps:
  1221  //  1. Deploy the Callable contract.
  1222  //  2. Set up an event subscription.
  1223  //  3. Save the current block which will serve as parent for the fork.
  1224  //  4. Send a transaction.
  1225  //  5. Check that the event was included.
  1226  //  6. Fork by using the parent block as ancestor.
  1227  //  7. Mine two blocks to trigger a reorg.
  1228  //  8. Check that the event was removed.
  1229  //  9. Re-send the transaction and mine a block.
  1230  // 10. Check that the event was reborn.
  1231  func TestForkLogsReborn(t *testing.T) {
  1232  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1233  	sim := simTestBackend(testAddr)
  1234  	defer sim.Close()
  1235  	// 1.
  1236  	parsed, _ := abi.JSON(strings.NewReader(callableAbi))
  1237  	auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
  1238  	_, _, contract, err := bind.DeployContract(auth, parsed, common.FromHex(callableBin), sim)
  1239  	if err != nil {
  1240  		t.Errorf("deploying contract: %v", err)
  1241  	}
  1242  	sim.Commit()
  1243  	// 2.
  1244  	logs, sub, err := contract.WatchLogs(nil, "Called")
  1245  	if err != nil {
  1246  		t.Errorf("watching logs: %v", err)
  1247  	}
  1248  	defer sub.Unsubscribe()
  1249  	// 3.
  1250  	parent := sim.blockchain.CurrentBlock()
  1251  	// 4.
  1252  	tx, err := contract.Transact(auth, "Call")
  1253  	if err != nil {
  1254  		t.Errorf("transacting: %v", err)
  1255  	}
  1256  	sim.Commit()
  1257  	// 5.
  1258  	log := <-logs
  1259  	if log.TxHash != tx.Hash() {
  1260  		t.Error("wrong event tx hash")
  1261  	}
  1262  	if log.Removed {
  1263  		t.Error("Event should be included")
  1264  	}
  1265  	// 6.
  1266  	if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
  1267  		t.Errorf("forking: %v", err)
  1268  	}
  1269  	// 7.
  1270  	sim.Commit()
  1271  	sim.Commit()
  1272  	// 8.
  1273  	log = <-logs
  1274  	if log.TxHash != tx.Hash() {
  1275  		t.Error("wrong event tx hash")
  1276  	}
  1277  	if !log.Removed {
  1278  		t.Error("Event should be removed")
  1279  	}
  1280  	// 9.
  1281  	if err := sim.SendTransaction(context.Background(), tx); err != nil {
  1282  		t.Errorf("sending transaction: %v", err)
  1283  	}
  1284  	sim.Commit()
  1285  	// 10.
  1286  	log = <-logs
  1287  	if log.TxHash != tx.Hash() {
  1288  		t.Error("wrong event tx hash")
  1289  	}
  1290  	if log.Removed {
  1291  		t.Error("Event should be included")
  1292  	}
  1293  }
  1294  
  1295  // TestForkResendTx checks that re-sending a TX after a fork
  1296  // is possible and does not cause a "nonce mismatch" panic.
  1297  // Steps:
  1298  //  1. Save the current block which will serve as parent for the fork.
  1299  //  2. Send a transaction.
  1300  //  3. Check that the TX is included in block 1.
  1301  //  4. Fork by using the parent block as ancestor.
  1302  //  5. Mine a block, Re-send the transaction and mine another one.
  1303  //  6. Check that the TX is now included in block 2.
  1304  func TestForkResendTx(t *testing.T) {
  1305  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1306  	sim := simTestBackend(testAddr)
  1307  	defer sim.Close()
  1308  	// 1.
  1309  	parent := sim.blockchain.CurrentBlock()
  1310  	// 2.
  1311  	head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
  1312  	gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
  1313  
  1314  	_tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
  1315  	tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey)
  1316  	sim.SendTransaction(context.Background(), tx)
  1317  	sim.Commit()
  1318  	// 3.
  1319  	receipt, _ := sim.TransactionReceipt(context.Background(), tx.Hash())
  1320  	if h := receipt.BlockNumber.Uint64(); h != 1 {
  1321  		t.Errorf("TX included in wrong block: %d", h)
  1322  	}
  1323  	// 4.
  1324  	if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
  1325  		t.Errorf("forking: %v", err)
  1326  	}
  1327  	// 5.
  1328  	sim.Commit()
  1329  	if err := sim.SendTransaction(context.Background(), tx); err != nil {
  1330  		t.Errorf("sending transaction: %v", err)
  1331  	}
  1332  	sim.Commit()
  1333  	// 6.
  1334  	receipt, _ = sim.TransactionReceipt(context.Background(), tx.Hash())
  1335  	if h := receipt.BlockNumber.Uint64(); h != 2 {
  1336  		t.Errorf("TX included in wrong block: %d", h)
  1337  	}
  1338  }