bus

package
v0.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

SPDX-License-Identifier: AGPL-3.0-or-later

Package bus implements the WebSocket transport and wire protocol for node-to-node task delegation (design doc §10).

Index

Constants

View Source
const (
	MsgHello = "hello"
	// MsgHelloReject is the only pre-auth frame a server sends back: the
	// peer's hello failed verification, and this is the reason it is about
	// to be dropped. Without it a rejected dialer saw "connected" then EOF —
	// indistinguishable from a network flap — and kept redialing forever.
	MsgHelloReject       = "hello_reject"
	MsgJoin              = "join"
	MsgHeartbeat         = "heartbeat"
	MsgTaskDelegate      = "task_delegate"
	MsgTaskAccept        = "task_accept"
	MsgTaskDecline       = "task_decline"
	MsgTaskProgress      = "task_progress"
	MsgTaskActivities    = "task_activities"
	MsgTaskActivityFetch = "task_activity_fetch"
	MsgTaskResult        = "task_result"
	MsgTaskRetry         = "task_retry"
	MsgTaskTransfer      = "task_transfer"
	MsgTaskCancel        = "task_cancel"
	// MsgTaskResume is the delegator's approval for a task the executor
	// parked in review for lack of tier-2 consent: the user granted it, and
	// the re-run belongs on the node that holds the task (its capability
	// match, context, and worktree), not wherever the approval was given.
	// With Payload.Accept set it is the mirror of that decision: the parked
	// copy closes as done instead of re-running (work that already ran was
	// accepted on the other side).
	MsgTaskResume = "task_resume"
	// MsgTaskMessage carries a sibling-board post between tasks of one scope
	// (plan stages, or a parent's delegate children). It is best-effort
	// signal traffic: member → scope owner → addressed fan-out copies, the
	// per-sender slot making a lost frame silently correctable by the next
	// post — which is why it carries no outbox of its own.
	MsgTaskMessage  = "task_message"
	MsgContextFetch = "context_fetch"
	MsgContextAck   = "context_ack"
	// Artifact transfer is a pull in fixed-size chunks: the node that needs a
	// task's output asks the node that holds it, one offset at a time. It is
	// chunked because a single frame may not exceed readLimit (4 MiB) and an
	// artifact is a build tree or a trained model.
	MsgArtifactFetch = "artifact_fetch"
	MsgArtifactChunk = "artifact_chunk"
	// Artifact push is the proactive half of the data plane (whitepaper §8.3
	// fat-push): instead of waiting for the consumer to pull, the holder
	// streams chunks out of a persisted outbox. The receiver stages them on
	// disk and reports contiguous progress (status) plus the terminal
	// verification verdict (done) — the custody signals that let a transfer
	// resume from the receiver's own offset after a reconnect instead of
	// restarting a multi-hundred-MiB archive.
	MsgArtifactPush       = "artifact_push"
	MsgArtifactPushStatus = "artifact_push_status"
	MsgArtifactPushDone   = "artifact_push_done"
	// Agent horizontal negotiation signaling (whitepaper §5.1).
	MsgAgentNegotiate = "agent_negotiate"
	MsgAgentGrant     = "agent_grant"
	MsgAgentYield     = "agent_yield"
	// MsgDTNBundle carries a signed CBOR DTN bundle (§8.3) on the wire: the
	// bundle — not a plain task_delegate — is the canonical form a
	// store-and-forward task takes once it leaves the origin, so a parked
	// row redelivers byte-identical signed data and a live DTN dispatch is
	// the same object as its outboxed copy.
	MsgDTNBundle = "dtn_bundle"
	// Punch coordination (farsky §9.2). The offer/ready pair are control
	// envelopes routed through the mesh (direct conn or link-state next hop)
	// to arrange a UDP pinhole between two NAT-bound nodes; the actual
	// punching is raw punch/ack datagrams, not envelopes. TTL inside the
	// payload bounds the relay hops, and the receiver's msg-id dedup kills
	// any residual loop.
	MsgPunchOffer = "punch_offer"
	MsgPunchReady = "punch_ready"
	// MsgPunchWant is the auto-punch hint (cross-network mesh M3): the
	// sender tells the receiver "please send ME a punch_offer" — the fix
	// for the election's blind end, where only the lexicographically
	// larger node observed the send failure but the smaller one owns the
	// offerer role. It relays like punch_offer (TTL-bounded); a receiver
	// honoring it punches env.From.
	MsgPunchWant = "punch_want"
	// MsgTransit is the blind-relay envelope (cross-network mesh design M3):
	// it carries a sealed inner frame toward a destination the sender cannot
	// reach directly. Relays read only the payload's outer shell — the
	// destination's stable key, a decremented TTL and a byte size — never the
	// contents, which are end-to-end sealed under the destination's X25519
	// identity (or the member-level mesh seal when the peer published none).
	MsgTransit = "transit"
	// MsgDirPull/MsgDirRows are the epidemic directory sync pair
	// (cross-network mesh design M1). A heartbeat's dir_digest mismatch
	// prompts the receiver to send dir_pull carrying its id→content_hash
	// stamp table; the peer answers dir_rows with the differing/missing
	// signed rows plus a want list of the ids IT lacks, so one exchange
	// converges both sides. Old nodes ignore both frames — their digest
	// field is absent, their pull never comes, sync simply never starts.
	MsgDirPull = "dir_pull"
	MsgDirRows = "dir_rows"
	// MsgDialCheck/MsgDialCheckAck are the AutoNAT-style proof (cross-network
	// mesh M2/P5): a node that wants to CLAIM rendezvous asks peers to dial
	// its advertised address back. The ability is verified, not asserted —
	// the claim rides the capability card only after an ack says the dial
	// actually reached us.
	MsgDialCheck    = "dial_check"
	MsgDialCheckAck = "dial_check_ack"
	// Bluetooth-style LAN pairing (pair_hello is the ONLY frame accepted on
	// an unauthenticated connection besides hello — it runs an ephemeral
	// X25519 exchange so the two operators can compare a short code and the
	// responder can hand the shared secret over the sealed channel; see
	// internal/core/pairing.go).
	MsgPairHello  = "pair_hello"
	MsgPairReady  = "pair_ready"
	MsgPairSecret = "pair_secret"
	MsgPairReject = "pair_reject"
)

Message types. These strings are the routing key in the envelope's "type" field and are part of the cross-node protocol.

View Source
const (
	// DeclineCodeTrustOpen — the origin's tier may not originate push-mode
	// work: open peers exist only in the directory until the market lands.
	DeclineCodeTrustOpen = "trust_open_origin"
	// DeclineCodeTrustRefused — the receiver's accept policy declined the
	// delegate (mode refuse, or an enforcing policy classifier's verdict).
	DeclineCodeTrustRefused = "trust_policy_refused"
	// DeclineCodeTrustCeiling — the sender's next-hop ceiling stripped a
	// need the task cannot run without (pack or inputs); re-routing is the
	// correct response, not retry.
	DeclineCodeTrustCeiling = "trust_send_ceiling"
)

