需要一个使用 dht_put_item 和 libtorrent 的示例



我正在尝试使用 dht 来使用 libtorrent 保存可变数据。据我了解,正确的方法是使用会话dht_put_item的方法。问题是我需要传递一个回调函数,但我不知道我做错了什么......我的代码如下所示

namespace lt = libtorrent;
//The callback function
void cb(lt::entry& cdentry, boost::array<char,64>& cbarray, boost::uint64_t& cbint, std::string const& cbstring){
//My stuff here
}
void main(){
//The session
lt::session ses;
//The data I want to insert into DHT
std::string cadenaStr = "519d818411de49652b4aaf34850321de28bb2dce";        
//Now I create the keys
unsigned char seed[32];
unsigned char public_key[32];
unsigned char private_key[64];
unsigned char signature[32];
ed25519_create_seed(seed);
ed25519_create_keypair(public_key, private_key, seed);
ed25519_sign(signature, cadenaStr.c_str(), sizeof(cadenaStr.c_str()), public_key, private_key);
//How can I use this?, where is the data supposed to go? :|
ses.dht_put_item(public_key, cb, false);
}

在libtorrent/session_handler.hpp上,此方法定义为

void dht_put_item(boost::array<char, 32> key
, boost::function<void(entry&, boost::array<char,64>&
, boost::uint64_t&, std::string const&)> cb
, std::string salt = std::string());

有人可以告诉我我做错了什么。

谢谢!

libtorrent 存储库中有一个用于测试的示例。它可以生成密钥,放置并获取可变和不可变的项目。

https://github.com/arvidn/libtorrent/blob/master/tools/dht_put.cpp

我如何使用它?,数据应该去哪里? :|

在调用的回调中提供数据。这种 API 的原因是,有些用例是你想要改变数据,然后你需要首先知道这个键下是否已经存储了一些东西,以及它是什么。

您缺少会话的设置包。

lt::settings_pack settings;
settings.set_bool(settings_pack::enable_dht, false);
settings.set_int(settings_pack::alert_mask, 0xffffffff);
ses.apply_settings(settings);
settings.set_bool(settings_pack::enable_dht, true);
ses.apply_settings(settings);

然后,您需要等待警报,直到收到增强消息。

wait_for_alert(ses, dht_bootstrap_alert::alert_type);

最后,您的dht_put_item电话:

char const* cadenaStr = "519d818411de49652b4aaf34850321de28bb2dce"; 
dht_put_item(public_key, std::bind(&put_string, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, public_key, private_key, cadenaStr));

您将需要以下函数:

static alert* wait_for_alert(session* ses, int alert_type)
{
alert* ret = nullptr;
bool found = false;
while (!found)
{
ses->wait_for_alert(seconds(5));
std::vector<alert*> alerts;
ses->pop_alerts(&alerts);
for (std::vector<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
if ((*i)->type() != alert_type)
{
continue;
}
ret = *i;
found = true;
}
}
return ret;
}
static void put_string(
entry& e
,boost::array<char, 64>& sig
,boost::int64_t& seq
,std::string const& salt
,boost::array<char, 32> const& pk
,boost::array<char, 64> const& sk
,char const* str)
{
using dht::sign_mutable_item;
if (str != NULL) {
e = std::string(str);
std::vector<char> buf;
bencode(std::back_inserter(buf), e);
dht::signature sign;
seq++;
sign = sign_mutable_item(buf, salt, dht::sequence_number(seq)
, dht::public_key(pk.data())
, dht::secret_key(sk.data()));
sig = sign.bytes;
}
}

最新更新