[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FJ0DBS8Y8CCMC1DZ18YV45":3,"skill-same:01M6FJ0DBS8Y8CCMC1DZ18YV45":47},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M6FJ0DBS8Y8CCMC1DZ18YV45","subsystem-summary-of-overlay",null,"ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fstellar\u002Fstellar-core\u002Fsubsystem-summary-of-overlay\u002FSKILL.md",[],[18,19],"summary","subsystem summary of overlay","2026-11-10 10:12:30",false,"# Overlay Subsystem — Technical Summary\n\n## Overview\n\nThe overlay subsystem implements stellar-core's peer-to-peer network layer. It manages TCP connections to other nodes, authenticates peers via ECDH+HMAC, floods broadcast messages (transactions, SCP messages) across the network, fetches missing data (tx sets, quorum sets) via anycast requests, and performs network surveys. The subsystem supports optional background thread processing for I\u002FO-heavy operations (reads\u002Fwrites on TCP sockets) to keep the main thread responsive.\n\n## Key Files\n\n- **OverlayManager.h \u002F OverlayManagerImpl.h\u002F.cpp** — Central manager; owns peer lists, Floodgate, TxDemandsManager, SurveyManager, PeerManager, PeerAuth, PeerDoor.\n- **Peer.h \u002F Peer.cpp** — Abstract base class for a connected peer; handles message dispatch, HMAC auth, flow control, pull-mode adverts.\n- **TCPPeer.h \u002F TCPPeer.cpp** — Concrete `Peer` subclass; async TCP read\u002Fwrite via Asio, framing with RFC5531 record marking.\n- **FlowControl.h \u002F FlowControl.cpp** — Per-peer flow control for flood traffic; outbound queuing with priority and load shedding.\n- **FlowControlCapacity.h \u002F FlowControlCapacity.cpp** — Tracks message-count and byte-count capacity for reading\u002Fwriting flood data.\n- **Floodgate.h \u002F Floodgate.cpp** — Tracks which peers have seen which broadcast messages; ensures each message is sent\u002Freceived at most once per peer.\n- **ItemFetcher.h \u002F ItemFetcher.cpp** — Manages anycast fetch requests for tx sets and quorum sets via Tracker instances.\n- **Tracker.h \u002F Tracker.cpp** — Tracks a single fetch request; tries peers sequentially with timeout-based retries.\n- **TxAdverts.h \u002F TxAdverts.cpp** — Per-peer incoming\u002Foutgoing transaction hash advertisement queues (pull mode).\n- **TxDemandsManager.h \u002F TxDemandsManager.cpp** — Global transaction demand scheduling; issues FLOOD_DEMAND messages based on received adverts.\n- **PeerManager.h \u002F PeerManager.cpp** — Persists peer records (address, type, failure count, next-attempt time) in the database.\n- **PeerDoor.h \u002F PeerDoor.cpp** — Listens on the configured TCP port; accepts incoming connections and hands them to OverlayManager.\n- **PeerAuth.h \u002F PeerAuth.cpp** — ECDH key exchange and HMAC key derivation for peer authentication.\n- **Hmac.h \u002F Hmac.cpp** — Per-peer HMAC state for message authentication (send\u002Frecv MAC keys, sequence numbers).\n- **PeerBareAddress.h \u002F PeerBareAddress.cpp** — Value type for an IPv4 address + port, with DNS resolution.\n- **PeerSharedKeyId.h \u002F PeerSharedKeyId.cpp** — Cache key type for shared ECDH keys (remote public key + role).\n- **RandomPeerSource.h \u002F RandomPeerSource.cpp** — Loads random peers from PeerManager matching a query, with local caching.\n- **BanManager.h \u002F BanManagerImpl.h\u002F.cpp** — Manages a persistent ban list of NodeIDs in the database.\n- **SurveyManager.h \u002F SurveyManager.cpp** — Orchestrates time-sliced overlay network surveys.\n- **SurveyDataManager.h \u002F SurveyDataManager.cpp** — Collects and finalizes per-node and per-peer survey data.\n- **SurveyMessageLimiter.h \u002F SurveyMessageLimiter.cpp** — Rate-limits and deduplicates survey messages.\n- **OverlayMetrics.h \u002F OverlayMetrics.cpp** — Central cache of medida metrics for the overlay (meters, timers, counters).\n- **OverlayUtils.h \u002F OverlayUtils.cpp** — Utility: `logErrorOrThrow` for error handling in overlay code.\n- **StellarXDR.h** — Convenience include aggregating all XDR headers used by overlay.\n\n---\n\n## Key Classes and Data Structures\n\n### `OverlayManager` (abstract interface)\n\nDefines the public API for managing the overlay network. Created via `OverlayManager::create(app)`. Key pure virtual methods:\n- `broadcastMessage(msg, hash)` — Flood a message to all authenticated peers.\n- `recvFloodedMsgID(peer, msgID)` — Record that a peer sent us a flooded message.\n- `recvTransaction(tx, peer, index)` — Process incoming transaction, pass to Herder.\n- `recvTxDemand(dmd, peer)` — Process incoming demand for a transaction.\n- `connectTo(address)` — Initiate outbound connection.\n- `acceptAuthenticatedPeer(peer)` — Promote peer from pending to authenticated.\n- `removePeer(peer)` — Remove a peer in CLOSING state.\n- `clearLedgersBelow(ledgerSeq, lclSeq)` — Purge old Floodgate\u002FItemFetcher data.\n- `start()` \u002F `shutdown()` — Lifecycle control.\n- `checkScheduledAndCache(tracker)` — Deduplicate messages already scheduled for processing.\n- `getOverlayThreadSnapshot()` — Get\u002Fcreate a bucket list snapshot for the overlay background thread.\n\nStatic helpers: `isFloodMessage(msg)`, `createTxBatch()`, `getFlowControlBytesBatch(cfg)`.\n\n### `OverlayManagerImpl` (concrete implementation)\n\nOwns all major overlay components:\n- `mInboundPeers`, `mOutboundPeers` — `PeersList` structs holding pending (vector) and authenticated (map by NodeID) peer collections, plus a `mDropped` set to extend lifetime until background I\u002FO completes.\n- `mFloodGate` (`Floodgate`) — Broadcast deduplication.\n- `mTxDemandsManager` (`TxDemandsManager`) — Pull-mode demand scheduling.\n- `mSurveyManager` (`shared_ptr\u003CSurveyManager>`) — Network survey orchestration.\n- `mPeerManager` (`PeerManager`) — Persistent peer record storage.\n- `mDoor` (`PeerDoor`) — TCP listener.\n- `mAuth` (`PeerAuth`) — Authentication key management.\n- `mOverlayMetrics` (`OverlayMetrics`) — Metrics cache.\n- `mMessageCache` (`RandomEvictionCache\u003Cuint64_t, bool>`) — Deduplicates received messages for metrics.\n- `mScheduledMessages` (`RandomEvictionCache\u003CHash, weak_ptr\u003CCapacityTrackedMessage>>`) — Tracks messages currently scheduled for processing to avoid duplicates.\n- `mPeerSources` (`map\u003CPeerType, unique_ptr\u003CRandomPeerSource>>`) — Peer sources for INBOUND, OUTBOUND, PREFERRED types.\n- `mResolvedPeers` (`future\u003CResolvedPeers>`) — Async DNS resolution result.\n- `mOverlayThreadSnapshot` — Bucket list snapshot for overlay thread use only.\n\nInner struct `PeersList`:\n- `mPending` (`vector\u003CPeer::pointer>`) — Peers that have connected but not yet authenticated.\n- `mAuthenticated` (`map\u003CNodeID, Peer::pointer>`) — Fully authenticated peers.\n- `mDropped` (`unordered_set\u003CPeer::pointer>`) — Dropped peers kept alive until background I\u002FO finishes.\n- Methods: `byAddress()`, `removePeer()`, `moveToAuthenticated()`, `acceptAuthenticatedPeer()`, `shutdown()`.\n\n### `Peer` (abstract base class)\n\nRepresents a single connected peer. Inherits `enable_shared_from_this`. Key state:\n- `mState` — `CONNECTING`, `CONNECTED`, `GOT_HELLO`, `GOT_AUTH`, `CLOSING`. Protected by `mStateMutex` (recursive mutex).\n- `mRole` — `WE_CALLED_REMOTE` or `REMOTE_CALLED_US` (const after construction).\n- `mFlowControl` (`shared_ptr\u003CFlowControl>`) — Per-peer flow control instance.\n- `mTxAdverts` (`shared_ptr\u003CTxAdverts>`) — Per-peer transaction advertisement state.\n- `mHmac` (`Hmac`) — Per-connection HMAC keys and sequence counters.\n- `mPeerMetrics` (`PeerMetrics`) — Atomic counters for per-peer statistics.\n- `mSendNonce` \u002F `mRecvNonce` — Random nonces for key derivation.\n- `mPeerID` (`NodeID`) — Remote node's public key (set during HELLO).\n- `mAddress` (`PeerBareAddress`) — Remote address.\n- `mRecurringTimer` — Fires every 5s for ping, idle timeout, straggler checks.\n- `mDelayedExecutionTimer` — One-shot timer for delayed operations.\n\nKey methods:\n- `sendMessage(msg)` — Enqueue a message for sending. Flood messages go through FlowControl; non-flood messages are sent directly via `sendAuthenticatedMessage()`.\n- `recvRawMessage(tracker)` — Entry point for processing a received message from the background thread. Posts to main thread.\n- `recvMessage(tracker)` — Main-thread message dispatch (called from main). Dispatches to `recvHello`, `recvAuth`, `recvTransaction`, `recvSCPMessage`, `recvFloodAdvert`, `recvFloodDemand`, etc.\n- `beginMessageProcessing(msg)` \u002F `endMessageProcessing(msg)` — Bracket message processing to track flow control capacity. `endMessageProcessing` may send `SEND_MORE_EXTENDED` to request more data.\n- `sendHello()` \u002F `sendAuth()` — Handshake messages.\n- `shutdownAndRemovePeer(reason, direction)` — Set state to CLOSING, remove from OverlayManager.\n- `maybeExecuteInBackground(name, f)` — Post work to overlay thread if background processing is enabled.\n- Pull mode facade: `sendAdvert(hash)`, `sendTxDemand(demands)`, `retryAdvert(hashes)`, `hasAdvert()`, `popAdvert()`.\n- `recurrentTimerExpired()` — Checks idle timeout, straggler timeout, and no-outbound-capacity timeout.\n\n### `CapacityTrackedMessage`\n\nRAII wrapper for a received `StellarMessage`. On construction, calls `Peer::beginMessageProcessing` to lock flow control capacity. On destruction, calls `Peer::endMessageProcessing` to release capacity and potentially send `SEND_MORE`. Also pre-computes BLAKE2 hash for SCP\u002FTX messages and optionally pre-populates signature cache on the overlay thread.\n\nMembers:\n- `mWeakPeer` — Weak reference to the owning Peer.\n- `mMsg` — The StellarMessage.\n- `mMaybeHash` — Optional BLAKE2 hash (for SCP_MESSAGE and TRANSACTION types).\n- `mTxsMap` — Map from hash to pre-constructed `TransactionFrameBasePtr` (with pre-cached hashes).\n\n### `TCPPeer` (concrete Peer subclass)\n\nImplements TCP socket I\u002FO using Asio's `buffered_read_stream`. Key details:\n- `mSocket` (`shared_ptr\u003CSocketType>`) — The Asio TCP socket with 256KB buffer.\n- `ThreadRestrictedVars` — Inner class ensuring write queue, write buffers, and incoming header\u002Fbody vectors are only accessed from the correct thread (overlay thread when background processing is enabled).\n- `mWriteQueue` (`deque\u003CTimestampedMessage>`) — Outgoing message queue.\n- `mDropStarted` (`atomic\u003Cbool>`) — Ensures drop is initiated only once across threads.\n- `mLiveInboundPeersCounter` (`shared_ptr\u003Cint>`) — Shared counter tracking live inbound TCPPeers for load shedding.\n\nStatic factory methods:\n- `initiate(app, address)` — Create outbound connection; resolves address, calls `async_connect`.\n- `accept(app, socket)` — Create from an accepted inbound socket; starts reading immediately.\n\nKey methods:\n- `sendMessage(xdrBytes, msg)` — Enqueues XDR bytes into `mWriteQueue`, calls `messageSender()`.\n- `messageSender()` — Batches queued messages into `mWriteBuffers`, calls `async_write`.\n- `scheduleRead()` \u002F `startRead()` — Initiates async read of 4-byte header, then body.\n- `readHeaderHandler()` \u002F `readBodyHandler()` — Process received data; construct `CapacityTrackedMessage`, call `recvRawMessage`.\n- `writeHandler()` — Completes write, processes sent messages via `FlowControl::processSentMessages`, sends next batch.\n- `drop(reason, direction)` — Atomic drop initiation; shuts down socket, posts cleanup to main thread.\n\n### `FlowControl` (thread-safe)\n\nPer-peer flow control managing both inbound capacity tracking and outbound message queuing. Protected by `mFlowControlMutex`.\n\nKey state:\n- `mFlowControlCapacity` (`FlowControlMessageCapacity`) — Tracks message-count capacity.\n- `mFlowControlBytesCapacity` (`FlowControlByteCapacity`) — Tracks byte-count capacity.\n- `mOutboundQueues` (`FloodQueues\u003CQueuedOutboundMessage>`, array of 4 deques) — Priority-ordered: [0] SCP, [1] transactions, [2] demands, [3] adverts.\n- `mTxQueueByteCount`, `mAdvertQueueTxHashCount`, `mDemandQueueTxHashCount` — Size trackers for load shedding.\n- `mFloodDataProcessed` \u002F `mFloodDataProcessedBytes` — Counters since last SEND_MORE.\n- `mLastThrottle` — Timestamp when reading was last throttled.\n- `mNoOutboundCapacity` — Timestamp when outbound capacity was last exhausted.\n\nKey methods:\n- `addMsgAndMaybeTrimQueue(msg)` — Add flood message to appropriate priority queue; shed oldest transactions if byte limit exceeded; shed excess adverts\u002Fdemands.\n- `getNextBatchToSend()` — Dequeue messages across all priorities while outbound capacity is available; lock capacity for each sent message.\n- `beginMessageProcessing(msg)` — Lock local reading capacity for an incoming message.\n- `endMessageProcessing(msg)` — Release local capacity; return `SendMoreCapacity` indicating how much to request from the peer.\n- `maybeThrottleRead()` — If local capacity is exhausted, mark peer as throttled.\n- `stopThrottling()` — Resume reading from a throttled peer.\n- `processSentMessages(sentMessages)` — After async_write completes, remove sent messages from front of queues and update size trackers.\n- `isSendMoreValid(msg, errorMsg)` — Validate a received SEND_MORE message.\n\n### `FlowControlCapacity` (abstract base)\n\nBase class for capacity tracking. Two subclasses:\n- `FlowControlMessageCapacity` — Tracks by message count. Capacity limits come from config (`PEER_FLOOD_READING_CAPACITY`).\n- `FlowControlByteCapacity` — Tracks by byte count. Limits come from `OverlayManager::getFlowControlBytesTotal()`. Supports `handleTxSizeIncrease()` for protocol upgrades that increase max tx size.\n\nBoth track:\n- `mCapacity.mFloodCapacity` — Local reading capacity for flood messages.\n- `mCapacity.mTotalCapacity` — Optional total capacity (flood + non-flood).\n- `mOutboundCapacity` — How much the remote peer has allowed us to send.\n\n### `Floodgate`\n\nEnsures each broadcast message is sent\u002Freceived at most once per peer. Uses a `FloodRecord` per message hash.\n\nKey state:\n- `mFloodMap` (`map\u003CHash, FloodRecord::pointer>`) — Hash of `StellarMessage` → record of which peers have been told.\n\nKey methods:\n- `addRecord(peer, msgID)` — Record that `peer` sent us message with hash `msgID`. Returns true if new.\n- `broadcast(msg, hash)` — Send message to all authenticated peers that haven't been told. For transactions (pull mode), sends adverts instead of the full message.\n- `clearBelow(maxLedger)` — Remove records for ledgers older than `maxLedger`.\n- `getPeersKnows(msgID)` — Return set of peers that have seen a given message.\n- `forgetRecord(msgID)` — Remove a record (e.g., when tx is rejected).\n\n### `ItemFetcher`\n\nManages fetching of tx sets and quorum sets via anycast. One `ItemFetcher` per item type, each with a configurable `AskPeer` delegate (e.g., `sendGetTxSet` or `sendGetQuorumSet`).\n\nKey state:\n- `mTrackers` (`map\u003CHash, shared_ptr\u003CTracker>>`) — One Tracker per item hash being fetched.\n\nKey methods:\n- `fetch(hash, envelope)` — Start or join fetching of item `hash` needed by SCP `envelope`.\n- `stopFetch(hash, envelope)` — Remove interest from a specific envelope.\n- `recv(hash, timer)` — Item received; cancel tracker, re-process waiting envelopes via Herder.\n- `doesntHave(hash, peer)` — Peer reported DONT_HAVE; try next peer.\n- `stopFetchingBelow(slotIndex, slotToKeep)` — Cleanup old trackers.\n\n### `Tracker`\n\nTracks a single item fetch across multiple peers. Tries peers sequentially with 1.5s timeout per attempt.\n\nKey state:\n- `mPeersAsked` (`map\u003CPeer::pointer, bool>`) — Which peers have been tried.\n- `mWaitingEnvelopes` (`vector\u003Cpair\u003CHash, SCPEnvelope>>`) — Envelopes waiting for this data.\n- `mTimer` — Timeout timer for current fetch attempt.\n- `mNumListRebuild` — Number of times the peer list has been rebuilt (max 20 tries).\n\nKey methods:\n- `tryNextPeer()` — Pick an authenticated peer that hasn't been tried (or rebuild list), send request via `mAskPeer` delegate, start timeout timer.\n- `doesntHave(peer)` — Mark peer and try next.\n- `listen(env)` \u002F `discard(env)` — Add\u002Fremove envelopes from wait list.\n- `cancel()` — Stop timer and fetching.\n\n### `TxAdverts`\n\nPer-peer transaction advertisement management. Handles both incoming adverts (hashes to demand) and outgoing adverts (hashes to advertise).\n\nKey state:\n- `mIncomingTxHashes` (`deque\u003CHash>`) — FIFO queue of hashes received from this peer.\n- `mTxHashesToRetry` (`list\u003CHash>`) — Hashes to retry demanding.\n- `mAdvertHistory` (`RandomEvictionCache\u003CHash, uint32_t>`) — Seen hash cache (50k entries).\n- `mOutgoingTxHashes` (`TxAdvertVector`) — Batch of hashes to advertise to this peer.\n- `mAdvertTimer` — Periodic flush timer.\n- `mSendCb` — Callback to send the advert message.\n\nKey methods:\n- `queueOutgoingAdvert(hash)` — Add hash to outgoing batch; flush if batch is full or timer fires.\n- `queueIncomingAdvert(hashes, seq)` — Deduplicate and enqueue incoming hashes.\n- `popIncomingAdvert()` — Pop next hash (retries first, then incoming queue).\n- `retryIncomingAdvert(list)` — Re-queue hashes for retry after failed demand.\n- `seenAdvert(hash)` — Check if hash was already seen.\n- `clearBelow(ledgerSeq)` — Remove stale advert history entries.\n\n### `TxDemandsManager`\n\nGlobal demand scheduling for pull-mode transactions. Runs on a periodic timer (`FLOOD_DEMAND_PERIOD_MS`, default 200ms).\n\nKey state:\n- `mDemandHistoryMap` (`UnorderedMap\u003CHash, DemandHistory>`) — Tracks per-hash demand history (peers tried, timestamps, retry count).\n- `mPendingDemands` (`queue\u003CHash>`) — FIFO of all demanded hashes for cleanup.\n- `mDemandTimer` — Periodic demand timer.\n\nKey methods:\n- `demand()` — Main demand loop: iterates over authenticated peers with pending adverts, determines demand status per hash (DEMAND \u002F RETRY_LATER \u002F DISCARD), batches demands, sends `FLOOD_DEMAND` messages. Uses linear backoff up to 2s between retries, max 15 retry attempts.\n- `recvTxDemand(dmd, peer)` — Process incoming demand: look up transactions in Herder, send back if available; track metrics for fulfilled\u002Funfulfilled demands.\n- `recordTxPullLatency(hash, peer)` — Record latency from first demand to receipt.\n\n### `PeerManager`\n\nPersists peer records in the database. Each peer record stores: address (IP:port), number of failures, next attempt time, type (inbound\u002Foutbound\u002Fpreferred).\n\nKey methods:\n- `ensureExists(address)` — Insert if not present.\n- `update(address, type, preferredTypeKnown, backOff)` — Update type and\u002For backoff. Type transitions: outbound→preferred (upgrade), preferred→outbound (downgrade only if definitely not preferred).\n- `loadRandomPeers(query, size)` — Load random peers matching criteria from DB.\n- `removePeersWithManyFailures(minFailures)` — Purge dead peers.\n- `getPeersToSend(size, address)` — Select peers to recommend to a requesting peer.\n\n### `PeerDoor`\n\nTCP listener using Asio acceptor. Calls `TCPPeer::accept()` to create inbound peers, then `OverlayManager::maybeAddInboundConnection()` to register them.\n\n### `PeerAuth`\n\nHandles per-connection authentication key derivation:\n- Generates ephemeral Curve25519 keypair on startup.\n- Creates `AuthCert` (signed ephemeral public key with expiration).\n- Derives shared HMAC keys via: `HKDF(ECDH(local_secret, remote_public) || local_pub || remote_pub)`, then per-session send\u002Frecv keys via `HKDF_expand` with nonces.\n- Uses `RandomEvictionCache` for shared key caching.\n\n### `Hmac`\n\nPer-connection HMAC state (thread-safe via mutex):\n- `mSendMacKey` \u002F `mRecvMacKey` — HMAC-SHA256 keys.\n- `mSendMacSeq` \u002F `mRecvMacSeq` — Monotonic sequence numbers preventing replay.\n- `checkAuthenticatedMessage()` — Verify incoming message MAC and sequence.\n- `setAuthenticatedMessageBody()` — Compute and set MAC on outgoing message.\n\n### `SurveyManager`\n\nOrchestrates time-sliced network surveys. Supports two phases: Collecting (gathering data) and Reporting (answering queries).\n\nKey state:\n- `mSurveyDataManager` (`SurveyDataManager`) — Manages collected data.\n- `mMessageLimiter` (`SurveyMessageLimiter`) — Rate-limits survey messages.\n- `mPeersToSurveyQueue` — Queue of nodes to survey.\n- `mRunningSurveyReportingPhase` — Whether in reporting phase.\n- `mCurve25519SecretKey\u002FPublicKey` — Keys for encrypting survey responses.\n\nKey methods:\n- `broadcastStartSurveyCollecting(nonce)` \u002F `broadcastStopSurveyCollecting()` — Start\u002Fstop collecting phase.\n- `startSurveyReporting()` \u002F `stopSurveyReporting()` — Start\u002Fstop reporting phase.\n- `addNodeToRunningSurveyBacklog(node, inIdx, outIdx)` — Queue a node for surveying.\n- `relayOrProcessRequest\u002FResponse(msg, peer)` — Route survey messages.\n- `updateSurveyPhase(...)` — Called from OverlayManager tick to check phase transitions\u002Ftimeouts.\n\n### `SurveyDataManager`\n\nThread-safe data collection for time-sliced surveys.\n\nKey state:\n- `mCollectingNodeData` (`optional\u003CCollectingNodeData>`) — Node-level stats during collecting.\n- `mCollectingInboundPeerData` \u002F `mCollectingOutboundPeerData` (`unordered_map\u003CNodeID, CollectingPeerData>`) — Per-peer stats during collecting.\n- `mFinalNodeData`, `mFinalInboundPeerData`, `mFinalOutboundPeerData` — Finalized data for reporting.\n- `mPhase` — `COLLECTING`, `REPORTING`, or `INACTIVE`.\n\n### `RandomPeerSource`\n\nLoads random peers from PeerManager matching a query. Maintains a local cache that is refreshed from the database when exhausted.\n\n### `BanManager` \u002F `BanManagerImpl`\n\nPersistent ban list stored in the database. Methods: `banNode(id)`, `unbanNode(id)`, `isBanned(id)`, `getBans()`.\n\n### `OverlayMetrics`\n\nCentralized cache of medida metrics for the overlay. Thread-safe (medida is thread-safe). Groups meters\u002Ftimers\u002Fcounters for: message read\u002Fwrite, byte read\u002Fwrite, async I\u002FO, per-message-type recv\u002Fsend timers, connection latency, flow control throttle, outbound queue delays\u002Fdrops, flood bytes (unique\u002Fduplicate), demand\u002Fpull metrics.\n\n---\n\n## Key Control Loops, Threads, and Tasks\n\n### Main Thread (`tick()` loop)\n\n`OverlayManagerImpl::tick()` runs every `PEER_AUTHENTICATION_TIMEOUT + 1` seconds (default 3s):\n1. Cleans up unreferenced dropped peers (use_count == 1).\n2. Checks if DNS resolution future is ready; stores resolved peers, schedules next resolution.\n3. Updates survey phase via `SurveyManager::updateSurveyPhase()`.\n4. Connects to preferred peers (highest priority).\n5. If out of sync, may randomly drop a non-preferred outbound peer.\n6. Connects to outbound peers (from DB).\n7. Attempts to promote inbound peers to outbound.\n\n### Overlay Background Thread\n\nWhen `BACKGROUND_OVERLAY_PROCESSING` is enabled, TCP socket I\u002FO (async_read, async_write) runs on a dedicated overlay thread (`Application::getOverlayIOContext()`). Key operations on overlay thread:\n- `TCPPeer::readHeaderHandler()` \u002F `readBodyHandler()` — Read messages from socket.\n- `TCPPeer::writeHandler()` — Process write completions, call `FlowControl::processSentMessages()`.\n- `TCPPeer::messageSender()` — Batch and send queued messages.\n- `CapacityTrackedMessage` constructor — Pre-parses transactions, optionally verifies signatures in background.\n- `Peer::recvRawMessage()` — Posts received message to main thread for processing.\n\n### Peer Recurrent Timer\n\nEach Peer runs a 5-second recurring timer (`startRecurrentTimer()`) checking:\n- Idle timeout: no read\u002Fwrite for `PEER_TIMEOUT` seconds (authenticated) or `PEER_AUTHENTICATION_TIMEOUT` (pending).\n- Straggler timeout: last write enqueue too old (`PEER_STRAGGLER_TIMEOUT`).\n- Flow control timeout: no outbound capacity for `PEER_SEND_MODE_IDLE_TIMEOUT` (60s).\n\n### Demand Timer\n\n`TxDemandsManager::demand()` fires every `FLOOD_DEMAND_PERIOD_MS` (default 200ms):\n1. Purges obsolete demand history entries.\n2. Iterates over authenticated peers with pending adverts.\n3. For each hash, checks demand status (demand\u002Fretry\u002Fdiscard).\n4. Batches demands up to `getMaxDemandSize()`, sends `FLOOD_DEMAND` to peer.\n5. Handles retry failures by requeueing hashes via `peer->retryAdvert()`.\n\n### Advert Timer\n\nPer-peer `TxAdverts::flushAdvert()` fires after `FLOOD_ADVERT_PERIOD_MS` or when batch is full. Sends accumulated outgoing adverts as a single `FLOOD_ADVERT` message.\n\n### DNS Resolution\n\n`triggerPeerResolution()` resolves `KNOWN_PEERS` and `PREFERRED_PEERS` on a background thread. Results are picked up in `tick()` and stored via `storePeerList()`. Retry with backoff on failure; resolves again every 600s on success.\n\n---\n\n## Ownership Relationships\n\n```\nApplication\n └─ OverlayManagerImpl (unique_ptr)\n     ├─ PeerDoor (value) — TCP acceptor\n     ├─ PeerAuth (value) — authentication key manager\n     ├─ PeerManager (value) — database peer records\n     ├─ Floodgate (value) — broadcast deduplication\n     ├─ TxDemandsManager (value) — demand scheduling\n     ├─ SurveyManager (shared_ptr)\n     │   ├─ SurveyDataManager (value)\n     │   └─ SurveyMessageLimiter (value)\n     ├─ OverlayMetrics (value)\n     ├─ PeersList mInboundPeers (value)\n     │   ├─ mPending: vector\u003CPeer::pointer>\n     │   ├─ mAuthenticated: map\u003CNodeID, Peer::pointer>\n     │   └─ mDropped: unordered_set\u003CPeer::pointer>\n     ├─ PeersList mOutboundPeers (value) — same structure\n     └─ RandomPeerSource[3] (unique_ptr per PeerType)\n\nPeer (shared_ptr, TCPPeer concrete)\n ├─ FlowControl (shared_ptr)\n │   ├─ FlowControlMessageCapacity (value)\n │   └─ FlowControlByteCapacity (value)\n ├─ TxAdverts (shared_ptr)\n ├─ Hmac (value)\n ├─ PeerMetrics (value)\n └─ TCPPeer::SocketType (shared_ptr) — Asio socket\n```\n\n---\n\n## Key Data Flows\n\n### Connection Handshake\n1. Initiator calls `TCPPeer::initiate()` → `async_connect` → `connectHandler` → `sendHello()`.\n2. Responder: `PeerDoor::acceptNextPeer()` → `TCPPeer::accept()` → `maybeAddInboundConnection()` → `startRead()`.\n3. Both sides: `recvHello()` validates version, network ID, addresses → `recvAuth()` sets up HMAC keys via `PeerAuth`, calls `acceptAuthenticatedPeer()` → `moveToAuthenticated()`.\n4. After auth: peers send `SEND_MORE_EXTENDED` to indicate initial reading capacity, exchange peer lists, start adverts.\n\n### Transaction Flooding (Pull Mode)\n1. Herder calls `OverlayManager::broadcastMessage(tx_msg, hash)`.\n2. `Floodgate::broadcast()` sends `FLOOD_ADVERT` (hash only) to each peer not already told.\n3. Per-peer `TxAdverts::queueOutgoingAdvert()` batches hashes; flushed on timer or batch full.\n4. Remote peer receives advert → `Peer::recvFloodAdvert()` → `TxAdverts::queueIncomingAdvert()`.\n5. `TxDemandsManager::demand()` timer fires → picks hashes from peers → sends `FLOOD_DEMAND`.\n6. Remote peer receives demand → `TxDemandsManager::recvTxDemand()` → looks up tx in Herder → sends full `TRANSACTION` message back.\n7. `Peer::recvTransaction()` → `OverlayManager::recvTransaction()` → `Herder::recvTransaction()`.\n\n### SCP Message Flooding (Push Mode)\n1. Herder calls `broadcastMessage(scp_msg)`.\n2. `Floodgate::broadcast()` sends full `SCP_MESSAGE` to all peers not yet told.\n3. Messages go through `FlowControl::addMsgAndMaybeTrimQueue()` with priority 0 (highest).\n4. Remote peer receives → `recvSCPMessage()` → posted to main thread → dispatched to Herder.\n\n### Anycast Fetch (TX Sets \u002F Quorum Sets)\n1. Herder needs a tx set or quorum set → calls `ItemFetcher::fetch(hash, envelope)`.\n2. `ItemFetcher` creates\u002Freuses a `Tracker` for the hash.\n3. `Tracker::tryNextPeer()` picks a peer, sends `GET_TX_SET` or `GET_SCP_QUORUMSET`.\n4. Remote peer responds with the data, or `DONT_HAVE`.\n5. On `DONT_HAVE`: `Tracker::doesntHave()` → try next peer.\n6. On receipt: `ItemFetcher::recv()` → cancel tracker → re-submit waiting envelopes to Herder.\n\n### Flow Control\n1. On connection, both sides start with initial flood reading capacity (messages + bytes).\n2. When peer sends flood data, it consumes outbound capacity (`lockOutboundCapacity`).\n3. Receiver processes message, releasing local capacity via `endMessageProcessing()`.\n4. When enough capacity freed (batch threshold), receiver sends `SEND_MORE_EXTENDED(numMessages, numBytes)`.\n5. Sender receives `SEND_MORE_EXTENDED` → `FlowControl::maybeReleaseCapacity()` → unlocks outbound capacity → can send more.\n6. If outbound capacity exhausted, messages queue up. Oldest tx messages are shed if byte limit exceeded.\n7. If reading capacity exhausted, `maybeThrottleRead()` stops scheduling reads until capacity is freed.\n",{},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Fstellar\u002Fstellar-core\u002Fsubsystem-summary-of-overlay",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":7,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill subsystem-summary-of-overlay",{"tool":39,"command":40},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill subsystem-summary-of-overlay",{"tool":42,"command":43},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill subsystem-summary-of-overlay","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fstellar\u002Fstellar-core\u002Fsubsystem-summary-of-overlay\u002FSKILL.md",true,[],[48,57,66,75,81,87],{"skillNo":49,"name":50,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":20},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[54,55,56],"model","model hierarchy","model hierarchy skill",{"skillNo":58,"name":59,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":20},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[63,64,65],"MCP","zoom","zoom mcp",{"skillNo":67,"name":68,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":20},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[72,73,74,64],"sdk","zoom apps sdk","apps",{"skillNo":76,"name":77,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":20},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[77],{"skillNo":82,"name":83,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":20},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[83],{"skillNo":88,"name":89,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":20},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[89]]