def decryptPrivateKey(_file, _pwd): with open(_file) as keyfile: encrypted_key = keyfile.read() keyfile.close() ac_obj = Account() decrypted_key = ac_obj.decrypt(encrypted_key, _pwd) return ac_obj.privateKeyToAccount(decrypted_key)
def create_acc(): acc = Account.create() # password = "******" keyfile_json = Account.encrypt(acc.privateKey, password) t = time.time() secondstr = str(time.time())[:9] timestr = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(t)) filename = "UTC--" + timestr + "." + secondstr + "Z--" + str(acc.address[2:]).lower() file_path = fileroot + filename with open(file_path, "w") as f: json.dump(keyfile_json, f) return acc.address
def eth_sign(self, params): sign_str = self.get_sign_str(params, None) message = Web3.toHex(Web3.sha3(text=sign_str)) private_key = Account.decrypt(self.key_store, self.key_pwd) acct = Account.privateKeyToAccount(private_key) hash = acct.signHash(message) border = 'big' v = hash['v'].to_bytes(1, border) r = hash['r'].to_bytes(32, border) s = hash['s'].to_bytes(32, border) z = v + r + s sign = z.hex() params['presign'] = sign
def transfer(contract_address, to, amount): with open(os.path.join('./contract_abi.json'), 'r') as abi_definition: abi = json.load(abi_definition) w3 = Web3(HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH')) contract = w3.eth.contract(address=contract_address, abi=abi) unicorn_txn = contract.functions.transfer( to, amount * 1000000000000000000).buildTransaction({ 'value': 0, 'gas': w3.toHex(1000001), 'gasPrice': w3.toWei('10000', 'gwei'), 'nonce': w3.eth.getTransactionCount( '0x6f212bF41DF64De9782dbfb26112BD3B0e39514B'), 'from': '0x6f212bF41DF64De9782dbfb26112BD3B0e39514B' }) private_key = r"955ca0f797c309aadd06d6bd9272ed71e57210ea145edff4b238c3db0b63f219" acct = Account.privateKeyToAccount(private_key) signed = acct.signTransaction(unicorn_txn) tx = w3.eth.sendRawTransaction(signed.rawTransaction) tx_hash = w3.toHex(tx) return tx_hash
def createAccount(): ACC = Account.create("RANDOMSTRINGTOINCREASETHEENTROPYOFTHEHASH!") print(term.SUCCESS + "Account public key: " + ACC.address) print(term.SENSITIVE + "Account PRIVATE KEY: " + ACC.privateKey.hex(), end=2 * "\n") return ACC
def run(method, address, game_id): # Web3 INFURA_PROJECT_ID = os.environ['INFURA_PROJECT_ID'] INFURA_PROJECT_SECRET = os.environ['INFURA_PROJECT_SECRET'] headers = {"auth": ("", INFURA_PROJECT_SECRET)} uri = 'https://ropsten.infura.io/v3/%s' % (INFURA_PROJECT_ID) web3 = Web3(HTTPProvider(uri, headers)) # Owner owner = Account.from_key(os.environ['PRIVATE_KEY_0x2048']) # ABI filepath = 'bin/combined.json' with open(filepath) as f: compiled_artifacts = json.load(f) data = compiled_artifacts["contracts"] contract_data = data["solidity/ArcadeProtocol.sol:ArcadeProtocol"] abi = contract_data["abi"] bytecode = contract_data["bin"] # Run interactor = ContractInteractor(web3) if method == 'deploy': interactor.deploy(abi, bytecode, from_addr=owner) elif method == 'add_game': price = 100000000000000 # 0.0001 ETH fee = 1 interactor.set_contract(abi, address) interactor.add_game(game_id, price, fee, from_addr=owner)
def transact(self, path: str, request: Any) -> None: assert self.key is not None response = requests.post( base_url + path, headers={"Content-Type": "application/json"}, data=json.dumps(request), ) response.raise_for_status() for tx in response.json()["transactions"]: address = self.key.address._checksummed nonce = w3.eth.getTransactionCount(address, "pending") params = fill_transaction_defaults( w3, TxParams({ "data": HexStr(tx["data"]), "from": address, "nonce": nonce, "to": Web3.toChecksumAddress(tx["to"]), }), ) signed = Account.sign_transaction(params, bytes(self.key)) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) assert tx_receipt["status"] == 1
def get_random_eth_account(): global pre_eth_acc if pre_eth_acc: acc = EthAccount(pre_eth_acc) pre_eth_acc = None return acc return EthAccount(Account.create())
def priv_key_to_account(coin, priv_key): if coin == ETH: # do something return Account.privateKeyToAccount(priv_key) elif coin == BTCTEST: # do something else return PrivateKeyTestnet(priv_key)
def priv_key_to_account(coin, privkey): if coin == ETH: return Account.privateKeyToAccount(privkey) elif coin == BTCTEST: account = PrivateKeyTestnet(privkey) print(account.address) return PrivateKeyTestnet(privkey)
def create_and_recharge(num): w3 = create_web3_instance("http://52.205.30.16:8545") acc = Account.privateKeyToAccount("f87fdefd98ef1347f4ee213d80e3495e4beaba5991a18bfee0fa80f0fba05b1a") nonce = w3.eth.getTransactionCount(acc.address) addrs = [] for i in range(num): addr = create_acc() print(addr) transaction = { 'to': addr, 'value': value, 'nonce': nonce, } gas = get_buffered_gas_estimate(w3, transaction) gas_price = w3.eth.gasPrice transaction['gas'] = gas transaction['gasPrice'] = gas_price signed = acc.signTransaction(transaction) w3.eth.sendRawTransaction(signed.rawTransaction) addrs.append(addr) nonce += 1 time.sleep(100) for t in addrs: print(t, w3.eth.getBalance(t))
def submit_sign_and_wait_for_transaction(w3: Web3, txn: Dict, private_key: str, timeout: int): signed = w3.eth.account.signTransaction(txn, private_key) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash, timeout=timeout) # after the transaction is confirmed, save it account_address = Account.privateKeyToAccount(private_key).address wallet = Wallet.objects.get(address=account_address) to = txn['to'] if isinstance(to, bytes): to = to.decode('utf-8') Transaction.objects.create( block_number=tx_receipt['blockNumber'], chain_id=txn['chainId'], contract_address=tx_receipt['contractAddress'], cumulative_gas_used=tx_receipt['cumulativeGasUsed'], data=txn['data'], gas_limit=txn['gas'], gas_price=txn['gasPrice'], gas_used=tx_receipt['gasUsed'], hash=tx_hash.hex(), nonce=txn['nonce'], status=tx_receipt.get('status', -1), to=to, value=txn['value'], wallet=wallet, ) return tx_receipt
def createAccount(self): self._master_gui.password_box1("Provide password for the key-store.") password = self._master_gui.blockFace.password self._master_gui.password_box1("Verify password for the key-store.") if (password != self._master_gui.blockFace.password): self._master_gui.error_box1("Passwords don't match") return account = Account.create() keystore = account.encrypt(password) if (self.keystore_name.get() == self.keystore_name_default): self.keystore_name.set( "new_keystore_" + datetime.now().strftime("%d-%m-%Y-%H:%M:%S")) try: print(self.keystore_name.get()) with open("Key_Stores" + os.path.sep + self.keystore_name.get(), 'w') as handle: json.dump(keystore, handle) self._master_gui.message_box1( 'Account created', 'Address:\n' + account.address + '\n\nKeystore location:\n' + os.getcwd() + os.path.sep + "Key_Stores" + os.path.sep + '\n\nKeystore name:\n' + self.keystore_name.get()) self.keystore_name.set(self.keystore_name_default) except Exception as err: self._master_gui.error_box1(err)
def deploy_contract(self): compiled_sol = compile_source_file('TokenERC20.sol') contract_interface = compiled_sol['<stdin>:TokenERC20'] # web3.py instance w3 = Web3( HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH')) # Instantiate and deploy contract contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) with open('contract_abi.json', 'w') as outfile: json.dump(contract_interface['abi'], outfile) data = contract._encode_constructor_data(args=(self.total_supply, self.name, self.symbol)) transaction = { 'data': data, 'gas': 3000001, 'gasPrice': 8000001, 'chainId': 4, 'to': '', 'from': self.ADDRESS, 'nonce': w3.eth.getTransactionCount(self.ADDRESS) } acct = Account.privateKeyToAccount(self.PRIVATE_KEY) signed = acct.signTransaction(transaction) tx = w3.eth.sendRawTransaction(signed.rawTransaction) tx_hash = w3.toHex(tx) return tx_hash
def test_is_valid_order_deserialized(self): account = Account.from_key(PRIVATE_KEY) zksync_signer = ZkSyncSigner.from_account(account, self.library, ChainId.MAINNET) ethereum_signer = EthereumSignerWeb3(account=account) token1 = Token(id=1, symbol='', address='', decimals=0) # only id matters token2 = Token(id=2, symbol='', address='', decimals=0) # only id matters tokens_pool = Tokens(tokens=[token1, token2]) order = Order(account_id=7, nonce=18, token_sell=token1, token_buy=token2, ratio=Fraction(1, 4), amount=1000000, recipient='0x823b6a996cea19e0c41e250b20e2e804ea72ccdf', valid_from=0, valid_until=4294967295) order.signature = zksync_signer.sign_tx(order) order.eth_signature = ethereum_signer.sign_tx(order) zksync_validator = EncodedTxValidator(self.library) serialized_order = json.dumps(order.dict(), indent=4) deserialized_order = Order.from_json(json.loads(serialized_order), tokens_pool) ret = zksync_validator.is_valid_signature(deserialized_order) self.assertTrue(ret) ret = deserialized_order.is_valid_eth_signature( ethereum_signer.address()) self.assertTrue(ret)
async def asyncSetUp(self) -> None: self.account = Account.from_key(self.private_key) ethereum_signer = EthereumSignerWeb3(account=self.account) self.library = ZkSyncLibrary() w3 = Web3( HTTPProvider( endpoint_uri= "https://rinkeby.infura.io/v3/bcf42e619a704151a1b0d95a35cb2e62" )) provider = ZkSyncProviderV01(provider=HttpJsonRPCTransport( network=rinkeby)) address = await provider.get_contract_address() self.zksync = ZkSync(account=self.account, web3=w3, zksync_contract_address=address.main_contract) ethereum_provider = EthereumProvider(w3, self.zksync) signer = ZkSyncSigner.from_account(self.account, self.library, rinkeby.chain_id) self.wallet = Wallet(ethereum_provider=ethereum_provider, zk_signer=signer, eth_signer=ethereum_signer, provider=provider)
def create_contract_tx_hash(self): compiled_sol = compile_source_file('%s/contract/OwnerToken.sol' % BASE_DIR) contract_interface = compiled_sol['<stdin>:OwnerToken'] # web3.py instance w3 = Web3(HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH')) # Instantiate and deploy contract contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) with open('%s/contract/owner_contract_abi.json' % BASE_DIR, 'w') as outfile: json.dump(contract_interface['abi'], outfile) data = contract._encode_constructor_data(args=(self.name, self.symbol)) transaction = {'data': data, 'gas': w3.toHex(1000000), 'gasPrice': w3.toWei('1000', 'gwei'), 'chainId': 4, 'to': '', 'from': self.ADDRESS, 'nonce': w3.eth.getTransactionCount(self.ADDRESS, "pending") } acct = Account.privateKeyToAccount(self.PRIVATE_KEY) signed = acct.signTransaction(transaction) tx = w3.eth.sendRawTransaction(signed.rawTransaction) tx_hash = w3.toHex(tx) return tx_hash
def __init__(self, private_key, wss_url=None, contract_address=None, **kwargs): self.logger = logging.getLogger('gnosis.extension.contract') self.web3 = Web3( Web3.WebsocketProvider(endpoint_uri=wss_url, websocket_timeout=1800)) self.private_key = private_key self.account = Account.privateKeyToAccount(self.private_key) self.contract_address = self.web3.toChecksumAddress(contract_address) self.gnosis_gas_station_url = kwargs.get( 'gnosis_gas_station_url', 'https://safe-relay.gnosis.io/api/v1/gas-station/') abi_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'gnosis/exchange_abi.json') with open(abi_file) as json_file: abi = json.load(json_file) self.contract = self.web3.eth.contract( address=self.contract_address, abi=abi) if not self.web3.isConnected(): raise ConnectionError("Failed to connect to the Ethereum network.") self.max_gas_price = kwargs.get('max_gas_price', -1) self.gas_price_level = kwargs.get('gas_price_level', 'standard')
def run_limit_case(tx_manager: TransactionManager): miner_w3 = create_web3_instance("http://127.0.0.1:1111") normal_w3 = create_web3_instance("http://127.0.0.1:2222") miner_addr = "0x040e18b1bbb5dead8120fec5885fdf56498bcd6a" # mainacc = get_rand_account() mainacc = Account.privateKeyToAccount( "15bac02dbaff32a8da673c490753a070b054b9d62adbc52cc474f2b49370613b") targetacc = get_rand_account() subaccs = [] acc3 = get_rand_account() acc_addrs = [] acc_addrs.append(miner_addr) acc_addrs.append(str(mainacc.address)) acc_addrs.append(str(targetacc.address)) acc_addrs.append(str(acc3.address)) for i in range(1000): acc = get_rand_account() subaccs.append(acc) acc_addrs.append(str(acc.address)) # rechargestartmoney # res = rechange_by_address(tx_manager, mainacc.address, 700000000000, miner_w3) # print("privatekey", str(binascii.b2a_hex(mainacc.privateKey), 'utf-8')) # return # if not res: # log_print("Rechange Failed") # log_print_is_case_pass(False, case_name) # return show_address_balance("start_send_txs", miner_w3, acc_addrs) mainacc_balance = miner_w3.eth.getBalance(mainacc.address) log_print("--------------Start create Txs-----------------") start_mutiple_send_txs(normal_w3, mainacc, subaccs, targetacc, 100000, 10000000000000, mainacc_balance) # send_normal_txs(acc1, acc2, 100000, 10000000000000000, acc1_start) log_print("--------------End create Txs-----------------") # res = rechange_by_address(tx_manager, acc3.address, 10000000000, miner_w3) # if not res: # log_print("Rechange Failed") # log_print_is_case_pass(False, case_name) # return global thread_tps if thread_tps: log_print("**********join tps*************") thread_tps.join() else: log_print("***********not join tps*******************") log_print("================show address result===================") for i in range(40): log_print("Show result at index ", i) show_address_balance("end_send_txs", miner_w3, acc_addrs) # get_address_balance(acc1.address, acc2.address, acc3.address, miner_addr) time.sleep(1)
def gen_eth_addr2(): account = Account.create() priv_key = '0x' + str(binascii.hexlify(account.key), 'utf-8') print(priv_key) print(account.address)
def send_tx(coin, account, to, amount): raw_tx = create_tx(coin, account, to, amount) if coin == ETH: tx = Account.signTransaction( raw_tx, '0x9953305bdca593d1008b3508f080a55f54d610e315676736da271823c19b3147' ) Web3().eth.sendRawTransaction(tx.rawTransaction)
def priv_key_to_account(coin, priv_key): # print(coin) # print(priv_key) if coin == ETH: return Account.privateKeyToAccount(priv_key) elif coin == BTC: key = wif_to_key("") return key.PrivateKeyTestnet(priv_key)
def transfer_between_accounts(w3: Web3, source_private_key: str, destination_private_key: str, amount_in_wei: int) -> None: source_account = Account.privateKeyToAccount(source_private_key) destination_account = Account.privateKeyToAccount(destination_private_key) signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(source_account.address), gasPrice=int(w3.eth.gasPrice * 1.1), # increase by 10% just to be sure this will be included gas=3 * 21000, # 3x normal transaction cost just to be safe to=destination_account.address, value=amount_in_wei ), source_private_key) tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) w3.eth.waitForTransactionReceipt(tx_hash, timeout=120)
def priv_key_to_account(coin, priv_key): # print(coin) # print(priv_key) if coin == ETH: account = Account.privateKeyToAccount(priv_key) return account if coin == BTCTEST: account = PrivateKeyTestnet(priv_key) return account
def get_nonce(*, web3: Web3, nonce: int, private_key: bytes): """get the nonce to be used as specified via command line options """ if nonce is not None: return nonce elif private_key is not None: return web3.eth.getTransactionCount( Account.from_key(private_key).address, block_identifier="pending") else: return web3.eth.getTransactionCount(web3.eth.accounts[0], block_identifier="pending")
def checkWallet(self, publicKey, privateKey): try: publicKey = Web3.toChecksumAddress(publicKey) account = Account.privateKeyToAccount(privateKey) if account.address == publicKey: return True else: return False except Exception as e: print(e) return False
def setUp(self) -> None: self.account = Account.from_key(self.private_key) w3 = Web3( HTTPProvider( endpoint_uri= "https://rinkeby.infura.io/v3/bcf42e619a704151a1b0d95a35cb2e62" )) self.zksync = ZkSync( account=self.account, web3=w3, zksync_contract_address="0x82F67958A5474e40E1485742d648C0b0686b6e5D" )
def _build_transaction_dict(w3, private_key, gas=None, gas_price=None): acc = Account.privateKeyToAccount(private_key) nonce = get_nonce_for_wallet(private_key) latest_block = w3.eth.getBlock('latest') if not gas: gas = 7000000 # tech debt until we figure out how to always pick a good gas limit if not gas_price: gas_price = int( w3.eth.gasPrice * 1.1) # add an additional 10% just to be safe return {'nonce': nonce, 'gas': gas, 'gasPrice': gas_price}
def main(): i = 1 priv = '2defac83d19dfe04610864da99cec58fdcf11af07178cfacbf30c02d6ac57e46' account = Account.privateKeyToAccount(priv) print(account.address) try: balance = w3.eth.getBalance(account.address) if balance != 0: logging.info("有钱地址-" + account.address + ",私钥-" + priv) print(balance) except BaseException as e: print(str(e))
def __init__(self, key: str, contract_address: str, node_address: str): self._account = Account.privateKeyToAccount(key) self._contract_address = contract_address self._node_address = node_address self.w3 = Web3(HTTPProvider(self._node_address)) self.contract = self.w3.eth.contract(address=self._contract_address, abi=EIP20_ABI) self._balanceOf = self.contract.functions.balanceOf self._totalSupply = self.contract.functions.totalSupply self._transfer = self.contract.functions.transfer