My Project 3.7.1
C++ Distributed Hash Table
Loading...
Searching...
No Matches
routing_table.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "node.h"
6
7namespace dht {
8
9static constexpr unsigned TARGET_NODES {8};
10namespace net {
11class NetworkEngine;
12}
13
14struct Bucket
15{
16 Bucket()
17 : cached()
18 {}
19 Bucket(sa_family_t af, const InfoHash& f = {}, time_point t = time_point::min())
20 : af(af)
21 , first(f)
22 , time(t)
23 , cached()
24 {}
25 sa_family_t af {0};
26 InfoHash first {};
27 time_point time {time_point::min()}; /* time of last reply in this bucket */
28 std::list<Sp<Node>> nodes {};
29 Sp<Node> cached; /* the address of a likely candidate */
30
32 Sp<Node> randomNode(std::mt19937_64& rd);
33
34 void sendCachedPing(net::NetworkEngine& ne);
35 void connectivityChanged()
36 {
37 time = time_point::min();
38 for (auto& node : nodes)
39 node->setTime(time_point::min());
40 }
41};
42
43class RoutingTable : public std::list<Bucket>
44{
45public:
46 using std::list<Bucket>::list;
47
48 time_point grow_time {time_point::min()};
49 bool is_client {false};
50
51 InfoHash middle(const RoutingTable::const_iterator&) const;
52
53 std::vector<Sp<Node>> findClosestNodes(const InfoHash id, time_point now, size_t count = TARGET_NODES) const;
54
55 RoutingTable::iterator findBucket(const InfoHash& id);
56 RoutingTable::const_iterator findBucket(const InfoHash& id) const;
57
61 inline bool contains(const RoutingTable::const_iterator& bucket, const InfoHash& id) const
62 {
63 return InfoHash::cmp(bucket->first, id) <= 0
64 && (std::next(bucket) == end() || InfoHash::cmp(id, std::next(bucket)->first) < 0);
65 }
66
70 inline bool isEmpty() const { return empty() || (size() == 1 && front().nodes.empty()); }
71
72 void connectivityChanged(const time_point& now)
73 {
74 grow_time = now;
75 for (auto& b : *this)
76 b.connectivityChanged();
77 }
78
79 bool onNewNode(
80 const Sp<Node>& node, int comfirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne);
81
85 InfoHash randomId(const RoutingTable::const_iterator& bucket, std::mt19937_64& rd) const;
86
87 unsigned depth(const RoutingTable::const_iterator& bucket) const;
88
92 bool split(const RoutingTable::iterator& b);
93};
94
95} // namespace dht
bool contains(const RoutingTable::const_iterator &bucket, const InfoHash &id) const
bool isEmpty() const
InfoHash randomId(const RoutingTable::const_iterator &bucket, std::mt19937_64 &rd) const
bool split(const RoutingTable::iterator &b)
An abstraction of communication protocol on the network.
Sp< Node > randomNode(std::mt19937_64 &rd)