decdn-cli 0.0.3

User-facing deCDN CLI (decdn binary): probe, fetch, pools, publishing, origin import, node admin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! `decdn config init` and `decdn config validate` — manage the deCDN
//! node TOML config file from the operator side.

use anyhow::Context;
use decdn_common::{cli, config};

use crate::known_chains;

/// Validate a configuration and print a resolved summary.
///
/// Runs the daemon's resolver against the same TOML + CLI + env-var
/// inputs `decdn-node run` would use, then prints the result. Does not
/// bind any ports, does not connect to the JSON-RPC endpoint, and does
/// not open the cache. Does touch the filesystem to verify the config
/// itself: reads the TOML, and stats / opens the configured
/// `blockchain.eth_keystore` for readability (the resolver rejects
/// missing paths, directories, and broken symlinks at this point so
/// the daemon doesn't fail later in startup).
pub fn config_validate(
    config_path: Option<&std::path::Path>,
    args: &cli::ConfigValidateArgs,
) -> anyhow::Result<()> {
    let (resolved, notices) = config::resolve_config(config_path, &args.run)?;
    let source = effective_source(config_path, cli::common::default_config_path)?;
    let mut stdout = std::io::stdout().lock();
    write_validate_summary(&mut stdout, source.as_deref(), &resolved, &notices)
        .map_err(|e| anyhow::anyhow!("failed to write summary: {e}"))
}

/// Resolve the config source actually consulted. When `--config` is omitted,
/// the default path is auto-loaded only if present, so report the file that
/// `resolve_config` will actually read — not just the explicit flag.
///
/// Uses `try_exists` rather than `exists`: a permission error on the default
/// path must be surfaced, not silently reported as "no config file" — the
/// whole point of `validate` is telling the operator what the node sees.
pub fn effective_source(
    config_path: Option<&std::path::Path>,
    default: impl FnOnce() -> Option<std::path::PathBuf>,
) -> anyhow::Result<Option<std::path::PathBuf>> {
    if let Some(p) = config_path {
        return Ok(Some(p.to_path_buf()));
    }
    let Some(default) = default() else {
        return Ok(None);
    };
    match default.try_exists() {
        Ok(true) => Ok(Some(default)),
        Ok(false) => Ok(None),
        Err(e) => Err(anyhow::anyhow!(
            "cannot determine whether default config {} exists: {e}",
            default.display()
        )),
    }
}

