Skip to content
This repository was archived by the owner on May 23, 2023. It is now read-only.

Commit 6d95df5

Browse files
vubvub
authored andcommitted
Improvements to testing modules
1 parent 9ac4219 commit 6d95df5

File tree

7 files changed

+66
-19
lines changed

7 files changed

+66
-19
lines changed

ethereum/new_statetest_utils.py

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@
77
import ethereum.transactions as transactions
88
import ethereum.state_transition as state_transition
99
import copy
10+
import json
1011

1112
from ethereum.slogging import LogRecorder, configure_logging, set_level
1213
config_string = ':info,eth.vm.log:trace,eth.vm.op:trace,eth.vm.stack:trace,eth.vm.exit:trace,eth.pb.msg:trace,eth.pb.tx:debug'
1314

14-
configure_logging(config_string=config_string)
15+
# configure_logging(config_string=config_string)
1516

1617
fake_headers = {}
1718

@@ -57,11 +58,37 @@ def mk_fake_header(blknum):
5758

5859
configs = {
5960
#"Homestead": konfig_homestead,
60-
"EIP150": konfig_tangerine,
61+
#"EIP150": konfig_tangerine,
6162
"EIP158": konfig_spurious,
6263
"Metropolis": konfig_metropolis
6364
}
6465

66+
def mk_state_diff(prev, post):
67+
o = {}
68+
for k in prev.keys():
69+
if k not in post:
70+
o[k] = ["-", prev[k]]
71+
for k in post.keys():
72+
if k not in prev:
73+
o[k] = ["+", post[k]]
74+
elif prev[k] != post[k]:
75+
ok = {}
76+
for key in ('nonce', 'balance', 'code'):
77+
if prev[k][key] != post[k][key]:
78+
ok[key] = [prev[k][key], "->", post[k][key]]
79+
if prev[k]["storage"] != post[k]["storage"]:
80+
ok["storage"] = {}
81+
for sk in prev[k]["storage"].keys():
82+
if sk not in post[k]["storage"]:
83+
ok["storage"][sk] = ["-", prev[k]["storage"][sk]]
84+
for sk in post[k]["storage"].keys():
85+
if sk not in prev[k]["storage"]:
86+
ok["storage"][sk] = ["+", post[k]["storage"][sk]]
87+
else:
88+
ok["storage"][sk] = [prev[k]["storage"][sk], "->", post[k]["storage"][sk]]
89+
o[k] = ok
90+
return o
91+
6592
def compute_state_test_unit(state, txdata, indices, konfig):
6693
state.env.config = konfig
6794
s = state.snapshot()
@@ -71,20 +98,24 @@ def compute_state_test_unit(state, txdata, indices, konfig):
7198
nonce=parse_int_or_hex(txdata['nonce'] or b"0"),
7299
gasprice=parse_int_or_hex(txdata['gasPrice'] or b"0"),
73100
startgas=parse_int_or_hex(txdata['gasLimit'][indices["gas"]] or b"0"),
74-
to=decode_hex(txdata['to']),
101+
to=decode_hex(remove_0x_head(txdata['to'])),
75102
value=parse_int_or_hex(txdata['value'][indices["value"]] or b"0"),
76103
data=decode_hex(remove_0x_head(txdata['data'][indices["data"]])))
77-
tx.sign(decode_hex(txdata['secretKey']))
104+
tx.sign(decode_hex(remove_0x_head(txdata['secretKey'])))
78105
# Run it
106+
prev = state.to_dict()
79107
success, output = state_transition.apply_transaction(state, tx)
108+
post = state.to_dict()
80109
print("Applied tx")
81110
except InvalidTransaction as e:
82111
print("Exception: %r" % e)
112+
post = state.to_dict()
83113
success, output = False, b''
84114
state.commit()
85115
output_decl = {
86-
"hash": encode_hex(state.trie.root_hash),
87-
"indexes": indices
116+
"hash": '0x' + encode_hex(state.trie.root_hash),
117+
"indexes": indices,
118+
"diff": mk_state_diff(prev, post)
88119
}
89120
state.revert(s)
90121
return output_decl
@@ -94,23 +125,23 @@ def init_state(env, pre):
94125
# Setup env
95126
state = State(
96127
env=Env(config=konfig),
97-
block_prevhash=decode_hex(env['previousHash']),
128+
block_prevhash=decode_hex(remove_0x_head(env['previousHash'])),
98129
prev_headers=[mk_fake_header(i) for i in range(parse_int_or_hex(env['currentNumber']) -1,
99130
max(-1, parse_int_or_hex(env['currentNumber']) -257), -1)],
100131
block_number=parse_int_or_hex(env['currentNumber']),
101-
block_coinbase=decode_hex(env['currentCoinbase']),
132+
block_coinbase=decode_hex(remove_0x_head(env['currentCoinbase'])),
102133
block_difficulty=parse_int_or_hex(env['currentDifficulty']),
103134
gas_limit=parse_int_or_hex(env['currentGasLimit']),
104135
timestamp=parse_int_or_hex(env['currentTimestamp']))
105136

