예제 #1
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

    priv = utils.sha3('some big long brainwallet password')
    pub = bitcoin.privtopub(priv)

    msghash = utils.sha3('the quick brown fox jumps over the lazy dog')

    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(msghash, raw=True)
    )
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)

    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])
    assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr

    result = c.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S)
    assert result == addr
예제 #2
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if not is_bitcoin_available() or not is_secp256k1_available():
            raise ImportError(
                "In order to sign transactions the "
                "`bitcoin` and `secp256k1` packages must be installed."
            )
        from bitcoin import privtopub
        from secp256k1 import PrivateKey

        if key in (0, b'', b'\x00' * 32, b'0' * 64):
            raise ValueError("Zero privkey cannot sign")

        rawhash = decode_hex(sha3(rlp.encode(self, UnsignedTransaction)))

        if len(key) in {64, 66}:
            # we need a binary key
            key = decode_hex(key)

        pk = PrivateKey(key, raw=True)
        sig_bytes, rec_id = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = sig_bytes + force_bytes(chr(rec_id))
        self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27
        self.r = decode_big_endian_int(signature[0:32])
        self.s = decode_big_endian_int(signature[32:64])

        self.sender = to_address(sha3(privtopub(key)[1:])[-40:])
        return self
예제 #3
0
class Secp256k1_compact(object):
    def __init__(self):
        self.priv_key = PrivateKey()
        self.pub_key = PublicKey(pubkey=None, raw=False, flags=secp256k1.ALL_FLAGS)

    def ecdsa_compact_sign(self, msg32, privkey):
        if type(privkey) == unicode:
            privkey = privkey.encode('utf-8')
        self.priv_key.set_raw_privkey(privkey)
        sig = self.priv_key.ecdsa_sign_recoverable(msg32, raw=True)
        return self.priv_key.ecdsa_recoverable_serialize(sig)

    def ecdsa_compact_recover(self, msg32, sign):
        if not len(sign) == 2:
            sign = (sign[:64], ord(sign[64]))
        assert len(sign) == 2
        deserialized_sig = self.pub_key.ecdsa_recoverable_deserialize(sign[0], sign[1])
        self.pub_key.public_key = self.pub_key.ecdsa_recover(msg32, deserialized_sig, raw=True)
        return self.pub_key.serialize(compressed=False)

    def ecdsa_compact_verify(self, msg32, sign, pub):
        # Check if pubkey has been bin_electrum encoded.
        # If so, append \04 to the front of the key, to make sure the length is 65
        if len(pub) == 64:
            pub = '\04'+pub
        pub_k = PublicKey().deserialize(pub)
        pub_key = PublicKey(pub_k, raw=False, flags=secp256k1.ALL_FLAGS)
        der_sig = pub_key.ecdsa_recoverable_deserialize(sign[0], sign[1])
        raw_sig = pub_key.ecdsa_recoverable_convert(der_sig)
        return pub_key.ecdsa_verify(msg32, raw_sig, raw=True)
def sign_eth(rawhash, priv):
    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(rawhash, raw=True)
    )
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    v = utils.safe_ord(signature[64]) + 27
    r = utils.big_endian_to_int(signature[0:32])
    s = utils.big_endian_to_int(signature[32:64])
    return (v, r, s)
예제 #5
0
def getDeployedSecret(dongle, masterPrivate, targetid):
	testMaster = PrivateKey(bytes(masterPrivate))
	testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False))
	targetid = bytearray(struct.pack('>I', targetid))

	# identify
	apdu = bytearray([0xe0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid
	dongle.exchange(apdu)

	# walk the chain 
	batch_info = bytearray(dongle.exchange(bytearray.fromhex('E050000000')))
	cardKey = batch_info[5:5 + batch_info[4]]

	# if not found, get another pair
	#if cardKey <> testMasterPublic:
	#	raise Exception("Invalid batch public key")

	# provide the ephemeral certificate
	ephemeralPrivate = PrivateKey()
	ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False))
	print "Using ephemeral key " + str(ephemeralPublic).encode('hex')
	signature = testMaster.ecdsa_sign(bytes(ephemeralPublic))
	signature = testMaster.ecdsa_serialize(signature)
	certificate = bytearray([len(ephemeralPublic)]) + ephemeralPublic + bytearray([len(signature)]) + signature
	apdu = bytearray([0xE0, 0x51, 0x00, 0x00]) + bytearray([len(certificate)]) + certificate
	dongle.exchange(apdu)

	# walk the device certificates to retrieve the public key to use for authentication
	index = 0
	last_pub_key = PublicKey(bytes(testMasterPublic), raw=True)
	while True:
		certificate = bytearray(dongle.exchange(bytearray.fromhex('E052000000')))
		if len(certificate) == 0:
			break
		certificatePublic = certificate[1 : 1 + certificate[0]]
		certificateSignature = last_pub_key.ecdsa_deserialize(bytes(certificate[2 + certificate[0] :]))		
		if not last_pub_key.ecdsa_verify(bytes(certificatePublic), certificateSignature):
			if index == 0:
				# Not an error if loading from user key
				print "Broken certificate chain - loading from user key"
			else:
				raise Exception("Broken certificate chain")
		last_pub_key = PublicKey(bytes(certificatePublic), raw=True)
		index = index + 1

	# Commit device ECDH channel
	dongle.exchange(bytearray.fromhex('E053000000'))
	secret = last_pub_key.ecdh(bytes(ephemeralPrivate.serialize().decode('hex')))
	return str(secret[0:16])