/// Render the validation summary. Separated from [`config_validate`] so tests
/// can capture the output into a buffer and assert on the printed contract —
/// in particular that `rpc_url` and `otlp_endpoint` values never appear.
// Linear "print each resolved config field" flow sitting right at the 100-line
// boundary; splitting the writeln! sequence across helpers would obscure the
// field-by-field narrative more than the length does.
#[allow(clippy::too_many_lines)]
pub fn write_validate_summary<W: std::io::Write>(
    w: &mut W,
    source: Option<&std::path::Path>,
    resolved: &config::ResolvedConfig,
    notices: &[config::ConfigNotice],
) -> std::io::Result<()> {
    writeln!(w, "config valid")?;
    match source {
        Some(path) => writeln!(w, "  source:                   {}", path.display())?,
        None => writeln!(
            w,
            "  source:                   (defaults + env only, no config file)"
        )?,
    }
    writeln!(
        w,
        "  data_dir:                 {}",
        resolved.identity.data_dir.display()
    )?;
    if let Some(region) = &resolved.identity.region {
        writeln!(w, "  region:                   {region}")?;
    }
    writeln!(
        w,
        "  bind_port:                {}",
        resolved.network.bind_port
    )?;
    // One line per configured relay; nothing when the list is empty (the node
    // then falls back to the n0 default relays). Relay URLs can carry
    // `user:pass@` userinfo, so redact it (host stays visible) — the same
    // treatment pkarr_url gets below, and the reason rpc_url/otlp_endpoint are
    // fully hidden in this same summary (#862).
    for relay in &resolved.network.relay_urls {
        writeln!(
            w,
            "  relay_url:                {}",
            decdn_common::redact::redact_userinfo(relay)
        )?;
    }
    // Operator-configurable discovery (#818); nothing printed when unset (the
    // node then uses the n0 pkarr/DNS default). A pkarr_url is an infra relay
    // endpoint — pkarr authenticates by the Ed25519-signed packet, not a URL
    // token — so its credentials, if any, are normally `user:pass@` userinfo.
    // Redact that (host stays visible for diagnostics) rather than fully hiding
    // it like rpc_url/otlp_endpoint, whose secret commonly lives in the path or
    // query. Caveat: `redact_userinfo` does NOT scrub a path/query secret, so a
    // nonstandard relay that put one there would still print it — acceptable
    // given pkarr's auth model and that relays themselves redact userinfo
    // above. dns_origin is a plain domain. Peer entries (id/relay/addrs) are
    // not echoed (verbose) — only the count.
    let discovery = &resolved.network.discovery;
    if let Some(pkarr) = &discovery.pkarr_url {
        writeln!(
            w,
            "  discovery.pkarr_url:      {}",
            decdn_common::redact::redact_userinfo(pkarr)
        )?;
    }
    if let Some(origin) = &discovery.dns_origin {
        writeln!(w, "  discovery.dns_origin:     {origin}")?;
    }
    if !discovery.peers.is_empty() {
        writeln!(w, "  discovery.peers:          {}", discovery.peers.len())?;
    }
    writeln!(
        w,
        "  rpc_url:                  <redacted> ({} chars)",
        resolved.blockchain.rpc_url.len()
    )?;
    writeln!(
        w,
        "  eth_keystore:             {}",
        resolved.blockchain.eth_keystore.display()
    )?;
    writeln!(
        w,
        "  payment_pool_address:  {}",
        resolved.blockchain.payment_pool_address
    )?;
    writeln!(
        w,
        "  capacity_bond_address: {}",
        resolved.blockchain.capacity_bond_address
    )?;
    writeln!(
        w,
        "  origin_assignment_address: {}",
        resolved
            .blockchain
            .origin_assignment_address
            .as_deref()
            .unwrap_or("(unset — origin directory empty: pull-through gate and FIND_VALUE fallback find no origins)")
    )?;
    writeln!(
        w,
        "  publisher_registry_address: {}",
        resolved
            .blockchain
            .publisher_registry_address
            .as_deref()
            .unwrap_or("(unset — origin directory empty: pull-through gate and FIND_VALUE fallback find no origins)")
    )?;
    writeln!(
        w,
        "  content_blacklist_address: {}",
        resolved
            .blockchain
            .content_blacklist_address
            .as_deref()
            .unwrap_or("(unset — REQUIRED: the node refuses to start without it)")
    )?;
    writeln!(
        w,
        "  content_blacklist_poll_interval_sec: {}",
        resolved.blockchain.content_blacklist_poll_interval_sec
    )?;
    writeln!(
        w,
        "  chain_staleness_grace_sec: {}",
        resolved.blockchain.chain_staleness_grace_sec
    )?;
    writeln!(
        w,
        "  rpc_watchdog_interval_sec: {}",
        resolved.blockchain.rpc_watchdog_interval_sec
    )?;
    writeln!(
        w,
        "  event_poll_interval_ms: {}",
        resolved.blockchain.event_poll_interval_ms
    )?;
    writeln!(
        w,
        "  get_logs_max_block_span: {}",
        resolved.blockchain.get_logs_max_block_span
    )?;
    writeln!(
        w,
        "  fee_shares_poll_interval_sec: {}",
        resolved.blockchain.fee_shares_poll_interval_sec
    )?;
    writeln!(
        w,
        "  redeem_threshold_micro_usdc: {}",
        resolved.blockchain.redeem_threshold_micro_usdc
    )?;
    writeln!(
        w,
        "  redeem_interval_secs: {}",
        resolved.blockchain.redeem_interval_secs
    )?;
    writeln!(
        w,
        "  buyer_working_deposit_micro_usdc: {}",
        resolved.blockchain.buyer_working_deposit_micro_usdc
    )?;
    writeln!(
        w,
        "  buyer_max_approve: {}",
        resolved.blockchain.buyer_max_approve
    )?;
    writeln!(
        w,
        "  pool_min_remaining_deposit_micro_usdc: {}",
        resolved.blockchain.pool_min_remaining_deposit_micro_usdc
    )?;
    writeln!(
        w,
        "  pool_floor_signer_live_windows: {}",
        resolved.blockchain.pool_floor_signer_live_windows
    )?;
    writeln!(
        w,
        "  cache_dir:                {}",
        resolved.cache.cache_dir.display()
    )?;
    writeln!(
        w,
        "  cache_size_mb:            {}",
        resolved.cache.cache_size_mb
    )?;
    writeln!(
        w,
        "  max_blob_size_mb:         {}",
        resolved.cache.max_blob_size_mb
    )?;
    match resolved.cache.max_rate_per_mb {
        0 => writeln!(w, "  max_rate_per_mb:          unlimited (buyer)")?,
        n => writeln!(w, "  max_rate_per_mb:          {n} (buyer ceiling)")?,
    }
    match resolved.cache.gc_interval_sec {
        0 => writeln!(w, "  gc_interval_sec:          disabled")?,
        n => writeln!(w, "  gc_interval_sec:          {n}")?,
    }
    match resolved.cache.fs_rescan_interval_sec {
        0 => writeln!(
            w,
            "  fs_rescan_interval_sec:   disabled (startup + reload only)"
        )?,
        n => writeln!(w, "  fs_rescan_interval_sec:   {n}")?,
    }
    writeln!(
        w,
        "  eviction:                 high_water_pct={}, target_pct={}, per_sweep_budget={}, tick_secs={}",
        resolved.cache.eviction_high_water_pct,
        resolved.cache.eviction_target_pct,
        resolved.cache.eviction_per_sweep_budget,
        resolved.cache.eviction_tick_secs
    )?;
    if resolved.cache.node_to_node_pull_through_enabled {
        writeln!(
            w,
            "  node_to_node_pull:        enabled (probe_fanout={}, pull_timeout_sec={}, stall_window_sec={}, min_throughput_bps={})",
            resolved.cache.node_pull_probe_fanout,
            resolved.cache.node_pull_timeout_sec,
            resolved.cache.node_pull_stall_window_sec,
            resolved.cache.node_pull_min_throughput_bps
        )?;
    } else {
        writeln!(w, "  node_to_node_pull:        disabled")?;
    }
    if resolved.cache.relay_foreign_namespaces {
        writeln!(w, "  relay_foreign_namespaces: true")?;
    } else {
        writeln!(w, "  relay_foreign_namespaces: false (origin-only node)")?;
    }
    writeln!(
        w,
        "  rate_per_mb:              {}",
        resolved.payment.rate_per_mb
    )?;
    writeln!(
        w,
        "  log_level:                {}",
        resolved.observability.log_level
    )?;
    writeln!(
        w,
        "  metrics_port:             {}",
        resolved.observability.metrics_port
    )?;
    writeln!(
        w,
        "  metrics_bind:             {}",
        resolved.observability.metrics_bind
    )?;
    match resolved.observability.admin_port {
        Some(p) => writeln!(w, "  admin_port:               {p}")?,
        None => writeln!(w, "  admin_port:               disabled")?,
    }
    // otlp_endpoint URLs commonly carry bearer tokens or API keys in the
    // path or query, so redact like rpc_url.
    if let Some(otlp) = &resolved.observability.otlp_endpoint {
        writeln!(
            w,
            "  otlp_endpoint:            <redacted> ({} chars)",
            otlp.len()
        )?;
    }
    // Surface the kill-switch / rate-limit knobs of the otherwise-silent
    // sections — the throttles an operator most needs to confirm, not every
    // field. All numeric/bool/bind-addr, so no secret-redaction concern.
    writeln!(
        w,
        "  security.max_concurrent_handlers: {}",
        resolved.security.max_concurrent_handlers
    )?;
    writeln!(
        w,
        "  security.per_source_rate_per_sec: {}",
        resolved.security.per_source_rate_per_sec
    )?;
    writeln!(
        w,
        "  security.per_source_burst: {}",
        resolved.security.per_source_burst
    )?;
    writeln!(
        w,
        "  dht.per_peer_rate_per_sec: {}",
        resolved.dht.per_peer_rate_per_sec
    )?;
    writeln!(
        w,
        "  dht.global_rate_per_sec:  {}",
        resolved.dht.global_rate_per_sec
    )?;
    writeln!(
        w,
        "  probe.per_peer_rate_per_sec: {}",
        resolved.probe.per_peer_rate_per_sec
    )?;
    writeln!(
        w,
        "  probe.global_rate_per_sec: {}",
        resolved.probe.global_rate_per_sec
    )?;
    // Download-receipt audit log (#802). The log lives at a fixed filename
    // inside data_dir; surface the resolved path so an operator can confirm
    // where receipts land without reading the daemon source, alongside the
    // rotation cap and retained-backup count that bound its disk use. The path
    // is derived (not a configurable field) — the daemon writes it to this
    // canonical name under data_dir.
    writeln!(
        w,
        "  receipts.log_path:        {}",
        resolved
            .identity
            .data_dir
            .join(config::RECEIPT_LOG_FILE)
            .display()
    )?;
    writeln!(
        w,
        "  receipts.max_file_bytes:  {}",
        resolved.receipts.max_file_bytes
    )?;
    writeln!(
        w,
        "  receipts.retained_files:  {}",
        resolved.receipts.retained_files
    )?;
    // Counts, not contents. An operator running `config validate` after adding a
    // takedown wants confirmation the entries were accepted — and a zero here is
    // the tell that a `[content]` section landed in the wrong file. Printing the
    // hashes themselves would put the subject of a legal order into terminal
    // scrollback and any CI log that captures it.
    writeln!(
        w,
        "  content.denied_hashes:    {}",
        resolved.content.denied_hashes.len()
    )?;
    writeln!(
        w,
        "  content.denied_origins:   {}",
        resolved.content.denied_origins.len()
    )?;
    write_notices(w, notices)
}

