Skip to content

Add boundary check for asset value #338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 5, 2024
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
7 changes: 7 additions & 0 deletions pycardano/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,13 @@ def __copy__(self):
def __deepcopy__(self, memodict={}):
return self.__class__(deepcopy(self.data))

def validate(self):
for key, value in self.data.items():
if isinstance(key, CBORSerializable):
key.validate()
if isinstance(value, CBORSerializable):
value.validate()

def to_shallow_primitive(self) -> dict:
# Sort keys in a map according to https://datatracker.ietf.org/doc/html/rfc7049#section-3.9
def _get_sortable_val(key):
Expand Down
12 changes: 12 additions & 0 deletions pycardano/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@
"Withdrawals",
]

_MAX_INT64 = (1 << 63) - 1
_MIN_INT64 = -(1 << 63)


@dataclass(repr=False)
class TransactionInput(ArrayCBORSerializable):
Expand Down Expand Up @@ -561,6 +564,15 @@ class TransactionBody(MapCBORSerializable):
},
)

def validate(self):
if (
self.mint
and self.mint.count(lambda p, n, v: v < _MIN_INT64 or v > _MAX_INT64) > 0
):
raise InvalidDataException(
f"Mint amount must be between {_MIN_INT64} and {_MAX_INT64}. \n Mint amount: {self.mint}"
)

def hash(self) -> bytes:
return blake2b(self.to_cbor(), TRANSACTION_HASH_SIZE, encoder=RawEncoder) # type: ignore

Expand Down
12 changes: 12 additions & 0 deletions test/pycardano/test_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,3 +469,15 @@ class TestDatum(PlutusData):
cbor = output.to_cbor_hex()

assert cbor == TransactionOutput.from_cbor(cbor).to_cbor_hex()


def test_out_of_bound_asset():
a = Asset({AssetName(b"abc"): 1 << 64})

a.to_cbor_hex() # okay to have out of bound asset

tx = TransactionBody(mint=MultiAsset({ScriptHash(b"1" * SCRIPT_HASH_SIZE): a}))

# Not okay only when minting
with pytest.raises(InvalidDataException):
tx.to_cbor_hex()
Loading