Skip to content

Commit 819a1ea

Browse files
committed
Add boundary check for asset value
1 parent 08c37c8 commit 819a1ea

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

pycardano/serialization.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,13 @@ def __copy__(self):
870870
def __deepcopy__(self, memodict={}):
871871
return self.__class__(deepcopy(self.data))
872872

873+
def validate(self):
874+
for key, value in self.data.items():
875+
if isinstance(key, CBORSerializable):
876+
key.validate()
877+
if isinstance(value, CBORSerializable):
878+
value.validate()
879+
873880
def to_shallow_primitive(self) -> dict:
874881
# Sort keys in a map according to https://datatracker.ietf.org/doc/html/rfc7049#section-3.9
875882
def _get_sortable_val(key):

pycardano/transaction.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@
5454
"Withdrawals",
5555
]
5656

57+
_MAX_INT64 = (1 << 63) - 1
58+
_MIN_INT64 = -(1 << 63)
59+
5760

5861
@dataclass(repr=False)
5962
class TransactionInput(ArrayCBORSerializable):
@@ -78,6 +81,13 @@ class Asset(DictCBORSerializable):
7881

7982
VALUE_TYPE = int
8083

84+
def validate(self):
85+
for n in self:
86+
if self[n] < _MIN_INT64 or self[n] > _MAX_INT64:
87+
raise InvalidDataException(
88+
f"Asset amount must be between {_MIN_INT64} and {_MAX_INT64}: \n {self[n]}"
89+
)
90+
8191
def union(self, other: Asset) -> Asset:
8292
return self + other
8393

test/pycardano/test_transaction.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,3 +469,10 @@ class TestDatum(PlutusData):
469469
cbor = output.to_cbor_hex()
470470

471471
assert cbor == TransactionOutput.from_cbor(cbor).to_cbor_hex()
472+
473+
474+
def test_out_of_bound_asset():
475+
bad_asset = Asset({AssetName(b"abc"): 1 << 64})
476+
477+
with pytest.raises(InvalidDataException):
478+
bad_asset.to_cbor_hex()

0 commit comments

Comments
 (0)