/// Render the resolve-time notices under the field summary, one line each.
///
/// The config still resolved — a notice never fails validation — so these sit
/// below the summary rather than replacing it, and the leading `config valid`
/// line stands. They go to the same writer as the summary, not to stderr,
/// because `config validate` exists to tell an operator what the node sees and
/// a notice is part of that answer.
fn write_notices<W: std::io::Write>(
    w: &mut W,
    notices: &[config::ConfigNotice],
) -> std::io::Result<()> {
    if notices.is_empty() {
        return Ok(());
    }
    writeln!(w, "notices ({}):", notices.len())?;
    for notice in notices {
        let level = match notice.level {
            config::ConfigNoticeLevel::Warn => "warning",
            config::ConfigNoticeLevel::Info => "info",
        };
        writeln!(w, "  - {level}: {}: {}", notice.field, notice.message)?;
    }
    Ok(())
}

/// The config shape `config init` writes, implied by the role flags (#1772).
///
/// Role is implied by `--origin`, not a separate flag: presence of an origin
/// backend IS the role signal, exactly mirroring the runtime's role-derived
/// `cache.relay_foreign_namespaces` default — so the generated config and the
/// resolver agree by construction. `--client` is a distinct role, not the
/// absence of the others: a consumer that fetches and pays, with none of the
/// serving sections.
#[derive(Debug)]
pub enum Role {
    /// No role flag: a serving node with no origin backend — relays foreign
    /// namespaces for pay (`relay_foreign_namespaces` derives to `true`).
    Relay,
    /// `--origin <URL>`: a serving node with an active `[cache.origin]`
    /// backend (`relay_foreign_namespaces` derives to `false`, origin-only).
    Origin(OriginSpec),
    /// `--client`: a fetch-only consumer — identity + chain coordinates,
    /// none of the cache/origin/serving sections.
    Client,
}

/// The `[cache.origin]` backend `--origin` asked for, one variant per
/// `OriginConfig` kind. Each spelling of the flag value maps to exactly one:
/// `http(s)://` → [`OriginSpec::Http`], `file:///` → [`OriginSpec::Fs`],
/// `s3` / `s3://<bucket>` → [`OriginSpec::S3`].
#[derive(Debug)]
pub enum OriginSpec {
    /// HTTP(S) pull-through base URL.
    Http(decdn_config_types::OriginUrl),
    /// Local filesystem root (from a `file:///` URL).
    Fs(std::path::PathBuf),
    /// S3-compatible origin. `bucket` is `None` for the bare `s3` spelling —
    /// the emitted block then carries a placeholder bucket to edit.
    S3 {
        /// The bucket named in `s3://<bucket>`, or `None` for the bare `s3`
        /// spelling.
        bucket: Option<String>,
    },
}

/// Map the `config init` role flags to a [`Role`]. `--origin` and `--client`
/// are mutually exclusive at the clap layer (`conflicts_with`).
fn resolve_role(args: &cli::ConfigInitArgs) -> anyhow::Result<Role> {
    if args.client {
        return Ok(Role::Client);
    }
    match args.origin.as_deref() {
        Some(raw) => Ok(Role::Origin(parse_origin_spec(raw)?)),
        None => Ok(Role::Relay),
    }
}

/// Parse the `--origin` flag value into an [`OriginSpec`].
///
/// Every accepted value is validated through the same guard the daemon's
/// config resolver applies to that origin kind — `parse_origin_url` for http,
/// `validate_s3_bucket_name` for a named bucket — so a value `config init`
/// accepts cannot fail resolution. The S3 key `prefix` stays a commented key
/// (its validation and normalization live in the resolver alone), so an
/// `s3://bucket/prefix` spelling is rejected rather than half-supported.
fn parse_origin_spec(raw: &str) -> anyhow::Result<OriginSpec> {
    if raw == "s3" {
        return Ok(OriginSpec::S3 { bucket: None });
    }
    // The raw value is not echoed on a parse failure: an unparseable origin
    // string can still carry `user:pass@` userinfo, and the redaction helpers
    // only work on values that parsed.
    let url = url::Url::parse(raw).context(
        "invalid --origin value (expected an http(s):// or file:/// URL, `s3`, or s3://<bucket>)",
    )?;
    match url.scheme() {
        "http" | "https" => Ok(OriginSpec::Http(decdn_config_types::parse_origin_url(raw)?)),
        "file" => {
            // `to_file_path` rejects a remote host (`file://host/path`) and
            // percent-decodes the path; the result is absolute by construction.
            let path = url.to_file_path().map_err(|()| {
                anyhow::anyhow!(
                    "--origin file:// URL must name a local absolute path \
                     (file:///var/lib/decdn/origin)"
                )
            })?;
            Ok(OriginSpec::Fs(path))
        }
        "s3" => {
            let bucket = url
                .host_str()
                .ok_or_else(|| anyhow::anyhow!("--origin s3:// URL must name a bucket"))?
                .to_string();
            decdn_common::config::validate_s3_bucket_name(&bucket)
                .with_context(|| format!("invalid --origin s3 bucket `{bucket}`"))?;
            anyhow::ensure!(
                url.path().is_empty() || url.path() == "/",
                "--origin s3://<bucket> takes no key prefix; set the commented `prefix` key \
                 in the generated [cache.origin] section instead"
            );
            Ok(OriginSpec::S3 {
                bucket: Some(bucket),
            })
        }
        other => anyhow::bail!(
            "unsupported --origin scheme {other:?}: pass an http(s):// or file:/// URL, `s3`, \
             or s3://<bucket>"
        ),
    }
}

/// Write a default TOML configuration file.
pub fn config_init(args: &cli::ConfigInitArgs) -> anyhow::Result<()> {
    let output = args
        .output
        .as_deref()
        .map(cli::common::expand_tilde)
        .or_else(cli::default_config_path)
        .ok_or_else(|| anyhow::anyhow!("cannot determine config path: home dir not found"))?;

    if output.exists() && !args.force {
        anyhow::bail!(
            "config file already exists at {}; use --force to overwrite",
            output.display()
        );
    }

    if let Some(parent) = output.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| anyhow::anyhow!("failed to create directory {}: {e}", parent.display()))?;
    }

    let role = resolve_role(args)?;
    let chain = known_chains::resolve(args.chain.as_deref())?;
    let contents = render_config(chain, &role)?;

    std::fs::write(&output, &contents)
        .map_err(|e| anyhow::anyhow!("failed to write config file {}: {e}", output.display()))?;

    let role_word = match &role {
        Role::Relay => "relay-node",
        Role::Origin(_) => "origin-node",
        Role::Client => "client",
    };
    // A client's keystore lives in the client-scoped data dir, not `key-gen`'s
    // node-shaped default.
    let key_gen = match &role {
        Role::Client => "decdn key-gen --output-dir ~/.decdn/client",
        Role::Relay | Role::Origin(_) => "decdn key-gen",
    };
    match chain {
        Some(c) => println!(
            "wrote {} {role_word} config to {} (run `{key_gen}` to create the keystore)",
            c.label,
            output.display()
        ),
        None => println!(
            "wrote blank {role_word} config template to {}",
            output.display()
        ),
    }
    if let Role::Origin(spec) = &role {
        let backend = match spec {
            OriginSpec::Http(url) => decdn_config_types::redact_for_log(url.as_url()),
            OriginSpec::Fs(path) => format!("fs {}", path.display()),
            OriginSpec::S3 { bucket: Some(b) } => format!("s3 bucket {b}"),
            OriginSpec::S3 { bucket: None } => {
                "s3 (edit the MUST-EDIT bucket in [cache.origin])".to_string()
            }
        };
        println!(
            "origin backend: {backend} — cache.relay_foreign_namespaces derives to false \
             (origin-only)"
        );
    }
    Ok(())
}