Decline reason codes (TaskDeclinePayload.ReasonCode) — machine-stable vocabulary layered over the human-readable Reason. The trust-zone codes let a delegator distinguish "this node cannot" from "this node's policy chose not to" — the first triggers re-routing as before, the second may surface a different fix (raise the peer's tier, or accept that open-tier strangers get no pushes until the offer/bid market exists).

View Source
const (
	QoSControl = iota // cancels, declines, grants, yields, hello/heartbeat
	QoSSignal         // task lifecycle: delegate/result/resume/context
	QoSData           // artifact chunks — the bandwidth-heavy plane
	QoSBulk           // everything else

)

QoS lanes (whitepaper §5.3): control beats signal beats data beats bulk. The lanes exist so a task_cancel or a negotiation yield jumps ahead of the artifact stream that would otherwise hold the write slot — the mesh's "control plane can always speak" guarantee.

View Source
const (
	CapTransitE2E   = "e2et"
	CapTransitRelay = "trnz"
)

Hello capabilities (additive wire negotiation, same pattern as CapBinaryData/CapSessionAEAD): e2et = the node can be a transit DESTINATION sealed for with X25519 (it published x_pub and implements the open side); trnz = the node understands transit frames and will relay them for authenticated members. A peer that lists neither predates the feature and is skipped as both relay and destination.

View Source
const (
	SealX25519 = "x25519"
	SealMesh   = "mesh"
	// SealNone is the pairing exemption (cross-network mesh P4b): a joiner
	// holds no shared secret yet and does not know the introducer's X25519
	// key, so a transit-wrapped pair_hello cannot be sealed to anything. It
	// carries no secret — the DH box and the SAS do the protecting — and
	// every receiver accepts it ONLY for pair_* inner types. Anything else
	// sealed "none" is refused.
	SealNone = "none"
)

Transit seal levels (design §3). x25519 is end-to-end: the blob opens only under the destination's X25519 identity key, so relays see dest + size + TTL and nothing else. mesh is the honest-degradation level for a peer that never published x_pub: HKDF over the shared secret keeps the contents member-confidential on the path but readable by any member relay — the sender reports transit_degraded when it has to pick it.

View Source
const ArtifactChunkBytes = 1 << 20

ArtifactChunkBytes is the payload size one artifact_chunk carries. The transport caps a frame at readLimit (4 MiB) and []byte is base64-encoded in JSON (a 4/3 expansion), so 1 MiB of artifact becomes roughly 1.4 MiB on the wire — comfortably under the cap even with the envelope around it.

View Source
const CapActivities = "activity-cursor-v1"
View Source
const CapBinaryData = "binart"

CapBinaryData is the hello-advertised capability for binary data frames: a peer that lists it accepts data-carrying envelopes (artifact_chunk, artifact_push) as a WS binary frame — 2-byte header length + JSON header + raw bytes — instead of the JSON/base64 form. A sender checks it before choosing the encoding, so mixed-version links keep working.

View Source
const CapCoordination = "child-coordination-v1"
View Source
const CapObjectives = "objective-policy-v1"
View Source
const CapSessionAEAD = "sessaead"

CapSessionAEAD is the hello capability that negotiates per-connection frame encryption (design §16). When both sides advertise it and the mesh has a shared secret, every application frame after the hello exchange is AEAD-sealed under a key derived from the secret and BOTH hello nonces — so an on-path observer who only relays the handshake never learns the session key, and replaying a captured hello does not reproduce it either (the nonces are fresh per dial).

Negotiation is capability-based, never a version parse: a peer without this cap keeps the legacy plaintext path, which the cleartext policy still gates. A relay that strips the cap to force plaintext downgrade only steers the link back into that policy — on non-safe networks the connection is refused rather than silently downgraded (fail closed).

View Source
const DirRowMaxBytes = 16 * 1024

DirRowMaxBytes bounds one gossiped row. The capability summary inside is the variable-sized member; a generous-but-finite ceiling keeps a crafted blob from eating the whole dir_rows budget in one entry.

View Source
const ExecutionProtocolVersion = 1
View Source
const MaxContextDataBytes = 2 << 20 // 2 MiB

MaxContextDataBytes bounds one inline context snapshot — whether it travels as ContextAckPayload.Data or TaskDelegatePayload.ContextData. A snapshot is bounded by the packing side's context store (entry cap, not byte cap), so a peer that let its store grow could ship a blob whose base64 encoding pushes the frame past readLimit: the message would send fine and the receiver's read limit would close the connection instead of delivering it. The cap sits under what a 4 MiB frame can base64-hold so a single context message still lands.

View Source
const MaxHelloAge = 5 * time.Minute

MaxHelloAge bounds how old a hello may be. It is the replay window: a captured hello's timestamp ages out of it, so the hello cannot be replayed indefinitely. It is generous enough to tolerate P2P clock skew while still expiring stale captures. Exported so the receiver can bound its replay cache by the same window that governs freshness.

View Source
const MaxProjectPackBytes = 1 << 20

MaxProjectPackBytes bounds the inline project pack. Project memory is capped at a few thousand characters and a skill is a Markdown file, so a real pack is kilobytes; the cap is what keeps a project directory that has accumulated something unexpected (a stray binary) from being pushed through every delegation. Over the cap the pack is dropped and the delegation proceeds without it — the task still runs, with less context, which is strictly better than a message that cannot be sent.

View Source
const PunchMaxTTL = 8

PunchMaxTTL bounds the relays a punch coordination envelope may take. The mesh's own relay bound is 3; punch adds headroom because coordination is cheap and a failed punch costs a real reachability path.

View Source
const TransitMaxTTL = 6

TransitMaxTTL bounds how many relay hops a transit frame may spend. Six matches the design's relay budget: long enough for a re-forwarded path through a sparse graph, short enough that a loop dies quickly on top of the msg-id dedup that kills the two-hop case outright.

View Source
const UDPMaxDatagram = 1400

UDPMaxDatagram is the largest datagram this plane emits: 1400 bytes stays inside a conservative path MTU on both v4 and v6 (tunnels, PPPoE) so the sender never has to learn fragmentation. A caller whose envelope does not fit falls back to the WS track or parks the message in the DTN outbox — datagrams are for signaling and small control traffic, not artifacts.

Variables

View Source
var ErrDatagramTooBig = errors.New("udp: envelope exceeds datagram bound")

ErrDatagramTooBig is returned when an envelope cannot fit inside one datagram; the sender should use the WS track or store-and-forward instead.

Functions

func AcceptMsgBytes added in v0.0.11

func AcceptMsgBytes(taskID, attemptID, nodeID string, ts int64) []byte

AcceptMsgBytes constructs the canonical byte slice a task's executor signs in its task_accept: the acceptance binds the task, the attempt it claimed and its own node id, so a relay echoing the frame cannot transplant the acceptance onto a different attempt or signer.

func ArtifactGrantMsg added in v0.0.9

func ArtifactGrantMsg(planID, consumerTaskID, producerTaskID, hash string) []byte

ArtifactGrantMsg constructs the canonical byte slice the plan orchestrator signs to let a stage's executor pull an input artifact straight from the node that produced it (direct stage handoff). Binding the plan, the consuming task, the producing task and the content hash means a grant cannot be transplanted to another fetch: it attests exactly "in this plan, this consumer may pull this hash from this producer's task".

func AuthMsgBytes added in v0.0.9

func AuthMsgBytes(taskID string, authorized bool, ts int64) []byte

AuthMsgBytes constructs the canonical byte slice for a signed Tier-2 authorization grant. This v1 form binds only the task id — it approves a NAME, not a task, and a relay that rewrites the payload between origin and executor keeps the grant valid. New signatures use AuthMsgBytesV2; v1 is retained only to verify grants minted by pre-digest peers.

func AuthMsgBytesV2 added in v0.0.10

func AuthMsgBytesV2(taskID string, authorized bool, ts int64, digest string) []byte

AuthMsgBytesV2 extends the grant with the payload's ConsentDigest, so the signature attests "this task id, in this exact content form, approved at this time". A relay that edits any intent-bearing field in transit invalidates the grant; edits the consent does not cover (chain, budgets) stay unsigned by design because relays may legitimately rewrite them.

func BeaconMsgBytes added in v0.0.11

func BeaconMsgBytes(id, addr, ver, pub string, ts int64) []byte

BeaconMsgBytes constructs the canonical byte slice a LAN-discovery beacon signs: everything the datagram asserts, so a verified signature proves the broadcaster controls the advertised key AND chose this id/address itself. The beacon is still only a hint — the signature's job is narrower: stop a LAN peer from broadcasting a victim's fingerprint next to its own address.

func CanonicalDirRowBytes added in v0.1.0

func CanonicalDirRowBytes(r *DirRow) []byte

CanonicalDirRowBytes returns the full-field serialization — the byte string stored as a row's gossip-layer copy and forwarded in dir_rows, signature and seen_at included. The stored bytes are always THIS form so the hash a peer recomputes from them equals the hash stamped at mint time.

func DirDigestFromStamps added in v0.1.0

func DirDigestFromStamps(stamps map[string]string) string

DirDigestFromStamps folds a stamp table (id → content_hash hex) into the single heartbeat digest. The input set IS the definition — both sides of a compare must build it with the same row filter (gossipable, session rows excluded) or the digests never meet.

func DirRowContentHash added in v0.1.0

func DirRowContentHash(r *DirRow) []byte

DirRowContentHash is the change-detection digest the stamp table and dir_digest compare (M1 §2): SHA-256 over the canonical row minus seen_at and sig. Freshness churn (a re-minted seen_at) leaves the hash untouched, so two peers holding the same CONTENT agree even when their copies were signed at different instants.

func DirRowContentHashHex added in v0.1.0

func DirRowContentHashHex(r *DirRow) string

DirRowContentHashHex is ContentHash as the lowercase hex the stamp table and pull payload carry.

func EID added in v0.0.9

func EID(nodeID string) string

EID builds the endpoint id form used on the DTN plane ("panda://node-id").

func GenerateNodeKey added in v0.0.9

func GenerateNodeKey() (ed25519.PublicKey, ed25519.PrivateKey, error)

GenerateNodeKey creates a new Ed25519 keypair for cryptographic per-node identity.

func GenerateX25519 added in v0.1.0

func GenerateX25519() (*ecdh.PrivateKey, error)

X25519 identity keys are the second half of the dual-key node identity (cross-network mesh design §3): Ed25519 signs, X25519 agrees keys — one key, one job. The private half persists in the settings table next to the Ed25519 key (core.nodeKeyPair); the public half rides the hello as x_pub and lands in the directory for transit sealing.

func HelloMsgBytes added in v0.0.9

func HelloMsgBytes(nodeID string, ts int64, nonce string) []byte

HelloMsgBytes constructs the canonical byte slice signed for a hello handshake.

func HelloSig deprecated

func HelloSig(secret, nodeID string, ts int64) string

Deprecated: use HelloSigN. Ts has second granularity, so two dials inside the same second mint the same signature — and the receiver's single-use replay cache cannot tell an honest same-second reconnect from a replay. HelloSigN binds a per-dial nonce so every hello is unique; the old form is still accepted by VerifyHello for peers that predate the nonce field.

func HelloSigB added in v0.1.2

func HelloSigB(secret, nodeID, to string, ts int64, nonce string) string

HelloSigB signs a hello for one named receiver. A capture replayed at any other node fails here, because that node's id is not the "to" this signature was minted over.

func HelloSigLegacy added in v0.1.6

func HelloSigLegacy(secret, nodeID string, ts int64) string

HelloSig computes the HMAC-SHA256 (hex) of nodeID and a unix timestamp under the shared secret. Binding the timestamp into the signature means a captured hello is only valid within the receiver's tolerance window, so it cannot be replayed after that window (design §16 / P0-1).

HelloSigLegacy computes the pre-nonce hello HMAC under a name that is not deprecated. Recognising a hello minted by a peer that predates the nonce field is not the same as adopting that format: VerifyHello needs this to stay compatible, and the handshake diagnostics need it to explain a rejection precisely. New call sites must still use HelloSigN or HelloSigB — HelloSig stays deprecated so staticcheck (SA1019) catches exactly the case where someone reaches for the replay-ambiguous form by accident.

func HelloSigN added in v0.0.9

func HelloSigN(secret, nodeID string, ts int64, nonce string) string

HelloSigN is HelloSig with a nonce bound into the signature. The nonce is a per-dial random value the caller carries in HelloPayload.Nonce; two hellos that share a timestamp differ in the nonce, so each gets a unique signature and the replay cache can reject one without collateral on the other.

The signed fields are the DIALER's alone. A hello carrying this signature therefore authenticates the sender to any holder of the secret, and a captured one can be replayed to a third node inside the freshness window — that node's replay cache has never seen it, and the replayer, being a member, can derive the session key from the two nonces. HelloSigB closes that hole by binding the receiver's node id; this form remains for peers that predate the binding.

func KeepaliveTimeout added in v0.0.11

func KeepaliveTimeout() time.Duration

KeepaliveTimeout exposes pongWait for the connection registry: a conn with no inbound proof-of-life for this long is dead even if its socket has not noticed, which is the bound same-id duplicate arbitration uses.

func LoadX25519 added in v0.1.0

func LoadX25519(raw []byte) (*ecdh.PrivateKey, error)

LoadX25519 decodes a stored private key, failing on any byte-shape that is not a canonical X25519 scalar.

func LoadX25519Pub added in v0.1.0

func LoadX25519Pub(raw []byte) (*ecdh.PublicKey, error)

LoadX25519Pub decodes a peer's advertised public key.

func MarshalEnvelope added in v0.1.4

func MarshalEnvelope(env Envelope) ([]byte, error)

MarshalEnvelope is marshalEnvelope for callers outside this package that put a frame on the wire themselves — transit seals the inner envelope's bytes, and an artifact chunk is the one payload big enough that the stock marshal's second compact pass shows up in transfer time.

func PunchSig added in v0.0.9

func PunchSig(secret, nonce, from string, ts int64) string

PunchSig computes the punch frame signature.

func RequiredExecutionProtocol added in v0.1.7

func RequiredExecutionProtocol(spec string) int

RequiredExecutionProtocol reads explicit structured requirements only.

func SessionAEAD added in v0.0.11

func SessionAEAD(secret, dialerID, listenerID, dialerNonce, listenerNonce string) (cipher.AEAD, error)

SessionAEAD derives the per-connection cipher for a negotiated sessaead link. The key is HKDF-SHA256 over the shared secret, bound to the hello exchange by info = domain || dialerID || listenerID || dialerNonce || listenerNonce — direction-aware so both ends derive the identical key regardless of which hello they saw first, and so a key minted for one conn cannot be replayed onto another (nonces are per-dial) or between two different node pairs.

func SignAcceptance added in v0.0.11

func SignAcceptance(privKey ed25519.PrivateKey, taskID, attemptID, nodeID string, ts int64) string

SignAcceptance mints the executor's Ed25519 signature for a task_accept.

func SignArtifactGrant added in v0.0.9

func SignArtifactGrant(privKey ed25519.PrivateKey, planID, consumerTaskID, producerTaskID, hash string) string

SignArtifactGrant mints the orchestrator's Ed25519 grant for a direct stage-to-stage artifact pull.

func SignAuthorization added in v0.0.9

func SignAuthorization(privKey ed25519.PrivateKey, taskID string, authorized bool, ts int64, digest string) string

SignAuthorization signs an approval grant with the approver's private key, creating a tamper-proof cryptographic delegation token. digest is the payload's ConsentDigest at signing time; "" mints the legacy v1 form and should only be used to sign for pre-digest receivers.

func SignBeacon added in v0.0.11

func SignBeacon(privKey ed25519.PrivateKey, id, addr, ver, pub string, ts int64) string

SignBeacon mints the beacon's Ed25519 signature over its asserted fields.

func SignDirRow added in v0.1.0

func SignDirRow(priv ed25519.PrivateKey, r *DirRow)

SignDirRow mints the owner's attestation over the canonical row (seen_at included — a gossiped row's freshness is source-asserted, so a forwarder cannot rewind or fast-forward it). The signature covers the row exactly as DirRowContentHash peers will later re-derive: Sig cleared, struct order fixed. Sets r.Sig; r.PubKey must already hold the matching public key.

func SignHelloEd added in v0.0.9

func SignHelloEd(privKey ed25519.PrivateKey, nodeID string, ts int64, nonce string) string

SignHelloEd signs the hello handshake message using the node's Ed25519 private key.

func SignHelloEdB added in v0.1.2

func SignHelloEdB(privKey ed25519.PrivateKey, nodeID, to string, ts int64, nonce string) string

SignHelloEdB signs a hello for one named receiver — the identity half of the binding HelloSigB provides for the HMAC half. The signed bytes cover both node ids, so a captured hello replayed at a third node cannot be made to verify there even by a member holding the shared secret.

func SignTransitInner added in v0.1.0

func SignTransitInner(priv ed25519.PrivateKey, envJSON []byte) string

SignTransitInner attests the marshalled inner envelope under the sender's Ed25519 identity. The signature is what makes env.From inside a transit mean something: a direct frame's From is bound to the conn it arrived on, but a transit inner arrives on a relay's conn — this signature is the only provenance it carries. Returns hex, matching the hello EdSig form.

func TransitInnerMsg added in v0.1.0

func TransitInnerMsg(envJSON []byte) []byte

TransitInnerMsg is the canonical byte string the sealed inner's Ed25519 attestation covers: the marshalled inner envelope verbatim. Binding the signature to the exact bytes means a relay cannot rewrite From, MsgID or the payload without breaking it — env.From inside a transit is verified content, not a conn-bound claim.

func TransitOpenMesh added in v0.1.0

func TransitOpenMesh(secret, destKey string, blob []byte) ([]byte, error)

TransitOpenMesh reverses TransitSealMesh.

func TransitOpenX25519 added in v0.1.0

func TransitOpenX25519(priv *ecdh.PrivateKey, blob []byte) ([]byte, error)

TransitOpenX25519 reverses TransitSealX25519 under the destination's private key. A malformed blob — short, wrong curve point, failed GCM — fails closed: a relay that tampered learns nothing, and the receiver drops rather than dispatching a guessed plaintext.

func TransitSealMesh added in v0.1.0

func TransitSealMesh(secret, destKey string, plaintext []byte) ([]byte, error)

