simulated_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. "strings"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum"
  26. "github.com/ethereum/go-ethereum/accounts/abi"
  27. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. func TestSimulatedBackend(t *testing.T) {
  35. var gasLimit uint64 = 8000029
  36. key, _ := crypto.GenerateKey() // nolint: gosec
  37. auth := bind.NewKeyedTransactor(key)
  38. genAlloc := make(core.GenesisAlloc)
  39. genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)}
  40. sim := NewSimulatedBackend(genAlloc, gasLimit)
  41. defer sim.Close()
  42. // should return an error if the tx is not found
  43. txHash := common.HexToHash("2")
  44. _, isPending, err := sim.TransactionByHash(context.Background(), txHash)
  45. if isPending {
  46. t.Fatal("transaction should not be pending")
  47. }
  48. if err != ethereum.NotFound {
  49. t.Fatalf("err should be `ethereum.NotFound` but received %v", err)
  50. }
  51. // generate a transaction and confirm you can retrieve it
  52. code := `6060604052600a8060106000396000f360606040526008565b00`
  53. var gas uint64 = 3000000
  54. tx := types.NewContractCreation(0, big.NewInt(0), gas, big.NewInt(1), common.FromHex(code))
  55. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key)
  56. err = sim.SendTransaction(context.Background(), tx)
  57. if err != nil {
  58. t.Fatal("error sending transaction")
  59. }
  60. txHash = tx.Hash()
  61. _, isPending, err = sim.TransactionByHash(context.Background(), txHash)
  62. if err != nil {
  63. t.Fatalf("error getting transaction with hash: %v", txHash.String())
  64. }
  65. if !isPending {
  66. t.Fatal("transaction should have pending status")
  67. }
  68. sim.Commit()
  69. _, isPending, err = sim.TransactionByHash(context.Background(), txHash)
  70. if err != nil {
  71. t.Fatalf("error getting transaction with hash: %v", txHash.String())
  72. }
  73. if isPending {
  74. t.Fatal("transaction should not have pending status")
  75. }
  76. }
  77. var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  78. // the following is based on this contract:
  79. // contract T {
  80. // event received(address sender, uint amount, bytes memo);
  81. // event receivedAddr(address sender);
  82. //
  83. // function receive(bytes calldata memo) external payable returns (string memory res) {
  84. // emit received(msg.sender, msg.value, memo);
  85. // emit receivedAddr(msg.sender);
  86. // return "hello world";
  87. // }
  88. // }
  89. 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" } ]`
  90. const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
  91. const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
  92. // expected return value contains "hello world"
  93. 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}
  94. func TestNewSimulatedBackend(t *testing.T) {
  95. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  96. expectedBal := big.NewInt(10000000000)
  97. sim := NewSimulatedBackend(
  98. core.GenesisAlloc{
  99. testAddr: {Balance: expectedBal},
  100. }, 10000000,
  101. )
  102. defer sim.Close()
  103. if sim.config != params.AllEthashProtocolChanges {
  104. t.Errorf("expected sim config to equal params.AllEthashProtocolChanges, got %v", sim.config)
  105. }
  106. if sim.blockchain.Config() != params.AllEthashProtocolChanges {
  107. t.Errorf("expected sim blockchain config to equal params.AllEthashProtocolChanges, got %v", sim.config)
  108. }
  109. statedb, _ := sim.blockchain.State()
  110. bal := statedb.GetBalance(testAddr)
  111. if bal.Cmp(expectedBal) != 0 {
  112. t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
  113. }
  114. }
  115. func TestSimulatedBackend_AdjustTime(t *testing.T) {
  116. sim := NewSimulatedBackend(
  117. core.GenesisAlloc{}, 10000000,
  118. )
  119. defer sim.Close()
  120. prevTime := sim.pendingBlock.Time()
  121. err := sim.AdjustTime(time.Second)
  122. if err != nil {
  123. t.Error(err)
  124. }
  125. newTime := sim.pendingBlock.Time()
  126. if newTime-prevTime != uint64(time.Second.Seconds()) {
  127. t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime)
  128. }
  129. }
  130. func TestSimulatedBackend_BalanceAt(t *testing.T) {
  131. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  132. expectedBal := big.NewInt(10000000000)
  133. sim := NewSimulatedBackend(
  134. core.GenesisAlloc{
  135. testAddr: {Balance: expectedBal},
  136. }, 10000000,
  137. )
  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 := NewSimulatedBackend(
  199. core.GenesisAlloc{
  200. testAddr: {Balance: big.NewInt(10000000000)},
  201. }, 10000000,
  202. )
  203. defer sim.Close()
  204. bgCtx := context.Background()
  205. nonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(0))
  206. if err != nil {
  207. t.Errorf("could not get nonce for test addr: %v", err)
  208. }
  209. if nonce != uint64(0) {
  210. t.Errorf("received incorrect nonce. expected 0, got %v", nonce)
  211. }
  212. // create a signed transaction to send
  213. tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  214. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  215. if err != nil {
  216. t.Errorf("could not sign tx: %v", err)
  217. }
  218. // send tx to simulated backend
  219. err = sim.SendTransaction(bgCtx, signedTx)
  220. if err != nil {
  221. t.Errorf("could not add tx to pending block: %v", err)
  222. }
  223. sim.Commit()
  224. newNonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
  225. if err != nil {
  226. t.Errorf("could not get nonce for test addr: %v", err)
  227. }
  228. if newNonce != nonce+uint64(1) {
  229. t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
  230. }
  231. // create some more blocks
  232. sim.Commit()
  233. // Check that we can get data for an older block/state
  234. newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
  235. if err != nil {
  236. t.Fatalf("could not get nonce for test addr: %v", err)
  237. }
  238. if newNonce != nonce+uint64(1) {
  239. t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
  240. }
  241. }
  242. func TestSimulatedBackend_SendTransaction(t *testing.T) {
  243. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  244. sim := NewSimulatedBackend(
  245. core.GenesisAlloc{
  246. testAddr: {Balance: big.NewInt(10000000000)},
  247. }, 10000000,
  248. )
  249. defer sim.Close()
  250. bgCtx := context.Background()
  251. // create a signed transaction to send
  252. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  253. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  254. if err != nil {
  255. t.Errorf("could not sign tx: %v", err)
  256. }
  257. // send tx to simulated backend
  258. err = sim.SendTransaction(bgCtx, signedTx)
  259. if err != nil {
  260. t.Errorf("could not add tx to pending block: %v", err)
  261. }
  262. sim.Commit()
  263. block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
  264. if err != nil {
  265. t.Errorf("could not get block at height 1: %v", err)
  266. }
  267. if signedTx.Hash() != block.Transactions()[0].Hash() {
  268. t.Errorf("did not commit sent transaction. expected hash %v got hash %v", block.Transactions()[0].Hash(), signedTx.Hash())
  269. }
  270. }
  271. func TestSimulatedBackend_TransactionByHash(t *testing.T) {
  272. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  273. sim := NewSimulatedBackend(
  274. core.GenesisAlloc{
  275. testAddr: {Balance: big.NewInt(10000000000)},
  276. }, 10000000,
  277. )
  278. defer sim.Close()
  279. bgCtx := context.Background()
  280. // create a signed transaction to send
  281. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  282. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  283. if err != nil {
  284. t.Errorf("could not sign tx: %v", err)
  285. }
  286. // send tx to simulated backend
  287. err = sim.SendTransaction(bgCtx, signedTx)
  288. if err != nil {
  289. t.Errorf("could not add tx to pending block: %v", err)
  290. }
  291. // ensure tx is committed pending
  292. receivedTx, pending, err := sim.TransactionByHash(bgCtx, signedTx.Hash())
  293. if err != nil {
  294. t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
  295. }
  296. if !pending {
  297. t.Errorf("expected transaction to be in pending state")
  298. }
  299. if receivedTx.Hash() != signedTx.Hash() {
  300. t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
  301. }
  302. sim.Commit()
  303. // ensure tx is not and committed pending
  304. receivedTx, pending, err = sim.TransactionByHash(bgCtx, signedTx.Hash())
  305. if err != nil {
  306. t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
  307. }
  308. if pending {
  309. t.Errorf("expected transaction to not be in pending state")
  310. }
  311. if receivedTx.Hash() != signedTx.Hash() {
  312. t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
  313. }
  314. }
  315. func TestSimulatedBackend_EstimateGas(t *testing.T) {
  316. /*
  317. pragma solidity ^0.6.4;
  318. contract GasEstimation {
  319. function PureRevert() public { revert(); }
  320. function Revert() public { revert("revert reason");}
  321. function OOG() public { for (uint i = 0; ; i++) {}}
  322. function Assert() public { assert(false);}
  323. function Valid() public {}
  324. }*/
  325. 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\"}]"
  326. const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
  327. key, _ := crypto.GenerateKey()
  328. addr := crypto.PubkeyToAddress(key.PublicKey)
  329. opts := bind.NewKeyedTransactor(key)
  330. sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000)
  331. defer sim.Close()
  332. parsed, _ := abi.JSON(strings.NewReader(contractAbi))
  333. contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim)
  334. sim.Commit()
  335. var cases = []struct {
  336. name string
  337. message ethereum.CallMsg
  338. expect uint64
  339. expectError error
  340. }{
  341. {"plain transfer(valid)", ethereum.CallMsg{
  342. From: addr,
  343. To: &addr,
  344. Gas: 0,
  345. GasPrice: big.NewInt(0),
  346. Value: big.NewInt(1),
  347. Data: nil,
  348. }, params.TxGas, nil},
  349. {"plain transfer(invalid)", ethereum.CallMsg{
  350. From: addr,
  351. To: &contractAddr,
  352. Gas: 0,
  353. GasPrice: big.NewInt(0),
  354. Value: big.NewInt(1),
  355. Data: nil,
  356. }, 0, errors.New("always failing transaction (execution reverted)")},
  357. {"Revert", ethereum.CallMsg{
  358. From: addr,
  359. To: &contractAddr,
  360. Gas: 0,
  361. GasPrice: big.NewInt(0),
  362. Value: nil,
  363. Data: common.Hex2Bytes("d8b98391"),
  364. }, 0, errors.New("always failing transaction (execution reverted) (revert reason)")},
  365. {"PureRevert", ethereum.CallMsg{
  366. From: addr,
  367. To: &contractAddr,
  368. Gas: 0,
  369. GasPrice: big.NewInt(0),
  370. Value: nil,
  371. Data: common.Hex2Bytes("aa8b1d30"),
  372. }, 0, errors.New("always failing transaction (execution reverted)")},
  373. {"OOG", ethereum.CallMsg{
  374. From: addr,
  375. To: &contractAddr,
  376. Gas: 100000,
  377. GasPrice: big.NewInt(0),
  378. Value: nil,
  379. Data: common.Hex2Bytes("50f6fe34"),
  380. }, 0, errors.New("gas required exceeds allowance (100000)")},
  381. {"Assert", ethereum.CallMsg{
  382. From: addr,
  383. To: &contractAddr,
  384. Gas: 100000,
  385. GasPrice: big.NewInt(0),
  386. Value: nil,
  387. Data: common.Hex2Bytes("b9b046f9"),
  388. }, 0, errors.New("always failing transaction (invalid opcode: opcode 0xfe not defined)")},
  389. {"Valid", ethereum.CallMsg{
  390. From: addr,
  391. To: &contractAddr,
  392. Gas: 100000,
  393. GasPrice: big.NewInt(0),
  394. Value: nil,
  395. Data: common.Hex2Bytes("e09fface"),
  396. }, 21275, nil},
  397. }
  398. for _, c := range cases {
  399. got, err := sim.EstimateGas(context.Background(), c.message)
  400. if c.expectError != nil {
  401. if err == nil {
  402. t.Fatalf("Expect error, got nil")
  403. }
  404. if c.expectError.Error() != err.Error() {
  405. t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
  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 := NewSimulatedBackend(
  478. core.GenesisAlloc{
  479. testAddr: {Balance: big.NewInt(10000000000)},
  480. }, 10000000,
  481. )
  482. defer sim.Close()
  483. bgCtx := context.Background()
  484. header, err := sim.HeaderByNumber(bgCtx, nil)
  485. if err != nil {
  486. t.Errorf("could not get recent block: %v", err)
  487. }
  488. headerByHash, err := sim.HeaderByHash(bgCtx, header.Hash())
  489. if err != nil {
  490. t.Errorf("could not get recent block: %v", err)
  491. }
  492. if header.Hash() != headerByHash.Hash() {
  493. t.Errorf("did not get expected block")
  494. }
  495. }
  496. func TestSimulatedBackend_HeaderByNumber(t *testing.T) {
  497. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  498. sim := NewSimulatedBackend(
  499. core.GenesisAlloc{
  500. testAddr: {Balance: big.NewInt(10000000000)},
  501. }, 10000000,
  502. )
  503. defer sim.Close()
  504. bgCtx := context.Background()
  505. latestBlockHeader, err := sim.HeaderByNumber(bgCtx, nil)
  506. if err != nil {
  507. t.Errorf("could not get header for tip of chain: %v", err)
  508. }
  509. if latestBlockHeader == nil {
  510. t.Errorf("received a nil block header")
  511. }
  512. if latestBlockHeader.Number.Uint64() != uint64(0) {
  513. t.Errorf("expected block header number 0, instead got %v", latestBlockHeader.Number.Uint64())
  514. }
  515. sim.Commit()
  516. latestBlockHeader, err = sim.HeaderByNumber(bgCtx, nil)
  517. if err != nil {
  518. t.Errorf("could not get header for blockheight of 1: %v", err)
  519. }
  520. blockHeader, err := sim.HeaderByNumber(bgCtx, big.NewInt(1))
  521. if err != nil {
  522. t.Errorf("could not get header for blockheight of 1: %v", err)
  523. }
  524. if blockHeader.Hash() != latestBlockHeader.Hash() {
  525. t.Errorf("block header and latest block header are not the same")
  526. }
  527. if blockHeader.Number.Int64() != int64(1) {
  528. t.Errorf("did not get blockheader for block 1. instead got block %v", blockHeader.Number.Int64())
  529. }
  530. block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
  531. if err != nil {
  532. t.Errorf("could not get block for blockheight of 1: %v", err)
  533. }
  534. if block.Hash() != blockHeader.Hash() {
  535. t.Errorf("block hash and block header hash do not match. expected %v, got %v", block.Hash(), blockHeader.Hash())
  536. }
  537. }
  538. func TestSimulatedBackend_TransactionCount(t *testing.T) {
  539. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  540. sim := NewSimulatedBackend(
  541. core.GenesisAlloc{
  542. testAddr: {Balance: big.NewInt(10000000000)},
  543. }, 10000000,
  544. )
  545. defer sim.Close()
  546. bgCtx := context.Background()
  547. currentBlock, err := sim.BlockByNumber(bgCtx, nil)
  548. if err != nil || currentBlock == nil {
  549. t.Error("could not get current block")
  550. }
  551. count, err := sim.TransactionCount(bgCtx, currentBlock.Hash())
  552. if err != nil {
  553. t.Error("could not get current block's transaction count")
  554. }
  555. if count != 0 {
  556. t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count)
  557. }
  558. // create a signed transaction to send
  559. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  560. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  561. if err != nil {
  562. t.Errorf("could not sign tx: %v", err)
  563. }
  564. // send tx to simulated backend
  565. err = sim.SendTransaction(bgCtx, signedTx)
  566. if err != nil {
  567. t.Errorf("could not add tx to pending block: %v", err)
  568. }
  569. sim.Commit()
  570. lastBlock, err := sim.BlockByNumber(bgCtx, nil)
  571. if err != nil {
  572. t.Errorf("could not get header for tip of chain: %v", err)
  573. }
  574. count, err = sim.TransactionCount(bgCtx, lastBlock.Hash())
  575. if err != nil {
  576. t.Error("could not get current block's transaction count")
  577. }
  578. if count != 1 {
  579. t.Errorf("expected transaction count of %v does not match actual count of %v", 1, count)
  580. }
  581. }
  582. func TestSimulatedBackend_TransactionInBlock(t *testing.T) {
  583. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  584. sim := NewSimulatedBackend(
  585. core.GenesisAlloc{
  586. testAddr: {Balance: big.NewInt(10000000000)},
  587. }, 10000000,
  588. )
  589. defer sim.Close()
  590. bgCtx := context.Background()
  591. transaction, err := sim.TransactionInBlock(bgCtx, sim.pendingBlock.Hash(), uint(0))
  592. if err == nil && err != errTransactionDoesNotExist {
  593. t.Errorf("expected a transaction does not exist error to be received but received %v", err)
  594. }
  595. if transaction != nil {
  596. t.Errorf("expected transaction to be nil but received %v", transaction)
  597. }
  598. // expect pending nonce to be 0 since account has not been used
  599. pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
  600. if err != nil {
  601. t.Errorf("did not get the pending nonce: %v", err)
  602. }
  603. if pendingNonce != uint64(0) {
  604. t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
  605. }
  606. // create a signed transaction to send
  607. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  608. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  609. if err != nil {
  610. t.Errorf("could not sign tx: %v", err)
  611. }
  612. // send tx to simulated backend
  613. err = sim.SendTransaction(bgCtx, signedTx)
  614. if err != nil {
  615. t.Errorf("could not add tx to pending block: %v", err)
  616. }
  617. sim.Commit()
  618. lastBlock, err := sim.BlockByNumber(bgCtx, nil)
  619. if err != nil {
  620. t.Errorf("could not get header for tip of chain: %v", err)
  621. }
  622. transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(1))
  623. if err == nil && err != errTransactionDoesNotExist {
  624. t.Errorf("expected a transaction does not exist error to be received but received %v", err)
  625. }
  626. if transaction != nil {
  627. t.Errorf("expected transaction to be nil but received %v", transaction)
  628. }
  629. transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(0))
  630. if err != nil {
  631. t.Errorf("could not get transaction in the lastest block with hash %v: %v", lastBlock.Hash().String(), err)
  632. }
  633. if signedTx.Hash().String() != transaction.Hash().String() {
  634. t.Errorf("received transaction that did not match the sent transaction. expected hash %v, got hash %v", signedTx.Hash().String(), transaction.Hash().String())
  635. }
  636. }
  637. func TestSimulatedBackend_PendingNonceAt(t *testing.T) {
  638. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  639. sim := NewSimulatedBackend(
  640. core.GenesisAlloc{
  641. testAddr: {Balance: big.NewInt(10000000000)},
  642. }, 10000000,
  643. )
  644. defer sim.Close()
  645. bgCtx := context.Background()
  646. // expect pending nonce to be 0 since account has not been used
  647. pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
  648. if err != nil {
  649. t.Errorf("did not get the pending nonce: %v", err)
  650. }
  651. if pendingNonce != uint64(0) {
  652. t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
  653. }
  654. // create a signed transaction to send
  655. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  656. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  657. if err != nil {
  658. t.Errorf("could not sign tx: %v", err)
  659. }
  660. // send tx to simulated backend
  661. err = sim.SendTransaction(bgCtx, signedTx)
  662. if err != nil {
  663. t.Errorf("could not add tx to pending block: %v", err)
  664. }
  665. // expect pending nonce to be 1 since account has submitted one transaction
  666. pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
  667. if err != nil {
  668. t.Errorf("did not get the pending nonce: %v", err)
  669. }
  670. if pendingNonce != uint64(1) {
  671. t.Errorf("expected pending nonce of 1 got %v", pendingNonce)
  672. }
  673. // make a new transaction with a nonce of 1
  674. tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  675. signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  676. if err != nil {
  677. t.Errorf("could not sign tx: %v", err)
  678. }
  679. err = sim.SendTransaction(bgCtx, signedTx)
  680. if err != nil {
  681. t.Errorf("could not send tx: %v", err)
  682. }
  683. // expect pending nonce to be 2 since account now has two transactions
  684. pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
  685. if err != nil {
  686. t.Errorf("did not get the pending nonce: %v", err)
  687. }
  688. if pendingNonce != uint64(2) {
  689. t.Errorf("expected pending nonce of 2 got %v", pendingNonce)
  690. }
  691. }
  692. func TestSimulatedBackend_TransactionReceipt(t *testing.T) {
  693. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  694. sim := NewSimulatedBackend(
  695. core.GenesisAlloc{
  696. testAddr: {Balance: big.NewInt(10000000000)},
  697. }, 10000000,
  698. )
  699. defer sim.Close()
  700. bgCtx := context.Background()
  701. // create a signed transaction to send
  702. tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, big.NewInt(1), nil)
  703. signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
  704. if err != nil {
  705. t.Errorf("could not sign tx: %v", err)
  706. }
  707. // send tx to simulated backend
  708. err = sim.SendTransaction(bgCtx, signedTx)
  709. if err != nil {
  710. t.Errorf("could not add tx to pending block: %v", err)
  711. }
  712. sim.Commit()
  713. receipt, err := sim.TransactionReceipt(bgCtx, signedTx.Hash())
  714. if err != nil {
  715. t.Errorf("could not get transaction receipt: %v", err)
  716. }
  717. if receipt.ContractAddress != testAddr && receipt.TxHash != signedTx.Hash() {
  718. t.Errorf("received receipt is not correct: %v", receipt)
  719. }
  720. }
  721. func TestSimulatedBackend_SuggestGasPrice(t *testing.T) {
  722. sim := NewSimulatedBackend(
  723. core.GenesisAlloc{},
  724. 10000000,
  725. )
  726. defer sim.Close()
  727. bgCtx := context.Background()
  728. gasPrice, err := sim.SuggestGasPrice(bgCtx)
  729. if err != nil {
  730. t.Errorf("could not get gas price: %v", err)
  731. }
  732. if gasPrice.Uint64() != uint64(1) {
  733. t.Errorf("gas price was not expected value of 1. actual: %v", gasPrice.Uint64())
  734. }
  735. }
  736. func TestSimulatedBackend_PendingCodeAt(t *testing.T) {
  737. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  738. sim := NewSimulatedBackend(
  739. core.GenesisAlloc{
  740. testAddr: {Balance: big.NewInt(10000000000)},
  741. },
  742. 10000000,
  743. )
  744. defer sim.Close()
  745. bgCtx := context.Background()
  746. code, err := sim.CodeAt(bgCtx, testAddr, nil)
  747. if err != nil {
  748. t.Errorf("could not get code at test addr: %v", err)
  749. }
  750. if len(code) != 0 {
  751. t.Errorf("got code for account that does not have contract code")
  752. }
  753. parsed, err := abi.JSON(strings.NewReader(abiJSON))
  754. if err != nil {
  755. t.Errorf("could not get code at test addr: %v", err)
  756. }
  757. auth := bind.NewKeyedTransactor(testKey)
  758. contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
  759. if err != nil {
  760. t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
  761. }
  762. code, err = sim.PendingCodeAt(bgCtx, contractAddr)
  763. if err != nil {
  764. t.Errorf("could not get code at test addr: %v", err)
  765. }
  766. if len(code) == 0 {
  767. t.Errorf("did not get code for account that has contract code")
  768. }
  769. // ensure code received equals code deployed
  770. if !bytes.Equal(code, common.FromHex(deployedCode)) {
  771. t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
  772. }
  773. }
  774. func TestSimulatedBackend_CodeAt(t *testing.T) {
  775. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  776. sim := NewSimulatedBackend(
  777. core.GenesisAlloc{
  778. testAddr: {Balance: big.NewInt(10000000000)},
  779. },
  780. 10000000,
  781. )
  782. defer sim.Close()
  783. bgCtx := context.Background()
  784. code, err := sim.CodeAt(bgCtx, testAddr, nil)
  785. if err != nil {
  786. t.Errorf("could not get code at test addr: %v", err)
  787. }
  788. if len(code) != 0 {
  789. t.Errorf("got code for account that does not have contract code")
  790. }
  791. parsed, err := abi.JSON(strings.NewReader(abiJSON))
  792. if err != nil {
  793. t.Errorf("could not get code at test addr: %v", err)
  794. }
  795. auth := bind.NewKeyedTransactor(testKey)
  796. contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
  797. if err != nil {
  798. t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
  799. }
  800. sim.Commit()
  801. code, err = sim.CodeAt(bgCtx, contractAddr, nil)
  802. if err != nil {
  803. t.Errorf("could not get code at test addr: %v", err)
  804. }
  805. if len(code) == 0 {
  806. t.Errorf("did not get code for account that has contract code")
  807. }
  808. // ensure code received equals code deployed
  809. if !bytes.Equal(code, common.FromHex(deployedCode)) {
  810. t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
  811. }
  812. }
  813. // When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
  814. // receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
  815. func TestSimulatedBackend_PendingAndCallContract(t *testing.T) {
  816. testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
  817. sim := NewSimulatedBackend(
  818. core.GenesisAlloc{
  819. testAddr: {Balance: big.NewInt(10000000000)},
  820. },
  821. 10000000,
  822. )
  823. defer sim.Close()
  824. bgCtx := context.Background()
  825. parsed, err := abi.JSON(strings.NewReader(abiJSON))
  826. if err != nil {
  827. t.Errorf("could not get code at test addr: %v", err)
  828. }
  829. contractAuth := bind.NewKeyedTransactor(testKey)
  830. addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(abiBin), sim)
  831. if err != nil {
  832. t.Errorf("could not deploy contract: %v", err)
  833. }
  834. input, err := parsed.Pack("receive", []byte("X"))
  835. if err != nil {
  836. t.Errorf("could pack receive function on contract: %v", err)
  837. }
  838. // make sure you can call the contract in pending state
  839. res, err := sim.PendingCallContract(bgCtx, ethereum.CallMsg{
  840. From: testAddr,
  841. To: &addr,
  842. Data: input,
  843. })
  844. if err != nil {
  845. t.Errorf("could not call receive method on contract: %v", err)
  846. }
  847. if len(res) == 0 {
  848. t.Errorf("result of contract call was empty: %v", res)
  849. }
  850. // while comparing against the byte array is more exact, also compare against the human readable string for readability
  851. if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
  852. t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
  853. }
  854. sim.Commit()
  855. // make sure you can call the contract
  856. res, err = sim.CallContract(bgCtx, ethereum.CallMsg{
  857. From: testAddr,
  858. To: &addr,
  859. Data: input,
  860. }, nil)
  861. if err != nil {
  862. t.Errorf("could not call receive method on contract: %v", err)
  863. }
  864. if len(res) == 0 {
  865. t.Errorf("result of contract call was empty: %v", res)
  866. }
  867. if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
  868. t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
  869. }
  870. }