Commit Graph

1081 Commits

Author SHA1 Message Date
Jamie Lokier fdebf6c1f7
EVM: Remove unused file `vm_message`
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 16:54:38 +01:00
Jamie Lokier 5e718bcbe2
EVM: Remove most unused imports of `vm_*` files
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 16:54:38 +01:00
Jamie Lokier beb750b8df
Transaction: Remove no longer used `setupComputation`
The last caller of `setupComputation` is gone, now that it's been replaced by
the single entry point for all EVM calls, `runComputation`.

With this removal, EVM's `Computation` type should no longer be used anywhere
outside the call module (except in some tests and the EVM itself).

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 16:54:34 +01:00
Jamie Lokier 8b4f5a1103 Transaction: Change transactions to go through unified EVM runner
Simplify transaction validations to use `runComputation`; drop other code.

Getting everything right up to this point to pass all the tests was trickier
than it looks.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 18:40:41 +03:00
Jamie Lokier bf6569bdeb Assembler: Change assembler tests to go through unified EVM runner
Simplify how assembler tests are run to use `runComputation`; drop other code.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 18:40:41 +03:00
Jamie Lokier 9211a15c0a Fixtures: Change JSON fixture tests to go through unified EVM runner
Simplify how JSON fixtures tests are run to use `runComputation`.
Drop other code.

These use the `noTransfer` option, which is similar enough to calling
`c.executeOpcodes()` instead of `c.execComputation()`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 18:40:41 +03:00
Jamie Lokier 5fb3c51e5e Transaction: Skip balance & nonce updates option in `runComputation`
Add another flag to disable a processing step when a call doesn't come from
a real transaction:

- `noTransfer`: Don't update balances, nonces, code.

This is to support VM fixtures tests which require account balances and nonces
to be unchanged when running the account's code.

These tests call `c.executeOpcodes()`, an internal function of the EVM, instead
of the usual `c.execComputation()`.  It goes direct to the bytecode dispatcher,
skipping parts of `Computation` that are normally called.

But we can't keep calling `c.executeOpcodes()` and have a single entry point to
the VM, let alone an EVMC entry point.

`noTransfer` provides similar enough behaviour to calling `c.executeOpcodes()`
that these tests can use the new single entry point like everything else.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-06-01 18:40:41 +03:00
Jamie Lokier deffa20b07
RPC and GraphQL: Change `estimateGas` to go through unified EVM runner
Simplify `estimateGas` to use `runComputation`; drop other code.

The RPC/GraphQL `estimateGas` operation is quite different from the `call`
operation.  It is much more like ordinary transaction execution than `call`,
though there are still enough differences that tx validation cannot be used.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 08:23:20 +01:00
Jamie Lokier b16aa2f1f7
RPC and GraphQL: Change `call` op to go through unified EVM runner
Simplify `call` to use `runComputation`; drop other code.

The RPC/GraphQL `call` operation differs in many ways from regular transaction
calls.  The following flags are set, to disable various steps in processing.
All four are true (disabling the corresponding step) for `call`:

- `noIntrinsic`:  Don't charge intrinsic gas.
- `noAccessList`: Don't initialise EIP2929 access list.
- `noGasCharge`:  Don't charge sender account for gas.
- `noRefund`:     Don't apply gas refund/burn rule.

Interestingly, the RPC/GraphQL `estimateGas` operation doesn't behave so
differently from regular transactions.  It might be that not all these steps
should be disabled for `call` either.  But until we investigate what
RPC/GraphQL clients are expecting, keep the same behaviour as before.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 08:23:20 +01:00
Jamie Lokier 306c8e92c2
Transaction: `runComputation` options for non-standard EVM behaviour
The following four flags are added, to change various steps in EVM processing
when a call doesn't come from a real transaction:

- `noIntrinsic`:  Don't charge intrinsic gas.
- `noAccessList`: Don't initialise EIP2929 access list.
- `noGasCharge`:  Don't charge sender account for gas.
- `noRefund`:     Don't apply gas refund/burn rule.

This is to support RPC and GraphQL `call` operations, which behave differently
in some ways from regular transaction calls, and to support some test suites.

In EVMC terms, all these alterations can be performed on the host side.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 08:23:19 +01:00
Jamie Lokier 12bf0fd346
Transaction: EIP-2930 (Berlin): Extra intrinsic gas for access list
Calculate extra intrinsic gas for an EIP-2930 transaction with access list.

While we're here, do the rest of the intrinsic gas calculation.  Make it clear,
explicit and in one place.  (Previous code delegated parts of the calculation
to `transaction.nim` but had to do the rest locally due to mismatched types.)

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 06:54:19 +01:00
Jamie Lokier f6cc6e3ed1
Transaction: EIP-2930 (Berlin): Per-transaction extra access list
Add `accessList` to the `runComputation` API for EIP-2930 transactions.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 06:53:11 +01:00
Jamie Lokier 76031ccbe4
Transaction: EIP-2929 (Berlin): Initial access list
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 06:53:11 +01:00
Jamie Lokier c6d50a0ef7
Transaction: Unified runner `runComputation` for all EVM call types
New entry point `runComputation`, for all EVM calls.
(Later the intent is `runComputationAsync`.)

As noted in commit 297d789, there are six entry points calling EVM computation,
with different parameters and expecting different behaviours.  Parameters were
dealt with in `setupComputation`.  Behaviours are unified in `runComputation`,
with options passed via `CallParams`.

This code performs the steps used when validating a transaction.  Options for
non-standard behaviour for RPC, GraphQL and tests to be added as required.

This replaces `setupComputation`, `execComputation` and `executeOpcodes`
(other than its own calls).  As a result `Computation` and other EVM types are
no longer referenced in the main program, and many imports can be dropped.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 06:53:11 +01:00
Jamie Lokier 94f95efd9e
Transaction: Move `setupComputation` to its own file
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-29 06:53:11 +01:00
Jamie Lokier 4e51a5bb35
Fixtures: Change fixture tests to use shared `setupComputation`
Change fixtures tests to use shared `setupComputation` instead of
their own slightly different variant.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 16:48:09 +01:00
Jamie Lokier a5385e5344 RPC/GraphQL: Change RPC/GraphQL to use shared `setupComputation`
Change RPC/GraphQL calls to the EVM to use shared `setupComputation`
instead of their own special variant.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 16:10:19 +01:00
Jamie Lokier 8b33cbe568
Assembler: Change assembler tests to use shared `setupComputation`
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 15:50:02 +01:00
Jamie Lokier c655d59b5f
Assembler: Rearrange logic where assembler tests call EVM
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 15:49:58 +01:00
Jamie Lokier 0d3117344a
Transaction: Change tx validation to use shared `setupComputation`
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 15:22:06 +01:00
Jamie Lokier 297d789d21
Transaction: Merge entry point for `*...SetupComputation` functions
There are currently six entry points to running an EVM computation, all with
slightly different parameters, and expecting slightly different EVM behaviours.

