def web3_rpc_persistent(geth_persistent): from web3 import ( Web3, RPCProvider, ) provider = RPCProvider(port=geth_persistent.rpc_port) provider._geth = geth_persistent web3 = Web3(provider) return web3
def web3_rpc_empty(): from web3 import ( Web3, RPCProvider, ) with setup_testing_geth() as geth: provider = RPCProvider(port=geth.rpc_port) provider._geth = geth web3 = Web3(provider) yield web3
def get_connection(self): if config.RPC_SERVER_PROTOCOL == 'IPC': return Web3(AsyncIPCProvider(ipc_path=config.RPC_SERVER_IPC_PATH)) elif config.RPC_SERVER_PROTOCOL == 'HTTP': return Web3(RPCProvider(host=config.RPC_SERVER_HOST, port=config.RPC_SERVER_HTTP_PORT)) else: raise ValueError('wrong or missing RPC_SERVER_PROTOCOL')
def __init__(self): # Load contract configuration self.web3 = Web3(RPCProvider(host='localhost', port='8545')) dir_path = path.dirname(path.realpath(__file__)) with open(str(path.join(dir_path, 'configuration.txt')), 'r') as configuration: for line in configuration: if line.startswith('contractPollingCenter='): self.contractPC_address = line.split('=')[1].rstrip('\n') if line.startswith('contractCryptoRF='): self.contractPoll_address = line.split('=')[1].rstrip('\n') if line.startswith('main_account='): self.main_account = line.split('=')[1].rstrip('\n') if line.startswith('main_password='******'=')[1].rstrip('\n') with open(str(path.join(dir_path, 'PollingCenter.json')), 'r') as abi_definition: self.abiPC = json.load(abi_definition) with open(str(path.join(dir_path, 'Poll.json')), 'r') as abi_definition: self.abiPoll = json.load(abi_definition) self.web3.personal.unlockAccount(self.main_account, self.main_password) self.contractPC = self.web3.eth.contract(self.abiPC, self.contractPC_address) self.contractPoll = self.web3.eth.contract(self.abiPoll, self.contractPoll_address) print(self.contractPC_address) print(self.contractPoll_address) self.polls = dict() self.polls['CryptoRF'] = self.contractPoll newPollFilter = self.contractPC.on( 'PollCreated', {'address': self.contractPC_address}, self.pollCreated)
class Contract(): eth = Web3(RPCProvider()).eth def __init__(self, moduleName, ownerAddress='', args=[]): path = '../../solidity/contracts/build/' abi = open(path + moduleName + '.abi').read() bin = open(path + moduleName + '.bin').read() self.contract = Contract.eth.contract(abi=loads(abi), bytecode=bin) self.transact = { 'from': ownerAddress if ownerAddress else Contract.eth.accounts[0] } self.address = Contract.eth.getTransactionReceipt( self.contract.deploy(transaction=self.transact, args=args))['contractAddress'] def owner(self): return self.transact['from'] def getter(self): return self.contract(self.address).call(self.transact) def setter(self): return self.contract(self.address).transact(self.transact) def tester(self): return self.contract(self.address).estimateGas(self.transact) def retval(self, hash): return int( Contract.eth.getTransactionReceipt(hash)['logs'][-1]['data'], 0)
def __init__(self, *args, **kwargs): """Initializes the `web3` object. Args: rpc_provider (:obj:`Provider`, optional): Valid `web3` Provider instance. """ rpc_provider = kwargs.pop('rpc_provider', None) if not rpc_provider: timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10) if HTTPProvider is not None: uri = "{scheme}://{host}:{port}".format( host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, scheme="https" if settings.ETHEREUM_NODE_SSL else "http", ) rpc_provider = HTTPProvider( endpoint_uri=uri, request_kwargs={"timeout": timeout}) elif RPCProvider is not None: rpc_provider = RPCProvider(host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, ssl=settings.ETHEREUM_NODE_SSL, timeout=timeout) else: raise ValueError("Cannot instantiate any RPC provider") self.web3 = Web3(rpc_provider) super(Web3Service, self).__init__()
def main(ctx, tracker_address, factory_address, payment_lib_address, request_lib_address, log_level, provider, ipc_path, rpc_host, rpc_port, compiled_assets_path, back_scan_seconds, forward_scan_seconds, back_scan_blocks, forward_scan_blocks): if provider == 'ipc': web3 = Web3(IPCProvider(ipc_path=ipc_path)) elif provider == 'rpc': web3 = Web3(RPCProvider(host=rpc_host, port=rpc_port)) elif provider: provider_class = import_string(provider) web3 = Web3(provider_class()) else: raise click.ClickException("This shouldn't be possible") config = Config( web3, compiled_assets_path=compiled_assets_path, log_level=log_level, tracker_address=tracker_address, factory_address=factory_address, payment_lib_address=payment_lib_address, request_lib_address=request_lib_address, scan_timestamp_range=(back_scan_seconds, forward_scan_seconds), scan_blocks_range=(back_scan_blocks, forward_scan_blocks), ) ctx.web3 = web3 ctx.config = config
def test_start_private_geth(test_config_path, dbsession): """We can spawn a standalone private geth instance for private testnet.""" project_dir = os.getcwd() # Goes under "chains" # Use non-default port, so that we don't conflict with existing # test geth daemon geth = start_private_geth("foobar", project_dir, "127.0.0.1", 10010, p2p_port=40000) web3 = Web3(RPCProvider("127.0.0.1", 10010)) deadline = time.time() + 10 while time.time() < deadline: if not geth.is_alive: pytest.fail("geth died") try: web3.eth.coinbase geth.stop() return except Exception as e: print(e) time.sleep(1) geth.stop() pytest.fail("Could not connect to geth instance using a specific port")
def mock_eth_service(eth_network_id, dbsession, registry): """Non-functional Ethereum Service without a connection to geth.""" from web3 import RPCProvider, Web3 web3 = Web3(RPCProvider("127.0.0.1", 666)) s = EthereumService(web3, eth_network_id, dbsession, registry) return s
def setUpClass(cls): cls.web3 = Web3(RPCProvider()) abi = json.loads(open('../contracts/build/BancorFormula.abi').read()) bin = open('../contracts/build/BancorFormula.bin').read() formula = cls.web3.eth.contract(abi=abi, bytecode=bin) tx = formula.deploy() cls.formula = formula( cls.web3.eth.getTransactionReceipt(tx)['contractAddress'])
def __init__(self): super(Bot, self).__init__() self.decoder = Decoder() self.web3 = Web3( RPCProvider(host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, ssl=settings.ETHEREUM_NODE_SSL)) self.batch = MailBatch()
def __init__(self): self.web3 = Web3(RPCProvider(host='testnet', port='8545')) with open('contract_abi.json', 'r') as abi_definision: self.abi = json.load(abi_definision) self.account = '0x1d963c56f257c23c0f6fc5abbb9b51bfb0f1cf57' self.contract_address = '0x22c0b2b96067023a25d2ff342aeca0dc3f70c3a4' self.password = '******' self.contract = self.web3.eth.contract(self.abi, self.contract_address)
def test(): evmbin = "evm" # evmbin = "/home/martin/data/workspace/go-ethereum/build/bin/evm" tx = "0x66abc672b9e427447a8a8964c7f4671953fab20571ae42ae6a4879687888c495" tx = "0x9dbf0326a03a2a3719c27be4fa69aacc9857fd231a8d9dcaede4bb083def75ec" web3 = Web3(RPCProvider(host='mainnet.infura.io', port=443, ssl=True)) chain = etherchain.EtherChainAPI() api = multiapi.MultiApi(web3=web3, etherchain=chain) reproduceTx(tx, evmbin, api)
def main(args): if args.parity_evm: vm = VMUtils.ParityVM(args.parity_evm, not args.no_docker) else: vm = VMUtils.GethVM(args.geth_evm, not args.no_docker) parsed_web3 = urlparse(args.web3) if not parsed_web3.hostname: #User probably omitted 'http://' parsed_web3 = urlparse("http://%s" % args.web3) ssl = (parsed_web3.scheme == 'https') port = parsed_web3.port if not port: #Not explicitly defined if ssl: port = 443 else: port = 80 web3 = Web3(RPCProvider(host=parsed_web3.hostname, port=port, ssl=ssl)) api = multiapi.MultiApi(web3=web3, etherchain=etherchain.EtherChainAPI()) if args.test: artefacts = test(vm, api) import pprint pprint.PrettyPrinter().pprint(artefacts) sys.exit(0) if app and args.www: app.debug = args.debug app.api = api app.vm = vm app.run(host=args.www) elif args.hash: artefacts, vm_args = reproduce.reproduceTx(args.hash, vm, api) saved_files = saveFiles(artefacts) #Some tricks to get the right command for local replay p_gen = saved_files['parity genesis']['name'] g_gen = saved_files['geth genesis']['name'] vm_args['genesis'] = g_gen vm_args['dontExecuteButReturnCommand'] = True command = vm.execute(**vm_args) print("") print("Command to execute locally (geth):") print("") print("\t %s" % " ".join(command)) print("") (zipfilepath, zipfilename) = zipFiles(saved_files, args.hash[:8]) print("Zipped files into %s%s" % (zipfilepath, zipfilename)) else: parser.print_usage()
def fetch(args): if len(args) < 1: print("Usage: ./reproduce.py <tx hash>") exit(1) evmbin = "evm" tx = args[0] web3 = Web3(RPCProvider(host='mainnet.infura.io', port=443, ssl=True)) chain = etherchain.EtherChainAPI() api = multiapi.MultiApi(web3=web3, etherchain=chain) reproduceTx(tx, evmbin, api)
def get_api(self, node): self.rpc_endpoint, kwargs = RpcMapper.get_rpc_addr(node) params = { 'host': kwargs.get('host'), 'port': kwargs.get('port'), } if self.rpc_endpoint not in self.api_cache: self.api_cache[self.rpc_endpoint] = Web3(RPCProvider(**params)) self.api = self.api_cache[self.rpc_endpoint] return self.api
def main(args): web3 = Web3(RPCProvider(args.rpchost, args.rpcport)) contract = web3.eth.contract(abi=abi, address=args.address) addresses = list(check_addresses(contract, read_addresses(args.addresses))) hashes = make_hashes(addresses) batches = chunk(hashes, args.batchsize) for batch in batches: txid = send_deposit(contract, args.sender, batch, args.amount, args.gaslimit) print "Posted %d deposits in transaction %s" % (len(batch), txid)
def setUp(self): # Run mocked testrpc for reorgs print('Starting httpd...') self.server_process = Process(target=start_mock_server) self.server_process.start() cache.set('block_number', '0x0') sleep(1) print('served') self.rpc = RPCProvider(host='127.0.0.1', port='8545', ssl=0) web3_service = Web3Service(self.rpc) self.web3 = web3_service.web3 # Mock web3 self.daemon = DaemonFactory()
def setUpClass(cls): cls.web3 = Web3(RPCProvider()) abi = json.loads(open('RoundTable.abi').read()) bin = open('RoundTable.bin').read() contract = cls.web3.eth.contract(abi=abi, bytecode=bin) cls.war_chest = "0x000000000000000000000000000000000000cafe" val = 100000000000000000000L # 100 ether tx = contract.deploy({ 'from': cls.web3.eth.accounts[0], "value": val }, [cls.war_chest]) cls.roundtable = contract( cls.web3.eth.getTransactionReceipt(tx)['contractAddress'])
def __init__(self, *args, **kwargs): """Initializes the `web3` object. Args: rpc_provider (:obj:`Provider`, optional): Valid `web3` Provider instance. """ rpc_provider = kwargs.pop('rpc_provider', None) if not rpc_provider: rpc_provider = RPCProvider( host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, ssl=settings.ETHEREUM_NODE_SSL ) self.web3 = Web3(rpc_provider) super(Web3Service, self).__init__()
def start(self): self.load_config() self.load_contracts() self._web3 = Web3( RPCProvider(self.config['rpc']['host'], self.config['rpc']['port'], ssl=self.config['rpc']['ssl'])) self.node = Node(self._web3) self.load_networks() ipport = ('', 5000) logger.info('Starting server') app = ApiApp(self) http_server = WSGIServer(ipport, app, log=None) logger.info('Server is running on {}'.format(ipport)) http_server.serve_forever()
def retrieve_main_node_peers(): w3 = Web3(RPCProvider(host=GETH_RPC_PATH)) try: peers_list = w3.admin.peers except ConnectionError: print("RPC down") return [] boot_nodes = [] for peer in peers_list: try: node_pubkey = peer["id"] node_remote_addr = peer["network"]["remoteAddress"].split(":")[0] boot_nodes.append("enode://{pubkey}@{ip}:30303".format( pubkey=node_pubkey, ip=node_remote_addr)) except (IndexError, KeyError, ValueError) as e: print(str(e)) return boot_nodes
def getApi(providerUrl): parsed_web3 = urlparse(providerUrl) if not parsed_web3.hostname: #User probably omitted 'http://' parsed_web3 = urlparse("http://%s" % providerUrl) ssl = (parsed_web3.scheme == 'https') port = parsed_web3.port if not port: #Not explicitly defined if ssl: port = 443 else: port = 80 web3 = Web3(RPCProvider(host=parsed_web3.hostname, port=port, ssl=ssl)) api = multiapi.MultiApi(web3=web3, etherchain=etherchain.EtherChainAPI()) return api
def check_signature(req): signature = "0x" + req.sign contract = "0x" + req.contract client = req.client dest = req.dest t = req.t.secs end = req.end.secs if client in dictc: if not (dictc[client] < t.req.secs): return False dictc[client] = t.req.secs msg = contract + client + dest + str(t) + str(end) web3 = Web3(RPCProvider(host="127.0.0.1", port="8545")) web3.config.defaultAccount = '0xa28779d29c49fd57d0fc4130e5ebec07c2c79ef5' abi = '[{"constant":false,"inputs":[],"name":"kill","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"owns","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"type":"function"},{"inputs":[{"name":"_greeting","type":"string"}],"type":"constructor"}]' contracto = web3.eth.contract(abi) inst = contracto.at('0xbc8c629cd7477fd580b8f9e8da49e5aad364b769') if (int(t) > int(rospy.get_rostime().secs)): diff = t - int(rospy.get_rostime().secs) else: diff = int(rospy.get_rostime().secs) - t if (diff > 600): return False print "msg: " + msg + " sign: " + signature + " contract: " + contract hash_msg = utils.sha3(msg).encode('hex') r = long(signature[0:66], 16) s = long('0x' + signature[66:130], 16) v = long('0x' + signature[130:132], 16) if not (v == 27 and v == 28): v += 27 address_from_hash = bitcoin.ecdsa_raw_recover(hash_msg.decode('hex'), (v, r, s)) public_key = bitcoin.encode_pubkey(address_from_hash, 'bin') if ('0x' + utils.sha3(public_key[1:]).encode('hex')[24:64] == inst.owns()): return True else: return False
def web3(self): if not self.geth.is_running: raise ValueError( "Underlying geth process doesn't appear to be running") if self._web3 is None: if issubclass(self.provider_class, IPCProvider): provider = IPCProvider(self.geth.ipc_path) elif issubclass(self.provider_class, RPCProvider): provider = RPCProvider(port=self.geth.rpc_port) else: raise NotImplementedError( "Unsupported provider class {0!r}. Must be one of " "IPCProvider or RPCProvider") _web3 = Web3(provider) if 'default_account' in self.chain_config: _web3.eth.defaultAccount = self.chain_config['default_account'] self._web3 = _web3 return self._web3
def __init__(self): # Load contract configuration self.web3 = Web3(RPCProvider(host='localhost', port='8545')) dir_path = path.dirname(path.realpath(__file__)) with open(str(path.join(dir_path, 'Configuration.txt')), 'r') as configuration: for line in configuration: if line.startswith('contract='): self.contract_address = line.split('=')[1].rstrip('\n') if line.startswith('trading_account='): self.trading_account = line.split('=')[1].rstrip('\n') if line.startswith('trading_password='******'=')[1].rstrip('\n') # Simulate trading by having a mining account to transfer ether if line.startswith('mining_account='): self.mining_account = line.split('=')[1].rstrip('\n') if line.startswith('mining_password='******'=')[1].rstrip('\n') with open(str(path.join(dir_path, 'contract_abi.json')), 'r') as abi_definition: self.abi = json.load(abi_definition) self.contract = self.web3.eth.contract(self.abi, self.contract_address)
from web3 import Web3, IPCProvider, RPCProvider import requests import base64 import time import json import six from store import PersistentStore from urllib.parse import urlparse pstore = PersistentStore() web3 = Web3(RPCProvider()) web3.config.defaultAccount = "0x3b63b366a72e5742B2aaa13a5e86725ED06a68f3" contract_address = "0x1EEcb87dE18ac28c1824d9274f2cEBC5442F8c57" abi = """[ { "constant": true, "inputs": [ { "name": "channel", "type": "uint256" }, { "name": "value", "type": "uint256" } ], "name": "getHash", "outputs": [ { "name": "", "type": "bytes32", "value": "0x1c44b375153723d5b41d6a7350691ea6f95b8a08e93f90b8c6d1f3ee6552bbba", "displayName": "" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "channel", "type": "uint256" } ], "name": "reclaim", "outputs": [], "type": "function" }, { "constant": true, "inputs": [ { "name": "channel", "type": "uint256" }, { "name": "value", "type": "uint256" }, { "name": "v", "type": "uint8" }, { "name": "r", "type": "bytes32" }, { "name": "s", "type": "bytes32" } ], "name": "verify", "outputs": [ { "name": "", "type": "bool", "value": false, "displayName": "" } ], "type": "function" }, { "constant": true, "inputs": [], "name": "channelCount", "outputs": [ { "name": "", "type": "uint256", "value": "0", "displayName": "" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "channel", "type": "uint256" } ], "name": "deposit", "outputs": [], "type": "function" }, { "constant": true, "inputs": [ { "name": "channel", "type": "uint256" } ], "name": "isValidChannel", "outputs": [ { "name": "", "type": "bool", "value": false, "displayName": "" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "receiver", "type": "address" }, { "name": "expiry", "type": "uint256" } ], "name": "createChannel", "outputs": [ { "name": "channel", "type": "uint256" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "uint256" } ], "name": "channels", "outputs": [ { "name": "sender", "type": "address", "value": "0x", "displayName": "sender" }, { "name": "receiver", "type": "address", "value": "0x", "displayName": "receiver" }, { "name": "value", "type": "uint256", "value": "0", "displayName": "value" }, { "name": "expiry", "type": "uint256", "value": "0", "displayName": "expiry" }, { "name": "valid", "type": "bool", "value": false, "displayName": "valid" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "channel", "type": "uint256" }, { "name": "value", "type": "uint256" }, { "name": "v", "type": "uint8" }, { "name": "r", "type": "bytes32" }, { "name": "s", "type": "bytes32" } ], "name": "claim", "outputs": [], "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "sender", "type": "address" }, { "indexed": true, "name": "receiver", "type": "address" }, { "indexed": false, "name": "channel", "type": "uint256" } ], "name": "NewChannel", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "sender", "type": "address" }, { "indexed": true, "name": "receiver", "type": "address" }, { "indexed": false, "name": "channel", "type": "uint256" } ], "name": "Deposit", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "who", "type": "address" }, { "indexed": true, "name": "channel", "type": "uint256" } ], "name": "Claim", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "channel", "type": "bytes32" } ], "name": "Reclaim", "type": "event" } ]""" contract = web3.eth.contract(abi).at(contract_address) doccache = {} cachetime = 10 #seconds def getEndpoint(method, path): parsed_uri = urlparse(path) domain = "{uri.scheme}://{uri.netloc}/".format(uri=parsed_uri) if domain in doccache and time.time(
def put_ether_on_team_smart_contract(team_addr, id, flag): wei_per_transaction = 10**16 # (1-20 ethers) gas_per_transaction = 190000 try: with open("contract_abi.json") as abi: contract_abi = json.load(abi) except OSError as e: return CheckerAnswers.CHECKER_ERROR("", "can't open contract abi!") req = create_request_object( SERVICE_FIRST_CONTRACT_ADDR_URL.format(team_addr)) try: try: contract_addr = urlopen(req, timeout=7).read().decode() except socket.timeout: contract_addr = urlopen(req, timeout=7).read().decode() if contract_addr == "": return CheckerAnswers.MUMBLE( "Couldn't get team contract", "Team hasn't generated block contract!") except KeyError as e: return CheckerAnswers.MUMBLE( "Incorrect json-api schema response req", "req = {}, e = {}".format(req.full_url, e)) except socket.timeout as e: return CheckerAnswers.MUMBLE( "Service response timed out!", "req = {}, e = {}".format(req.full_url, e)) except URLError as e: return CheckerAnswers.DOWN("Can't reach service address!", "req = {}, e = {}".format(req.full_url, e)) req = BLACK_MARKET_ADDR + "/putFlag_C6EDEE7179BD4E2887A5887901F23060?{}"\ .format( urlencode( { "flag": flag, "contractAddr": contract_addr, "sum": int(wei_per_transaction), "vulnboxIp": team_addr })) try: try: urlopen(req, timeout=7).read().decode() except socket.timeout: urlopen(req, timeout=7).read().decode() except (URLError, socket.timeout) as e: return CheckerAnswers.CHECKER_ERROR( "", "Black Market is down! ({}), req = {}".format(e, req)) try: w3 = Web3(RPCProvider(host=GETH_RPC_PATH)) contract_instance = w3.eth.contract( contract_abi, contract_addr, ContractFactoryClass=ConciseContract) transaction_id = contract_instance.addToBalance( transact={ "from": ACCOUNT_ID, "gas": gas_per_transaction, "value": wei_per_transaction }) except ConnectionError as e: return CheckerAnswers.CHECKER_ERROR( "", "can't connect to checker rpc! {}".format(e)) # flag_id = contract_addr return CheckerAnswers.OK(flag_id="{}".format(contract_addr))
RPC_PORT = '8545' GAS = 410000 # Read the Smart Contract's file data with open('hello.sol', 'r') as f: data = f.read() # Compiling the Smart Contract contract_compiled = compile_source(data) print('Contract is compiled') # Contract interface contract_interface = contract_compiled.get('<stdin>:Hello') # Open connection to the RPC server w3 = Web3(RPCProvider(RPC_IP, RPC_PORT)) print('RPC connection to the blockchain node opened at: http://{0}:{1}'.format( RPC_IP, RPC_PORT)) # Create the contract contract = w3.eth.contract(abi=contract_interface.get('abi'), bytecode=contract_interface.get('bin')) print('Contract created') # Get the transaction Hash of the deployed contract tx_hash = contract.deploy(transaction={'from': w3.eth.accounts[0], 'gas': GAS}) print('''Contract deployed: transaction hash: {0} from account: {1} / Gas used: {2}'''.format(tx_hash, w3.eth.accounts[0], GAS)) # Wait untill the transaction will be mined! otherwise tx_receipt will be None
def __init__(self, rpc_provider=RPCProvider(host=settings.ETHEREUM_NODE_HOST, port=settings.ETHEREUM_NODE_PORT, ssl=settings.ETHEREUM_NODE_SSL)): super(Web3Service, self).__init__() self.web3 = Web3(rpc_provider)