diff --git a/.coveragerc b/.coveragerc index 44c7c654..017e653c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,6 +1,8 @@ [run] branch = True source = crypto +omit = + crypto/thirdparty/* [report] exclude_lines = diff --git a/crypto/identity/address.py b/crypto/identity/address.py index ca0b739c..83d6b8a7 100644 --- a/crypto/identity/address.py +++ b/crypto/identity/address.py @@ -87,4 +87,4 @@ def get_checksum_address(cls, address: str) -> str: @classmethod def validate(cls, address: str) -> bool: # Simple validation to check if the address starts with 0x and is 42 characters long - return re.search(r'^0x[a-fA-F0-9]{40}$', address) is not None + return re.fullmatch(r'0x[a-fA-F0-9]{40}', address) is not None diff --git a/crypto/transactions/builder/username_registration_builder.py b/crypto/transactions/builder/username_registration_builder.py index a4b5fc41..5f86fa67 100644 --- a/crypto/transactions/builder/username_registration_builder.py +++ b/crypto/transactions/builder/username_registration_builder.py @@ -26,13 +26,13 @@ def is_valid_username(username: str) -> bool: if len(username) < 1 or len(username) > 20: raise InvalidUsernameException(f'Username must be between 1 and 20 characters long. Got {len(username)} characters.') - if re.match('/[^a-z0-9_]/', username): + if re.search(r'[^a-z0-9_]', username): raise InvalidUsernameException('Username can only contain lowercase letters, numbers and underscores.') - if re.match('/^_|_$/', username): + if re.search(r'^_|_$', username): raise InvalidUsernameException('Username cannot start or end with an underscore.') - if re.match('/__/', username): + if '__' in username: raise InvalidUsernameException('Username cannot contain consecutive underscores.') return True diff --git a/crypto/transactions/deserializer.py b/crypto/transactions/deserializer.py index 84f71c57..c4a45e45 100644 --- a/crypto/transactions/deserializer.py +++ b/crypto/transactions/deserializer.py @@ -79,10 +79,11 @@ def decode_payload(data: dict, abi_type: ContractAbiType = ContractAbiType.CONSE def __guess_transaction_from_data(self, data: dict) -> AbstractTransaction: multipayment_payload_data = self.decode_payload(data, ContractAbiType.MULTIPAYMENT) - if multipayment_payload_data is not None: - function_name = multipayment_payload_data.get('functionName') - if function_name == AbiFunction.MULTIPAYMENT.value: - return Multipayment(data) + if ( + multipayment_payload_data is not None + and multipayment_payload_data.get('functionName') == AbiFunction.MULTIPAYMENT.value + ): + return Multipayment(data) consensus_payload_data = self.decode_payload(data) if consensus_payload_data is not None: diff --git a/crypto/utils/abi_base.py b/crypto/utils/abi_base.py index 74ca0c67..237e9551 100644 --- a/crypto/utils/abi_base.py +++ b/crypto/utils/abi_base.py @@ -36,10 +36,7 @@ def strip_hex_prefix(self, hex_str): return hex_str def is_valid_address(self, address): - # Compute the checksum address and compare - computed_checksum_address = Address.get_checksum_address(address.lower()) - - return address.lower() == computed_checksum_address.lower() + return isinstance(address, str) and Address.validate(address) def keccak256(self, input_str): k = keccak.new(digest_bits=256) diff --git a/crypto/utils/abi_decoder.py b/crypto/utils/abi_decoder.py index 9c2b2a15..c1eea4d4 100644 --- a/crypto/utils/abi_decoder.py +++ b/crypto/utils/abi_decoder.py @@ -51,9 +51,8 @@ def decode_parameter(self, bytes_data, offset, param): array_components = self.get_array_components(type_) if array_components: length, base_type = array_components - param['type'] = base_type - return self.decode_array(bytes_data, offset, param, length) + return self.decode_array(bytes_data, offset, {**param, 'type': base_type}, length) if type_ == 'address': return self.decode_address(bytes_data, offset) @@ -130,11 +129,7 @@ def decode_fixed_bytes(self, bytes_data, offset, size): value = '0x' + data[:size].hex() return value, 32 - def decode_array(self, bytes_data, offset, param, length): - base_type = param['type'] - element_type = param.copy() - element_type['type'] = base_type - + def decode_array(self, bytes_data, offset, element_type, length): if length is None: data_offset = self.read_uint(bytes_data, offset) array_offset = data_offset @@ -150,7 +145,8 @@ def decode_array(self, bytes_data, offset, param, length): cursor += consumed values.append(value) - return values, 32 + # A fixed-length array is encoded in place, so it takes up all of its elements' slots + return values, 32 if length is None else cursor - offset def decode_tuple(self, bytes_data, offset, param): components = param['components'] @@ -163,7 +159,7 @@ def decode_tuple(self, bytes_data, offset, param): name = component.get('name', '') values[name] = value - return values, 32 + return values, cursor - offset @staticmethod def read_uint(bytes_data, offset): diff --git a/crypto/utils/abi_encoder.py b/crypto/utils/abi_encoder.py index c14fff54..0c625b4f 100644 --- a/crypto/utils/abi_encoder.py +++ b/crypto/utils/abi_encoder.py @@ -14,10 +14,7 @@ def encode_function_call(self, function_name, args=[]): return self.encode_function_data(parameters) def encode_function_call_hex(self, function_name, args=[]): - result = self.encode_function_call(function_name, args) - if not result.startswith('0x'): - return '0x' + result - return result + return self.encode_function_call(function_name, args) def encode_function_data(self, parameters): args = parameters.get('args', []) @@ -52,8 +49,6 @@ def prepare_encode_function_data(self, params): raise Exception('Function name is not provided and ABI has multiple functions') else: abi_item = self.get_abi_item(abi, function_name, params.get('args', [])) - if not abi_item: - raise Exception('Function not found in ABI: ' + function_name) signature = self.to_function_selector(abi_item) return abi_item, signature @@ -128,11 +123,10 @@ def encode_array(self, value, length, param): 'dynamic': True, 'encoded': '0x' + length_hex + data[2:], } - if dynamic_child: - return { - 'dynamic': True, - 'encoded': data, - } + return { + 'dynamic': True, + 'encoded': data, + } encoded = ''.join([p['encoded'][2:] for p in prepared_params]) return { 'dynamic': False, @@ -222,10 +216,11 @@ def encode_bytes(self, value, param): } def encode_string(self, value): - hex_value = binascii.hexlify(value.encode('utf-8')).decode() - length_hex = '{:064x}'.format(len(value)) + value_bytes = value.encode('utf-8') + hex_value = binascii.hexlify(value_bytes).decode() + length_hex = '{:064x}'.format(len(value_bytes)) value_padded = hex_value - padding = (32 - (len(value) % 32)) % 32 + padding = (32 - (len(value_bytes) % 32)) % 32 if padding > 0: value_padded += '00' * padding return { @@ -237,8 +232,13 @@ def encode_tuple(self, value, param): dynamic = False prepared_params = [] for index, component in enumerate(param['components']): - key = index if isinstance(value, list) else component.get('name') - if key not in value: + if isinstance(value, list): + key = index + missing = index >= len(value) + else: + key = component.get('name') + missing = key not in value + if missing: raise Exception('Tuple value missing component: ' + component.get('name', '')) prepared_param = self.prepare_param(component, value[key]) if prepared_param['dynamic']: diff --git a/crypto/utils/message.py b/crypto/utils/message.py index 2fbcd8b4..d03bff16 100644 --- a/crypto/utils/message.py +++ b/crypto/utils/message.py @@ -59,7 +59,7 @@ def sign(cls, message: Union[bytes, str], passphrase: Union[bytes, str]): message = message.encode() if not isinstance(passphrase, str): - passphrase = passphrase.hex() + passphrase = passphrase.decode() private_key = PrivateKey.from_passphrase(passphrase) public_key = private_key.public_key diff --git a/crypto/utils/rlp_decoder.py b/crypto/utils/rlp_decoder.py index a42fe729..d8f0dfcc 100644 --- a/crypto/utils/rlp_decoder.py +++ b/crypto/utils/rlp_decoder.py @@ -118,5 +118,5 @@ def __decode(cls, data: list[int], offset: int) -> DecodedType: @classmethod def __check_offset(cls, offset: int, data: list[int]) -> None: - if offset > len(data): + if offset >= len(data): raise ValueError('data short segment or out of range') diff --git a/crypto/utils/rlp_encoder.py b/crypto/utils/rlp_encoder.py index e685d999..d2742bd0 100644 --- a/crypto/utils/rlp_encoder.py +++ b/crypto/utils/rlp_encoder.py @@ -59,7 +59,7 @@ def __arrayify_integer(cls, value: int) -> list: return result @classmethod - def __get_bytes(cls, value: Union[str, bytes, int, list]) -> list: + def __get_bytes(cls, value: Union[str, bytes, int]) -> list: if isinstance(value, str) or isinstance(value, bytes): # Only strings carry a `0x` hex prefix, raw bytes can start with 0x3078 too is_hex_string = isinstance(value, str) and value.startswith('0x') @@ -69,9 +69,6 @@ def __get_bytes(cls, value: Union[str, bytes, int, list]) -> list: if is_hex_string: hex_str = value[2:] - if hex_str == '': - return [] - if len(hex_str) % 2 != 0: hex_str = b'0' + hex_str @@ -90,7 +87,4 @@ def __get_bytes(cls, value: Union[str, bytes, int, list]) -> list: return result - if isinstance(value, list): - return [v & 0xff for v in value] - raise ValueError('invalid type', type(value)) diff --git a/requirements.txt b/requirements.txt index 52d77f39..0cc90cf8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,7 @@ base58==2.1.1 binary-helpers==0.0.4 -cffi==2.1.1 coincurve==21.0.0 coverage==7.18.0 -cryptography==50.0.2 flake8==7.5.0 flake8-import-order==0.19.2 flake8-print==5.0.0 @@ -13,7 +11,6 @@ mccabe==0.7.0 packaging==26.4 pluggy==1.7.0 pycodestyle==2.15.0 -pycparser==3.12 pycryptodomex==3.24.2 pyflakes==4.1.0 pygments==2.21.0 diff --git a/setup.py b/setup.py index c4daccd7..d5f67961 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,6 @@ 'binary-helpers>=0.0.4', 'coincurve>=21.0.0', 'pycryptodomex>=3.24.2', - 'cryptography>=50.0.2', ] tests_require = [ diff --git a/tests/configuration/test_network.py b/tests/configuration/test_network.py index a7080f12..3607c079 100644 --- a/tests/configuration/test_network.py +++ b/tests/configuration/test_network.py @@ -42,3 +42,7 @@ def test_set_custom_network(): assert result.chain_id() == 20000 Network.set_network(Testnet()) # set back to Testnet so other tests don't fail + + +def test_mainnet_epoch(): + assert Mainnet().epoch() == '2017-03-21T13:00:00.000Z' diff --git a/tests/identity/test_address.py b/tests/identity/test_address.py index e8251986..ff77aa3c 100644 --- a/tests/identity/test_address.py +++ b/tests/identity/test_address.py @@ -17,3 +17,7 @@ def test_address_from_passphrase(identity): def test_it_should_validate_the_address(identity): assert Address.validate(identity['data']['address']) is True assert Address.validate(identity['data']['address'][2:]) is False + + +def test_it_should_not_validate_an_address_with_a_trailing_newline(identity): + assert Address.validate(identity['data']['address'] + '\n') is False diff --git a/tests/identity/test_legacy_address.py b/tests/identity/test_legacy_address.py index f3507fd4..5568afd3 100644 --- a/tests/identity/test_legacy_address.py +++ b/tests/identity/test_legacy_address.py @@ -1,3 +1,5 @@ +from base58 import b58encode_check + from crypto.identity.legacy_address import LegacyAddress @@ -30,3 +32,9 @@ def test_validate_invalid_address(legacy_identity): def test_validate_decoding_error(legacy_identity): assert LegacyAddress.validate('invalid', legacy_identity['pub_key_hash']) is False + + +def test_it_rejects_an_address_with_the_wrong_length(legacy_identity): + address = b58encode_check(bytes([legacy_identity['pub_key_hash']]) + bytes(19)).decode() + + assert LegacyAddress.validate(address, legacy_identity['pub_key_hash']) is False diff --git a/tests/identity/test_private_key.py b/tests/identity/test_private_key.py index fcbe7b77..2e5a960c 100644 --- a/tests/identity/test_private_key.py +++ b/tests/identity/test_private_key.py @@ -1,4 +1,7 @@ +import pytest + from crypto.identity.private_key import PrivateKey +from crypto.identity.wif import WIF def test_private_key_from_passphrase(identity): private_key = PrivateKey.from_passphrase(identity['passphrase']) @@ -25,3 +28,10 @@ def test_it_should_parse_the_private_key_from_wif(identity): private_key = PrivateKey.from_wif(identity['data']['wif']) assert isinstance(private_key, PrivateKey) assert private_key.to_hex() == identity['data']['private_key'] + + +def test_it_should_reject_a_wif_from_another_network(identity): + wif = WIF.from_passphrase(identity['passphrase'], '82') + + with pytest.raises(ValueError, match='Invalid network version: 82'): + PrivateKey.from_wif(wif) diff --git a/tests/identity/test_proof_of_possession.py b/tests/identity/test_proof_of_possession.py index 37764a9e..959e3c0e 100644 --- a/tests/identity/test_proof_of_possession.py +++ b/tests/identity/test_proof_of_possession.py @@ -93,3 +93,16 @@ def test_it_rejects_an_invalid_registrant(registrant_address): def test_it_rejects_an_invalid_registrant_from_passphrase(passphrase): with pytest.raises(InvalidProofOfPossessionException): ProofOfPossession.from_passphrase(passphrase, '0xinvalid') + + +def test_it_derives_the_bls_public_key(load_transaction_fixture): + fixture = load_transaction_fixture('transactions/validator-update') + + public_key = ProofOfPossession.derive_bls_public_key(fixture['validatorPassphrase']) + + assert '0x' + public_key == fixture['data']['validatorPublicKey'] + + +def test_it_rejects_a_zero_secret_key(): + with pytest.raises(ValueError, match='BLS secret key must not be zero'): + ProofOfPossession.build_proof_of_possession(bytes(32), REGISTRANT) diff --git a/tests/identity/test_wif.py b/tests/identity/test_wif.py index 5c550ef2..c1924574 100644 --- a/tests/identity/test_wif.py +++ b/tests/identity/test_wif.py @@ -8,3 +8,10 @@ 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'], Testnet().wif()) + assert result == identity['data']['wif'] + + assert WIF.from_passphrase(identity['passphrase'], '82') != result diff --git a/tests/transactions/builder/test_token_approve_builder.py b/tests/transactions/builder/test_token_approve_builder.py index 75865376..ece12885 100644 --- a/tests/transactions/builder/test_token_approve_builder.py +++ b/tests/transactions/builder/test_token_approve_builder.py @@ -51,3 +51,10 @@ def test_token_approve_serialization(passphrase, load_transaction_fixture): serialized = builder.transaction.serialize().hex() assert serialized == fixture['serialized'] + + +def test_it_should_set_the_contract_address(): + address = '0x6F0182a0cc707b055322CcF6d4CB6a5Aff1aEb22' + builder = TokenApproveBuilder.new().contract_address(address) + + assert builder.transaction.data['to'] == address diff --git a/tests/transactions/builder/test_token_transfer_builder.py b/tests/transactions/builder/test_token_transfer_builder.py index 376b8a39..be0af5d2 100644 --- a/tests/transactions/builder/test_token_transfer_builder.py +++ b/tests/transactions/builder/test_token_transfer_builder.py @@ -51,3 +51,10 @@ def test_token_transfer_serialization(passphrase, load_transaction_fixture): serialized = builder.transaction.serialize().hex() assert serialized == fixture['serialized'] + + +def test_it_should_set_the_contract_address(): + address = '0x6F0182a0cc707b055322CcF6d4CB6a5Aff1aEb22' + builder = TokenTransferBuilder.new().contract_address(address) + + assert builder.transaction.data['to'] == address diff --git a/tests/transactions/builder/test_transfer_builder.py b/tests/transactions/builder/test_transfer_builder.py index 8213f1a3..03909ebe 100644 --- a/tests/transactions/builder/test_transfer_builder.py +++ b/tests/transactions/builder/test_transfer_builder.py @@ -1,3 +1,8 @@ +import json + +import pytest + +from crypto.transactions.builder.abstract_transaction_builder import AbstractTransactionBuilder from crypto.transactions.builder.transfer_builder import TransferBuilder from crypto.utils.unit_converter import UnitConverter @@ -74,3 +79,22 @@ def test_it_should_handle_unit_converter(passphrase, address): assert builder.transaction.data['value'] == 10000000000000000000 assert builder.verify() + + +def test_it_should_convert_to_dict_and_json(passphrase): + builder = ( + TransferBuilder + .new() + .to('0x6F0182a0cc707b055322CcF6d4CB6a5Aff1aEb22') + .value('100') + .sign(passphrase) + ) + + assert builder.to_dict() == builder.transaction.to_dict() + assert json.loads(builder.to_json()) == builder.to_dict() + assert str(builder) == builder.to_json() + + +def test_it_requires_subclasses_to_create_the_transaction(): + with pytest.raises(NotImplementedError): + AbstractTransactionBuilder({}) diff --git a/tests/transactions/builder/test_username_registration_builder.py b/tests/transactions/builder/test_username_registration_builder.py index 26e01acc..06402f87 100644 --- a/tests/transactions/builder/test_username_registration_builder.py +++ b/tests/transactions/builder/test_username_registration_builder.py @@ -1,3 +1,7 @@ +import re + +import pytest + from crypto.exceptions import InvalidUsernameException from crypto.transactions.builder.username_registration_builder import UsernameRegistrationBuilder @@ -29,49 +33,34 @@ def test_it_accepts_valid_usernames(): except InvalidUsernameException as e: raise Exception(f'Valid username threw an exception: {e}') -def test_it_rejects_usernames_with_invalid_length(): - for username, character_count in {'': 0, 'abcdefghijklmnopqrstu': 21}.items(): - try: - UsernameRegistrationBuilder.is_valid_username(username) - except InvalidUsernameException as e: - assert str(e) == f'Username must be between 1 and 20 characters long. Got {character_count} characters.' - -def test_it_rejects_usernames_with_invalid_characters(): - usernames = [ - 'John', - 'john@doe', - 'john doe', - 'jöhn', - ] - - for username in usernames: - try: - UsernameRegistrationBuilder.is_valid_username(username) - except InvalidUsernameException as e: - assert str(e) == 'Username can only contain lowercase letters, numbers and underscores' - -def test_it_rejects_usernames_starting_or_ending_with_underscore(): - usernames = [ - '_john', - 'john_', - '_john_', - ] - - for username in usernames: - try: - UsernameRegistrationBuilder.is_valid_username(username) - except InvalidUsernameException as e: - assert str(e) == 'Username cannot start or end with an underscore' - -def test_it_rejects_usernames_with_consecutive_underscores(): - usernames = [ - 'john__doe', - 'john___doe', - 'john__doe__smith', - ] - - for username in usernames: - try: - UsernameRegistrationBuilder.is_valid_username(username) - except InvalidUsernameException as e: - assert str(e) == 'Username cannot contain consecutive underscores' + +@pytest.mark.parametrize('username', ['', 'abcdefghijklmnopqrstu']) +def test_it_rejects_usernames_with_invalid_length(username): + message = f'Username must be between 1 and 20 characters long. Got {len(username)} characters.' + + with pytest.raises(InvalidUsernameException, match=re.escape(message)): + UsernameRegistrationBuilder.is_valid_username(username) + + +@pytest.mark.parametrize('username', ['John', 'john@doe', 'john doe', 'jöhn']) +def test_it_rejects_usernames_with_invalid_characters(username): + message = 'Username can only contain lowercase letters, numbers and underscores.' + + with pytest.raises(InvalidUsernameException, match=re.escape(message)): + UsernameRegistrationBuilder.is_valid_username(username) + + +@pytest.mark.parametrize('username', ['_john', 'john_', '_john_']) +def test_it_rejects_usernames_starting_or_ending_with_underscore(username): + message = 'Username cannot start or end with an underscore.' + + with pytest.raises(InvalidUsernameException, match=re.escape(message)): + UsernameRegistrationBuilder.is_valid_username(username) + + +@pytest.mark.parametrize('username', ['john__doe', 'john___doe', 'john__doe__smith']) +def test_it_rejects_usernames_with_consecutive_underscores(username): + message = 'Username cannot contain consecutive underscores.' + + with pytest.raises(InvalidUsernameException, match=re.escape(message)): + UsernameRegistrationBuilder.is_valid_username(username) diff --git a/tests/transactions/test_deserializer.py b/tests/transactions/test_deserializer.py index 4d532fd4..20345a00 100644 --- a/tests/transactions/test_deserializer.py +++ b/tests/transactions/test_deserializer.py @@ -1,4 +1,10 @@ +import pytest + +from crypto.enums.contract_abi_type import ContractAbiType +from crypto.enums.contract_addresses import ContractAddresses +from crypto.transactions.builder.evm_call_builder import EvmCallBuilder from crypto.transactions.deserializer import Deserializer +from crypto.transactions.types.evm_call import EvmCall from crypto.transactions.types.multipayment import Multipayment from crypto.transactions.types.transfer import Transfer from crypto.transactions.types.username_registration import UsernameRegistration @@ -7,6 +13,9 @@ from crypto.transactions.types.unvote import Unvote from crypto.transactions.types.validator_registration import ValidatorRegistration from crypto.transactions.types.validator_resignation import ValidatorResignation +from crypto.transactions.types.validator_update import ValidatorUpdate +from crypto.utils.abi_encoder import AbiEncoder +from crypto.utils.rlp_encoder import RlpEncoder def assert_deserialized(fixture, keys): deserializer = Deserializer.new(fixture['serialized']) @@ -95,3 +104,73 @@ def test_parse_big_number(): def test_parse_address(): assert Deserializer._Deserializer__parse_address('0x52B7D2DCC80CD2E4000000') == '0x52B7D2DCC80CD2E4000000' assert Deserializer._Deserializer__parse_address('0x') is None + + +def test_deserialize_validator_update(load_transaction_fixture): + fixture = load_transaction_fixture('transactions/validator-update') + transaction = assert_deserialized( + fixture, + ['hash', 'nonce', 'gasPrice', 'gasLimit', 'v', 'r', 's'], + ) + + assert isinstance(transaction, ValidatorUpdate) + assert transaction.data['validatorPublicKey'] == fixture['data']['validatorPublicKey'] + assert transaction.data['validatorProof'] == fixture['data']['validatorProof'] + + +def test_deserialize_evm_call(load_transaction_fixture): + fixture = load_transaction_fixture('transactions/token-transfer') + transaction = assert_deserialized( + fixture, + ['hash', 'nonce', 'gasPrice', 'gasLimit', 'value', 'v', 'r', 's'], + ) + + assert isinstance(transaction, EvmCall) + + +@pytest.mark.parametrize('abi_type, contract_address, function_name, args', [ + (ContractAbiType.CONSENSUS, ContractAddresses.CONSENSUS, 'isValidatorRegistered', [ + '0xC3bBE9B1CeE1ff85Ad72b87414B0E9B7F2366763', + ]), + (ContractAbiType.USERNAMES, ContractAddresses.USERNAMES, 'isUsernameValid', ['john']), +]) +def test_deserialize_other_contract_calls_as_evm_call( + passphrase, + abi_type, + contract_address, + function_name, + args, +): + payload = AbiEncoder(abi_type).encode_function_call(function_name, args) + + builder = ( + EvmCallBuilder + .new() + .payload(payload) + .to(contract_address.value) + .sign(passphrase) + ) + + transaction = Deserializer.new(builder.transaction.serialize().hex()).deserialize() + + assert isinstance(transaction, EvmCall) + assert transaction.data['hash'] == builder.transaction.data['hash'] + + +def test_deserialize_unsigned_transaction(): + serialized = RlpEncoder.encode([ + b'\x01', + b'\x05', + (21000).to_bytes(3, 'big'), + bytes.fromhex('6f0182a0cc707b055322ccf6d4cb6a5aff1aeb22'), + (100).to_bytes(1, 'big'), + b'', + ]) + + transaction = Deserializer.new(serialized).deserialize() + + assert isinstance(transaction, Transfer) + assert transaction.data['value'] == '100' + assert 'v' not in transaction.data + assert 'senderPublicKey' not in transaction.data + assert transaction.verify() is False diff --git a/tests/transactions/test_serializer.py b/tests/transactions/test_serializer.py index 229e4067..4ad433d1 100644 --- a/tests/transactions/test_serializer.py +++ b/tests/transactions/test_serializer.py @@ -1,3 +1,5 @@ +import pytest + from crypto.transactions.serializer import Serializer from crypto.transactions.types.transfer import Transfer from crypto.transactions.types.vote import Vote @@ -34,3 +36,8 @@ def test_validator_resignation_serialization(load_transaction_fixture): transaction = ValidatorResignation(fixture['data']) serializer = Serializer.new(transaction) assert serializer.serialize().hex() == fixture['serialized'] + + +def test_it_requires_a_transaction(): + with pytest.raises(ValueError, match='No transaction data provided'): + Serializer(None) diff --git a/tests/transactions/test_transaction.py b/tests/transactions/test_transaction.py index 129676a0..d8ca57c3 100644 --- a/tests/transactions/test_transaction.py +++ b/tests/transactions/test_transaction.py @@ -1,5 +1,7 @@ from crypto.identity.private_key import PrivateKey from crypto.transactions.deserializer import Deserializer +from crypto.transactions.types.abstract_transaction import AbstractTransaction +from crypto.transactions.types.transfer import Transfer def test_compute_id_of_transaction(load_transaction_fixture): transaction = Deserializer.new(load_transaction_fixture('transactions/transfer')['serialized']).deserialize() @@ -36,3 +38,26 @@ def test_transaction_to_json(load_transaction_fixture): transaction = Deserializer.new(load_transaction_fixture('transactions/transfer')['serialized']).deserialize() actual = transaction.to_json() assert isinstance(actual, str) + + +def test_base_transaction_has_no_payload(): + transaction = AbstractTransaction({'data': '0x1234'}) + + assert transaction.get_payload() == '' + assert transaction.data['data'] == '' + + +def test_unsigned_transaction_cannot_be_verified(load_transaction_fixture): + fixture = load_transaction_fixture('transactions/transfer') + data = {key: value for key, value in fixture['data'].items() if key not in ['r', 's']} + transaction = Transfer(data) + + assert transaction.recover_sender() is False + assert transaction.verify() is False + + +def test_transaction_without_sender_public_key_cannot_be_verified(load_transaction_fixture): + fixture = load_transaction_fixture('transactions/transfer') + data = {key: value for key, value in fixture['data'].items() if key != 'senderPublicKey'} + + assert Transfer(data).verify() is False diff --git a/tests/utils/abi/test_argument_decoder.py b/tests/utils/abi/test_argument_decoder.py index 4feacbdc..d2b85d9d 100644 --- a/tests/utils/abi/test_argument_decoder.py +++ b/tests/utils/abi/test_argument_decoder.py @@ -1,4 +1,5 @@ from crypto.utils.abi.argument_decoder import ArgumentDecoder +from crypto.utils.abi_encoder import AbiEncoder def test_it_should_decode_address(): @@ -40,3 +41,16 @@ def test_it_should_decode_bool_as_false(): decoder = ArgumentDecoder(payload) assert decoder.decode_bool() == expected + + +def test_it_should_decode_string(): + payload = AbiEncoder().encode_abi_parameters([{'name': 'a', 'type': 'string'}], ['john'])[2:] + + assert ArgumentDecoder(payload).decode_string() == 'john' + + +def test_it_should_treat_invalid_hex_as_empty(): + decoder = ArgumentDecoder('not hex') + + assert decoder.bytes == b'' + assert decoder.decode_unsigned_int() == 0 diff --git a/tests/utils/test_abi_base.py b/tests/utils/test_abi_base.py index 124c2757..9ff4093f 100644 --- a/tests/utils/test_abi_base.py +++ b/tests/utils/test_abi_base.py @@ -1,3 +1,7 @@ +import json + +import pytest + from crypto.enums.contract_abi_type import ContractAbiType from crypto.utils.abi_base import AbiBase @@ -19,3 +23,29 @@ def test_it_should_validate_uppercase_addresses(): def test_it_should_validate_lowercase_addresses(): assert AbiBase().is_valid_address('0xc3bbe9b1cee1ff85ad72b87414b0e9b7f2366763') is True + + +@pytest.mark.parametrize('address', [ + '0x1234', + '0x' + 'zz' * 20, + '0x' + 'ab' * 25, + 'xx' + 'ab' * 20, + '0x' + 'ab' * 20 + '\n', + None, +]) +def test_it_should_not_validate_invalid_addresses(address): + assert AbiBase().is_valid_address(address) is False + + +def test_it_should_load_a_custom_abi(tmp_path): + path = tmp_path / 'Abi.Custom.json' + path.write_text(json.dumps({'abi': [{'type': 'function', 'name': 'store', 'inputs': []}]})) + + abi_base = AbiBase(ContractAbiType.CUSTOM, str(path)) + + assert abi_base.abi == [{'type': 'function', 'name': 'store', 'inputs': []}] + + +def test_it_requires_a_path_for_a_custom_abi(): + with pytest.raises(Exception, match='ABI file path is not provided'): + AbiBase(ContractAbiType.CUSTOM) diff --git a/tests/utils/test_abi_decoder.py b/tests/utils/test_abi_decoder.py index 369563bf..d38cdb8c 100644 --- a/tests/utils/test_abi_decoder.py +++ b/tests/utils/test_abi_decoder.py @@ -1,5 +1,8 @@ +import pytest + from crypto.enums.contract_abi_type import ContractAbiType from crypto.utils.abi_decoder import AbiDecoder +from crypto.utils.abi_encoder import AbiEncoder def test_decode_vote_payload(): @@ -29,3 +32,81 @@ def test_decode_token_transfer(): '0xC3bBE9B1CeE1ff85Ad72b87414B0E9B7F2366763', 1000, ] + + +def _decoder(inputs): + decoder = AbiDecoder() + decoder.abi = [{'type': 'function', 'name': 'f', 'inputs': inputs}] + + return decoder + + +def _encoder(inputs): + encoder = AbiEncoder() + encoder.abi = [{'type': 'function', 'name': 'f', 'inputs': inputs}] + + return encoder + + +def test_decode_with_unknown_function_selector(): + with pytest.raises(Exception, match='Function selector not found in ABI: 12345678'): + AbiDecoder().decode_function_data('0x12345678') + + +def test_decode_without_data(): + with pytest.raises(Exception, match='No data to decode'): + AbiDecoder().decode_abi_parameters([{'name': 'a', 'type': 'uint256'}], '') + + +def test_decode_the_same_array_function_twice(): + decoder = AbiDecoder(ContractAbiType.MULTIPAYMENT) + data = AbiEncoder(ContractAbiType.MULTIPAYMENT).encode_function_call( + 'pay', + [['0xC3bBE9B1CeE1ff85Ad72b87414B0E9B7F2366763'], [5]], + ) + + assert decoder.decode_function_data(data) == decoder.decode_function_data(data) + assert decoder.abi[0]['inputs'][0]['type'] == 'address[]' + + +@pytest.mark.parametrize('inputs, args', [ + ( + [{'name': 'a', 'type': 'bool'}, {'name': 'b', 'type': 'bool'}], + [True, False], + ), + ( + [{'name': 'a', 'type': 'bytes2'}, {'name': 'b', 'type': 'int256'}], + ['0xabcd', -1], + ), + ( + [{'name': 'a', 'type': 'bytes'}, {'name': 'b', 'type': 'string'}], + ['0xdeadbeef', 'héllo'], + ), + ( + [{'name': 'a', 'type': 'uint256[2]'}, {'name': 'b', 'type': 'uint256'}], + [[1, 2], 3], + ), + ( + [ + { + 'name': 'a', + 'type': 'tuple', + 'components': [ + {'name': 'owner', 'type': 'address'}, + {'name': 'amount', 'type': 'uint256'}, + ], + }, + {'name': 'b', 'type': 'uint256'}, + ], + [{'owner': '0xC3bBE9B1CeE1ff85Ad72b87414B0E9B7F2366763', 'amount': 5}, 3], + ), +]) +def test_decode_round_trip(inputs, args): + data = _encoder(inputs).encode_function_call('f', args) + + assert _decoder(inputs).decode_function_data(data) == {'functionName': 'f', 'args': args} + + +def test_decode_unsupported_type(): + with pytest.raises(Exception, match='Unsupported type: fixed128x18'): + AbiDecoder().decode_parameter(bytes(32), 0, {'name': 'a', 'type': 'fixed128x18'}) diff --git a/tests/utils/test_abi_encoder.py b/tests/utils/test_abi_encoder.py index c1e8749e..b9ae32c9 100644 --- a/tests/utils/test_abi_encoder.py +++ b/tests/utils/test_abi_encoder.py @@ -1,3 +1,5 @@ +import pytest + from crypto.enums.contract_abi_type import ContractAbiType from crypto.utils.abi_encoder import AbiEncoder @@ -37,3 +39,245 @@ def test_encode_token_transfer(): '00000000000000000000000000000000000000000000000000000000000003e8' ) assert encoded == expected + + +ADDRESS = '0x' + '11' * 20 + + +def _words(*words): + return '0x' + ''.join(words) + + +def _uint(value): + return '{:064x}'.format(value) + + +def test_encode_function_call_hex(): + encoder = AbiEncoder() + + assert encoder.encode_function_call_hex('unvote') == '0x3174b689' + + +def test_encode_function_data_with_function_selector(): + abi = [{'type': 'function', 'name': 'store', 'inputs': [{'name': 'value', 'type': 'uint256'}]}] + + encoded = AbiEncoder().encode_function_data({ + 'abi': abi, + 'functionName': '0x6057361d', + 'args': [5], + }) + + assert encoded == '0x6057361d' + _uint(5) + + +def test_encode_function_data_without_function_name(): + abi = [ + {'type': 'event', 'name': 'Stored', 'inputs': []}, + {'type': 'function', 'name': 'store', 'inputs': [{'name': 'value', 'type': 'uint256'}]}, + ] + + encoded = AbiEncoder().encode_function_data({'abi': abi, 'args': [5]}) + + assert encoded == '0x6057361d' + _uint(5) + + +def test_encode_function_data_without_function_name_and_multiple_functions(): + abi = [ + {'type': 'function', 'name': 'store', 'inputs': [{'name': 'value', 'type': 'uint256'}]}, + {'type': 'function', 'name': 'retrieve', 'inputs': []}, + ] + + message = 'Function name is not provided and ABI has multiple functions' + + with pytest.raises(Exception, match=message): + AbiEncoder().encode_function_data({'abi': abi, 'args': []}) + + +def test_encode_function_call_with_unknown_function(): + with pytest.raises(Exception, match='Function not found in ABI: unknown'): + AbiEncoder().encode_function_call('unknown', []) + + +def test_encode_function_call_with_wrong_number_of_arguments(): + with pytest.raises(Exception, match='Function with matching arguments not found in ABI: vote'): + AbiEncoder().encode_function_call('vote', []) + + +def test_encode_function_call_picks_overload_by_number_of_arguments(): + abi = [ + {'type': 'function', 'name': 'store', 'inputs': [{'name': 'value', 'type': 'uint256'}]}, + {'type': 'function', 'name': 'store', 'inputs': []}, + ] + encoder = AbiEncoder() + encoder.abi = abi + + assert encoder.encode_function_call('store', []) == '0x975057e7' + + +def test_encode_abi_parameters_with_mismatched_values(): + with pytest.raises(Exception, match='Length of parameters and values do not match'): + AbiEncoder().encode_abi_parameters([{'name': 'value', 'type': 'uint256'}], []) + + +def test_encode_abi_parameters_without_parameters(): + assert AbiEncoder().encode_abi_parameters([], []) == '0x' + + +def test_encode_invalid_type(): + with pytest.raises(Exception, match='Invalid ABI type: fixed128x18'): + AbiEncoder().prepare_param({'name': 'value', 'type': 'fixed128x18'}, 1) + + +def test_encode_invalid_address(): + with pytest.raises(Exception, match='Invalid address: 0x1234'): + AbiEncoder().encode_address('0x1234') + + +def test_encode_bool(): + params = [{'name': 'a', 'type': 'bool'}, {'name': 'b', 'type': 'bool'}] + + assert AbiEncoder().encode_abi_parameters(params, [True, False]) == _words(_uint(1), _uint(0)) + + +def test_encode_number(): + encoder = AbiEncoder() + + assert encoder.encode_number('1000', False)['encoded'] == _words(_uint(1000)) + assert encoder.encode_number(-1, True)['encoded'] == '0x' + 'f' * 64 + assert encoder.encode_number(5, True)['encoded'] == _words(_uint(5)) + + +def test_encode_number_with_invalid_value(): + with pytest.raises(Exception, match='Invalid number value'): + AbiEncoder().encode_number(1.5, False) + + +def test_encode_negative_number_as_unsigned(): + with pytest.raises(Exception, match='Negative value provided for unsigned integer type'): + AbiEncoder().encode_number(-1, False) + + +def test_encode_fixed_bytes(): + params = [{'name': 'a', 'type': 'bool'}, {'name': 'b', 'type': 'bytes2'}] + + assert AbiEncoder().encode_abi_parameters(params, [True, 'abcd']) == _words( + _uint(1), + 'abcd' + '0' * 60, + ) + + +def test_encode_fixed_bytes_with_wrong_size(): + with pytest.raises(Exception, match='Bytes size mismatch: expected 4, got 2'): + AbiEncoder().encode_bytes('0xabcd', {'name': 'a', 'type': 'bytes4'}) + + +def test_encode_string_with_multibyte_characters(): + encoded = AbiEncoder().encode_abi_parameters([{'name': 'a', 'type': 'string'}], ['héllo']) + + assert encoded == _words(_uint(32), _uint(6), '68c3a96c6c6f' + '0' * 52) + + +def test_encode_string_without_padding(): + encoded = AbiEncoder().encode_abi_parameters([{'name': 'a', 'type': 'string'}], ['a' * 32]) + + assert encoded == _words(_uint(32), _uint(32), '61' * 32) + + +def test_encode_fixed_array(): + params = [{'name': 'a', 'type': 'uint256[2]'}, {'name': 'b', 'type': 'uint256'}] + + assert AbiEncoder().encode_abi_parameters(params, [[1, 2], 3]) == _words( + _uint(1), + _uint(2), + _uint(3), + ) + + +def test_encode_fixed_array_of_dynamic_values(): + encoded = AbiEncoder().encode_abi_parameters([{'name': 'a', 'type': 'string[2]'}], [['a', 'b']]) + + assert encoded == _words( + _uint(32), + _uint(64), + _uint(128), + _uint(1), + '61' + '0' * 62, + _uint(1), + '62' + '0' * 62, + ) + + +def test_encode_dynamic_array_of_dynamic_values(): + encoded = AbiEncoder().encode_abi_parameters([{'name': 'a', 'type': 'string[]'}], [['a', 'b']]) + + assert encoded == _words( + _uint(32), + _uint(2), + _uint(64), + _uint(128), + _uint(1), + '61' + '0' * 62, + _uint(1), + '62' + '0' * 62, + ) + + +def test_encode_array_with_invalid_value(): + with pytest.raises(Exception, match='Invalid array value'): + AbiEncoder().prepare_param({'name': 'a', 'type': 'uint256[]'}, 1) + + +def test_encode_fixed_array_with_wrong_length(): + with pytest.raises(Exception, match='Array length mismatch'): + AbiEncoder().prepare_param({'name': 'a', 'type': 'uint256[2]'}, [1]) + + +@pytest.mark.parametrize('value', [[ADDRESS, 5], {'owner': ADDRESS, 'amount': 5}]) +def test_encode_static_tuple(value): + param = { + 'name': 'a', + 'type': 'tuple', + 'components': [ + {'name': 'owner', 'type': 'address'}, + {'name': 'amount', 'type': 'uint256'}, + ], + } + + assert AbiEncoder().encode_abi_parameters([param], [value]) == _words( + '0' * 24 + '11' * 20, + _uint(5), + ) + + +def test_encode_dynamic_tuple(): + param = { + 'name': 'a', + 'type': 'tuple', + 'components': [ + {'name': 'name', 'type': 'string'}, + {'name': 'amount', 'type': 'uint256'}, + ], + } + + assert AbiEncoder().encode_abi_parameters([param], [['hi', 5]]) == _words( + _uint(32), + _uint(64), + _uint(5), + _uint(2), + '6869' + '0' * 60, + ) + + +@pytest.mark.parametrize('value', [[ADDRESS], {'owner': ADDRESS}]) +def test_encode_tuple_with_missing_component(value): + param = { + 'name': 'a', + 'type': 'tuple', + 'components': [ + {'name': 'owner', 'type': 'address'}, + {'name': 'amount', 'type': 'uint256'}, + ], + } + + with pytest.raises(Exception, match='Tuple value missing component: amount'): + AbiEncoder().prepare_param(param, value) diff --git a/tests/utils/test_message.py b/tests/utils/test_message.py index 5ac627c3..0d89c8fd 100644 --- a/tests/utils/test_message.py +++ b/tests/utils/test_message.py @@ -58,3 +58,25 @@ def test_to_json(load_transaction_fixture): assert data['signature'] == fixture['signature'] assert data['public_key'] == fixture['publicKey'] assert data['message'] == fixture['message'] + + +def test_it_accepts_bytes(load_transaction_fixture): + fixture = load_transaction_fixture('message-sign') + + result = Message.new( + message=fixture['message'].encode(), + signature=fixture['signature'][2:].encode(), + public_key=fixture['publicKey'].encode(), + ) + + assert result.verify() is True + assert str(result) == result.to_json() + + +def test_sign_with_bytes(load_transaction_fixture, passphrase): + fixture = load_transaction_fixture('message-sign') + + message = Message.sign(fixture['message'].encode(), passphrase.encode()) + + assert message.signature.decode() == fixture['signature'][2:] + assert message.public_key.decode() == fixture['publicKey'] diff --git a/tests/utils/test_rpl_decoder.py b/tests/utils/test_rpl_decoder.py index c7adc5bd..657d831f 100644 --- a/tests/utils/test_rpl_decoder.py +++ b/tests/utils/test_rpl_decoder.py @@ -1,3 +1,5 @@ +import pytest + from crypto.utils.rlp_decoder import RlpDecoder @@ -36,3 +38,32 @@ def test_decoding_int(): decoded = RlpDecoder.decode('0x86313233343536') assert decoded == '0x313233343536' + + +def test_decoding_empty_list(): + assert RlpDecoder.decode('0xc0') == [] + + +def test_decoding_long_string_without_data(): + assert RlpDecoder.decode('0xb800') == '0x' + + +def test_decoding_with_junk_after_payload(): + with pytest.raises(ValueError, match='unexpected junk after RLP payload'): + RlpDecoder.decode('0x0102') + + +def test_decoding_invalid_hex(): + with pytest.raises(ValueError, match='Invalid BytesLike value: 0x123'): + RlpDecoder.decode('0x123') + + +def test_decoding_child_longer_than_list(): + with pytest.raises(ValueError, match='child data too short or malformed'): + RlpDecoder.decode('0xc282aabb') + + +@pytest.mark.parametrize('data', ['0x', '0x82ff', '0xb9', '0xc2ff']) +def test_decoding_truncated_data(data): + with pytest.raises(ValueError, match='data short segment or out of range'): + RlpDecoder.decode(data) diff --git a/tests/utils/test_rpl_encoder.py b/tests/utils/test_rpl_encoder.py index 9a37c9b4..62b3ffde 100644 --- a/tests/utils/test_rpl_encoder.py +++ b/tests/utils/test_rpl_encoder.py @@ -1,3 +1,5 @@ +import pytest + from crypto.utils.rlp_encoder import RlpEncoder from crypto.utils.transaction_utils import TransactionUtils @@ -39,3 +41,21 @@ def test_encoding_hex_str(): encoded = RlpEncoder.encode('0x3078ab') assert encoded == '833078ab' + + +def test_encoding_empty_hex_str(): + assert RlpEncoder.encode('0x') == '80' + + +def test_encoding_odd_length_hex_str(): + assert RlpEncoder.encode('0x1') == '01' + + +def test_encoding_integers(): + assert RlpEncoder.encode(0) == '80' + assert RlpEncoder.encode(1024) == '820400' + + +def test_encoding_invalid_type(): + with pytest.raises(ValueError, match='invalid type'): + RlpEncoder.encode(1.5) diff --git a/tests/utils/test_slot.py b/tests/utils/test_slot.py index 7119784c..bd52f0b1 100644 --- a/tests/utils/test_slot.py +++ b/tests/utils/test_slot.py @@ -1,5 +1,15 @@ +from datetime import datetime + +from crypto.configuration.network import Network +from crypto.networks.testnet import Testnet from crypto.utils.slot import Slot + +class NetworkWithoutTimezone(Testnet): + def epoch(self): + return '2017-03-21T13:00:00' + + def test_get_epoch(): result = Slot.epoch() assert isinstance(result, int) @@ -7,3 +17,12 @@ def test_get_epoch(): def test_get_time(): result = Slot.time() assert isinstance(result, int) + + +def test_get_epoch_without_timezone_designator(): + Network.set_network(NetworkWithoutTimezone()) + + try: + assert Slot.epoch() == int(datetime(2017, 3, 21, 13).timestamp()) + finally: + Network.set_network(Testnet()) diff --git a/tests/utils/test_transaction_data_encoder.py b/tests/utils/test_transaction_data_encoder.py index 56f57e55..0d963e1f 100644 --- a/tests/utils/test_transaction_data_encoder.py +++ b/tests/utils/test_transaction_data_encoder.py @@ -1,3 +1,4 @@ +from crypto.utils.abi_encoder import AbiEncoder from crypto.utils.transaction_data_encoder import TransactionDataEncoder @@ -49,3 +50,15 @@ def test_encode_multi_payment(load_transaction_fixture): [fixture['Address']], ['1000'] ) assert encoded == fixture['Encoded']['MultiPayment'] + + +def test_encode_vote(): + address = '0xC3bBE9B1CeE1ff85Ad72b87414B0E9B7F2366763' + + expected = AbiEncoder().encode_function_call('vote', [address]) + + assert TransactionDataEncoder.vote(address) == expected + + +def test_encode_unvote(): + assert TransactionDataEncoder.unvote() == '0x3174b689' diff --git a/tests/utils/test_transaction_utils.py b/tests/utils/test_transaction_utils.py new file mode 100644 index 00000000..acd2ce18 --- /dev/null +++ b/tests/utils/test_transaction_utils.py @@ -0,0 +1,22 @@ +import pytest + +from crypto.utils.transaction_utils import TransactionUtils + + +def test_to_buffer_pads_an_odd_length_address(): + transaction = {'gasPrice': 5, 'gasLimit': 21000, 'nonce': 1, 'value': 1} + + padded = TransactionUtils.to_buffer({**transaction, 'to': '0x0abc'}) + + assert TransactionUtils.to_buffer({**transaction, 'to': '0xabc'}) == padded + + +def test_to_be_array(): + assert TransactionUtils.to_be_array(0) == b'' + assert TransactionUtils.to_be_array(256) == b'\x01\x00' + assert TransactionUtils.to_be_array(b'\x01\x02') == b'\x01\x02' + + +def test_to_be_array_with_unsupported_type(): + with pytest.raises(TypeError, match='Unsupported type for to_be_array'): + TransactionUtils.to_be_array('1')