Python web3.IPCProvider() Examples

The following are 16 code examples of web3.IPCProvider(). 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 , or try the search function .
Example #1
Source File: bcinterface.py    From ddash with MIT License 7 votes vote down vote up
def __init__(self,host='localhost',port=5001,mainnet=False):
		self.last_contract_address = None
		self.last_hash_added = None
		#self.api = ipfsapi.connect(host='127.0.0.1',port=port)
		# self.web3 = Web3(HTTPProvider('http://localhost:8545'))
		if mainnet:
			ipc_path=os.path.dirname(os.path.realpath(__file__))+'/data_mainnet/geth.ipc'
		else:
			ipc_path = os.path.dirname(os.path.realpath(__file__))+'/data/geth.ipc'
		print("IPCProvider path: ",ipc_path)
		self.web3 = Web3(IPCProvider(ipc_path))
		self.blockNumber = self.web3.eth.blockNumber
		self.eth_accounts = self.web3.personal.listAccounts
		self.account_index = 0
		self.ethereum_acc_pass = None
		
		self.tx = {}

		print("Initializing a DDASH Interface object.")

		# log Ethereum accounts to ddash/nfo/
		self.write_ethereum_address(mainnet)

	# contract_name is without the sol extension 
Example #2
Source File: test_singleton.py    From django-eth-events with MIT License 6 votes vote down vote up
def test_event_listener_singleton(self):
        ipc_provider = IPCProvider(
            ipc_path=None,
            testnet=True
        )

        listener1 = EventListener()
        listener2 = EventListener()
        self.assertEqual(listener1, listener2)
        listener3 = EventListener(provider=ipc_provider)
        self.assertNotEqual(listener2, listener3)

        # For a different contract we need a different instance of the singleton even if provider is the same
        contract_map = [
            {'NAME': 'Tester Oracle Factory', 'EVENT_ABI': [],
             'EVENT_DATA_RECEIVER': 'django_eth_events.tests.test_celery.DummyEventReceiver',
             'ADDRESSES': ['c305c901078781C232A2a521C2aF7980f8385ee9']
             }
        ]
        listener4 = EventListener(provider=ipc_provider, contract_map=contract_map)
        self.assertNotEqual(listener3, listener4)
        listener5 = EventListener(provider=ipc_provider, contract_map=contract_map)
        self.assertEqual(listener4, listener5) 
Example #3
Source File: create_txs.py    From airdrop with Apache License 2.0 6 votes vote down vote up
def create_txs(ipc_path, rpc_host, rpc_port, signer_addr, airdropper_addr, omgtoken_addr, verify_eth,
               processed_file, unsigned_file):

    if ipc_path and (rpc_host or rpc_port):
        raise Exception("both ipc and rpc cannot be specified")
    if ipc_path:
        web3 = Web3(IPCProvider(ipc_path))
    else:
        web3 = Web3(RPCProvider(host=rpc_host,
                                port=rpc_port))

    airdropper, omgToken = get_contracts(web3,
                                         airdropper_addr=airdropper_addr,
                                         omgtoken_addr=omgtoken_addr)

    creator = Creator(signer_addr, airdropper, omgToken, GAS_LIMIT, GAS_PRICE, GAS_RESERVE,
                      verify_eth=verify_eth)

    airdrops = json.loads(processed_file.read())

    unsigned = creator.create_txs(airdrops, BATCH_SIZE)

    unsigned_file.write(json.dumps(unsigned, sort_keys=True)) 
Example #4
Source File: send_txs.py    From airdrop with Apache License 2.0 6 votes vote down vote up
def send_txs(ipc_path, rpc_host, rpc_port, recovery_mode,
             final_check_unsigned_file, signed_file):

    if ipc_path and (rpc_host or rpc_port):
        raise Exception("both ipc and rpc cannot be specified")
    if ipc_path:
        web3 = Web3(IPCProvider(ipc_path))
    else:
        web3 = Web3(RPCProvider(host=rpc_host,
                                port=rpc_port))

    sender = Sender(web3)

    signed = json.loads(signed_file.read())
    final_check_local_transactions = json.loads(final_check_unsigned_file.read())

    if recovery_mode:
        signed, final_check_local_transactions = sender.recover_unsent(signed, final_check_local_transactions)

    sender.send_transactions(signed, final_check_local_transactions) 
Example #5
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 #6
Source File: web3_service.py    From django-eth-events with MIT License 5 votes vote down vote up
def get_provider_from_uri(node_uri: str):
        if node_uri.startswith('http'):
            return HTTPProvider(node_uri)
        elif node_uri.startswith('ipc'):
            path = node_uri.replace('ipc://', '')
            return IPCProvider(ipc_path=path)
        elif node_uri.startswith('test'):
            return EthereumTesterProvider(EthereumTester())
        else:
            raise ValueError('%s uri is not supported. Must start by http, ipc, or test' % node_uri) 
Example #7
Source File: web3_service.py    From django-eth-events with MIT License 5 votes vote down vote up
def slow_provider(self):
        if isinstance(self.provider, HTTPProvider):
            return HTTPProvider(endpoint_uri=self.provider.endpoint_uri,
                                request_kwargs={'timeout': self.slow_provider_timeout})
        elif isinstance(self.provider, IPCProvider):
            return IPCProvider(ipc_path=self.provider.ipc_path, timeout=self.slow_provider_timeout)
        else:
            return self.provider 
