mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-30 08:33:45 +00:00
* cmd, core, trie: verkle-capable `geth init` (#28270) This change allows the creation of a genesis block for verkle testnets. This makes for a chunk of code that is easier to review and still touches many discussion points. * eth/tracers/js: fix isPush for push0 (#28520) Fixes so that `push0` opcode is correctly reported as `true` by the `IsPush` function --------- Co-authored-by: Martin Holst Swende <martin@swende.se> * trie: spelling - fix comments in hasher (#28507) Co-authored-by: VM <arimas@foxmail.com> * tests/fuzzers: move fuzzers into native packages (#28467) This PR moves our fuzzers from tests/fuzzers into whatever their respective 'native' package is. The historical reason why they were placed in an external location, is that when they were based on go-fuzz, they could not be "hidden" via the _test.go prefix. So in order to shove them away from the go-ethereum "production code", they were put aside. But now we've rewritten them to be based on golang testing, and thus can be brought back. I've left (in tests/) the ones that are not production (bls128381), require non-standard imports (secp requires btcec, bn256 requires gnark/google/cloudflare deps). This PR also adds a fuzzer for precompiled contracts, because why not. This PR utilizes a newly rewritten replacement for go-118-fuzz-build, namely gofuzz-shim, which utilises the inputs from the fuzzing engine better. * tests: skip tests on windows 32bit CI (#28521) tests: skip half the blockchain- and state-tests on windows 32bit CI-tests * cmd/geth: more special cases logging tests (#28527) adds logging tests for errors and custom fmt.Stringer-types which output strings that needs to be quoted/escaped. * accounts,cmd,console,les,metrics: refactor some errors checked by (ST1005) go-staticcheck (#28532) fix: fix some (ST1005)go-staticcheck * miner: run tests in parallel (#28506) Changes many of the tests in the miner package to run in parallel * internal/jsre/deps: fix typo in jsdoc (#28511) minor typo fix * accounts/abi: improve readability of method-to-string conversion (#28530) refactor: improve readability of NewMethod print * all: replace some cases of strings.SplitN with strings.Cut (#28446) * ethdb/memorydb, trie: reduced allocations (#28473) * trie: use pooling of iterator states in iterator The node iterator burns through a lot of memory while iterating a trie, and a lot of that can be avoided by using a fairly small pool (max 40 items). name old time/op new time/op delta Iterator-8 6.22ms ± 3% 5.40ms ± 6% -13.18% (p=0.008 n=5+5) name old alloc/op new alloc/op delta Iterator-8 2.36MB ± 0% 1.67MB ± 0% -29.23% (p=0.008 n=5+5) name old allocs/op new allocs/op delta Iterator-8 37.0k ± 0% 29.8k ± 0% ~ (p=0.079 n=4+5) * ethdb/memorydb: avoid one copying of key By making the transformation from []byte to string at an earlier point, we save an allocation which otherwise happens later on. name old time/op new time/op delta BatchAllocs-8 412µs ± 6% 382µs ± 2% -7.18% (p=0.016 n=5+4) name old alloc/op new alloc/op delta BatchAllocs-8 480kB ± 0% 490kB ± 0% +1.93% (p=0.008 n=5+5) name old allocs/op new allocs/op delta BatchAllocs-8 3.03k ± 0% 2.03k ± 0% -32.98% (p=0.008 n=5+5) * Dockerfile: update Go to 1.21 (#28538) * cmd/evm: validate blockchain tests poststate account storage (#28443) This PR verifies the accounts' storage as specified in a blockchain test's postState field The expect-section, it does really only check that the test works. It's meant for the test-author to verify that "If the test does what it's supposed to, then the nonce of X should be 2, and the slot Y at Z should be 0x123. This expect-section is not exhaustive (not full post-state) It is also not auto-generated, but put there manually by the author. We can still check it, as a test-sanity-check, in geth * signer: run tests in parallel (#28536) marks tests as parallel-safe in package signer * accounts, cmd: fix typos (#28526) * core/txpool/legacypool: respect nolocals-setting (#28435) This change adds a check to ensure that transactions added to the legacy pool are not treated as 'locals' if the global locals-management has been disabled. This change makes the pool enforce the --txpool.pricelimit setting. * cmd: run tests in parallel (#28546) * core/state/snapshot: print correct error from trie iterator (#28560) * cmd/evm: capitalize evm commands (#28569) * standard:fix for a unified standard * standard:fix more as a complements --------- Co-authored-by: haotian <haotian@haotiandeMacBook-Air.local> * accounts/abi: context info on unpack-errors (#28529) adds contextual information to errors returned by unpack * core, trie, rpc: speed up tests (#28461) * rpc: make subscription test faster reduces time for TestClientSubscriptionChannelClose from 25 sec to < 1 sec. * trie: cache trie nodes for faster sanity check This reduces the time spent on TestIncompleteSyncHash from ~25s to ~16s. * core/forkid: speed up validation test This takes the validation test from > 5s to sub 1 sec * core/state: improve snapshot test run brings the time for TestSnapshotRandom from 13s down to 6s * accounts/keystore: improve keyfile test This removes some unnecessary waits and reduces the runtime of TestUpdatedKeyfileContents from 5 to 3 seconds * trie: remove resolver * trie: only check ~5% of all trie nodes * ethdb/pebble: don't double-close iterator inside pebbleIterator (#28566) Adds 'released' flag to pebbleIterator to avoid double closing cockroachdb/pebble.Iterator as it is an invalid operation. Fixes #28565 * eth/filters: reuse error msg for invalid block range (#28479) * core/types: make 'v' optional for DynamicFeeTx and BlobTx (#28564) This fixes an issue where transactions would not be accepted when they have only 'yParity' and not 'v'. * rpc: improve performance of subscription notification encoding (#28328) It turns out that encoding json.RawMessage is slow because package json basically parses the message again to ensure it is valid. We can avoid the slowdown by encoding the entire RPC notification once, which yields a 30% speedup. * cmd/utils: validate pre-existing genesis in --dev mode (#28468) geth --dev can be used with an existing data directory and genesis block. Since dev mode only works with PoS, we need to verify that the merge has happened. Co-authored-by: Felix Lange <fjl@twurst.com> * cmd/geth: add support for --dev flag in dumpgenesis (#28463) Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: lightclient <lightclient@protonmail.com> * les/vflux: run tests in parallel (#28524) * cmd/{geth,utils}: add cmd to export preimages in snap enumeration order (#28256) Adds a subcommand: `geth snapshot export-preimages`, to export preimages of every hash found during a snapshot enumeration: that is, it exports _only the active state_, and not _all_ preimages that have been used but are no longer part of the state. This tool is needed for the verkle transition, in order to distribute the preimages needed for the conversion. Since only the 'active' preimages are exported, the output is shrunk from ~70GB to ~4GB. The order of the output is the order used by the snapshot enumeration, which avoids database thrashing. However, it also means that storage-slot preimages are not deduplicated. * cmd/geth: fix build error (#28585) * cmd/devp2p/internal/ethtest: undo debug-hack (#28588) cmd/devp2p/internal/ethtest: remove a debug-hack flaw which prevented certain tests from running * params: update discV5 bootnodes (#28562) update discV5 bootnodes from https://github.com/eth-clients/eth2-networks/blob/master/shared/mainnet/bootstrap_nodes.txt * cmd, les, tests: remove light client code (#28586) * cmd, les, tests: remove light client code This commit removes the light client (LES) code. Since the merge the light client has been broken and it is hard to maintain it alongside the normal client. We decided it would be best to remove it for now and maybe rework and reintroduce it in the future. * cmd, eth: remove some more mentions of light mode * cmd: re-add flags and mark as deprecated * cmd: warn the user about deprecated flags * eth: better error message * eth, internal/ethapi: drop some weird indirection (#28597) * trie: fix random test generator early terminate (#28590) This change fixes a minor bug in the `randTest.Generate` function, which caused the `quick.Check` to be a no-op. * eth/gasestimator, internal/ethapi: move gas estimator out of rpc (#28600) * go.mod: update uint256 to v1.2.4 (#28612) * eth/catalyst, eth/downloader: expose more sync information (#28584) This change exposes more information from sync module internally * light: remove package light(#28614) This changes removes the package 'light', which is currently unused. * cmd/evm, core/state: fix post-exec dump of state (statetests, blockchaintests) (#28504) There were several problems related to dumping state. - If a preimage was missing, even if we had set the `OnlyWithAddresses` to `false`, to export them anyway, the way the mapping was constructed (using `common.Address` as key) made the entries get lost anyway. Concerns both state- and blockchain tests. - Blockchain test execution was not configured to store preimages. This changes makes it so that the block test executor takes a callback, just like the state test executor already does. This callback can be used to examine the post-execution state, e.g. to aid debugging of test failures. * ethereum: remove TODO comment about subscription (#28609) * eth/tracers/js: fix type inconsistencies (#28488) This change fixes two type-inconsistencies in the JS tracer: - In most places we return byte arrays as a `Uint8Array` to the tracer. However it seems we missed doing the conversion for `ctx` fields which are passed to the tracer during `result`. They are passed as simple arrays. I think Uint8Arrays are more suitable and we should change this inconsistency. Note: this will be a breaking-change. But I believe the effect is small. If we look at our tracers we see that these fields (`ctx.from`, `ctx.to`, etc.) are used in 2 ways. Passed to `toHex` which takes both array or buffer. Or the length was measured which is the same for both types. - The `slice` taking in `int, int` params versus `memory.slice` taking `int64, int64` params. I suggest changing `slice` types to `int64`. This should have no effect almost in any case. * crypto/secp256k1: fix 32-bit tests when CGO_ENABLED=0 (#28602) * consensus: verify the nonexistence of shanghai- and cancun-specific header fields (#28605) * eth/gasestimator: allow slight estimation error in favor of less iterations (#28618) * eth/gasestimator: early exit for plain transfer and error allowance * core, eth/gasestimator: hard guess at a possible required gas * internal/ethapi: update estimation tests with the error ratio * eth/gasestimator: I hate you linter * graphql: fix gas estimation test --------- Co-authored-by: Oren <orenyomtov@users.noreply.github.com> * all: replace log15 with slog (#28187) This PR replaces Geth's logger package (a fork of [log15](https://github.com/inconshreveable/log15)) with an implementation using slog, a logging library included as part of the Go standard library as of Go1.21. Main changes are as follows: * removes any log handlers that were unused in the Geth codebase. * Json, logfmt, and terminal formatters are now slog handlers. * Verbosity level constants are changed to match slog constant values. Internal translation is done to make this opaque to the user and backwards compatible with existing `--verbosity` and `--vmodule` options. * `--log.backtraceat` and `--log.debug` are removed. The external-facing API is largely the same as the existing Geth logger. Logger method signatures remain unchanged. A small semantic difference is that a `Handler` can only be set once per `Logger` and not changed dynamically. This just means that a new logger must be instantiated every time the handler of the root logger is changed. ---- For users of the `go-ethereum/log` module. If you were using this module for your own project, you will need to change the initialization. If you previously did ```golang log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) ``` You now instead need to do ```golang log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelInfo, true))) ``` See more about reasoning here: https://github.com/ethereum/go-ethereum/issues/28558#issuecomment-1820606613 * core/state: make stateobject.create selfcontain (#28459) * trie/triedb/hashdb: take lock around access to dirties cache (#28542) Add read locking of db lock around access to dirties cache in hashdb.Database to prevent data race versus hashdb.Database.dereference which can modify the dirities map by deleting an item. Fixes #28541 --------- Co-authored-by: Gary Rong <garyrong0905@gmail.com> * accounts/abi/bind: fix typo (#28630) * slog: faster and less memory-consumption (#28621) These changes improves the performance of the non-coloured terminal formatting, _quite a lot_. ``` name old time/op new time/op delta TerminalHandler-8 10.2µs ±15% 5.4µs ± 9% -47.02% (p=0.008 n=5+5) name old alloc/op new alloc/op delta TerminalHandler-8 2.17kB ± 0% 0.40kB ± 0% -81.46% (p=0.008 n=5+5) name old allocs/op new allocs/op delta TerminalHandler-8 33.0 ± 0% 5.0 ± 0% -84.85% (p=0.008 n=5+5) ``` I tried to _somewhat_ organize the commits, but the it might still be a bit chaotic. Some core insights: - The function `terminalHandler.Handl` uses a mutex, and writes all output immediately to 'upstream'. Thus, it can reuse a scratch-buffer every time. - This buffer can be propagated internally, making all the internal formatters either write directly to it, - OR, make use of the `tmp := buf.AvailableBuffer()` in some cases, where a byte buffer "extra capacity" can be temporarily used. - The `slog` package uses `Attr` by value. It makes sense to minimize operating on them, since iterating / collecting into a new slice, iterating again etc causes copy-on-heap. Better to operate on them only once. - If we want to do padding, it's better to copy from a constant `space`-buffer than to invoke `bytes.Repeat` every single time. * eth/tracers: tx-level state in debug_traceCall (#28460) * cmd/evm: fix Env struct json tag (#28635) * accounts/abi/bind: fixed typos (#28634) * Update auth.go * Update backend.go * Update bind.go * Update bind_test.go * eth/fetcher: fix invalid tracking of received at time for block (#28637) eth/fetcher: fix invalid tracking of received at time * accounts: run tests in parallel (#28544) * eth/tracers/logger: make structlog/json-log stack hex again (#28628) * common/hexutil: define hex wrappers for uint256.Int * eth/tracers/logger: make structlog/json-log stack hex again * common/hexutil: goimports * log: remove lazy, remove unused interfaces, unexport methods (#28622) This change - Removes interface `log.Format`, - Removes method `log.FormatFunc`, - unexports `TerminalHandler.TerminalFormat` formatting methods (renamed to `TerminalHandler.format`) - removes the notion of `log.Lazy` values The lazy handler was useful in the old log package, since it could defer the evaluation of costly attributes until later in the log pipeline: thus, if the logging was done at 'Trace', we could skip evaluation if logging only was set to 'Info'. With the move to slog, this way of deferring evaluation is no longer needed, since slog introduced 'Enabled': the caller can thus do the evaluate-or-not decision at the callsite, which is much more straight-forward than dealing with lazy reflect-based evaluation. Also, lazy evaluation would not work with 'native' slog, as in, these two statements would be evaluated differently: ```golang log.Info("foo", "my lazy", lazyObj) slog.Info("foo", "my lazy", lazyObj) ``` * .github: use github actions to run 32-bit linux tests (#28549) use github actions to run 32-bit linux tests * ethdb/pebble: remove a dependency (#28627) The dependency was not really used anyway, so we can get rid of it. Co-authored-by: Felix Lange <fjl@twurst.com> * tests/fuzzers/bls12381: deactivate BLS fuzzer when CGO_ENABLED=0 (#28653) tests/fuzzers/bls12381: deactivate fuzzer when CGO_ENABLED=0 * build: upgrade -dlgo version to Go 1.21.5 (#28648) * rpc: fix ns/µs mismatch in metrics (#28649) The rpc/duration/all meter was in nanoseconds, the individual meter in microseconds. This PR changes it so both of them use nanoseconds. * cmd/evm: fix dump after state-test exec (#28650) The dump after state-test didn't work, the problem was an error, "Already committed", which was silently ignored. This change re-initialises the state, so the dumping works again. * beacon/light: add CommitteeChain (#27766) This change implements CommitteeChain which is a key component of the beacon light client. It is a passive data structure that can validate, hold and update a chain of beacon light sync committees and updates, starting from a checkpoint that proves the starting committee through a beacon block hash, header and corresponding state. Once synced to the current sync period, CommitteeChain can also validate signed beacon headers. * cmd/utils, eth: disallow invalid snap sync / snapshot flag combos (#28657) * eth: prevent startup in snap mode without snapshots * cmd/utils: try to fix bad flag combos wrt snap sync and snapshot generation * trie: remove inconsistent trie nodes during sync in path mode (#28595) This fixes a database corruption issue that could occur during state healing. When sync is aborted while certain modifications were already committed, and a reorg occurs, the database would contain incorrect trie nodes stored by path. These nodes need to detected/deleted in order to obtain a complete and fully correct state after state healing. --------- Co-authored-by: Felix Lange <fjl@twurst.com> * cmd/utils: fix HTTPHost, WSHost flag priority (#28669) Co-authored-by: Felix Lange <fjl@twurst.com> * eth/protocols/eth: fix typos in comments (#28652) * core/txpool : small cleanup refactors (#28654) * eth/fetcher, eth/gasestimator: fix typos in comments (#28675) * all: fix typos in comments (#28662) Co-authored-by: Felix Lange <fjl@twurst.com> * miner: eliminate the dead loop possibility for `newWorkLoop` and `mainLoop` (#28677) discard the intervalAdjust message if the channel is full * all: fix typos in comments (#28682) chore(core,eth):fix a couple of typos * p2p/discover: add liveness check in collectTableNodes (#28686) * p2p/discover: add liveness check in collectTableNodes * p2p/discover: fix test * p2p/discover: rename to appendLiveNodes * p2p/discover: add dedup logic back * p2p/discover: simplify * p2p/discover: fix issue found by test * internal/flags: add missing flag types for auto-env-var generation (#28692) Certain flags, such as `--rpc.txfeecap` currently do not have an env-var auto-generated for them. This change adds three missing cli flag types to the auto env-var helper function to fix this. * cmd/evm: default to mirror mainnet forks enabled (#28691) cmd/evm: default to using dev chain config (all mainnet HFs activated at block/timestamp 0 * cmd/evm, cmd/clef, cmd/bootnode: fix / unify logging (#28696) This change fixes a problem with our non-core binaries: evm, clef, bootnode. First of all, they failed to convert from legacy loglevels 1 to 5, to the new slog loglevels -4 to 4. Secondly, the logging was actually setup in the init phase, and then overridden in the main. This is not needed for evm, since it used the same flag name as the main geth verbosity. Better to let the flags/internal handle the logging init. * cmd/evm: t8n support custom tracers (#28557) This change implements ability for the `evm t8n` tool to use custom tracers; either 'native' golang tracers or javascript tracers. * params: release go-ethereum v1.13.6 stable * Fix build errors * Fix test-integration --------- Co-authored-by: Guillaume Ballet <3272758+gballet@users.noreply.github.com> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: VM <112189277+sysvm@users.noreply.github.com> Co-authored-by: VM <arimas@foxmail.com> Co-authored-by: jwasinger <j-wasinger@hotmail.com> Co-authored-by: Zoro <40222601+BabyHalimao@users.noreply.github.com> Co-authored-by: Håvard Anda Estensen <haavard.ae@gmail.com> Co-authored-by: aliening <128203330+aliening@users.noreply.github.com> Co-authored-by: Halimao <1065621723@qq.com> Co-authored-by: danceratopz <danceratopz@gmail.com> Co-authored-by: levisyin <150114626+levisyin@users.noreply.github.com> Co-authored-by: jp-imx <109574657+jp-imx@users.noreply.github.com> Co-authored-by: rjl493456442 <garyrong0905@gmail.com> Co-authored-by: Haotian <51777534+tmelhao@users.noreply.github.com> Co-authored-by: haotian <haotian@haotiandeMacBook-Air.local> Co-authored-by: Marius van der Wijden <m.vanderwijden@live.de> Co-authored-by: Maciej Kulawik <10907694+magicxyyz@users.noreply.github.com> Co-authored-by: ucwong <ucwong@126.com> Co-authored-by: Mario Vega <marioevz@gmail.com> Co-authored-by: Delweng <delweng@gmail.com> Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: lightclient <lightclient@protonmail.com> Co-authored-by: Mikel Cortes <45786396+cortze@users.noreply.github.com> Co-authored-by: Péter Szilágyi <peterke@gmail.com> Co-authored-by: Ng Wei Han <47109095+weiihann@users.noreply.github.com> Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com> Co-authored-by: Shivam Sandbhor <shivam.sandbhor@gmail.com> Co-authored-by: Jakub Freebit <49676311+jakub-freebit@users.noreply.github.com> Co-authored-by: Oren <orenyomtov@users.noreply.github.com> Co-authored-by: BorkBorked <107079055+BorkBorked@users.noreply.github.com> Co-authored-by: ddl <dengdiliang@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Marius Kjærstad <sandakersmann@users.noreply.github.com> Co-authored-by: Felföldi Zsolt <zsfelfoldi@gmail.com> Co-authored-by: Ford <153042616+guerrierindien@users.noreply.github.com> Co-authored-by: Ursulafe <152976968+Ursulafe@users.noreply.github.com> Co-authored-by: Elias Rad <146735585+nnsW3@users.noreply.github.com> Co-authored-by: FletcherMan <fanciture@163.com> Co-authored-by: alex <152680487+bodhi-crypo@users.noreply.github.com> Co-authored-by: Sebastian Stammler <seb@oplabs.co>
1607 lines
52 KiB
Go
1607 lines
52 KiB
Go
// Copyright 2019 The go-ethereum Authors
|
|
// This file is part of the go-ethereum library.
|
|
//
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU Lesser General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
package backends
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"math/big"
|
|
"math/rand"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"go.uber.org/goleak"
|
|
|
|
"github.com/ethereum/go-ethereum"
|
|
"github.com/ethereum/go-ethereum/accounts/abi"
|
|
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/common/leak"
|
|
"github.com/ethereum/go-ethereum/core"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
"github.com/ethereum/go-ethereum/params"
|
|
)
|
|
|
|
func TestSimulatedBackend(t *testing.T) {
|
|
defer goleak.VerifyNone(t, leak.IgnoreList()...)
|
|
var gasLimit uint64 = 8000029
|
|
|
|
key, _ := crypto.GenerateKey() // nolint: gosec
|
|
auth, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
|
genAlloc := make(core.GenesisAlloc)
|
|
genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)}
|
|
|
|
sim := NewSimulatedBackend(genAlloc, gasLimit)
|
|
defer sim.Close()
|
|
|
|
// should return an error if the tx is not found
|
|
txHash := common.HexToHash("2")
|
|
_, isPending, err := sim.TransactionByHash(context.Background(), txHash)
|
|
|
|
if isPending {
|
|
t.Fatal("transaction should not be pending")
|
|
}
|
|
|
|
if err != ethereum.NotFound {
|
|
t.Fatalf("err should be `ethereum.NotFound` but received %v", err)
|
|
}
|
|
|
|
// generate a transaction and confirm you can retrieve it
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
code := `6060604052600a8060106000396000f360606040526008565b00`
|
|
|
|
var gas uint64 = 3000000
|
|
tx := types.NewContractCreation(0, big.NewInt(0), gas, gasPrice, common.FromHex(code))
|
|
tx, _ = types.SignTx(tx, types.HomesteadSigner{}, key)
|
|
|
|
err = sim.SendTransaction(context.Background(), tx)
|
|
if err != nil {
|
|
t.Fatal("error sending transaction")
|
|
}
|
|
|
|
txHash = tx.Hash()
|
|
_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
|
|
|
|
if err != nil {
|
|
t.Fatalf("error getting transaction with hash: %v", txHash.String())
|
|
}
|
|
|
|
if !isPending {
|
|
t.Fatal("transaction should have pending status")
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
_, isPending, err = sim.TransactionByHash(context.Background(), txHash)
|
|
if err != nil {
|
|
t.Fatalf("error getting transaction with hash: %v", txHash.String())
|
|
}
|
|
|
|
if isPending {
|
|
t.Fatal("transaction should not have pending status")
|
|
}
|
|
}
|
|
|
|
var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
|
|
|
|
// the following is based on this contract:
|
|
//
|
|
// contract T {
|
|
// event received(address sender, uint amount, bytes memo);
|
|
// event receivedAddr(address sender);
|
|
//
|
|
// function receive(bytes calldata memo) external payable returns (string memory res) {
|
|
// emit received(msg.sender, msg.value, memo);
|
|
// emit receivedAddr(msg.sender);
|
|
// return "hello world";
|
|
// }
|
|
// }
|
|
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" } ]`
|
|
const abiBin = `0x608060405234801561001057600080fd5b506102a0806100206000396000f3fe60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
|
|
const deployedCode = `60806040526004361061003b576000357c010000000000000000000000000000000000000000000000000000000090048063a69b6ed014610040575b600080fd5b6100b76004803603602081101561005657600080fd5b810190808035906020019064010000000081111561007357600080fd5b82018360208201111561008557600080fd5b803590602001918460018302840111640100000000831117156100a757600080fd5b9091929391929390505050610132565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f75780820151818401526020810190506100dc565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60607f75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed33348585604051808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509550505050505060405180910390a17f46923992397eac56cf13058aced2a1871933622717e27b24eabc13bf9dd329c833604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a16040805190810160405280600b81526020017f68656c6c6f20776f726c6400000000000000000000000000000000000000000081525090509291505056fea165627a7a72305820ff0c57dad254cfeda48c9cfb47f1353a558bccb4d1bc31da1dae69315772d29e0029`
|
|
|
|
// expected return value contains "hello world"
|
|
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}
|
|
|
|
func simTestBackend(testAddr common.Address) *SimulatedBackend {
|
|
return NewSimulatedBackend(
|
|
core.GenesisAlloc{
|
|
testAddr: {Balance: big.NewInt(10000000000000000)},
|
|
}, 10000000,
|
|
)
|
|
}
|
|
|
|
func TestNewSimulatedBackend(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
expectedBal := big.NewInt(10000000000000000)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
if sim.config != params.AllEthashProtocolChanges {
|
|
t.Errorf("expected sim config to equal params.AllEthashProtocolChanges, got %v", sim.config)
|
|
}
|
|
|
|
if sim.blockchain.Config() != params.AllEthashProtocolChanges {
|
|
t.Errorf("expected sim blockchain config to equal params.AllEthashProtocolChanges, got %v", sim.config)
|
|
}
|
|
|
|
stateDB, _ := sim.blockchain.State()
|
|
|
|
bal := stateDB.GetBalance(testAddr)
|
|
if bal.Cmp(expectedBal) != 0 {
|
|
t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
|
|
}
|
|
}
|
|
|
|
func TestAdjustTime(t *testing.T) {
|
|
t.Parallel()
|
|
sim := NewSimulatedBackend(
|
|
core.GenesisAlloc{}, 10000000,
|
|
)
|
|
defer sim.Close()
|
|
|
|
prevTime := sim.pendingBlock.Time()
|
|
|
|
if err := sim.AdjustTime(time.Second); err != nil {
|
|
t.Error(err)
|
|
}
|
|
|
|
newTime := sim.pendingBlock.Time()
|
|
|
|
if newTime-prevTime != uint64(time.Second.Seconds()) {
|
|
t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime)
|
|
}
|
|
}
|
|
|
|
func TestNewAdjustTimeFail(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.blockchain.Stop()
|
|
|
|
// Create tx and send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
sim.SendTransaction(context.Background(), signedTx)
|
|
// AdjustTime should fail on non-empty block
|
|
if err := sim.AdjustTime(time.Second); err == nil {
|
|
t.Error("Expected adjust time to error on non-empty block")
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
prevTime := sim.pendingBlock.Time()
|
|
|
|
if err := sim.AdjustTime(time.Minute); err != nil {
|
|
t.Error(err)
|
|
}
|
|
|
|
newTime := sim.pendingBlock.Time()
|
|
if newTime-prevTime != uint64(time.Minute.Seconds()) {
|
|
t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime)
|
|
}
|
|
// Put a transaction after adjusting time
|
|
tx2 := types.NewTransaction(1, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx2, err := types.SignTx(tx2, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
sim.SendTransaction(context.Background(), signedTx2)
|
|
sim.Commit()
|
|
|
|
newTime = sim.pendingBlock.Time()
|
|
if newTime-prevTime >= uint64(time.Minute.Seconds()) {
|
|
t.Errorf("time adjusted, but shouldn't be: prev: %v, new: %v", prevTime, newTime)
|
|
}
|
|
}
|
|
|
|
func TestBalanceAt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
expectedBal := big.NewInt(10000000000000000)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
bal, err := sim.BalanceAt(bgCtx, testAddr, nil)
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
|
|
if bal.Cmp(expectedBal) != 0 {
|
|
t.Errorf("expected balance for test address not received. expected: %v actual: %v", expectedBal, bal)
|
|
}
|
|
}
|
|
|
|
func TestBlockByHash(t *testing.T) {
|
|
t.Parallel()
|
|
sim := NewSimulatedBackend(
|
|
core.GenesisAlloc{}, 10000000,
|
|
)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
block, err := sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
blockByHash, err := sim.BlockByHash(bgCtx, block.Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
if block.Hash() != blockByHash.Hash() {
|
|
t.Errorf("did not get expected block")
|
|
}
|
|
}
|
|
|
|
func TestBlockByNumber(t *testing.T) {
|
|
t.Parallel()
|
|
sim := NewSimulatedBackend(
|
|
core.GenesisAlloc{}, 10000000,
|
|
)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
block, err := sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
if block.NumberU64() != 0 {
|
|
t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
|
|
}
|
|
|
|
// create one block
|
|
sim.Commit()
|
|
|
|
block, err = sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
if block.NumberU64() != 1 {
|
|
t.Errorf("did not get most recent block, instead got block number %v", block.NumberU64())
|
|
}
|
|
|
|
blockByNumber, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
|
|
if err != nil {
|
|
t.Errorf("could not get block by number: %v", err)
|
|
}
|
|
|
|
if blockByNumber.Hash() != block.Hash() {
|
|
t.Errorf("did not get the same block with height of 1 as before")
|
|
}
|
|
}
|
|
|
|
func TestNonceAt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
nonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(0))
|
|
if err != nil {
|
|
t.Errorf("could not get nonce for test addr: %v", err)
|
|
}
|
|
|
|
if nonce != uint64(0) {
|
|
t.Errorf("received incorrect nonce. expected 0, got %v", nonce)
|
|
}
|
|
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(nonce, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
newNonce, err := sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
|
|
if err != nil {
|
|
t.Errorf("could not get nonce for test addr: %v", err)
|
|
}
|
|
|
|
if newNonce != nonce+uint64(1) {
|
|
t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
|
|
}
|
|
// create some more blocks
|
|
sim.Commit()
|
|
// Check that we can get data for an older block/state
|
|
newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
|
|
if err != nil {
|
|
t.Fatalf("could not get nonce for test addr: %v", err)
|
|
}
|
|
|
|
if newNonce != nonce+uint64(1) {
|
|
t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
|
|
}
|
|
}
|
|
|
|
func TestSendTransaction(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
|
|
if err != nil {
|
|
t.Errorf("could not get block at height 1: %v", err)
|
|
}
|
|
|
|
if signedTx.Hash() != block.Transactions()[0].Hash() {
|
|
t.Errorf("did not commit sent transaction. expected hash %v got hash %v", block.Transactions()[0].Hash(), signedTx.Hash())
|
|
}
|
|
}
|
|
|
|
func TestTransactionByHash(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := NewSimulatedBackend(
|
|
core.GenesisAlloc{
|
|
testAddr: {Balance: big.NewInt(10000000000000000)},
|
|
}, 10000000,
|
|
)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
// ensure tx is committed pending
|
|
receivedTx, pending, err := sim.TransactionByHash(bgCtx, signedTx.Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
|
|
}
|
|
|
|
if !pending {
|
|
t.Errorf("expected transaction to be in pending state")
|
|
}
|
|
|
|
if receivedTx.Hash() != signedTx.Hash() {
|
|
t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
// ensure tx is not and committed pending
|
|
receivedTx, pending, err = sim.TransactionByHash(bgCtx, signedTx.Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get transaction by hash %v: %v", signedTx.Hash(), err)
|
|
}
|
|
|
|
if pending {
|
|
t.Errorf("expected transaction to not be in pending state")
|
|
}
|
|
|
|
if receivedTx.Hash() != signedTx.Hash() {
|
|
t.Errorf("did not received committed transaction. expected hash %v got hash %v", signedTx.Hash(), receivedTx.Hash())
|
|
}
|
|
}
|
|
|
|
func TestEstimateGas(t *testing.T) {
|
|
t.Parallel()
|
|
/*
|
|
pragma solidity ^0.6.4;
|
|
contract GasEstimation {
|
|
function PureRevert() public { revert(); }
|
|
function Revert() public { revert("revert reason");}
|
|
function OOG() public { for (uint i = 0; ; i++) {}}
|
|
function Assert() public { assert(false);}
|
|
function Valid() public {}
|
|
}
|
|
*/
|
|
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\"}]"
|
|
|
|
const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
|
|
|
|
key, _ := crypto.GenerateKey()
|
|
addr := crypto.PubkeyToAddress(key.PublicKey)
|
|
opts, _ := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
|
|
|
|
sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000)
|
|
defer sim.Close()
|
|
|
|
parsed, _ := abi.JSON(strings.NewReader(contractAbi))
|
|
contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim)
|
|
sim.Commit()
|
|
|
|
var cases = []struct {
|
|
name string
|
|
message ethereum.CallMsg
|
|
expect uint64
|
|
expectError error
|
|
expectData interface{}
|
|
}{
|
|
{"plain transfer(valid)", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &addr,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(0),
|
|
Value: big.NewInt(1),
|
|
Data: nil,
|
|
}, params.TxGas, nil, nil},
|
|
|
|
{"plain transfer(invalid)", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(0),
|
|
Value: big.NewInt(1),
|
|
Data: nil,
|
|
}, 0, errors.New("execution reverted"), nil},
|
|
|
|
{"Revert", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(0),
|
|
Value: nil,
|
|
Data: common.Hex2Bytes("d8b98391"),
|
|
}, 0, errors.New("execution reverted: revert reason"), "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000"},
|
|
|
|
{"PureRevert", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(0),
|
|
Value: nil,
|
|
Data: common.Hex2Bytes("aa8b1d30"),
|
|
}, 0, errors.New("execution reverted"), nil},
|
|
|
|
{"OOG", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 100000,
|
|
GasPrice: big.NewInt(0),
|
|
Value: nil,
|
|
Data: common.Hex2Bytes("50f6fe34"),
|
|
}, 0, errors.New("gas required exceeds allowance (100000)"), nil},
|
|
|
|
{"Assert", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 100000,
|
|
GasPrice: big.NewInt(0),
|
|
Value: nil,
|
|
Data: common.Hex2Bytes("b9b046f9"),
|
|
}, 0, errors.New("invalid opcode: INVALID"), nil},
|
|
|
|
{"Valid", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &contractAddr,
|
|
Gas: 100000,
|
|
GasPrice: big.NewInt(0),
|
|
Value: nil,
|
|
Data: common.Hex2Bytes("e09fface"),
|
|
}, 21275, nil, nil},
|
|
}
|
|
|
|
for _, c := range cases {
|
|
got, err := sim.EstimateGas(context.Background(), c.message)
|
|
if c.expectError != nil {
|
|
if err == nil {
|
|
t.Fatalf("Expect error, got nil")
|
|
}
|
|
|
|
if c.expectError.Error() != err.Error() {
|
|
t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
|
|
}
|
|
|
|
if c.expectData != nil {
|
|
if err, ok := err.(*revertError); !ok {
|
|
t.Fatalf("Expect revert error, got %T", err)
|
|
} else if !reflect.DeepEqual(err.ErrorData(), c.expectData) {
|
|
t.Fatalf("Error data mismatch, want %v, got %v", c.expectData, err.ErrorData())
|
|
}
|
|
}
|
|
|
|
continue
|
|
}
|
|
|
|
if got != c.expect {
|
|
t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEstimateGasWithPrice(t *testing.T) {
|
|
t.Parallel()
|
|
key, _ := crypto.GenerateKey()
|
|
addr := crypto.PubkeyToAddress(key.PublicKey)
|
|
|
|
sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether*2 + 2e17)}}, 10000000)
|
|
defer sim.Close()
|
|
|
|
recipient := common.HexToAddress("deadbeef")
|
|
|
|
var cases = []struct {
|
|
name string
|
|
message ethereum.CallMsg
|
|
expect uint64
|
|
expectError error
|
|
}{
|
|
{"EstimateWithoutPrice", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &recipient,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(0),
|
|
Value: big.NewInt(100000000000),
|
|
Data: nil,
|
|
}, 21000, nil},
|
|
|
|
{"EstimateWithPrice", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &recipient,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(100000000000),
|
|
Value: big.NewInt(100000000000),
|
|
Data: nil,
|
|
}, 21000, nil},
|
|
|
|
{"EstimateWithVeryHighPrice", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &recipient,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(1e14), // gascost = 2.1ether
|
|
Value: big.NewInt(1e17), // the remaining balance for fee is 2.1ether
|
|
Data: nil,
|
|
}, 21000, nil},
|
|
|
|
{"EstimateWithSuperhighPrice", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &recipient,
|
|
Gas: 0,
|
|
GasPrice: big.NewInt(2e14), // gascost = 4.2ether
|
|
Value: big.NewInt(100000000000),
|
|
Data: nil,
|
|
}, 21000, errors.New("gas required exceeds allowance (10999)")}, // 10999=(2.2ether-1000wei)/(2e14)
|
|
|
|
{"EstimateEIP1559WithHighFees", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &addr,
|
|
Gas: 0,
|
|
GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
|
|
GasTipCap: big.NewInt(1),
|
|
Value: big.NewInt(1e17), // the remaining balance for fee is 2.1ether
|
|
Data: nil,
|
|
}, params.TxGas, nil},
|
|
|
|
{"EstimateEIP1559WithSuperHighFees", ethereum.CallMsg{
|
|
From: addr,
|
|
To: &addr,
|
|
Gas: 0,
|
|
GasFeeCap: big.NewInt(1e14), // maxgascost = 2.1ether
|
|
GasTipCap: big.NewInt(1),
|
|
Value: big.NewInt(1e17 + 1), // the remaining balance for fee is 2.1ether
|
|
Data: nil,
|
|
}, params.TxGas, errors.New("gas required exceeds allowance (20999)")}, // 20999=(2.2ether-0.1ether-1wei)/(1e14)
|
|
}
|
|
|
|
for i, c := range cases {
|
|
got, err := sim.EstimateGas(context.Background(), c.message)
|
|
if c.expectError != nil {
|
|
if err == nil {
|
|
t.Fatalf("test %d: expect error, got nil", i)
|
|
}
|
|
|
|
if c.expectError.Error() != err.Error() {
|
|
t.Fatalf("test %d: expect error, want %v, got %v", i, c.expectError, err)
|
|
}
|
|
|
|
continue
|
|
}
|
|
|
|
if c.expectError == nil && err != nil {
|
|
t.Fatalf("test %d: didn't expect error, got %v", i, err)
|
|
}
|
|
|
|
if got != c.expect {
|
|
t.Fatalf("test %d: gas estimation mismatch, want %d, got %d", i, c.expect, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHeaderByHash(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
header, err := sim.HeaderByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
headerByHash, err := sim.HeaderByHash(bgCtx, header.Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get recent block: %v", err)
|
|
}
|
|
|
|
if header.Hash() != headerByHash.Hash() {
|
|
t.Errorf("did not get expected block")
|
|
}
|
|
}
|
|
|
|
func TestHeaderByNumber(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
latestBlockHeader, err := sim.HeaderByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get header for tip of chain: %v", err)
|
|
}
|
|
|
|
if latestBlockHeader == nil {
|
|
t.Errorf("received a nil block header")
|
|
} else if latestBlockHeader.Number.Uint64() != uint64(0) {
|
|
t.Errorf("expected block header number 0, instead got %v", latestBlockHeader.Number.Uint64())
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
latestBlockHeader, err = sim.HeaderByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get header for blockheight of 1: %v", err)
|
|
}
|
|
|
|
blockHeader, err := sim.HeaderByNumber(bgCtx, big.NewInt(1))
|
|
if err != nil {
|
|
t.Errorf("could not get header for blockheight of 1: %v", err)
|
|
}
|
|
|
|
if blockHeader.Hash() != latestBlockHeader.Hash() {
|
|
t.Errorf("block header and latest block header are not the same")
|
|
}
|
|
|
|
if blockHeader.Number.Int64() != int64(1) {
|
|
t.Errorf("did not get blockheader for block 1. instead got block %v", blockHeader.Number.Int64())
|
|
}
|
|
|
|
block, err := sim.BlockByNumber(bgCtx, big.NewInt(1))
|
|
if err != nil {
|
|
t.Errorf("could not get block for blockheight of 1: %v", err)
|
|
}
|
|
|
|
if block.Hash() != blockHeader.Hash() {
|
|
t.Errorf("block hash and block header hash do not match. expected %v, got %v", block.Hash(), blockHeader.Hash())
|
|
}
|
|
}
|
|
|
|
func TestTransactionCount(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
currentBlock, err := sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil || currentBlock == nil {
|
|
t.Error("could not get current block")
|
|
}
|
|
|
|
count, err := sim.TransactionCount(bgCtx, currentBlock.Hash())
|
|
if err != nil {
|
|
t.Error("could not get current block's transaction count")
|
|
}
|
|
|
|
if count != 0 {
|
|
t.Errorf("expected transaction count of %v does not match actual count of %v", 0, count)
|
|
}
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
lastBlock, err := sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get header for tip of chain: %v", err)
|
|
}
|
|
|
|
count, err = sim.TransactionCount(bgCtx, lastBlock.Hash())
|
|
if err != nil {
|
|
t.Error("could not get current block's transaction count")
|
|
}
|
|
|
|
if count != 1 {
|
|
t.Errorf("expected transaction count of %v does not match actual count of %v", 1, count)
|
|
}
|
|
}
|
|
|
|
func TestTransactionInBlock(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
transaction, err := sim.TransactionInBlock(bgCtx, sim.pendingBlock.Hash(), uint(0))
|
|
if err == nil && err != errTransactionDoesNotExist {
|
|
t.Errorf("expected a transaction does not exist error to be received but received %v", err)
|
|
}
|
|
|
|
if transaction != nil {
|
|
t.Errorf("expected transaction to be nil but received %v", transaction)
|
|
}
|
|
|
|
// expect pending nonce to be 0 since account has not been used
|
|
pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
|
|
if err != nil {
|
|
t.Errorf("did not get the pending nonce: %v", err)
|
|
}
|
|
|
|
if pendingNonce != uint64(0) {
|
|
t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
|
|
}
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
lastBlock, err := sim.BlockByNumber(bgCtx, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get header for tip of chain: %v", err)
|
|
}
|
|
|
|
transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(1))
|
|
if err == nil && err != errTransactionDoesNotExist {
|
|
t.Errorf("expected a transaction does not exist error to be received but received %v", err)
|
|
}
|
|
|
|
if transaction != nil {
|
|
t.Errorf("expected transaction to be nil but received %v", transaction)
|
|
}
|
|
|
|
transaction, err = sim.TransactionInBlock(bgCtx, lastBlock.Hash(), uint(0))
|
|
if err != nil {
|
|
t.Errorf("could not get transaction in the latest block with hash %v: %v", lastBlock.Hash().String(), err)
|
|
}
|
|
|
|
if signedTx.Hash().String() != transaction.Hash().String() {
|
|
t.Errorf("received transaction that did not match the sent transaction. expected hash %v, got hash %v", signedTx.Hash().String(), transaction.Hash().String())
|
|
}
|
|
}
|
|
|
|
func TestPendingNonceAt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
// expect pending nonce to be 0 since account has not been used
|
|
pendingNonce, err := sim.PendingNonceAt(bgCtx, testAddr)
|
|
if err != nil {
|
|
t.Errorf("did not get the pending nonce: %v", err)
|
|
}
|
|
|
|
if pendingNonce != uint64(0) {
|
|
t.Errorf("expected pending nonce of 0 got %v", pendingNonce)
|
|
}
|
|
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
// expect pending nonce to be 1 since account has submitted one transaction
|
|
pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
|
|
if err != nil {
|
|
t.Errorf("did not get the pending nonce: %v", err)
|
|
}
|
|
|
|
if pendingNonce != uint64(1) {
|
|
t.Errorf("expected pending nonce of 1 got %v", pendingNonce)
|
|
}
|
|
|
|
// make a new transaction with a nonce of 1
|
|
tx = types.NewTransaction(uint64(1), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err = types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not send tx: %v", err)
|
|
}
|
|
|
|
// expect pending nonce to be 2 since account now has two transactions
|
|
pendingNonce, err = sim.PendingNonceAt(bgCtx, testAddr)
|
|
if err != nil {
|
|
t.Errorf("did not get the pending nonce: %v", err)
|
|
}
|
|
|
|
if pendingNonce != uint64(2) {
|
|
t.Errorf("expected pending nonce of 2 got %v", pendingNonce)
|
|
}
|
|
}
|
|
|
|
func TestTransactionReceipt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
// create a signed transaction to send
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
tx := types.NewTransaction(uint64(0), testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
|
|
signedTx, err := types.SignTx(tx, types.HomesteadSigner{}, testKey)
|
|
if err != nil {
|
|
t.Errorf("could not sign tx: %v", err)
|
|
}
|
|
|
|
// send tx to simulated backend
|
|
err = sim.SendTransaction(bgCtx, signedTx)
|
|
if err != nil {
|
|
t.Errorf("could not add tx to pending block: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
receipt, err := sim.TransactionReceipt(bgCtx, signedTx.Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get transaction receipt: %v", err)
|
|
}
|
|
|
|
if receipt.ContractAddress != testAddr && receipt.TxHash != signedTx.Hash() {
|
|
t.Errorf("received receipt is not correct: %v", receipt)
|
|
}
|
|
}
|
|
|
|
func TestSuggestGasPrice(t *testing.T) {
|
|
t.Parallel()
|
|
sim := NewSimulatedBackend(
|
|
core.GenesisAlloc{},
|
|
10000000,
|
|
)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
gasPrice, err := sim.SuggestGasPrice(bgCtx)
|
|
if err != nil {
|
|
t.Errorf("could not get gas price: %v", err)
|
|
}
|
|
|
|
if gasPrice.Uint64() != sim.pendingBlock.Header().BaseFee.Uint64() {
|
|
t.Errorf("gas price was not expected value of %v. actual: %v", sim.pendingBlock.Header().BaseFee.Uint64(), gasPrice.Uint64())
|
|
}
|
|
}
|
|
|
|
func TestPendingCodeAt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
code, err := sim.CodeAt(bgCtx, testAddr, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
if len(code) != 0 {
|
|
t.Errorf("got code for account that does not have contract code")
|
|
}
|
|
|
|
parsed, err := abi.JSON(strings.NewReader(abiJSON))
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
|
|
contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
|
|
if err != nil {
|
|
t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
|
|
}
|
|
|
|
code, err = sim.PendingCodeAt(bgCtx, contractAddr)
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
if len(code) == 0 {
|
|
t.Errorf("did not get code for account that has contract code")
|
|
}
|
|
// ensure code received equals code deployed
|
|
if !bytes.Equal(code, common.FromHex(deployedCode)) {
|
|
t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
|
|
}
|
|
}
|
|
|
|
func TestCodeAt(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
code, err := sim.CodeAt(bgCtx, testAddr, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
if len(code) != 0 {
|
|
t.Errorf("got code for account that does not have contract code")
|
|
}
|
|
|
|
parsed, err := abi.JSON(strings.NewReader(abiJSON))
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
|
|
contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
|
|
if err != nil {
|
|
t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
|
|
}
|
|
|
|
sim.Commit()
|
|
|
|
code, err = sim.CodeAt(bgCtx, contractAddr, nil)
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
if len(code) == 0 {
|
|
t.Errorf("did not get code for account that has contract code")
|
|
}
|
|
// ensure code received equals code deployed
|
|
if !bytes.Equal(code, common.FromHex(deployedCode)) {
|
|
t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
|
|
}
|
|
}
|
|
|
|
func TestCodeAtHash(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
bgCtx := context.Background()
|
|
code, err := sim.CodeAtHash(bgCtx, testAddr, sim.Blockchain().CurrentHeader().Hash())
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
if len(code) != 0 {
|
|
t.Errorf("got code for account that does not have contract code")
|
|
}
|
|
|
|
parsed, err := abi.JSON(strings.NewReader(abiJSON))
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
contractAddr, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(abiBin), sim)
|
|
if err != nil {
|
|
t.Errorf("could not deploy contract: %v tx: %v contract: %v", err, tx, contract)
|
|
}
|
|
|
|
blockHash := sim.Commit()
|
|
code, err = sim.CodeAtHash(bgCtx, contractAddr, blockHash)
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
if len(code) == 0 {
|
|
t.Errorf("did not get code for account that has contract code")
|
|
}
|
|
// ensure code received equals code deployed
|
|
if !bytes.Equal(code, common.FromHex(deployedCode)) {
|
|
t.Errorf("code received did not match expected deployed code:\n expected %v\n actual %v", common.FromHex(deployedCode), code)
|
|
}
|
|
}
|
|
|
|
// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt:
|
|
//
|
|
// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]}
|
|
func TestPendingAndCallContract(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
parsed, err := abi.JSON(strings.NewReader(abiJSON))
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
|
|
addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(abiBin), sim)
|
|
if err != nil {
|
|
t.Errorf("could not deploy contract: %v", err)
|
|
}
|
|
|
|
input, err := parsed.Pack("receive", []byte("X"))
|
|
if err != nil {
|
|
t.Errorf("could not pack receive function on contract: %v", err)
|
|
}
|
|
|
|
// make sure you can call the contract in pending state
|
|
res, err := sim.PendingCallContract(bgCtx, ethereum.CallMsg{
|
|
From: testAddr,
|
|
To: &addr,
|
|
Data: input,
|
|
})
|
|
if err != nil {
|
|
t.Errorf("could not call receive method on contract: %v", err)
|
|
}
|
|
|
|
if len(res) == 0 {
|
|
t.Errorf("result of contract call was empty: %v", res)
|
|
}
|
|
|
|
// while comparing against the byte array is more exact, also compare against the human readable string for readability
|
|
if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
|
|
t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
|
|
}
|
|
|
|
blockHash := sim.Commit()
|
|
|
|
// make sure you can call the contract
|
|
res, err = sim.CallContract(bgCtx, ethereum.CallMsg{
|
|
From: testAddr,
|
|
To: &addr,
|
|
Data: input,
|
|
}, nil)
|
|
if err != nil {
|
|
t.Errorf("could not call receive method on contract: %v", err)
|
|
}
|
|
|
|
if len(res) == 0 {
|
|
t.Errorf("result of contract call was empty: %v", res)
|
|
}
|
|
|
|
if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
|
|
t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
|
|
}
|
|
|
|
// make sure you can call the contract by hash
|
|
res, err = sim.CallContractAtHash(bgCtx, ethereum.CallMsg{
|
|
From: testAddr,
|
|
To: &addr,
|
|
Data: input,
|
|
}, blockHash)
|
|
if err != nil {
|
|
t.Errorf("could not call receive method on contract: %v", err)
|
|
}
|
|
if len(res) == 0 {
|
|
t.Errorf("result of contract call was empty: %v", res)
|
|
}
|
|
|
|
if !bytes.Equal(res, expectedReturn) || !strings.Contains(string(res), "hello world") {
|
|
t.Errorf("response from calling contract was expected to be 'hello world' instead received %v", string(res))
|
|
}
|
|
}
|
|
|
|
// This test is based on the following contract:
|
|
/*
|
|
contract Reverter {
|
|
function revertString() public pure{
|
|
require(false, "some error");
|
|
}
|
|
function revertNoString() public pure {
|
|
require(false, "");
|
|
}
|
|
function revertASM() public pure {
|
|
assembly {
|
|
revert(0x0, 0x0)
|
|
}
|
|
}
|
|
function noRevert() public pure {
|
|
assembly {
|
|
// Assembles something that looks like require(false, "some error") but is not reverted
|
|
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
|
|
mstore(0x4, 0x0000000000000000000000000000000000000000000000000000000000000020)
|
|
mstore(0x24, 0x000000000000000000000000000000000000000000000000000000000000000a)
|
|
mstore(0x44, 0x736f6d65206572726f7200000000000000000000000000000000000000000000)
|
|
return(0x0, 0x64)
|
|
}
|
|
}
|
|
}*/
|
|
func TestCallContractRevert(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
|
|
bgCtx := context.Background()
|
|
|
|
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"}]`
|
|
reverterBin := "608060405234801561001057600080fd5b506101d3806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80634b409e01146100515780639b340e361461005b5780639bd6103714610065578063b7246fc11461006f575b600080fd5b610059610079565b005b6100636100ca565b005b61006d6100cf565b005b610077610145565b005b60006100c8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526000815260200160200191505060405180910390fd5b565b600080fd5b6000610143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f736f6d65206572726f720000000000000000000000000000000000000000000081525060200191505060405180910390fd5b565b7f08c379a0000000000000000000000000000000000000000000000000000000006000526020600452600a6024527f736f6d65206572726f720000000000000000000000000000000000000000000060445260646000f3fea2646970667358221220cdd8af0609ec4996b7360c7c780bad5c735740c64b1fffc3445aa12d37f07cb164736f6c63430006070033"
|
|
|
|
parsed, err := abi.JSON(strings.NewReader(reverterABI))
|
|
if err != nil {
|
|
t.Errorf("could not get code at test addr: %v", err)
|
|
}
|
|
|
|
contractAuth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
|
|
addr, _, _, err := bind.DeployContract(contractAuth, parsed, common.FromHex(reverterBin), sim)
|
|
if err != nil {
|
|
t.Errorf("could not deploy contract: %v", err)
|
|
}
|
|
|
|
inputs := make(map[string]interface{}, 3)
|
|
inputs["revertASM"] = nil
|
|
inputs["revertNoString"] = ""
|
|
inputs["revertString"] = "some error"
|
|
|
|
call := make([]func([]byte) ([]byte, error), 2)
|
|
call[0] = func(input []byte) ([]byte, error) {
|
|
return sim.PendingCallContract(bgCtx, ethereum.CallMsg{
|
|
From: testAddr,
|
|
To: &addr,
|
|
Data: input,
|
|
})
|
|
}
|
|
call[1] = func(input []byte) ([]byte, error) {
|
|
return sim.CallContract(bgCtx, ethereum.CallMsg{
|
|
From: testAddr,
|
|
To: &addr,
|
|
Data: input,
|
|
}, nil)
|
|
}
|
|
|
|
// Run pending calls then commit
|
|
for _, cl := range call {
|
|
for key, val := range inputs {
|
|
input, err := parsed.Pack(key)
|
|
if err != nil {
|
|
t.Errorf("could not pack %v function on contract: %v", key, err)
|
|
}
|
|
|
|
res, err := cl(input)
|
|
if err == nil {
|
|
t.Errorf("call to %v was not reverted", key)
|
|
}
|
|
|
|
if res != nil {
|
|
t.Errorf("result from %v was not nil: %v", key, res)
|
|
}
|
|
|
|
if val != nil {
|
|
rerr, ok := err.(*revertError)
|
|
if !ok {
|
|
t.Errorf("expect revert error")
|
|
}
|
|
|
|
if rerr.Error() != "execution reverted: "+val.(string) {
|
|
t.Errorf("error was malformed: got %v want %v", rerr.Error(), val)
|
|
}
|
|
} else {
|
|
// revert(0x0,0x0)
|
|
if err.Error() != "execution reverted" {
|
|
t.Errorf("error was malformed: got %v want %v", err, "execution reverted")
|
|
}
|
|
}
|
|
}
|
|
|
|
input, err := parsed.Pack("noRevert")
|
|
if err != nil {
|
|
t.Errorf("could not pack noRevert function on contract: %v", err)
|
|
}
|
|
|
|
res, err := cl(input)
|
|
if err != nil {
|
|
t.Error("call to noRevert was reverted")
|
|
}
|
|
|
|
if res == nil {
|
|
t.Errorf("result from noRevert was nil")
|
|
}
|
|
|
|
sim.Commit()
|
|
}
|
|
}
|
|
|
|
// TestFork check that the chain length after a reorg is correct.
|
|
// Steps:
|
|
// 1. Save the current block which will serve as parent for the fork.
|
|
// 2. Mine n blocks with n ∈ [0, 20].
|
|
// 3. Assert that the chain length is n.
|
|
// 4. Fork by using the parent block as ancestor.
|
|
// 5. Mine n+1 blocks which should trigger a reorg.
|
|
// 6. Assert that the chain length is n+1.
|
|
// Since Commit() was called 2n+1 times in total,
|
|
// having a chain length of just n+1 means that a reorg occurred.
|
|
func TestFork(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
// 1.
|
|
parent := sim.blockchain.CurrentBlock()
|
|
// 2.
|
|
n := int(rand.Int31n(21))
|
|
for i := 0; i < n; i++ {
|
|
sim.Commit()
|
|
}
|
|
// 3.
|
|
if sim.blockchain.CurrentBlock().Number.Uint64() != uint64(n) {
|
|
t.Error("wrong chain length")
|
|
}
|
|
// 4.
|
|
sim.Fork(context.Background(), parent.Hash())
|
|
// 5.
|
|
for i := 0; i < n+1; i++ {
|
|
sim.Commit()
|
|
}
|
|
// 6.
|
|
if sim.blockchain.CurrentBlock().Number.Uint64() != uint64(n+1) {
|
|
t.Error("wrong chain length")
|
|
}
|
|
}
|
|
|
|
/*
|
|
Example contract to test event emission:
|
|
|
|
pragma solidity >=0.7.0 <0.9.0;
|
|
contract Callable {
|
|
event Called();
|
|
function Call() public { emit Called(); }
|
|
}
|
|
*/
|
|
const callableAbi = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"Called\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"Call\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
|
|
|
|
const callableBin = "6080604052348015600f57600080fd5b5060998061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806334e2292114602d575b600080fd5b60336035565b005b7f81fab7a4a0aa961db47eefc81f143a5220e8c8495260dd65b1356f1d19d3c7b860405160405180910390a156fea2646970667358221220029436d24f3ac598ceca41d4d712e13ced6d70727f4cdc580667de66d2f51d8b64736f6c63430008010033"
|
|
|
|
// TestForkLogsReborn check that the simulated reorgs
|
|
// correctly remove and reborn logs.
|
|
// Steps:
|
|
// 1. Deploy the Callable contract.
|
|
// 2. Set up an event subscription.
|
|
// 3. Save the current block which will serve as parent for the fork.
|
|
// 4. Send a transaction.
|
|
// 5. Check that the event was included.
|
|
// 6. Fork by using the parent block as ancestor.
|
|
// 7. Mine two blocks to trigger a reorg.
|
|
// 8. Check that the event was removed.
|
|
// 9. Re-send the transaction and mine a block.
|
|
// 10. Check that the event was reborn.
|
|
func TestForkLogsReborn(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
// 1.
|
|
parsed, _ := abi.JSON(strings.NewReader(callableAbi))
|
|
auth, _ := bind.NewKeyedTransactorWithChainID(testKey, big.NewInt(1337))
|
|
|
|
_, _, contract, err := bind.DeployContract(auth, parsed, common.FromHex(callableBin), sim)
|
|
if err != nil {
|
|
t.Errorf("deploying contract: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
// 2.
|
|
logs, sub, err := contract.WatchLogs(nil, "Called")
|
|
if err != nil {
|
|
t.Errorf("watching logs: %v", err)
|
|
}
|
|
defer sub.Unsubscribe()
|
|
// 3.
|
|
parent := sim.blockchain.CurrentBlock()
|
|
// 4.
|
|
tx, err := contract.Transact(auth, "Call")
|
|
if err != nil {
|
|
t.Errorf("transacting: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
// 5.
|
|
log := <-logs
|
|
if log.TxHash != tx.Hash() {
|
|
t.Error("wrong event tx hash")
|
|
}
|
|
|
|
if log.Removed {
|
|
t.Error("Event should be included")
|
|
}
|
|
// 6.
|
|
if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
|
|
t.Errorf("forking: %v", err)
|
|
}
|
|
// 7.
|
|
sim.Commit()
|
|
sim.Commit()
|
|
// 8.
|
|
log = <-logs
|
|
if log.TxHash != tx.Hash() {
|
|
t.Error("wrong event tx hash")
|
|
}
|
|
|
|
if !log.Removed {
|
|
t.Error("Event should be removed")
|
|
}
|
|
// 9.
|
|
if err := sim.SendTransaction(context.Background(), tx); err != nil {
|
|
t.Errorf("sending transaction: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
// 10.
|
|
log = <-logs
|
|
if log.TxHash != tx.Hash() {
|
|
t.Error("wrong event tx hash")
|
|
}
|
|
|
|
if log.Removed {
|
|
t.Error("Event should be included")
|
|
}
|
|
}
|
|
|
|
// TestForkResendTx checks that re-sending a TX after a fork
|
|
// is possible and does not cause a "nonce mismatch" panic.
|
|
// Steps:
|
|
// 1. Save the current block which will serve as parent for the fork.
|
|
// 2. Send a transaction.
|
|
// 3. Check that the TX is included in block 1.
|
|
// 4. Fork by using the parent block as ancestor.
|
|
// 5. Mine a block, Re-send the transaction and mine another one.
|
|
// 6. Check that the TX is now included in block 2.
|
|
func TestForkResendTx(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
|
|
sim := simTestBackend(testAddr)
|
|
defer sim.Close()
|
|
// 1.
|
|
parent := sim.blockchain.CurrentBlock()
|
|
// 2.
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
|
|
_tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey)
|
|
sim.SendTransaction(context.Background(), tx)
|
|
sim.Commit()
|
|
// 3.
|
|
receipt, _ := sim.TransactionReceipt(context.Background(), tx.Hash())
|
|
if h := receipt.BlockNumber.Uint64(); h != 1 {
|
|
t.Errorf("TX included in wrong block: %d", h)
|
|
}
|
|
// 4.
|
|
if err := sim.Fork(context.Background(), parent.Hash()); err != nil {
|
|
t.Errorf("forking: %v", err)
|
|
}
|
|
// 5.
|
|
sim.Commit()
|
|
|
|
if err := sim.SendTransaction(context.Background(), tx); err != nil {
|
|
t.Errorf("sending transaction: %v", err)
|
|
}
|
|
|
|
sim.Commit()
|
|
// 6.
|
|
receipt, _ = sim.TransactionReceipt(context.Background(), tx.Hash())
|
|
if h := receipt.BlockNumber.Uint64(); h != 2 {
|
|
t.Errorf("TX included in wrong block: %d", h)
|
|
}
|
|
}
|
|
|
|
func TestCommitReturnValue(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
sim := simTestBackend(testAddr)
|
|
|
|
defer sim.Close()
|
|
|
|
startBlockHeight := sim.blockchain.CurrentBlock().Number.Uint64()
|
|
|
|
// Test if Commit returns the correct block hash
|
|
h1 := sim.Commit()
|
|
if h1 != sim.blockchain.CurrentBlock().Hash() {
|
|
t.Error("Commit did not return the hash of the last block.")
|
|
}
|
|
|
|
// Create a block in the original chain (containing a transaction to force different block hashes)
|
|
head, _ := sim.HeaderByNumber(context.Background(), nil) // Should be child's, good enough
|
|
gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1))
|
|
_tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil)
|
|
tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey)
|
|
_ = sim.SendTransaction(context.Background(), tx)
|
|
h2 := sim.Commit()
|
|
|
|
// Create another block in the original chain
|
|
sim.Commit()
|
|
|
|
// Fork at the first bock
|
|
if err := sim.Fork(context.Background(), h1); err != nil {
|
|
t.Errorf("forking: %v", err)
|
|
}
|
|
|
|
// Test if Commit returns the correct block hash after the reorg
|
|
h2fork := sim.Commit()
|
|
if h2 == h2fork {
|
|
t.Error("The block in the fork and the original block are the same block!")
|
|
}
|
|
|
|
if sim.blockchain.GetHeader(h2fork, startBlockHeight+2) == nil {
|
|
t.Error("Could not retrieve the just created block (side-chain)")
|
|
}
|
|
}
|
|
|
|
// TestAdjustTimeAfterFork ensures that after a fork, AdjustTime uses the pending fork
|
|
// block's parent rather than the canonical head's parent.
|
|
func TestAdjustTimeAfterFork(t *testing.T) {
|
|
t.Parallel()
|
|
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
|
|
sim := simTestBackend(testAddr)
|
|
|
|
defer sim.Close()
|
|
|
|
sim.Commit() // h1
|
|
h1 := sim.blockchain.CurrentHeader().Hash()
|
|
sim.Commit() // h2
|
|
_ = sim.Fork(context.Background(), h1)
|
|
_ = sim.AdjustTime(1 * time.Second)
|
|
sim.Commit()
|
|
|
|
head := sim.blockchain.CurrentHeader()
|
|
if head.Number == common.Big2 && head.ParentHash != h1 {
|
|
t.Errorf("failed to build block on fork")
|
|
}
|
|
}
|