First step in merging them is a common `setupComputation` that replaces all
the different `*...SetupComputation` functions.

This uses the `TransactionHost` type because it's a step towards using that
type for all EVM calls using only EVMC.  For now an EVMC message is created
then translated to EVM-internal `Message`.  It is done this way to build up
the new interface in stages where all tests pass at each stage.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 12:12:10 +01:00
Jamie Lokier e60ad129a2
Transaction: New object `TransactionHost` for "EVMC host services"
`TransactionHost` represents the interface to the EVM from the application once
we've fully transitioned to EVMC.  It represents a managed EVM call, and the
"EVMC host" side of the host<->EVM boundary.

This holds transaction state which sits outside the EVM, but a pointer to this
is passed around by the EVM as _opaque_ type `evmc_host_context`.

To the EVM, this offers "host services", which manage account state that the
EVM cannot do, such as balance transfers, call costs, storage, logs, gas
refunds, nested calls and new contract addresses.  The EVM has no direct access
to the account state database or network; it's all via "host services".

To the application (host side), this object represents a managed EVM call, with
inputs, a method to run, outputs, hidden transaction state, and later async
scheduling.  It is to replace `Computation` on the application side, while
`Computation` will remain but just be for the EVM side.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-28 12:12:02 +01:00
Jamie Lokier 537cac1bf5
EVM: Move where `continuation` is cleared to fix a potential stall
This fixes a bug spotted by @mjfh that was introduced by commit 2a7ccceb:

    try:
      if not c.continuation.isNil:
        (c.continuation)()
        c.continuation = nil
      c.selectVM(fork)
    except CatchableError as e:
      ...

The call to `(c.continuation)()` was moved by 2a7ccceb inside the `try` so
that, like all the Op functions do already, if the continuation raises, the
interpreter's general catch turns the exception into a an error status result.

But if the continuation raises an exception, `continuation` is not cleared in
the next line, and at the next resumption the continuation is called again.
It may loop doing this.

This doesn't currently happen because the continuations don't really raise, but
it's still a correctness issue.

This fix also allows a continuation to spawn a second continuation, if it
encounters a second suspension point.  This also doesn't happen currently,
but the pattern will become useful with async EVM.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-27 12:16:37 +01:00
Jamie Lokier 90a961243e
Clear up meaning of `ZERO_ADDRESS`, delete `CREATE_CONTRACT_ADDRESS`
There is no valid `CREATE_CONTRACT_ADDRESS`.  Some places on the internet say
account zero means contract creation, but that's not correct.

Transactions to `ZERO_ADDRESS` are legitimate transfers to that account, not
contract creations.  They are used to "burn" Eth.  People also send Eth to
address zero by accident, unrecoverably, due to poor user interface issues.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-27 12:14:51 +01:00
Jamie Lokier 745129c4ac
Transaction: Don't calculate `contractAddress` redundantly
Each place in `call_evm` that sets up an EVM call calculates the new contract
address for contract creations.  But it's redundant, because `newComputation`
ignores the provided value and does the calculation again.

Remove the unused address calculation.

This is also a step to merging different entry points and EVMC.  This change
ends up with the same value in both `msg.contractAddress` and `msg.codeAddress`
for every entry point, and this is good because it matches the EVMC message
structure, where they are replaced by only one value called `msg.destination`

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-27 12:01:47 +01:00
Jamie Lokier fa74dc909e
Fixtures: Verify EVM continuation is clear after `c.executeOpcodes`
`c.executeOpcodes` is called by some JSON fixture tests.  These tests bypass
some of the setup and return, and because of this call, continuations aren't
processed either.  Opcodes that use continuations will behave incorrectly.

The opcodes used in these particular tests don't use continuations currently,
so just add some assertions to verify this remains the case.

This is only used by local tests, and the call to `c.executeOpcodes` will be
replaced by the common entry point (that handles things like this correctly in
all cases) so we don't need to spend more time on this.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-27 11:54:44 +01:00
jangko 5fc57e4093
add validateKinship in persistBlocks of nimbus/p2p/chain.nim
put jordan's work #668 into effect, and this bring down
failing consensus test cases from 59 to 44
2021-05-27 16:28:26 +07:00
Jordan Hrycaj e5947f4db6 Deep copy semantics for LRU cache
why:
  follows standard nim semantics

