github.com/snowblossomcoin/go-ethereum@v1.9.25/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  	"reflect"
    25  	"strings"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum"
    30  	"github.com/ethereum/go-ethereum/accounts/abi"
    31  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/core"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/params"
    37  )
    38  
    39  func TestSimulatedBackend(t *testing.T) {
    40  	var gasLimit uint64 = 8000029
    41  	key, _ := crypto.GenerateKey() // nolint: gosec
    42  	auth := bind.NewKeyedTransactor(key)
    43  	genAlloc := make(core.GenesisAlloc)
    44  	genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)}
    45  
    46  	sim := NewSimulatedBackend(genAlloc, gasLimit)
    47  	defer sim.Close()
    48  
    49  	// should return an error if the tx is not found
    50  	txHash := common.HexToHash("2")
    51  	_, isPending, err := sim.TransactionByHash(context.Background(), txHash)
    52  
    53  	if isPending {
    54  		t.Fatal("transaction should not be pending")
    55  	}
    56  	if err != ethereum.NotFound {
    57  		t.Fatalf("err should be `ethereum.NotFound` but received %v", err)
    58  	}
    59  
    60  	// generate a transaction and confirm you can retrieve it
    61  	code := `6060604052600a8060106000396000f360606040526008565b00`
    62  	var gas uint64 = 3000000
    63  	tx := types.NewContractCreation(0, big.NewInt(0), gas, big.NewInt(1), common.FromHex(code))
    64  	tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key)
    65  
    66  	err = sim.SendTransaction(context.Background(), tx)
    67  	if err != nil {
    68  		t.Fatal("error sending transaction")
    69  	}
    70  
    71  	txHash = tx.Hash()
    72  	_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
    73  	if err != nil {
    74  		t.Fatalf("error getting transaction with hash: %v", txHash.String())
    75  	}
    76  	if !isPending {
    77  		t.Fatal("transaction should have pending status")
    78  	}
    79  
    80  	sim.Commit()
    81  	_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
    82  	if err != nil {
    83  		t.Fatalf("error getting transaction with hash: %v", txHash.String())
    84  	}
    85  	if isPending {
    86  		t.Fatal("transaction should not have pending status")
    87  	}
    88  }
    89  
    90  var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    91  
    92  //  the following is based on this contract:
    93  //  contract T {
    94  //  	event received(address sender, uint amount, bytes memo);
    95  //  	event receivedAddr(address sender);
    96  //
    97  //  	function receive(bytes calldata memo) external payable returns (string memory res) {
    98  //  		emit received(msg.sender, msg.value, memo);
    99  //  		emit receivedAddr(msg.sender);
   100  //		    return "hello world";
   101  //  	}
   102  //  }
   103  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" } ]`
   104  const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
   105  const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
   106  
   107  // expected return value contains "hello world"
   108  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}
   109  
   110  func simTestBackend(testAddr common.Address) *SimulatedBackend {
   111  	return NewSimulatedBackend(
   112  		core.GenesisAlloc{
   113  			testAddr: {Balance: big.NewInt(10000000000)},
   114  		}, 10000000,
   115  	)
   116  }
   117  
   118  func TestNewSimulatedBackend(t *testing.T) {
   119  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   120  	expectedBal := big.NewInt(10000000000)
   121  	sim := simTestBackend(testAddr)
   122  	defer sim.Close()
   123  
   124  	if sim.config != params.AllEthashProtocolChanges {
   125  		t.Errorf("expected sim config to equal params.AllEthashProtocolChanges, got %v", sim.config)
   126  	}
   127  
   128  	if sim.blockchain.Config() != params.AllEthashProtocolChanges {
   129  		t.Errorf("expected sim blockchain config to equal params.AllEthashProtocolChanges, got %v", sim.config)
   130  	}
   131  
   132  	stateDB, _ := sim.blockchain.State()
   133  	bal := stateDB.GetBalance(testAddr)
   134  	if bal.Cmp(expectedBal) != 0 {
   135  		t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
   136  	}
   137  }
   138  
   139  func TestSimulatedBackend_AdjustTime(t *testing.T) {
   140  	sim := NewSimulatedBackend(
   141  		core.GenesisAlloc{}, 10000000,
   142  	)
   143  	defer sim.Close()
   144  
   145  	prevTime := sim.pendingBlock.Time()
   146  	if err := sim.AdjustTime(time.Second); err != nil {
   147  		t.Error(err)
   148  	}
   149  	newTime := sim.pendingBlock.Time()
   150  
   151  	if newTime-prevTime != uint64(time.Second.Seconds()) {
   152  		t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime)
   153  	}
   154  }
   155  
   156  func TestNewSimulatedBackend_AdjustTimeFail(t *testing.T) {
   157  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   158  	sim := simTestBackend(testAddr)
   159  	// Create tx and send
   160  	tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   161  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   162  	if err != nil {
   163  		t.Errorf("could not sign tx: %v", err)
   164  	}
   165  	sim.SendTransaction(context.Background(), signedTx)
   166  	// AdjustTime should fail on non-empty block
   167  	if err := sim.AdjustTime(time.Second); err == nil {
   168  		t.Error("Expected adjust time to error on non-empty block")
   169  	}
   170  	sim.Commit()
   171  
   172  	prevTime := sim.pendingBlock.Time()
   173  	if err := sim.AdjustTime(time.Minute); err != nil {
   174  		t.Error(err)
   175  	}
   176  	newTime := sim.pendingBlock.Time()
   177  	if newTime-prevTime != uint64(time.Minute.Seconds()) {
   178  		t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime)
   179  	}
   180  	// Put a transaction after adjusting time
   181  	tx2 := types.NewTransaction(1, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   182  	signedTx2, err := types.SignTx(tx2, types.HomesteadSigner{}, testKey)
   183  	if err != nil {
   184  		t.Errorf("could not sign tx: %v", err)
   185  	}
   186  	sim.SendTransaction(context.Background(), signedTx2)
   187  	sim.Commit()
   188  	newTime = sim.pendingBlock.Time()
   189  	if newTime-prevTime >= uint64(time.Minute.Seconds()) {
   190  		t.Errorf("time adjusted, but shouldn't be: prev: %v, new: %v", prevTime, newTime)
   191  	}
   192  }
   193  
   194  func TestSimulatedBackend_BalanceAt(t *testing.T) {
   195  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   196  	expectedBal := big.NewInt(10000000000)
   197  	sim := simTestBackend(testAddr)
   198  	defer sim.Close()
   199  	bgCtx := context.Background()
   200  
   201  	bal, err := sim.BalanceAt(bgCtx, testAddr, nil)
   202  	if err != nil {
   203  		t.Error(err)
   204  	}
   205  
   206  	if bal.Cmp(expectedBal) != 0 {
   207  		t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
   208  	}
   209  }
   210  
   211  func TestSimulatedBackend_BlockByHash(t *testing.T) {
   212  	sim := NewSimulatedBackend(
   213  		core.GenesisAlloc{}, 10000000,
   214  	)
   215  	defer sim.Close()
   216  	bgCtx := context.Background()
   217  
   218  	block, err := sim.BlockByNumber(bgCtx, nil)
   219  	if err != nil {
   220  		t.Errorf("could not get recent block: %v", err)
   221  	}
   222  	blockByHash, err := sim.BlockByHash(bgCtx, block.Hash())
   223  	if err != nil {
   224  		t.Errorf("could not get recent block: %v", err)
   225  	}
   226  
   227  	if block.Hash() != blockByHash.Hash() {
   228  		t.Errorf("did not get expected block")
   229  	}
   230  }
   231  
   232  func TestSimulatedBackend_BlockByNumber(t *testing.T) {
   233  	sim := NewSimulatedBackend(
   234  		core.GenesisAlloc{}, 10000000,
   235  	)
   236  	defer sim.Close()
   237  	bgCtx := context.Background()
   238  
   239  	block, err := sim.BlockByNumber(bgCtx, nil)
   240  	if err != nil {
   241  		t.Errorf("could not get recent block: %v", err)
   242  	}
   243  	if block.NumberU64() != 0 {
   244  		t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
   245  	}
   246  
   247  	// create one block
   248  	sim.Commit()
   249  
   250  	block, err = sim.BlockByNumber(bgCtx, nil)
   251  	if err != nil {
   252  		t.Errorf("could not get recent block: %v", err)
   253  	}
   254  	if block.NumberU64() != 1 {
   255  		t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
   256  	}
   257  
   258  	blockByNumber, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   259  	if err != nil {
   260  		t.Errorf("could not get block by number: %v", err)
   261  	}
   262  	if blockByNumber.Hash() != block.Hash() {
   263  		t.Errorf("did not get the same block with height of 1 as before")
   264  	}
   265  }
   266  
   267  func TestSimulatedBackend_NonceAt(t *testing.T) {
   268  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   269  
   270  	sim := simTestBackend(testAddr)
   271  	defer sim.Close()
   272  	bgCtx := context.Background()
   273  
   274  	nonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(0))
   275  	if err != nil {
   276  		t.Errorf("could not get nonce for test addr: %v", err)
   277  	}
   278  
   279  	if nonce != uint64(0) {
   280  		t.Errorf("received incorrect nonce. expected 0, got %v", nonce)
   281  	}
   282  
   283  	// create a signed transaction to send
   284  	tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   285  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   286  	if err != nil {
   287  		t.Errorf("could not sign tx: %v", err)
   288  	}
   289  
   290  	// send tx to simulated backend
   291  	err = sim.SendTransaction(bgCtx, signedTx)
   292  	if err != nil {
   293  		t.Errorf("could not add tx to pending block: %v", err)
   294  	}
   295  	sim.Commit()
   296  
   297  	newNonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
   298  	if err != nil {
   299  		t.Errorf("could not get nonce for test addr: %v", err)
   300  	}
   301  
   302  	if newNonce != nonce+uint64(1) {
   303  		t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
   304  	}
   305  	// create some more blocks
   306  	sim.Commit()
   307  	// Check that we can get data for an older block/state
   308  	newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
   309  	if err != nil {
   310  		t.Fatalf("could not get nonce for test addr: %v", err)
   311  	}
   312  	if newNonce != nonce+uint64(1) {
   313  		t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
   314  	}
   315  }
   316  
   317  func TestSimulatedBackend_SendTransaction(t *testing.T) {
   318  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   319  
   320  	sim := simTestBackend(testAddr)
   321  	defer sim.Close()
   322  	bgCtx := context.Background()
   323  
   324  	// create a signed transaction to send
   325  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   326  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   327  	if err != nil {
   328  		t.Errorf("could not sign tx: %v", err)
   329  	}
   330  
   331  	// send tx to simulated backend
   332  	err = sim.SendTransaction(bgCtx, signedTx)
   333  	if err != nil {
   334  		t.Errorf("could not add tx to pending block: %v", err)
   335  	}
   336  	sim.Commit()
   337  
   338  	block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   339  	if err != nil {
   340  		t.Errorf("could not get block at height 1: %v", err)
   341  	}
   342  
   343  	if signedTx.Hash() != block.Transactions()[0].Hash() {
   344  		t.Errorf("did not commit sent transaction. expected hash %v got hash %v", block.Transactions()[0].Hash(), signedTx.Hash())
   345  	}
   346  }
   347  
   348  func TestSimulatedBackend_TransactionByHash(t *testing.T) {
   349  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   350  
   351  	sim := NewSimulatedBackend(
   352  		core.GenesisAlloc{
   353  			testAddr: {Balance: big.NewInt(10000000000)},
   354  		}, 10000000,
   355  	)
   356  	defer sim.Close()
   357  	bgCtx := context.Background()
   358  
   359  	// create a signed transaction to send
   360  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   361  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   362  	if err != nil {
   363  		t.Errorf("could not sign tx: %v", err)
   364  	}
   365  
   366  	// send tx to simulated backend
   367  	err = sim.SendTransaction(bgCtx, signedTx)
   368  	if err != nil {
   369  		t.Errorf("could not add tx to pending block: %v", err)
   370  	}
   371  
   372  	// ensure tx is committed pending
   373  	receivedTx, pending, err := sim.TransactionByHash(bgCtx, signedTx.Hash())
   374  	if err != nil {
   375  		t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
   376  	}
   377  	if !pending {
   378  		t.Errorf("expected transaction to be in pending state")
   379  	}
   380  	if receivedTx.Hash() != signedTx.Hash() {
   381  		t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
   382  	}
   383  
   384  	sim.Commit()
   385  
   386  	// ensure tx is not and committed pending
   387  	receivedTx, pending, err = sim.TransactionByHash(bgCtx, signedTx.Hash())
   388  	if err != nil {
   389  		t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
   390  	}
   391  	if pending {
   392  		t.Errorf("expected transaction to not be in pending state")
   393  	}
   394  	if receivedTx.Hash() != signedTx.Hash() {
   395  		t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
   396  	}
   397  }
   398  
   399  func TestSimulatedBackend_EstimateGas(t *testing.T) {
   400  	/*
   401  		pragma solidity ^0.6.4;
   402  		contract GasEstimation {
   403  		    function PureRevert() public { revert(); }
   404  		    function Revert() public { revert("revert reason");}
   405  		    function OOG() public { for (uint i = 0; ; i++) {}}
   406  		    function Assert() public { assert(false);}
   407  		    function Valid() public {}
   408  		}*/
   409  	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\"}]"
   410  	const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
   411  
   412  	key, _ := crypto.GenerateKey()
   413  	addr := crypto.PubkeyToAddress(key.PublicKey)
   414  	opts := bind.NewKeyedTransactor(key)
   415  
   416  	sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000)
   417  	defer sim.Close()
   418  
   419  	parsed, _ := abi.JSON(strings.NewReader(contractAbi))
   420  	contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim)
   421  	sim.Commit()
   422  
   423  	var cases = []struct {
   424  		name        string
   425  		message     ethereum.CallMsg
   426  		expect      uint64
   427  		expectError error
   428  		expectData  interface{}
   429  	}{
   430  		{"plain transfer(valid)", ethereum.CallMsg{
   431  			From:     addr,
   432  			To:       &addr,
   433  			Gas:      0,
   434  			GasPrice: big.NewInt(0),
   435  			Value:    big.NewInt(1),
   436  			Data:     nil,
   437  		}, params.TxGas, nil, nil},
   438  
   439  		{"plain transfer(invalid)", ethereum.CallMsg{
   440  			From:     addr,
   441  			To:       &contractAddr,
   442  			Gas:      0,
   443  			GasPrice: big.NewInt(0),
   444  			Value:    big.NewInt(1),
   445  			Data:     nil,
   446  		}, 0, errors.New("execution reverted"), nil},
   447  
   448  		{"Revert", ethereum.CallMsg{
   449  			From:     addr,
   450  			To:       &contractAddr,
   451  			Gas:      0,
   452  			GasPrice: big.NewInt(0),
   453  			Value:    nil,
   454  			Data:     common.Hex2Bytes("d8b98391"),
   455  		}, 0, errors.New("execution reverted: revert reason"), "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000"},
   456  
   457  		{"PureRevert", ethereum.CallMsg{
   458  			From:     addr,
   459  			To:       &contractAddr,
   460  			Gas:      0,
   461  			GasPrice: big.NewInt(0),
   462  			Value:    nil,
   463  			Data:     common.Hex2Bytes("aa8b1d30"),
   464  		}, 0, errors.New("execution reverted"), nil},
   465  
   466  		{"OOG", ethereum.CallMsg{
   467  			From:     addr,
   468  			To:       &contractAddr,
   469  			Gas:      100000,
   470  			GasPrice: big.NewInt(0),
   471  			Value:    nil,
   472  			Data:     common.Hex2Bytes("50f6fe34"),
   473  		}, 0, errors.New("gas required exceeds allowance (100000)"), nil},
   474  
   475  		{"Assert", ethereum.CallMsg{
   476  			From:     addr,
   477  			To:       &contractAddr,
   478  			Gas:      100000,
   479  			GasPrice: big.NewInt(0),
   480  			Value:    nil,
   481  			Data:     common.Hex2Bytes("b9b046f9"),
   482  		}, 0, errors.New("invalid opcode: opcode 0xfe not defined"), nil},
   483  
   484  		{"Valid", ethereum.CallMsg{
   485  			From:     addr,
   486  			To:       &contractAddr,
   487  			Gas:      100000,
   488  			GasPrice: big.NewInt(0),
   489  			Value:    nil,
   490  			Data:     common.Hex2Bytes("e09fface"),
   491  		}, 21275, nil, nil},
   492  	}
   493  	for _, c := range cases {
   494  		got, err := sim.EstimateGas(context.Background(), c.message)
   495  		if c.expectError != nil {
   496  			if err == nil {
   497  				t.Fatalf("Expect error, got nil")
   498  			}
   499  			if c.expectError.Error() != err.Error() {
   500  				t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
   501  			}
   502  			if c.expectData != nil {
   503  				if err, ok := err.(*revertError); !ok {
   504  					t.Fatalf("Expect revert error, got %T", err)
   505  				} else if !reflect.DeepEqual(err.ErrorData(), c.expectData) {
   506  					t.Fatalf("Error data mismatch, want %v, got %v", c.expectData, err.ErrorData())
   507  				}
   508  			}
   509  			continue
   510  		}
   511  		if got != c.expect {
   512  			t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
   513  		}
   514  	}
   515  }
   516  
   517  func TestSimulatedBackend_EstimateGasWithPrice(t *testing.T) {
   518  	key, _ := crypto.GenerateKey()
   519  	addr := crypto.PubkeyToAddress(key.PublicKey)
   520  
   521  	sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000)
   522  	defer sim.Close()
   523  
   524  	recipient := common.HexToAddress("deadbeef")
   525  	var cases = []struct {
   526  		name        string
   527  		message     ethereum.CallMsg
   528  		expect      uint64
   529  		expectError error
   530  	}{
   531  		{"EstimateWithoutPrice", ethereum.CallMsg{
   532  			From:     addr,
   533  			To:       &recipient,
   534  			Gas:      0,
   535  			GasPrice: big.NewInt(0),
   536  			Value:    big.NewInt(1000),
   537  			Data:     nil,
   538  		}, 21000, nil},
   539  
   540  		{"EstimateWithPrice", ethereum.CallMsg{
   541  			From:     addr,
   542  			To:       &recipient,
   543  			Gas:      0,
   544  			GasPrice: big.NewInt(1000),
   545  			Value:    big.NewInt(1000),
   546  			Data:     nil,
   547  		}, 21000, nil},
   548  
   549  		{"EstimateWithVeryHighPrice", ethereum.CallMsg{
   550  			From:     addr,
   551  			To:       &recipient,
   552  			Gas:      0,
   553  			GasPrice: big.NewInt(1e14), // gascost = 2.1ether
   554  			Value:    big.NewInt(1e17), // the remaining balance for fee is 2.1ether
   555  			Data:     nil,
   556  		}, 21000, nil},
   557  
   558  		{"EstimateWithSuperhighPrice", ethereum.CallMsg{
   559  			From:     addr,
   560  			To:       &recipient,
   561  			Gas:      0,
   562  			GasPrice: big.NewInt(2e14), // gascost = 4.2ether
   563  			Value:    big.NewInt(1000),
   564  			Data:     nil,
   565  		}, 21000, errors.New("gas required exceeds allowance (10999)")}, // 10999=(2.2ether-1000wei)/(2e14)
   566  	}
   567  	for _, c := range cases {
   568  		got, err := sim.EstimateGas(context.Background(), c.message)
   569  		if c.expectError != nil {
   570  			if err == nil {
   571  				t.Fatalf("Expect error, got nil")
   572  			}
   573  			if c.expectError.Error() != err.Error() {
   574  				t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
   575  			}
   576  			continue
   577  		}
   578  		if got != c.expect {
   579  			t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
   580  		}
   581  	}
   582  }
   583  
   584  func TestSimulatedBackend_HeaderByHash(t *testing.T) {
   585  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   586  
   587  	sim := simTestBackend(testAddr)
   588  	defer sim.Close()
   589  	bgCtx := context.Background()
   590  
   591  	header, err := sim.HeaderByNumber(bgCtx, nil)
   592  	if err != nil {
   593  		t.Errorf("could not get recent block: %v", err)
   594  	}
   595  	headerByHash, err := sim.HeaderByHash(bgCtx, header.Hash())
   596  	if err != nil {
   597  		t.Errorf("could not get recent block: %v", err)
   598  	}
   599  
   600  	if header.Hash() != headerByHash.Hash() {
   601  		t.Errorf("did not get expected block")
   602  	}
   603  }
   604  
   605  func TestSimulatedBackend_HeaderByNumber(t *testing.T) {
   606  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   607  
   608  	sim := simTestBackend(testAddr)
   609  	defer sim.Close()
   610  	bgCtx := context.Background()
   611  
   612  	latestBlockHeader, err := sim.HeaderByNumber(bgCtx, nil)
   613  	if err != nil {
   614  		t.Errorf("could not get header for tip of chain: %v", err)
   615  	}
   616  	if latestBlockHeader == nil {
   617  		t.Errorf("received a nil block header")
   618  	}
   619  	if latestBlockHeader.Number.Uint64() != uint64(0) {
   620  		t.Errorf("expected block header number 0, instead got %v", latestBlockHeader.Number.Uint64())
   621  	}
   622  
   623  	sim.Commit()
   624  
   625  	latestBlockHeader, err = sim.HeaderByNumber(bgCtx, nil)
   626  	if err != nil {
   627  		t.Errorf("could not get header for blockheight of 1: %v", err)
   628  	}
   629  
   630  	blockHeader, err := sim.HeaderByNumber(bgCtx, big.NewInt(1))
   631  	if err != nil {
   632  		t.Errorf("could not get header for blockheight of 1: %v", err)
   633  	}
   634  
   635  	if blockHeader.Hash() != latestBlockHeader.Hash() {
   636  		t.Errorf("block header and latest block header are not the same")
   637  	}
   638  	if blockHeader.Number.Int64() != int64(1) {
   639  		t.Errorf("did not get blockheader for block 1. instead got block %v", blockHeader.Number.Int64())
   640  	}
   641  
   642  	block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
   643  	if err != nil {
   644  		t.Errorf("could not get block for blockheight of 1: %v", err)
   645  	}
   646  
   647  	if block.Hash() != blockHeader.Hash() {
   648  		t.Errorf("block hash and block header hash do not match. expected %v, got %v", block.Hash(), blockHeader.Hash())
   649  	}
   650  }
   651  
   652  func TestSimulatedBackend_TransactionCount(t *testing.T) {
   653  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   654  
   655  	sim := simTestBackend(testAddr)
   656  	defer sim.Close()
   657  	bgCtx := context.Background()
   658  	currentBlock, err := sim.BlockByNumber(bgCtx, nil)
   659  	if err != nil || currentBlock == nil {
   660  		t.Error("could not get current block")
   661  	}
   662  
   663  	count, err := sim.TransactionCount(bgCtx, currentBlock.Hash())
   664  	if err != nil {
   665  		t.Error("could not get current block's transaction count")
   666  	}
   667  
   668  	if count != 0 {
   669  		t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count)
   670  	}
   671  
   672  	// create a signed transaction to send
   673  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   674  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   675  	if err != nil {
   676  		t.Errorf("could not sign tx: %v", err)
   677  	}
   678  
   679  	// send tx to simulated backend
   680  	err = sim.SendTransaction(bgCtx, signedTx)
   681  	if err != nil {
   682  		t.Errorf("could not add tx to pending block: %v", err)
   683  	}
   684  
   685  	sim.Commit()
   686  
   687  	lastBlock, err := sim.BlockByNumber(bgCtx, nil)
   688  	if err != nil {
   689  		t.Errorf("could not get header for tip of chain: %v", err)
   690  	}
   691  
   692  	count, err = sim.TransactionCount(bgCtx, lastBlock.Hash())
   693  	if err != nil {
   694  		t.Error("could not get current block's transaction count")
   695  	}
   696  
   697  	if count != 1 {
   698  		t.Errorf("expected transaction count of %v does not match actual count of %v", 1, count)
   699  	}
   700  }
   701  
   702  func TestSimulatedBackend_TransactionInBlock(t *testing.T) {
   703  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   704  
   705  	sim := simTestBackend(testAddr)
   706  	defer sim.Close()
   707  	bgCtx := context.Background()
   708  
   709  	transaction, err := sim.TransactionInBlock(bgCtx, sim.pendingBlock.Hash(), uint(0))
   710  	if err == nil && err != errTransactionDoesNotExist {
   711  		t.Errorf("expected a transaction does not exist error to be received but received %v", err)
   712  	}
   713  	if transaction != nil {
   714  		t.Errorf("expected transaction to be nil but received %v", transaction)
   715  	}
   716  
   717  	// expect pending nonce to be 0 since account has not been used
   718  	pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
   719  	if err != nil {
   720  		t.Errorf("did not get the pending nonce: %v", err)
   721  	}
   722  
   723  	if pendingNonce != uint64(0) {
   724  		t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
   725  	}
   726  
   727  	// create a signed transaction to send
   728  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   729  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   730  	if err != nil {
   731  		t.Errorf("could not sign tx: %v", err)
   732  	}
   733  
   734  	// send tx to simulated backend
   735  	err = sim.SendTransaction(bgCtx, signedTx)
   736  	if err != nil {
   737  		t.Errorf("could not add tx to pending block: %v", err)
   738  	}
   739  
   740  	sim.Commit()
   741  
   742  	lastBlock, err := sim.BlockByNumber(bgCtx, nil)
   743  	if err != nil {
   744  		t.Errorf("could not get header for tip of chain: %v", err)
   745  	}
   746  
   747  	transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(1))
   748  	if err == nil && err != errTransactionDoesNotExist {
   749  		t.Errorf("expected a transaction does not exist error to be received but received %v", err)
   750  	}
   751  	if transaction != nil {
   752  		t.Errorf("expected transaction to be nil but received %v", transaction)
   753  	}
   754  
   755  	transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(0))
   756  	if err != nil {
   757  		t.Errorf("could not get transaction in the lastest block with hash %v: %v", lastBlock.Hash().String(), err)
   758  	}
   759  
   760  	if signedTx.Hash().String() != transaction.Hash().String() {
   761  		t.Errorf("received transaction that did not match the sent transaction. expected hash %v, got hash %v", signedTx.Hash().String(), transaction.Hash().String())
   762  	}
   763  }
   764  
   765  func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
   766  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   767  
   768  	sim := simTestBackend(testAddr)
   769  	defer sim.Close()
   770  	bgCtx := context.Background()
   771  
   772  	// expect pending nonce to be 0 since account has not been used
   773  	pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
   774  	if err != nil {
   775  		t.Errorf("did not get the pending nonce: %v", err)
   776  	}
   777  
   778  	if pendingNonce != uint64(0) {
   779  		t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
   780  	}
   781  
   782  	// create a signed transaction to send
   783  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   784  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   785  	if err != nil {
   786  		t.Errorf("could not sign tx: %v", err)
   787  	}
   788  
   789  	// send tx to simulated backend
   790  	err = sim.SendTransaction(bgCtx, signedTx)
   791  	if err != nil {
   792  		t.Errorf("could not add tx to pending block: %v", err)
   793  	}
   794  
   795  	// expect pending nonce to be 1 since account has submitted one transaction
   796  	pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
   797  	if err != nil {
   798  		t.Errorf("did not get the pending nonce: %v", err)
   799  	}
   800  
   801  	if pendingNonce != uint64(1) {
   802  		t.Errorf("expected pending nonce of 1 got %v", pendingNonce)
   803  	}
   804  
   805  	// make a new transaction with a nonce of 1
   806  	tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   807  	signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey)
   808  	if err != nil {
   809  		t.Errorf("could not sign tx: %v", err)
   810  	}
   811  	err = sim.SendTransaction(bgCtx, signedTx)
   812  	if err != nil {
   813  		t.Errorf("could not send tx: %v", err)
   814  	}
   815  
   816  	// expect pending nonce to be 2 since account now has two transactions
   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(2) {
   823  		t.Errorf("expected pending nonce of 2 got %v", pendingNonce)
   824  	}
   825  }
   826  
   827  func TestSimulatedBackend_TransactionReceipt(t *testing.T) {
   828  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   829  
   830  	sim := simTestBackend(testAddr)
   831  	defer sim.Close()
   832  	bgCtx := context.Background()
   833  
   834  	// create a signed transaction to send
   835  	tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
   836  	signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
   837  	if err != nil {
   838  		t.Errorf("could not sign tx: %v", err)
   839  	}
   840  
   841  	// send tx to simulated backend
   842  	err = sim.SendTransaction(bgCtx, signedTx)
   843  	if err != nil {
   844  		t.Errorf("could not add tx to pending block: %v", err)
   845  	}
   846  	sim.Commit()
   847  
   848  	receipt, err := sim.TransactionReceipt(bgCtx, signedTx.Hash())
   849  	if err != nil {
   850  		t.Errorf("could not get transaction receipt: %v", err)
   851  	}
   852  
   853  	if receipt.ContractAddress != testAddr && receipt.TxHash != signedTx.Hash() {
   854  		t.Errorf("received receipt is not correct: %v", receipt)
   855  	}
   856  }
   857  
   858  func TestSimulatedBackend_SuggestGasPrice(t *testing.T) {
   859  	sim := NewSimulatedBackend(
   860  		core.GenesisAlloc{},
   861  		10000000,
   862  	)
   863  	defer sim.Close()
   864  	bgCtx := context.Background()
   865  	gasPrice, err := sim.SuggestGasPrice(bgCtx)
   866  	if err != nil {
   867  		t.Errorf("could not get gas price: %v", err)
   868  	}
   869  	if gasPrice.Uint64() != uint64(1) {
   870  		t.Errorf("gas price was not expected value of 1. actual: %v", gasPrice.Uint64())
   871  	}
   872  }
   873  
   874  func TestSimulatedBackend_PendingCodeAt(t *testing.T) {
   875  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   876  	sim := simTestBackend(testAddr)
   877  	defer sim.Close()
   878  	bgCtx := context.Background()
   879  	code, err := sim.CodeAt(bgCtx, testAddr, nil)
   880  	if err != nil {
   881  		t.Errorf("could not get code at test addr: %v", err)
   882  	}
   883  	if len(code) != 0 {
   884  		t.Errorf("got code for account that does not have contract code")
   885  	}
   886  
   887  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
   888  	if err != nil {
   889  		t.Errorf("could not get code at test addr: %v", err)
   890  	}
   891  	auth := bind.NewKeyedTransactor(testKey)
   892  	contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
   893  	if err != nil {
   894  		t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
   895  	}
   896  
   897  	code, err = sim.PendingCodeAt(bgCtx, contractAddr)
   898  	if err != nil {
   899  		t.Errorf("could not get code at test addr: %v", err)
   900  	}
   901  	if len(code) == 0 {
   902  		t.Errorf("did not get code for account that has contract code")
   903  	}
   904  	// ensure code received equals code deployed
   905  	if !bytes.Equal(code, common.FromHex(deployedCode)) {
   906  		t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
   907  	}
   908  }
   909  
   910  func TestSimulatedBackend_CodeAt(t *testing.T) {
   911  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   912  	sim := simTestBackend(testAddr)
   913  	defer sim.Close()
   914  	bgCtx := context.Background()
   915  	code, err := sim.CodeAt(bgCtx, testAddr, nil)
   916  	if err != nil {
   917  		t.Errorf("could not get code at test addr: %v", err)
   918  	}
   919  	if len(code) != 0 {
   920  		t.Errorf("got code for account that does not have contract code")
   921  	}
   922  
   923  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
   924  	if err != nil {
   925  		t.Errorf("could not get code at test addr: %v", err)
   926  	}
   927  	auth := bind.NewKeyedTransactor(testKey)
   928  	contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
   929  	if err != nil {
   930  		t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
   931  	}
   932  
   933  	sim.Commit()
   934  	code, err = sim.CodeAt(bgCtx, contractAddr, nil)
   935  	if err != nil {
   936  		t.Errorf("could not get code at test addr: %v", err)
   937  	}
   938  	if len(code) == 0 {
   939  		t.Errorf("did not get code for account that has contract code")
   940  	}
   941  	// ensure code received equals code deployed
   942  	if !bytes.Equal(code, common.FromHex(deployedCode)) {
   943  		t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
   944  	}
   945  }
   946  
   947  // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
   948  //   receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
   949  func TestSimulatedBackend_PendingAndCallContract(t *testing.T) {
   950  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
   951  	sim := simTestBackend(testAddr)
   952  	defer sim.Close()
   953  	bgCtx := context.Background()
   954  
   955  	parsed, err := abi.JSON(strings.NewReader(abiJSON))
   956  	if err != nil {
   957  		t.Errorf("could not get code at test addr: %v", err)
   958  	}
   959  	contractAuth := bind.NewKeyedTransactor(testKey)
   960  	addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(abiBin), sim)
   961  	if err != nil {
   962  		t.Errorf("could not deploy contract: %v", err)
   963  	}
   964  
   965  	input, err := parsed.Pack("receive", []byte("X"))
   966  	if err != nil {
   967  		t.Errorf("could not pack receive function on contract: %v", err)
   968  	}
   969  
   970  	// make sure you can call the contract in pending state
   971  	res, err := sim.PendingCallContract(bgCtx, ethereum.CallMsg{
   972  		From: testAddr,
   973  		To:   &addr,
   974  		Data: input,
   975  	})
   976  	if err != nil {
   977  		t.Errorf("could not call receive method on contract: %v", err)
   978  	}
   979  	if len(res) == 0 {
   980  		t.Errorf("result of contract call was empty: %v", res)
   981  	}
   982  
   983  	// while comparing against the byte array is more exact, also compare against the human readable string for readability
   984  	if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
   985  		t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
   986  	}
   987  
   988  	sim.Commit()
   989  
   990  	// make sure you can call the contract
   991  	res, err = sim.CallContract(bgCtx, ethereum.CallMsg{
   992  		From: testAddr,
   993  		To:   &addr,
   994  		Data: input,
   995  	}, nil)
   996  	if err != nil {
   997  		t.Errorf("could not call receive method on contract: %v", err)
   998  	}
   999  	if len(res) == 0 {
  1000  		t.Errorf("result of contract call was empty: %v", res)
  1001  	}
  1002  
  1003  	if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
  1004  		t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
  1005  	}
  1006  }
  1007  
  1008  // This test is based on the following contract:
  1009  /*
  1010  contract Reverter {
  1011      function revertString() public pure{
  1012          require(false, "some error");
  1013      }
  1014      function revertNoString() public pure {
  1015          require(false, "");
  1016      }
  1017      function revertASM() public pure {
  1018          assembly {
  1019              revert(0x0, 0x0)
  1020          }
  1021      }
  1022      function noRevert() public pure {
  1023          assembly {
  1024              // Assembles something that looks like require(false, "some error") but is not reverted
  1025              mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
  1026              mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020)
  1027              mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a)
  1028              mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000)
  1029              return(0x0, 0x64)
  1030          }
  1031      }
  1032  }*/
  1033  func TestSimulatedBackend_CallContractRevert(t *testing.T) {
  1034  	testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  1035  	sim := simTestBackend(testAddr)
  1036  	defer sim.Close()
  1037  	bgCtx := context.Background()
  1038  
  1039  	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"}]`
  1040  	reverterBin := "608060405234801561001057600080fd5b506101d3806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80634b409e01146100515780639b340e361461005b5780639bd6103714610065578063b7246fc11461006f575b600080fd5b610059610079565b005b6100636100ca565b005b61006d6100cf565b005b610077610145565b005b60006100c8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526000815260200160200191505060405180910390fd5b565b600080fd5b6000610143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f736f6d65206572726f720000000000000000000000000000000000000000000081525060200191505060405180910390fd5b565b7f08c379a0000000000000000000000000000000000000000000000000000000006000526020600452600a6024527f736f6d65206572726f720000000000000000000000000000000000000000000060445260646000f3fea2646970667358221220cdd8af0609ec4996b7360c7c780bad5c735740c64b1fffc3445aa12d37f07cb164736f6c63430006070033"
  1041  
  1042  	parsed, err := abi.JSON(strings.NewReader(reverterABI))
  1043  	if err != nil {
  1044  		t.Errorf("could not get code at test addr: %v", err)
  1045  	}
  1046  	contractAuth := bind.NewKeyedTransactor(testKey)
  1047  	addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(reverterBin), sim)
  1048  	if err != nil {
  1049  		t.Errorf("could not deploy contract: %v", err)
  1050  	}
  1051  
  1052  	inputs := make(map[string]interface{}, 3)
  1053  	inputs["revertASM"] = nil
  1054  	inputs["revertNoString"] = ""
  1055  	inputs["revertString"] = "some error"
  1056  
  1057  	call := make([]func([]byte) ([]byte, error), 2)
  1058  	call[0] = func(input []byte) ([]byte, error) {
  1059  		return sim.PendingCallContract(bgCtx, ethereum.CallMsg{
  1060  			From: testAddr,
  1061  			To:   &addr,
  1062  			Data: input,
  1063  		})
  1064  	}
  1065  	call[1] = func(input []byte) ([]byte, error) {
  1066  		return sim.CallContract(bgCtx, ethereum.CallMsg{
  1067  			From: testAddr,
  1068  			To:   &addr,
  1069  			Data: input,
  1070  		}, nil)
  1071  	}
  1072  
  1073  	// Run pending calls then commit
  1074  	for _, cl := range call {
  1075  		for key, val := range inputs {
  1076  			input, err := parsed.Pack(key)
  1077  			if err != nil {
  1078  				t.Errorf("could not pack %v function on contract: %v", key, err)
  1079  			}
  1080  
  1081  			res, err := cl(input)
  1082  			if err == nil {
  1083  				t.Errorf("call to %v was not reverted", key)
  1084  			}
  1085  			if res != nil {
  1086  				t.Errorf("result from %v was not nil: %v", key, res)
  1087  			}
  1088  			if val != nil {
  1089  				rerr, ok := err.(*revertError)
  1090  				if !ok {
  1091  					t.Errorf("expect revert error")
  1092  				}
  1093  				if rerr.Error() != "execution reverted: "+val.(string) {
  1094  					t.Errorf("error was malformed: got %v want %v", rerr.Error(), val)
  1095  				}
  1096  			} else {
  1097  				// revert(0x0,0x0)
  1098  				if err.Error() != "execution reverted" {
  1099  					t.Errorf("error was malformed: got %v want %v", err, "execution reverted")
  1100  				}
  1101  			}
  1102  		}
  1103  		input, err := parsed.Pack("noRevert")
  1104  		if err != nil {
  1105  			t.Errorf("could not pack noRevert function on contract: %v", err)
  1106  		}
  1107  		res, err := cl(input)
  1108  		if err != nil {
  1109  			t.Error("call to noRevert was reverted")
  1110  		}
  1111  		if res == nil {
  1112  			t.Errorf("result from noRevert was nil")
  1113  		}
  1114  		sim.Commit()
  1115  	}
  1116  }