def has_matching_signatures(self) -> bool: """ Check that the signatures match the terms of trade. :return: True if the transaction has been signed by both parties """ w3 = Web3() singable_message = encode_defunct(primitive=self.sender_hash) result = ( w3.eth.account.recover_message( signable_message=singable_message, signature=HexBytes(self.sender_signature), ) == self.sender_addr ) counterparty_signable_message = encode_defunct(primitive=self.counterparty_hash) result = ( result and w3.eth.account.recover_message( signable_message=counterparty_signable_message, signature=HexBytes(self.counterparty_signature), ) == self.counterparty_addr ) return result
def sign(self, msg=None, node=_node): if isinstance(msg, bytes): message = encode_defunct(msg) elif isinstance(msg, str): message = encode_defunct(hexstr=msg) else: raise Exception("Only string or bytes are signable.") return node.eth.account.sign_message( message, private_key=self.account.private_key)
def create_finalization_values(sk, balance, index, party): sigma_E_msg = "updated|" + str(index) sigma_E = w3.eth.account.sign_message(encode_defunct(text=sigma_E_msg), private_key=sk) msg = str(index) + "|" + str(balance) + "|0x" + str.upper(party[2:]) sigma_i = to_hex( w3.eth.account.sign_message(encode_defunct(text=msg), private_key=sk).signature) return sigma_E_msg, to_hex(sigma_E.signature), msg, sigma_i
def __check_token_owner(self, token_id, signature): # web3の初期化 provider = Web3.HTTPProvider(os.environ['PUBLIC_CHAIN_OPERATION_URL']) web3 = Web3(provider) # 署名からEOAのアドレスを復元 try: data = f"この署名はトークンを保有していることの証明に利用されます。\nTokenID: {token_id}" sender_address = web3.eth.account.recover_message( encode_defunct(text=data), signature=signature) except Exception: raise ValidationError('Invalid signature') # トークンの所有者を取得 license_token_contract = web3.eth.contract( web3.toChecksumAddress( os.environ['PUBLIC_CHAIN_LICENSE_TOKEN_ADDRESS']), abi=self.LICENSE_TOKEN_CONTRACT_ABI) try: owner_address = license_token_contract.functions.ownerOf( token_id).call() except Exception: # トークンが存在しないためエラー raise ValidationError('Invalid token_id - Token not found') # トークンの保有者では無い場合はエラー if owner_address != sender_address: raise ValidationError('Not owner of the token')
def authHeader(self, account, body): message = messages.encode_defunct( text='0x' + keccak_256(bytearray(dumps(body).encode('utf-8'))).hexdigest()) self.instance_headers['X-Flashbots-Signature'] = '%s:%s' % ( account.addr, eth_Account.sign_message( message, account.privateKey).signature.hex())
def sign(privateKey, msg): msg = msg private_key = privateKey message = encode_defunct(text=msg) signed_message = w3.eth.account.sign_message(message, private_key=private_key) print(signed_message)
def build_credentials(self) -> str: timestamp = str(int(datetime.timestamp(datetime.utcnow()))) signature = w3.eth.account.sign_message( encode_defunct(text=timestamp), private_key=self.private_key ).signature.hex() return base64.b64encode(f'{timestamp}:{signature}'.encode()).decode()
def submit_vote( network: str, oracle: LocalAccount, encoded_data: bytes, vote: Union[RewardVote, DistributorVote, ValidatorVote], name: str, ) -> None: """Submits vote to the votes' aggregator.""" network_config = NETWORKS[network] aws_bucket_name = network_config["AWS_BUCKET_NAME"] s3_client = boto3.client( "s3", aws_access_key_id=network_config["AWS_ACCESS_KEY_ID"], aws_secret_access_key=network_config["AWS_SECRET_ACCESS_KEY"], ) # generate candidate ID candidate_id: bytes = Web3.keccak(primitive=encoded_data) message = encode_defunct(primitive=candidate_id) signed_message = oracle.sign_message(message) vote["signature"] = signed_message.signature.hex() # TODO: support more aggregators (GCP, Azure, etc.) bucket_key = f"{oracle.address}/{name}" s3_client.put_object( Bucket=aws_bucket_name, Key=bucket_key, Body=json.dumps(vote), ACL="public-read", ) s3_client.get_waiter("object_exists").wait(Bucket=aws_bucket_name, Key=bucket_key)
def verify_chain_data(binFile=None, sig=None, test=True): contaddr, web3, net = get_net_url(test=test) # Check if signature is valid if len(sig) != 132: print("NO VALID SIGNATURE") return 0, None, "signature" # If a file is provided, then the user triggered the action under the "Verify" tab, else "Who singed...?" tab if binFile: _hashedFile = hash_file(binFile) message = messages.encode_defunct(primitive=_hashedFile) _addr, _abi = load_dependencies(contaddr, contabi) _contract = web3.eth.contract(address=_addr, abi=_abi) _addr = _contract.functions.getsig(sig).call() addr = web3.eth.account.recover_message(message, signature=HexBytes(sig)) # Verification if the address is either stored in the Smart Conract # and the signature and file result in the same address if _addr == addr: status = 1 else: status = 2 return status, _addr, addr # Calling the Smart Contract for verification if binFile == None and sig: _addr, _abi = load_dependencies(contaddr, contabi) _contract = web3.eth.contract(address=_addr, abi=_abi) _addr = _contract.functions.getsig(sig).call() if _addr and _addr != "0x0000000000000000000000000000000000000000": status2 = 1 else: status2 = 2 match = match_data(sig) return status2, _addr, match
def test_eth_account_sign(acct, message_text, key, expected_bytes, expected_hash, v, r, s, signature): message = encode_defunct(text=message_text) signed_message = Web3.keccak( b"\x19Ethereum Signed Message:\n" + bytes(f"{len(message.body)}", encoding='utf-8') + message.body ) assert signed_message == expected_hash signed = acct.sign_message(message, private_key=key) assert signed.messageHash == expected_hash assert signed.v == v assert signed.r == r assert signed.s == s assert signed.signature == signature account = acct.from_key(key) assert account.sign_message(message) == signed
def _sign_message(self, token_id): message = encode_defunct(text=str(token_id)) private_key = accounts[0].private_key signed_message = web3.eth.account.sign_message(message, private_key=private_key) return signed_message.signature
def verify(self, sign, data = None, address = None): if not address: address = self.default if not address: raise ValueError('Address not in wallet') address = self.Address(address) if address not in self: raise ValueError('Address not in wallet') if type(data) in [dict]: try: valid_address = Address(w3.eth.account.recover_transaction(sign)) return valid_address == address except: return False if not data: return False message = encode_defunct(text=str(data)) valid_address = Address(w3.eth.account.recover_message(message, signature=sign)) try: return valid_address == address except: return False
def Sig_done(adder_dis, model_up, ver_new, hash_f, ts): sk = bytes.fromhex("IoT機器の秘密鍵") hash_c = web3.soliditySha3( ["address", "string", "uint256", "bytes32", "uint256"], [adder_dis, model_up, ver_new, hash_f, ts]).hex() message = encode_defunct(hexstr=hash_c) return web3.eth.account.sign_message(message, private_key=sk).signature
def inner_wrap(*args, **kwargs): message = request.headers.get(MESSAGE_HEADER) signature = request.headers.get(SIGNATURE_HEADER) authed_user_id = None if message and signature: web3 = web3_provider.get_web3() encoded_to_recover = encode_defunct(text=message) wallet = web3.eth.account.recover_message( encoded_to_recover, signature=signature ) db = db_session.get_db_read_replica() with db.scoped_session() as session: user = ( session.query(User.user_id) .filter( # Convert checksum wallet to lowercase User.wallet == wallet.lower(), User.is_current == True, ) # In the case that multiple wallets match (not enforced on the data layer), # pick the user id that is lowest (created first). .order_by(User.user_id.asc()) .first() ) if user: authed_user_id = user.user_id logger.info( f"auth_middleware.py | authed_user_id: {authed_user_id}" ) return func(*args, **kwargs, authed_user_id=authed_user_id)
def process_tx(self): """ Processing transactions and finalize epoch :return: finalization and balance values """ for transaction_dump, signature in self._tx_queue: transaction = json.loads(transaction_dump) signature_bytes = to_bytes(hexstr=signature) encoding = encode_defunct(text=transaction_dump) sender = transaction["sender"] receiver = transaction["receiver"] value = transaction["value"] index = transaction["index"] signer = w3.eth.account.recover_message(encoding, signature=signature_bytes) if self._index != index or signer != sender or self._balances.get(sender, 0) < value\ or (sender, receiver, value) in self._transactions.get(sender, []): x = 0 else: tx_sender = self._transactions.get(sender, []) if tx_sender: self._transactions[sender] = tx_sender.append( (sender, receiver, value)) else: self._transactions[sender] = [(sender, receiver, value)] tx_receiver = self._transactions.get(receiver, []) if tx_receiver: self._transactions[receiver] = tx_receiver.append( (sender, receiver, value)) else: self._transactions[receiver] = [(sender, receiver, value)] self._balances[sender] = self._balances.get(sender, 0) - value self._balances[receiver] = self._balances.get(receiver, 0) + value return self.finalize()
def addAdmin(self): w3 = self.nodeSetup() contract = self.contractSetup() ketua_nonce = w3.eth.getTransactionCount( w3.toChecksumAddress(ketua_address)) msg = w3.soliditySha3( ["address", "uint256"], [w3.toChecksumAddress(admin_address), ketua_nonce], ) message = encode_defunct(primitive=msg) sign_message = w3.eth.account.sign_message(message, ketua_priv) # save to smart-contract nonce = w3.eth.getTransactionCount( w3.toChecksumAddress(default_address)) tx_hash = contract.functions.addAdminPetugas( w3.toChecksumAddress(admin_address), ketua_nonce, sign_message.signature, ).buildTransaction({ "chainId": 5777, "gas": 70000, "gasPrice": w3.toWei("1", "gwei"), "nonce": nonce, }) sign_tx = w3.eth.account.sign_transaction(tx_hash, default_priv) w3.eth.sendRawTransaction(sign_tx.rawTransaction) return w3.toHex(w3.keccak(sign_tx.rawTransaction))
def sig_test(filename, pubaddr, privkey): #acct = w3.eth.account.create('dkapd98fy7sd7dd') #print(acct.address) #print(acct.privateKey.hex()) print(pubaddr) print(privkey) file = open(filename, 'r') txnfile = file.read() print("file:") print(txnfile) txnjson = json.loads(txnfile) print(f'json: {json.dumps(txnjson)}') txn_s = txnjson['txn'] print(f'txn_s:') print(txn_s) #// This part prepares "version E" messages, using the EIP-191 standard #msg = str(txn).replace("'", '"').replace(' ', '') #print("msg:\n") #print(msg) message = messages.encode_defunct(text=txn_s) print("encoded message:") print(message) #// This part signs any EIP-191-valid message signed_message = Account.sign_message(message, private_key=privkey) print("signature =", signed_message.signature.hex()) txnjson['sig'] = signed_message.signature verify_txn_sig(txnjson)
def sign_message(self, account: str, message: bytes) -> str: """Sign, EIP-191 (Geth) Style""" signing_key = self.__get_signing_key(account=account) signable_message = encode_defunct(primitive=message) signature_and_stuff = Account.sign_message( signable_message=signable_message, private_key=signing_key) return signature_and_stuff['signature']
def registerPemilih(self): w3 = self.nodeSetup() contract = self.contractSetup() liveTime = time.mktime( datetime.strptime("26/03/2021 14:00:00", "%d/%m/%Y %H:%M:%S").timetuple()) tx_list = [] for i in range(len(pemilih_address)): petugas_nonce = w3.eth.getTransactionCount( w3.toChecksumAddress(petugas_address)) nonce = w3.eth.getTransactionCount( w3.toChecksumAddress(default_address)) msg = w3.soliditySha3( ['address', 'uint256'], [w3.toChecksumAddress(pemilih_address[i]), petugas_nonce]) message = encode_defunct(primitive=msg) sign_message = w3.eth.account.sign_message(message, petugas_priv) #save to smart-contract tx_hash = contract.functions.registerPemilih( w3.toChecksumAddress(pemilih_address[i]), petugas_nonce, int(liveTime), sign_message.signature).buildTransaction({ "chainId": 5777, "gas": 700000, "gasPrice": w3.toWei('1', 'gwei'), "nonce": nonce }) sign_tx = w3.eth.account.sign_transaction(tx_hash, default_priv) w3.eth.sendRawTransaction(sign_tx.rawTransaction) tx_list.append(w3.toHex(w3.keccak(sign_tx.rawTransaction))) return tx_list
def login(): if request.method == 'GET': return render_template('index.html') if request.method == 'POST': input = request.form['button'] if input == 'fc': data = { 'response_type': 'code', 'client_id': client_id, 'state': str(random.randint(0, 99999)), 'nonce': str(random.randint(10000, 999999)), 'redirect_uri': url_callback, 'scope': 'openid did_authn', 'client_did': client_did } session['flow'] = 'authorization_code' # data request is signed by client with its ECDSA key. Signature is added to data request canonical_message = data['nonce'] + data['client_did'] msg = encode_defunct(text=canonical_message) data['signature'] = Account.sign_message( msg, client_private_key).signature.hex() session['state'] = data['state'] print('step 1 : demande d autorisation envoyée ' + session['flow']) return redirect(talao_url_authorize + '?' + urlencode(data))
def recover_public_keys_from_message( cls, message: bytes, signature: str, is_deprecated_mode: bool = False) -> Tuple[str, ...]: """ Get the public key used to produce the `signature` of the `message` :param message: raw bytes used to produce signature :param signature: signature of the message :param is_deprecated_mode: if the deprecated signing was used :return: the recovered public keys """ if not is_deprecated_mode: signable_message = encode_defunct(primitive=message) message = _hash_eip191_message(signable_message) hash_bytes = HexBytes(message) # code taken from https://github.com/ethereum/eth-account/blob/master/eth_account/account.py#L428 if len(hash_bytes) != 32: # pragma: nocover raise ValueError("The message hash must be exactly 32-bytes") signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = keys.Signature( signature_bytes=signature_bytes_standard) pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return (str(pubkey), )
def get_ecrecover(self, signedData:str, data: str = None, dataHash: str = None): """ Get address associated with the signature (ecrecover) """ if (data is None) and (dataHash is None): cprint("Missing Argument, either 'dataHash' or 'data' must be passed?", "red") return 0 try: if data is not None: from eth_account.messages import encode_defunct, _hash_eip191_message hex_message_hash = w3.toHex(_hash_eip191_message(encode_defunct(hexstr=data))) elif dataHash is not None: hex_message_hash = dataHash sig = w3.toBytes(hexstr=signedData) v, hex_r, hex_s = w3.toInt(sig[-1]), w3.toHex(sig[:32]), w3.toHex(sig[32:64]) address = w3.eth.account.recoverHash(hex_message_hash, signature=sig) #TODO: verify this! seems that sometimes it returns wrong address # test with : # data="0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" # signedData="0xe7225f986f192f859a9bf84e34b2b7001dfa11aeb5c7164f81a2bee0d79943e2587be1faa11502eba0f803bb0ee071a082b6fe40fba025f3309263a1eef52c711c" # Correct address: 0xb60e8dd61c5d32be8058bb8eb970870f07233155 //based on https://wiki.parity.io/JSONRPC-personal-module.html#personal_ecrecover # Returned address: 0x02F0D4b967a73D6907a221DB6106446F1d3d4CDB cprint("Address: {}".format(address), "green") #TODO: make this print pretty json cprint("r: {}\ns: {}\nv: {} ".format(hex_r, hex_s, v), "white") except Exception as e: cprint("failed to get address: {} \n".format(e), "yellow")
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: self.logger.debug("Making request HTTP. URI: %s, Method: %s", self.endpoint_uri, method) request_data = self.encode_rpc_request(method, params) message = messages.encode_defunct(text=Web3.keccak( text=request_data.decode("utf-8")).hex()) signed_message = Account.sign_message( message, private_key=self.signature_account.privateKey.hex()) headers = self.get_request_headers() | { "X-Flashbots-Signature": f"{self.signature_account.address}:{signed_message.signature.hex()}" } raw_response = make_post_request(self.endpoint_uri, request_data, headers=headers) response = self.decode_rpc_response(raw_response) self.logger.debug( "Getting response HTTP. URI: %s, " "Method: %s, Response: %s", self.endpoint_uri, method, response, ) return response
def recover_message( cls, message: bytes, signature: str, is_deprecated_mode: bool = False) -> Tuple[Address, ...]: """ Recover the addresses from the hash. :param message: the message we expect :param signature: the transaction signature :param is_deprecated_mode: if the deprecated signing was used :return: the recovered addresses """ if is_deprecated_mode: enforce( len(message) == 32, "Message must be hashed to exactly 32 bytes.") with warnings.catch_warnings(): warnings.simplefilter("ignore") address = Account.recoverHash( # pylint: disable=no-value-for-parameter message_hash=message, signature=signature) else: signable_message = encode_defunct(primitive=message) address = Account.recover_message( # pylint: disable=no-value-for-parameter signable_message=signable_message, signature=signature) return (address, )
def get_signature(message: str, key: str) -> dict: """ Returns the signature of the given message when signed using the reveived key as the private key. :param message: string :param key: string :return: dict The key param will be interpreted as a hex string if possible. In that way, if an existing private key is received in hex form, the returned signature would be the same as if signed from the original wallet possesing that key. Otherwise a 32 bytes private key will be formed by adding leading null-bytes to the bytes of the received string. """ try: key = bytes.fromhex(key) except ValueError: key = bytes(key, 'utf-8') key = (b'\00' * 32 + key)[-32:] acc = Account.from_key(key) # the received message is encoded as in EIP-191 "version ``E``" encoded = encode_defunct(text=message) signed = acc.sign_message(encoded)['signature'].hex() return {"address": acc.address, "signature": signed, "message": message}
def Voting(self, json_data, user_data): w3 = es.SetupW3() pemilih_address, pemilih_access = ps.GetPemilihEthereumData(user_data) try: nonce = w3.eth.getTransactionCount(pemilih_address) msg = w3.soliditySha3( ["uint256", "uint256"], [int(json_data["kandidatId"]), nonce], ) message = encode_defunct(primitive=msg) sign_message = w3.eth.account.sign_message(message, pemilih_access) result = VotingTask.delay( int(json_data["kandidatId"]), nonce, sign_message.signature.hex(), ) if result == "Gagal": raise SolidityError except SolidityError: message_object = { "status": "Error", "message": "Terjadi kesalahan pada server", } return message_object else: ps.SavePemilihTxHistory(user_data, result.get(), sign_message.signature.hex()) message_object = { "status": "Berhasil", "message": "Anda berhasil memberikan suara anda", } return message_object
def derive_private_key(library: ZkSyncLibrary, message: str, account: BaseAccount, chain_id: ChainId): if chain_id != ChainId.MAINNET: message = f"{message}\nChain ID: {chain_id}." signable_message = encode_defunct(message.encode()) signature = account.sign_message(signable_message) private_key = library.private_key_from_seed(signature.signature) return private_key
def __call__(self, message: AnyStr) -> str: if type(message) == str: message = message.encode("utf8") if type(message) != bytes: raise TypeError("message only support str or bytes.") encoded_message = encode_defunct(hexstr=message.hex()) signed_message = w3.eth.account.sign_message(encoded_message, self.key) return signed_message.signature.hex()
def test_unlock_with_passphrase_and_sign_message(runner, temp_ape_account): temp_ape_account.unlock(passphrase="a") message = encode_defunct(text="Hello Apes!") # y: yes, sign (note: unlocking makes the key available but is not the same as autosign). with runner.isolation(input="y\n"): signature = temp_ape_account.sign_message(message) assert temp_ape_account.check_signature(message, signature)
def recover_address_eip_191(message: bytes, signature: bytes) -> str: """ Recover checksum address from EIP-191 signature """ signable_message = encode_defunct(primitive=message) recovery = Account.recover_message(signable_message=signable_message, signature=signature) recovered_address = to_checksum_address(recovery) return recovered_address