i2pd/libi2pd/KadDHT.h

75 lines
1.8 KiB
C
Raw Normal View History

2023-02-17 06:14:02 +03:00
/*
* Copyright (c) 2023, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*
*/
#ifndef KADDHT_H__
#define KADDHT_H__
#include <memory>
2023-02-19 03:45:31 +03:00
#include <vector>
2023-02-17 06:14:02 +03:00
#include <sstream>
2023-02-22 03:08:12 +03:00
#include <functional>
#include "RouterInfo.h"
2023-02-17 06:14:02 +03:00
// Kademlia DHT (XOR distance)
namespace i2p
{
namespace data
{
struct DHTNode
{
DHTNode * zero, * one;
2023-02-22 03:08:12 +03:00
std::shared_ptr<RouterInfo> router;
2023-02-17 06:14:02 +03:00
DHTNode ();
~DHTNode ();
2023-02-22 03:08:12 +03:00
bool IsEmpty () const { return !zero && !one && !router; };
void MoveRouterUp (bool fromOne);
2023-02-17 06:14:02 +03:00
};
class DHTTable
{
2023-02-22 03:08:12 +03:00
typedef std::function<bool (const std::shared_ptr<RouterInfo>&)> Filter;
2023-02-17 06:14:02 +03:00
public:
DHTTable ();
~DHTTable ();
2023-02-22 03:08:12 +03:00
void Insert (const std::shared_ptr<RouterInfo>& r);
2023-02-17 06:14:02 +03:00
bool Remove (const IdentHash& h);
2023-02-22 23:58:20 +03:00
std::shared_ptr<RouterInfo> FindClosest (const IdentHash& h, const Filter& filter = nullptr) const;
std::vector<std::shared_ptr<RouterInfo> > FindClosest (const IdentHash& h, size_t num, const Filter& filter = nullptr) const;
2023-02-17 06:14:02 +03:00
void Print (std::stringstream& s);
size_t GetSize () const { return m_Size; };
2023-02-22 03:08:12 +03:00
void Clear ();
2023-02-22 23:58:20 +03:00
void Cleanup (const Filter& filter);
2023-02-17 06:14:02 +03:00
private:
2023-02-22 03:08:12 +03:00
void Insert (const std::shared_ptr<RouterInfo>& r, DHTNode * root, int level); // recursive
2023-02-17 06:14:02 +03:00
bool Remove (const IdentHash& h, DHTNode * root, int level);
2023-02-22 23:58:20 +03:00
std::shared_ptr<RouterInfo> FindClosest (const IdentHash& h, DHTNode * root, int level) const;
void FindClosest (const IdentHash& h, size_t num, DHTNode * root, int level, std::vector<std::shared_ptr<RouterInfo> >& hashes) const;
2023-02-22 03:08:12 +03:00
void Cleanup (DHTNode * root);
2023-02-17 06:14:02 +03:00
void Print (std::stringstream& s, DHTNode * root, int level);
private:
DHTNode * m_Root;
size_t m_Size;
2023-02-22 03:08:12 +03:00
// transient
2023-02-22 23:58:20 +03:00
mutable Filter m_Filter;
2023-02-17 06:14:02 +03:00
};
}
}
#endif