"""p2panda protocol wire data structures and cryptographic operations.
Conforms to p2panda specification v0.4.0:
- Canonical CBOR deterministic encoding (RFC 8949) using `fleetmesh_core.wire.cbor`.
- Ed25519 author identities and signatures.
- Append-only cryptographic operation logs with monotonic sequence numbers and backlinks.
"""
from __future__ import annotations
import dataclasses
import hashlib
import time
from typing import Any, Mapping, Optional, Sequence, TypedDict, Union
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric import ed25519
from ..conformance.errors import FleetmeshError
from .cbor import cbor_decode, cbor_encode
P2PANDA_VERSION: int = 1
DEFAULT_HASH_ALGO: str = 'sha256'
[docs]class P2PandaHeaderDict(TypedDict, total=False):
version: int
public_key: str
signature: str
payload_size: int
payload_hash: str
timestamp: int
seq_num: int
backlink: str
previous_seq_num: int
extensions: Mapping[str, Any]
[docs]class P2PandaOperationDict(TypedDict, total=False):
header: P2PandaHeaderDict
body: Union[bytes, str]
[docs]class P2PandaError(FleetmeshError, ValueError):
"""Base error for p2panda wire parsing, serialization, and validation."""
pass
def _hash_bytes(data: bytes, algo: str = DEFAULT_HASH_ALGO) -> str:
"""Compute hex digest of bytes using specified algorithm."""
if algo == 'sha256':
return hashlib.sha256(data).hexdigest()
if algo in ('blake2b', 'blake2s'):
h = hashlib.new(algo)
h.update(data)
return h.hexdigest()
# Fallback to sha256
return hashlib.sha256(data).hexdigest()
[docs]@dataclasses.dataclass(frozen=True)
class P2PandaHeader:
"""Header for a p2panda operation.
Contains cryptographic provenance, log ordering, author identity,
and payload integrity metadata.
"""
version: int = P2PANDA_VERSION
public_key: str = '' # 64-character lowercase hex Ed25519 public key
signature: Optional[str] = None # 128-character lowercase hex Ed25519 signature
payload_size: int = 0 # Size of body in bytes
payload_hash: str = '' # Hex digest of payload body
timestamp: int = 0 # UNIX timestamp in seconds
seq_num: int = 0 # Monotonic sequence number (0-indexed)
backlink: Optional[str] = None # ID (hash) of previous operation in log
previous_seq_num: Optional[int] = None # Sequence number of previous operation
extensions: Optional[Mapping[str, Any]] = None
def __post_init__(self) -> None:
if self.public_key and len(self.public_key) != 64:
raise P2PandaError(f"public_key must be a 64-char hex string, got {len(self.public_key)} chars")
if self.signature and len(self.signature) != 128:
raise P2PandaError(f"signature must be a 128-char hex string, got {len(self.signature)} chars")
if self.payload_size < 0:
raise P2PandaError(f"payload_size must be non-negative, got {self.payload_size}")
if self.seq_num < 0:
raise P2PandaError(f"seq_num must be non-negative, got {self.seq_num}")
if self.seq_num == 0:
if self.backlink is not None:
raise P2PandaError("Genesis operation (seq_num 0) cannot have a backlink")
if self.previous_seq_num is not None:
raise P2PandaError("Genesis operation (seq_num 0) cannot have previous_seq_num")
else:
if self.backlink is None:
raise P2PandaError(f"seq_num {self.seq_num} requires a backlink pointing to previous operation")
if self.previous_seq_num is not None and self.previous_seq_num != self.seq_num - 1:
raise P2PandaError(f"previous_seq_num {self.previous_seq_num} must equal seq_num - 1 ({self.seq_num - 1})")
[docs] def to_unsigned_dict(self) -> P2PandaHeaderDict:
"""Return canonical mapping of fields covered by the author's signature."""
d: P2PandaHeaderDict = {
'version': self.version,
'public_key': self.public_key.lower(),
'payload_size': self.payload_size,
'payload_hash': self.payload_hash.lower(),
'timestamp': self.timestamp,
'seq_num': self.seq_num,
}
if self.backlink is not None:
d['backlink'] = self.backlink.lower()
if self.previous_seq_num is not None:
d['previous_seq_num'] = self.previous_seq_num
if self.extensions is not None:
d['extensions'] = dict(self.extensions)
return d
[docs] def to_dict(self, include_signature: bool = True) -> P2PandaHeaderDict:
"""Return dictionary representation of the header."""
d = self.to_unsigned_dict()
if include_signature and self.signature is not None:
d['signature'] = self.signature.lower()
return d
[docs] def to_cbor(self, include_signature: bool = True) -> bytes:
"""Encode header into canonical CBOR (RFC 8949)."""
d = self.to_dict(include_signature=include_signature)
return cbor_encode(d, canonical=True)
[docs] def unsigned_cbor(self) -> bytes:
"""Encode unsigned header fields into canonical CBOR for signing/verifying."""
d = self.to_unsigned_dict()
return cbor_encode(d, canonical=True)
[docs] def unsigned_hash(self, algo: str = DEFAULT_HASH_ALGO) -> str:
"""Compute digest of the unsigned canonical CBOR bytes."""
return _hash_bytes(self.unsigned_cbor(), algo=algo)
[docs] def hash(self, algo: str = DEFAULT_HASH_ALGO) -> str:
"""Compute digest of the complete (signed) canonical CBOR header bytes.
This serves as the operation identifier (op_id).
"""
return _hash_bytes(self.to_cbor(include_signature=True), algo=algo)
[docs] @classmethod
def from_dict(cls, raw: Mapping[str, Any]) -> 'P2PandaHeader':
"""Construct P2PandaHeader from a dictionary."""
if not isinstance(raw, Mapping):
raise P2PandaError("Header raw data must be a mapping")
version = int(raw.get('version', P2PANDA_VERSION))
public_key = str(raw.get('public_key', '')).lower()
signature = str(raw['signature']).lower() if raw.get('signature') else None
payload_size = int(raw.get('payload_size', 0))
payload_hash = str(raw.get('payload_hash', '')).lower()
timestamp = int(raw.get('timestamp', 0))
seq_num = int(raw.get('seq_num', 0))
backlink = str(raw['backlink']).lower() if raw.get('backlink') else None
previous_seq_num = int(raw['previous_seq_num']) if raw.get('previous_seq_num') is not None else None
extensions = dict(raw['extensions']) if isinstance(raw.get('extensions'), Mapping) else None
return cls(
version=version,
public_key=public_key,
signature=signature,
payload_size=payload_size,
payload_hash=payload_hash,
timestamp=timestamp,
seq_num=seq_num,
backlink=backlink,
previous_seq_num=previous_seq_num,
extensions=extensions,
)
[docs] @classmethod
def from_cbor(cls, data: bytes) -> 'P2PandaHeader':
"""Decode P2PandaHeader from canonical CBOR bytes."""
val, consumed = cbor_decode(data)
if not isinstance(val, Mapping):
raise P2PandaError("Decoded CBOR header is not a mapping")
return cls.from_dict(val)
[docs]@dataclasses.dataclass(frozen=True)
class P2PandaOperation:
"""A complete p2panda operation comprising a signed header and body payload."""
header: P2PandaHeader
body: Optional[bytes] = None
@property
def id(self) -> str:
"""Unique operation ID derived from the signed header hash."""
return self.header.hash()
@property
def author(self) -> str:
"""Author's Ed25519 public key hex string."""
return self.header.public_key
@property
def seq_num(self) -> int:
return self.header.seq_num
@property
def backlink(self) -> Optional[str]:
return self.header.backlink
[docs] def verify_signature(self) -> bool:
"""Verify the author's Ed25519 signature over the canonical unsigned header bytes."""
if not self.header.signature or not self.header.public_key:
return False
try:
pub_bytes = bytes.fromhex(self.header.public_key)
sig_bytes = bytes.fromhex(self.header.signature)
verifier = ed25519.Ed25519PublicKey.from_public_bytes(pub_bytes)
# Author signs the canonical CBOR encoded unsigned header fields
unsigned_bytes = self.header.unsigned_cbor()
verifier.verify(sig_bytes, unsigned_bytes)
return True
except (InvalidSignature, ValueError):
return False
[docs] def verify_payload(self) -> bool:
"""Verify that the payload size and hash match the body (if body is present)."""
if self.body is None:
# Body omitted / pruned; header-only verification passes if payload_size is 0 or body unattached
return self.header.payload_size == 0 or len(self.header.payload_hash) > 0
if len(self.body) != self.header.payload_size:
return False
computed = _hash_bytes(self.body)
return computed.lower() == self.header.payload_hash.lower()
[docs] def verify(self) -> bool:
"""Verify both cryptographic signature and payload integrity."""
return self.verify_signature() and self.verify_payload()
[docs] def sign(self, private_key: ed25519.Ed25519PrivateKey) -> 'P2PandaOperation':
"""Sign this operation with the given Ed25519 private key, returning a new operation with signature set."""
pub_raw = private_key.public_key().public_bytes_raw()
pub_hex = pub_raw.hex()
if self.header.public_key and self.header.public_key.lower() != pub_hex.lower():
raise P2PandaError(f"Header public_key ({self.header.public_key}) does not match signing key ({pub_hex})")
unsigned_bytes = self.header.unsigned_cbor()
signature_bytes = private_key.sign(unsigned_bytes)
new_header = dataclasses.replace(
self.header,
public_key=pub_hex,
signature=signature_bytes.hex(),
)
return P2PandaOperation(header=new_header, body=self.body)
[docs] def to_dict(self, json_safe: bool = False) -> P2PandaOperationDict:
"""Serialize operation to dictionary."""
d: P2PandaOperationDict = {
'header': self.header.to_dict(include_signature=True),
}
if self.body is not None:
if json_safe:
try:
d['body'] = self.body.decode('utf-8')
except UnicodeDecodeError:
d['body'] = "hex:" + self.body.hex()
else:
d['body'] = self.body
return d
[docs] def to_cbor(self) -> bytes:
"""Serialize entire operation to canonical CBOR."""
return cbor_encode(self.to_dict(json_safe=False), canonical=True)
[docs] @classmethod
def from_dict(cls, raw: Mapping[str, Any]) -> 'P2PandaOperation':
"""Construct P2PandaOperation from dictionary."""
if not isinstance(raw, Mapping):
raise P2PandaError("Operation raw data must be a mapping")
header_raw = raw.get('header')
if not isinstance(header_raw, Mapping):
raise P2PandaError("Missing or invalid 'header' in operation mapping")
header = P2PandaHeader.from_dict(header_raw)
body = raw.get('body')
body_bytes: Optional[bytes] = None
if body is not None:
if isinstance(body, (bytes, bytearray)):
body_bytes = bytes(body)
elif isinstance(body, str):
if body.startswith("hex:"):
try:
body_bytes = bytes.fromhex(body[4:])
except ValueError:
body_bytes = body.encode('utf-8')
else:
body_bytes = body.encode('utf-8')
elif isinstance(body, Mapping):
body_bytes = cbor_encode(body, canonical=True)
else:
body_bytes = bytes(body)
return cls(header=header, body=body_bytes)
[docs] @classmethod
def from_cbor(cls, data: bytes) -> 'P2PandaOperation':
"""Decode P2PandaOperation from CBOR bytes."""
val, consumed = cbor_decode(data)
if not isinstance(val, Mapping):
raise P2PandaError("Decoded CBOR operation is not a mapping")
return cls.from_dict(val)
[docs] @classmethod
def create(
cls,
public_key: str,
body: Optional[Union[bytes, str, Mapping[str, Any]]] = None,
seq_num: int = 0,
backlink: Optional[str] = None,
timestamp: Optional[int] = None,
private_key: Optional[ed25519.Ed25519PrivateKey] = None,
extensions: Optional[Mapping[str, Any]] = None,
) -> 'P2PandaOperation':
"""Factory method to assemble, hash, and optionally sign a new operation."""
ts = int(time.time()) if timestamp is None else int(timestamp)
payload_bytes: Optional[bytes] = None
if body is not None:
if isinstance(body, bytes):
payload_bytes = body
elif isinstance(body, str):
payload_bytes = body.encode('utf-8')
else:
payload_bytes = cbor_encode(body, canonical=True)
payload_size = len(payload_bytes) if payload_bytes is not None else 0
payload_hash = _hash_bytes(payload_bytes) if payload_bytes is not None else _hash_bytes(b'')
previous_seq = (seq_num - 1) if seq_num > 0 else None
header = P2PandaHeader(
version=P2PANDA_VERSION,
public_key=public_key.lower(),
signature=None,
payload_size=payload_size,
payload_hash=payload_hash,
timestamp=ts,
seq_num=seq_num,
backlink=backlink.lower() if backlink else None,
previous_seq_num=previous_seq,
extensions=extensions,
)
op = cls(header=header, body=payload_bytes)
if private_key is not None:
op = op.sign(private_key)
return op
[docs]def validate_operation_chain(ops: Sequence[P2PandaOperation]) -> tuple[bool, Optional[str]]:
"""Validate an ordered append-only sequence of operations by an author.
Checks:
1. Signature validity for every operation.
2. Payload integrity for operations containing bodies.
3. Author consistency across all operations in the chain.
4. Strict monotonic sequence numbers (seq_num == prev_seq_num + 1).
5. Backlink continuity (backlink == prev_operation.id).
6. Non-decreasing chronological timestamps.
"""
if not ops:
return True, None
author = ops[0].author
prev_op: Optional[P2PandaOperation] = None
for i, op in enumerate(ops):
# 1. Author consistency
if op.author != author:
return False, f"Author mismatch at index {i}: expected {author}, got {op.author}"
# 2. Cryptographic signature check
if not op.verify_signature():
return False, f"Invalid signature at index {i} (seq_num {op.seq_num})"
# 3. Payload integrity check (if body present)
if not op.verify_payload():
return False, f"Payload verification failed at index {i} (seq_num {op.seq_num})"
# 4. Chain link validation
if prev_op is None:
# First item in sequence
if op.seq_num == 0:
if op.backlink is not None:
return False, f"Genesis operation at index {i} must not have a backlink"
if op.header.previous_seq_num is not None:
return False, f"Genesis operation at index {i} must not have previous_seq_num"
elif op.backlink is None:
return False, f"Non-genesis operation at index 0 (seq_num {op.seq_num}) missing backlink"
else:
expected_seq = prev_op.seq_num + 1
if op.seq_num != expected_seq:
return False, f"Sequence gap at index {i}: expected {expected_seq}, got {op.seq_num}"
if op.header.previous_seq_num != prev_op.seq_num:
return False, f"previous_seq_num mismatch at index {i}: expected {prev_op.seq_num}, got {op.header.previous_seq_num}"
expected_backlink = prev_op.id.lower()
actual_backlink = (op.backlink or '').lower()
if actual_backlink != expected_backlink:
return False, f"Backlink mismatch at index {i}: expected {expected_backlink}, got {actual_backlink}"
if op.header.timestamp < prev_op.header.timestamp:
return False, f"Timestamp retrograde at index {i}: {op.header.timestamp} < {prev_op.header.timestamp}"
prev_op = op
return True, None