/// Render the config `config init` writes for the selected chain and role.
///
/// Chain `None` starts from the blank template; `Some(chain)` bakes that
/// chain's id, RPC, and manifest contract addresses into the `[blockchain]`
/// section — so the file runs out of the box once a keystore exists. The role
/// then picks the shape: [`Role::Client`] uses the trimmed [`CLIENT_CONFIG`]
/// template, [`Role::Origin`] additionally activates a `[cache.origin]` block,
/// and [`Role::Relay`] leaves the node template as-is.
fn render_config(chain: Option<&known_chains::KnownChain>, role: &Role) -> anyhow::Result<String> {
    if let Role::Client = role {
        let Some(chain) = chain else {
            return Ok(CLIENT_CONFIG.to_string());
        };
        let filled = render_client_blockchain_section(chain)?;
        // The client template ends with `[blockchain]`, so the splice runs to EOF.
        return splice_section(CLIENT_CONFIG, &filled, "\n[blockchain]\n", None);
    }
    let base = match chain {
        None => DEFAULT_CONFIG.to_string(),
        Some(chain) => {
            let filled = render_blockchain_section(chain)?;
            splice_section(
                DEFAULT_CONFIG,
                &filled,
                "\n[blockchain]\n",
                Some("\n[cache]\n"),
            )?
        }
    };
    match role {
        Role::Origin(spec) => insert_origin_block(&base, spec),
        Role::Relay | Role::Client => Ok(base),
    }
}

/// Build the filled `[blockchain]` section for a known chain.
fn render_blockchain_section(chain: &known_chains::KnownChain) -> anyhow::Result<String> {
    let a = chain.addresses()?;
    Ok(format!(
        "[blockchain]\n\
         # Baked in for {label} (chain {chain_id}) from the shipped deployment\n\
         # manifest (contracts/deployments/{chain_id}.json). Ready to run as-is;\n\
         # `eth_keystore` defaults to <data_dir>/keystore.json — create it with\n\
         # `decdn key-gen`. Point `rpc_url` at your own provider for production.\n\
         rpc_url = \"{rpc}\"\n\
         chain_id = {chain_id}\n\
         # eth_keystore = \"~/.decdn/keystore.json\"   # defaults to <data_dir>/keystore.json\n\
         # --- Contract addresses (from deployments/{chain_id}.json) ---\n\
         payment_pool_address       = \"{payment_pool}\"\n\
         capacity_bond_address      = \"{capacity_bond}\"\n\
         slash_judge_address        = \"{slash_judge}\"\n\
         content_blacklist_address  = \"{content_blacklist}\"\n\
         origin_assignment_address  = \"{origin_assignment}\"\n\
         publisher_registry_address = \"{publisher_registry}\"\n\
         slash_appeal_address       = \"{slash_appeal}\"\n\
         usdc_address               = \"{usdc}\"\n\
         # Optional tuning knobs (economics, poll intervals) are commented in the\n\
         # blank template — see `decdn config init --chain none`.\n\
         \n",
        label = chain.label,
        chain_id = chain.chain_id,
        rpc = chain.public_rpc,
        payment_pool = a.payment_pool,
        capacity_bond = a.capacity_bond,
        slash_judge = a.slash_judge,
        content_blacklist = a.content_blacklist,
        origin_assignment = a.origin_assignment,
        publisher_registry = a.publisher_registry,
        slash_appeal = a.slash_appeal,
        usdc = a.usdc,
    ))
}

/// Build the filled `[blockchain]` section for the client shape of a known
/// chain. The client consumes `rpc_url`, `chain_id`, `eth_keystore`,
/// `payment_pool_address`, and `usdc_address`; the remaining contract
/// addresses are daemon/operator keys the client ignores, kept active so the
/// same file also passes `decdn config validate` (whose resolver requires
/// `capacity_bond_address` and `slash_judge_address`).
fn render_client_blockchain_section(chain: &known_chains::KnownChain) -> anyhow::Result<String> {
    let a = chain.addresses()?;
    Ok(format!(
        "[blockchain]\n\
         # Baked in for {label} (chain {chain_id}) from the shipped deployment\n\
         # manifest (contracts/deployments/{chain_id}.json). The client consumes the\n\
         # first block of keys; the remaining contract addresses are daemon/operator\n\
         # keys it ignores, kept active so this file also passes `decdn config\n\
         # validate`. Ready to fetch as-is once the keystore exists (`decdn key-gen\n\
         # --output-dir ~/.decdn/client`) and holds USDC. Point `rpc_url` at your own\n\
         # provider for production.\n\
         rpc_url = \"{rpc}\"\n\
         chain_id = {chain_id}\n\
         # eth_keystore = \"~/.decdn/client/keystore.json\"   # defaults to <data_dir>/keystore.json\n\
         payment_pool_address       = \"{payment_pool}\"\n\
         usdc_address               = \"{usdc}\"\n\
         # buyer_working_deposit_micro_usdc = 10000000  # deposit when OPENING a pool and refill target; must be > 0; default 10 USDC\n\
         # buyer_max_approve = false          # exact deposit-sized USDC approvals (client default); true opts into an unlimited standing approval\n\
         # --- Daemon/operator addresses (ignored by the client) ---\n\
         capacity_bond_address      = \"{capacity_bond}\"\n\
         slash_judge_address        = \"{slash_judge}\"\n\
         content_blacklist_address  = \"{content_blacklist}\"\n\
         origin_assignment_address  = \"{origin_assignment}\"\n\
         publisher_registry_address = \"{publisher_registry}\"\n\
         slash_appeal_address       = \"{slash_appeal}\"\n",
        label = chain.label,
        chain_id = chain.chain_id,
        rpc = chain.public_rpc,
        payment_pool = a.payment_pool,
        usdc = a.usdc,
        capacity_bond = a.capacity_bond,
        slash_judge = a.slash_judge,
        content_blacklist = a.content_blacklist,
        origin_assignment = a.origin_assignment,
        publisher_registry = a.publisher_registry,
        slash_appeal = a.slash_appeal,
    ))
}