예제 #6
0
파일: signing.py 프로젝트: ahuachen/raiden
def sign(messagedata, private_key):
    if not isinstance(private_key, bytes) or len(private_key) != 32:
        raise ValueError('invalid private_key')

    key = PrivateKey(private_key, raw=True)

    message_hash = sha3(messagedata)
    secp_signature = key.ecdsa_sign_recoverable(message_hash, raw=True)
    signature_data = key.ecdsa_recoverable_serialize(secp_signature)
    signature = signature_data[0] + chr(signature_data[1])

    if len(signature) != 65:
        raise ValueError('invalid signature')

    publickey = key.pubkey.serialize(compressed=False)

    return signature, publickey
예제 #7
0
def test_eth_sign(web3, skip_if_testrpc):
    skip_if_testrpc(web3)

    private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a'
    private_key = decode_hex(private_key_hex)

    # This imports the private key into the running geth instance and unlocks
    # the account so that it can sign things.
    # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0`
    address = web3.personal.importRawKey(private_key, "password")
    web3.personal.unlockAccount(address, "password")

    assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address)
    assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'

    # the data to be signed
    data = b'1234567890abcdefghijklmnopqrstuvwxyz'
    # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3`
    data_hash = web3.sha3(data, encoding=None)
    data_hash_bytes = decode_hex(data_hash)

    assert force_bytes(data_hash) == sha3(data)

    priv_key = PrivateKey(flags=ALL_FLAGS)
    priv_key.set_raw_privkey(private_key)

    # sanit check the extract_ecdsa_signer function works as expected.
    vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256)
    vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig)
    vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id))
    vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full))

    assert vector_address == address

    # Now have geth sign some data.
    signature_hex = web3.eth.sign(address, data)
    signature_bytes = decode_hex(signature_hex)

    actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes)

    assert actual_signer == address

    # Verify the signature against the public key derived from the
    # original private key.  It fails.
    rec_id = signature_bytes[64]
    if is_string(rec_id):
        rec_id = ord(rec_id)
    recoverable_signature = priv_key.ecdsa_recoverable_deserialize(
        signature_bytes[:64],
        rec_id,
    )
    signature = priv_key.ecdsa_recoverable_convert(recoverable_signature)
    is_valid = priv_key.pubkey.ecdsa_verify(
        msg=data,
        raw_sig=signature,
        digest=sha3_256,
    )

    assert is_valid
예제 #8
0
def test_receive_directtransfer_unknown(raiden_network):
    app0 = raiden_network[0]  # pylint: disable=unbalanced-tuple-unpacking
    graph0 = app0.raiden.channelgraphs.values()[0]

    other_key = PrivateKey(HASH, ctx=GLOBAL_CTX, raw=True)
    other_address = privatekey_to_address(other_key.private_key)
    direct_transfer = DirectTransfer(identifier=1,
                                     nonce=1,
                                     token=graph0.token_address,
                                     transferred_amount=10,
                                     recipient=app0.raiden.address,
                                     locksroot=HASH)
    sign_and_send(direct_transfer, other_key, other_address, app0)
예제 #9
0
def sign(data: bytes, private_key_seed_ascii: str, hash_function=bitcoin.bin_sha256):
    """Sign data using Ethereum private key.

    :param private_key_seed_ascii: Private key seed as ASCII string
    """

    msghash = hash_function(data)

    priv = utils.sha3(private_key_seed_ascii)
    pub = bitcoin.privtopub(priv)

    # Based on ethereum/tesrt_contracts.py test_ecrecover
    pk = PrivateKey(priv, raw=True)

    signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(msghash, raw=True))
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])

    v = utils.safe_ord(signature[64]) + 27
    r_bytes = signature[0:32]
    r = big_endian_to_int(r_bytes)
    s_bytes = signature[32:64]
    s = big_endian_to_int(s_bytes)

    #: XXX Ethereum wants its address in different format
    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])

    return {
        "signature": signature,
        "v": v,
        "r": r,
        "s": s,
        "r_bytes": r_bytes,
        "s_bytes": s_bytes,
        "address_bitcoin": addr,
        "address_ethereum": eth_privtoaddr(priv),
        "public_key": pub,
        "hash": msghash,
        "payload": bytes([v] + list(r_bytes)+ list(s_bytes,))
    }
