diff --git a/.coveragerc b/.coveragerc index 60afd11d0..79192b34e 100644 --- a/.coveragerc +++ b/.coveragerc @@ -9,7 +9,6 @@ omit = */ethereum/fastvm.py */ethereum/spv.py -[report] exclude_lines = pragma: no cover def __repr__ diff --git a/.travis.yml b/.travis.yml index 83ced25b8..41c349f0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: python -python: 2.7 +python: 3.5 sudo: required dist: trusty before_install: @@ -9,17 +9,26 @@ before_install: env: matrix: - TOX_ENV=py27 + - TOX_ENV=py34 + - TOX_ENV=py35 global: - secure: cKbIgpTJ1yjKLBxpCEiT6IH7NShDWZUE+BvnrAfc+ujCsR6LyLJcKxFQmKnWryJCqg7fp82Ep2bF2oDKzanAROar2xDY1SFGbai42seYMaFCw53YPGJ6u3VNCcfT0rN9BWgE7el/m4fjcD6CRsZYKArNNJbMX8csRt3uXXCFLso= + - COVERAGE_APPEND="--append" + - secure: cKbIgpTJ1yjKLBxpCEiT6IH7NShDWZUE+BvnrAfc+ujCsR6LyLJcKxFQmKnWryJCqg7fp82Ep2bF2oDKzanAROar2xDY1SFGbai42seYMaFCw53YPGJ6u3VNCcfT0rN9BWgE7el/m4fjcD6CRsZYKArNNJbMX8csRt3uXXCFLso= install: -- pip install -Ur requirements.txt -- pip install -Ur dev_requirements.txt + - travis_retry pip install setuptools --upgrade + - travis_retry pip install tox + - travis_retry pip install coverage script: -- coverage run --source ethereum -m py.test --ignore ethereum/tests/test_vm.py --ignore ethereum/tests/test_state.py -- coverage run --append --source ethereum -m py.test ethereum/tests/test_vm.py -- coverage run --append --source ethereum -m py.test ethereum/tests/test_state.py + - if [ -d .tox/$TOX_ENV/ ]; then cd .tox/$TOX_ENV && coverage erase; fi; + - tox -e $TOX_ENV -- --ignore ethereum/tests/test_vm.py --ignore ethereum/tests/test_state.py + - tox -e $TOX_ENV -- ethereum/tests/test_vm.py + - tox -e $TOX_ENV -- ethereum/tests/test_state.py + - cd .tox/$TOX_ENV && coverage report --show-missing after_success: -- coveralls + - travis_retry pip install coveralls + - cd .tox/$TOX_ENV && coveralls +after_script: + - cat .tox/$TOX_ENV/log/*.log notifications: slack: secure: W/UAhQ/GgYwMWrl3aiVAVOWr4WGdWrxUOX/rTB3ZgwDwGqDYLzQO5UqbsQlo1JXPZ6JOWfIPMURhHu7DSfue9dBW6xQ+NL+bFHe9lSXG4nqFK3IjezYyTBzNRJRDbGUvSSqgj6D5cwhJ8BjfUIRPbJz3CxL64KmsNXezEaMY60w= diff --git a/dev_requirements.txt b/dev_requirements.txt index 8bd463833..f09e78f97 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -3,4 +3,4 @@ coveralls pytest>=2.9.0 pytest-catchlog==1.2.2 pytest-timeout==1.0.0 -https://github.com/ethereum/serpent/tarball/develop +https://github.com/pipermerriam/serpent/tarball/piper/python3-support-with-pyethereum3 diff --git a/ethereum/__init__.py b/ethereum/__init__.py index 568b40b54..dea805bdb 100644 --- a/ethereum/__init__.py +++ b/ethereum/__init__.py @@ -5,7 +5,7 @@ import subprocess import re # Import slogging to patch logging as soon as possible -import slogging # noqa +from . import slogging # noqa GIT_DESCRIBE_RE = re.compile('^(?Pv\d+\.\d+\.\d+)-(?P\d+-g[a-fA-F0-9]+(?:-dirty)?)$') diff --git a/ethereum/_solidity.py b/ethereum/_solidity.py index 3b743798a..462210d6a 100644 --- a/ethereum/_solidity.py +++ b/ethereum/_solidity.py @@ -6,6 +6,9 @@ import yaml +from rlp.utils import decode_hex +from . import utils + BINARY = 'solc' @@ -49,7 +52,7 @@ def solc_arguments(libraries=None, combined='bin,abi', optimize=True): if libraries is not None and len(libraries): addresses = [ - '{name}:{address}'.format(name=name, address=address) + '{name}:{address}'.format(name=name, address=address.decode('utf8')) for name, address in libraries.items() ] args.extend([ @@ -64,13 +67,13 @@ def solc_parse_output(compiler_output): """ Parses the compiler output. """ result = yaml.safe_load(compiler_output)['contracts'] - if 'bin' in result.values()[0]: + if 'bin' in tuple(result.values())[0]: for value in result.values(): value['bin_hex'] = value['bin'] # decoding can fail if the compiled contract has unresolved symbols try: - value['bin'] = value['bin_hex'].decode('hex') + value['bin'] = decode_hex(value['bin_hex']) except TypeError: pass @@ -78,7 +81,7 @@ def solc_parse_output(compiler_output): # the values in the output can be configured through the # --combined-json flag, check that it's present in the first value and # assume all values are consistent - if json_data not in result.values()[0]: + if json_data not in tuple(result.values())[0]: continue for value in result.values(): @@ -182,7 +185,7 @@ def solidity_resolve_address(hex_code, library_symbol, library_address): raise ValueError('Address should not contain the 0x prefix') try: - _ = library_address.decode('hex') + _ = decode_hex(library_address) except TypeError: raise ValueError('library_address contains invalid characters, it must be hex encoded.') @@ -291,8 +294,11 @@ def compile_code(sourcecode, libraries=None, combined='bin,abi', optimize=True): args = solc_arguments(libraries=libraries, combined=combined, optimize=optimize) args.insert(0, get_compiler_path()) - process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - stdoutdata, _ = process.communicate(input=sourcecode) + process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdoutdata, stderrdata = process.communicate(input=utils.to_string(sourcecode)) + + if process.returncode != 0: + raise CompileError(stderrdata) return solc_parse_output(stdoutdata) diff --git a/ethereum/abi.py b/ethereum/abi.py index f174019a0..1ac037d64 100644 --- a/ethereum/abi.py +++ b/ethereum/abi.py @@ -222,7 +222,7 @@ def listen(self, log, noprint=True): if indexed[i]] unindexed_types = [types[i] for i in range(len(types)) if not indexed[i]] - # print('listen', log.data.encode('hex'), log.topics) + # print('listen', encode_hex(log.data), log.topics) deserialized_args = decode_abi(unindexed_types, log.data) o = {} c1, c2 = 0, 0 @@ -494,14 +494,14 @@ def decode_single(typ, data): return (o - 2**int(sub)) if o >= 2**(int(sub) - 1) else o elif base == 'ureal': high, low = [int(x) for x in sub.split('x')] - return big_endian_to_int(data) * 1.0 / 2**low + return big_endian_to_int(data) * 1.0 // 2**low elif base == 'real': high, low = [int(x) for x in sub.split('x')] o = big_endian_to_int(data) i = (o - 2**(high+low)) if o >= 2**(high+low-1) else o - return (i * 1.0 / 2**low) + return (i * 1.0 // 2**low) elif base == 'bool': - return bool(int(data.encode('hex'), 16)) + return bool(int(encode_hex(data), 16)) # Decodes multiple arguments using the head/tail mechanism diff --git a/ethereum/blocks.py b/ethereum/blocks.py index ee20a4059..59dc223e7 100644 --- a/ethereum/blocks.py +++ b/ethereum/blocks.py @@ -74,7 +74,7 @@ def calc_difficulty(parent, timestamp): period_count = (parent.number + 1) // config['EXPDIFF_PERIOD'] if period_count >= config['EXPDIFF_FREE_PERIODS']: o = max(o + 2**(period_count - config['EXPDIFF_FREE_PERIODS']), config['MIN_DIFF']) - # print 'Calculating difficulty of block %d, timestamp difference %d, parent diff %d, child diff %d' % (parent.number + 1, timestamp - parent.timestamp, parent.difficulty, o) + # print('Calculating difficulty of block %d, timestamp difference %d, parent diff %d, child diff %d' % (parent.number + 1, timestamp - parent.timestamp, parent.difficulty, o)) return o @@ -676,8 +676,8 @@ def validate_uncles(self): return False if uncle.prevhash not in eligible_ancestor_hashes: log.error("Uncle does not have a valid ancestor", block=self, - eligible=[x.encode('hex') for x in eligible_ancestor_hashes], - uncle_prevhash=uncle.prevhash.encode('hex')) + eligible=[encode_hex(x) for x in eligible_ancestor_hashes], + uncle_prevhash=encode_hex(uncle.prevhash)) return False if uncle in ineligible: log.error("Duplicate uncle", block=self, @@ -1035,7 +1035,7 @@ def commit_state(self): # except: # pass # sys.stderr.write("pre: %r\n" % self.account_to_dict(addr)['storage']) - # sys.stderr.write("pre: %r\n" % self.get_storage(addr).root_hash.encode('hex')) + # sys.stderr.write("pre: %r\n" % encode_hex(self.get_storage(addr).root_hash)) # sys.stderr.write("changed: %s %s %s\n" % (encode_hex(addr), encode_hex(enckey), encode_hex(val))) if v: t.update(enckey, val) @@ -1168,11 +1168,12 @@ def finalize(self): self.delta_balance(self.coinbase, delta) self.ether_delta += delta + br = self.config['BLOCK_REWARD'] + udpf = self.config['UNCLE_DEPTH_PENALTY_FACTOR'] + for uncle in self.uncles: - r = self.config['BLOCK_REWARD'] * \ - (self.config['UNCLE_DEPTH_PENALTY_FACTOR'] + uncle.number - self.number) \ - / self.config['UNCLE_DEPTH_PENALTY_FACTOR'] - r = int(r) + r = int(br * (udpf + uncle.number - self.number) // udpf) + self.delta_balance(uncle.coinbase, r) self.ether_delta += r self.commit_state() @@ -1307,7 +1308,7 @@ def calc_gaslimit(parent): def check_gaslimit(parent, gas_limit): config = parent.config - # block.gasLimit - parent.gasLimit <= parent.gasLimit / GasLimitBoundDivisor + # block.gasLimit - parent.gasLimit <= parent.gasLimit // GasLimitBoundDivisor gl = parent.gas_limit // config['GASLIMIT_ADJMAX_FACTOR'] a = bool(abs(gas_limit - parent.gas_limit) <= gl) b = bool(gas_limit >= config['MIN_GAS_LIMIT']) diff --git a/ethereum/bloom.py b/ethereum/bloom.py index 97156bd75..fc8a4cb2f 100644 --- a/ethereum/bloom.py +++ b/ethereum/bloom.py @@ -27,7 +27,7 @@ def bloom(val): def bloom_insert(bloom, val): h = utils.sha3(val) -# print 'bloom_insert', bloom_bits(val), repr(val) +# print('bloom_insert', bloom_bits(val), repr(val)) for i in range(0, BUCKETS_PER_VAL * 2, 2): bloom |= 1 << ((safe_ord(h[i + 1]) + (safe_ord(h[i]) << 8)) & 2047) return bloom diff --git a/ethereum/chain.py b/ethereum/chain.py index 12c1faa5f..7228e7aaa 100644 --- a/ethereum/chain.py +++ b/ethereum/chain.py @@ -110,7 +110,7 @@ class Chain(object): """ head_candidate = None - def __init__(self, env, genesis=None, new_head_cb=None, coinbase='\x00' * 20): + def __init__(self, env, genesis=None, new_head_cb=None, coinbase=b'\x00' * 20): assert isinstance(env, Env) self.env = env self.db = self.blockchain = env.db @@ -121,7 +121,7 @@ def __init__(self, env, genesis=None, new_head_cb=None, coinbase='\x00' * 20): self._initialize_blockchain(genesis) log.debug('chain @', head_hash=self.head) self.genesis = self.get(self.index.get_block_by_number(0)) - log.debug('got genesis', nonce=self.genesis.nonce.encode('hex'), + log.debug('got genesis', nonce=encode_hex(self.genesis.nonce), difficulty=self.genesis.difficulty) self._update_head_candidate() diff --git a/ethereum/ethash.py b/ethereum/ethash.py index 5d805a077..45347e94c 100644 --- a/ethereum/ethash.py +++ b/ethereum/ethash.py @@ -9,7 +9,7 @@ from functools import lru_cache -cache_seeds = ['\x00' * 32] +cache_seeds = [b'\x00' * 32] def mkcache(block_number): diff --git a/ethereum/ethash_utils.py b/ethereum/ethash_utils.py index 61b252a0b..84fe71c23 100644 --- a/ethereum/ethash_utils.py +++ b/ethereum/ethash_utils.py @@ -94,7 +94,7 @@ def deserialize_cache(ds): class ListWrapper(list): def __init__(self, data): self.data = data - self.len = len(data) / HASH_BYTES + self.len = len(data) // HASH_BYTES def __len__(self): return self.len @@ -122,7 +122,7 @@ def isprime(x): def get_cache_size(block_number): sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * (block_number // EPOCH_LENGTH) sz -= HASH_BYTES - while not isprime(sz / HASH_BYTES): + while not isprime(sz // HASH_BYTES): sz -= 2 * HASH_BYTES return sz @@ -130,6 +130,6 @@ def get_cache_size(block_number): def get_full_size(block_number): sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * (block_number // EPOCH_LENGTH) sz -= MIX_BYTES - while not isprime(sz / MIX_BYTES): + while not isprime(sz // MIX_BYTES): sz -= 2 * MIX_BYTES return sz diff --git a/ethereum/ethpow.py b/ethereum/ethpow.py index f501c9509..5223df96b 100644 --- a/ethereum/ethpow.py +++ b/ethereum/ethpow.py @@ -69,9 +69,9 @@ def check_pow(block_number, header_hash, mixhash, nonce, difficulty): # Grab current cache cache = get_cache(block_number) mining_output = hashimoto_light(block_number, cache, header_hash, nonce) - if mining_output['mix digest'] != mixhash: + if mining_output[b'mix digest'] != mixhash: return False - return utils.big_endian_to_int(mining_output['result']) <= 2**256 / (difficulty or 1) + return utils.big_endian_to_int(mining_output[b'result']) <= 2**256 // (difficulty or 1) class Miner(): @@ -114,9 +114,9 @@ def mine(block_number, difficulty, mining_hash, start_nonce=0, rounds=1000): for i in range(1, rounds + 1): bin_nonce = utils.zpad(utils.int_to_big_endian((nonce + i) & TT64M1), 8) o = hashimoto_light(block_number, cache, mining_hash, bin_nonce) - if o["result"] <= target: + if o[b"result"] <= target: log.debug("nonce found") assert len(bin_nonce) == 8 - assert len(o["mix digest"]) == 32 - return bin_nonce, o["mix digest"] + assert len(o[b"mix digest"]) == 32 + return bin_nonce, o[b"mix digest"] return None, None diff --git a/ethereum/fast_rlp.py b/ethereum/fast_rlp.py index 3db6e6384..87cce5d43 100644 --- a/ethereum/fast_rlp.py +++ b/ethereum/fast_rlp.py @@ -1,7 +1,7 @@ import sys import rlp -from utils import int_to_big_endian, big_endian_to_int, safe_ord -import db +from .utils import int_to_big_endian, big_endian_to_int, safe_ord +from . import db def _encode_optimized(item): @@ -73,7 +73,9 @@ def consume_length_prefix(rlp, start): decode_optimized = _decode_optimized else: encode_optimized = rlp.codec.encode_raw - decode_optimized = rlp.codec.decode_raw + # rlp does not implement a decode_raw function. + # decode_optimized = rlp.codec.decode_raw + decode_optimized = _decode_optimized def main(): @@ -85,20 +87,20 @@ def run(): x = trie.Trie(db.EphemDB()) for i in range(10000): x.update(str(i), str(i**3)) - print 'elapsed', time.time() - st + print('elapsed', time.time() - st) return x.root_hash trie.rlp_encode = _encode_optimized - print 'trie.rlp_encode = encode_optimized' + print('trie.rlp_encode = encode_optimized') r3 = run() trie.rlp_encode = rlp.codec.encode_raw - print 'trie.rlp_encode = rlp.codec.encode_raw' + print('trie.rlp_encode = rlp.codec.encode_raw') r2 = run() assert r2 == r3 trie.rlp_encode = rlp.encode - print 'trie.rlp_encode = rlp.encode' + print('trie.rlp_encode = rlp.encode') r = run() assert r == r2 diff --git a/ethereum/fastvm.py b/ethereum/fastvm.py index 70efc3e73..932de166b 100644 --- a/ethereum/fastvm.py +++ b/ethereum/fastvm.py @@ -209,7 +209,7 @@ def vm_execute(ext, msg, code): _prevop = None # for trace only while 1: - # print 'op: ', op, time.time() - s + # print('op: ', op, time.time() - s) # s = time.time() # stack size limit error if compustate.pc not in processed_code: diff --git a/ethereum/keys.py b/ethereum/keys.py index ff58524bd..0623c1791 100644 --- a/ethereum/keys.py +++ b/ethereum/keys.py @@ -2,6 +2,8 @@ import pbkdf2 import sys +from rlp.utils import encode_hex, decode_hex + try: scrypt = __import__('scrypt') except ImportError: @@ -225,16 +227,6 @@ def zpad(x, l): if sys.version_info.major == 2: - def decode_hex(s): - if not isinstance(s, (str, unicode)): - raise TypeError('Value must be an instance of str or unicode') - return s.decode('hex') - - def encode_hex(s): - if not isinstance(s, (str, unicode)): - raise TypeError('Value must be an instance of str or unicode') - return s.encode('hex') - def int_to_big_endian(value): cs = [] while value > 0: @@ -247,29 +239,15 @@ def big_endian_to_int(value): if len(value) == 1: return ord(value) elif len(value) <= 8: - return struct.unpack('>Q', value.rjust(8, '\x00'))[0] + return struct.unpack('>Q', value.rjust(8, b'\x00'))[0] else: return int(encode_hex(value), 16) if sys.version_info.major == 3: - def decode_hex(s): - if isinstance(s, str): - return bytes.fromhex(s) - if isinstance(s, bytes): - return binascii.unhexlify(s) - raise TypeError('Value must be an instance of str or bytes') - - def encode_hex(b): - if isinstance(b, str): - b = bytes(b, 'utf-8') - if isinstance(b, bytes): - return binascii.hexlify(b) - raise TypeError('Value must be an instance of str or bytes') - def int_to_big_endian(value): - byte_length = ceil(value.bit_length() / 8) + byte_length = ceil(value.bit_length() // 8) return (value).to_bytes(byte_length, byteorder='big') def big_endian_to_int(value): diff --git a/ethereum/processblock.py b/ethereum/processblock.py index 0797b4dac..c7745f3e2 100644 --- a/ethereum/processblock.py +++ b/ethereum/processblock.py @@ -136,7 +136,7 @@ def __repr__(self): def apply_transaction(block, tx): validate_transaction(block, tx) - # print block.get_nonce(tx.sender), '@@@' + # print(block.get_nonce(tx.sender), '@@@') def rp(what, actual, target): return '%r: %r actual:%r target:%r' % (tx, what, actual, target) @@ -256,10 +256,10 @@ def _apply_msg(ext, msg, code): gas=msg.gas, value=msg.value, data=encode_hex(msg.data.extract_all())) if log_state.is_active('trace'): - log_state.trace('MSG PRE STATE SENDER', account=msg.sender.encode('hex'), + log_state.trace('MSG PRE STATE SENDER', account=encode_hex(msg.sender), bal=ext.get_balance(msg.sender), state=ext.log_storage(msg.sender)) - log_state.trace('MSG PRE STATE RECIPIENT', account=msg.to.encode('hex'), + log_state.trace('MSG PRE STATE RECIPIENT', account=encode_hex(msg.to), bal=ext.get_balance(msg.to), state=ext.log_storage(msg.to)) # log_state.trace('CODE', code=code) @@ -281,10 +281,10 @@ def _apply_msg(ext, msg, code): log_msg.debug('MSG APPLIED', gas_remained=gas, sender=encode_hex(msg.sender), to=encode_hex(msg.to), data=dat) if log_state.is_active('trace'): - log_state.trace('MSG POST STATE SENDER', account=msg.sender.encode('hex'), + log_state.trace('MSG POST STATE SENDER', account=encode_hex(msg.sender), bal=ext.get_balance(msg.sender), state=ext.log_storage(msg.sender)) - log_state.trace('MSG POST STATE RECIPIENT', account=msg.to.encode('hex'), + log_state.trace('MSG POST STATE RECIPIENT', account=encode_hex(msg.to), bal=ext.get_balance(msg.to), state=ext.log_storage(msg.to)) diff --git a/ethereum/pruning_trie.py b/ethereum/pruning_trie.py index 9cb53e6a9..c37aafa5a 100644 --- a/ethereum/pruning_trie.py +++ b/ethereum/pruning_trie.py @@ -270,7 +270,7 @@ def replace_root_hash(self, old_node, new_node): self._delete_node_storage(old_node, is_root=True) self._encode_node(new_node, is_root=True) self.root_node = new_node - # sys.stderr.write('nrh: %s\n' % self.root_hash.encode('hex')) + # sys.stderr.write('nrh: %s\n' % encode_hex(self.root_hash)) @root_hash.setter def root_hash(self, value): @@ -285,7 +285,7 @@ def set_root_hash(self, root_hash): if root_hash == BLANK_ROOT: self.root_node = BLANK_NODE return - # print repr(root_hash) + # print(repr(root_hash)) self.root_node = self._decode_to_node(root_hash) # dummy to increase reference count # self._encode_node(self.root_node) diff --git a/ethereum/refcount_db.py b/ethereum/refcount_db.py index 8f89d8dca..dbca86410 100644 --- a/ethereum/refcount_db.py +++ b/ethereum/refcount_db.py @@ -1,7 +1,7 @@ import rlp import ethereum.utils as utils import sys -from db import BaseDB +from .db import BaseDB DEATH_ROW_OFFSET = 2**62 ZERO_ENCODED = utils.encode_int(0) diff --git a/ethereum/specials.py b/ethereum/specials.py index 8763382c4..8a4a1cd76 100644 --- a/ethereum/specials.py +++ b/ethereum/specials.py @@ -92,10 +92,10 @@ def proc_identity(ext, msg): specials = { decode_hex(k): v for k, v in { - '0000000000000000000000000000000000000001': proc_ecrecover, - '0000000000000000000000000000000000000002': proc_sha256, - '0000000000000000000000000000000000000003': proc_ripemd160, - '0000000000000000000000000000000000000004': proc_identity, + b'0000000000000000000000000000000000000001': proc_ecrecover, + b'0000000000000000000000000000000000000002': proc_sha256, + b'0000000000000000000000000000000000000003': proc_ripemd160, + b'0000000000000000000000000000000000000004': proc_identity, }.items() } diff --git a/ethereum/tests/benchmark_db.py b/ethereum/tests/benchmark_db.py index c2cf09afb..4ce8d76ed 100644 --- a/ethereum/tests/benchmark_db.py +++ b/ethereum/tests/benchmark_db.py @@ -17,6 +17,6 @@ def benchmark(size): nsz.append(sum([len(v) for k, v in ldb2.kv.items()])) t.db = odb ldbsz = sum([len(v) for k, v in ldb.kv.items()]) - print sz, sum(nsz) // len(nsz), ldbsz + print(sz, sum(nsz) // len(nsz), ldbsz) benchmark(int(sys.argv[1]) if len(sys.argv) > 1 else 1000) diff --git a/ethereum/tests/bintrie.py b/ethereum/tests/bintrie.py index 721e72854..97e474e05 100644 --- a/ethereum/tests/bintrie.py +++ b/ethereum/tests/bintrie.py @@ -255,8 +255,8 @@ def test(n, m=100): k = hashfunc(str(i)) v = hashfunc('v'+str(i)) x = update(x, db, [int(a) for a in encode_bin(rlp.encode(k))], v) - print x - print sum([len(val) for key, val in db.db.items()]) + print(x) + print(sum([len(val) for key, val in db.db.items()])) l1 = ListeningDB(db) o = 0 p = 0 @@ -282,8 +282,8 @@ def test(n, m=100): o = { 'total_db_size': sum([len(val) for key, val in l1.kv.items()]), 'avg_proof_size': sum([len(val) for key, val in l1.kv.items()]), - 'avg_compressed_proof_size': (p / min(n, m)), - 'avg_branch_size': (q / min(n, m)), + 'avg_compressed_proof_size': (p // min(n, m)), + 'avg_branch_size': (q // min(n, m)), 'compressed_db_size': len(compress_db(l1)) } return o diff --git a/ethereum/tests/profile_vm.py b/ethereum/tests/profile_vm.py index 4e573ebe8..f90a08abb 100644 --- a/ethereum/tests/profile_vm.py +++ b/ethereum/tests/profile_vm.py @@ -1,29 +1,34 @@ -import json import os import sys import ethereum.testutils as testutils import cProfile import pstats -import StringIO import time -from ethereum.utils import sha3 +from rlp.utils import encode_hex +from ethereum.utils import sha3, to_string from ethereum.slogging import get_logger logger = get_logger() +if sys.version_info.major == 2: + from io import BytesIO as StringIO +else: + from io import StringIO + + def do_test_vm(filename, testname=None, testdata=None, limit=99999999, profiler=None): logger.debug('running test:%r in %r' % (testname, filename)) testutils.run_vm_test(testutils.fixture_to_bytes(testdata), testutils.VERIFY, profiler=profiler) if __name__ == '__main__': num = 5000 - print 'profile_vm.py [no_cprofile]' - print 'loading tests' + print('profile_vm.py [no_cprofile]') + print('loading tests') fixtures = testutils.get_tests_from_file_or_dir( os.path.join(testutils.fixture_path, 'VMTests')) def run(profiler=None): - print 'running' + print('running') i = 0 seen = b'' for filename, tests in fixtures.items(): @@ -31,27 +36,26 @@ def run(profiler=None): if i == num: break do_test_vm(filename, testname, testdata, profiler=profiler) - seen += str(testname) + seen += to_string(testname) i += 1 - print 'ran %d tests' % i - print 'test key', sha3(seen).encode('hex') + print('ran %d tests' % i) + print('test key', encode_hex(sha3(seen))) if len(sys.argv) == 1: pr = cProfile.Profile() run(pr) - s = StringIO.StringIO() + s = StringIO() sortby = 'tottime' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats(50) - print s.getvalue() + print(s.getvalue()) else: # pypy version st = time.time() run() - print - print 'took total', time.time() - st + print('took total', time.time() - st) try: # pypy branch from ethereum.utils import sha3_call_counter - print 'took w/o sha3', time.time() - st - sha3_call_counter[3] + print('took w/o sha3', time.time() - st - sha3_call_counter[3]) except ImportError: pass diff --git a/ethereum/tests/test_abi.py b/ethereum/tests/test_abi.py index 03fd3933a..7c371a5b3 100644 --- a/ethereum/tests/test_abi.py +++ b/ethereum/tests/test_abi.py @@ -34,7 +34,7 @@ def test_abi_encode_single_int(): def test_abi_encode_single_ureal(): assert abi.encode_single(['ureal', '128x128', []], 0) == (b'\x00'*32) - assert abi.encode_single(['ureal', '128x128', []], 1.125) == (b'\x00'*15 + b'\x01\x20' + '\x00'*15) + assert abi.encode_single(['ureal', '128x128', []], 1.125) == (b'\x00'*15 + b'\x01\x20' + b'\x00'*15) assert abi.encode_single(['ureal', '128x128', []], 2**127-1) == (b'\x7f' + b'\xff'*15 + b'\x00'*16) def test_abi_encode_single_real(): @@ -51,10 +51,10 @@ def test_abi_decode_single_hash(): def test_abi_decode_single_bytes(): typ = ['bytes', '8', []] - assert (b'\x01\x02' + b'\x00'*6) == abi.decode_single(typ, abi.encode_single(typ, '\x01\x02')) + assert (b'\x01\x02' + b'\x00'*6) == abi.decode_single(typ, abi.encode_single(typ, b'\x01\x02')) typ = ['bytes', '', []] - assert b'\x01\x02' == abi.decode_single(typ, abi.encode_single(typ, '\x01\x02')) + assert b'\x01\x02' == abi.decode_single(typ, abi.encode_single(typ, b'\x01\x02')) def test_abi_encode_single_prefixed_address(): prefixed_address = '0x' + '0'*40 diff --git a/ethereum/tests/test_blocks.py b/ethereum/tests/test_blocks.py index 6d53cff77..55ad5cca4 100644 --- a/ethereum/tests/test_blocks.py +++ b/ethereum/tests/test_blocks.py @@ -95,7 +95,7 @@ def run_block_test(params, config_overrides = {}): blockmap[b2.hash] = b2 env.db.put(b2.hash, rlp.encode(b2)) if b2: - print 'Block %d with state root %s' % (b2.number, b2.state.root_hash.encode('hex')) + print('Block %d with state root %s' % (b2.number, encode_hex(b2.state.root_hash))) # blkdict = b.to_dict(False, True, False, True) # assert blk["blockHeader"] == \ # translate_keys(blkdict["header"], translator_list, lambda y, x: x, []) diff --git a/ethereum/tests/test_chain.py b/ethereum/tests/test_chain.py index 220c8883a..1848dc60f 100644 --- a/ethereum/tests/test_chain.py +++ b/ethereum/tests/test_chain.py @@ -525,7 +525,7 @@ def test_reward_uncles(db): assert blk2 == chain.head assert chain.head.get_balance(local_coinbase) == \ 2 * chain.env.config['BLOCK_REWARD'] + chain.env.config['NEPHEW_REWARD'] - assert chain.head.get_balance(uncle_coinbase) == chain.env.config['BLOCK_REWARD'] * 7 / 8 + assert chain.head.get_balance(uncle_coinbase) == chain.env.config['BLOCK_REWARD'] * 7 // 8 # TODO ########################################## diff --git a/ethereum/tests/test_contracts.py b/ethereum/tests/test_contracts.py index 6d652603b..ec8c94615 100644 --- a/ethereum/tests/test_contracts.py +++ b/ethereum/tests/test_contracts.py @@ -1207,8 +1207,8 @@ def test_ecrecover(): signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(msghash, raw=True) ) - signature = signature[0] + chr(signature[1]) - V = ord(signature[64]) + 27 + signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) + V = utils.safe_ord(signature[64]) + 27 R = big_endian_to_int(signature[0:32]) S = big_endian_to_int(signature[32:64]) @@ -1629,9 +1629,15 @@ def test_string_logging(): o = [] s.block.log_listeners.append(lambda x: o.append(c.translator.listen(x))) c.moo() - assert o == [{"_event_type": "foo", "x": "bob", "__hash_x": utils.sha3("bob"), - "y": "cow", "__hash_y": utils.sha3("cow"), "z": "dog", - "__hash_z": utils.sha3("dog")}] + assert o == [{ + "_event_type": b"foo", + "x": b"bob", + "__hash_x": utils.sha3(b"bob"), + "y": b"cow", + "__hash_y": utils.sha3(b"cow"), + "z": b"dog", + "__hash_z": utils.sha3(b"dog"), + }] params_code = """ @@ -1654,7 +1660,7 @@ def test_params_contract(): s = tester.state() c = s.abi_contract(params_code, FOO=4, BAR='horse') assert c.garble() == 4 - assert c.marble() == 'horse' + assert c.marble() == b'horse' prefix_types_in_functions_code = """ type fixedp: fp_ diff --git a/ethereum/tests/test_difficulty.py b/ethereum/tests/test_difficulty.py index 732e160ae..a0068cb8b 100644 --- a/ethereum/tests/test_difficulty.py +++ b/ethereum/tests/test_difficulty.py @@ -40,8 +40,8 @@ def test_difficulty(filename, testname, testdata): calculated_dif = blocks.calc_difficulty(block, cur_blk_timestamp) - print calculated_dif - print reference_dif + print(calculated_dif) + print(reference_dif) assert calculated_dif == reference_dif diff --git a/ethereum/tests/test_genesis.py b/ethereum/tests/test_genesis.py index 82df102c8..777605737 100644 --- a/ethereum/tests/test_genesis.py +++ b/ethereum/tests/test_genesis.py @@ -3,6 +3,7 @@ import json import ethereum.blocks as blocks import ethereum.testutils as testutils +from ethereum.testutils import fixture_to_bytes import ethereum.utils as utils from rlp.utils import encode_hex from ethereum.tests.utils import new_env @@ -23,7 +24,7 @@ def genesis_fixture(): # FIXME: assert that link is uptodate for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash'): assert k in genesis_fixture - return genesis_fixture + return fixture_to_bytes(genesis_fixture) @pytest.mark.xfail # code not in sync with genesis fixtures diff --git a/ethereum/tests/test_logging.py b/ethereum/tests/test_logging.py index 804f18ec6..e481351e0 100644 --- a/ethereum/tests/test_logging.py +++ b/ethereum/tests/test_logging.py @@ -71,7 +71,7 @@ def test_tracebacks(caplog): def div(a, b): try: - _ = a / b + _ = a // b log.error('heres the stack', stack_info=True) except Exception as e: log.error('an Exception trace should preceed this msg', exc_info=True) diff --git a/ethereum/tests/test_solidity.py b/ethereum/tests/test_solidity.py index bddf4ad8c..fc58c1f2f 100644 --- a/ethereum/tests/test_solidity.py +++ b/ethereum/tests/test_solidity.py @@ -3,6 +3,8 @@ import pytest +from rlp.utils import encode_hex + from ethereum import tester from ethereum import utils from ethereum import _solidity @@ -24,7 +26,7 @@ def test_library_from_file(): ) libraries = { - 'SevenLibrary': library.address.encode('hex'), + 'SevenLibrary': encode_hex(library.address), } contract = state.abi_contract( None, @@ -56,7 +58,7 @@ def test_library_from_code(): ) libraries = { - 'SevenLibrary': library.address.encode('hex'), + 'SevenLibrary': encode_hex(library.address), } contract = state.abi_contract( contract_code, diff --git a/ethereum/tests/test_transactions.py b/ethereum/tests/test_transactions.py index d19ddb55b..6d6a84938 100644 --- a/ethereum/tests/test_transactions.py +++ b/ethereum/tests/test_transactions.py @@ -39,7 +39,7 @@ def test_transaction(filename, testname, testdata): "value": str_to_bytes(str(tx.value)), "to": encode_hex(tx.to), } - except Exception, e: + except Exception as e: tx = None sys.stderr.write(str(e)) if 'transaction' not in testdata: # expected to fail diff --git a/ethereum/tests/test_trie_next_prev.py b/ethereum/tests/test_trie_next_prev.py index f2a5d7276..d50355a7a 100644 --- a/ethereum/tests/test_trie_next_prev.py +++ b/ethereum/tests/test_trie_next_prev.py @@ -3,6 +3,7 @@ import ethereum.trie as trie from ethereum.utils import to_string from ethereum.tests.utils import new_db +from ethereum.testutils import fixture_to_bytes import ethereum.testutils as testutils from ethereum.slogging import get_logger logger = get_logger() @@ -30,7 +31,7 @@ def run_test(name): logger.debug('testing %s' % name) t = trie.Trie(new_db()) - data = load_tests()[name] + data = fixture_to_bytes(load_tests()[name]) for k in data['in']: logger.debug('updating with (%s, %s)' % (k, k)) diff --git a/ethereum/tests/test_vm_failing.py b/ethereum/tests/test_vm_failing.py index ba912aa12..b45098909 100644 --- a/ethereum/tests/test_vm_failing.py +++ b/ethereum/tests/test_vm_failing.py @@ -50,10 +50,17 @@ def mk_test_func(filename, testname, testdata): def test_testutils_check_vm_test(): func_name, filename, testname, testdata = collected[1] testutils.check_vm_test(testutils.fixture_to_bytes(testdata)) - # manipulate post data - storage = testdata['post'].values()[0]['storage'] - assert storage['0x23'] == '0x01' - storage['0x23'] = '0x02' + for address_data in testdata['post'].values(): + storage = address_data['storage'] + if "0x23" not in storage: + continue + assert storage['0x23'] == '0x01' + # manipulate post data + storage['0x23'] = '0x02' + break + else: + raise AssertionError("Did not find `0x23` in storage values") + failed_as_expected = False try: testutils.check_vm_test(testutils.fixture_to_bytes(testdata)) diff --git a/ethereum/testutils.py b/ethereum/testutils.py index 5a8e62a97..9f1164142 100644 --- a/ethereum/testutils.py +++ b/ethereum/testutils.py @@ -67,7 +67,7 @@ def acct_standard_form(a): "nonce": parse_int_or_hex(a["nonce"]), "code": to_string(a["code"]), "storage": {normalize_hex(k): normalize_hex(v) for - k, v in a["storage"].items() if normalize_hex(v).rstrip('0') != '0x'} + k, v in a["storage"].items() if normalize_hex(v).rstrip(b'0') != b'0x'} } @@ -358,10 +358,10 @@ def blkhash(n): time_pre = time.time() try: - print 'trying' + print('trying') success, output = pb.apply_transaction(blk, tx) blk.commit_state() - print 'success', blk.get_receipts()[-1].gas_used + print('success', blk.get_receipts()[-1].gas_used) except InvalidTransaction: success, output = False, b'' blk.commit_state() @@ -508,7 +508,7 @@ def run_genesis_test(params, mode): assert b.mixhash == decode_hex(remove_0x_head(params['mixhash'])) assert b.prevhash == decode_hex(remove_0x_head(params['parentHash'])) assert b.nonce == decode_hex(remove_0x_head(params['nonce'])) - print 9 + print(9) if mode == FILL: params['result'] = encode_hex(rlp.encode(b)) return params diff --git a/ethereum/transactions.py b/ethereum/transactions.py index ca3f1e2c2..fa153787a 100644 --- a/ethereum/transactions.py +++ b/ethereum/transactions.py @@ -87,7 +87,7 @@ def sender(self): pk.public_key = pk.ecdsa_recover( rawhash, pk.ecdsa_recoverable_deserialize( - zpad("".join(chr(c) for c in int_to_32bytearray(self.r)), 32) + zpad("".join(chr(c) for c in int_to_32bytearray(self.s)), 32), + zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.r)), 32) + zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.s)), 32), self.v - 27 ), raw=True @@ -96,7 +96,7 @@ def sender(self): except Exception: raise InvalidTransaction("Invalid signature values (x^3+7 is non-residue)") - if pub[1:] == "\x00" * 32: + if pub[1:] == b"\x00" * 32: raise InvalidTransaction("Invalid signature (zero privkey cannot sign)") pub = encode_pubkey(pub, 'bin') self._sender = utils.sha3(pub[1:])[-20:] @@ -114,7 +114,7 @@ def sign(self, key): A potentially already existing signature would be overridden. """ - if key in (0, '', '\x00' * 32, '0' * 64): + if key in (0, '', b'\x00' * 32, '0' * 64): raise InvalidTransaction("Zero privkey cannot sign") rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction)) @@ -126,8 +126,8 @@ def sign(self, key): signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(rawhash, raw=True) ) - signature = signature[0] + chr(signature[1]) - self.v = ord(signature[64]) + 27 + signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) + self.v = utils.safe_ord(signature[64]) + 27 self.r = big_endian_to_int(signature[0:32]) self.s = big_endian_to_int(signature[32:64]) @@ -195,7 +195,7 @@ def __structlog__(self): # The >= operator is replaced by > because the integer division N/2 always produces the value # which is by 0.5 less than the real N/2 def check_low_s(self): - if self.s > N / 2 or self.s == 0: + if self.s > N // 2 or self.s == 0: raise InvalidTransaction("Invalid signature S value!") diff --git a/ethereum/trie.py b/ethereum/trie.py index 72980c380..879342380 100644 --- a/ethereum/trie.py +++ b/ethereum/trie.py @@ -458,13 +458,13 @@ def _update_kv_node(self, node, key, value): return new_node def _getany(self, node, reverse=False, path=[]): - # print 'getany', node, 'reverse=', reverse, path + # print('getany', node, 'reverse=', reverse, path) node_type = self._get_node_type(node) if node_type == NODE_TYPE_BLANK: return None if node_type == NODE_TYPE_BRANCH: if node[16] and not reverse: - # print 'found!', [16], path + # print('found!', [16], path) return [16] scan_range = list(range(16)) if reverse: @@ -472,15 +472,15 @@ def _getany(self, node, reverse=False, path=[]): for i in scan_range: o = self._getany(self._decode_to_node(node[i]), reverse=reverse, path=path + [i]) if o is not None: - # print 'found@', [i] + o, path + # print('found@', [i] + o, path) return [i] + o if node[16] and reverse: - # print 'found!', [16], path + # print('found!', [16], path) return [16] return None curr_key = without_terminator(unpack_to_nibbles(node[0])) if node_type == NODE_TYPE_LEAF: - # print 'found#', curr_key, path + # print('found#', curr_key, path) return curr_key if node_type == NODE_TYPE_EXTENSION: @@ -580,7 +580,7 @@ def _merge(self, node1, node2): ] if descend_key2[prefix_length:] else sub2 return [pack_nibbles(descend_key1[:prefix_length]), self._encode_node(self._merge(new_sub1, new_sub2))] - + nodes = [[node1], [node2]] for (node, node_type) in zip(nodes, [node_type1, node_type2]): if node_type != NODE_TYPE_BRANCH: @@ -597,25 +597,25 @@ def _merge(self, node1, node2): return new_node @classmethod - def unsafe_merge(cls, trie1, trie2): + def unsafe_merge(cls, trie1, trie2): t = Trie(trie1.db) t.root_node = t._merge(trie1.root_node, trie2.root_node) return t def _iter(self, node, key, reverse=False, path=[]): - # print 'iter', node, key, 'reverse =', reverse, 'path =', path + # print('iter', node, key, 'reverse =', reverse, 'path =', path) node_type = self._get_node_type(node) if node_type == NODE_TYPE_BLANK: return None elif node_type == NODE_TYPE_BRANCH: - # print 'b' + # print('b') if len(key): sub_node = self._decode_to_node(node[key[0]]) o = self._iter(sub_node, key[1:], reverse, path + [key[0]]) if o is not None: - # print 'returning', [key[0]] + o, path + # print('returning', [key[0]] + o, path) return [key[0]] + o if reverse: scan_range = reversed(list(range(key[0] if len(key) else 0))) @@ -623,57 +623,57 @@ def _iter(self, node, key, reverse=False, path=[]): scan_range = list(range(key[0] + 1 if len(key) else 0, 16)) for i in scan_range: sub_node = self._decode_to_node(node[i]) - # print 'prelim getany', path+[i] + # print('prelim getany', path+[i]) o = self._getany(sub_node, reverse, path + [i]) if o is not None: - # print 'returning', [i] + o, path + # print('returning', [i] + o, path) return [i] + o if reverse and key and node[16]: - # print 'o' + # print('o') return [16] return None descend_key = without_terminator(unpack_to_nibbles(node[0])) if node_type == NODE_TYPE_LEAF: if reverse: - # print 'L', descend_key, key, descend_key if descend_key < key else None, path + # print('L', descend_key, key, descend_key if descend_key < key else None, path) return descend_key if descend_key < key else None else: - # print 'L', descend_key, key, descend_key if descend_key > key else None, path + # print('L', descend_key, key, descend_key if descend_key > key else None, path) return descend_key if descend_key > key else None if node_type == NODE_TYPE_EXTENSION: # traverse child nodes sub_node = self._decode_to_node(node[1]) sub_key = key[len(descend_key):] - # print 'amhere', key, descend_key, descend_key > key[:len(descend_key)] + # print('amhere', key, descend_key, descend_key > key[:len(descend_key)]) if starts_with(key, descend_key): o = self._iter(sub_node, sub_key, reverse, path + descend_key) elif descend_key > key[:len(descend_key)] and not reverse: - # print 1 - # print 'prelim getany', path+descend_key + # print(1) + # print('prelim getany', path+descend_key) o = self._getany(sub_node, False, path + descend_key) elif descend_key < key[:len(descend_key)] and reverse: - # print 2 - # print 'prelim getany', path+descend_key + # print(2) + # print('prelim getany', path+descend_key) o = self._getany(sub_node, True, path + descend_key) else: o = None - # print 'returning@', descend_key + o if o else None, path + # print('returning@', descend_key + o if o else None, path) return descend_key + o if o else None def next(self, key): - # print 'nextting' + # print('nextting') key = bin_to_nibbles(key) o = self._iter(self.root_node, key) - # print 'answer', o + # print('answer', o) return nibbles_to_bin(without_terminator(o)) if o else None def prev(self, key): - # print 'prevving' + # print('prevving') key = bin_to_nibbles(key) o = self._iter(self.root_node, key, reverse=True) - # print 'answer', o + # print('answer', o) return nibbles_to_bin(without_terminator(o)) if o else None def _delete_node_storage(self, node): diff --git a/ethereum/utils.py b/ethereum/utils.py index b24f80691..17f7d5eb6 100644 --- a/ethereum/utils.py +++ b/ethereum/utils.py @@ -35,6 +35,9 @@ def to_string_for_regexp(value): return str(value) unicode = unicode + def bytearray_to_bytestr(value): + return bytes(''.join(chr(c) for c in value)) + else: is_numeric = lambda x: isinstance(x, int) is_string = lambda x: isinstance(x, bytes) @@ -56,6 +59,9 @@ def to_string_for_regexp(value): return str(to_string(value), 'utf-8') unicode = str + def bytearray_to_bytestr(value): + return bytes(value) + isnumeric = is_numeric @@ -110,7 +116,8 @@ def int_to_32bytearray(i): def sha3(seed): sha3_count[0] += 1 return sha3_256(to_string(seed)) -assert sha3('').encode('hex') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' + +assert encode_hex(sha3('')) == b'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' def privtoaddr(x, extended=False): @@ -136,8 +143,8 @@ def check_and_strip_checksum(x): def normalize_address(x, allow_blank=False): - if allow_blank and x == '': - return '' + if allow_blank and (x == '' or x == b''): + return b'' if len(x) in (42, 50) and x[:2] == '0x': x = x[2:] if len(x) in (40, 48): @@ -156,7 +163,7 @@ def zpad(x, l): def zunpad(x): i = 0 - while i < len(x) and (x[i] == 0 or x[i] == '\x00'): + while i < len(x) and (x[i] == 0 or x[i] == b'\x00'): i += 1 return x[i:] @@ -247,7 +254,7 @@ def decode_addr(v): def decode_int(v): '''decodes and integer from serialization''' - if len(v) > 0 and (v[0] == '\x00' or v[0] == 0): + if len(v) > 0 and (v[0] == b'\x00' or v[0] == 0): raise Exception("No leading zero bytes allowed for integers") return big_endian_to_int(v) @@ -328,7 +335,7 @@ def scan_int(v): def int_to_hex(x): o = encode_hex(encode_int(x)) - return '0x' + (o[1:] if (len(o) > 0 and o[0] == '0') else o) + return b'0x' + (o[1:] if (len(o) > 0 and o[0] == b'0') else o) def remove_0x_head(s): diff --git a/ethereum/vm.py b/ethereum/vm.py index 428a44c59..e8af89b83 100644 --- a/ethereum/vm.py +++ b/ethereum/vm.py @@ -55,7 +55,7 @@ def extract_copy(self, mem, memstart, datastart, size): class Message(object): - def __init__(self, sender, to, value, gas, data, depth=0, + def __init__(self, sender, to, value, gas, data, depth=0, code_address=None, is_create=False, transfers_value=True): self.sender = sender self.to = to @@ -170,7 +170,7 @@ def vm_execute(ext, msg, code): _prevop = None # for trace only while 1: - # print 'op: ', op, time.time() - s + # print('op: ', op, time.time() - s) # s = time.time() # stack size limit error if compustate.pc >= codelen: diff --git a/setup.py b/setup.py index 275efd8bb..1fea10f9d 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,10 @@ # dev requirements tests_require = set(x.strip() for x in open('dev_requirements.txt')) tests_require_replacements = { - 'https://github.com/ethereum/serpent/tarball/develop': 'ethereum-serpent>=1.8.1'} + # 'https://github.com/ethereum/serpent/tarball/develop': 'ethereum-serpent>=1.8.1', + # THIS SHOULD NOT BE MERGED + 'https://github.com/pipermerriam/serpent/tarball/piper/python3-support-with-pyethereum3': 'ethereum-serpent>=1.8.1', +} tests_require = [tests_require_replacements.get(r, r) for r in tests_require] # *IMPORTANT*: Don't manually change the version here. Use the 'bumpversion' utility. @@ -37,4 +40,13 @@ "https://github.com/ulope/secp256k1-py/archive/master.zip#egg=secp256k1-0.11.1" ], version=version, + classifiers=[ + 'Intended Audience :: Developers', + 'Natural Language :: English', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + ], ) diff --git a/tools/keystorer.py b/tools/keystorer.py index 6b2b72893..70c5d844c 100644 --- a/tools/keystorer.py +++ b/tools/keystorer.py @@ -25,7 +25,7 @@ assert pw == pw2, "Password mismatch" print("Applying hard key derivation function. Wait a little") j = keys.make_keystore_json(key, pw) - print j + print(j) open(j["id"]+'.json', 'w').write(json.dumps(j, indent=4)) print("Wallet creation successful, file saved at: " + j["id"] + ".json") # Decode a json diff --git a/tools/random_vm_test_generator.py b/tools/random_vm_test_generator.py index 1ce2b0ae6..7f33cd3c3 100644 --- a/tools/random_vm_test_generator.py +++ b/tools/random_vm_test_generator.py @@ -99,4 +99,4 @@ def apply_msg_wrapper(_block, _tx, msg, code): if __name__ == "__main__": o = gen_test((sys.argv + [str(random.randrange(10**50))])[2]) - print json.dumps({sys.argv[1]: o}, indent=4) + print(json.dumps({sys.argv[1]: o}, indent=4)) diff --git a/tools/vm_test_generator.py b/tools/vm_test_generator.py index fd2dddd9f..ad0adb806 100644 --- a/tools/vm_test_generator.py +++ b/tools/vm_test_generator.py @@ -67,4 +67,4 @@ def apply_msg_wrapper(_block, _tx, msg, code): if __name__ == "__main__": o = gen_test(sys.argv[2], int(sys.argv[3]), sys.argv[4:]) - print json.dumps({sys.argv[1]: o}, indent=4) + print(json.dumps({sys.argv[1]: o}, indent=4)) diff --git a/tox.ini b/tox.ini index 40b327c88..c653a554e 100644 --- a/tox.ini +++ b/tox.ini @@ -1,19 +1,12 @@ [tox] -envlist = py27,coverage - +envlist = + py27, + py34, + py35 [testenv] -setenv = - PYTHONPATH = {toxinidir}:{toxinidir}/ethereum -commands = coverage run --source=ethereum --branch -m py.test {posargs} -deps = - -r{toxinidir}/requirements.txt - -r{toxinidir}/dev_requirements.txt - - -[testenv:coverage] +commands= + coverage run {env:COVERAGE_APPEND:} --source ethereum -m py.test {posargs} deps = coverage -skip_install = true -commands = - coverage report --show-missing + -r{toxinidir}/dev_requirements.txt