TransitSealMesh is the member-level fallback seal: AEAD keyed by HKDF over the mesh shared secret with the destination identity bound into info, so a blob minted for one peer cannot be opened under a different dest claim. Every member holds the secret — this is path confidentiality, not end-to-end, and the caller marks it degraded.

func TransitSealX25519 added in v0.1.0

func TransitSealX25519(destPub *ecdh.PublicKey, plaintext []byte) ([]byte, error)

TransitSealX25519 wraps plaintext for destPub with an ephemeral-key ECIES: blob = eph_pub(32) ‖ nonce(12) ‖ AEAD(plaintext). The AEAD key derives from ECDH(eph, destPub) through HKDF bound to BOTH public keys, so the ciphertext authenticates "sealed by someone, for exactly this identity" — and the relay carrying the blob learns nothing a size field and the dest envelope do not already say. An ephemeral sender key keeps sender static material out of the derivation entirely: identity proof for the receiver lives inside the plaintext (the transit inner's Ed25519 signature), not in this channel.

func UDPPairAEAD added in v0.1.1

func UDPPairAEAD(priv *ecdh.PrivateKey, peerPub *ecdh.PublicKey, selfID, peerID string) (cipher.AEAD, error)

UDPPairAEAD derives the datagram-plane AEAD for one peer pair: a static- static X25519 DH between the two identity keys, run through HKDF with both node ids bound in sorted order so the two sides derive the same key regardless of who speaks first.

This is what makes a datagram's From provable. The mesh-wide key every member holds can only prove membership — any member can mint a frame claiming to be any other — so the datagram plane seals to the pair instead. No handshake is needed: each side already publishes its X25519 public key in an Ed25519-signed hello, and a third member watching the exchange learns nothing, because the derivation needs a private key it does not have.

func VerifyAcceptance added in v0.0.11

func VerifyAcceptance(pubKey ed25519.PublicKey, taskID, attemptID, nodeID string, ts int64, sigHex string) bool

VerifyAcceptance checks a task_accept signature against the accepting node's recorded public key.

func VerifyArtifactGrant added in v0.0.9

func VerifyArtifactGrant(pubKey ed25519.PublicKey, planID, consumerTaskID, producerTaskID, hash, sigHex string) bool

VerifyArtifactGrant checks an artifact grant against the public key of the node that claims to have orchestrated the plan.

func VerifyAuthorization added in v0.0.9

func VerifyAuthorization(pubKey ed25519.PublicKey, taskID string, authorized bool, ts int64, digest, sigHex string) bool

VerifyAuthorization verifies that an authorization token was signed by the holder of the given public key. A v2 (digest-bound) grant verifies only against the digest the EXECUTOR computed over the payload it received — transit edits fail closed. A v1 grant has no digest to compare against, so it verifies on the bare tuple (the best a legacy mint can prove).

func VerifyBeaconSig added in v0.0.11

func VerifyBeaconSig(pubKey ed25519.PublicKey, id, addr, ver, pub string, ts int64, sigHex string) bool

VerifyBeaconSig checks a beacon signature against the key the beacon itself advertises — self-signed by design, since discovery predates pairing and no trusted key directory exists yet. Verification proves key control, not mesh membership: what it buys is an unfakeable fingerprint, not admission.

func VerifyDirRow added in v0.1.0

func VerifyDirRow(r *DirRow) bool

VerifyDirRow checks r.Sig against the canonical row under r.PubKey. A row that fails is not "unsigned" — it is corrupt, and callers must drop rather than downgrade it: unsigned rows lose every conflict to signed ones anyway.

func VerifyHello deprecated

func VerifyHello(secret, nodeID string, ts int64, sig string, now time.Time) bool

VerifyHello reports whether sig is the valid HMAC for nodeID and ts under secret, and that ts is within MaxHelloAge of now. An empty secret or empty signature always fails (fail-closed): a node without a shared secret must not authenticate any peer. A stale or future timestamp also fails, so a replayed hello ages out rather than remaining valid forever.

Deprecated: use VerifyHelloP, which also verifies the nonce-bound form. Kept for callers that only know the two-field signature (old peers).

func VerifyHelloEd added in v0.0.9

func VerifyHelloEd(pubKey ed25519.PublicKey, nodeID string, ts int64, nonce string, sigHex string) bool

VerifyHelloEd checks the Ed25519 signature on a hello handshake against the sender's public key.

func VerifyHelloEdB added in v0.1.2

func VerifyHelloEdB(pubKey ed25519.PublicKey, nodeID, to string, ts int64, nonce string, sigHex string) bool

VerifyHelloEdB checks a receiver-bound hello signature against the sender's public key and the receiver it names.

func VerifyHelloP added in v0.0.9

func VerifyHelloP(secret, receiverID string, p HelloPayload, now time.Time) bool

VerifyHelloP verifies a hello the way the receiver does: freshness first, then signatures. Two layers answer two different questions, and BOTH must hold — they are conjunctive, not alternatives:

  • Sig (HMAC under the mesh shared secret) proves mesh MEMBERSHIP. It is always required: the Ed25519 fields are self-asserted, so accepting them alone would let anyone who can reach the listener mint a keypair, claim any node id, and register as a peer — unauthenticated mesh join, and from there task delegation (i.e. remote code execution on this node).
  • PubKey+EdSig (Ed25519 over NodeID:Ts:Nonce) proves control of the identity key a member ADVERTISES. It is optional because pre-key peers send neither field — but a hello that carries identity must carry a coherent pair: a bad or half-present Ed25519 block under a valid HMAC is tampering or corruption, not a legacy peer, and fails closed. The receiver still only records the key after this check, so identity metadata that fails verification never reaches the directory.

receiverID is this node's own id. A hello that names a receiver ("to") must name THIS one and carry the matching bound signature pair (SigB, and EdSigB when it carries identity). Anything else is a hello minted for another node — the shape a cross-node replay takes — and is refused outright. A hello with no "to" is a peer that predates binding or one that could not resolve us by address; it is verified the old way, and the caller decides whether it may still be admitted (see the binding memory in core).

Binding the advertised key to a node-id already known under a different key (the pin check) is the caller's job — this function sees only the wire.

func VerifyPunch added in v0.0.9

func VerifyPunch(secret string, f PunchFrame, now time.Time) bool

VerifyPunch reports whether f is a fresh, correctly-signed punch frame. Fail-closed on empty secret, empty sig, or stale timestamp — same posture as VerifyHelloP. Freshness alone does not make a frame single-use: a captured punch replays cleanly inside MaxHelloAge, so callers gate replays through UDPConn.claimPunch.

func VerifyTransitInner added in v0.1.0

func VerifyTransitInner(pub ed25519.PublicKey, envJSON []byte, sigHex string) bool

VerifyTransitInner checks a transit inner attestation. A short or malformed hex signature fails closed, the same as a bad GCM tag.

Types

type AgentGrantPayload added in v0.0.9

type AgentGrantPayload struct {
	LockID    string `json:"lock_id"`
	GrantedTo string `json:"granted_to"`
	LeaseMS   int64  `json:"lease_ms"`
	Denied    bool   `json:"denied,omitempty"`
	Reason    string `json:"reason,omitempty"`
}

AgentGrantPayload carries lease-based lock authorization or yield acknowledgement (whitepaper §5.2). Denied/Reason make an explicit negative verdict distinguishable from a missing reply — older peers that always grant simply leave them zero.

type AgentNegotiatePayload added in v0.0.9

type AgentNegotiatePayload struct {
	FromNode      string      `json:"from_node"`
	FromAgent     string      `json:"from_agent"`
	Timestamp     int64       `json:"timestamp"`
	Weight        int         `json:"weight"`
	TargetScope   TargetScope `json:"target_scope"`
	Intent        string      `json:"intent"`
	ActionPreview string      `json:"action_preview,omitempty"`
}

AgentNegotiatePayload carries horizontal peer-to-peer conflict negotiation signaling (whitepaper §5.1).

type AgentYieldPayload added in v0.0.9

type AgentYieldPayload struct {
	FromAgent string      `json:"from_agent"`
	Scope     TargetScope `json:"scope"`
	Reason    string      `json:"reason,omitempty"`
}

AgentYieldPayload indicates an agent has halted at an AST checkpoint and ceded execution.

type ArtifactChunkPayload added in v0.0.6

type ArtifactChunkPayload struct {
	TaskID string `json:"task_id"`
	Hash   string `json:"hash"`
	Offset int64  `json:"offset"`
	Data   []byte `json:"data,omitempty"`
	Total  int64  `json:"total,omitempty"`
	EOF    bool   `json:"eof,omitempty"`
	OK     bool   `json:"ok"`
	Reason string `json:"reason,omitempty"`
}

ArtifactChunkPayload answers an artifact_fetch. Data holds at most ArtifactChunkBytes of the packed archive at Offset (base64 on the wire, since it is a []byte). Total is the archive's full size so the requester can show progress and reject a stream that changes length mid-transfer, and EOF marks the last chunk — the point at which the accumulated bytes are hashed against Hash before the artifact is allowed into the pool.

OK is false when the peer does not hold the artifact or refuses to serve it; the requester then asks a different node instead of retrying forever.

type ArtifactFetchPayload added in v0.0.6

type ArtifactFetchPayload struct {
	TaskID string `json:"task_id"`
	Hash   string `json:"hash"`
	Offset int64  `json:"offset"`
	// OfTask/Grant/Issuer ride along when the fetch is a direct stage-to-stage
	// pull: OfTask is the producing task's id as named by the orchestrator's
	// input ref, Grant is the orchestrator-signed authorization, and Issuer is
	// the orchestrator's node id. All three are absent on legacy fetches,
	// which keep the participant-based authorization path.
	OfTask string `json:"of_task,omitempty"`
	Grant  string `json:"grant,omitempty"`
	Issuer string `json:"issuer,omitempty"`
}

ArtifactFetchPayload asks a peer for one chunk of a task artifact, starting at Offset. The requester drives the transfer: it asks for the next offset only after the previous chunk landed, which makes a dropped or corrupt chunk a re-request rather than a failed transfer.

type ArtifactPushDonePayload added in v0.0.9

type ArtifactPushDonePayload struct {
	TaskID string `json:"task_id"`
	Hash   string `json:"hash"`
	OK     bool   `json:"ok"`
	Reason string `json:"reason,omitempty"`
}

ArtifactPushDonePayload ends one push: the staged archive verified against its content hash and entered the receiver's pool (OK), or staging failed and the sender should stop spending bandwidth on it. A receiver that already holds the artifact answers OK immediately, which is also how a sender learns it can retire rows for a peer that finished long ago.

type ArtifactPushPayload added in v0.0.9

type ArtifactPushPayload struct {
	TaskID string `json:"task_id"`
	Hash   string `json:"hash"`
	Offset int64  `json:"offset"`
	Data   []byte `json:"data,omitempty"`
	Total  int64  `json:"total"`
}

ArtifactPushPayload is one proactively-pushed artifact chunk (§8.3 fat-push). It mirrors the pull-side chunk shape minus the answer fields: Offset positions the bytes inside the archive named by Hash, and Total is the archive's full size so the receiver can bound and complete the staged copy. Chunks are sent in order on an ordered lane, but the receiver tolerates duplicates and gaps — its contiguous-progress status reply is the authoritative resume point.

type ArtifactPushStatusPayload added in v0.0.9

type ArtifactPushStatusPayload struct {
	TaskID          string `json:"task_id"`
	Hash            string `json:"hash"`
	ReceivedThrough int64  `json:"received_through"`
}

ArtifactPushStatusPayload is the receiver's custody report: how many contiguous bytes of Hash it holds, counted from offset 0. The sender-side outbox retires rows only as this number covers them, which is what makes a send-then-crash recoverable — an unacknowledged chunk is resent on the next flush rather than leaving a permanent gap in the staged copy.

type ArtifactRef added in v0.0.6

type ArtifactRef struct {
	Stage  string `json:"stage,omitempty"`
	Hash   string `json:"hash"`
	Source string `json:"source"`
	// OfTask names the producing stage's task id on the holder — the row the
	// serving node can actually resolve for authorization. The fetching
	// stage's own id cannot serve that purpose: a producer holds only its own
	// stage's row, never its siblings'.
	OfTask string `json:"of_task,omitempty"`
	// Grant is the orchestrator's Ed25519 signature over
	// (plan, consumer task, producer task, hash): capability proof that this
	// input was legitimately issued, so the producer need not know the
	// consumer's row to serve it. Issuer is the orchestrator's node id, used
	// to look up the signing key in the peer directory.
	Grant  string `json:"grant,omitempty"`
	Issuer string `json:"issuer,omitempty"`
	// Screen marks the referenced artifact as display content (the producing
	// stage drove a screen_sensing actuator). The orchestrator stamps it from
	// the producer's row so every hop downstream — routing, admission, the
	// serving verdict on a node that never saw the producer's row — can bind
	// the bytes to the mesh-only rule. Like the result flag it only narrows
	// an audience: a forged mark shrinks who may hold the input, it cannot
	// widen one.
	Screen bool `json:"screen,omitempty"`
}

ArtifactRef names one artifact and a node known to hold it — the data-plane half of a stage dependency. A hash alone is not enough to fetch: content addressing says what the bytes must be, not who has them. Stage records which plan stage produced it, which is what makes the extraction order of a multi-input stage deterministic across nodes.

type Bundle added in v0.0.9

type Bundle struct {
	BundleID    string // unique id for dedup at relays
	Version     int    // format: 1 = plaintext payload, 2 = sealed, 3 = relative lifetime
	SourceEID   string // "panda://<node-id>"
	DestEID     string
	CreatedUnix int64
	LifetimeSec int64  // seconds after creation the bundle stays live; 0 = no expiry
	Kind        string // the envelope type this bundle carries
	Payload     []byte // wire form: plaintext on v1, nonce||AEAD-ciphertext on v2+
	Signature   []byte // HMAC-SHA256 over fields 1..8, keyed by the mesh secret
	// contains filtered or unexported fields
}

Bundle is the DTN wire unit: Header (EID/TTL) + kind + payload + signature. Fields marshal as a fixed-length CBOR array (toarray semantics) so the layout is schema-pinned — a field cannot drift into a different slot.

func NewBundle added in v0.0.9

func NewBundle(id, srcEID, dstEID, kind string, lifetimeSec int64, payload, secret []byte) (*Bundle, error)

NewBundle wraps kind+payload in a signed, lifetime-bound bundle addressed from srcEID to dstEID. lifetimeSec is seconds of life from creation; 0 disables expiry. secret is the mesh shared key: the signature makes a parked or relayed bundle tamper-evident on media that never authenticates, and the payload is sealed first (encrypt-then-sign) so the signed bytes — not the plaintext — are what custody carries.

func UnmarshalBundle added in v0.0.9

func UnmarshalBundle(data []byte) (*Bundle, error)

UnmarshalBundle decodes a CBOR bundle produced by Marshal. It checks structure only — Verify performs the trust checks.

func (*Bundle) LocalExpiry added in v0.0.9

func (b *Bundle) LocalExpiry(now int64) int64

LocalExpiry returns the local-clock unix time at which custody of this bundle should lapse, or 0 for no expiry. Custody bookkeeping (outbox rows, relay logs) must run on the holding node's own clock — the only clock a parked row can trust — so the origin's lifetime is re-anchored to now and clamped to [1, LifetimeSec]: a skewed origin clock can neither kill a fresh bundle nor stretch local custody past one full lifetime.

func (*Bundle) Marshal added in v0.0.9

func (b *Bundle) Marshal() []byte

Marshal serializes the bundle to canonical CBOR (including the signature).

func (*Bundle) Open added in v0.0.9

func (b *Bundle) Open(secret []byte) ([]byte, error)

Open returns the bundle's plaintext payload. Version-1 bundles carry it directly; version-2 unseals with the header AAD, so a bundle that fails Open is tampered — never delivered. Call after Verify: Open authenticates the payload but says nothing about the signature or TTL.

func (*Bundle) Verify added in v0.0.9

func (b *Bundle) Verify(secret []byte, now int64) error

Verify checks the signature against secret and reports whether the bundle is still within its lifetime. A bundle that fails either check must not be delivered — it is either tampered or dead. All readable versions verify identically (the signature covers the wire payload either way, and UnmarshalBundle has already normalized legacy absolute deadlines into LifetimeSec); Open is what differs.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client dials a peer and returns a connected Conn (after hello exchange is handled by the caller).

func NewClient

func NewClient(url string, logger *slog.Logger) *Client

NewClient creates a client for a ws:// or wss:// endpoint.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context) (*Conn, error)

Dial establishes a connection. Callers should then send hello and start reading.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn wraps one websocket.Conn with a prioritized writer goroutine (the single writer goroutine; reads happen on the caller's side).

func (*Conn) ArmSession added in v0.0.11

func (c *Conn) ArmSession(aead cipher.AEAD)

ArmSession installs the negotiated per-connection cipher; every subsequent application frame is AEAD-sealed on write and opened on read. Called once per conn, after the verified hello exchange.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the underlying socket and fails the writer loop so queued senders unblock with an error instead of waiting forever.

func (*Conn) CloseReason added in v0.0.11

func (c *Conn) CloseReason(code int, reason string)

CloseReason sends a WebSocket close frame carrying a human-readable reason, then closes the socket — the far read loop surfaces it as the close error, so a post-handshake policy refusal is diagnosable instead of a bare EOF that looks like flaky connectivity.

func (*Conn) DialAddr added in v0.0.11

func (c *Conn) DialAddr() string

DialAddr returns the configured outbound address, or "" on inbound conns.

func (*Conn) Encrypted added in v0.0.11

func (c *Conn) Encrypted() bool

Encrypted reports whether this conn carries sealed application frames.

func (*Conn) Live added in v0.0.11

func (c *Conn) Live() bool

Live reports whether this conn is still demonstrably alive: inbound proof-of-life within the keepalive bound. Same-id duplicate sessions use it for arbitration — a live incumbent keeps the peer edge instead of being swapped out every time a sibling process dials.

func (*Conn) LiveWithin added in v0.0.11

func (c *Conn) LiveWithin(d time.Duration) bool

LiveWithin is SeenWithin under a caller-chosen bound: the registry's arbitration window is a Core-level knob (tests shrink it; zero means "never trust the incumbent"), so arbitration consults this form.

func (*Conn) LocalNonce added in v0.0.11

func (c *Conn) LocalNonce() string

LocalNonce returns the hello nonce this side sent.

func (*Conn) MarkOutbound

func (c *Conn) MarkOutbound()

MarkOutbound flags this connection as locally-initiated; Outbound reports it.

func (*Conn) Outbound

func (c *Conn) Outbound() bool

Outbound reports whether this connection was initiated by this side.

func (*Conn) PeerID

func (c *Conn) PeerID() string

PeerID returns the node id bound to this connection by the hello handshake.

func (*Conn) RTT added in v0.0.9

func (c *Conn) RTT() time.Duration

RTT returns the last measured ping/pong round trip on this link, or 0 before the first sample. It is the edge weight the mesh's weighted shortest-path routing consumes (§4.1).

func (*Conn) ReadJSON

func (c *Conn) ReadJSON(v any) error

ReadJSON reads one message into v. Text frames decode as JSON. A binary frame is a data frame (CapBinaryData): 2-byte header length + JSON header + raw body; the header decodes into v and — when v is an *Envelope — the body lands in Envelope.BinaryPayload for the dispatcher to attach to its payload struct. Callers must set a read deadline for a timeout. A successful read is inbound proof-of-life either way, so it refreshes the liveness stamp the same way a received pong does.

func (*Conn) RejectReason added in v0.0.11

func (c *Conn) RejectReason() string

RejectReason returns the hello_reject code the peer sent before closing, or "" when the conn died without a stated reason.

func (*Conn) RemoteAddr added in v0.0.9

func (c *Conn) RemoteAddr() string

RemoteAddr returns the peer's transport address as our socket observed it — the reflexive-IP hint the hello reply hands back so a NAT-bound peer can learn its public address without a STUN server (HelloPayload.You).

func (*Conn) RemoteNonce added in v0.0.11

func (c *Conn) RemoteNonce() string

RemoteNonce returns the first hello nonce the peer presented.

func (*Conn) ResetReadDeadline

func (c *Conn) ResetReadDeadline() error

ResetReadDeadline restores the normal keepalive read deadline (pongWait). Callers should invoke this once a hello handshake succeeds.

func (*Conn) SeenWithin added in v0.0.11

func (c *Conn) SeenWithin(d time.Duration) bool

SeenWithin reports whether the conn produced inbound proof-of-life within the last d. A conn silent longer than that is treated as dead even if its socket has not noticed yet (the half-dead-TCP case, P1-7).

func (*Conn) Send

func (c *Conn) Send(v any) error

Send marshals v to JSON and queues it on its QoS lane — an Envelope's own type picks the lane, so callers get §5.3 priority without any change.

func (*Conn) SendData added in v0.0.11

func (c *Conn) SendData(v any, body []byte) error

SendData writes v as a binary data frame (CapBinaryData): a 2-byte big-endian header length, the JSON header (the envelope marshalled with its bulk field already cleared), then the raw body bytes. It removes the base64 expansion and its codec cost from the data plane — a 1 MiB chunk is ~1 MiB on the wire instead of 1.4, and neither side runs the codec. Callers must only use it when the peer advertised CapBinaryData; a JSON-fallback caller never reaches here.

func (*Conn) SetCaps added in v0.0.11

func (c *Conn) SetCaps(caps []string)

SetCaps records the capabilities the peer advertised in its hello; call it once the hello is verified. Supports reports whether cap was advertised — senders consult it before choosing an encoding old peers would not parse.

func (*Conn) SetDialAddr added in v0.0.11

func (c *Conn) SetDialAddr(addr string)

SetDialAddr records the configured outbound address (pre-resolution) so post-handshake link policy can evaluate the operator's intent — an allow_cleartext_for entry names the configured host, not the socket IP.

func (*Conn) SetLocalNonce added in v0.0.11

func (c *Conn) SetLocalNonce(n string)

SetLocalNonce records the nonce this side sent in its hello (the dial nonce outbound, the reply nonce inbound); the session-key KDF needs it because the nonce never returns to us over the wire.

func (*Conn) SetPeerID

func (c *Conn) SetPeerID(id string)

SetPeerID binds the authenticated node id to this connection (set once, at hello). PeerID returns it, or "" before the handshake completes.

func (*Conn) SetRejectReason added in v0.0.11

func (c *Conn) SetRejectReason(reason string)

SetRejectReason records the hello_reject reason the peer sent us (first write wins — a later frame must not rewrite the verdict). RejectReason returns "" until one arrives.

func (*Conn) SetRemoteNonce added in v0.0.11

func (c *Conn) SetRemoteNonce(n string)

SetRemoteNonce records the peer's hello nonce. First-write-wins: a second hello on an already-bound conn must not silently re-key the session cipher out from under in-flight frames.

func (*Conn) StartPingLoop

func (c *Conn) StartPingLoop(ctx context.Context, period time.Duration)

StartPingLoop sends a ping every period and refreshes the read deadline, keeping the connection alive and letting the peer's pong reset our deadline. It returns when ctx is done. Pings ride the control lane so keepalives are never stuck behind a data backlog. A period <= 0 or one that would outrun pongWait falls back to the package default: pinging slower than the read deadline kills a healthy connection by starvation.

func (*Conn) Supports added in v0.0.11

func (c *Conn) Supports(cap string) bool

type Contact added in v0.0.9

type Contact struct {
	Peer    string `json:"peer"`
	Start   int64  `json:"start"`
	End     int64  `json:"end"`
	RateBps int64  `json:"rate_bps,omitempty"`
	Period  int64  `json:"period,omitempty"`
}

Contact is the wire form of one scheduled transmission window (§8.4), duplicating ledger.Contact's JSON shape for the same decoupling reason as LinkMetric above. [Start, End) is the first window in unix seconds; Period > 0 repeats it.

type ContextAckPayload

type ContextAckPayload struct {
	TaskID string   `json:"task_id"`
	Hash   string   `json:"hash"`
	OK     bool     `json:"ok"`
	Data   []byte   `json:"data,omitempty"`
	Refs   []string `json:"refs,omitempty"`
}

ContextAckPayload is the source node's response to a context_fetch. On OK it carries the full snapshot blob (base64) whose SHA-256 must equal Hash; on failure OK is false and the executor fails the task rather than guessing.

type ContextFetchPayload

type ContextFetchPayload struct {
	TaskID      string `json:"task_id"`
	Hash        string `json:"hash"`
	ContextType string `json:"context_type,omitempty"`
}

ContextFetchPayload asks the source node for a full context snapshot.

type DTNBundlePayload added in v0.0.9

type DTNBundlePayload struct {
	Blob []byte `json:"blob"`
}

DTNBundlePayload carries one CBOR-encoded DTN bundle (§8.3) verbatim. The receiver unmarshals, verifies signature+TTL, then feeds the inner payload back through the normal message path — the bundle is a signed transport container, not a second task protocol.

type DialCheckAckPayload added in v0.1.0

type DialCheckAckPayload struct {
	Nonce string `json:"nonce"`
	OK    bool   `json:"ok"`
	Proto string `json:"proto,omitempty"`
}

DialCheckAckPayload reports what a dial_check actually achieved. Proto is "ws" for the TCP probe (udp arrives with the datagram-plane variant).

type DialCheckPayload added in v0.1.0

type DialCheckPayload struct {
	Addr  string `json:"addr"`
	UDP   int    `json:"udp,omitempty"`
	Nonce string `json:"nonce"`
}

DialCheckPayload asks the receiver to try reaching this node once, so an advertised rendezvous role is proven rather than claimed. Addr is the ws endpoint to dial (host:port); UDP carries the datagram port for a future STUN-bind probe. Nonce correlates the answer with the request.

type DirPullPayload added in v0.1.0

type DirPullPayload struct {
	// Stamps maps directory id → content_hash (hex). Bounded by the sync
	// cap; a requester with more rows sends the prefix and pages with After.
	Stamps map[string]string `json:"stamps"`
	// After resumes a paged reply: only rows with id > After are eligible.
	// A non-empty After marks the pull as a continuation — the 30s per-peer
	// pull limit applies to fresh pulls, not to finishing a sync already
	// underway.
	After string `json:"after,omitempty"`
}

DirPullPayload is the differential-sync request (M1): the requester's own id→content_hash stamp table plus an optional resume cursor for paged replies. The responder diffs it against its own table and answers dir_rows — rows the requester lacks or hashes differently on, plus a want list of the ids the RESPONDER lacks, so a single exchange converges both directions.

type DirRow added in v0.1.0

type DirRow struct {
	ID        string          `json:"id"`
	PubKey    string          `json:"pub,omitempty"`
	XPub      string          `json:"x_pub,omitempty"`
	Ver       string          `json:"ver,omitempty"`
	Card      json.RawMessage `json:"card,omitempty"` // CapabilitySummary JSON
	Addrs     []string        `json:"addrs,omitempty"`
	Neighbors []string        `json:"neighbors,omitempty"`
	Links     []LinkMetric    `json:"links,omitempty"`
	UDPPort   int             `json:"udp_port,omitempty"`
	Relay     json.RawMessage `json:"relay,omitempty"` // RelayProfile JSON
	SeenAt    int64           `json:"seen_at"`
	Sig       string          `json:"sig,omitempty"` // Ed25519 over canonical minus sig
}

DirRow is the canonical row shape for content hashing and signing (M1 §2). content_hash covers every field EXCEPT seen_at and sig — freshness churn must not defeat the digest — while sig signs everything except itself (seen_at included: a gossiped row's age is source-minted, not attacker- rewritable). Field order here IS the canonical serialization order.

func ParseDirRow added in v0.1.0

func ParseDirRow(raw []byte) (*DirRow, error)

ParseDirRow validates a row blob pulled off the wire: JSON shape, sane id, size ceiling enforced by the caller's payload budget. It does NOT check the signature — callers branch on Sig=="" vs VerifyDirRow because unsigned rows remain legal gossip (a direct observation has no signature to forward).

type DirRowsPayload added in v0.1.0

type DirRowsPayload struct {
	Rows []json.RawMessage `json:"rows,omitempty"`
	// Want lists the ids the SENDER of this frame still lacks: the receiver
	// should answer with one dir_rows carrying those rows (and no want of
	// its own — one round completes the exchange).
	Want []string `json:"want,omitempty"`
	// Cursor/More paginate: when the response hit a budget (row count or
	// byte cap) before the last differing id, Cursor is the last id sent and
	// More is true; the requester continues with dir_pull{after: cursor}.
	Cursor string `json:"cursor,omitempty"`
	More   bool   `json:"more,omitempty"`
}

DirRowsPayload carries signed directory rows plus the responder's want list. Rows travel as canonical JSON blobs — each is a credential signed by its owner's Ed25519 key, forwarded byte-for-byte so the signature keeps verifying no matter how many hops it crossed.

type Envelope

type Envelope struct {
	V       int             `json:"v"`
	Type    string          `json:"type"`
	MsgID   string          `json:"msg_id"`
	From    string          `json:"from"`
	To      string          `json:"to,omitempty"`
	TS      int64           `json:"ts"`
	Payload json.RawMessage `json:"payload,omitempty"`
	// BinaryPayload carries the raw body of a binary data frame — the
	// CapBinaryData wire form that lifts a payload's bulk bytes out of the
	// JSON. It is populated by the read path only and never marshals: a
	// re-marshal of the envelope (UDP route, outbox parking) reproduces the
	// JSON form, which is why binary frames are only used on direct conns.
	BinaryPayload []byte `json:"-"`
}

Envelope is the JSON wire format (design doc §10.3). MsgID is a UUIDv7 used for dedup at the receiving end.

func NewEnvelope

func NewEnvelope(typ, from, msgID string, payload any) (Envelope, error)

NewEnvelope builds an envelope. msgID must be non-empty for idempotency.

A payload that carries process output gets a chance to shrink first (wireClamper). The frame limit is this package's own constraint, so honouring it belongs here rather than in every caller: a sender is free to write a frame larger than readLimit, and the cost lands on the receiver, which closes the connection instead of delivering the message. Clamping at the point every message is built means a completed task cannot lose its result — and take the peer link with it — because its log was long.

func (*Envelope) PayloadInto

func (e *Envelope) PayloadInto(v any) error

PayloadInto decodes the envelope payload into v.

type FatBundleArtifact added in v0.0.9

type FatBundleArtifact struct {
	Hash string `json:"hash"`
	Data []byte `json:"data"`
}

FatBundleArtifact carries an inline artifact payload for proactive push-based DTN delivery (whitepaper §8.3).

type HeartbeatPayload

type HeartbeatPayload struct {
	Status   string          `json:"status"`   // online|busy|offline
	Load     float64         `json:"load"`     // 0.0-1.0
	Capacity string          `json:"capacity"` // raw JSON from the card
	Card     json.RawMessage `json:"card,omitempty"`
	// BlockedAgents lists agent names whose circuit is open on the sender
	// (repeated failures). Peers strip these from the sender's ability set
	// when routing, so failure history weighs into candidate selection
	// instead of being learned one bounce-decline at a time. Absent on old
	// nodes and when nothing is blocked; receivers treat absent as "drop
	// any previously published list".
	BlockedAgents []string `json:"blocked_agents,omitempty"`
	// Neighbors/Links refresh the sender's adjacency in the receiver's
	// directory every beat (§4.1): hellos only arrive at dial time and card
	// beats only at reload, but the link-state graph's edge set AND its
	// measured weights have to track the live topology continuously.
	Neighbors []string     `json:"neighbors,omitempty"`
	Links     []LinkMetric `json:"links,omitempty"`
	// Contacts carries the sender's advertised contact plan (§8.4): the
	// scheduled transmission windows custody routing plans custody moves
	// around. Semi-static — it changes on config reload, not per beat — but
	// rides the same gossip channel so a peer's plan arrives without waiting
	// for a card refresh. Deliberately NOT omitempty: a new node always emits
	// the field (empty array = "no plan"), so removing a plan clears the
	// peer directory's copy; a field absent outright is an old node's beat
	// and leaves the stored plan alone.
	Contacts []Contact `json:"contacts"`
	// Projects carries the sender's advertised residence set (§6.3): the
	// names of the projects it holds a checkout of. Semi-static like the
	// contact plan — it changes when work lands, not per beat — and shares
	// the same contract: a new node always emits it (empty = "no projects"),
	// while a field absent outright is an old node's beat and leaves the
	// stored set alone.
	Projects []string `json:"projects"`
	// Ver is the sender's software version (Track 3). Heartbeats repeat the
	// hello's stamp so a mid-release upgrade refreshes every peer's
	// directory row without waiting for a reconnect — that row is what the
	// fleet panel's version-skew warning diffs against its own build.
	// Absent on old nodes; receivers leave any stored stamp alone.
	Ver string `json:"ver,omitempty"`
	// Prov mirrors HelloPayload.Prov on every beat so a mid-life binary
	// swap (update apply, self-build) refreshes the directory row without
	// waiting for a reconnect. Absent on old nodes; receivers leave any
	// stored stamp alone.
	Prov string `json:"prov,omitempty"`
	// DirDigest is the sender's directory table digest (cross-network mesh
	// M1): SHA-256 over the sorted "id:content_hash" lines of every gossipable
	// row (session/ghost rows excluded). A receiver whose own digest differs
	// sends dir_pull — matching digests mean the two tables already agree and
	// no frames flow. Absent on old nodes; receivers skip the compare.
	DirDigest string `json:"dir_digest,omitempty"`
	// EdgeLoad is the sender's live peer-edge count (M2): rendezvous
	// scoring prefers a candidate whose mesh is not already pinned on it —
	// a node carrying forty edges is a worse redundancy pick than one
	// carrying four. Absent on old nodes; receivers treat it as unknown.
	EdgeLoad int `json:"edge_load,omitempty"`
}

HeartbeatPayload carries status + capacity. Card is an optional capability summary (same compact JSON form as HelloPayload.Card) sent when the sender just reloaded its card, so peers learn the new abilities without waiting for a reconnect — heartbeats flow every few seconds, hellos only at dial time. Old nodes that do not know the field ignore it; new nodes that receive it without it fall back to the hello-time card.

type HelloPayload

type HelloPayload struct {
	NodeID string `json:"node_id"`
	Ver    string `json:"ver"`
	// Prov is the sender's build provenance (release | self | unsigned) —
	// the version.ProvenanceClass stamp. Absent means a pre-provenance peer
	// that does not send the field; a current dev build sends "unsigned"
	// explicitly. Self-asserted and outside the signature domain, like Ver:
	// honest-node bookkeeping the receiver's trust policy reads
	// (accept.<tier>.self_signed), never a security proof — the locally
	// asserted tier stays the boundary.
	Prov   string          `json:"prov,omitempty"`
	Card   json.RawMessage `json:"card,omitempty"`
	Ts     int64           `json:"ts,omitempty"`    // unix seconds, bound into Sig
	Nonce  string          `json:"nonce,omitempty"` // per-dial random, bound into Sig when present
	Sig    string          `json:"sig"`
	PubKey string          `json:"pub_key,omitempty"` // Ed25519 public key hex (cryptographic identity)
	EdSig  string          `json:"ed_sig,omitempty"`  // Ed25519 signature over NodeID:Ts:Nonce
	// To names the node this hello is addressed to. When set, the hello is
	// signed for that receiver alone (SigB/EdSigB) and a receiver will refuse
	// it unless the id is its own — the cross-node replay a member could
	// otherwise mount with a captured hello inside the freshness window.
	// Empty means the sender predates binding, or could not resolve the
	// address it dialed to a node id; such a hello is verified the legacy way
	// and SigB/EdSigB carry nothing.
	To     string `json:"to,omitempty"`
	SigB   string `json:"sig_b,omitempty"`    // HMAC over NodeID:To:Ts:Nonce
	EdSigB string `json:"ed_sig_b,omitempty"` // Ed25519 over the same bytes
	// XPub is the node's X25519 identity key (hex) — the second half of the
	// dual-key identity (cross-network mesh design §3): Ed25519 signs,
	// X25519 agrees transit keys. It is self-asserted like UDPPort: only
	// recorded after the hello's EdSig verified the claimed Ed25519 key, and
	// a peer that lies about its own x_pub only breaks sealing TO itself.
	// Peers that predate the field send nothing and transit to them
	// degrades to the member-level mesh seal.
	XPub string `json:"x_pub,omitempty"`
	// UDPPort advertises the sender's datagram-plane listener (farsky). A
	// peer that cannot hold a TCP session to us can still be reached by a
	// punch: combine this port with the IP we observe its connection coming
	// from and the reflexive addresses its punch offer carries. Zero means
	// the node runs no UDP plane; old peers send nothing.
	UDPPort int `json:"udp_port,omitempty"`
	// You is set only on the hello REPLY: the IP this peer's connection
	// arrived from, as our listener observed it. It is free reflexive
	// discovery — a node behind NAT learns its public IP without a STUN
	// server, and punches at <You>:<own UDP port>. Unsigned (the sig covers
	// NodeID/Ts/Nonce only): a tampered You costs the attacker nothing but a
	// wrong candidate list, which the punch handshake detects anyway.
	You string `json:"you,omitempty"`
	// Caps advertises optional wire features this build supports (e.g.
	// binary data frames) so a peer can pick the better encoding without a
	// version-number parse. Absent on old nodes; receivers that do not know
	// a listed capability simply never exercise it.
	Caps []string `json:"caps,omitempty"`
	// Authoritative declares that the sending process holds the node
	// identity lock — the daemon, not a borrowed engine (CLI/TUI sibling
	// that probe-passed at startup). Same-id arbitration uses it to let a
	// real daemon reclaim its peer edge from a sibling session that claimed
	// ownership while the daemon was down: without it, a live stray conn
	// holds the edge indefinitely and delegated work lands on the wrong
	// engine. Unsigned like You — a forged claim is no worse than a forged
	// node id, which the sig already gates.
	Authoritative bool `json:"authoritative,omitempty"`
}

HelloPayload is sent when a node connects to declare its identity. Card is the node's capability summary (a compact JSON object); it is carried as raw JSON so the transport stays decoupled from the ledger package that owns the CapabilitySummary type. Sig is the HMAC-SHA256 (hex) of NodeID, Ts, and — when present — Nonce under the shared secret, proving the identity was minted by a node that holds the secret and bounding replay to MaxHelloAge (design §16 / P0-1). Nonce makes every dial's signature unique even when two hellos land inside the same second: the receiver's single-use replay cache keys on signed fields only, so without it an honest same-second reconnect is indistinguishable from a replay. Old peers send none and are verified against the two-field form.

type HelloRejectPayload added in v0.0.11

type HelloRejectPayload struct {
	Reason string `json:"reason"`
}

HelloRejectPayload is what the server sends before closing a connection whose hello failed. Reason is a stable machine-readable code: "auth" (signature/secret mismatch — the usual case, and the one a dialer must surface so an operator knows the peer is online but rejecting us), "identity" (claimed id collides or re-keys a verified identity), "binding" (the peer has bound its hello before and sent an unbound one — a downgrade, or a rollback to a build without binding), and "replay" (a consumed signature). It deliberately carries nothing derived from the secret — the frame rides the still-unauthenticated channel.

type LinkMetric added in v0.0.9

type LinkMetric struct {
	Peer  string `json:"peer"`
	RTTms int64  `json:"rtt_ms"`
	// Kind names the transport carrying the edge right now ("ws", "udp") —
	// the fleet view's per-peer transport display (Track 3). Empty on nodes
	// that predate the field; their only transport was ws.
	Kind string `json:"kind,omitempty"`
}

LinkMetric is the wire form of one measured edge weight (§4.1): the round- trip time in milliseconds toward a directly connected neighbor, sampled by the transport's ping/pong. It duplicates ledger.LinkMetric's JSON shape so the transport package stays decoupled from the capability directory — the same rule that keeps Card a raw JSON blob above.

type PairHelloPayload added in v0.0.11

type PairHelloPayload struct {
	Session string `json:"session"` // initiator-minted session id (uuid)
	X       string `json:"x"`       // initiator ephemeral X25519 pub, hex
	Pub     string `json:"pub"`     // initiator Ed25519 identity pub, hex (SAS-bound)
	Nonce   string `json:"nonce"`   // initiator nonce, hex — HKDF salt half
	Addr    string `json:"addr"`    // initiator's advertised listen addr (host may be 0.0.0.0)
	Name    string `json:"name"`    // configured node.name, display only
	NodeID  string `json:"node_id"` // runtime node id, display only
	// Target (P4b) asks the receiver to FORWARD this pair_hello to the named
	// stable identity instead of answering it: the receiver is being used as
	// a contact point by a joiner that cannot reach the introducer directly.
	// Absent on every pre-feature frame and on the direct (LAN) path.
	Target string `json:"target,omitempty"`
}

PairHelloPayload opens a Bluetooth-style pairing session on an unauthenticated connection. The initiator is not yet a mesh peer — this frame carries only ephemeral key material and self-describing display fields; nothing in it is trusted until the two humans compare the derived code on both screens.

type PairReadyPayload added in v0.0.11

type PairReadyPayload struct {
	Session string `json:"session"`
	X       string `json:"x"`
	Pub     string `json:"pub"`
	Nonce   string `json:"nonce"`
}

PairReadyPayload answers pair_hello with the responder's ephemeral half. After this frame both sides hold enough material to derive the same short authentication string — a MITM relay produces a different one on each end because its two DH secrets differ.

type PairRejectPayload added in v0.0.11

type PairRejectPayload struct {
	Session string `json:"session"`
	Reason  string `json:"reason"`
}

PairRejectPayload ends a session without joining: human said no, the confirm window expired, or the responder refused. Reason is a stable machine token ("rejected", "expired", "busy") plus optional detail.

type PairSecretPayload added in v0.0.11

type PairSecretPayload struct {
	Session string `json:"session"`
	Box     string `json:"box"`
}

PairSecretPayload delivers the mesh shared secret to the confirmed initiator. Box is base64(gcm-nonce ‖ AES-256-GCM ciphertext) keyed by HKDF(dh, salt=nonces, info="panda-pair/1") — the secret never crosses the LAN readable, and only ever flows responder→initiator.

type PunchFrame added in v0.0.9

type PunchFrame struct {
	Nonce string `json:"n"`
	From  string `json:"f"`
	TS    int64  `json:"t"`
	Sig   string `json:"s"`
}

PunchFrame is the pinhole opener: proof of mesh membership small enough to spray at every candidate endpoint. Sig is HMAC-SHA256 (hex) of "punch|<nonce>|<from>|<ts>" under the mesh secret — the same membership proof a hello carries, bound to a session nonce so a captured frame cannot open a pinhole for a different handshake. TS bounds replay to MaxHelloAge.

type PunchOfferPayload added in v0.0.9

type PunchOfferPayload struct {
	Nonce string   `json:"nonce"`
	Src   string   `json:"src"`   // origin node id — survives relay re-enveloping
	Hosts []string `json:"hosts"` // candidate host:port UDP endpoints
	TTL   int      `json:"ttl"`
}

PunchOfferPayload arranges a UDP pinhole between two NAT-bound nodes (farsky §9.2). It travels as an envelope through the mesh — direct conn when one exists, link-state next-hop relay otherwise — carrying everything the responder needs to start punching: the session nonce (which becomes the pinhole proof inside every punch datagram) and the initiator's candidate endpoints. Hosts mixes every address form the initiator knows: its local interface addresses, the reflexive IP peers have observed for it (HelloPayload.You), and any STUN-discovered mapping — all at its UDP listener port, because the punch is always sprayed FROM the shared socket so the mapping a NAT opens is the listener's.

TTL bounds relay hops. PunchMaxTTL is the starting value; each forwarder decrements it and a spent offer drops, so a routed offer cannot orbit the mesh forever between dedup evictions.

Src is the initiator's node id. It must live in the payload, not the envelope: a relay forwards the envelope as ITSELF (env.From = last hop, like dtn_bundle) because the receiving conn authenticates envelopes by their bound peer id — a relayed envelope that kept the origin's From would trip the conn's spoof check. Receivers read Src, falling back to env.From for a direct (unrelayed) arrival.

type PunchReadyPayload added in v0.0.9

type PunchReadyPayload = PunchOfferPayload

PunchReadyPayload answers an offer: the responder accepts the session and reports its own candidates so both sides can spray at once. Nonce echoes the offer's — the session key both sides already hold.

type PunchWantPayload added in v0.1.0

type PunchWantPayload struct {
	Src string `json:"src,omitempty"`
	TTL int    `json:"ttl"`
}

PunchWantPayload is the auto-punch request (M3): the sender asks the receiver — the lexicographically-smaller, offerer-elected side — to send it a punch_offer. TTL bounds relay hops the same way punch_offer's does.

Src names the REQUESTER and must survive the relay. A relayed envelope is re-minted as the forwarder's (env.From = this node) because the receiving conn authenticates envelopes by their bound peer id — so the requester would otherwise be lost, and the elected offerer would punch the RELAY instead of the node that asked. It rides the payload for the same reason PunchOfferPayload.Src does.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server listens for inbound node connections.

func NewServer

func NewServer(addr string, logger *slog.Logger, onConn func(*Conn)) *Server

NewServer creates a WebSocket server on addr. onConn is invoked once the socket upgrades — the hello handshake that binds a peer identity happens inside it, on the conn's read loop. onConn must block while the connection is alive so the server can accurately enforce connection limits.

func (*Server) Addr added in v0.1.1

func (s *Server) Addr() string

Addr returns the address the listener actually bound to, or the configured address while no listener has bound yet.

It exists for the port-0 case: a caller that asks the kernel for an ephemeral port needs to learn which one it got, and Listen blocks serving, so reading it back afterwards is not an option.

func (*Server) Listen

func (s *Server) Listen(ctx context.Context) error

Listen blocks serving WebSocket requests until ctx is done.

The bind happens here, synchronously, before anything is announced or served. ListenAndServe would do the same bind internally but reports the failure only after the fact, which meant the "websocket listening" line was printed first: a daemon whose port was already held logged that it was listening, then logged the bind failure, and repeated both every retry. The announcement is now true when it is printed, and a bind error comes back to the caller as a return value instead of racing a goroutine.

func (*Server) OnBound added in v0.1.1

func (s *Server) OnBound(fn func(addr string))

OnBound registers a callback invoked once the listener is bound, with the address that was actually bound ("127.0.0.1:0" reports the chosen port).

Unlike Ready, this carries the address to a caller that advertises itself (the Core's listen address feeds hello payloads and discovery beacons). The callback runs on Listen's goroutine before Ready closes and before the accept loop starts, so it must not block — and anything it stores is visible to a caller once Ready fires.

func (*Server) Ready added in v0.1.1

func (s *Server) Ready() <-chan struct{}

Ready is closed once the listener is bound and accepting connections.

A caller that starts Listen in a goroutine must wait on this instead of sleeping a guessed interval: the bind completes whenever the scheduler gets to it, and a fixed sleep is a race on a loaded machine. Callers that also need bind failures must select on this and on their own Listen-error channel — a failed bind never closes Ready.

func (*Server) SetLimits

func (s *Server) SetLimits(maxConns, maxConnsPerIP int)

SetLimits configures the global and per-IP concurrent connection limits. A limit <= 0 means unlimited.

type TargetScope added in v0.0.9

type TargetScope struct {
	Repo   string `json:"repo,omitempty"`
	File   string `json:"file"`
	Symbol string `json:"symbol,omitempty"`
}

TargetScope defines the repository, file, and symbol scope for peer conflict negotiation (whitepaper §5.1).

type TaskAcceptPayload

type TaskAcceptPayload struct {
	TaskID    string `json:"task_id"`
	AttemptID string `json:"attempt_id,omitempty"`
	Sig       string `json:"sig,omitempty"`
	Pub       string `json:"pub,omitempty"`
	Ts        int64  `json:"ts,omitempty"`
}

TaskAcceptPayload confirms acceptance. The Sig/Pub/Ts fields carry the executor's Ed25519 signature over (task, attempt, acceptor, ts) — the bilateral half of the contract the consent grant opens (trust zones): the origin's grant says WHAT may run, the executor's accept says WHO agreed to run it, and a relay forwarding either cannot mint the other's side. Empty fields mark a pre-signature peer; a peer that sends a signature that fails verification has its accept dropped, not degraded.

type TaskActivitiesPayload added in v0.1.7

type TaskActivitiesPayload struct {
	TaskID     string         `json:"task_id"`
	AttemptID  string         `json:"attempt_id"`
	After      int64          `json:"after,omitempty"`
	Cursor     int64          `json:"cursor"`
	More       bool           `json:"more,omitempty"`
	Activities []TaskActivity `json:"activities,omitempty"`
}

type TaskActivity added in v0.1.7

type TaskActivity struct {
	ID       string          `json:"id"`
	Executor string          `json:"executor"`
	Type     string          `json:"type"`
	TS       int64           `json:"ts"`
	Data     json.RawMessage `json:"data"`
}

type TaskActivityFetchPayload added in v0.1.7

type TaskActivityFetchPayload struct {
	TaskID    string `json:"task_id"`
	AttemptID string `json:"attempt_id"`
	After     int64  `json:"after,omitempty"`
}

TaskActivityFetchPayload requests bounded history from the immediate task executor/custodian. Cursor is local to that peer and must not be used as an event identity across relay hops.

type TaskCancelPayload

type TaskCancelPayload struct {
	TaskID string `json:"task_id"`
	Reason string `json:"reason,omitempty"`
	// AttemptID bounds a dispensation-scoped cancel — a lease-expiry or
	// supersede kill order — to the attempt that lapsed: a copy the
	// delegator already moved past it (a newer delegate landed first on a
	// reordered link) must not die with the dispensation it replaced.
	// Empty means tree-scoped: a human cancel/reject kills whatever the
	// row currently is.
	AttemptID string `json:"attempt_id,omitempty"`
}

TaskCancelPayload requests cancellation.

type TaskDeclinePayload

type TaskDeclinePayload struct {
	TaskID string `json:"task_id"`
	Reason string `json:"reason"`
	// ReasonCode is the optional machine-stable refusal vocabulary above —
	// empty for every refusal that predates the trust zones (drain, capacity,
	// chain loop), which is itself meaningful: reroute handles them alike.
	ReasonCode string `json:"reason_code,omitempty"`
	// AttemptID is the dispensation declining — a refusal from a superseded
	// attempt arriving after a re-route must not bounce the fresh copy back
	// to queued. Empty is legacy (pre-fence peers) and always processes.
	AttemptID string `json:"attempt_id,omitempty"`
}

TaskDeclinePayload rejects with a reason.

type TaskDelegatePayload

type TaskDelegatePayload struct {
	TaskID       string   `json:"task_id"`
	ParentID     string   `json:"parent_id,omitempty"`
	Project      string   `json:"project,omitempty"`
	Title        string   `json:"title,omitempty"`
	ContextType  string   `json:"context_type,omitempty"`
	ContextHash  string   `json:"context_hash,omitempty"`
	ContextLevel string   `json:"context_level,omitempty"` // pointer|summary|full
	ContextData  []byte   `json:"context_data,omitempty"`  // inline full snapshot
	Intent       string   `json:"intent"`
	SpecJSON     string   `json:"spec_json,omitempty"`
	Requires     []string `json:"requires,omitempty"`
	// Paths is the child's declared project scope — the subtrees it owns
	// inside a shared worktree. It rides the wire so the receiving node
	// derives the same scope leaf locks the origin used: same-node siblings
	// with disjoint claims parallelize, overlapping ones serialize, and an
	// empty claim keeps the whole-project lock on every hop.
	Paths []string `json:"paths,omitempty"`
	// Isolate gives the child a private copy of the project tree on the
	// executing node (git worktree when available) instead of the shared
	// one; the child locks nothing shared and its changes merge back into
	// that node's project tree when it finishes. Carried so every hop and
	// requeue preserves the mode the origin's agent chose.
	Isolate       bool   `json:"isolate,omitempty"`
	PreferredNode string `json:"preferred_node,omitempty"` // soft routing hint; honored when it matches
	// TargetNode is the hard pin: the receiving node executes when the pin
	// resolves to itself, forwards toward it when it resolves onward, and
	// declines honestly when it resolves nowhere. It is the resolved row id
	// by the time it leaves the origin, so every hop reads the same identity.
	TargetNode      string   `json:"target_node,omitempty"`
	Chain           []string `json:"chain"`
	TimeoutMS       int64    `json:"timeout_ms,omitempty"`
	MaxRetries      int      `json:"max_retries,omitempty"`
	Complexity      float64  `json:"complexity,omitempty"`
	Risk            string   `json:"risk,omitempty"`
	AttemptID       string   `json:"attempt_id,omitempty"`
	ResumeSessionID string   `json:"resume_session_id,omitempty"`
	// ResumeSessionAdapter names the adapter file that minted
	// ResumeSessionID; the executor drops the hint when the run lands on a
	// different adapter rather than feeding it a foreign handle. It stays
	// OUT of ConsentDigest: it is routing provenance, not consent — and
	// keeping it unbound lets a mixed-version mesh verify a delegate frame
	// whose sender did not yet emit the field.
	ResumeSessionAdapter string `json:"resume_session_adapter,omitempty"`
	// ResourceJSON is the task's declared hardware requirement (a marshalled
	// entry.ResourceProfile). It travels with the delegation because the
	// requirement is a property of the work, not of the node that first saw it:
	// a relay that re-routes a task onward must be able to keep a training run
	// off a node with no VRAM, and without this field the constraint would be
	// lost at the first hop.
	ResourceJSON string `json:"resource_json,omitempty"`
	// Authorized carries the origin user's tier-2 consent (design §16) so a
	// delegated task does not bounce at the executor's defense layer. It is
	// only meaningful on an authenticated bus: the transport's shared-secret
	// HMAC is what makes this unforgeable by non-peers, and the origin node
	// only sets it after the user explicitly authorized (task add
	// --authorize / ask --authorize).
	Authorized bool   `json:"authorized,omitempty"`
	AuthSig    string `json:"auth_sig,omitempty"` // Ed25519 signature over TaskID:Authorized:TS (tamper-proof approval)
	AuthPub    string `json:"auth_pub,omitempty"` // Ed25519 public key hex of the authorizing node
	AuthTs     int64  `json:"auth_ts,omitempty"`  // unix seconds the consent was minted, bound into AuthSig
	// AuthHops bounds how far Authorized may travel (hop-limited consent):
	// each relay decrements it before forwarding onward, and a payload whose
	// hops are spent has its consent cleared, so the executor's defense layer
	// asks for fresh approval instead of running irreversible work under a
	// consent minted several nodes away. Zero alongside Authorized means
	// "legacy/unlimited" — senders from before this field never set it, and
	// the network's behavior for them is unchanged. New senders always set
	// it; direct re-dispatches (decline re-route, queue forward) use 1.
	AuthHops int `json:"auth_hops,omitempty"`
	// Plan-plane fields (v0.0.6). A delegated stage carries its place in the
	// plan and the artifacts it consumes: PlanID/StageID identify it for the
	// orchestrator's audit trail, and Inputs names each predecessor's packed
	// output plus a node that holds it, so the executor can pull the tree it
	// must start from. Empty on a standalone task.
	PlanID  string        `json:"plan_id,omitempty"`
	StageID string        `json:"stage_id,omitempty"`
	Inputs  []ArtifactRef `json:"inputs,omitempty"`

	// Project plane (v0.0.8). A task that belongs to a project used to travel as
	// a bare project *name*, which meant nothing on the receiving machine: the
	// executor looked the name up in its own empty projects directory, found no
	// memory and no tree, and ran an agent that could not tell what it was
	// working on. These two fields are what make the name mean something.
	//
	// ProjectPack is the project's own directory — its MEMORY.md and any
	// project-scoped skills — packed as a tar.gz and carried inline. It is
	// bounded (MaxProjectPackBytes) because it rides in the message rather than
	// being fetched: project memory is capped at a few thousand characters by
	// design, so inline is cheaper than a round trip.
	//
	// The project's *work tree* does not travel here. It goes through the
	// artifact plane as an entry in Inputs, which already knows how to move a
	// tree in chunks and how to skip the transfer when the receiver holds the
	// hash already.
	//
	// ProjectDir is the origin's path for the tree. It is display and log
	// material only — a path from another machine names nothing here, and the
	// executor derives its own directory (see Core.projectWorkDir).
	ProjectPack []byte `json:"project_pack,omitempty"`
	ProjectDir  string `json:"project_dir,omitempty"`
	// UserLocale carries the origin user's language preference across nodes.
	UserLocale string `json:"user_locale,omitempty"`
	// BundledArtifacts carries self-contained input artifacts for proactive push (whitepaper §8.3).
	BundledArtifacts []FatBundleArtifact `json:"bundled_artifacts,omitempty"`
	// Transport specifies whether the delegation travels via live streaming or DTN ("live" or "dtn").
	Transport string `json:"transport,omitempty"`
	// DeadlineUnix is the absolute task deadline for DTN tasks (§8.2): past
	// it the task is expired rather than lease-killed, because a
	// store-and-forward path has no heartbeat to renew against. It is the
	// origin's wall-clock intent carried inside the sealed payload — the
	// bundle that wraps it converts the same bound to a relative lifetime
	// (Bundle.LifetimeSec) for custody decisions at relays.
	DeadlineUnix int64 `json:"deadline_unix,omitempty"`
	// Causal-depth and budget fields (§6.1). Depth is Parent.Depth+1 at every
	// spawn hop, hard-capped by scheduler.MaxChainDepth. DelegationBudget is
	// the remaining mesh-wide delegation quota: each forward decrements it,
	// and a task that reaches zero may only execute or decline — never route
	// onward. The pointer distinguishes an absent field (a pre-budget peer —
	// the receiver seeds the default) from an explicit zero (a new-protocol
	// peer reporting the quota spent — the task must not route onward).
	// TokenBudget is the remaining LLM token quota the task may
	// consume across the mesh; zero means unbounded (legacy peers).
	Depth            int   `json:"depth,omitempty"`
	DelegationBudget *int  `json:"delegation_budget,omitempty"`
	TokenBudget      int64 `json:"token_budget,omitempty"`
	// MaxDepth advertises the effective delegation.max_depth the sender
	// enforced for this subtree — its own config tightened by whatever its
	// ancestors carried. The receiver clamps min(its own config, this value)
	// and persists the result, so the strictest bound any hop's operator set
	// governs the whole subtree. Zero = legacy sender: the receiver's own
	// config alone applies.
	MaxDepth int `json:"max_depth,omitempty"`
}

TaskDelegatePayload is the task handoff (design doc §10.3 example). The context transfer fields (design doc §12.4) select how the executor obtains the task's full context:

  • context_level "pointer": context_hash references a snapshot the executor may already have; on miss it fetches from the source node.
  • context_level "summary": the intent/spec carried on the wire is the whole context (no snapshot transfer).
  • context_level "full": context_data carries the inline snapshot (base64).

func (TaskDelegatePayload) ConsentDigest added in v0.0.10

func (p TaskDelegatePayload) ConsentDigest() string

ConsentDigest is the content hash a tier-2 consent grant binds to (the digest leg of AuthMsgBytesV2). It covers the fields that decide WHAT the task is — identity, intent, spec, requirements, inputs, project material — but deliberately not HOW it travels: the delegation chain, spent budgets, lease stamps and the fat-bundle cache are legitimately rewritten by relays in transit, and binding them would break consent on honest routes. The fat bundle's Data bytes are content-addressed against Inputs/ContextHash (which ARE bound), so excluding BundledArtifacts loses nothing to tampering.

The whitelist struct is load-bearing: new payload fields must not silently change the digest, because a digest mismatch across versions drops consent mid-mesh (fail closed, but needlessly).

The clamp mirrors clampForWire exactly: the signer computes this digest before marshal and the verifier after unmarshal, so the digest must cover what actually crossed the wire — clamped-off inline blobs are nil on both sides.

func (*TaskDelegatePayload) TitleOrDefault

func (p *TaskDelegatePayload) TitleOrDefault() string

TitleOrDefault returns the explicit title, falling back to the intent.

type TaskMessagePayload added in v0.0.11

type TaskMessagePayload struct {
	Scope       string `json:"scope"`
	Sender      string `json:"sender"`                 // sender task_id
	To          string `json:"to,omitempty"`           // unresolved address (member → owner leg)
	Rcpt        string `json:"rcpt,omitempty"`         // resolved recipient task id ("" = broadcast)
	Member      string `json:"member,omitempty"`       // member this fan-out copy is for (receiver-side check)
	Src         string `json:"src,omitempty"`          // origin node id — survives relay re-enveloping
	SenderLabel string `json:"sender_label,omitempty"` // stage id or title, owner-resolved
	Grade       string `json:"grade"`                  // status | report | artifact_ref
	Body        string `json:"body"`
	Seq         int64  `json:"seq"` // sender's monotone slot seq
	SentAt      int64  `json:"sent_at"`
	Fanout      bool   `json:"fanout,omitempty"` // owner → member copy marker
	TTL         int    `json:"ttl,omitempty"`    // remaining relay hops — one spent per forward
}

TaskMessagePayload is one sibling-board post on the wire. The member→owner leg carries To (the unresolved address the sender wrote — "stage:build", "parent", "siblings", or a member task id); the owner's fan-out copies carry Rcpt (the resolved member task id) and Fanout=true instead, so a replica can tell "store this slot" from "resolve and forward".

Src is the node the post originates from — the posting member on the member→owner leg, the scope owner on fan-out copies. It lives in the payload for the same reason punch keeps Src there: relays re-mint the envelope as themselves (env.From = last hop, or the receiving conn's bound-peer check kills the link), so the origin identity can only survive inside. Receivers bind Src against what their own rows know — the owner expects a member-leg frame to ARRIVE along the member's dispatch path (env.From = the first dispatch hop), and a replica expects Src to name the scope owner its member row's chain root records.

TTL bounds relay hops; each forwarder spends one and a spent copy drops, so a routed post cannot orbit the mesh between dedup evictions. A zero TTL is a pre-TTL peer: the first forwarder grants the standard budget.

type TaskProgressPayload added in v0.0.6

type TaskProgressPayload struct {
	TaskID    string `json:"task_id"`
	AttemptID string `json:"attempt_id,omitempty"`
	Note      string `json:"note,omitempty"`
	// ActivityCursor advertises durable display history at the sender. Peers
	// that understand it pull missing rows; legacy peers keep showing Note.
	ActivityCursor int64 `json:"activity_cursor,omitempty"`
}

TaskProgressPayload is a liveness beat from the node executing a task to the node that delegated it. The executor sends one per lease-renewal tick; each receiver refreshes the lease on its own copy of the task and relays the beat one hop further up the chain, so a stage that legitimately runs for an hour is never mistaken for a dead executor anywhere along the delegation path. Note is an optional human-readable status line.

type TaskResultPayload

type TaskResultPayload struct {
	TaskID    string `json:"task_id"`
	AttemptID string `json:"attempt_id"`
	// Chain echoes the executor's delegation chain (root → executor) so a
	// receiver that lost its local row (a restart between dispatch and
	// result) can reconstruct the real upstream path instead of guessing
	// [self, sender] — without it the relayed result stops one hop short of
	// the root. Empty for nodes that predate the field; receivers fall back
	// to the guess then.
	Chain []string `json:"chain,omitempty"`
	// State is the executor's persisted task state at the time it reports.
	// It is optional for wire compatibility with older nodes; when absent the
	// receiver derives done/failed from OK. New nodes must preserve review so a
	// supervisor that did not accept the work cannot be promoted to done by a
	// parent node.
	State string `json:"state,omitempty"`
	// ApprovalDisposition tells the delegator what approving a review means.
	// It is optional for wire compatibility; receivers classify legacy review
	// results conservatively from explicit authorization-refusal evidence only.
	ApprovalDisposition string `json:"approval_disposition,omitempty"`
	// Preserve completion evidence across the wire. Without these fields a
	// delegator could approve work the executor explicitly left unfinished.
	NeedsFollowup bool   `json:"needs_followup,omitempty"`
	Verdict       string `json:"verdict,omitempty"`
	VerdictReason string `json:"verdict_reason,omitempty"`
	Followup      string `json:"followup,omitempty"`
	// Independent acceptance evidence must survive relay, reconnect and approval.
	ObjectiveAssessments []objectives.Assessment `json:"objective_assessments,omitempty"`
	// Deferred marks a result that reports custody, not execution: the
	// caller's request (a resume approval) was accepted and parked in an
	// outbox for delivery when the executor's link returns. Surfaces must
	// render it as "queued for delivery" — not as a failed exit code.
	Deferred  bool    `json:"deferred,omitempty"`
	OK        bool    `json:"ok"`
	ExitCode  int     `json:"exit_code"`
	Stdout    string  `json:"stdout,omitempty"`
	Stderr    string  `json:"stderr,omitempty"`
	Artifacts string  `json:"artifacts,omitempty"`
	Tokens    int     `json:"tokens,omitempty"`
	Cost      float64 `json:"cost,omitempty"`
	// OutputArtifact is the hash of the tree this stage produced, packed into the
	// executor's artifact pool. The node orchestrating the plan records it and
	// hands it to the successor stages as their input; the executor stays the
	// node that holds the bytes until someone pulls them.
	OutputArtifact string `json:"output_artifact,omitempty"`
	// ScreenOutput marks the output as display content (the run drove a
	// screen_sensing actuator). Every hop that adopts the result stamps its
	// own task row, so artifact_fetch can apply the mesh-only rule even for
	// operator-defined actuator ids the requires/spec predicates cannot
	// name. It can only ever make a task MORE restricted on the wire — a
	// forged flag shrinks an audience, it cannot widen one.
	ScreenOutput bool `json:"screen_output,omitempty"`
	// FilesChanged lists the workdir-relative paths the run added, removed or
	// modified — the result's footprint, so the delegator sees what the task
	// actually touched rather than trusting the agent's prose. Capped for the
	// wire (maxFilesChangedReport); absent/empty for non-agent plans and
	// executors from before the field.
	FilesChanged []string `json:"files_changed,omitempty"`
	// FilesTruncated marks a footprint diffed over a workdir too large to
	// snapshot fully (the walk stopped at the file cap, so the list covers
	// only the deterministic lexical prefix). Consumers should read it as
	// "partial evidence", not "nothing changed" — the work itself may sit
	// past the boundary.
	FilesTruncated bool `json:"files_truncated,omitempty"`
	// Question carries the clarification an agent parked on (PANDA_QUESTION):
	// the review state travels with it so the origin's task display can show
	// what the executor is asking, and a task_resume.answer replies to it.
	Question string `json:"question,omitempty"`
	// QuestionSpec is the structured form of a parked question (an
	// entry.ClarifySpec document) when the agent offered bounded options.
	// Question stays the plain-text summary for surfaces without a card.
	QuestionSpec string `json:"question_spec,omitempty"`
	// Structured attribution so the origin can consume a cross-device result
	// like an ordinary sub-agent's: who ran it (Executor — the node, stable
	// across relay hops where env.From is only the last hop), which agent
	// actually executed (Agent — the fallback chain may have swapped it),
	// and how long the execution took on the executor's clock.
	Executor       string `json:"executor,omitempty"`
	ActivityCursor int64  `json:"activity_cursor,omitempty"`
	// WorkDir is the workspace the executor actually ran in — the derived
	// directory, not the submitter's pin — so the origin can locate the
	// produced files on the machine that ran the work.
	WorkDir  string `json:"work_dir,omitempty"`
	Agent    string `json:"agent,omitempty"`
	Model    string `json:"model,omitempty"`
	Injected bool   `json:"injected,omitempty"`
	// Verified and Verification carry the delivery-contract verdict. Verified
	// is true only when every selected check ran and passed; Verification is
	// the status word (verified|failed|partial|skipped) and is empty when the
	// task carried no contract. A done task without Verified is exactly what a
	// surface must not present as an unqualified success.
	Verified     bool   `json:"verified,omitempty"`
	Verification string `json:"verification,omitempty"`
	// NoRetry marks a verdict a blind re-run cannot improve: the work ran to
	// completion and failed its contract, so the orchestrator's retry budget
	// must not re-execute the same task and pay for the same result. The row
	// stays failed; the caller or a human decides what happens next.
	NoRetry        bool   `json:"no_retry,omitempty"`
	DurationMS     int64  `json:"duration_ms,omitempty"`
	SessionID      string `json:"session_id,omitempty"`
	AgentSessionID string `json:"agent_session_id,omitempty"`
	// AgentSessionAdapter names the adapter file that minted
	// AgentSessionID; the delegator stores it so a later re-dispatch only
	// offers the handle back to a run that can consume it.
	AgentSessionAdapter string `json:"agent_session_adapter,omitempty"`
}

TaskResultPayload is the completion result.

type TaskResumePayload added in v0.0.7

type TaskResumePayload struct {
	TaskID    string `json:"task_id"`
	AttemptID string `json:"attempt_id,omitempty"`
	// Answer carries the user's reply to a clarification question the
	// executor parked on (Q4): a review parked on PANDA_QUESTION resumes
	// with the answer folded into the re-run's intent. Empty for the
	// classic tier-2 consent resume — older nodes ignore the field.
	Answer string `json:"answer,omitempty"`
	// Accept closes the parked copy instead of re-running it: the human on
	// one side accepted work that already ran (AcceptWork disposition), and
	// this tells the copy parked on the other side to mirror the decision
	// (review -> done). Without it, whichever side approved first left the
	// other's copy in review forever. An accept carries no consent to run
	// anything — it only ever closes a finished copy — so the receiving
	// side refuses it for any other disposition. Older nodes ignore the
	// field and stay parked; their own human can still approve locally.
	Accept bool `json:"accept,omitempty"`
}

TaskResumePayload carries an approved re-run across the wire: the delegator's user consented to the tier-2 (irreversible) work the executor refused to run unauthorized, and the re-run happens on the executor — the node whose capability match routed the task there in the first place. AttemptID bounds the resume to the attempt the delegator's copy still carries, so a task that was transferred or re-dispatched in the meantime ignores a stale resume.

type TransitPayload added in v0.1.0

type TransitPayload struct {
	Dest  string `json:"dest"`  // stable "k:<pub>" identity or instance id
	TTL   int    `json:"ttl"`   // decremented per relay; <=1 dies at the next relay
	Seal  string `json:"seal"`  // SealX25519 | SealMesh
	Inner []byte `json:"inner"` // sealed transitInner blob
}

TransitPayload is the outer shell of a transit frame (cross-network mesh design M3/§3). A relay reads ONLY this: where the frame is headed, how many hops it has left, which seal level wraps the body, and the sealed body itself. Inner is the AEAD blob (nonce‖ciphertext, plus the ephemeral key prefix under the x25519 level) carrying a transitInner — the original envelope plus the sender's Ed25519 attestation binding env.From to its identity. The blob never rides plaintext; relays are blind by design.

type UDPConn added in v0.0.9

type UDPConn struct {
	OnEnvelope func(env Envelope, src *net.UDPAddr)
	OnPunch    func(f PunchFrame, src *net.UDPAddr, isAck bool)
	// OnKeepalive fires on a successfully unsealed keepalive datagram. The
	// frame carries no identity — the AEAD open proves only mesh membership —
	// so callers must match src against a known endpoint rather than trusting
	// it standalone.
	OnKeepalive func(src *net.UDPAddr)
	// contains filtered or unexported fields
}

UDPConn is a bound UDP socket carrying sealed envelopes and punch frames. The callbacks are wired by the core: OnEnvelope gets an authenticated, decrypted envelope whose From is proven by the AEAD key; OnPunch gets a verified punch frame; OnSTUN is left nil in production (the socket answers binding requests itself) and exists for tests.

func ListenUDP added in v0.0.9

func ListenUDP(addr, secret string, logger *slog.Logger) (*UDPConn, error)

ListenUDP binds addr (e.g. ":7836") and returns a plane ready to ReadLoop. The AEAD key is derived from the mesh secret under a domain separator so a datagram key is never the same bytes as the hello HMAC key.

func (*UDPConn) Close added in v0.0.9

func (u *UDPConn) Close() error

Close shuts the socket; an in-flight ReadLoop exits on the read error.

func (*UDPConn) LocalAddr added in v0.0.9

func (u *UDPConn) LocalAddr() *net.UDPAddr

LocalAddr returns the socket's bound address (tests use it to learn the ephemeral port they were given).

func (*UDPConn) ReadLoop added in v0.0.9

func (u *UDPConn) ReadLoop(ctx context.Context)

ReadLoop reads datagrams until ctx is done or the socket closes. Each datagram is classified: STUN traffic goes to the STUN handler, PN frames are dispatched by kind. Malformed or unverifiable input is dropped without a reply — the same fail-closed posture as the WS track's pre-hello gate.

func (*UDPConn) STUNBinding added in v0.0.9

func (u *UDPConn) STUNBinding(ctx context.Context, server string) (*net.UDPAddr, error)

STUNBinding asks server (host:port) for our reflexive address on this socket. It uses the shared socket — never a fresh one — because the whole point is the mapping the socket's outbound packets create.

func (*UDPConn) SendEnvelope added in v0.0.9

func (u *UDPConn) SendEnvelope(env Envelope, to *net.UDPAddr, peer string) error

SendEnvelope seals env into one datagram addressed to to, under the pair key shared with peer. peer is the datagram's RECIPIENT, which is not the envelope's destination whenever a hop forwards the frame: a relay seals to the key it shares with the next hop, because that is the node that has to open the datagram. Sealing to env.To instead would leave the hop unable to read the frame it is meant to relay, so the recipient is passed explicitly. An empty peer, or a peer that published no identity key, falls back to the mesh key. Oversize frames are refused rather than fragmented — see UDPMaxDatagram.

func (*UDPConn) SendKeepalive added in v0.0.9

func (u *UDPConn) SendKeepalive(peer string, to *net.UDPAddr) error

SendKeepalive emits a sealed empty datagram — proof-of-life that refreshes the NAT mapping without carrying a message. peer names the far end so the frame seals to the pair like everything else on the plane.

func (*UDPConn) SendPunch added in v0.0.9

func (u *UDPConn) SendPunch(f PunchFrame, to *net.UDPAddr, isAck bool) error

SendPunch writes an unsigned-size punch frame (its own HMAC is the auth). isAck selects the ack kind so the receiver can distinguish an opener from the path-confirmation reply.

func (*UDPConn) SetKeySource added in v0.1.1

func (u *UDPConn) SetKeySource(src UDPKeySource, selfID string)

SetKeySource installs the per-pair key source and this node's own id — the id a sealed frame carries as its sender selector. Call it before the read loop starts.

type UDPKeySource added in v0.1.1

type UDPKeySource interface {
	// PairKey returns the AEAD shared with peer. False means the peer
	// published no identity key: unknown, or a build that predates them.
	PairKey(peer string) (cipher.AEAD, bool)
	// PeerAtAddr names the peer whose confirmed endpoint is src.
	PeerAtAddr(src *net.UDPAddr) (string, bool)
}

UDPKeySource supplies the per-pair datagram keys and the address-to-peer map the receiver needs to refuse a legacy frame from an address that belongs to a peer able to seal to the pair. A nil source keeps the plane on the mesh key alone, which only proves membership — the behaviour every build before this one had, and the only thing available toward a peer that never published an identity key.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL