Skip to content

Latest commit

 

History

History
592 lines (497 loc) · 35.9 KB

architecture.md

File metadata and controls

592 lines (497 loc) · 35.9 KB

Architecture

Overview

shard-proxy receives BSV transaction frames (BRC-12, BRC-124, BRC-128, or BRC-134), bare header-stripped transactions, and BRC-148/149 BEEF objects (submission records or FrameVer 0x09) over UDP (and optionally TCP), derives a deterministic multicast group address from each transaction's txid (the TopicID on the BEEF plane; a fixed control-plane group for BRC-134 anchors), then retransmits the original bytes verbatim to all configured egress interfaces. An already-coalesced BRC-142 bundle arriving over UDP is relayed verbatim to the group in its header. Block (BRC-131) and subtree-data (BRC-132) frames never enter through the public ingress: those sockets are transaction-class and drop them (bsp_privileged_frame_rejected_total). They originate from the privileged BRC-143/144 push lanes (-subtree-listen-port / -block-listen-port), which reframe push objects into BRC-132/BRC-131 before the same forwarder pipeline routes them to the control groups.

BRC wire formats live in bsv-multicast/docs/.

tx sender ──UDP/TCP (8725)──────►  shard-proxy  ──UDP multicast──►  FF05::B:<shard>  (data plane, configurable scope)
BEEF ─(8725, or 8728 lane)──────►  (forwarder pipeline) ├────────►  FF05::B:1<xxx>   (BRC-148 BEEF plane, IDX 0x1000 + shard(TopicID))
miner ──push lanes (8726/8727)──►                       ├────────►  FF05::B:FFFE     (GroupBlockBroadcast, BRC-131/134, at the configured scope)
                                                        ├────────►  FF05::B:FFFB     (GroupSubtreeDataAnnounce, BRC-132)
                                                        └────────►  FF05::B:FFFC     (GroupSubtreeGroupAnnounce, BRC-127)

Shard Address Derivation

groupIndex = (txid[0:4] as uint32 BE) >> (32 - shardBits)        // 16-bit max
IPv6 group = [FF0X:0:0:0:0:0:GroupID:groupIndex]                  // X = scope nibble
                                                                  // GroupID = 0x000B (IANA Bitcoin)

The top bits of the first four bytes of the txid are used as the group key. Using top bits rather than modulo gives consistent-hashing: when shardBits increases by 1, every existing group splits into exactly two child groups. Subscribers join additional groups; existing subscriptions remain valid.

The scope nibble X is derived from (source-mode, scope) via shard.Prefix():

Mode Site scope (intra-domain) Global scope (inter-domain)
ASM FF05::B:idx (default) rejected (RFC 8815)
SSM FF35::B:idx FF3E::B:idx

-source-mode=ssm switches every data-plane group to the FF3x::/32 range (RFC 4607). The egress socket is bound to -bind-source (a distinct IPv6 per replica) so SSM receivers can pre-declare this proxy in their (S,G) join calls; anycast / ECMP-shared sources break PIM-SSM RPF. See the Source-Specific Multicast design for fabric prerequisites (PIM-SSM, MLDv2, raised mld_max_msf).

Control Groups

BRC-131 and BRC-132 frames are routed to fixed control-plane multicast groups rather than shard-derived data-plane groups. The reserved indices (top of the 16-bit space, far above the BRC-129 shard zone 0x0000–0x0FFF) are defined in shard-common/shard/control.go:

Constant Index Canonical Address (group-id 0x000B) Purpose
GroupBlockHeader 0xFFFA egress-scope FF0X::<egress-gid>:FFFA Block header egress channel (BRC-135), emitted by shard-listener's header egress; the proxy never sends on it
GroupSubtreeDataAnnounce 0xFFFB FF05::B:FFFB (data-plane scope) BRC-132 subtree data frames
GroupSubtreeGroupAnnounce 0xFFFC FF05::B:FFFC (data-plane scope) BRC-127 subtree group announcements
GroupBeacon 0xFFFD FF05::B:FFFD (site) / FF0E::B:FFFD (global) ADVERT beacon (BRC-126 discovery) + BRC-139 shard manifests
GroupBlockBroadcast 0xFFFE FF05::B:FFFE (data-plane scope; FF0E::B:FFFE when deployed global) BRC-131 block control + BRC-133 coinbase (deprecated) + BRC-134 anchor frames

