Python web3.middleware.geth_poa_middleware() Examples

The following are 9 code examples of web3.middleware.geth_poa_middleware(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module web3.middleware , or try the search function .
Example #1
Source File: web3_service.py    From django-ethereum-events with MIT License 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initializes the `web3` object.

        Args:
            rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional)
        """
        rpc_provider = kwargs.pop('rpc_provider', None)
        if not rpc_provider:
            timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)

            uri = settings.ETHEREUM_NODE_URI
            rpc_provider = HTTPProvider(
                endpoint_uri=uri,
                request_kwargs={
                    "timeout": timeout
                }
            )

        self.web3 = Web3(rpc_provider)

        # If running in a network with PoA consensus, inject the middleware
        if getattr(settings, "ETHEREUM_GETH_POA", False):
            self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)

        super(Web3Service, self).__init__() 
Example #2
Source File: gas_station.py    From safe-relay-service with MIT License 6 votes vote down vote up
def __init__(self,
                 http_provider_uri='http://localhost:8545',
                 number_of_blocks: int = 200,
                 cache_timeout_seconds: int = 10 * 60,
                 constant_gas_increment: int = 1):  # Increase a little for fastest mining for API Calls

        self.http_provider_uri = http_provider_uri
        self.http_session = requests.session()
        self.number_of_blocks = number_of_blocks
        self.cache_timeout = cache_timeout_seconds
        self.constant_gas_increment = constant_gas_increment
        self.w3 = Web3(HTTPProvider(http_provider_uri))
        try:
            if self.w3.net.version != 1:
                self.w3.middleware_onion.inject(geth_poa_middleware, layer=0)
            # For tests using dummy connections (like IPC)
        except (ConnectionError, FileNotFoundError):
            self.w3.middleware_onion.inject(geth_poa_middleware, layer=0) 
Example #3
Source File: web3_service.py    From django-eth-events with MIT License 6 votes vote down vote up
def __init__(self, provider,
                 max_workers: int=10, max_batch_requests: int=10, slow_provider_timeout: int=400):
        """
        :param node_uri: Node http address. If uri starts with 'test', EthereumTester will be used
        :param max_workers: Max workers for multithread calls. 1 -> No multithread
        :param max_batch_requests: Max requests in the same batch for RPC
        :param self.slow_provider_timeout: Timeout for time lasting requests (like filters)
        """
        self.provider = provider
        self.max_workers = max_workers
        self.max_batch_requests = max_batch_requests
        self.slow_provider_timeout = slow_provider_timeout
        self.node_uri = self.get_node_uri()

        self.web3 = Web3(provider)
        self.web3_slow = Web3(self.slow_provider)
        self.http_session = requests.session()

        # If rinkeby, inject Geth PoA middleware
        # http://web3py.readthedocs.io/en/latest/middleware.html#geth-style-proof-of-authority
        try:
            if int(self.web3.net.version) == RINKEBY_CHAIN_ID:
                self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
        # For tests using dummy connections (like IPC)
        except (UnhandledRequest, ConnectionError, ConnectionRefusedError, FileNotFoundError):
            pass 
Example #4
Source File: web3.py    From brownie with MIT License 5 votes vote down vote up
def connect(self, uri: str, timeout: int = 30) -> None:
        """Connects to a provider"""
        for middleware in self._custom_middleware:
            self.middleware_onion.remove(middleware)
        self._custom_middleware.clear()
        self.provider = None

        uri = _expand_environment_vars(uri)
        try:
            if Path(uri).exists():
                self.provider = IPCProvider(uri, timeout=timeout)
        except OSError:
            pass

        if self.provider is None:
            if uri.startswith("ws"):
                self.provider = WebsocketProvider(uri, {"close_timeout": timeout})
            elif uri.startswith("http"):

                self.provider = HTTPProvider(uri, {"timeout": timeout})
            else:
                raise ValueError(
                    "Unknown URI - must be a path to an IPC socket, a websocket "
                    "beginning with 'ws' or a URL beginning with 'http'"
                )

        try:
            if not self.isConnected():
                return
        except Exception:
            # checking an invalid connection sometimes raises on windows systems
            return

        # add middlewares
        try:
            if "fork" in CONFIG.active_network["cmd_settings"]:
                self._custom_middleware.add(_ForkMiddleware)
                self.middleware_onion.add(_ForkMiddleware)
        except (ConnectionError, KeyError):
            pass

        try:
            self.eth.getBlock("latest")
        except ExtraDataLengthError:
            self._custom_middleware.add(geth_poa_middleware)
            self.middleware_onion.inject(geth_poa_middleware, layer=0)
        except ConnectionError:
            pass 
Example #5
Source File: connection.py    From shadowlands with MIT License 5 votes vote down vote up
def is_connected_with(self, _w3, connection_type, _heart_rate, _bg_w3=None):
        if not _w3.isConnected():
            return False

        self.w3 = _w3

        self.network = self.w3.eth.chainId

        if self.network == 1 and self._sai_pip is None:
            self._sai_pip = SaiPip(self)

        self._heart_rate = _heart_rate
        self._connection_type = connection_type


        if self.network == 4:
            from web3.middleware import geth_poa_middleware
            self.w3.middleware_stack.inject(geth_poa_middleware, layer=0)

        try:
            self._update_status()
        except (StaleBlockchain):
            return False

        logging.debug("is connected with " + connection_type + " every " + str(_heart_rate) + " seconds.")

        return True 
Example #6
Source File: token_ops.py    From raiden-contracts with MIT License 5 votes vote down vote up
def __init__(
        self, rpc_url: URI, private_key: Path, password: Optional[Path] = None, wait: int = 10
    ):
        self.web3 = Web3(HTTPProvider(rpc_url))
        self.private_key = get_private_key(private_key, password)
        assert self.private_key is not None
        self.owner = private_key_to_address(self.private_key)
        self.wait = wait
        self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(self.private_key))
        self.web3.eth.defaultAccount = self.owner  # type: ignore
        self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) 
Example #7
Source File: __main__.py    From raiden-contracts with MIT License 5 votes vote down vote up
def verify(_: Any, rpc_provider: URI, contracts_version: Optional[str]) -> None:
    web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={"timeout": 60}))
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)
    print("Web3 provider is", web3.provider)

    verifier = ContractVerifier(web3=web3, contracts_version=contracts_version)
    verifier.verify_deployed_contracts_in_filesystem() 
Example #8
Source File: cli.py    From raiden-services with MIT License 4 votes vote down vote up
def connect_to_blockchain(
    eth_rpc: URI,
    gas_price_strategy: Callable[[Web3, Any], Wei],
    used_contracts: List[str],
    address_overwrites: Dict[str, Address],
) -> Tuple[Web3, Dict[str, Contract], BlockNumber]:
    try:
        provider = HTTPProvider(eth_rpc)
        web3 = Web3(provider)
        # Will throw ConnectionError on bad Ethereum client
        chain_id = ChainID(web3.eth.chainId)
    except requests.exceptions.ConnectionError:
        log.error(
            "Can not connect to the Ethereum client. Please check that it is running and that "
            "your settings are correct.",
            eth_rpc=eth_rpc,
        )
        sys.exit(1)

    # Add POA middleware for geth POA chains, no/op for other chains
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)

    # Set gas price strategy
    # for that we also need a cache middleware, otherwise sampling is expensive
    web3.middleware_onion.add(simple_cache_middleware)
    web3.eth.setGasPriceStrategy(gas_price_strategy)

    # give web3 some time between retries before failing
    # TODO: find a way to to this type safe
    provider.middlewares.replace(  # type: ignore
        "http_retry_request", http_retry_with_backoff_middleware
    )

    addresses, start_block = get_contract_addresses_and_start_block(
        chain_id=chain_id, contracts=used_contracts, address_overwrites=address_overwrites
    )
    contracts = {
        c: web3.eth.contract(abi=CONTRACT_MANAGER.get_contract_abi(c), address=address)
        for c, address in addresses.items()
    }

    return web3, contracts, start_block 
Example #9
Source File: __main__.py    From raiden-contracts with MIT License 4 votes vote down vote up
def setup_ctx(
    ctx: click.Context,
    private_key: str,
    password_file: Optional[Path],
    rpc_provider: URI,
    wait: int,
    gas_price: int,
    gas_limit: int,
    contracts_version: Optional[str] = None,
) -> None:
    """Set up deployment context according to common options (shared among all
    subcommands).
    """

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger("web3").setLevel(logging.INFO)
    logging.getLogger("urllib3").setLevel(logging.INFO)

    web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={"timeout": 60}))
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)
    print("Web3 provider is", web3.provider)
    private_key_string = get_private_key(Path(private_key).expanduser(), password_file)
    if not private_key_string:
        raise RuntimeError("Could not access the private key.")
    owner = private_key_to_address(private_key_string)
    # pylint: disable=E1101
    if web3.eth.getBalance(owner) == 0:
        raise RuntimeError("Account with insufficient funds.")
    deployer = ContractDeployer(
        web3=web3,
        private_key=private_key_string,
        gas_limit=gas_limit,
        gas_price=gas_price,
        wait=wait,
        contracts_version=contracts_version,
    )
    ctx.obj = {
        "deployer": deployer,
        "deployed_contracts": {},
        "token_type": "CustomToken",
        "wait": wait,
    }