def test_set_solc_version(): compiler.set_solc_version("0.5.7") assert solcx.get_solc_version().truncate() == compiler.solidity.get_version() assert solcx.get_solc_version().truncate() == Version("0.5.7") compiler.set_solc_version("0.4.25") assert solcx.get_solc_version().truncate() == compiler.solidity.get_version() assert solcx.get_solc_version().truncate() == Version("0.4.25")
def compile_contract(path, name): try : get_solc_version() except : install_solc(solc_version) print("install solc : {}".find(solc_version)) compiled_contacts = solcx.compile_files([path]) contract_interface = compiled_contacts['{}:{}'.format(path, name)] return contract_interface
def test_set_solc_version(): compiler.set_solc_version("0.5.7") assert solcx.get_solc_version( with_commit_hash=True) == compiler.solidity.get_version() assert solcx.get_solc_version( with_commit_hash=True).truncate() == Version("0.5.7") compiler.set_solc_version("0.4.25") assert solcx.get_solc_version( with_commit_hash=True) == compiler.solidity.get_version() assert solcx.get_solc_version( with_commit_hash=True).truncate() == Version("0.4.25")
def generate_input_json(contracts, optimize=True, runs=200, evm_version=None, minify=False): '''Formats contracts to the standard solc input json. Args: contracts: a dictionary in the form of {path: 'source code'} optimize: enable solc optimizer runs: optimizer runs evm_version: evm version to compile for minify: should source code be minified? Returns: dict ''' if evm_version is None: evm_version = "petersburg" if solcx.get_solc_version() >= Version( "0.5.5") else "byzantium" input_json = deepcopy(STANDARD_JSON) input_json['settings']['optimizer']['enabled'] = optimize input_json['settings']['optimizer']['runs'] = runs if optimize else False input_json['settings']['evmVersion'] = evm_version input_json['sources'] = dict( (k, { 'content': sources.minify(v)[0] if minify else v }) for k, v in contracts.items()) return input_json
def test_removed_kwargs(popen, foo_source, kwarg, min_solc): popen.expect(kwarg) if solcx.get_solc_version() >= Version(min_solc): with pytest.raises(UnknownOption): solcx.wrapper.solc_wrapper(stdin=foo_source, **{kwarg: True}) else: solcx.wrapper.solc_wrapper(stdin=foo_source, **{kwarg: True})
def generate_input_json( contracts: Dict[str, str], optimize: bool = True, runs: int = 200, evm_version: Union[int, str, None] = None, minify: bool = False, ) -> Dict: """Formats contracts to the standard solc input json. Args: contracts: a dictionary in the form of {path: 'source code'} optimize: enable solc optimizer runs: optimizer runs evm_version: evm version to compile for minify: should source code be minified? Returns: dict """ if evm_version is None: evm_version = "petersburg" if solcx.get_solc_version() >= Version( "0.5.5") else "byzantium" input_json: Dict = deepcopy(STANDARD_JSON) input_json["settings"]["optimizer"]["enabled"] = optimize input_json["settings"]["optimizer"]["runs"] = runs if optimize else 0 input_json["settings"]["evmVersion"] = evm_version input_json["sources"] = dict( (k, { "content": sources.minify(v)[0] if minify else v }) for k, v in contracts.items()) return input_json
def compile(solc_version, evm_version, source_code_file): out = None with open(source_code_file, 'r') as file: source_code = file.read() try: if solc_version != solcx.get_solc_version(): solcx.set_solc_version(solc_version, True) out = solcx.compile_standard({ 'language': 'Solidity', 'sources': {source_code_file: {'content': source_code}}, 'settings': { "optimizer": { "enabled": True, "runs": 200 }, "evmVersion": evm_version, "outputSelection": { source_code_file: { "*": [ "abi", "evm.deployedBytecode", "evm.bytecode.object", "evm.legacyAssembly", ], } } } }, allow_paths='.') except Exception as e: print("Error: Solidity compilation failed!") print(e.message) return out
def __init__(self, config): if self.__validate(config): # Ethereum account address to interact with ethereum network self.__eth_account_address = config['ethereum']['eth_account'] provider = config["ethereum"]["provider"] # Ethereum provider is endpoint to submit the transaction self.__w3 = web3.Web3( PROVIDER_DICT[urlparse(provider).scheme](provider)) self._is_ropsten_provider = self._is_ropsten(provider) # Private key to sign the transaction if self._is_ropsten_provider: self.__eth_private_key = config['ethereum']['acc_pvt_key'] # Chain id signifies the which ethereum network to use: # test net/main ethereum network self._chain_id = config["ethereum"]["chain_id"] # Maximum amount of gas you’re willing to spend on # a particular transaction self.__gas_limit = config["ethereum"]["gas_limit"] # Amount of Ether you’re willing to pay for every unit of gas self.__gas_price = config["ethereum"]["gas_price"] set_solc_version(config['ethereum']['solc_version']) logging.info("Solidity compiler version being used : {}".format( get_solc_version())) else: raise Exception("Invalid configuration parameter")
def _compile_assertions(output, key): assert output assert key in output for value in ALL_OUTPUT_VALUES: if value == "clone-bin" and solcx.get_solc_version().minor >= 5: assert value not in output[key] else: assert value in output[key]
def test_removed_kwargs(popen, foo_source, kwarg, min_solc_minor): solc_minor_version = solcx.get_solc_version().minor popen.expect(kwarg) if solc_minor_version >= min_solc_minor: with pytest.raises(AttributeError): solcx.wrapper.solc_wrapper(stdin=foo_source, **{kwarg: True}) else: solcx.wrapper.solc_wrapper(stdin=foo_source, **{kwarg: True})
def test_removed_kwargs(popen, foo_source): solc_minor_version = solcx.get_solc_version().minor kwargs = [("ast", 6), ("clone_bin", 5), ("formal", 5)] for value, minor in kwargs: popen.expect(value) if solc_minor_version >= minor: with pytest.raises(AttributeError): solcx.wrapper.solc_wrapper(stdin=foo_source, **{value: True}) else: solcx.wrapper.solc_wrapper(stdin=foo_source, **{value: True})
def set_solc_version(version: str) -> str: """Sets the solc version. If not available it will be installed.""" if Version(version.lstrip("v")) < Version("0.4.22"): raise IncompatibleSolcVersion("Brownie only supports Solidity versions >=0.4.22") try: solcx.set_solc_version(version, silent=True) except solcx.exceptions.SolcNotInstalled: install_solc(version) solcx.set_solc_version(version, silent=True) return str(solcx.get_solc_version())
def printVersions(): import sys from web3 import __version__ as web3version from solcx import get_solc_version from testrpc import __version__ as ethtestrpcversion import pkg_resources pysolcversion = pkg_resources.get_distribution("py-solc-x").version print("versions: web3 %s, py-solc-x: %s, solc %s, testrpc %s, python %s" % (web3version, pysolcversion, get_solc_version(), ethtestrpcversion, sys.version.replace("\n", "")))
def compile_source_file(file_path): """Read and compile the source file with the solc Solidity compiler. If the compiler is not available, it will be installed. """ # Check if solc compiler is available otherwise install try: print(solcx.get_solc_version()) except solcx.exceptions.SolcNotInstalled as e: print(e) version = solcx.install_solc('0.7.4') print(f'Installed version: {version}') with open(file_path, 'r') as f: source = f.read() return solcx.compile_source(source)
def set_solc_version(version: Union[str, Version]) -> str: """Sets the solc version. If not available it will be installed.""" if not isinstance(version, Version): version = Version(version.lstrip("v")) if version < Version("0.4.22"): raise IncompatibleSolcVersion("Brownie only supports Solidity versions >=0.4.22") try: solcx.set_solc_version(version, silent=True) except solcx.exceptions.SolcNotInstalled: if version not in _get_solc_version_list()[0]: raise IncompatibleSolcVersion( f"Cannot install Solidity v{version} on this OS. You may be able to " f"manually compile from source with `solcx.compile_solc('{version}')`" ) install_solc(version) solcx.set_solc_version(version, silent=True) return str(solcx.get_solc_version())
def get_version() -> Version: return solcx.get_solc_version(with_commit_hash=True)
def test_compile_source_output_types(foo_source, key): if key == "hashes" and str( solcx.get_solc_version().truncate()) == "0.4.11": return output = solcx.compile_source(foo_source, output_values=[key]) assert key in output["<stdin>:Foo"]
def get_version() -> Version: return solcx.get_solc_version().truncate()
def test_compile_files_output_types(foo_path, key): if key == "hashes" and str( solcx.get_solc_version().truncate()) == "0.4.11": return output = solcx.compile_files([foo_path], output_values=[key]) assert key in output[f"{foo_path}:Foo"]
def get_version() -> Version: return solcx.get_solc_version()
def test_get_solc_version(): version = solcx.get_solc_version() version_with_hash = solcx.get_solc_version(with_commit_hash=True) assert version != version_with_hash assert version == version_with_hash.truncate()
def test_get_solc_version(all_versions): v = solcx.get_solc_version() assert isinstance(v, Version)
import solcx versions = solcx.get_installable_solc_versions() print(versions) # solcx.install_solc("0.8.9") installed = solcx.get_solc_version() print(installed)
def test_added_kwargs(popen, foo_source, kwarg, min_version): if solcx.get_solc_version().truncate() >= Version(min_version): solcx.wrapper.solc_wrapper(stdin=foo_source, **kwarg) else: with pytest.raises(AttributeError): solcx.wrapper.solc_wrapper(stdin=foo_source, **kwarg)
def launch_argument_parser(): parser = argparse.ArgumentParser() # Contract parameters group1 = parser.add_mutually_exclusive_group(required=True) group1.add_argument( "-s", "--source", type=str, help="Solidity smart contract source code file (.sol).") group1.add_argument("-a", "--abi", type=str, help="Smart contract ABI file (.json).") #group2 = parser.add_mutually_exclusive_group(required=True) parser.add_argument( "-c", "--contract", type=str, help= "Contract name to be fuzzed (if Solidity source code file provided) or blockchain contract address (if ABI file provided)." ) parser.add_argument( "-b", "--blockchain-state", type=str, help= "Initialize fuzzer with a blockchain state by providing a JSON file (if Solidity source code file provided) or a block number (if ABI file provided)." ) # Compiler parameters parser.add_argument("--solc", help="Solidity compiler version (default '" + str(solcx.get_solc_version()) + "'). Installed compiler versions: " + str(solcx.get_installed_solc_versions()) + ".", action="store", dest="solc_version", type=str) parser.add_argument( "--evm", help="Ethereum VM (default '" + str(settings.EVM_VERSION) + "'). Available VM's: 'homestead', 'byzantium' or 'petersburg'.", action="store", dest="evm_version", type=str) # Evolutionary parameters group3 = parser.add_mutually_exclusive_group(required=False) group3.add_argument("-g", "--generations", help="Number of generations (default " + str(settings.GENERATIONS) + ").", action="store", dest="generations", type=int) group3.add_argument("-t", "--timeout", help="Number of seconds for fuzzer to stop.", action="store", dest="global_timeout", type=int) parser.add_argument("-n", "--population-size", help="Size of the population.", action="store", dest="population_size", type=int) parser.add_argument("-pc", "--probability-crossover", help="Size of the population.", action="store", dest="probability_crossover", type=float) parser.add_argument("-pm", "--probability-mutation", help="Size of the population.", action="store", dest="probability_mutation", type=float) # Miscellaneous parameters parser.add_argument( "-r", "--results", type=str, help="Folder or JSON file where results should be stored.") parser.add_argument( "--seed", type=float, help="Initialize the random number generator with a given seed.") parser.add_argument( "--cfg", help="Build control-flow graph and highlight code coverage.", action="store_true") parser.add_argument("--rpc-host", help="Ethereum client RPC hostname.", action="store", dest="rpc_host", type=str) parser.add_argument("--rpc-port", help="Ethereum client RPC port.", action="store", dest="rpc_port", type=int) parser.add_argument( "--data-dependency", help= "Disable/Enable data dependency analysis: 0 - Disable, 1 - Enable (default: 1)", action="store", dest="data_dependency", type=int) parser.add_argument( "--constraint-solving", help= "Disable/Enable constraint solving: 0 - Disable, 1 - Enable (default: 1)", action="store", dest="constraint_solving", type=int) parser.add_argument( "--environmental-instrumentation", help= "Disable/Enable environmental instrumentation: 0 - Disable, 1 - Enable (default: 1)", action="store", dest="environmental_instrumentation", type=int) version = "ConFuzzius - Version 0.0.1 - " version += "\"By three methods we may learn wisdom:\n" version += "First, by reflection, which is noblest;\n" version += "Second, by imitation, which is easiest;\n" version += "And third by experience, which is the bitterest.\"\n" parser.add_argument("-v", "--version", action="version", version=version) args = parser.parse_args() if not args.contract: args.contract = "" if args.source and args.contract.startswith("0x"): parser.error( "--source requires --contract to be a name, not an address.") if args.source and args.blockchain_state and args.blockchain_state.isnumeric( ): parser.error( "--source requires --blockchain-state to be a file, not a number.") if args.abi and not args.contract.startswith("0x"): parser.error("--abi requires --contract to be an address, not a name.") if args.abi and args.blockchain_state and not args.blockchain_state.isnumeric( ): parser.error( "--abi requires --blockchain-state to be a number, not a file.") if args.evm_version: settings.EVM_VERSION = args.evm_version if not args.solc_version: args.solc_version = solcx.get_solc_version() if args.generations: settings.GENERATIONS = args.generations if args.global_timeout: settings.GLOBAL_TIMEOUT = args.global_timeout if args.population_size: settings.POPULATION_SIZE = args.population_size if args.probability_crossover: settings.PROBABILITY_CROSSOVER = args.probability_crossover if args.probability_mutation: settings.PROBABILITY_MUTATION = args.probability_mutation if args.data_dependency == None: args.data_dependency = 1 if args.constraint_solving == None: args.constraint_solving = 1 if args.environmental_instrumentation == None: args.environmental_instrumentation = 1 if args.environmental_instrumentation == 1: settings.ENVIRONMENTAL_INSTRUMENTATION = True elif args.environmental_instrumentation == 0: settings.ENVIRONMENTAL_INSTRUMENTATION = False if args.abi: settings.REMOTE_FUZZING = True if args.rpc_host: settings.RPC_HOST = args.rpc_host if args.rpc_port: settings.RPC_PORT = args.rpc_port return args