diff --git a/CHANGELOG.md b/CHANGELOG.md index 384c278f..ecee0212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## Unreleased +### Fixed + +- Deserialize the vendor field into `vendorFieldHex`, which also fixes the id of transactions with a vendor field +- Serialize transactions that only have a `vendorFieldHex` +- Write the vendor field length in bytes, so non-ASCII vendor fields serialize correctly +- `str()` of `HTLC_LOCK_EXPIRATION_TYPE` values no longer raises a `TypeError` +- `verify_schnorr_secondsig` returns `True` when valid, like the other verify methods +- Deserializing an unsigned transaction leaves `signature` unset instead of an empty string + +### Removed + +- Broken `sign` methods on the `Vote` and `DelegateRegistration` builders (use `schnorr_sign`) +- Unused internal `_handle_transaction_type` and `_handle_signature` methods on `Transaction` + ## 2.0.0 - 2021-09-21 ## Fixed diff --git a/crypto/constants.py b/crypto/constants.py index e5cf084f..ba7ce848 100644 --- a/crypto/constants.py +++ b/crypto/constants.py @@ -52,7 +52,7 @@ def __int__(self): class HTLC_LOCK_EXPIRATION_TYPE(Enum): def __str__(self): - return int(self.value) + return str(self.value) EPOCH_TIMESTAMP = 1 BLOCK_HEIGHT = 2 diff --git a/crypto/transactions/builder/delegate_registration.py b/crypto/transactions/builder/delegate_registration.py index 04a0a0f7..64836361 100644 --- a/crypto/transactions/builder/delegate_registration.py +++ b/crypto/transactions/builder/delegate_registration.py @@ -1,5 +1,4 @@ from crypto.constants import TRANSACTION_DELEGATE_REGISTRATION -from crypto.identity.public_key import PublicKey from crypto.transactions.builder.base import BaseTransactionBuilder @@ -20,8 +19,3 @@ def __init__(self, username, fee=None): if fee: self.transaction.fee = fee - - def sign(self, passphrase): - public_key = PublicKey.from_passphrase(passphrase) - self.transaction.asset['delegate']['publicKey'] = public_key - super().sign(passphrase) diff --git a/crypto/transactions/builder/vote.py b/crypto/transactions/builder/vote.py index baf9be9f..9b642734 100644 --- a/crypto/transactions/builder/vote.py +++ b/crypto/transactions/builder/vote.py @@ -1,5 +1,4 @@ from crypto.constants import TRANSACTION_VOTE -from crypto.identity.address import address_from_passphrase from crypto.transactions.builder.base import BaseTransactionBuilder @@ -20,7 +19,3 @@ def __init__(self, vote, fee=None): if fee: self.transaction.fee = fee - - def sign(self, passphrase): - self.transaction.recipientId = address_from_passphrase(passphrase) - super().sign(passphrase) diff --git a/crypto/transactions/deserializer.py b/crypto/transactions/deserializer.py index c0d9f73f..6cb847f9 100644 --- a/crypto/transactions/deserializer.py +++ b/crypto/transactions/deserializer.py @@ -38,11 +38,10 @@ def deserialize(self): vendor_field_length = read_bit8(self.serialized, offset=58) if vendor_field_length > 0: - vendor_field_offset = (58 + 8) * 2 - vendorField_take = vendor_field_length * 2 + vendor_field_offset = 59 transaction.vendorFieldHex = hexlify( - self.serialized - )[vendor_field_offset:vendorField_take] + self.serialized[vendor_field_offset:vendor_field_offset + vendor_field_length] + ) asset_offset = (58 + 1) * 2 + vendor_field_length * 2 @@ -68,17 +67,13 @@ def _handle_transaction_type(self, asset_offset, transaction): """ deserializer_name = TRANSACTION_TYPES[transaction.type] module = import_module('crypto.transactions.deserializers.{}'.format(deserializer_name)) - for attr in dir(module): - # If attr name is `BaseDeserializer`, skip it as it's a class and also has a - # subclass of BaseDeserializer - if attr == 'BaseDeserializer': - continue - - attribute = getattr(module, attr) - if inspect.isclass(attribute) and issubclass(attribute, BaseDeserializer): - # this attribute is actually a specific deserializer that we want to use - deserializer = attribute - break + # Use the module's subclass of BaseDeserializer, which the module also imports + deserializer = [ + attribute for attribute in vars(module).values() + if inspect.isclass(attribute) + and issubclass(attribute, BaseDeserializer) + and attribute is not BaseDeserializer + ][0] return deserializer(self.serialized, asset_offset, transaction).deserialize() def _handle_version_two(self, transaction): diff --git a/crypto/transactions/serializer.py b/crypto/transactions/serializer.py index f95e9c93..c88de23d 100644 --- a/crypto/transactions/serializer.py +++ b/crypto/transactions/serializer.py @@ -41,13 +41,13 @@ def serialize(self, skip_signature=True, skip_second_signature=True, skip_multi_ bytes_data += write_bit64(self.transaction.get('fee')) if self.transaction.get('vendorField'): - vendorFieldLength = len(self.transaction.get('vendorField')) - bytes_data += write_bit8(vendorFieldLength) - bytes_data += self.transaction['vendorField'].encode() + vendor_field = self.transaction['vendorField'].encode() + bytes_data += write_bit8(len(vendor_field)) + bytes_data += vendor_field elif self.transaction.get('vendorFieldHex'): - vendorField_hex_length = len(self.transaction['vendorFieldHex']) - bytes_data += write_bit8(vendorField_hex_length / 2) - bytes_data += self.transaction['vendorFieldHex'] + vendor_field = unhexlify(self.transaction['vendorFieldHex']) + bytes_data += write_bit8(len(vendor_field)) + bytes_data += vendor_field else: bytes_data += write_bit8(0x00) bytes_data = self._handle_transaction_type(bytes_data) @@ -67,17 +67,13 @@ def _handle_transaction_type(self, bytes_data): serializer_name = TRANSACTION_TYPES[self.transaction['type']] module = import_module('crypto.transactions.serializers.{}'.format(serializer_name)) - for attr in dir(module): - # If attr name is `BaseSerializer`, skip it as it's a class and also has a - # subclass of BaseSerializer - if attr == 'BaseSerializer': - continue - - attribute = getattr(module, attr) - if inspect.isclass(attribute) and issubclass(attribute, BaseSerializer): - # this attribute is actually a specific serializer that we want to use - serializer = attribute - break + # Use the module's subclass of BaseSerializer, which the module also imports + serializer = [ + attribute for attribute in vars(module).values() + if inspect.isclass(attribute) + and issubclass(attribute, BaseSerializer) + and attribute is not BaseSerializer + ][0] return serializer(self.transaction, bytes_data).serialize() def _handle_signature(self, bytes_data, skip_signature, skip_second_signature, skip_multi_signature): diff --git a/crypto/transactions/transaction.py b/crypto/transactions/transaction.py index b3a2a653..166faf9c 100644 --- a/crypto/transactions/transaction.py +++ b/crypto/transactions/transaction.py @@ -1,14 +1,6 @@ import json -from binascii import unhexlify from hashlib import sha256 -from binary.hex.writer import write_high -from binary.unsigned_integer.writer import write_bit8 - -from crypto.constants import ( - TRANSACTION_DELEGATE_REGISTRATION, TRANSACTION_MULTI_SIGNATURE_REGISTRATION, - TRANSACTION_SECOND_SIGNATURE_REGISTRATION, TRANSACTION_VOTE -) from crypto.exceptions import ArkInvalidTransaction from crypto.schnorr import schnorr from crypto.transactions.deserializer import Deserializer @@ -104,7 +96,7 @@ def parse_signatures(self, serialized, start_offset): signature_end_offset = start_offset + (64 * 2) - if len(serialized) - signature_end_offset % 65 != 0: + if len(serialized) >= signature_end_offset: self.signature = serialized[start_offset:signature_end_offset] second_signature_end_offset = signature_end_offset + (64 * 2) @@ -167,10 +159,12 @@ def verify_schnorr_secondsig(self, secondPublicKey): returns True """ is_valid = schnorr.b410_schnorr_verify(self.to_bytes(False, True), secondPublicKey, self.signSignature) - + if not is_valid: raise ArkInvalidTransaction('Transaction could not be verified') - + + return is_valid + def verify_schnorr_multisig(self): """Verify the multisignatures transaction. Method will raise an exception if invalid, it will returns True @@ -181,46 +175,3 @@ def verify_schnorr_multisig(self): raise ArkInvalidTransaction('Transaction could not be verified') return is_valid - - def _handle_transaction_type(self, bytes_data): - """Handled each transaction type differently - - Args: - bytes_data (bytes): input the bytes data to which you want to append new bytes - - Raises: - NotImplementedError: raised only if the child transaction doesn't implement this - required method - """ - if self.type == TRANSACTION_SECOND_SIGNATURE_REGISTRATION: - public_key = self.asset['signature']['publicKey'] - bytes_data += unhexlify(public_key) - elif self.type == TRANSACTION_DELEGATE_REGISTRATION: - bytes_data += self.asset['delegate']['username'].encode() - elif self.type == TRANSACTION_VOTE: - bytes_data += ''.join(self.asset['votes']).encode() - elif self.type == TRANSACTION_MULTI_SIGNATURE_REGISTRATION: - bytes_data += write_bit8(self.asset['multiSignature']['min']) - bytes_data += ''.join(self.asset['multiSignature']['publicKeys']).encode() - - return bytes_data - - def _handle_signature(self, bytes_data, skip_signature, skip_second_signature, skip_multi_signature): - """Internal method, used to handle the signature - - Args: - bytes_data (bytes): input the bytes data to which you want to append new bytes from - signature - skip_signature (bool): whether you want to skip it or not - skip_second_signature (bool): whether you want to skip it or not - - Returns: - bytes: bytes string - """ - if not skip_signature and self.signature: - bytes_data += write_high(self.signature) - if not skip_second_signature and self.signSignature: - bytes_data += write_high(self.signSignature) - if not skip_multi_signature and self.signatures: - bytes_data += write_high(self.signatures) - return bytes_data diff --git a/tests/configuration/test_network.py b/tests/configuration/test_network.py index 3b608e45..7915546a 100644 --- a/tests/configuration/test_network.py +++ b/tests/configuration/test_network.py @@ -33,3 +33,11 @@ def test_set_custom_network(): assert result['wif'] == 130 assert result['epoch'] == epoch_time set_network(Devnet) # set back to devnet so other tests don't fail + + +def test_get_network_defaults_to_devnet(monkeypatch): + monkeypatch.setattr('crypto.configuration.network.network', {}) + result = get_network() + assert result['version'] == Devnet.version + assert result['wif'] == Devnet.wif + assert result['epoch'] == Devnet.epoch diff --git a/tests/identity/test_address.py b/tests/identity/test_address.py index 512a9f2b..9b34e943 100644 --- a/tests/identity/test_address.py +++ b/tests/identity/test_address.py @@ -1,6 +1,8 @@ from crypto.identity.address import ( address_from_passphrase, address_from_private_key, address_from_public_key, validate_address ) +from crypto.networks.devnet import Devnet +from crypto.networks.mainnet import Mainnet def test_address_from_public_key(identity): @@ -20,3 +22,26 @@ def test_address_from_passphrase(identity): def test_validate_address(identity): assert validate_address(identity['data']['address']) is True + + +def test_address_from_public_key_with_network_version(identity): + address = address_from_public_key(identity['data']['public_key'], Devnet.version) + assert address == identity['data']['address'] + assert address_from_public_key(identity['data']['public_key'], Mainnet.version) != address + + +def test_address_from_private_key_with_network_version(identity): + address = address_from_private_key(identity['data']['private_key'], Devnet.version) + assert address == identity['data']['address'] + assert address_from_private_key(identity['data']['private_key'], Mainnet.version) != address + + +def test_address_from_passphrase_with_network_version(identity): + address = address_from_passphrase(identity['passphrase'], Devnet.version) + assert address == identity['data']['address'] + assert address_from_passphrase(identity['passphrase'], Mainnet.version) != address + + +def test_validate_address_with_network_version(identity): + assert validate_address(identity['data']['address'], Devnet.version) is True + assert validate_address(identity['data']['address'], Mainnet.version) is False diff --git a/tests/identity/test_wif.py b/tests/identity/test_wif.py index ddb7b936..b0056d2e 100644 --- a/tests/identity/test_wif.py +++ b/tests/identity/test_wif.py @@ -1,6 +1,14 @@ from crypto.identity.wif import wif_from_passphrase +from crypto.networks.devnet import Devnet +from crypto.networks.testnet import Testnet def test_wif_from_passphrase(identity): result = wif_from_passphrase(identity['passphrase']) assert result == identity['data']['wif'] + + +def test_wif_from_passphrase_with_network_wif(identity): + result = wif_from_passphrase(identity['passphrase'], Devnet.wif) + assert result == identity['data']['wif'] + assert wif_from_passphrase(identity['passphrase'], Testnet.wif) != result diff --git a/tests/schnorr/__init__.py b/tests/schnorr/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/schnorr/test_schnorr.py b/tests/schnorr/test_schnorr.py new file mode 100644 index 00000000..2d86c7e0 --- /dev/null +++ b/tests/schnorr/test_schnorr.py @@ -0,0 +1,126 @@ +import hashlib +from binascii import hexlify, unhexlify + +import pytest + +from crypto.identity.private_key import PrivateKey +from crypto.identity.public_key import PublicKey +from crypto.schnorr import schnorr + +PASSPHRASE = 'this is a top secret passphrase' +MESSAGE = hashlib.sha256(b'message').digest() + + +def _secret(): + return unhexlify(PrivateKey.from_passphrase(PASSPHRASE).to_hex()) + + +def _public_key(): + return unhexlify(PublicKey.from_passphrase(PASSPHRASE)) + + +def test_y_from_x_not_on_curve(): + assert schnorr.y_from_x(5) is None + + +def test_point_from_encoded_not_on_curve(): + with pytest.raises(ValueError, match='Point not on ``secp256k1`` curve'): + schnorr.point_from_encoded(b'\x02' + schnorr.bytes_from_int(5)) + + +def test_point_without_coordinates(): + assert schnorr.Point() == [0, None] + + +def test_point_decode_encode(): + public_key = _public_key() + assert schnorr.Point.decode(public_key).encode() == public_key + + +def test_point_multiply_by_non_int(): + with pytest.raises(TypeError, match="'2' should be an int"): + schnorr.G * '2' + + +def test_point_add_non_list(): + with pytest.raises(TypeError, match="'2' should be a 2-int-length list"): + schnorr.G + 2 + + +def test_point_add_none(): + assert schnorr.point_add(None, schnorr.G) == schnorr.G + assert schnorr.point_add(schnorr.G, None) == schnorr.G + + +def test_point_add_inverse_points(): + inverse = [schnorr.G.x, -schnorr.G.y % schnorr.p] + + with pytest.raises(ValueError, match='One of the point is not on the curve'): + schnorr.point_add(schnorr.G, inverse) + + +def test_sign_and_verify(): + signature = schnorr.bcrypto410_sign(MESSAGE, _secret()) + + assert schnorr.bcrypto410_verify(MESSAGE, _public_key(), signature) is True + + +def test_b410_schnorr_verify(): + signature = schnorr.bcrypto410_sign(hashlib.sha256(b'message').digest(), _secret()) + + assert schnorr.b410_schnorr_verify( + b'message', + PublicKey.from_passphrase(PASSPHRASE), + hexlify(signature), + ) is True + + +def test_sign_invalid_message_length(): + with pytest.raises(ValueError, match='The message must be a 32-byte array.'): + schnorr.bcrypto410_sign(b'message', _secret()) + + +def test_sign_invalid_secret_key(): + with pytest.raises(ValueError, match='The secret key must be an integer in the range 1..n-1.'): + schnorr.bcrypto410_sign(MESSAGE, schnorr.bytes_from_int(0)) + + with pytest.raises(ValueError, match='The secret key must be an integer in the range 1..n-1.'): + schnorr.bcrypto410_sign(MESSAGE, schnorr.bytes_from_int(schnorr.n)) + + +def test_sign_zero_nonce(monkeypatch): + monkeypatch.setattr(schnorr, 'hash_sha256', lambda b: schnorr.bytes_from_int(schnorr.n)) + + with pytest.raises(RuntimeError, match='This happens only with negligible probability.'): + schnorr.bcrypto410_sign(MESSAGE, _secret()) + + +def test_verify_invalid_message_length(): + signature = schnorr.bcrypto410_sign(MESSAGE, _secret()) + + with pytest.raises(ValueError, match='The message must be a 32-byte array.'): + schnorr.bcrypto410_verify(b'message', _public_key(), signature) + + +def test_verify_invalid_signature_length(): + with pytest.raises(ValueError, match='The signature must be a 64-byte array.'): + schnorr.bcrypto410_verify(MESSAGE, _public_key(), b'signature') + + +def test_verify_signature_out_of_range(): + signature = schnorr.bytes_from_int(schnorr.p) + schnorr.bytes_from_int(1) + assert schnorr.bcrypto410_verify(MESSAGE, _public_key(), signature) is False + + signature = schnorr.bytes_from_int(1) + schnorr.bytes_from_int(schnorr.n) + assert schnorr.bcrypto410_verify(MESSAGE, _public_key(), signature) is False + + +def test_verify_wrong_message(): + signature = schnorr.bcrypto410_sign(MESSAGE, _secret()) + other_message = hashlib.sha256(b'other message').digest() + + assert schnorr.bcrypto410_verify(other_message, _public_key(), signature) is False + + +def test_hash_sha256_with_str(): + assert schnorr.hash_sha256('message') == schnorr.hash_sha256(b'message') diff --git a/tests/test_constants.py b/tests/test_constants.py new file mode 100644 index 00000000..2226abf8 --- /dev/null +++ b/tests/test_constants.py @@ -0,0 +1,12 @@ +from crypto.constants import HTLC_LOCK_EXPIRATION_TYPE, TRANSACTION_TYPE_GROUP + + +def test_transaction_type_group_to_int(): + assert int(TRANSACTION_TYPE_GROUP.TEST) == 0 + assert int(TRANSACTION_TYPE_GROUP.CORE) == 1 + assert int(TRANSACTION_TYPE_GROUP.RESERVED) == 1000 + + +def test_htlc_lock_expiration_type_to_str(): + assert str(HTLC_LOCK_EXPIRATION_TYPE.EPOCH_TIMESTAMP) == '1' + assert str(HTLC_LOCK_EXPIRATION_TYPE.BLOCK_HEIGHT) == '2' diff --git a/tests/transactions/builder/test_base.py b/tests/transactions/builder/test_base.py new file mode 100644 index 00000000..dea36e4e --- /dev/null +++ b/tests/transactions/builder/test_base.py @@ -0,0 +1,58 @@ +import json + +from crypto.configuration.network import set_network +from crypto.constants import HTLC_LOCK_EXPIRATION_TYPE, TRANSACTION_TYPE_GROUP +from crypto.networks.devnet import Devnet +from crypto.transactions.builder.transfer import Transfer + +set_network(Devnet) + + +def _transfer(): + return Transfer(recipientId='AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC', amount=200000000) + + +def test_to_json(): + transaction = _transfer() + transaction.set_nonce(1) + transaction.schnorr_sign('this is a top secret passphrase') + + data = json.loads(transaction.to_json()) + + assert data == transaction.to_dict() + assert data['nonce'] == 1 + assert data['signature'] + + +def test_set_expiration_with_int(): + transaction = _transfer() + transaction.set_expiration(1573455822) + + assert transaction.transaction.expiration == 1573455822 + + +def test_set_expiration_with_expiration_type(): + transaction = _transfer() + + transaction.set_expiration(HTLC_LOCK_EXPIRATION_TYPE.EPOCH_TIMESTAMP) + assert transaction.transaction.expiration == 1 + + transaction.set_expiration(HTLC_LOCK_EXPIRATION_TYPE.BLOCK_HEIGHT) + assert transaction.transaction.expiration == 2 + + +def test_set_type_group_with_int(): + transaction = _transfer() + transaction.set_type_group(1000) + + assert transaction.transaction.typeGroup == 1000 + + +def test_set_type_group_with_type_group(): + transaction = _transfer() + + transaction.set_type_group(TRANSACTION_TYPE_GROUP.TEST) + assert transaction.transaction.typeGroup == 0 + + transaction.set_type_group(TRANSACTION_TYPE_GROUP.RESERVED) + assert transaction.transaction.typeGroup == 1000 diff --git a/tests/transactions/builder/test_multi_signature_registration.py b/tests/transactions/builder/test_multi_signature_registration.py index bd471d65..263a5ff0 100644 --- a/tests/transactions/builder/test_multi_signature_registration.py +++ b/tests/transactions/builder/test_multi_signature_registration.py @@ -43,3 +43,12 @@ def test_multi_signature_registration_transaction(): assert transaction_dict['asset']['multiSignature']['publicKeys'][2] == '03860d76b1df09659ac282cea3da5bd84fc45729f348a4a8e5f802186be72dc17f' transaction.schnorr_verify_multisig() # if no exception is raised, it means the transaction is valid + + +def test_multi_signature_registration_transaction_custom_fee(): + """Test if a multi signature registration transaction gets built with a custom fee + """ + transaction = MultiSignatureRegistration(fee=5) + + assert transaction.to_dict()['fee'] == 5 + assert transaction.to_dict()['asset'] == {'multiSignature': {'min': None, 'publicKeys': []}} diff --git a/tests/transactions/builder/test_vote.py b/tests/transactions/builder/test_vote.py index 3f87333d..47395b2c 100644 --- a/tests/transactions/builder/test_vote.py +++ b/tests/transactions/builder/test_vote.py @@ -48,3 +48,19 @@ def test_vote_transaction_custom_fee(): assert transaction_dict['fee'] == 5 transaction.schnorr_verify() # if no exception is raised, it means the transaction is valid + + +def test_unvote_transaction(): + """Test if an unvote transaction gets built + """ + vote = '-034151a3ec46b5670a682b0a63394f863587d1bc97483b1b6c70eb58e7f0aed192' + + transaction = Vote(vote) + transaction.set_nonce(1) + transaction.schnorr_sign('testing') + transaction_dict = transaction.to_dict() + + assert transaction_dict['asset']['votes'] == [vote] + assert transaction_dict['type'] is TRANSACTION_VOTE + + transaction.schnorr_verify() # if no exception is raised, it means the transaction is valid diff --git a/tests/transactions/deserializers/test_vote.py b/tests/transactions/deserializers/test_vote.py index 14f8834c..1bbe22b5 100644 --- a/tests/transactions/deserializers/test_vote.py +++ b/tests/transactions/deserializers/test_vote.py @@ -1,4 +1,5 @@ from crypto.transactions.deserializer import Deserializer +from crypto.transactions.serializer import Serializer def test_vote_deserializer(): @@ -21,3 +22,17 @@ def test_vote_deserializer(): assert actual.asset['votes'] == ['+022cca9529ec97a772156c152a00aad155ee6708243e65c9d211a589cb5d43234d'] # noqa actual.verify_schnorr() + + +def test_unvote_deserializer(transaction_type_3): + transaction = dict(transaction_type_3) + transaction['asset'] = { + 'votes': ['-022cca9529ec97a772156c152a00aad155ee6708243e65c9d211a589cb5d43234d'] + } + del transaction['signature'] + serialized = Serializer(transaction).serialize() + + actual = Deserializer(serialized).deserialize() + + assert actual.asset['votes'] == ['-022cca9529ec97a772156c152a00aad155ee6708243e65c9d211a589cb5d43234d'] # noqa + assert actual.signature is None diff --git a/tests/transactions/serializers/test_vote.py b/tests/transactions/serializers/test_vote.py index ed83e62d..e46af35a 100644 --- a/tests/transactions/serializers/test_vote.py +++ b/tests/transactions/serializers/test_vote.py @@ -4,3 +4,15 @@ def test_serializer(transaction_type_3): result = Serializer(transaction_type_3).serialize(False, True) assert result == transaction_type_3['serialized'] + + +def test_serializer_unvote(transaction_type_3): + transaction = dict(transaction_type_3) + transaction['asset'] = { + 'votes': ['-022cca9529ec97a772156c152a00aad155ee6708243e65c9d211a589cb5d43234d'] + } + + result = Serializer(transaction).serialize(True, True) + + # vote count (01) followed by the unvote flag (00) and the public key + assert result.endswith('0100022cca9529ec97a772156c152a00aad155ee6708243e65c9d211a589cb5d43234d') diff --git a/tests/transactions/test_deserializer.py b/tests/transactions/test_deserializer.py new file mode 100644 index 00000000..c1e43957 --- /dev/null +++ b/tests/transactions/test_deserializer.py @@ -0,0 +1,59 @@ +from binascii import unhexlify + +import pytest + +from crypto.configuration.network import set_network +from crypto.networks.devnet import Devnet +from crypto.transactions.builder.transfer import Transfer +from crypto.transactions.deserializer import Deserializer + +set_network(Devnet) + + +def test_deserializer_with_vendor_field(): + transaction = Transfer( + recipientId='AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC', + amount=200000000, + vendorField='hello', + ) + transaction.set_nonce(1) + transaction.schnorr_sign('this is a top secret passphrase') + serialized = transaction.transaction.serialize(False, True, True) + + actual = Deserializer(serialized).deserialize() + + assert actual.vendorFieldHex == 'hello'.encode().hex().encode() + assert actual.recipientId == 'AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC' + assert actual.amount == 200000000 + assert actual.signature == transaction.transaction.signature.decode() + assert actual.id == transaction.transaction.id + assert actual.serialize(False, True, True) == serialized + + actual.verify_schnorr() # if no exception is raised, it means the transaction is valid + + +def test_deserializer_with_multibyte_vendor_field(): + transaction = Transfer( + recipientId='AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC', + amount=200000000, + vendorField='héllo', + ) + transaction.set_nonce(1) + transaction.schnorr_sign('this is a top secret passphrase') + serialized = transaction.transaction.serialize(False, True, True) + + actual = Deserializer(serialized).deserialize() + + assert unhexlify(actual.vendorFieldHex).decode() == 'héllo' + assert actual.recipientId == 'AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC' + assert actual.id == transaction.transaction.id + + actual.verify_schnorr() # if no exception is raised, it means the transaction is valid + + +def test_deserializer_with_unsupported_version(transaction_type_0): + # replace the version byte (02) that follows the 0xff marker + serialized = 'ff01' + transaction_type_0['serialized'][4:] + + with pytest.raises(Exception, match=r'should this ever happen\?'): + Deserializer(serialized).deserialize() diff --git a/tests/transactions/test_serializer.py b/tests/transactions/test_serializer.py new file mode 100644 index 00000000..229f9ad3 --- /dev/null +++ b/tests/transactions/test_serializer.py @@ -0,0 +1,45 @@ +import pytest + +from crypto.exceptions import ArkSerializerException +from crypto.transactions.serializer import Serializer + + +def test_serializer_without_transaction(): + with pytest.raises(ArkSerializerException, match='No transaction data provided'): + Serializer({}) + + +def test_serializer_with_vendor_field(transaction_type_0): + transaction = dict(transaction_type_0, vendorField='hello') + + result = Serializer(transaction).serialize(False, True) + + # vendor field length (05) followed by the vendor field, after the fee + assert '809698000000000005' + 'hello'.encode().hex() in result + + +def test_serializer_with_multibyte_vendor_field(transaction_type_0): + transaction = dict(transaction_type_0, vendorField='héllo') + + result = Serializer(transaction).serialize(False, True) + + # the length is in bytes, and "é" is 2 bytes + assert '809698000000000006' + 'héllo'.encode().hex() in result + + +def test_serializer_with_vendor_field_hex(transaction_type_0): + with_vendor_field = dict(transaction_type_0, vendorField='hello') + with_vendor_field_hex = dict(transaction_type_0, vendorFieldHex='hello'.encode().hex()) + + result = Serializer(with_vendor_field_hex).serialize(False, True) + + assert result == Serializer(with_vendor_field).serialize(False, True) + + +def test_serializer_with_second_signature(transaction_type_0): + second_signature = 'ab' * 64 + transaction = dict(transaction_type_0, secondSignature=second_signature) + + assert Serializer(transaction).serialize(False, False) == \ + transaction_type_0['serialized'] + second_signature + assert Serializer(transaction).serialize(False, True) == transaction_type_0['serialized'] diff --git a/tests/transactions/test_transaction.py b/tests/transactions/test_transaction.py index 76bca5f6..3c7a79eb 100644 --- a/tests/transactions/test_transaction.py +++ b/tests/transactions/test_transaction.py @@ -1,3 +1,11 @@ +import json + +import pytest + +from crypto.exceptions import ArkInvalidTransaction +from crypto.identity.public_key import PublicKey +from crypto.transactions.builder.multi_signature_registration import MultiSignatureRegistration +from crypto.transactions.builder.transfer import Transfer from crypto.transactions.transaction import Transaction @@ -22,3 +30,78 @@ def test_transaction_deserialize(transaction_type_0): assert data['type'] == transaction_type_0['type'] assert data['typeGroup'] == transaction_type_0['typeGroup'] assert data['nonce'] == transaction_type_0['nonce'] + + +def _signed_transfer(): + transaction = Transfer(recipientId='AGeYmgbg2LgGxRW2vNNJvQ88PknEJsYizC', amount=200000000) + transaction.set_nonce(1) + transaction.schnorr_sign('this is a top secret passphrase') + return transaction + + +def test_transaction_to_json(transaction_type_0): + transaction = Transaction(**transaction_type_0) + data = json.loads(transaction.to_json()) + assert data == transaction.to_dict() + assert data['id'] == transaction_type_0['id'] + + +def test_transaction_deserialize_second_signature(): + transaction = _signed_transfer() + transaction.second_sign('this is a second secret passphrase') + + serialized = transaction.transaction.serialize(False, False, True) + deserialized = Transaction().deserialize(serialized) + + assert deserialized.signature == transaction.transaction.signature.decode() + assert deserialized.signSignature == transaction.transaction.signSignature.decode() + + +def test_transaction_deserialize_without_signature(transaction_type_0): + serialized = Transaction(**transaction_type_0).serialize() + deserialized = Transaction().deserialize(serialized) + + assert deserialized.signature is None + assert deserialized.signSignature is None + assert deserialized.recipientId == transaction_type_0['recipientId'] + + +def test_transaction_verify_schnorr_invalid(): + transaction = _signed_transfer() + transaction.set_amount(1) + + with pytest.raises(ArkInvalidTransaction, match='Transaction could not be verified'): + transaction.schnorr_verify() + + +def test_transaction_verify_schnorr_second_signature(): + transaction = _signed_transfer() + transaction.second_sign('this is a second secret passphrase') + second_public_key = PublicKey.from_passphrase('this is a second secret passphrase') + + assert transaction.schnorr_verify_second(second_public_key) is True + + +def test_transaction_verify_schnorr_second_signature_invalid(): + transaction = _signed_transfer() + transaction.second_sign('this is a second secret passphrase') + wrong_public_key = PublicKey.from_passphrase('this is a top secret passphrase') + + with pytest.raises(ArkInvalidTransaction, match='Transaction could not be verified'): + transaction.schnorr_verify_second(wrong_public_key) + + +def test_transaction_verify_schnorr_multisig_invalid(): + public_key = PublicKey.from_passphrase('this is a top secret passphrase 1') + + transaction = MultiSignatureRegistration() + transaction.set_sender_public_key(public_key) + transaction.set_nonce(1) + transaction.set_min(1) + transaction.add_participant(public_key) + transaction.multi_sign('this is a top secret passphrase 1', 0) + transaction.schnorr_sign('this is a top secret passphrase 1') + transaction.set_min(2) + + with pytest.raises(ArkInvalidTransaction, match='Transaction could not be verified'): + transaction.schnorr_verify_multisig() diff --git a/tests/utils/test_message.py b/tests/utils/test_message.py index 8f02d5e2..1d618bf5 100644 --- a/tests/utils/test_message.py +++ b/tests/utils/test_message.py @@ -1,5 +1,7 @@ import json +import pytest + from crypto.utils.message import Message @@ -30,3 +32,8 @@ def test_to_json(message): assert data['signature'] == message['camelCase_pk']['signature'] assert data['publicKey'] == message['camelCase_pk']['publicKey'] assert data['message'] == message['camelCase_pk']['message'] + + +def test_invalid_keyword_argument(message): + with pytest.raises(TypeError, match='Invalid keyword argument foo'): + Message(foo='bar', **message['camelCase_pk'])