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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
//! Node implementation - thin wrapper around saorsa-core's `P2PNode`.
use crate::ant_protocol::CHUNK_PROTOCOL_ID;
use crate::config::{
default_nodes_dir, default_root_dir, NetworkMode, NodeConfig, NODE_IDENTITY_FILENAME,
};
use crate::error::{Error, Result};
use crate::event::{create_event_channel, NodeEvent, NodeEventsChannel, NodeEventsSender};
use crate::logging::{debug, error, info, warn};
use crate::payment::metrics::QuotingMetricsTracker;
use crate::payment::wallet::parse_rewards_address;
use crate::payment::{
EvmVerifierConfig, PaymentVerifier, PaymentVerifierConfig, PriceFloorConfig, QuoteGenerator,
};
use crate::replication::config::ReplicationConfig;
use crate::replication::fresh::FreshWriteEvent;
use crate::replication::ReplicationEngine;
use crate::storage::legacy_artifacts;
use crate::storage::traffic as storage_traffic;
use crate::storage::MIB;
use crate::storage::{AntProtocol, ChunkRequestContext, ChunkStore, ChunkStoreConfig};
use crate::upgrade::{
upgrade_cache_dir, AutoApplyUpgrader, BinaryCache, ReleaseCache, UpgradeMonitor, UpgradeResult,
};
use rand::Rng;
use saorsa_core::identity::NodeIdentity;
use saorsa_core::{
IPDiversityConfig as CoreDiversityConfig, MultiAddr, NodeConfig as CoreNodeConfig, P2PEvent,
P2PNode,
};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::Semaphore;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
#[cfg(unix)]
use tokio::signal::unix::{signal, SignalKind};
/// How long shutdown waits for in-flight request handlers to finish.
///
/// Short, because these are single request/response exchanges and the peer will retry.
/// The point is to stop new storage work starting, not to see every last request through.
const PROTOCOL_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(5);
/// The user agent this node announces itself with.
///
/// `saorsa-core` admits a peer to the DHT only when its agent starts with `node/`, so a node
/// that lost the prefix would stop being routed to. The version is this build's rather than
/// the transport's, because it is the one a peer needs in order to tell which release it is
/// talking to.
fn user_agent() -> String {
format!("node/{}", env!("CARGO_PKG_VERSION"))
}
/// Builder for constructing an Ant node.
pub struct NodeBuilder {
config: NodeConfig,
}
impl NodeBuilder {
/// Create a new node builder with the given configuration.
#[must_use]
pub fn new(config: NodeConfig) -> Self {
Self { config }
}
/// Reject startup in production mode without a usable rewards address.
///
/// A node that cannot receive payment must not silently run on the
/// production network. The placeholder address shipped in the example
/// config and an empty string both count as "unconfigured".
///
/// # Errors
///
/// Returns [`Error::Config`] if `network_mode` is `Production` and
/// `payment.rewards_address` is unset, empty, or the example placeholder.
fn validate_production_rewards_address(config: &NodeConfig) -> Result<()> {
if config.network_mode != NetworkMode::Production {
return Ok(());
}
let configured = config
.payment
.rewards_address
.as_deref()
.is_some_and(|addr| !addr.is_empty() && addr != "0xYOUR_ARBITRUM_ADDRESS_HERE");
if configured {
Ok(())
} else {
Err(Error::Config(
"CRITICAL: Rewards address is not configured. \
Set payment.rewards_address in config to your Arbitrum wallet address."
.to_string(),
))
}
}
/// Build and start the node.
///
/// # Errors
///
/// Returns an error if the node fails to start.
#[allow(clippy::too_many_lines)]
pub async fn build(mut self) -> Result<RunningNode> {
info!("Building ant-node with config: {:?}", self.config);
Self::validate_production_rewards_address(&self.config)?;
#[cfg(not(feature = "webrtc-direct"))]
if self.config.webrtc_direct.enabled {
return Err(Error::Config(
"webrtc_direct is enabled but this binary was not built with the \
'webrtc-direct' feature"
.to_string(),
));
}
// Resolve identity and root_dir (may update self.config.root_dir)
let identity = Arc::new(Self::resolve_identity(&mut self.config).await?);
let peer_id = identity.peer_id().to_hex();
info!(peer_id = %peer_id, root_dir = %self.config.root_dir.display(), "Node identity resolved");
// Ensure root directory exists
std::fs::create_dir_all(&self.config.root_dir)?;
// Create shutdown token
let shutdown = CancellationToken::new();
// Create event channel
let (events_tx, events_rx) = create_event_channel();
// Convert our config to saorsa-core's config
let mut core_config = Self::build_core_config(&self.config)?;
// Inject the ML-DSA identity so the P2PNode's transport peer ID
// matches the pub_key embedded in payment quotes.
core_config.node_identity = Some(Arc::clone(&identity));
debug!("Core config: {:?}", core_config);
// Initialize saorsa-core's P2PNode
let p2p_node = P2PNode::new(core_config)
.await
.map_err(|e| Error::Startup(format!("Failed to create P2P node: {e}")))?;
// Create upgrade monitor
let upgrade_monitor = {
let node_id_seed = p2p_node.peer_id().as_bytes();
Some(Self::build_upgrade_monitor(&self.config, node_id_seed))
};
let repl_config = ReplicationConfig::default();
// Initialize ANT protocol handler for chunk storage and
// wire the fresh-write channel so PUTs trigger replication.
let (ant_protocol, fresh_write_rx) = if self.config.storage.enabled {
let (fresh_write_tx, fresh_write_rx) = tokio::sync::mpsc::unbounded_channel();
let mut protocol =
Self::build_ant_protocol(&self.config, &identity, repl_config.close_group_size)
.await?;
protocol.set_fresh_write_sender(fresh_write_tx);
(Some(Arc::new(protocol)), Some(fresh_write_rx))
} else {
info!("Chunk storage disabled");
(None, None)
};
// Only now, and only if a store was actually opened. Clearing up after the storage
// migration deletes directories the previous release had retired, and retirement
// counted on every chunk the node kept being in the file store — which is only true
// if the file store is there. Doing this earlier put the deletion in front of a
// constructor that can still fail on an unreadable layout, a directory it cannot
// create, or a lock another process has not let go of, and a node that lost both
// stores that way had nothing to go back to.
//
// A node with storage switched off never builds one at all, so it never establishes
// that anything was copied anywhere, and it does not delete. It also has no use for
// the disk it would recover. Leaving the directory costs space on a node that is not
// storing anything anyway.
if ant_protocol.is_some() {
legacy_artifacts::clean_up(&self.config.root_dir);
} else {
info!(
"Chunk storage is disabled, so anything the storage migration left behind is \
being left where it is: nothing here can establish that its chunks were \
copied anywhere."
);
}
let p2p_arc = Arc::new(p2p_node);
// Wire the P2PNode handle into AntProtocol so payment proofs can query
// live-DHT closeness.
if let Some(ref protocol) = ant_protocol {
protocol.attach_p2p_node(Arc::clone(&p2p_arc));
}
let replication_engine = match (&ant_protocol, fresh_write_rx) {
(Some(protocol), Some(fresh_rx)) => {
Self::build_replication_engine(
protocol,
repl_config,
&p2p_arc,
&identity,
&self.config.root_dir,
fresh_rx,
&shutdown,
)
.await?
}
_ => None,
};
let node = RunningNode {
config: self.config,
p2p_node: p2p_arc,
shutdown,
events_tx,
events_rx: Some(events_rx),
upgrade_monitor,
ant_protocol,
replication_engine,
protocol_task: None,
protocol_children: TaskTracker::new(),
#[cfg(feature = "webrtc-direct")]
webrtc_direct_task: None,
#[cfg(feature = "webrtc-direct")]
webrtc_diagnostics: tokio::sync::watch::channel(None).0,
upgrade_exit_code: Arc::new(AtomicI32::new(-1)),
};
Ok(node)
}
/// Start the replication engine.
///
/// # Errors
///
/// Never, currently: an engine that fails to start is logged and the node runs without
/// one, as it always has. The signature keeps its `Result` because the caller's does.
async fn build_replication_engine(
protocol: &Arc<AntProtocol>,
repl_config: ReplicationConfig,
p2p: &Arc<P2PNode>,
identity: &Arc<NodeIdentity>,
root_dir: &Path,
fresh_rx: UnboundedReceiver<FreshWriteEvent>,
shutdown: &CancellationToken,
) -> Result<Option<ReplicationEngine>> {
let mut engine = match ReplicationEngine::new(
repl_config,
Arc::clone(p2p),
protocol.storage(),
protocol.payment_verifier_arc(),
Arc::clone(identity),
root_dir,
fresh_rx,
shutdown.clone(),
)
.await
{
Ok(engine) => engine,
Err(e) => {
warn!("Failed to initialize replication engine: {e}");
return Ok(None);
}
};
// ADR-0016: pointers replicate through the same engine. The PUT handler
// hands each newly stored paid state to it, and asks it before taking
// a final state (ADR-0018).
if let Some(service) = protocol.pointer_service() {
engine.with_pointer_service(service);
}
// ADR-0004: wire the engine's commitment state as the quote generator's
// commitment source so quotes force their price from the live storage
// commitment. Done here because the engine owns the commitment state and is
// built after the protocol.
let concrete = Arc::clone(engine.commitment_state());
let source: Arc<dyn crate::payment::quote::CommitmentSource> = concrete;
protocol.attach_commitment_source(source);
// ADR-0004: share the engine's gossip commitment cache with the verifier so the
// cross-check can resolve quote pins against neighbours' commitments.
protocol
.payment_verifier_arc()
.attach_commitment_cache(Arc::clone(engine.last_commitment_by_peer()));
// ADR-0004: give the verifier the monetized-pin sender so commitments that back
// a payment get a deterministic first audit from the engine's drainer.
protocol
.payment_verifier_arc()
.attach_monetized_pin_sender(engine.monetized_pin_sender());
Ok(Some(engine))
}
/// Build the saorsa-core `NodeConfig` from our config.
fn build_core_config(config: &NodeConfig) -> Result<CoreNodeConfig> {
let local = matches!(config.network_mode, NetworkMode::Development);
let mut core_config = CoreNodeConfig::builder()
.port(config.port)
.ipv6(!config.ipv4_only)
.local(local)
.max_message_size(config.max_message_size)
.build()
.map_err(|e| Error::Config(format!("Failed to create core config: {e}")))?;
// Add bootstrap peers.
core_config.bootstrap_peers = config
.bootstrap
.iter()
.map(|addr| MultiAddr::quic(*addr))
.collect();
// Propagate network-mode tuning into saorsa-core where supported.
match config.network_mode {
NetworkMode::Production => {
core_config.diversity_config = Some(CoreDiversityConfig::default());
}
NetworkMode::Testnet => {
// Testnet allows loopback so nodes can be co-located on one machine.
core_config.allow_loopback = true;
core_config.diversity_config = Some(CoreDiversityConfig {
max_per_ip: config.testnet.max_per_ip,
max_per_subnet: config.testnet.max_per_subnet,
});
}
NetworkMode::Development => {
core_config.diversity_config = Some(CoreDiversityConfig::permissive());
}
}
core_config.custom_user_agent = Some(user_agent());
// Persist close group peers + trust scores across restarts.
// Default to root_dir (alongside node_identity.key) when not explicitly set.
core_config.close_group_cache_dir = Some(
config
.close_group_cache_dir
.clone()
.unwrap_or_else(|| config.root_dir.clone()),
);
Ok(core_config)
}
/// Resolve the node identity from disk or generate a new one.
///
/// **When `root_dir` differs from the platform default** (set via `--root-dir`
/// or loaded from `config.toml`):
/// - Use `root_dir` directly: load existing identity or generate a new one.
///
/// **When `root_dir` is the platform default** (first run, no config file):
/// 1. Scan `{default_root_dir}/nodes/` for subdirectories containing
/// `node_identity.key`.
/// 2. **None found** — first run: generate identity, create
/// `nodes/{full_peer_id}/`, save identity there, update `config.root_dir`.
/// 3. **Exactly one found** — load it and update `config.root_dir`.
/// 4. **Multiple found** — return an error asking for `--root-dir`.
async fn resolve_identity(config: &mut NodeConfig) -> Result<NodeIdentity> {
if config.root_dir != default_root_dir() {
return Self::load_or_generate_identity(&config.root_dir).await;
}
let nodes_dir = default_nodes_dir();
let identity_dirs = Self::scan_identity_dirs(&nodes_dir)?;
match identity_dirs.len() {
0 => {
// First run: generate new identity and create a peer-id-scoped subdirectory
let identity = NodeIdentity::generate().map_err(|e| {
Error::Startup(format!("Failed to generate node identity: {e}"))
})?;
let peer_id = identity.peer_id().to_hex();
let peer_dir = nodes_dir.join(&peer_id);
std::fs::create_dir_all(&peer_dir)?;
identity
.save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
.await
.map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
config.root_dir = peer_dir;
Ok(identity)
}
1 => {
let dir = identity_dirs
.first()
.ok_or_else(|| Error::Config("No identity dirs found".to_string()))?;
let identity = NodeIdentity::load_from_file(&dir.join(NODE_IDENTITY_FILENAME))
.await
.map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))?;
config.root_dir.clone_from(dir);
Ok(identity)
}
_ => {
let dirs: Vec<String> = identity_dirs
.iter()
.filter_map(|d| d.file_name().map(|n| n.to_string_lossy().into_owned()))
.collect();
Err(Error::Config(format!(
"Multiple node identities found at {}: [{}]. Specify --root-dir to select one.",
nodes_dir.display(),
dirs.join(", ")
)))
}
}
}
/// Load an existing identity from `dir/node_identity.key`, or generate and save a new one.
async fn load_or_generate_identity(dir: &std::path::Path) -> Result<NodeIdentity> {
let key_path = dir.join(NODE_IDENTITY_FILENAME);
if key_path.exists() {
NodeIdentity::load_from_file(&key_path)
.await
.map_err(|e| Error::Startup(format!("Failed to load node identity: {e}")))
} else {
let identity = NodeIdentity::generate()
.map_err(|e| Error::Startup(format!("Failed to generate node identity: {e}")))?;
std::fs::create_dir_all(dir)?;
identity
.save_to_file(&key_path)
.await
.map_err(|e| Error::Startup(format!("Failed to save node identity: {e}")))?;
Ok(identity)
}
}
/// Scan `base_dir` for immediate subdirectories that contain `node_identity.key`.
fn scan_identity_dirs(base_dir: &std::path::Path) -> Result<Vec<PathBuf>> {
let mut dirs = Vec::new();
let read_dir = match std::fs::read_dir(base_dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(dirs),
Err(e) => return Err(e.into()),
};
for entry in read_dir {
let entry = entry?;
let path = entry.path();
if path.is_dir() && path.join(NODE_IDENTITY_FILENAME).exists() {
dirs.push(path);
}
}
Ok(dirs)
}
fn build_upgrade_monitor(config: &NodeConfig, node_id_seed: &[u8]) -> UpgradeMonitor {
let mut monitor = UpgradeMonitor::new(
config.upgrade.github_repo.clone(),
config.upgrade.channel,
config.upgrade.check_interval_hours,
);
if let Ok(cache_dir) = upgrade_cache_dir() {
monitor = monitor.with_release_cache(ReleaseCache::new(
cache_dir,
std::time::Duration::from_hours(1),
));
}
if config.upgrade.staged_rollout_hours > 0 {
monitor =
monitor.with_staged_rollout(node_id_seed, config.upgrade.staged_rollout_hours);
}
monitor
}
/// Build the ANT protocol handler from config.
///
/// Initializes the chunk store, payment verifier, and quote generator.
/// Wires ML-DSA-65 signing from the node's identity into the quote generator.
async fn build_ant_protocol(
config: &NodeConfig,
identity: &NodeIdentity,
close_group_size: usize,
) -> Result<AntProtocol> {
let storage_config = ChunkStoreConfig {
root_dir: config.root_dir.clone(),
verify_on_read: config.storage.verify_on_read,
disk_reserve: config.storage.disk_reserve_mb.saturating_mul(MIB),
};
let storage = ChunkStore::new(storage_config)
.await
.map_err(|e| Error::Startup(format!("Failed to create the chunk store: {e}")))?;
// Parse rewards address (required — node must know where to receive payments)
let rewards_address = match config.payment.rewards_address {
Some(ref addr) => parse_rewards_address(addr)?,
None => {
return Err(Error::Startup(
"No rewards address configured. Set --rewards-address or payment.rewards_address in config.".to_string(),
));
}
};
// Create payment verifier
let evm_network = config.payment.evm_network.clone().into_evm_network();
let payment_config = PaymentVerifierConfig {
evm: EvmVerifierConfig {
network: evm_network,
},
cache_capacity: config.payment.cache_capacity,
close_group_size,
local_rewards_address: rewards_address,
// Shadow mode by default; enforcement is a per-node canary opt-in
// via ANT_PRICE_FLOOR_ENFORCE (see PriceFloorConfig).
price_floor: PriceFloorConfig::from_env(),
};
if payment_config.price_floor.enforce {
info!(
"Price floor ENFORCEMENT enabled (tolerance {}%)",
payment_config.price_floor.tolerance_percent
);
}
let payment_verifier = PaymentVerifier::new(payment_config);
let metrics_tracker = QuotingMetricsTracker::new(0);
let mut quote_generator = QuoteGenerator::new(rewards_address, metrics_tracker);
// Wire ML-DSA-65 signing from node identity.
// This same signer is used for both regular quotes and merkle candidate quotes.
crate::payment::wire_ml_dsa_signer(&mut quote_generator, identity)?;
let storage = Arc::new(storage);
let payment_verifier = Arc::new(payment_verifier);
// Pointers live beside the chunks, under the same root. Opening the
// store here is what makes pointer PUT/GET answerable at all: without
// it every pointer request is refused, which is the right answer for a
// node that keeps none but the wrong one for a node that should.
let pointer_store = crate::pointer::PointerStore::new(&config.root_dir).await?;
let pointers = crate::pointer::PointerService::new(pointer_store)
// Refuse a pointer whose address a chunk already occupies, rather
// than letting one kind silently overwrite the other.
.with_chunk_store(Arc::clone(&storage))
// Payment is verified against each record's state, so every update
// is paid for rather than riding the first one.
.with_payments(Arc::clone(&payment_verifier));
let protocol = AntProtocol::new(storage, payment_verifier, Arc::new(quote_generator))
.with_pointer_service(pointers);
info!(
"ANT protocol handler initialized with ML-DSA-65 signing (protocol={CHUNK_PROTOCOL_ID})"
);
Ok(protocol)
}
}
/// A running Ant node.
pub struct RunningNode {
config: NodeConfig,
p2p_node: Arc<P2PNode>,
shutdown: CancellationToken,
events_tx: NodeEventsSender,
events_rx: Option<NodeEventsChannel>,
upgrade_monitor: Option<UpgradeMonitor>,
/// ANT protocol handler for chunk storage.
ant_protocol: Option<Arc<AntProtocol>>,
/// Replication engine (manages neighbor sync, verification, audits).
replication_engine: Option<ReplicationEngine>,
/// Protocol message routing background task.
protocol_task: Option<JoinHandle<()>>,
/// The per-message handler tasks the protocol loop spawns.
///
/// Tracked rather than detached so shutdown can stop accepting work and then wait for
/// what is already in flight. Aborting only the loop leaves its children running, and
/// a chunk read that outlives the loop keeps working against a store the shutdown is
/// about to tear down.
protocol_children: TaskTracker,
/// ADR-0015 browser listener task.
#[cfg(feature = "webrtc-direct")]
webrtc_direct_task: Option<JoinHandle<()>>,
#[cfg(feature = "webrtc-direct")]
webrtc_diagnostics: tokio::sync::watch::Sender<Option<crate::web_rtc::WebRtcServerDiagnostics>>,
/// Exit code requested by a successful upgrade (-1 = no upgrade exit pending).
upgrade_exit_code: Arc<AtomicI32>,
}
impl RunningNode {
/// Subscribe before `run()` to receive the browser diagnostics handle after startup.
/// The handle can be sampled at any time and retains counters after shutdown.
#[cfg(feature = "webrtc-direct")]
#[must_use]
pub fn subscribe_webrtc_diagnostics(
&self,
) -> tokio::sync::watch::Receiver<Option<crate::web_rtc::WebRtcServerDiagnostics>> {
self.webrtc_diagnostics.subscribe()
}
/// Get the node's root directory.
#[must_use]
pub fn root_dir(&self) -> &PathBuf {
&self.config.root_dir
}
/// Get a receiver for node events.
///
/// Note: Can only be called once. Subsequent calls return None.
pub fn events(&mut self) -> Option<NodeEventsChannel> {
self.events_rx.take()
}
/// Subscribe to node events.
#[must_use]
pub fn subscribe_events(&self) -> NodeEventsChannel {
self.events_tx.subscribe()
}
/// Run the node until shutdown is requested.
///
/// # Errors
///
/// Returns an error if the node encounters a fatal error.
pub async fn run(&mut self) -> Result<()> {
let result = self.run_until_shutdown().await;
self.cleanup().await;
// If an upgrade triggered the shutdown, exit with the requested code.
// This happens *after* all cleanup (P2P shutdown, log flush, etc.) so
// that destructors and async resources are properly torn down.
let exit_code = self.upgrade_exit_code.load(Ordering::SeqCst);
if result.is_ok() && exit_code >= 0 {
info!("Exiting with code {} for upgrade restart", exit_code);
std::process::exit(exit_code);
}
result
}
/// Start serving and wait for shutdown; the caller owns cleanup on every exit.
#[allow(clippy::too_many_lines)]
async fn run_until_shutdown(&mut self) -> Result<()> {
info!("Node runtime loop starting");
// Subscribe to DHT events BEFORE starting the P2P node so the
// bootstrap-sync task does not miss the BootstrapComplete event
// emitted during P2PNode::start().
let dht_events_for_bootstrap = self
.replication_engine
.as_ref()
.map(|_| self.p2p_node.dht_manager().subscribe_events());
// Start the P2P node
self.p2p_node
.start()
.await
.map_err(|e| Error::Startup(format!("Failed to start P2P node: {e}")))?;
let listen_addrs = self.p2p_node.listen_addrs().await;
info!(listen_addrs = ?listen_addrs, "P2P node started");
// Extract the actual bound port (config port may be 0 = auto-select)
let actual_port = listen_addrs
.first()
.and_then(MultiAddr::port)
.unwrap_or(self.config.port);
info!(
port = actual_port,
"Node is running on port: {}", actual_port
);
#[cfg(feature = "webrtc-direct")]
if self.config.webrtc_direct.enabled {
let evm_network = self.config.payment.evm_network.clone().into_evm_network();
match crate::web_rtc::spawn(
&self.config.webrtc_direct,
&self.config.root_dir,
Arc::clone(&self.p2p_node),
self.ant_protocol.clone(),
&evm_network,
self.shutdown.clone(),
None,
)
.await
{
Ok(server) => {
let _ = self
.webrtc_diagnostics
.send_replace(Some(server.diagnostics));
self.webrtc_direct_task = Some(server.task);
}
Err(error) => {
return Err(error);
}
}
}
// Emit started event
if let Err(e) = self.events_tx.send(NodeEvent::Started) {
warn!("Failed to send Started event: {e}");
}
// Start protocol message routing (P2P → AntProtocol → P2P response)
self.start_protocol_routing();
// Start replication engine background tasks
if let Some(ref mut engine) = self.replication_engine {
// Safety: dht_events_for_bootstrap is Some when replication_engine
// is Some (both arms use the same condition).
if let Some(dht_events) = dht_events_for_bootstrap {
engine.start(dht_events);
}
info!("Replication engine started");
}
// Start upgrade monitor if enabled
if let Some(monitor) = self.upgrade_monitor.take() {
let events_tx = self.events_tx.clone();
let shutdown = self.shutdown.clone();
let stop_on_upgrade = self.config.upgrade.stop_on_upgrade;
let upgrade_exit_code = Arc::clone(&self.upgrade_exit_code);
tokio::spawn(async move {
let mut monitor = monitor;
let mut upgrader = AutoApplyUpgrader::new().with_stop_on_upgrade(stop_on_upgrade);
if let Ok(cache_dir) = upgrade_cache_dir() {
upgrader = upgrader.with_binary_cache(BinaryCache::new(cache_dir));
}
// Add randomized jitter before the first upgrade check to prevent all nodes
// from hitting the GitHub API simultaneously when started together.
{
let jitter_duration = jittered_interval(monitor.check_interval());
let first_check_time = chrono::Utc::now()
+ chrono::Duration::from_std(jitter_duration).unwrap_or_else(|e| {
warn!("chrono::Duration::from_std failed for jitter ({e}), defaulting to 1 minute");
chrono::Duration::minutes(1)
});
info!(
"First upgrade check scheduled for {} (jitter: {}s)",
first_check_time.to_rfc3339(),
jitter_duration.as_secs()
);
tokio::time::sleep(jitter_duration).await;
}
loop {
tokio::select! {
() = shutdown.cancelled() => {
break;
}
result = monitor.check_for_ready_upgrade() => {
match result {
Ok(Some(upgrade_info)) => {
info!(
current_version = %upgrader.current_version(),
new_version = %upgrade_info.version,
"Upgrade available"
);
// Send notification event
if let Err(e) = events_tx.send(NodeEvent::UpgradeAvailable {
version: upgrade_info.version.to_string(),
}) {
warn!("Failed to send UpgradeAvailable event: {e}");
}
// Auto-apply the upgrade
info!("Starting auto-apply upgrade...");
match upgrader.apply_upgrade(&upgrade_info).await {
Ok(UpgradeResult::Success { version, exit_code }) => {
info!("Upgrade to {} successful, initiating graceful shutdown", version);
upgrade_exit_code.store(exit_code, Ordering::SeqCst);
shutdown.cancel();
break;
}
Ok(UpgradeResult::RolledBack { reason }) => {
warn!("Error during upgrade process: {}", reason);
}
Ok(UpgradeResult::NoUpgrade) => {
info!("Already running latest version");
}
Err(e) => {
error!("Error during upgrade process: {}", e);
}
}
}
Ok(None) => {
if let Some(remaining) = monitor.time_until_upgrade() {
info!(
"Upgrade pending, rollout delay remaining: {}m {}s",
remaining.as_secs() / 60,
remaining.as_secs() % 60
);
} else {
info!("No upgrade available");
}
}
Err(e) => {
warn!("Error during upgrade process: {}", e);
}
}
// If an upgrade is pending, sleep for exactly the remaining
// rollout delay so the node restarts at its scheduled time
// rather than waiting for the next check interval tick.
let sleep_duration = monitor.time_until_upgrade().map_or_else(
|| {
// No pending upgrade - schedule next check with jitter
let jittered_duration =
jittered_interval(monitor.check_interval());
let next_check = chrono::Utc::now()
+ chrono::Duration::from_std(jittered_duration).unwrap_or_else(|e| {
warn!("chrono::Duration::from_std failed for interval ({e}), defaulting to 1 hour");
chrono::Duration::hours(1)
});
info!("Next upgrade check scheduled for {}", next_check.to_rfc3339());
jittered_duration
},
|remaining| {
// If the rollout delay has fully elapsed but the upgrade was
// not successfully applied, avoid a tight loop by backing off
// at least one check interval before retrying.
if remaining.is_zero() {
let backoff = jittered_interval(monitor.check_interval());
let next_check = chrono::Utc::now()
+ chrono::Duration::from_std(backoff).unwrap_or_else(|e| {
warn!("chrono::Duration::from_std failed for backoff ({e}), defaulting to 1 hour");
chrono::Duration::hours(1)
});
info!(
"Upgrade rollout delay elapsed but previous apply did not succeed; \
backing off, next check scheduled for {}",
next_check.to_rfc3339()
);
backoff
} else {
let wake_time = chrono::Utc::now()
+ chrono::Duration::from_std(remaining).unwrap_or_else(|e| {
warn!("chrono::Duration::from_std failed for rollout delay ({e}), defaulting to 1 minute");
chrono::Duration::minutes(1)
});
info!("Will apply upgrade at {}", wake_time.to_rfc3339());
remaining
}
},
);
// Use select! so shutdown can interrupt long sleeps
// (e.g. during a full rollout window delay).
tokio::select! {
() = shutdown.cancelled() => {
break;
}
() = tokio::time::sleep(sleep_duration) => {}
}
}
}
}
});
}
info!("Node running, waiting for shutdown signal");
// The main event loop, with signal handling. Everything above this starts
// something; this is where the node waits.
self.run_event_loop().await
}
/// Drain dependent work before shutting down native networking.
async fn cleanup(&mut self) {
self.shutdown.cancel();
// The shared token closes the WebRtcDirect accept loop and active
// browser sessions before storage and native P2P are torn down.
#[cfg(feature = "webrtc-direct")]
if let Some(task) = self.webrtc_direct_task.take() {
if let Err(error) = task.await {
warn!("WebRtcDirect task shutdown failed: {error}");
}
}
// Protocol routing stops first, loop and children both. The routing loop waits on
// `events.recv()` and has no cancellation branch of its own, and it holds an `Arc`
// on the P2P node that keeps the sender it is waiting on alive, so nothing else
// here will ever wake it. Left running it holds the chunk store and its
// single-process lock open after the node has returned. Aborting the accept loop
// alone is not enough either: the requests already in flight run in their own
// tasks, which is what the drain below is for.
if let Some(handle) = self.protocol_task.take() {
handle.abort();
// Awaited, not just asked to stop. `abort` schedules cancellation; it does not
// establish that the task is gone, and what matters here is that it has
// dropped its `Arc` on the protocol and with it the store's single-process
// lock before this function returns. The join resolves as cancelled.
let _ = handle.await;
}
// Cancelled first, so anything still queued behind the concurrency permits gives
// up rather than starting fresh storage work, then given a moment to finish what
// is genuinely in flight.
self.shutdown.cancel();
self.protocol_children.close();
if tokio::time::timeout(PROTOCOL_DRAIN_GRACE, self.protocol_children.wait())
.await
.is_err()
{
warn!(
"{} request handler(s) had not finished after {}s; continuing shutdown \
without them.",
self.protocol_children.len(),
PROTOCOL_DRAIN_GRACE.as_secs()
);
}
// Shutdown replication engine before P2P so background tasks don't
// use a dead P2P layer, and Arc<ChunkStore> references are released.
if let Some(ref mut engine) = self.replication_engine {
engine.shutdown().await;
}
// Shutdown P2P node
info!("Shutting down P2P node...");
if let Err(e) = self.p2p_node.shutdown().await {
warn!("Error during P2P node shutdown: {e}");
}
if let Err(e) = self.events_tx.send(NodeEvent::ShuttingDown) {
warn!("Failed to send ShuttingDown event: {e}");
}
info!("Node shutdown complete");
}
/// Run the main event loop, handling shutdown and signals.
#[cfg(unix)]
async fn run_event_loop(&self) -> Result<()> {
let mut sigterm = signal(SignalKind::terminate())?;
let mut sighup = signal(SignalKind::hangup())?;
loop {
tokio::select! {
() = self.shutdown.cancelled() => {
info!("Shutdown signal received");
break;
}
_ = tokio::signal::ctrl_c() => {
info!("Received SIGINT (Ctrl-C), initiating shutdown");
self.shutdown();
break;
}
_ = sigterm.recv() => {
info!("Received SIGTERM, initiating shutdown");
self.shutdown();
break;
}
_ = sighup.recv() => {
info!("Received SIGHUP (config reload not yet supported)");
}
}
}
Ok(())
}
/// Run the main event loop, handling shutdown signals (non-Unix version).
#[cfg(not(unix))]
async fn run_event_loop(&self) -> Result<()> {
loop {
tokio::select! {
() = self.shutdown.cancelled() => {
info!("Shutdown signal received");
break;
}
_ = tokio::signal::ctrl_c() => {
info!("Received Ctrl-C, initiating shutdown");
self.shutdown();
break;
}
}
}
Ok(())
}
/// Handle one inbound protocol message and send whatever it produced.
async fn answer_one_request(
protocol: &Arc<AntProtocol>,
p2p: &Arc<P2PNode>,
source: &saorsa_core::identity::PeerId,
data: &[u8],
data_type: &str,
response_topic: &str,
received_at: Instant,
) {
if data_type != "chunk" {
return;
}
let queue_wait = received_at.elapsed();
let handled = protocol
.try_handle_request_with_context(
data,
Some(ChunkRequestContext::new(
source.to_string(),
received_at,
queue_wait,
)),
)
.await;
let telemetry = handled.get_telemetry;
let traffic_key = handled.traffic_key;
match handled.response {
Ok(Some(response)) => {
let response_len = response.len();
let send_started = Instant::now();
// Handed over as the `Bytes` it already is: a chunk GET
// response is up to a whole chunk, and `to_vec` copied it.
let send_result = p2p
.send_message(source, response_topic, response, &[])
.await;
if let Some(telemetry) = telemetry {
telemetry.finish_send(send_started.elapsed(), send_result.is_ok());
}
// V2-834: attribute response bytes only once the send is
// confirmed; failed sends are itemised separately.
match (&send_result, traffic_key) {
(Ok(()), Some(key)) => storage_traffic::record_tx(key, response_len),
(Ok(()), None) => {
storage_traffic::record_tx(
storage_traffic::ChunkResponseKey::Other,
response_len,
);
}
(Err(_), _) => storage_traffic::record_send_failed(response_len),
}
if let Err(e) = send_result {
warn!("Failed to send {data_type} protocol response to {source}: {e}");
}
}
Ok(None) => {
if let Some(telemetry) = telemetry {
telemetry.finish_without_send("no_response");
}
}
Err(e) => {
if let Some(telemetry) = telemetry {
telemetry.finish_without_send("encode_error");
}
warn!("{data_type} protocol handler error: {e}");
}
}
}
/// Start the protocol message routing background task.
///
/// Subscribes to P2P events and routes incoming chunk protocol messages
/// to the `AntProtocol` handler, sending responses back to the sender.
fn start_protocol_routing(&mut self) {
let protocol = match self.ant_protocol {
Some(ref p) => Arc::clone(p),
None => return,
};
let mut events = self.p2p_node.subscribe_events();
let p2p = Arc::clone(&self.p2p_node);
let semaphore = Arc::new(Semaphore::new(64));
let children = self.protocol_children.clone();
let stopping = self.shutdown.clone();
self.protocol_task = Some(tokio::spawn(async move {
while let Ok(event) = events.recv().await {
if let P2PEvent::Message {
topic,
source: Some(source),
data,
..
} = event
{
let handler_info: Option<(&str, &str)> = if topic == CHUNK_PROTOCOL_ID {
Some(("chunk", CHUNK_PROTOCOL_ID))
} else {
None
};
if let Some((data_type, response_topic)) = handler_info {
debug!("Received {data_type} protocol message from {source}");
let received_at = Instant::now();
let protocol = Arc::clone(&protocol);
let p2p = Arc::clone(&p2p);
let sem = semaphore.clone();
let stopping = stopping.clone();
children.spawn(async move {
// A queued handler must not start work once shutdown has
// begun. With 64 permits and a busy node the queue behind them
// can be long, and every one of those would otherwise start
// fresh storage reads while the store beneath is being torn
// down.
let _permit = {
let acquired = tokio::select! {
biased;
() = stopping.cancelled() => return,
p = sem.acquire() => p,
};
match acquired {
Ok(permit) => permit,
Err(_) => return,
}
};
// Checked again: the wait for a permit may have been long.
if stopping.is_cancelled() {
return;
}
Self::answer_one_request(
&protocol,
&p2p,
&source,
&data,
data_type,
response_topic,
received_at,
)
.await;
});
}
}
}
}));
info!("Protocol message routing started");
}
/// Request the node to shut down.
pub fn shutdown(&self) {
self.shutdown.cancel();
}
}
/// Apply ±5% jitter to a base interval to prevent thundering-herd behaviour
/// when multiple nodes check for upgrades on the same schedule.
fn jittered_interval(base: std::time::Duration) -> std::time::Duration {
let secs = base.as_secs();
let variance = secs / 20; // 5%
if variance == 0 {
return base;
}
let jitter = rand::thread_rng().gen_range(0..=variance * 2);
std::time::Duration::from_secs(secs.saturating_sub(variance) + jitter)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use rand::Rng;
use tempfile::TempDir;
use crate::storage::legacy_artifacts::LEGACY_ENV_DIR;
/// The e2e port range, so a test bind never lands on a production or dev instance.
const TEST_PORT_RANGE: std::ops::Range<u16> = 20000..60000;
/// How many times a bind is retried before the failure is treated as real.
const BIND_ATTEMPTS: u32 = 5;
/// A well-formed address that receives nothing; no chain is contacted in these tests.
const TEST_REWARDS_ADDRESS: &str = "0x0000000000000000000000000000000000000001";
/// A node config that builds without touching a chain or a real network.
fn local_node_config(root: &std::path::Path, port: u16) -> NodeConfig {
NodeConfig {
root_dir: root.to_path_buf(),
port,
ipv4_only: true,
network_mode: NetworkMode::Development,
payment: crate::config::PaymentConfig {
rewards_address: Some(TEST_REWARDS_ADDRESS.to_string()),
..crate::config::PaymentConfig::default()
},
..NodeConfig::default()
}
}
/// A browser listener that cannot bind fails startup, and `run` still drains what it
/// had started before returning.
#[cfg(feature = "webrtc-direct")]
#[tokio::test]
async fn browser_startup_failure_drains_before_returning() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
std::fs::create_dir_all(&root).expect("mkdir");
let occupied = tokio::net::UdpSocket::bind("127.0.0.1:0")
.await
.expect("bind");
let mut config = local_node_config(&root, 0);
config.webrtc_direct.enabled = true;
config.webrtc_direct.bind = occupied.local_addr().expect("address");
let mut node = NodeBuilder::new(config).build().await.expect("build");
let cancelled = node.shutdown.clone();
let result = node.run().await;
assert!(result.is_err(), "occupied browser port must fail startup");
assert!(cancelled.is_cancelled());
assert!(node.protocol_children.is_empty());
// The test runtime remains alive: cleanup must not rely on process exit.
tokio::task::yield_now().await;
}
/// A node builds on a root with nothing left over from the old store.
#[tokio::test]
async fn a_node_builds_on_a_clean_root() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
std::fs::create_dir_all(&root).expect("mkdir");
let mut built = None;
let mut last_err = String::new();
for _ in 0..BIND_ATTEMPTS {
let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
match NodeBuilder::new(local_node_config(&root, port))
.build()
.await
{
Ok(node) => {
built = Some(node);
break;
}
Err(e) => {
last_err = e.to_string();
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
}
}
let Some(node) = built else {
panic!("could not build a node after {BIND_ATTEMPTS} attempts: {last_err}");
};
node.shutdown.cancel();
}
/// A node with chunks in a store this build cannot read STARTS, however it is
/// configured, and does not lose them.
///
/// This asserted the opposite until the release that shipped it was reconsidered twice.
/// First it refused to start, which serves nothing at all and cannot be recovered by
/// hand, because nothing can hold a node on an older build. Then it deleted whatever it
/// found, which is data loss for exactly the node that most needs the data: the upgrade
/// monitor picks the newest eligible release rather than the next one, so a node that was
/// offline through the previous release arrives here with everything it owns in that
/// directory and nothing in the file store.
///
/// Both configurations, because they are different code paths: a node with
/// `storage.enabled = false` never builds a store, and the old environment is on its disk
/// just the same.
#[tokio::test]
async fn a_node_with_an_unmigrated_store_starts_and_keeps_it() {
for storage_enabled in [true, false] {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
let env = root.join(LEGACY_ENV_DIR);
std::fs::create_dir_all(&env).expect("mkdir");
std::fs::write(env.join("data.mdb"), b"chunks that were never copied out")
.expect("seed");
let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
let mut config = local_node_config(&root, port);
config.storage.enabled = storage_enabled;
let node = NodeBuilder::new(config).build().await.unwrap_or_else(|e| {
panic!(
"a node with an unmigrated store must start (storage.enabled = \
{storage_enabled}): {e}"
)
});
settle();
assert!(
env.join("data.mdb").exists(),
"chunks that were never copied out were deleted (storage.enabled = \
{storage_enabled})"
);
node.shutdown.cancel();
}
}
/// A node with storage switched off deletes nothing, even a leftover marked finished.
///
/// It never builds a store, so nothing about this node establishes that those chunks were
/// copied anywhere: the mark is a claim made by a previous release about a file store
/// this process has not opened and will not open. It also has no use for the disk. So the
/// directory stays and stays recoverable.
#[tokio::test]
async fn a_node_with_storage_disabled_deletes_nothing() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
let env = root.join(LEGACY_ENV_DIR);
std::fs::create_dir_all(&env).expect("mkdir");
std::fs::write(
env.join("data.mdb"),
b"bytes retirement had already cleared",
)
.expect("seed");
std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
let mut config = local_node_config(&root, port);
config.storage.enabled = false;
let node = NodeBuilder::new(config).build().await.expect("must start");
settle();
assert!(
env.join("data.mdb").exists(),
"a node that never opened a store deleted one on the strength of a mark it \
could not check"
);
node.shutdown.cancel();
}
/// A store the migration finished with is removed, once the file store has opened.
#[tokio::test]
async fn a_finished_store_is_removed_once_the_replacement_opens() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
let env = root.join(LEGACY_ENV_DIR);
std::fs::create_dir_all(&env).expect("mkdir");
std::fs::write(
env.join("data.mdb"),
b"bytes retirement had already cleared",
)
.expect("seed");
std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
let node = NodeBuilder::new(local_node_config(&root, port))
.build()
.await
.expect("a node with a finished leftover must start");
assert!(wait_gone(&env));
node.shutdown.cancel();
}
/// Nothing is deleted until the store that replaced it has actually opened.
///
/// Retirement counted on every chunk the node kept being in the file store, which is only
/// true if the file store opens. An earlier version deleted first and let the constructor fail behind it,
/// on an unreadable layout or a directory it could not create, and a node that lost both
/// stores that way had nothing left to go back to.
#[tokio::test]
async fn a_finished_store_survives_a_file_store_that_will_not_open() {
let dir = TempDir::new().expect("temp dir");
let root = dir.path().join("node");
let env = root.join(LEGACY_ENV_DIR);
std::fs::create_dir_all(&env).expect("mkdir");
std::fs::write(
env.join("data.mdb"),
b"bytes retirement had already cleared",
)
.expect("seed");
std::fs::write(env.join("RETIRED"), b"retired").expect("mark");
// A file where the chunk directory has to be, so the store cannot create it.
std::fs::write(root.join("chunks"), b"not a directory").expect("block the store");
let port = rand::thread_rng().gen_range(TEST_PORT_RANGE);
let built = NodeBuilder::new(local_node_config(&root, port))
.build()
.await;
assert!(
built.is_err(),
"the file store was supposed to fail to open"
);
settle();
assert!(
env.join("data.mdb").exists(),
"the old store was deleted before the one replacing it could open"
);
}
/// The removal runs on its own thread.
fn settle() {
std::thread::sleep(std::time::Duration::from_millis(200));
}
/// The removal runs on its own thread, so give it a moment.
fn wait_gone(path: &std::path::Path) -> bool {
for _ in 0..200 {
if !path.exists() {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
false
}
use super::*;
use crate::config::NODES_SUBDIR;
#[test]
fn test_build_upgrade_monitor_staged_rollout_enabled() {
let config = NodeConfig {
upgrade: crate::config::UpgradeConfig {
staged_rollout_hours: 24,
..Default::default()
},
..Default::default()
};
let seed = b"node-seed";
let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
assert!(monitor.has_staged_rollout());
}
#[test]
fn test_build_upgrade_monitor_staged_rollout_disabled() {
let config = NodeConfig {
upgrade: crate::config::UpgradeConfig {
staged_rollout_hours: 0,
..Default::default()
},
..Default::default()
};
let seed = b"node-seed";
let monitor = NodeBuilder::build_upgrade_monitor(&config, seed);
assert!(!monitor.has_staged_rollout());
}
#[test]
fn test_build_core_config_sets_production_mode() {
let config = NodeConfig {
network_mode: NetworkMode::Production,
..Default::default()
};
let core = NodeBuilder::build_core_config(&config).expect("core config");
assert!(core.diversity_config.is_some());
}
#[test]
fn test_build_core_config_ipv4_only() {
let config = NodeConfig {
ipv4_only: true,
..Default::default()
};
let core = NodeBuilder::build_core_config(&config).expect("core config");
assert!(!core.ipv6, "ipv4_only should disable IPv6");
}
#[test]
fn test_build_core_config_dual_stack_by_default() {
let config = NodeConfig::default();
let core = NodeBuilder::build_core_config(&config).expect("core config");
assert!(core.ipv6, "dual-stack should be the default");
}
#[test]
fn test_build_core_config_sets_development_mode_permissive() {
let config = NodeConfig {
network_mode: NetworkMode::Development,
..Default::default()
};
let core = NodeBuilder::build_core_config(&config).expect("core config");
let diversity = core.diversity_config.expect("diversity");
assert_eq!(diversity.max_per_ip, Some(usize::MAX));
assert_eq!(diversity.max_per_subnet, Some(usize::MAX));
}
#[test]
fn test_scan_identity_dirs_empty_dir() {
let tmp = tempfile::tempdir().unwrap();
let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
assert!(dirs.is_empty(), "expected no identity dirs, got {dirs:?}");
}
#[test]
fn test_scan_identity_dirs_nonexistent_dir() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("nonexistent_identity_dir");
let dirs = NodeBuilder::scan_identity_dirs(&path).unwrap();
assert!(dirs.is_empty(), "expected no identity dirs, got {dirs:?}");
}
#[test]
fn test_scan_identity_dirs_finds_one() {
let tmp = tempfile::tempdir().unwrap();
let node_dir = tmp.path().join("abc123");
std::fs::create_dir_all(&node_dir).unwrap();
std::fs::write(node_dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
assert_eq!(dirs.len(), 1);
assert_eq!(dirs[0], node_dir);
}
#[test]
fn test_scan_identity_dirs_finds_multiple() {
let tmp = tempfile::tempdir().unwrap();
for name in &["node_a", "node_b"] {
let dir = tmp.path().join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(NODE_IDENTITY_FILENAME), "{}").unwrap();
}
// A directory without a key file should be ignored
std::fs::create_dir_all(tmp.path().join("no_key")).unwrap();
let dirs = NodeBuilder::scan_identity_dirs(tmp.path()).unwrap();
assert_eq!(dirs.len(), 2);
}
#[tokio::test]
async fn test_resolve_identity_first_run_creates_identity() {
let tmp = tempfile::tempdir().unwrap();
let mut config = NodeConfig {
root_dir: tmp.path().to_path_buf(),
..Default::default()
};
let identity = NodeBuilder::resolve_identity(&mut config).await.unwrap();
// Key file should exist
assert!(tmp.path().join(NODE_IDENTITY_FILENAME).exists());
// peer_id should be derivable from the identity
let peer_id = identity.peer_id().to_hex();
assert_eq!(peer_id.len(), 64); // 32 bytes hex-encoded
}
#[tokio::test]
async fn test_resolve_identity_loads_existing() {
let tmp = tempfile::tempdir().unwrap();
// Generate and save an identity
let original = NodeIdentity::generate().unwrap();
original
.save_to_file(&tmp.path().join(NODE_IDENTITY_FILENAME))
.await
.unwrap();
let mut config = NodeConfig {
root_dir: tmp.path().to_path_buf(),
..Default::default()
};
let loaded = NodeBuilder::resolve_identity(&mut config).await.unwrap();
assert_eq!(loaded.peer_id(), original.peer_id());
}
#[test]
fn test_peer_id_hex_length() {
let id = saorsa_core::identity::PeerId::from_bytes([0x42; 32]);
let hex = id.to_hex();
assert_eq!(hex.len(), 64); // 32 bytes = 64 hex chars
}
/// Simulates a node restart: first run creates identity in a scoped subdir
/// under `nodes/`, second run discovers and reloads it — `peer_id` must be
/// identical and the directory name is the full 64-char hex peer ID.
#[tokio::test]
async fn test_identity_persisted_across_restarts() {
let base_dir = tempfile::tempdir().unwrap();
let nodes_dir = base_dir.path().join(NODES_SUBDIR);
// First "boot": generate identity, save it in nodes/{peer_id}/
let identity1 = NodeIdentity::generate().unwrap();
let peer_id1 = identity1.peer_id().to_hex();
let peer_dir = nodes_dir.join(&peer_id1);
std::fs::create_dir_all(&peer_dir).unwrap();
identity1
.save_to_file(&peer_dir.join(NODE_IDENTITY_FILENAME))
.await
.unwrap();
// Verify directory name is the full 64-char hex peer ID
assert_eq!(peer_id1.len(), 64);
assert_eq!(peer_dir.file_name().unwrap().to_string_lossy(), peer_id1);
// Second "boot": scan should find and reload the same identity
let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
assert_eq!(identity_dirs.len(), 1);
let loaded = NodeIdentity::load_from_file(&identity_dirs[0].join(NODE_IDENTITY_FILENAME))
.await
.unwrap();
let peer_id2 = loaded.peer_id().to_hex();
assert_eq!(peer_id1, peer_id2, "peer_id must survive restart");
assert_eq!(
identity_dirs[0], peer_dir,
"root_dir must be the same directory"
);
}
/// When two identity subdirs exist under `nodes/`, the scan finds multiple
/// and the resolve path would error asking for `--root-dir`.
#[tokio::test]
async fn test_multiple_identities_errors() {
let base_dir = tempfile::tempdir().unwrap();
let nodes_dir = base_dir.path().join(NODES_SUBDIR);
// Create two identity subdirectories under nodes/
for name in &["aaaa", "bbbb"] {
let dir = nodes_dir.join(name);
std::fs::create_dir_all(&dir).unwrap();
let identity = NodeIdentity::generate().unwrap();
identity
.save_to_file(&dir.join(NODE_IDENTITY_FILENAME))
.await
.unwrap();
}
let identity_dirs = NodeBuilder::scan_identity_dirs(&nodes_dir).unwrap();
assert_eq!(identity_dirs.len(), 2, "should find both identity dirs");
}
/// With a non-default `root_dir` (explicit path), the identity is created on
/// first run and reloaded on subsequent runs from the same directory.
#[tokio::test]
async fn test_explicit_root_dir_persists_across_restarts() {
let tmp = tempfile::tempdir().unwrap();
// First boot — non-default root_dir triggers explicit path
let mut config1 = NodeConfig {
root_dir: tmp.path().to_path_buf(),
..Default::default()
};
let identity1 = NodeBuilder::resolve_identity(&mut config1).await.unwrap();
// Second boot — same dir
let mut config2 = NodeConfig {
root_dir: tmp.path().to_path_buf(),
..Default::default()
};
let identity2 = NodeBuilder::resolve_identity(&mut config2).await.unwrap();
assert_eq!(
identity1.peer_id(),
identity2.peer_id(),
"explicit --root-dir must yield stable identity"
);
}
/// The prefix is what keeps this node in its peers' routing tables, and the version is
/// this build's, with nothing after it.
#[test]
fn the_user_agent_is_this_builds_version_under_the_node_prefix() {
assert_eq!(
super::user_agent(),
format!("node/{}", env!("CARGO_PKG_VERSION"))
);
assert!(super::user_agent().starts_with("node/"));
}
}