/// Replace one top-level section of a template with a filled block.
///
/// The section runs from `start_header` to `end_header` — or to the end of the
/// template when `end_header` is `None` (for a template whose spliced section
/// is last). The needed headers are guaranteed present by the template guard
/// tests; a missing marker is a hard error rather than a silent mis-splice.
fn splice_section(
    template: &str,
    filled: &str,
    start_header: &str,
    end_header: Option<&str>,
) -> anyhow::Result<String> {
    let start = template
        .find(start_header)
        .map(|i| i + 1)
        .with_context(|| {
            format!(
                "template is missing the {} section header",
                start_header.trim()
            )
        })?;
    let rest = template
        .get(start..)
        .context("template section slice out of bounds")?;
    let end = match end_header {
        Some(header) => {
            let rel = rest.find(header).map(|i| i + 1).with_context(|| {
                format!(
                    "template is missing the {} section header after {}",
                    header.trim(),
                    start_header.trim()
                )
            })?;
            start + rel
        }
        None => template.len(),
    };
    let head = template
        .get(..start)
        .context("template head slice out of bounds")?;
    let tail = template
        .get(end..)
        .context("template tail slice out of bounds")?;
    Ok(format!("{head}{filled}{tail}"))
}

/// Splice the active `[cache.origin]` block `--origin <URL>` asked for into a
/// rendered node config, at the end of its `[cache]` section — immediately
/// before the `[payment]` header.
///
/// Everything between the `[cache]` header and `[payment]` in the template is
/// comments, so the last active header above the insertion point is `[cache]`
/// itself. That placement is why the commented `relay_foreign_namespaces`
/// override line sits *above* the `[cache.origin]` header: uncommented in
/// place it lands in `[cache]`, where the key belongs — below the header it
/// would parse as an unknown `[cache.origin]` field and fail resolution.
fn insert_origin_block(template: &str, spec: &OriginSpec) -> anyhow::Result<String> {
    let at = template
        .find("\n[payment]\n")
        .map(|i| i + 1)
        .context("rendered config is missing the [payment] section header")?;
    let head = template
        .get(..at)
        .context("rendered config head slice out of bounds")?;
    let tail = template
        .get(at..)
        .context("rendered config tail slice out of bounds")?;
    let backend = match spec {
        // `url` came through `parse_origin_url`, whose normalization
        // percent-encodes characters that could break out of a TOML basic
        // string.
        OriginSpec::Http(url) => format!(
            "[cache.origin]\n\
             kind = \"http\"\n\
             url = \"{url}\"\n"
        ),
        OriginSpec::Fs(path) => {
            let path = path
                .to_str()
                .context("--origin file:// path is not valid UTF-8, so it cannot be written to a TOML config")?;
            format!(
                "[cache.origin]\n\
                 kind = \"fs\"\n\
                 path = {}\n",
                toml_basic_string(path)?
            )
        }
        OriginSpec::S3 { bucket } => {
            let (bucket_line, edit_note) = match bucket {
                Some(b) => (format!("bucket = {}", toml_basic_string(b)?), ""),
                None => (
                    "bucket = \"your-origin-bucket\"    # MUST-EDIT: your bucket name".to_string(),
                    " Edit the MUST-EDIT bucket, then",
                ),
            };
            format!(
                "# S3-compatible origin (AWS S3 / Cloudflare R2 / Backblaze B2 / MinIO).{edit_note}\n\
                 # confirm `region`; for non-AWS providers uncomment `endpoint_url` (and\n\
                 # `path_style = true` for MinIO). Credentials default to the AWS chain\n\
                 # (env / ~/.aws / IAM role) — uncomment [cache.origin.credentials] to override.\n\
                 [cache.origin]\n\
                 kind = \"s3\"\n\
                 {bucket_line}\n\
                 region = \"us-east-1\"                      # required even with a custom endpoint_url (SigV4 signing)\n\
                 # endpoint_url = \"https://<accountid>.r2.cloudflarestorage.com\"  # for R2/B2/MinIO; omit for AWS\n\
                 # path_style = true                         # required true for MinIO\n\
                 # prefix = \"blobs/\"                         # optional key prefix; final key is {{prefix}}{{hex[0..2]}}/{{hex}}\n\
                 # decompress = \"auto\"                       # \"auto\" decompresses gzip/zstd, \"strict\" refuses non-identity encodings\n\
                 # [cache.origin.credentials]\n\
                 # source = \"default-chain\"                  # or \"static\" with access_key_id = \"...\" and secret_access_key = \"...\"\n"
            )
        }
    };
    let block = format!(
        "# --- Origin backend (written by `decdn config init --origin`) ---\n\
         # An active origin backend makes this an ORIGIN node: the runtime derives\n\
         # relay_foreign_namespaces = false (serve own namespaces only). Uncomment the\n\
         # next line to override the derived value — set true to also relay foreign\n\
         # content for pay while running an origin backend.\n\
         # relay_foreign_namespaces = false\n\
         {backend}\
         \n"
    );
    Ok(format!("{head}{block}{tail}"))
}

/// Quote a value as a TOML basic string, escaping `\` and `"`.
///
/// Needed for values that did not come through `parse_origin_url`'s
/// percent-encoding — a filesystem path or a bucket name — where a quote or
/// backslash in the value would otherwise break out of the emitted string.
/// Control characters (which TOML basic strings also forbid) are rejected
/// rather than escaped: none has a legitimate place in a path or bucket name.
fn toml_basic_string(value: &str) -> anyhow::Result<String> {
    anyhow::ensure!(
        !value.chars().any(char::is_control),
        "value contains a control character, which cannot be written to a TOML config"
    );
    Ok(format!(
        "\"{}\"",
        value.replace('\\', "\\\\").replace('"', "\\\"")
    ))
}

/// Trimmed TOML template `decdn config init --client` writes.
///
/// A client is a fetch-only consumer (`decdn fetch`, `decdn bundle pull`): it
/// needs an identity, chain coordinates, and USDC to deposit — none of the
/// cache/origin/serving sections a `decdn-node` daemon reads. The
/// `client_config_template_is_trimmed_and_parses` guard keeps this template
/// parsing against the live `FileConfig` schema with only the `[identity]`
/// and `[blockchain]` sections present.
const CLIENT_CONFIG: &str = r#"# deCDN client configuration — fetch-only consumer.
# A client fetches and pays (`decdn fetch`, `decdn bundle pull`); it needs an
# identity, chain coordinates, and USDC to deposit. The cache/origin/serving
# sections a `decdn-node` daemon reads do not apply and are omitted.
# CLI flags override values in this file.

[identity]
# data_dir = "~/.decdn/client"       # holds the eth keystore and the buyer pool store

