Skip to content

Commit

Permalink
#93 fixed gas calculation for CREATE2, improved slightly trace loggin…
Browse files Browse the repository at this point in the history
…g for VM
  • Loading branch information
tkstanczak committed Nov 8, 2018
1 parent 633b223 commit 510e3d3
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 21 deletions.
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Blockchain/BlockProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ private void ApplyMinerRewards(Block block)

private void ApplyMinerReward(Block block, BlockReward reward)
{
if (_logger.IsTrace) _logger.Trace($" {(decimal) reward.Value / (decimal) Unit.Ether:N3}{Unit.EthSymbol} for account at {reward.Address}");
if (_logger.IsTrace) _logger.Trace($" {(decimal) reward.Value / (decimal) Unit.Ether:N3}{Unit.EthSymbol} for account at {reward.Address}");
if (!_stateProvider.AccountExists(reward.Address))
{
_stateProvider.CreateAccount(reward.Address, (UInt256) reward.Value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,27 @@ public bool ValidateProcessedBlock(Block processedBlock, Block suggestedBlock)
bool isValid = processedBlock.Header.Hash == suggestedBlock.Header.Hash;
if (_logger != null && !isValid)
{
if (_logger.IsError) _logger.Error($"Processed block {processedBlock.ToString(Block.Format.Short)} is not valid");
if(_logger.IsError) _logger.Error($" hash {processedBlock.Hash} != stated hash {suggestedBlock.Hash}");

if (processedBlock.Header.GasUsed != suggestedBlock.Header.GasUsed)
{
if(_logger.IsError) _logger.Error($"Processed block {processedBlock.ToString(Block.Format.HashAndNumber)} is invalid - gas used {processedBlock.Header.GasUsed} != stated gas used {suggestedBlock.Header.GasUsed} ({processedBlock.Header.GasUsed - suggestedBlock.Header.GasUsed} difference)");
if(_logger.IsError) _logger.Error($" gas used {processedBlock.Header.GasUsed} != stated gas used {suggestedBlock.Header.GasUsed} ({processedBlock.Header.GasUsed - suggestedBlock.Header.GasUsed} difference)");
}

if (processedBlock.Header.Bloom != suggestedBlock.Header.Bloom)
{
if(_logger.IsError) _logger.Error($"Processed block {processedBlock.ToString(Block.Format.HashAndNumber)} is invalid - bloom {processedBlock.Header.Bloom} != stated bloom {suggestedBlock.Header.Bloom}");
if(_logger.IsError) _logger.Error($" bloom {processedBlock.Header.Bloom} != stated bloom {suggestedBlock.Header.Bloom}");
}

if (processedBlock.Header.ReceiptsRoot != suggestedBlock.Header.ReceiptsRoot)
{
if(_logger.IsError) _logger.Error($"Processed block {processedBlock.ToString(Block.Format.HashAndNumber)} is invalid - receipts root {processedBlock.Header.ReceiptsRoot} != stated receipts root {suggestedBlock.Header.ReceiptsRoot}");
if(_logger.IsError) _logger.Error($" receipts root {processedBlock.Header.ReceiptsRoot} != stated receipts root {suggestedBlock.Header.ReceiptsRoot}");
}

if (processedBlock.Header.StateRoot != suggestedBlock.Header.StateRoot)
{
if(_logger.IsError) _logger.Error($"Processed block {processedBlock.ToString(Block.Format.HashAndNumber)} is invalid - state root {processedBlock.Header.StateRoot} != stated state root {suggestedBlock.Header.StateRoot}");
if(_logger.IsError) _logger.Error($" state root {processedBlock.Header.StateRoot} != stated state root {suggestedBlock.Header.StateRoot}");
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/Nethermind/Nethermind.Evm.Test/Eip1014Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

using System;
using System.Linq;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
Expand Down Expand Up @@ -73,7 +74,7 @@ public void Test()
[TestCase("0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0xdeadbeef", 32006, "0x70f2b2914A2a4b783FaEFb75f459A580616Fcb5e")]
[TestCase("0x00000000000000000000000000000000deadbeef", "0x00000000000000000000000000000000000000000000000000000000cafebabe", "0xdeadbeef", 32006, "0x60f3f640a8508fC6a86d45DF051962668E1e8AC7")]
[TestCase("0x00000000000000000000000000000000deadbeef", "0x00000000000000000000000000000000000000000000000000000000cafebabe", "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", 32012, "0x1d8bfDC5D46DC4f61D6b6115972536eBE6A8854C")]
[TestCase("0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x00", 32000, "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0")]
[TestCase("0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x", 32000, "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0")]
public void Examples_from_eip_spec_are_executed_correctly(string addressHex, string saltHex, string initCodeHex, long gas, string resultHex)
{
byte[] salt = Bytes.FromHexString(saltHex);
Expand All @@ -93,10 +94,11 @@ public void Examples_from_eip_spec_are_executed_correctly(string addressHex, str
.Call(TestObject.AddressC, 50000)
.Done;

Execute(code);
(var receipt, var trace) = ExecuteAndTrace(code);

Address expectedAddress = new Address(resultHex);
AssertEip1014(expectedAddress, deployedCode);
Assert.AreEqual(gas, trace.Entries.Single(e => e.Operation == Instruction.CREATE2.ToString()).GasCost);
}
}
}
12 changes: 8 additions & 4 deletions src/Nethermind/Nethermind.Evm/VirtualMachine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ public TransactionSubstate Run(EvmState state, IReleaseSpec releaseSpec, bool en
}
catch (Exception ex) when (ex is EvmException || ex is OverflowException)
{
if (_logger.IsTrace) _logger.Trace($"EXCEPTION ({ex.GetType().Name}) IN {currentState.ExecutionType} AT DEPTH {currentState.Env.CallDepth} - RESTORING SNAPSHOT");
if (_logger.IsTrace) _logger.Trace($"exception ({ex.GetType().Name}) in {currentState.ExecutionType} at depth {currentState.Env.CallDepth} - restorign snapshot");

_state.Restore(currentState.StateSnapshot);
_storage.Restore(currentState.StorageSnapshot);
Expand Down Expand Up @@ -339,6 +339,7 @@ private void InitializePrecompiledContracts()

private bool UpdateGas(long gasCost, ref long gasAvailable)
{
if (_logger.IsTrace) _logger.Trace($" UPDATE GAS (-{gasCost})");
if (gasAvailable < gasCost)
{
Metrics.EvmExceptions++;
Expand All @@ -351,6 +352,7 @@ private bool UpdateGas(long gasCost, ref long gasAvailable)

private void RefundGas(long refund, ref long gasAvailable)
{
if (_logger.IsTrace) _logger.Trace($" UPDATE GAS (+{refund})");
gasAvailable += refund;
}

Expand Down Expand Up @@ -772,7 +774,7 @@ Address PopAddress(Span<byte> stack)
void UpdateMemoryCost(UInt256 position, UInt256 length)
{
long memoryCost = evmState.Memory.CalculateMemoryCost(position, length);
if (_logger.IsTrace) _logger.Trace($" memory cost {memoryCost}");
if (_logger.IsTrace) _logger.Trace($" MEMORY COST {memoryCost}");

if (!UpdateGas(memoryCost, ref gasAvailable))
{
Expand Down Expand Up @@ -802,6 +804,7 @@ void UpdateMemoryCost(UInt256 position, UInt256 length)
}

programCounter++;
if (_logger.IsTrace) _logger.Trace($"{instruction} (0x{instruction:X})");

switch (instruction)
{
Expand Down Expand Up @@ -2105,7 +2108,8 @@ void UpdateMemoryCost(UInt256 position, UInt256 length)
salt = PopBytes(bytesOnStack);
}

if (!UpdateGas(GasCostOf.Create, ref gasAvailable))
long gasCost = GasCostOf.Create + (instruction == Instruction.CREATE2 ? GasCostOf.Sha3Word * EvmPooledMemory.Div32Ceiling(initCodeLength) : 0);
if (!UpdateGas(gasCost, ref gasAvailable))
{
EndInstructionTraceError(OutOfGasErrorText);
return CallResult.OutOfGasException;
Expand Down Expand Up @@ -2304,7 +2308,7 @@ void UpdateMemoryCost(UInt256 position, UInt256 length)
//evmState.Memory.Save(outputOffset, new byte[(int)outputLength]); // TODO: probably should not save memory here
_returnDataBuffer = EmptyBytes;
PushZero(bytesOnStack);
if (_logger.IsTrace) _logger.Trace("Fail - code depth");
if (_logger.IsTrace) _logger.Trace("FAIL - call depth");
break;
}

Expand Down
17 changes: 9 additions & 8 deletions src/Nethermind/Nethermind.Store/StateProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public void UpdateCodeHash(Address address, Keccak codeHash, IReleaseSpec releas
Account account = GetThroughCache(address);
if (account.CodeHash != codeHash)
{
if (_logger.IsTrace) _logger.Trace($" Update code hash of {address} to {codeHash}");
if (_logger.IsTrace) _logger.Trace($" Update {address} C {account.CodeHash} -> {codeHash}");
Account changedAccount = account.WithChangedCodeHash(codeHash);
PushUpdate(address, changedAccount);
}
Expand Down Expand Up @@ -154,7 +154,7 @@ private void SetNewBalance(Address address, UInt256 balanceChange, IReleaseSpec
UInt256 newBalance = isSubtracting ? account.Balance - balanceChange : account.Balance + balanceChange;

Account changedAccount = account.WithChangedBalance(newBalance);
if (_logger.IsTrace) _logger.Trace($" Update {address} B = {newBalance} B_CHANGE = {(isSubtracting ? "-" : "+")}{balanceChange}");
if (_logger.IsTrace) _logger.Trace($" Update {address} B {account.Balance} -> {newBalance} ({(isSubtracting ? "-" : "+")}{balanceChange})");
PushUpdate(address, changedAccount);
}

Expand All @@ -179,7 +179,7 @@ public void UpdateStorageRoot(Address address, Keccak storageRoot)
Account account = GetThroughCache(address);
if (account.StorageRoot != storageRoot)
{
if (_logger.IsTrace) _logger.Trace($" Update {address} storage root = {storageRoot}");
if (_logger.IsTrace) _logger.Trace($" Update {address} S {account.StorageRoot} -> {storageRoot}");
Account changedAccount = account.WithChangedStorageRoot(storageRoot);
PushUpdate(address, changedAccount);
}
Expand All @@ -189,6 +189,7 @@ public void IncrementNonce(Address address)
{
Account account = GetThroughCache(address);
Account changedAccount = account.WithChangedNonce(account.Nonce + 1);
if (_logger.IsTrace) _logger.Trace($" Update {address} N {account.Nonce} -> {changedAccount.Nonce}");
PushUpdate(address, changedAccount);
}

Expand Down Expand Up @@ -314,7 +315,7 @@ public void Commit(IReleaseSpec releaseSpec)
return;
}

if (_logger.IsTrace) _logger.Trace($" committing state changes (at {_currentPosition})");
if (_logger.IsTrace) _logger.Trace($"Committing state changes (at {_currentPosition})");
if (_changes[_currentPosition] == null)
{
throw new InvalidOperationException($"Change at current position {_currentPosition} was null when commiting {nameof(StateProvider)}");
Expand Down Expand Up @@ -352,12 +353,12 @@ public void Commit(IReleaseSpec releaseSpec)
{
if (releaseSpec.IsEip158Enabled && change.Account.IsEmpty)
{
if (_logger.IsTrace) _logger.Trace($" Remove empty {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
if (_logger.IsTrace) _logger.Trace($" Commit remove empty {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
SetState(change.Address, null);
}
else
{
if (_logger.IsTrace) _logger.Trace($" Update {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
if (_logger.IsTrace) _logger.Trace($" Commit update {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
SetState(change.Address, change.Account);
}

Expand All @@ -367,15 +368,15 @@ public void Commit(IReleaseSpec releaseSpec)
{
if (!releaseSpec.IsEip158Enabled || !change.Account.IsEmpty)
{
if (_logger.IsTrace) _logger.Trace($" Create {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
if (_logger.IsTrace) _logger.Trace($" Commit create {change.Address} B = {change.Account.Balance} N = {change.Account.Nonce}");
SetState(change.Address, change.Account);
}

break;
}
case ChangeType.Delete:
{
if (_logger.IsTrace) _logger.Trace($" Remove {change.Address}");
if (_logger.IsTrace) _logger.Trace($" Commit remove {change.Address}");
bool wasItCreatedNow = false;
while (_intraBlockCache[change.Address].Count > 0)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Store/StorageProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ public void Commit(IReleaseSpec spec)

if (_logger.IsTrace)
{
_logger.Trace($" UPDATE {change.StorageAddress.Address}_{change.StorageAddress.Index} V = {change.Value.ToHexString(true)}");
_logger.Trace($" Update {change.StorageAddress.Address}_{change.StorageAddress.Index} V = {change.Value.ToHexString(true)}");
}

StorageTree tree = GetOrCreateStorage(change.StorageAddress.Address);
Expand Down Expand Up @@ -249,7 +249,7 @@ public void Commit(IReleaseSpec spec)

public void Reset()
{
if (_logger.IsTrace) _logger.Trace("Resetting storage.");
if (_logger.IsTrace) _logger.Trace("Resetting storage");

_intraBlockCache.Clear();
_originalValues.Clear();
Expand Down

0 comments on commit 510e3d3

Please sign in to comment.