class Key(object): def __init__(self, secret=None) -> None: self.private_key = PrivateKey(secret) self.addr = address_by_public_key(self.private_key.public_key.format(False)) def sign(self, _hash: bytes) -> bytes: return self.private_key.sign_recoverable(_hash, None)
def signRecoverableMessage(pri_key, message): message = prepareMessage(message) privkey = PrivateKey( pri_key ) # we expect to have a private key as bytes. unhexlify it before passing. sig_check = privkey.sign_recoverable(message) return electrumSig(sig_check)
class Account(object): def __init__(self, keyfile, passfile): with open(keyfile) as data_file: data = json.load(data_file) with open(passfile) as f: password = f.read().strip('\n') privkey_bin = decode_keystore_json(data, password) self.private_key = PrivateKey(privkey_bin) def address(self): return binascii.hexlify( bytearray( sha3(self.private_key.public_key.format( compressed=False)[1:])[-20:])).decode('utf-8') def sign(self, messagedata): signature = self.private_key.sign_recoverable(messagedata, hasher=sha3) if len(signature) != 65: raise ValueError('invalid signature') return signature[:-1] + bytearray(chr(signature[-1] + 27), 'utf-8') def create_signed_message(self, user_address_hex, timestamp): message_data = (bytearray(address_decoder(user_address_hex)) + bytearray(struct.pack(">Q", timestamp))) sig = self.sign(message_data) message_data = message_data + bytearray(sig) return message_data
def sign(data: bytes, private_key: bytes) -> bytes: """ Generates on the ECDSA signature in bytes from data. :param data: data to be signed :param private_key: private key :return signature: signature made from input data """ private_key_object = PrivateKey(private_key) return private_key_object.sign_recoverable(data, hasher=None)
def sign(data: bytes, private_key: bytes) -> bytes: """ Generates on the ECDSA-SHA256 signature in bytes from data. It refers to a document on https://github.com/ludbb/secp256k1-py. :param data: data to be signed :param private_key: private key :return signature: signature made from input data """ private_key_object = PrivateKey(private_key) return private_key_object.sign_recoverable(data, hasher=None)
def sign(msg, private_key): """ Signs message using private key """ if not msg: raise ValueError("Message is required") if len(private_key) != eth_common_constants.PRIVATE_KEY_LEN: raise ValueError( "Private key is expected of len {0} but was {1}".format( eth_common_constants.PRIVATE_KEY_LEN, len(private_key))) new_private_key = PrivateKey(private_key) return new_private_key.sign_recoverable(msg, hasher=None)
def sign_transaction(self, private_key, transaction): """ Sign :param private_key: private key :param transaction: transaction :return: the signed transaction """ assert isinstance(transaction, Transaction), 'Invalid transaction' if isinstance(private_key, str): private_key = bytes(bytearray.fromhex(private_key)) if isinstance(private_key, bytes): private_key = PrivateKey(private_key) public_key = private_key.public_key.format(compressed=False) transaction.from_address.CopyFrom(self.get_address_from_public_key(public_key)) transaction.signature = private_key.sign_recoverable(transaction.SerializeToString()) return transaction
def sign_ecdsa(message, priv): """Gets ECDSA signature for message from private key.""" if not isinstance(message, (bytes, bytearray)): raise TypeError(f"Invalid message") if len(message) != 32: raise ValueError(f"Invalid length message: {len(message)} != 32") if not isinstance(priv, (bytes, bytearray)): raise TypeError(f"Invalid private key") if len(priv) != 32: raise ValueError(f"Invalid length private key: {len(priv)} != 32") privkey = PrivateKey(priv) sig_check = privkey.sign_recoverable(message, hasher=None) return sig_check
def sign(privkey: ContractsPrivateKey, msg_hash: bytes, v: int = 0) -> bytes: if not isinstance(msg_hash, bytes): raise TypeError("sign(): msg_hash is not an instance of bytes") if len(msg_hash) != 32: raise ValueError("sign(): msg_hash has to be exactly 32 bytes") if not isinstance(privkey, bytes): raise TypeError("sign(): privkey is not an instance of bytes") if v not in {0, 27}: raise ValueError(f"sign(): got v = {v} expected 0 or 27.") pk = PrivateKey(privkey) sig: bytes = pk.sign_recoverable(msg_hash, hasher=None) assert len(sig) == 65 pub = pk.public_key recovered = PublicKey.from_signature_and_message(sig, msg_hash, hasher=None) assert pub == recovered sig = sig[:-1] + bytes([sig[-1] + v]) return sig
from eth_utils import decode_hex, keccak from server import prefix, convert_eth_signature_and_data import binascii from coincurve import PublicKey, PrivateKey signature_jozef_orig = decode_hex( 'CC9E2B0B338D1BDD1328D88E6750F7CE5F7C6DEA8D73D4DE43E7755029576C1F07D8954640CB698A802729C4C31B17E9D1BF92B23A6CAEEAA2477087D5CCF3541C' ) message = b'{"timestamp":4180,"temperature":{"val1":25,"val2":173643},"lat":{"val1":1,"val2":2},"lon":{"val1":-4,"val2":5}}' private_key = PrivateKey() public_key = private_key.public_key private_key_2 = PrivateKey() public_key_2 = private_key.public_key # Prepare data! Message needs to be prefixed. Signature needs to be EIP converted? signature_jozef, message = convert_eth_signature_and_data( signature_jozef_orig, message) signature = private_key.sign_recoverable(prefix(message), hasher=keccak) print(signature.hex()) public_key_recovered = PublicKey.from_signature_and_message(signature, prefix(message), hasher=keccak) # Apparently verify() is never used because it doesn't do the signature schema!
def ecdsa_sign(msghash, privkey): pk = PrivateKey(privkey) return pk.sign_recoverable(msghash, hasher=None)
def sign_recoverable(hash_msg_str, pk_str): from coincurve import PrivateKey pk = PrivateKey(bytearray.fromhex(pk_str)) return pk.sign_recoverable(hash2hex(hash_msg_str), hasher=None).hex()
def ecdsa_sign(privkey, msghash): pk = PrivateKey(privkey) msghash = sha3(msghash) return pk.sign_recoverable(msghash, hasher=None)
class AElfTest(unittest.TestCase): _url = 'http://192.168.197.42:8000' _private_key = None _public_key = None def setUp(self): private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa' self._private_key = PrivateKey( bytes(bytearray.fromhex(private_key_string))) self._public_key = self._private_key.public_key.format( compressed=False) self.chain = AElf(self._url) self.toolkit = AElfToolkit(self._url, self._private_key) def test_chain_api(self): chain_status = self.chain.get_chain_status() print('# get_chain_status', chain_status) self.assertTrue(chain_status['BestChainHeight'] > 0) chain_id = self.chain.get_chain_id() print('# get_chain_id', chain_id) def test_block_api(self): block_height = self.chain.get_block_height() print('# get_block_height', block_height) self.assertTrue(block_height > 0) block = self.chain.get_block_by_height(1, include_transactions=True) print('# get_block_by_height', block) self.assertTrue(block['Header']['Height'] == 1) block2 = self.chain.get_block(block['BlockHash'], include_transactions=False) print('# get_block', block2) self.assertTrue(block['Header']['Height'] == 1) def test_transaction_result_api(self): block = self.chain.get_block_by_height(1, include_transactions=True) transaction_result = self.chain.get_transaction_result( block['Body']['Transactions'][0]) print('# get_transaction_result', transaction_result) self.assertTrue(transaction_result['Status'] == 'MINED') transaction_results = self.chain.get_transaction_results( block['BlockHash']) print('# get_transaction_results', transaction_results) merkle_path = self.chain.get_merkle_path( block['Body']['Transactions'][0]) self.assertTrue(isinstance(merkle_path['MerklePathNodes'], list)) def test_raw_transaction_api(self): transaction = { "From": self.chain.get_address_string_from_public_key(self._public_key), "To": self.chain.get_system_contract_address_string( "AElf.ContractNames.Consensus"), "RefBlockNumber": 0, "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa", "MethodName": "GetCurrentMinerList", "Params": '{}' } raw_transaction = self.chain.create_raw_transaction(transaction) signature = self._private_key.sign_recoverable( bytes.fromhex(raw_transaction['RawTransaction'])) transaction_1 = { "RawTransaction": raw_transaction['RawTransaction'], "Signature": signature.hex() } # test execute_raw_transaction print('# execute_raw_transaction', self.chain.execute_raw_transaction(transaction_1)) # test send_raw_transaction transaction_2 = { "Transaction": raw_transaction['RawTransaction'], 'Signature': signature.hex(), 'ReturnTransaction': True } print('# send_raw_transaction', self.chain.send_raw_transaction(transaction_2)) def test_send_transaction_api(self): current_height = self.chain.get_block_height() block = self.chain.get_block_by_height(current_height, include_transactions=False) transaction = Transaction() transaction.to_address.CopyFrom( self.chain.get_system_contract_address( "AElf.ContractNames.Consensus")) transaction.ref_block_number = current_height transaction.ref_block_prefix = bytes.fromhex(block['BlockHash'])[0:4] transaction.method_name = 'GetCurrentMinerList' transaction = self.chain.sign_transaction(self._private_key, transaction) result = self.chain.send_transaction( transaction.SerializePartialToString().hex()) print('# send_transaction', result) self.assertTrue(result['TransactionId'] != "") def test_tx_pool_api(self): tx_pool_status = self.chain.get_transaction_pool_status() print('# get_transaction_pool_status', tx_pool_status) self.assertTrue(tx_pool_status['Queued'] >= 0) def test_task_queue_api(self): task_queue_status = self.chain.get_task_queue_status() print('# get_task_queue_status', task_queue_status) self.assertTrue(len(task_queue_status) > 0) def test_network_api(self): print('# get_network_info', self.chain.get_network_info()) print('# remove_peer') self.assertTrue(self.chain.remove_peer('127.0.0.1:6801')) print('# add_peer') self.assertTrue(self.chain.add_peer('127.0.0.1:6801')) def test_miner_api(self): balance = self.toolkit.get_balance( 'ELF', '28Y8JA1i2cN6oHvdv7EraXJr9a1gY6D1PpJXw9QtRMRwKcBQMK') print('# get_balance', balance) miners = self.toolkit.get_current_miners() self.assertTrue(len(miners) > 0) print('# get_current_miners', len(miners)) for miner in miners: print(' > miner:', miner['public_key'], miner['address']) candidates = self.toolkit.get_candidates() print('# get_candidates', len(candidates)) self.assertTrue(len(candidates) >= 0) for candidate in candidates: print(' > candidate:', candidate['public_key'], candidate['address']) def test_helpers(self): is_connected = self.chain.is_connected() self.assertTrue(is_connected) address = self.chain.get_system_contract_address( "AElf.ContractNames.Consensus") formatted_address = self.chain.get_formatted_address(address) print('formatted address', formatted_address) self.assertIsNotNone(formatted_address)