[blockchain]
# rpc_url = ""                       # REQUIRED: JSON-RPC URL for the payment chain
# chain_id = 421614                  # EIP-712 chain id; default Arbitrum Sepolia
# eth_keystore = "~/.decdn/client/keystore.json"   # defaults to <data_dir>/keystore.json; create with `decdn key-gen --output-dir ~/.decdn/client`
# payment_pool_address = ""          # REQUIRED: 0x-prefixed hex; PaymentPool contract the client opens its pool on
# usdc_address = ""                  # USDC settlement token deposits spend
# buyer_working_deposit_micro_usdc = 10000000  # deposit when OPENING a pool and refill target; must be > 0; default 10 USDC
# buyer_max_approve = false          # exact deposit-sized USDC approvals (client default); true opts into an unlimited standing approval
"#;

/// Default TOML config file content, written by `decdn config init`.
///
/// This is the **canonical, fully-commented node config template** — the one
/// place that enumerates every section and knob. There is no hand-maintained
/// sample config beside it: `config init` (role flags + `--chain` presets) is
/// the single source of a valid config. The one other hand-maintained copy
/// (the e2e `render_config` template) is not derived from it, so CI guards
/// against drift instead:
///
/// - `default_config_template_parses_with_every_section` — this template
///   parses under `deny_unknown_fields` (no stale/typo'd section headers) and
///   carries a header for *every* top-level `FileConfig` section, so adding a
///   schema section without surfacing it here fails CI.
/// - `render_config_emits_parseable_toml` (in `decdn_e2e`) — the e2e template
///   parses as valid TOML and spot-checks the daemon-critical keys.
///
/// When adding a config knob, update this template first — the
/// `default_config_template_covers_every_wired_field` guard below enforces
/// field-level coverage for the daemon-config sections.
const DEFAULT_CONFIG: &str = r#"# deCDN node configuration
# CLI flags override values in this file.

[identity]
# data_dir = "~/.decdn"
# region = "US"

[network]
# bind_port = 4433
# Multiple relays give redundancy/failover; the node logs whether a relay connected
# after bring-up but never fails on it (iroh retries in the background).
# relay_urls = ["https://relay-a.example.", "https://relay-b.example."]
# Operator-configurable address discovery (#818). Absent => n0-hosted pkarr/DNS.
# Present => the node drops the n0 discovery leg and uses only what is set here.
# [network.discovery]
# pkarr_url = "https://pkarr.example./"      # publish this node's signed address record here
# dns_origin = "discovery.example."          # resolve peers via DNS TXT under this origin
# Static peer address book (fully offline; keyed by NodeId — 64-char lowercase hex):
# [network.discovery.peers.0000000000000000000000000000000000000000000000000000000000000000]
# relay_url = "https://relay.example./"
# addrs = ["203.0.113.4:4433"]

[blockchain]
# rpc_url = ""                       # REQUIRED: Arbitrum Sepolia JSON-RPC URL
# eth_keystore = "~/.decdn/keystore.json"
# payment_pool_address = ""          # REQUIRED: 0x-prefixed hex
# capacity_bond_address = ""        # REQUIRED: 0x-prefixed hex
# origin_assignment_address = ""     # OPTIONAL: 0x-prefixed hex; `decdn publish assign` target, and the chain-backed origin directory for cache-miss pull-through fallback (ADR 022).
# origin_directory_positive_ttl_sec = 300  # lazy origin directory: how long a resolved, non-empty getOrigins() set is served before a re-read; only consulted when origin_assignment_address is set; 0 disables caching; default 300s
# origin_directory_negative_ttl_sec = 30   # lazy origin directory: how long "namespace has no origins" is cached — the DoS bound against permissionless/free namespace creation; only consulted when origin_assignment_address is set; 0 disables caching; default 30s
# origin_directory_cache_capacity = 4096   # lazy origin directory: max distinct namespaces held (LRU eviction); only consulted when origin_assignment_address is set; default 4096
# publisher_registry_address = ""    # OPTIONAL: 0x-prefixed hex; `decdn publish namespace create` target (#1029).
# slash_judge_address = ""           # REQUIRED: 0x-prefixed hex (EIP-712 verifyingContract, ADR 014)
# content_blacklist_address = ""     # REQUIRED: 0x-prefixed hex; deployed ContentBlacklist (ADR 011/031). Absent => startup fails before any ALPN accepts; the zero address is rejected (it is a fail-open compliance trap).
# content_blacklist_poll_interval_sec = 600  # blacklist watcher periodic replay + re-scope cadence (ADR 011); must be > 0; default 600s
# chain_staleness_grace_sec = 1800   # stop serving after this long without a successful chain read (ADR 011); guards deny-set/pool/signer-cap staleness; must be > 0; set large to opt out; default 1800s
# chain_id = 421614                  # EIP-712 chain id; default Arbitrum Sepolia
# rpc_watchdog_interval_sec = 30     # 0 disables the connectivity watchdog
# event_poll_interval_ms = 7000      # eth_getLogs tick cadence for chain watchers + pending-tx receipt polling (#1011/#1106); default 7000ms, min 250ms (lower for a local anvil)
# get_logs_max_block_span = 10000    # max blocks per chain-watcher eth_getLogs request; set to your RPC provider's range limit (the poller also shrinks the window when the provider rejects a range; set it to the lowest span the poller reaches while rejections keep coming); default 10000, must be > 0
# fee_shares_poll_interval_sec = 3600  # authoritative getShares() re-read cadence, safety net beside the SharesUpdated subscription (ADR 041); default 3600s, must be > 0
# redeem_threshold_micro_usdc = 1000000          # seller redeems accrued vouchers on-chain at this µUSDC balance (#327); default 1 USDC
# redeem_max_vouchers_per_tx = 300  # max vouchers per redeemMany tx; the redeemer chunks a sweep to stay under the block gas limit (default 300)
# redeem_interval_secs = 300                      # redeemer self-tick sweep cadence, the backstop beside the per-voucher hints (#327/#751); default 300s, must be > 0
# buyer_working_deposit_micro_usdc = 10000000    # deposit when OPENING a pool and refill target on reuse or mid-transfer shortfall; must be > 0; default 10 USDC
# buyer_max_approve = true                       # unlimited USDC approval for PaymentPool (#744); node default true, decdn client default false (exact deposit-sized approval); set true on the client to opt into unlimited
# pool_min_remaining_deposit_micro_usdc = 1000000 # refundable floor M the node keeps in reserve on a pool it serves (ADR 003 § Sizing); default 1 USDC
# pool_floor_signer_live_windows = 8              # per-signer LIVE concurrency cap k, in ramp-start credit windows: the most live un-vouchered floor reservation one capability signer may hold against a pool, k × one window (ADR 003 § Pool solvency); recycles as streams pay; lower-clamped to one window; default 8
# CLI-only [blockchain] keys — consumed by `decdn appeal` / the client, NOT the daemon.
# They live here because [blockchain] denies unknown fields and a node's node.toml is
# shared with those CLIs, so a config that drives them must still pass `config validate`.
# slash_appeal_address = ""          # `decdn appeal slash` target (ADR 028)
# usdc_address = ""                  # USDC settlement token clients spend on pool deposits (client resolves it from PaymentPool.usdc() at runtime)

