def delete(self): passphrase = click.prompt( f"Enter Passphrase to delete '{self.alias}'", hide_input=True, default="", # Just in case there's no passphrase ) EthAccount.decrypt(self.keyfile, passphrase) self._keyfile.unlink()
def player_roll_dice(self, bet_size_ether, chances, wallet_path, wallet_password, gas_price_gwei=DEFAULT_GAS_PRICE_GWEI): """ Signs and broadcasts `playerRollDice` transaction. Returns transaction hash. """ roll_under = chances # `w3.toWei` one has some issues on Android, see: # https://github.com/AndreMiras/EtherollApp/issues/77 # value_wei = w3.toWei(bet_size_ether, 'ether') value_wei = int(bet_size_ether * 1e18) gas = 310000 gas_price = w3.toWei(gas_price_gwei, 'gwei') wallet_encrypted = load_keyfile(wallet_path) address = wallet_encrypted['address'] from_address_normalized = to_checksum_address(address) nonce = self.web3.eth.getTransactionCount(from_address_normalized) transaction = { 'chainId': self.chain_id.value, 'gas': gas, 'gasPrice': gas_price, 'nonce': nonce, 'value': value_wei, } transaction = self.contract.functions.playerRollDice( roll_under).buildTransaction(transaction) private_key = Account.decrypt(wallet_encrypted, wallet_password) signed_tx = self.web3.eth.account.signTransaction( transaction, private_key) tx_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction) return tx_hash
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 get_address(account_name, password=""): """Gets the address and public key of the account. --- Definitions --- {"name": "account_name", "prompt": "Alias of account", "default": "Myaccount"} """ db = get_wallet_db() account = db.execute('SELECT * FROM testaccount WHERE name = ?', (account_name, )).fetchone() if account is None: return None # Attemp to decrypt with the provided password if len(password) > 0: pk = Account.decrypt(account["privatekey"], password).hex() return { "address": account["address"], "publicKey": account["publickey"], "privateKey": pk } else: return { "address": account["address"], "publicKey": account["publickey"] }
def transaction( self, to, value, wallet_path, wallet_password, gas_price_wei=DEFAULT_GAS_PRICE_WEI, ): gas = 25000 wallet_encrypted = load_keyfile(wallet_path) address = wallet_encrypted["address"] from_address_normalized = to_checksum_address(address) nonce = self.web3.eth.getTransactionCount(from_address_normalized) transaction = { "chainId": self.chain_id.value, "gas": gas, "gasPrice": gas_price_wei, "nonce": nonce, "value": value, "to": to, } private_key = Account.decrypt(wallet_encrypted, wallet_password) signed_tx = self.web3.eth.account.signTransaction( transaction, private_key) tx_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction) return tx_hash
def player_roll_dice( self, bet_size_wei, chances, wallet_path, wallet_password, gas_price_wei=DEFAULT_GAS_PRICE_WEI, ): """ Signs and broadcasts `playerRollDice` transaction. Returns transaction hash. """ roll_under = chances gas = 310000 wallet_encrypted = load_keyfile(wallet_path) address = wallet_encrypted["address"] from_address_normalized = to_checksum_address(address) nonce = self.web3.eth.getTransactionCount(from_address_normalized) transaction = { "chainId": self.chain_id.value, "gas": gas, "gasPrice": gas_price_wei, "nonce": nonce, "value": bet_size_wei, } transaction = self.contract.functions.playerRollDice( roll_under).buildTransaction(transaction) private_key = Account.decrypt(wallet_encrypted, wallet_password) signed_tx = self.web3.eth.account.signTransaction( transaction, private_key) tx_hash = self.web3.eth.sendRawTransaction(signed_tx.rawTransaction) return tx_hash
def __key(self) -> EthAccount: if self.__cached_key is not None: if not self.locked: click.echo(f"Using cached key for '{self.alias}'") return self.__cached_key else: self.__cached_key = None passphrase = click.prompt( f"Enter Passphrase to unlock '{self.alias}'", hide_input=True, default="", # Just in case there's no passphrase ) try: key = EthAccount.decrypt(self.keyfile, passphrase) except ValueError as e: raise Exception("Invalid password") from e if click.confirm(f"Leave '{self.alias}' unlocked?"): self.locked = False self.__cached_key = key return key
def get_private_key(key_path, password_path=None): """Open a JSON-encoded private key and return it If a password file is provided, uses it to decrypt the key. If not, the password is asked interactively. Raw hex-encoded private keys are supported, but deprecated.""" assert key_path, key_path if not os.path.exists(key_path): log.fatal("%s: no such file", key_path) return None # if not check_permission_safety(key_path): # log.fatal("Private key file %s must be readable only by its owner.", key_path) # return None # # if password_path and not check_permission_safety(password_path): # log.fatal("Password file %s must be readable only by its owner.", password_path) # return None with open(key_path) as keyfile: private_key = keyfile.readline().strip() if is_hex(private_key) and len(decode_hex(private_key)) == 32: log.warning("Private key in raw format. Consider switching to JSON-encoded") else: if password_path: with open(password_path) as password_file: password = password_file.readline().strip() else: password = getpass.getpass("Enter the private key password: ") with open(key_path) as fh: encrypted = json.load(fh) private_key = Account.decrypt(encrypted, password).hex() return private_key
def btn_login_fuc(self): if self.splitter.widget(1).objectName() == 'Ui_Filekey': if self.splitter.widget(1).lineEdit.text().endswith(".json") ==False: reply = QMessageBox.warning(self, "警告", "请选择KEYFILE文件!") return if self.splitter.widget(1).lineEdit_2.text() == '': reply = QMessageBox.warning(self, "警告", "KEYFILE密码不能为空,请输入!") return with open(self.splitter.widget(1).lineEdit.text().replace("/", "\\"), 'r') as f: wallet = json.load(f) try: priv_key = Account.decrypt(wallet, self.splitter.widget(1).lineEdit_2.text()).hex() account = Account.privateKeyToAccount(priv_key) except Exception as e: reply = QMessageBox.warning(self, "警告", str(e)) return if self.splitter.widget(1).objectName() == 'Ui_Private': if self.splitter.widget(1).lineEdit_2.text() =='': reply = QMessageBox.warning(self, "警告", "private不能为空,请输入!") return try: account = Account.from_key(self.splitter.widget(1).lineEdit_2.text()) except Exception as e: reply = QMessageBox.warning(self, "警告", str(e)) return mainwindow.address = account.address mainwindow.private = account._key_obj mainwindow.public = account._key_obj.public_key # print(account.address,account._key_obj,account._key_obj.public_key) mainwindow.lineEdit_2.setText(str(account.address)) mainwindow.show() self.close()
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 __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 decrypt_account(self, fname, fpath=None, password=None): """ Decrypts private key """ fpath = './accs/' + fname if not fpath else fpath password = getpass.getpass() if not password else password with open(fpath, 'r') as f: encrypted = json.load(f) self.pk = Account.decrypt(encrypted, password)
def _export_wallet_to_node( self, blockchain, passphrase): # TODO: Deprecate with geth.parity signing EIPs """Decrypt the wallet with a passphrase, then import the key to the nodes's keyring over RPC""" with open(self.__wallet_path, 'rb') as wallet: data = wallet.read().decode(FILE_ENCODING) account = Account.decrypt(keyfile_json=data, password=passphrase) blockchain.interface.w3.personal.importRawKey( private_key=account, passphrase=passphrase)
def export_account_key(self, address, password, url=None): if url: web3 = Web3(HTTPProvider(url)) raw_data = web3.manager.request_blocking('parity_exportAccount', [address, password]) key_json = json.dumps(raw_data, default=as_attrdict) else: key_json = json.dumps(self._key_chain.get_key(address)) return EthAccount.decrypt(key_json, password)
def set_account_from_wallet(self, wallet_file, wallet_password): """从密钥文件加载accout对象""" wallet = self._load_wallet(wallet_file) private_key = Account.decrypt(wallet, wallet_password) setattr(self, "account", Account.privateKeyToAccount(private_key)) self.main_address = self.web3.eth.account.privateKeyToAccount( private_key).address return dict(privateKey=Web3.toHex(private_key), address=self.account.address)
def _get_private_key(self, key_file, password): """ Decrypts a key file on disk with the given password and returns the private key :param key_file: An encrypted json keystore file, requires a password to decrypt :param password: The password to decrypt the encrypted key store file :return: """ json_dict = json.load(open(key_file, 'r')) return self.w3.toHex(Account.decrypt(json_dict, password))[2:]
def unlock_wallet(wallet_address: str, password: str) -> str: """ Search get_key_file_path() by a public key for an account file, then decrypt the private key from the file with the provided password """ file_path: str = "%s%s%s%s" % (get_key_file_path(), KEYFILE_PREFIX, wallet_address, KEYFILE_POSTFIX) with open(file_path, 'r') as f: encrypted = f.read() private_key: str = Account.decrypt(encrypted, password) return private_key
def Import_Keystore(passphrase, filecontent): try: # content = json.loads(filecontent) private_key = w3.toHex(Account.decrypt(filecontent, passphrase)) public_key = Account.privateKeyToAccount(private_key).address encrypted = Account.encrypt(private_key, passphrase) return (1, [public_key, private_key], json.dumps(encrypted)) except Exception as err: print(err) return (0, 10000)
def get_private_key(keystore_file, password): with open(keystore_file, "r") as keystore: try: private_key = Account.decrypt( keyfile_json=json.load(keystore), password=password ).hex() return private_key except ValueError as error: print("Could not decode keyfile with given password. Please try again.", str(error)) sys.exit(1)
def unlock(self): passphrase = click.prompt( f"Enter Passphrase to permanently unlock '{self.alias}'", hide_input=True, ) try: self.__cached_key = EthAccount.decrypt(self.keyfile, passphrase) except ValueError as e: raise Exception("Invalid password") from e
def get_private_key(password: str, f: str) -> Account: if not os.path.exists(f): print("JSON Keystore not found.") sys.exit() with open(f, "r") as f: data = json.load(f) # Returning the Account result with the prefix 0x removed return Account.decrypt(password=password, keyfile_json=data).hex().strip("0x")
async def main(): cmd_args = CmdlineParser().parse_args() with open(cmd_args.key_file, "r") as fd: encrypted_json: Dict[str, any] = json.load(fd) wallet: Web3Wallet = Web3Wallet( Account.decrypt(encrypted_json, getpass.getpass("Wallet password: "******"createdAt"], o["id"], o["marketId"]) for o in orders], columns=["Created", "OrderID", "Symbol"]) order_data.Created = order_data.Created.astype( "datetime64[ms]").astype("datetime64[ns, UTC]") order_data = order_data.set_index("Created") while True: try: sample_ids: List[str] = list(order_data.sample(10).OrderID) tasks: List[asyncio.Future] = [ market.get_order(order_id) for order_id in sample_ids ] response_data: List[Dict[str, any]] = await asyncio.gather(*tasks) mismatches: int = 0 for expected_id, response in zip(sample_ids, response_data): returned_order_id = response["id"] if returned_order_id != expected_id: print( f" - Error: requested for {expected_id} but got {returned_order_id} back." ) mismatches += 1 if mismatches < 1: print( f"[{str(pd.Timestamp.utcnow())}] All fetches passed.") else: print( f"[{str(pd.Timestamp.utcnow())}] {mismatches} out of 10 requests failed." ) now: float = time.time() next_tick: float = now // 1 + 1 await asyncio.sleep(next_tick - now) except asyncio.CancelledError: raise
def _open_keystore(keystore_file: str, password: str) -> str: with open(keystore_file, "r") as keystore: try: private_key = Account.decrypt(keyfile_json=json.load(keystore), password=password).hex() return private_key except ValueError as error: log.critical( "Could not decode keyfile with given password. Please try again.", reason=str(error), ) sys.exit(1)
def decrypt(self, passphrase): if self.keyFile != None: try: self.__privateKey = Account.decrypt(self.keyFile, passphrase) self.account = Account.privateKeyToAccount(self.__privateKey) self.address = self.account.address except: print('Wrong passphrase') return False else: self.lock = False return True
def get_private_key(address, mode) : if not mode.w3.isAddress(address) or address == '0x0000000000000000000000000000000000000000' : logging.error('wrong address') return None try : fp = open(mode.keystore_path + address[2:] + '.json', "r") except : logging.error('private key not found in privatekey.py') return None encrypted = fp.read() fp.close() return Account.decrypt(encrypted, mode.password).hex()
def _open_keystore(keystore_file: str, password: str) -> PrivateKey: with open(keystore_file, mode="r", encoding="utf-8") as keystore: try: private_key = bytes( Account.decrypt(keyfile_json=json.load(keystore), password=password)) return PrivateKey(private_key) except ValueError as error: log.critical( "Could not decode keyfile with given password. Please try again.", reason=str(error), ) sys.exit(1)
def account_from_name(name, password): """Get the account with the specified name.""" db = get_wallet_db() account = db.execute('SELECT * FROM testaccount WHERE name = ?', (name, )).fetchone() if account is None: return None, None private_key = Account.decrypt(account["privatekey"], password) return account["address"], private_key
def _keyfile_middleware(keyfile_path): import json with open(keyfile_path, 'r') as f: keyfile = json.loads(f.read()) from getpass import getpass password = getpass("Please Input Keyfile Password: ") from eth_account import Account privateKey = Account.decrypt(keyfile, password) account = Account.privateKeyToAccount(privateKey) from web3.middleware.signing import construct_sign_and_send_raw_middleware middleware = construct_sign_and_send_raw_middleware(privateKey) return account, middleware
def unlock_keyfile(self, keyfile, password): """Unlock a JSON keyfile for signing transactions to this network. :param keyfile: Keyfile to unlock :param password: Password to decrypt keyfile :return: True if success, else False """ try: self.priv_key = Account.decrypt(keyfile.read(), password) self.address = Account.privateKeyToAccount(self.priv_key).address except ValueError: logger.exception('Incorrect password for keyfile') return False return True
def signer_key(self): """Decrypts the private key from keystore file using the password provider or the password. If both exist, the password will be used to unlock the targeted keystore file. Returns: bytes: the private key Raises: ValueError: if the password used from decryption is invalid """ with open(self.keyfile) as f: data = json.load(f) return Account.decrypt(data, self.signer_password)