github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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/scroll-tech/go-ethereum" 31 "github.com/scroll-tech/go-ethereum/accounts/abi" 32 "github.com/scroll-tech/go-ethereum/accounts/abi/bind" 33 "github.com/scroll-tech/go-ethereum/common" 34 "github.com/scroll-tech/go-ethereum/core" 35 "github.com/scroll-tech/go-ethereum/core/types" 36 "github.com/scroll-tech/go-ethereum/crypto" 37 "github.com/scroll-tech/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.12; 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 SelfDestruct() public { selfdestruct(msg.sender); } 425 function Valid() public {} 426 function Difficulty() public { assert(block.difficulty == 0); } 427 }*/ 428 const contractAbi = "[{\"inputs\":[],\"name\":\"Assert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Difficulty\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"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\":\"SelfDestruct\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Valid\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" 429 const contractBin = "0x608060405234801561001057600080fd5b506101b2806100206000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c8063b9b046f91161005b578063b9b046f9146100a0578063d8b98391146100aa578063dba5e917146100b4578063e09fface146100be5761007d565b806350f6fe341461008257806391b4a0e71461008c578063aa8b1d3014610096575b600080fd5b61008a6100c8565b005b6100946100d8565b005b61009e6100e4565b005b6100a86100e9565b005b6100b26100f3565b005b6100bc610161565b005b6100c661017a565b005b60005b80806001019150506100cb565b600044146100e257fe5b565b600080fd5b60006100f157fe5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081525060200191505060405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff16ff5b56fea26469706673582212201b608395248efd3133d81869fff20e9b287dc3fd8c43c02baf86a41efe9bfae164736f6c634300060c0033" 430 431 key, _ := crypto.GenerateKey() 432 addr := crypto.PubkeyToAddress(key.PublicKey) 433 opts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337)) 434 435 sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000) 436 defer sim.Close() 437 438 parsed, _ := abi.JSON(strings.NewReader(contractAbi)) 439 contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim) 440 sim.Commit() 441 442 var cases = []struct { 443 name string 444 message ethereum.CallMsg 445 expect uint64 446 expectError error 447 expectData interface{} 448 }{ 449 {"plain transfer(valid)", ethereum.CallMsg{ 450 From: addr, 451 To: &addr, 452 Gas: 0, 453 GasPrice: big.NewInt(0), 454 Value: big.NewInt(1), 455 Data: nil, 456 }, params.TxGas, nil, nil}, 457 458 {"plain transfer(invalid)", ethereum.CallMsg{ 459 From: addr, 460 To: &contractAddr, 461 Gas: 0, 462 GasPrice: big.NewInt(0), 463 Value: big.NewInt(1), 464 Data: nil, 465 }, 0, errors.New("execution reverted"), nil}, 466 467 {"Revert", ethereum.CallMsg{ 468 From: addr, 469 To: &contractAddr, 470 Gas: 0, 471 GasPrice: big.NewInt(0), 472 Value: nil, 473 Data: common.Hex2Bytes("d8b98391"), 474 }, 0, errors.New("execution reverted: revert reason"), "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000"}, 475 476 {"PureRevert", ethereum.CallMsg{ 477 From: addr, 478 To: &contractAddr, 479 Gas: 0, 480 GasPrice: big.NewInt(0), 481 Value: nil, 482 Data: common.Hex2Bytes("aa8b1d30"), 483 }, 0, errors.New("execution reverted"), nil}, 484 485 {"OOG", ethereum.CallMsg{ 486 From: addr, 487 To: &contractAddr, 488 Gas: 100000, 489 GasPrice: big.NewInt(0), 490 Value: nil, 491 Data: common.Hex2Bytes("50f6fe34"), 492 }, 0, errors.New("gas required exceeds allowance (100000)"), nil}, 493 494 {"Assert", ethereum.CallMsg{ 495 From: addr, 496 To: &contractAddr, 497 Gas: 100000, 498 GasPrice: big.NewInt(0), 499 Value: nil, 500 Data: common.Hex2Bytes("b9b046f9"), 501 }, 0, errors.New("invalid opcode: INVALID"), nil}, 502 503 {"SelfDestruct", ethereum.CallMsg{ 504 From: addr, 505 To: &contractAddr, 506 Gas: 100000, 507 GasPrice: big.NewInt(0), 508 Value: nil, 509 Data: common.Hex2Bytes("dba5e917"), 510 }, 0, errors.New("invalid opcode: SELFDESTRUCT"), nil}, 511 512 {"Valid", ethereum.CallMsg{ 513 From: addr, 514 To: &contractAddr, 515 Gas: 100000, 516 GasPrice: big.NewInt(0), 517 Value: nil, 518 Data: common.Hex2Bytes("e09fface"), 519 }, 21274, nil, nil}, 520 521 {"Difficulty", ethereum.CallMsg{ 522 From: addr, 523 To: &contractAddr, 524 Gas: 100000, 525 GasPrice: big.NewInt(0), 526 Value: nil, 527 Data: common.Hex2Bytes("91b4a0e7"), 528 }, 21253, nil, nil}, 529 } 530 for _, c := range cases { 531 got, err := sim.EstimateGas(context.Background(), c.message) 532 if c.expectError != nil { 533 if err == nil { 534 t.Fatalf("Expect error, got nil") 535 } 536 if c.expectError.Error() != err.Error() { 537 t.Fatalf("Expect error, want %v, got %v", c.expectError, err) 538 } 539 if c.expectData != nil { 540 if err, ok := err.(*revertError); !ok { 541 t.Fatalf("Expect revert error, got %T", err) 542 } else if !reflect.DeepEqual(err.ErrorData(), c.expectData) { 543 t.Fatalf("Error data mismatch, want %v, got %v", c.expectData, err.ErrorData()) 544 } 545 } 546 continue 547 } 548 if got != c.expect { 549 t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got) 550 } 551 } 552 } 553 554 func TestEstimateGasWithPrice(t *testing.T) { 555 key, _ := crypto.GenerateKey() 556 addr := crypto.PubkeyToAddress(key.PublicKey) 557 558 sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000) 559 defer sim.Close() 560 561 recipient := common.HexToAddress("deadbeef") 562 var cases = []struct { 563 name string 564 message ethereum.CallMsg 565 expect uint64 566 expectError error 567 }{ 568 {"EstimateWithoutPrice", ethereum.CallMsg{ 569 From: addr, 570 To: &recipient, 571 Gas: 0, 572 GasPrice: big.NewInt(0), 573 Value: big.NewInt(100000000000), 574 Data: nil, 575 }, 21000, nil}, 576 577 {"EstimateWithPrice", ethereum.CallMsg{ 578 From: addr, 579 To: &recipient, 580 Gas: 0, 581 GasPrice: big.NewInt(100000000000), 582 Value: big.NewInt(100000000000), 583 Data: nil, 584 }, 21000, nil}, 585 586 {"EstimateWithVeryHighPrice", ethereum.CallMsg{ 587 From: addr, 588 To: &recipient, 589 Gas: 0, 590 GasPrice: big.NewInt(1e14), // gascost = 2.1ether 591 Value: big.NewInt(1e17), // the remaining balance for fee is 2.1ether 592 Data: nil, 593 }, 21000, nil}, 594 595 {"EstimateWithSuperhighPrice", ethereum.CallMsg{ 596 From: addr, 597 To: &recipient, 598 Gas: 0, 599 GasPrice: big.NewInt(2e14), // gascost = 4.2ether 600 Value: big.NewInt(100000000000), 601 Data: nil, 602 }, 21000, errors.New("gas required exceeds allowance (10999)")}, // 10999=(2.2ether-1000wei)/(2e14) 603 604 {"EstimateEIP1559WithHighFees", ethereum.CallMsg{ 605 From: addr, 606 To: &addr, 607 Gas: 0, 608 GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether 609 GasTipCap: big.NewInt(1), 610 Value: big.NewInt(1e17), // the remaining balance for fee is 2.1ether 611 Data: nil, 612 }, params.TxGas, nil}, 613 614 {"EstimateEIP1559WithSuperHighFees", ethereum.CallMsg{ 615 From: addr, 616 To: &addr, 617 Gas: 0, 618 GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether 619 GasTipCap: big.NewInt(1), 620 Value: big.NewInt(1e17 + 1), // the remaining balance for fee is 2.1ether 621 Data: nil, 622 }, params.TxGas, errors.New("gas required exceeds allowance (20999)")}, // 20999=(2.2ether-0.1ether-1wei)/(1e14) 623 } 624 for i, c := range cases { 625 got, err := sim.EstimateGas(context.Background(), c.message) 626 if c.expectError != nil { 627 if err == nil { 628 t.Fatalf("test %d: expect error, got nil", i) 629 } 630 if c.expectError.Error() != err.Error() { 631 t.Fatalf("test %d: expect error, want %v, got %v", i, c.expectError, err) 632 } 633 continue 634 } 635 if c.expectError == nil && err != nil { 636 t.Fatalf("test %d: didn't expect error, got %v", i, err) 637 } 638 if got != c.expect { 639 t.Fatalf("test %d: gas estimation mismatch, want %d, got %d", i, c.expect, got) 640 } 641 } 642 } 643 644 func TestHeaderByHash(t *testing.T) { 645 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 646 647 sim := simTestBackend(testAddr) 648 defer sim.Close() 649 bgCtx := context.Background() 650 651 header, err := sim.HeaderByNumber(bgCtx, nil) 652 if err != nil { 653 t.Errorf("could not get recent block: %v", err) 654 } 655 headerByHash, err := sim.HeaderByHash(bgCtx, header.Hash()) 656 if err != nil { 657 t.Errorf("could not get recent block: %v", err) 658 } 659 660 if header.Hash() != headerByHash.Hash() { 661 t.Errorf("did not get expected block") 662 } 663 } 664 665 func TestHeaderByNumber(t *testing.T) { 666 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 667 668 sim := simTestBackend(testAddr) 669 defer sim.Close() 670 bgCtx := context.Background() 671 672 latestBlockHeader, err := sim.HeaderByNumber(bgCtx, nil) 673 if err != nil { 674 t.Errorf("could not get header for tip of chain: %v", err) 675 } 676 if latestBlockHeader == nil { 677 t.Errorf("received a nil block header") 678 } 679 if latestBlockHeader.Number.Uint64() != uint64(0) { 680 t.Errorf("expected block header number 0, instead got %v", latestBlockHeader.Number.Uint64()) 681 } 682 683 sim.Commit() 684 685 latestBlockHeader, err = sim.HeaderByNumber(bgCtx, nil) 686 if err != nil { 687 t.Errorf("could not get header for blockheight of 1: %v", err) 688 } 689 690 blockHeader, err := sim.HeaderByNumber(bgCtx, big.NewInt(1)) 691 if err != nil { 692 t.Errorf("could not get header for blockheight of 1: %v", err) 693 } 694 695 if blockHeader.Hash() != latestBlockHeader.Hash() { 696 t.Errorf("block header and latest block header are not the same") 697 } 698 if blockHeader.Number.Int64() != int64(1) { 699 t.Errorf("did not get blockheader for block 1. instead got block %v", blockHeader.Number.Int64()) 700 } 701 702 block, err := sim.BlockByNumber(bgCtx, big.NewInt(1)) 703 if err != nil { 704 t.Errorf("could not get block for blockheight of 1: %v", err) 705 } 706 707 if block.Hash() != blockHeader.Hash() { 708 t.Errorf("block hash and block header hash do not match. expected %v, got %v", block.Hash(), blockHeader.Hash()) 709 } 710 } 711 712 func TestTransactionCount(t *testing.T) { 713 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 714 715 sim := simTestBackend(testAddr) 716 defer sim.Close() 717 bgCtx := context.Background() 718 currentBlock, err := sim.BlockByNumber(bgCtx, nil) 719 if err != nil || currentBlock == nil { 720 t.Error("could not get current block") 721 } 722 723 count, err := sim.TransactionCount(bgCtx, currentBlock.Hash()) 724 if err != nil { 725 t.Error("could not get current block's transaction count") 726 } 727 728 if count != 0 { 729 t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count) 730 } 731 // create a signed transaction to send 732 head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough 733 gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) 734 735 tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 736 signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey) 737 if err != nil { 738 t.Errorf("could not sign tx: %v", err) 739 } 740 741 // send tx to simulated backend 742 err = sim.SendTransaction(bgCtx, signedTx) 743 if err != nil { 744 t.Errorf("could not add tx to pending block: %v", err) 745 } 746 747 sim.Commit() 748 749 lastBlock, err := sim.BlockByNumber(bgCtx, nil) 750 if err != nil { 751 t.Errorf("could not get header for tip of chain: %v", err) 752 } 753 754 count, err = sim.TransactionCount(bgCtx, lastBlock.Hash()) 755 if err != nil { 756 t.Error("could not get current block's transaction count") 757 } 758 759 if count != 1 { 760 t.Errorf("expected transaction count of %v does not match actual count of %v", 1, count) 761 } 762 } 763 764 func TestTransactionInBlock(t *testing.T) { 765 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 766 767 sim := simTestBackend(testAddr) 768 defer sim.Close() 769 bgCtx := context.Background() 770 771 transaction, err := sim.TransactionInBlock(bgCtx, sim.pendingBlock.Hash(), uint(0)) 772 if err == nil && err != errTransactionDoesNotExist { 773 t.Errorf("expected a transaction does not exist error to be received but received %v", err) 774 } 775 if transaction != nil { 776 t.Errorf("expected transaction to be nil but received %v", transaction) 777 } 778 779 // expect pending nonce to be 0 since account has not been used 780 pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr) 781 if err != nil { 782 t.Errorf("did not get the pending nonce: %v", err) 783 } 784 785 if pendingNonce != uint64(0) { 786 t.Errorf("expected pending nonce of 0 got %v", pendingNonce) 787 } 788 // create a signed transaction to send 789 head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough 790 gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) 791 792 tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 793 signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey) 794 if err != nil { 795 t.Errorf("could not sign tx: %v", err) 796 } 797 798 // send tx to simulated backend 799 err = sim.SendTransaction(bgCtx, signedTx) 800 if err != nil { 801 t.Errorf("could not add tx to pending block: %v", err) 802 } 803 804 sim.Commit() 805 806 lastBlock, err := sim.BlockByNumber(bgCtx, nil) 807 if err != nil { 808 t.Errorf("could not get header for tip of chain: %v", err) 809 } 810 811 transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(1)) 812 if err == nil && err != errTransactionDoesNotExist { 813 t.Errorf("expected a transaction does not exist error to be received but received %v", err) 814 } 815 if transaction != nil { 816 t.Errorf("expected transaction to be nil but received %v", transaction) 817 } 818 819 transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(0)) 820 if err != nil { 821 t.Errorf("could not get transaction in the lastest block with hash %v: %v", lastBlock.Hash().String(), err) 822 } 823 824 if signedTx.Hash().String() != transaction.Hash().String() { 825 t.Errorf("received transaction that did not match the sent transaction. expected hash %v, got hash %v", signedTx.Hash().String(), transaction.Hash().String()) 826 } 827 } 828 829 func TestPendingNonceAt(t *testing.T) { 830 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 831 832 sim := simTestBackend(testAddr) 833 defer sim.Close() 834 bgCtx := context.Background() 835 836 // expect pending nonce to be 0 since account has not been used 837 pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr) 838 if err != nil { 839 t.Errorf("did not get the pending nonce: %v", err) 840 } 841 842 if pendingNonce != uint64(0) { 843 t.Errorf("expected pending nonce of 0 got %v", pendingNonce) 844 } 845 846 // create a signed transaction to send 847 head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough 848 gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) 849 850 tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 851 signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey) 852 if err != nil { 853 t.Errorf("could not sign tx: %v", err) 854 } 855 856 // send tx to simulated backend 857 err = sim.SendTransaction(bgCtx, signedTx) 858 if err != nil { 859 t.Errorf("could not add tx to pending block: %v", err) 860 } 861 862 // expect pending nonce to be 1 since account has submitted one transaction 863 pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr) 864 if err != nil { 865 t.Errorf("did not get the pending nonce: %v", err) 866 } 867 868 if pendingNonce != uint64(1) { 869 t.Errorf("expected pending nonce of 1 got %v", pendingNonce) 870 } 871 872 // make a new transaction with a nonce of 1 873 tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 874 signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey) 875 if err != nil { 876 t.Errorf("could not sign tx: %v", err) 877 } 878 err = sim.SendTransaction(bgCtx, signedTx) 879 if err != nil { 880 t.Errorf("could not send tx: %v", err) 881 } 882 883 // expect pending nonce to be 2 since account now has two transactions 884 pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr) 885 if err != nil { 886 t.Errorf("did not get the pending nonce: %v", err) 887 } 888 889 if pendingNonce != uint64(2) { 890 t.Errorf("expected pending nonce of 2 got %v", pendingNonce) 891 } 892 } 893 894 func TestTransactionReceipt(t *testing.T) { 895 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 896 897 sim := simTestBackend(testAddr) 898 defer sim.Close() 899 bgCtx := context.Background() 900 901 // create a signed transaction to send 902 head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough 903 gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) 904 905 tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 906 signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey) 907 if err != nil { 908 t.Errorf("could not sign tx: %v", err) 909 } 910 911 // send tx to simulated backend 912 err = sim.SendTransaction(bgCtx, signedTx) 913 if err != nil { 914 t.Errorf("could not add tx to pending block: %v", err) 915 } 916 sim.Commit() 917 918 receipt, err := sim.TransactionReceipt(bgCtx, signedTx.Hash()) 919 if err != nil { 920 t.Errorf("could not get transaction receipt: %v", err) 921 } 922 923 if receipt.ContractAddress != testAddr && receipt.TxHash != signedTx.Hash() { 924 t.Errorf("received receipt is not correct: %v", receipt) 925 } 926 } 927 928 func TestSuggestGasPrice(t *testing.T) { 929 sim := NewSimulatedBackend( 930 core.GenesisAlloc{}, 931 10000000, 932 ) 933 defer sim.Close() 934 bgCtx := context.Background() 935 gasPrice, err := sim.SuggestGasPrice(bgCtx) 936 if err != nil { 937 t.Errorf("could not get gas price: %v", err) 938 } 939 if gasPrice.Uint64() != sim.pendingBlock.Header().BaseFee.Uint64() { 940 t.Errorf("gas price was not expected value of %v. actual: %v", sim.pendingBlock.Header().BaseFee.Uint64(), gasPrice.Uint64()) 941 } 942 } 943 944 func TestPendingCodeAt(t *testing.T) { 945 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 946 sim := simTestBackend(testAddr) 947 defer sim.Close() 948 bgCtx := context.Background() 949 code, err := sim.CodeAt(bgCtx, testAddr, nil) 950 if err != nil { 951 t.Errorf("could not get code at test addr: %v", err) 952 } 953 if len(code) != 0 { 954 t.Errorf("got code for account that does not have contract code") 955 } 956 957 parsed, err := abi.JSON(strings.NewReader(abiJSON)) 958 if err != nil { 959 t.Errorf("could not get code at test addr: %v", err) 960 } 961 auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337)) 962 contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim) 963 if err != nil { 964 t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract) 965 } 966 967 code, err = sim.PendingCodeAt(bgCtx, contractAddr) 968 if err != nil { 969 t.Errorf("could not get code at test addr: %v", err) 970 } 971 if len(code) == 0 { 972 t.Errorf("did not get code for account that has contract code") 973 } 974 // ensure code received equals code deployed 975 if !bytes.Equal(code, common.FromHex(deployedCode)) { 976 t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code) 977 } 978 } 979 980 func TestCodeAt(t *testing.T) { 981 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 982 sim := simTestBackend(testAddr) 983 defer sim.Close() 984 bgCtx := context.Background() 985 code, err := sim.CodeAt(bgCtx, testAddr, nil) 986 if err != nil { 987 t.Errorf("could not get code at test addr: %v", err) 988 } 989 if len(code) != 0 { 990 t.Errorf("got code for account that does not have contract code") 991 } 992 993 parsed, err := abi.JSON(strings.NewReader(abiJSON)) 994 if err != nil { 995 t.Errorf("could not get code at test addr: %v", err) 996 } 997 auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337)) 998 contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim) 999 if err != nil { 1000 t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract) 1001 } 1002 1003 sim.Commit() 1004 code, err = sim.CodeAt(bgCtx, contractAddr, nil) 1005 if err != nil { 1006 t.Errorf("could not get code at test addr: %v", err) 1007 } 1008 if len(code) == 0 { 1009 t.Errorf("did not get code for account that has contract code") 1010 } 1011 // ensure code received equals code deployed 1012 if !bytes.Equal(code, common.FromHex(deployedCode)) { 1013 t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code) 1014 } 1015 } 1016 1017 // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: 1018 // receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} 1019 func TestPendingAndCallContract(t *testing.T) { 1020 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 1021 sim := simTestBackend(testAddr) 1022 defer sim.Close() 1023 bgCtx := context.Background() 1024 1025 parsed, err := abi.JSON(strings.NewReader(abiJSON)) 1026 if err != nil { 1027 t.Errorf("could not get code at test addr: %v", err) 1028 } 1029 contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337)) 1030 addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(abiBin), sim) 1031 if err != nil { 1032 t.Errorf("could not deploy contract: %v", err) 1033 } 1034 1035 input, err := parsed.Pack("receive", []byte("X")) 1036 if err != nil { 1037 t.Errorf("could not pack receive function on contract: %v", err) 1038 } 1039 1040 // make sure you can call the contract in pending state 1041 res, err := sim.PendingCallContract(bgCtx, ethereum.CallMsg{ 1042 From: testAddr, 1043 To: &addr, 1044 Data: input, 1045 }) 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 // while comparing against the byte array is more exact, also compare against the human readable string for readability 1054 if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") { 1055 t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res)) 1056 } 1057 1058 sim.Commit() 1059 1060 // make sure you can call the contract 1061 res, err = sim.CallContract(bgCtx, ethereum.CallMsg{ 1062 From: testAddr, 1063 To: &addr, 1064 Data: input, 1065 }, nil) 1066 if err != nil { 1067 t.Errorf("could not call receive method on contract: %v", err) 1068 } 1069 if len(res) == 0 { 1070 t.Errorf("result of contract call was empty: %v", res) 1071 } 1072 1073 if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") { 1074 t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res)) 1075 } 1076 } 1077 1078 // This test is based on the following contract: 1079 /* 1080 contract Reverter { 1081 function revertString() public pure{ 1082 require(false, "some error"); 1083 } 1084 function revertNoString() public pure { 1085 require(false, ""); 1086 } 1087 function revertASM() public pure { 1088 assembly { 1089 revert(0x0, 0x0) 1090 } 1091 } 1092 function noRevert() public pure { 1093 assembly { 1094 // Assembles something that looks like require(false, "some error") but is not reverted 1095 mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) 1096 mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020) 1097 mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a) 1098 mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000) 1099 return(0x0, 0x64) 1100 } 1101 } 1102 }*/ 1103 func TestCallContractRevert(t *testing.T) { 1104 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 1105 sim := simTestBackend(testAddr) 1106 defer sim.Close() 1107 bgCtx := context.Background() 1108 1109 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"}]` 1110 reverterBin := "608060405234801561001057600080fd5b506101d3806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80634b409e01146100515780639b340e361461005b5780639bd6103714610065578063b7246fc11461006f575b600080fd5b610059610079565b005b6100636100ca565b005b61006d6100cf565b005b610077610145565b005b60006100c8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526000815260200160200191505060405180910390fd5b565b600080fd5b6000610143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f736f6d65206572726f720000000000000000000000000000000000000000000081525060200191505060405180910390fd5b565b7f08c379a0000000000000000000000000000000000000000000000000000000006000526020600452600a6024527f736f6d65206572726f720000000000000000000000000000000000000000000060445260646000f3fea2646970667358221220cdd8af0609ec4996b7360c7c780bad5c735740c64b1fffc3445aa12d37f07cb164736f6c63430006070033" 1111 1112 parsed, err := abi.JSON(strings.NewReader(reverterABI)) 1113 if err != nil { 1114 t.Errorf("could not get code at test addr: %v", err) 1115 } 1116 contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337)) 1117 addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(reverterBin), sim) 1118 if err != nil { 1119 t.Errorf("could not deploy contract: %v", err) 1120 } 1121 1122 inputs := make(map[string]interface{}, 3) 1123 inputs["revertASM"] = nil 1124 inputs["revertNoString"] = "" 1125 inputs["revertString"] = "some error" 1126 1127 call := make([]func([]byte) ([]byte, error), 2) 1128 call[0] = func(input []byte) ([]byte, error) { 1129 return sim.PendingCallContract(bgCtx, ethereum.CallMsg{ 1130 From: testAddr, 1131 To: &addr, 1132 Data: input, 1133 }) 1134 } 1135 call[1] = func(input []byte) ([]byte, error) { 1136 return sim.CallContract(bgCtx, ethereum.CallMsg{ 1137 From: testAddr, 1138 To: &addr, 1139 Data: input, 1140 }, nil) 1141 } 1142 1143 // Run pending calls then commit 1144 for _, cl := range call { 1145 for key, val := range inputs { 1146 input, err := parsed.Pack(key) 1147 if err != nil { 1148 t.Errorf("could not pack %v function on contract: %v", key, err) 1149 } 1150 1151 res, err := cl(input) 1152 if err == nil { 1153 t.Errorf("call to %v was not reverted", key) 1154 } 1155 if res != nil { 1156 t.Errorf("result from %v was not nil: %v", key, res) 1157 } 1158 if val != nil { 1159 rerr, ok := err.(*revertError) 1160 if !ok { 1161 t.Errorf("expect revert error") 1162 } 1163 if rerr.Error() != "execution reverted: "+val.(string) { 1164 t.Errorf("error was malformed: got %v want %v", rerr.Error(), val) 1165 } 1166 } else { 1167 // revert(0x0,0x0) 1168 if err.Error() != "execution reverted" { 1169 t.Errorf("error was malformed: got %v want %v", err, "execution reverted") 1170 } 1171 } 1172 } 1173 input, err := parsed.Pack("noRevert") 1174 if err != nil { 1175 t.Errorf("could not pack noRevert function on contract: %v", err) 1176 } 1177 res, err := cl(input) 1178 if err != nil { 1179 t.Error("call to noRevert was reverted") 1180 } 1181 if res == nil { 1182 t.Errorf("result from noRevert was nil") 1183 } 1184 sim.Commit() 1185 } 1186 } 1187 1188 // TestFork check that the chain length after a reorg is correct. 1189 // Steps: 1190 // 1. Save the current block which will serve as parent for the fork. 1191 // 2. Mine n blocks with n ∈ [0, 20]. 1192 // 3. Assert that the chain length is n. 1193 // 4. Fork by using the parent block as ancestor. 1194 // 5. Mine n+1 blocks which should trigger a reorg. 1195 // 6. Assert that the chain length is n+1. 1196 // Since Commit() was called 2n+1 times in total, 1197 // having a chain length of just n+1 means that a reorg occurred. 1198 func TestFork(t *testing.T) { 1199 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 1200 sim := simTestBackend(testAddr) 1201 defer sim.Close() 1202 // 1. 1203 parent := sim.blockchain.CurrentBlock() 1204 // 2. 1205 n := int(rand.Int31n(21)) 1206 for i := 0; i < n; i++ { 1207 sim.Commit() 1208 } 1209 // 3. 1210 if sim.blockchain.CurrentBlock().NumberU64() != uint64(n) { 1211 t.Error("wrong chain length") 1212 } 1213 // 4. 1214 sim.Fork(context.Background(), parent.Hash()) 1215 // 5. 1216 for i := 0; i < n+1; i++ { 1217 sim.Commit() 1218 } 1219 // 6. 1220 if sim.blockchain.CurrentBlock().NumberU64() != uint64(n+1) { 1221 t.Error("wrong chain length") 1222 } 1223 } 1224 1225 /* 1226 Example contract to test event emission: 1227 1228 pragma solidity >=0.7.0 <0.9.0; 1229 contract Callable { 1230 event Called(); 1231 function Call() public { emit Called(); } 1232 } 1233 */ 1234 const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" 1235 1236 const callableBin = "6080604052348015600f57600080fd5b5060998061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806334e2292114602d575b600080fd5b60336035565b005b7f81fab7a4a0aa961db47eefc81f143a5220e8c8495260dd65b1356f1d19d3c7b860405160405180910390a156fea2646970667358221220029436d24f3ac598ceca41d4d712e13ced6d70727f4cdc580667de66d2f51d8b64736f6c63430008010033" 1237 1238 // TestForkLogsReborn check that the simulated reorgs 1239 // correctly remove and reborn logs. 1240 // Steps: 1241 // 1. Deploy the Callable contract. 1242 // 2. Set up an event subscription. 1243 // 3. Save the current block which will serve as parent for the fork. 1244 // 4. Send a transaction. 1245 // 5. Check that the event was included. 1246 // 6. Fork by using the parent block as ancestor. 1247 // 7. Mine two blocks to trigger a reorg. 1248 // 8. Check that the event was removed. 1249 // 9. Re-send the transaction and mine a block. 1250 // 10. Check that the event was reborn. 1251 func TestForkLogsReborn(t *testing.T) { 1252 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 1253 sim := simTestBackend(testAddr) 1254 defer sim.Close() 1255 // 1. 1256 parsed, _ := abi.JSON(strings.NewReader(callableAbi)) 1257 auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337)) 1258 _, _, contract, err := bind.DeployContract(auth, parsed, common.FromHex(callableBin), sim) 1259 if err != nil { 1260 t.Errorf("deploying contract: %v", err) 1261 } 1262 sim.Commit() 1263 // 2. 1264 logs, sub, err := contract.WatchLogs(nil, "Called") 1265 if err != nil { 1266 t.Errorf("watching logs: %v", err) 1267 } 1268 defer sub.Unsubscribe() 1269 // 3. 1270 parent := sim.blockchain.CurrentBlock() 1271 // 4. 1272 tx, err := contract.Transact(auth, "Call") 1273 if err != nil { 1274 t.Errorf("transacting: %v", err) 1275 } 1276 sim.Commit() 1277 // 5. 1278 log := <-logs 1279 if log.TxHash != tx.Hash() { 1280 t.Error("wrong event tx hash") 1281 } 1282 if log.Removed { 1283 t.Error("Event should be included") 1284 } 1285 // 6. 1286 if err := sim.Fork(context.Background(), parent.Hash()); err != nil { 1287 t.Errorf("forking: %v", err) 1288 } 1289 // 7. 1290 sim.Commit() 1291 sim.Commit() 1292 // 8. 1293 log = <-logs 1294 if log.TxHash != tx.Hash() { 1295 t.Error("wrong event tx hash") 1296 } 1297 if !log.Removed { 1298 t.Error("Event should be removed") 1299 } 1300 // 9. 1301 if err := sim.SendTransaction(context.Background(), tx); err != nil { 1302 t.Errorf("sending transaction: %v", err) 1303 } 1304 sim.Commit() 1305 // 10. 1306 log = <-logs 1307 if log.TxHash != tx.Hash() { 1308 t.Error("wrong event tx hash") 1309 } 1310 if log.Removed { 1311 t.Error("Event should be included") 1312 } 1313 } 1314 1315 // TestForkResendTx checks that re-sending a TX after a fork 1316 // is possible and does not cause a "nonce mismatch" panic. 1317 // Steps: 1318 // 1. Save the current block which will serve as parent for the fork. 1319 // 2. Send a transaction. 1320 // 3. Check that the TX is included in block 1. 1321 // 4. Fork by using the parent block as ancestor. 1322 // 5. Mine a block, Re-send the transaction and mine another one. 1323 // 6. Check that the TX is now included in block 2. 1324 func TestForkResendTx(t *testing.T) { 1325 testAddr := crypto.PubkeyToAddress(testKey.PublicKey) 1326 sim := simTestBackend(testAddr) 1327 defer sim.Close() 1328 // 1. 1329 parent := sim.blockchain.CurrentBlock() 1330 // 2. 1331 head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough 1332 gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) 1333 1334 _tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) 1335 tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey) 1336 sim.SendTransaction(context.Background(), tx) 1337 sim.Commit() 1338 // 3. 1339 receipt, _ := sim.TransactionReceipt(context.Background(), tx.Hash()) 1340 if h := receipt.BlockNumber.Uint64(); h != 1 { 1341 t.Errorf("TX included in wrong block: %d", h) 1342 } 1343 // 4. 1344 if err := sim.Fork(context.Background(), parent.Hash()); err != nil { 1345 t.Errorf("forking: %v", err) 1346 } 1347 // 5. 1348 sim.Commit() 1349 if err := sim.SendTransaction(context.Background(), tx); err != nil { 1350 t.Errorf("sending transaction: %v", err) 1351 } 1352 sim.Commit() 1353 // 6. 1354 receipt, _ = sim.TransactionReceipt(context.Background(), tx.Hash()) 1355 if h := receipt.BlockNumber.Uint64(); h != 2 { 1356 t.Errorf("TX included in wrong block: %d", h) 1357 } 1358 }