예제 #10
0
def eth_sign(message: bytes, web3: Web3):
    assert(isinstance(message, bytes))
    assert(isinstance(web3, Web3))

    # as `EthereumTesterProvider` does not support `eth_sign`, we implement it ourselves
    if str(web3.providers[0]) == 'EthereumTesterProvider':
        key = k0
        msg = hexstring_to_bytes(Eth._recoveryMessageHash(data=message))

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(msg, 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

    return web3.manager.request_blocking(
        "eth_sign", [web3.eth.defaultAccount, encode_hex(message)],
    )
예제 #11
0
    def __init__(self, private_key=None):
        self.__private_key = private_key or PrivateKey()
        self.__address = self.create_address(self.__private_key.pubkey)
        self.__last_tx_hash = ""
        self.__hash_generator = get_tx_hash_generator(
            conf.LOOPCHAIN_DEFAULT_CHANNEL)

        self.to_address = None
        self.value = None
        self.message = None
        self.fee = ICX_FEE
        self.nid = '0x3'
        self.is_logging = True
예제 #12
0
    def test_verify_recoverable_sign(self):
        """Verifies recovering a signature."""

        test_requests = [
            TEST_REQUEST_TRANSFER_ICX, TEST_REQUEST_SCORE_FUNCTION_CALL,
            TEST_REQUEST_SEND_MESSAGE, TEST_REQUEST_SCORE_UPDATE,
            TEST_REQUEST_SCORE_ISNTALL
        ]

        for request in test_requests:
            # Serialize a signature
            private_key_object = PrivateKey()
            msg_hash_bytes = sha3_256(serialize(request["params"])).digest()
            sign_bytes = sign(msg_hash_bytes, private_key_object.private_key)

            # Deserialize a signature
            recoverable_sign = private_key_object.ecdsa_recoverable_deserialize(
                sign_bytes[0:64], sign_bytes[64])
            sign_ = private_key_object.ecdsa_recoverable_convert(
                recoverable_sign)
            # Verify a signature with a public key
            self.assertTrue(
                private_key_object.pubkey.ecdsa_verify(msg_hash_bytes,
                                                       sign_,
                                                       raw=True))

            # Verify a signature when an message is invalid
            invalid_msg_hash = sha3_256(f'invalid message'.encode()).digest()
            self.assertFalse(
                private_key_object.pubkey.ecdsa_verify(invalid_msg_hash,
                                                       sign_,
                                                       raw=True))

            # Verify a signature when a private key is invalid
            invalid_private_key = PrivateKey()
            self.assertFalse(
                invalid_private_key.pubkey.ecdsa_verify(msg_hash_bytes,
                                                        sign_,
                                                        raw=True))
예제 #13
0
class PingServer(object):
    def __init__(self, my_endpoint):
        self.endpoint = my_endpoint

        ## get private key
        priv_key_file = open('priv_key', 'r')
        priv_key_serialized = priv_key_file.read()
        priv_key_file.close()
        self.priv_key = PrivateKey()
        self.priv_key.deserialize(priv_key_serialized)

    def wrap_packet(self, packet):
        payload = packet.packet_type + rlp.encode(packet.pack())
        sig = self.priv_key.ecdsa_sign_recoverable(keccak256(payload),
                                                   raw=True)
        sig_serialized = self.priv_key.ecdsa_recoverable_serialize(sig)
        payload = sig_serialized[0] + chr(sig_serialized[1]) + payload

        payload_hash = keccak256(payload)
        return payload_hash + payload

    def udp_listen(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(('0.0.0.0', self.endpoint.udpPort))

        def receive_ping():
            print "listening..."
            data, addr = sock.recvfrom(1024)
            print "received message[", addr, "]"

        return threading.Thread(target=receive_ping)

    def ping(self, endpoint):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ping = PingNode(self.endpoint, endpoint)
        message = self.wrap_packet(ping)
        print "sending ping."
        sock.sendto(message, (endpoint.address.exploded, endpoint.udpPort))
예제 #14
0
def proxyDeleteApp(dongle, args):
    args.targetId = auto_int(args.targetId)
    if args.appName == None:
        raise Exception("Missing appName")
    if args.targetId == None:
        args.targetId = 0x31000002
    if args.rootPrivateKey == None:
        privateKey = PrivateKey()
        publicKey = str(
            privateKey.pubkey.serialize(compressed=False)).encode('hex')
        print "Generated random root public key : " + publicKey
        args.rootPrivateKey = privateKey.serialize().encode('ascii')

    if args.deployLegacy:
        secret = getDeployedSecretV1(dongle,
                                     bytearray.fromhex(args.rootPrivateKey),
                                     args.targetId)
    else:
        secret = getDeployedSecretV2(dongle,
                                     bytearray.fromhex(args.rootPrivateKey),
                                     args.targetId)
    loader = HexLoader(dongle, 0xe0, True, secret)
    loader.deleteApp(args.appName)
예제 #15
0
파일: views.py 프로젝트: scresh/fashion_dlt
    def get(self, request):
        try:
            private_key_hex = request.GET.get('private_key')
            public_key_hex = request.GET.get('public_key')

            private_key = PrivateKey(bytes(bytearray.fromhex(private_key_hex)),
                                     raw=True)
            if public_key_hex == private_key.pubkey.serialize().hex():
                return JsonResponse({'result': 'OK'})

            else:
                return JsonResponse({'result': 'Key pair does not match'})
        except:
            return JsonResponse({'result': 'Incorrect values'})
예제 #16
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if key in (0, '', b'\x00' * 32, '0' * 64):
            raise InvalidTransaction("Zero privkey cannot sign")
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))

        if len(key) == 64:
            # we need a binary key
            key = encode_privkey(key, 'bin')

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True))
        signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
        self.v = utils.safe_ord(signature[64]) + 27
        self.r = big_endian_to_int(signature[0:32])
        self.s = big_endian_to_int(signature[32:64])

        self.sender = utils.privtoaddr(key)
        return self
예제 #17
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if key in (0, '', b'\x00' * 32, '0' * 64):
            raise InvalidTransaction("Zero privkey cannot sign")
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))

        if len(key) == 64:
            # we need a binary key
            key = encode_privkey(key, 'bin')

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
        self.v = utils.safe_ord(signature[64]) + 27
        self.r = big_endian_to_int(signature[0:32])
        self.s = big_endian_to_int(signature[32:64])

        self.sender = utils.privtoaddr(key)
        return self