details:
  changed Table to TableRef in previous patch which was the
  wrong choice (see andri's comment.)
2021-05-26 11:12:52 +01:00
Jordan Hrycaj 7b72109afa Use sorted RLP serialisation for LRU cache
why:
  previously, table data were stored with the table iterator. while
  loading a table with permuted entries will always reconstruct equivalent
  tables (in the sense of `==`), serialisation data are not comparable.

  this patch produces always the same serialised data for equivalent
  tables.
2021-05-26 07:58:12 +01:00
Jordan Hrycaj b83b47e541 LRU cache tests makeover
why:
  source-local unit tests would hardly be triggered by github CI as rightly
  criticised with the last patch.

details:
  source-local unit tests have been moved to tests folder.

  this version also contains rlp serialisation code so rlp encode/decode
  will apply tranparently. this is not needed in p2p/validate but will be
   useful with the clique protocol.
2021-05-26 07:58:12 +01:00
jangko 396f3e9909
add missing poaEngine configuration in config.nim
later we will use real engine configuration it if become available to us
2021-05-24 14:35:47 +07:00
Jordan Hrycaj 179cc75c32 Update LRU complexity comment
why:
  hash tables might worst-case degrade into linear mode, so it is not
  strictly O(1)
2021-05-24 07:57:21 +01:00
Jordan Hrycaj 1965ea027b updated LRU cache to run with complexity O(1)
why:
  to be used in Clique consensus protocol which suggests 4k cache entries.
  the previous implementation used OrderTable[] which has complexity O(n)
  for deleting entries.
2021-05-24 07:57:21 +01:00
Jordan Hrycaj a5e0bb6139 use general lru_cache for EpochHashCache
why:
  generic implementation will be also be used elsewhere
2021-05-24 07:57:21 +01:00
Jordan Hrycaj 3663b1603f pulled out cache logic into separate file
why:
  handy to re-use, eg. for upcoming clique implementation
2021-05-24 07:57:21 +01:00
Jordan Hrycaj d6a5cecb98 re-wrote validation with exceptionless functions
why:
  exceptions were from test code should be avoided in production code
2021-05-24 07:57:21 +01:00
Jordan Hrycaj 40c7bdfc06 update lookup cache management
details:
  enable fifo behaviour, using cache as argument
2021-05-24 07:57:21 +01:00
Jordan Hrycaj ce8e5511e3 backport from test_blockchain_json, see issue #666 2021-05-24 07:57:21 +01:00
jangko b82061bf46
don't mix customBootNodes and bootNodes usage 2021-05-20 14:04:17 +07:00
jangko a0d10f5728
drop PublicNetwork enum usage and replace it with NetworkId
we cannot limit the `--networkid` switch to values available in
`PublicNetwork` enum. it should able to accept very wide range of
custom NetworkId.
2021-05-20 14:04:16 +07:00
jangko ec1af91370
implement "net_nodeInfo" rpc
fixes #569
2021-05-19 16:35:13 +07:00
jangko 0ecf9fe1af
add more query fields and resolvers to graphql api
after EIP2718/EIP2930, we have additional fields:

type AccessTuple {
  address: Address!
  storageKeys : [Bytes32!]
}

type Transaction {
  r: BigInt!
  s: BigInt!
  v: BigInt!
  # Envelope transaction support
  type: Int
  accessList: [AccessTuple!]
}

close #606
2021-05-18 07:32:03 +07:00
jangko d2b47139e1
fixes `importRlpBlocks` in conf_utils.nim
now we are importing block one by one to satisfy
some of hive test cases.

we also catch exception instead of letting it terminate the
process.
2021-05-17 18:43:44 +07:00
jangko 76543da456
disable EIP-2537: Precompile for BLS12-381 curve operations
reason: not included in berlin hard fork

but we keep the code around, for future inclusion
2021-05-17 01:29:03 +07:00
jangko 3ccc4642f2
disable EIP-2315: Simple Subroutines for the EVM
reason: not included in berlin hard fork
2021-05-17 01:29:03 +07:00
jangko 6fc3df637c
reenable EIP-2565: modExp gas cost
now it's officially included in berlin hard fork
2021-05-17 01:28:31 +07:00
jangko 01a27ff328
EIP-2930: optional access list
the new AccessListTx contains address and storage keys
that will go into global access list. and this come with
prices.... in ether
2021-05-16 19:54:48 +07:00
jangko a2f77e8627
eip2718: rename vm2 ChainId op code to ChainIdOp
this is to avoid clash with ChainId type
imported from eth/common
2021-05-15 18:09:36 +07:00
jangko 87c6ec7309
eip2718: add tx validate for AccessListTx 2021-05-15 18:09:36 +07:00
jangko 77f080c8c2
eip2718: nimbus is compileable 2021-05-15 18:09:36 +07:00
jangko 79044f1e92
eip2718: test_blockchain_json pass test 2021-05-15 18:09:35 +07:00
jangko f2491e6307
fixes crappy custom genesis and chain config parser
instead of using stdlib/json, now we switch to json_serialization
the result is much tidier code and more robust when parsing
optional fields.

fixes #635
2021-05-13 16:04:08 +07:00
jangko a57ac65c8c
fixes --customnetwork parser
now it can ignore an optional fork e.g. MuirGlacier
2021-05-12 19:05:32 +07:00
jangko 97f4226171
update berlin fork number in config.nim
also update test_forkid because of berlin changes
2021-05-12 17:24:27 +07:00
jangko 5ee918f4ef
fixes test_graphql crash due to recent changes related to `chainId`
now test_graphql takes another route to initialize the empty db
that is safer instead of bypassing commonly used route.
2021-05-12 09:45:09 +07:00
jangko f6a0e4bcbd
fixes wrong usage of `chainId` in places where it should be networkId
fixes #643
2021-05-12 09:45:09 +07:00
jangko 2d3d450075
fixes `validateFixedLenHex` in graphql/ethapi.nim
now it can detect too long hex besides padding too short hex
2021-05-12 08:12:26 +07:00
jangko d0546becfb
add query complexity calculator to graphql/ethapi
this will allow us to pass two more hive tests
2021-05-10 22:22:04 +07:00
jangko 76189c6357
fixes graphql.scalar.Bytes32
relaxing the rigid length validation of Bytes32 scalar.
allow it to parse hex less than 64 bytes, and add leading
zeroes if needed.
2021-05-05 19:48:56 +07:00
jangko b8c55229e7
implement graphql.Query.account
although this is not part of EIP 1767
but the hive test cases derived from besu
test cases contains this.
we add this now to pass more test hive.graphql cases
2021-05-05 19:18:35 +07:00
jangko 9c04202412
using inheritance on Node in graphql resolvers
this remove usage of unsafe cast
2021-05-05 11:20:12 +07:00
jangko dabff33689
turn all CatchableError into error code, not only EVMError 2021-05-05 11:20:12 +07:00
jangko 0dd6d1e3d4
add some comments to graphql/sendRawTransaction
the comment is about missing things need to be addressed
by sendRawTransaction
2021-05-05 11:20:11 +07:00
jangko 728f3a24be
fixes `rpcMakeCall`: using parent.stateRoot
instead of using header.stateRoot, now it is using parent.stateRoot
2021-05-05 11:20:11 +07:00
jangko c200cebb1d
fixes various bugs in graphql/ethapi.nim 2021-05-05 11:00:12 +07:00
Jamie Lokier 1574136a25
Precompiles: Change precompile tests to use fixtureCallEvm
Move the EVM setup and call in precompile tests to `fixtureCallEvm` in
`call_evm`.  Extra return values needed for testing are returned specially, and
the convention for reporting gas used is changed to match `asmCallEvm`.

Although the precompile tests used `execPrecompiles` before, `executeOpcodes`
does perfectly well as a substitute, allowing `fixtureCallEvm` to be shared.

_Significantly, this patch also makes `Computation` more or less an internal
type of the EVM now._

Nothing outside the EVM (except `call_evm`) needs access any more to
`Computation`, `execComputation`, `executeOpcodes` or `execPrecompiles`.
Many imports can be trimmed, some files removed, and EVMC is much closer.

(As a bonus, the functions in `call_evm` reveal what capabilities parts of the
program have needed over time, makes certain bugs and inconsistencies clearer,
and suggests how to refactor into a more useful shared entry point.)

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-05 02:31:46 +01:00
Jamie Lokier 751068a4d4
EVM call: Simplify and make consistent how to select the fork
Allow the fork to be specified consistently through an `option[Fork]` instead
of varying inconsistencies depending on which call.  When fork is not
specified, the `BaseVMState` code picks the correct fork by default for the
block number and chain.

This change actually deletes code, because a number of functions (RPC etc) had
redundant code to pick the fork, which always resolved to same as default.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-05 02:26:21 +01:00
Jamie Lokier 236a65d598
Fixtures: Make fixture "vm json tests" use new function fixtureCallEvm
Move the EVM setup and call in fixtures "vm json tests" to new function
`fixtureCallEvm` in `call_evm`.  Extra return values needed for testing are
returned specially.

This entry point is different from all other `..CallEvm` type functions,
because it uses `executeOpcodes` instead of `execComputation`, so it doesn't
update the account balance or nonce on entry and exit from the EVM.

The new code is a bit redundant and simplistic intentionally, as the purpose is
to move functionality to `call_evm` with high confidence nothing really
changed.  The calls will be jointly refactored afterwards to merge differences.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 15:21:15 +01:00
Jamie Lokier 9e99bb6cd9
Fixtures: Prepare fixtureSetupComputation to support fixtureCallEvm
In the `text_vm_json` ("fixtures") test code, there is another variant of
`rpcSetupComputation` and `txSetupComputation` with slightly different
paremeters.  The similarity is obvious.

It is a special setup for testing, though, as it requires slightly different
parameters.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 15:21:14 +01:00
jangko 39ce2390ae
fixes `getRecipient`: using `sender` param instead of calculating sender itself
usually, there is always a sender around `getRecipient` call.
no need to recalculate sender. and more important, in some of
JSON-RPC/GraphQL call, the sender is come from `rpcCallData`,
not from `tx.getSender`. or in ohter situation when the tx is
an unsigned tx, without `r,s,v` fields to calculate sender.
2021-05-04 15:31:47 +07:00
Jamie Lokier d2586c3a73
Assembler: Make macro_assembler tests use new function asmCallEvm
Move the EVM setup and call in `macro_assembler` (`runVM`) entirely to new
function `asmCallEvm` in `call_evm`.  Extra return values needed for
testing are returned specially from `asmCallEvm`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 01:36:00 +01:00
Jamie Lokier 834449d943
Assembler: Second asmSetupComputation, calls the first
The second `asmSetupComputation looks up state by block number and preceding
block number, modifies the first transaction with code for testing, and uses
some parts of that transaction to setup an an EVM test.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 01:03:55 +01:00
Jamie Lokier 5728491d60
Assembler: First asmSetupComputation to support asmCallEvm
In the `macro_assembler` test code, `initComputation` is another variant of
`rpcSetupComputation` and `txSetupComputation` with slightly different
paremeters.  The similarity is obvious.

It is a special setup for testing, though, as it requires a contract-creation
transaction for parameters, but sets up a `CALL` execution not `CREATE`.

Gather this into `call_evm`: `initComputation` -> `asmSetupComputation`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 01:03:55 +01:00
Jamie Lokier cc7307186d
RPC: Don't export rpcSetupComputation
The point of the `call_vm` exercise is to allow `Computation` to become an
internal type of the EVM, not used as API by the rest of the program.  So
`rpcSetupComputation` should be private.  It was left exported by mistake.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 01:00:51 +01:00
Jamie Lokier c7e1cb61ee
Transaction: Make transaction validation use new function txCallEvm
Split out and move the EVM setup and call in `processTransaction` to
`call_evm`.  This is the last part of the main program which calls the EVM
to be moved.  (There's still test code.)

While we're here, move the EIP2929 access list setup too, as the similarity
to `rpcInitialAccessListEIP2929` is obvious.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-04 00:56:03 +01:00
Jamie Lokier 4187eb1959
Transaction: Prepare txRefundGas to support txCallEvm
There's only one call left to `refundGas(Transaction, ...)`, and the
similarity to the tail of `rpcEstimateGas` is obvious.

Gather this into `call_evm`: `refundGas` -> `txRefundGas`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 19:51:20 +01:00
Jamie Lokier 52fd8b8129
Transaction: Prepare txSetupComputation to support txCallEvm
After recent changes, there's only one call left to `setupComputation`, and
it's just a variant like `rpcSetupComputation` but for transaction processing.
The similarity to `rpcSetupComputation` is obvious.

Gather this into `call_evm`: `setupComputation` -> `txSetupComputation`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 19:51:20 +01:00
Jamie Lokier 7eb4471004
Bugfix: Avoid numeric overflow when validating transaction value
It's possible for `tx.value` in the transaction to have a deliberately
constructed large 256-bit value, such that adding `gasLimit * gasPrice` to it
overflows to a small value.

Prior to this patch, the code would allow such a transaction to pass
validation, even though such a large transfer cannot be valid.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 19:34:22 +01:00
Jamie Lokier 9a5e0d2833
RPC: Change rpcEstimateGas to use the EVM without a fake transaction
Change `rpcEstimateGas` to setup and execute a computation directly, in a
similar way to `rpcDoCall` and `rpcMakeCall`, instead of constructing a fake
transaction and then validating it.

This patch does not (or should not) change any behaviour.

Although this looks a bit messy as it duplicates parts of `validateTransaction`
and `processTransaction`, proc names have been used to hopefully keep the
meanings clear, and it's just a stepping stone as those transaction functions
will be changed next.  Also the behaviour of RPC `estimateGas` may not be
correct (although this patch is careful not to change it), so it's good to make
it explicit so we can see how it differs from other RPCs.

Doing this change exposed some interesting behaviour differences between the
`call` RPC and `estimateGas` RPC, which may be bugs, or may be intentional.
These differences are now obvious and explicit.

The unclear areas are not well documented by any of the clients, even Infura
which says a bit more than the others.  So to find out if they are intended,
we'll have to run tests against other Ethereum services.

Guessing, on the face of it, it looks likely that RPC `call` should:

- Setup EIP2929 access lists
- Account for intrinsic gas (maybe not because zero-gas transactions are ok)

And it looks likely that RPC `estimateGas` should:

- Not return zero when an account has insufficient balance
- Maybe use a different gas cost estimate when one isn't supplied in the RPC

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 16:41:37 +01:00
Jamie Lokier 76c4c72abb
RPC: Prepare rpcSetupComputation to support estimateGas
The RPC `estimateGas` behaves differently from RPC `call` in a number of ways.

These differences may be bugs due to `rpcEstimateGas` calling the EVM in a very
different way than `rpcDoCall`, or they may be intentional.  To be sure, we'll
need to test behaviour with Geth, Infura etc to find out (their documentation
isn't enough.)  For now, though, we'll keep the same behaviour as we always had.

`rpcEstimateGas` cannot use `rpcSetupComputation` as it is, because
`estimateGas` accounts for "intrinsic gas", and `call` does not.

This patch changes `rpcSetupComputation` to accomodate both behaviours.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 16:41:33 +01:00
Jamie Lokier f3f872d707
GraphQL: Typo in error message for GraphQL "call" request
Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 15:08:50 +01:00
Jamie Lokier 6dd14e4f4f
GraphQL: Move EVM-calling function makeCall to rpcMakeCall
`makeCall` used by GraphQL is another way to setup and call the EVM.
Move it to `transaction/call_evm`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 10:59:13 +01:00
Jamie Lokier 8bda81496a
RPC: Move EVM-calling function estimateGas to rpcEstimateGas
`estimateGas` used by JSON-RPC is another way to setup and call the EVM,
also used by GraphQL.  Move it to `transaction/call_evm`.

This function has too much direct knowledge of details that shouldn't be used
outside transaction handling code, details we need to change when changing the
db and transaction memory layer.

Moving this one exposed quite a bit of abstraction leakage, as it calls
directly to the hexary trie db around `processTransaction`.

It looks like the _intended_ functionality of `estimateGas` is similar to
`rpcDoCall` with the only real difference being to not store the final state.
It looks like the extra stuff in `estimateGas` compared with `doCall` is a
messy workaround for computation not exposing the right API ("don't save final
state") for RPC to use.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 10:59:10 +01:00
Jamie Lokier 2732af99eb
RPC: Move EVM-calling function doCall to rpcDoCall
`doCall` used by JSON-RPC is another way to setup and call the EVM.
Move it to `transaction/call_evm`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 10:59:07 +01:00
Jamie Lokier 7c3b7ab7a8
RPC: Gather EVM-calling functions to one place; rpcSetupComputation
Start gathering the functions that call the EVM into one place,
`transaction/call_evm.nim`.

This is first of a series of changes to gather all ways the EVM is called to
one place.  Duplicate, slightly different setup functions have accumulated over
time, each with some knowledge of EVM internals.  When they are brought
together, these methods will be changed to use a single entry point to the EVM,
allowing the entry point to be refactored, EVMC to be completed, and async
concurrency to be implemented on top.  This also simplifies the callers.

First, a helper function used by RPC and GraphQL to make EVM calls without
permanently modifying the account state.  `setupComputation` ->
`rpcSetupComputation`.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-05-03 10:59:05 +01:00
jangko e6d7d6188c
`processArguments` now can have alternate OptParser instead of fixed one
the `processArguments` now have overloaded proc, one with opt param and one without.
the OptParser now can be passed to `opt` param.
this is useful in scenario where in test code we need to simulate something
without using real command line arguments.
2021-04-30 12:56:19 +07:00
jangko 68e70ebdca
fixes hard fork block number initialization in `processCustomGenesisConfig`
rather than initialize it to 0, those block numbers
are initialized to high(BlockNumber). this will fix
issue when imported genesis.json doesn't contains all
forks' blockNumber.
2021-04-30 12:56:18 +07:00
jangko 287f1b2ba0
fixes `importRlpBlock` algorithm
it will skip blocks with blockNumber <= than current
head blockNumber
2021-04-30 12:56:18 +07:00
Jamie Lokier 2a7ccceb3e
EVM: Make continuation exceptions behave as they did before
The account database code is not supposed to raise exceptions in the EVM, and
the behaviour is not well defined if it does.  It isn't compliant with EVMC
spec either.  But that will be dealt with properly when the account state-cache
is dealt with, as there is some work to be done on it.

Meanwhile, if it raises in code under `chainTo` and then `(continuation)()`,
the behaviour was changed slightly by the stack-shrink patches.

Before those patches, an exception after the recursion-point was converted to
`c.setError` "Opcode Dispatch Error" in `executeOpcodes.  After, it would
propagate out, a different behaviour.  (It still correctly walked the chain of
`c.dispose()` calls to clean up.)

It's easy to restore the original behaviour just by moving the continuation
call, so let's do that.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-04-30 11:32:42 +07:00
Jordan Hrycaj 5d0d44c38f re-named compu_helper.nim => computation.nim
why:
  exports all except one of the original computation.nim functional
  objects
2021-04-28 15:24:14 +03:00
Jordan Hrycaj a86308c079 merged contents of computations.nim int interpreter_dispatch.nim
why:
  only two public functions left: executeOpcodes() and execCallOrCreate()
  where the former one was originally in interpreter_dispatch.nim and
  the latter one calls this one.

  improves maintainability
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 49afac46b7 move dispatcher case switch from interpterer_dispatcher.nim into separate file
why:
  insulate for improving maintenance
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 028a3d6a37 removed redundant source file: interpreter.nim
why:
  works as import concentrator for state_transaction.nim for
  vm_internals.nim interface.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 0a4c34f13b removed circular import dependencies
overview:
  can be verified by running "make check_vm2 X=0" in the nimbus directory
  (be patient when running it.) the X=0 flag is necessary if there is a
  native NIM compiler which may bail out at some vendor imports.

details:
  when compiling state_transaction.nim, the nim flag vm2_enabled must
  be set in order to avoid implicit import of native VM definitions.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj caabc9c292 removed kludge and simplified sources oph_call.nim and oph_create.nim
why:
  kludge not needed anymore for oph_handlers.nim sub-sources and sources
  that rely on oph_handlers.nim (but not state_transactions.nim which
  relies on computation.nim.)
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 77518446d9 shift functions from computation.nim => compu_helper.nim
why:
  insulate exec functions in computation.nim
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 73900270db extracted macros from oph_helpers.nim => oph_gen_handlers.nim
why:
  imports mostly need to import only one of either
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 45558282f7 merged oph_*_kludge.nim sources => single oph_kludge.nim 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 69a1ee5fc8 re-named some v2state_transactions.nim to its original name without the v2
also:
  re-integrated stack_defs.nim back into stack.nim

why:
  the v2 prefix of the file name was used as a visual aid when
  comparing vm2 against vm sources
2021-04-28 15:24:14 +03:00
Jordan Hrycaj e6eee3f3a6 prepared v2state_transaction.nim so it can be compiled locally
details:
  use the -d:kludge:1 flag for syntax check
2021-04-28 15:24:14 +03:00
Jordan Hrycaj ff6921eb1a re-named some v2*.nim sources to its original name *.nim (without the v2)
why:
  the v2 prefix of the file name was used as a visual aid when
  comparing vm2 against vm sources

details:
  all renamed v2*.nim sources compile locally with the -d:kludge:1 flag
  set or without (some work with either)

  only sources not renamed yet: v2state_transactions.nim
2021-04-28 15:24:14 +03:00
Jordan Hrycaj bca6e791aa provide experimental op handler switch -d:lowmem:1 for low memory C compiler
why:
  on 32bit windows 7, there seems to be a 64k memory ceiling for the gcc
  compiler which was exceeded on some test platform.

details:
  compiling VM2 for low memory C compiler can be triggered with
  "make ENABLE_VM2LOWMEM". this comes with a ~24% longer execution time
  of the test suite against old VM and optimised VM2.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 1b3117edbd re-implemented handler-call statement by doubly nested case statement
why:
  the new implementation lost more then 25% execution time on the test
  suite when compared to the original VM. so the handler call and the
  surrounding statements have been wrapped in a big case statement similar
  to the original VM implementation. on Linux/x64, the execution time of
  the new VM2 seems to be on par with the old VM.

details:
  on Linux/x64, computed goto works and is activated with the -d:release
  flag. here the execution time of the new VM2 was tested short of 0.02%
  better than the old VM. without the computed goto, it is short of
  0.4% slower than the old VM.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 3ed234e0a1 clean up cyclic-import-breaker function stubs where possible for op handlers
why:
  using function stubs made it possible to check the syntax of an op
  handler source file by compiling this very file. this was previously
  impossible due cyclic import/include mechanism.

details:
  only oph_call.nim, oph_create.nim and subsequently op_handlers.nim
  still need the -d:kludge:1 flag for syntax check compiling. this flag
  also works with interpreter_dispatch.nim which imports op_handlers.nim.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 59d7ba1f1e print compiler warning about the VM used
why:
  handy to have confirmation about which of the three different VMs
  is activated
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 18587f5496 move setupTxContext() from v2state.nim to v2state_transactions.nim
why:
  removes circular dependency in v2state.nim which is more used than
  v2state_transactions.nim
2021-04-28 15:24:14 +03:00
Jordan Hrycaj a86bcefc7a re-named v2gas_costs.nim to its original name v2gas_costs.nim
why:
  the v2 prefix of the file name was used as a visual aid when
  comparing vm2 against vm sources
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 72b36e154b eliminated v2opcode_values, v2forks in favour of op_codes, forks_list 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 01b96df99f applies jamie's patch for eliminating recursion
original comment:
  This patch eliminates recursion entirely from the EVM when ENABLE_EVMC=0.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj b2ce6d9e70 re-arrange functions from v2computation.nim and interpreter_dispatch.nim
why:
  step towards breaking circular dependency

details:
  some functions from v2computation.nim have been extracted into
  compu_helper.nim which does not explicitly back-import
  v2computation.nim. all non recursive op handlers now import this source
  file rather than v2computation.nim.

  recursive call/create op handler still need to import v2computation.nim.

  the executeOpcodes() function from interpreter_dispatch.nim has been
  moved to v2computation.nim which allows for <import> rather than
  <include> the interpreter_dispatch.nim source.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 9b70ab5f8f update handler prototype using call-by-reference argument
why:
  this allows for passing back information which can eventually be
  used for reducing use of exceptions

caveat:
  call/create currently needs to un-capture the call-by-reference
  (wrapper) argument using the Computation reference inside
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 06b34a4a56 remove obsolete files
why:
  opcodes_impl.nim was fully replaced by functionality from
  op_handlers.nim
2021-04-28 15:24:14 +03:00
Jordan Hrycaj b388e966cc simplify interpreter_dispatch.nim code
details:
  replace generated macro loop/switch by explicit call using the
  fork/op handler matrix (encapsulated via opHandlersRun() function)
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 2fb18bf88c install new op handlers
details:
  in the source file interpreter_dispatch.nim, op handlers imported from
  opcodes_impl.nim are replaced by table entries from op_handlers.nim
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 51587208b4 verifying new op handler tables layout against original tables
why:
  the previous approach was replacing the function-lets in
  opcode_impl.nim by the particulate table handlers. the test
  functions will verify the the handler functions are sort of
  correct but not the assignments in the fork tables.

  the handler names of old and new for tables are checked here.

caveat:
  verifying tables currently takes a while at compile time.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 4e2af7937b clean up code for call handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 4ac32d360b re-integrated call op handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 1bdbfda37f re-integrated/added Create and Create2 handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 1bb6ef43a1 re-integrated handlers with op codes 0xf2/return ..0xff/selfdestruct 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 7436e516fd re-integrated/added EIP2929 handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 716bd64419 re-integrated 0x60..0xaf (push, dup, swap, log) op handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj f4bc9c4561 updated circular dependency klugde
why:
  removing <when> clauses and replacing gas calculation by stubs
  makes up for better reading of the code
2021-04-28 15:24:14 +03:00
Jordan Hrycaj d373ab6460 re-integrated 0x5# op handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj 0f1c7cee43 re-integrated 0x4# op handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj a9719f2dae added comments for better readability
and:
  reduced some import clause arguments
2021-04-28 15:24:14 +03:00
Jordan Hrycaj fb94aa8a35 re-integrated 0x3# op handlers 2021-04-28 15:24:14 +03:00
Jordan Hrycaj fda676062f integrated current op handlers into opcodes_impl.nim (tbc.)
why:
  integration tests will verify op code handlers which wher rephrased
  from the very opcodes_impl module into the handler tables.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 5e7d4ac9c5 experimental op handlers table (tbc.)
details:
  the op handler table is accessible via op_handlers.nim module

  op handler function implementations are found in the op_handlers/
  sub-directory

kludge:
  for development and pre-testing, any new module can be individually
  compiled setting the kludge flag using -d:kludge:1. this causes some
  proc/func replacements in turn allowing for omitting imports that would
  otherwise cause a circular dependency. otherwise individual compilation
  would fail.

  in order to prove the overall correctness of the code, the
  op_handlers.nim is imported by opcodes_impl.nim when compiling all,
  nimbus or test.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj f37591ca35 need to remove vm2_defined sentinel
why:
  subsequent development will compile sources as main without setting
  the vm2_enabled flag. also, the doc generator would fail an vm2 without
  setting the flag for the vm2 files.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj fd7b1bd040 update doc generator
why:
  generally, there is no role for libbacktrace when docs are generated

  for vm2, undo settings of config.nim and provide the "kludge" flag, so
  circular import/include dependencies can be taken care of (not only)
  for generating docs
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 5c01b3548d extract forks definition (all but rename v2forks.nim)
why:
  new name forks_list.nim file name matches additional documentation
  file names.

details:
  v2forks.nim remains a hollowed out shell serving as interface file.
2021-04-28 15:24:14 +03:00
Jordan Hrycaj a095183812 isolate memory type definition
how:
  extract from methods implementation source into separate file
2021-04-28 15:24:14 +03:00
Jordan Hrycaj a868108ae7 isolate stack type definition
how:
  extract from methods implementation source into separate file
2021-04-28 15:24:14 +03:00
Jordan Hrycaj 579fed5010 manually rewrite op-codes
why:
  activate NIM comments needed re-write. as there is no advantage in using
  the macro replacing a few missing op-codes by "Nop##" name symbols, the
  macro wrapper has been removed.

details:
  when explicitly accessed by numeric value ##, missing Op enum entries
  result in a symbol name something like "Op ##".

  rather than implicitly using a macro to fix the op-codes list, missing
  entries are detected at compile time when a fatal exception is thrown.

  the static compile time check verifies that
    all op-codes 0 .. 255 are defined
    op code name/mnemonic has at least 2 chars and starts with a capital
    op code name/mnemonic is not NIM auto-generated (i.e. has a space)

  also, original '#' comments are exposed as doc comments '##'
2021-04-28 15:24:14 +03:00
Jamie Lokier 90cefc7a3d
Shell: Update help text to match reality
Capitalisation:
- The option is lower case `--logmetrics` but help said `--logMetrics`
- Same for `--logmetricsiterval`
- Same for `--metricsserver` and `--metricsserverport`

Ethereum network selection:
- Moved out into their own, cleaner help section
- Added help for `--mainnet`, `--goerli` and `--kovan`
- Moved `--networkid` and `--customnetwork` to this section as well

Other:
- Reworded or formatted some help lines for clarity and consistency

Changed options:
- Renamed `--metricserver` to `--metrics`
- Renamed `--matricsserverport` to `--metricsport`
- Removed Morden network; this didn't have an option, but could be
  selected with `--networkid:2` and then fail to work

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-04-27 11:11:13 +01:00
Jamie Lokier a3c8a5c3f3
EVMC: Small stacks when using EVMC, closes #575 (segfaults)
This patch reduces stack space used with EVM in ENABLE_EVMC=1 mode, from 13 MB
worst case to 550 kB, a 24x reduction.

This completes fixing the "stack problem" and closes #575 (`EVM: Different
segmentation faults when running the test suite with EVMC`).

It also closes #256 (`recursive EVM call trigger unrecoverable stack overflow`).

After this patch, it is possible to re-enable the CI targets which had to be
disabled due to #575.

This change is also a required precursor for switching over to "nearly EVMC" as
the clean and focused Nimbus-internal API between EVM and sync/database
processes, and is also key to the use of Chronos `async` in those processes
when calling the EVM.

(The motivation is the internal interface has to be substantially changed
_anyway_ for the parallel sync and database processes, and EVMC turns out to be
well-designed and well-suited for this.  It provides good separation between
modules, and suits our needs better than our other current interface.  Might as
well use a good one designed by someone else.  EVMC is 98% done in Nimbus
thanks to great work done before by @jangko, and we can use Nimbus-specific
extensions where we need flexibility, including for performance.  Being aligned
with the ecosystem is a useful bonus feature.)

All tests below were run on Ubuntu 20.04 LTS server, x86-64.  This matches one
of the targets that has been disabled for a while in CI in EVMC mode due to
stack overflow crashing the tests, so it's a good choice.

Measurements before
===================

Testing commit `e76e0144 2021-04-22 11:29:42 +0700 add submodules: graphql and
toml-serialization`.

    $ rm -f build/all_tests && make ENABLE_EVMC=1 test
    $ ulimit -S -s 16384 # Requires larger stack than default to avoid crash.
    $ ./build/all_tests 9 | tee tlog
    [Suite] persist block json tests
    ...
    Stack range 38416 depthHigh 3
    ...
    Stack range 13074720 depthHigh 1024
    [OK] tests/fixtures/PersistBlockTests/block1431916.json

These tests use 13.07 MB of stack to run, and so crash with the default stack
limit on Ubuntu Server 20.04 (8MB).  Exactly 12768 bytes per EVM call stack
frame.

    $ rm -f build/all_tests && make ENABLE_EVMC=1 test
    $ ulimit -S -s 16384 # Requires larger stack than default.
    $ ./build/all_tests 7 | tee tlog
    [Suite] new generalstate json tests
        ...
    Stack range 14384 depthHigh 2
        ...
    Stack range 3495456 depthHigh 457
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stRandom2/randomStatetest639.json
    ...
    Stack range 3709600 depthHigh 485
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stRandom2/randomStatetest458.json
        ...
    Stack range 7831600 depthHigh 1024
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stCreate2/Create2OnDepth1024.json

These tests use 7.83MB of stack to run.  About 7648 bytes per EVM call stack
frame.  It _only just_ avoids crashing with the default Ubuntu Server stack
limit of 8 MB.  However, it still crashes on Windows x86-64, which is why the
Windows CI EVMC target is currently disabled.

On Linux where this passes, this is so borderline that it affects work and
testing of the complex storage code, because that's called from the EVM.

Also, this greatly exceeds the default thread stack size.

Measurements after
==================

    $ rm -f build/all_tests && make ENABLE_EVMC=1 test
    $ ulimit -S -s 600 # Because we can!  600k stack.
    $ ./build/all_tests 9 | tee tlog
    [Suite] persist block json tests
    ...
    Stack range 1936 depthHigh 3
    ...
        Stack range 556272 depthHigh 1022
        Stack range 556512 depthHigh 1023
        Stack range 556816 depthHigh 1023
        Stack range 557056 depthHigh 1024
        Stack range 557360 depthHigh 1024
        [OK] tests/fixtures/PersistBlockTests/block1431916.json

    $ rm -f build/all_tests && make ENABLE_EVMC=1 test
    $ ulimit -S -s 600 # Because we can!  600k stack.
    $ ./build/all_tests 7 | tee tlog
    [Suite] new generalstate json tests
        ...
    Stack range 1392 depthHigh 2
        ...
    Stack range 248912 depthHigh 457
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stRandom2/randomStatetest639.json
    ...
    Stack range 264144 depthHigh 485
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stRandom2/randomStatetest458.json
        ...
        Stack range 557360 depthHigh 1024
    [OK] tests/fixtures/eth_tests/GeneralStateTests/stStaticCall/static_CallRecursiveBombPreCall.json

For both tests, a satisfying *544 bytes* per EVM call stack frame, and EVM
takes less than 600 kB total.  With other overheads, both tests run in 600 kB
stack total at maximum EVM depth.

We must add some headroom on this for database activity called from the EVM,
and different compile targets.  But it means the EVM itself is no longer a
stack burden.

This is much smaller than the default thread stack size on Linux (2MB), with
plenty of margin.  (Just fyi, it isn't smaller than a _small_ thread stack on
Linux from a long time ago (128kB), and some small embedded C targets.)

This size is well suited to running EVMs in threads.

Further reduction
=================

This patch solves the stack problem.  Windows and Linux 64-bit EVMC CI targets
can be re-enabled, and there is no longer a problem with stack usage.

We can reduce further to ~340 bytes per frame and 350 kB total, while still
complying with EVMC.  But as this involves changing how errors are handled to
comply fully with EVMC, and removing `dispose` calls, it's not worth doing now
while there are other EVMC changes in progress that will have the same effect.

A Nimbus-specific extension will allow us to avoid recursion with EVMC anyway,
bringing bytes per frame to zero.  We need the extension anyway, to support
Chronos `async` which parallel transaction processing is built around.

Interop with non-Nimbus over EVMC won't let us avoid recursion, but then we
can't control the stack frame size either.  To prevent stack overflow in
interop I anticipate using (this method in Aleth)
[6e96ce34e3/libethereum/ExtVM.cpp (L61)].

Smoke test other versions of GCC and Clang/LLVM
===============================================

As all builds including Windows use GCC or Apple's Clang/LLVM, this is just to
verify we're in the right ballpark on all targets.  I've only checked `x86_64`
though, not 32-bit, and not ARM.

It's interesting to see GCC 10 uses less stack.  This is because it optimises
`struct` returns better, sometimes skipping an intermediate copy.  Here it
benefits the EVMC API, but I found GCC 10 also improves the larger stack usage
of the rest of `nimbus-eth1` as well.

Apple clang 12.0.0 (clang-1200.0.26.2) on MacOS 10.15:

- 544 bytes per EVM call stack frame

GCC 10.3.0 (Ubuntu 10.3.0-1ubuntu1) on Ubuntu 21.04:

- 464 bytes per EVM call stack frame

GCC 10.2.0 (Ubuntu 10.2.0-5ubuntu1~20.04) on Ubuntu 20.04 LTS:

- 464 bytes per EVM call stack frame

GCC 11.0.1 20210417 (experimental; Ubuntu 11-20210417-1ubuntu1) on Ubuntu 21.04:

- 8 bytes per EVM call stack frame

GCC 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04) on Ubuntu 20.04 LTS:

- 544 bytes per EVM call stack frame

GCC 8.4.0 (Ubuntu 8.4.0-3ubuntu2) on Ubuntu 20.04 LTS:

- 544 bytes per EVM call stack frame

GCC 7.5.0 (Ubuntu 7.5.0-6ubuntu2) on Ubuntu 20.04 LTS:

- 544 bytes per EVM call stack frame

GCC 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2) on Ubuntu 19.10:

- 528 bytes per EVM call stack frame

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-04-27 05:53:32 +01:00
jangko 103996f6b2
integrate graphql service into nimbus-eth1 2021-04-24 11:01:09 +07:00
jangko 5367b2ddf5
add graphql service files to nimbus-eth1 2021-04-24 10:59:55 +07:00
jangko 34536b0d25
add --graphql and --graphqlbind to cli parser 2021-04-24 10:58:05 +07:00
jangko 3dfc1501f0
modify estimateGas in rpc_utils.nim and it can be reusable for graphql too 2021-04-24 10:56:22 +07:00
jangko 82d4f6a2d4
fixes getReceipts proc signature in db_chain.nim
instead of using header as input param, now getReceipts using
receiptRoot hash, the intention is clearer and less data passed around
when we only using receiptRoot instead of whole block header.
2021-04-24 10:51:05 +07:00
jangko 1728dd8d54
fix getTransactionCount bug in db_chain.nim
getTransactionCount will always return 0 because the txCount
variable is not returned
2021-04-24 10:47:37 +07:00
Jordan Hrycaj e02c6d4c3d renamed computation.nim, memory.nim, utils_numeric.nim, interpreter.nim => v2*.nim
why:
  these files provide part of the externally accessible interface
  provided by vm_cpmputation.nim, vm_internals.nim. so the
  new filename indicates that the source code belongs to vm2 (rather
  than vm).
2021-04-23 14:04:06 +03:00
Jordan Hrycaj 2ca9621799 renamed message.nim, precompiles.nim, gas_costs.nim => v2*.nim
why:
  these files provide part of the externally accessible interface
  provided by vm_message.nim, vm_precompile.nim, vm_gas_cost.nim. so the
  new filename indicates that the source code belongs to vm2 (rather
  than vm).
2021-04-23 14:04:06 +03:00
Jordan Hrycaj f159e67bba renamed states*.nim => v2states*.nim
why:
  these files provide part of the externally accessible interface
  provided by vm_state*.nim. so the new filename indicates that the
  source code belongs to vm2 (rather than vm).
2021-04-23 14:04:06 +03:00
Jordan Hrycaj 7b6767c4a3 renamed types.nim, vm_fork.nim, opcode_values.nim => v2*.nim
why:
  these files provide part of the externally accessible interface
  provided by vm_types*.nim. so the new filename indicates that the
  source code belongs to vm2 (rather than vm).
2021-04-23 14:04:06 +03:00
Jordan Hrycaj cf2d771c4d remove evmc code from vm2
why:
  handled by original vm
2021-04-23 14:04:06 +03:00
Jordan Hrycaj b7bf84a71f added compiler flag sentinels to vm2 headers
why:
  making sure that deep links into vm2 sources are configured properly. it
  is intended that only the vm_*.nim interface headers are allowed to
  source files in vm2. the sentinels just protect from coding errors.
2021-04-23 14:04:06 +03:00
Jordan Hrycaj b4f8450968 provide identical copy of vm folder => vm2, activated by make flag ENABLE_VM2=1
why:
  vm2 enabled by ENABLE_VM2=1 behaves as vm without ENABLE_EVMC=1 until
  it doesn't in some future fatch set. this leaves some wiggle room
  to work on a vm copy without degrading the original implementation.

details:
  + additional make flag ENABLE_VM2=1 (or ENABLE_VM2=0 to explicitely disable)
  + when both flags ENABLE_EVMC=1 and ENABLE_VM2=1 are present, the former
    flag ENABLE_EVMC=1 takes precedence, this is implemented at the NIM
    compiler level for -d:evmc_enabled and -d:vm2_enabled
2021-04-23 14:04:06 +03:00
Jamie Lokier 085661c24f
EVM: Eliminate recursion entirely
This patch eliminates recursion entirely from the EVM when ENABLE_EVMC=0.

Signed-off-by: Jamie Lokier <jamie@shareable.org>
2021-04-20 16:12:45 +01:00