feat(holdings): holdings are DECLARED, not inferred from transport

Until now every receive path recorded the SENDER in `file_holders`, and
those rows went straight back out on the wire to third parties as
`cdn_redirect_peers`, as worm holder answers, and as HTTP 302 targets.
Exchanging bytes with a peer enrolled its node id -- and its addresses --
into a list we republished to anyone who asked.

Two things follow, and both matter. The concealment model the erasure
work depends on ("hold k shards quietly, announce exactly one slot") is
impossible on an inferred foundation: acquiring a shard registers you as
its holder whether you consented or not. And an enumerator never had to
hold anything -- it just asked holders who else holds.

`file_holders` rows now split two ways:

  * local hint (`declared = 0`) -- "we exchanged bytes about this file
    with that peer". Drives fetch retry, diff-propagation targets and
    manifest refresh. Never published as a holder of a specific file.
  * declaration (`declared = 1`) -- the peer told us "I hold this and you
    may advertise me for it" (0xD3). The only holder list that may leave
    the node.

All 12 inference sites were triaged into hints with a per-site reason
rather than deleted. 0xD3 became the declaration handler and is validated
hard, since it is now the only unauthenticated input reaching an outbound
holder surface: 16 KB read ceiling (was MAX_PAYLOAD, 64 MB), reject rather
than truncate oversized batches, a `tracks_file` gate so a stranger cannot
mint rows for arbitrary 32-byte ids, a per-peer token bucket and row
budget, and normalised publicly-routable addresses capped at 4. An
introducer nominee must be a known anchor -- otherwise a peer could make
us publish an arbitrary victim's address.

Declarations are soft state: a rotating per-peer sweep rides each
content-sync cycle and `DECLARATION_TTL_MS` (30d) ages out a holder that
goes quiet, so a peer that wipes its database re-learns them.

Durability decisions count EVIDENCE, never claims. A new `witnessed`
column records transport events we handled ourselves, independent of
`declared` because a peer can be both; keying the count on `declared = 0`
instead dropped every honest custodian that declared out of its author's
durability count, making the post look less durable and provoking
replication it did not need. Gating replication on claims would also let
five Sybil identities declare a post and silently stop its author
replicating it -- the data-availability attack the erasure study rules
against.

Alpha policy defaults are deliberately generous (both classes declare,
per-author cap off) because a tight cap makes content unfindable and
there is no spare holder population yet. Own-authored content is never
declared by default: it publishes device <-> posting identity, the
binding the manifest address strip exists to prevent. Non-public content
is never declared at all, at a single chokepoint. Policy changes are
retroactive, so the open alpha shape is transitional.

Known limit, documented in `holdings.rs` and design.html: this hides
WHICH and HOW MANY of an author's posts you hold, not THAT you hold some
of that author's content -- `build_own_uniques` still announces every
distinct author, deliberately interest-blind-but-complete so discovery
works. The one-shard-announcement property holds at file granularity
only; closing the author-level surface is a discovery trade Round 10 has
not ruled on.

Wire format (clean break, zero users): drops
`BlobRequestPayload.requester_addresses`, `BlobResponsePayload`'s
`cdn_registered`, and `CdnManifest.host` -- the last rode every blob
response and was relayed verbatim, so a third party learned "node A holds
this CID" with no declaration from A. ALPN is NOT bumped here; see the PR.

301 core tests (was 267), a3 23/23 (12 pre-existing + 11 new behavioural
assertions), c_topology 33/33 unchanged. Policy knobs reachable from the
desktop app, not CLI-only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LGiPD2cF75mnvneSCjdDC5
This commit is contained in:
Scott Reimers 2026-10-31 15:09:08 -04:00
parent eebf0d86f0
commit 3430a9d4c9
17 changed files with 3560 additions and 157 deletions

View file

@ -246,6 +246,7 @@ async fn main() -> anyhow::Result<()> {
println!(" dismiss <greeting_index> Dismiss a greeting (local only)"); println!(" dismiss <greeting_index> Dismiss a greeting (local only)");
println!(" greetings-open <on|off> Toggle the greeting slot on your bio (republishes bio)"); println!(" greetings-open <on|off> Toggle the greeting slot on your bio (republishes bio)");
println!(" greetings-max <n|default> Limit live stranger greetings on your bio (republishes bio)"); println!(" greetings-max <n|default> Limit live stranger greetings on your bio (republishes bio)");
println!(" holdings [cap|custodial|interest|introducer] ... Declared-holdings policy (what we consent to be advertised for)");
println!(" stats Show node stats"); println!(" stats Show node stats");
println!(" export-key Export identity key (KEEP SECRET)"); println!(" export-key Export identity key (KEEP SECRET)");
println!(" id Show this node's ID"); println!(" id Show this node's ID");
@ -1203,6 +1204,77 @@ async fn main() -> anyhow::Result<()> {
} }
} }
// v0.8.1 PHASE 2: declared-holdings policy. Holdings are DECLARED,
// not inferred from transport — these knobs decide what this node
// consents to be advertised as a source for.
"holdings" => {
let a = arg.unwrap_or("").trim().to_string();
let mut parts = a.split_whitespace();
match (parts.next(), parts.next()) {
(None, _) | (Some(""), _) => {
println!("{}", node.holdings_summary().await);
println!("Usage: holdings cap <n|off> | holdings custodial <on|off> | holdings interest <on|off> | holdings own-authored <on|off> | holdings introducer <off|auto|<nodeid>>");
}
(Some("cap"), Some(v)) => {
let cap = if v == "off" || v == "unlimited" { Some(0) } else { v.parse::<u32>().ok() };
match cap {
Some(c) => match node.set_holdings_cap_per_author(c).await {
Ok(()) if c == 0 => println!("Per-author declaration cap: unlimited (alpha default)."),
Ok(()) => println!(
"Per-author declaration cap: {}. Retroactive: declarations beyond the cap were retracted (newest kept) and withdrawals sent.",
c
),
Err(e) => println!("Error: {}", e),
},
None => println!("Usage: holdings cap <n|off>"),
}
}
(Some(class @ ("custodial" | "interest")), Some(v)) => {
let on = matches!(v, "on" | "true" | "yes");
let reason = if class == "custodial" {
itsgoin_core::holdings::DeclareReason::Custodial
} else {
itsgoin_core::holdings::DeclareReason::Interest
};
match node.set_holdings_declare_class(reason, on).await {
Ok(()) if on => println!("Declare {} holdings: on", class),
Ok(()) => println!(
"Declare {} holdings: off. Existing {} declarations were retracted and withdrawals sent.",
class, class
),
Err(e) => println!("Error: {}", e),
}
}
(Some("own-authored"), Some(v)) => {
let on = matches!(v, "on" | "true" | "yes");
match node.set_holdings_declare_own_authored(on).await {
Ok(()) if on => println!("Declaring own authored content: ON (publishes device <-> persona in holder lists)."),
Ok(()) => println!("Declaring own authored content: OFF (default)."),
Err(e) => println!("Error: {}", e),
}
}
(Some("introducer"), Some(v)) => {
let (enabled, peer) = match v {
"off" | "false" => (false, None),
"auto" | "on" | "true" => (true, None),
hex_id => match itsgoin_core::parse_node_id_hex(hex_id) {
Ok(nid) => (true, Some(nid)),
Err(_) => {
println!("Usage: holdings introducer <off|auto|<nodeid-hex>>");
continue;
}
},
};
match node.set_holdings_introducer(enabled, peer).await {
Ok(()) if !enabled => println!("Introducer mode OFF — declarations publish our own reach."),
Ok(()) => println!("Introducer mode ON (hole-punch coordination only; NOT session relay)."),
Err(e) => println!("Error: {}", e),
}
}
_ => println!("Usage: holdings cap <n|off> | holdings custodial <on|off> | holdings interest <on|off> | holdings own-authored <on|off> | holdings introducer <off|auto|<nodeid>>"),
}
}
"quit" | "exit" | "q" => { "quit" | "exit" | "q" => {
println!("Shutting down..."); println!("Shutting down...");
break; break;

View file

@ -28,13 +28,42 @@ use crate::protocol::{
pack_ids, unpack_ids, AnchorEntry, UniquesAnnouncePayload, UniquesSlice, pack_ids, unpack_ids, AnchorEntry, UniquesAnnouncePayload, UniquesSlice,
}; };
use crate::types::{ use crate::types::{
DeviceProfile, IdClass, MeshSlot, NodeId, PeerWithAddress, PostId, PostVisibility, CdnRedirectPeer, DeviceProfile, IdClass, MeshSlot, NodeId, PeerWithAddress, PostId,
ReachEntry, ReachMethod, SessionReachMethod, SocialRouteEntry, SocialStatus, UniquesPools, PostVisibility, ReachEntry, ReachMethod, SessionReachMethod, SocialRouteEntry, SocialStatus,
WormId, WormResult, UniquesPools, WormId, WormResult,
}; };
const MAX_PAYLOAD: usize = 64 * 1024 * 1024; // 64 MB const MAX_PAYLOAD: usize = 64 * 1024 * 1024; // 64 MB
/// Extra file ids one holding declaration (0xD3) may cover beyond its primary
/// `post_id`. Enough to batch a sync cycle's worth of declarations into one or
/// two messages; small enough that no single message rewrites a large slice of
/// our `file_holders`.
const MAX_DECLARED_FILES_PER_MESSAGE: usize = 32;
/// Posts we will consider declaring per content-sync cycle. Caps the work, not
/// the footprint — the footprint is capped by `holdings.cap_per_author`.
const DECLARE_POSTS_PER_SYNC: usize = 50;
/// Read ceiling for a holding declaration (0xD3). 33 file ids plus a short
/// address list and an introducer fits in a couple of KB; anything larger is
/// rejected rather than silently truncated.
const MAX_DECLARATION_PAYLOAD: usize = 16 * 1024;
/// Already-declared holdings re-announced per content-sync cycle, per peer.
/// Rotates through `declared_holdings` so successive cycles cover everything
/// while any single cycle stays one cheap message.
const REDECLARE_PER_SYNC: usize = 24;
/// How many publishable holder rows ONE peer may occupy across all files.
/// `file_holders` is capped per file, not globally, so this is what bounds the
/// table against a single declaring peer.
const MAX_DECLARED_ROWS_PER_PEER: usize = 512;
/// Token bucket on inbound declarations: burst, and refill window.
const DECLARATION_BURST: u32 = 64;
const DECLARATION_WINDOW_MS: u64 = 60_000;
/// Read ceiling for the uniques opcodes (0x01 announce, 0x40/0x41 pull). /// Read ceiling for the uniques opcodes (0x01 announce, 0x40/0x41 pull).
/// ///
/// `MAX_PAYLOAD` exists for FILE transfer. Applying it to the index exchange /// `MAX_PAYLOAD` exists for FILE transfer. Applying it to the index exchange
@ -1038,6 +1067,11 @@ pub struct ConnectionManager {
/// Peers known to be unreachable directly: node_id → last_failed_at_ms /// Peers known to be unreachable directly: node_id → last_failed_at_ms
/// Learned over the session — cleared on restart, updated on connect success/failure /// Learned over the session — cleared on restart, updated on connect success/failure
unreachable_peers: HashMap<NodeId, u64>, unreachable_peers: HashMap<NodeId, u64>,
/// Token bucket on inbound holding declarations (0xD3):
/// node_id → (window start ms, declarations seen in window). A declaration
/// is the only unauthenticated input that can mark a peer publishable, so
/// one peer must not be able to rewrite our holder tables at line rate.
declaration_quota: HashMap<NodeId, (u64, u32)>,
/// Anchor-side rolling window of recent callers. Newest at the back. /// Anchor-side rolling window of recent callers. Newest at the back.
/// In-memory only — no registration DB, no persistence. /// In-memory only — no registration DB, no persistence.
convection_window: VecDeque<ConvectionEntry>, convection_window: VecDeque<ConvectionEntry>,
@ -1146,6 +1180,7 @@ impl ConnectionManager {
diff_seq: AtomicU64::new(0), diff_seq: AtomicU64::new(0),
blob_store, blob_store,
seen_worms: HashMap::new(), seen_worms: HashMap::new(),
declaration_quota: HashMap::new(),
last_announce_digest: 0, last_announce_digest: 0,
mesh_slots: profile.mesh_slots(), mesh_slots: profile.mesh_slots(),
temp_referral_slots: profile.temp_referral_slots(), temp_referral_slots: profile.temp_referral_slots(),
@ -1596,6 +1631,31 @@ impl ConnectionManager {
Ok(()) Ok(())
} }
/// Token bucket for inbound holding declarations (0xD3). `true` = accept.
pub(crate) fn allow_declaration_from(&mut self, peer: &NodeId) -> bool {
let now = now_ms();
let entry = self.declaration_quota.entry(*peer).or_insert((now, 0));
if now.saturating_sub(entry.0) >= DECLARATION_WINDOW_MS {
*entry = (now, 0);
}
if entry.1 >= DECLARATION_BURST {
return false;
}
entry.1 += 1;
true
}
/// Peers we currently have any live connection to (mesh or session).
/// Used when resolving a declaration's introducer: an introducer we are
/// not connected to cannot introduce anyone to us.
pub(crate) fn connected_peer_ids(&self) -> Vec<NodeId> {
self.connections
.keys()
.chain(self.sessions.keys())
.copied()
.collect()
}
/// Build the stable advertised address for this anchor node. /// Build the stable advertised address for this anchor node.
/// Returns None if not an anchor or no suitable address found. /// Returns None if not an anchor or no suitable address found.
pub fn build_anchor_advertised_addr(&self) -> Option<String> { pub fn build_anchor_advertised_addr(&self) -> Option<String> {
@ -1903,6 +1963,8 @@ impl ConnectionManager {
storage: &Arc<StoragePool>, storage: &Arc<StoragePool>,
peer_id: &NodeId, peer_id: &NodeId,
_our_node_id: NodeId, _our_node_id: NodeId,
anchor_addr: Option<String>,
connected_peers: Vec<NodeId>,
) -> anyhow::Result<PullSyncStats> { ) -> anyhow::Result<PullSyncStats> {
let (our_follows, follows_sync, our_personas) = { let (our_follows, follows_sync, our_personas) = {
let s = storage.get().await; let s = storage.get().await;
@ -1942,6 +2004,30 @@ impl ConnectionManager {
let mut new_post_ids: Vec<PostId> = Vec::new(); let mut new_post_ids: Vec<PostId> = Vec::new();
let now_ms = crate::connection::now_ms(); let now_ms = crate::connection::now_ms();
let mut synced_authors: HashSet<NodeId> = HashSet::new(); let mut synced_authors: HashSet<NodeId> = HashSet::new();
// ACQUISITION half of the declaration work: every PUBLIC post from
// this response that we now hold, as (post_id, author). These are
// candidates for a NEW declaration.
//
// The RE-DECLARATION half does not come from the response at all, and
// must not: `handle_content_sync_request_unlocked` drops every post the
// requester already has (`peer_has_post` against its per-author
// `last_sync_ms`, which this function advances to now at the end of
// each cycle), so after the first successful sync the response is empty
// and a response-derived list would never re-declare anything. The
// rotating sweep over `declared_holdings` below is what actually makes
// a peer's view of us self-heal, and it is what carries the migration.
//
// Non-public posts are NEVER declared: a declaration says "advertise me
// as a source", and advertising yourself as a holder of a DM, a group
// post or an FoFClosed post announces your membership in its audience.
// (Belt and braces — `declare_own_holding` refuses non-public content
// at the chokepoint too.)
//
// Posts only, never their attachment CIDs: a declaration claims "I hold
// this file", and a synced post does not mean we fetched its blobs.
// Blob declarations are emitted from `Node::declare_blob_holding`, once
// the bytes are actually on disk.
let mut declarable: Vec<(PostId, NodeId)> = Vec::new();
// Brief storage lock: store posts // Brief storage lock: store posts
{ {
@ -1960,14 +2046,22 @@ impl ConnectionManager {
} }
Err(e) => { Err(e) => {
warn!(post_id = hex::encode(sp.id), error = %e, "rejecting post"); warn!(post_id = hex::encode(sp.id), error = %e, "rejecting post");
continue;
} }
} }
if matches!(sp.visibility, PostVisibility::Public) {
declarable.push((sp.id, sp.post.author));
}
} }
} }
} }
// Brief storage lock: upstream + last_sync // Brief storage lock: local hints + last_sync + declaration policy.
{ //
// The holder row for the SENDER is a LOCAL HINT only (declared = 0):
// the fact that they sent us bytes is not their consent to be
// advertised. They enrol themselves via their own declaration.
let declarations: Vec<PostDownstreamRegisterPayload> = {
let s = storage.get().await; let s = storage.get().await;
for pid in &new_post_ids { for pid in &new_post_ids {
let _ = s.touch_file_holder( let _ = s.touch_file_holder(
@ -1980,14 +2074,58 @@ impl ConnectionManager {
for author in &synced_authors { for author in &synced_authors {
let _ = s.update_follow_last_sync(author, now_ms); let _ = s.update_follow_last_sync(author, now_ms);
} }
// Policy read ONCE for the whole batch: `holdings_policy()` is four
// `settings` queries and this loop runs inside a held storage guard.
let policy = s.holdings_policy();
// Flat list of file ids to declare, then BATCHED. One or two
// messages per sync cycle instead of one per post.
let mut file_ids: Vec<[u8; 32]> = Vec::new();
for (post_id, author) in declarable.into_iter().take(DECLARE_POSTS_PER_SYNC) {
if s.declare_own_holding_with(
&policy, &post_id, &post_id, &author,
crate::holdings::DeclareReason::Interest,
).unwrap_or(false) {
file_ids.push(post_id);
} }
}
// RE-DECLARATION sweep: a rotating, per-peer slice of everything we
// have already declared. This is the mechanism the migration ruling
// rests on — a peer that wiped its database, or evicted our row
// from a 5-deep keep-set, re-learns our declarations within a few
// cycles without us having to re-acquire the content.
for fid in s
.next_declarations_to_announce(peer_id, REDECLARE_PER_SYNC)
.unwrap_or_default()
{
if !file_ids.contains(&fid) {
file_ids.push(fid);
}
}
if file_ids.is_empty() {
Vec::new()
} else {
// Reach is resolved only once we know we are sending something.
let (addresses, introducer) = s
.build_declaration_reach(anchor_addr.as_deref(), &connected_peers)
.into_payload_parts();
file_ids
.chunks(MAX_DECLARED_FILES_PER_MESSAGE + 1)
.map(|chunk| PostDownstreamRegisterPayload {
post_id: chunk[0],
extra_file_ids: chunk[1..].to_vec(),
addresses: addresses.clone(),
introducer: introducer.clone(),
withdraw: false,
})
.collect()
}
};
// Register as downstream (spawned, no lock needed) // Declare our holdings (spawned, no lock needed)
if !new_post_ids.is_empty() { if !declarations.is_empty() {
let c = conn.clone(); let c = conn.clone();
tokio::spawn(async move { tokio::spawn(async move {
for post_id in new_post_ids.into_iter().take(50) { for payload in declarations {
let payload = PostDownstreamRegisterPayload { post_id };
if let Ok(mut send) = c.open_uni().await { if let Ok(mut send) = c.open_uni().await {
let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &payload).await; let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &payload).await;
let _ = send.finish(); let _ = send.finish();
@ -2912,9 +3050,10 @@ impl ConnectionManager {
if store.get_post_with_visibility(post_id).ok().flatten().is_some() { if store.get_post_with_visibility(post_id).ok().flatten().is_some() {
Some(self.our_node_id) Some(self.our_node_id)
} else { } else {
// Any known holder of this post? // v0.8.1 PHASE 2: a worm answer names a third party to the
let holders = store.get_file_holders(post_id).unwrap_or_default(); // asker, so only DECLARED holders may be named here.
holders.first().map(|(nid, _)| *nid) let holders = store.get_declared_file_holders(post_id).unwrap_or_default();
holders.first().map(|(nid, _, _)| *nid)
} }
}; };
post_holder = found; post_holder = found;
@ -2928,8 +3067,8 @@ impl ConnectionManager {
// Check CDN: do we know who has it via blob post ownership? // Check CDN: do we know who has it via blob post ownership?
let store = self.storage.get().await; let store = self.storage.get().await;
if let Ok(Some(pid)) = store.get_blob_post_id(blob_id) { if let Ok(Some(pid)) = store.get_blob_post_id(blob_id) {
let holders = store.get_file_holders(&pid).unwrap_or_default(); let holders = store.get_declared_file_holders(&pid).unwrap_or_default();
if let Some((nid, _)) = holders.first() { if let Some((nid, _, _)) = holders.first() {
blob_holder = Some(*nid); blob_holder = Some(*nid);
} }
} }
@ -5103,7 +5242,9 @@ impl ConnectionManager {
&entry.manifest.author_manifest.author, &entry.manifest.author_manifest.author,
entry.manifest.author_manifest.updated_at, entry.manifest.author_manifest.updated_at,
); );
// Remote peer pushed us this manifest → they hold the file. // LOCAL HINT only (v0.8.1): pushing us a manifest shows the
// peer has the file, but is not consent to be advertised for
// it. Hints are propagation targets, never published.
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
&entry.cid, &entry.cid,
&remote_node_id, &remote_node_id,
@ -5219,8 +5360,10 @@ impl ConnectionManager {
Ok(Some(sync_post)) => { Ok(Some(sync_post)) => {
if crate::content::verify_post_id(&sync_post.id, &sync_post.post) { if crate::content::verify_post_id(&sync_post.id, &sync_post.post) {
// Brief re-acquire for storage writes only // Brief re-acquire for storage writes only
let stored = { let (stored, declaration) = {
let cm = cm_arc.lock().await; let cm = cm_arc.lock().await;
let anchor_addr = cm.build_anchor_advertised_addr();
let connected = cm.connected_peer_ids();
let storage = cm.storage.get().await; let storage = cm.storage.get().await;
let newly_stored = crate::control::receive_post( let newly_stored = crate::control::receive_post(
&storage, &storage,
@ -5230,6 +5373,8 @@ impl ConnectionManager {
sync_post.intent.as_ref(), sync_post.intent.as_ref(),
).unwrap_or(false); ).unwrap_or(false);
if newly_stored { if newly_stored {
// LOCAL HINT for the sender (v0.8.1) — not a
// declaration on their behalf.
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
&sync_post.id, &sync_post.id,
&sender_id, &sender_id,
@ -5241,18 +5386,38 @@ impl ConnectionManager {
.unwrap_or_default() .unwrap_or_default()
.as_millis() as u64; .as_millis() as u64;
let _ = storage.update_follow_last_sync(&sync_post.post.author, now); let _ = storage.update_follow_last_sync(&sync_post.post.author, now);
true
} else {
false
} }
// Declare OUR holding, policy permitting. Public
// only — see content_sync_unlocked.
let declaration = if matches!(sync_post.visibility, PostVisibility::Public)
&& storage.declare_own_holding(
&sync_post.id, &sync_post.id, &sync_post.post.author,
crate::holdings::DeclareReason::Interest,
).unwrap_or(false)
{
let (addresses, introducer) = storage
.build_declaration_reach(anchor_addr.as_deref(), &connected)
.into_payload_parts();
Some(crate::protocol::PostDownstreamRegisterPayload {
post_id: sync_post.id,
extra_file_ids: Vec::new(),
addresses,
introducer,
withdraw: false,
})
} else {
None
}; };
// cm lock RELEASED — register downstream without lock (newly_stored, declaration)
if stored { };
let reg = crate::protocol::PostDownstreamRegisterPayload { post_id: sync_post.id }; // cm lock RELEASED — declare without lock
if let Some(reg) = declaration {
if let Ok(mut send) = conn.open_uni().await { if let Ok(mut send) = conn.open_uni().await {
let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &reg).await; let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &reg).await;
let _ = send.finish(); let _ = send.finish();
} }
}
if stored {
fetched += 1; fetched += 1;
} }
} }
@ -5279,7 +5444,7 @@ impl ConnectionManager {
if blob_store.has(&att.cid) { continue; } if blob_store.has(&att.cid) { continue; }
let blob_result: anyhow::Result<()> = async { let blob_result: anyhow::Result<()> = async {
let (mut bs, mut br) = conn.open_bi().await?; let (mut bs, mut br) = conn.open_bi().await?;
let req = BlobRequestPayload { cid: att.cid, requester_addresses: vec![] }; let req = BlobRequestPayload { cid: att.cid };
write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?; write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?;
bs.finish()?; bs.finish()?;
let mt = read_message_type(&mut br).await?; let mt = read_message_type(&mut br).await?;
@ -5394,20 +5559,128 @@ impl ConnectionManager {
cm.handle_blob_header_diff(payload, remote_node_id).await; cm.handle_blob_header_diff(payload, remote_node_id).await;
} }
MessageType::PostDownstreamRegister => { MessageType::PostDownstreamRegister => {
let payload: PostDownstreamRegisterPayload = read_payload(recv, MAX_PAYLOAD).await?; // v0.8.1 PHASE 2: the HOLDING DECLARATION handler. This is the
let cm = conn_mgr.lock().await; // only path that can mark a peer publishable for a file. Every
let storage = cm.storage.get().await; // other holder write in this file is a local hint.
let _ = storage.touch_file_holder( //
&payload.post_id, // It is therefore the only unauthenticated input that can reach
&remote_node_id, // `cdn_redirect_peers`, worm holder answers and HTTP 302s, so
&[], // it is validated hard. `MAX_DECLARATION_PAYLOAD` rejects
crate::storage::HolderDirection::Sent, // (rather than truncates) anything larger than a full batch
// needs; the ceiling used to be MAX_PAYLOAD = 64 MB.
let payload: PostDownstreamRegisterPayload =
read_payload(recv, MAX_DECLARATION_PAYLOAD).await?;
if payload.extra_file_ids.len() > MAX_DECLARED_FILES_PER_MESSAGE {
anyhow::bail!(
"holding declaration covers {} extra files (max {})",
payload.extra_file_ids.len(), MAX_DECLARED_FILES_PER_MESSAGE
); );
}
let mut cm = conn_mgr.lock().await;
// Per-peer token bucket. A declaration is cheap to send and
// each one writes rows, so one peer must not be able to
// rewrite our holder tables at line rate.
if !cm.allow_declaration_from(&remote_node_id) {
drop(cm);
debug!(peer = hex::encode(remote_node_id), "holding declaration rate-limited");
return Ok(());
}
let storage = cm.storage.get().await;
let mut file_ids: Vec<[u8; 32]> = vec![payload.post_id];
file_ids.extend(payload.extra_file_ids.iter().copied());
// Addresses: publicly routable only (bugs-fixed #8), NORMALISED
// (bugs-fixed #4 — an IPv4-mapped v6 address passes
// `is_public_ip`'s V6 arm and then breaks IPv4-only clients, and
// `[::ffff:10.0.0.1]` is a private LAN address in mapped form),
// and capped (an uncapped list is fed to
// `EndpointAddr::with_ip_addr` by every fetcher, which is the
// iroh path-store amplification shape the EDM scanner was
// disabled for).
let addrs: Vec<String> = payload.addresses.iter()
.filter_map(|a| a.parse::<SocketAddr>().ok())
.map(normalize_addr)
.filter(crate::network::is_publicly_routable)
.take(crate::holdings::MAX_DECLARED_ADDRESSES)
.map(|sa| sa.to_string())
.collect();
// The introducer is a THIRD PARTY's id + address that we would
// republish to anyone asking for this file. Unfiltered, a peer
// could make us publish an arbitrary victim's address (or a
// loopback/RFC1918 one that burns fetchers' punch time). So:
// same routability + normalisation + cap as our own addresses,
// AND the nominee must be a known anchor — the only address
// class Round 10 lets ride the wire, and the only one whose
// owner has opted into being publicly named.
let introducer = payload.introducer.as_ref().and_then(|i| {
let nid = crate::parse_node_id_hex(&i.n).ok()?;
if !storage.is_peer_anchor(&nid).unwrap_or(false) {
return None;
}
let a: Vec<String> = i.a.iter()
.filter_map(|s| s.parse::<SocketAddr>().ok())
.map(normalize_addr)
.filter(crate::network::is_publicly_routable)
.take(crate::holdings::MAX_DECLARED_ADDRESSES)
.map(|sa| sa.to_string())
.collect();
if a.is_empty() { return None; }
Some(crate::types::RedirectIntroducer { n: i.n.clone(), a })
});
// Per-peer declared-row budget: `file_holders` has only a
// per-file cap, so without this one peer grows the table
// without bound by declaring many files.
let peer_rows = storage.count_declared_rows_for_peer(&remote_node_id).unwrap_or(0);
let mut budget_left =
MAX_DECLARED_ROWS_PER_PEER.saturating_sub(peer_rows as usize);
let mut recorded = 0usize;
let mut skipped_unknown = 0usize;
for fid in &file_ids {
if payload.withdraw {
let _ = storage.clear_holder_declaration(fid, &remote_node_id);
continue;
}
// Only for a file we actually track. Every legitimate
// declarer declares to the peer that just served it the
// file, so this costs nothing honest — and it is what stops
// a stranger from minting holder rows (and inflating
// `get_file_holder_count`, the replication under-
// replication gate) for arbitrary 32-byte ids.
if !storage.tracks_file(fid) {
skipped_unknown += 1;
continue;
}
// Over budget: accept only what keeps content reachable —
// a file that has NO declared holder yet. Anything else is
// refused, so the budget actually bounds the peer. (The
// test is this way round deliberately: refusing the
// first-and-only holder while admitting the sixth is both
// unbounded and bad for availability.)
if budget_left == 0
&& storage.get_declared_file_holder_count(fid).unwrap_or(0) > 0
{
continue;
}
if storage.record_declared_holder(
fid,
&remote_node_id,
&addrs,
crate::storage::HolderDirection::Sent,
introducer.as_ref(),
).is_ok() {
budget_left = budget_left.saturating_sub(1);
recorded += 1;
}
}
drop(storage); drop(storage);
drop(cm);
trace!( trace!(
peer = hex::encode(remote_node_id), peer = hex::encode(remote_node_id),
post = hex::encode(payload.post_id), post = hex::encode(payload.post_id),
"Registered as post downstream" files = file_ids.len(),
recorded,
skipped_unknown,
withdraw = payload.withdraw,
"Holding declaration recorded"
); );
} }
other => { other => {
@ -5652,61 +5925,54 @@ impl ConnectionManager {
MessageType::BlobRequest => { MessageType::BlobRequest => {
let payload: BlobRequestPayload = read_payload(&mut recv, 4096).await?; let payload: BlobRequestPayload = read_payload(&mut recv, 4096).await?;
// Extract Arcs under brief lock — no conn_mgr lock needed for blob serving // Extract Arcs under brief lock — no conn_mgr lock needed for blob serving
let (blob_store, storage, our_node_id) = { let (blob_store, storage) = {
let cm = conn_mgr.lock().await; let cm = conn_mgr.lock().await;
(Arc::clone(&cm.blob_store), Arc::clone(&cm.storage), cm.our_node_id) (Arc::clone(&cm.blob_store), Arc::clone(&cm.storage))
}; };
// All I/O outside the lock // All I/O outside the lock
let data = blob_store.get(&payload.cid)?; let data = blob_store.get(&payload.cid)?;
// v0.8.1 PHASE 2: serving a blob no longer enrols the requester
// as a holder — `requester_addresses` is gone from the request,
// and a requester that wants to be advertised sends a holding
// declaration (0xD3) once it has the bytes.
//
// Redirects list ONLY declared holders, and are built ONCE for
// all three response shapes. They used to be attached to the
// `found: true` arm only, which made the whole declared-holder
// redirect path (including the introducer) dead code — and the
// budget-exhausted arm is exactly where a redirect is worth
// most, since we have the blob and are refusing to serve it.
let (manifest, cdn_redirect_peers) = {
let storage = storage.get().await;
let manifest: Option<crate::types::CdnManifest> = storage.get_cdn_manifest(&payload.cid).ok().flatten().and_then(|json| {
serde_json::from_str::<crate::types::AuthorManifest>(&json).ok()
.map(|am| crate::types::CdnManifest { author_manifest: am })
});
let redirects = declared_redirects(&storage, &payload.cid, &remote_node_id);
(manifest, redirects)
};
let response = match data { let response = match data {
Some(bytes) => { Some(bytes) => {
if !blob_store.consume_delivery_budget(bytes.len() as u64) { if !blob_store.consume_delivery_budget(bytes.len() as u64) {
debug!(peer = hex::encode(remote_node_id), cid = hex::encode(payload.cid), "Delivery budget exhausted"); debug!(peer = hex::encode(remote_node_id), cid = hex::encode(payload.cid), "Delivery budget exhausted");
BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_registered: false, cdn_redirect_peers: vec![] } BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_redirect_peers }
} else { } else {
use base64::Engine; use base64::Engine;
let storage = storage.get().await; BlobResponsePayload { cid: payload.cid, found: true, data_b64: base64::engine::general_purpose::STANDARD.encode(&bytes), manifest, cdn_redirect_peers }
let manifest: Option<crate::types::CdnManifest> = storage.get_cdn_manifest(&payload.cid).ok().flatten().and_then(|json| {
serde_json::from_str::<crate::types::AuthorManifest>(&json).ok()
.map(|am| crate::types::CdnManifest { author_manifest: am, host: our_node_id })
});
let (cdn_registered, cdn_redirect_peers) = if !payload.requester_addresses.is_empty() {
let prior_count = storage.get_file_holder_count(&payload.cid).unwrap_or(0);
let _ = storage.touch_file_holder(
&payload.cid,
&remote_node_id,
&payload.requester_addresses,
crate::storage::HolderDirection::Sent,
);
// If we already had 5 holders before adding this one, the
// requester should consult them too for CDN lookups.
if prior_count < 5 {
(true, vec![])
} else {
let holders = storage.get_file_holders(&payload.cid).unwrap_or_default();
let redirects: Vec<PeerWithAddress> = holders.into_iter()
.filter(|(nid, _)| *nid != remote_node_id)
.map(|(nid, addrs)| PeerWithAddress { n: hex::encode(nid), a: addrs })
.collect();
(false, redirects)
}
} else { (false, vec![]) };
drop(storage);
BlobResponsePayload { cid: payload.cid, found: true, data_b64: base64::engine::general_purpose::STANDARD.encode(&bytes), manifest, cdn_registered, cdn_redirect_peers }
} }
} }
None => BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_registered: false, cdn_redirect_peers: vec![] }, None => BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_redirect_peers },
}; };
write_typed_message(&mut send, MessageType::BlobResponse, &response).await?; write_typed_message(&mut send, MessageType::BlobResponse, &response).await?;
send.finish()?; send.finish()?;
debug!(peer = hex::encode(remote_node_id), found = response.found, cdn_reg = response.cdn_registered, "Handled blob request"); debug!(peer = hex::encode(remote_node_id), found = response.found, redirects = response.cdn_redirect_peers.len(), "Handled blob request");
} }
MessageType::ManifestRefreshRequest => { MessageType::ManifestRefreshRequest => {
let payload: crate::protocol::ManifestRefreshRequestPayload = read_payload(&mut recv, 1024).await?; let payload: crate::protocol::ManifestRefreshRequestPayload = read_payload(&mut recv, 1024).await?;
// Brief lock: get storage Arc + our_node_id // Brief lock: get storage Arc
let (storage, our_node_id) = { let storage = {
let cm = conn_mgr.lock().await; let cm = conn_mgr.lock().await;
(Arc::clone(&cm.storage), cm.our_node_id) Arc::clone(&cm.storage)
}; };
let response = { let response = {
let store = storage.get().await; let store = storage.get().await;
@ -5714,7 +5980,7 @@ impl ConnectionManager {
Some(json) => { Some(json) => {
let manifest = if let Ok(am) = serde_json::from_str::<crate::types::AuthorManifest>(&json) { let manifest = if let Ok(am) = serde_json::from_str::<crate::types::AuthorManifest>(&json) {
if am.updated_at > payload.current_updated_at { if am.updated_at > payload.current_updated_at {
Some(crate::types::CdnManifest { author_manifest: am, host: our_node_id }) Some(crate::types::CdnManifest { author_manifest: am })
} else { None } } else { None }
} else { None }; } else { None };
crate::protocol::ManifestRefreshResponsePayload { cid: payload.cid, updated: manifest.is_some(), manifest } crate::protocol::ManifestRefreshResponsePayload { cid: payload.cid, updated: manifest.is_some(), manifest }
@ -6015,7 +6281,10 @@ impl ConnectionManager {
to_pull.push(*pid); to_pull.push(*pid);
} }
// Register as holder for all accepted posts // LOCAL HINT for the requester (v0.8.1): it asked us to
// replicate, so it holds these — but that is our inference
// about it, not its declaration, and the requester is
// normally the author anyway (reachable as such).
for pid in &acc { for pid in &acc {
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
pid, pid,
@ -6071,6 +6340,8 @@ impl ConnectionManager {
let attachments = sp.post.attachments.clone(); let attachments = sp.post.attachments.clone();
let post_author = sp.post.author; let post_author = sp.post.author;
let cm = cm_arc.lock().await; let cm = cm_arc.lock().await;
let anchor_addr = cm.build_anchor_advertised_addr();
let connected = cm.connected_peer_ids();
let storage = cm.storage.get().await; let storage = cm.storage.get().await;
let _ = crate::control::receive_post( let _ = crate::control::receive_post(
&storage, &storage,
@ -6079,26 +6350,58 @@ impl ConnectionManager {
&sp.visibility, &sp.visibility,
sp.intent.as_ref(), sp.intent.as_ref(),
); );
// LOCAL HINT for the sender (v0.8.1).
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
&sp.id, &sp.id,
&sender, &sender,
&[], &[],
crate::storage::HolderDirection::Received, crate::storage::HolderDirection::Received,
); );
// CUSTODIAL declaration: this content was PUSHED to
// us, we never chose it, and being findable for it is
// the entire function of holding it. So custodians
// declare by default (`holdings.declare_custodial`).
// Public only, same rule as the interest path.
// The POST's declaration decision, hoisted so the
// attachment loop below can require it: declaring an
// attachment of a non-public post announces audience
// membership just as loudly as declaring the post.
let post_is_public = matches!(sp.visibility, PostVisibility::Public);
let post_declared = post_is_public
&& storage.declare_own_holding(
&sp.id, &sp.id, &post_author,
crate::holdings::DeclareReason::Custodial,
).unwrap_or(false);
let declaration = if post_declared {
let (addresses, introducer) = storage
.build_declaration_reach(anchor_addr.as_deref(), &connected)
.into_payload_parts();
Some(crate::protocol::PostDownstreamRegisterPayload {
post_id: sp.id,
extra_file_ids: Vec::new(),
addresses,
introducer,
withdraw: false,
})
} else { None };
let blob_store = cm.blob_store.clone(); let blob_store = cm.blob_store.clone();
drop(storage); drop(storage);
drop(cm); drop(cm);
fetched += 1; fetched += 1;
if let Some(reg) = declaration {
if let Ok(mut send) = conn.open_uni().await {
let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &reg).await;
let _ = send.finish();
}
}
// Fetch blobs for this post from the requester // Fetch blobs for this post from the requester
for att in &attachments { for att in &attachments {
if blob_store.has(&att.cid) { continue; } if blob_store.has(&att.cid) { continue; }
let blob_result: anyhow::Result<()> = async { let blob_result: anyhow::Result<()> = async {
let (mut bs, mut br) = conn.open_bi().await?; let (mut bs, mut br) = conn.open_bi().await?;
let req = BlobRequestPayload { let req = BlobRequestPayload { cid: att.cid };
cid: att.cid,
requester_addresses: vec![],
};
write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?; write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?;
bs.finish()?; bs.finish()?;
let mt = read_message_type(&mut br).await?; let mt = read_message_type(&mut br).await?;
@ -6111,12 +6414,46 @@ impl ConnectionManager {
let cm = cm_arc.lock().await; let cm = cm_arc.lock().await;
let storage = cm.storage.get().await; let storage = cm.storage.get().await;
let _ = storage.record_blob(&att.cid, post_id, &post_author, data.len() as u64, &att.mime_type, att.size_bytes); let _ = storage.record_blob(&att.cid, post_id, &post_author, data.len() as u64, &att.mime_type, att.size_bytes);
// LOCAL HINT for the sender (v0.8.1).
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
&att.cid, &att.cid,
&sender, &sender,
&[], &[],
crate::storage::HolderDirection::Received, crate::storage::HolderDirection::Received,
); );
// Custodial declaration for the attachment.
// Gated on the POST's own visibility decision
// (`post_is_public`) — `declare_own_holding`
// cannot infer it from an attachment CID, and
// without this gate a peer that mislabels a
// FollowersOnly/FoFClosed/group post on the
// wire makes us publish ourselves as a holder
// of a private post's attachments.
let declared = post_is_public
&& storage.declare_own_holding(
&att.cid, post_id, &post_author,
crate::holdings::DeclareReason::Custodial,
).unwrap_or(false);
let reach = if declared {
Some(storage
.build_declaration_reach(anchor_addr.as_deref(), &connected)
.into_payload_parts())
} else { None };
drop(storage);
drop(cm);
if let Some((addresses, introducer)) = reach {
let reg = crate::protocol::PostDownstreamRegisterPayload {
post_id: att.cid,
extra_file_ids: Vec::new(),
addresses,
introducer,
withdraw: false,
};
if let Ok(mut send) = conn.open_uni().await {
let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &reg).await;
let _ = send.finish();
}
}
} }
Ok(()) Ok(())
}.await; }.await;
@ -6145,7 +6482,8 @@ impl ConnectionManager {
/// to the post's file_holders (flat set, up to 5 most recent). /// to the post's file_holders (flat set, up to 5 most recent).
async fn handle_blob_header_diff(&self, payload: BlobHeaderDiffPayload, sender: NodeId) { async fn handle_blob_header_diff(&self, payload: BlobHeaderDiffPayload, sender: NodeId) {
// Gather policy + followers set + holders, then drop lock immediately. // Gather policy + followers set + holders, then drop lock immediately.
// Remote peer clearly holds this post — record them as a holder. // Sending us a diff shows the peer holds the post, so record a LOCAL
// HINT (v0.8.1): we use it as a propagation target but never publish it.
// v0.6.2: `AudienceOnly` → `FollowersOnly`; checked against our public // v0.6.2: `AudienceOnly` → `FollowersOnly`; checked against our public
// follows list rather than a separate audience table. // follows list rather than a separate audience table.
let (policy, followers_set, holders) = { let (policy, followers_set, holders) = {
@ -7576,8 +7914,9 @@ impl ConnectionActor {
if s.get_post_with_visibility(post_id).ok().flatten().is_some() { if s.get_post_with_visibility(post_id).ok().flatten().is_some() {
post_holder = Some(ctx.our_node_id); post_holder = Some(ctx.our_node_id);
} else { } else {
let holders = s.get_file_holders(post_id).unwrap_or_default(); // Declared holders only — see handle_worm_query.
if let Some((nid, _)) = holders.first() { post_holder = Some(*nid); } let holders = s.get_declared_file_holders(post_id).unwrap_or_default();
if let Some((nid, _, _)) = holders.first() { post_holder = Some(*nid); }
} }
} }
@ -7587,8 +7926,8 @@ impl ConnectionActor {
} else { } else {
let s = ctx.storage.get().await; let s = ctx.storage.get().await;
if let Ok(Some(pid)) = s.get_blob_post_id(blob_id) { if let Ok(Some(pid)) = s.get_blob_post_id(blob_id) {
let holders = s.get_file_holders(&pid).unwrap_or_default(); let holders = s.get_declared_file_holders(&pid).unwrap_or_default();
if let Some((nid, _)) = holders.first() { blob_holder = Some(*nid); } if let Some((nid, _, _)) = holders.first() { blob_holder = Some(*nid); }
} }
} }
} }
@ -8171,11 +8510,12 @@ impl ConnectionActor {
let cm = self.cm.lock().await; let cm = self.cm.lock().await;
cm.connections.get(&peer) cm.connections.get(&peer)
.map(|pc| (pc.connection.clone(), cm.our_node_id)) .map(|pc| (pc.connection.clone(), cm.our_node_id))
.map(|(c, nid)| (c, nid, cm.build_anchor_advertised_addr(), cm.connected_peer_ids()))
}; };
let r = match gather { let r = match gather {
Some((conn, our_node_id)) => { Some((conn, our_node_id, anchor_addr, connected)) => {
// All I/O outside the lock, storage accessed via hoisted Arc // All I/O outside the lock, storage accessed via hoisted Arc
ConnectionManager::content_sync_unlocked(conn, &self.storage, &peer, our_node_id).await ConnectionManager::content_sync_unlocked(conn, &self.storage, &peer, our_node_id, anchor_addr, connected).await
} }
None => Err(anyhow::anyhow!("not connected to {}", hex::encode(peer))), None => Err(anyhow::anyhow!("not connected to {}", hex::encode(peer))),
}; };
@ -8511,6 +8851,32 @@ fn persist_direct_anchor_claim(storage: &crate::storage::Storage, e: &ReachEntry
/// Standalone initial exchange (connector side) — does NOT require conn_mgr lock. /// Standalone initial exchange (connector side) — does NOT require conn_mgr lock.
/// Opens a bi-stream, sends our uniques announce/profile/deletes/post_ids, reads theirs. /// Opens a bi-stream, sends our uniques announce/profile/deletes/post_ids, reads theirs.
/// Build the `cdn_redirect_peers` list for a blob response: the DECLARED
/// holders of `cid`, minus the requester itself.
///
/// Shared by all three response shapes (served, budget-exhausted, absent).
/// Attaching it only to the served arm made the whole declared-holder redirect
/// path — including the introducer — unreachable, and the budget-exhausted arm
/// is where a redirect is worth most: we have the blob and are refusing to
/// serve it, so the requester needs somewhere else to go.
pub(crate) fn declared_redirects(
storage: &crate::storage::Storage,
cid: &[u8; 32],
requester: &NodeId,
) -> Vec<CdnRedirectPeer> {
storage
.get_declared_file_holders(cid)
.unwrap_or_default()
.into_iter()
.filter(|(nid, _, _)| nid != requester)
.map(|(nid, addrs, intro)| CdnRedirectPeer {
n: hex::encode(nid),
a: addrs,
x: intro,
})
.collect()
}
pub async fn initial_exchange_connect( pub async fn initial_exchange_connect(
storage: &Arc<StoragePool>, storage: &Arc<StoragePool>,
our_node_id: &NodeId, our_node_id: &NodeId,
@ -8546,7 +8912,24 @@ pub async fn initial_exchange_connect(
let profile = storage.get_profile(our_node_id)? let profile = storage.get_profile(our_node_id)?
.map(|p| p.sanitized_for_network_broadcast()); .map(|p| p.sanitized_for_network_broadcast());
let deletes = storage.list_delete_records()?; let deletes = storage.list_delete_records()?;
let post_ids = storage.list_post_ids()?; // v0.8.1 PHASE 2: the post-id announce is narrowed, not gated.
//
// It used to be `list_post_ids()` — the node's COMPLETE, uncapped
// corpus, INCLUDING non-public rows, shipped to every peer that dialled
// us. A peer who knew a private post's id learned we were in its
// audience, which is the one thing the declaration paths are careful
// never to say, and it is a far larger enumeration surface than the
// 5-per-file holder lists Phase 2 locked down.
//
// It is NOT gated on `carry_knowledge`: that flag is `slot.is_mesh()`,
// and the anchor refuse-mesh path keeps clients as SESSIONS
// (bugs-fixed #6), so gating it would silently drop anchors out of
// every NAT'd client's `post_replicas` — the cheapest and most
// reachable blob source in the cascade. What we announce is now
// consent-shaped instead: ids we DECLARED plus our own public authored
// posts, which is exactly what the replica/durability intersection in
// `process_exchange_payload` consumes.
let post_ids = storage.list_announceable_post_ids()?;
// Knowledge boundary: a temporary referral slot carries NO knowledge // Knowledge boundary: a temporary referral slot carries NO knowledge
// exchange (design.html §connections). Peer addresses ARE knowledge — // exchange (design.html §connections). Peer addresses ARE knowledge —
// up to 10 of our mesh peers with their addresses — so they are gated // up to 10 of our mesh peers with their addresses — so they are gated
@ -8649,7 +9032,24 @@ pub async fn initial_exchange_accept(
let profile = storage.get_profile(our_node_id)? let profile = storage.get_profile(our_node_id)?
.map(|p| p.sanitized_for_network_broadcast()); .map(|p| p.sanitized_for_network_broadcast());
let deletes = storage.list_delete_records()?; let deletes = storage.list_delete_records()?;
let post_ids = storage.list_post_ids()?; // v0.8.1 PHASE 2: the post-id announce is narrowed, not gated.
//
// It used to be `list_post_ids()` — the node's COMPLETE, uncapped
// corpus, INCLUDING non-public rows, shipped to every peer that dialled
// us. A peer who knew a private post's id learned we were in its
// audience, which is the one thing the declaration paths are careful
// never to say, and it is a far larger enumeration surface than the
// 5-per-file holder lists Phase 2 locked down.
//
// It is NOT gated on `carry_knowledge`: that flag is `slot.is_mesh()`,
// and the anchor refuse-mesh path keeps clients as SESSIONS
// (bugs-fixed #6), so gating it would silently drop anchors out of
// every NAT'd client's `post_replicas` — the cheapest and most
// reachable blob source in the cascade. What we announce is now
// consent-shaped instead: ids we DECLARED plus our own public authored
// posts, which is exactly what the replica/durability intersection in
// `process_exchange_payload` consumes.
let post_ids = storage.list_announceable_post_ids()?;
// Knowledge boundary: a temporary referral slot carries NO knowledge // Knowledge boundary: a temporary referral slot carries NO knowledge
// exchange (design.html §connections). Peer addresses ARE knowledge — // exchange (design.html §connections). Peer addresses ARE knowledge —
// up to 10 of our mesh peers with their addresses — so they are gated // up to 10 of our mesh peers with their addresses — so they are gated
@ -8753,6 +9153,11 @@ async fn process_exchange_payload(
} }
} }
// Replica index from the peer's corpus announce. Symmetric with the send
// side, which is now narrowed rather than gated (see
// `initial_exchange_connect`): a session peer — notably an anchor that
// refused mesh — must still land in `post_replicas`, because it is the
// cheapest blob source a NAT'd client has.
let our_post_ids: HashSet<[u8; 32]> = storage.list_post_ids()?.into_iter().collect(); let our_post_ids: HashSet<[u8; 32]> = storage.list_post_ids()?.into_iter().collect();
for pid in &payload.post_ids { for pid in &payload.post_ids {
if our_post_ids.contains(pid) { if our_post_ids.contains(pid) {
@ -9649,6 +10054,80 @@ fn append_comment_slots(
} }
} }
#[cfg(test)]
mod redirect_tests {
//! v0.8.1 PHASE 2: the declared-holder REDIRECT list — the only thing a
//! node can hand a requester it cannot serve. This is the path that was
//! previously attached to the `found: true` arm alone, which made it (and
//! the introducer with it) unreachable in production.
use super::declared_redirects;
use crate::storage::{HolderDirection, Storage};
use crate::types::{NodeId, RedirectIntroducer};
fn temp_storage() -> Storage {
Storage::open(":memory:").unwrap()
}
fn nid(b: u8) -> NodeId {
NodeId::from([b; 32])
}
#[test]
fn a_node_that_cannot_serve_hands_back_declared_holders_only() {
let s = temp_storage();
let cid = [7u8; 32];
let requester = nid(1);
let hinted = nid(2);
let declared = nid(3);
// We never had the bytes; we only know who has talked to us about it.
s.touch_file_holder(&cid, &hinted, &["198.51.100.2:4433".to_string()],
HolderDirection::Received).unwrap();
// ...and one peer that actually consented to be advertised.
s.record_declared_holder(&cid, &declared, &["198.51.100.3:4433".to_string()],
HolderDirection::Sent, None).unwrap();
let out = declared_redirects(&s, &cid, &requester);
assert_eq!(out.len(), 1, "a hint must never become a redirect candidate");
assert_eq!(out[0].n, hex::encode(declared));
assert_eq!(out[0].a, vec!["198.51.100.3:4433".to_string()]);
assert!(out[0].x.is_none());
}
#[test]
fn the_requester_is_never_redirected_to_itself() {
let s = temp_storage();
let cid = [7u8; 32];
let requester = nid(1);
s.record_declared_holder(&cid, &requester, &[], HolderDirection::Sent, None).unwrap();
assert!(declared_redirects(&s, &cid, &requester).is_empty());
}
#[test]
fn an_introducer_rides_the_redirect_instead_of_the_holder_address() {
let s = temp_storage();
let cid = [7u8; 32];
let holder = nid(4);
let intro = RedirectIntroducer {
n: hex::encode(nid(9)),
a: vec!["203.0.113.9:4433".to_string()],
};
s.record_declared_holder(&cid, &holder, &[], HolderDirection::Sent, Some(&intro)).unwrap();
let out = declared_redirects(&s, &cid, &nid(1));
assert_eq!(out.len(), 1);
assert!(out[0].a.is_empty(), "introducer mode must not publish the holder's address");
assert_eq!(out[0].x.as_ref().unwrap().a, vec!["203.0.113.9:4433".to_string()]);
}
#[test]
fn there_is_nothing_to_redirect_to_when_nobody_declared() {
let s = temp_storage();
let cid = [7u8; 32];
s.touch_file_holder(&cid, &nid(2), &[], HolderDirection::Received).unwrap();
s.touch_file_holder(&cid, &nid(3), &[], HolderDirection::Sent).unwrap();
assert!(declared_redirects(&s, &cid, &nid(1)).is_empty());
}
}
#[cfg(test)] #[cfg(test)]
mod accept_gate_tests { mod accept_gate_tests {
//! v0.8 (A3) T9: the accept-gate matrix, exercised BOTH through the //! v0.8 (A3) T9: the accept-gate matrix, exercised BOTH through the

View file

@ -1705,7 +1705,7 @@ mod tests {
fn test_manifest_carries_no_addresses() { fn test_manifest_carries_no_addresses() {
use crate::types::{AuthorManifest, CdnManifest, ManifestEntry}; use crate::types::{AuthorManifest, CdnManifest, ManifestEntry};
let (seed, node_id) = make_keypair(1); let (seed, node_id) = make_keypair(1);
let (_hseed, host_id) = make_keypair(2); let (_hseed, _host_id) = make_keypair(2);
let mut manifest = AuthorManifest { let mut manifest = AuthorManifest {
post_id: [42u8; 32], post_id: [42u8; 32],
@ -1731,7 +1731,6 @@ mod tests {
let cdn = CdnManifest { let cdn = CdnManifest {
author_manifest: manifest, author_manifest: manifest,
host: host_id,
}; };
let cdn_json = serde_json::to_string(&cdn).unwrap(); let cdn_json = serde_json::to_string(&cdn).unwrap();
assert!( assert!(

282
crates/core/src/holdings.rs Normal file
View file

@ -0,0 +1,282 @@
//! Declared holdings — the consent layer between "this node has the bytes"
//! and "this node may be advertised to third parties as a source for them".
//!
//! # Why this exists
//!
//! Until v0.8.1 holdings were **inferred from transport**: every receive path
//! called `touch_file_holder(sender, Received)`, and the resulting rows went
//! straight back out on the wire as `BlobResponsePayload.cdn_redirect_peers`
//! and as worm-lookup holder answers. Merely exchanging bytes with a peer
//! enrolled your node id *and addresses* into a list that peer republished to
//! anyone who asked.
//!
//! Two consequences, both load-bearing:
//!
//! 1. The erasure/concealment model ("hold k shards quietly, announce exactly
//! one slot") is impossible on an inferred foundation — the act of
//! acquiring a shard registers you as its holder whether you wanted to be
//! advertised or not.
//! 2. It is the enumeration surface Round 10's per-(holder, author) listing
//! cap was aimed at: an enumerator does not need to hold anything, it just
//! asks holders who else holds.
//!
//! # The split
//!
//! * **Local hint** (`file_holders.declared = 0`) — "we exchanged bytes about
//! this file with that peer." Usable locally for fetch retry, diff
//! propagation targets and manifest-refresh sources. **Never published as a
//! holder of a specific file** — no hint ever reaches `cdn_redirect_peers`,
//! a worm holder answer, an HTTP 302 or a manifest. One documented
//! exception, which is not a holder claim: `Storage::build_own_uniques`
//! announces hinted peer IDs as bare reachable node ids in the uniques
//! pools, with no file association, because the uniques index is explicitly
//! an "IDs I can help you reach" index rather than a holder list.
//! * **Declaration** (`file_holders.declared = 1`) — the peer explicitly told
//! us "I hold this and you may advertise me for it", via the holding
//! declaration message (`MessageType::PostDownstreamRegister`, 0xD3).
//! Only these may appear in an outbound holder list.
//!
//! An *undeclared* holder stays invisible but still serves a direct request it
//! receives — declaration governs advertisement, not willingness to serve.
//!
//! # What declaration does NOT hide (known limit)
//!
//! Declaration governs the per-FILE holder lists. It hides **which** and **how
//! many** of an author's posts you hold; it does not hide **that** you hold
//! some of that author's content. `Storage::build_own_uniques` puts every
//! distinct `cdn_manifests.author` and every received-comment author into our
//! bounce-1 uniques pool, which is announced to all ~20 mesh peers and is
//! deliberately interest-blind-but-complete so discovery works at all. So
//! [`SETTING_CAP_PER_AUTHOR`] caps the POST count per author, never the author
//! set — the one-shard-announcement property ("declare one slot, the other k-1
//! stay invisible") holds at file granularity only. Closing the author-level
//! surface means deriving the `authors` half of the uniques announce from
//! `declared_holdings`, which is a discovery trade Round 10 has not ruled on.
//!
//! # Our own declarations
//!
//! `declared_holdings` records what *we* have declared, so the policy below
//! can be enforced and so a declaration can be withdrawn when content is
//! deleted or evicted.
use crate::types::NodeId;
/// Setting key: declare content we received via `ReplicationRequest`.
pub const SETTING_DECLARE_CUSTODIAL: &str = "holdings.declare_custodial";
/// Setting key: declare content we fetched out of our own interest.
pub const SETTING_DECLARE_INTEREST: &str = "holdings.declare_interest";
/// Setting key: per-(us, author) cap on distinct declared posts. `0` = no cap.
pub const SETTING_CAP_PER_AUTHOR: &str = "holdings.cap_per_author";
/// Setting key: declare holdings of content WE authored. Default OFF — see
/// [`HoldingsPolicy::declare_own_authored`].
pub const SETTING_DECLARE_OWN_AUTHORED: &str = "holdings.declare_own_authored";
/// Setting key: publish an introducer's address instead of our own.
pub const SETTING_INTRODUCER_ENABLED: &str = "holdings.introducer_enabled";
/// Setting key: hex node id of the introducer to publish. Empty = auto-pick.
pub const SETTING_INTRODUCER_PEER: &str = "holdings.introducer_peer";
/// Round 10's eventual target for `cap_per_author` (1 to keep the gossip tap,
/// 2 as the ceiling). **Not** the alpha default — see [`HoldingsPolicy`].
pub const ROUND10_TARGET_CAP_PER_AUTHOR: u32 = 2;
/// How long a received declaration stays publishable without being renewed.
///
/// A declaration is soft state: the declarer's rotating re-declaration sweep
/// (`Storage::next_declarations_to_announce`) refreshes it on every content
/// sync. One that has not been renewed inside this window means the holder is
/// gone or has shed the file, and publishing it would send fetchers to a dead
/// end. Generous on purpose for the alpha — a quiet node must not vanish from
/// holder lists over a long weekend.
pub const DECLARATION_TTL_MS: u64 = 30 * 24 * 60 * 60 * 1000;
/// Most addresses a single declaration may carry (ours or an introducer's).
///
/// Every published address is fed to `EndpointAddr::with_ip_addr` by whoever
/// fetches, and MEMORY records that iroh probes every path inserted into an
/// endpoint in the background (the 22 MB/s EDM incident). An attacker-supplied,
/// third-party-republished address list must therefore be short.
pub const MAX_DECLARED_ADDRESSES: usize = 4;
/// Why a holding was declared. Governs the default policy: a custodian exists
/// *in order to* be findable, an interested holder does not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeclareReason {
/// Pushed to us by a `ReplicationRequest` — we never chose this content.
/// Being findable IS the function, so these declare by default.
Custodial,
/// We fetched it because we wanted it (follow, pull, share link). These
/// are the rows that carry the follow signal, so they declare sparingly.
Interest,
}
impl DeclareReason {
pub fn as_str(&self) -> &'static str {
match self {
DeclareReason::Custodial => "custodial",
DeclareReason::Interest => "interest",
}
}
pub fn from_str_label(s: &str) -> Self {
match s {
"custodial" => DeclareReason::Custodial,
_ => DeclareReason::Interest,
}
}
}
/// Local declaration policy. Read from `settings` on every decision (cheap —
/// three key lookups against an in-process SQLite) so a change takes effect
/// without a restart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HoldingsPolicy {
pub declare_custodial: bool,
pub declare_interest: bool,
/// Declare holdings of posts authored by one of OUR posting identities.
///
/// **Default OFF, and not a discovery knob.** A declaration is a
/// publishable "node N holds file F" claim. Made about a post we authored,
/// it publishes `device ↔ posting identity` — the exact binding that
/// Iteration A's AuthorManifest address strip and the v0.8
/// location-anonymity goal exist to prevent. Before Phase 2 the transport
/// leaked this implicitly (the author served the bytes, so every recipient
/// listed the author's device); re-creating it as a default would undo the
/// change. Authors still SERVE direct requests; third-party findability
/// comes from custodians and from interested holders, who declare.
pub declare_own_authored: bool,
/// Distinct declared posts per author. `0` = unlimited.
pub cap_per_author: u32,
}
impl Default for HoldingsPolicy {
/// **Alpha defaults are deliberately generous.** A tight cap makes content
/// unfindable, and the 4-device alpha test has no spare holder population
/// to absorb that. Both classes declare and there is no cap; the knob is
/// implemented, defaulted open, and documented. Round 10's target is
/// `cap_per_author = `[`ROUND10_TARGET_CAP_PER_AUTHOR`], to be adopted once
/// the activity digest exists to carry coverage that the cap gives up.
fn default() -> Self {
Self {
declare_custodial: true,
declare_interest: true,
declare_own_authored: false,
cap_per_author: 0,
}
}
}
impl HoldingsPolicy {
/// Is this declaration CLASS enabled? Checked separately from the cap
/// because a disabled class must refuse even a file that was declared
/// while the class was on — otherwise turning the knob off is write-only
/// for the existing footprint.
pub fn class_allows(&self, reason: DeclareReason) -> bool {
match reason {
DeclareReason::Custodial => self.declare_custodial,
DeclareReason::Interest => self.declare_interest,
}
}
/// Would this policy admit one more declaration?
///
/// `distinct_posts_for_author` counts posts of that author we have ALREADY
/// declared; `post_already_declared` is true when this declaration is for
/// one of them (a second attachment of an already-declared post), in which
/// case it does not grow the footprint and the cap must not reject it.
pub fn allows(
&self,
reason: DeclareReason,
distinct_posts_for_author: u32,
post_already_declared: bool,
) -> bool {
if !self.class_allows(reason) {
return false;
}
if post_already_declared {
return true;
}
self.cap_per_author == 0 || distinct_posts_for_author < self.cap_per_author
}
}
/// How we want to be reached for files we declare: directly, or through an
/// introducer that coordinates a hole punch.
///
/// The introducer carries **no bulk data** — it answers `RelayIntroduce`
/// (0xB0, always-on signalling) and the fetch then flows direct. This is not
/// session relay and does not touch `relay.session_relay_enabled`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeclaredReach {
/// Publish our own addresses. Empty = bare node id, the default for every
/// non-anchor (Round 10: addresses ride the wire only for anchors).
Direct(Vec<String>),
/// Publish the introducer's address instead of ours.
ViaIntroducer { node_id: NodeId, addresses: Vec<String> },
}
impl DeclaredReach {
/// Split into the `(addresses, introducer)` pair the wire payload carries.
pub fn into_payload_parts(
self,
) -> (Vec<String>, Option<crate::types::RedirectIntroducer>) {
match self {
DeclaredReach::Direct(addrs) => (addrs, None),
DeclaredReach::ViaIntroducer { node_id, addresses } => (
Vec::new(),
Some(crate::types::RedirectIntroducer {
n: hex::encode(node_id),
a: addresses,
}),
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alpha_defaults_declare_everything_uncapped() {
let p = HoldingsPolicy::default();
assert!(p.allows(DeclareReason::Custodial, 10_000, false));
assert!(p.allows(DeclareReason::Interest, 10_000, false));
assert!(
!p.declare_own_authored,
"declaring our own posts would republish device <-> persona"
);
}
#[test]
fn cap_bites_only_on_new_posts() {
let p = HoldingsPolicy {
cap_per_author: ROUND10_TARGET_CAP_PER_AUTHOR,
..HoldingsPolicy::default()
};
assert!(p.allows(DeclareReason::Interest, 0, false));
assert!(p.allows(DeclareReason::Interest, 1, false));
// At the cap a NEW post is refused...
assert!(!p.allows(DeclareReason::Interest, 2, false));
// ...but another file of an already-declared post is not a new listing.
assert!(p.allows(DeclareReason::Interest, 2, true));
}
#[test]
fn class_switch_overrides_cap() {
let p = HoldingsPolicy {
declare_interest: false,
..HoldingsPolicy::default()
};
assert!(p.allows(DeclareReason::Custodial, 500, false));
assert!(!p.allows(DeclareReason::Interest, 0, false));
// A disabled class is disabled even for an already-declared post.
assert!(!p.allows(DeclareReason::Interest, 0, true));
}
#[test]
fn reason_label_roundtrip() {
for r in [DeclareReason::Custodial, DeclareReason::Interest] {
assert_eq!(DeclareReason::from_str_label(r.as_str()), r);
}
}
}

View file

@ -373,10 +373,12 @@ async fn try_redirect(
Ok(Some((_, PostVisibility::Public))) => {} Ok(Some((_, PostVisibility::Public))) => {}
_ => return false, // not found or not public — hard close _ => return false, // not found or not public — hard close
} }
store.get_file_holders(post_id) // DECLARED holders only — this builds an HTTP 302 to a third party's
// address (v0.8.1 PHASE 2).
store.get_declared_file_holders(post_id)
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(|(nid, _addrs)| nid) .map(|(nid, _addrs, _intro)| nid)
.collect::<Vec<_>>() .collect::<Vec<_>>()
}; };

View file

@ -8,6 +8,7 @@ pub mod content;
pub mod control; pub mod control;
pub mod crypto; pub mod crypto;
pub mod group_key_distribution; pub mod group_key_distribution;
pub mod holdings;
pub mod http; pub mod http;
pub mod export; pub mod export;
pub mod fof; pub mod fof;

View file

@ -1088,14 +1088,18 @@ impl Network {
}], }],
}; };
let mut sent = 0; let mut sent = 0;
for (peer, peer_addrs) in &holders { for (peer, _peer_addrs) in &holders {
if self.send_to_peer_uni(peer, MessageType::ManifestPush, &payload).await.is_ok() { if self.send_to_peer_uni(peer, MessageType::ManifestPush, &payload).await.is_ok() {
sent += 1; sent += 1;
let storage = self.storage.get().await; let storage = self.storage.get().await;
// Bump the hint's recency only. Writing the addresses back
// kept inferred reach alive indefinitely; a declaration is the
// only thing allowed to set a holder's published addresses
// (v0.8.1).
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
cid, cid,
peer, peer,
peer_addrs, &[],
crate::storage::HolderDirection::Sent, crate::storage::HolderDirection::Sent,
); );
} }
@ -1801,10 +1805,7 @@ impl Network {
write_typed_message( write_typed_message(
&mut send, &mut send,
MessageType::BlobRequest, MessageType::BlobRequest,
&BlobRequestPayload { &BlobRequestPayload { cid: *cid },
cid: *cid,
requester_addresses: self.our_addresses(),
},
) )
.await?; .await?;
send.finish()?; send.finish()?;
@ -1954,6 +1955,147 @@ impl Network {
) )
} }
/// Connect to a DECLARED holder using the addresses it published in its
/// holding declaration, and register the result as a session.
///
/// Deliberately does NOT write those addresses into the `peers` table: the
/// declaration is scoped to the files it covered, whereas a `peers` row is
/// a general routing fact. Keeping it ephemeral also keeps the
/// "addresses ride only for anchors" storage shape intact.
pub async fn connect_declared_holder(
&self,
peer: &NodeId,
addrs: &[String],
) -> anyhow::Result<()> {
if self.conn_handle.get_any_connection(peer).await.is_some() {
return Ok(());
}
let endpoint_id = iroh::EndpointId::from_bytes(peer)?;
let mut ep_addr = iroh::EndpointAddr::from(endpoint_id);
// Cap the address list regardless of what arrived: every address here
// is inserted into an iroh `EndpointAddr`, and iroh probes every path
// it has been given in the background (the 22 MB/s EDM incident). These
// addresses came off the wire from a third party, so the cap is the
// defence, not the sender's good manners.
let mut any = false;
for a in addrs.iter().take(crate::holdings::MAX_DECLARED_ADDRESSES) {
if let Ok(sa) = a.parse::<std::net::SocketAddr>() {
let sa = crate::connection::normalize_addr(sa);
if is_publicly_routable(&sa) {
ep_addr = ep_addr.with_ip_addr(sa);
any = true;
}
}
}
if !any {
anyhow::bail!("declared holder published no routable address");
}
let conn = crate::connection::ConnectionManager::connect_to_unlocked(&self.endpoint, ep_addr).await?;
self.conn_handle
.add_session(*peer, conn, SessionReachMethod::Direct, None)
.await;
Ok(())
}
/// Ask an INTRODUCER nominated by a declared holder to coordinate a hole
/// punch to that holder, then hole-punch directly.
///
/// Uses `RelayIntroduce`/`RelayIntroduceResult` (0xB0/0xB1), which are
/// always-on signalling. **No file bytes ever traverse the introducer** —
/// the caller fetches directly afterwards. This is therefore not session
/// relay and does not consult `relay.session_relay_enabled`.
pub async fn introduce_via_address(
&self,
introducer: &crate::types::RedirectIntroducer,
target: &NodeId,
) -> anyhow::Result<()> {
if self.conn_handle.get_any_connection(target).await.is_some() {
return Ok(());
}
let intro_id_bytes = hex::decode(&introducer.n)?;
let intro_nid: NodeId = intro_id_bytes.as_slice().try_into()
.map_err(|_| anyhow::anyhow!("bad introducer node id"))?;
// Reuse an existing connection to the introducer if we have one,
// otherwise connect to the address it published.
let conn = match self.conn_handle.get_any_connection(&intro_nid).await {
Some(c) => c,
None => {
let endpoint_id = iroh::EndpointId::from_bytes(&intro_nid)?;
let mut ep_addr = iroh::EndpointAddr::from(endpoint_id);
// Same cap and normalisation as `connect_declared_holder`.
let mut any = false;
for a in introducer.a.iter().take(crate::holdings::MAX_DECLARED_ADDRESSES) {
if let Ok(sa) = a.parse::<std::net::SocketAddr>() {
let sa = crate::connection::normalize_addr(sa);
if is_publicly_routable(&sa) {
ep_addr = ep_addr.with_ip_addr(sa);
any = true;
}
}
}
if !any {
anyhow::bail!("introducer published no routable address");
}
crate::connection::ConnectionManager::connect_to_unlocked(&self.endpoint, ep_addr).await?
}
};
let intro_id: crate::connection::IntroId = rand::random();
let mut our_addrs: Vec<String> = self.endpoint.addr().ip_addrs()
.filter(|s| is_publicly_routable(s))
.map(|s| s.to_string())
.collect();
if let Some(ref mapping) = self.upnp_mapping {
let ext_str = mapping.external_addr.to_string();
if !our_addrs.contains(&ext_str) {
our_addrs.insert(0, ext_str);
}
}
let our_profile = self.conn_handle.our_nat_profile().await;
let payload = crate::protocol::RelayIntroducePayload {
intro_id,
target: *target,
requester: self.our_node_id,
requester_addresses: our_addrs,
ttl: 1,
nat_mapping: Some(our_profile.mapping.to_string()),
nat_filtering: Some(our_profile.filtering.to_string()),
};
let (mut send, mut recv) = conn.open_bi().await?;
write_typed_message(&mut send, MessageType::RelayIntroduce, &payload).await?;
send.finish()?;
let msg_type = read_message_type(&mut recv).await?;
if msg_type != MessageType::RelayIntroduceResult {
anyhow::bail!("expected RelayIntroduceResult, got {:?}", msg_type);
}
let result: crate::protocol::RelayIntroduceResultPayload =
read_payload(&mut recv, 64 * 1024).await?;
if !result.accepted {
anyhow::bail!("introducer refused: {:?}", result.reject_reason);
}
// The holder may have connected to us while the intro was in flight.
if self.conn_handle.get_any_connection(target).await.is_some() {
return Ok(());
}
let peer_profile = {
let s = self.storage.get().await;
s.get_peer_nat_profile(target)
};
let punched = crate::connection::hole_punch_with_scanning(
&self.endpoint, target, &result.target_addresses, our_profile, peer_profile,
).await;
match punched {
Some(c) => {
self.conn_handle
.add_session(*target, c, SessionReachMethod::HolePunch, None)
.await;
Ok(())
}
None => anyhow::bail!("hole punch to declared holder failed"),
}
}
/// Build an EndpointAddr for a peer using stored addresses from the DB. /// Build an EndpointAddr for a peer using stored addresses from the DB.
pub async fn addr_from_storage(&self, peer_id: &NodeId) -> Option<iroh::EndpointAddr> { pub async fn addr_from_storage(&self, peer_id: &NodeId) -> Option<iroh::EndpointAddr> {
let endpoint_id = iroh::EndpointId::from_bytes(peer_id).ok()?; let endpoint_id = iroh::EndpointId::from_bytes(peer_id).ok()?;

View file

@ -1883,9 +1883,9 @@ impl Node {
if let Ok(author_manifest) = serde_json::from_str::<crate::types::AuthorManifest>(push_json) { if let Ok(author_manifest) = serde_json::from_str::<crate::types::AuthorManifest>(push_json) {
// v0.8: no device addresses ride the manifest — receivers // v0.8: no device addresses ride the manifest — receivers
// learn the holder from the QUIC-authenticated connection. // learn the holder from the QUIC-authenticated connection.
// v0.8.1: and no host id either — see `CdnManifest`.
let cdn_manifest = crate::types::CdnManifest { let cdn_manifest = crate::types::CdnManifest {
author_manifest, author_manifest,
host: self.node_id,
}; };
self.network.push_manifest_to_downstream(push_cid, &cdn_manifest).await; self.network.push_manifest_to_downstream(push_cid, &cdn_manifest).await;
} }
@ -2775,19 +2775,82 @@ impl Node {
} }
} }
// Record upstream source. v0.8: manifests carry no addresses; // LOCAL HINT for the source (v0.8.1 PHASE 2): having served us a
// the holder's address is already known from the live connection // blob is not consent to be advertised as its holder. Hints drive
// (peers table) — record the holder id with no manifest addrs. // our own retry/propagation only.
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
cid, cid,
from_peer, from_peer,
&[], &[],
crate::storage::HolderDirection::Received, crate::storage::HolderDirection::Received,
); );
drop(storage);
self.declare_blob_holding(cid, post_id, author, from_peer).await;
} }
Ok(data) Ok(data)
} }
/// Declare a blob we now hold to the peer we got it from, if the local
/// policy admits it (`crate::holdings`). Silent no-op when it does not —
/// an undeclared holding still serves direct requests, it just never
/// appears in anyone's publishable holder list.
async fn declare_blob_holding(
&self,
cid: &[u8; 32],
post_id: &PostId,
author: &NodeId,
to_peer: &NodeId,
) {
// POLICY FIRST, then the connection-actor round-trips. Resolving the
// anchor address and the connected-peer set costs two actor round-trips
// each time a blob lands, and they are only needed if we are actually
// going to declare — so the cheap local decision runs first.
{
let storage = self.storage.get().await;
// Private content is never declared: advertising yourself as a
// holder of a DM / group / FoFClosed post announces audience
// membership. No local post row yet (blob-first fetch) means we
// cannot tell, so we do not declare speculatively; the post path
// declares once it lands.
match storage.get_post_with_visibility(post_id) {
Ok(Some((_, crate::types::PostVisibility::Public))) => {}
_ => return,
}
if !storage.would_declare_own_holding(
cid, post_id, author, crate::holdings::DeclareReason::Interest,
).unwrap_or(false) {
return;
}
}
// Awaiting the connection actor while holding a storage guard is the
// shape behind this project's recorded lock-contention bugs, so both
// round-trips happen with no guard held.
let anchor_addr = self.network.conn_handle().build_anchor_advertised_addr().await;
let connected = self.network.conn_handle().connected_peers().await;
let reach = {
let storage = self.storage.get().await;
if !storage.declare_own_holding(
cid, post_id, author, crate::holdings::DeclareReason::Interest,
).unwrap_or(false) {
return;
}
storage.build_declaration_reach(anchor_addr.as_deref(), &connected)
};
let (addresses, introducer) = reach.into_payload_parts();
let payload = crate::protocol::PostDownstreamRegisterPayload {
post_id: *cid,
extra_file_ids: Vec::new(),
addresses,
introducer,
withdraw: false,
};
let _ = self.network.send_to_peer_uni(
to_peer,
crate::protocol::MessageType::PostDownstreamRegister,
&payload,
).await;
}
/// Fetch a blob with CDN-aware cascade, preferring non-anchor sources to save anchor /// Fetch a blob with CDN-aware cascade, preferring non-anchor sources to save anchor
/// delivery budget: /// delivery budget:
/// 1. Local → 2. Existing upstream → 3. Lateral peers (non-anchor first) /// 1. Local → 2. Existing upstream → 3. Lateral peers (non-anchor first)
@ -2809,7 +2872,7 @@ impl Node {
} }
// Collect redirect peers from responses in case we need them later // Collect redirect peers from responses in case we need them later
let mut redirect_peers: Vec<crate::types::PeerWithAddress> = Vec::new(); let mut redirect_peers: Vec<crate::types::CdnRedirectPeer> = Vec::new();
// 2. Try known holders (up to 5 most-recent peers we've interacted // 2. Try known holders (up to 5 most-recent peers we've interacted
// with about this file). // with about this file).
@ -2846,12 +2909,15 @@ impl Node {
let _ = storage.store_cdn_manifest(cid, &author_json, &cdn_manifest.author_manifest.author, cdn_manifest.author_manifest.updated_at); let _ = storage.store_cdn_manifest(cid, &author_json, &cdn_manifest.author_manifest.author, cdn_manifest.author_manifest.updated_at);
} }
} }
// LOCAL HINT (v0.8.1) — see fetch_blob_from_peer.
let _ = storage.touch_file_holder( let _ = storage.touch_file_holder(
cid, cid,
&lateral, &lateral,
&[], &[],
crate::storage::HolderDirection::Received, crate::storage::HolderDirection::Received,
); );
drop(storage);
self.declare_blob_holding(cid, post_id, author, &lateral).await;
return Ok(Some(data)); return Ok(Some(data));
} }
Ok((None, response)) => { Ok((None, response)) => {
@ -2881,20 +2947,193 @@ impl Node {
Err(e) => warn!(error = %e, "blob fetch from author failed"), Err(e) => warn!(error = %e, "blob fetch from author failed"),
} }
// 6. Try redirect peers (from any step that returned cdn_redirect_peers) // 6. Try redirect peers (from any step that returned cdn_redirect_peers).
// These are DECLARED holders only (v0.8.1 PHASE 2).
for rp in &redirect_peers { for rp in &redirect_peers {
if let Ok(nid_bytes) = hex::decode(&rp.n) { let Ok(nid_bytes) = hex::decode(&rp.n) else { continue };
if let Ok(nid) = <[u8; 32]>::try_from(nid_bytes.as_slice()) { let Ok(nid) = <[u8; 32]>::try_from(nid_bytes.as_slice()) else { continue };
// If the holder published an INTRODUCER instead of its own address,
// ask the introducer to coordinate a hole punch first. The
// introducer carries no blob bytes — the fetch below is direct —
// so this is signalling, not session relay.
if let Some(ref intro) = rp.x {
if let Err(e) = self.network.introduce_via_address(intro, &nid).await {
debug!(holder = &rp.n, introducer = &intro.n, error = %e,
"introducer hole-punch coordination failed");
}
} else if !rp.a.is_empty() {
// The holder published its own address (anchor carve-out). Use
// it for an ephemeral session WITHOUT persisting it as a
// general routing fact — the consent was file-scoped.
if let Err(e) = self.network.connect_declared_holder(&nid, &rp.a).await {
debug!(holder = &rp.n, error = %e, "declared-holder direct connect failed");
}
}
match self.fetch_blob_from_peer(cid, &nid, post_id, author, mime_type, created_at).await { match self.fetch_blob_from_peer(cid, &nid, post_id, author, mime_type, created_at).await {
Ok(Some(data)) => return Ok(Some(data)), Ok(Some(data)) => return Ok(Some(data)),
Ok(None) => {} Ok(None) => {}
Err(e) => warn!(peer = &rp.n, error = %e, "redirect blob fetch failed"), Err(e) => warn!(peer = &rp.n, error = %e, "redirect blob fetch failed"),
} }
} }
Ok(None)
}
// ---- Declared holdings policy (crate::holdings) ----
/// Current local declaration policy.
pub async fn holdings_policy(&self) -> crate::holdings::HoldingsPolicy {
self.storage.get().await.holdings_policy()
}
/// Per-(us, author) cap on distinct declared posts. `0` disables the cap.
///
/// ALPHA DEFAULT IS 0 (uncapped) on purpose: a tight cap makes content
/// unfindable, and there is no spare holder population to absorb that yet.
/// Round 10's target is 2.
///
/// RETROACTIVE: lowering the cap prunes the declarations it no longer
/// admits (keeping the most recent N per author) and withdraws them from
/// the peers publishing us. Without that the generous alpha footprint would
/// be permanent — the knob would only ever stop NEW declarations.
pub async fn set_holdings_cap_per_author(&self, cap: u32) -> anyhow::Result<()> {
{
let s = self.storage.get().await;
s.set_setting(crate::holdings::SETTING_CAP_PER_AUTHOR, &cap.to_string())?;
s.prune_declarations_for_policy()?;
}
self.drain_declaration_withdrawals().await;
Ok(())
}
/// Enable/disable declaring a whole class of holdings. Retroactive — see
/// [`Node::set_holdings_cap_per_author`].
pub async fn set_holdings_declare_class(
&self,
reason: crate::holdings::DeclareReason,
enabled: bool,
) -> anyhow::Result<()> {
let key = match reason {
crate::holdings::DeclareReason::Custodial => crate::holdings::SETTING_DECLARE_CUSTODIAL,
crate::holdings::DeclareReason::Interest => crate::holdings::SETTING_DECLARE_INTEREST,
};
{
let s = self.storage.get().await;
s.set_setting(key, if enabled { "true" } else { "false" })?;
s.prune_declarations_for_policy()?;
}
self.drain_declaration_withdrawals().await;
Ok(())
}
/// Declare holdings of content WE authored. Default OFF — enabling it
/// publishes `device <-> posting identity` in third-party holder lists.
/// Retroactive — see [`Node::set_holdings_cap_per_author`].
pub async fn set_holdings_declare_own_authored(&self, enabled: bool) -> anyhow::Result<()> {
{
let s = self.storage.get().await;
s.set_setting(
crate::holdings::SETTING_DECLARE_OWN_AUTHORED,
if enabled { "true" } else { "false" },
)?;
s.prune_declarations_for_policy()?;
}
self.drain_declaration_withdrawals().await;
Ok(())
}
/// Publish an introducer's address in place of our own in holding
/// declarations. Default OFF. `peer = None` auto-picks a connected anchor.
///
/// This is NOT session relay: the introducer only answers `RelayIntroduce`
/// and never carries file bytes.
pub async fn set_holdings_introducer(
&self,
enabled: bool,
peer: Option<NodeId>,
) -> anyhow::Result<()> {
let s = self.storage.get().await;
s.set_setting(
crate::holdings::SETTING_INTRODUCER_ENABLED,
if enabled { "true" } else { "false" },
)?;
s.set_setting(
crate::holdings::SETTING_INTRODUCER_PEER,
&peer.map(hex::encode).unwrap_or_default(),
)?;
Ok(())
}
/// Send the `withdraw: true` declarations that storage has queued.
///
/// Every path that retracts one of our declarations — signed delete, post
/// removal, blob eviction, a policy change — queues one row per peer that
/// may be publishing us, because those paths are synchronous storage code
/// and cannot send. A stale declaration is worse than none: it sends
/// fetchers to a node that no longer serves the file and, under the erasure
/// model, misreports slot health.
pub async fn drain_declaration_withdrawals(&self) {
let queued = {
let s = self.storage.get().await;
s.take_pending_withdrawals(256).unwrap_or_default()
};
for (file_id, peer) in queued {
let payload = crate::protocol::PostDownstreamRegisterPayload {
post_id: file_id,
extra_file_ids: Vec::new(),
addresses: Vec::new(),
introducer: None,
withdraw: true,
};
let _ = self.network.send_to_peer_uni(
&peer,
crate::protocol::MessageType::PostDownstreamRegister,
&payload,
).await;
} }
} }
Ok(None) /// Re-declare the content we already hold, through the ordinary policy
/// chokepoint, and announce the result to every connected peer.
///
/// Runs once at startup. This is what makes the Phase 2 migration ruling
/// survivable: all legacy `file_holders` rows became undeclared hints and
/// `declared_holdings` starts empty, so without this an upgrading node's
/// entire pre-existing corpus could never be named as held by anyone.
pub async fn backfill_declared_holdings(&self) {
let admitted = {
let s = self.storage.get().await;
s.backfill_declared_holdings(2_000).unwrap_or_default()
};
if admitted.is_empty() {
return;
}
info!(files = admitted.len(), "Declared-holdings backfill admitted files");
// The rotating per-peer sweep in `content_sync_unlocked` carries these
// out to peers as sync cycles run, so nothing is announced here — that
// keeps one mechanism responsible for announcement.
}
/// Human-readable policy + current footprint, for the CLI.
pub async fn holdings_summary(&self) -> String {
let connected = self.network.conn_handle().connected_peers().await;
let s = self.storage.get().await;
let p = s.holdings_policy();
let intro = s.resolve_declared_introducer(&connected);
let total = s.count_declared_holdings().unwrap_or(0);
let authors = s.count_declared_authors().unwrap_or(0);
format!(
"declare_custodial={} declare_interest={} declare_own_authored={} \
cap_per_author={} introducer={}\n\
declared: {} files across {} authors",
p.declare_custodial,
p.declare_interest,
p.declare_own_authored,
if p.cap_per_author == 0 { "unlimited".to_string() } else { p.cap_per_author.to_string() },
intro.map(|i| i.n).unwrap_or_else(|| "off".to_string()),
total,
authors,
)
} }
// ---- Circles ---- // ---- Circles ----
@ -4934,14 +5173,23 @@ impl Node {
/// Delete a blob locally. BlobDeleteNotice was removed in v0.6.2; remote /// Delete a blob locally. BlobDeleteNotice was removed in v0.6.2; remote
/// holders notice eviction via their own LRU / replica-miss handling. /// holders notice eviction via their own LRU / replica-miss handling.
///
/// v0.8.1 PHASE 2: if we had DECLARED this blob, withdraw the declaration
/// from the peers that may be publishing us for it. A stale declaration is
/// worse than none — it sends fetchers to a node that no longer serves the
/// file, and (under the erasure model) misreports slot health.
pub async fn delete_blob_local(&self, cid: &[u8; 32]) -> anyhow::Result<()> { pub async fn delete_blob_local(&self, cid: &[u8; 32]) -> anyhow::Result<()> {
{ {
let storage = self.storage.get().await; let storage = self.storage.get().await;
// `cleanup_cdn_for_blob` -> `undeclare_own_holding` queues a
// withdrawal for every peer that may be publishing us, so the
// retraction is symmetric with the declaration and goes through the
// same mechanism as a signed delete or a policy change.
storage.cleanup_cdn_for_blob(cid)?; storage.cleanup_cdn_for_blob(cid)?;
storage.remove_blob(cid)?; storage.remove_blob(cid)?;
} }
let _ = self.blob_store.delete(cid); let _ = self.blob_store.delete(cid);
self.drain_declaration_withdrawals().await;
Ok(()) Ok(())
} }
@ -6436,11 +6684,53 @@ impl Node {
for holder in holders { for holder in holders {
let _ = self.connect_by_node_id(holder).await; let _ = self.connect_by_node_id(holder).await;
if let Ok(Some(sp)) = self.network.post_fetch(&holder, post_id).await { if let Ok(Some(sp)) = self.network.post_fetch(&holder, post_id).await {
// Actor round-trips before the storage guard — see
// declare_blob_holding.
let anchor_addr = self.network.conn_handle()
.build_anchor_advertised_addr().await;
let connected = self.network.conn_handle().connected_peers().await;
let (post, declaration) = {
let s = self.storage.get().await; let s = self.storage.get().await;
let _ = crate::control::receive_post( let _ = crate::control::receive_post(
&s, &sp.id, &sp.post, &sp.visibility, sp.intent.as_ref(), &s, &sp.id, &sp.post, &sp.visibility, sp.intent.as_ref(),
); );
return Ok(s.get_post(post_id)?); // LOCAL HINT for the holder that served us (v0.8.1).
let _ = s.touch_file_holder(
&sp.id, &holder, &[],
crate::storage::HolderDirection::Received,
);
// Declare OUR new holding, policy permitting. Public
// only, and never our own authored content — the policy
// chokepoint in `declare_own_holding` enforces both.
let declaration = if matches!(sp.visibility, crate::types::PostVisibility::Public)
&& s.declare_own_holding(
&sp.id, &sp.id, &sp.post.author,
crate::holdings::DeclareReason::Interest,
).unwrap_or(false)
{
let (addresses, introducer) = s
.build_declaration_reach(anchor_addr.as_deref(), &connected)
.into_payload_parts();
Some(crate::protocol::PostDownstreamRegisterPayload {
post_id: sp.id,
extra_file_ids: Vec::new(),
addresses,
introducer,
withdraw: false,
})
} else {
None
};
(s.get_post(post_id)?, declaration)
};
if let Some(reg) = declaration {
let _ = self.network.send_to_peer_uni(
&holder,
crate::protocol::MessageType::PostDownstreamRegister,
&reg,
).await;
}
return Ok(post);
} }
} }
} }
@ -7093,11 +7383,20 @@ impl Node {
pub fn start_replication_cycle(self: &Arc<Self>, interval_secs: u64) -> tokio::task::JoinHandle<()> { pub fn start_replication_cycle(self: &Arc<Self>, interval_secs: u64) -> tokio::task::JoinHandle<()> {
let node = Arc::clone(self); let node = Arc::clone(self);
tokio::spawn(async move { tokio::spawn(async move {
// v0.8.1 PHASE 2: re-declare what we already hold before anything
// else. On an upgraded database every legacy holder row became an
// undeclared hint and `declared_holdings` starts empty, so without
// this the node's whole pre-existing corpus would be unnameable by
// any peer. Idempotent, so running it on every start is harmless.
node.backfill_declared_holdings().await;
// Wait 2 minutes before first cycle (let connections establish) // Wait 2 minutes before first cycle (let connections establish)
tokio::time::sleep(std::time::Duration::from_secs(120)).await; tokio::time::sleep(std::time::Duration::from_secs(120)).await;
let mut interval = tokio::time::interval(std::time::Duration::from_secs(interval_secs)); let mut interval = tokio::time::interval(std::time::Duration::from_secs(interval_secs));
loop { loop {
interval.tick().await; interval.tick().await;
// Retractions queued by synchronous storage paths (signed
// delete, eviction, policy change) go out here.
node.drain_declaration_withdrawals().await;
node.run_replication_check().await; node.run_replication_check().await;
} }
}) })
@ -7149,10 +7448,17 @@ impl Node {
} }
} }
// Filter to under-replicated (< 2 holders) // Filter to under-replicated (< 2 holders).
//
// v0.8.1: EVIDENCED holders only. Counting declarations here would
// let five Sybil identities declare an author's post and silently
// stop the author replicating it — the data-availability attack the
// erasure study rules against ("verify claimed holders by RESPONSE,
// not claim"). Erring toward over-replication is the safe direction
// for durability.
let mut needs_replication = Vec::new(); let mut needs_replication = Vec::new();
for pid in &recent_ids { for pid in &recent_ids {
match storage.get_file_holder_count(pid) { match storage.get_durability_holder_count(pid) {
Ok(count) if count < 2 => { Ok(count) if count < 2 => {
needs_replication.push(*pid); needs_replication.push(*pid);
} }

View file

@ -2,7 +2,8 @@ use serde::{Deserialize, Serialize};
use crate::types::{ use crate::types::{
BlobHeaderDiffOp, CdnManifest, DeleteRecord, GroupEpoch, GroupId, NodeId, BlobHeaderDiffOp, CdnManifest, DeleteRecord, GroupEpoch, GroupId, NodeId,
PeerWithAddress, Post, PostId, PostVisibility, PublicProfile, WormId, CdnRedirectPeer, PeerWithAddress, Post, PostId, PostVisibility, PublicProfile,
RedirectIntroducer, WormId,
}; };
/// Wire-protocol ALPN. One protocol version per build, no negotiation — /// Wire-protocol ALPN. One protocol version per build, no negotiation —
@ -432,11 +433,13 @@ pub struct SocialCheckinPayload {
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct BlobRequestPayload { pub struct BlobRequestPayload {
pub cid: [u8; 32], pub cid: [u8; 32],
/// Requester's addresses so the host can record downstream
pub requester_addresses: Vec<String>,
} }
/// Blob response: found flag + base64-encoded data + CDN manifest /// Blob response: found flag + base64-encoded data + CDN manifest
///
/// v0.8.1 PHASE 2: `cdn_registered` is gone. It reported whether the host had
/// silently enrolled the requester as a downstream holder, which is exactly
/// the inference this phase removed, and nothing ever read it.
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct BlobResponsePayload { pub struct BlobResponsePayload {
pub cid: [u8; 32], pub cid: [u8; 32],
@ -445,10 +448,9 @@ pub struct BlobResponsePayload {
pub data_b64: String, pub data_b64: String,
/// Author manifest + host info (if available) /// Author manifest + host info (if available)
pub manifest: Option<CdnManifest>, pub manifest: Option<CdnManifest>,
/// Whether host accepted requester as downstream /// Other DECLARED holders of this CID to try. Only peers that explicitly
pub cdn_registered: bool, /// declared themselves appear here (`crate::holdings`).
/// If not registered (host full), try these peers pub cdn_redirect_peers: Vec<CdnRedirectPeer>,
pub cdn_redirect_peers: Vec<PeerWithAddress>,
} }
/// Request a manifest refresh for a CID (bi-stream: ask upstream) /// Request a manifest refresh for a CID (bi-stream: ask upstream)
@ -685,10 +687,35 @@ pub struct BlobHeaderResponsePayload {
pub header_json: Option<String>, pub header_json: Option<String>,
} }
/// Register as a downstream holder of a post (uni-stream) /// **Holding declaration** (uni-stream, 0xD3).
///
/// v0.8.1 PHASE 2: this is the one explicit channel by which a node enters
/// another node's publishable holder list. Semantics: "I hold these files and
/// you may advertise me as a source for them." Idempotent and soft — it is
/// re-sent on each content-sync cycle and ages out through the `file_holders`
/// LRU, so declarations self-heal rather than needing durable registration.
///
/// `post_id` is the primary file id (a `PostId`, or any 32-byte content
/// address); `extra_file_ids` batches the post's attachment CIDs so a declared
/// post and its blobs cost one message.
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct PostDownstreamRegisterPayload { pub struct PostDownstreamRegisterPayload {
pub post_id: PostId, pub post_id: PostId,
/// Additional 32-byte file ids covered by the same declaration.
#[serde(default)]
pub extra_file_ids: Vec<[u8; 32]>,
/// Addresses we consent to have published for these files. Empty means
/// "publish my node id only", or "reach me via `introducer`".
#[serde(default)]
pub addresses: Vec<String>,
/// Publish this introducer's address in place of ours
/// (`holdings.introducer_enabled`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub introducer: Option<RedirectIntroducer>,
/// Withdraw instead of declare: drop us from the publishable holder list
/// for these files. We may still serve a direct request.
#[serde(default)]
pub withdraw: bool,
} }
/// Request a single post by ID (bi-stream) /// Request a single post by ID (bi-stream)
@ -967,6 +994,59 @@ mod tests {
assert_eq!(decoded.updated_at, 1700000000000); assert_eq!(decoded.updated_at, 1700000000000);
} }
#[test]
fn holding_declaration_roundtrip_and_defaults() {
use crate::types::RedirectIntroducer;
let payload = PostDownstreamRegisterPayload {
post_id: [3u8; 32],
extra_file_ids: vec![[4u8; 32], [5u8; 32]],
addresses: vec!["198.51.100.1:4433".to_string()],
introducer: Some(RedirectIntroducer {
n: hex::encode([9u8; 32]),
a: vec!["203.0.113.9:4433".to_string()],
}),
withdraw: false,
};
let json = serde_json::to_string(&payload).unwrap();
let decoded: PostDownstreamRegisterPayload = serde_json::from_str(&json).unwrap();
assert_eq!(decoded.post_id, [3u8; 32]);
assert_eq!(decoded.extra_file_ids.len(), 2);
assert_eq!(decoded.addresses, vec!["198.51.100.1:4433".to_string()]);
assert_eq!(decoded.introducer.unwrap().a, vec!["203.0.113.9:4433".to_string()]);
assert!(!decoded.withdraw);
// A bare declaration (the default shape: no address, no introducer)
// must decode from the minimal form.
let minimal = format!(r#"{{"post_id":{:?}}}"#, vec![3u8; 32]);
let decoded: PostDownstreamRegisterPayload = serde_json::from_str(&minimal).unwrap();
assert!(decoded.extra_file_ids.is_empty());
assert!(decoded.addresses.is_empty());
assert!(decoded.introducer.is_none());
assert!(!decoded.withdraw);
}
#[test]
fn blob_response_has_no_registration_flag() {
// v0.8.1 PHASE 2: redirects are declared holders; there is no
// "host silently registered you" signal left on the wire.
let payload = BlobResponsePayload {
cid: [1u8; 32],
found: true,
data_b64: "AAA=".to_string(),
manifest: None,
cdn_redirect_peers: vec![CdnRedirectPeer {
n: hex::encode([2u8; 32]),
a: vec![],
x: None,
}],
};
let json = serde_json::to_string(&payload).unwrap();
assert!(!json.contains("cdn_registered"));
let decoded: BlobResponsePayload = serde_json::from_str(&json).unwrap();
assert_eq!(decoded.cdn_redirect_peers.len(), 1);
assert!(decoded.cdn_redirect_peers[0].a.is_empty());
}
#[test] #[test]
fn convection_request_carries_the_class_bit() { fn convection_request_carries_the_class_bit() {
for class in [ConvectionClass::Entry, ConvectionClass::TopUp] { for class in [ConvectionClass::Entry, ConvectionClass::TopUp] {

File diff suppressed because it is too large Load diff

View file

@ -982,6 +982,37 @@ pub struct PeerWithAddress {
pub a: Vec<String>, pub a: Vec<String>,
} }
/// An introducer a declared holder nominated in place of its own address.
///
/// A requester that wants the file contacts the introducer, which coordinates
/// a hole punch via the always-on `RelayIntroduce` signalling (0xB0/0xB1); the
/// bulk transfer then flows DIRECT between requester and holder. The
/// introducer never carries file bytes, so this is NOT session relay and is
/// unaffected by `relay.session_relay_enabled`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RedirectIntroducer {
/// Introducer node id, hex.
pub n: String,
/// Introducer addresses.
pub a: Vec<String>,
}
/// A holder we may advertise as a source for a file, because that holder
/// DECLARED itself for it (see `crate::holdings`). Distinct from
/// `PeerWithAddress` so the consent-bearing CDN candidate can never be
/// confused with the social-route / mesh-refusal peer lists.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CdnRedirectPeer {
/// Holder node id, hex.
pub n: String,
/// Holder's own addresses. Empty when it published an introducer instead.
#[serde(default)]
pub a: Vec<String>,
/// Optional introducer to reach the holder through.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x: Option<RedirectIntroducer>,
}
// --- CDN Manifest Layer --- // --- CDN Manifest Layer ---
/// Lightweight post reference in a manifest /// Lightweight post reference in a manifest
@ -1010,16 +1041,24 @@ pub struct AuthorManifest {
pub signature: Vec<u8>, pub signature: Vec<u8>,
} }
/// CDN manifest traveling with blobs (author-signed part + serving host). /// CDN manifest traveling with blobs (the author-signed part, and nothing
/// else).
///
/// v0.8: ALL device-address fields removed (host_addresses, source, /// v0.8: ALL device-address fields removed (host_addresses, source,
/// source_addresses, downstream_count) — posting-identity manifests must not /// source_addresses, downstream_count) — posting-identity manifests must not
/// carry device addresses (location anonymity). Holder resolution goes via /// carry device addresses (location anonymity). Holder resolution goes via
/// file_holders / worm lookup / redirect peers instead. /// file_holders / worm lookup / redirect peers instead.
///
/// v0.8.1 PHASE 2: `host` removed too. It carried the serving node's own id,
/// rode every `BlobResponse` and `ManifestPush`, and the ManifestPush relay
/// forwarded received entries verbatim — so a third party learned "node A
/// holds cid C" with no declaration from A, which is exactly the inferred
/// holding this phase removed. Nothing in the workspace ever read it, and a
/// receiver already learns the serving host from the QUIC-authenticated
/// connection.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdnManifest { pub struct CdnManifest {
pub author_manifest: AuthorManifest, pub author_manifest: AuthorManifest,
/// Serving host's NodeId (the QUIC-authenticated device serving the blob)
pub host: NodeId,
} }
/// Cached routing info for a social contact /// Cached routing info for a social contact

View file

@ -117,9 +117,11 @@ async fn serve_post(stream: &mut TcpStream, path: &str, node: &Arc<Node>, browse
let (holders, local_post, local_author_name) = { let (holders, local_post, local_author_name) = {
let store = node.storage.get().await; let store = node.storage.get().await;
// v0.8.1 PHASE 2: a 302 hands a holder's IP to an arbitrary browser —
// the most public disclosure in the codebase. DECLARED holders only.
let mut holders = Vec::new(); let mut holders = Vec::new();
if let Ok(file_holders) = store.get_file_holders(&post_id) { if let Ok(file_holders) = store.get_declared_file_holders(&post_id) {
for (peer, _addrs) in file_holders { for (peer, _addrs, _intro) in file_holders {
if !holders.contains(&peer) { if !holders.contains(&peer) {
holders.push(peer); holders.push(peer);
} }

View file

@ -2043,6 +2043,93 @@ async fn get_greetings_max(
node.get_greetings_max(&posting_id).await.map_err(|e| e.to_string()) node.get_greetings_max(&posting_id).await.map_err(|e| e.to_string())
} }
// ---- v0.8.1 PHASE 2: declared-holdings policy ----
//
// Holdings are DECLARED, not inferred from transport. These commands are what
// make the policy reachable from the apps rather than CLI-only — the 4-device
// alpha runs the deliberately GENEROUS default (`cap_per_author = 0`), so a
// tester who finds the footprint leakier than they want needs a way to tighten
// it without a terminal.
/// Current policy + footprint, as a flat object for the Settings panel.
#[tauri::command]
async fn get_holdings_policy(state: State<'_, AppNode>) -> Result<serde_json::Value, String> {
let node = get_node(&state).await;
let p = node.holdings_policy().await;
let summary = node.holdings_summary().await;
let introducer_enabled = node
.get_setting(itsgoin_core::holdings::SETTING_INTRODUCER_ENABLED)
.await
.ok()
.flatten()
.as_deref()
== Some("true");
Ok(serde_json::json!({
"declare_custodial": p.declare_custodial,
"declare_interest": p.declare_interest,
"declare_own_authored": p.declare_own_authored,
"cap_per_author": p.cap_per_author,
"introducer_enabled": introducer_enabled,
"round10_target_cap": itsgoin_core::holdings::ROUND10_TARGET_CAP_PER_AUTHOR,
"summary": summary,
}))
}
/// Per-(us, author) cap on distinct declared posts. `0` = unlimited (the alpha
/// default). Retroactive: lowering it retracts what it no longer admits.
#[tauri::command]
async fn set_holdings_cap_per_author(
state: State<'_, AppNode>,
cap: u32,
) -> Result<(), String> {
let node = get_node(&state).await;
node.set_holdings_cap_per_author(cap).await.map_err(|e| e.to_string())
}
/// Enable/disable a declaration class. `class` is "custodial" or "interest".
#[tauri::command]
async fn set_holdings_declare_class(
state: State<'_, AppNode>,
class: String,
enabled: bool,
) -> Result<(), String> {
let reason = match class.as_str() {
"custodial" => itsgoin_core::holdings::DeclareReason::Custodial,
"interest" => itsgoin_core::holdings::DeclareReason::Interest,
other => return Err(format!("unknown holdings class: {other}")),
};
let node = get_node(&state).await;
node.set_holdings_declare_class(reason, enabled).await.map_err(|e| e.to_string())
}
/// Declare holdings of content WE authored. Default OFF — enabling it
/// publishes `device <-> posting identity` in third-party holder lists.
#[tauri::command]
async fn set_holdings_declare_own_authored(
state: State<'_, AppNode>,
enabled: bool,
) -> Result<(), String> {
let node = get_node(&state).await;
node.set_holdings_declare_own_authored(enabled).await.map_err(|e| e.to_string())
}
/// Publish an introducer's address in place of ours. Default OFF. Empty
/// `peer_hex` auto-picks a CONNECTED anchor. Hole-punch coordination only —
/// this is NOT session relay and does not touch `relay.session_relay_enabled`.
#[tauri::command]
async fn set_holdings_introducer(
state: State<'_, AppNode>,
enabled: bool,
peer_hex: Option<String>,
) -> Result<(), String> {
let peer = match peer_hex.as_deref() {
Some(h) if !h.is_empty() => Some(parse_node_id(h)?),
_ => None,
};
let node = get_node(&state).await;
node.set_holdings_introducer(enabled, peer).await.map_err(|e| e.to_string())
}
/// Open a URL in the user's default system browser. /// Open a URL in the user's default system browser.
/// Desktop: spawns the platform opener (xdg-open / open / cmd start). /// Desktop: spawns the platform opener (xdg-open / open / cmd start).
/// Only https:// URLs are accepted to avoid being a generic command exec. /// Only https:// URLs are accepted to avoid being a generic command exec.
@ -3776,6 +3863,11 @@ pub fn run() {
get_greetings_open, get_greetings_open,
set_greetings_max, set_greetings_max,
get_greetings_max, get_greetings_max,
get_holdings_policy,
set_holdings_cap_per_author,
set_holdings_declare_class,
set_holdings_declare_own_authored,
set_holdings_introducer,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while building tauri application") .expect("error while building tauri application")

View file

@ -4689,6 +4689,56 @@ $('#import-btn').addEventListener('click', () => {
}); });
})(); })();
// v0.8.1 PHASE 2 — declared-holdings policy. "Holding" and "being advertised
// as a holder" are separate; these knobs govern the second. Defaults are
// deliberately open for the alpha so content stays findable, and every change
// is retroactive on the core side (tightening retracts what it no longer
// admits and tells the peers publishing us).
(async () => {
const cap = $('#holdings-cap');
if (!cap) return;
const custodial = $('#holdings-custodial');
const interest = $('#holdings-interest');
const introducer = $('#holdings-introducer');
const summary = $('#holdings-summary');
const target = $('#holdings-cap-target');
async function load() {
try {
const p = await invoke('get_holdings_policy');
cap.value = p.cap_per_author;
custodial.checked = !!p.declare_custodial;
interest.checked = !!p.declare_interest;
introducer.checked = !!p.introducer_enabled;
if (summary) summary.textContent = p.summary || '';
if (target) target.textContent = 'Planned target: ' + p.round10_target_cap + '.';
} catch (_) {}
}
await load();
cap.addEventListener('change', async () => {
const v = Math.max(0, parseInt(cap.value, 10) || 0);
try {
await invoke('set_holdings_cap_per_author', { cap: v });
await load();
} catch (e) { alert('Failed to set per-author listing cap: ' + e); await load(); }
});
for (const [el, cls] of [[custodial, 'custodial'], [interest, 'interest']]) {
el.addEventListener('change', async () => {
try {
await invoke('set_holdings_declare_class', { class: cls, enabled: el.checked });
await load();
} catch (e) { el.checked = !el.checked; alert('Failed to update holdings policy: ' + e); }
});
}
introducer.addEventListener('change', async () => {
try {
await invoke('set_holdings_introducer', { enabled: introducer.checked, peerHex: null });
await load();
} catch (e) { introducer.checked = !introducer.checked; alert('Failed to update introducer setting: ' + e); }
});
})();
$('#notifications-btn').addEventListener('click', async () => { $('#notifications-btn').addEventListener('click', async () => {
// Load current settings // Load current settings
const msgVal = await invoke('get_setting', { key: 'notif_messages' }).catch(() => null) || 'on'; const msgVal = await invoke('get_setting', { key: 'notif_messages' }).catch(() => null) || 'on';

View file

@ -307,6 +307,31 @@
</label> </label>
</div> </div>
<div class="section-card">
<h3 style="margin-bottom:0.4rem;font-size:0.85rem;color:#888">Advertised Holdings</h3>
<p class="empty-hint" style="margin-bottom:0.5rem;font-size:0.72rem">
Holding a file and being <em>advertised</em> as a place to get it are separate things. You always serve what you hold when someone asks you directly; these settings control what other nodes may tell strangers about you. Listing lots of one author's posts is what reveals who you follow, so there is a per-author limit — left open for the alpha so content stays findable.
</p>
<label style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.35rem">
<span style="flex:1">Max posts listed per author</span>
<input type="number" id="holdings-cap" min="0" max="999" style="width:5rem">
</label>
<p class="empty-hint" style="margin:0 0 0.5rem;font-size:0.68rem">0 = no limit (alpha default). <span id="holdings-cap-target"></span></p>
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer">
<input type="checkbox" id="holdings-custodial">
<span>Advertise content pushed to me for safekeeping</span>
</label>
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer">
<input type="checkbox" id="holdings-interest">
<span>Advertise content I fetched because I wanted it</span>
</label>
<label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer">
<input type="checkbox" id="holdings-introducer">
<span>Publish an introducer's address instead of mine (not session relay)</span>
</label>
<p class="empty-hint" id="holdings-summary" style="margin:0.5rem 0 0;font-size:0.68rem"></p>
</div>
<!-- Hidden: node-info, anchors, diagnostics btn moved elsewhere --> <!-- Hidden: node-info, anchors, diagnostics btn moved elsewhere -->
<div class="hidden"> <div class="hidden">
<button id="anchors-toggle"></button> <button id="anchors-toggle"></button>

View file

@ -175,6 +175,111 @@ done
check "no stored comment claims a TTL past the 366d holder ceiling" \ check "no stored comment claims a TTL past the 366d holder ceiling" \
bash -c "[ $over_cap -eq 0 ]" bash -c "[ $over_cap -eq 0 ]"
# v0.8.1 PHASE 2 — holdings are DECLARED, not inferred from transport.
#
# The scenario above is already a holder-discovery exercise: node2 and node3
# each pull the other's bio to greet it, and node1 serves the registry post to
# both. Declarations ride the content-sync cycle, so drive one explicitly
# rather than waiting for the 60s tick to land inside the run.
echo "== step 7: declared holdings =="
for fd in 13 14 15; do echo "sync" >&$fd; done
sleep 10
# Second pass: the first sweep teaches each peer our declarations; the second
# proves the sweep RECURS rather than firing only at acquisition.
for fd in 13 14 15; do echo "sync" >&$fd; done
sleep 10
# Transport events (serving posts, receiving diffs, greeting exchanges) still
# record LOCAL HINTS, which stay usable for fetch retry and diff propagation.
# Under the old inference rule every one of them wrote a PUBLISHABLE row
# instead. (node1 ends the run with publishable rows only, because serving
# content no longer writes a holder row for the requester at all - which is
# itself the property under test.)
hint_rows=0
for i in 1 2 3; do
hint_rows=$((hint_rows + $(sq $i "SELECT count(*) FROM file_holders WHERE declared=0")))
done
check "transport still records local hints (usable, never published)" \
bash -c "[ $hint_rows -gt 0 ]"
# The declaring side: nodes declare what they hold, through the policy.
d2=$(sq 2 "SELECT count(*) FROM declared_holdings")
d3=$(sq 3 "SELECT count(*) FROM declared_holdings")
check "node2 and node3 each declared a holding (explicit declaration works)" \
bash -c "[ $d2 -ge 1 ] && [ $d3 -ge 1 ]"
# Every publishable row must be attributable to a peer that actually sent us a
# 0xD3 - which, since a declaration only arrives over a live connection, means
# every declared row's peer is a peer we know.
orphan_declared=0
for i in 1 2 3; do
orphan_declared=$((orphan_declared + $(sq $i "SELECT count(*) FROM file_holders f
WHERE f.declared=1 AND f.peer_id NOT IN (SELECT node_id FROM peers)")))
done
check "every publishable holder row came from a peer that declared to us" \
bash -c "[ $orphan_declared -eq 0 ]"
# HUNT ITEM 3 - the point of the whole change: a node that wants content it
# does not hold must be able to find somebody who does. Every node declares the
# registry post (it is not its own authored content), the sweep carries that to
# its peers, so each node must be able to NAME a declared holder for it.
reg=$(grep shipped_constant /tmp/itsgoin-genesis.log | awk '{print $2}')
reg_declared=$(sq 1 "SELECT count(*) FROM file_holders WHERE declared=1 AND lower(hex(file_id))='$reg'")
check "a serving node can name a declared holder for the registry post" \
bash -c "[ $reg_declared -ge 1 ]"
# SELF-HEAL - the mechanism the migration ruling rests on. Clear a declaration
# from node1's view and show the sweep puts it back, so a peer that wipes its
# database (or evicts the row) re-learns our holdings.
victim=$(sq 1 "SELECT lower(hex(peer_id)) FROM file_holders WHERE declared=1 LIMIT 1")
sq 1 "DELETE FROM file_holders WHERE lower(hex(peer_id))='$victim' AND declared=1"
gone=$(sq 1 "SELECT count(*) FROM file_holders WHERE lower(hex(peer_id))='$victim' AND declared=1")
check "the deleted declarations are really gone before the sweep" \
bash -c "[ $gone -eq 0 ]"
for fd in 13 14 15; do echo "sync" >&$fd; done
sleep 12
healed=$(sq 1 "SELECT count(*) FROM file_holders WHERE lower(hex(peer_id))='$victim' AND declared=1")
check "a declaration self-heals after a sync cycle (re-declaration works)" \
bash -c "[ $healed -ge 1 ]"
# Round 10: addresses ride only for anchors. These are loopback test nodes with
# no anchor role, so every declaration must be a bare id.
addr_bearing=0
for i in 1 2 3; do
addr_bearing=$((addr_bearing + $(sq $i "SELECT count(*) FROM file_holders
WHERE declared=1 AND peer_addresses NOT IN ('"''"',\"[]\")")))
done
check "no non-anchor declaration carries an address (bare ids only)" \
bash -c "[ $addr_bearing -eq 0 ]"
# A declaration for a post we authored would publish device <-> persona, which
# is exactly what Iteration A's manifest address strip removed. Checked against
# the never-pruned ledger, so a rotated-out persona counts too.
own_authored=0
for i in 1 2 3; do
own_authored=$((own_authored + $(sq $i "SELECT count(*) FROM declared_holdings d
JOIN own_authored_identities p ON p.node_id = d.author")))
done
check "nobody declared content authored by one of its own personas" \
bash -c "[ $own_authored -eq 0 ]"
# Non-public content is never declared: a declaration announces audience
# membership. Greeting/DM traffic in this run gives the gate something to bite.
nonpublic=0
for i in 1 2 3; do
nonpublic=$((nonpublic + $(sq $i 'SELECT count(*) FROM declared_holdings d JOIN posts p ON p.id = d.post_id WHERE p.visibility != '\''"Public"'\''')))
done
check "no declaration covers non-public content" \
bash -c "[ $nonpublic -eq 0 ]"
# Standing assertions: the wire fields that reported/implied silent enrolment
# are gone. `cdn_registered` said "the host registered you"; `CdnManifest.host`
# said "node A holds this cid" and was relayed verbatim to third parties.
check "the cdn_registered silent-enrolment flag is gone from the tree" \
bash -c '! grep -rq "cdn_registered" --include=*.rs "$(dirname "$0")/../crates"'
check "CdnManifest no longer carries a serving-host id" \
bash -c '! grep -rq "pub host: NodeId" --include=*.rs "$(dirname "$0")/../crates"'
echo echo
echo "== results: $PASS passed, $FAIL failed ==" echo "== results: $PASS passed, $FAIL failed =="
[ "$FAIL" -eq 0 ] [ "$FAIL" -eq 0 ]

View file

@ -907,31 +907,58 @@
<h3>Blob transfer flow (<code>0x90</code>/<code>0x91</code>) <span class="badge badge-complete">Implemented</span></h3> <h3>Blob transfer flow (<code>0x90</code>/<code>0x91</code>) <span class="badge badge-complete">Implemented</span></h3>
<ol style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);"> <ol style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);">
<li>Requester sends <code>BlobRequest { cid, requester_addresses }</code></li> <li>Requester sends <code>BlobRequest { cid }</code>. It carries no addresses: asking for a file is not an application to be advertised as one of its sources.</li>
<li>Host checks local BlobStore and delivery budget: <li>Host checks local BlobStore and delivery budget:
<ul style="margin-top: 0.3rem;"> <ul style="margin-top: 0.3rem;">
<li><strong>Has blob, budget OK</strong>: Return base64-encoded data + CDN manifest (with current holder count). If the host knows fewer than 5 holders, register the requester (<code>cdn_registered: true</code>); otherwise return the known holders as <code>cdn_redirect_peers</code>.</li> <li><strong>Has blob, budget OK</strong>: return base64-encoded data + the author-signed manifest.</li>
<li><strong>No blob / budget exhausted</strong>: Return <code>found: false</code></li> <li><strong>No blob, or budget exhausted</strong>: return <code>found: false</code>.</li>
</ul> </ul>
</li> </li>
<li>Requester verifies CID, stores blob locally, records the host in <code>file_holders</code> (direction <code>received</code>), and stores any redirect peers as additional holder knowledge.</li> <li><strong>All three outcomes carry <code>cdn_redirect_peers</code></strong> &mdash; the <em>declared</em> holders of that CID, minus the requester. The budget-exhausted case is where a redirect matters most: the host has the bytes and is declining to send them, so the requester needs somewhere else to go.</li>
<li>Requester verifies the CID, stores the blob, and records the host as a <strong>local hint</strong>. If its own policy admits it, it then sends a <strong>holding declaration</strong> (<code>0xD3</code>) &mdash; the only way it enters anyone's publishable holder list.</li>
</ol> </ol>
<h3>Manifests <span class="badge badge-rework">Rework</span></h3> <h3>Manifests <span class="badge badge-rework">Rework</span></h3>
<ul style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);"> <ul style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);">
<li><strong>AuthorManifest</strong>: ed25519-signed by the post author (posting key). Contains the anchor post, creation/update timestamps, and the author's post neighborhood. In v0.8 the neighborhood is capped to the <strong>2&ndash;5 post concealment budget</strong> and the manifest carries <strong>no device addresses</strong> &mdash; readers reach the author's content through <code>file_holders</code> search, never through addresses tied to the posting identity.</li> <li><strong>AuthorManifest</strong>: ed25519-signed by the post author (posting key). Contains the anchor post, creation/update timestamps, and the author's post neighborhood. In v0.8 the neighborhood is capped to the <strong>2&ndash;5 post concealment budget</strong> and the manifest carries <strong>no device addresses</strong> &mdash; readers reach the author's content through <code>file_holders</code> search, never through addresses tied to the posting identity.</li>
<li><strong>CdnManifest</strong>: AuthorManifest + serving-host metadata. The v0.8 wire format drops the legacy tree fields (source, source addresses, downstream count) as part of the clean protocol break (see <a href="#sync">Sync Protocol</a>).</li> <li><strong>CdnManifest</strong>: the author-signed manifest, and nothing else. The v0.8 wire format dropped the legacy tree fields (source, source addresses, downstream count) as part of the clean protocol break (see <a href="#sync">Sync Protocol</a>); v0.8.1 dropped the last one, the serving host&rsquo;s NodeId. It was never read, it rode every blob response and manifest push, and the manifest-push relay forwarded received entries verbatim &mdash; so a third party learned &ldquo;node A holds this CID&rdquo; with no declaration from A. A receiver already learns the serving host from the QUIC-authenticated connection.</li>
</ul> </ul>
<div class="note"> <div class="note">
<strong>v0.8 change (privacy fix):</strong> today's AuthorManifest ships the device's real addresses under a posting-identity author and a 10+10 post neighborhood. Both violate the v0.8 privacy rulings: posting identities must be location-anonymous, and the neighborhood must not reveal more than the concealment budget. This fix is a prerequisite for the discovery registry (<a href="#discovery">Discovery &amp; First Contact</a>). <strong>v0.8 change (privacy fix):</strong> today's AuthorManifest ships the device's real addresses under a posting-identity author and a 10+10 post neighborhood. Both violate the v0.8 privacy rulings: posting identities must be location-anonymous, and the neighborhood must not reveal more than the concealment budget. This fix is a prerequisite for the discovery registry (<a href="#discovery">Discovery &amp; First Contact</a>).
</div> </div>
<h3>Declared holdings &mdash; holding vs. being advertised <span class="badge badge-complete">Implemented</span></h3>
<p>Until v0.8.1 holdings were <strong>inferred from transport</strong>: every receive path recorded the <em>sender</em> in <code>file_holders</code>, and those rows went back out on the wire to third parties as <code>cdn_redirect_peers</code>, as worm holder answers, and as HTTP 302 targets. Merely exchanging bytes with a peer enrolled your node ID &mdash; and your addresses &mdash; into a list that peer republished to anyone who asked. Two things follow from that, and both matter: the concealment model below (&ldquo;hold several shards quietly, announce exactly one slot&rdquo;) is impossible on an inferred foundation, and an enumerator never had to hold anything &mdash; it just asked holders who else holds.</p>
<p>Holder registration is therefore a <strong>deliberate self-declaration</strong>:</p>
<table>
<tr><th>Row</th><th>Means</th><th>Used for</th></tr>
<tr><td><strong>Local hint</strong> (<code>declared = 0</code>)</td><td>&ldquo;We exchanged bytes about this file with that peer.&rdquo;</td><td>Fetch retry, diff-propagation targets, manifest refresh. Never published as a holder of a specific file.</td></tr>
<tr><td><strong>Declaration</strong> (<code>declared = 1</code>)</td><td>The peer told us &ldquo;I hold this and you may advertise me for it&rdquo; (<code>0xD3</code>).</td><td>The only holder list that may go on the wire, into a worm answer, or into an HTTP redirect.</td></tr>
</table>
<p>An <em>undeclared</em> holder stays invisible but still serves a direct request it receives &mdash; declaration governs advertisement, not willingness to serve. Declarations are <strong>soft state</strong>: they are re-sent on a rotating per-peer sweep riding each content-sync cycle, and they expire if not renewed, so a peer that wipes its database re-learns them and a holder that goes quiet drops out of other nodes&rsquo; lists.</p>
<p>What a node declares is local policy. The alpha defaults are deliberately <strong>generous</strong> &mdash; both classes declare and the per-author cap is off &mdash; because a tight cap makes content unfindable and there is no spare holder population yet to absorb that:</p>
<table>
<tr><th>Knob</th><th>Default</th><th>Meaning</th></tr>
<tr><td>Custodial declarations</td><td>On</td><td>Content pushed to us by a <code>ReplicationRequest</code>. Being findable <em>is</em> the function of holding it.</td></tr>
<tr><td>Interest declarations</td><td>On</td><td>Content we fetched because we wanted it. These are the rows that carry the follow signal.</td></tr>
<tr><td>Per-author listing cap</td><td>0 (unlimited)</td><td>Round 10&rsquo;s per-(holder, author) axis. Target is 2, adopted once the activity digest exists to carry the coverage the cap gives up.</td></tr>
<tr><td>Own authored content</td><td>Off</td><td>Declaring a post we authored publishes <code>device &harr; posting identity</code> &mdash; the binding the manifest address strip exists to prevent. Authors still serve direct requests.</td></tr>
<tr><td>Introducer</td><td>Off</td><td>Publish a connected anchor&rsquo;s address instead of ours; a fetcher reaches us through <code>RelayIntroduce</code> and the bulk transfer flows direct. Not session relay &mdash; no bytes cross the introducer.</td></tr>
</table>
<p>Non-public content is never declared, at a single chokepoint: advertising yourself as a holder of a DM, a group post or an FoF-closed post announces your membership in its audience. Policy changes are <strong>retroactive</strong> &mdash; tightening a knob retracts the declarations it no longer admits and tells the peers publishing us &mdash; so the alpha&rsquo;s open shape is transitional rather than permanent.</p>
<div class="note">
<strong>Honest limit.</strong> Declaration governs the per-<em>file</em> holder lists. It hides <strong>which</strong> and <strong>how many</strong> of an author&rsquo;s posts you hold; it does <strong>not</strong> hide <em>that</em> you hold some of that author&rsquo;s content. The uniques index (see <a href="#layers">Network Knowledge</a>) announces every distinct author whose content you carry, deliberately interest-blind-but-complete so discovery works at all. So the per-author cap bounds post counts, never the author set, and the one-shard-announcement property holds at file granularity only. Closing the author-level surface means deriving that half of the announce from declared holdings &mdash; a discovery trade that has not been ruled on.
</div>
<div class="note">
<strong>Upgrade behaviour.</strong> Every pre-existing <code>file_holders</code> row was inferred, so on upgrade it becomes a local hint and stops being republished &mdash; including its inferred addresses, which are cleared. Carrying those rows forward as declarations would have preserved exactly the leak the change closes, for subjects who can never be asked. The discovery cost is bounded by a one-time startup backfill that re-declares the public content a node already holds through the ordinary policy, plus the rotating re-declaration sweep.
</div>
<h3>Blob eviction <span class="badge badge-complete">Implemented</span></h3> <h3>Blob eviction <span class="badge badge-complete">Implemented</span></h3>
<pre><code>priority = pin_boost + share_boost + (relationship &times; heart_recency &times; freshness / (peer_copies + 1))</code></pre> <pre><code>priority = pin_boost + share_boost + (relationship &times; heart_recency &times; freshness / (peer_copies + 1))</code></pre>
<table> <table>
<tr><th>Factor</th><th>Calculation</th></tr> <tr><th>Factor</th><th>Calculation</th></tr>
<tr><td><code>pin_boost</code></td><td>1000.0 if pinned, else 0.0. Own blobs auto-pinned.</td></tr> <tr><td><code>pin_boost</code></td><td>1000.0 if pinned, else 0.0. Own blobs auto-pinned.</td></tr>
<tr><td><code>share_boost</code></td><td>100.0 at 3+ known holders; <code>50.0 &times; n / 3</code> for 1&ndash;2 holders; 0 otherwise. Holder count comes from <code>file_holders</code> (max 5) &mdash; content with a healthy holder set is being actively served and stays cached longer.</td></tr> <tr><td><code>share_boost</code></td><td>100.0 at 3+ known holders; <code>50.0 &times; n / 3</code> for 1&ndash;2 holders; 0 otherwise. Holder count comes from <code>file_holders</code> (max 5 per class) &mdash; content with a healthy holder set is being actively served and stays cached longer. <em>Durability decisions (is my own post under-replicated?) count only holders we have evidence for &mdash; transport events we witnessed, or corroborated replica announcements &mdash; never bare declarations: a claimed holder set is cheap to forge, and a forged &ldquo;this is healthy&rdquo; would suppress healing.</em></td></tr>
<tr><td><code>relationship</code></td><td>5.0 (own content), 2.0 (followed author), 0.1 (stranger). <em>The own-content tier currently compares against the network ID and never matches post-split; own blobs stay protected via auto-pin. Fix rides the ID-class sweep (see <a href="#identity-architecture">Identity Architecture</a>).</em></td></tr> <tr><td><code>relationship</code></td><td>5.0 (own content), 2.0 (followed author), 0.1 (stranger). <em>The own-content tier currently compares against the network ID and never matches post-split; own blobs stay protected via auto-pin. Fix rides the ID-class sweep (see <a href="#identity-architecture">Identity Architecture</a>).</em></td></tr>
<tr><td><code>heart_recency</code></td><td>Linear decay over 30 days since last access: <code>max(0, 1 - age/30d)</code></td></tr> <tr><td><code>heart_recency</code></td><td>Linear decay over 30 days since last access: <code>max(0, 1 - age/30d)</code></td></tr>
<tr><td><code>freshness</code></td><td><code>1 / (1 + post_age_days)</code></td></tr> <tr><td><code>freshness</code></td><td><code>1 / (1 + post_age_days)</code></td></tr>
@ -1442,11 +1469,11 @@
<ul style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);"> <ul style="padding-left: 1.25rem; margin: 0.5rem 0; color: var(--text-muted);">
<li><strong>Jittered, tiered update cadence</strong>: CDN update checks run on a descending-frequency schedule (minutes &rarr; days) keyed on freshness &times; relationship tier, with jitter on every timer (see <a href="#keep-alive">Update Cadence</a>). No check fires <em>because</em> a post appeared; checks fire because a schedule slot came up.</li> <li><strong>Jittered, tiered update cadence</strong>: CDN update checks run on a descending-frequency schedule (minutes &rarr; days) keyed on freshness &times; relationship tier, with jitter on every timer (see <a href="#keep-alive">Update Cadence</a>). No check fires <em>because</em> a post appeared; checks fire because a schedule slot came up.</li>
<li><strong>Replication shaped as overhead</strong>: replication pushes are paced and jittered so an author seeding their own content is indistinguishable from a holder performing routine redundancy maintenance. The goal: update + replication traffic reads as uniform network overhead, with no observable "origin burst".</li> <li><strong>Replication shaped as overhead</strong>: replication pushes are paced and jittered so an author seeding their own content is indistinguishable from a holder performing routine redundancy maintenance. The goal: update + replication traffic reads as uniform network overhead, with no observable "origin burst".</li>
<li><strong>2&ndash;5 visible posts per author</strong>: the public CDN surface reveals at most 2&ndash;5 posts per author at any time; the surplus is pushed out to holders via replication requests and reached through the uniques index. This caps what enumeration of any single node's public holdings discloses about any author's corpus &mdash; and hides the author's own node behind ordinary public mesh IDs.</li> <li><strong>2&ndash;5 visible posts per author</strong>: the public CDN surface reveals at most 2&ndash;5 posts per author at any time; the surplus is pushed out to holders via replication requests and reached through the uniques index. This caps what enumeration of any single node's public holdings discloses about any author's corpus &mdash; and hides the author's own node behind ordinary public mesh IDs. The mechanism is the per-author cap on <a href="#files">declared holdings</a>, which is <em>implemented but defaulted open for the alpha</em>; the cap bounds posts per author, not the author set itself.</li>
<li><strong>Open-slot comment TTL</strong>: long-lived comment trails are the easiest correlation anchors across time. The 30&ndash;365-day expiry bounds how long a <em>throwaway-ID</em> trail exists &mdash; it applies to the open-slot stranger channel (greetings), which is where the anonymity claim lives. Public and post-key-signed comments do not expire; they are attributable content, and their trail is bounded by nothing but deletion.</li> <li><strong>Open-slot comment TTL</strong>: long-lived comment trails are the easiest correlation anchors across time. The 30&ndash;365-day expiry bounds how long a <em>throwaway-ID</em> trail exists &mdash; it applies to the open-slot stranger channel (greetings), which is where the anonymity claim lives. Public and post-key-signed comments do not expire; they are attributable content, and their trail is bounded by nothing but deletion.</li>
</ul> </ul>
<div class="note"> <div class="note">
<strong>Honest scope</strong>: this defeats passive observers correlating timing and public holdings. A global adversary who can watch every link, or an adversary who compromises your own device, is out of scope &mdash; as in every friend-to-friend design. <strong>Honest scope</strong>: this defeats passive observers correlating timing and public holdings. Holder-list enumeration specifically &mdash; asking holders who else holds &mdash; is bounded by <a href="#files">declared holdings</a>: an enumerator now sees only peers that consented to be named for that file, not everyone who ever exchanged bytes about it. A global adversary who can watch every link, or an adversary who compromises your own device, is out of scope &mdash; as in every friend-to-friend design.
</div> </div>
</section> </section>
<section id="multidevice"> <section id="multidevice">