BRC-129 names global scope (FF0E) as the deployment posture for GroupBlockBroadcast, because block headers, the coinbase (inline in the block frame), and anchor transactions must reach every subscriber across organizational boundaries. The implementation derives the address from the configured -scope like every other control group: a site-scoped deployment emits FF05::B:FFFE, and an inter-domain one sets -scope global.

Per BRC-129 zoning, shard group indices are bounded to 0x0000–0x0FFF, so -shard-bits is at most 12 for conformant deployments (the flag validator enforces [1, 12]) and user shard indices never overlap the control groups (0xFFFA–0xFFFE).

BRC-131 Block Control Frames (FrameVerV4)

BRC-131 frames do not arrive via the public UDP/TCP ingress: those sockets are transaction-class, and DispatchClass drops version byte 0x04 frames there (counted in bsp_privileged_frame_rejected_total). They originate from the privileged block push lane (-block-listen-port, standard 8727): objingress reframes each BRC-144 push object into a BRC-131 frame and dispatches it as privileged, routing to Forwarder.ProcessBlock.

ProcessBlock:

  • Validates via frame.DecodeBlock.
  • With -require-block-pow (default on), drops a BlockAnnounce whose in-frame header fails the proof-of-work check, before the ingress dedup claim. See configuration.
  • When the incoming SeqNum is zero, stamps HashKey as XXH64(senderIPv6 ∥ 0xFFFE ∥ zeros) and SeqNum as a monotonic per-flow counter. A nonzero SeqNum is kept; HashKey is then stamped only when it is zero, or always with -stamp-source.
  • Forwards the raw bytes verbatim to GroupBlockBroadcast (FF0X::B:FFFE) on all egress interfaces.
  • If the payload exceeds the BRC-130 fragment threshold, calls fragmentBlock() instead. Each fragment carries OrigFrameVer=0x04 so listeners route the reassembled payload to their block processing path.

Two MsgType values are defined (byte 7 of the header):

MsgType Value Payload
BlockAnnounce 0x01 A BRC-144 block object, carried verbatim (the 80-byte block header comes first)
CoinbaseTx 0x02 Raw serialized coinbase transaction. Deprecated (BRC-133): the push lane never produces it, since the coinbase travels inline in the BRC-144 body; the listener's default-on block-control gate drops one (coinbase_legacy). Retained and reserved so a future design could carry blocks and their coinbase separately on the fabric and recombine them at the edges

BRC-132 Subtree Data Frames (FrameVerV5)

BRC-132 frames (version byte 0x05) are likewise dropped on the public transaction-class ingress. They originate from the privileged subtree push lane (-subtree-listen-port, standard 8726): objingress reframes each BRC-143 push object into a BRC-132 frame and dispatches it as privileged, routing to Forwarder.ProcessSubtreeData.

ProcessSubtreeData:

  • Validates via frame.DecodeSubtreeData.
  • With -verify-subtree-root (default on), recomputes the merkle root from the node hashes and drops the frame if it differs from SubtreeID, before the ingress dedup claim. See configuration.
  • Stamps HashKey as XXH64(senderIPv6 ∥ 0xFFFB ∥ subtreeID) and SeqNum as a monotonic per-flow counter. The flow key incorporates subtreeID so each distinct subtree is sequenced independently.
  • Forwards the raw bytes to GroupSubtreeDataAnnounce (FF0X::B:FFFB) on all egress interfaces.
  • If the payload exceeds the BRC-130 fragment threshold, calls fragmentSubtreeData(). Each fragment carries OrigFrameVer=0x05 and preserves the MsgType byte (offset 7).

Two MsgType values are defined:

MsgType Value Payload
HashesOnly 0x01 32 bytes per subtree node (SHA256 hash only)
FullNodes 0x02 48 bytes per subtree node (hash + fee + size metadata)

BRC-134 Chained Anchor Transaction Frames (FrameVerV6)

