Пример #1
0
def buildTxApdu(dongle_path, data):
    """
	Generate apdu from tx data to be sent into the ledger key.

	Argument:
	dongle_path -- value returned by parseBip32Path
	data -- value returned by arky.core.crypto.getBytes

	Return bytes
	"""

    path_len = len(dongle_path)

    if len(data) > 255 - (path_len + 1):
        data1 = data[:255 - (path_len + 1)]
        data2 = data[255 - (path_len + 1):]
        p1 = util.unhexlify("e0040040")
    else:
        data1 = data
        data2 = util.unhexlify("")
        p1 = util.unhexlify("e0048040")

    return [
        p1 + util.intasb(path_len + 1 + len(data1)) +
        util.intasb(path_len // 4) + dongle_path + data1,
        util.unhexlify("e0048140") + util.intasb(len(data2)) +
        data2 if len(data2) else None
    ]
Пример #2
0
def getBytes(tx):
	"""
	Hash transaction object into bytes data.

	Argument:
	tx (dict) -- transaction object

	Return bytes sequence
	"""
	buf = BytesIO()
	# write type and timestamp
	pack("<bi", buf, (tx["type"], int(tx["timestamp"])))
	# write senderPublicKey as bytes in buffer
	if "senderPublicKey" in tx:
		pack_bytes(buf, unhexlify(tx["senderPublicKey"]))
	# if there is a requesterPublicKey
	if "requesterPublicKey" in tx:
		pack_bytes(buf, unhexlify(tx["requesterPublicKey"]))
	# if there is a recipientId
	if tx.get("recipientId", False):
		recipientId = tx["recipientId"]
		recipientId = base58.b58decode_check(str(recipientId) if not isinstance(recipientId, bytes) \
			else recipientId)
	else:
		recipientId = b"\x00" * 21
	pack_bytes(buf, recipientId)
	# if there is a vendorField
	if tx.get("vendorField", False):
		vendorField = tx["vendorField"][:64].ljust(64, "\x00")
	else:
		vendorField = "\x00" * 64
	pack_bytes(buf, vendorField.encode("utf-8"))
	# write amount and fee value
	pack("<QQ", buf, (int(tx["amount"]), int(tx["fee"])))
	# if there is asset data
	if tx.get("asset", False):
		asset = tx["asset"]
		typ = tx["type"]
		if typ == 1 and "signature" in asset:
			pack_bytes(buf, unhexlify(asset["signature"]["publicKey"]))
		elif typ == 2 and "delegate" in asset:
			pack_bytes(buf, asset["delegate"]["username"].encode("utf-8"))
		elif typ == 3 and "votes" in asset:
			pack_bytes(buf, "".join(asset["votes"]).encode("utf-8"))
		else:
			pass
	# if there is a signature
	if tx.get("signature", False):
		pack_bytes(buf, unhexlify(tx["signature"]))
	# if there is a second signature
	if tx.get("signSignature", False):
		pack_bytes(buf, unhexlify(tx["signSignature"]))

	result = buf.getvalue()
	buf.close()
	return result
Пример #3
0
def getAddress(publicKey):
	"""
	Computes ARK address from keyring.

	Argument:
	keys (ArkyDict) -- keyring returned by `getKeys`

	Return str
	"""
	ripemd160 = hashlib.new('ripemd160', unhexlify(publicKey)).digest()[:20]
	seed = unhexlify(cfg.marker) + ripemd160
	return base58.b58encode_check(seed)
Пример #4
0
def get(privateKey):
    """
	Generate a bytearray containing signature and random seed
	"""
    rand = os.urandom(128)
    return pack(
        bin.unhexlify(
            arky.core.crypto.getSignatureFromBytes(seed() + rand, privateKey)),
        rand)
Пример #5
0
def verifySignatureFromBytes(data, publicKey, signature):
	"""
	Verify signature.

	Arguments:
	data (bytes) -- data in bytes
	publicKey (str) -- a public key as hex string
	signature (str) -- a signature as hex string

	Return bool
	"""
	if len(publicKey) == 66:
		publicKey = uncompressEcdsaPublicKey(publicKey)
	verifyingKey = VerifyingKey.from_string(unhexlify(publicKey), SECP256k1, hashlib.sha256)
	try:
		verifyingKey.verify(unhexlify(signature), data, hashlib.sha256, sigdecode_der)
	except (BadSignatureError, UnexpectedDER):
		return False
	return True
Пример #6
0
def getWIF(seed):
	"""
	Computes WIF address from seed.

	Argument:
	seed (bytes) -- a sha256 sequence bytes

	Return str
	"""
	seed = unhexlify(cfg.wif) + seed[:32] + (b"\x01" if cfg.compressed else b"")
	return base58.b58encode_check(seed)
Пример #7
0
def buildPkeyApdu(dongle_path):
    """
	Generate apdu to get public key from ledger key.

	Argument:
	dongle_path -- value returned by parseBip32Path

	Return bytes
	"""

    path_len = len(dongle_path)
    return util.unhexlify("e0020040") + util.intasb(1 + path_len) + \
     util.intasb(path_len//4) + dongle_path
Пример #8
0
def getBytes(tx):
    buf = BytesIO()

    # write type and timestamp
    pack("<bi", buf, (tx["type"], int(tx["timestamp"])))
    # write senderPublicKey as bytes in buffer
    pack_bytes(buf, unhexlify(tx["senderPublicKey"]))
    # if there is a requesterPublicKey
    if "requesterPublicKey" in tx:
        pack_bytes(buf, unhexlify(tx["requesterPublicKey"]))
    # if there is a recipientId
    if "recipientId" in tx:
        pack(">Q", buf, (int(tx["recipientId"][:-len(cfg.marker)]), ))
    else:
        pack("<Q", buf, (0, ))
    # write amount
    pack("<Q", buf, (int(tx["amount"]), ))
    # if there is asset data
    if tx.get("asset", False):
        asset = tx["asset"]
        typ = tx["type"]
        if typ == 1 and "signature" in asset:
            pack_bytes(buf, unhexlify(asset["signature"]["publicKey"]))
        elif typ == 2 and "delegate" in asset:
            pack_bytes(buf, asset["delegate"]["username"].encode("utf-8"))
        elif typ == 3 and "votes" in asset:
            pack_bytes(buf, "".join(asset["votes"]).encode("utf-8"))
        else:
            pass
    # if there is a signature
    if tx.get("signature", False):
        pack_bytes(buf, unhexlify(tx["signature"]))
    # if there is a second signature
    if tx.get("signSignature", False):
        pack_bytes(buf, unhexlify(tx["signSignature"]))

    result = buf.getvalue()
    buf.close()
    return result
Пример #9
0
def loadBip39(pin, name="unamed"):
    """
	Decrypt your saved passphrase located in ~/.bip39/<network-name>.

	Argument:
	pin -- a str containing pin code (no limit in digit number) or a password

	Keyword argument:
	name -- the filname you want decrypt
	"""

    filename = os.path.join(HOME, ".bip39", cfg.network, name + ".bip39")
    if os.path.exists(filename):
        with io.open(filename, "rb") as in_:
            tmp = data.unScramble(data.createBase(pin), in_.read())
        return util.unhexlify(tmp).decode("utf-8")
Пример #10
0
def getSignatureFromBytes(data, privateKey):
	"""
	Generate data signature using private key.

	Arguments:
	data (bytes) -- data in bytes
	privateKey (str) -- a private key as hex string

	Return str
	"""
	signingKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1, hashlib.sha256)
	return hexlify(signingKey.sign_deterministic(
		data,
		hashlib.sha256,
		sigencode=sigencode_der_canonize)
	)
Пример #11
0
def getSignature(tx, privateKey):
	"""
	Generate transaction signature using private key.

	Arguments:
	tx (dict) -- a transaction description
	privateKey (str) -- a private key as hex string

	Return str
	"""
	signingKey = SigningKey.from_string(unhexlify(privateKey), SECP256k1, hashlib.sha256)
	return hexlify(signingKey.sign_deterministic(
		getBytes(tx),
		hashlib.sha256,
		sigencode=sigencode_der_canonize)
	)
Пример #12
0
def getSignature(tx, private):
    return hexlify(
        crypto_sign(hashlib.sha256(getBytes(tx)).digest(),
                    unhexlify(private))[:crypto_sign_BYTES])
Пример #13
0
def getAddress(public):
    seed = hashlib.sha256(unhexlify(public)).digest()
    return "%s%s" % (struct.unpack("<Q", seed[:8]) + (cfg.marker, ))
Пример #14
0
 def test_get_id_from_bytes(self):
     self.assertEqual(
         'a299642a90a25fdfea93eab43cf18c6ab21f1c16565d64066f896001594fd892',
         arky.core.crypto.getIdFromBytes(unhexlify(self.hexaTx)))