"""p2panda transport rung for TransportRouter ladder.
Standard library only. Delivers messages wrapped as append-only p2panda operations
to local log and sync peers.
"""
from __future__ import annotations
import logging
from typing import Any, Callable, Mapping, Optional
from fleetmesh_core.wire.cbor import cbor_encode
from fleetmesh_core.wire.p2panda import P2PandaOperation
from fleetmesh_node.transport import netfetch
from fleetmesh_node.transport.const import TransportError
from fleetmesh_node.transport.ladder import FaultLog
from fleetmesh_node.transport.rung import Rung, Verdict, endpoints_of
from .identity import P2PandaIdentityAdapter
from .store import P2PandaLogStore
__all__ = [
'P2PandaRung',
]
log = logging.getLogger(__name__)
# A push answers with a status line and, at most, a short JSON body; anything
# larger is a hostile or broken peer, not a delivery receipt.
MAX_PUSH_RESPONSE_BYTES = 64 * 1024
[docs]class P2PandaRung(Rung):
"""Outbound transport rung delivering through p2panda append-only operation chains."""
name = 'p2panda'
rank = 15
[docs] def __init__(
self,
store: Optional[P2PandaLogStore] = None,
identity: Optional[P2PandaIdentityAdapter] = None,
enabled: bool = True,
clock: Optional[Callable[[], int]] = None,
allow_local_peers: bool = False,
) -> None:
self.store = store
self.identity = identity
self.enabled = enabled
self.clock = clock
# Dev/LAN only: the target URL comes from the peer's descriptor, so
# netfetch refuses private addresses unless the operator turns this on.
self.allow_local_peers = allow_local_peers
self.faults = FaultLog(rung=self.name, clock=clock)
[docs] def available(self) -> bool:
"""The local side of this rung is up and an identity is configured."""
return (
self.enabled
and self.identity is not None
and bool(self.identity.author_id)
and self.store is not None
)
[docs] def target_of(self, desc: Optional[Mapping[str, Any]], theirs: Mapping[str, int]) -> Optional[str]:
"""Where this rung would reach the peer that published desc."""
if desc is not None:
_, where = endpoints_of(desc)
if 'p2panda' in where:
return where['p2panda']
for t in desc.get('tags', []):
if not t:
continue
if t[0] == 'c' and len(t) > 1 and t[1] == 'p2panda':
return ''
if 'p2panda' in theirs:
return ''
return None
[docs] def deliver(self, message: Mapping[str, Any], to_pubkey: str, target: str, anonymous: bool) -> Verdict:
"""Deliver message by signing and appending a p2panda operation to the log."""
if not self.available():
raise TransportError('p2panda rung unavailable or not configured with signing identity and store')
assert self.identity is not None
assert self.store is not None
if self.identity._private_key is None:
raise TransportError('p2panda identity does not have private signing key configured')
author_id = self.identity.author_id
try:
latest_seq = self.store.get_latest_seq(author_id)
next_seq = latest_seq + 1
backlink = None
if latest_seq >= 0:
latest_op = self.store.get_latest_operation(author_id)
if latest_op is not None:
backlink = latest_op.id
# Canonical CBOR serialization of the payload
payload_bytes = cbor_encode(dict(message), canonical=True)
extensions = {
'target': to_pubkey,
'anonymous': bool(anonymous),
}
op = P2PandaOperation.create(
public_key=author_id,
body=payload_bytes,
seq_num=next_seq,
backlink=backlink,
private_key=self.identity._private_key,
extensions=extensions,
)
self.store.append_operation(op, verify_chain=True)
# If target specifies an HTTP/HTTPS endpoint, push operation
if target and (target.startswith('http://') or target.startswith('https://')):
self._push_http(target, op)
return {self.name: (True, f'delivered via operation {op.id[:16]} seq={op.seq_num}')}
except Exception as e:
self.faults.record(f'deliver failed: {e}', ident=to_pubkey[:16] if to_pubkey else None)
raise TransportError(f'p2panda delivery failed: {e}') from e
def _push_http(self, target_url: str, op: P2PandaOperation) -> None:
url = target_url
if not url.endswith('/p2panda/operations') and not url.endswith('/operations'):
url = f"{url.rstrip('/')}/p2panda/operations"
data = op.to_cbor()
# The endpoint comes from the peer's published descriptor (see
# TransportRouter: target_of(desc)), so the peer chooses it. It gets
# the full netfetch policy -- no loopback/private/link-local/metadata
# address, redirects re-checked -- unless the operator opted into
# local peers, and a small cap either way: a push only ever answers
# with a status and, at most, a short JSON body.
try:
netfetch.fetch(
url,
max_bytes=MAX_PUSH_RESPONSE_BYTES,
timeout=5.0,
method='POST',
data=data,
headers={
'Content-Type': 'application/cbor',
'User-Agent': 'Fleetmesh-p2panda/0.4.0',
},
allow_private=self.allow_local_peers,
)
except netfetch.FetchHTTPError as e:
raise TransportError(f"HTTP upstream returned status {e.code}") from e
except netfetch.FetchError as e:
raise TransportError(f"Failed to push operation to {url}: {e}") from e
[docs] def health(self) -> Optional[Mapping[str, Any]]:
return {
'available': self.available(),
'author_id': self.identity.author_id if self.identity else '',
'ops_stored': self.store.count_operations() if self.store else 0,
}
[docs] def fault_log(self) -> Optional[FaultLog]:
return self.faults