Convert llarp::Router into an abstract base class

pull/284/head
Michael 5 years ago
parent 8096633753
commit 729cd045f1
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C

@ -400,14 +400,14 @@ extern "C"
void void
llarp_main_abort(struct llarp_main *ptr) llarp_main_abort(struct llarp_main *ptr)
{ {
ptr->ctx->router->logic->stop_timer(); ptr->ctx->router->logic()->stop_timer();
} }
void void
llarp_main_queryDHT_RC(struct llarp_main *ptr, llarp_main_queryDHT_RC(struct llarp_main *ptr,
struct llarp_router_lookup_job *job) struct llarp_router_lookup_job *job)
{ {
llarp_dht_lookup_router(ptr->ctx->router->dht, job); llarp_dht_lookup_router(ptr->ctx->router->dht(), job);
} }
bool bool
@ -495,8 +495,8 @@ extern "C"
// llarp::Info("checkOnline - DHT nodes ", // llarp::Info("checkOnline - DHT nodes ",
// request->ptr->ctx->router->dht->impl.nodes->nodes.size()); // request->ptr->ctx->router->dht->impl.nodes->nodes.size());
request->online = false; request->online = false;
request->nodes = request->ptr->ctx->router->dht->impl.nodes->nodes.size(); request->nodes = request->ptr->ctx->router->dht()->impl.nodes->nodes.size();
if(request->ptr->ctx->router->dht->impl.nodes->nodes.size()) if(request->ptr->ctx->router->dht()->impl.nodes->nodes.size())
{ {
// llarp::Info("checkOnline - Going to say we're online"); // llarp::Info("checkOnline - Going to say we're online");
request->online = true; request->online = true;
@ -516,7 +516,7 @@ extern "C"
request->first = true; request->first = true;
llarp::LogInfo("llarp_main_queryDHT_online - We're online"); llarp::LogInfo("llarp_main_queryDHT_online - We're online");
llarp::LogInfo("llarp_main_queryDHT_online - Querying DHT"); llarp::LogInfo("llarp_main_queryDHT_online - Querying DHT");
llarp_dht_lookup_router(request->ptr->ctx->router->dht, request->job); llarp_dht_lookup_router(request->ptr->ctx->router->dht(), request->job);
} }
} }
@ -525,7 +525,7 @@ extern "C"
{ {
// llarp::Info("llarp_main_queryDHT - setting up timer"); // llarp::Info("llarp_main_queryDHT - setting up timer");
request->hook = &llarp_main_queryDHT_online; request->hook = &llarp_main_queryDHT_online;
request->ptr->ctx->router->logic->call_later( request->ptr->ctx->router->logic()->call_later(
{1000, request, &llarp_main_checkOnline}); {1000, request, &llarp_main_checkOnline});
// llarp_dht_lookup_router(ptr->ctx->router->dht, job); // llarp_dht_lookup_router(ptr->ctx->router->dht, job);
} }

@ -66,7 +66,7 @@ namespace llarp
return; return;
Context *ctx = static_cast< Context * >(u); Context *ctx = static_cast< Context * >(u);
ctx->Explore(1); ctx->Explore(1);
ctx->router->logic->call_later({orig, ctx, &handle_explore_timer}); ctx->router->logic()->call_later({orig, ctx, &handle_explore_timer});
} }
void void
@ -233,7 +233,7 @@ namespace llarp
llarp::LogDebug("initialize dht with key ", ourKey); llarp::LogDebug("initialize dht with key ", ourKey);
// start exploring // start exploring
r->logic->call_later( r->logic()->call_later(
{exploreInterval, this, &llarp::dht::Context::handle_explore_timer}); {exploreInterval, this, &llarp::dht::Context::handle_explore_timer});
// start cleanup timer // start cleanup timer
ScheduleCleanupTimer(); ScheduleCleanupTimer();
@ -242,7 +242,7 @@ namespace llarp
void void
Context::ScheduleCleanupTimer() Context::ScheduleCleanupTimer()
{ {
router->logic->call_later({1000, this, &handle_cleaner_timer}); router->logic()->call_later({1000, this, &handle_cleaner_timer});
} }
void void
@ -262,11 +262,11 @@ namespace llarp
Context::RelayRequestForPath(const llarp::PathID_t &id, const IMessage *msg) Context::RelayRequestForPath(const llarp::PathID_t &id, const IMessage *msg)
{ {
llarp::routing::DHTMessage reply; llarp::routing::DHTMessage reply;
if(!msg->HandleMessage(router->dht, reply.M)) if(!msg->HandleMessage(router->dht(), reply.M))
return false; return false;
if(!reply.M.empty()) if(!reply.M.empty())
{ {
auto path = router->paths.GetByUpstream(router->pubkey(), id); auto path = router->pathContext().GetByUpstream(router->pubkey(), id);
return path && path->SendRoutingMessage(&reply, router); return path && path->SendRoutingMessage(&reply, router);
} }
return true; return true;
@ -419,13 +419,13 @@ namespace llarp
llarp::Crypto * llarp::Crypto *
Context::Crypto() const Context::Crypto() const
{ {
return router->crypto.get(); return router->crypto();
} }
llarp_time_t llarp_time_t
Context::Now() const Context::Now() const
{ {
return llarp_ev_loop_time_now_ms(router->netloop); return router->Now();
} }
} // namespace dht } // namespace dht

@ -17,7 +17,7 @@
namespace llarp namespace llarp
{ {
struct Router; struct AbstractRouter;
namespace dht namespace dht
{ {
@ -58,7 +58,7 @@ namespace llarp
virtual llarp::Crypto* virtual llarp::Crypto*
Crypto() const = 0; Crypto() const = 0;
virtual llarp::Router* virtual llarp::AbstractRouter*
GetRouter() const = 0; GetRouter() const = 0;
virtual const Key_t& virtual const Key_t&
@ -193,7 +193,7 @@ namespace llarp
void void
Explore(size_t N = 3); Explore(size_t N = 3);
llarp::Router* router; llarp::AbstractRouter* router;
// for router contacts // for router contacts
std::unique_ptr< Bucket< RCNode > > nodes; std::unique_ptr< Bucket< RCNode > > nodes;
@ -213,7 +213,7 @@ namespace llarp
return ourKey; return ourKey;
} }
llarp::Router* llarp::AbstractRouter*
GetRouter() const override GetRouter() const override
{ {
return router; return router;

@ -25,7 +25,9 @@ namespace llarp
{ {
// lookup router // lookup router
parent->LookupRouter( parent->LookupRouter(
pk, std::bind(&Router::HandleDHTLookupForExplore, router, pk, _1)); pk,
std::bind(&AbstractRouter::HandleDHTLookupForExplore, router, pk,
_1));
} }
} }
} // namespace dht } // namespace dht

@ -22,7 +22,7 @@ namespace llarp
void void
LocalRouterLookup::SendReply() LocalRouterLookup::SendReply()
{ {
auto path = parent->GetRouter()->paths.GetByUpstream( auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath); parent->OurKey().as_array(), localPath);
if(!path) if(!path)
{ {

@ -21,7 +21,7 @@ namespace llarp
void void
LocalServiceAddressLookup::SendReply() LocalServiceAddressLookup::SendReply()
{ {
auto path = parent->GetRouter()->paths.GetByUpstream( auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath); parent->OurKey().as_array(), localPath);
if(!path) if(!path)
{ {

@ -20,7 +20,7 @@ namespace llarp
void void
LocalTagLookup::SendReply() LocalTagLookup::SendReply()
{ {
auto path = parent->GetRouter()->paths.GetByUpstream( auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath); parent->OurKey().as_array(), localPath);
if(!path) if(!path)
{ {

@ -20,7 +20,7 @@ namespace llarp
Key_t k{K}; Key_t k{K};
if(K == us) if(K == us)
{ {
auto path = dht.router->paths.GetByUpstream(K, pathID); auto path = dht.router->pathContext().GetByUpstream(K, pathID);
if(path) if(path)
{ {
replies.emplace_back( replies.emplace_back(
@ -33,7 +33,7 @@ namespace llarp
Key_t peer; Key_t peer;
// check if we know this in our nodedb first // check if we know this in our nodedb first
RouterContact found; RouterContact found;
if(dht.router->nodedb->Get(K, found)) if(dht.router->nodedb()->Get(K, found))
{ {
replies.emplace_back(new GotRouterMessage(k, txid, {found}, false)); replies.emplace_back(new GotRouterMessage(k, txid, {found}, false));
return true; return true;
@ -159,7 +159,7 @@ namespace llarp
Key_t k{K}; Key_t k{K};
if(exploritory) if(exploritory)
return dht.HandleExploritoryRouterLookup(From, txid, K, replies); return dht.HandleExploritoryRouterLookup(From, txid, K, replies);
else if(dht.router->nodedb->Get(K, found)) else if(dht.router->nodedb()->Get(K, found))
{ {
replies.emplace_back(new GotRouterMessage(k, txid, {found}, false)); replies.emplace_back(new GotRouterMessage(k, txid, {found}, false));
return true; return true;

@ -25,7 +25,7 @@ namespace llarp
std::vector< std::unique_ptr< IMessage > > &replies) const std::vector< std::unique_ptr< IMessage > > &replies) const
{ {
auto &dht = ctx->impl; auto &dht = ctx->impl;
auto crypto = dht.router->crypto.get(); auto crypto = dht.router->crypto();
for(const auto &introset : I) for(const auto &introset : I)
{ {
@ -70,7 +70,7 @@ namespace llarp
std::vector< std::unique_ptr< IMessage > > &replies) const std::vector< std::unique_ptr< IMessage > > &replies) const
{ {
// TODO: implement me better? // TODO: implement me better?
auto pathset = ctx->impl.router->paths.GetLocalPathSet(pathID); auto pathset = ctx->impl.router->pathContext().GetLocalPathSet(pathID);
if(pathset) if(pathset)
{ {
return pathset->HandleGotIntroMessage(this); return pathset->HandleGotIntroMessage(this);

@ -87,7 +87,7 @@ namespace llarp
auto &dht = ctx->impl; auto &dht = ctx->impl;
if(relayed) if(relayed)
{ {
auto pathset = ctx->impl.router->paths.GetLocalPathSet(pathID); auto pathset = ctx->impl.router->pathContext().GetLocalPathSet(pathID);
return pathset && pathset->HandleGotRouterMessage(this); return pathset && pathset->HandleGotRouterMessage(this);
} }
// not relayed // not relayed

@ -53,7 +53,7 @@ namespace llarp
return false; return false;
} }
auto &dht = ctx->impl; auto &dht = ctx->impl;
if(!I.Verify(dht.router->crypto.get(), now)) if(!I.Verify(dht.router->crypto(), now))
{ {
llarp::LogWarn("invalid introset: ", I); llarp::LogWarn("invalid introset: ", I);
// don't propogate or store // don't propogate or store
@ -63,7 +63,7 @@ namespace llarp
using namespace std::placeholders; using namespace std::placeholders;
shorthash_func shorthash = shorthash_func shorthash =
std::bind(&Crypto::shorthash, dht.router->crypto.get(), _1, _2); std::bind(&Crypto::shorthash, dht.router->crypto(), _1, _2);
if(I.W && !I.W->IsValid(shorthash, now)) if(I.W && !I.W->IsValid(shorthash, now))
{ {
llarp::LogWarn("proof of work not good enough for IntroSet"); llarp::LogWarn("proof of work not good enough for IntroSet");

@ -11,13 +11,13 @@ namespace llarp
const llarp::RouterID& router, const llarp::RouterID& router,
std::function< bool(const llarp_buffer_t&) > writepkt, llarp::Router* r, std::function< bool(const llarp_buffer_t&) > writepkt, llarp::Router* r,
size_t numpaths, size_t hoplen) size_t numpaths, size_t hoplen)
: llarp::path::Builder(r, r->dht, numpaths, hoplen) : llarp::path::Builder(r, r->dht(), numpaths, hoplen)
, m_ExitRouter(router) , m_ExitRouter(router)
, m_WritePacket(writepkt) , m_WritePacket(writepkt)
, m_Counter(0) , m_Counter(0)
, m_LastUse(0) , m_LastUse(0)
{ {
r->crypto->identity_keygen(m_ExitIdentity); r->crypto()->identity_keygen(m_ExitIdentity);
} }
BaseSession::~BaseSession() BaseSession::~BaseSession()
@ -79,7 +79,7 @@ namespace llarp
obtain.S = p->NextSeqNo(); obtain.S = p->NextSeqNo();
obtain.T = llarp::randint(); obtain.T = llarp::randint();
PopulateRequest(obtain); PopulateRequest(obtain);
if(!obtain.Sign(router->crypto.get(), m_ExitIdentity)) if(!obtain.Sign(router->crypto(), m_ExitIdentity))
{ {
llarp::LogError("Failed to sign exit request"); llarp::LogError("Failed to sign exit request");
return; return;
@ -108,7 +108,7 @@ namespace llarp
{ {
llarp::LogInfo(p->Name(), " closing exit path"); llarp::LogInfo(p->Name(), " closing exit path");
llarp::routing::CloseExitMessage msg; llarp::routing::CloseExitMessage msg;
if(!(msg.Sign(router->crypto.get(), m_ExitIdentity) if(!(msg.Sign(router->crypto(), m_ExitIdentity)
&& p->SendExitClose(&msg, router))) && p->SendExitClose(&msg, router)))
llarp::LogWarn(p->Name(), " failed to send exit close message"); llarp::LogWarn(p->Name(), " failed to send exit close message");
} }

@ -246,7 +246,7 @@ namespace llarp
Crypto * Crypto *
ExitEndpoint::GetCrypto() ExitEndpoint::GetCrypto()
{ {
return m_Router->crypto.get(); return m_Router->crypto();
} }
huint32_t huint32_t

@ -551,7 +551,7 @@ namespace llarp
NewServerFromRouter(llarp::Router* r) NewServerFromRouter(llarp::Router* r)
{ {
return NewServer( return NewServer(
r->crypto.get(), r->encryption, std::bind(&llarp::Router::rc, r), r->crypto(), r->encryption, std::bind(&llarp::Router::rc, r),
std::bind(&llarp::Router::HandleRecvLinkMessageBuffer, r, std::bind(&llarp::Router::HandleRecvLinkMessageBuffer, r,
std::placeholders::_1, std::placeholders::_2), std::placeholders::_1, std::placeholders::_2),
std::bind(&llarp::Router::OnSessionEstablished, r, std::bind(&llarp::Router::OnSessionEstablished, r,

@ -72,7 +72,7 @@ namespace llarp
bool result = true; bool result = true;
for(auto &msg : msgs) for(auto &msg : msgs)
{ {
result &= msg->HandleMessage(router->dht, reply.msgs); result &= msg->HandleMessage(router->dht(), reply.msgs);
} }
if(reply.msgs.size()) if(reply.msgs.size())
{ {

@ -117,7 +117,7 @@ namespace llarp
bool bool
LinkIntroMessage::HandleMessage(llarp::Router* router) const LinkIntroMessage::HandleMessage(llarp::Router* router) const
{ {
if(!Verify(router->crypto.get())) if(!Verify(router->crypto()))
return false; return false;
return session->GotLIM(this); return session->GotLIM(this);
} }

@ -43,13 +43,13 @@ namespace llarp
llarp::Crypto* llarp::Crypto*
PathContext::Crypto() PathContext::Crypto()
{ {
return m_Router->crypto.get(); return m_Router->crypto();
} }
llarp::Logic* llarp::Logic*
PathContext::Logic() PathContext::Logic()
{ {
return m_Router->logic; return m_Router->logic();
} }
llarp::SecretKey& llarp::SecretKey&
@ -155,24 +155,26 @@ namespace llarp
IHopHandler* IHopHandler*
PathContext::GetByUpstream(const RouterID& remote, const PathID_t& id) PathContext::GetByUpstream(const RouterID& remote, const PathID_t& id)
{ {
auto own = MapGet(m_OurPaths, id, auto own = MapGet(
[](__attribute__((unused)) const PathSet* s) -> bool { m_OurPaths, id,
// TODO: is this right? [](__attribute__((unused)) const PathSet* s) -> bool {
return true; // TODO: is this right?
}, return true;
[remote, id](PathSet* p) -> IHopHandler* { },
return p->GetByUpstream(remote, id); [remote, id](PathSet* p) -> IHopHandler* {
}); return p->GetByUpstream(remote, id);
});
if(own) if(own)
return own; return own;
return MapGet(m_TransitPaths, id, return MapGet(
[remote](const std::shared_ptr< TransitHop >& hop) -> bool { m_TransitPaths, id,
return hop->info.upstream == remote; [remote](const std::shared_ptr< TransitHop >& hop) -> bool {
}, return hop->info.upstream == remote;
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { },
return h.get(); [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
}); return h.get();
});
} }
bool bool
@ -189,13 +191,14 @@ namespace llarp
IHopHandler* IHopHandler*
PathContext::GetByDownstream(const RouterID& remote, const PathID_t& id) PathContext::GetByDownstream(const RouterID& remote, const PathID_t& id)
{ {
return MapGet(m_TransitPaths, id, return MapGet(
[remote](const std::shared_ptr< TransitHop >& hop) -> bool { m_TransitPaths, id,
return hop->info.downstream == remote; [remote](const std::shared_ptr< TransitHop >& hop) -> bool {
}, return hop->info.downstream == remote;
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { },
return h.get(); [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
}); return h.get();
});
} }
PathSet* PathSet*
@ -505,12 +508,12 @@ namespace llarp
bool bool
Path::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y, Path::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r) AbstractRouter* r)
{ {
TunnelNonce n = Y; TunnelNonce n = Y;
for(const auto& hop : hops) for(const auto& hop : hops)
{ {
r->crypto->xchacha20(buf, hop.shared, n); r->crypto()->xchacha20(buf, hop.shared, n);
n ^= hop.nonceXOR; n ^= hop.nonceXOR;
} }
RelayUpstreamMessage msg; RelayUpstreamMessage msg;
@ -544,19 +547,19 @@ namespace llarp
bool bool
Path::HandleDownstream(const llarp_buffer_t& buf, const TunnelNonce& Y, Path::HandleDownstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r) AbstractRouter* r)
{ {
TunnelNonce n = Y; TunnelNonce n = Y;
for(const auto& hop : hops) for(const auto& hop : hops)
{ {
n ^= hop.nonceXOR; n ^= hop.nonceXOR;
r->crypto->xchacha20(buf, hop.shared, n); r->crypto()->xchacha20(buf, hop.shared, n);
} }
return HandleRoutingMessage(buf, r); return HandleRoutingMessage(buf, r);
} }
bool bool
Path::HandleRoutingMessage(const llarp_buffer_t& buf, llarp::Router* r) Path::HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r)
{ {
if(!r->ParseRoutingMessageBuffer(buf, this, RXID())) if(!r->ParseRoutingMessageBuffer(buf, this, RXID()))
{ {
@ -587,7 +590,7 @@ namespace llarp
bool bool
Path::SendRoutingMessage(const llarp::routing::IMessage* msg, Path::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) llarp::AbstractRouter* r)
{ {
std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp; std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -609,7 +612,7 @@ namespace llarp
if(buf.sz < MESSAGE_PAD_SIZE) if(buf.sz < MESSAGE_PAD_SIZE)
{ {
// randomize padding // randomize padding
r->crypto->randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz); r->crypto()->randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz);
buf.sz = MESSAGE_PAD_SIZE; buf.sz = MESSAGE_PAD_SIZE;
} }
buf.cur = buf.base; buf.cur = buf.base;
@ -699,7 +702,7 @@ namespace llarp
Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp::Router* r) Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp::Router* r)
{ {
llarp::routing::DHTMessage reply; llarp::routing::DHTMessage reply;
if(!msg->HandleMessage(r->dht, reply.M)) if(!msg->HandleMessage(r->dht(), reply.M))
return false; return false;
MarkActive(r->Now()); MarkActive(r->Now());
if(reply.M.size()) if(reply.M.size())
@ -714,7 +717,7 @@ namespace llarp
/// allows exits to close from their end /// allows exits to close from their end
if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC))
{ {
if(msg->Verify(r->crypto.get(), EndpointPubKey())) if(msg->Verify(r->crypto(), EndpointPubKey()))
{ {
llarp::LogInfo(Name(), " had its exit closed"); llarp::LogInfo(Name(), " had its exit closed");
_role &= ~ePathRoleExit; _role &= ~ePathRoleExit;
@ -773,7 +776,7 @@ namespace llarp
{ {
if(m_ExitObtainTX && msg->T == m_ExitObtainTX) if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{ {
if(!msg->Verify(r->crypto.get(), EndpointPubKey())) if(!msg->Verify(r->crypto(), EndpointPubKey()))
{ {
llarp::LogError(Name(), "RXM invalid signature"); llarp::LogError(Name(), "RXM invalid signature");
return false; return false;
@ -792,7 +795,7 @@ namespace llarp
{ {
if(m_ExitObtainTX && msg->T == m_ExitObtainTX) if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{ {
if(!msg->Verify(r->crypto.get(), EndpointPubKey())) if(!msg->Verify(r->crypto(), EndpointPubKey()))
{ {
llarp::LogError(Name(), " GXM signature failed"); llarp::LogError(Name(), " GXM signature failed");
return false; return false;

@ -32,6 +32,7 @@
namespace llarp namespace llarp
{ {
struct AbstractRouter;
struct Crypto; struct Crypto;
struct LR_CommitMessage; struct LR_CommitMessage;
struct LR_CommitRecord; struct LR_CommitRecord;
@ -112,17 +113,17 @@ namespace llarp
/// send routing message and increment sequence number /// send routing message and increment sequence number
virtual bool virtual bool
SendRoutingMessage(const llarp::routing::IMessage* msg, SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) = 0; llarp::AbstractRouter* r) = 0;
// handle data in upstream direction // handle data in upstream direction
virtual bool virtual bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) = 0; AbstractRouter* r) = 0;
// handle data in downstream direction // handle data in downstream direction
virtual bool virtual bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) = 0; AbstractRouter* r) = 0;
/// return timestamp last remote activity happened at /// return timestamp last remote activity happened at
virtual llarp_time_t virtual llarp_time_t
@ -188,12 +189,12 @@ namespace llarp
// send routing message when end of path // send routing message when end of path
bool bool
SendRoutingMessage(const llarp::routing::IMessage* msg, SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) override; AbstractRouter* r) override;
// handle routing message when end of path // handle routing message when end of path
bool bool
HandleRoutingMessage(const llarp::routing::IMessage* msg, HandleRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r); AbstractRouter* r);
bool bool
HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg, HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg,
@ -257,12 +258,12 @@ namespace llarp
// handle data in upstream direction // handle data in upstream direction
bool bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override; AbstractRouter* r) override;
// handle data in downstream direction // handle data in downstream direction
bool bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override; AbstractRouter* r) override;
}; };
/// configuration for a single hop when building a path /// configuration for a single hop when building a path
@ -417,7 +418,7 @@ namespace llarp
bool bool
SendRoutingMessage(const llarp::routing::IMessage* msg, SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) override; llarp::AbstractRouter* r) override;
bool bool
HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg, HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg,
@ -475,17 +476,17 @@ namespace llarp
llarp::Router* r) override; llarp::Router* r) override;
bool bool
HandleRoutingMessage(const llarp_buffer_t& buf, llarp::Router* r); HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r);
// handle data in upstream direction // handle data in upstream direction
bool bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override; AbstractRouter* r) override;
// handle data in downstream direction // handle data in downstream direction
bool bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override; AbstractRouter* r) override;
bool bool
IsReady() const; IsReady() const;

@ -173,8 +173,8 @@ namespace llarp
, dht(p_dht) , dht(p_dht)
, numHops(hops) , numHops(hops)
{ {
p_router->paths.AddPathBuilder(this); p_router->pathContext().AddPathBuilder(this);
p_router->crypto->encryption_keygen(enckey); p_router->crypto()->encryption_keygen(enckey);
_run.store(true); _run.store(true);
keygens.store(0); keygens.store(0);
} }
@ -246,7 +246,7 @@ namespace llarp
Builder::BuildOne(PathRole roles) Builder::BuildOne(PathRole roles)
{ {
std::vector< RouterContact > hops; std::vector< RouterContact > hops;
if(SelectHops(router->nodedb, hops, roles)) if(SelectHops(router->nodedb(), hops, roles))
Build(hops, roles); Build(hops, roles);
} }
@ -294,14 +294,14 @@ namespace llarp
lastBuild = Now(); lastBuild = Now();
// async generate keys // async generate keys
AsyncPathKeyExchangeContext< Builder >* ctx = AsyncPathKeyExchangeContext< Builder >* ctx =
new AsyncPathKeyExchangeContext< Builder >(router->crypto.get()); new AsyncPathKeyExchangeContext< Builder >(router->crypto());
ctx->router = router; ctx->router = router;
ctx->pathset = this; ctx->pathset = this;
auto path = new llarp::path::Path(hops, this, roles); auto path = new llarp::path::Path(hops, this, roles);
path->SetBuildResultHook(std::bind(&llarp::path::Builder::HandlePathBuilt, path->SetBuildResultHook(std::bind(&llarp::path::Builder::HandlePathBuilt,
this, std::placeholders::_1)); this, std::placeholders::_1));
++keygens; ++keygens;
ctx->AsyncGenerateKeys(path, router->logic, router->tp, this, ctx->AsyncGenerateKeys(path, router->logic(), router->tp, this,
&PathBuilderKeysGenerated); &PathBuilderKeysGenerated);
} }

@ -55,7 +55,7 @@ namespace llarp
bool bool
TransitHop::SendRoutingMessage(const llarp::routing::IMessage* msg, TransitHop::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) AbstractRouter* r)
{ {
if(!IsEndpoint(r->pubkey())) if(!IsEndpoint(r->pubkey()))
return false; return false;
@ -76,7 +76,7 @@ namespace llarp
{ {
dlt = MESSAGE_PAD_SIZE - dlt; dlt = MESSAGE_PAD_SIZE - dlt;
// randomize padding // randomize padding
r->crypto->randbytes(buf.cur, dlt); r->crypto()->randbytes(buf.cur, dlt);
buf.sz += dlt; buf.sz += dlt;
} }
buf.cur = buf.base; buf.cur = buf.base;
@ -85,12 +85,12 @@ namespace llarp
bool bool
TransitHop::HandleDownstream(const llarp_buffer_t& buf, TransitHop::HandleDownstream(const llarp_buffer_t& buf,
const TunnelNonce& Y, llarp::Router* r) const TunnelNonce& Y, AbstractRouter* r)
{ {
RelayDownstreamMessage msg; RelayDownstreamMessage msg;
msg.pathid = info.rxID; msg.pathid = info.rxID;
msg.Y = Y ^ nonceXOR; msg.Y = Y ^ nonceXOR;
r->crypto->xchacha20(buf, pathKey, Y); r->crypto()->xchacha20(buf, pathKey, Y);
msg.X = buf; msg.X = buf;
llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ",
info.upstream, " to ", info.downstream); info.upstream, " to ", info.downstream);
@ -99,9 +99,9 @@ namespace llarp
bool bool
TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y, TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r) AbstractRouter* r)
{ {
r->crypto->xchacha20(buf, pathKey, Y); r->crypto()->xchacha20(buf, pathKey, Y);
if(IsEndpoint(r->pubkey())) if(IsEndpoint(r->pubkey()))
{ {
m_LastActivity = r->Now(); m_LastActivity = r->Now();
@ -124,7 +124,7 @@ namespace llarp
TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg, TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp::Router* r) llarp::Router* r)
{ {
return r->dht->impl.RelayRequestForPath(info.rxID, msg); return r->dht()->impl.RelayRequestForPath(info.rxID, msg);
} }
bool bool
@ -158,13 +158,13 @@ namespace llarp
TransitHop::HandleObtainExitMessage( TransitHop::HandleObtainExitMessage(
const llarp::routing::ObtainExitMessage* msg, llarp::Router* r) const llarp::routing::ObtainExitMessage* msg, llarp::Router* r)
{ {
if(msg->Verify(r->crypto.get()) if(msg->Verify(r->crypto())
&& r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0)) && r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0))
{ {
llarp::routing::GrantExitMessage grant; llarp::routing::GrantExitMessage grant;
grant.S = NextSeqNo(); grant.S = NextSeqNo();
grant.T = msg->T; grant.T = msg->T;
if(!grant.Sign(r->crypto.get(), r->identity)) if(!grant.Sign(r->crypto(), r->identity))
{ {
llarp::LogError("Failed to sign grant exit message"); llarp::LogError("Failed to sign grant exit message");
return false; return false;
@ -176,7 +176,7 @@ namespace llarp
llarp::routing::RejectExitMessage reject; llarp::routing::RejectExitMessage reject;
reject.S = NextSeqNo(); reject.S = NextSeqNo();
reject.T = msg->T; reject.T = msg->T;
if(!reject.Sign(r->crypto.get(), r->identity)) if(!reject.Sign(r->crypto(), r->identity))
{ {
llarp::LogError("Failed to sign reject exit message"); llarp::LogError("Failed to sign reject exit message");
return false; return false;
@ -190,13 +190,13 @@ namespace llarp
{ {
llarp::routing::DataDiscardMessage discard(info.rxID, msg->S); llarp::routing::DataDiscardMessage discard(info.rxID, msg->S);
auto ep = r->exitContext.FindEndpointForPath(info.rxID); auto ep = r->exitContext.FindEndpointForPath(info.rxID);
if(ep && msg->Verify(r->crypto.get(), ep->PubKey())) if(ep && msg->Verify(r->crypto(), ep->PubKey()))
{ {
ep->Close(); ep->Close();
// ep is now gone af // ep is now gone af
llarp::routing::CloseExitMessage reply; llarp::routing::CloseExitMessage reply;
reply.S = NextSeqNo(); reply.S = NextSeqNo();
if(reply.Sign(r->crypto.get(), r->identity)) if(reply.Sign(r->crypto(), r->identity))
return SendRoutingMessage(&reply, r); return SendRoutingMessage(&reply, r);
} }
return SendRoutingMessage(&discard, r); return SendRoutingMessage(&discard, r);
@ -219,7 +219,7 @@ namespace llarp
auto ep = r->exitContext.FindEndpointForPath(msg->P); auto ep = r->exitContext.FindEndpointForPath(msg->P);
if(ep) if(ep)
{ {
if(!msg->Verify(r->crypto.get(), ep->PubKey())) if(!msg->Verify(r->crypto(), ep->PubKey()))
return false; return false;
if(ep->UpdateLocalPath(info.rxID)) if(ep->UpdateLocalPath(info.rxID))

@ -80,7 +80,9 @@ struct TryConnectJob
if(!router->IsServiceNode()) if(!router->IsServiceNode())
{ {
if(router->routerProfiling.IsBad(rc.pubkey)) if(router->routerProfiling.IsBad(rc.pubkey))
router->nodedb->Remove(rc.pubkey); {
router->nodedb()->Remove(rc.pubkey);
}
} }
// delete this // delete this
router->pendingEstablishJobs.erase(rc.pubkey); router->pendingEstablishJobs.erase(rc.pubkey);
@ -164,6 +166,10 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path,
namespace llarp namespace llarp
{ {
AbstractRouter::~AbstractRouter()
{
}
bool bool
Router::TryConnectAsync(llarp::RouterContact remote, uint16_t numretries) Router::TryConnectAsync(llarp::RouterContact remote, uint16_t numretries)
{ {
@ -186,7 +192,7 @@ namespace llarp
// only try establishing if we inserted a new element // only try establishing if we inserted a new element
TryConnectJob *job = itr.first->second.get(); TryConnectJob *job = itr.first->second.get();
// try establishing async // try establishing async
logic->queue_job({job, &on_try_connecting}); _logic->queue_job({job, &on_try_connecting});
return true; return true;
} }
} }
@ -201,15 +207,15 @@ namespace llarp
} }
Router::Router(struct llarp_threadpool *_tp, struct llarp_ev_loop *_netloop, Router::Router(struct llarp_threadpool *_tp, struct llarp_ev_loop *_netloop,
llarp::Logic *_logic) llarp::Logic *l)
: ready(false) : ready(false)
, netloop(_netloop) , netloop(_netloop)
, tp(_tp) , tp(_tp)
, logic(_logic) , _logic(l)
, crypto(std::make_unique< sodium::CryptoLibSodium >()) , _crypto(std::make_unique< sodium::CryptoLibSodium >())
, paths(this) , paths(this)
, exitContext(this) , exitContext(this)
, dht(llarp_dht_context_new(this)) , _dht(llarp_dht_context_new(this))
, inbound_link_msg_parser(this) , inbound_link_msg_parser(this)
, hiddenServiceContext(this) , hiddenServiceContext(this)
{ {
@ -228,7 +234,7 @@ namespace llarp
Router::~Router() Router::~Router()
{ {
llarp_dht_context_free(dht); llarp_dht_context_free(_dht);
} }
bool bool
@ -257,10 +263,10 @@ namespace llarp
bool bool
Router::GetRandomGoodRouter(RouterID &router) Router::GetRandomGoodRouter(RouterID &router)
{ {
auto sz = nodedb->entries.size(); auto sz = nodedb()->entries.size();
if(sz == 0) if(sz == 0)
return false; return false;
auto itr = nodedb->entries.begin(); auto itr = nodedb()->entries.begin();
if(sz > 1) if(sz > 1)
std::advance(itr, randint() % sz); std::advance(itr, randint() % sz);
router = itr->first; router = itr->first;
@ -317,7 +323,7 @@ namespace llarp
} }
llarp::RouterContact remoteRC; llarp::RouterContact remoteRC;
// we don't have an open session to that router right now // we don't have an open session to that router right now
if(nodedb->Get(remote, remoteRC)) if(nodedb()->Get(remote, remoteRC))
{ {
// try connecting directly as the rc is loaded from disk // try connecting directly as the rc is loaded from disk
TryConnectAsync(remoteRC, 10); TryConnectAsync(remoteRC, 10);
@ -325,9 +331,9 @@ namespace llarp
} }
// we don't have the RC locally so do a dht lookup // we don't have the RC locally so do a dht lookup
dht->impl.LookupRouter(remote, _dht->impl.LookupRouter(remote,
std::bind(&Router::HandleDHTLookupForSendTo, this, std::bind(&Router::HandleDHTLookupForSendTo, this,
remote, std::placeholders::_1)); remote, std::placeholders::_1));
return true; return true;
} }
@ -343,9 +349,9 @@ namespace llarp
{ {
return; return;
} }
if(results[0].Verify(crypto.get(), Now())) if(results[0].Verify(crypto(), Now()))
{ {
nodedb->Insert(results[0]); nodedb()->Insert(results[0]);
TryConnectAsync(results[0], 10); TryConnectAsync(results[0], 10);
return; return;
} }
@ -391,11 +397,11 @@ namespace llarp
llarp::LogError("failure to decode or verify of remote RC"); llarp::LogError("failure to decode or verify of remote RC");
return; return;
} }
if(remote.Verify(crypto.get(), Now())) if(remote.Verify(crypto(), Now()))
{ {
llarp::LogDebug("verified signature"); llarp::LogDebug("verified signature");
// store into filesystem // store into filesystem
if(!nodedb->Insert(remote)) if(!nodedb()->Insert(remote))
{ {
llarp::LogWarn("failed to store"); llarp::LogWarn("failed to store");
} }
@ -415,16 +421,16 @@ namespace llarp
if(!EnsureEncryptionKey()) if(!EnsureEncryptionKey())
return false; return false;
if(usingSNSeed) if(usingSNSeed)
return llarp_loadServiceNodeIdentityKey(crypto.get(), ident_keyfile, return llarp_loadServiceNodeIdentityKey(crypto(), ident_keyfile,
identity); identity);
else else
return llarp_findOrCreateIdentity(crypto.get(), ident_keyfile, identity); return llarp_findOrCreateIdentity(crypto(), ident_keyfile, identity);
} }
bool bool
Router::EnsureEncryptionKey() Router::EnsureEncryptionKey()
{ {
return llarp_findOrCreateEncryption(crypto.get(), encryption_keyfile, return llarp_findOrCreateEncryption(crypto(), encryption_keyfile,
this->encryption); this->encryption);
} }
@ -460,7 +466,7 @@ namespace llarp
Router::SaveRC() Router::SaveRC()
{ {
llarp::LogDebug("verify RC signature"); llarp::LogDebug("verify RC signature");
if(!_rc.Verify(crypto.get(), Now())) if(!_rc.Verify(crypto(), Now()))
{ {
rc().Dump< MAX_RC_SIZE >(); rc().Dump< MAX_RC_SIZE >();
llarp::LogError("RC is invalid, not saving"); llarp::LogError("RC is invalid, not saving");
@ -532,7 +538,7 @@ namespace llarp
router->validRouters.emplace(pk, rc); router->validRouters.emplace(pk, rc);
// track valid router in dht // track valid router in dht
router->dht->impl.nodes->PutNode(rc); router->dht()->impl.nodes->PutNode(rc);
// mark success in profile // mark success in profile
router->routerProfiling.MarkSuccess(pk); router->routerProfiling.MarkSuccess(pk);
@ -586,8 +592,8 @@ namespace llarp
return; return;
for(const auto &rc : results) for(const auto &rc : results)
{ {
if(rc.Verify(crypto.get(), Now())) if(rc.Verify(crypto(), Now()))
nodedb->Insert(rc); nodedb()->Insert(rc);
else else
return; return;
} }
@ -608,18 +614,18 @@ namespace llarp
} }
llarp::RouterContact rc; llarp::RouterContact rc;
if(nodedb->Get(remote, rc)) if(nodedb()->Get(remote, rc))
{ {
// try connecting async // try connecting async
TryConnectAsync(rc, 5); TryConnectAsync(rc, 5);
} }
else if(IsServiceNode() || !routerProfiling.IsBad(remote)) else if(IsServiceNode() || !routerProfiling.IsBad(remote))
{ {
if(dht->impl.HasRouterLookup(remote)) if(dht()->impl.HasRouterLookup(remote))
return; return;
llarp::LogInfo("looking up router ", remote); llarp::LogInfo("looking up router ", remote);
// dht lookup as we don't know it // dht lookup as we don't know it
dht->impl.LookupRouter( dht()->impl.LookupRouter(
remote, remote,
std::bind(&Router::HandleDHTLookupForTryEstablishTo, this, remote, std::bind(&Router::HandleDHTLookupForTryEstablishTo, this, remote,
std::placeholders::_1)); std::placeholders::_1));
@ -655,7 +661,7 @@ namespace llarp
if(whitelistRouters if(whitelistRouters
&& lokinetRouters.find(result.pubkey) == lokinetRouters.end()) && lokinetRouters.find(result.pubkey) == lokinetRouters.end())
continue; continue;
nodedb->Insert(result); nodedb()->Insert(result);
TryConnectAsync(result, 10); TryConnectAsync(result, 10);
} }
} }
@ -673,7 +679,7 @@ namespace llarp
llarp::RouterContact nextRC = _rc; llarp::RouterContact nextRC = _rc;
if(rotateKeys) if(rotateKeys)
{ {
crypto->encryption_keygen(nextOnionKey); crypto()->encryption_keygen(nextOnionKey);
std::string f = encryption_keyfile.string(); std::string f = encryption_keyfile.string();
if(nextOnionKey.SaveToFile(f.c_str())) if(nextOnionKey.SaveToFile(f.c_str()))
{ {
@ -682,7 +688,7 @@ namespace llarp
} }
} }
nextRC.last_updated = Now(); nextRC.last_updated = Now();
if(!nextRC.Sign(crypto.get(), identity)) if(!nextRC.Sign(crypto(), identity))
return false; return false;
_rc = nextRC; _rc = nextRC;
// propagate RC by renegotiating sessions // propagate RC by renegotiating sessions
@ -705,11 +711,11 @@ namespace llarp
return false; return false;
// store it in nodedb async // store it in nodedb async
nodedb->InsertAsync(newrc); nodedb()->InsertAsync(newrc);
// update dht if required // update dht if required
if(dht->impl.nodes->HasNode(dht::Key_t{newrc.pubkey})) if(dht()->impl.nodes->HasNode(dht::Key_t{newrc.pubkey}))
{ {
dht->impl.nodes->PutNode(newrc); dht()->impl.nodes->PutNode(newrc);
} }
// update valid routers // update valid routers
{ {
@ -726,9 +732,9 @@ namespace llarp
void void
Router::ServiceNodeLookupRouterWhenExpired(RouterID router) Router::ServiceNodeLookupRouterWhenExpired(RouterID router)
{ {
dht->impl.LookupRouter(router, dht()->impl.LookupRouter(router,
std::bind(&Router::HandleDHTLookupForExplore, this, std::bind(&Router::HandleDHTLookupForExplore, this,
router, std::placeholders::_1)); router, std::placeholders::_1));
} }
void void
@ -748,7 +754,7 @@ namespace llarp
{ {
// only do this as service node // only do this as service node
// client endpoints do this on their own // client endpoints do this on their own
nodedb->visit([&](const RouterContact &rc) -> bool { nodedb()->visit([&](const RouterContact &rc) -> bool {
if(rc.ExpiresSoon(now, llarp::randint() % 10000)) if(rc.ExpiresSoon(now, llarp::randint() % 10000))
ServiceNodeLookupRouterWhenExpired(rc.pubkey); ServiceNodeLookupRouterWhenExpired(rc.pubkey);
return true; return true;
@ -783,7 +789,7 @@ namespace llarp
} }
} }
size_t N = nodedb->num_loaded(); size_t N = nodedb()->num_loaded();
if(N < minRequiredRouters) if(N < minRequiredRouters)
{ {
llarp::LogInfo("We need at least ", minRequiredRouters, llarp::LogInfo("We need at least ", minRequiredRouters,
@ -795,7 +801,7 @@ namespace llarp
for(const auto &rc : bootstrapRCList) for(const auto &rc : bootstrapRCList)
{ {
TryConnectAsync(rc, 4); TryConnectAsync(rc, 4);
dht->impl.ExploreNetworkVia(dht::Key_t{rc.pubkey}); dht()->impl.ExploreNetworkVia(dht::Key_t{rc.pubkey});
} }
} }
else else
@ -819,7 +825,7 @@ namespace llarp
bool bool
Router::Sign(llarp::Signature &sig, const llarp_buffer_t &buf) const Router::Sign(llarp::Signature &sig, const llarp_buffer_t &buf) const
{ {
return crypto->sign(sig, identity, buf); return crypto()->sign(sig, identity, buf);
} }
void void
@ -859,13 +865,13 @@ namespace llarp
void void
Router::ScheduleTicker(uint64_t ms) Router::ScheduleTicker(uint64_t ms)
{ {
ticker_job_id = logic->call_later({ms, this, &handle_router_ticker}); ticker_job_id = _logic->call_later({ms, this, &handle_router_ticker});
} }
void void
Router::SessionClosed(llarp::RouterID remote) Router::SessionClosed(llarp::RouterID remote)
{ {
__llarp_dht_remove_peer(dht, remote.data()); __llarp_dht_remove_peer(dht(), remote.data());
// remove from valid routers if it's a valid router // remove from valid routers if it's a valid router
validRouters.erase(remote); validRouters.erase(remote);
llarp::LogInfo("Session to ", remote, " fully closed"); llarp::LogInfo("Session to ", remote, " fully closed");
@ -966,9 +972,8 @@ namespace llarp
job->valid = false; job->valid = false;
job->hook = nullptr; job->hook = nullptr;
job->nodedb = nodedb; job->nodedb = _nodedb;
job->logic = logic; job->logic = _logic;
// job->crypto = crypto.get(); // we already have this
job->cryptoworker = tp; job->cryptoworker = tp;
job->diskworker = disk; job->diskworker = disk;
if(rc.IsPublicRouter()) if(rc.IsPublicRouter())
@ -984,7 +989,7 @@ namespace llarp
{ {
if(_running || _stopping) if(_running || _stopping)
return false; return false;
this->nodedb = nodedb; this->_nodedb = nodedb;
if(enableRPCServer) if(enableRPCServer)
{ {
@ -1066,7 +1071,7 @@ namespace llarp
a); a);
} }
llarp::LogInfo("Signing rc..."); llarp::LogInfo("Signing rc...");
if(!_rc.Sign(crypto.get(), identity)) if(!_rc.Sign(crypto(), identity))
{ {
llarp::LogError("failed to sign rc"); llarp::LogError("failed to sign rc");
return false; return false;
@ -1083,7 +1088,7 @@ namespace llarp
llarp::LogInfo("starting outbound ", outboundLinks.size(), " links"); llarp::LogInfo("starting outbound ", outboundLinks.size(), " links");
for(const auto &link : outboundLinks) for(const auto &link : outboundLinks)
{ {
if(!link->Start(logic)) if(!link->Start(_logic))
{ {
llarp::LogWarn("outbound link '", link->Name(), "' failed to start"); llarp::LogWarn("outbound link '", link->Name(), "' failed to start");
return false; return false;
@ -1095,7 +1100,7 @@ namespace llarp
// start links // start links
for(const auto &link : inboundLinks) for(const auto &link : inboundLinks)
{ {
if(link->Start(logic)) if(link->Start(_logic))
{ {
llarp::LogDebug("Link ", link->Name(), " started"); llarp::LogDebug("Link ", link->Name(), " started");
IBLinksStarted++; IBLinksStarted++;
@ -1119,11 +1124,11 @@ namespace llarp
{ {
// we are a client // we are a client
// regenerate keys and resign rc before everything else // regenerate keys and resign rc before everything else
crypto->identity_keygen(identity); crypto()->identity_keygen(identity);
crypto->encryption_keygen(encryption); crypto()->encryption_keygen(encryption);
_rc.pubkey = llarp::seckey_topublic(identity); _rc.pubkey = llarp::seckey_topublic(identity);
_rc.enckey = llarp::seckey_topublic(encryption); _rc.enckey = llarp::seckey_topublic(encryption);
if(!_rc.Sign(crypto.get(), identity)) if(!_rc.Sign(crypto(), identity))
{ {
llarp::LogError("failed to regenerate keys and sign RC"); llarp::LogError("failed to regenerate keys and sign RC");
return false; return false;
@ -1148,7 +1153,7 @@ namespace llarp
llarp::LogError("Failed to start hidden service context"); llarp::LogError("Failed to start hidden service context");
return false; return false;
} }
llarp_dht_context_start(dht, pubkey()); llarp_dht_context_start(dht(), pubkey());
ScheduleTicker(1000); ScheduleTicker(1000);
_running.store(true); _running.store(true);
return _running; return _running;
@ -1166,7 +1171,7 @@ namespace llarp
{ {
Router *self = static_cast< Router * >(u); Router *self = static_cast< Router * >(u);
self->StopLinks(); self->StopLinks();
self->logic->call_later({200, self, &RouterAfterStopLinks}); self->_logic->call_later({200, self, &RouterAfterStopLinks});
} }
void void
@ -1271,7 +1276,7 @@ namespace llarp
exitContext.Stop(); exitContext.Stop();
if(rpcServer) if(rpcServer)
rpcServer->Stop(); rpcServer->Stop();
logic->call_later({200, this, &RouterAfterStopIssued}); _logic->call_later({200, this, &RouterAfterStopIssued});
} }
bool bool
@ -1286,7 +1291,7 @@ namespace llarp
int wanted = want; int wanted = want;
Router *self = this; Router *self = this;
self->nodedb->visit( self->nodedb()->visit(
[self, &want](const llarp::RouterContact &other) -> bool { [self, &want](const llarp::RouterContact &other) -> bool {
// check if we really want to // check if we really want to
if(other.ExpiresSoon(self->Now(), 30000)) if(other.ExpiresSoon(self->Now(), 30000))
@ -1312,7 +1317,7 @@ namespace llarp
{ {
llarp::LogInfo("accepting transit traffic"); llarp::LogInfo("accepting transit traffic");
paths.AllowTransit(); paths.AllowTransit();
llarp_dht_allow_transit(dht); llarp_dht_allow_transit(dht());
return exitContext.AddExitEndpoint("default-connectivity", netConfig); return exitContext.AddExitEndpoint("default-connectivity", netConfig);
} }
@ -1643,7 +1648,7 @@ namespace llarp
self->bootstrapRCList.pop_back(); self->bootstrapRCList.pop_back();
return; return;
} }
if(rc.Verify(self->crypto.get(), self->Now())) if(rc.Verify(self->crypto(), self->Now()))
{ {
llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey)); llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey));
} }

@ -65,7 +65,55 @@ namespace llarp
} }
}; };
struct Router struct AbstractRouter
{
virtual ~AbstractRouter() = 0;
virtual Logic *
logic() const = 0;
virtual llarp_dht_context *
dht() const = 0;
virtual Crypto *
crypto() const = 0;
virtual llarp_nodedb *
nodedb() const = 0;
virtual const path::PathContext &
pathContext() const = 0;
virtual path::PathContext &
pathContext() = 0;
virtual const llarp::RouterContact &
rc() const = 0;
virtual const byte_t *
pubkey() const = 0;
virtual llarp_time_t
Now() const = 0;
virtual bool
SendToOrQueue(const llarp::RouterID &remote,
const llarp::ILinkMessage *msg) = 0;
virtual void
PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until) = 0;
virtual bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h, PathID_t rxid) = 0;
virtual void
HandleDHTLookupForExplore(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results) = 0;
};
struct Router final : public AbstractRouter
{ {
bool ready; bool ready;
// transient iwp encryption key // transient iwp encryption key
@ -92,8 +140,44 @@ namespace llarp
/// should we obey the service node whitelist? /// should we obey the service node whitelist?
bool whitelistRouters = false; bool whitelistRouters = false;
Logic *
logic() const override
{
return _logic;
}
llarp_dht_context *
dht() const override
{
return _dht;
}
Crypto *
crypto() const override
{
return _crypto.get();
}
llarp_nodedb *
nodedb() const override
{
return _nodedb;
}
const path::PathContext &
pathContext() const override
{
return paths;
}
path::PathContext &
pathContext() override
{
return paths;
}
const llarp::RouterContact & const llarp::RouterContact &
rc() const rc() const override
{ {
return _rc; return _rc;
} }
@ -105,20 +189,19 @@ namespace llarp
llarp_ev_loop *netloop; llarp_ev_loop *netloop;
llarp_threadpool *tp; llarp_threadpool *tp;
llarp::Logic *logic; Logic *_logic;
std::unique_ptr< llarp::Crypto > crypto; std::unique_ptr< Crypto > _crypto;
llarp::path::PathContext paths; path::PathContext paths;
llarp::exit::Context exitContext; exit::Context exitContext;
llarp::SecretKey identity; SecretKey identity;
llarp::SecretKey encryption; SecretKey encryption;
llarp_threadpool *disk; llarp_threadpool *disk;
llarp_dht_context *dht = nullptr; llarp_dht_context *_dht = nullptr;
llarp_nodedb *_nodedb;
bool bool
Sign(Signature &sig, const llarp_buffer_t &buf) const; Sign(Signature &sig, const llarp_buffer_t &buf) const;
llarp_nodedb *nodedb;
// buffer for serializing link messages // buffer for serializing link messages
std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer; std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer;
@ -276,7 +359,8 @@ namespace llarp
StopLinks(); StopLinks();
void void
PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until); PersistSessionUntil(const llarp::RouterID &remote,
llarp_time_t until) override;
bool bool
EnsureIdentity(); EnsureIdentity();
@ -291,7 +375,7 @@ namespace llarp
SaveRC(); SaveRC();
const byte_t * const byte_t *
pubkey() const pubkey() const override
{ {
return llarp::seckey_topublic(identity); return llarp::seckey_topublic(identity);
} }
@ -322,7 +406,7 @@ namespace llarp
/// MUST be called in the logic thread /// MUST be called in the logic thread
bool bool
SendToOrQueue(const llarp::RouterID &remote, SendToOrQueue(const llarp::RouterID &remote,
const llarp::ILinkMessage *msg); const llarp::ILinkMessage *msg) override;
/// sendto or drop /// sendto or drop
void void
@ -349,7 +433,7 @@ namespace llarp
void void
HandleDHTLookupForExplore( HandleDHTLookupForExplore(
llarp::RouterID remote, llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results); const std::vector< llarp::RouterContact > &results) override;
void void
ForEachPeer( ForEachPeer(
@ -379,7 +463,7 @@ namespace llarp
/// get time from event loop /// get time from event loop
llarp_time_t llarp_time_t
Now() const Now() const override
{ {
return llarp_ev_loop_time_now_ms(netloop); return llarp_ev_loop_time_now_ms(netloop);
} }
@ -396,7 +480,8 @@ namespace llarp
/// return false /// return false
bool bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf, ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h, PathID_t rxid); routing::IMessageHandler *h,
PathID_t rxid) override;
void void
ConnectToRandomRouters(int N); ConnectToRandomRouters(int N);

@ -332,7 +332,7 @@ namespace llarp
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
saddr.sin_family = AF_INET; saddr.sin_family = AF_INET;
saddr.sin_port = htons(port); saddr.sin_port = htons(port);
return _handler.ServeAsync(router->netloop, router->logic, return _handler.ServeAsync(router->netloop, router->logic(),
(const sockaddr*)&saddr); (const sockaddr*)&saddr);
} }
}; };

@ -82,7 +82,7 @@ namespace llarp
++itr; ++itr;
} }
} }
m_Router->nodedb->visit([&](const RouterContact &rc) -> bool { m_Router->nodedb()->visit([&](const RouterContact &rc) -> bool {
if(rc.IsExpired(now)) if(rc.IsExpired(now))
getFirstEndpoint()->LookupRouterAnon(rc.pubkey); getFirstEndpoint()->LookupRouterAnon(rc.pubkey);
return true; return true;

@ -18,7 +18,7 @@ namespace llarp
{ {
Endpoint::Endpoint(const std::string& name, llarp::Router* r, Endpoint::Endpoint(const std::string& name, llarp::Router* r,
Context* parent) Context* parent)
: path::Builder(r, r->dht, 6, DEFAULT_HOP_LENGTH) : path::Builder(r, r->dht(), 6, DEFAULT_HOP_LENGTH)
, context(parent) , context(parent)
, m_Router(r) , m_Router(r)
, m_Name(name) , m_Name(name)
@ -118,7 +118,7 @@ namespace llarp
return; return;
} }
m_IntroSet.topic = m_Tag; m_IntroSet.topic = m_Tag;
if(!m_Identity.SignIntroSet(m_IntroSet, m_Router->crypto.get(), now)) if(!m_Identity.SignIntroSet(m_IntroSet, m_Router->crypto(), now))
{ {
llarp::LogWarn("failed to sign introset for endpoint ", Name()); llarp::LogWarn("failed to sign introset for endpoint ", Name());
return; return;
@ -360,7 +360,7 @@ namespace llarp
bool bool
Endpoint::HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg) Endpoint::HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg)
{ {
auto crypto = m_Router->crypto.get(); auto crypto = m_Router->crypto();
std::set< IntroSet > remote; std::set< IntroSet > remote;
for(const auto& introset : msg->I) for(const auto& introset : msg->I)
{ {
@ -500,7 +500,7 @@ namespace llarp
bool bool
Endpoint::LoadKeyFile() Endpoint::LoadKeyFile()
{ {
auto crypto = m_Router->crypto.get(); auto crypto = m_Router->crypto();
if(m_Keyfile.size()) if(m_Keyfile.size())
{ {
if(!m_Identity.EnsureKeys(m_Keyfile, crypto)) if(!m_Identity.EnsureKeys(m_Keyfile, crypto))
@ -765,10 +765,10 @@ namespace llarp
if(itr == m_PendingRouters.end()) if(itr == m_PendingRouters.end())
return false; return false;
llarp_async_verify_rc* job = new llarp_async_verify_rc; llarp_async_verify_rc* job = new llarp_async_verify_rc;
job->nodedb = m_Router->nodedb; job->nodedb = m_Router->nodedb();
job->cryptoworker = m_Router->tp; job->cryptoworker = m_Router->tp;
job->diskworker = m_Router->disk; job->diskworker = m_Router->disk;
job->logic = m_Router->logic; job->logic = m_Router->logic();
job->hook = nullptr; job->hook = nullptr;
job->rc = msg->R[0]; job->rc = msg->R[0];
llarp_nodedb_async_verify(job); llarp_nodedb_async_verify(job);
@ -783,7 +783,7 @@ namespace llarp
if(router.IsZero()) if(router.IsZero())
return; return;
RouterContact rc; RouterContact rc;
if(!m_Router->nodedb->Get(router, rc)) if(!m_Router->nodedb()->Get(router, rc))
{ {
LookupRouterAnon(router); LookupRouterAnon(router);
} }
@ -1051,7 +1051,7 @@ namespace llarp
Endpoint::OutboundContext::OutboundContext(const IntroSet& introset, Endpoint::OutboundContext::OutboundContext(const IntroSet& introset,
Endpoint* parent) Endpoint* parent)
: path::Builder(parent->m_Router, parent->m_Router->dht, 3, : path::Builder(parent->m_Router, parent->m_Router->dht(), 3,
DEFAULT_HOP_LENGTH) DEFAULT_HOP_LENGTH)
, SendContext(introset.A, {}, this, parent) , SendContext(introset.A, {}, this, parent)
, currentIntroSet(introset) , currentIntroSet(introset)
@ -1242,7 +1242,7 @@ namespace llarp
f.C.Zero(); f.C.Zero();
transfer.Y.Randomize(); transfer.Y.Randomize();
transfer.P = remoteIntro.pathID; transfer.P = remoteIntro.pathID;
if(!f.EncryptAndSign(Router()->crypto.get(), m, K, m_Identity)) if(!f.EncryptAndSign(Router()->crypto(), m, K, m_Identity))
{ {
llarp::LogError("failed to encrypt and sign"); llarp::LogError("failed to encrypt and sign");
return false; return false;
@ -1281,7 +1281,7 @@ namespace llarp
Endpoint::OutboundContext::BuildOneAlignedTo(const RouterID& remote) Endpoint::OutboundContext::BuildOneAlignedTo(const RouterID& remote)
{ {
llarp::LogInfo(Name(), " building path to ", remote); llarp::LogInfo(Name(), " building path to ", remote);
auto nodedb = m_Endpoint->Router()->nodedb; auto nodedb = m_Endpoint->Router()->nodedb();
std::vector< RouterContact > hops; std::vector< RouterContact > hops;
hops.resize(numHops); hops.resize(numHops);
for(size_t hop = 0; hop < numHops; ++hop) for(size_t hop = 0; hop < numHops; ++hop)
@ -1736,7 +1736,7 @@ namespace llarp
Endpoint::SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, Endpoint::SendContext::EncryptAndSendTo(const llarp_buffer_t& payload,
ProtocolType t) ProtocolType t)
{ {
auto crypto = m_Endpoint->Router()->crypto.get(); auto crypto = m_Endpoint->Router()->crypto();
SharedSecret shared; SharedSecret shared;
routing::PathTransferMessage msg; routing::PathTransferMessage msg;
ProtocolFrame& f = msg.T; ProtocolFrame& f = msg.T;
@ -1802,19 +1802,19 @@ namespace llarp
llarp::Logic* llarp::Logic*
Endpoint::RouterLogic() Endpoint::RouterLogic()
{ {
return m_Router->logic; return m_Router->logic();
} }
llarp::Logic* llarp::Logic*
Endpoint::EndpointLogic() Endpoint::EndpointLogic()
{ {
return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic; return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic();
} }
llarp::Crypto* llarp::Crypto*
Endpoint::Crypto() Endpoint::Crypto()
{ {
return m_Router->crypto.get(); return m_Router->crypto();
} }
llarp_threadpool* llarp_threadpool*

@ -1,6 +1,7 @@
#include <service/lookup.hpp> #include <service/lookup.hpp>
#include <path/path.hpp> #include <path/path.hpp>
#include <router/router.hpp>
#include <service/endpoint.hpp> #include <service/endpoint.hpp>
#include <util/time.hpp> #include <util/time.hpp>
@ -17,8 +18,7 @@ namespace llarp
} }
bool bool
IServiceLookup::SendRequestViaPath(llarp::path::Path *path, IServiceLookup::SendRequestViaPath(path::Path *path, Router *r)
llarp::Router *r)
{ {
auto msg = BuildRequestMessage(); auto msg = BuildRequestMessage();
if(!msg) if(!msg)

@ -33,7 +33,7 @@ namespace llarp
MOCK_CONST_METHOD0(Crypto, llarp::Crypto*()); MOCK_CONST_METHOD0(Crypto, llarp::Crypto*());
MOCK_CONST_METHOD0(GetRouter, llarp::Router*()); MOCK_CONST_METHOD0(GetRouter, llarp::AbstractRouter*());
MOCK_CONST_METHOD0(OurKey, const dht::Key_t&()); MOCK_CONST_METHOD0(OurKey, const dht::Key_t&());

Loading…
Cancel
Save