Example #8
Source File: test_singleton.py    From django-eth-events with MIT License 5 votes vote down vote up
def test_arg_ipc_provider(self):
        ipc_provider = IPCProvider(
            ipc_path=None,
            testnet=True
        )

        service1 = Web3ServiceProvider()
        self.assertIsInstance(service1.web3.providers[0], HTTPProvider)
        service2 = Web3Service(ipc_provider)
        self.assertIsInstance(service2.web3.providers[0], IPCProvider)
        self.assertEqual(service2.web3.providers[0], ipc_provider) 
Example #9
Source File: test_web3_service.py    From django-eth-events with MIT License 5 votes vote down vote up
def test_provider_ipc(self):
        socket_path = str(Path('/tmp/socket.ipc').expanduser().resolve())
        with self.settings(ETHEREUM_NODE_URL='ipc://' + socket_path):
            web3_service = Web3ServiceProvider()
            provider = web3_service.web3.providers[0]
            self.assertTrue(isinstance(provider, IPCProvider))
            self.assertEqual(provider.ipc_path, socket_path) 
Example #10
Source File: blockchain.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def __init__(self):
        self.w3 = Web3(IPCProvider('/tmp/geth.ipc')) 
Example #11
Source File: models.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def __init__(self):
        self.w3 = Web3(IPCProvider('/tmp/geth.ipc'))
        with open('../address.txt', 'r') as f:
            address = f.read().rstrip("\n")

        with open('../videos_sharing_smart_contract/build/contracts.json') as f:
            contract = json.load(f)
            abi = contract['VideosSharing']['abi']

        self.SmartContract = self.w3.eth.contract(address=address, abi=abi)

        self.ipfs_con = ipfsapi.connect() 
Example #12
Source File: filter_sent_airdrops.py    From airdrop with Apache License 2.0 5 votes vote down vote up
def filter(ipc_path, airdropper_addr, omgtoken_addr,
           processed_file, signed_file, unsent_airdrops_file):
    web3 = Web3(IPCProvider(ipc_path))
    airdropper, omg_token = get_contracts(web3,
                                          airdropper_addr=airdropper_addr,
                                          omgtoken_addr=omgtoken_addr)
    sender = Sender(web3)

    signed = json.loads(signed_file.read())
    airdrops = json.loads(processed_file.read())

    unsent_airdrops = sender.recover_unsent_airdrops(airdrops, signed, airdropper, omg_token)

    unsent_airdrops_file.write(json.dumps(unsent_airdrops)) 
Example #13
Source File: test_utils.py    From airdrop with Apache License 2.0 5 votes vote down vote up
def web3():
    web3 = Web3(IPCProvider("/tmp/ethereum_dev_mode/geth.ipc"))
    web3.personal.unlockAccount(web3.eth.accounts[0], "")
    return web3 
Example #14
Source File: sign_txs.py    From airdrop with Apache License 2.0 5 votes vote down vote up
def sign_txs(ipc_path, unsigned_file, signed_file):
    web3 = Web3(IPCProvider(ipc_path))
    signer = Signer(web3)

    unsigned = json.loads(unsigned_file.read())

    signed = signer.sign_transactions(unsigned)

    signed_file.write(json.dumps(signed)) 
Example #15
Source File: console.py    From trinity with MIT License 5 votes vote down vote up
def console(ipc_path: Path,
            use_ipython: bool = True,
            env: Dict[str, Any] = None,
            banner: str = DEFAULT_BANNER) -> None:
    """
    Method that starts the chain, setups the trinity CLI and register the
    cleanup function.
    """
    if env is None:
        env = {}

    # if ipc_path is not found, raise an exception with a useful message
    if not ipc_path.exists():
        raise FileNotFoundError(create_missing_ipc_error_message(ipc_path))

    # wait to import web3, because it's somewhat large, and not usually used
    import web3
    ipc_provider = web3.IPCProvider(ipc_path)
    w3 = web3.Web3(ipc_provider)

    # Allow omitting params by defaulting to `None`
    def rpc(method: RPCEndpoint, params: Dict[str, Any] = None) -> RPCResponse:
        return ipc_provider.make_request(method, params)

    namespace = merge({'w3': w3, 'rpc': rpc}, env)

    shell(use_ipython, namespace, banner) 
Example #16
Source File: settings.py    From ethgasstation-backend with GNU General Public License v3.0 4 votes vote down vote up
def get_web3_provider(protocol=None, hostname=None, port=None, timeout=None):
    """Get Web3 instance. Supports websocket, http, ipc."""
    if protocol is None:
        protocol = get_setting('rpc', 'protocol')
    if hostname is None:
        hostname = get_setting('rpc', 'hostname')
    if port is None:
        port = get_setting('rpc', 'port')
    if timeout is None:
        try:
            timeout = int(get_setting('rpc', 'timeout'))
        except KeyError:
            timeout = 15 # default timeout is 15 seconds

    if protocol == 'ws' or protocol == 'wss':
        provider = WebsocketProvider(
            "%s://%s:%s" % (
                protocol,
                hostname,
                port),
            websocket_kwargs={'timeout':timeout}
        )
        provider.egs_timeout = timeout
        return Web3(provider)
    elif protocol == 'http' or protocol == 'https':
        provider = HTTPProvider(
            "%s://%s:%s" % (
                protocol,
                hostname,
                port),
            request_kwargs={'timeout':timeout}
        )
        provider.egs_timeout = timeout
        return Web3(provider)
    elif protocol == 'ipc':
        provider = IPCProvider(
            hostname,
            timeout=timeout
        )
        provider.egs_timeout = timeout
        return Web3(provider)
    else:
        raise Exception("Can't set web3 provider type %s" % str(protocol))