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
//! Dht node.
use std::{
collections::HashMap,
net::{Ipv4Addr, SocketAddrV4, ToSocketAddrs},
thread,
time::Duration,
};
use flume::{Receiver, Sender, TryRecvError};
use tracing::info;
use crate::{
common::{
hash_immutable, AnnouncePeerRequestArguments, FindNodeRequestArguments,
GetPeersRequestArguments, GetValueRequestArguments, Id, MutableItem,
PutImmutableRequestArguments, PutMutableRequestArguments, PutRequestSpecific,
},
rpc::{
to_socket_address, ConcurrencyError, GetRequestSpecific, Info, PutError, PutQueryError,
Response, Rpc,
},
Node, ServerSettings,
};
use crate::rpc::config::Config;
#[derive(Debug, Clone)]
/// Mainline Dht node.
pub struct Dht(pub(crate) Sender<ActorMessage>);
#[derive(Debug, Default, Clone)]
/// A builder for the [Dht] node.
pub struct DhtBuilder(Config);
impl DhtBuilder {
/// Set this node's server_mode.
pub fn server_mode(&mut self) -> &mut Self {
self.0.server_mode = true;
self
}
/// Set a custom settings for the node to use at server mode.
///
/// Defaults to [ServerSettings::default]
pub fn server_settings(&mut self, server_settings: ServerSettings) -> &mut Self {
self.0.server_settings = server_settings;
self
}
/// Set bootstrapping nodes.
pub fn bootstrap<T: ToSocketAddrs>(&mut self, bootstrap: &[T]) -> &mut Self {
self.0.bootstrap = Some(to_socket_address(bootstrap));
self
}
/// Add more bootstrap nodes to default bootstrapping nodes.
///
/// Useful when you want to augment the default bootstrapping nodes with
/// dynamic list of nodes you have seen in previous sessions.
pub fn extra_bootstrap<T: ToSocketAddrs>(&mut self, extra_bootstrap: &[T]) -> &mut Self {
let mut bootstrap = self.0.bootstrap.clone().unwrap_or_default();
for address in to_socket_address(extra_bootstrap) {
bootstrap.push(address);
}
self.0.bootstrap = Some(bootstrap);
self
}
/// Remove the existing bootstrapping nodes, usually to create the first node in a new network.
pub fn no_bootstrap(&mut self) -> &mut Self {
self.0.bootstrap = Some(vec![]);
self
}
/// Set an explicit port to listen on.
pub fn port(&mut self, port: u16) -> &mut Self {
self.0.port = Some(port);
self
}
/// A known public IPv4 address for this node to generate
/// a secure node Id from according to [BEP_0042](https://www.bittorrent.org/beps/bep_0042.html)
///
/// Defaults to depending on suggestions from responding nodes.
pub fn public_ip(&mut self, public_ip: Ipv4Addr) -> &mut Self {
self.0.public_ip = Some(public_ip);
self
}
/// UDP socket request timeout duration.
///
/// The longer this duration is, the longer queries take until they are deemeed "done".
/// The shortet this duration is, the more responses from busy nodes we miss out on,
/// which affects the accuracy of queries trying to find closest nodes to a target.
///
/// Defaults to [crate::DEFAULT_REQUEST_TIMEOUT]
pub fn request_timeout(&mut self, request_timeout: Duration) -> &mut Self {
self.0.request_timeout = request_timeout;
self
}
/// Set the address to bind to.
///
/// Defaults to 0.0.0.0 (all interfaces).
pub fn bind_address(&mut self, bind_address: Ipv4Addr) -> &mut Self {
self.0.bind_address = Some(bind_address);
self
}
/// Create a Dht node.
pub fn build(&self) -> Result<Dht, std::io::Error> {
Dht::new(self.0.clone())
}
}
impl Dht {
/// Create a new Dht node.
///
/// Could return an error if it failed to bind to the specified
/// port or other io errors while binding the udp socket.
pub fn new(config: Config) -> Result<Self, std::io::Error> {
let (sender, receiver) = flume::unbounded();
thread::Builder::new()
.name("Mainline Dht actor thread".to_string())
.spawn(move || run(config, receiver))?;
let (tx, rx) = flume::bounded(1);
sender
.send(ActorMessage::Check(tx))
.expect("actor thread unexpectedly shutdown");
rx.recv().expect("actor thread unexpectedly shutdown")?;
Ok(Dht(sender))
}
/// Returns a builder to edit settings before creating a Dht node.
pub fn builder() -> DhtBuilder {
DhtBuilder::default()
}
/// Create a new DHT client with default bootstrap nodes.
pub fn client() -> Result<Self, std::io::Error> {
Dht::builder().build()
}
/// Create a new DHT node that is running in [Server mode][DhtBuilder::server_mode] as
/// soon as possible.
///
/// You shouldn't use this option unless you are sure your
/// DHT node is publicly accessible (not firewalled) _AND_ will be long running,
/// and/or you are running your own local network for testing.
///
/// If you are not sure, use [Self::client] and it will switch
/// to server mode when/if these two conditions are met.
pub fn server() -> Result<Self, std::io::Error> {
Dht::builder().server_mode().build()
}
// === Getters ===
/// Information and statistics about this [Dht] node.
pub fn info(&self) -> Info {
let (tx, rx) = flume::bounded::<Info>(1);
self.send(ActorMessage::Info(tx));
rx.recv().expect("actor thread unexpectedly shutdown")
}
/// Turn this node's routing table to a list of bootstrapping nodes.
pub fn to_bootstrap(&self) -> Vec<String> {
let (tx, rx) = flume::bounded::<Vec<String>>(1);
self.send(ActorMessage::ToBootstrap(tx));
rx.recv().expect("actor thread unexpectedly shutdown")
}
// === Public Methods ===
/// Block until the bootstrapping query is done.
///
/// Returns true if the bootstrapping was successful.
pub fn bootstrapped(&self) -> bool {
let info = self.info();
let nodes = self.find_node(*info.id());
!nodes.is_empty()
}
// === Find nodes ===
/// Returns the closest 20 [secure](Node::is_secure) nodes to a target [Id].
///
/// Mostly useful to crawl the DHT.
///
/// The returned nodes are claims by other nodes, they may be lies, or may have churned
/// since they were last seen, but haven't been pinged yet.
///
/// You might need to ping them to confirm they exist, and responsive, or if you want to
/// learn more about them like the client they are using, or if they support a given BEP.
///
/// If you are trying to find the closest nodes to a target with intent to [Self::put],
/// a request directly to these nodes (using `extra_nodes` parameter), then you should
/// use [Self::get_closest_nodes] instead.
pub fn find_node(&self, target: Id) -> Box<[Node]> {
let (tx, rx) = flume::bounded::<Box<[Node]>>(1);
self.send(ActorMessage::Get(
GetRequestSpecific::FindNode(FindNodeRequestArguments { target }),
ResponseSender::ClosestNodes(tx),
));
rx.recv()
.expect("Query was dropped before sending a response, please open an issue.")
}
// === Peers ===
/// Get peers for a given infohash.
///
/// Note: each node of the network will only return a _random_ subset (usually 20)
/// of the total peers it has for a given infohash, so if you are getting responses
/// from 20 nodes, you can expect up to 400 peers in total, but if there are more
/// announced peers on that infohash, you are likely to miss some, the logic here
/// for Bittorrent is that any peer will introduce you to more peers through "peer exchange"
/// so if you are implementing something different from Bittorrent, you might want
/// to implement your own logic for gossipping more peers after you discover the first ones.
pub fn get_peers(&self, info_hash: Id) -> GetIterator<Vec<SocketAddrV4>> {
let (tx, rx) = flume::unbounded::<Vec<SocketAddrV4>>();
self.send(ActorMessage::Get(
GetRequestSpecific::GetPeers(GetPeersRequestArguments { info_hash }),
ResponseSender::Peers(tx),
));
GetIterator(rx.into_iter())
}
/// Announce a peer for a given infohash.
///
/// The peer will be announced on this process IP.
/// If explicit port is passed, it will be used, otherwise the port will be implicitly
/// assumed by remote nodes to be the same ase port they received the request from.
pub fn announce_peer(&self, info_hash: Id, port: Option<u16>) -> Result<Id, PutQueryError> {
let (port, implied_port) = match port {
Some(port) => (port, None),
None => (0, Some(true)),
};
self.put(
PutRequestSpecific::AnnouncePeer(AnnouncePeerRequestArguments {
info_hash,
port,
implied_port,
}),
None,
)
.map_err(|error| match error {
PutError::Query(error) => error,
PutError::Concurrency(_) => {
unreachable!("should not receive a concurrency error from announce peer query")
}
})
}
// === Immutable data ===
/// Get an Immutable data by its sha1 hash.
pub fn get_immutable(&self, target: Id) -> Option<Box<[u8]>> {
let (tx, rx) = flume::unbounded::<Box<[u8]>>();
self.send(ActorMessage::Get(
GetRequestSpecific::GetValue(GetValueRequestArguments {
target,
seq: None,
salt: None,
}),
ResponseSender::Immutable(tx),
));
rx.recv().map(Some).unwrap_or(None)
}
/// Put an immutable data to the DHT.
pub fn put_immutable(&self, value: &[u8]) -> Result<Id, PutQueryError> {
let target: Id = hash_immutable(value).into();
self.put(
PutRequestSpecific::PutImmutable(PutImmutableRequestArguments {
target,
v: value.into(),
}),
None,
)
.map_err(|error| match error {
PutError::Query(error) => error,
PutError::Concurrency(_) => {
unreachable!("should not receive a concurrency error from put immutable query")
}
})
}
// === Mutable data ===
/// Get a mutable data by its `public_key` and optional `salt`.
///
/// You can ask for items `more_recent_than` than a certain `seq`,
/// usually one that you already have seen before, similar to `If-Modified-Since` header in HTTP.
///
/// # Order
///
/// The order of [MutableItem]s returned by this iterator is not guaranteed to
/// reflect their `seq` value. You should not assume that the later items are
/// more recent than earlier ones.
///
/// Consider using [Self::get_mutable_most_recent] if that is what you need.
pub fn get_mutable(
&self,
public_key: &[u8; 32],
salt: Option<&[u8]>,
more_recent_than: Option<i64>,
) -> GetIterator<MutableItem> {
let salt = salt.map(|s| s.into());
let target = MutableItem::target_from_key(public_key, salt.as_deref());
let (tx, rx) = flume::unbounded::<MutableItem>();
self.send(ActorMessage::Get(
GetRequestSpecific::GetValue(GetValueRequestArguments {
target,
seq: more_recent_than,
salt,
}),
ResponseSender::Mutable(tx),
));
GetIterator(rx.into_iter())
}
/// Get the most recent [MutableItem] from the network.
pub fn get_mutable_most_recent(
&self,
public_key: &[u8; 32],
salt: Option<&[u8]>,
) -> Option<MutableItem> {
let mut most_recent: Option<MutableItem> = None;
let iter = self.get_mutable(public_key, salt, None);
for item in iter {
if let Some(mr) = &most_recent {
if item.seq() == mr.seq && item.value() > &mr.value {
most_recent = Some(item)
}
} else {
most_recent = Some(item);
}
}
most_recent
}
/// Put a mutable data to the DHT.
///
/// # Lost Update Problem
///
/// As mainline DHT is a distributed system, it is vulnerable to [Write–write conflict](https://en.wikipedia.org/wiki/Write-write_conflict).
///
/// ## Read first
///
/// To mitigate the risk of lost updates, you should call the [Self::get_mutable_most_recent] method
/// then start authoring the new [MutableItem] based on the most recent as in the following example:
///
///```rust
/// use mainline::{Dht, MutableItem, SigningKey, Testnet};
/// use std::net::Ipv4Addr;
///
/// let testnet = Testnet::builder(3).build().unwrap();
/// let dht = Dht::builder()
/// .bootstrap(&testnet.bootstrap)
/// .bind_address(Ipv4Addr::LOCALHOST)
/// .build()
/// .unwrap();
///
/// let signing_key = SigningKey::from_bytes(&[0; 32]);
/// let key = signing_key.verifying_key().to_bytes();
/// let salt = Some(b"salt".as_ref());
///
/// let (item, cas) = if let Some(most_recent) = dht .get_mutable_most_recent(&key, salt) {
/// // 1. Optionally Create a new value to take the most recent's value in consideration.
/// let mut new_value = most_recent.value().to_vec();
/// new_value.extend_from_slice(b" more data");
///
/// // 2. Increment the sequence number to be higher than the most recent's.
/// let most_recent_seq = most_recent.seq();
/// let new_seq = most_recent_seq + 1;
///
/// (
/// MutableItem::new(signing_key, &new_value, new_seq, salt),
/// // 3. Use the most recent [MutableItem::seq] as a `CAS`.
/// Some(most_recent_seq)
/// )
/// } else {
/// (MutableItem::new(signing_key, b"first value", 1, salt), None)
/// };
///
/// dht.put_mutable(item, cas).unwrap();
/// ```
///
/// ## Errors
///
/// In addition to the [PutQueryError] common with all PUT queries, PUT mutable item
/// query has other [Concurrency errors][ConcurrencyError], that try to detect write conflict
/// risks or obvious conflicts.
///
/// If you are lucky to get one of these errors (which is not guaranteed), then you should
/// read the most recent item again, and repeat the steps in the previous example.
pub fn put_mutable(&self, item: MutableItem, cas: Option<i64>) -> Result<Id, PutMutableError> {
let request = PutRequestSpecific::PutMutable(PutMutableRequestArguments::from(item, cas));
self.put(request, None).map_err(|error| match error {
PutError::Query(err) => PutMutableError::Query(err),
PutError::Concurrency(err) => PutMutableError::Concurrency(err),
})
}
// === Raw ===
/// Get closet nodes to a specific target, that support [BEP_0044](https://www.bittorrent.org/beps/bep_0044.html).
///
/// Useful to [Self::put] a request to nodes further from the 20 closest nodes to the
/// [PutRequestSpecific::target]. Which itself is useful to circumvent [extreme vertical sybil attacks](https://github.com/pubky/mainline/blob/main/docs/censorship-resistance.md#extreme-vertical-sybil-attacks).
pub fn get_closest_nodes(&self, target: Id) -> Box<[Node]> {
let (tx, rx) = flume::unbounded::<Box<[Node]>>();
self.send(ActorMessage::Get(
GetRequestSpecific::GetValue(GetValueRequestArguments {
target,
salt: None,
seq: None,
}),
ResponseSender::ClosestNodes(tx),
));
rx.recv()
.expect("Query was dropped before sending a response, please open an issue.")
}
/// Send a PUT request to the closest nodes, and optionally some extra nodes.
///
/// This is useful to put data to regions of the DHT other than the closest nodes
/// to this request's [target][PutRequestSpecific::target].
///
/// You can find nodes close to other regions of the network by calling
/// [Self::get_closest_nodes] with the target that you want to find the closest nodes to.
///
/// Note: extra nodes need to have [Node::valid_token].
pub fn put(
&self,
request: PutRequestSpecific,
extra_nodes: Option<Box<[Node]>>,
) -> Result<Id, PutError> {
self.put_inner(request, extra_nodes)
.recv()
.expect("Query was dropped before sending a response, please open an issue.")
}
// === Private Methods ===
pub(crate) fn put_inner(
&self,
request: PutRequestSpecific,
extra_nodes: Option<Box<[Node]>>,
) -> flume::Receiver<Result<Id, PutError>> {
let (tx, rx) = flume::bounded::<Result<Id, PutError>>(1);
self.send(ActorMessage::Put(request, tx, extra_nodes));
rx
}
pub(crate) fn send(&self, message: ActorMessage) {
self.0
.send(message)
.expect("actor thrread unexpectedly shutdown");
}
}
pub struct GetIterator<T>(flume::IntoIter<T>);
impl<T> Iterator for GetIterator<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
fn run(config: Config, receiver: Receiver<ActorMessage>) {
match Rpc::new(config) {
Ok(mut rpc) => {
let address = rpc.local_addr();
info!(?address, "Mainline DHT listening");
let mut put_senders = HashMap::new();
let mut get_senders = HashMap::new();
loop {
match receiver.try_recv() {
Ok(actor_message) => match actor_message {
ActorMessage::Check(sender) => {
let _ = sender.send(Ok(()));
}
ActorMessage::Info(sender) => {
let _ = sender.send(rpc.info());
}
ActorMessage::Put(request, sender, extra_nodes) => {
let target = *request.target();
match rpc.put(request, extra_nodes) {
Ok(()) => {
let senders = put_senders.entry(target).or_insert(vec![]);
senders.push(sender);
}
Err(error) => {
let _ = sender.send(Err(error));
}
};
}
ActorMessage::Get(request, sender) => {
let target = *request.target();
if let Some(responses) = rpc.get(request, None) {
for response in responses {
send(&sender, response);
}
};
let senders = get_senders.entry(target).or_insert(vec![]);
senders.push(sender);
}
ActorMessage::ToBootstrap(sender) => {
let _ = sender.send(rpc.routing_table().to_bootstrap());
}
ActorMessage::SeedRouting(nodes, sender) => {
for node in nodes {
rpc.routing_table_mut().add(node);
}
let _ = sender.send(());
}
},
Err(TryRecvError::Disconnected) => {
// Node was dropped, kill this thread.
tracing::debug!("mainline::Dht's actor thread was shutdown after Drop.");
break;
}
Err(TryRecvError::Empty) => {
// No op
}
}
let report = rpc.tick();
// Response for an ongoing GET query
if let Some((target, response)) = report.new_query_response {
if let Some(senders) = get_senders.get(&target) {
for sender in senders {
send(sender, response.clone());
}
}
}
// Cleanup done GET queries
for (id, closest_nodes) in report.done_get_queries {
if let Some(senders) = get_senders.remove(&id) {
for sender in senders {
// return closest_nodes to whoever was asking
if let ResponseSender::ClosestNodes(sender) = sender {
let _ = sender.send(closest_nodes.clone());
}
}
}
}
// Cleanup done PUT query and send a resulting error if any.
for (id, error) in report.done_put_queries {
if let Some(senders) = put_senders.remove(&id) {
let result = if let Some(error) = error {
Err(error)
} else {
Ok(id)
};
for sender in senders {
let _ = sender.send(result.clone());
}
}
}
}
}
Err(err) => {
if let Ok(ActorMessage::Check(sender)) = receiver.try_recv() {
let _ = sender.send(Err(err));
}
}
};
}
fn send(sender: &ResponseSender, response: Response) {
match (sender, response) {
(ResponseSender::Peers(s), Response::Peers(r)) => {
let _ = s.send(r);
}
(ResponseSender::Mutable(s), Response::Mutable(r)) => {
let _ = s.send(r);
}
(ResponseSender::Immutable(s), Response::Immutable(r)) => {
let _ = s.send(r);
}
_ => {}
}
}
#[derive(Debug)]
pub(crate) enum ActorMessage {
Info(Sender<Info>),
Put(
PutRequestSpecific,
Sender<Result<Id, PutError>>,
Option<Box<[Node]>>,
),
Get(GetRequestSpecific, ResponseSender),
Check(Sender<Result<(), std::io::Error>>),
ToBootstrap(Sender<Vec<String>>),
SeedRouting(Vec<Node>, Sender<()>),
}
#[derive(Debug, Clone)]
pub enum ResponseSender {
ClosestNodes(Sender<Box<[Node]>>),
Peers(Sender<Vec<SocketAddrV4>>),
Mutable(Sender<MutableItem>),
Immutable(Sender<Box<[u8]>>),
}
/// Builder for creating a [Testnet] with custom configuration.
///
/// # Defaults
///
/// - `bind_address`: `127.0.0.1` (localhost)
/// - `seeded`: `true` - nodes start with fully populated routing tables
///
/// # Example
///
/// ```ignore
/// use std::net::Ipv4Addr;
/// use mainline::Testnet;
///
/// // Use localhost (default)
/// let testnet = Testnet::builder(3).build().unwrap();
///
/// // Use all interfaces (0.0.0.0)
/// let testnet = Testnet::builder(3)
/// .bind_address(Ipv4Addr::UNSPECIFIED)
/// .build()
/// .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct TestnetBuilder {
count: usize,
bind_address: Ipv4Addr,
seeded: bool,
}
impl TestnetBuilder {
/// Create a new builder with the specified number of nodes.
///
/// # Defaults
///
/// - `bind_address`: `127.0.0.1` (localhost)
/// - `seeded`: `true`
pub fn new(count: usize) -> Self {
Self {
count,
bind_address: Ipv4Addr::LOCALHOST,
seeded: true,
}
}
/// Set the address to bind all nodes to.
///
/// Defaults to `127.0.0.1` (localhost).
/// Use `Ipv4Addr::UNSPECIFIED` (`0.0.0.0`) to bind to all interfaces.
pub fn bind_address(&mut self, bind_address: Ipv4Addr) -> &mut Self {
self.bind_address = bind_address;
self
}
/// Whether to pre-seed routing tables with all nodes.
///
/// Defaults to `true`.
///
/// When `true`, all nodes start with fully populated routing tables.
/// When `false`, nodes bootstrap from each other which is faster at startup
/// but may not have immediate full connectivity.
pub fn seeded(&mut self, seeded: bool) -> &mut Self {
self.seeded = seeded;
self
}
/// Build the testnet.
///
/// Nodes will be bound to the configured `bind_address` (default: `127.0.0.1`).
///
/// This will block until all nodes are created (and seeded if `seeded` is true).
pub fn build(&self) -> Result<Testnet, std::io::Error> {
if self.seeded {
Testnet::build_seeded(self.count, self.bind_address)
} else {
Testnet::build_unseeded(self.count, self.bind_address)
}
}
}
/// Create a testnet of Dht nodes to run tests against instead of the real mainline network.
///
/// # Bind Address
///
/// The convenience methods ([`Self::new`], [`Self::new_unseeded`], etc.) bind to `0.0.0.0`
/// for backwards compatibility. Use [`Self::builder`] to bind to a different address.
// TODO(breaking): In the next major version, change the default bind address from
// `0.0.0.0` to `127.0.0.1` for better cross-platform compatibility (especially macOS).
#[derive(Debug)]
pub struct Testnet {
/// bootstrapping nodes for this testnet.
pub bootstrap: Vec<String>,
/// all nodes in this testnet
pub nodes: Vec<Dht>,
}
// TODO(breaking): In the next major version, change `new()` and related methods to bind
// to `127.0.0.1` instead of `0.0.0.0` for better macOS compatibility. The builder already
// defaults to `127.0.0.1`.
impl Testnet {
/// Returns a builder to configure and create a [Testnet].
///
/// The builder defaults to binding to `127.0.0.1` (localhost).
///
/// # Example
///
/// ```ignore
/// let testnet = Testnet::builder(3).build().unwrap();
/// ```
pub fn builder(count: usize) -> TestnetBuilder {
TestnetBuilder::new(count)
}
/// Create a new testnet with a certain size.
///
/// Note: this network will be shutdown as soon as this struct
/// gets dropped, if you want the network to be `'static`, then
/// you should call [Self::leak].
///
/// This will block until all nodes are seeded with local peers.
/// If you are using an async runtime, consider using [Self::new_async].
///
/// # Bind Address
///
/// Nodes are bound to `0.0.0.0` (all interfaces). Use [`Self::builder`] to bind to
/// a different address.
pub fn new(count: usize) -> Result<Testnet, std::io::Error> {
Testnet::build_seeded(count, Ipv4Addr::UNSPECIFIED)
}
/// Create a new testnet without pre-seeding routing tables.
///
/// This is faster at startup, but nodes will not start with fully populated routing tables.
/// Use this when your tests do not require immediate full connectivity.
///
/// # Bind Address
///
/// Nodes are bound to `0.0.0.0` (all interfaces). Use [`Self::builder`] with `.seeded(false)`
/// to bind to a different address.
pub fn new_unseeded(count: usize) -> Result<Testnet, std::io::Error> {
Testnet::build_unseeded(count, Ipv4Addr::UNSPECIFIED)
}
#[cfg(feature = "async")]
/// Similar to [Self::new], but available for async contexts.
///
/// # Bind Address
///
/// Nodes are bound to `0.0.0.0` (all interfaces). Use [`Self::builder`] to bind to
/// a different address.
pub async fn new_async(count: usize) -> Result<Testnet, std::io::Error> {
Testnet::build_seeded(count, Ipv4Addr::UNSPECIFIED)
}
#[cfg(feature = "async")]
/// Similar to [Self::new_unseeded], but available for async contexts.
///
/// # Bind Address
///
/// Nodes are bound to `0.0.0.0` (all interfaces). Use [`Self::builder`] with `.seeded(false)`
/// to bind to a different address.
pub async fn new_unseeded_async(count: usize) -> Result<Testnet, std::io::Error> {
Testnet::build_unseeded(count, Ipv4Addr::UNSPECIFIED)
}
fn build_seeded(count: usize, bind_address: Ipv4Addr) -> Result<Testnet, std::io::Error> {
let mut nodes = Vec::with_capacity(count);
for _ in 0..count {
let node = Dht::builder()
.server_mode()
.no_bootstrap()
.bind_address(bind_address)
.build()?;
nodes.push(node);
}
let infos: Vec<_> = nodes.iter().map(|node| node.info()).collect();
let bootstrap = infos
.iter()
.map(|info| info.local_addr().to_string())
.collect::<Vec<_>>();
let seeded_nodes: Vec<_> = infos
.iter()
.map(|info| Node::new(*info.id(), info.local_addr()))
.collect();
for (node, info) in nodes.iter().zip(infos.iter()) {
let peers = seeded_nodes
.iter()
.filter(|peer| peer.id() != info.id())
.cloned()
.collect::<Vec<_>>();
let (tx, rx) = flume::bounded(1);
node.send(ActorMessage::SeedRouting(peers, tx));
let _ = rx.recv();
}
Ok(Self { bootstrap, nodes })
}
fn build_unseeded(count: usize, bind_address: Ipv4Addr) -> Result<Testnet, std::io::Error> {
let mut nodes = Vec::with_capacity(count);
let mut bootstrap = Vec::new();
for i in 0..count {
if i == 0 {
let node = Dht::builder()
.server_mode()
.no_bootstrap()
.bind_address(bind_address)
.build()?;
let info = node.info();
bootstrap.push(info.local_addr().to_string());
nodes.push(node);
} else {
let node = Dht::builder()
.server_mode()
.bootstrap(&bootstrap)
.bind_address(bind_address)
.build()?;
nodes.push(node);
}
}
Ok(Self { bootstrap, nodes })
}
/// By default as soon as this testnet gets dropped,
/// all the nodes get dropped and the entire network is shutdown.
///
/// This method uses [Box::leak] to keep nodes running, which is
/// useful if you need to keep running the testnet in the process
/// even if this struct gets dropped.
pub fn leak(&self) {
for node in self.nodes.clone() {
Box::leak(Box::new(node));
}
}
}
#[derive(thiserror::Error, Debug)]
/// Put MutableItem errors.
pub enum PutMutableError {
#[error(transparent)]
/// Common PutQuery errors
Query(#[from] PutQueryError),
#[error(transparent)]
/// PutQuery for [crate::MutableItem] errors
Concurrency(#[from] ConcurrencyError),
}
#[cfg(test)]
mod test {
use std::net::Ipv4Addr;
use std::str::FromStr;
use ed25519_dalek::SigningKey;
use crate::rpc::ConcurrencyError;
use super::*;
#[test]
fn bind_twice() {
let a = Dht::client().unwrap();
let result = Dht::builder()
.port(a.info().local_addr().port())
.server_mode()
.build();
assert!(result.is_err());
}
#[test]
fn announce_get_peer() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let b = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let info_hash = Id::random();
a.announce_peer(info_hash, Some(45555))
.expect("failed to announce");
let peers = b.get_peers(info_hash).next().expect("No peers");
assert_eq!(peers.first().unwrap().port(), 45555);
}
#[test]
fn put_get_immutable() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let b = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let value = b"Hello World!";
let expected_target = Id::from_str("e5f96f6f38320f0f33959cb4d3d656452117aadb").unwrap();
let target = a.put_immutable(value).unwrap();
assert_eq!(target, expected_target);
let response = b.get_immutable(target).unwrap();
assert_eq!(response, value.to_vec().into_boxed_slice());
}
#[test]
fn find_node_no_values() {
let client = Dht::builder().no_bootstrap().build().unwrap();
client.find_node(Id::random());
}
#[test]
fn put_get_immutable_no_values() {
let client = Dht::builder().no_bootstrap().build().unwrap();
assert_eq!(client.get_immutable(Id::random()), None);
}
#[test]
fn put_get_mutable() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let b = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
let seq = 1000;
let value = b"Hello World!";
let item = MutableItem::new(signer.clone(), value, seq, None);
a.put_mutable(item.clone(), None).unwrap();
let response = b
.get_mutable(signer.verifying_key().as_bytes(), None, None)
.next()
.expect("No mutable values");
assert_eq!(&response, &item);
}
#[test]
fn put_get_mutable_no_more_recent_value() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let b = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
let seq = 1000;
let value = b"Hello World!";
let item = MutableItem::new(signer.clone(), value, seq, None);
a.put_mutable(item.clone(), None).unwrap();
let response = b
.get_mutable(signer.verifying_key().as_bytes(), None, Some(seq))
.next();
assert!(&response.is_none());
}
#[test]
fn repeated_put_query() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let id = a.put_immutable(&[1, 2, 3]).unwrap();
assert_eq!(a.put_immutable(&[1, 2, 3]).unwrap(), id);
}
#[test]
fn concurrent_get_mutable() {
let testnet = Testnet::builder(10).build().unwrap();
let a = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let b = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
let key = signer.verifying_key().to_bytes();
let seq = 1000;
let value = b"Hello World!";
let item = MutableItem::new(signer.clone(), value, seq, None);
a.put_mutable(item.clone(), None).unwrap();
let _response_first = b
.get_mutable(&key, None, None)
.next()
.expect("No mutable values");
let response_second = b
.get_mutable(&key, None, None)
.next()
.expect("No mutable values");
assert_eq!(&response_second, &item);
}
#[test]
fn concurrent_put_mutable_same() {
let testnet = Testnet::builder(10).build().unwrap();
let client = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
let seq = 1000;
let value = b"Hello World!";
let item = MutableItem::new(signer.clone(), value, seq, None);
let mut handles = vec![];
for _ in 0..2 {
let client = client.clone();
let item = item.clone();
let handle = std::thread::spawn(move || client.put_mutable(item, None).unwrap());
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
#[test]
fn concurrent_put_mutable_different() {
let testnet = Testnet::builder(10).build().unwrap();
let client = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let mut handles = vec![];
for i in 0..2 {
let client = client.clone();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
let seq = 1000;
let mut value = b"Hello World!".to_vec();
value.push(i);
let item = MutableItem::new(signer.clone(), &value, seq, None);
let handle = std::thread::spawn(move || {
let result = client.put_mutable(item, None);
if i == 0 {
assert!(result.is_ok())
} else {
assert!(matches!(
result,
Err(PutMutableError::Concurrency(ConcurrencyError::ConflictRisk))
))
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
#[test]
fn concurrent_put_mutable_different_with_cas() {
let testnet = Testnet::builder(10).build().unwrap();
let client = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
// First
{
let item = MutableItem::new(signer.clone(), &[], 1000, None);
let (sender, _) = flume::bounded::<Result<Id, PutError>>(1);
let request =
PutRequestSpecific::PutMutable(PutMutableRequestArguments::from(item, None));
client
.0
.send(ActorMessage::Put(request, sender, None))
.unwrap();
}
std::thread::sleep(Duration::from_millis(100));
// Second
{
let item = MutableItem::new(signer, &[], 1001, None);
let most_recent = client.get_mutable_most_recent(item.key(), None);
if let Some(cas) = most_recent.map(|item| item.seq()) {
client.put_mutable(item, Some(cas)).unwrap();
} else {
client.put_mutable(item, None).unwrap();
}
}
}
#[test]
fn conflict_302_seq_less_than_current() {
let testnet = Testnet::builder(10).build().unwrap();
let client = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
client
.put_mutable(MutableItem::new(signer.clone(), &[], 1001, None), None)
.unwrap();
assert!(matches!(
client.put_mutable(MutableItem::new(signer, &[], 1000, None), None),
Err(PutMutableError::Concurrency(
ConcurrencyError::NotMostRecent
))
));
}
#[test]
fn conflict_301_cas() {
let testnet = Testnet::builder(10).build().unwrap();
let client = Dht::builder()
.bootstrap(&testnet.bootstrap)
.bind_address(Ipv4Addr::LOCALHOST)
.build()
.unwrap();
let signer = SigningKey::from_bytes(&[
56, 171, 62, 85, 105, 58, 155, 209, 189, 8, 59, 109, 137, 84, 84, 201, 221, 115, 7,
228, 127, 70, 4, 204, 182, 64, 77, 98, 92, 215, 27, 103,
]);
client
.put_mutable(MutableItem::new(signer.clone(), &[], 1001, None), None)
.unwrap();
assert!(matches!(
client.put_mutable(MutableItem::new(signer, &[], 1002, None), Some(1000)),
Err(PutMutableError::Concurrency(ConcurrencyError::CasFailed))
));
}
#[test]
fn populate_bootstrapping_node_routing_table() {
let size = 3;
let testnet = Testnet::builder(size).build().unwrap();
assert!(testnet
.nodes
.iter()
.all(|n| n.to_bootstrap().len() == size - 1));
}
}