ipld / ipld/py-ipld-dag

`Block.encode()` doesn't validate CIDv0 requires dag-pb codec

Open Beginner friendly
#26 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
13
Forks
9
PR merge metrics
No merged PRs in 30d

Description

`Block.encode()` accepts `version=0` with any codec. Per the CID specification, CIDv0 must use the `dag-pb` codec. The code should validate this constraint.

### Problem

In `dag/block.py`:

```python
@classmethod
def encode(cls, *, value, codec, hasher="sha2-256", version=1):
if isinstance(codec, int):
codec = get_codec(codec)

encoded = codec.encode(value)
mh = _multihash.digest(encoded, hasher)
cid = make_cid(version, codec.name, mh.encode())
# ← No validation that version=0 requires codec="dag-pb"
return cls(cid=cid, data=encoded, value=value, codec=codec)
```

This allows creating invalid CIDv0 objects:

```python
# This should raise an error, but doesn't:
block = Block.encode(
value=b"hello",
codec=raw.codec, # raw codec, not dag-pb!
version=0, # CIDv0 requires dag-pb
)
```

### Proposed Solution

Add validation:

```python
@classmethod
def encode(cls, *, value, codec, hasher="sha2-256", version=1):
if isinstance(codec, int):
codec = get_codec(codec)

# Validate CIDv0 constraints
if version == 0 and codec.name != "dag-pb":
raise ValueError(
f"CIDv0 requires dag-pb codec, got {codec.name!r}. "
f"Use version=1 for other codecs."
)

# Validate CIDv0 hasher constraint
if version == 0 and hasher != "sha2-256":
raise ValueError(
f"CIDv0 requires sha2-256 hasher, got {hasher!r}."
)

encoded = codec.encode(value)
mh = _multihash.digest(encoded, hasher)
cid = make_cid(version, codec.name, mh.encode())
return cls(cid=cid, data=encoded, value=value, codec=codec)
```

### Related

- CID spec: https://github.com/multiformats/cid
- File: `dag/block.py`

Contributor guide

Open the contributing guide

Research direction

Start with dag/block.py and the Block.encode entry point shown in the issue. Check how codec names and hashers are represented, then verify that CIDv0 rejects non-dag-pb codecs and non-sha2-256 hashers while valid inputs remain supported. Done means the invalid examples raise the documented errors without changing CIDv1 behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
distributed-systems
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
76/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.