diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index c8cf867..81181d1 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -246,7 +246,6 @@ async fn main() -> anyhow::Result<()> { println!(" dismiss Dismiss a greeting (local only)"); println!(" greetings-open Toggle the greeting slot on your bio (republishes bio)"); println!(" greetings-max 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!(" export-key Export identity key (KEEP SECRET)"); println!(" id Show this node's ID"); @@ -1204,77 +1203,6 @@ 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 | holdings custodial | holdings interest | holdings own-authored | holdings introducer >"); - } - (Some("cap"), Some(v)) => { - let cap = if v == "off" || v == "unlimited" { Some(0) } else { v.parse::().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 "), - } - } - (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 >"); - 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 | holdings custodial | holdings interest | holdings own-authored | holdings introducer >"), - } - } - "quit" | "exit" | "q" => { println!("Shutting down..."); break; diff --git a/crates/core/src/connection.rs b/crates/core/src/connection.rs index 5b5cdd1..5e4ab4c 100644 --- a/crates/core/src/connection.rs +++ b/crates/core/src/connection.rs @@ -28,42 +28,13 @@ use crate::protocol::{ pack_ids, unpack_ids, AnchorEntry, UniquesAnnouncePayload, UniquesSlice, }; use crate::types::{ - CdnRedirectPeer, DeviceProfile, IdClass, MeshSlot, NodeId, PeerWithAddress, PostId, - PostVisibility, ReachEntry, ReachMethod, SessionReachMethod, SocialRouteEntry, SocialStatus, - UniquesPools, WormId, WormResult, + DeviceProfile, IdClass, MeshSlot, NodeId, PeerWithAddress, PostId, PostVisibility, + ReachEntry, ReachMethod, SessionReachMethod, SocialRouteEntry, SocialStatus, UniquesPools, + WormId, WormResult, }; 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). /// /// `MAX_PAYLOAD` exists for FILE transfer. Applying it to the index exchange @@ -1067,11 +1038,6 @@ pub struct ConnectionManager { /// Peers known to be unreachable directly: node_id → last_failed_at_ms /// Learned over the session — cleared on restart, updated on connect success/failure unreachable_peers: HashMap, - /// 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, /// Anchor-side rolling window of recent callers. Newest at the back. /// In-memory only — no registration DB, no persistence. convection_window: VecDeque, @@ -1180,7 +1146,6 @@ impl ConnectionManager { diff_seq: AtomicU64::new(0), blob_store, seen_worms: HashMap::new(), - declaration_quota: HashMap::new(), last_announce_digest: 0, mesh_slots: profile.mesh_slots(), temp_referral_slots: profile.temp_referral_slots(), @@ -1631,31 +1596,6 @@ impl ConnectionManager { 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 { - self.connections - .keys() - .chain(self.sessions.keys()) - .copied() - .collect() - } - /// Build the stable advertised address for this anchor node. /// Returns None if not an anchor or no suitable address found. pub fn build_anchor_advertised_addr(&self) -> Option { @@ -1963,8 +1903,6 @@ impl ConnectionManager { storage: &Arc, peer_id: &NodeId, _our_node_id: NodeId, - anchor_addr: Option, - connected_peers: Vec, ) -> anyhow::Result { let (our_follows, follows_sync, our_personas) = { let s = storage.get().await; @@ -2004,30 +1942,6 @@ impl ConnectionManager { let mut new_post_ids: Vec = Vec::new(); let now_ms = crate::connection::now_ms(); let mut synced_authors: HashSet = 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 { @@ -2046,22 +1960,14 @@ impl ConnectionManager { } Err(e) => { 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: 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 = { + // Brief storage lock: upstream + last_sync + { let s = storage.get().await; for pid in &new_post_ids { let _ = s.touch_file_holder( @@ -2074,58 +1980,14 @@ impl ConnectionManager { for author in &synced_authors { 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() - } - }; + } - // Declare our holdings (spawned, no lock needed) - if !declarations.is_empty() { + // Register as downstream (spawned, no lock needed) + if !new_post_ids.is_empty() { let c = conn.clone(); tokio::spawn(async move { - for payload in declarations { + for post_id in new_post_ids.into_iter().take(50) { + let payload = PostDownstreamRegisterPayload { post_id }; if let Ok(mut send) = c.open_uni().await { let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, &payload).await; let _ = send.finish(); @@ -3050,10 +2912,9 @@ impl ConnectionManager { if store.get_post_with_visibility(post_id).ok().flatten().is_some() { Some(self.our_node_id) } else { - // v0.8.1 PHASE 2: a worm answer names a third party to the - // asker, so only DECLARED holders may be named here. - let holders = store.get_declared_file_holders(post_id).unwrap_or_default(); - holders.first().map(|(nid, _, _)| *nid) + // Any known holder of this post? + let holders = store.get_file_holders(post_id).unwrap_or_default(); + holders.first().map(|(nid, _)| *nid) } }; post_holder = found; @@ -3067,8 +2928,8 @@ impl ConnectionManager { // Check CDN: do we know who has it via blob post ownership? let store = self.storage.get().await; if let Ok(Some(pid)) = store.get_blob_post_id(blob_id) { - let holders = store.get_declared_file_holders(&pid).unwrap_or_default(); - if let Some((nid, _, _)) = holders.first() { + let holders = store.get_file_holders(&pid).unwrap_or_default(); + if let Some((nid, _)) = holders.first() { blob_holder = Some(*nid); } } @@ -5242,9 +5103,7 @@ impl ConnectionManager { &entry.manifest.author_manifest.author, entry.manifest.author_manifest.updated_at, ); - // 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. + // Remote peer pushed us this manifest → they hold the file. let _ = storage.touch_file_holder( &entry.cid, &remote_node_id, @@ -5360,10 +5219,8 @@ impl ConnectionManager { Ok(Some(sync_post)) => { if crate::content::verify_post_id(&sync_post.id, &sync_post.post) { // Brief re-acquire for storage writes only - let (stored, declaration) = { + let stored = { 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 newly_stored = crate::control::receive_post( &storage, @@ -5373,8 +5230,6 @@ impl ConnectionManager { sync_post.intent.as_ref(), ).unwrap_or(false); if newly_stored { - // LOCAL HINT for the sender (v0.8.1) — not a - // declaration on their behalf. let _ = storage.touch_file_holder( &sync_post.id, &sender_id, @@ -5386,38 +5241,18 @@ impl ConnectionManager { .unwrap_or_default() .as_millis() as u64; let _ = storage.update_follow_last_sync(&sync_post.post.author, now); - } - // 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, - }) + true } else { - None - }; - (newly_stored, declaration) + false + } }; - // cm lock RELEASED — declare without lock - if let Some(reg) = declaration { + // cm lock RELEASED — register downstream without lock + if stored { + let reg = crate::protocol::PostDownstreamRegisterPayload { post_id: sync_post.id }; if let Ok(mut send) = conn.open_uni().await { let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, ®).await; let _ = send.finish(); } - } - if stored { fetched += 1; } } @@ -5444,7 +5279,7 @@ impl ConnectionManager { if blob_store.has(&att.cid) { continue; } let blob_result: anyhow::Result<()> = async { let (mut bs, mut br) = conn.open_bi().await?; - let req = BlobRequestPayload { cid: att.cid }; + let req = BlobRequestPayload { cid: att.cid, requester_addresses: vec![] }; write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?; bs.finish()?; let mt = read_message_type(&mut br).await?; @@ -5559,128 +5394,20 @@ impl ConnectionManager { cm.handle_blob_header_diff(payload, remote_node_id).await; } MessageType::PostDownstreamRegister => { - // v0.8.1 PHASE 2: the HOLDING DECLARATION handler. This is the - // only path that can mark a peer publishable for a file. Every - // other holder write in this file is a local hint. - // - // It is therefore the only unauthenticated input that can reach - // `cdn_redirect_peers`, worm holder answers and HTTP 302s, so - // it is validated hard. `MAX_DECLARATION_PAYLOAD` rejects - // (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 payload: PostDownstreamRegisterPayload = read_payload(recv, MAX_PAYLOAD).await?; + let cm = conn_mgr.lock().await; 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 = payload.addresses.iter() - .filter_map(|a| a.parse::().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 = i.a.iter() - .filter_map(|s| s.parse::().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; - } - } + let _ = storage.touch_file_holder( + &payload.post_id, + &remote_node_id, + &[], + crate::storage::HolderDirection::Sent, + ); drop(storage); - drop(cm); trace!( peer = hex::encode(remote_node_id), post = hex::encode(payload.post_id), - files = file_ids.len(), - recorded, - skipped_unknown, - withdraw = payload.withdraw, - "Holding declaration recorded" + "Registered as post downstream" ); } other => { @@ -5925,54 +5652,61 @@ impl ConnectionManager { MessageType::BlobRequest => { let payload: BlobRequestPayload = read_payload(&mut recv, 4096).await?; // Extract Arcs under brief lock — no conn_mgr lock needed for blob serving - let (blob_store, storage) = { + let (blob_store, storage, our_node_id) = { let cm = conn_mgr.lock().await; - (Arc::clone(&cm.blob_store), Arc::clone(&cm.storage)) + (Arc::clone(&cm.blob_store), Arc::clone(&cm.storage), cm.our_node_id) }; // All I/O outside the lock 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 = storage.get_cdn_manifest(&payload.cid).ok().flatten().and_then(|json| { - serde_json::from_str::(&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 { Some(bytes) => { 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"); - BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_redirect_peers } + BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_registered: false, cdn_redirect_peers: vec![] } } else { use base64::Engine; - BlobResponsePayload { cid: payload.cid, found: true, data_b64: base64::engine::general_purpose::STANDARD.encode(&bytes), manifest, cdn_redirect_peers } + let storage = storage.get().await; + let manifest: Option = storage.get_cdn_manifest(&payload.cid).ok().flatten().and_then(|json| { + serde_json::from_str::(&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 = 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_redirect_peers }, + None => BlobResponsePayload { cid: payload.cid, found: false, data_b64: String::new(), manifest: None, cdn_registered: false, cdn_redirect_peers: vec![] }, }; write_typed_message(&mut send, MessageType::BlobResponse, &response).await?; send.finish()?; - debug!(peer = hex::encode(remote_node_id), found = response.found, redirects = response.cdn_redirect_peers.len(), "Handled blob request"); + debug!(peer = hex::encode(remote_node_id), found = response.found, cdn_reg = response.cdn_registered, "Handled blob request"); } MessageType::ManifestRefreshRequest => { let payload: crate::protocol::ManifestRefreshRequestPayload = read_payload(&mut recv, 1024).await?; - // Brief lock: get storage Arc - let storage = { + // Brief lock: get storage Arc + our_node_id + let (storage, our_node_id) = { let cm = conn_mgr.lock().await; - Arc::clone(&cm.storage) + (Arc::clone(&cm.storage), cm.our_node_id) }; let response = { let store = storage.get().await; @@ -5980,7 +5714,7 @@ impl ConnectionManager { Some(json) => { let manifest = if let Ok(am) = serde_json::from_str::(&json) { if am.updated_at > payload.current_updated_at { - Some(crate::types::CdnManifest { author_manifest: am }) + Some(crate::types::CdnManifest { author_manifest: am, host: our_node_id }) } else { None } } else { None }; crate::protocol::ManifestRefreshResponsePayload { cid: payload.cid, updated: manifest.is_some(), manifest } @@ -6281,10 +6015,7 @@ impl ConnectionManager { to_pull.push(*pid); } - // 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). + // Register as holder for all accepted posts for pid in &acc { let _ = storage.touch_file_holder( pid, @@ -6340,8 +6071,6 @@ impl ConnectionManager { let attachments = sp.post.attachments.clone(); let post_author = sp.post.author; 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 _ = crate::control::receive_post( &storage, @@ -6350,58 +6079,26 @@ impl ConnectionManager { &sp.visibility, sp.intent.as_ref(), ); - // LOCAL HINT for the sender (v0.8.1). let _ = storage.touch_file_holder( &sp.id, &sender, &[], 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(); drop(storage); drop(cm); fetched += 1; - if let Some(reg) = declaration { - if let Ok(mut send) = conn.open_uni().await { - let _ = write_typed_message(&mut send, MessageType::PostDownstreamRegister, ®).await; - let _ = send.finish(); - } - } - // Fetch blobs for this post from the requester for att in &attachments { if blob_store.has(&att.cid) { continue; } let blob_result: anyhow::Result<()> = async { let (mut bs, mut br) = conn.open_bi().await?; - let req = BlobRequestPayload { cid: att.cid }; + let req = BlobRequestPayload { + cid: att.cid, + requester_addresses: vec![], + }; write_typed_message(&mut bs, MessageType::BlobRequest, &req).await?; bs.finish()?; let mt = read_message_type(&mut br).await?; @@ -6414,46 +6111,12 @@ impl ConnectionManager { let cm = cm_arc.lock().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); - // LOCAL HINT for the sender (v0.8.1). let _ = storage.touch_file_holder( &att.cid, &sender, &[], 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, ®).await; - let _ = send.finish(); - } - } } Ok(()) }.await; @@ -6482,8 +6145,7 @@ impl ConnectionManager { /// to the post's file_holders (flat set, up to 5 most recent). async fn handle_blob_header_diff(&self, payload: BlobHeaderDiffPayload, sender: NodeId) { // Gather policy + followers set + holders, then drop lock immediately. - // 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. + // Remote peer clearly holds this post — record them as a holder. // v0.6.2: `AudienceOnly` → `FollowersOnly`; checked against our public // follows list rather than a separate audience table. let (policy, followers_set, holders) = { @@ -7914,9 +7576,8 @@ impl ConnectionActor { if s.get_post_with_visibility(post_id).ok().flatten().is_some() { post_holder = Some(ctx.our_node_id); } else { - // Declared holders only — see handle_worm_query. - let holders = s.get_declared_file_holders(post_id).unwrap_or_default(); - if let Some((nid, _, _)) = holders.first() { post_holder = Some(*nid); } + let holders = s.get_file_holders(post_id).unwrap_or_default(); + if let Some((nid, _)) = holders.first() { post_holder = Some(*nid); } } } @@ -7926,8 +7587,8 @@ impl ConnectionActor { } else { let s = ctx.storage.get().await; if let Ok(Some(pid)) = s.get_blob_post_id(blob_id) { - let holders = s.get_declared_file_holders(&pid).unwrap_or_default(); - if let Some((nid, _, _)) = holders.first() { blob_holder = Some(*nid); } + let holders = s.get_file_holders(&pid).unwrap_or_default(); + if let Some((nid, _)) = holders.first() { blob_holder = Some(*nid); } } } } @@ -8510,12 +8171,11 @@ impl ConnectionActor { let cm = self.cm.lock().await; cm.connections.get(&peer) .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 { - Some((conn, our_node_id, anchor_addr, connected)) => { + Some((conn, our_node_id)) => { // All I/O outside the lock, storage accessed via hoisted Arc - ConnectionManager::content_sync_unlocked(conn, &self.storage, &peer, our_node_id, anchor_addr, connected).await + ConnectionManager::content_sync_unlocked(conn, &self.storage, &peer, our_node_id).await } None => Err(anyhow::anyhow!("not connected to {}", hex::encode(peer))), }; @@ -8851,32 +8511,6 @@ fn persist_direct_anchor_claim(storage: &crate::storage::Storage, e: &ReachEntry /// 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. -/// 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 { - 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( storage: &Arc, our_node_id: &NodeId, @@ -8912,24 +8546,7 @@ pub async fn initial_exchange_connect( let profile = storage.get_profile(our_node_id)? .map(|p| p.sanitized_for_network_broadcast()); let deletes = storage.list_delete_records()?; - // 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()?; + let post_ids = storage.list_post_ids()?; // Knowledge boundary: a temporary referral slot carries NO knowledge // exchange (design.html §connections). Peer addresses ARE knowledge — // up to 10 of our mesh peers with their addresses — so they are gated @@ -9032,24 +8649,7 @@ pub async fn initial_exchange_accept( let profile = storage.get_profile(our_node_id)? .map(|p| p.sanitized_for_network_broadcast()); let deletes = storage.list_delete_records()?; - // 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()?; + let post_ids = storage.list_post_ids()?; // Knowledge boundary: a temporary referral slot carries NO knowledge // exchange (design.html §connections). Peer addresses ARE knowledge — // up to 10 of our mesh peers with their addresses — so they are gated @@ -9153,11 +8753,6 @@ 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(); for pid in &payload.post_ids { if our_post_ids.contains(pid) { @@ -10054,80 +9649,6 @@ 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)] mod accept_gate_tests { //! v0.8 (A3) T9: the accept-gate matrix, exercised BOTH through the diff --git a/crates/core/src/crypto.rs b/crates/core/src/crypto.rs index 45e91b1..dbf3f0a 100644 --- a/crates/core/src/crypto.rs +++ b/crates/core/src/crypto.rs @@ -1705,7 +1705,7 @@ mod tests { fn test_manifest_carries_no_addresses() { use crate::types::{AuthorManifest, CdnManifest, ManifestEntry}; 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 { post_id: [42u8; 32], @@ -1731,6 +1731,7 @@ mod tests { let cdn = CdnManifest { author_manifest: manifest, + host: host_id, }; let cdn_json = serde_json::to_string(&cdn).unwrap(); assert!( diff --git a/crates/core/src/holdings.rs b/crates/core/src/holdings.rs deleted file mode 100644 index e901173..0000000 --- a/crates/core/src/holdings.rs +++ /dev/null @@ -1,282 +0,0 @@ -//! 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), - /// Publish the introducer's address instead of ours. - ViaIntroducer { node_id: NodeId, addresses: Vec }, -} - -impl DeclaredReach { - /// Split into the `(addresses, introducer)` pair the wire payload carries. - pub fn into_payload_parts( - self, - ) -> (Vec, Option) { - 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); - } - } -} diff --git a/crates/core/src/http.rs b/crates/core/src/http.rs index a74724c..3e43d3a 100644 --- a/crates/core/src/http.rs +++ b/crates/core/src/http.rs @@ -373,12 +373,10 @@ async fn try_redirect( Ok(Some((_, PostVisibility::Public))) => {} _ => return false, // not found or not public — hard close } - // 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) + store.get_file_holders(post_id) .unwrap_or_default() .into_iter() - .map(|(nid, _addrs, _intro)| nid) + .map(|(nid, _addrs)| nid) .collect::>() }; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 5f4d8a5..99eddcd 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -8,7 +8,6 @@ pub mod content; pub mod control; pub mod crypto; pub mod group_key_distribution; -pub mod holdings; pub mod http; pub mod export; pub mod fof; diff --git a/crates/core/src/network.rs b/crates/core/src/network.rs index 40ee20e..0777f72 100644 --- a/crates/core/src/network.rs +++ b/crates/core/src/network.rs @@ -1088,18 +1088,14 @@ impl Network { }], }; 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() { sent += 1; 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( cid, peer, - &[], + peer_addrs, crate::storage::HolderDirection::Sent, ); } @@ -1805,7 +1801,10 @@ impl Network { write_typed_message( &mut send, MessageType::BlobRequest, - &BlobRequestPayload { cid: *cid }, + &BlobRequestPayload { + cid: *cid, + requester_addresses: self.our_addresses(), + }, ) .await?; send.finish()?; @@ -1955,147 +1954,6 @@ 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::() { - 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::() { - 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 = 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. pub async fn addr_from_storage(&self, peer_id: &NodeId) -> Option { let endpoint_id = iroh::EndpointId::from_bytes(peer_id).ok()?; diff --git a/crates/core/src/node.rs b/crates/core/src/node.rs index b429d30..30695ee 100644 --- a/crates/core/src/node.rs +++ b/crates/core/src/node.rs @@ -1883,9 +1883,9 @@ impl Node { if let Ok(author_manifest) = serde_json::from_str::(push_json) { // v0.8: no device addresses ride the manifest — receivers // learn the holder from the QUIC-authenticated connection. - // v0.8.1: and no host id either — see `CdnManifest`. let cdn_manifest = crate::types::CdnManifest { author_manifest, + host: self.node_id, }; self.network.push_manifest_to_downstream(push_cid, &cdn_manifest).await; } @@ -2775,82 +2775,19 @@ impl Node { } } - // LOCAL HINT for the source (v0.8.1 PHASE 2): having served us a - // blob is not consent to be advertised as its holder. Hints drive - // our own retry/propagation only. + // Record upstream source. v0.8: manifests carry no addresses; + // the holder's address is already known from the live connection + // (peers table) — record the holder id with no manifest addrs. let _ = storage.touch_file_holder( cid, from_peer, &[], crate::storage::HolderDirection::Received, ); - drop(storage); - self.declare_blob_holding(cid, post_id, author, from_peer).await; } 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 /// delivery budget: /// 1. Local → 2. Existing upstream → 3. Lateral peers (non-anchor first) @@ -2872,7 +2809,7 @@ impl Node { } // Collect redirect peers from responses in case we need them later - let mut redirect_peers: Vec = Vec::new(); + let mut redirect_peers: Vec = Vec::new(); // 2. Try known holders (up to 5 most-recent peers we've interacted // with about this file). @@ -2909,15 +2846,12 @@ impl Node { 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( cid, &lateral, &[], crate::storage::HolderDirection::Received, ); - drop(storage); - self.declare_blob_holding(cid, post_id, author, &lateral).await; return Ok(Some(data)); } Ok((None, response)) => { @@ -2947,195 +2881,22 @@ impl Node { Err(e) => warn!(error = %e, "blob fetch from author failed"), } - // 6. Try redirect peers (from any step that returned cdn_redirect_peers). - // These are DECLARED holders only (v0.8.1 PHASE 2). + // 6. Try redirect peers (from any step that returned cdn_redirect_peers) for rp in &redirect_peers { - let Ok(nid_bytes) = hex::decode(&rp.n) else { continue }; - 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"); + if let Ok(nid_bytes) = hex::decode(&rp.n) { + if let Ok(nid) = <[u8; 32]>::try_from(nid_bytes.as_slice()) { + match self.fetch_blob_from_peer(cid, &nid, post_id, author, mime_type, created_at).await { + Ok(Some(data)) => return Ok(Some(data)), + Ok(None) => {} + Err(e) => warn!(peer = &rp.n, error = %e, "redirect blob fetch 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 { - Ok(Some(data)) => return Ok(Some(data)), - Ok(None) => {} - 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, - ) -> 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; - } - } - - /// 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 ---- pub async fn create_circle(&self, name: String) -> anyhow::Result<()> { @@ -5173,23 +4934,14 @@ impl Node { /// Delete a blob locally. BlobDeleteNotice was removed in v0.6.2; remote /// 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<()> { { 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.remove_blob(cid)?; } let _ = self.blob_store.delete(cid); - self.drain_declaration_withdrawals().await; + Ok(()) } @@ -6684,53 +6436,11 @@ impl Node { for holder in holders { let _ = self.connect_by_node_id(holder).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 _ = crate::control::receive_post( - &s, &sp.id, &sp.post, &sp.visibility, sp.intent.as_ref(), - ); - // 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, - ®, - ).await; - } - return Ok(post); + let s = self.storage.get().await; + let _ = crate::control::receive_post( + &s, &sp.id, &sp.post, &sp.visibility, sp.intent.as_ref(), + ); + return Ok(s.get_post(post_id)?); } } } @@ -7383,20 +7093,11 @@ impl Node { pub fn start_replication_cycle(self: &Arc, interval_secs: u64) -> tokio::task::JoinHandle<()> { let node = Arc::clone(self); 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) tokio::time::sleep(std::time::Duration::from_secs(120)).await; let mut interval = tokio::time::interval(std::time::Duration::from_secs(interval_secs)); loop { 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; } }) @@ -7448,17 +7149,10 @@ impl Node { } } - // 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. + // Filter to under-replicated (< 2 holders) let mut needs_replication = Vec::new(); for pid in &recent_ids { - match storage.get_durability_holder_count(pid) { + match storage.get_file_holder_count(pid) { Ok(count) if count < 2 => { needs_replication.push(*pid); } diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 992663e..1e354b8 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -2,8 +2,7 @@ use serde::{Deserialize, Serialize}; use crate::types::{ BlobHeaderDiffOp, CdnManifest, DeleteRecord, GroupEpoch, GroupId, NodeId, - CdnRedirectPeer, PeerWithAddress, Post, PostId, PostVisibility, PublicProfile, - RedirectIntroducer, WormId, + PeerWithAddress, Post, PostId, PostVisibility, PublicProfile, WormId, }; /// Wire-protocol ALPN. One protocol version per build, no negotiation — @@ -433,13 +432,11 @@ pub struct SocialCheckinPayload { #[derive(Debug, Serialize, Deserialize)] pub struct BlobRequestPayload { pub cid: [u8; 32], + /// Requester's addresses so the host can record downstream + pub requester_addresses: Vec, } /// 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)] pub struct BlobResponsePayload { pub cid: [u8; 32], @@ -448,9 +445,10 @@ pub struct BlobResponsePayload { pub data_b64: String, /// Author manifest + host info (if available) pub manifest: Option, - /// Other DECLARED holders of this CID to try. Only peers that explicitly - /// declared themselves appear here (`crate::holdings`). - pub cdn_redirect_peers: Vec, + /// Whether host accepted requester as downstream + pub cdn_registered: bool, + /// If not registered (host full), try these peers + pub cdn_redirect_peers: Vec, } /// Request a manifest refresh for a CID (bi-stream: ask upstream) @@ -687,35 +685,10 @@ pub struct BlobHeaderResponsePayload { pub header_json: Option, } -/// **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. +/// Register as a downstream holder of a post (uni-stream) #[derive(Debug, Serialize, Deserialize)] pub struct PostDownstreamRegisterPayload { 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, - /// Publish this introducer's address in place of ours - /// (`holdings.introducer_enabled`). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub introducer: Option, - /// 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) @@ -994,59 +967,6 @@ mod tests { 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] fn convection_request_carries_the_class_bit() { for class in [ConvectionClass::Entry, ConvectionClass::TopUp] { diff --git a/crates/core/src/storage.rs b/crates/core/src/storage.rs index 25ef47c..d302c6a 100644 --- a/crates/core/src/storage.rs +++ b/crates/core/src/storage.rs @@ -1,7 +1,7 @@ use std::net::SocketAddr; use std::path::Path; -use rusqlite::{params, Connection, OptionalExtension}; +use rusqlite::{params, Connection}; use crate::types::{ Attachment, Circle, CircleProfile, @@ -492,73 +492,10 @@ impl Storage { peer_addresses TEXT NOT NULL DEFAULT '[]', last_interaction_ms INTEGER NOT NULL, direction TEXT NOT NULL, - declared INTEGER NOT NULL DEFAULT 0, - introducer TEXT, - -- When this peer FIRST declared for this file, and when it - -- last did. `declared_since_ms` makes the 5-row declared - -- keep-set favour established holders, so a burst of fresh - -- (possibly Sybil) declarations cannot displace them; - -- `declared_at_ms` ages a silent declaration out, so a holder - -- that stops re-declaring stops being published. - declared_since_ms INTEGER NOT NULL DEFAULT 0, - declared_at_ms INTEGER NOT NULL DEFAULT 0, - -- Did WE observe a transport event with this peer about this - -- file? Independent of `declared`, because the two answer - -- different questions and a peer can be both. `declared` is a - -- CLAIM (cheap to forge, so useless for durability); this is - -- EVIDENCE, and it is what `get_durability_holder_count` counts. - -- Monotonic: set by the hint path, never cleared, so a witnessed - -- holder that later declares still counts toward durability. - witnessed INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (file_id, peer_id) ); CREATE INDEX IF NOT EXISTS idx_file_holders_recency ON file_holders(file_id, last_interaction_ms DESC); - -- NOTE: idx_file_holders_declared is created in `migrate()`, NOT - -- here. `init_tables()` runs BEFORE `migrate()`, so on a database - -- predating the `declared` column an index over that column would - -- fail the whole init batch and the node would refuse to open. - -- What WE have declared, so the per-(us, author) policy in - -- `crate::holdings` is enforceable and a declaration can be - -- withdrawn on delete/eviction. - -- - -- Key is (file_id, post_id): one blob CID can be referenced by two - -- posts, and a declaration must survive while ANY referencing post - -- is still held. A single-column key silently dropped the second - -- association and let `undeclare_own_post_holdings(post_A)` revoke - -- a blob we still hold for post_B. - CREATE TABLE IF NOT EXISTS declared_holdings ( - file_id BLOB NOT NULL, - post_id BLOB NOT NULL, - author BLOB NOT NULL, - reason TEXT NOT NULL, - declared_at INTEGER NOT NULL, - PRIMARY KEY (file_id, post_id) - ); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_author - ON declared_holdings(author); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_post - ON declared_holdings(post_id); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_file - ON declared_holdings(file_id); - -- Withdrawals we still owe other nodes. Written by every path that - -- retracts one of our declarations (content deleted, blob evicted, - -- policy tightened); drained by `Node::drain_declaration_withdrawals`, - -- which sends `withdraw: true` declarations. Queued rather than sent - -- inline because the retracting paths are synchronous storage code. - CREATE TABLE IF NOT EXISTS pending_withdrawals ( - file_id BLOB NOT NULL, - peer_id BLOB NOT NULL, - queued_at INTEGER NOT NULL, - PRIMARY KEY (file_id, peer_id) - ); - -- Per-peer rotation cursor for the re-declaration sweep, so every - -- declared holding eventually reaches every peer we sync with even - -- though each cycle only carries a bounded slice. - CREATE TABLE IF NOT EXISTS declaration_announce_cursor ( - peer_id BLOB PRIMARY KEY, - last_rowid INTEGER NOT NULL - ); CREATE TABLE IF NOT EXISTS post_recipients ( post_id BLOB NOT NULL, recipient BLOB NOT NULL, @@ -572,16 +509,6 @@ impl Storage { display_name TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL ); - -- Append-only ledger of every posting identity this device has - -- EVER held. `posting_identities` is mutable (personas are - -- deleted, rotated, de-personed), but the own-authored - -- declaration guard must never lapse for a retired persona — - -- declaring a post authored by a former persona publishes - -- `device <-> persona` just as loudly as a current one. - CREATE TABLE IF NOT EXISTS own_authored_identities ( - node_id BLOB PRIMARY KEY, - first_seen_ms INTEGER NOT NULL - ); -- FoF Layer 1: per-persona V_me history. Rows are append-only -- on rotation (Layer 4); old epochs retained for unwrapping -- historical wrap_slots. is_current marks the active outgoing @@ -1090,115 +1017,6 @@ impl Storage { )?; } - // v0.8.1 PHASE 2: declared holdings. - // - // MIGRATION RULING: every pre-existing `file_holders` row was INFERRED - // from a transport event — nobody consented to being advertised. They - // therefore migrate to `declared = 0` (the column default), i.e. legacy - // rows become purely local hints and stop being republished. Carrying - // them forward as declared would preserve discovery by preserving - // exactly the leak this change exists to close, and it would do so for - // rows whose subjects can never be asked. - // - // The discovery cost is bounded by TWO mechanisms that exist in code, - // not by assertion: - // 1. `Storage::backfill_declared_holdings`, run once at startup, - // re-declares every PUBLIC post and blob we already hold through - // the ordinary policy chokepoint, so an upgrading node recovers - // its own footprint without waiting for new content. - // 2. `Storage::next_declarations_to_announce`, a per-peer rotating - // sweep driven from each content-sync cycle, so a peer that wipes - // its database (or evicts a row) re-learns our declarations. - // Local fetch is unaffected throughout: `get_file_holders` still - // returns hints, only `get_declared_file_holders` is publishable. - let has_declared = self.conn.prepare( - "SELECT COUNT(*) FROM pragma_table_info('file_holders') WHERE name='declared'" - )?.query_row([], |row| row.get::<_, i64>(0))?; - if has_declared == 0 { - self.conn.execute_batch( - "ALTER TABLE file_holders ADD COLUMN declared INTEGER NOT NULL DEFAULT 0; - ALTER TABLE file_holders ADD COLUMN introducer TEXT;" - )?; - } - let has_declared_at = self.conn.prepare( - "SELECT COUNT(*) FROM pragma_table_info('file_holders') WHERE name='declared_at_ms'" - )?.query_row([], |row| row.get::<_, i64>(0))?; - if has_declared_at == 0 { - self.conn.execute_batch( - "ALTER TABLE file_holders ADD COLUMN declared_since_ms INTEGER NOT NULL DEFAULT 0; - ALTER TABLE file_holders ADD COLUMN declared_at_ms INTEGER NOT NULL DEFAULT 0;" - )?; - } - // `witnessed` separates evidence from claim. Every pre-existing row was - // INFERRED from a transport event we handled ourselves, so each one is - // witnessed — that is precisely why those rows stay usable locally after - // losing their publishability. - let has_witnessed = self.conn.prepare( - "SELECT COUNT(*) FROM pragma_table_info('file_holders') WHERE name='witnessed'" - )?.query_row([], |row| row.get::<_, i64>(0))?; - if has_witnessed == 0 { - self.conn.execute_batch( - "ALTER TABLE file_holders ADD COLUMN witnessed INTEGER NOT NULL DEFAULT 0; - UPDATE file_holders SET witnessed = 1;" - )?; - } - // ...and the ADDRESSES on those legacy rows are inferred too. They - // came from `BlobRequestPayload.requester_addresses` via - // `Network::our_addresses()`, which admits LAN/private addresses on - // purpose (they are useful for a hole punch, not for publication). If - // they survive, one later bare-id declaration from that peer flips the - // row to `declared = 1` and we start republishing an address its owner - // never consented to publish — which would defeat the whole ruling. - // A declaration is authoritative about its own reach, so the pre- - // declaration reach is cleared here and re-supplied by the declarer. - if has_declared == 0 { - self.conn.execute("UPDATE file_holders SET peer_addresses = '[]'", [])?; - } - // Unconditional, and only reachable once the column is guaranteed to - // exist (fresh DBs get it from `init_tables`, old ones from the ALTER - // directly above). - self.conn.execute_batch( - "CREATE INDEX IF NOT EXISTS idx_file_holders_declared - ON file_holders(file_id, declared, last_interaction_ms DESC);" - )?; - - // Back-fill the never-pruned own-authored ledger from whatever - // personas exist today, so the guard covers content authored before - // the ledger existed. Idempotent. - self.conn.execute( - "INSERT OR IGNORE INTO own_authored_identities (node_id, first_seen_ms) - SELECT node_id, created_at FROM posting_identities", - [], - )?; - - // `declared_holdings` was keyed on `file_id` alone in the first cut of - // this branch. Rebuild it on the composite key so a blob shared by two - // posts records both associations. Pre-release shape change; the table - // is rebuilt rather than migrated because every row in it is - // re-derivable from local content by the startup backfill. - let declared_holdings_pk_cols = self.conn.prepare( - "SELECT COUNT(*) FROM pragma_table_info('declared_holdings') WHERE pk > 0" - )?.query_row([], |row| row.get::<_, i64>(0))?; - if declared_holdings_pk_cols == 1 { - self.conn.execute_batch( - "DROP TABLE declared_holdings; - CREATE TABLE declared_holdings ( - file_id BLOB NOT NULL, - post_id BLOB NOT NULL, - author BLOB NOT NULL, - reason TEXT NOT NULL, - declared_at INTEGER NOT NULL, - PRIMARY KEY (file_id, post_id) - ); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_author - ON declared_holdings(author); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_post - ON declared_holdings(post_id); - CREATE INDEX IF NOT EXISTS idx_declared_holdings_file - ON declared_holdings(file_id);" - )?; - } - Ok(()) } @@ -3240,11 +3058,6 @@ impl Storage { params![record.post_id.as_slice(), record.author.as_slice()], )?; if deleted > 0 { - // v0.8.1: a declaration must not outlive the content it points at, - // and the retraction must reach the peers publishing us — so it - // runs BEFORE `file_holders` is cleared, which is where the - // withdrawal queue gets its recipients. - self.undeclare_own_post_holdings(&record.post_id)?; self.conn.execute("DELETE FROM file_holders WHERE file_id = ?1", params![record.post_id.as_slice()])?; self.conn.execute("DELETE FROM post_recipients WHERE post_id = ?1", params![record.post_id.as_slice()])?; self.conn.execute("DELETE FROM seen_engagement WHERE post_id = ?1", params![record.post_id.as_slice()])?; @@ -4920,11 +4733,6 @@ impl Storage { /// Clean up all CDN metadata for a blob (manifests + file_holders). pub fn cleanup_cdn_for_blob(&self, cid: &[u8; 32]) -> anyhow::Result<()> { self.conn.execute("DELETE FROM cdn_manifests WHERE cid = ?1", params![cid.as_slice()])?; - // v0.8.1: evicting the bytes withdraws our declaration for them. - // BEFORE dropping `file_holders` — the withdrawal queue is built from - // those rows, so clearing them first would retract the declaration - // locally and tell nobody. - self.undeclare_own_holding(cid)?; self.conn.execute("DELETE FROM file_holders WHERE file_id = ?1", params![cid.as_slice()])?; Ok(()) } @@ -5242,9 +5050,6 @@ impl Storage { id.created_at as i64, ], )?; - // Never-pruned record for the own-authored declaration guard: see - // `is_own_posting_identity`. - self.remember_own_authored_identity(&id.node_id)?; Ok(()) } @@ -6182,153 +5987,35 @@ impl Storage { // A single table for PostId-keyed engagement propagation and CID-keyed // manifest/blob propagation. Any 32-byte content-addressed file_id fits. - /// Record a **local hint**: we exchanged bytes about this file with this - /// peer. Bumps `last_interaction_ms` and enforces an LRU cap of 5 holders - /// per file. - /// - /// v0.8.1 PHASE 2 — a hint is NEVER published. It is usable as a fetch - /// retry source, a diff-propagation target and a manifest-refresh source, - /// all of which are things *we* do to the peer, not things we tell third - /// parties about it. Anything outbound must go through - /// [`Storage::get_declared_file_holders`]. This function can only ever - /// create `declared = 0` rows and never clears an existing declaration — - /// a declared holder that we then exchange bytes with stays declared. + /// Upsert a holder for a file. Bumps last_interaction_ms to now and + /// enforces an LRU cap of 5 holders per file. pub fn touch_file_holder( &self, file_id: &[u8; 32], peer_id: &NodeId, peer_addresses: &[String], direction: HolderDirection, - ) -> anyhow::Result<()> { - self.upsert_file_holder(file_id, peer_id, peer_addresses, direction, None) - } - - /// Record an explicit **declaration**: this peer told us it holds the file - /// and that we may advertise it as a source (`MessageType::PostDownstreamRegister`). - /// - /// `introducer` is the holder's nominated stand-in address, if it published - /// one instead of its own (see `crate::holdings::DeclaredReach`). - pub fn record_declared_holder( - &self, - file_id: &[u8; 32], - peer_id: &NodeId, - peer_addresses: &[String], - direction: HolderDirection, - introducer: Option<&crate::types::RedirectIntroducer>, - ) -> anyhow::Result<()> { - let intro_json = match introducer { - Some(i) => Some(serde_json::to_string(i)?), - None => None, - }; - self.upsert_file_holder(file_id, peer_id, peer_addresses, direction, Some(intro_json)) - } - - /// Withdraw a peer's declaration without forgetting the local hint. Used - /// when a holder tells us it is shedding the file. - /// - /// Clears the published reach too: the addresses and introducer on the row - /// were supplied BY the declaration, so they must not outlive it and be - /// picked up again by a later bare declaration. - pub fn clear_holder_declaration( - &self, - file_id: &[u8; 32], - peer_id: &NodeId, - ) -> anyhow::Result<()> { - self.conn.execute( - "UPDATE file_holders - SET declared = 0, introducer = NULL, peer_addresses = '[]', - declared_since_ms = 0, declared_at_ms = 0 - WHERE file_id = ?1 AND peer_id = ?2", - params![file_id.as_slice(), peer_id.as_slice()], - )?; - Ok(()) - } - - /// Shared upsert. `declare = None` leaves the declaration flag untouched - /// (hint path); `Some(intro)` sets `declared = 1` and stores the introducer. - fn upsert_file_holder( - &self, - file_id: &[u8; 32], - peer_id: &NodeId, - peer_addresses: &[String], - direction: HolderDirection, - declare: Option>, ) -> anyhow::Result<()> { let addrs_json = serde_json::to_string(peer_addresses)?; let now = now_ms(); let new_dir = direction.as_str(); - let declared_flag: i64 = if declare.is_some() { 1 } else { 0 }; - let intro_json: Option = declare.clone().flatten(); - // Upsert. If the row exists with a different direction, promote to - // "both". `declared` is monotonic: a hint never demotes a declaration, - // only `clear_holder_declaration` does. - // - // ADDRESSES: a DECLARATION is authoritative about its own reach, so the - // declare path writes `?3` unconditionally — an empty list CLEARS a - // previously published address. Without that, a bare-id declaration - // (the default shape for every non-anchor) silently resurrects an - // address captured earlier: a legacy inferred one, or a stale anchor - // address from before the v0.7.2 reachability watcher cleared - // `is_anchor`. The HINT path keeps the "don't overwrite with nothing" - // guard, because a hint carries no reach claim at all. + // Upsert. If the row exists with a different direction, promote to "both". self.conn.execute( - "INSERT INTO file_holders - (file_id, peer_id, peer_addresses, last_interaction_ms, direction, declared, - introducer, declared_since_ms, declared_at_ms, witnessed) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, ?9) + "INSERT INTO file_holders (file_id, peer_id, peer_addresses, last_interaction_ms, direction) + VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(file_id, peer_id) DO UPDATE SET - witnessed = MAX(witnessed, ?9), - peer_addresses = CASE - WHEN ?6 = 1 THEN ?3 - WHEN length(?3) > 2 THEN ?3 - ELSE peer_addresses END, + peer_addresses = CASE WHEN length(?3) > 2 THEN ?3 ELSE peer_addresses END, last_interaction_ms = ?4, - direction = CASE WHEN direction = ?5 THEN direction ELSE 'both' END, - declared = MAX(declared, ?6), - introducer = CASE WHEN ?6 = 1 THEN ?7 ELSE introducer END, - declared_since_ms = CASE - WHEN ?6 = 1 AND declared_since_ms = 0 THEN ?8 - ELSE declared_since_ms END, - declared_at_ms = CASE WHEN ?6 = 1 THEN ?8 ELSE declared_at_ms END", - params![ - file_id.as_slice(), peer_id.as_slice(), addrs_json, now as i64, - new_dir, declared_flag, intro_json, - if declared_flag == 1 { now as i64 } else { 0i64 }, - // The hint path is the one that witnessed something. - 1i64 - declared_flag - ], + direction = CASE WHEN direction = ?5 THEN direction ELSE 'both' END", + params![file_id.as_slice(), peer_id.as_slice(), addrs_json, now as i64, new_dir], )?; - // Enforce the per-file cap WITHIN each class, 5 declared + 5 hints, - // rather than ranking one against the other. - // - // Ranking `declared DESC` first had two failure modes: five declared - // rows starved every subsequent transport hint (so on exactly the hot - // open-slot posts — registry, greeting bios — a peer that had just sent - // us a comment was recorded and instantly deleted, losing it as a diff - // target and as a proven fetch source), and nothing could ever evict a - // declared row, so a Sybil burst was permanent. - // - // Within the declared class the keep-set favours the LONGEST-ESTABLISHED - // holders, so a burst of fresh declarations cannot displace holders that - // have been serving a file; declarations that go silent age out through - // `DECLARATION_TTL_MS` instead. + // Enforce LRU cap of 5. Oldest get dropped. self.conn.execute( "DELETE FROM file_holders - WHERE file_id = ?1 AND declared = 1 + WHERE file_id = ?1 AND peer_id NOT IN ( SELECT peer_id FROM file_holders - WHERE file_id = ?1 AND declared = 1 - ORDER BY declared_since_ms ASC, last_interaction_ms DESC - LIMIT 5 - )", - params![file_id.as_slice()], - )?; - self.conn.execute( - "DELETE FROM file_holders - WHERE file_id = ?1 AND declared = 0 - AND peer_id NOT IN ( - SELECT peer_id FROM file_holders - WHERE file_id = ?1 AND declared = 0 + WHERE file_id = ?1 ORDER BY last_interaction_ms DESC LIMIT 5 )", @@ -6337,41 +6024,7 @@ impl Storage { Ok(()) } - /// Declared rows for a single peer, across all files. Bounds how much of - /// our `file_holders` one peer can occupy (`file_holders` has only a - /// per-file cap, so without this one peer could grow the table without - /// limit by declaring many files). - pub fn count_declared_rows_for_peer(&self, peer_id: &NodeId) -> anyhow::Result { - let count: i64 = self.conn.prepare( - "SELECT COUNT(*) FROM file_holders WHERE peer_id = ?1 AND declared = 1", - )?.query_row(params![peer_id.as_slice()], |row| row.get(0))?; - Ok(count as u32) - } - - /// Do we track this file at all? A declaration for a file we have never - /// heard of is either noise or an attempt to grow `file_holders` without - /// bound, and no legitimate declarer sends one: a node declares to the peer - /// that just served it the file. - pub fn tracks_file(&self, file_id: &[u8; 32]) -> bool { - let known: i64 = match self.conn.prepare( - "SELECT - (SELECT COUNT(*) FROM posts WHERE id = ?1) - + (SELECT COUNT(*) FROM blobs WHERE cid = ?1) - + (SELECT COUNT(*) FROM cdn_manifests WHERE cid = ?1) - + (SELECT COUNT(*) FROM declared_holdings WHERE file_id = ?1)", - ) { - Ok(mut stmt) => stmt - .query_row(params![file_id.as_slice()], |row| row.get(0)) - .unwrap_or(0), - Err(_) => 0, - }; - known > 0 - } - - /// Count file holders, declared or hinted (bounded at 5 by the LRU cap). - /// - /// Durability questions ("is my own post under-replicated?") want this - /// count, not the declared one: a silent holder is still a copy. + /// Count file holders (bounded at 5 by touch_file_holder's LRU cap). pub fn get_file_holder_count(&self, file_id: &[u8; 32]) -> anyhow::Result { let count: i64 = self.conn.prepare( "SELECT COUNT(*) FROM file_holders WHERE file_id = ?1", @@ -6379,122 +6032,27 @@ impl Storage { Ok(count as u32) } - /// Return the up-to-5 most recently interacted holders of a file, - /// declared or hinted. **LOCAL USE ONLY** — see - /// [`Storage::get_declared_file_holders`] for anything that leaves the node. + /// Return the up-to-5 most recently interacted holders of a file. pub fn get_file_holders(&self, file_id: &[u8; 32]) -> anyhow::Result)>> { - let rows = self.query_file_holders(file_id, false)?; - Ok(rows.into_iter().map(|(n, a, _)| (n, a)).collect()) - } - - /// Holders of a file we have EVIDENCE for, for durability decisions. - /// - /// Counts peers we actually exchanged bytes with about this file - /// (`witnessed = 1` — our own observation, unforgeable by a third party) - /// plus peers that announced the same post id in an initial exchange - /// (`post_replicas`). Deliberately excludes a holder known ONLY by its own - /// declaration: a claimed holder set is cheap to forge, and a forged "this - /// is healthy" suppresses healing, so replication must never be gated on - /// claims. - /// - /// It keys on `witnessed`, NOT on `declared = 0`. Those are not complements - /// — a peer we served and which then declared is both, and testing - /// `declared = 0` dropped exactly those peers from the count, so every - /// honest custodian that declared made its author's post look LESS durable - /// and provoked more replication. - pub fn get_durability_holder_count(&self, file_id: &[u8; 32]) -> anyhow::Result { - let count: i64 = self.conn.prepare( - "SELECT COUNT(*) FROM ( - SELECT peer_id AS p FROM file_holders - WHERE file_id = ?1 AND witnessed = 1 - UNION - SELECT node_id AS p FROM post_replicas WHERE post_id = ?1 - )", - )?.query_row(params![file_id.as_slice()], |row| row.get(0))?; - Ok(count as u32) - } - - /// Return the up-to-5 most recent holders of a file that DECLARED - /// themselves for it. This is the only holder list that may be put on the - /// wire, written into an HTTP redirect, or otherwise disclosed to a third - /// party. - /// - /// Third element is the holder's nominated introducer, if any. - #[allow(clippy::type_complexity)] - pub fn get_declared_file_holders( - &self, - file_id: &[u8; 32], - ) -> anyhow::Result, Option)>> { - self.query_file_holders(file_id, true) - } - - /// Count only the holders that declared themselves for a file. - pub fn get_declared_file_holder_count(&self, file_id: &[u8; 32]) -> anyhow::Result { - let _ = self.expire_stale_declarations(file_id); - let count: i64 = self.conn.prepare( - "SELECT COUNT(*) FROM file_holders WHERE file_id = ?1 AND declared = 1", - )?.query_row(params![file_id.as_slice()], |row| row.get(0))?; - Ok(count as u32) - } - - /// Drop declarations that have gone silent. A declaration is SOFT STATE — - /// it is re-sent by the declarer's rotating sweep - /// ([`Storage::next_declarations_to_announce`]) — so one that has not been - /// renewed within `crate::holdings::DECLARATION_TTL_MS` means the holder is gone, has - /// evicted the file, or never implemented the sweep. Publishing it sends - /// fetchers to a dead end and (under the erasure model) misreports slot - /// health, so it expires rather than living forever. - /// - /// Demotes to a local hint rather than deleting the row: the peer may well - /// still be a useful fetch/propagation target, it just may not be named to - /// third parties. - fn expire_stale_declarations(&self, file_id: &[u8; 32]) -> anyhow::Result<()> { - let cutoff = now_ms().saturating_sub(crate::holdings::DECLARATION_TTL_MS as i64); - self.conn.execute( - "UPDATE file_holders - SET declared = 0, introducer = NULL, peer_addresses = '[]', - declared_since_ms = 0, declared_at_ms = 0 - WHERE file_id = ?1 AND declared = 1 AND declared_at_ms < ?2", - params![file_id.as_slice(), cutoff], - )?; - Ok(()) - } - - #[allow(clippy::type_complexity)] - fn query_file_holders( - &self, - file_id: &[u8; 32], - declared_only: bool, - ) -> anyhow::Result, Option)>> { - let sql = if declared_only { - let _ = self.expire_stale_declarations(file_id); - "SELECT peer_id, peer_addresses, introducer FROM file_holders - WHERE file_id = ?1 AND declared = 1 - ORDER BY last_interaction_ms DESC - LIMIT 5" - } else { - "SELECT peer_id, peer_addresses, introducer FROM file_holders + let mut stmt = self.conn.prepare( + "SELECT peer_id, peer_addresses FROM file_holders WHERE file_id = ?1 ORDER BY last_interaction_ms DESC - LIMIT 5" - }; - let mut stmt = self.conn.prepare(sql)?; + LIMIT 5", + )?; let rows = stmt.query_map(params![file_id.as_slice()], |row| { let peer_bytes: Vec = row.get(0)?; let addrs_json: String = row.get(1)?; - let intro_json: Option = row.get(2)?; - Ok((peer_bytes, addrs_json, intro_json)) + Ok((peer_bytes, addrs_json)) })?; let mut out = Vec::new(); for row in rows { - let (peer_bytes, addrs_json, intro_json) = row?; + let (peer_bytes, addrs_json) = row?; if peer_bytes.len() != 32 { continue; } let mut peer = [0u8; 32]; peer.copy_from_slice(&peer_bytes); let addrs: Vec = serde_json::from_str(&addrs_json).unwrap_or_default(); - let intro = intro_json - .and_then(|j| serde_json::from_str::(&j).ok()); - out.push((NodeId::from(peer), addrs, intro)); + out.push((NodeId::from(peer), addrs)); } Ok(out) } @@ -6508,637 +6066,6 @@ impl Storage { Ok(()) } - // --- Our own declared holdings (crate::holdings) --- - - /// Read the local declaration policy out of `settings`. - pub fn holdings_policy(&self) -> crate::holdings::HoldingsPolicy { - use crate::holdings::*; - let d = HoldingsPolicy::default(); - let flag = |key: &str, fallback: bool| -> bool { - match self.get_setting(key) { - Ok(Some(v)) => v == "true", - _ => fallback, - } - }; - HoldingsPolicy { - declare_custodial: flag(SETTING_DECLARE_CUSTODIAL, d.declare_custodial), - declare_interest: flag(SETTING_DECLARE_INTEREST, d.declare_interest), - declare_own_authored: flag(SETTING_DECLARE_OWN_AUTHORED, d.declare_own_authored), - cap_per_author: self - .get_setting(SETTING_CAP_PER_AUTHOR) - .ok() - .flatten() - .and_then(|v| v.parse::().ok()) - .unwrap_or(d.cap_per_author), - } - } - - /// Number of DISTINCT posts of `author` we have already declared. This is - /// the Round 10 per-(holder, author) listing axis. - pub fn count_declared_posts_for_author(&self, author: &NodeId) -> anyhow::Result { - let count: i64 = self.conn.prepare( - "SELECT COUNT(DISTINCT post_id) FROM declared_holdings WHERE author = ?1", - )?.query_row(params![author.as_slice()], |row| row.get(0))?; - Ok(count as u32) - } - - /// Have we declared this exact file, under any post? - pub fn is_own_holding_declared(&self, file_id: &[u8; 32]) -> anyhow::Result { - let count: i64 = self.conn.prepare( - "SELECT COUNT(*) FROM declared_holdings WHERE file_id = ?1", - )?.query_row(params![file_id.as_slice()], |row| row.get(0))?; - Ok(count > 0) - } - - /// Is this id one of our own posting identities — ever, not just currently? - /// - /// The own-authored guard is what keeps Iteration A's `device <-> persona` - /// leak closed, so it must not lapse when a persona is rotated out, - /// retired or de-personed (`reference_identity_architecture.md`). Current - /// `posting_identities` alone would let a rotated-out persona's posts - /// become freely declarable, publishing the very binding the guard exists - /// to prevent — so we also consult the append-only - /// `own_authored_identities` ledger, which every persona insert appends to - /// and nothing removes from. (Greeting reply keys are deliberately NOT in - /// scope: they sign comments, not posts, so no `posts.author` row can - /// carry one.) - pub fn is_own_posting_identity(&self, id: &NodeId) -> anyhow::Result { - let count: i64 = self.conn.prepare( - "SELECT - (SELECT COUNT(*) FROM posting_identities WHERE node_id = ?1) - + (SELECT COUNT(*) FROM own_authored_identities WHERE node_id = ?1)", - )?.query_row(params![id.as_slice()], |row| row.get(0))?; - Ok(count > 0) - } - - /// Append an identity to the never-pruned own-authored ledger. Called - /// whenever a posting identity is created, and by the startup sweep that - /// back-fills existing ones, so that retiring a persona cannot re-open the - /// own-authored declaration path. - pub fn remember_own_authored_identity(&self, id: &NodeId) -> anyhow::Result<()> { - self.conn.execute( - "INSERT OR IGNORE INTO own_authored_identities (node_id, first_seen_ms) - VALUES (?1, ?2)", - params![id.as_slice(), now_ms() as i64], - )?; - Ok(()) - } - - /// Would `policy` admit a declaration for this file, WITHOUT recording - /// one? Used where the decision must be made before the bytes land. - /// - /// The policy is passed in rather than read here: a caller deciding for a - /// batch of files reads it once ([`Storage::holdings_policy`] is four - /// `settings` queries) instead of twice per file. This runs inside a held - /// storage guard, and this codebase has a recorded history of lock - /// contention. - pub fn would_declare_own_holding_with( - &self, - policy: &crate::holdings::HoldingsPolicy, - file_id: &[u8; 32], - post_id: &PostId, - author: &NodeId, - reason: crate::holdings::DeclareReason, - ) -> anyhow::Result { - // SINGLE CHOKEPOINT for the own-authored rule. Every declaration in the - // tree routes through here, so the guard cannot be forgotten at a call - // site: see `HoldingsPolicy::declare_own_authored`. - // - // Checked BEFORE the "already declared" short-circuit, so turning the - // knob off is not silently re-affirmed by a repeat declaration of a - // file that was declared while it was on. - if !policy.declare_own_authored && self.is_own_posting_identity(author).unwrap_or(false) { - return Ok(false); - } - // The CLASS switch also sits above the "already declared" - // short-circuit, so disabling a class refuses a repeat declaration of - // a file that was declared while it was on. - if !policy.class_allows(reason) { - return Ok(false); - } - // SECOND CHOKEPOINT: visibility. A declaration says "advertise me as a - // source for this file"; made about a DM, a group post or an FoFClosed - // post it announces our membership in that post's audience. Enforced - // here rather than at each call site because three call sites already - // had to remember it and one of them (replicated attachments) did not. - if let Ok(Some((_, vis))) = self.get_post_with_visibility(post_id) { - if !matches!(vis, PostVisibility::Public) { - return Ok(false); - } - } - if self.is_own_holding_declared(file_id)? { - return Ok(true); - } - let post_already: i64 = self.conn.prepare( - "SELECT COUNT(*) FROM declared_holdings WHERE post_id = ?1 AND author = ?2", - )?.query_row(params![post_id.as_slice(), author.as_slice()], |row| row.get(0))?; - let distinct = self.count_declared_posts_for_author(author)?; - Ok(policy.allows(reason, distinct, post_already > 0)) - } - - /// [`Storage::would_declare_own_holding_with`] reading the policy itself. - pub fn would_declare_own_holding( - &self, - file_id: &[u8; 32], - post_id: &PostId, - author: &NodeId, - reason: crate::holdings::DeclareReason, - ) -> anyhow::Result { - let policy = self.holdings_policy(); - self.would_declare_own_holding_with(&policy, file_id, post_id, author, reason) - } - - /// Apply the policy and, if it admits, record the declaration. Returns - /// whether this file may now be advertised on our behalf. - pub fn declare_own_holding( - &self, - file_id: &[u8; 32], - post_id: &PostId, - author: &NodeId, - reason: crate::holdings::DeclareReason, - ) -> anyhow::Result { - let policy = self.holdings_policy(); - self.declare_own_holding_with(&policy, file_id, post_id, author, reason) - } - - /// [`Storage::declare_own_holding`] against a pre-read policy. - pub fn declare_own_holding_with( - &self, - policy: &crate::holdings::HoldingsPolicy, - file_id: &[u8; 32], - post_id: &PostId, - author: &NodeId, - reason: crate::holdings::DeclareReason, - ) -> anyhow::Result { - if !self.would_declare_own_holding_with(policy, file_id, post_id, author, reason)? { - return Ok(false); - } - self.conn.execute( - "INSERT INTO declared_holdings (file_id, post_id, author, reason, declared_at) - VALUES (?1, ?2, ?3, ?4, ?5) - ON CONFLICT(file_id, post_id) DO UPDATE SET - declared_at = ?5, - reason = ?4, - author = ?3", - params![ - file_id.as_slice(), post_id.as_slice(), author.as_slice(), - reason.as_str(), now_ms() as i64 - ], - )?; - Ok(true) - } - - /// Withdraw our declaration for a file (delete, eviction, shed) and queue a - /// `withdraw: true` declaration to every peer that may be publishing us. - pub fn undeclare_own_holding(&self, file_id: &[u8; 32]) -> anyhow::Result<()> { - let was_declared = self.is_own_holding_declared(file_id)?; - self.conn.execute( - "DELETE FROM declared_holdings WHERE file_id = ?1", - params![file_id.as_slice()], - )?; - if was_declared { - self.queue_declaration_withdrawal(file_id)?; - } - Ok(()) - } - - /// Withdraw every declaration attached to a post (the post itself and all - /// of its attachment CIDs) — but keep a blob that another post we still - /// hold also references, since we still hold it and still serve it. - pub fn undeclare_own_post_holdings(&self, post_id: &PostId) -> anyhow::Result<()> { - let mut victims: Vec<[u8; 32]> = Vec::new(); - { - let mut stmt = self.conn.prepare( - "SELECT file_id FROM declared_holdings WHERE post_id = ?1 OR file_id = ?1", - )?; - let rows = stmt.query_map(params![post_id.as_slice()], |row| row.get::<_, Vec>(0))?; - for r in rows { - if let Ok(b) = r { - if b.len() == 32 { - let mut f = [0u8; 32]; - f.copy_from_slice(&b); - victims.push(f); - } - } - } - } - self.conn.execute( - "DELETE FROM declared_holdings WHERE post_id = ?1 OR file_id = ?1", - params![post_id.as_slice()], - )?; - for f in victims { - // Still declared under a different post that references the same - // blob? Then nothing was withdrawn and nobody needs telling. - if !self.is_own_holding_declared(&f)? { - self.queue_declaration_withdrawal(&f)?; - } - } - Ok(()) - } - - /// Queue a withdrawal for every peer we have a holder row for, so - /// `Node::drain_declaration_withdrawals` can tell them to stop publishing - /// us for this file. Both classes of row are queued: a peer that holds our - /// declaration is not necessarily one we currently have a declared row for. - fn queue_declaration_withdrawal(&self, file_id: &[u8; 32]) -> anyhow::Result<()> { - self.conn.execute( - "INSERT OR IGNORE INTO pending_withdrawals (file_id, peer_id, queued_at) - SELECT ?1, peer_id, ?2 FROM file_holders WHERE file_id = ?1", - params![file_id.as_slice(), now_ms() as i64], - )?; - Ok(()) - } - - /// Take queued withdrawals, newest-last, and clear them. Callers send a - /// `withdraw: true` declaration per (peer, file). - pub fn take_pending_withdrawals(&self, limit: usize) -> anyhow::Result> { - let mut out: Vec<([u8; 32], NodeId)> = Vec::new(); - { - let mut stmt = self.conn.prepare( - "SELECT file_id, peer_id FROM pending_withdrawals - ORDER BY queued_at ASC LIMIT ?1", - )?; - let rows = stmt.query_map(params![limit as i64], |row| { - Ok((row.get::<_, Vec>(0)?, row.get::<_, Vec>(1)?)) - })?; - for r in rows { - let (f, p) = r?; - if f.len() != 32 || p.len() != 32 { continue; } - let mut fid = [0u8; 32]; - fid.copy_from_slice(&f); - out.push((fid, blob_to_nodeid(p)?)); - } - } - for (fid, peer) in &out { - self.conn.execute( - "DELETE FROM pending_withdrawals WHERE file_id = ?1 AND peer_id = ?2", - params![fid.as_slice(), peer.as_slice()], - )?; - } - Ok(out) - } - - /// Re-evaluate every existing declaration against the CURRENT policy and - /// retract the ones it no longer admits, queueing a withdrawal for each. - /// - /// Called from every policy setter. Without this, the knobs are write-only - /// for anything already declared: turning a class off, or lowering - /// `cap_per_author` from the deliberately generous alpha default, would - /// stop NEW declarations while the existing footprint stayed published - /// forever — so the alpha's uncapped shape would be permanent and Round - /// 10's target cap unreachable without wiping the database. - /// - /// For the cap, the N most recently declared posts per author are kept. - /// - /// This is also the only reader of `declared_holdings.reason`: the column - /// exists so a class switch can be applied retroactively to the rows that - /// class created, which is exactly what happens here. - pub fn prune_declarations_for_policy(&self) -> anyhow::Result { - let policy = self.holdings_policy(); - // (file_id, post_id, author, reason, declared_at) - #[allow(clippy::type_complexity)] - let rows: Vec<([u8; 32], PostId, NodeId, String, i64)> = { - let mut stmt = self.conn.prepare( - "SELECT file_id, post_id, author, reason, declared_at FROM declared_holdings", - )?; - let mapped = stmt.query_map([], |row| { - Ok(( - row.get::<_, Vec>(0)?, - row.get::<_, Vec>(1)?, - row.get::<_, Vec>(2)?, - row.get::<_, String>(3)?, - row.get::<_, i64>(4)?, - )) - })?; - let mut v = Vec::new(); - for r in mapped { - let (f, p, a, reason, at) = r?; - if f.len() != 32 || p.len() != 32 || a.len() != 32 { continue; } - let mut fid = [0u8; 32]; - fid.copy_from_slice(&f); - v.push((fid, blob_to_postid(p)?, blob_to_nodeid(a)?, reason, at)); - } - v - }; - - // Per author, the set of post ids the cap allows to stay: the most - // recently declared `cap_per_author`. - let mut by_author: std::collections::HashMap> = - std::collections::HashMap::new(); - for (_, post_id, author, _, at) in &rows { - let e = by_author.entry(*author).or_default(); - if !e.iter().any(|(p, _)| p == post_id) { - e.push((*post_id, *at)); - } else if let Some(slot) = e.iter_mut().find(|(p, _)| p == post_id) { - slot.1 = slot.1.max(*at); - } - } - let mut keep_posts: std::collections::HashMap> = - std::collections::HashMap::new(); - for (author, mut posts) in by_author { - posts.sort_by(|a, b| b.1.cmp(&a.1)); - let keep: std::collections::HashSet = if policy.cap_per_author == 0 { - posts.iter().map(|(p, _)| *p).collect() - } else { - posts.iter().take(policy.cap_per_author as usize).map(|(p, _)| *p).collect() - }; - keep_posts.insert(author, keep); - } - - let mut removed = 0usize; - for (file_id, post_id, author, reason, _) in &rows { - let reason = crate::holdings::DeclareReason::from_str_label(reason); - let class_ok = match reason { - crate::holdings::DeclareReason::Custodial => policy.declare_custodial, - crate::holdings::DeclareReason::Interest => policy.declare_interest, - }; - let own_ok = policy.declare_own_authored - || !self.is_own_posting_identity(author).unwrap_or(false); - let cap_ok = keep_posts - .get(author) - .map(|k| k.contains(post_id)) - .unwrap_or(false); - if class_ok && own_ok && cap_ok { - continue; - } - self.conn.execute( - "DELETE FROM declared_holdings WHERE file_id = ?1 AND post_id = ?2", - params![file_id.as_slice(), post_id.as_slice()], - )?; - if !self.is_own_holding_declared(file_id)? { - self.queue_declaration_withdrawal(file_id)?; - } - removed += 1; - } - Ok(removed) - } - - /// Re-declare what we already hold, through the ordinary policy chokepoint. - /// - /// This is the migration's recovery path, made real. Every pre-existing - /// `file_holders` row became an undeclared hint on upgrade, and - /// `declared_holdings` starts EMPTY, so without a backfill a node's whole - /// pre-upgrade corpus could never be named by any peer: a permanent - /// discovery dip rather than the bounded one the ruling assumes. Runs at - /// startup, is idempotent, and declares only PUBLIC content (the - /// visibility and own-authored guards live in the chokepoint). - /// - /// Returns the file ids newly admitted, for the caller to announce. - pub fn backfill_declared_holdings(&self, limit: usize) -> anyhow::Result> { - let policy = self.holdings_policy(); - let mut admitted: Vec<[u8; 32]> = Vec::new(); - - // Public posts we hold. - let posts: Vec<(PostId, NodeId)> = { - let mut stmt = self.conn.prepare( - "SELECT id, author FROM posts WHERE visibility = '\"Public\"' LIMIT ?1", - )?; - let mapped = stmt.query_map(params![limit as i64], |row| { - Ok((row.get::<_, Vec>(0)?, row.get::<_, Vec>(1)?)) - })?; - let mut v = Vec::new(); - for r in mapped { - let (p, a) = r?; - v.push((blob_to_postid(p)?, blob_to_nodeid(a)?)); - } - v - }; - for (post_id, author) in &posts { - if self - .declare_own_holding_with( - &policy, post_id, post_id, author, - crate::holdings::DeclareReason::Interest, - ) - .unwrap_or(false) - { - admitted.push(*post_id); - } - } - - // Blobs we hold, attributed to their post. - let blobs: Vec<([u8; 32], PostId, NodeId)> = { - let mut stmt = self.conn.prepare( - "SELECT cid, post_id, author FROM blobs LIMIT ?1", - )?; - let mapped = stmt.query_map(params![limit as i64], |row| { - Ok(( - row.get::<_, Vec>(0)?, - row.get::<_, Vec>(1)?, - row.get::<_, Vec>(2)?, - )) - })?; - let mut v = Vec::new(); - for r in mapped { - let (c, p, a) = r?; - if c.len() != 32 { continue; } - let mut cid = [0u8; 32]; - cid.copy_from_slice(&c); - v.push((cid, blob_to_postid(p)?, blob_to_nodeid(a)?)); - } - v - }; - for (cid, post_id, author) in &blobs { - if self - .declare_own_holding_with( - &policy, cid, post_id, author, - crate::holdings::DeclareReason::Interest, - ) - .unwrap_or(false) - { - admitted.push(*cid); - } - } - Ok(admitted) - } - - /// Next slice of our declared holdings to RE-DECLARE to `peer`. - /// - /// Declarations are soft state in the peer's `file_holders` (capped at 5 - /// per file, aged out by `DECLARATION_TTL_MS`, and lost outright if the - /// peer reinstalls), so a one-shot declaration at acquisition is not - /// enough: it would make a wiped peer's view of us unrecoverable and a - /// cap-evicted row gone for good. This walks `declared_holdings` in rowid - /// order with a PER-PEER cursor, so each sync cycle carries a bounded - /// slice and successive cycles cover everything, wrapping at the end. - pub fn next_declarations_to_announce( - &self, - peer_id: &NodeId, - limit: usize, - ) -> anyhow::Result> { - let cursor: i64 = self.conn.prepare( - "SELECT last_rowid FROM declaration_announce_cursor WHERE peer_id = ?1", - )?.query_row(params![peer_id.as_slice()], |row| row.get(0)).optional()?.unwrap_or(0); - - let mut out: Vec<[u8; 32]> = Vec::new(); - let mut last = cursor; - { - let mut stmt = self.conn.prepare( - "SELECT rowid, file_id FROM declared_holdings - WHERE rowid > ?1 ORDER BY rowid ASC LIMIT ?2", - )?; - let rows = stmt.query_map(params![cursor, limit as i64], |row| { - Ok((row.get::<_, i64>(0)?, row.get::<_, Vec>(1)?)) - })?; - for r in rows { - let (rid, f) = r?; - last = rid; - if f.len() != 32 { continue; } - let mut fid = [0u8; 32]; - fid.copy_from_slice(&f); - if !out.contains(&fid) { - out.push(fid); - } - } - } - // Short slice = we reached the end; wrap so the next cycle restarts. - let next_cursor = if out.len() < limit { 0 } else { last }; - self.conn.execute( - "INSERT INTO declaration_announce_cursor (peer_id, last_rowid) VALUES (?1, ?2) - ON CONFLICT(peer_id) DO UPDATE SET last_rowid = ?2", - params![peer_id.as_slice(), next_cursor], - )?; - Ok(out) - } - - /// Post ids we are willing to ANNOUNCE in the initial exchange. - /// - /// Consent-shaped, not "everything we have": ids we have deliberately - /// declared, plus PUBLIC posts authored by one of our own personas (which - /// we serve publicly anyway, and which the author needs announced so peers - /// can record themselves as replicas for its durability check). Non-public - /// rows never appear — announcing a DM/group/FoFClosed id tells a peer who - /// knows that id that we are in its audience. - pub fn list_announceable_post_ids(&self) -> anyhow::Result> { - let mut stmt = self.conn.prepare( - "SELECT DISTINCT p.id FROM posts p - WHERE p.visibility = '\"Public\"' - AND (p.id IN (SELECT file_id FROM declared_holdings) - OR p.author IN (SELECT node_id FROM posting_identities))", - )?; - let rows = stmt.query_map([], |row| row.get::<_, Vec>(0))?; - let mut ids = Vec::new(); - for row in rows { - ids.push(blob_to_postid(row?)?); - } - Ok(ids) - } - - /// How many files we have declared. - pub fn count_declared_holdings(&self) -> anyhow::Result { - let n: i64 = self.conn.prepare( - "SELECT COUNT(DISTINCT file_id) FROM declared_holdings", - )?.query_row([], |row| row.get(0))?; - Ok(n as u32) - } - - /// Across how many distinct authors. - pub fn count_declared_authors(&self) -> anyhow::Result { - let n: i64 = self.conn.prepare( - "SELECT COUNT(DISTINCT author) FROM declared_holdings", - )?.query_row([], |row| row.get(0))?; - Ok(n as u32) - } - - /// Resolve the introducer to publish in place of our own address, if the - /// option is enabled (`holdings.introducer_enabled`, default OFF). - /// - /// An explicit `holdings.introducer_peer` wins; otherwise an anchor is - /// auto-picked, because an anchor's address is already public by its own - /// opt-in, so nominating one discloses nothing new about the anchor while - /// removing our address from the holder list. - /// - /// `connected` is the set of peers we currently have a live connection to, - /// and the candidate MUST be in it. The 0xB0 handler can only introduce a - /// target it is itself connected to (or has TTL reporters for), so an - /// introducer we are not connected to refuses every fetcher while we stay - /// listed as a holder — strictly worse than publishing nothing, because - /// the redirect slot is consumed. Callers re-resolve on every declaration, - /// so the nomination follows the connection rather than outliving it. - pub fn resolve_declared_introducer( - &self, - connected: &[NodeId], - ) -> Option { - use crate::holdings::{SETTING_INTRODUCER_ENABLED, SETTING_INTRODUCER_PEER}; - if self.get_setting(SETTING_INTRODUCER_ENABLED).ok().flatten().as_deref() != Some("true") { - return None; - } - if connected.is_empty() { - return None; - } - let explicit = self - .get_setting(SETTING_INTRODUCER_PEER) - .ok() - .flatten() - .filter(|s| !s.is_empty()) - .and_then(|hex_id| crate::parse_node_id_hex(&hex_id).ok()); - let (nid, addrs) = match explicit { - Some(nid) => { - if !connected.contains(&nid) { - return None; - } - let rec = self.get_peer_record(&nid).ok().flatten()?; - (nid, rec.addresses) - } - None => { - let rec = self - .list_anchor_peers() - .ok()? - .into_iter() - .find(|r| !r.addresses.is_empty() && connected.contains(&r.node_id))?; - (rec.node_id, rec.addresses) - } - }; - let addrs: Vec = addrs - .iter() - .filter(|a| crate::network::is_publicly_routable(a)) - .take(crate::holdings::MAX_DECLARED_ADDRESSES) - .map(|a| crate::connection::normalize_addr(*a).to_string()) - .collect(); - if addrs.is_empty() { - return None; - } - Some(crate::types::RedirectIntroducer { - n: hex::encode(nid), - a: addrs, - }) - } - - /// Decide what a holding declaration should publish as our reach. - /// - /// RULE (v0.8.1): an address rides a declaration only when it is already - /// public by our own choice, or when it is not our address at all. - /// - /// 1. Introducer configured AND currently connected → publish the - /// introducer, no address of ours. - /// 2. We are an anchor → publish our stable advertised address. Round 10's - /// "addresses ride the pools only for anchors" already grants this, and - /// a declared holder is self-nominated infrastructure for that file, so - /// the consent shape matches. - /// 3. Otherwise → bare node id. The declaration's recipient has a live - /// connection to us and has persisted our address (`upsert_peer`); a - /// third party it hands the id to resolves us through the mesh via - /// `RelayIntroduce`, the same path any non-anchor peer already needs. - /// - /// Either way the published reach is AUTHORITATIVE: an empty list means - /// "no address of mine may be published", and the receiver clears any - /// address it previously held for us (`upsert_file_holder`). - pub fn build_declaration_reach( - &self, - anchor_addr: Option<&str>, - connected: &[NodeId], - ) -> crate::holdings::DeclaredReach { - use crate::holdings::DeclaredReach; - if let Some(intro) = self.resolve_declared_introducer(connected) { - if let Ok(nid) = crate::parse_node_id_hex(&intro.n) { - return DeclaredReach::ViaIntroducer { node_id: nid, addresses: intro.a }; - } - } - match anchor_addr { - Some(a) if !a.is_empty() => DeclaredReach::Direct(vec![a.to_string()]), - _ => DeclaredReach::Direct(Vec::new()), - } - } - /// Remove a single peer's holder entry for a file. pub fn remove_file_holder(&self, file_id: &[u8; 32], peer_id: &NodeId) -> anyhow::Result<()> { self.conn.execute( @@ -9325,633 +8252,6 @@ mod tests { assert!(kept.contains(&make_node_id(6))); } - // --- v0.8.1 PHASE 2: declared holdings --- - - #[test] - fn a_witnessed_holder_still_counts_for_durability_after_it_declares() { - let s = temp_storage(); - let file = [11u8; 32]; - let peer = make_node_id(2); - // We served this peer, so we have EVIDENCE it holds the file. - s.touch_file_holder(&file, &peer, &[], HolderDirection::Sent).unwrap(); - assert_eq!(s.get_durability_holder_count(&file).unwrap(), 1); - // It then declares, as every honest custodian does. The declaration is - // a claim ON TOP OF our observation; it must not erase the observation, - // or declaring would make the author's post look less durable and - // provoke replication it does not need. - s.record_declared_holder(&file, &peer, &[], HolderDirection::Sent, None).unwrap(); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 1); - assert_eq!( - s.get_durability_holder_count(&file).unwrap(), 1, - "a witnessed holder must keep counting as evidence once it declares" - ); - // A peer known ONLY by its own claim is still not evidence. - let stranger = make_node_id(3); - s.record_declared_holder(&file, &stranger, &[], HolderDirection::Sent, None).unwrap(); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 2); - assert_eq!(s.get_durability_holder_count(&file).unwrap(), 1); - } - - #[test] - fn transport_hints_are_never_publishable() { - let s = temp_storage(); - let file = [7u8; 32]; - let peer = make_node_id(1); - // A transport event records a hint... - s.touch_file_holder(&file, &peer, &["1.2.3.4:4433".to_string()], HolderDirection::Received).unwrap(); - assert_eq!(s.get_file_holder_count(&file).unwrap(), 1); - assert_eq!(s.get_file_holders(&file).unwrap().len(), 1); - // ...which is invisible to every outbound path. - assert!(s.get_declared_file_holders(&file).unwrap().is_empty()); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 0); - } - - #[test] - fn declaration_publishes_and_carries_addresses_and_introducer() { - use crate::types::RedirectIntroducer; - let s = temp_storage(); - let file = [7u8; 32]; - let direct = make_node_id(1); - let behind = make_node_id(2); - let intro = RedirectIntroducer { - n: hex::encode(make_node_id(9)), - a: vec!["203.0.113.9:4433".to_string()], - }; - s.record_declared_holder( - &file, &direct, &["198.51.100.1:4433".to_string()], - HolderDirection::Sent, None, - ).unwrap(); - s.record_declared_holder(&file, &behind, &[], HolderDirection::Sent, Some(&intro)).unwrap(); - - let declared = s.get_declared_file_holders(&file).unwrap(); - assert_eq!(declared.len(), 2); - let d = declared.iter().find(|(n, _, _)| *n == direct).unwrap(); - assert_eq!(d.1, vec!["198.51.100.1:4433".to_string()]); - assert!(d.2.is_none()); - let b = declared.iter().find(|(n, _, _)| *n == behind).unwrap(); - assert!(b.1.is_empty()); - assert_eq!(b.2.as_ref().unwrap(), &intro); - } - - #[test] - fn a_hint_never_demotes_a_declaration() { - let s = temp_storage(); - let file = [7u8; 32]; - let peer = make_node_id(1); - s.record_declared_holder(&file, &peer, &[], HolderDirection::Sent, None).unwrap(); - s.touch_file_holder(&file, &peer, &[], HolderDirection::Received).unwrap(); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 1); - // Only an explicit withdrawal clears it. - s.clear_holder_declaration(&file, &peer).unwrap(); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 0); - // The local hint survives the withdrawal. - assert_eq!(s.get_file_holder_count(&file).unwrap(), 1); - } - - #[test] - fn lru_cap_is_enforced_per_class_so_neither_starves_the_other() { - let s = temp_storage(); - let file = [7u8; 32]; - let declared = make_node_id(0); - s.record_declared_holder(&file, &declared, &[], HolderDirection::Sent, None).unwrap(); - std::thread::sleep(std::time::Duration::from_millis(2)); - // Six later hints would push the oldest row out under a single - // pure-recency cap, and under a `declared DESC` cap they would be - // inserted and immediately deleted instead — on hot open-slot posts - // (registry, greeting bios) that silently discards a peer that just - // commented, losing it as a diff target and a proven fetch source. - for i in 1..7u8 { - s.touch_file_holder(&file, &make_node_id(i), &[], HolderDirection::Received).unwrap(); - std::thread::sleep(std::time::Duration::from_millis(2)); - } - // 5 hints kept (the oldest hint evicted) PLUS the declaration. - assert_eq!(s.get_file_holder_count(&file).unwrap(), 6); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 1); - assert_eq!(s.get_declared_file_holders(&file).unwrap()[0].0, declared); - // The most recent hint survived, i.e. hints are not starved. - let hints = s.get_file_holders(&file).unwrap(); - assert!(hints.iter().any(|(n, _)| *n == make_node_id(6))); - } - - #[test] - fn a_declared_keep_set_favours_established_holders_over_a_fresh_burst() { - let s = temp_storage(); - let file = [7u8; 32]; - let established: Vec = (0..5u8).map(make_node_id).collect(); - for p in &established { - s.record_declared_holder(&file, p, &[], HolderDirection::Sent, None).unwrap(); - std::thread::sleep(std::time::Duration::from_millis(2)); - } - // A Sybil burst arrives later. Under pure recency it would evict every - // genuine holder and the holder path would answer with attacker ids - // only — a data-availability attack. - for i in 100..105u8 { - s.record_declared_holder(&file, &make_node_id(i), &[], HolderDirection::Sent, None).unwrap(); - } - let kept: Vec = s.get_declared_file_holders(&file).unwrap() - .into_iter().map(|(n, _, _)| n).collect(); - assert_eq!(kept.len(), 5); - for p in &established { - assert!(kept.contains(p), "an established declared holder was displaced"); - } - } - - #[test] - fn a_silent_declaration_expires_and_stops_being_published() { - let s = temp_storage(); - let file = [7u8; 32]; - let peer = make_node_id(1); - s.record_declared_holder(&file, &peer, &["198.51.100.1:4433".to_string()], - HolderDirection::Sent, None).unwrap(); - assert_eq!(s.get_declared_file_holder_count(&file).unwrap(), 1); - // Age the declaration past the TTL. A declaration is soft state: the - // declarer re-sends it on each sync cycle, so one that stops being - // renewed means the holder is gone or has shed the file. - let stale = (now_ms() - (crate::holdings::DECLARATION_TTL_MS as i64) - 1) as i64; - s.conn.execute( - "UPDATE file_holders SET declared_at_ms = ?1 WHERE file_id = ?2", - params![stale, file.as_slice()], - ).unwrap(); - assert!(s.get_declared_file_holders(&file).unwrap().is_empty()); - // Demoted to a hint, not deleted — still a useful local fetch target, - // and its published reach is cleared. - assert_eq!(s.get_file_holder_count(&file).unwrap(), 1); - assert!(s.get_file_holders(&file).unwrap()[0].1.is_empty()); - } - - #[test] - fn a_bare_declaration_clears_a_legacy_inferred_address() { - // A declaration is AUTHORITATIVE about its own reach. The legacy row's - // address was inferred from transport (and `is_shareable_addr` admits - // LAN addresses on purpose), so a later bare-id declaration — the - // default shape for every non-anchor — must CLEAR it, not inherit it. - let s = temp_storage(); - let file = [9u8; 32]; - let peer = make_node_id(1); - s.conn.execute( - "INSERT INTO file_holders - (file_id, peer_id, peer_addresses, last_interaction_ms, direction, declared) - VALUES (?1, ?2, '[\"203.0.113.5:4433\"]', 1, 'received', 0)", - params![file.as_slice(), peer.as_slice()], - ).unwrap(); - s.record_declared_holder(&file, &peer, &[], HolderDirection::Sent, None).unwrap(); - let declared = s.get_declared_file_holders(&file).unwrap(); - assert_eq!(declared.len(), 1); - assert!( - declared[0].1.is_empty(), - "a bare declaration must not publish an address it never claimed" - ); - // Same shape as an anchor that re-declares after losing its mapping. - s.record_declared_holder(&file, &peer, &["198.51.100.1:4433".to_string()], - HolderDirection::Sent, None).unwrap(); - assert_eq!(s.get_declared_file_holders(&file).unwrap()[0].1, - vec!["198.51.100.1:4433".to_string()]); - s.record_declared_holder(&file, &peer, &[], HolderDirection::Sent, None).unwrap(); - assert!(s.get_declared_file_holders(&file).unwrap()[0].1.is_empty()); - } - - #[test] - fn holding_many_files_while_announcing_one_is_invisible_for_the_rest() { - // THE target property of the whole change (erasure study, "THE - // CONCEALMENT REFRAME"): a node may hold k files of a post/author and - // announce exactly ONE. The other k-1 must not resolve on any - // outbound path. - use crate::holdings::DeclareReason; - let s = temp_storage(); - let author = make_node_id(1); - let post = make_post_id(1); - let peer = make_node_id(2); - let siblings = [[11u8; 32], [12u8; 32], [13u8; 32]]; - // We hold all three locally, and a peer exchanged bytes with us about - // each of them (so there IS a hint row for every one). - for f in &siblings { - s.touch_file_holder(f, &peer, &[], HolderDirection::Received).unwrap(); - } - // We announce exactly one, and the peer-side view records it. - assert!(s.declare_own_holding(&siblings[0], &post, &author, DeclareReason::Interest).unwrap()); - s.record_declared_holder(&siblings[0], &peer, &[], HolderDirection::Sent, None).unwrap(); - - // The announced slot resolves... - assert_eq!(s.get_declared_file_holder_count(&siblings[0]).unwrap(), 1); - assert!(s.is_own_holding_declared(&siblings[0]).unwrap()); - // ...and the ones we merely hold are invisible to every publishing - // path while remaining locally usable. - for f in &siblings[1..] { - assert!(s.get_declared_file_holders(f).unwrap().is_empty()); - assert_eq!(s.get_declared_file_holder_count(f).unwrap(), 0); - assert!(!s.is_own_holding_declared(f).unwrap()); - assert!(s.get_file_holder_count(f).unwrap() > 0, "still usable locally"); - } - } - - #[test] - fn a_blob_shared_by_two_posts_survives_one_post_being_deleted() { - use crate::holdings::DeclareReason; - let s = temp_storage(); - let author = make_node_id(1); - let post_a = make_post_id(1); - let post_b = make_post_id(2); - let shared = [77u8; 32]; - assert!(s.declare_own_holding(&shared, &post_a, &author, DeclareReason::Interest).unwrap()); - assert!(s.declare_own_holding(&shared, &post_b, &author, DeclareReason::Interest).unwrap()); - s.undeclare_own_post_holdings(&post_a).unwrap(); - assert!( - s.is_own_holding_declared(&shared).unwrap(), - "we still hold the blob for post B and still serve it" - ); - s.undeclare_own_post_holdings(&post_b).unwrap(); - assert!(!s.is_own_holding_declared(&shared).unwrap()); - } - - #[test] - fn tightening_the_policy_retracts_what_it_no_longer_admits() { - use crate::holdings::{DeclareReason, SETTING_CAP_PER_AUTHOR, SETTING_DECLARE_INTEREST}; - let s = temp_storage(); - let author = make_node_id(1); - let peer = make_node_id(9); - let posts: Vec = (1..5u8).map(make_post_id).collect(); - for p in &posts { - // A peer holds our declaration, so a retraction has somewhere to go. - s.touch_file_holder(p, &peer, &[], HolderDirection::Sent).unwrap(); - assert!(s.declare_own_holding(p, p, &author, DeclareReason::Interest).unwrap()); - } - assert_eq!(s.count_declared_posts_for_author(&author).unwrap(), 4); - - // Lowering the cap must prune, not merely stop new declarations — - // otherwise the generous alpha footprint is permanent. - s.set_setting(SETTING_CAP_PER_AUTHOR, "2").unwrap(); - let removed = s.prune_declarations_for_policy().unwrap(); - assert_eq!(removed, 2); - assert_eq!(s.count_declared_posts_for_author(&author).unwrap(), 2); - let queued = s.take_pending_withdrawals(100).unwrap(); - assert_eq!(queued.len(), 2, "each retraction must be announced"); - assert!(queued.iter().all(|(_, p)| *p == peer)); - - // Turning the class off retracts the remainder. - s.set_setting(SETTING_DECLARE_INTEREST, "false").unwrap(); - assert_eq!(s.prune_declarations_for_policy().unwrap(), 2); - assert_eq!(s.count_declared_holdings().unwrap(), 0); - assert_eq!(s.take_pending_withdrawals(100).unwrap().len(), 2); - } - - #[test] - fn a_disabled_knob_is_not_re_affirmed_by_a_repeat_declaration() { - use crate::holdings::{DeclareReason, SETTING_DECLARE_INTEREST}; - let s = temp_storage(); - let author = make_node_id(1); - let pid = make_post_id(1); - assert!(s.declare_own_holding(&pid, &pid, &author, DeclareReason::Interest).unwrap()); - s.set_setting(SETTING_DECLARE_INTEREST, "false").unwrap(); - // The "already declared" short-circuit must not sit above the guards. - assert!(!s.would_declare_own_holding(&pid, &pid, &author, DeclareReason::Interest).unwrap()); - } - - #[test] - fn the_own_authored_guard_survives_persona_retirement() { - use crate::holdings::DeclareReason; - use crate::types::PostingIdentity; - let s = temp_storage(); - let mine = make_node_id(1); - s.upsert_posting_identity(&PostingIdentity { - node_id: mine, - secret_seed: [7u8; 32], - display_name: "rotating".to_string(), - created_at: 1, - }).unwrap(); - // Rotate it out — the planned ephemeral-rotation model does exactly - // this. The guard must not lapse: declaring a retired persona's post - // publishes `device <-> persona` just as loudly. - s.delete_posting_identity(&mine).unwrap(); - assert!(s.is_own_posting_identity(&mine).unwrap()); - let pid = make_post_id(1); - assert!(!s.declare_own_holding(&pid, &pid, &mine, DeclareReason::Interest).unwrap()); - } - - #[test] - fn redeclaration_sweep_rotates_and_wraps_per_peer() { - use crate::holdings::DeclareReason; - let s = temp_storage(); - let author = make_node_id(1); - let peer = make_node_id(2); - let posts: Vec = (1..6u8).map(make_post_id).collect(); - for p in &posts { - assert!(s.declare_own_holding(p, p, &author, DeclareReason::Interest).unwrap()); - } - // Successive cycles must cover everything, not repeat the same slice — - // this is the mechanism the migration ruling rests on. - let first = s.next_declarations_to_announce(&peer, 2).unwrap(); - let second = s.next_declarations_to_announce(&peer, 2).unwrap(); - let third = s.next_declarations_to_announce(&peer, 2).unwrap(); - assert_eq!(first.len(), 2); - assert_eq!(second.len(), 2); - assert_eq!(third.len(), 1, "short slice ends the pass"); - let mut all = [first, second, third].concat(); - all.sort(); - let mut expected: Vec<[u8; 32]> = posts.clone(); - expected.sort(); - assert_eq!(all, expected); - // ...and then it wraps. - assert_eq!(s.next_declarations_to_announce(&peer, 2).unwrap().len(), 2); - // Each peer has its own cursor, so a newly met peer starts at the top. - let other = make_node_id(3); - let fresh = s.next_declarations_to_announce(&other, 2).unwrap(); - assert_eq!(fresh.len(), 2); - assert_eq!(fresh, first_two_by_rowid(&s)); - } - - /// The first two declared file ids in rowid order. - fn first_two_by_rowid(s: &Storage) -> Vec<[u8; 32]> { - let mut stmt = s.conn.prepare( - "SELECT file_id FROM declared_holdings ORDER BY rowid ASC LIMIT 2", - ).unwrap(); - let rows = stmt.query_map([], |row| row.get::<_, Vec>(0)).unwrap(); - rows.map(|r| { - let b = r.unwrap(); - let mut f = [0u8; 32]; - f.copy_from_slice(&b); - f - }).collect() - } - - #[test] - fn own_declarations_follow_the_policy_cap() { - use crate::holdings::{DeclareReason, SETTING_CAP_PER_AUTHOR}; - let s = temp_storage(); - let author = make_node_id(1); - let p1 = make_post_id(1); - let p2 = make_post_id(2); - let p3 = make_post_id(3); - s.set_setting(SETTING_CAP_PER_AUTHOR, "2").unwrap(); - - assert!(s.declare_own_holding(&p1, &p1, &author, DeclareReason::Interest).unwrap()); - assert!(s.declare_own_holding(&p2, &p2, &author, DeclareReason::Interest).unwrap()); - // Third distinct post of the same author exceeds the cap. - assert!(!s.declare_own_holding(&p3, &p3, &author, DeclareReason::Interest).unwrap()); - // An attachment of an ALREADY declared post is not a new listing. - let att = [99u8; 32]; - assert!(s.declare_own_holding(&att, &p1, &author, DeclareReason::Interest).unwrap()); - assert_eq!(s.count_declared_posts_for_author(&author).unwrap(), 2); - // A different author gets its own budget. - let other = make_node_id(2); - assert!(s.declare_own_holding(&p3, &p3, &other, DeclareReason::Interest).unwrap()); - } - - #[test] - fn alpha_default_policy_is_uncapped_and_declares_both_classes() { - use crate::holdings::DeclareReason; - let s = temp_storage(); - let policy = s.holdings_policy(); - assert!(policy.declare_custodial); - assert!(policy.declare_interest); - assert_eq!(policy.cap_per_author, 0, "alpha default must not cap discovery"); - let author = make_node_id(1); - for i in 0..40u8 { - let pid = make_post_id(i); - assert!(s.declare_own_holding(&pid, &pid, &author, DeclareReason::Interest).unwrap()); - } - assert_eq!(s.count_declared_posts_for_author(&author).unwrap(), 40); - } - - #[test] - fn custodial_class_can_be_declared_while_interest_is_off() { - use crate::holdings::{DeclareReason, SETTING_DECLARE_INTEREST}; - let s = temp_storage(); - s.set_setting(SETTING_DECLARE_INTEREST, "false").unwrap(); - let author = make_node_id(1); - let a = make_post_id(1); - let b = make_post_id(2); - assert!(s.declare_own_holding(&a, &a, &author, DeclareReason::Custodial).unwrap()); - assert!(!s.declare_own_holding(&b, &b, &author, DeclareReason::Interest).unwrap()); - } - - #[test] - fn eviction_and_delete_withdraw_our_declaration() { - use crate::holdings::DeclareReason; - let s = temp_storage(); - let author = make_node_id(1); - let pid = make_post_id(1); - let cid = [55u8; 32]; - assert!(s.declare_own_holding(&pid, &pid, &author, DeclareReason::Custodial).unwrap()); - assert!(s.declare_own_holding(&cid, &pid, &author, DeclareReason::Custodial).unwrap()); - - s.cleanup_cdn_for_blob(&cid).unwrap(); - assert!(!s.is_own_holding_declared(&cid).unwrap()); - assert!(s.is_own_holding_declared(&pid).unwrap()); - - s.undeclare_own_post_holdings(&pid).unwrap(); - assert!(!s.is_own_holding_declared(&pid).unwrap()); - assert_eq!(s.count_declared_posts_for_author(&author).unwrap(), 0); - } - - #[test] - fn non_public_content_is_refused_at_the_chokepoint() { - // Advertising yourself as a holder of a DM / group / FoF-closed post - // announces your membership in its audience. Three call sites had to - // remember this and one of them (a replicated post's attachments) did - // not, so the rule lives in the chokepoint. - use crate::holdings::DeclareReason; - use crate::types::Post; - let s = temp_storage(); - let author = make_node_id(1); - let post = Post { - author, - content: "private".to_string(), - attachments: vec![], - timestamp_ms: 1, - fof_gating: None, - supersedes_post_id: None, - comment_ttl: None, - }; - let pid = crate::content::compute_post_id(&post); - s.store_post_with_visibility(&pid, &post, &PostVisibility::FoFClosed).unwrap(); - assert!(!s.declare_own_holding(&pid, &pid, &author, DeclareReason::Interest).unwrap()); - // ...and so is one of its attachment CIDs, which is the case the - // call-site guard missed: `declare_own_holding` cannot infer - // visibility from a bare CID, so it resolves the PARENT post. - let att = [66u8; 32]; - assert!(!s.declare_own_holding(&att, &pid, &author, DeclareReason::Custodial).unwrap()); - // The same post made public declares normally. - s.update_post_visibility(&pid, &PostVisibility::Public).unwrap(); - assert!(s.declare_own_holding(&att, &pid, &author, DeclareReason::Custodial).unwrap()); - } - - #[test] - fn eviction_queues_a_withdrawal_to_the_peers_publishing_us() { - // A stale declaration is worse than none: it sends fetchers to a node - // that no longer serves the file. The retraction has to reach the - // peers holding our declaration, so it must be queued BEFORE - // `file_holders` is cleared — that table is where the recipients come - // from. - use crate::holdings::DeclareReason; - let s = temp_storage(); - let author = make_node_id(1); - let pid = make_post_id(1); - let cid = [55u8; 32]; - let peer_a = make_node_id(2); - let peer_b = make_node_id(3); - s.touch_file_holder(&cid, &peer_a, &[], HolderDirection::Sent).unwrap(); - s.record_declared_holder(&cid, &peer_b, &[], HolderDirection::Sent, None).unwrap(); - assert!(s.declare_own_holding(&cid, &pid, &author, DeclareReason::Custodial).unwrap()); - - s.cleanup_cdn_for_blob(&cid).unwrap(); - assert!(!s.is_own_holding_declared(&cid).unwrap()); - let queued = s.take_pending_withdrawals(100).unwrap(); - let peers: Vec = queued.iter().map(|(_, p)| *p).collect(); - assert_eq!(queued.len(), 2, "every peer with a holder row must be told"); - assert!(peers.contains(&peer_a) && peers.contains(&peer_b)); - assert!(queued.iter().all(|(f, _)| *f == cid)); - // Draining is destructive — nothing is sent twice. - assert!(s.take_pending_withdrawals(100).unwrap().is_empty()); - } - - #[test] - fn a_signed_delete_withdraws_our_declaration_too() { - use crate::holdings::DeclareReason; - use crate::types::{DeleteRecord, Post}; - let s = temp_storage(); - let author = make_node_id(1); - let peer = make_node_id(2); - let post = Post { - author, - content: "hi".to_string(), - attachments: vec![], - timestamp_ms: 1, - fof_gating: None, - supersedes_post_id: None, - comment_ttl: None, - }; - let pid = crate::content::compute_post_id(&post); - s.store_post(&pid, &post).unwrap(); - s.touch_file_holder(&pid, &peer, &[], HolderDirection::Sent).unwrap(); - assert!(s.declare_own_holding(&pid, &pid, &author, DeclareReason::Interest).unwrap()); - - s.apply_delete(&DeleteRecord { - post_id: pid, - author, - timestamp_ms: 2, - signature: vec![0u8; 64], - }).unwrap(); - assert!(!s.is_own_holding_declared(&pid).unwrap()); - let queued = s.take_pending_withdrawals(100).unwrap(); - assert_eq!(queued.len(), 1); - assert_eq!(queued[0], (pid, peer)); - } - - #[test] - fn legacy_inferred_holder_rows_migrate_to_undeclared() { - // MIGRATION RULING (Phase 2): a pre-existing `file_holders` row was - // inferred from a transport event, so nobody consented to being - // advertised. On upgrade it must become a LOCAL HINT, not a - // declaration — otherwise the upgrade preserves the exact leak the - // change exists to close, for subjects who can never be asked. - let dir = std::env::temp_dir().join(format!("itsgoin-mig-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("legacy.db"); - let _ = std::fs::remove_file(&path); - - let peer = make_node_id(1); - let file = [9u8; 32]; - { - // Build the PRE-Phase-2 schema by hand and seed an inferred row. - let conn = rusqlite::Connection::open(&path).unwrap(); - conn.pragma_update(None, "user_version", MIN_MIGRATABLE_VERSION).unwrap(); - conn.execute_batch( - "CREATE TABLE file_holders ( - file_id BLOB NOT NULL, - peer_id BLOB NOT NULL, - peer_addresses TEXT NOT NULL DEFAULT '[]', - last_interaction_ms INTEGER NOT NULL, - direction TEXT NOT NULL, - PRIMARY KEY (file_id, peer_id) - );", - ).unwrap(); - conn.execute( - "INSERT INTO file_holders (file_id, peer_id, peer_addresses, last_interaction_ms, direction) - VALUES (?1, ?2, '[\"203.0.113.5:4433\"]', 1, 'received')", - params![file.as_slice(), peer.as_slice()], - ).unwrap(); - } - - let s = Storage::open(&path).unwrap(); - // The row survives as a usable local hint... - let hints = s.get_file_holders(&file).unwrap(); - assert_eq!(hints.len(), 1); - assert_eq!(hints[0].0, peer); - // ...and is invisible to every publishing path, addresses included. - assert!(s.get_declared_file_holders(&file).unwrap().is_empty()); - // The own-declaration ledger exists on an upgraded database. - assert_eq!(s.count_declared_posts_for_author(&make_node_id(2)).unwrap(), 0); - drop(s); - let _ = std::fs::remove_file(&path); - } - - #[test] - fn we_never_declare_our_own_authored_content_by_default() { - use crate::holdings::{DeclareReason, SETTING_DECLARE_OWN_AUTHORED}; - use crate::types::PostingIdentity; - let s = temp_storage(); - let mine = make_node_id(1); - s.upsert_posting_identity(&PostingIdentity { - node_id: mine, - secret_seed: [7u8; 32], - display_name: "me".to_string(), - created_at: 1, - }).unwrap(); - let pid = make_post_id(1); - // Declaring a post we authored would publish device <-> persona. - assert!(!s.declare_own_holding(&pid, &pid, &mine, DeclareReason::Interest).unwrap()); - assert!(!s.declare_own_holding(&pid, &pid, &mine, DeclareReason::Custodial).unwrap()); - assert!(!s.is_own_holding_declared(&pid).unwrap()); - // Someone else's post of course still declares. - let theirs = make_node_id(2); - let pid2 = make_post_id(2); - assert!(s.declare_own_holding(&pid2, &pid2, &theirs, DeclareReason::Interest).unwrap()); - // The knob exists for operators who want authored content listed. - s.set_setting(SETTING_DECLARE_OWN_AUTHORED, "true").unwrap(); - assert!(s.declare_own_holding(&pid, &pid, &mine, DeclareReason::Interest).unwrap()); - } - - #[test] - fn declaration_reach_prefers_introducer_then_anchor_then_bare_id() { - use crate::holdings::{SETTING_INTRODUCER_ENABLED, SETTING_INTRODUCER_PEER}; - let s = temp_storage(); - let anchor_id = make_node_id(8); - let connected = vec![anchor_id]; - // Default (introducer off, not an anchor): bare id. - let (addrs, intro) = s.build_declaration_reach(None, &connected).into_payload_parts(); - assert!(addrs.is_empty()); - assert!(intro.is_none()); - - // Anchor: our own, already-public address rides the declaration. - let (addrs, intro) = s - .build_declaration_reach(Some("198.51.100.7:4433"), &connected) - .into_payload_parts(); - assert_eq!(addrs, vec!["198.51.100.7:4433".to_string()]); - assert!(intro.is_none()); - - // Introducer configured: the holder's own address never ships. - s.upsert_peer(&anchor_id, &["203.0.113.8:4433".parse().unwrap()], None).unwrap(); - s.set_peer_anchor(&anchor_id, true).unwrap(); - s.set_setting(SETTING_INTRODUCER_ENABLED, "true").unwrap(); - s.set_setting(SETTING_INTRODUCER_PEER, &hex::encode(anchor_id)).unwrap(); - let (addrs, intro) = s - .build_declaration_reach(Some("198.51.100.7:4433"), &connected) - .into_payload_parts(); - assert!(addrs.is_empty(), "introducer mode must not publish our address"); - let intro = intro.expect("introducer resolved"); - assert_eq!(intro.n, hex::encode(anchor_id)); - assert_eq!(intro.a, vec!["203.0.113.8:4433".to_string()]); - - // ...but ONLY while we are actually connected to it. An introducer we - // cannot reach refuses every fetcher while we stay listed as a holder, - // which is worse than publishing nothing. - let (addrs, intro) = s - .build_declaration_reach(Some("198.51.100.7:4433"), &[]) - .into_payload_parts(); - assert!(intro.is_none(), "an unconnected introducer must not be published"); - assert_eq!(addrs, vec!["198.51.100.7:4433".to_string()]); - } - #[test] fn file_holders_direction_promotion() { let s = temp_storage(); diff --git a/crates/core/src/types.rs b/crates/core/src/types.rs index be59d42..b1bfad6 100644 --- a/crates/core/src/types.rs +++ b/crates/core/src/types.rs @@ -982,37 +982,6 @@ pub struct PeerWithAddress { pub a: Vec, } -/// 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, -} - -/// 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, - /// Optional introducer to reach the holder through. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub x: Option, -} - // --- CDN Manifest Layer --- /// Lightweight post reference in a manifest @@ -1041,24 +1010,16 @@ pub struct AuthorManifest { pub signature: Vec, } -/// CDN manifest traveling with blobs (the author-signed part, and nothing -/// else). -/// +/// CDN manifest traveling with blobs (author-signed part + serving host). /// v0.8: ALL device-address fields removed (host_addresses, source, /// source_addresses, downstream_count) — posting-identity manifests must not /// carry device addresses (location anonymity). Holder resolution goes via /// 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)] pub struct CdnManifest { 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 diff --git a/crates/core/src/web.rs b/crates/core/src/web.rs index bdbc763..e1efe0e 100644 --- a/crates/core/src/web.rs +++ b/crates/core/src/web.rs @@ -117,11 +117,9 @@ async fn serve_post(stream: &mut TcpStream, path: &str, node: &Arc, browse let (holders, local_post, local_author_name) = { 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(); - if let Ok(file_holders) = store.get_declared_file_holders(&post_id) { - for (peer, _addrs, _intro) in file_holders { + if let Ok(file_holders) = store.get_file_holders(&post_id) { + for (peer, _addrs) in file_holders { if !holders.contains(&peer) { holders.push(peer); } diff --git a/crates/tauri-app/src/lib.rs b/crates/tauri-app/src/lib.rs index f1ede46..7238091 100644 --- a/crates/tauri-app/src/lib.rs +++ b/crates/tauri-app/src/lib.rs @@ -2043,93 +2043,6 @@ async fn get_greetings_max( 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 { - 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, -) -> 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. /// Desktop: spawns the platform opener (xdg-open / open / cmd start). /// Only https:// URLs are accepted to avoid being a generic command exec. @@ -3863,11 +3776,6 @@ pub fn run() { get_greetings_open, set_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!()) .expect("error while building tauri application") diff --git a/frontend/app.js b/frontend/app.js index bfb3cfa..a798ae6 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -4689,56 +4689,6 @@ $('#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 () => { // Load current settings const msgVal = await invoke('get_setting', { key: 'notif_messages' }).catch(() => null) || 'on'; diff --git a/frontend/index.html b/frontend/index.html index 6f99a57..3fcfc55 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -307,31 +307,6 @@ -
-

Advertised Holdings

-

- Holding a file and being advertised 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. -

- -

0 = no limit (alpha default).

- - - -

-
-