BRC-134 frames may arrive via UDP or TCP ingress; version byte 0x06. Anchor transactions are the root of a chain of dependent transactions and must reach every subscriber regardless of which shard their TxID would otherwise hash to. UDP workers and handleConn both reach Forwarder.ProcessAnchor through DispatchClass.

ProcessAnchor:

  • Validates via frame.DecodeAnchor.
  • Stamps as ProcessBlock does, with HashKey as XXH64(senderIPv6 ∥ 0xFFF9 ∥ zeros). The virtual index 0xFFF9 gives anchor frames an independent flow identity from BRC-131 block frames.
  • Forwards the raw bytes verbatim to GroupBlockBroadcast (FF0X::B:FFFE) on all egress interfaces.
  • No BRC-130 fragmentation (anchor transactions are expected to be small).

BRC-142 Bundle (FrameVerV8)

BRC-142 is the inverse of BRC-130 fragmentation: it packs many small BRC-124/BRC-128 transactions of one (sender, group, subtree) flow into a single bundle datagram (FrameVer 0x08, 66-byte header) to cut egress packets-per-second. It is opt-in via -coalesce (off by default). The wire format is decoded by shard-common/bundle (not frame.Decode, which returns ErrBadVer for 0x08); it is specified in bsv-multicast/docs/brc-142-coalescing-frame.md (codec summary: shard-common docs/protocol.md § 3a) and is not restated here.

Within-batch origin coalescing. Coalescing is bounded to a single receive batch: a UDP worker's recvmmsg batch (so -recv-batch must be above 1), or on the TCP lane the frames one connection has buffered (up to 64, flushed before any read that would block, or once a read sits idle for the linger when a build sets one). As a worker dispatches a batch, eligible transactions are bucketed by their (sender, group, subtree) flow in a per-Egress coalBuffer (forwarder/coalesce.go); member payloads alias the worker's reused receive buffers. At batch end (immediately before Egress.Flush overwrites those buffers), Forwarder.FlushCoalesced packs each bucket into one or more owned bundle datagrams (up to -coalesce-max-bytes, a path-MTU budget with IPv6+UDP headers included, and -coalesce-max-members) and enqueues them. Each bundle draws its HashKey/SeqNum from the same per-flow striped counter (nextSeq) that stamps individual frames, so a flow's bundles interleave contiguously with any individual frames it also emits; a listener gap-tracks the (group, subtree, HashKey) flow uniformly regardless of frame version, and BRC-126 NACK/retry treats a bundle as one "fat frame."