예제 #18
0
def main():
	# Generate keypair which we will use for signing block header
	privkey = PrivateKey()
	pubkey = privkey.pubkey

	print('Private key: {}'.format(privkey.serialize()))
	print('Public key: {}'.format(pubkey.serialize().hex()))

	# Execure Proof-of-Work for block header
	# For sake of simplicity this example uses sha256d as PoW function
	raw_header, signature = miner({
		'version': 1,
		'prev_block': "0000000000000000000000000000000000000000000000000000000000000000",
		'merkle_root': "4e9a7450cf706f05c9f7cf6b6f4c4c267e911c0d8d5066df1da4deb318637fd3",
		'timestamp': 1568015489,
		'bits': 524287999,
		'nonce': 0,
		'miner_pubkey': pubkey.serialize().hex()
	}, privkey)

	mined_hash = sha256d(raw_header + signature)
	mined_header = header_deserialize(raw_header)

	print('Block hash:', mined_hash[::-1].hex())
	print('Block nonce:', mined_header['nonce'])

	# Validate Proof-of-Work
	pow_validation = validate_target(mined_hash, mined_header['bits'])
	print('PoW validation: {}'.format(pow_validation))

	# Validate header signature
	sighash = ripemd160(raw_header)
	miner_pubkey = bytes(bytearray.fromhex(mined_header['miner_pubkey']))
	header_signature = signature[::-1]
	signature_validation = validate_signature(sighash, header_signature, miner_pubkey)
	print('Signature validation: {}'.format(signature_validation))
예제 #19
0
    def __init__(self, private_key=None):
        self.__private_key = private_key or PrivateKey()
        self.__address = self.create_address(self.__private_key.pubkey)
        self.__last_tx_hash = ""

        tx_hash_version = 1
        self.__hash_generator = build_hash_generator(tx_hash_version,
                                                     "icx_sendTransaction")

        self.to_address = None
        self.value = None
        self.message = None
        self.fee = ICX_FEE
        self.nid = '0x3'
        self.is_logging = True
예제 #20
0
파일: game.py 프로젝트: ziwon/nekoyume
 def decorated_function(*args, **kwargs):
     private_key_hex = session.get('private_key')
     error = None
     if private_key_hex is not None:
         if private_key_hex.startswith(('0x', '0X')):
             private_key_hex = private_key_hex[2:]
         try:
             private_key_bytes = bytes.fromhex(private_key_hex)
             private_key = PrivateKey(private_key_bytes)
         except (ValueError, TypeError):
             error = 'invalid-private-key'
         else:
             g.user = User(private_key)
             return f(*args, **kwargs)
     return redirect(url_for('.get_login', next=request.url, error=error))
예제 #21
0
def test_receive_directtransfer_unknown(raiden_network):
    app0 = raiden_network[0]  # pylint: disable=unbalanced-tuple-unpacking
    asset_manager0 = app0.raiden.managers_by_asset_address.values()[0]

    other_key = PrivateKey(sha3("rainyweather"), ctx=GLOBAL_CTX, raw=True)
    other_address = privatekey_to_address(other_key.private_key)
    direct_transfer = DirectTransfer(
        identifier=1,
        nonce=1,
        asset=asset_manager0.asset_address,
        transferred_amount=10,
        recipient=app0.raiden.address,
        locksroot=sha3("muchrain")
    )
    sign_and_send(direct_transfer, other_key, other_address, app0)
예제 #22
0
class IcxVerifier:
    _pri = PrivateKey()

    def __init__(self):
        self._address: str = None
        self._serialize_pubkey: bytes = None

    @property
    def address(self):
        return self._address

    @property
    def peer_cert(self):
        return self._serialize_pubkey

    def _init_using_pub(self, pubkey: bytes):
        self._serialize_pubkey = pubkey
        hash_pub = hashlib.sha3_256(self._serialize_pubkey[1:]).hexdigest()
        self._address = f"hx{hash_pub[-40:]}"

    def init_and_verify_address(self, pubkey: bytes, address: str):
        self._init_using_pub(pubkey)
        if self._address != address:
            raise ValueError(f"Invalid Address : {address}")

    def verify_data(self, origin_data: bytes, signature: bytes):
        return self.__verify_signature(origin_data, signature, False)

    def verify_hash(self, origin_data, signature):
        return self.__verify_signature(origin_data, signature, True)

    def __verify_signature(self, origin_data: bytes, signature: bytes,
                           is_hash):
        try:
            if is_hash:
                origin_data = binascii.unhexlify(origin_data)
            origin_signature, recover_code = signature[:-1], signature[-1]
            recoverable_sig = self._pri.ecdsa_recoverable_deserialize(
                origin_signature, recover_code)
            pub = self._pri.ecdsa_recover(origin_data,
                                          recover_sig=recoverable_sig,
                                          raw=is_hash,
                                          digest=hashlib.sha3_256)
            extract_pub = PublicKey(pub).serialize(compressed=False)
            return self._serialize_pubkey == extract_pub
        except Exception:
            logging.debug(f"signature verify fail : {origin_data} {signature}")
            return False
예제 #23
0
def test_receive_mediatedtransfer_invalid_address(raiden_network,
                                                  private_keys):
    alice_app = raiden_network[0]
    setup_messages_cb()

    graph = alice_app.raiden.channelgraphs.values()[0]
    token_address = graph.token_address

    mt_helper = MediatedTransferTestHelper(raiden_network, graph)
    initiator_address = alice_app.raiden.address
    path = mt_helper.get_paths_of_length(initiator_address, 2)

    alice_address, bob_address, charlie_address = path
    amount = 10
    alice_app.raiden.api.transfer(
        token_address,
        amount,
        charlie_address,
    )
    gevent.sleep(1.)

    # and now send one more mediated transfer with the same nonce, simulating
    # an out-of-order/resent message that arrives late
    locksroot = HASH
    lock = Lock(amount, 1, locksroot)
    identifier = create_default_identifier(
        alice_app.raiden.address,
        graph.token_address,
        charlie_address,
    )
    mediated_transfer = MediatedTransfer(identifier=identifier,
                                         nonce=1,
                                         token=token_address,
                                         transferred_amount=amount,
                                         recipient=bob_address,
                                         locksroot=locksroot,
                                         lock=lock,
                                         target=charlie_address,
                                         initiator=initiator_address,
                                         fee=0)
    alice_key = PrivateKey(private_keys[0])
    target_app = None
    for app in raiden_network:
        if app.raiden.address not in path:
            target_app = app
            break
    sign_and_send(mediated_transfer, alice_key, alice_address, target_app)
