From 1cb2c4ac7d15e6ad2d7d40eac1a42c08b1bcf94d Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:25:40 +0000 Subject: [PATCH 1/6] chore: update dependencies --- .github/workflows/test.yml | 10 ++++++---- crypto/utils/slot.py | 5 +++-- setup.cfg | 3 --- setup.py | 25 ++++++++++--------------- tests/utils/test_slot.py | 14 +++++++++++++- 5 files changed, 32 insertions(+), 25 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ffd42f4d..ba2b841d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,12 +14,12 @@ jobs: strategy: max-parallel: 4 matrix: - python-version: [3.6, 3.7, 3.8, 3.9] + python-version: ["3.11", "3.12", "3.13"] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v1 + uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} - name: install dependencies @@ -33,4 +33,6 @@ jobs: mkdir test-results pytest -v -s --junitxml=test-reports/junit.xml --cov=crypto --cov-config=.coveragerc --cov-report xml - name: Codecov - run: bash <(curl -s https://codecov.io/bash) -t ${{ secrets.CODECOV_TOKEN }} + uses: codecov/codecov-action@v7 + with: + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/crypto/utils/slot.py b/crypto/utils/slot.py index 23b3d080..ba934d97 100644 --- a/crypto/utils/slot.py +++ b/crypto/utils/slot.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timezone from crypto.configuration.network import get_network @@ -9,7 +9,8 @@ def get_time(): Returns: int: difference in seconds """ - now = datetime.utcnow() + # Network epochs are naive UTC datetimes, so drop tzinfo to keep them comparable + now = datetime.now(timezone.utc).replace(tzinfo=None) network = get_network() seconds = int((now - network['epoch']).total_seconds()) return seconds diff --git a/setup.cfg b/setup.cfg index 3a6687a9..3ee7b291 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,3 @@ -[aliases] -test=pytest - [flake8] max-line-length = 100 application-import-names = crypto diff --git a/setup.py b/setup.py index 0a5c77db..2eb98f16 100644 --- a/setup.py +++ b/setup.py @@ -1,21 +1,19 @@ -import sys - import setuptools requires = [ - 'base58', - 'binary-helpers', - 'coincurve' + 'base58>=2.1.1', + 'binary-helpers>=0.0.4', + 'coincurve>=21.0.0', ] tests_require = [ - 'flake8>=3.5.0', - 'flake8-import-order>=0.17.1', - 'flake8-print>=3.1.0', - 'flake8-quotes>=1.0.0', - 'pytest>=3.6.1', - 'pytest-cov>=2.5.1' + 'flake8>=7.5.0', + 'flake8-import-order>=0.19.2', + 'flake8-print>=5.0.0', + 'flake8-quotes>=3.4.0', + 'pytest>=9.2.0', + 'pytest-cov>=7.1.0', ] extras_require = { @@ -23,8 +21,6 @@ 'dev': requires + tests_require } -setup_requires = ['pytest-runner'] if {'pytest', 'test', 'ptr'}.intersection(sys.argv) else [] - setuptools.setup( name='arkecosystem-crypto', description='A simple Cryptography Implementation in Python for the Ark Blockchain.', @@ -33,8 +29,7 @@ author_email='info@ark.io', url='https://github.com/ArkEcosystem/python-crypto', packages=setuptools.find_packages(exclude=['tests', 'tests.*']), + python_requires='>=3.11', install_requires=requires, extras_require=extras_require, - tests_require=tests_require, - setup_requires=setup_requires, ) diff --git a/tests/utils/test_slot.py b/tests/utils/test_slot.py index fa17037a..58821b59 100644 --- a/tests/utils/test_slot.py +++ b/tests/utils/test_slot.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timezone from crypto.utils.slot import get_epoch, get_time @@ -11,3 +11,15 @@ def test_get_epoch(): def test_get_time(): result = get_time() assert isinstance(result, int) + + +def test_get_time_returns_seconds_since_epoch_in_utc(): + def seconds_since_epoch(): + now = datetime.now(timezone.utc).replace(tzinfo=None) + return int((now - get_epoch()).total_seconds()) + + before = seconds_since_epoch() + result = get_time() + after = seconds_since_epoch() + + assert before <= result <= after From a8ff2eb4fb8eaa7918fdef5c2426b42b2fafde9f Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:25:57 +0000 Subject: [PATCH 2/6] gitignore .venv --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5176d6e9..1fe45f11 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,5 @@ dist/ .vscode .vs venv -venv/ \ No newline at end of file +venv/ +.venv From 3d7c2e8d36c62ef8e9d732e4edfd8464adaa7f36 Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Wed, 2 Dec 2026 03:25:09 +0000 Subject: [PATCH 3/6] fix: vendor field serialization and deserialization The deserializer sliced the vendor field from the wrong offset, so vendorFieldHex was always empty and the id of transactions with a vendor field was wrong. Serializing a vendorFieldHex crashed, and the vendor field length was written in characters rather than bytes. --- CHANGELOG.md | 6 +++ crypto/transactions/deserializer.py | 7 ++- crypto/transactions/serializer.py | 12 ++--- tests/transactions/test_deserializer.py | 59 +++++++++++++++++++++++++ tests/transactions/test_serializer.py | 45 +++++++++++++++++++ 5 files changed, 119 insertions(+), 10 deletions(-) create mode 100644 tests/transactions/test_deserializer.py create mode 100644 tests/transactions/test_serializer.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 384c278f..8bf53b81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ 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 + ## 2.0.0 - 2021-09-21 ## Fixed diff --git a/crypto/transactions/deserializer.py b/crypto/transactions/deserializer.py index c0d9f73f..35614f6a 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 diff --git a/crypto/transactions/serializer.py b/crypto/transactions/serializer.py index f95e9c93..869df800 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) 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'] From adf8aff28623f9477b8e1d63c52be3a5696a38da Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Wed, 2 Dec 2026 03:25:09 +0000 Subject: [PATCH 4/6] fix: HTLC expiration type str, second signature verify result and unsigned deserialization str() of an HTLC_LOCK_EXPIRATION_TYPE raised a TypeError, verify_schnorr_secondsig returned None when valid, and the signature check in parse_signatures had an operator precedence bug that set an empty signature on unsigned transactions. --- CHANGELOG.md | 9 +++++++++ crypto/constants.py | 2 +- crypto/transactions/transaction.py | 8 +++++--- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bf53b81..0e9e3094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ### 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 + +### 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 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/transaction.py b/crypto/transactions/transaction.py index b3a2a653..32c1bc70 100644 --- a/crypto/transactions/transaction.py +++ b/crypto/transactions/transaction.py @@ -104,7 +104,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 +167,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 From 8d9ff863cf2b0169ea2320a89b5c4aa10270c412 Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Wed, 2 Dec 2026 03:25:17 +0000 Subject: [PATCH 5/6] refactor: remove broken sign methods and unused transaction code The sign methods on the Vote and DelegateRegistration builders called a parent sign method that no longer exists, so they always raised. The Transaction _handle_transaction_type and _handle_signature methods were never called. The serializer and deserializer lookup loops had branches that could never run. --- CHANGELOG.md | 7 ++- .../builder/delegate_registration.py | 6 --- crypto/transactions/builder/vote.py | 5 -- crypto/transactions/deserializer.py | 18 +++---- crypto/transactions/serializer.py | 18 +++---- crypto/transactions/transaction.py | 51 ------------------- 6 files changed, 17 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e9e3094..ecee0212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,11 +16,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - `verify_schnorr_secondsig` returns `True` when valid, like the other verify methods - Deserializing an unsigned transaction leaves `signature` unset instead of an empty string -### Fixed +### Removed -- 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 +- 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 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 35614f6a..6cb847f9 100644 --- a/crypto/transactions/deserializer.py +++ b/crypto/transactions/deserializer.py @@ -67,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 869df800..c88de23d 100644 --- a/crypto/transactions/serializer.py +++ b/crypto/transactions/serializer.py @@ -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 32c1bc70..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 @@ -183,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 From 64a253aa222ff918105cf104ed1ed7f69656f84e Mon Sep 17 00:00:00 2001 From: Alex Barnsley <8069294+alexbarnsley@users.noreply.github.com> Date: Wed, 2 Dec 2026 03:25:17 +0000 Subject: [PATCH 6/6] test: increase test coverage to 100% --- tests/configuration/test_network.py | 8 ++ tests/identity/test_address.py | 25 ++++ tests/identity/test_wif.py | 8 ++ tests/schnorr/__init__.py | 0 tests/schnorr/test_schnorr.py | 126 ++++++++++++++++++ tests/test_constants.py | 12 ++ tests/transactions/builder/test_base.py | 58 ++++++++ .../test_multi_signature_registration.py | 9 ++ tests/transactions/builder/test_vote.py | 16 +++ tests/transactions/deserializers/test_vote.py | 15 +++ tests/transactions/serializers/test_vote.py | 12 ++ tests/transactions/test_transaction.py | 83 ++++++++++++ tests/utils/test_message.py | 7 + 13 files changed, 379 insertions(+) create mode 100644 tests/schnorr/__init__.py create mode 100644 tests/schnorr/test_schnorr.py create mode 100644 tests/test_constants.py create mode 100644 tests/transactions/builder/test_base.py 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_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'])