[cache]
# cache_dir = "~/.decdn/cache"
# cache_size_mb = 102400                  # UPPER bound on the cache; the eviction driver clamps it down to keep disk_headroom_mb free on the volume (#1930). Set it large to let free disk size the cache.
# disk_headroom_mb = 8192                  # free disk (MiB) the eviction driver keeps unused on the cache_dir volume, defended against ANY process (#1930); default 8 GiB. 0 opts out (only cache_size_mb binds)
# max_blob_size_mb = 51200             # largest single blob admitted; unset => 50 GB capped to cache_size_mb. Must be <= cache_size_mb; 0 = unlimited
# max_rate_per_mb = 0                      # buyer-side per-MB rate ceiling for paid cache-miss pulls (USDC base units); 0 = unlimited (#1375). Refuses a provider quote above the lower of this and the candidate's probe rate, before paying. A buyer-side ceiling only; the node never bounds its own sell rate
# pinned_hashes = []                       # blob hashes (hex) exempted from LRU eviction (#276)
# user_agent = "decdn-node/<version>"      # User-Agent on HTTP origin pull-through (#435); default embeds the crate version
# Pull-through origin (singular). Mutually exclusive with the plural [[cache.origins]] form below.
# Empty => no pull-through; cache misses return NoOrigin.
# [cache.origin]
# kind = "http"
# url = "https://origin.example/"
# decompress = "auto"                      # optional; "auto" decompresses gzip/zstd, "strict" refuses non-identity encodings
# — or a local filesystem origin (blobs at {path}/{hex[0..2]}/{hex}):
# [cache.origin]
# kind = "fs"
# path = "/var/lib/decdn/origin"
# — or an S3-compatible origin (AWS S3 / Cloudflare R2 / Backblaze B2 / MinIO):
# [cache.origin]
# kind = "s3"
# bucket = "decdn-blobs"
# region = "us-east-1"                      # required even with a custom endpoint_url (SigV4 signing)
# endpoint_url = "https://<accountid>.r2.cloudflarestorage.com"  # for R2/B2/MinIO; omit for AWS
# path_style = true                         # required true for MinIO; AWS/R2 default to virtual-hosted-style
# prefix = "blobs/"                         # optional key prefix; final key is {prefix}{hex[0..2]}/{hex}
# decompress = "auto"                       # optional; mirrors the HTTP origin's knob
# [cache.origin.credentials]               # omit entirely to use the AWS default credential chain (env / ~/.aws / IAM role)
# source = "default-chain"                  # or "static" with access_key_id = "..." and secret_access_key = "..."
# Multi-origin fallback (#284), tried in order on a miss:
# [[cache.origins]]
# kind = "http"
# url = "https://primary.example/"
# Origin pull-through retry policy (#285); restart-required.
# [cache.origin_retry]
# max_retries = 3
# Per-origin circuit breaker (#963); restart-required. Fronts the retry loop: after
# failure_threshold consecutive origin-unavailable failures it trips OPEN and fast-fails
# every miss for cooldown_ms, then admits half_open_max_calls trial pulls. Structurally
# identical to [cache.origin_retry]. Set enabled = false (or failure_threshold = 0) to opt out.
# [cache.circuit_breaker]
# enabled = true
# failure_threshold = 5
# cooldown_ms = 30000
# half_open_max_calls = 1
# NOTE: the keys below belong to [cache], NOT to the [cache.origin_retry] table
# above — uncomment this header along with them or TOML will nest them wrongly.
# [cache]
# gc_interval_sec = 300                    # iroh-blobs GC sweep cadence; 0 disables (#518). NOTE: the eviction driver only drops GC protection, so with 0 it can never reclaim disk and cache_size_mb is unenforceable (#1173)
# fs_rescan_interval_sec = 60              # re-walk the fs origin + re-check pins into the origin-held index, so a file dropped into the origin becomes probe-answerable and DHT-announced within one interval (#1130); 0 disables the timer (startup and `decdn node reload` still rescan)
# origin_probe_ttl_sec = 15                # TTL for a memoised positive live-origin probe answer — a hash absent from the fs/pins index falls back to a HEAD/HeadObject against the http/s3 origin, a present answer cached this long (#1130 pt3)
# origin_probe_negative_ttl_sec = 2        # TTL for a memoised negative (absent) live-origin probe answer; short on purpose so a stale absent cannot hide newly-available own content for long (#1130 pt3)
# origin_probe_fault_ttl_sec = 5           # TTL for a memoised fault (backend outage) live-origin probe answer; the memo is per hash, so this collapses one hash's repeats rather than a namespace's load. Must satisfy origin_probe_negative_ttl_sec <= this <= origin_probe_ttl_sec: patient enough to beat the negative TTL on a retried hash, eager enough that a recovered origin stops refusing clients soon (#1130 pt3, #1789 item 6)
# origin_probe_timeout_ms = 2000           # per-probe ceiling on the live-origin HEAD/HeadObject; on timeout the probe answers has_blob:false and the miss is memoised absent for one negative TTL (#1130 pt3)
# origin_probe_memo_capacity = 4096        # max distinct hashes held in the live-origin probe memo; bounds memo memory under a random-hash probe flood (#1130 pt3)
# eviction_high_water_pct = 90             # LRU driver evicts above this % of cache_size_mb (#1173); bounds [60,95]
# eviction_target_pct = 80                 # LRU driver evicts down to this % (#1173); bounds [40,90], must be <= high_water-5
# eviction_per_sweep_budget = 16           # max LRU victims per tick before yielding (#1173); bounds [1,256]
# eviction_tick_secs = 1                   # LRU driver wakeup cadence in seconds (#1173); bounds [1,60]
# max_probe_holds = 256                    # probe eviction-hold budget (ADR 005 §Hold budget); 0 disables has_blob:true
# stake_lane_reserved_holds = 0            # hold slots reserved for node-to-node probes (#757, ADR 003 §Admission); 0 = off
# node_to_node_pull_through_enabled = false # paid cache-miss pull from upstream nodes (#831, ADR 001/022); OFF by default
# relay_foreign_namespaces = true          # relay content this node's own backend does not hold (#1759); default is role-derived — origin-only (false) when a [cache.origin]/[[cache.origins]] backend is configured, relay (true) when none is; set explicitly to override
# node_pull_probe_fanout = 5               # providers probed before ranking on a node-to-node pull (#831)
# node_pull_timeout_sec = 20               # per-upstream STREAM-OPEN timeout (connect/handshake/response) on a node-to-node miss; NOT the pool open, which has its own 5s budget. The overall pull-through deadline is derived from this, the pool-open budget, and the stall window, so every ranked upstream can be tried before falling back (#831, #859)
# node_pull_stall_window_sec = 20          # per-upstream THROUGHPUT-FLOOR window while streaming (#1797); bytes are counted off the stream sub-frame, so it trips only when throughput falls below the floor — not on a large blob or a big frame. Budgeted per candidate, so raising it raises the worst-case client wait ~3x (167.5s at defaults); also the head start of each own-origin range-pull read's time budget (ADR 037)
# node_pull_min_throughput_bps = 4096      # minimum sustained upstream throughput (bytes/sec) over node_pull_stall_window_sec (#1797); catches a slow-drip wedge. 0 = idle detection only (one byte per window). The abort is requester-local and does not score the upstream's reputation; also the average throughput each own-origin range-pull read ({H}.obao4 or one data window) must sustain after that head start, 0 = those reads unbounded
# eviction_policy = "lru"                  # ADR 040: "lru" or "tinylfu"; restart-required
# admission_policy = "always"              # ADR 040: "always" or "tinylfu"; restart-required
# [cache.tinylfu]                          # W-TinyLFU tuning (ADR 040); promotion_threshold/probation_target_pct apply only under a "tinylfu" selector, but sketch_bytes also sizes the serve_economics "margin" heat estimator (the default), so it is live on a stock node
# sketch_bytes = 262144                    # count-min sketch size, shared by admission and eviction; minimum 16384
# promotion_threshold = 2                  # prior sightings before a probation member promotes to main
# probation_target_pct = 10                # % of cache_size_mb the probation segment is capped to; bounds [1,50]
# aging_halflife_sec = 600                 # reserved: not yet consulted by the shipped sketch (fixed observation-count window)
# [cache.serve_economics]                  # refuse-to-serve economics (ADR 041)
# policy = "margin"                        # "off" or "margin"
# discount = 0.5                           # (0.0, 1.0]; discount applied to the sell price for the margin gate
# n_max = 64                               # max concurrent speculative-warming sources; >= 1
# warming_budget = 5000000                 # per-source warming allowance, in payment base units; > 0
# warming_refill = 58                      # per-source allowance refill rate, base units/sec; 0 disables time-based refill

