simulated_test.go 49 KB

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