simulated_test.go 39 KB

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