Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[run]
branch = True
source = crypto
omit =
crypto/thirdparty/*

[report]
exclude_lines =
Expand Down
2 changes: 1 addition & 1 deletion crypto/identity/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 5 additions & 4 deletions crypto/transactions/deserializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 1 addition & 4 deletions crypto/utils/abi_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 5 additions & 9 deletions crypto/utils/abi_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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']
Expand All @@ -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):
Expand Down
32 changes: 16 additions & 16 deletions crypto/utils/abi_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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', [])
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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']:
Expand Down
2 changes: 1 addition & 1 deletion crypto/utils/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crypto/utils/rlp_decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
8 changes: 1 addition & 7 deletions crypto/utils/rlp_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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

Expand All @@ -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))
3 changes: 0 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
'binary-helpers>=0.0.4',
'coincurve>=21.0.0',
'pycryptodomex>=3.24.2',
'cryptography>=50.0.2',
]

tests_require = [
Expand Down
4 changes: 4 additions & 0 deletions tests/configuration/test_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
4 changes: 4 additions & 0 deletions tests/identity/test_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions tests/identity/test_legacy_address.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from base58 import b58encode_check

from crypto.identity.legacy_address import LegacyAddress


Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions tests/identity/test_private_key.py
Original file line number Diff line number Diff line change
@@ -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'])
Expand All @@ -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)
13 changes: 13 additions & 0 deletions tests/identity/test_proof_of_possession.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
7 changes: 7 additions & 0 deletions tests/identity/test_wif.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions tests/transactions/builder/test_token_approve_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions tests/transactions/builder/test_token_transfer_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
24 changes: 24 additions & 0 deletions tests/transactions/builder/test_transfer_builder.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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({})
Loading