Ejemplo n.º 1
0
    def launch(self, cmd: str, **kwargs: Dict) -> None:
        """Launches the RPC client.

        Args:
            cmd: command string to execute as subprocess"""
        if self.is_active():
            raise SystemError("RPC is already active.")
        if sys.platform == "win32" and not cmd.split(" ")[0].endswith(".cmd"):
            if " " in cmd:
                cmd = cmd.replace(" ", ".cmd ", 1)
            else:
                cmd += ".cmd"
        cmd_list = cmd.split(" ")
        kwargs.setdefault("evm_version", EVM_DEFAULT)  # type: ignore
        if kwargs["evm_version"] in EVM_EQUIVALENTS:
            kwargs["evm_version"] = EVM_EQUIVALENTS[
                kwargs["evm_version"]]  # type: ignore
        kwargs = _validate_cmd_settings(kwargs)
        for key, value in [(k, v) for k, v in kwargs.items() if v]:
            if key == "unlock":
                if not isinstance(value, list):
                    value = [value]  # type: ignore
                for address in value:
                    if isinstance(address, int):
                        address = HexBytes(address.to_bytes(20, "big")).hex()
                    cmd_list.extend([CLI_FLAGS[key], address])
            else:
                try:
                    cmd_list.extend([CLI_FLAGS[key], str(value)])
                except KeyError:
                    warnings.warn(
                        f"Ignoring invalid commandline setting for ganache-cli: "
                        f'"{key}" with value "{value}".',
                        InvalidArgumentWarning,
                    )
        print(f"\nLaunching '{' '.join(cmd_list)}'...")
        out = DEVNULL if sys.platform == "win32" else PIPE
        self._rpc = psutil.Popen(cmd_list,
                                 stdin=DEVNULL,
                                 stdout=out,
                                 stderr=out)
        # check that web3 can connect
        if not web3.provider:
            chain._network_disconnected()
            return
        uri = web3.provider.endpoint_uri if web3.provider else None
        for i in range(100):
            if web3.isConnected():
                chain._network_connected()
                return
            time.sleep(0.1)
            if type(self._rpc) is psutil.Popen:
                self._rpc.poll()
            if not self._rpc.is_running():
                self.kill(False)
                raise RPCProcessError(cmd, uri)
        self.kill(False)
        raise RPCConnectionError(cmd, self._rpc, uri)
Ejemplo n.º 2
0
def launch(cmd: str, **kwargs: Dict) -> None:
    """Launches the RPC client.

    Args:
        cmd: command string to execute as subprocess"""
    if sys.platform == "win32" and not cmd.split(" ")[0].endswith(".cmd"):
        if " " in cmd:
            cmd = cmd.replace(" ", ".cmd ", 1)
        else:
            cmd += ".cmd"
    cmd_list = cmd.split(" ")
    ganache_version = get_ganache_version(cmd_list[0])

    if ganache_version <= 6:
        cli_flags = CLI_FLAGS["<=6"]
    else:
        cli_flags = CLI_FLAGS["7"]
        # this flag must be true so that reverting tx's return a
        # more verbose output similar to what ganache 6 produced
        cmd_list.extend(["--chain.vmErrorsOnRPCResponse", "true"])

    kwargs.setdefault("evm_version", EVM_DEFAULT)  # type: ignore
    if kwargs["evm_version"] in EVM_EQUIVALENTS:
        kwargs["evm_version"] = EVM_EQUIVALENTS[
            kwargs["evm_version"]]  # type: ignore
    kwargs = _validate_cmd_settings(kwargs)
    for key, value in [(k, v) for k, v in kwargs.items() if v]:
        if key == "unlock":
            if not isinstance(value, list):
                value = [value]  # type: ignore
            for address in value:
                if isinstance(address, int):
                    address = HexBytes(address.to_bytes(20, "big")).hex()
                cmd_list.extend([cli_flags[key], address])
        else:
            try:
                if value is True:
                    cmd_list.append(cli_flags[key])
                elif value is not False:
                    cmd_list.extend([cli_flags[key], str(value)])
            except KeyError:
                warnings.warn(
                    f"Ignoring invalid commandline setting for ganache-cli: "
                    f'"{key}" with value "{value}".',
                    InvalidArgumentWarning,
                )
    print(f"\nLaunching '{' '.join(cmd_list)}'...")
    out = DEVNULL if sys.platform == "win32" else PIPE

    return psutil.Popen(cmd_list, stdin=DEVNULL, stdout=out, stderr=out)
Ejemplo n.º 3
0
def launch(cmd: str, **kwargs: Dict) -> None:
    """Launches the RPC client.

    Args:
        cmd: command string to execute as subprocess"""
    if sys.platform == "win32" and not cmd.split(" ")[0].endswith(".cmd"):
        if " " in cmd:
            cmd = cmd.replace(" ", ".cmd ", 1)
        else:
            cmd += ".cmd"
    cmd_list = cmd.split(" ")
    kwargs.setdefault("evm_version", EVM_DEFAULT)  # type: ignore
    if kwargs["evm_version"] in EVM_EQUIVALENTS:
        kwargs["evm_version"] = EVM_EQUIVALENTS[kwargs["evm_version"]]  # type: ignore
    kwargs = _validate_cmd_settings(kwargs)
    for key, value in [(k, v) for k, v in kwargs.items() if v]:
        if key == "unlock":
            if not isinstance(value, list):
                value = [value]  # type: ignore
            for address in value:
                if isinstance(address, int):
                    address = HexBytes(address.to_bytes(20, "big")).hex()
                cmd_list.extend([CLI_FLAGS[key], address])
        else:
            try:
                cmd_list.extend([CLI_FLAGS[key], str(value)])
            except KeyError:
                warnings.warn(
                    f"Ignoring invalid commandline setting for ganache-cli: "
                    f'"{key}" with value "{value}".',
                    InvalidArgumentWarning,
                )
    print(f"\nLaunching '{' '.join(cmd_list)}'...")
    out = DEVNULL if sys.platform == "win32" else PIPE

    try:
        p = psutil.Popen(cmd_list, stdin=DEVNULL, stdout=out, stderr=out)
    except FileNotFoundError:
        print("Error: Failed to start ganache-cli. Check installation!!")
        print("Insturctions https://github.com/trufflesuite/ganache-cli")
        sys.exit(2)

    return p
Ejemplo n.º 4
0
    def _reset(self) -> None:
        self._accounts.clear()
        try:
            self._accounts = [Account(i) for i in web3.eth.accounts]
        except Exception:
            pass

        # Check if accounts were manually unlocked and add them
        try:
            unlocked_accounts = CONFIG.active_network["cmd_settings"]["unlock"]
            if not isinstance(unlocked_accounts, list):
                unlocked_accounts = [unlocked_accounts]
            for address in unlocked_accounts:
                if isinstance(address, int):
                    address = HexBytes(address.to_bytes(20, "big")).hex()
                account = Account(address)
                if account not in self._accounts:
                    self._accounts.append(account)
        except (ConnectionError, ValueError, KeyError):
            pass

        if self.default not in self._accounts:
            self.default = None