Verbatim spine relay (origin-only rule). Coalescing runs only at the emitting origin: the collapsed / ingress proxy that first sees the individual transactions. A regional spine that relays an already-coalesced bundle takes the Forwarder.ProcessBundle path: it does a cheap structural check (BSV magic + self-consistent PayloadLen), reads the destination GroupIdx from the bundle header (offset 56; a bundle is bound to the single group it was built for, not re-derived from a member TxID), and re-emits the datagram unchanged. A bundle is never re-coalesced, re-stamped, or split in this proxy: one bundle in → one multicast datagram out. Decoalesce (split back to individual frames) and re-bucket (re-align to the receiver's shard generation) happen at the delivery edge (listener), not here.

Multi-CPU Design

Each UDP worker goroutine owns one ingress socket bound via SO_REUSEPORT plus one egress socket per configured interface. The kernel distributes incoming datagrams across all workers with no userspace coordination. Forwarding logic is centralized in the shared forwarder.Forwarder.

Workers process datagrams in batches: each iteration pulls up to -recv-batch ingress packets via ipv6.PacketConn.ReadBatch (one recvmmsg(2) syscall on Linux), dispatches each packet through the forwarder pipeline which enqueues outbound datagrams into a per-worker forwarder.Egress, then flushes that queue via ipv6.PacketConn.WriteBatch (one sendmmsg(2) syscall per egress interface). Per-flow SeqNum counters live in a 64-stripe map keyed on a hash of the sender IP, so concurrent workers contend on independent shards; once a flow's counter exists the increment is lock-free via atomic.AddUint64. A caller that builds a record's datagrams off the dispatching goroutine admits it with Forwarder.AdmitBEEF (the checks, the claim and the flow's SeqNums, reserved in admission order) and fragments it into memory of its own with Forwarder.FragmentBEEFInto, which emits what DispatchBEEF would have. A caller that read the record into a buffer with BEEFFrameHeadroom (92) bytes left ahead of it prepares it with Forwarder.PrepareBEEFFramed, which writes the frame header into that room instead of copying the record into a new frame.

TCP ingress

When -tcp-listen-port is non-zero, a single TCPIngress goroutine accepts connections and dispatches each connection to a per-connection goroutine. TCP and UDP share the same forwarder.Forwarder and egress interfaces; the TCP listener opens its own egress sockets (a pool of up to 8, with connections spread across them) and flushes each connection's egress in batches of up to 64 frames, always before a read that would block. (TCPIngress.SetCoalesceLinger lets a build that arms coalescing keep reading before that flush until a read sits idle for the linger: an idle-read timeout, not a bound on the total wait. This binary sets no linger.)

handleConn reads 44 bytes first (minimum header), then branches on the version byte:

Version byte Frame type Header total Additional read Dispatch
0x01 (BRC-12) Transaction 44 bytes PayLen bytes Process
0x02 (BRC-124/BRC-128) Transaction 92 bytes 48 more + PayLen Process
0x04 (BRC-131) Block control 92 bytes 48 more + PayLen dropped; DispatchClass rejects privileged frames on the transaction-class port
0x05 (BRC-132) Subtree data 92 bytes 48 more + PayLen dropped; DispatchClass rejects privileged frames on the transaction-class port
0x06 (BRC-134) Anchor tx 92 bytes 48 more + PayLen ProcessAnchor
0x09 (BRC-149) BEEF object 92 bytes 48 more + PayLen (bounded by -beef-max-object-bytes) ProcessBEEF
0x30 (MsgType, BRC-127) SubtreeGroupAnnounce 64 bytes 20 more (no payload) ForwardControl

The dispatcher branches on hdrBuf[6]. For BRC-12/124/131/132/134/149 this byte is the Frame Version (0x01/0x02/0x04/0x05/0x06/0x09); for BRC-127 it is the MsgType byte (0x30 = MsgTypeSubtreeGroupAnnounce). Any other version byte (including a BRC-142 bundle, 0x08, which is relayed over UDP only) closes the connection.

The framed table applies only to a connection whose first bytes are the BSV magic. Grammar is detected once per connection: a leading 0xBEEF tag selects a BEEF submission-record stream (objfmt.ClassBEEF reader → SubmitBEEF), and anything else selects a bare-transaction stream (objfmt.ClassTx reader → DispatchBareTx).

senders                       proxy (N UDP workers + 1 TCP listener + push lanes)
───────                       ──────────────────────────────────────────────────
tx_a  ──UDP 8725──▶ [worker 0]  ─▶ forwarder ─▶ FF05::B:3    ──▶ sub_X   (shard, data-plane)
tx_b  ──UDP 8725──▶ [worker 1]  ─▶ forwarder ─▶ FF05::B:1    ──▶ sub_Y
anc_c ──UDP 8725──▶ [worker N]  ─▶ forwarder ─▶ FF05::B:FFFE ──▶ sub_Z   (GroupBlockBroadcast, BRC-134)
beef  ──UDP 8725──▶ [worker 1]  ─▶ SubmitBEEF → 0x09 ─▶ forwarder ─▶ FF05::B:1000 ──▶ sub_V   (BRC-148 BEEF plane, -beef-shard-bits 0)
blk_d ──TCP 8727──▶ [push lane] ─▶ BRC-144 → BRC-131 ─▶ forwarder ─▶ FF05::B:FFFE ──▶ sub_Z   (GroupBlockBroadcast)
sub_e ──TCP 8726──▶ [push lane] ─▶ BRC-143 → BRC-132 ─▶ forwarder ─▶ FF05::B:FFFB ──▶ sub_W   (GroupSubtreeDataAnnounce)
blk_f ──UDP 8725──▶ [worker N]  ─▶ dropped (privileged frame on transaction-class ingress)

Forward rules, TCP framing, and error handling

Wire formats are specified in shard-common docs/protocol.md.

Forward rules

The proxy processes each incoming datagram in two steps:

  1. Decode: parse the frame header (BRC-12 or BRC-124/BRC-128); drop with a debug log on an unsupported version or a truncated datagram. The TxID is extracted to derive the destination multicast group.

  2. Forward: for BRC-124 frames, if SeqNum (raw[48:56]) is non-zero the sender has pre-stamped the frame: it is dropped (stamped_ingress) unless -allow-stamped-ingress is set (see Stamped ingress); an admitted frame keeps its SeqNum, and its HashKey is stamped from the observed source (with -stamp-source=false, only when it is zero). If SeqNum is zero the proxy stamps HashKey at raw[40:48] and SeqNum at raw[48:56] in-place: HashKey = XXH64(senderIPv6 ∥ groupIdx ∥ subtreeID) and SeqNum is the next monotonic counter for that flow. SubtreeID is read from raw[56:88] (zeros if unset). Write the raw bytes to every configured egress interface via IPV6_MULTICAST_IF. BRC-12 frames are forwarded without modification (and rejected under -require-ef).

TCP framing

When -tcp-listen-port is non-zero, the proxy also accepts TCP connections for reliable frame delivery. Grammar is detected once per connection from the leading bytes: the BSV network magic selects a framed stream; a 0xBEEF record tag selects a BEEF submission-record stream (BRC-149 BEEF object frame); anything else is a bare transaction stream. On a framed stream the wire format is identical to UDP: BRC-12, BRC-124, or BRC-128 frames concatenated end-to-end with no additional envelope.

Read sequence per frame (framed stream):

  1. Read 44 bytes (minimum header, sufficient for both BRC-12 and the start of BRC-124/BRC-128).
  2. Inspect FrameVer at byte 6.
    • BRC-12: header is complete; PayLen is at bytes 40–43.
    • BRC-124/BRC-128: read 48 more bytes to complete the 92-byte header; PayLen is at bytes 88–91.
  3. Read exactly PayLen bytes (the payload).
  4. Forward the reassembled raw bytes (HashKey/SeqNum stamped at 40–55 if SeqNum was zero, before processing).

The proxy closes the TCP connection on any protocol violation (bad magic, unsupported version byte, a declared payload length above the 64 MiB stream ceiling or, for a 0x09 frame, above -beef-max-object-bytes, or a read error).

Error handling

Condition UDP TCP
Leading bytes are not the BSV magic parsed as a 0xBEEF submission record or a bare transaction; a malformed one is dropped (bsp_beef_submissions_total{result="malformed"} or bare_tx_malformed) selects the BEEF or bare grammar for the connection
Bad magic inside a framed stream n/a connection closed
Unknown frame version datagram dropped (decode_error) connection closed
Truncated datagram datagram dropped (decode_error) read error → connection closed
Egress write error logged; next interface attempted logged; next interface attempted

Datagram drops are counted in the bsp_packets_dropped_total Prometheus metric with a reason label (e.g. decode_error, write_error, truncated, bundle_malformed, stamped_ingress, ingress_not_ef, beef_oversize); the authoritative reason set is the forwarder package. Class, proof-of-work, subtree-root, dedup and BEEF-record rejections have their own counters; see the Metrics Reference.

Wire Format

Header layouts are specified once, in the bsv-multicast design docs, and are not restated here:

Frame FrameVer Header Layout
BRC-124/BRC-128 transaction 0x02 92 bytes brc-124-frame-format.md (EF payload: brc-128-ef-frame-format.md)
BRC-12 legacy transaction 0x01 44 bytes brc-124-frame-format.md, BRC-12 section
BRC-130 fragment 0x03 104 bytes brc-130-fragmentation.md
BRC-131 block control 0x04 92 bytes brc-131-block-announcements.md
BRC-132 subtree data 0x05 92 bytes brc-132-subtree-data.md
BRC-134 anchor transaction 0x06 92 bytes brc-134-anchor-transactions.md
BRC-142 bundle 0x08 66 bytes brc-142-coalescing-frame.md
BRC-149 BEEF object 0x09 92 bytes brc-149-beef-object-frame.md

Every stamped frame carries HashKey at bytes 40–47 and SeqNum at bytes 48–55. The proxy derives HashKey as XXH64(senderIPv6 ∥ index ∥ 32-byte ingredient) and keeps one SeqNum counter per such flow:

Frame Index Ingredient
BRC-124/BRC-128 transaction, BRC-142 bundle shard group index SubtreeID
BRC-131 block announce 0xFFFE zeros
BRC-132 subtree data 0xFFFB SubtreeID
BRC-134 anchor 0xFFF9 (virtual) zeros
BRC-149 BEEF object BEEF-plane group index (0x1000 + shard) zeros

BRC-130 fragments take the index and ingredient of the frame they were cut from.

BRC-12 frames carry no HashKey, SeqNum, or SubtreeID fields. By default the proxy accepts them and forwards the original bytes unchanged. Under -require-ef (EF-native ingress) legacy BRC-12 is rejected: it carries a raw transaction and the fabric is Extended-Format-only. See Transaction ingress: framed, bare, and EF-native.

Transaction ingress: framed, bare, and EF-native

The transaction ingress port (-udp-listen-port, default 8725) accepts a submission in three shapes, distinguished by the leading bytes:

  • Framed: a BRC-124/BRC-128 (or legacy BRC-12) frame, which begins with the BSV network magic 0xE3E1F3E8. Decoded, dedup-claimed by TxID, stamped, and forwarded: the relay hot path.
  • Bare: a header-stripped transaction (no frame). The magic is absent, so DispatchClass routes it to the bare path, wraps it into an unstamped BRC-124/128 frame, and drives it through the same forward path. One transaction per datagram. No separate raw-tx port is needed: submitters send bare transactions to the same 8725 as framed traffic.
  • BEEF submission record: a leading 0xBEEF record tag (BRC-149). DispatchClass routes it to SubmitBEEF, which carries the record as one stamped FrameVer 0x09 frame at any topic count (see BRC-148 BEEF object plane). BEEF is an open class, so records are admitted on every ingress class.

The magic pre-check is a single uint32 compare in the same cache line as the frame-version byte the router already reads, so the framed relay hot path is byte-identical; the bare branch is cold (submissions only).

EF-native ingress (-require-ef)

Teranode requires Extended Format (EF, the BRC-30 marker 00 00 00 00 00 EF at payload bytes 4–9): a raw transaction (BRC-12) omits each input's funding value and locking script, which the stateless fabric cannot supply (extension needs a UTXO lookup, a wallet/submitter concern). With -require-ef set the ingress is EF-native: a transaction must be EF, or it is rejected:

  • a legacy BRC-12 (44-byte, FrameVerV1) frame,
  • a raw BRC-124 (92-byte, FrameVerV2 without the marker) frame, and
  • a bare non-EF transaction

are dropped (bsp packet-dropped counters reason=ingress_not_ef / bare_tx_not_ef). When -require-ef is off (default) both raw and EF are accepted and forwarded verbatim (legacy contract preserved). The requireEF guard short-circuits to a single predicted branch when off, so there is no measurable hot-path cost either way (forwarder micro-benchmarks: relay and submission both within run-to-run noise of baseline).

Stamped frames are not exempt. A relayed frame was validated at its own ingress, but nothing distinguishes it from a submission whose sender set a non-zero SeqNum; an exemption would make the EF posture opt-out with a one-byte edit. A lane that legitimately carries relayed frames declares itself with -allow-stamped-ingress; every other lane rejects stamped input outright (reason=stamped_ingress). See Stamped ingress.

Because a raw transaction and its extended form share the same TxID (the ID is over the standard serialization), a raw→EF "re-transmit" service on the fabric would collide with ingress TxID dedup; EF must therefore be produced at the wallet, at signing time, where the input UTXOs are already in hand.

Hot Path

The hot path below applies to BRC-12/BRC-124/BRC-128 frames received via UDP:

  1. frame.Decode(raw): extract the TxID; drop on an unknown version or a truncated frame.
  2. Ingress gates, in order: the stamped-ingress gate, -require-ef, -verify-payload-hash, then the ingress TxID dedup claim (BRC-124/BRC-128 only). A frame that fails one is dropped.
  3. HashKey/SeqNum stamp (BRC-124/BRC-128 only): stamp raw[40:48] (HashKey) as XXH64(senderIPv6 ∥ groupIdx ∥ subtreeID) and raw[48:56] (SeqNum) as a monotonic per-flow counter, in-place. A frame admitted with a SeqNum already set (-allow-stamped-ingress) keeps it. BRC-12 frames are always untouched.
  4. Egress.EnqueueData(raw): fan the raw bytes out into the worker's outbound queue, one entry per egress interface.
  5. After every packet in the current receive batch has been processed, Egress.Flush() dispatches one WriteBatch (sendmmsg) per target.

No re-encoding, no per-worker encode buffer. The verbatim path references the receive-batch buffers directly; buffer reuse is safe because Flush completes before the next ReadBatch overwrites the same memory.

BRC-134 anchor frames received via UDP or TCP follow a parallel path through ProcessAnchor. BRC-131 and BRC-132 frames follow the same pattern through ProcessBlock and ProcessSubtreeData, but enter only via the privileged push lanes; the public ingress rejects them. These functions perform the same in-place HashKey/SeqNum stamping (and optional BRC-130 fragmentation for BRC-131/BRC-132), but route to fixed control-plane groups rather than shard-derived addresses.

Graceful Shutdown

Shutdown proceeds in two phases when SIGINT or SIGTERM is received:

  1. Drain: rec.SetDraining() is called immediately, flipping /readyz to 503 so load balancers stop routing new connections. If -drain-timeout is non-zero, the process sleeps for that duration while workers continue forwarding in-flight packets.

  2. Quiesce: the done channel is closed. Each UDP worker and the TCP listener close their ingress sockets, unblocking any pending ReadBatch / Accept calls. Each UDP worker runs a deferred Egress.Flush() so the last receive batch's egress is not lost. Active TCP connections are force-closed so handleConn goroutines do not hang. main flushes the OTLP metric exporter, then waits for all goroutines via sync.WaitGroup before returning.

BRC-139 Manifest Consumer (auto-shard-config)

Off by default; enabled with -manifest-consumer-enabled. When on, the proxy opens a dedicated beacon-receive socket on the beacon group (FFxx::B:FFFD; unlike the listener, the proxy is not otherwise a multicast subscriber), decodes BRC-139 ShardManifest datagrams into the shared shard-common/manifest Registry, and runs the Evaluator on a 1 s tick. Adoption requires ≥ -pilot-quorum distinct Authoritative announcers agreeing for the hysteresis window; manual CLI values always win. -manifest-bootstrap=required is accepted but not implemented: no gate holds data-plane egress back, so the proxy binds with its pinned CLI values either way.

The consumer never moves the running configuration:

  • Pinned values, compared with what runs. -shard-bits, -source-mode and -beef-shard-bits are pinned at their CLI values, and the manifest applier compares the adopted view with that running configuration, never with a zero value. Announcers that agree change nothing; announcers that disagree surface as divergence (multicast_manifest_divergence_total on every tick, a warning when it starts).
  • No self-restart. A restart re-reads the same flags, so it could not apply an announced value: the proxy would come back unchanged, see the same disagreement and, restarting again, loop. To move a proxy to a new value, change the flag and restart it.
  • Bridging (opt-in, -live-resharding). An announced Successor block installs a forwarder.BridgingEngine, so the per-frame fast path dual-emits each transaction to its running group and to its group in the successor's ShardBits layout; listener-side egress dedup absorbs the duplicates. Two paths emit once: a fragmented (BRC-130) transaction goes to the running group only, and a relayed BRC-142 bundle goes only to the group recorded in its header, in its origin's layout (origin-side coalescing pauses while bridging). Every destination uses the running prefix, so a successor that changes the source mode gets no dual emit under its own prefix. Receivers therefore join both layouts, each under its own source mode, for the whole migration, and leave the running one only after every proxy runs the successor's configuration. Dual emit lasts while the Successor block holds quorum; inside that window, restart each proxy with the successor's -shard-bits and, when the successor changes it, -source-mode (plus -bind-source for SSM).

Flag reference and fail-closed rules: configuration.md. System-level design: Automatic Shard Configuration design.

Logging & Tracing

The proxy uses the shared shard-common/logging package: main calls logging.Init once, which installs a process-wide slog default carrying the service.{name,instance.id,version} identity triple (the same tuple the OTLP metrics resource attributes use, so logs and metrics join on shared dimensions). -log-format json emits one JSON object per line on stdout for log aggregation; text (default) is human-readable on stderr. -log-level is runtime-togglable without a restart via POST /loglevel?level=<lvl> on the metrics server and via SIGHUP (toggles debug↔configured level).

At startup the proxy emits a one-shot host.inventory event (OS, CPU, memory, per-NIC facts incl. IPv4+IPv6, multicast sysctls) and mirrors the slim numerics as a bsp_host_info gauge.

Category-8 OS/NIC logs (the kernel conditions metrics show only as counts) are emitted, throttled, at the syscall sites that observe them:

  • forwarder/egress.go: Egress.Flush classifies WriteBatch/sendmmsg errors, logging ENOBUFS (kernel send-buffer / qdisc backpressure) with errno + dropped count, throttled per interface (log-once-then-count).
  • worker/worker.go: warns when the kernel clamps SO_RCVBUF below the requested size (undersized net.core.rmem_max).

Tracing is opt-in (-trace-sampling > 0 with an -otlp-endpoint) and control-plane only; the forwarder receive/send loops take no span. Export is out-of-process via the collector. See the Unified Component Logging.

Package Structure

shard-proxy/
  main.go            entry point; wires config → engine → forwarder → workers
  config/            runtime configuration (flags + env vars + validation)
  forwarder/         decode → zero-copy verbatim forward pipeline;
                     Process (BRC-12/BRC-124/BRC-128), ProcessBlock (BRC-131),
                     ProcessSubtreeData (BRC-132), ProcessAnchor (BRC-134),
                     BRC-130 fragmentation; per-worker Egress batcher with
                     sync.Pool fragment buffers (egress.go); opt-in
                     BridgingEngine dual-emit for live resharding;
                     opt-in BRC-142 coalescing (coalesce.go): within-batch
                     coalBuffer + FlushCoalesced origin packing, ProcessBundle
                     verbatim spine relay; BRC-148/149 BEEF submission-record
                     admission + FrameVer 0x09 process path (beef.go);
                     -retry-tee egress mirror to a co-located retry cache
                     (retrytee.go)
  worker/            per-CPU SO_REUSEPORT UDP ingress loop using recvmmsg
                     (ReadBatch), dispatching each datagram through
                     forwarder.DispatchClass (worker.go); TCP ingress listener
                     with BRC-127 routing (tcp.go); single-class BRC-143/144
                     push lanes and the optional BEEF lane (objingress.go)
  manifest/          opt-in BRC-139 consumer: beacon-receive listener +
                     applier (divergence telemetry, BridgingEngine dual-emit)
  metrics/           OTel + Prometheus instrumentation

Protocol primitives are provided by github.com/lightwebinc/shard-common:

shard-common/
  frame/             BRC-12/BRC-124/BRC-128/BRC-130/BRC-131/BRC-132/BRC-134/
                     BRC-149 wire formats + BRC-127/BRC-139 control datagrams:
                     Decode, Encode, constants
  bundle/            BRC-142 coalescing bundle frame (FrameVer 0x08): Bundle
                     Encode/Decode, Member, MemberOverhead, Coalescer/Decoalesce
  objfmt/            bare/push object codecs (ClassTx/ClassSubtree/ClassBlock/
                     ClassBEEF): stream reader, MulticastBytes reframe, TxID,
                     BEEF submission-record codec, TopicID/ContentID
  shard/             txid → group index → IPv6 multicast address derivation;
                     control group constants, GroupAddr, BRC-148 PlaneEngine
  seqhash/           XXH64 per-flow HashKey computation (senderIPv6 ∥ groupIdx ∥ subtreeID)
  pow/               stateless block-header proof-of-work gate (-require-block-pow)
  cache/, txidset/   modular tier-2 backend + two-tier TxID claim store (ingress dedup)
  netjoin/           IPv6 multicast join helpers (beacon-receive socket)
  manifest/          BRC-139 Registry + Evaluator (auto-shard-config consumer)
  logging/, hostinfo/, tracing/
                     unified slog init, host.inventory, opt-in OTLP tracer