예제 #24
0
async def rmain(config_file, remark):
    with open(config_file, 'r') as stream:
        config = yaml.safe_load(stream)
        
    pri_key = bytes.fromhex(config['distribution_pkey'])
    # address = await get_address(pub_key, config['chain_id'], config['prefix'])
    # pri_key = bytes.fromhex(config['source_pkey'])
    privkey = PrivateKey(pri_key, raw=True)
    pub_key = privkey.pubkey.serialize()
    address = await get_address(pub_key, config['chain_id'], config['prefix'])
    server = get_server(config['api_server'])
    
    distribution_list = []    
    content = await fetch_aggregate(config['aleph_balances_oracle'], 'contract_'+config['old_contract_address'] , api_server=config['aleph_api_server'])
    distribution_list = [
        (address, amount)
        for address, amount in content['holders'].items()
        if address != config['old_source_address'] 
    ]
    print(distribution_list)

    nonce = None

    # return
#    for address in addresses[:50]:
#        nutxo = await nuls_packer([address],
#                                  method='transfer', gas_limit=20000,
#                                  gas_price=100,
#                                  utxo=nutxo)
#        print(address)
    max_items = config.get('bulk_max_items')
    if len(distribution_list):
        for i in range(math.ceil(len(distribution_list) / max_items)):
            step_items = distribution_list[max_items*i:max_items*(i+1)]
            nash = await contract_call_packer(
                server, config['distribution_address'], config['contract_address'],
                'batchTransferFrom',
                [[config['source_address'],],
                 [i[0] for i in step_items],
                 [str(int(i[1])) for i in step_items]],
                pri_key, nonce=nonce, remark=remark,
                chain_id=config['chain_id'],
                asset_id=config.get('asset_id', 1),
                gas_limit=len(step_items)*30000)
            nonce = nash[-16:]
            await asyncio.sleep(10)
            print("distribution stage", i, len(step_items), "items")
예제 #25
0
    def __init__(self, private_key=None):
        self.__private_key = private_key or PrivateKey()
        self.__address = self.create_address(self.__private_key.pubkey)
        self.__last_tx_hash = ""

        tx_hash_versions = conf.CHANNEL_OPTION[conf.LOOPCHAIN_DEFAULT_CHANNEL]["hash_versions"]
        self.__hash_generators = {
            "0x2": build_hash_generator(tx_hash_versions["0x2"], "icx_sendTransaction"),
            "0x3": build_hash_generator(tx_hash_versions["0x3"], "icx_sendTransaction")
        }

        self.to_address = None
        self.value = None
        self.message = None
        self.fee = ICX_FEE
        self.nid = '0x3'
        self.is_logging = True
예제 #26
0
def make_key_store_content(password):
    """ Make a content of key_store.
    :param password: Password including alphabet character, number, and special character.
    If the user doesn't give password with -p, then CLI will show the prompt and user need to type the password.
    :return: key_store_content (dict)
    """
    # create PrivateKey object and using this, make public key, address
    private_key_obj = PrivateKey()
    private_key = private_key_obj.private_key
    public_key = private_key_obj.pubkey.serialize(compressed=False)
    address = f'hx{address_from_public_key(public_key).hex()}'
    key_store_contents = create_keyfile_json(private_key,
                                             password.encode(),
                                             iterations=16384,
                                             kdf="scrypt")
    key_store_contents['coinType'] = 'icx'
    key_store_contents['address'] = address
    return key_store_contents
예제 #27
0
def make_mediated_transfer(channel,
                           partner_channel,
                           initiator,
                           target,
                           lock,
                           pkey,
                           block_number,
                           secret=None):
    """ Helper to create and register a mediated transfer from `channel` to
    `partner_channel`.
    """
    identifier = channel.our_state.nonce
    fee = 0

    receiver = channel.partner_state.address

    mediated_transfer = channel.create_mediatedtransfer(
        initiator,
        receiver,
        fee,
        lock.amount,
        identifier,
        lock.expiration,
        lock.hashlock,
    )

    address = privatekey_to_address(pkey)
    sign_key = PrivateKey(pkey, ctx=GLOBAL_CTX, raw=True)
    mediated_transfer.sign(sign_key, address)

    channel.block_number = block_number
    partner_channel.block_number = block_number

    # if this fails it's not the right key for the current `channel`
    assert mediated_transfer.sender == channel.our_state.address

    channel.register_transfer(mediated_transfer)
    partner_channel.register_transfer(mediated_transfer)

    if secret is not None:
        channel.register_secret(secret)
        partner_channel.register_secret(secret)

    return mediated_transfer
예제 #28
0
def test_receive_mediatedtransfer_unknown(raiden_network):
    app0 = raiden_network[0]  # pylint: disable=unbalanced-tuple-unpacking
    graph0 = app0.raiden.channelgraphs.values()[0]

    other_key = PrivateKey(HASH, ctx=GLOBAL_CTX, raw=True)
    other_address = privatekey_to_address(other_key.private_key)
    amount = 10
    locksroot = HASH
    mediated_transfer = MediatedTransfer(identifier=1,
                                         nonce=1,
                                         token=graph0.token_address,
                                         transferred_amount=amount,
                                         recipient=app0.raiden.address,
                                         locksroot=locksroot,
                                         lock=Lock(amount, 1, locksroot),
                                         target=privatekey_to_address(HASH2),
                                         initiator=other_address,
                                         fee=0)
    sign_and_send(mediated_transfer, other_key, other_address, app0)
