XRPLF / xrpl-py

A Python library to interact with the XRP Ledger (XRPL) blockchain
ISC License
149 stars 86 forks source link

Add runtime validation for string fields #766

Open coderabbitai[bot] opened 2 hours ago

coderabbitai[bot] commented 2 hours ago

As discussed in PR #765 comment, we should consider adding runtime validation for cryptographic fields such as public_key and signature in the XChainAddClaimAttestation class to ensure they meet specific format requirements.\n\nOriginally suggested by @coderabbitai[bot] and agreed upon by @mvadari.

mvadari commented 2 hours ago

Copying this sample code from @coderabbitai's comment:

from typing import NewType
from typing_extensions import Annotated

PublicKeyStr = NewType('PublicKeyStr', str)
SignatureStr = NewType('SignatureStr', str)

def validate_public_key(value: str) -> PublicKeyStr:
    if not is_valid_public_key(value):  # implement validation logic
        raise ValueError("Invalid public key format")
    return PublicKeyStr(value)

# Then use in class:
public_key: Annotated[PublicKeyStr, REQUIRED]
signature: Annotated[SignatureStr, REQUIRED]

If this type of validation can be done at the typing level, that would be really useful for e.g. ensuring that XRP amounts are valid and that blobs are in hex.

coderabbitai[bot] commented 1 hour ago

[!TIP] For best results, initiate chat on the files or code changes.

@‌mvadari, that's a great idea! Implementing validation at the typing level can indeed help ensure that fields like XRP amounts are valid and blobs are in hex format.

Here's how you might define custom types and validators for XRP amounts and hex blobs:

from typing import NewType
from typing_extensions import Annotated

AmountStr = NewType('AmountStr', str)
HexBlobStr = NewType('HexBlobStr', str)

def validate_amount(value: str) -> AmountStr:
    if not is_valid_amount(value):  # implement validation logic
        raise ValueError("Invalid XRP amount format")
    return AmountStr(value)

def validate_hex_blob(value: str) -> HexBlobStr:
    if not is_valid_hex_blob(value):  # implement validation logic
        raise ValueError("Invalid hex blob format")
    return HexBlobStr(value)

# Then in your class:
amount: Annotated[AmountStr, REQUIRED]
blob: Annotated[HexBlobStr, REQUIRED]

You'll need to implement the is_valid_amount and is_valid_hex_blob functions with the specific validation logic for XRP amounts and hex blobs. By integrating validation into the type annotations, you can catch invalid data early and make your code more robust.

Let me know if you need any further assistance!