106137
# Fill up pre
107138
for address, h in list(pre.items()):
108-
assert len(address) == 40
109-
address = decode_hex(address)
139+
assert len(address) in (40, 42)
140+
address = decode_hex(remove_0x_head(address))
110141
assert set(h.keys()) == set(['code', 'nonce', 'balance', 'storage'])
111142
state.set_nonce(address, parse_int_or_hex(h['nonce']))
112143
state.set_balance(address, parse_int_or_hex(h['balance']))
113-
state.set_code(address, decode_hex(h['code'][2:]))
144+
state.set_code(address, decode_hex(remove_0x_head(h['code'])))
114145
for k, v in h['storage'].items():
115146
state.set_storage_data(address,
116147
big_endian_to_int(decode_hex(k[2:])),
@@ -128,12 +159,17 @@ def verify_state_test(test):
128159
continue
129160
print("Testing for %s" % config_name)
130161
for result in results:
162+
data = test["transaction"]['data'][result["indexes"]["data"]]
163+
if len(data) > 2000:
164+
data = "data<%d>" % (len(data) // 2 - 1)
131165
print("Checking for values: g %d v %d d %s" % (
132166
parse_int_or_hex(test["transaction"]['gasLimit'][result["indexes"]["gas"]]),
133167
parse_int_or_hex(test["transaction"]['value'][result["indexes"]["value"]]),
134-
test["transaction"]['data'][result["indexes"]["data"]]))
168+
data))
135169
computed = compute_state_test_unit(_state, test["transaction"], result["indexes"], configs[config_name])
136170
if computed["hash"] != result["hash"]:
171+
for k in computed["diff"]:
172+
print(k, computed["diff"][k])
137173
raise Exception("Hash mismatch, computed: %s, supplied: %s" % (computed["hash"], result["hash"]))
138174
else:
139175
print("Hash matched!: %s" % computed["hash"])

ethereum/processblock.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from ethereum import bloom
99
from ethereum import vm as vm
1010
from ethereum.utils import safe_ord, normalize_address, mk_contract_address, \
11-
mk_metropolis_contract_address, int_to_addr, big_endian_to_int, encode_hex
11+
mk_metropolis_contract_address, int_to_addr, big_endian_to_int, encode_hex, sha3
1212
from ethereum.exceptions import InvalidNonce, InsufficientStartGas, UnsignedTransaction, \
1313
BlockGasLimitReached, InsufficientBalance
1414
from ethereum import transactions
@@ -121,7 +121,10 @@ def create_contract(ext, msg):
121121
if ext.tx_origin != msg.sender:
122122
ext.increment_nonce(msg.sender)
123123
nonce = utils.encode_int(ext.get_nonce(msg.sender) - 1)
124-
msg.to = mk_contract_address(sender, nonce)
124+
if ext.post_metropolis_hardfork() and msg.sender == ext.tx_origin and False:
125+
msg.to = sha3(msg.sender + code)[12:]
126+
else:
127+
msg.to = mk_contract_address(sender, nonce)
125128
b = ext.get_balance(msg.to)
126129
if b > 0:
127130
ext.set_balance(msg.to, b)
@@ -132,6 +135,8 @@ def create_contract(ext, msg):
132135
# assert not ext.get_code(msg.to)
133136
msg.data = vm.CallData([], 0, 0)
134137
snapshot = ext.snapshot()
138+
# if len(ext.get_code(msg.to)):
139+
# return 0, 0, b''
135140
ext.set_nonce(msg.to, 1 if ext.post_clearing_hardfork() else 0)
136141
res, gas, dat = _apply_msg(ext, msg, code)
137142
assert utils.is_numeric(gas)
@@ -145,7 +150,7 @@ def create_contract(ext, msg):
145150
gas -= gcost
146151
else:
147152
dat = []
148-
log_msg.debug('CONTRACT CREATION OOG', have=gas, want=gcost, block_number=ext.block_number)
153+
log_msg.debug('CONTRACT CREATION FAILED', have=gas, want=gcost, block_number=ext.block_number)
149154
if ext.post_homestead_hardfork():
150155
ext.revert(snapshot)
151156
return 0, 0, b''

