當前位置: 首頁>>代碼示例>>Python>>正文


Python middleware.geth_poa_middleware方法代碼示例

本文整理匯總了Python中web3.middleware.geth_poa_middleware方法的典型用法代碼示例。如果您正苦於以下問題:Python middleware.geth_poa_middleware方法的具體用法?Python middleware.geth_poa_middleware怎麽用?Python middleware.geth_poa_middleware使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在web3.middleware的用法示例。


在下文中一共展示了middleware.geth_poa_middleware方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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) 
開發者ID:gnosis,項目名稱:safe-relay-service,代碼行數:20,代碼來源:gas_station.py

示例2: __init__

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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__() 
開發者ID:artemistomaras,項目名稱:django-ethereum-events,代碼行數:27,代碼來源:web3_service.py

示例3: __init__

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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 
開發者ID:gnosis,項目名稱:django-eth-events,代碼行數:28,代碼來源:web3_service.py

示例4: is_connected_with

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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 
開發者ID:kayagoban,項目名稱:shadowlands,代碼行數:29,代碼來源:connection.py

示例5: __init__

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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) 
開發者ID:raiden-network,項目名稱:raiden-contracts,代碼行數:13,代碼來源:token_ops.py

示例6: verify

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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() 
開發者ID:raiden-network,項目名稱:raiden-contracts,代碼行數:9,代碼來源:__main__.py

示例7: connect

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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 
開發者ID:eth-brownie,項目名稱:brownie,代碼行數:50,代碼來源:web3.py

示例8: connect_to_blockchain

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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 
開發者ID:raiden-network,項目名稱:raiden-services,代碼行數:44,代碼來源:cli.py

示例9: setup_ctx

# 需要導入模塊: from web3 import middleware [as 別名]
# 或者: from web3.middleware import geth_poa_middleware [as 別名]
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,
    } 
開發者ID:raiden-network,項目名稱:raiden-contracts,代碼行數:44,代碼來源:__main__.py


注:本文中的web3.middleware.geth_poa_middleware方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。