예제 #29
0
def test_receive_directtransfer_outoforder(raiden_network, private_keys):
    app0, app1 = raiden_network  # pylint: disable=unbalanced-tuple-unpacking

    graph0 = app0.raiden.channelgraphs.values()[0]
    graph1 = app1.raiden.channelgraphs.values()[0]

    channel0 = graph0.partneraddress_channel[app1.raiden.address]
    channel1 = graph1.partneraddress_channel[app0.raiden.address]

    balance0 = channel0.balance
    balance1 = channel1.balance

    assert graph0.token_address == graph1.token_address
    assert app1.raiden.address in graph0.partneraddress_channel

    amount = 10
    app0.raiden.api.transfer(
        graph0.token_address,
        amount,
        target=app1.raiden.address,
    )
    gevent.sleep(1)

    assert_synched_channels(channel0, balance0 - amount, [], channel1,
                            balance1 + amount, [])

    # and now send one more direct transfer with the same nonce, simulating
    # an out-of-order/resent message that arrives late
    identifier = create_default_identifier(
        app0.raiden.address,
        graph0.token_address,
        app1.raiden.address,
    )
    direct_transfer = DirectTransfer(
        identifier=identifier,
        nonce=1,
        token=graph0.token_address,
        transferred_amount=10,
        recipient=app1.raiden.address,
        locksroot=HASH,
    )
    app0_key = PrivateKey(private_keys[0])
    sign_and_send(direct_transfer, app0_key, app0.raiden.address, app1)
예제 #30
0
class BlockVerifier(ABC):
    _ecdsa = PrivateKey()

    def __init__(self):
        self.invoke_func: Callable[['Block'], ('Block', dict)] = None

    @abstractmethod
    def verify(self, block: 'Block', prev_block: 'Block', blockchain=None):
        raise RuntimeError

    @abstractmethod
    def verify_loosely(self,
                       block: 'Block',
                       prev_block: 'Block',
                       blockchain=None):
        raise RuntimeError

    def verify_signature(self, block: 'Block'):
        recoverable_sig = self._ecdsa.ecdsa_recoverable_deserialize(
            block.header.signature.signature(),
            block.header.signature.recover_id())
        raw_public_key = self._ecdsa.ecdsa_recover(block.header.hash,
                                                   recover_sig=recoverable_sig,
                                                   raw=True,
                                                   digest=hashlib.sha3_256)

        public_key = PublicKey(raw_public_key, ctx=self._ecdsa.ctx)
        hash_pub = hashlib.sha3_256(
            public_key.serialize(compressed=False)[1:]).digest()
        expect_address = hash_pub[-20:]
        if expect_address != block.header.peer_id:
            raise RuntimeError(
                f"block peer id {block.header.peer_id.hex_xx()}, "
                f"expected {ExternalAddress(expect_address).hex_xx()}")

    @classmethod
    def new(cls, version: str) -> 'BlockVerifier':
        from . import v0_1a
        if version == v0_1a.version:
            return v0_1a.BlockVerifier()

        raise RuntimeError
def test_decode_mediated_transfer(private_keys, settle_timeout, tester_state,
                                  tester_token, tester_events,
                                  tester_registry):

    privatekey0 = tester.DEFAULT_KEY
    privatekey1 = tester.k1
    privatekey2 = tester.k2
    address0 = privatekey_to_address(privatekey0)
    address1 = privatekey_to_address(privatekey1)
    address2 = privatekey_to_address(privatekey2)

    dtester = deploy_decoder_tester(tester_state, tester_token.address,
                                    address0, address1, settle_timeout)

    locksroot = sha3("Sikorka")
    amount = 1337
    expiration = 5
    lock = Lock(amount, expiration, locksroot)

    message = MediatedTransfer(identifier=313151,
                               nonce=88924902,
                               token=tester_token.address,
                               transferred_amount=amount,
                               recipient=address1,
                               locksroot=locksroot,
                               lock=lock,
                               target=address2,
                               initiator=address0)

    message.sign(PrivateKey(privatekey0, ctx=GLOBAL_CTX, raw=True), address0)
    _, publickey = wrap_and_validate(message.encode())
    recovered_address = address_from_key(publickey)
    assert recovered_address == address0

    assert dtester.testDecodeTransfer(message.encode(),
                                      sender=privatekey1) is True
    assert dtester.decodedNonce() == 88924902
    assert dtester.decodedExpiration() == expiration
    assert dtester.decodedToken() == tester_token.address.encode('hex')
    assert dtester.decodedRecipient() == address1.encode('hex')
    assert dtester.decodedAmount() == amount
    assert dtester.decodedLocksroot() == locksroot