ethereum/state.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ def to_dict(self):
353353
state_dump[encode_hex(address)][c] = snapshot_form(getattr(blanky, c))
354354
acct_dump = state_dump[encode_hex(address)]
355355
for key, val in v.items():
356-
if key in ACCOUNT_SPECIAL_PARAMS:
356+
if key in ACCOUNT_SPECIAL_PARAMS and key != 'storage':
357357
acct_dump[key] = snapshot_form(val)
358358
else:
359359
if val:

ethereum/state_transition.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,10 @@ def rp(what, actual, target):
237237
if tx.startgas < intrinsic_gas:
238238
raise InsufficientStartGas(rp('startgas', tx.startgas, intrinsic_gas))
239239

240-
log_tx.debug('TX NEW', tx_dict=tx.to_dict())
240+
txdict = tx.to_dict()
241+
if len(txdict["data"]) > 2000:
242+
txdict["data"] = "data<%d>" % (len(txdict["data"]) // 2 - 1)
243+
log_tx.debug('TX NEW', tx_dict=txdict)
241244
# start transacting #################
242245
state.increment_nonce(tx.sender)
243246

ethereum/transactions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def intrinsic_gas_used(self):
138138
num_zero_bytes = str_to_bytes(self.data).count(ascii_chr(0))
139139
num_non_zero_bytes = len(self.data) - num_zero_bytes
140140
return (opcodes.GTXCOST
141-
+ (0 if self.to else opcodes.CREATE[3])
141+
# + (0 if self.to else opcodes.CREATE[3])
142142
+ opcodes.GTXDATAZERO * num_zero_bytes
143143
+ opcodes.GTXDATANONZERO * num_non_zero_bytes)
144144

ethereum/vm.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from ethereum.utils import to_string, encode_int, zpad
1616

1717
log_log = get_logger('eth.vm.log')
18+
log_msg = get_logger('eth.pb.msg')
1819
log_vm_exit = get_logger('eth.vm.exit')
1920
log_vm_op = get_logger('eth.vm.op')
2021
log_vm_op_stack = get_logger('eth.vm.op.stack')
@@ -250,6 +251,7 @@ def vm_execute(ext, msg, code):
250251
trace_data['depth'] = msg.depth
251252
trace_data['address'] = msg.to
252253
trace_data['steps'] = steps
254+
trace_data['depth'] = msg.depth
253255
if op[:4] == 'PUSH':
254256
trace_data['pushvalue'] = pushval
255257
log_vm_op.trace('vm', op=op, **trace_data)
@@ -712,6 +714,7 @@ def vm_execute(ext, msg, code):
712714
ext.set_balance(to, ext.get_balance(to) + xfer)
713715
ext.set_balance(msg.to, 0)
714716
ext.add_suicide(msg.to)
717+
log_msg.debug('SUICIDING', addr=utils.checksum_encode(msg.to), to=utils.checksum_encode(to), xferring=xfer)
715718
return 1, compustate.gas, []
716719

717720
# assert utils.is_numeric(compustate.gas)

fixtures

Submodule fixtures updated 3345 files

0 commit comments

Comments
 (0)