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: 1 addition & 1 deletion src/agirails/dispute/bond_escalation.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

from agirails.types.dispute import AIRuling, DisputeState, Ruling
from agirails.types.dispute import Tier as Tier
from agirails.utils.validation import ensure_valid_cid
from agirails.utils.cid import ensure_valid_cid

# ---------------------------------------------------------------------------
# Constants (AIP-14 §7.4) — load-bearing, mirror BondEscalation.sol + TS twin
Expand Down
2 changes: 1 addition & 1 deletion src/agirails/dispute/uma_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

from agirails.utils.validation import ensure_valid_cid
from agirails.utils.cid import ensure_valid_cid

# ---------------------------------------------------------------------------
# Constants (AIP-14b §7.4 / §8) — load-bearing, mirror BondEscalation.sol + TS
Expand Down
85 changes: 85 additions & 0 deletions src/agirails/utils/cid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""IPFS CID format validation for values the SDK forwards on-chain.

``MAX_CID_LENGTH`` equals the BondEscalation contract's limit.
"""

from __future__ import annotations

import re
from typing import Any

from agirails.errors.storage import InvalidCIDError

CID_V0_PATTERN = re.compile(r"^Qm[1-9A-HJ-NP-Za-km-z]{44}$")
CID_V1_PATTERN = re.compile(r"^b[a-z2-7]{58,}$")

MAX_CID_LENGTH = 256


def validate_cid(cid: Any) -> bool:
"""
Validate IPFS CID format (v0 or v1).

The WHOLE string must be a CIDv0 (``Qm`` + 44 base58btc characters) or a
CIDv1 in base32 (``b`` + at least 58 of ``[a-z2-7]``), at most
:data:`MAX_CID_LENGTH` characters long. Surrounding whitespace, a trailing
newline, paths, query strings and URI schemes are rejected.

Args:
cid: IPFS CID to validate

Returns:
True if valid CID format, False otherwise

Example:
>>> validate_cid("QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco")
True
>>> validate_cid("bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi")
True
>>> validate_cid("invalid-cid")
False
"""
if not isinstance(cid, str) or not cid:
return False

if len(cid) > MAX_CID_LENGTH:
return False

if CID_V0_PATTERN.fullmatch(cid):
return True

return bool(CID_V1_PATTERN.fullmatch(cid))


def ensure_valid_cid(cid: Any, field_name: str = "cid") -> str:
"""
Raise :class:`InvalidCIDError` unless ``cid`` passes :func:`validate_cid`.

Args:
cid: IPFS CID to validate
field_name: Name of the parameter being validated (reported in the error)

Returns:
The CID, unchanged

Raises:
InvalidCIDError: If the CID is missing, too long or malformed
"""
if not isinstance(cid, str) or not cid:
raise InvalidCIDError(str(cid), reason="CID is required", field=field_name)

if len(cid) > MAX_CID_LENGTH:
raise InvalidCIDError(
f"{cid[:64]}...",
reason=f"CID exceeds {MAX_CID_LENGTH} characters (got {len(cid)})",
field=field_name,
)

if not validate_cid(cid):
raise InvalidCIDError(
cid,
reason="Invalid CID format (expected CIDv0 Qm... or CIDv1 bafy...)",
field=field_name,
)

return cid
85 changes: 6 additions & 79 deletions src/agirails/utils/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@
import ipaddress
import re
import socket
from typing import Any, Optional, Union
from typing import Optional, Union
from urllib.parse import urlparse

from agirails.errors import InvalidAddressError, InvalidAmountError, ValidationError
from agirails.errors.storage import InvalidCIDError
from agirails.utils.cid import CID_V0_PATTERN as CID_V0_PATTERN
from agirails.utils.cid import CID_V1_PATTERN as CID_V1_PATTERN
from agirails.utils.cid import MAX_CID_LENGTH as MAX_CID_LENGTH
from agirails.utils.cid import ensure_valid_cid as ensure_valid_cid
from agirails.utils.cid import validate_cid as validate_cid
from agirails.utils.helpers import DisputeWindow

# Constants
Expand Down Expand Up @@ -679,83 +683,6 @@ def validate_content_hash(
]
)

# CID Patterns
CID_V0_PATTERN = re.compile(r"^Qm[1-9A-HJ-NP-Za-km-z]{44}$")
CID_V1_PATTERN = re.compile(r"^b[a-z2-7]{58,}$")

# Maximum accepted CID length in characters (matches the on-chain MAX_CID_LENGTH).
MAX_CID_LENGTH = 256


def validate_cid(cid: Any) -> bool:
"""
Validate IPFS CID format (v0 or v1).

