def __init__(self, settings): self.apiurl: str = settings["apiUrl"] self.testmode = False if "providerType" in settings: pT = settings["providerType"] if pT == "HTTPProvider": self.provider: Web3 = Web3( HTTPProvider(settings["providerUrl"])) elif pT == "IPCProvider": self.provider: Web3 = Web3(IPCProvider( settings["providerUrl"])) elif pT == "WebsocketProvider": self.provider: Web3 = Web3( WebsocketProvider(settings["providerUrl"])) else: self.provider: Web3 = Web3(HTTPProvider(settings["providerUrl"])) if "mnemonicKey" in settings: self.wallet: Account = Account.privateKeyToAccount( mnemonic_to_private_key(settings["mnemonicKey"])) if "privateKey" in settings: self.wallet: Account = Account.privateKeyToAccount( str(settings["privateKey"])) self.blockchain: str = str(settings["blockchain"]).lower() self.myaddress: str = self.wallet.address self.query = RequestManager(self.apiurl, self.provider, self.wallet, self.blockchain) if "testMode" in settings: if bool(settings["testMode"]) == True: print("TEST MODE ENABLED, TRANSACTION WONT BE BROADCASTED") self.testmode = True # The following flag values default to False, to allow the simplest and best trading experience for most users. # SBTKN False means TRADES ARE REQUESTED IN DECIMAL TOKEN UNITS. True means they are requested in integer subtoken units. # BNDL False means WE DO NOT ALLOW BUNDLE PRICING ON NEW ORDERS, ONLY INTEGER PRICES. True means we allow Fraction prices. # STRICT False means WE CREATE OR EXECUTE NEAREST VALID TRADE <= REQUESTED TRADE. True means invalid trades throw an error. # These flags can and should be ignored and left out of function calls unless the user wants to change them. self.SBTKN = False self.STRICT = False self.BNDL = False self.DEBUG = False if "SBTKN" in settings: self.SBTKN = settings["SBTKN"] if "STRICT" in settings: self.STRICT = settings["STRICT"] if "BNDL" in settings: self.BNDL = settings["BNDL"] if "DEBUG" in settings: self.DEBUG = settings["DEBUG"] self.exchange = ExchangeInterface(self.provider, self.wallet, self.query, self.blockchain, self.testmode, self.SBTKN, self.STRICT, self.BNDL, self.DEBUG) print("TRADING WALLET: " + self.myaddress)
async def test_lnd_create_wallet(fee_mocker, lnd_helper): lnd = Lendingblock() addr1, priv1 = await lnd.create_wallet() pattern_address = re.compile('^(0x)[0-9a-fA-F]{40}$') pattern_private = re.compile('^(0x)[0-9a-fA-F]{64}$') assert pattern_address.match(addr1) assert pattern_private.match(priv1) assert eth_utils.is_checksum_address(addr1) is True assert Account.privateKeyToAccount(priv1).address == addr1 priv2 = ( '0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364') addr2 = '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' assert Account.privateKeyToAccount(priv2).address == addr2
def get_eth_wallet_private_key() -> Optional[str]: ethereum_wallet = global_config_map.get("ethereum_wallet").value if ethereum_wallet is None or ethereum_wallet == "": return None private_key = Security._private_keys[ethereum_wallet] account = Account.privateKeyToAccount(private_key) return account.privateKey.hex()
def transction(text, name): w3 = Web3( Web3.HTTPProvider( 'https://mainnet.infura.io/9dhHYFuxJixnXwEdnwIy ')) #连接到Eth的远程节点 priv_key = env_dist['BLOCK_KEY'] #爱链的eth账户的私钥 account = Account.privateKeyToAccount(priv_key) #通过私钥得到公钥也就是账户地址 nonce = w3.eth.getTransactionCount( account.address) #通) #通过返回指定地址发起的交易数,得到防止重放攻击的数字 # data=Web3.toHex(str.encode(text+'——'+name))#交易附加的信息,需要将字符串转换为16进制编码,需要前端传递来需要保存的数据 data = Web3.toHex(str.encode(text + ' ' + name)) payload = { 'to': '0x8Fe2Af03Ed1d362371261AB33C400F24fBB82D8f', 'value': 0, 'gas': 200000, #运算步数的上限 'gasPrice': Web3.toWei(3, 'gwei'), #每一步运算耗费的Eth 'nonce': nonce, 'data': data } signed = account.signTransaction(payload) #打包 # estimation = w3.eth.estimateGas(payload) # print(estimation) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) #生成裸交易,得到交易号 # receipt = w3.eth.waitForTransactionReceipt(tx_hash) #通过交易号得到交易的信息,一般需要等1分钟 # print('hash: '+tx_hash) tx_hash = ''.join(['%02x' % b for b in tx_hash]) return tx_hash
def main(): ''' Main method. Runs the program if it is used standalone (rather than as an exported library). ''' parser = _get_args() #prov = Web3.HTTPProvider(parser.rpc_url) # not necessary if using infura #w3 = Web3(prov) with open('./compiles/Registry.abi', 'r') as f: abi = json.loads(f.read()) with open('./compiles/Registry.bin', 'r') as f: content = f.read() acct = Account.privateKeyToAccount(parser.key) pool_addr = acct.address tx = { 'from': pool_addr, 'gasPrice': 3000000000, 'gas': 2000000, 'value': 0, 'data': content } tx['nonce'] = w3.eth.getTransactionCount(tx['from']) signed_tx = w3.eth.account.signTransaction(tx, parser.key) sent = w3.eth.sendRawTransaction(signed_tx.rawTransaction) receipt = w3.eth.waitForTransactionReceipt(sent) print(receipt)
def register_private_key(web3: Web3, private_key): assert (isinstance(web3, Web3)) account = Account.privateKeyToAccount(private_key) _registered_accounts[(web3, Address(account.address))] = account web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
def priv_key_to_account(coin_type, priv_key): for coin_type in coins: if coin_type == 'ETH': return Account.privateKeyToAccount(priv_key) elif coin_type == 'BTCTEST': return PrivateKeyTestnet(priv_key)
def __init__(self, web3, config_file, metadata_contract=None): self._oceandb = OceanDb(config_file).plugin self._other_db_index = f'{self._oceandb.driver.db_index}_plus' self._oceandb.driver.es.indices.create(index=self._other_db_index, ignore=400) self._web3 = web3 self._pool_monitor = None if bool(int(os.getenv('PROCESS_POOL_EVENTS', 1)) == 1): self._pool_monitor = MetadataUpdater( self._oceandb, self._other_db_index, self._web3, ConfigProvider.get_config() ) if not metadata_contract: metadata_contract = get_metadata_contract(self._web3) self._contract = metadata_contract self._contract_address = self._contract.address self._ecies_private_key = os.getenv('EVENTS_ECIES_PRIVATE_KEY', '') self._ecies_account = None if self._ecies_private_key: self._ecies_account = Account.privateKeyToAccount(self._ecies_private_key) metadata_block = int(os.getenv('METADATA_CONTRACT_BLOCK', 0)) try: self.get_last_processed_block() except Exception: self.store_last_processed_block(metadata_block) allowed_publishers = set() try: publishers_str = os.getenv('ALLOWED_PUBLISHERS', '') allowed_publishers = set(json.loads(publishers_str)) if publishers_str else set() except (JSONDecodeError, TypeError, Exception) as e: logger.error(f'Reading list of allowed publishers failed: {e}\n' f'ALLOWED_PUBLISHER is set to "{os.getenv("ALLOWED_PUBLISHER")}"') self._allowed_publishers = set(sanitize_addresses(allowed_publishers)) logger.debug(f'allowed publishers: {self._allowed_publishers}') logger.debug(f'EventsMonitor: using Metadata contract address {self._contract_address}.') self._monitor_is_on = False default_sleep_time = 10 try: self._monitor_sleep_time = int(os.getenv('OCN_EVENTS_MONITOR_QUITE_TIME', default_sleep_time)) except ValueError: self._monitor_sleep_time = default_sleep_time self._monitor_sleep_time = max(self._monitor_sleep_time, default_sleep_time) if not self._contract or not self._web3.isAddress(self._contract_address): logger.error( f"Contract address {self._contract_address} is not a valid address. Events thread not starting") self._contract = None self._purgatory_enabled = bool(int(os.getenv('PROCESS_PURGATORY', 1)) == 1) self._purgatory_list = set() self._purgatory_update_time = None
def audit(pri_key, doc_id, hash): """ 審核 pri_key: str : 新增文件的人的私鑰 doc_id: str : 文件id hash: str : 審核內容的hash """ try: web3 = AuditDocContractService.get_web3_client() account = Account.privateKeyToAccount(pri_key) web3.eth.defaultAccount = account.address contract = AuditDocContractService.get_contract(web3) params = { 'from': account.address, 'nonce': web3.eth.getTransactionCount(account.address), 'gasPrice': web3.toWei('50', 'gwei') } transaction = contract.functions.audit( doc_id, hash).buildTransaction(params) signed_txn = web3.eth.account.signTransaction( transaction, private_key=account.privateKey) tx_id = web3.eth.sendRawTransaction(signed_txn.rawTransaction) return tx_id.hex() except Exception as e: print(str(e)) return None
def handle(self, *args, **options): ethereum_client = EthereumClientProvider() proxy_factory_address = settings.SAFE_PROXY_FACTORY_ADDRESS deployer_key = options['deployer_key'] deployer_account = Account.privateKeyToAccount( deployer_key) if deployer_key else self.DEFAULT_ACCOUNT self.stdout.write( self.style.SUCCESS( 'Checking if proxy factory was already deployed on %s' % proxy_factory_address)) if ethereum_client.is_contract(proxy_factory_address): self.stdout.write( self.style.NOTICE('Proxy factory was already deployed on %s' % proxy_factory_address)) else: self.stdout.write( self.style.SUCCESS( 'Deploying proxy factory using deployer account, ' 'proxy factory %s not found' % proxy_factory_address)) proxy_factory_address = ProxyFactory.deploy_proxy_factory_contract( ethereum_client, deployer_account=deployer_account).contract_address self.stdout.write( self.style.SUCCESS('Proxy factory has been deployed on %s' % proxy_factory_address))
def priv_key_to_account(coin, priv_key): if (coin == ETH): return Account.privateKeyToAccount(priv_key) elif (coin == BTCTEST): return PrivateKeyTestnet(priv_key) else: return None
def priv_key_to_account(coin, priv_key): if coin == BTCTEST: return bit.PrivateKeyTestnet(priv_key) elif coin == ETH: return Account.privateKeyToAccount(priv_key) else: print('Must use either BTCTEST or ETH')
def __init__(self, pool, node, pk, gas_multiplier, uniswapex_addr, whitelisted): self.pool = pool self.node = node self.w3 = Web3(Web3.HTTPProvider(node)) self.watcher = Watcher(self.w3) self.internal_nonce = 0 self.gas_multiplier = gas_multiplier self.account = Account.privateKeyToAccount(pk.replace('0x', '')) self.w3.eth.setGasPriceStrategy(fast_gas_price_strategy) self.whitelisted_tokens = set() for token in whitelisted.split(','): self.whitelisted_tokens.add(token.lower()) self.uniswap_ex = self.w3.eth.contract( address=self.w3.toChecksumAddress(uniswapex_addr), abi=uniswap_ex.abi, ) self.uniswap_ex_concise = ConciseContract(self.uniswap_ex) def on_block(block_number): logger.debug("Executor on block {}".format(block_number)) self.check_open_orders() self.watcher.on_new_block(on_block) logger.info("Using account {}".format(self.account.address))
def patch(self): """ Create new transfer """ # TODO add check for address format # HTTPServerRequest(protocol='http', host='18.185.116.64:8000', method='PATCH', uri='/transfer', version='HTTP/1.1', remote_ip='178.95.234.243') # Traceback (most recent call last): # File "/home/nynja/NynjaWalletPy/.env/lib/python3.5/site-packages/tornado/web.py", line 1590, in _execute # result = method(*self.path_args, **self.path_kwargs) # File "/home/nynja/NynjaWalletPy/api/handlers/transfer.py", line 48, in patch # 'to': checksum(required_params['address_to']), # File "/home/nynja/NynjaWalletPy/blockchain/helpers.py", line 26, in checksum # adr = Web3.toChecksumAddress(adr) # File "/home/nynja/NynjaWalletPy/.env/lib/python3.5/site-packages/eth_utils/address.py", line 113, in to_checksum_address # norm_address = to_normalized_address(address) # File "/home/nynja/NynjaWalletPy/.env/lib/python3.5/site-packages/eth_utils/address.py", line 68, in to_normalized_address # "Unknown format {}, attempted to normalize to {}".format(address, hex_address) # ValueError: Unknown format 0x82538f8d2a2fff835ae2b62c46ba0799e261df509643003039ac951b0ffd24a0, attempted to normalize to 0x82538f8d2a2fff835ae2b62c46ba0799e261df509643003039ac951b0ffd24a0 logger.info("WalletTransfer/Patch: {0}".format(self.request_body)) required_param_names = ['address_to', 'amount', 'private_key'] required_params = self.get_request_params(required_param_names) # check for missing params missed_param_names = self.missing_required_params( required_param_names, required_params) if missed_param_names: return self.failure(message=MISSED_REQUIRED_PARAMS.format( ', '.join(missed_param_names))) w3 = blockchain_connection() addr_from = Account.privateKeyToAccount( Web3.toBytes(hexstr=required_params['private_key'])).address transaction = { 'gasPrice': w3.eth.gasPrice, 'value': required_params['amount'], 'to': checksum(required_params['address_to']), 'nonce': w3.eth.getTransactionCount(checksum(addr_from)) } gas_estimate = w3.eth.estimateGas(transaction) transaction['gas'] = gas_estimate logger.info("WalletTransfer.Transaction: {0}".format(transaction)) signed = w3.eth.account.signTransaction(transaction, required_params['private_key']) try: hash_transaction = Web3.toHex( w3.eth.sendRawTransaction(signed.rawTransaction)) except Exception as E: logger.info("{0}".format(E)) return self.failure(message=str(E)) response = {'hash_transaction': hash_transaction} return self.success(response)
def get_account(): if settings.ethereum_pkey: pri_key = HexBytes(settings.ethereum_pkey) account = Account.privateKeyToAccount(pri_key) return account else: return None
def Transaction_out(private_key, toaddr, value, gas, gasprice): print(private_key) acct = Account.privateKeyToAccount(private_key) print(acct) public_key = acct.address print(public_key) nonce = requests.get( "https://waltonchain.net:18950/api/getSendTransactionNonce/"+public_key).json()["send_nonce"] print(nonce) transaction = { 'to': toaddr, 'value': int(float(value) * (10 ** 18)), 'gas': int(gas), 'gasPrice': int(float(gasprice) * (10 ** 18)), 'nonce': nonce, 'chainId': 15 } print(transaction) #key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' signed = w3.eth.account.signTransaction(transaction, private_key) print(w3.toHex(signed.rawTransaction)) tx_hash = requests.get( "https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json() print(tx_hash) return (1, tx_hash['tx_hash'])
def priv_key_to_account(coin, priv_key): if coin == ETH: return Account.privateKeyToAccount(priv_key) if coin == BTCTEST: return bit.PrivateKeyTestnet(priv_key)
def transction(): w3 = Web3( Web3.HTTPProvider( 'https://mainnet.infura.io/9dhHYFuxJixnXwEdnwIy ')) #连接到Eth的远程节点 priv_key = '5a71be5b4d5bea28a3b841f5f6a7a7a14b077cff3a82b9a02d738145a157c2fb' #爱链的eth账户的私钥 account = Account.privateKeyToAccount(priv_key) #通过私钥得到公钥也就是账户地址 nonce = w3.eth.getTransactionCount( account.address) #通过返回指定地址发起的交易数,得到防止重放攻击的数字 data = Web3.toHex( str.encode('爱链')) #交易附加的信息,需要将字符串转换为16进制编码,需要前端传递来需要保存的数据 payload = { 'to': '0x8Fe2Af03Ed1d362371261AB33C400F24fBB82D8f', 'value': 0, 'gas': 200000, #运算步数的上限 'gasPrice': Web3.toWei(10, 'gwei'), #每一步运算耗费的Eth 'nonce': nonce, 'data': data } signed = account.signTransaction(payload) #打包 # estimation = w3.eth.estimateGas(payload) # print(estimation) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) #生成裸交易,得到交易号 receipt = w3.eth.waitForTransactionReceipt(tx_hash) #通过交易号得到交易的信息,一般需要等1分钟 print(tx_hash) print(receipt)
def send_data(self, data): try: with open(config('private_key_file')) as keyfile: keyfile_json = keyfile.read() private_key = Account.decrypt(keyfile_json, config('PASSWORD')) except (ValueError, OSError) as e: sys.exit('Error loading private key: ' + str(e)) account = Account.privateKeyToAccount(private_key) w3 = Web3(HTTPProvider(config('INFURA_URL'))) signed_transaction = w3.eth.account.signTransaction( { 'nonce': w3.eth.getTransactionCount(account.address, 'pending'), 'gasPrice': w3.eth.gasPrice, 'gas': 30000, 'to': config('ADDRESS'), 'value': 0, 'data': data }, private_key) try: return w3.eth.sendRawTransaction(signed_transaction.rawTransaction) except ethereum.exceptions.InsufficientBalance as e: print(str(e)) return False return True
def unlock_wallet(public_key: str, password: str) -> Account: file_path: str = "%s%s%s%s" % (get_key_file_path(), KEYFILE_PREFIX, public_key, KEYFILE_POSTFIX) with open(file_path, 'r') as f: encrypted = f.read() private_key: str = Account.decrypt(encrypted, password) acct: Account = Account.privateKeyToAccount(private_key) return acct
def __load_private_key(self): if hasattr(self, 'private_key'): return self.__ask_decrypt_password() try: with open(self.ini_args.get('ethereum', 'private_key_file')) as keyfile: keyfile_json = keyfile.read() self.private_key = Account.decrypt(keyfile_json, self.decrypt_password) except (ValueError, OSError) as e: sys.exit('Error loading private key: ' + str(e)) if self.ini_args.get('ethereum', 'provider') == 'test': # make sure the sending account is well funded account = Account.privateKeyToAccount(self.private_key) if self.w3.eth.getBalance(account.address) == 0: self.w3.eth.sendTransaction({ 'from': self.w3.eth.coinbase, 'to': account.address, 'gas': 30000, 'value': 0, 'nonce': self.w3.eth.getTransactionCount(self.w3.eth.coinbase), })
def raw_transaction(self, privkey, addrto, amount, gasPrice, gasLimit): """裸交易""" value = amount * (10**self.decimals) # 单位转转 # 通过private key实例化账户 account = Account.privateKeyToAccount(privkey) address = account.address nonce = self.w3.eth.getTransactionCount(address) # 创建交易的json文件(将value从科学计数法变为浮点数) value = int(value) gasLimit = int(gasLimit) gasPrice = int(gasPrice) payload = { 'value': 0, 'gas': gasLimit, 'gasPrice': gasPrice, 'nonce': nonce, 'from': address } try: unicorn_txn = self.token_contract.functions.transfer( addrto, value).buildTransaction(payload) # 使用发送方账户对裸交易对象进行签名 signed = account.signTransaction(unicorn_txn) tx_hash = self.w3.eth.sendRawTransaction(signed.rawTransaction) return True, to_hex(tx_hash) except ValueError as e: print('ValueError:', e) return False, str(e)
def migrate(): private_key = os.environ.get('ETHEREUM_PRIVATE_KEY') if not private_key: print("No value found for required environment variable ETHEREUM_PRIVATE_KEY") sys.exit() account = Account.privateKeyToAccount(private_key) address = account.address nonce = w3.eth.getTransactionCount(address) v1_balance = legacyReputationToken.functions.balanceOf(address).call() if v1_balance == 0: print("Account %s has no V1 REP balance to migrate" % address) sys.exit() v1_display_balance = v1_balance / 10**18 yes = input("\nThe Provided Account %s has a V1 REP balance of %i.\n\nEnter 'Y' to convert that balance into V2 REP.\n\n" % (address, v1_display_balance)) if yes != "Y" and yes != "y": print("Did not migrate") sys.exit() approve(v1_balance, account, nonce) nonce = nonce + 1 doMigration(account, nonce) print('Migration Complete')
def priv_key_to_account(coin, priv_key): print(coin) print(priv_key) if coin == ETH: return Account.privateKeyToAccount(priv_key) elif coin == BTCTEST: return PrivateKeyTestnet(priv_key)
def pay(self, to_provider): """ Sends money to the provider :param to_provider: the provider to which money needs to be sent """ try: if self.utils.get_provider().isConnected(): self.utils.get_provider().eth.defaultAccount = \ Account.privateKeyToAccount(self.private_key).address hash = self.contract.functions.userPayForTrip(to_provider).transact() # Wait for transaction to be mined... provider_information = self.get_provider_data(to_provider) transaction_information = dict( self.utils.get_provider().eth.waitForTransactionReceipt(hash) ) transaction_information["companyName"] = provider_information[0].strip() transaction_information["price"] = provider_information[1] / math.pow(10, 18) tx_json = json.dumps( transaction_information, cls=HexJsonEncoder ) return tx_json else: raise Warning("Couldn't connect to the provider") except: return False
def top_up(self, amount): """ Puts money on a user account :param amount: the amount of token to deposit """ try: if self.utils.get_provider().isConnected(): self.utils.get_provider().eth.defaultAccount = \ Account.privateKeyToAccount(self.private_key).address hash = self.contract.functions.userTopUp().transact( { 'from': self.utils.get_provider().eth.defaultAccount, 'value': int(float(amount)*math.pow(10, 18)) # Converts to wei } ) # Wait for transaction to be mined... tx_json = json.dumps( dict( self.utils.get_provider().eth.waitForTransactionReceipt(hash) ), cls=HexJsonEncoder ) return tx_json else: raise Warning("Couldn't connect to the provider") except: return False
def add_multiple_hash(pri_key, doc_hash_list): try: web3 = ArchiveDocContractService.get_web3_client() account = Account.privateKeyToAccount(pri_key) web3.eth.defaultAccount = account.address contract = ArchiveDocContractService.get_contract(web3) params = { 'from': account.address, 'nonce': web3.eth.getTransactionCount(account.address), 'gasPrice': web3.toWei('50', 'gwei') } transaction = contract.functions.addMultipleHash( doc_hash_list).buildTransaction(params) signed_txn = web3.eth.account.signTransaction( transaction, private_key=account.privateKey) tx_id = web3.eth.sendRawTransaction(signed_txn.rawTransaction) return tx_id.hex() except Exception as e: print(str(e)) return None
def get_account(): if config['web3']['pkey']: pri_key = HexBytes(config['web3']['pkey']) account = Account.privateKeyToAccount(pri_key) return account else: return None
def remove_staff(owner_pri_key, staff_address): try: web3 = ArchiveDocContractService.get_web3_client() account = Account.privateKeyToAccount(owner_pri_key) web3.eth.defaultAccount = account.address contract = ArchiveDocContractService.get_contract(web3) params = { 'from': account.address, 'nonce': web3.eth.getTransactionCount(account.address), 'gasPrice': web3.toWei('50', 'gwei') } staff_address = web3.toChecksumAddress(staff_address) transaction = contract.functions.removeStaff( staff_address).buildTransaction(params) signed_txn = web3.eth.account.signTransaction( transaction, private_key=account.privateKey) tx_id = web3.eth.sendRawTransaction(signed_txn.rawTransaction) return tx_id.hex() except Exception as e: print(str(e)) return None
def __init__(self, address, abi, private, val, to_add): address = Web3.toChecksumAddress(address) erc20 = self.w3.eth.contract(address=address, abi=abi) try: name = erc20.functions.name().call() except Exception as e: print(e) try: to_add = Web3.toChecksumAddress(to_add) except Exception as e: print(e) acct = Account.privateKeyToAccount(private) tran = erc20.functions.transfer(to_add, int(val)).buildTransaction({ 'from': acct.address, 'nonce': self.w3.eth.getTransactionCount(acct.address), 'gas': 2728712, 'gasPrice': self.w3.toWei('41', 'gwei') }) self.signed = acct.signTransaction(tran)
def private_key_to_account(val): normalized_key = key_normalizer(val) return Account.privateKeyToAccount(normalized_key)