예제 #32
0
async def nuls_packer(config):
    from secp256k1 import PrivateKey

    pri_key = bytes.fromhex(config.nuls.private_key.value)
    privkey = PrivateKey(pri_key, raw=True)
    pub_key = privkey.pubkey.serialize()
    address = await get_address(pub_key, config.nuls.chain_id.value)
    LOGGER.info("NULS Connector set up with address %s" % address)
    utxo = await get_utxo(config, address)
    i = 0
    while True:
        if (i >= 100) or (utxo[0]['value'] < CHEAP_UNIT_FEE):
            await asyncio.sleep(30)  # wait three (!!) blocks
            # utxo = await get_utxo(config, address)
            i = 0

        utxo = await get_utxo(config, address)
        selected_utxo = utxo[:10]
        messages = [
            message async for message in (await Message.get_unconfirmed_raw(
                limit=5000, for_chain=CHAIN_NAME))
        ]
        if len(messages):
            content = await get_chaindata(messages, bulk_threshold=600)
            content = json.dumps(content)
            tx = await prepare_businessdata_tx(address, selected_utxo,
                                               content.encode('UTF-8'))
            await tx.sign_tx(pri_key)
            tx_hex = (await tx.serialize()).hex()
            # tx_hash = await tx.get_hash()
            LOGGER.info("Broadcasting TX")
            tx_hash = await broadcast(config, tx_hex)
            utxo = [{
                'hash': tx_hash,
                'idx': 0,
                'lockTime': 0,
                'value': tx.coin_data.outputs[0].na
            }]

        await asyncio.sleep(11)

        i += 1
예제 #33
0
    def test_sign_recoverable_verify_sig(self):
        # get sign, recovery
        sign, recovery_id = self.signer.sign_recoverable(self.hashed_message)

        # Convert recoverable sig to normal sig
        deserialized_recoverable_sig = self.test_private_key.ecdsa_recoverable_deserialize(sign, recovery_id)
        normal_sig = self.test_private_key.ecdsa_recoverable_convert(deserialized_recoverable_sig)

        # Check sig
        self.assertTrue(self.test_private_key.pubkey.ecdsa_verify(self.hashed_message, normal_sig, raw=True))

        # Verify using invalid message
        m = hashlib.sha256()
        m.update(b'invalid message')
        invalid_message = m.digest()
        self.assertFalse(self.test_private_key.pubkey.ecdsa_verify(invalid_message, normal_sig, raw=True))

        # Verify using invalid private key
        invalid_privateKey = PrivateKey()
        self.assertFalse(invalid_privateKey.pubkey.ecdsa_verify(self.hashed_message, normal_sig, raw=True))
예제 #34
0
    def __init__(self, chain, private_key_bin, transport, discovery, config):
        # pylint: disable=too-many-arguments

        if not isinstance(private_key_bin,
                          bytes) or len(private_key_bin) != 32:
            raise ValueError('invalid private_key')

        private_key = PrivateKey(
            private_key_bin,
            ctx=GLOBAL_CTX,
            raw=True,
        )
        pubkey = private_key.pubkey.serialize(compressed=False)

        self.registries = list()
        self.managers_by_asset_address = dict()
        self.managers_by_address = dict()
        self.event_listeners = list()

        self.chain = chain
        self.config = config
        self.privkey = private_key_bin
        self.pubkey = pubkey
        self.private_key = private_key
        self.address = privatekey_to_address(private_key_bin)
        self.protocol = RaidenProtocol(transport, discovery, self)
        transport.protocol = self.protocol

        message_handler = RaidenMessageHandler(self)
        event_handler = RaidenEventHandler(self)

        alarm = AlarmTask(chain)
        alarm.start()

        self.api = RaidenAPI(self)
        self.alarm = alarm
        self.event_handler = event_handler
        self.message_handler = message_handler

        self.on_message = message_handler.on_message
        self.on_event = event_handler.on_event
예제 #35
0
def _sha3_secp256k1_deploy_data(current_height,
                                bytecode,
                                value,
                                quota,
                                privatekey,
                                version=0,
                                receiver=None):
    sender = get_sender(privatekey, False)
    if privatekey is None:
        temp = private_key()
        privkey = PrivateKey(hex2bytes(temp))
    else:
        privkey = PrivateKey(hex2bytes(privatekey))

    logger.debug(sender)
    nonce = get_nonce()
    logger.debug("nonce is {}".format(nonce))
    chainid = get_chainid()
    logger.debug("chainid is {}".format(chainid))

    tx = Transaction()
    tx.valid_until_block = current_height + 88
    tx.nonce = nonce
    tx.chain_id = chainid
    tx.version = version
    if receiver is not None:
        tx.to = receiver
    tx.data = hex2bytes(bytecode)
    tx.value = value.to_bytes(32, byteorder='big')
    tx.quota = quota

    message = sha3(tx.SerializeToString())

    logger.debug("hash message: {}")
    sign_recover = privkey.ecdsa_sign_recoverable(message, raw=True)
    sig = privkey.ecdsa_recoverable_serialize(sign_recover)

    signature = binascii.hexlify(sig[0]) + binascii.hexlify(
        bytes(bytearray([sig[1]])))

    unverify_tx = UnverifiedTransaction()
    unverify_tx.transaction.CopyFrom(tx)
    unverify_tx.signature = hex2bytes(signature)
    unverify_tx.crypto = Crypto.Value('SECP')

    logger.info("unverify_tx is {}".format(
        binascii.hexlify(unverify_tx.SerializeToString())))
    return binascii.hexlify(unverify_tx.SerializeToString())
