def __init__(self, eth_url): self.web3 = Web3(HTTPProvider(eth_url))
# encoding: utf-8 from web3 import Web3, IPCProvider, WebsocketProvider, HTTPProvider import sys # w3 = Web3(Web3.WebsocketProvider('ws://0.0.0.0:31000')) # websocket #w3 = Web3(IPCProvider("/home/cc/istanbultest/qdata/dd1/geth.ipc"))#ipc w3 = Web3(HTTPProvider('http://10.50.0.2:22000')) #http rpc # init # with open('/Users/Radish/chain2/keystore/UTC--2018-05-08T11-52-01.776592127Z--f95dfc6771d82aae281dc6c7f5dae7190861fb10') as keyfile: # encrypted_key = keyfile.read() # private_key = w3.eth.account.decrypt(encrypted_key, 'correcthorsebatterystaple') keyfile = open( '/root/UTC--2019-01-23T02-49-21.786433600Z--b00df519186469ac2fc4c7d9057716ddd41728e1' ) encrypted_key = keyfile.read() private_key = w3.eth.account.decrypt(encrypted_key, '123') # 提交100000次交易 看看多久 # 看看cpu运行情况 import timeit import time base = w3.eth.getTransactionCount( Web3.toChecksumAddress("0xb00df519186469ac2fc4c7d9057716ddd41728e1")) start_ = timeit.default_timer() #for i in range(10000): while True: start = timeit.default_timer()
from statistics import mean import py_ecc.bn128.bn128_pairing as slow_pairing from py_ecc.bn128.bn128_pairing import FQ2, FQ import py_ecc.optimized_bn128.optimized_pairing as fast_pairing from web3 import Web3, HTTPProvider from solc import compile_files from math import floor import time from deploy_contract import deploy_contract, URL from examine_trans_logs import gas_usage, max_gas_usage from conversion_utility import split_g2_points, split_g1_points import equality_test if __name__ == "__main__": web3 = Web3(HTTPProvider(URL)) contract_file = "solidity_test_pairing_code.sol" contract_name = "solidity_test_pairing_code.sol:pairing_check" (contractAddr, contract_trans) = deploy_contract(contract_file, contract_name, web3, verbose=False) print("Gas used to deploy contract: ", gas_usage(contract_trans, web3)) # address no pairings: 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 # address with pairing: 0xFB88dE099e13c3ED21F80a7a1E49f8CAEcF10df6 # need contract code to know what methods can be addressed in contract on blockchain compiled = compile_files([contract_file], "--optimized") compiledCode = compiled[contract_name]
#!/usr/bin/python3 import json import hashlib import sys from web3 import Web3, HTTPProvider, IPCProvider web3 = Web3(HTTPProvider("http://localhost:9545")) #Account Class class Account: def __init__(self, choice, randonNumber, address): self.choice = choice self.randomNumber = randonNumber self.address = address def hash(self): data = int.to_bytes(self.choice, 32, "big") + int.to_bytes( self.randomNumber, 32, "big") hash_nr = hashlib.sha256(data).hexdigest() return hash_nr def play(self, hashValue, contract): contract.transact({ "from": self.address, "value": web3.toWei(1.0, "ether") }).play(Web3.toBytes(hexstr=hashValue)) def getBalance(self): balance = web3.eth.getBalance(self.address)
# log_loop(nftkey_bid_withdrawn, 30) ) ) finally: loop.close() def load_env(): dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # bnny_cont_addr_1 = os.environ.get("BNNY_CONTRACT_1") # bnny_cont_addr_2 = os.environ.get("BNNY_CONTRACT_2") nftkey_cont_addr = os.environ.get("NFTKEY_CONTRACT") telegram_bot_token = os.environ.get("TELEGRAM_BOT_TOKEN") chat_id = os.environ.get("CHAT_ID") return nftkey_cont_addr, telegram_bot_token, chat_id if __name__ == '__main__': NFTKEY_CONT_ADDR, TELEGRAM_BOT_TOKEN, CHAT_ID = load_env() # w3 = Web3(WebsocketProvider("wss://bsc-ws-node.nariox.org:443")) w3 = Web3(HTTPProvider("https://bsc-dataseed.binance.org/")) bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN) nftkey_abi = json.loads( open(join(dirname(__file__), "nftkey_abi.json")).read()) nftkey_cont = w3.eth.contract(address=NFTKEY_CONT_ADDR, abi=nftkey_abi) main()
import math,csv,time,os,random,shutil from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider import src.txFunction as txF import src.initNode as init w3 = Web3(HTTPProvider('http://localhost:8544')) # init.deployContract(w3) # init.getAvailableContract(w3) # init.checkSuccessfulContract()
group = json2['groupId'] cf.BaseUrl.set(BASE_URL) try: e = cf.Key.set(key) except: print("Incorrect subscription key") sys.exit() with open('network.json') as file: infor = json.load(file) privateKey = infor["privKey"] rpc_url = infor["rpcUrl"] web3 = Web3(HTTPProvider(rpc_url)) if args[0] == "--balance": if sizeM == 2: PINcode = args[1] Key = GenerateKey(PINcode) if Key == None: print("ID is not found") else: PrintBalance(Key) if args[0] == '--cancel': PINcode = args[1] Key = GenerateKey(PINcode) if Key == None:
import json import os from collections import OrderedDict from typing import Any, Dict, List from aea.helpers.yaml_utils import yaml_dump_all, yaml_load_all from web3 import HTTPProvider, Web3 from interface import ContractInterface try: w3 = Web3(HTTPProvider("http://ganachecli:7545")) print(w3.eth.accounts[0]) except Exception: w3 = Web3(HTTPProvider("http://127.0.0.1:7545")) print(w3.eth.accounts[0]) PATH = os.getcwd() def deploy_contracts(): contract_dir = PATH + "/contracts" deploy_dir = PATH + "/deployment_vars" print("deploy_dir", deploy_dir) # setup fake stablecoin path = PATH + "/contracts/TestContracts.sol:FakeUSD" StableCoin = ContractInterface( w3, path, contract_dir, deployment_vars_path=deploy_dir )
import TrustIndex as TI import networkx as nx import matplotlib.pyplot as plt import time import sys from datetime import datetime #ABI for smart contract import contract_abi from web3 import Web3, HTTPProvider # Load web3.py instance w3 = Web3( HTTPProvider( "https://ropsten.infura.io/v3/e3edb56114244a31b698dd92dc7cfcf7", request_kwargs={'timeout': 60})) contract = w3.eth.contract( address="0xD946eddE77A7486321D9445EC78f7b1ea0B9EA53", abi=contract_abi.abi) def main(ATR, PayloadID, seconds=300): previous = 0 while (1): TotalRecords = contract.functions.getRecordNumber() if previous != TotalRecords: print("%s - Starting update" % datetime.now().strftime('%m-%d %H:%M:%S')) UpdateRecords(ATR, PayloadID) previous = TotalRecords else: #Sleep for 5 minutes
def __init__(self, args: list, **kwargs): parser = argparse.ArgumentParser(prog='oasis-market-maker-keeper') parser.add_argument( "--endpoint-uri", type=str, help="JSON-RPC uri (example: `http://localhost:8545`)") parser.add_argument( "--rpc-host", default="localhost", type=str, help="[DEPRECATED] JSON-RPC host (default: `localhost')") parser.add_argument( "--rpc-port", default=8545, type=int, help="[DEPRECATED] JSON-RPC port (default: `8545')") parser.add_argument("--rpc-timeout", type=int, default=10, help="JSON-RPC timeout (in seconds, default: 10)") parser.add_argument( "--eth-from", type=str, required=True, help="Ethereum account from which to send transactions") parser.add_argument( "--eth-key", type=str, nargs='*', help= "Ethereum private key(s) to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass')" ) parser.add_argument("--tub-address", type=str, required=False, help="Ethereum address of the Tub contract") parser.add_argument("--oasis-address", type=str, required=True, help="Ethereum address of the OasisDEX contract") parser.add_argument( "--oasis-support-address", type=str, required=False, help="Ethereum address of the OasisDEX support contract") parser.add_argument("--buy-token-address", type=str, required=True, help="Ethereum address of the buy token") parser.add_argument("--sell-token-address", type=str, required=True, help="Ethereum address of the sell token") parser.add_argument("--buy-token-name", type=str, required=True, help="Ethereum address of the buy token") parser.add_argument("--sell-token-name", type=str, required=True, help="Ethereum address of the sell token") parser.add_argument("--buy-token-decimals", type=int, required=True, help="Ethereum address of the buy token") parser.add_argument("--sell-token-decimals", type=int, required=True, help="Ethereum address of the sell token") parser.add_argument("--config", type=str, required=True, help="Bands configuration file") parser.add_argument("--price-feed", type=str, required=True, help="Source of price feed") parser.add_argument( "--price-feed-expiry", type=int, default=120, help="Maximum age of the price feed (in seconds, default: 120)") parser.add_argument("--spread-feed", type=str, help="Source of spread feed") parser.add_argument( "--spread-feed-expiry", type=int, default=3600, help="Maximum age of the spread feed (in seconds, default: 3600)") parser.add_argument("--control-feed", type=str, help="Source of control feed") parser.add_argument( "--control-feed-expiry", type=int, default=86400, help="Maximum age of the control feed (in seconds, default: 86400)" ) parser.add_argument("--order-history", type=str, help="Endpoint to report active orders to") parser.add_argument( "--order-history-every", type=int, default=30, help= "Frequency of reporting active orders (in seconds, default: 30)") parser.add_argument( "--round-places", type=int, default=2, help="Number of decimal places to round order prices to (default=2)" ) parser.add_argument( "--min-eth-balance", type=float, default=0, help="Minimum ETH balance below which keeper will cease operation") parser.add_argument("--gas-price", type=int, default=0, help="Gas price (in Wei)") parser.add_argument( "--smart-gas-price", dest='smart_gas_price', action='store_true', help= "Use smart gas pricing strategy, based on the ethgasstation.info feed" ) parser.add_argument("--ethgasstation-api-key", type=str, default=None, help="ethgasstation API key") parser.add_argument( "--refresh-frequency", type=int, default=10, help="Order book refresh frequency (in seconds, default: 10)") parser.add_argument("--debug", dest='debug', action='store_true', help="Enable debug output") self.arguments = parser.parse_args(args) setup_logging(self.arguments) if 'web3' in kwargs: self.web3 = kwargs['web3'] elif self.arguments.endpoint_uri: self.web3: Web3 = web3_via_http(self.arguments.endpoint_uri, self.arguments.rpc_timeout) else: self.logger.warning( "Configuring node endpoint by host and port is deprecated; please use --endpoint-uri" ) self.web3 = Web3( HTTPProvider( endpoint_uri= f"http://{self.arguments.rpc_host}:{self.arguments.rpc_port}", request_kwargs={"timeout": self.arguments.rpc_timeout})) self.web3.eth.defaultAccount = self.arguments.eth_from register_keys(self.web3, self.arguments.eth_key) self.our_address = Address(self.arguments.eth_from) self.otc = MatchingMarket( web3=self.web3, address=Address(self.arguments.oasis_address), support_address=Address(self.arguments.oasis_support_address) if self.arguments.oasis_support_address else None) tub = Tub(web3=self.web3, address=Address(self.arguments.tub_address)) \ if self.arguments.tub_address is not None else None self.token_buy = ERC20Token(web3=self.web3, address=Address( self.arguments.buy_token_address)) self.token_sell = ERC20Token(web3=self.web3, address=Address( self.arguments.sell_token_address)) self.buy_token = Token(name=self.arguments.buy_token_name, address=Address( self.arguments.buy_token_address), decimals=self.arguments.buy_token_decimals) self.sell_token = Token(name=self.arguments.sell_token_name, address=Address( self.arguments.sell_token_address), decimals=self.arguments.sell_token_decimals) self.min_eth_balance = Wad.from_number(self.arguments.min_eth_balance) self.bands_config = ReloadableConfig(self.arguments.config) self.gas_price = GasPriceFactory().create_gas_price( self.web3, self.arguments) self.price_feed = PriceFeedFactory().create_price_feed( self.arguments, tub) self.spread_feed = create_spread_feed(self.arguments) self.control_feed = create_control_feed(self.arguments) self.order_history_reporter = create_order_history_reporter( self.arguments) self.history = History() self.order_book_manager = OrderBookManager( refresh_frequency=self.arguments.refresh_frequency) self.order_book_manager.get_orders_with(lambda: self.our_orders()) self.order_book_manager.place_orders_with(self.place_order_function) self.order_book_manager.cancel_orders_with(self.cancel_order_function) self.order_book_manager.enable_history_reporting( self.order_history_reporter, self.our_buy_orders, self.our_sell_orders) self.order_book_manager.start()
import time from web3 import Web3, HTTPProvider import contract_abi contract_address = '0x460d45b106a170cb6fcfb4faebb56d181c457265' wallet_private_key = '' wallet_address = '0x9eB9601d7AA4035A06db8EDC1B524bc1615e646e' w3 = Web3(HTTPProvider('https://ropsten.infura.io/v3/1813753c51d74d51b522be063421c90e')) w3.eth.enable_unaudited_features() contract_address_checksum = w3.toChecksumAddress(contract_address) contract = w3.eth.contract(address=contract_address_checksum, abi=contract_abi.abi) def send_ether_to_contract(amount_in_ether): amount_in_wei = w3.toWei(amount_in_ether, 'ether') nonce = w3.eth.getTransactionCount(wallet_address) txn_dict = { 'to': contract_address_checksum, 'value': amount_in_wei, 'gas': 2000000, 'gasPrice': w3.toWei('40', 'gwei'), 'nonce': nonce, 'chainId': 3, } signed_txn = w3.eth.account.signTransaction(txn_dict, wallet_private_key) txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
path = "C:\\Users\\wassimj\\.conda\\envs\\Blender377\\lib\\site-packages" #message = "Hello From Blender" number = 377 contract_abi = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"IPFSHash\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getIPFSHash\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"myUint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"_IPFSHash\",\"type\":\"string\"}],\"name\":\"setIPFSHash\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_myUint\",\"type\":\"uint256\"}],\"name\":\"setMyUint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" import time import sys sys.path.append(path) from web3 import Web3, HTTPProvider from topologic import Vertex, Topology import cppyy v = Vertex.ByCoordinates(10, 20, 30) message = str(v.String()) w3 = Web3(HTTPProvider(infura_url)) smartContract = w3.eth.contract(address=contract_address, abi=contract_abi) receipts = [] nonce = w3.eth.getTransactionCount(wallet_address) tx_dict = smartContract.functions.setIPFSHash(message).buildTransaction({ 'chainId': 3, 'gas': 210000, 'gasPrice': w3.toWei('50', 'gwei'), 'nonce': nonce, })
events = foreignBridge.events.UserRequestForSignature( ).processReceipt(receipt) for ev in events: nonce = _w3Home.eth.getTransactionCount(acct.address) tx_home = { "gas": 7000000, "gasPrice": gasPrice, "nonce": nonce } tx = homeBridge.functions.transferApproved( ev.args['_from'], ev.args['_tokenVIN'], ev.args['_data'], ev.transactionHash).buildTransaction(tx_home) signed_tx = acct.signTransaction(tx) tx_hash = _w3Home.eth.sendRawTransaction( signed_tx.rawTransaction) _w3Home.eth.waitForTransactionReceipt(tx_hash) print(tx_hash.hex()) writeDataBase({'blockNumber': receipt.blockNumber + 1}, lastProcessedForeignBlockPath) sleep(5) w3Home = Web3(HTTPProvider("https://sokol.poa.network/")) w3Foreign = Web3(HTTPProvider("https://kovan.infura.io/mew")) lastProcessedHomeBlockPath = "../additional_data/homeLastProcessedBlock.json" lastProcessedForeignBlockPath = "../additional_data/foreignLastProcessedBlock.json" gasPrice = Web3.toWei(1, "gwei") main(w3Home, w3Foreign)
def run_app( address, keystore_path, gas_price, eth_rpc_endpoint, registry_contract_address, secret_registry_contract_address, discovery_contract_address, listen_address, mapped_socket, max_unresponsive_time, api_address, rpc, sync_check, console, password_file, web_ui, datadir, transport, matrix_server, network_id, extra_config=None, **kwargs, ): # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument from raiden.app import App if transport == 'udp' and not mapped_socket: raise RuntimeError('Missing socket') address_hex = to_normalized_address(address) if address else None address_hex, privatekey_bin = prompt_account(address_hex, keystore_path, password_file) address = to_canonical_address(address_hex) (listen_host, listen_port) = split_endpoint(listen_address) (api_host, api_port) = split_endpoint(api_address) if datadir is None: datadir = os.path.join(os.path.expanduser('~'), '.raiden') config = deepcopy(App.DEFAULT_CONFIG) if extra_config: merge_dict(config, extra_config) config['transport']['udp']['host'] = listen_host config['transport']['udp']['port'] = listen_port config['console'] = console config['rpc'] = rpc config['web_ui'] = rpc and web_ui config['api_host'] = api_host config['api_port'] = api_port if mapped_socket: config['socket'] = mapped_socket.socket config['transport']['udp']['external_ip'] = mapped_socket.external_ip config['transport']['udp'][ 'external_port'] = mapped_socket.external_port config['transport_type'] = transport config['transport']['matrix']['server'] = matrix_server config['transport']['udp'][ 'nat_keepalive_retries'] = DEFAULT_NAT_KEEPALIVE_RETRIES timeout = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES config['transport']['udp']['nat_keepalive_timeout'] = timeout privatekey_hex = hexlify(privatekey_bin) config['privatekey_hex'] = privatekey_hex parsed_eth_rpc_endpoint = urlparse(eth_rpc_endpoint) if not parsed_eth_rpc_endpoint.scheme: eth_rpc_endpoint = f'http://{eth_rpc_endpoint}' web3 = Web3(HTTPProvider(eth_rpc_endpoint)) try: node_version = web3.version.node # pylint: disable=no-member except ConnectTimeout: raise EthNodeCommunicationError( "Couldn't connect to the ethereum node") supported, _ = is_supported_client(node_version) if not supported: print( 'You need a Byzantium enabled ethereum node. Parity >= 1.7.6 or Geth >= 1.7.2' ) sys.exit(1) rpc_client = JSONRPCClient( web3, privatekey_bin, gasprice=gas_price, ) blockchain_service = BlockChainService(privatekey_bin, rpc_client) net_id = blockchain_service.network_id if net_id != network_id: if network_id in constants.ID_TO_NETWORKNAME and net_id in constants.ID_TO_NETWORKNAME: print(( "The chosen ethereum network '{}' differs from the ethereum client '{}'. " 'Please update your settings.').format( constants.ID_TO_NETWORKNAME[network_id], constants.ID_TO_NETWORKNAME[net_id])) else: print(( "The chosen ethereum network id '{}' differs from the ethereum client '{}'. " 'Please update your settings.').format(network_id, net_id)) sys.exit(1) config['chain_id'] = network_id if sync_check: check_synced(blockchain_service) database_path = os.path.join(datadir, 'netid_%s' % net_id, address_hex[:8], 'log.db') config['database_path'] = database_path print( '\nYou are connected to the \'{}\' network and the DB path is: {}'. format( constants.ID_TO_NETWORKNAME.get(net_id) or net_id, database_path, ), ) contract_addresses_given = (registry_contract_address is not None and secret_registry_contract_address is not None and discovery_contract_address is not None) contract_addresses_known = net_id in constants.ID_TO_NETWORK_CONFIG if not contract_addresses_given and not contract_addresses_known: print(( "There are known contract addresses for network id '{}'. Please provide " 'them in the command line or the configuration file.' ).format(net_id)) sys.exit(1) contract_addresses = constants.ID_TO_NETWORK_CONFIG.get(net_id, dict()) try: token_network_registry = blockchain_service.token_network_registry( registry_contract_address or contract_addresses[CONTRACT_TOKEN_NETWORK_REGISTRY], ) except ContractVersionMismatch: handle_contract_version_mismatch('token network registry', registry_contract_address) except AddressWithoutCode: handle_contract_no_code('token network registry', registry_contract_address) except AddressWrongContract: handle_contract_wrong_address('token network registry', registry_contract_address) try: secret_registry = blockchain_service.secret_registry( secret_registry_contract_address or contract_addresses[CONTRACT_SECRET_REGISTRY], ) except ContractVersionMismatch: handle_contract_version_mismatch('secret registry', secret_registry_contract_address) except AddressWithoutCode: handle_contract_no_code('secret registry', secret_registry_contract_address) except AddressWrongContract: handle_contract_wrong_address('secret registry', secret_registry_contract_address) discovery = None if transport == 'udp': check_discovery_registration_gas(blockchain_service, address) try: dicovery_proxy = blockchain_service.discovery( discovery_contract_address or contract_addresses[CONTRACT_ENDPOINT_REGISTRY], ) discovery = ContractDiscovery( blockchain_service.node_address, dicovery_proxy, ) except ContractVersionMismatch: handle_contract_version_mismatch('discovery', discovery_contract_address) except AddressWithoutCode: handle_contract_no_code('discovery', discovery_contract_address) except AddressWrongContract: handle_contract_wrong_address('discovery', discovery_contract_address) throttle_policy = TokenBucket( config['transport']['udp']['throttle_capacity'], config['transport']['udp']['throttle_fill_rate'], ) transport = UDPTransport( discovery, mapped_socket.socket, throttle_policy, config['transport']['udp'], ) elif transport == 'matrix': try: transport = MatrixTransport(config['transport']['matrix']) except RaidenError as ex: click.secho(f'FATAL: {ex}', fg='red') sys.exit(1) else: raise RuntimeError(f'Unknown transport type "{transport}" given') try: chain_config = constants.ID_TO_NETWORK_CONFIG.get(net_id, {}) start_block = chain_config.get(constants.START_QUERY_BLOCK_KEY, 0) raiden_app = App( config=config, chain=blockchain_service, query_start_block=start_block, default_registry=token_network_registry, default_secret_registry=secret_registry, transport=transport, discovery=discovery, ) except RaidenError as e: click.secho(f'FATAL: {e}', fg='red') sys.exit(1) try: raiden_app.start() except filelock.Timeout: name_or_id = constants.ID_TO_NETWORKNAME.get(network_id, network_id) print( f'FATAL: Another Raiden instance already running for account {address_hex} on ' f'network id {name_or_id}', ) sys.exit(1) return raiden_app
def __init__( self, host: str, port: int, privkey: bytes, gasprice: int = None, nonce_update_interval: float = 5.0, nonce_offset: int = 0, web3: Web3 = None, ): if privkey is None or len(privkey) != 32: raise ValueError('Invalid private key') endpoint = 'http://{}:{}'.format(host, port) self.port = port self.privkey = privkey self.sender = privatekey_to_address(privkey) # Needs to be initialized to None in the beginning since JSONRPCClient # gets constructed before the RaidenService Object. self.stop_event = None self.nonce_last_update = 0 self.nonce_available_value = None self.nonce_lock = Semaphore() self.nonce_update_interval = nonce_update_interval self.nonce_offset = nonce_offset self.given_gas_price = gasprice cache = cachetools.TTLCache( maxsize=1, ttl=RPC_CACHE_TTL, ) cache_wrapper = cachetools.cached(cache=cache) self.gaslimit = cache_wrapper(self._gaslimit) cache = cachetools.TTLCache( maxsize=1, ttl=RPC_CACHE_TTL, ) cache_wrapper = cachetools.cached(cache=cache) self.gasprice = cache_wrapper(self._gasprice) # web3 if web3 is None: self.web3: Web3 = Web3(HTTPProvider(endpoint)) else: self.web3 = web3 try: # we use a PoA chain for smoketest, use this middleware to fix this self.web3.middleware_stack.inject(geth_poa_middleware, layer=0) except ValueError: # `middleware_stack.inject()` raises a value error if the same middleware is # injected twice. This happens with `eth-tester` setup where a single session # scoped web3 instance is used for all clients pass supported, self.eth_node = is_supported_client(self.web3.version.node) if not supported: print( 'You need a Byzantium enabled ethereum node. Parity >= 1.7.6 or Geth >= 1.7.2' ) sys.exit(1) # create the connection test middleware (but only for non-tester chain) if not hasattr(web3, 'testing'): connection_test = make_connection_test_middleware(self) self.web3.middleware_stack.inject(connection_test, layer=0)
def from_http_provider(cls, http_provider, contract_address, abi): return cls(Web3(HTTPProvider(http_provider)), contract_address, abi)
from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider import json with open('Full path to contract ABI') as f: abi = json.load(f) w3 = Web3(HTTPProvider('https://rpc.tomochain.com')) contract_address = '0xd432Ff87E9F6BF8AACE8866eD351435EBDD1Ec00' contract_address = Web3.toChecksumAddress(contract_address) contract = w3.eth.contract(address = contract_address, abi = abi) def check_certification(tokenId): tokenId = int(tokenId) tx_receipt = contract.functions.viewcert(tokenId).call() return(tx_receipt) def check_owner(tokenId): tokenId = int(tokenId) tx_receipt = contract.functions.ownerOf(tokenId).call() return(tx_receipt) tokenId = 0 print (check_owner(tokenId)) print (check_certification(tokenId))
def reload_http_provider(self, http_provider): self.w3 = Web3(HTTPProvider(http_provider))
import argparse import json import socket from web3 import Web3, HTTPProvider PROVIDER = "http://127.0.0.1:8545" ABI_DIRECTORY = "../build/contracts/Ponte.json" W3 = Web3(HTTPProvider(PROVIDER)) class Client(object): """ Our client to interact with the smart contract Attributes: contract_address (string): the address of the main contract contract (Contract): a Contract object that we can use to access functions """ def __init__(self, contract_address): self.contract_address = contract_address with open(ABI_DIRECTORY) as f: info_json = json.load(f) abi = info_json["abi"] self.contract = W3.eth.contract(address=self.contract_address, abi=abi) def retrieve_captcha(self): """ Gets most recent command from contract
import argparse import json import sys import requests import time from web3 import Web3, HTTPProvider web3 = Web3(HTTPProvider('https://sokol.poa.network')) import service_function def key_to_value(args): if args.list == "add": print("Add") if args.list == "del": print("Del") if args.confirm != " ": pin_code = args.confirm c = open('person.json', 'r') account_config = json.load(c) uuid = str(account_config['id']) uuid = uuid.replace('-', '') private_key = service_function.generate_private_key(uuid=uuid, pin_code=pin_code) address_for_confirm = web3.eth.account.privateKeyToAccount( private_key).address #print(address_for_confirm) try: d = open('registrar.json', 'r') contract_config = json.load(d) contract_address = str(contract_config['registrar']['address']) try:
def attempt_connect(self, ethrpc_port: int, mainnet_check=True) -> Tuple[bool, str]: if self.rpc_port == ethrpc_port and self.connected: # We are already connected return True, 'Already connected to an ethereum node' if self.web3: del self.web3 try: self.web3 = Web3( HTTPProvider('http://localhost:{}'.format(ethrpc_port))) except ConnectionError: log.warning( 'Could not connect to a local ethereum node. Will use etherscan only' ) self.connected = False return False, 'Failed to connect to ethereum node at port {}'.format( ethrpc_port) if self.web3.isConnected(): dir_path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dir_path, 'data', 'token_abi.json'), 'r') as f: self.token_abi = rlk_jsonloads(f.read()) # Also make sure we are actually connected to the Ethereum mainnet if mainnet_check: genesis_hash = self.web3.eth.getBlock(0)['hash'].hex() # pylint: disable=no-member target = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' if genesis_hash != target: log.warning( 'Connected to a local ethereum node but it is not on the ethereum mainnet', ) self.connected = False message = ( 'Connected to ethereum node at port {} but it is not on ' 'the ethereum mainnet'.format(ethrpc_port)) return False, message if self.web3.eth.syncing: # pylint: disable=no-member current_block = self.web3.eth.syncing.currentBlock # pylint: disable=no-member latest_block = self.web3.eth.syncing.highestBlock # pylint: disable=no-member return self.is_synchronized(current_block, latest_block) else: current_block = self.web3.eth.blockNumber # pylint: disable=no-member latest_block = self.query_eth_highest_block() if latest_block is None: return False, 'Could not query latest block from blockcypher.' return self.is_synchronized(current_block, latest_block) self.connected = True return True, '' else: log.warning( 'Could not connect to a local ethereum node. Will use etherscan only' ) self.connected = False message = 'Failed to connect to ethereum node at port {}'.format( ethrpc_port) # If we get here we did not connnect return False, message
import os import json from web3 import Web3, HTTPProvider from pprint import pprint from web3.middleware import geth_poa_middleware contract_address = os.getenv('CONTRACT_ADDRESS') private_key = os.getenv('PRIVATE_KEY') #Also the mnemonic infura_key = os.getenv('INFURA_KEY') w3 = Web3(HTTPProvider('http://127.0.0.1:9545')) w3.middleware_onion.inject(geth_poa_middleware, layer=0) pprint(f'First Account being used is: {w3.eth.accounts[0]}') with open('build/contracts/S3FileStorage.json') as f: info = json.load(f) abi = info['abi'] # This is the address of the contract contract = w3.eth.contract(address=contract_address, abi=abi) pprint(contract.all_functions()) estimated_gas = contract.functions.addFileReference('tripid1', 'someurl', 'somehash').estimateGas() pprint(f"Estimating Gas price for addFileReference: {estimated_gas}") transaction = contract.functions.addFileReference( 'tripid1', 'someurl', 'somehash').buildTransaction()
def web3_instance(): return Web3(HTTPProvider(get_keeper_url()))
# HadesCoin go to the moon # # $$ $$ $$$$$$ $$$$$$$$ $$$$$$$$$ $$$$$$$$ # $$ $$ $$ $$ $$ $$ $$ $$ # $$ $$ $$ $$ $$ $$ $$ $$ # $$$$$$$$ $$$$$$$$ $$ $$ $$$$$$$$$ $$$$$$$$ # $$ $$ $$ $$ $$ $$ $$ $$ # $$ $$ $$ $$ $$ $$ $$ $$ # $$ $$ $$ $$ $$$$$$$$ $$$$$$$$$ $$$$$$$$ # import os,sys,time,re,xlrd from web3 import Web3, HTTPProvider import rlp from ethereum.transactions import Transaction #web3 = Web3(HTTPProvider('http://127.0.0.1:8545')) #local eth wallet web3 = Web3(HTTPProvider('https://mainnet.infura.io/')) workbook=xlrd.open_workbook('sendethallto1.xlsx') table=workbook.sheet_by_index(0) nrows = table.nrows if __name__ == '__main__': i=2 toAddress=table.cell(1,0).value print("toAddr:",toAddress) gasLimit=table.cell(1,1).value gasPrice=table.cell(1,2).value ethValue=table.cell(1,3).value #print(fromAddress,privateKey,gasLimit,gasPrice,ethValue) #nrows=3 sucess=0 while i<nrows:
from marketing.mails import ( grant_cancellation, new_grant, new_grant_admin, new_supporter, subscription_terminated, support_cancellation, thank_you_for_supporting, ) from marketing.models import Keyword, Stat from retail.helpers import get_ip from townsquare.models import Comment from web3 import HTTPProvider, Web3 logger = logging.getLogger(__name__) w3 = Web3(HTTPProvider(settings.WEB3_HTTP_PROVIDER)) clr_matching_banners_style = 'pledging' matching_live = '($200K matching live now!) ' total_clr_pot = 200000 clr_round = 4 clr_active = False show_clr_card = True next_round_start = timezone.datetime(2020, 3, 23) if True: clr_matching_banners_style = 'results' matching_live = '' def get_keywords():
def __init__( self, account: Account, chain_urls: Dict[str, List[str]], auth: str, data_path: Path, scenario_file: Path, ): from scenario_player.tasks.base import get_task_class_for_type from scenario_player.node_support import RaidenReleaseKeeper, NodeController self.task_count = 0 self.running_task_count = 0 self.auth = auth self.release_keeper = RaidenReleaseKeeper( data_path.joinpath('raiden_releases')) self.task_cache = {} self.task_storage = defaultdict(dict) self.scenario_name = os.path.basename( scenario_file.name).partition('.')[0] self.scenario = yaml.load(scenario_file) self.scenario_version = self.scenario.get('version', 1) if self.scenario_version not in SUPPORTED_SCENARIO_VERSIONS: raise ScenarioError( f'Unexpected scenario version {self.scenario_version}') self.data_path = data_path.joinpath('scenarios', self.scenario_name) self.data_path.mkdir(exist_ok=True, parents=True) log.debug('Data path', path=self.data_path) self.run_number = 0 run_number_file = self.data_path.joinpath('run_number.txt') if run_number_file.exists(): self.run_number = int(run_number_file.read_text()) + 1 run_number_file.write_text(str(self.run_number)) log.info('Run number', run_number=self.run_number) nodes = self.scenario['nodes'] node_mode = NodeMode.EXTERNAL.name if self.is_v2: node_mode = nodes.get('mode', '').upper() if not node_mode: raise ScenarioError( 'Version 2 scenarios require a "mode" in the "nodes" section.' ) try: self.node_mode = NodeMode[node_mode] except KeyError: known_modes = ', '.join(mode.name.lower() for mode in NodeMode) raise ScenarioError( f'Unknown node mode "{node_mode}". Expected one of {known_modes}', ) from None if self.is_managed: self.node_controller = NodeController( self, nodes.get('raiden_version', 'LATEST'), nodes['count'], nodes.get('default_options', {}), nodes.get('node_options', {}), ) else: if 'range' in nodes: range_config = nodes['range'] template = range_config['template'] self.raiden_nodes = [ template.format(i) for i in range(range_config['first'], range_config['last'] + 1) ] else: self.raiden_nodes = nodes['list'] self.node_commands = nodes.get('commands', {}) settings = self.scenario.get('settings') if settings is None: settings = {} self.timeout = settings.get('timeout', TIMEOUT) if self.is_managed: self.protocol = 'http' if 'protocol' in settings: log.warning( 'The "protocol" setting is not supported in "managed" node mode.' ) else: self.protocol = settings.get('protocol', 'http') self.notification_email = settings.get('notify') self.chain_name = settings.get('chain', 'any') if self.chain_name == 'any': self.chain_name = random.choice(list(chain_urls.keys())) elif self.chain_name not in chain_urls: raise ScenarioError( f'The scenario requested chain "{self.chain_name}" for which no RPC-URL is known.', ) log.info('Using chain', chain=self.chain_name) self.eth_rpc_urls = chain_urls[self.chain_name] self.client = JSONRPCClient( Web3(HTTPProvider(chain_urls[self.chain_name][0])), privkey=account.privkey, gas_price_strategy=get_gas_price_strategy( settings.get('gas_price', 'fast')), ) self.chain_id = self.client.web3.net.version self.contract_manager = ContractManager(contracts_precompiled_path()) balance = self.client.balance(account.address) if balance < OWN_ACCOUNT_BALANCE_MIN: raise ScenarioError( f'Insufficient balance ({balance / 10 ** 18} Eth) ' f'in account {to_checksum_address(account.address)} on chain "{self.chain_name}"', ) self.session = Session() # WTF? https://github.com/requests/requests/issues/2605 if auth: self.session.auth = tuple(auth.split(":")) self.session.mount('http', TimeOutHTTPAdapter(timeout=self.timeout)) self.session.mount('https', TimeOutHTTPAdapter(timeout=self.timeout)) self._node_to_address = None self.token_address = None self.token_deployment_block = 0 scenario_config = self.scenario.get('scenario') if not scenario_config: raise ScenarioError( "Invalid scenario definition. Missing 'scenario' key.") try: (root_task_type, root_task_config), = scenario_config.items() except ValueError: # will be thrown if it's not a 1-element dict raise ScenarioError( "Invalid scenario definition. " "Exactly one root task is required below the 'scenario' key.", ) from None task_class = get_task_class_for_type(root_task_type) self.root_task = task_class(runner=self, config=root_task_config)
def __init__(self, args: list): # Define basic arguments parser = argparse.ArgumentParser(prog='plunger') parser.add_argument( "address", help="Ethereum address to check for pending transactions", type=str) parser.add_argument("--rpc-host", help="JSON-RPC host (default: `localhost')", default="localhost", type=str) parser.add_argument("--rpc-port", help="JSON-RPC port (default: `8545')", default=8545, type=int) parser.add_argument( "--gas-price", help="Gas price (in Wei) for overriding transactions", default=0, type=int) parser.add_argument( "--source", help= f"Comma-separated list of sources to use for pending transaction discovery" f" (available: {self.SOURCE_PARITY_TXQUEUE}, {self.SOURCE_JSONRPC_GETBLOCK})", type=lambda x: x.split(','), required=True) # Define mutually exclusive action arguments action = parser.add_mutually_exclusive_group(required=True) action.add_argument('--list', help="List pending transactions", dest='list', action='store_true') action.add_argument('--wait', help="Wait for the pending transactions to clear", dest='wait', action='store_true') action.add_argument( '--override-with-zero-txs', help="Override the pending transactions with zero-value txs", dest='override', action='store_true') parser.add_argument( "--eth-key", type=str, help= "Ethereum private key to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass') for unlocking account" ) # Parse the arguments, validate source self.arguments = parser.parse_args(args) # Initialize pending transactions list self.transactions = [] # Initialize web3.py if self.arguments.rpc_host.startswith("http"): endpoint_uri = f"{self.arguments.rpc_host}:{self.arguments.rpc_port}" else: endpoint_uri = f"http://{self.arguments.rpc_host}:{self.arguments.rpc_port}" self.web3 = Web3(HTTPProvider(endpoint_uri=endpoint_uri)) self.web3.eth.defaultAccount = self.arguments.address if self.arguments.eth_key: register_key(self.web3, self.arguments.eth_key) self.validate_sources(self.web3)
def revealvote(request, poll_id, nounce, vote): # get question object question = get_object_or_404(Question, pk=poll_id) publishDate = question.pub_date pwd = os.path.dirname(__file__) if _pollActive(publishDate): return HttpResponse('poll is still active, ' + 'cannot reveal vote now.', content_type='text/plain') # need to send the poll to blockchain print(poll_id, nounce, vote) http_provider = HTTPProvider('http://localhost:8545') eth_provider = Web3(http_provider).eth contract_abi = pickle.load( open(pwd + "/../conf/" + str(poll_id) + "contract_abi", 'rb')) contract_address = pickle.load( open(pwd + "/../conf/" + str(poll_id) + "contract_address", 'rb')) ConciseContract = pickle.load( open(pwd + "/../conf/" + str(poll_id) + "ConciseContract", 'rb')) contract_instance = eth_provider.contract( abi=contract_abi, address=contract_address, ContractFactoryClass=ConciseContract, ) default_account = eth_provider.accounts[0] transaction_details = { 'from': default_account, } vote = int(vote) nonce = nounce.encode().hex() hexvote = hex(vote)[2:] if (vote < 16): hexvote = '0' + hexvote revealval = '0x' + nonce + hexvote contract_instance.revealVote(revealval, transact=transaction_details) # time.sleep(31) # contract_instance.countVotes(transact=transaction_details) # num_votes = [] # for i in range(10): # count_vote = contract_instance.voteCountCandidate(i) # num_votes.append(count_vote) # print (num_votes) return HttpResponse('your vote has been reveal in blockchain, ' + 'hold back for results :)', content_type='text/plain')
from werkzeug.exceptions import HTTPException app = Flask(__name__, static_url_path="", static_folder="static") CORS(app) app.config.from_object('crypto_predict.config.DevConfig') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False handler = RotatingFileHandler('crypto_predict.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.INFO) app.logger.addHandler(handler) db = SQLAlchemy(app) w3 = Web3(HTTPProvider(app.config["RPC_PROVIDER"])) ######################### # JWT Handler ######################### from crypto_predict.models.user import UserModel def authenticate(username, password): user = UserModel.query.filter_by(user_name=username).first() if user and safe_str_cmp( user.password.encode('utf-8'), hashlib.md5(str(password).encode('utf-8')).hexdigest()): return user
import os import sys from werkzeug.utils import secure_filename from flask import Flask, send_from_directory, render_template, request, redirect, url_for from web3 import Web3, HTTPProvider import json import ipfsapi web3=Web3(HTTPProvider('http://*****:*****@app.route('/', methods=['GET', 'POST']) def index(): if request.method == "POST": try: r = request.form['isMobile'] except: r = None username = request.form['username'] password = request.form['password']