[payment]
# rate_per_mb = 10
# credit_max = 67108864                    # downstream credit-window ceiling in bytes (ADR 003 §Credit window); the window ramps toward this cap as the stream pays; default 64 MiB; floored at one chunk plus one chunk group (1 MiB + 16 KiB)
# credit_ramp_divisor = 2                  # ramp divisor (ADR 003 §Credit window); window is paid/credit_ramp_divisor, capped at credit_max; 0 opens the full ceiling immediately
# frame_target_bytes = 1048576              # serve-path wire-frame target in bytes (ADR 005 §cdn/client/v1); node-local, never negotiated; clamped down to the credit window's remaining room; must be in 1..=1048576 (one payment chunk); default 1 MiB
# voucher_commit_interval_ms = 5000        # background flush period (ms) for durable voucher persistence (ADR 003); must be > 0; default 5000 (5s)

[observability]
# log_level = "info"
# log_format = "pretty"
# metrics_port = 9090
# metrics_bind = "127.0.0.1"               # IP the metrics HTTP server binds; default loopback only
# admin_port = 9191                        # loopback-only; 0 disables (appendix-local-admin-http.md)
# otlp_endpoint = "http://localhost:4317"  # OTLP gRPC collector (http:// only); enables span export

[security]
# max_concurrent_handlers = 256             # global cap on in-flight QUIC handler tasks; 0 disables the cap
# per_source_rate_per_sec = 100.0           # per-source rate-limit refill (cells/sec); 0.0 disables the layer
# per_source_burst = 200                    # per-source burst capacity; required > 0 when the rate is > 0
# max_tracked_sources = 4096                # cap on tracked sources in the keyed limiter; 0 = unbounded

[load_shed]
# policy = "resource-pressure"              # "resource-pressure" (default) or "always-admit"
# egress_budget_mbps = 0                    # serving egress budget in Mbps; 0 disables the egress ceiling
# max_concurrent_serves_high = 256          # concurrency high-water mark; start shedding misses at/above
# max_concurrent_serves_low = 192           # concurrency low-water mark; resume at/below
# per_client_serve_cap = 32                 # per-client concurrent-serve cap under pressure; 0 disables

[dht.rate_limit]
# per_peer_rate_per_sec = 20.0              # per-peer (NodeId) sustained rate (ADR 022); 0.0 disables the layer
# per_peer_burst = 40                       # per-peer burst capacity; required > 0 when the rate is > 0
# per_ip_rate_per_sec = 100.0               # per-IP sustained rate; 0.0 disables
# per_ip_burst = 200                        # per-IP burst capacity
# global_rate_per_sec = 1000.0              # global inbound DHT sustained rate; 0.0 disables
# global_burst = 2000                       # global inbound DHT burst capacity
# max_tracked_per_ip = 4096                 # cap on the per-IP keyed-limiter map (#645); 0 = unbounded
# max_tracked_per_peer = 4096               # cap on the per-peer keyed-limiter map (#645); 0 = unbounded

[probe.rate_limit]
# per_peer_rate_per_sec = 5.0               # per-peer (NodeId) sustained rate (ADR 005); 0.0 disables the layer
# per_peer_burst = 5                        # per-peer burst capacity; required > 0 when the rate is > 0
# per_ip_rate_per_sec = 50.0                # per-IP sustained rate; 0.0 disables
# per_ip_burst = 200                        # per-IP burst capacity
# global_rate_per_sec = 1000.0              # global inbound probe sustained rate; 0.0 disables
# global_burst = 2000                       # global inbound probe burst capacity
# max_tracked_per_ip = 4096                 # cap on the per-IP keyed-limiter map (#645); 0 = unbounded
# max_tracked_per_peer = 4096               # cap on the per-peer keyed-limiter map (#645); 0 = unbounded

[receipts]
# max_file_bytes = 134217728                # rotate the download-receipt log at this size (#802); default 128 MiB
# retained_files = 4                        # rotated backup receipt files retained (#802); 0 keeps none

[content]
# ADR 011 local denylist — this operator's own removal lever, independent of
# governance. Entries take effect on `decdn node reload` (no restart) and bind
# only this node. This is the fastest removal path the protocol offers and the
# one sized to a sub-day statutory deadline (e.g. the EU TCO one-hour clock),
# because it is entirely within the order recipient's control. Refused
# requests are signed as Declined, which does not reveal whether the entry is
# local or on-chain.
#
# Hashes are bare 64-char lowercase hex — the same spelling as
# cache.pinned_hashes. An invalid entry FAILS startup rather than being skipped:
# a typo in a takedown must not silently leave content served.
# denied_hashes = ["0000000000000000000000000000000000000000000000000000000000000000"]
# denied_origins = ["0x000000000000000000000000000000000000dEaD"]   # operator addresses whose pools are refused (the zero address is rejected)

[client]
# `decdn fetch`/`decdn bundle pull` discovery pre-filter (independent of the
# node-scoped [network.discovery] address discovery above). Narrows which
# registered nodes are probed/discovered; never ranks them. Absent/empty =>
# no filter, every registered node is eligible.
# region_allowlist = ["US", "DE"]
"#;

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] // tests
mod tests;