예제 #36
0
파일: wallet.py 프로젝트: icona2/crawling
    def load(file_path, password):
        """Loads a wallet from a keystore file with your password and generates an instance of Wallet.

        :param file_path: File path of the keystore file. type(str)
        :param password:
            Password for the keystore file.
            It must include alphabet character, number, and special character.
        :return: An instance of Wallet class.
        """
        try:
            with open(file_path, 'rb') as file:
                bytes_private_key = extract_key_from_keyfile(file, 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.")
        except Exception as e:
            raise KeyStoreException(f'keystore file error.{e}')
예제 #37
0
def test_receive_mediatedtransfer_unknown(raiden_network):
    app0 = raiden_network[0]  # pylint: disable=unbalanced-tuple-unpacking
    asset_manager0 = app0.raiden.managers_by_asset_address.values()[0]

    other_key = PrivateKey(sha3("rainstopped"), ctx=GLOBAL_CTX, raw=True)
    other_address = privatekey_to_address(other_key.private_key)
    amount = 10
    locksroot = sha3("muchsunny")
    mediated_transfer = MediatedTransfer(
        identifier=1,
        nonce=1,
        asset=asset_manager0.asset_address,
        transferred_amount=amount,
        recipient=app0.raiden.address,
        locksroot=locksroot,
        lock=Lock(amount, 1, locksroot),
        target=privatekey_to_address(sha3("cloudsagain")),
        initiator=other_address,
        fee=0
    )
    sign_and_send(mediated_transfer, other_key, other_address, app0)
예제 #38
0
def test_receive_directtransfer_invalidlocksroot(raiden_network, private_keys):
    app0, app1 = raiden_network  # pylint: disable=unbalanced-tuple-unpacking

    token_manager0 = app0.raiden.managers_by_token_address.values()[0]
    token_manager1 = app1.raiden.managers_by_token_address.values()[0]

    channel0 = token_manager0.partneraddress_channel[app1.raiden.address]
    channel1 = token_manager1.partneraddress_channel[app0.raiden.address]

    balance0 = channel0.balance
    balance1 = channel1.balance

    assert token_manager0.token_address == token_manager1.token_address
    assert app1.raiden.address in token_manager0.partneraddress_channel

    amount = 10
    app0.raiden.api.transfer(
        token_manager0.token_address,
        amount,
        target=app1.raiden.address,
    )
    gevent.sleep(1)

    assert_synched_channels(channel0, balance0 - amount, [], channel1,
                            balance1 + amount, [])

    # and now send one more direct transfer with the locksroot not set correctly
    direct_transfer = DirectTransfer(
        identifier=app0.raiden.api.create_default_identifier(
            app1.raiden.address,
            token_manager0.token_address,
        ),
        nonce=2,
        token=token_manager0.token_address,
        transferred_amount=10,
        recipient=app1.raiden.address,
        locksroot=HASH,
    )
    app0_key = PrivateKey(private_keys[0])
    sign_and_send(direct_transfer, app0_key, app0.raiden.address, app1)
예제 #39
0
def make_direct_transfer(channel, partner_channel, amount, pkey):
    """ Helper to create and register a direct transfer from `channel` to
    `partner_channel`.
    """
    identifier = channel.our_state.nonce

    direct_transfer = channel.create_directtransfer(
        amount,
        identifier=identifier,
    )

    address = privatekey_to_address(pkey)
    sign_key = PrivateKey(pkey, ctx=GLOBAL_CTX, raw=True)
    direct_transfer.sign(sign_key, address)

    # if this fails it's not the right key for the current `channel`
    assert direct_transfer.sender == channel.our_state.address

    channel.register_transfer(direct_transfer)
    partner_channel.register_transfer(direct_transfer)

    return direct_transfer
if args.signedHex == None:
	raise Exception("Missing output signed hex filename")
if args.sigAddr == None:
	raise Exception("Missing signature start address")

# parse
parser = IntelHexParser(args.hex)
printer = IntelHexPrinter(parser)

# prepare data
dataToHash = ""
# consider areas are ordered by ascending address and non-overlaped
for a in parser.getAreas():
	dataToHash += a.data

m = hashlib.sha256()
m.update(dataToHash)
dataToSign = m.digest()

print "Hash: " + dataToSign.encode('hex')

# sign
signKey = PrivateKey(bytes(bytearray.fromhex(args.key)))
sign = signKey.ecdsa_sign(bytes(dataToSign), raw=True)
sign = signKey.ecdsa_serialize(sign)

#append sign and print out
printer.addArea(args.sigAddr, sign + "FFFFFFFF".decode('hex'))
printer.writeTo(args.signedHex)

예제 #41
0
 def __init__(self):
     self.priv_key = PrivateKey()
     self.pub_key = PublicKey(pubkey=None, raw=False, flags=secp256k1.ALL_FLAGS)
예제 #42
0
def sign(data: bytes, private_key_seed_ascii: str):
    priv = private_key_seed_ascii
    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(data, raw=True))
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    return signature, eth_privtoaddr(priv)
예제 #43
0
from ledgerblue.deployed import getDeployedSecret
from ledgerblue.hexLoader import HexLoader
import argparse

def auto_int(x):
    return int(x, 0)

parser = argparse.ArgumentParser()
parser.add_argument("--targetId", help="Set the chip target ID", type=auto_int)
parser.add_argument("--appName", help="Set the application name")
parser.add_argument("--rootPrivateKey", help="Set the root private key")
parser.add_argument("--apdu", help="Display APDU log", action='store_true')

args = parser.parse_args()

if args.appName == None:
	raise Exception("Missing appName")
if args.targetId == None:
	args.targetId = 0x31000001
if args.rootPrivateKey == None:
	privateKey = PrivateKey()
	publicKey = str(privateKey.pubkey.serialize(compressed=False)).encode('hex')
	print "Generated random root public key : " + publicKey
	args.rootPrivateKey = privateKey.serialize().encode('ascii')

dongle = getDongle(args.apdu)

secret = getDeployedSecret(dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId)
loader = HexLoader(dongle, 0xe0, True, secret)
loader.deleteApp(args.appName)