The WHOLE string must be a CIDv0 (``Qm`` + 44 base58btc characters) or a
CIDv1 in base32 (``b`` + at least 58 of ``[a-z2-7]``), at most
:data:`MAX_CID_LENGTH` characters long. Surrounding whitespace, a trailing
newline, paths, query strings and URI schemes are rejected.

Args:
cid: IPFS CID to validate

Returns:
True if valid CID format, False otherwise

Example:
>>> validate_cid("QmXoypizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco")
True
>>> validate_cid("bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi")
True
>>> validate_cid("invalid-cid")
False
"""
if not isinstance(cid, str) or not cid:
return False

if len(cid) > MAX_CID_LENGTH:
return False

# fullmatch: ``$`` alone would also accept a single trailing newline.
if CID_V0_PATTERN.fullmatch(cid):
return True

return bool(CID_V1_PATTERN.fullmatch(cid))


def ensure_valid_cid(cid: Any, field_name: str = "cid") -> str:
"""
Raise :class:`InvalidCIDError` unless ``cid`` passes :func:`validate_cid`.

Args:
cid: IPFS CID to validate
field_name: Name of the parameter being validated (reported in the error)

Returns:
The CID, unchanged

Raises:
InvalidCIDError: If the CID is missing, too long or malformed
"""
if not isinstance(cid, str) or not cid:
raise InvalidCIDError(str(cid), reason="CID is required", field=field_name)

if len(cid) > MAX_CID_LENGTH:
raise InvalidCIDError(
f"{cid[:64]}...",
reason=f"CID exceeds {MAX_CID_LENGTH} characters (got {len(cid)})",
field=field_name,
)

if not validate_cid(cid):
raise InvalidCIDError(
cid,
reason="Invalid CID format (expected CIDv0 Qm... or CIDv1 bafy...)",
field=field_name,
)

return cid


def is_gateway_allowed(gateway_url: str) -> bool:
"""
Expand Down
39 changes: 17 additions & 22 deletions tests/test_dispute/test_dispute_cid_validation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# PARITY: sdk-js/tests/dispute-cid-validation.test.ts
"""
CID validation on the dispute escalation path.

Twin of sdk-js/tests/dispute-cid-validation.test.ts.

Consumes the shared cross-SDK fixture
``test-vectors/dispute/cid-validation-vectors.json`` (byte-identical to the TS
copy). For every call that forwards a CID to BondEscalation, and for each CID
Expand All @@ -18,7 +19,7 @@

import json
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
from typing import Any, Awaitable, Callable, Dict, Generator, List, Optional, Tuple

import pytest
from web3 import Web3
Expand All @@ -32,7 +33,7 @@
compute_evidence_ref_hash,
compute_reasoning_ref_hash,
)
from agirails.utils.validation import validate_cid
from agirails.utils.cid import validate_cid

_ROOT = Path(__file__).resolve().parents[2]
VECTORS = json.loads(
Expand All @@ -59,13 +60,10 @@

FIELDS = ["evidence_cid", "reasoning_cid"]

# (target, kind, method, args); kind is "encode" | "send" | "read".
Recorded = Tuple[str, str, str, Tuple[Any, ...]]


class _Fn:
"""Records a send when called, or a read when ``.call()`` is awaited."""

def __init__(self, sink: List[Recorded], target: str, name: str, read_value: Any):
self._sink = sink
self._target = target
Expand All @@ -83,7 +81,7 @@ async def call(self) -> Any:
self._sink.append((self._target, "read", self._name, self._args))
return self._read_value

def __await__(self): # type: ignore[no-untyped-def]
def __await__(self) -> Generator[Any, None, bytes]:
async def _coro() -> bytes:
return b"\xaa" * 32

Expand Down Expand Up @@ -125,8 +123,6 @@ async def _run_submit_ai_ruling(evidence_cid: str, reasoning_cid: str, sink: Lis
client = BondEscalationClient(contract, address=BOND_ADDR)
reasoning_hash = "0x" + "11" * 32
bundle_hash = "0x" + "22" * 32
# Refs are derived from the SAME CIDs, so without validation the call
# would reach the contract.
ruling = AIRuling(
dispute_id=DISPUTE_ID,
ruling=Ruling.REQUESTER_WINS,
Expand Down Expand Up @@ -174,7 +170,6 @@ async def _run_requester_force_dvm(

Runner = Callable[[str, str, List[Recorded]], Awaitable[Any]]

# (entry name, runner, contract method the CIDs are sent with)
ENTRIES: List[Tuple[str, Runner, str]] = [
("BondEscalationClient.submit_ai_ruling", _run_submit_ai_ruling, "submitAIRuling"),
("BondEscalationClient.escalate_to_uma", _run_escalate_to_uma, "escalateToUMA"),
Expand All @@ -190,19 +185,14 @@ def _cids_for(field: str, cid: str) -> Tuple[str, str]:


def test_vector_file_is_well_formed() -> None:
from agirails.utils.validation import MAX_CID_LENGTH
from agirails.utils.cid import MAX_CID_LENGTH

assert VECTORS["version"] == 1
assert VECTORS["maxLength"] == MAX_CID_LENGTH == 256
assert ACCEPT and REJECT
assert {VALID_EVIDENCE, VALID_REASONING} <= {cid for _n, cid in ACCEPT}


# ---------------------------------------------------------------------------
# validate_cid / ensure_valid_cid over every vector
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("name,cid", ACCEPT, ids=[n for n, _c in ACCEPT])
def test_validate_cid_accepts(name: str, cid: str) -> None:
assert validate_cid(cid) is True
Expand All @@ -215,7 +205,7 @@ def test_validate_cid_rejects(name: str, cid: str) -> None:

@pytest.mark.parametrize("name,cid", REJECT, ids=[n for n, _c in REJECT])
def test_ensure_valid_cid_raises_with_field(name: str, cid: str) -> None:
from agirails.utils.validation import ensure_valid_cid
from agirails.utils.cid import ensure_valid_cid

with pytest.raises(InvalidCIDError) as exc_info:
ensure_valid_cid(cid, "evidence_cid")
Expand All @@ -228,11 +218,6 @@ def test_validate_cid_rejects_non_strings(bad: Any) -> None:
assert validate_cid(bad) is False


# ---------------------------------------------------------------------------
# Every call that forwards a CID to BondEscalation
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("entry", ENTRIES, ids=_ENTRY_IDS)
@pytest.mark.parametrize("field", FIELDS)
@pytest.mark.parametrize("name,cid", ACCEPT, ids=[n for n, _c in ACCEPT])
Expand Down Expand Up @@ -263,3 +248,13 @@ async def test_rejected_cid_raises_before_any_contract_activity(
assert exc_info.value.details["field"] == field
assert field in str(exc_info.value)
assert sink == []


@pytest.mark.parametrize(
"name",
["validate_cid", "ensure_valid_cid", "MAX_CID_LENGTH", "CID_V0_PATTERN", "CID_V1_PATTERN"],
)
def test_validation_module_still_exports_cid_names(name: str) -> None:
from agirails.utils import cid, validation

assert getattr(validation, name) is getattr(cid, name)
Loading