-
Notifications
You must be signed in to change notification settings - Fork 650
/
test_rpc_fixtures.py
420 lines (334 loc) · 13.7 KB
/
test_rpc_fixtures.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import json
import os
import pytest
from cytoolz import (
dissoc,
identity,
get_in,
)
from eth_utils import (
add_0x_prefix,
is_hex,
is_integer,
is_string,
)
from eth.chains.base import (
MiningChain,
)
from eth.tools.fixtures import (
filter_fixtures,
generate_fixture_tests,
load_fixture,
should_run_slow_tests,
)
from trinity.chains.mainnet import (
MainnetFullChain
)
from trinity.rpc import RPCServer
from trinity.rpc.format import (
empty_to_0x,
remove_leading_zeros,
)
ROOT_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
BASE_FIXTURE_PATH = os.path.join(ROOT_PROJECT_DIR, 'fixtures', 'BlockchainTests')
SLOW_TESTS = (
'Call1024PreCalls_d0g0v0_Byzantium',
'Call1024PreCalls_d0g0v0_EIP150',
'Call1024PreCalls_d0g0v0_EIP158',
'ContractCreationSpam_d0g0v0_Homestead',
'ContractCreationSpam_d0g0v0_Frontier',
'ForkStressTest_EIP150',
'ForkStressTest_EIP158',
'ForkStressTest_Homestead',
'ForkStressTest_Frontier',
'ForkStressTest_Byzantium',
'stQuadraticComplexityTest/Call50000_d0g1v0.json',
'stQuadraticComplexityTest/QuadraticComplexitySolidity_CallDataCopy_d0g1v0.json',
'stQuadraticComplexityTest/Return50000_2_d0g1v0.json',
'stQuadraticComplexityTest/Return50000_d0g1v0.json',
'stQuadraticComplexityTest/Callcode50000_d0g1v0.json',
'stQuadraticComplexityTest/Call50000_sha256_d0g1v0.json',
'stQuadraticComplexityTest/Call50000_ecrec_d0g1v0.json',
'walletReorganizeOwners',
'bcExploitTest/SuicideIssue.json',
'DelegateCallSpam_Homestead',
'static_Call50000_sha256_d0g0v0_Byzantium',
'static_Call50000_rip160_d0g0v0_Byzantium',
'static_Call50000_rip160_d1g0v0_Byzantium',
'static_Call50000_sha256_d1g0v0_Byzantium',
'static_Call50000_ecrec_d1g0v0_Byzantium',
'static_Call50000_d1g0v0_Byzantium',
'static_Call50000_d0g0v0_Byzantium',
'static_Call50000_ecrec_d0g0v0_Byzantium',
'static_Call50000_identity2_d0g0v0_Byzantium',
'static_Call50000_identity2_d1g0v0_Byzantium',
'static_Call50000_identity_d1g0v0_Byzantium',
'static_Call50000_identity_d0g0v0_Byzantium',
'static_Call50000bytesContract50_1_d1g0v0_Byzantium',
'static_Call50000bytesContract50_2_d1g0v0_Byzantium',
'static_LoopCallsThenRevert_d0g0v0_Byzantium',
'static_LoopCallsThenRevert_d0g1v0_Byzantium',
'Call1024PreCalls_d0g0v0_Byzantium',
'Call1024PreCalls_d0g0v0_EIP158',
'Call1024PreCalls_d0g0v0_EIP150',
'Call1024PreCalls_d0g0v0_Byzantium',
'Call1024PreCalls_d0g0v0_EIP150',
'Call1024PreCalls_d0g0v0_EIP158',
'stQuadraticComplexityTest/Call50000_identity2_d0g1v0.json',
'stQuadraticComplexityTest/Call50000_identity_d0g1v0.json',
'stQuadraticComplexityTest/Call50000_rip160_d0g1v0.json',
'stQuadraticComplexityTest/Call50000bytesContract50_1_d0g1v0.json',
'stQuadraticComplexityTest/Create1000_d0g1v0.json',
'ShanghaiLove_Homestead',
'ShanghaiLove_Frontier',
'DelegateCallSpam_EIP158',
'DelegateCallSpam_Byzantium',
'DelegateCallSpam_EIP150',
)
# These are tests that are thought to be incorrect or buggy upstream,
# at the commit currently checked out in submodule `fixtures`.
# Ideally, this list should be empty.
# WHEN ADDING ENTRIES, ALWAYS PROVIDE AN EXPLANATION!
INCORRECT_UPSTREAM_TESTS = {
# The test considers a "synthetic" scenario (the state described there can't
# be arrived at using regular consensus rules).
# * https://github.com/ethereum/py-evm/pull/1224#issuecomment-418775512
# The result is in conflict with the yellow-paper:
# * https://github.com/ethereum/py-evm/pull/1224#issuecomment-418800369
('GeneralStateTests/stRevertTest/RevertInCreateInInit_d0g0v0.json', 'RevertInCreateInInit_d0g0v0_Byzantium'), # noqa: E501
}
RPC_STATE_NORMALIZERS = {
'balance': remove_leading_zeros,
'code': empty_to_0x,
'nonce': remove_leading_zeros,
}
RPC_BLOCK_REMAPPERS = {
'bloom': 'logsBloom',
'coinbase': 'miner',
'transactionsTrie': 'transactionsRoot',
'uncleHash': 'sha3Uncles',
'receiptTrie': 'receiptsRoot',
}
RPC_BLOCK_NORMALIZERS = {
'difficulty': remove_leading_zeros,
'extraData': empty_to_0x,
'gasLimit': remove_leading_zeros,
'gasUsed': remove_leading_zeros,
'number': remove_leading_zeros,
'timestamp': remove_leading_zeros,
}
RPC_TRANSACTION_REMAPPERS = {
'data': 'input',
'gasLimit': 'gas',
}
RPC_TRANSACTION_NORMALIZERS = {
'nonce': remove_leading_zeros,
'gasLimit': remove_leading_zeros,
'gasPrice': remove_leading_zeros,
'value': remove_leading_zeros,
'data': empty_to_0x,
'to': add_0x_prefix,
'r': remove_leading_zeros,
's': remove_leading_zeros,
'v': remove_leading_zeros,
}
def fixture_block_in_rpc_format(state):
return {
RPC_BLOCK_REMAPPERS.get(key, key):
RPC_BLOCK_NORMALIZERS.get(key, identity)(value)
for key, value in state.items()
}
def fixture_state_in_rpc_format(state):
return {
key: RPC_STATE_NORMALIZERS.get(key, identity)(value)
for key, value in state.items()
}
def fixture_transaction_in_rpc_format(state):
return {
RPC_TRANSACTION_REMAPPERS.get(key, key):
RPC_TRANSACTION_NORMALIZERS.get(key, identity)(value)
for key, value in state.items()
}
def blockchain_fixture_mark_fn(fixture_path, fixture_name):
for slow_test in SLOW_TESTS:
if slow_test in fixture_path or slow_test in fixture_name:
if not should_run_slow_tests():
return pytest.mark.skip("skipping slow test on a quick run")
break
if (fixture_path, fixture_name) in INCORRECT_UPSTREAM_TESTS:
return pytest.mark.xfail(reason="Listed in INCORRECT_UPSTREAM_TESTS.")
def pytest_generate_tests(metafunc):
generate_fixture_tests(
metafunc=metafunc,
base_fixture_path=BASE_FIXTURE_PATH,
filter_fn=filter_fixtures(
fixtures_base_dir=BASE_FIXTURE_PATH,
mark_fn=blockchain_fixture_mark_fn,
),
)
def build_request(method, params):
return {"jsonrpc": "2.0", "method": method, "params": params, "id": 3}
def result_from_response(response_str):
response = json.loads(response_str)
return (response.get('result', None), response.get('error', None))
async def call_rpc(rpc, method, params):
request = build_request(method, params)
response = await rpc.execute(request)
return result_from_response(response)
async def assert_rpc_result(rpc, method, params, expected):
result, error = await call_rpc(rpc, method, params)
assert error is None
assert result == expected
return result
async def validate_account_attribute(*, fixture_key, rpc_method, rpc, state, addr, at_block):
state_result, state_error = await call_rpc(rpc, rpc_method, [addr, at_block])
assert state_result == state[fixture_key], "Invalid state - %s" % state_error
RPC_STATE_LOOKUPS = (
('balance', 'eth_getBalance'),
('code', 'eth_getCode'),
('nonce', 'eth_getTransactionCount'),
)
async def validate_account_state(rpc, state, addr, at_block):
standardized_state = fixture_state_in_rpc_format(state)
for fixture_key, rpc_method in RPC_STATE_LOOKUPS:
await validate_account_attribute(
fixture_key=fixture_key,
rpc_method=rpc_method,
rpc=rpc,
state=standardized_state,
addr=addr,
at_block=at_block
)
for key in state['storage']:
position = '0x0' if key == '0x' else key
expected_storage = state['storage'][key]
await assert_rpc_result(
rpc,
'eth_getStorageAt',
[addr, position, at_block],
expected_storage
)
async def validate_accounts(rpc, states, at_block='latest'):
for addr in states:
await validate_account_state(rpc, states[addr], addr, at_block)
def validate_rpc_block_vs_fixture(block, block_fixture):
return validate_rpc_block_vs_fixture_header(block, block_fixture['blockHeader'])
def validate_rpc_block_vs_fixture_header(block, header_fixture):
expected = fixture_block_in_rpc_format(header_fixture)
actual_block = dissoc(
block,
'size',
'totalDifficulty',
'transactions',
'uncles',
)
assert actual_block == expected
def is_by_hash(at_block):
if is_string(at_block) and is_hex(at_block) and len(at_block) == 66:
return True
elif is_integer(at_block) or at_block in ('latest', 'earliest', 'pending'):
return False
else:
raise ValueError("Unrecognized 'at_block' value: %r" % at_block)
async def validate_transaction_count(rpc, block_fixture, at_block):
if is_by_hash(at_block):
rpc_method = 'eth_getBlockTransactionCountByHash'
else:
rpc_method = 'eth_getBlockTransactionCountByNumber'
expected_transaction_count = hex(len(block_fixture['transactions']))
await assert_rpc_result(rpc, rpc_method, [at_block], expected_transaction_count)
def validate_rpc_transaction_vs_fixture(transaction, fixture):
expected = fixture_transaction_in_rpc_format(fixture)
actual_transaction = dissoc(
transaction,
'hash',
)
assert actual_transaction == expected
async def validate_transaction_by_index(rpc, transaction_fixture, at_block, index):
if is_by_hash(at_block):
rpc_method = 'eth_getTransactionByBlockHashAndIndex'
else:
rpc_method = 'eth_getTransactionByBlockNumberAndIndex'
result, error = await call_rpc(rpc, rpc_method, [at_block, hex(index)])
assert error is None
validate_rpc_transaction_vs_fixture(result, transaction_fixture)
async def validate_block(rpc, block_fixture, at_block):
if is_by_hash(at_block):
rpc_method = 'eth_getBlockByHash'
else:
rpc_method = 'eth_getBlockByNumber'
# validate without transaction bodies
result, error = await call_rpc(rpc, rpc_method, [at_block, False])
assert error is None
validate_rpc_block_vs_fixture(result, block_fixture)
assert len(result['transactions']) == len(block_fixture['transactions'])
for index, transaction_fixture in enumerate(block_fixture['transactions']):
await validate_transaction_by_index(rpc, transaction_fixture, at_block, index)
await validate_transaction_count(rpc, block_fixture, at_block)
# TODO validate transaction bodies
result, error = await call_rpc(rpc, rpc_method, [at_block, True])
# assert error is None
# assert result['transactions'] == block_fixture['transactions']
await validate_uncles(rpc, block_fixture, at_block)
async def validate_last_block(rpc, block_fixture):
header = block_fixture['blockHeader']
await validate_block(rpc, block_fixture, 'latest')
await validate_block(rpc, block_fixture, header['hash'])
await validate_block(rpc, block_fixture, int(header['number'], 16))
async def validate_uncle_count(rpc, block_fixture, at_block):
if is_by_hash(at_block):
rpc_method = 'eth_getUncleCountByBlockHash'
else:
rpc_method = 'eth_getUncleCountByBlockNumber'
num_uncles = len(block_fixture['uncleHeaders'])
await assert_rpc_result(rpc, rpc_method, [at_block], hex(num_uncles))
async def validate_uncle_headers(rpc, block_fixture, at_block):
if is_by_hash(at_block):
rpc_method = 'eth_getUncleByBlockHashAndIndex'
else:
rpc_method = 'eth_getUncleByBlockNumberAndIndex'
for idx, uncle in enumerate(block_fixture['uncleHeaders']):
result, error = await call_rpc(rpc, rpc_method, [at_block, hex(idx)])
assert error is None
validate_rpc_block_vs_fixture_header(result, uncle)
async def validate_uncles(rpc, block_fixture, at_block):
await validate_uncle_count(rpc, block_fixture, at_block)
await validate_uncle_headers(rpc, block_fixture, at_block)
@pytest.fixture
def chain_fixture(fixture_data):
fixture = load_fixture(*fixture_data)
if fixture['network'] == 'Constantinople':
pytest.skip('Constantinople VM rules not yet supported')
return fixture
@pytest.fixture
def chain(chain_without_block_validation):
if isinstance(chain_without_block_validation, MiningChain):
# These tests are long. For RPC state tests, there shouldn't be any
# significant difference between a mining chain and a basic chain.
pytest.skip("Only need to test basic chain")
return
@pytest.mark.asyncio
async def test_rpc_against_fixtures(chain, ipc_server, chain_fixture, fixture_data):
rpc = RPCServer(MainnetFullChain(None))
setup_result, setup_error = await call_rpc(rpc, 'evm_resetToGenesisFixture', [chain_fixture])
assert setup_error is None and setup_result is True, "cannot load chain for {0}".format(fixture_data) # noqa: E501
await validate_accounts(rpc, chain_fixture['pre'])
for block_fixture in chain_fixture['blocks']:
should_be_good_block = 'blockHeader' in block_fixture
if 'rlp_error' in block_fixture:
assert not should_be_good_block
continue
block_result, block_error = await call_rpc(rpc, 'evm_applyBlockFixture', [block_fixture])
if should_be_good_block:
assert block_error is None
assert block_result == block_fixture['rlp']
await validate_block(rpc, block_fixture, block_fixture['blockHeader']['hash'])
else:
assert block_error is not None
if chain_fixture.get('lastblockhash', None):
for block_fixture in chain_fixture['blocks']:
if get_in(['blockHeader', 'hash'], block_fixture) == chain_fixture['lastblockhash']:
await validate_last_block(rpc, block_fixture)
await validate_accounts(rpc, chain_fixture['postState'])
await validate_accounts(rpc, chain_fixture['pre'], 'earliest')
await validate_accounts(rpc, chain_fixture['pre'], 0)