def load_or_create_smoketest_config(): # get the contract and compiler (if available) versions versions = dict() for file in os.listdir(get_contract_path('')): if file.endswith('.sol'): versions[file] = contract_checksum(get_contract_path(file)) # if solc is available, record its version, too if get_solidity() is not None: solc_version_out, _ = subprocess.Popen( [get_solidity().compiler_available(), '--version'], stdout=subprocess.PIPE).communicate() versions['solc'] = solc_version_out.split()[-1] smoketest_config_path = os.path.join(get_project_root(), 'smoketest_config.json') # try to load an existing smoketest genesis config smoketest_config = dict() if os.path.exists(smoketest_config_path): with open(smoketest_config_path) as handler: smoketest_config = json.load(handler) # if the file versions still fit, return the genesis config (ignore solc if not available) if all(versions[key] == smoketest_config['versions'][key] for key in versions.keys()): return smoketest_config # something did not fit -- we will create the genesis smoketest_config['versions'] = versions raiden_config, smoketest_genesis = complete_genesis() smoketest_config['genesis'] = smoketest_genesis smoketest_config.update(raiden_config) with open(os.path.join(get_project_root(), 'smoketest_config.json'), 'w') as handler: json.dump(smoketest_config, handler) return smoketest_config
def test_extra_args(): src = """ contract foo { function add7(uint a) returns(uint d) { return a + 7; } function add42(uint a) returns(uint d) { return a + 42; } } """ contract_info = get_solidity().compile_rich( src, extra_args="--optimize-runs 100") assert bytecode_is_generated(contract_info, 'foo') contract_info = get_solidity().compile_rich( src, extra_args=["--optimize-runs", "100"]) assert bytecode_is_generated(contract_info, 'foo')
def test_solidity_compile_rich(): contract_info = get_solidity().compile_rich(compile_rich_contract) assert len(contract_info) == 2 assert set(contract_info.keys()) == {'contract_add', 'contract_sub'} assert set(contract_info['contract_add'].keys()) == {'info', 'code'} assert set(contract_info['contract_add']['info'].keys()) == { 'language', 'languageVersion', 'abiDefinition', 'source', 'compilerVersion', 'developerDoc', 'userDoc' } assert contract_info['contract_add']['code'] == ( "0x606060405260ad8060116000396000f30060606040526000357c0100000000000000" "00000000000000000000000000000000000000000090048063651ae239146041578063" "cb02919f14606657603f565b005b6050600480359060200150608b565b604051808281" "5260200191505060405180910390f35b6075600480359060200150609c565b60405180" "82815260200191505060405180910390f35b60006007820190506097565b919050565b" "6000602a8201905060a8565b91905056") assert contract_info['contract_sub']['code'] == ( "0x606060405260ad8060116000396000f30060606040526000357c0100000000000000" "0000000000000000000000000000000000000000009004806361752024146041578063" "7aaef1a014606657603f565b005b6050600480359060200150608b565b604051808281" "5260200191505060405180910390f35b6075600480359060200150609c565b60405180" "82815260200191505060405180910390f35b60006007820390506097565b919050565b" "6000602a8203905060a8565b91905056") assert { defn['name'] for defn in contract_info['contract_add']['info']['abiDefinition'] } == {'add7', 'add42'} assert { defn['name'] for defn in contract_info['contract_sub']['info']['abiDefinition'] } == {'subtract7', 'subtract42'}
def test_solidity_compile_rich(): compile_rich_contract = """ contract contract_add { function add7(uint a) returns(uint d) { return a + 7; } function add42(uint a) returns(uint d) { return a + 42; } } contract contract_sub { function subtract7(uint a) returns(uint d) { return a - 7; } function subtract42(uint a) returns(uint d) { return a - 42; } } """ contract_info = get_solidity().compile_rich(compile_rich_contract) assert len(contract_info) == 2 assert set(contract_info.keys()) == {'contract_add', 'contract_sub'} assert set(contract_info['contract_add'].keys()) == {'info', 'code'} assert set(contract_info['contract_add']['info'].keys()) == { 'language', 'languageVersion', 'abiDefinition', 'source', 'compilerVersion', 'developerDoc', 'userDoc' } assert bytecode_is_generated(contract_info, 'contract_add') assert bytecode_is_generated(contract_info, 'contract_sub') assert { defn['name'] for defn in contract_info['contract_add']['info']['abiDefinition'] } == {'add7', 'add42'} assert { defn['name'] for defn in contract_info['contract_sub']['info']['abiDefinition'] } == {'subtract7', 'subtract42'}
def get_static_or_compile( contract_path, contract_name, **compiler_flags): """Search the path of `contract_path` for a file with the same name and the extension `.static-abi.json`. If the file exists, and the recorded checksum matches, this will return the precompiled contract, otherwise it will compile it. Writing compiled contracts to the desired file and path happens only when the environment variable `STORE_PRECOMPILED` is set (to whatever value). Users are not expected to ever set this value, the functionality is exposed through the `setup.py compile_contracts` command. Args: contract_path (str): the path of the contract file contract_name (str): the contract name **compiler_flags (dict): flags that will be passed to the compiler """ # this will be set by `setup.py compile_contracts` store_updated = os.environ.get('STORE_PRECOMPILED', False) precompiled = None precompiled_path = '{}.static-abi.json'.format(contract_path) try: with open(precompiled_path) as f: precompiled = json.load(f) except IOError: pass if precompiled or store_updated: checksum = contract_checksum(contract_path) if precompiled and precompiled['checksum'] == checksum: return precompiled if _solidity.get_solidity() is None: raise RuntimeError('The solidity compiler, `solc`, is not available.') compiled = _solidity.compile_contract( contract_path, contract_name, **compiler_flags ) if store_updated: compiled['checksum'] = checksum with open(precompiled_path, 'w') as f: json.dump(compiled, f) print("'{}' written".format(precompiled_path)) return compiled
def get_compiler_for_file(file_path): _, _, ext = file_path.rpartition('.') if ext == 'sol': compiler = get_solidity() if compiler is None: raise ValueError("No solidity compiler") return compiler elif ext == 'lll': raise ValueError("Compilation of LLL contracts is not yet supported") elif ext == 'mu': raise ValueError("Compilation of LLL contracts is not yet supported") elif ext == 'se': raise ValueError("Compilation of LLL contracts is not yet supported") raise ValueError("Unknown contract extension {0}".format(ext))
def test_solidity_compile_rich(): compile_rich_contract = """ contract contract_add { function add7(uint a) returns(uint d) { return a + 7; } function add42(uint a) returns(uint d) { return a + 42; } } contract contract_sub { function subtract7(uint a) returns(uint d) { return a - 7; } function subtract42(uint a) returns(uint d) { return a - 42; } } """ contract_info = get_solidity().compile_rich(compile_rich_contract) assert len(contract_info) == 2 assert set(contract_info.keys()) == {'contract_add', 'contract_sub'} assert set(contract_info['contract_add'].keys()) == {'info', 'code'} assert set(contract_info['contract_add']['info'].keys()) == { 'language', 'languageVersion', 'abiDefinition', 'source', 'compilerVersion', 'developerDoc', 'userDoc' } assert contract_info['contract_add']['code'] == ( '0x606060405260ad8060116000396000f30060606040526000357c0100000000000000' '00000000000000000000000000000000000000000090048063651ae239146041578063' 'cb02919f14606657603f565b005b6050600480359060200150608b565b604051808281' '5260200191505060405180910390f35b6075600480359060200150609c565b60405180' '82815260200191505060405180910390f35b60006007820190506097565b919050565b' '6000602a8201905060a8565b91905056' ) assert contract_info['contract_sub']['code'] == ( '0x606060405260ad8060116000396000f30060606040526000357c0100000000000000' '0000000000000000000000000000000000000000009004806361752024146041578063' '7aaef1a014606657603f565b005b6050600480359060200150608b565b604051808281' '5260200191505060405180910390f35b6075600480359060200150609c565b60405180' '82815260200191505060405180910390f35b60006007820390506097565b919050565b' '6000602a8203905060a8565b91905056' ) assert { defn['name'] for defn in contract_info['contract_add']['info']['abiDefinition'] } == {'add7', 'add42'} assert { defn['name'] for defn in contract_info['contract_sub']['info']['abiDefinition'] } == {'subtract7', 'subtract42'}
def test_solidity_compile_rich(): compile_rich_contract = """ contract contract_add { function add7(uint a) returns(uint d) { return a + 7; } function add42(uint a) returns(uint d) { return a + 42; } } contract contract_sub { function subtract7(uint a) returns(uint d) { return a - 7; } function subtract42(uint a) returns(uint d) { return a - 42; } } """ contract_info = get_solidity().compile_rich(compile_rich_contract) assert len(contract_info) == 2 assert set(contract_info.keys()) == {'contract_add', 'contract_sub'} assert set(contract_info['contract_add'].keys()) == {'info', 'code'} assert set(contract_info['contract_add']['info'].keys()) == { 'language', 'languageVersion', 'abiDefinition', 'source', 'compilerVersion', 'developerDoc', 'userDoc' } assert contract_info['contract_add']['code'] == ( '0x606060405260ad8060116000396000f30060606040526000357c0100000000000000' '00000000000000000000000000000000000000000090048063651ae239146041578063' 'cb02919f14606657603f565b005b6050600480359060200150608b565b604051808281' '5260200191505060405180910390f35b6075600480359060200150609c565b60405180' '82815260200191505060405180910390f35b60006007820190506097565b919050565b' '6000602a8201905060a8565b91905056') assert contract_info['contract_sub']['code'] == ( '0x606060405260ad8060116000396000f30060606040526000357c0100000000000000' '0000000000000000000000000000000000000000009004806361752024146041578063' '7aaef1a014606657603f565b005b6050600480359060200150608b565b604051808281' '5260200191505060405180910390f35b6075600480359060200150609c565b60405180' '82815260200191505060405180910390f35b60006007820390506097565b919050565b' '6000602a8203905060a8565b91905056') assert { defn['name'] for defn in contract_info['contract_add']['info']['abiDefinition'] } == {'add7', 'add42'} assert { defn['name'] for defn in contract_info['contract_sub']['info']['abiDefinition'] } == {'subtract7', 'subtract42'}
def test_solidity_compile_rich(): contract_info = get_solidity().compile_rich(compile_rich_contract) assert len(contract_info) == 2 assert set(contract_info.keys()) == {"contract_add", "contract_sub"} assert set(contract_info["contract_add"].keys()) == {"info", "code"} assert set(contract_info["contract_add"]["info"].keys()) == { "language", "languageVersion", "abiDefinition", "source", "compilerVersion", "developerDoc", "userDoc", } assert contract_info["contract_add"]["code"] == ( "0x606060405260ad8060116000396000f30060606040526000357c0100000000000000" "00000000000000000000000000000000000000000090048063651ae239146041578063" "cb02919f14606657603f565b005b6050600480359060200150608b565b604051808281" "5260200191505060405180910390f35b6075600480359060200150609c565b60405180" "82815260200191505060405180910390f35b60006007820190506097565b919050565b" "6000602a8201905060a8565b91905056" ) assert contract_info["contract_sub"]["code"] == ( "0x606060405260ad8060116000396000f30060606040526000357c0100000000000000" "0000000000000000000000000000000000000000009004806361752024146041578063" "7aaef1a014606657603f565b005b6050600480359060200150608b565b604051808281" "5260200191505060405180910390f35b6075600480359060200150609c565b60405180" "82815260200191505060405180910390f35b60006007820390506097565b919050565b" "6000602a8203905060a8565b91905056" ) assert { defn["name"] for defn in contract_info["contract_add"]["info"]["abiDefinition"] } == {"add7", "add42"} assert { defn["name"] for defn in contract_info["contract_sub"]["info"]["abiDefinition"] } == {"subtract7", "subtract42"}
def validate_solc(): if _solidity.get_solidity() is None: raise RuntimeError( "Couldn't find the solc in the current $PATH.\n" "Make sure the solidity compiler is installed and available on your $PATH." ) try: _solidity.compile_contract( get_contract_path('HumanStandardToken.sol'), 'HumanStandardToken', combined='abi', optimize=False, ) except subprocess.CalledProcessError as e: msg = ( 'The solidity compiler failed to execute. Please make sure that you\n' 'are using the binary version of the compiler (solc-js is not compatible)\n' ) if e.output: msg += ('\n' 'Output: ' + e.output) raise RuntimeError(msg) except OSError as e: msg = ( 'The solidity compiler failed to execute. Please make sure the\n' 'binary is compatible with your architecture and you can execute it.' ) child_traceback = getattr(e, 'child_traceback', None) if child_traceback: msg += ('\n' 'Traceback: ' + child_traceback) raise RuntimeError(msg)
pb = ethereum.processblock vm = ethereum.vm accounts = [] keys = [] for i in range(10): keys.append(u.sha3(to_string(i))) accounts.append(u.privtoaddr(keys[-1])) k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 = keys[:10] a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = accounts[:10] languages = {} _solidity = get_solidity() if _solidity: languages['solidity'] = _solidity seed = 3**160 def dict_without(d, *args): o = {} for k, v in list(d.items()): if k not in args: o[k] = v return o def dict_with(d, **kwargs):
# -*- coding: utf8 -*- from os import path import pytest from rlp.utils import encode_hex from ethereum import tester from ethereum import utils from ethereum import _solidity from ethereum._solidity import get_solidity SOLIDITY_AVAILABLE = get_solidity() is not None CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts') @pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available') def test_library_from_file(): state = tester.state() state.env.config['HOMESTEAD_FORK_BLKNUM'] = 0 # enable CALLCODE opcode library = state.abi_contract( None, path=path.join(CONTRACTS_DIR, 'seven_library.sol'), language='solidity', ) libraries = { 'SevenLibrary': encode_hex(library.address), } contract = state.abi_contract(
import sys from ethereum import transactions as t from ethereum.abi import ContractTranslator from ethereum._solidity import get_solidity import rlp solidity = get_solidity() print 'opa', solidity.mk_full_signature(open('one_phase_auction.sol').read() + open('two_phase_auction.sol').read() + open('adStorer.sol').read(), contract_name='OnePhaseAuction') print 'tpa', solidity.mk_full_signature(open('one_phase_auction.sol').read() + open('two_phase_auction.sol').read() + open('adStorer.sol').read(), contract_name='TwoPhaseAuction') print 'ads', solidity.mk_full_signature(open('one_phase_auction.sol').read() + open('two_phase_auction.sol').read() + open('adStorer.sol').read(), contract_name='adStorer')
import pytest from ethereum import tester from ethereum import utils from ethereum._solidity import get_solidity solidity_currency = open('currency.sol').read() serpent_currency = open('currency.se').read() @pytest.mark.skipif(get_solidity() is None, reason="'solc' compiler not available") def test_currency_apis(): s = tester.state() c1 = s.abi_contract(serpent_currency, sender=tester.k0) c2 = s.abi_contract(solidity_currency, language='solidity', sender=tester.k0) o = [] s.block.log_listeners.append(lambda x: o.append(c._translator.listen(x))) for c in (c1, c2): o = [] assert c.coinBalanceOf(tester.a0) == 1000000 assert c.sendCoin(1000, tester.a2, sender=tester.k0) is True assert c.sendCoin(999001, tester.a2, sender=tester.k0) is False assert c.sendCoinFrom(tester.a2, 500, tester.a3, sender=tester.k0) is False c.approveOnce(tester.a0, 500, sender=tester.k2) assert c.sendCoinFrom(tester.a2, 400, tester.a3, sender=tester.k0) is True assert c.sendCoinFrom(tester.a2, 400, tester.a3, sender=tester.k0) is False
# -*- coding: utf-8 -*- from __future__ import division import pytest from ethereum import _solidity from ethereum._solidity import compile_file from ethereum.utils import denoms from pyethapp.rpc_client import JSONRPCClient from raiden.network.rpc.client import decode_topic, patch_send_transaction from raiden.utils import privatekey_to_address, get_contract_path solidity = _solidity.get_solidity() # pylint: disable=invalid-name @pytest.mark.timeout(120) @pytest.mark.parametrize('privatekey_seed', ['blockchain:{}']) @pytest.mark.parametrize('number_of_nodes', [3]) @pytest.mark.parametrize('channels_per_node', [0]) @pytest.mark.parametrize('number_of_assets', [0]) def test_new_netting_contract(raiden_network, asset_amount, settle_timeout): # pylint: disable=line-too-long,too-many-statements,too-many-locals app0, app1, app2 = raiden_network peer0_address = app0.raiden.address peer1_address = app1.raiden.address peer2_address = app2.raiden.address blockchain_service0 = app0.raiden.chain asset_address = blockchain_service0.deploy_and_register_asset(
contract serpent { function sub1() returns (int256 y) {} } contract zoo { function main(address a) returns (int256 y) { y = serpent(a).sub1() * 2; } function sub2() returns (int256 y) { y = 7; } function sub3(address a) returns (address b) { b = a; } } """ @pytest.mark.skipif(get_solidity() is None, reason="'solc' compiler not available") def test_interop(): if "solidity" not in tester.languages: return s = tester.state() c1 = s.abi_contract(serpent_contract) # should be zoo c2 = s.abi_contract(solidity_contract, language="solidity") assert c1.sub1() == 5 assert c2.sub2() == 7 assert c2.sub3(utils.encode_hex(c2.address)) == utils.encode_hex(c2.address) assert c1.main(c2.address) == 14 assert c2.main(c1.address) == 10 compile_rich_contract = """
import pytest from populus.utils import get_compiler_for_file from ethereum._solidity import get_solidity @pytest.mark.parametrize('filename', ['unknown.txt', 'unknown.bak', 'swap.sol.swp']) def test_unknown_contract_extensions(filename): with pytest.raises(ValueError): get_compiler_for_file(filename) @pytest.mark.skipif(get_solidity() is None, reason="'solc' compiler not available") def test_solidity_compiler(): compiler = get_compiler_for_file('Example.sol') assert compiler == get_solidity() @pytest.mark.skipif(get_solidity() is not None, reason="'solc' compiler available") def test_solidity_compiler_not_available(): with pytest.raises(ValueError): get_compiler_for_file('Example.sol')
# application. import sys import json import serpent import os solidity = None accounts = {} # Fill in contract ABI declarations for f in os.listdir(os.getcwd()): if f[-3:] == ".se": accounts[f[:-3]] = {"abi": serpent.mk_full_signature(f)} elif f[-4:] == ".sol": if not solidity: from ethereum import _solidity solidity = _solidity.get_solidity() accounts[f[:-4]] = {"abi": solidity.mk_full_signature(open(f).read())} # Fill in previously known addresses if 'config.js' in os.listdir(os.getcwd()): data = open('config.js').read() code = json.loads(data[data.find('{'):]) # For contracts (ie. objects that contain an 'abi' parameter), if # we detect a .se or .sol file removed then we do not add the # associated address from the registry. For regular accounts, we # transfer all of them over for k, v in code.items(): if 'address' in v and (k in accounts or 'abi' not in v): if k not in accounts: accounts[k] = {} accounts[k]["address"] = v['address'] # Fill in addresses from sys.argv
from ethereum import tester from ethereum import utils from ethereum._solidity import get_solidity SOLIDITY_AVAILABLE = get_solidity() is not None from Crypto.Hash import SHA256 import bitcoin # Logging from ethereum import slogging slogging.configure(':INFO,eth.vm:INFO') #slogging.configure(':DEBUG') #slogging.configure(':DEBUG,eth.vm:TRACE') xor = lambda (x,y): chr(ord(x) ^ ord(y)) xors = lambda x,y: ''.join(map(xor,zip(x,y))) zfill = lambda s: (32-len(s))*'\x00' + s flatten = lambda x: [z for y in x for z in y] def int_to_bytes(x): # pyethereum int to bytes does not handle negative numbers assert -(1<<255) <= x < (1<<255) return utils.int_to_bytes((1<<256) + x if x < 0 else x) def broadcast(p, r, h, sig): print 'player[%d]'%p.i, 'broadcasts', r, h.encode('hex'), sig def sign(h, priv): assert len(h) == 32 V, R, S = bitcoin.ecdsa_raw_sign(h, priv) return V,R,S
def test_solidity_compiler(): compiler = get_compiler_for_file('Example.sol') assert compiler == get_solidity()
# application. import sys import json import serpent import os solidity = None accounts = {} # Fill in contract ABI declarations for f in os.listdir(os.getcwd()): if f[-3:] == ".se": accounts[f[:-3]] = {"abi": serpent.mk_full_signature(f)} solidity_files = [f for f in os.listdir(os.getcwd()) if f[-4:] == ".sol"] if len(solidity_files): from ethereum import _solidity solidity = _solidity.get_solidity() code = '\n'.join([open(f).read() for f in solidity_files]) contracts = solidity.contract_names(code) for c in contracts: accounts[c] = { "abi": solidity.mk_full_signature(code, contract_name=c) } # Fill in previously known addresses if 'config.js' in os.listdir(os.getcwd()): data = open('config.js').read() code = json.loads(data[data.find('{'):]) # For contracts (ie. objects that contain an 'abi' parameter), if # we detect a .se or .sol file removed then we do not add the # associated address from the registry. For regular accounts, we # transfer all of them over for k, v in code.items():
# -*- coding: utf8 -*- from __future__ import division import pytest from ethereum import _solidity from ethereum._solidity import compile_file from ethereum.utils import denoms from pyethapp.rpc_client import JSONRPCClient from raiden.blockchain.abi import get_contract_path from raiden.network.rpc.client import decode_topic, patch_send_transaction from raiden.utils import privatekey_to_address solidity = _solidity.get_solidity() # pylint: disable=invalid-name @pytest.mark.parametrize('privatekey_seed', ['blockchain:{}']) @pytest.mark.parametrize('number_of_nodes', [3]) @pytest.mark.parametrize('channels_per_node', [0]) @pytest.mark.parametrize('number_of_assets', [0]) def test_new_netting_contract(raiden_network, asset_amount, settle_timeout): # pylint: disable=line-too-long,too-many-statements,too-many-locals app0, app1, app2 = raiden_network peer0_address = app0.raiden.address peer1_address = app1.raiden.address peer2_address = app2.raiden.address blockchain_service0 = app0.raiden.chain asset_address = blockchain_service0.deploy_and_register_asset(