def validate_key_store_file(key_store_file_path: object) -> bool: """Check key_store file was saved in the correct format. :return: bool True: When the key_store_file was saved in valid format. False: When the key_store_file was saved in invalid format. """ is_valid = True # The key values that should be in the root location. root_keys = ["version", "id", "address", "crypto"] crypto_keys = ["ciphertext", "cipherparams", "cipher", "kdf", "kdfparams", "mac"] crypto_cipherparams_keys = ["iv"] crypto_kdfparams_keys = ["dklen", "salt", "c", "prf"] is_valid = False try: with open(key_store_file_path, 'rb') as key_store_file: key_file = eth_keyfile.load_keyfile(key_store_file) is_valid = has_keys(key_file, root_keys) and has_keys(key_file["crypto"], crypto_keys) and has_keys(key_file["crypto"]["cipherparams"], crypto_cipherparams_keys) and has_keys(key_file["crypto"]["kdfparams"], crypto_kdfparams_keys) except KeyError: raise NotAKeyStoreFile except JSONDecodeError: raise NotAKeyStoreFile if is_valid is not True: raise NotAKeyStoreFile return is_valid
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 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 collect_keystore_files(self): self.accounts_dict = dict() keystore_files = glob.glob(KEYSTORE_PATH) for keystore_file in keystore_files: keyfile = load_keyfile(keystore_file) self.accounts_dict[to_checksum_address("0x" + keyfile["address"])] = { "keyfile_json": keyfile, "keystore_file": keystore_file, }
def test_validate_keystore_file_is_for_icon(self): """Case when validating keystore file if for icon or not.""" keystore = load_keyfile(self.TEST_KEYSTORE_FILE_PATH) self.assertTrue(is_keystore_file_for_icon(keystore)) # when an address's length is too short. keystore["address"] = "hx123" self.assertRaises(KeyStoreException, is_keystore_file_for_icon, keystore) # when an address doesn't start with 'hx'. keystore["address"] = "axfd7e4560ba363f5aabd32caac7317feeee70ea57" self.assertRaises(KeyStoreException, is_keystore_file_for_icon, keystore) # when an value of key 'coinType' is not same as 'icx'. keystore["address"] = "hxfd7e4560ba363f5aabd32caac7317feeee70ea57" keystore["coinType"] = "ic" self.assertRaises(KeyStoreException, is_keystore_file_for_icon, keystore)
def eth_sign_with_keyfile(message: bytes, raw: bool, keyfile: str, password: str): assert(isinstance(message, bytes)) assert(isinstance(raw, bool)) assert(isinstance(keyfile, str)) assert(isinstance(password, str)) if not raw: message = hexstring_to_bytes(Eth._recoveryMessageHash(data=message)) key = eth_keyfile.decode_keyfile_json(eth_keyfile.load_keyfile(keyfile), bytes(password, 'utf-8')) pk = PrivateKey(key, raw=True) signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(message, raw=True) ) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) signature_hex = signature.hex()[0:128] + int_to_bytes(ord(bytes.fromhex(signature.hex()[128:130]))+27).hex() return '0x' + signature_hex
def load(file_path, password): """Loads a wallet from a key store file with your password and generates an instance of Wallet. :param file_path: File path of the key store file. type(str) :param password: Password for the key store file. It must include alphabet character, number, and special character. :return: An instance of Wallet class. """ if not is_password_of_keystore_file(password): raise KeyStoreException('Invalid password.') try: keystore = load_keyfile(file_path) if is_keystore_file(keystore): bytes_private_key = decode_keyfile_json(keystore, bytes(password, 'utf-8')) private_key_object = PrivateKey(bytes_private_key) wallet = KeyWallet(private_key_object) return wallet except FileNotFoundError: raise KeyStoreException("File is not found.") except ValueError: raise KeyStoreException("Password is wrong.")
def validate_keyfile(keyfile_path: Path) -> None: keyfile_data = eth_keyfile.load_keyfile(str(keyfile_path)) if keyfile_data["version"] != 3: raise AuthorizationError( f"Keyfile found at {keyfile_path} does not look like a supported eth-keyfile object." )
def get_keyfile_data() -> Dict[str, Any]: keyfile_path = get_keyfile_path() return eth_keyfile.load_keyfile(str(keyfile_path))
def _load_eth_key(path: str, password: str) -> (str, bytes): keyfile_data = load_keyfile(path) pkey = decode_keyfile_json(keyfile_data, password) return keyfile_data.get('address'), pkey
def test_method_validate_keystore_file(self): """Case when validating a keystore file correctly. """ keystore = load_keyfile(self.TEST_KEYSTORE_FILE_DIR) self.assertTrue(is_keystore_file(keystore)) keystore = load_keyfile(self.TEST_NOT_KEYSTORE_FILE_DIR) self.assertRaises(KeyStoreException, is_keystore_file, keystore)
from eth_keyfile import load_keyfile, decode_keyfile_json directory = "C:/Users/alegr/OneDrive/Documents/GitHub/ethereum/StealthAddresses/py/" keystore_file = "Keystore--975fbcbaeb9b3852b096ec0242aa2d96400406af.json" address = 0x975fbcbaeb9b3852b096ec0242aa2d96400406af tokens = 70000000000000000 nonce = 1 tx_data = address.to_bytes(20, 'big') tx_data += tokens.to_bytes(32, 'big') tx_data += nonce.to_bytes(32, 'big') message = keccak_256(tx_data).digest() #Import Scan and Spend Key password = getpass() priv_key = decode_keyfile_json(load_keyfile(directory + keystore_file), bytes(password, 'utf')) #Create Signature from py_ecc import secp256k1 sig = secp256k1.ecdsa_raw_sign(message, priv_key) print("data:") print(hex(int.from_bytes(tx_data, 'big'))) print() print("sig:") print(sig[0]) print(hex(sig[1])) print(hex(sig[2]))
def load_keyfile(self): self.keyfile_content = load_keyfile(self.keyfile_path) assert self.keyfile_content[ 'version'] == 3, 'Older keyfile versions not supported.'
def from_path(cls, path: str) -> LightWallet: return cls(load_keyfile(path))