llarp_time_t is now using std::chrono

pull/1128/head
Jeff Becker 4 years ago
parent f4520ac920
commit d2d109e92c
No known key found for this signature in database
GPG Key ID: F357B3B42F6F9B05

@ -1,10 +1,11 @@
#ifndef LLARP_LINK_LAYER_HPP #ifndef LLARP_LINK_LAYER_HPP
#define LLARP_LINK_LAYER_HPP #define LLARP_LINK_LAYER_HPP
#include <util/types.hpp> #include <util/types.hpp>
#include <util/time.hpp>
#include <cstdlib> #include <cstdlib>
constexpr size_t MAX_LINK_MSG_SIZE = 8192; constexpr size_t MAX_LINK_MSG_SIZE = 8192;
constexpr llarp_time_t DefaultLinkSessionLifetime = 60 * 1000; static constexpr auto DefaultLinkSessionLifetime = 1min;
constexpr size_t MaxSendQueueSize = 1024; constexpr size_t MaxSendQueueSize = 1024;
#endif #endif

@ -4,6 +4,7 @@
#include <cstddef> #include <cstddef>
#include <util/types.hpp> #include <util/types.hpp>
#include <util/time.hpp>
namespace llarp namespace llarp
{ {
@ -16,15 +17,14 @@ namespace llarp
/// pad messages to the nearest this many bytes /// pad messages to the nearest this many bytes
constexpr std::size_t pad_size = 128; constexpr std::size_t pad_size = 128;
/// default path lifetime in ms /// default path lifetime in ms
constexpr llarp_time_t default_lifetime = 10 * 60 * 1000; static constexpr auto default_lifetime = 10min;
/// after this many ms a path build times out /// after this many ms a path build times out
constexpr llarp_time_t build_timeout = 30000; static constexpr auto build_timeout = 30s;
/// measure latency every this interval ms /// measure latency every this interval ms
constexpr llarp_time_t latency_interval = 5000; static constexpr auto latency_interval = 5s;
/// if a path is inactive for this amount of time it's dead /// if a path is inactive for this amount of time it's dead
constexpr llarp_time_t alive_timeout = 60000; static constexpr auto alive_timeout = 30s;
} // namespace path } // namespace path
} // namespace llarp } // namespace llarp

@ -327,7 +327,7 @@ namespace llarp
if(num) if(num)
Explore(num); Explore(num);
router->logic()->call_later( router->logic()->call_later(
interval, std::chrono::milliseconds(interval),
std::bind(&llarp::dht::Context::handle_explore_timer, this, std::bind(&llarp::dht::Context::handle_explore_timer, this,
interval)); interval));
} }
@ -499,7 +499,7 @@ namespace llarp
router->logic()->call_later( router->logic()->call_later(
exploreInterval, exploreInterval,
std::bind(&llarp::dht::Context::handle_explore_timer, this, std::bind(&llarp::dht::Context::handle_explore_timer, this,
exploreInterval)); exploreInterval.count()));
// start cleanup timer // start cleanup timer
ScheduleCleanupTimer(); ScheduleCleanupTimer();
} }
@ -508,7 +508,7 @@ namespace llarp
Context::ScheduleCleanupTimer() Context::ScheduleCleanupTimer()
{ {
router->logic()->call_later( router->logic()->call_later(
1000, 1s,
std::bind(&llarp::dht::Context::handle_cleaner_timer, this, 1000)); std::bind(&llarp::dht::Context::handle_cleaner_timer, this, 1000));
} }
@ -519,7 +519,7 @@ namespace llarp
m.msgs.emplace_back(msg); m.msgs.emplace_back(msg);
router->SendToOrQueue(peer, &m); router->SendToOrQueue(peer, &m);
auto now = Now(); auto now = Now();
router->PersistSessionUntil(peer, now + 60000); router->PersistSessionUntil(peer, now + 1min);
} }
bool bool
@ -595,7 +595,7 @@ namespace llarp
TXOwner peer(askpeer, ++ids); TXOwner peer(askpeer, ++ids);
_pendingIntrosetLookups.NewTX( _pendingIntrosetLookups.NewTX(
peer, asker, addr, peer, asker, addr,
new ServiceAddressLookup(asker, addr, this, 0, handler), 1000); new ServiceAddressLookup(asker, addr, this, 0, handler), 1s);
} }
bool bool

@ -35,7 +35,7 @@ llarp_dht_allow_transit(llarp_dht_context *ctx)
void void
llarp_dht_context_start(struct llarp_dht_context *ctx, const byte_t *key) llarp_dht_context_start(struct llarp_dht_context *ctx, const byte_t *key)
{ {
ctx->impl->Init(llarp::dht::Key_t(key), ctx->parent, 2000); ctx->impl->Init(llarp::dht::Key_t(key), ctx->parent, 2s);
} }
void void

@ -42,7 +42,7 @@ namespace llarp
std::transform( std::transform(
timeouts.begin(), timeouts.end(), std::back_inserter(timeoutsObjs), timeouts.begin(), timeouts.end(), std::back_inserter(timeoutsObjs),
[](const auto& item) -> util::StatusObject { [](const auto& item) -> util::StatusObject {
return util::StatusObject{{"time", item.second}, return util::StatusObject{{"time", item.second.count()},
{"target", item.first.ToString()}}; {"target", item.first.ToString()}};
}); });
obj["timeouts"] = timeoutsObjs; obj["timeouts"] = timeoutsObjs;
@ -71,7 +71,7 @@ namespace llarp
void void
NewTX(const TXOwner& askpeer, const TXOwner& whoasked, const K& k, NewTX(const TXOwner& askpeer, const TXOwner& whoasked, const K& k,
TX< K, V >* t, llarp_time_t requestTimeoutMS = 15000); TX< K, V >* t, llarp_time_t requestTimeoutMS = 15s);
/// mark tx as not fond /// mark tx as not fond
void void

@ -72,7 +72,7 @@ namespace llarp
{ {
struct WriteBuffer struct WriteBuffer
{ {
llarp_time_t timestamp = 0; llarp_time_t timestamp = 0s;
size_t bufsz; size_t bufsz;
byte_t buf[EV_WRITE_BUF_SZ] = {0}; byte_t buf[EV_WRITE_BUF_SZ] = {0};
@ -278,7 +278,7 @@ namespace llarp
{ {
struct WriteBuffer struct WriteBuffer
{ {
llarp_time_t timestamp = 0; llarp_time_t timestamp = 0s;
size_t bufsz; size_t bufsz;
byte_t buf[EV_WRITE_BUF_SZ]; byte_t buf[EV_WRITE_BUF_SZ];
@ -345,7 +345,7 @@ namespace llarp
llarp::util::CoDelQueue< WriteBuffer, WriteBuffer::GetTime, llarp::util::CoDelQueue< WriteBuffer, WriteBuffer::GetTime,
WriteBuffer::PutTime, WriteBuffer::Compare, WriteBuffer::PutTime, WriteBuffer::Compare,
WriteBuffer::GetNow, llarp::util::NullMutex, WriteBuffer::GetNow, llarp::util::NullMutex,
llarp::util::NullLock, 5, 100, 1024 >; llarp::util::NullLock >;
using LosslessWriteQueue_t = std::deque< WriteBuffer >; using LosslessWriteQueue_t = std::deque< WriteBuffer >;

@ -914,7 +914,7 @@ namespace libuv
newTimer->data = (void*)timer_data; newTimer->data = (void*)timer_data;
uv_timer_init(&m_Impl, newTimer); uv_timer_init(&m_Impl, newTimer);
uv_timer_start(newTimer, &OnUVTimer, job.delay_ms, 0); uv_timer_start(newTimer, &OnUVTimer, job.delay_ms.count(), 0);
} }
} }

@ -41,7 +41,7 @@ namespace llarp
{"ip", m_IP.ToString()}, {"ip", m_IP.ToString()},
{"txRate", m_TxRate}, {"txRate", m_TxRate},
{"rxRate", m_RxRate}, {"rxRate", m_RxRate},
{"createdAt", createdAt}, {"createdAt", createdAt.count()},
{"exiting", !m_RewriteSource}, {"exiting", !m_RewriteSource},
{"looksDead", LooksDead(now)}, {"looksDead", LooksDead(now)},
{"expiresSoon", ExpiresSoon(now)}, {"expiresSoon", ExpiresSoon(now)},
@ -96,11 +96,11 @@ namespace llarp
if(!path) if(!path)
return true; return true;
auto lastPing = path->LastRemoteActivityAt(); auto lastPing = path->LastRemoteActivityAt();
if(lastPing == 0 || (now > lastPing && now - lastPing > timeout)) if(lastPing == 0s || (now > lastPing && now - lastPing > timeout))
return now > m_LastActive && now - m_LastActive > timeout; return now > m_LastActive && now - m_LastActive > timeout;
else if(lastPing) // NOLINT else if(lastPing > 0s) // NOLINT
return now > lastPing && now - lastPing > timeout; return now > lastPing && now - lastPing > timeout;
return lastPing > 0; return lastPing > 0s;
} }
bool bool

@ -42,11 +42,11 @@ namespace llarp
IsExpired(llarp_time_t now) const; IsExpired(llarp_time_t now) const;
bool bool
ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5000) const; ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5s) const;
/// return true if this endpoint looks dead right now /// return true if this endpoint looks dead right now
bool bool
LooksDead(llarp_time_t now, llarp_time_t timeout = 10000) const; LooksDead(llarp_time_t now, llarp_time_t timeout = 10s) const;
/// tick ourself, reset tx/rx rates /// tick ourself, reset tx/rx rates
void void

@ -18,7 +18,7 @@ namespace llarp
llarp::PubKey I; llarp::PubKey I;
uint64_t T{0}; uint64_t T{0};
std::vector< llarp::exit::Policy > W; std::vector< llarp::exit::Policy > W;
llarp_time_t X{0}; uint64_t X{0};
llarp::Signature Z; llarp::Signature Z;
ObtainExitMessage() : IMessage() ObtainExitMessage() : IMessage()

@ -38,7 +38,7 @@ namespace llarp
BaseSession::ExtractStatus() const BaseSession::ExtractStatus() const
{ {
auto obj = path::Builder::ExtractStatus(); auto obj = path::Builder::ExtractStatus();
obj["lastExitUse"] = m_LastUse; obj["lastExitUse"] = m_LastUse.count();
auto pub = m_ExitIdentity.toPublic(); auto pub = m_ExitIdentity.toPublic();
obj["exitIdentity"] = pub.ToString(); obj["exitIdentity"] = pub.ToString();
return obj; return obj;
@ -55,7 +55,7 @@ namespace llarp
{ {
const size_t expect = (1 + (numPaths / 2)); const size_t expect = (1 + (numPaths / 2));
// check 30 seconds into the future and see if we need more paths // check 30 seconds into the future and see if we need more paths
const llarp_time_t future = now + (30 * 1000) + buildIntervalLimit; const llarp_time_t future = now + 30s + buildIntervalLimit;
return NumPathsExistingAt(future) < expect && !BuildCooldownHit(now); return NumPathsExistingAt(future) < expect && !BuildCooldownHit(now);
} }
@ -91,7 +91,7 @@ namespace llarp
bool bool
BaseSession::CheckPathDead(path::Path_ptr, llarp_time_t dlt) BaseSession::CheckPathDead(path::Path_ptr, llarp_time_t dlt)
{ {
return dlt >= 10000; return dlt >= 10s;
} }
void void
@ -127,7 +127,7 @@ namespace llarp
bool bool
BaseSession::HandleGotExit(llarp::path::Path_ptr p, llarp_time_t b) BaseSession::HandleGotExit(llarp::path::Path_ptr p, llarp_time_t b)
{ {
if(b == 0) if(b == 0s)
{ {
llarp::LogInfo("obtained an exit via ", p->Endpoint()); llarp::LogInfo("obtained an exit via ", p->Endpoint());
CallPendingCallbacks(true); CallPendingCallbacks(true);

@ -19,12 +19,13 @@ namespace llarp
using SessionReadyFunc = std::function< void(BaseSession_ptr) >; using SessionReadyFunc = std::function< void(BaseSession_ptr) >;
static constexpr auto LifeSpan = path::default_lifetime;
/// a persisting exit session with an exit router /// a persisting exit session with an exit router
struct BaseSession : public llarp::path::Builder, struct BaseSession : public llarp::path::Builder,
public std::enable_shared_from_this< BaseSession > public std::enable_shared_from_this< BaseSession >
{ {
static constexpr size_t MaxUpstreamQueueLength = 256; static constexpr size_t MaxUpstreamQueueLength = 256;
static constexpr llarp_time_t LifeSpan = 60 * 10 * 1000;
BaseSession(const llarp::RouterID& exitRouter, BaseSession(const llarp::RouterID& exitRouter,
std::function< bool(const llarp_buffer_t&) > writepkt, std::function< bool(const llarp_buffer_t&) > writepkt,

@ -180,7 +180,7 @@ namespace llarp
using PacketQueue_t = using PacketQueue_t =
util::CoDelQueue< Pkt_t, Pkt_t::GetTime, Pkt_t::PutTime, util::CoDelQueue< Pkt_t, Pkt_t::GetTime, Pkt_t::PutTime,
Pkt_t::CompareOrder, Pkt_t::GetNow, util::NullMutex, Pkt_t::CompareOrder, Pkt_t::GetNow, util::NullMutex,
util::NullLock, 5, 100, 1024 >; util::NullLock >;
/// internet to llarp packet queue /// internet to llarp packet queue
PacketQueue_t m_InetToNetwork; PacketQueue_t m_InetToNetwork;

@ -33,7 +33,7 @@ namespace llarp
bool bool
TunEndpoint::ShouldFlushNow(llarp_time_t now) const TunEndpoint::ShouldFlushNow(llarp_time_t now) const
{ {
static constexpr llarp_time_t FlushInterval = 25; static constexpr auto FlushInterval = 25ms;
return now >= m_LastFlushAt + FlushInterval; return now >= m_LastFlushAt + FlushInterval;
} }
@ -88,7 +88,7 @@ namespace llarp
util::StatusObject ips{}; util::StatusObject ips{};
for(const auto &item : m_IPActivity) for(const auto &item : m_IPActivity)
{ {
util::StatusObject ipObj{{"lastActive", item.second}}; util::StatusObject ipObj{{"lastActive", item.second.count()}};
std::string remoteStr; std::string remoteStr;
AlignedBuffer< 32 > addr = m_IPToAddr.at(item.first); AlignedBuffer< 32 > addr = m_IPToAddr.at(item.first);
if(m_SNodes.at(addr)) if(m_SNodes.at(addr))
@ -499,7 +499,7 @@ namespace llarp
SendDNSReply(addr, ctx, replyMsg, reply, false, SendDNSReply(addr, ctx, replyMsg, reply, false,
isV6 || !isV4); isV6 || !isV4);
}, },
2000); 2s);
} }
} }
else if(addr.FromString(qname, ".snode")) else if(addr.FromString(qname, ".snode"))
@ -975,7 +975,7 @@ namespace llarp
// we are full // we are full
// expire least active ip // expire least active ip
// TODO: prevent DoS // TODO: prevent DoS
std::pair< huint128_t, llarp_time_t > oldest = {huint128_t{0}, 0}; std::pair< huint128_t, llarp_time_t > oldest = {huint128_t{0}, 0s};
// find oldest entry // find oldest entry
auto itr = m_IPActivity.begin(); auto itr = m_IPActivity.begin();
@ -1019,7 +1019,7 @@ namespace llarp
void void
TunEndpoint::MarkIPActiveForever(huint128_t ip) TunEndpoint::MarkIPActiveForever(huint128_t ip)
{ {
m_IPActivity[ip] = std::numeric_limits< uint64_t >::max(); m_IPActivity[ip] = std::numeric_limits< llarp_time_t >::max();
} }
void void

@ -187,7 +187,7 @@ namespace llarp
bool bool
ShouldFlushNow(llarp_time_t now) const; ShouldFlushNow(llarp_time_t now) const;
llarp_time_t m_LastFlushAt = 0; llarp_time_t m_LastFlushAt = 0s;
using PacketQueue_t = llarp::util::CoDelQueue< using PacketQueue_t = llarp::util::CoDelQueue<
net::IPPacket, net::IPPacket::GetTime, net::IPPacket::PutTime, net::IPPacket, net::IPPacket::GetTime, net::IPPacket::PutTime,
net::IPPacket::CompareOrder, net::IPPacket::GetNow >; net::IPPacket::CompareOrder, net::IPPacket::GetNow >;

@ -46,7 +46,7 @@ namespace llarp
bool bool
OutboundMessage::ShouldFlush(llarp_time_t now) const OutboundMessage::ShouldFlush(llarp_time_t now) const
{ {
return now - m_LastFlush >= Session::TXFlushInterval; return now - m_LastFlush >= TXFlushInterval;
} }
void void
@ -97,7 +97,7 @@ namespace llarp
OutboundMessage::IsTimedOut(const llarp_time_t now) const OutboundMessage::IsTimedOut(const llarp_time_t now) const
{ {
// TODO: make configurable by outbound message deliverer // TODO: make configurable by outbound message deliverer
return now > m_StartedAt && now - m_StartedAt > Session::DeliveryTimeout; return now > m_StartedAt && now - m_StartedAt > DeliveryTimeout;
} }
void void
@ -165,14 +165,13 @@ namespace llarp
bool bool
InboundMessage::ShouldSendACKS(llarp_time_t now) const InboundMessage::ShouldSendACKS(llarp_time_t now) const
{ {
return now > m_LastACKSent + Session::ACKResendInterval; return now > m_LastACKSent + ACKResendInterval;
} }
bool bool
InboundMessage::IsTimedOut(const llarp_time_t now) const InboundMessage::IsTimedOut(const llarp_time_t now) const
{ {
return now > m_LastActiveAt return now > m_LastActiveAt && now - m_LastActiveAt > DeliveryTimeout;
&& now - m_LastActiveAt > Session::DeliveryTimeout;
} }
void void

@ -45,9 +45,9 @@ namespace llarp
uint64_t m_MsgID = 0; uint64_t m_MsgID = 0;
std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks; std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks;
ILinkSession::CompletionHandler m_Completed; ILinkSession::CompletionHandler m_Completed;
llarp_time_t m_LastFlush = 0; llarp_time_t m_LastFlush = 0s;
ShortHash m_Digest; ShortHash m_Digest;
llarp_time_t m_StartedAt = 0; llarp_time_t m_StartedAt = 0s;
ILinkSession::Packet_t ILinkSession::Packet_t
XMIT() const; XMIT() const;
@ -84,8 +84,8 @@ namespace llarp
ILinkSession::Message_t m_Data; ILinkSession::Message_t m_Data;
ShortHash m_Digset; ShortHash m_Digset;
uint64_t m_MsgID = 0; uint64_t m_MsgID = 0;
llarp_time_t m_LastACKSent = 0; llarp_time_t m_LastACKSent = 0s;
llarp_time_t m_LastActiveAt = 0; llarp_time_t m_LastActiveAt = 0s;
std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks; std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks;
void void
@ -117,4 +117,4 @@ namespace llarp
} // namespace iwp } // namespace iwp
} // namespace llarp } // namespace llarp
#endif #endif

@ -320,8 +320,8 @@ namespace llarp
{"rxMsgQueueSize", m_RXMsgs.size()}, {"rxMsgQueueSize", m_RXMsgs.size()},
{"remoteAddr", m_RemoteAddr.ToString()}, {"remoteAddr", m_RemoteAddr.ToString()},
{"remoteRC", m_RemoteRC.ExtractStatus()}, {"remoteRC", m_RemoteRC.ExtractStatus()},
{"created", m_CreatedAt}, {"created", m_CreatedAt.count()},
{"uptime", (now - m_CreatedAt)}}; {"uptime", Time_t(now - m_CreatedAt).count()}};
} }
bool bool
@ -355,7 +355,7 @@ namespace llarp
if(ShouldResetRates(now)) if(ShouldResetRates(now))
{ {
ResetRates(); ResetRates();
m_ResetRatesAt = now + 1000; m_ResetRatesAt = now + 1s;
} }
// remove pending outbound messsages that timed out // remove pending outbound messsages that timed out
// inform waiters // inform waiters

@ -17,24 +17,24 @@ namespace llarp
ILinkSession::Packet_t ILinkSession::Packet_t
CreatePacket(Command cmd, size_t plainsize, size_t min_pad = 16, CreatePacket(Command cmd, size_t plainsize, size_t min_pad = 16,
size_t pad_variance = 16); size_t pad_variance = 16);
/// Time how long we try delivery for
static constexpr auto DeliveryTimeout = 500ms;
/// Time how long we wait to recieve a message
static constexpr auto ReceivalTimeout = (DeliveryTimeout * 8) / 5;
/// How long to keep a replay window for
static constexpr auto ReplayWindow = (ReceivalTimeout * 3) / 2;
/// How often to acks RX messages
static constexpr auto ACKResendInterval = DeliveryTimeout / 2;
/// How often to retransmit TX fragments
static constexpr auto TXFlushInterval = (DeliveryTimeout / 5) * 4;
/// How often we send a keepalive
static constexpr auto PingInterval = 5s;
/// How long we wait for a session to die with no tx from them
static constexpr auto SessionAliveTimeout = PingInterval * 5;
struct Session : public ILinkSession, struct Session : public ILinkSession,
public std::enable_shared_from_this< Session > public std::enable_shared_from_this< Session >
{ {
/// Time how long we try delivery for
static constexpr llarp_time_t DeliveryTimeout = 500;
/// Time how long we wait to recieve a message
static constexpr llarp_time_t ReceivalTimeout = (DeliveryTimeout * 8) / 5;
/// How long to keep a replay window for
static constexpr llarp_time_t ReplayWindow = (ReceivalTimeout * 3) / 2;
/// How often to acks RX messages
static constexpr llarp_time_t ACKResendInterval = DeliveryTimeout / 2;
/// How often to retransmit TX fragments
static constexpr llarp_time_t TXFlushInterval = (DeliveryTimeout / 5) * 4;
/// How often we send a keepalive
static constexpr llarp_time_t PingInterval = 5000;
/// How long we wait for a session to die with no tx from them
static constexpr llarp_time_t SessionAliveTimeout = PingInterval * 5;
/// maximum number of messages we can ack in a multiack /// maximum number of messages we can ack in a multiack
static constexpr std::size_t MaxACKSInMACK = 1024 / sizeof(uint64_t); static constexpr std::size_t MaxACKSInMACK = 1024 / sizeof(uint64_t);
@ -179,14 +179,14 @@ namespace llarp
PubKey m_ExpectedIdent; PubKey m_ExpectedIdent;
PubKey m_RemoteOnionKey; PubKey m_RemoteOnionKey;
llarp_time_t m_LastTX = 0; llarp_time_t m_LastTX = 0s;
llarp_time_t m_LastRX = 0; llarp_time_t m_LastRX = 0s;
// accumulate for periodic rate calculation // accumulate for periodic rate calculation
uint64_t m_TXRate = 0; uint64_t m_TXRate = 0;
uint64_t m_RXRate = 0; uint64_t m_RXRate = 0;
llarp_time_t m_ResetRatesAt = 0; llarp_time_t m_ResetRatesAt = 0s;
uint64_t m_TXID = 0; uint64_t m_TXID = 0;

@ -150,7 +150,7 @@ namespace llarp
m_PersistingSessions[remote] = m_PersistingSessions[remote] =
std::max(until, m_PersistingSessions[remote]); std::max(until, m_PersistingSessions[remote]);
LogDebug("persist session to ", remote, " until ", LogDebug("persist session to ", remote, " until ",
m_PersistingSessions[remote]); m_PersistingSessions[remote].count());
} }
void void

@ -7,7 +7,7 @@
#include <utility> #include <utility>
#include <unordered_set> #include <unordered_set>
constexpr uint64_t LINK_LAYER_TICK_INTERVAL = 100; static constexpr auto LINK_LAYER_TICK_INTERVAL = 100ms;
namespace llarp namespace llarp
{ {
@ -360,8 +360,8 @@ namespace llarp
void void
ILinkLayer::CloseSessionTo(const RouterID& remote) ILinkLayer::CloseSessionTo(const RouterID& remote)
{ {
static constexpr llarp_time_t CloseGraceWindow = 500; static constexpr auto CloseGraceWindow = 500ms;
const auto now = Now(); const auto now = Now();
Lock_t l(m_AuthedLinksMutex); Lock_t l(m_AuthedLinksMutex);
RouterID r = remote; RouterID r = remote;
llarp::LogInfo("Closing all to ", r); llarp::LogInfo("Closing all to ", r);
@ -462,7 +462,7 @@ namespace llarp
} }
void void
ILinkLayer::ScheduleTick(uint64_t interval) ILinkLayer::ScheduleTick(llarp_time_t interval)
{ {
tick_id = tick_id =
m_Logic->call_later(interval, std::bind(&ILinkLayer::OnTick, this)); m_Logic->call_later(interval, std::bind(&ILinkLayer::OnTick, this));

@ -210,7 +210,7 @@ namespace llarp
OnTick(); OnTick();
void void
ScheduleTick(uint64_t interval); ScheduleTick(llarp_time_t interval);
uint32_t tick_id; uint32_t tick_id;
const SecretKey& m_RouterEncSecret; const SecretKey& m_RouterEncSecret;

@ -88,9 +88,9 @@ namespace llarp
return false; return false;
if(!BEncodeWriteDictEntry("i", nextHop, buf)) if(!BEncodeWriteDictEntry("i", nextHop, buf))
return false; return false;
if(lifetime > 10 && lifetime < 600) if(lifetime > 10s && lifetime < path::default_lifetime)
{ {
if(!BEncodeWriteDictInt("i", lifetime, buf)) if(!BEncodeWriteDictInt("i", lifetime.count(), buf))
return false; return false;
} }
if(!BEncodeWriteDictEntry("n", tunnelNonce, buf)) if(!BEncodeWriteDictEntry("n", tunnelNonce, buf))
@ -288,9 +288,9 @@ namespace llarp
// persist sessions to upstream and downstream routers until the commit // persist sessions to upstream and downstream routers until the commit
// ends // ends
self->context->Router()->PersistSessionUntil( self->context->Router()->PersistSessionUntil(
self->hop->info.downstream, self->hop->ExpireTime() + 10000); self->hop->info.downstream, self->hop->ExpireTime() + 10s);
self->context->Router()->PersistSessionUntil( self->context->Router()->PersistSessionUntil(
self->hop->info.upstream, self->hop->ExpireTime() + 10000); self->hop->info.upstream, self->hop->ExpireTime() + 10s);
// put hop // put hop
self->context->PutTransitHop(self->hop); self->context->PutTransitHop(self->hop);
// if we have an rc for this hop... // if we have an rc for this hop...
@ -333,7 +333,7 @@ namespace llarp
{ {
// persist session to downstream until path expiration // persist session to downstream until path expiration
self->context->Router()->PersistSessionUntil( self->context->Router()->PersistSessionUntil(
self->hop->info.downstream, self->hop->ExpireTime() + 10000); self->hop->info.downstream, self->hop->ExpireTime() + 10s);
// put hop // put hop
self->context->PutTransitHop(self->hop); self->context->PutTransitHop(self->hop);
} }
@ -401,15 +401,16 @@ namespace llarp
if(self->record.work && self->record.work->IsValid(now)) if(self->record.work && self->record.work->IsValid(now))
{ {
llarp::LogDebug("LRCM extended lifetime by ", llarp::LogDebug("LRCM extended lifetime by ",
self->record.work->extendedLifetime, " seconds for ", self->record.work->extendedLifetime.count(), " for ",
info); info);
self->hop->lifetime += 1000 * self->record.work->extendedLifetime; self->hop->lifetime += self->record.work->extendedLifetime;
} }
else if(self->record.lifetime < 600 && self->record.lifetime > 10) else if(self->record.lifetime < path::default_lifetime
&& self->record.lifetime > 10s)
{ {
self->hop->lifetime = self->record.lifetime; self->hop->lifetime = self->record.lifetime;
llarp::LogDebug("LRCM short lifespan set to ", self->hop->lifetime, llarp::LogDebug("LRCM short lifespan set to ",
" seconds for ", info); self->hop->lifetime.count(), " ms for ", info);
} }
// TODO: check if we really want to accept it // TODO: check if we really want to accept it

@ -29,8 +29,8 @@ namespace llarp
std::unique_ptr< RouterContact > nextRC; std::unique_ptr< RouterContact > nextRC;
std::unique_ptr< PoW > work; std::unique_ptr< PoW > work;
uint64_t version = 0; uint64_t version = 0;
uint64_t lifetime = 0; llarp_time_t lifetime = 0s;
bool bool
BDecode(llarp_buffer_t *buf); BDecode(llarp_buffer_t *buf);

@ -266,9 +266,9 @@ llarp_nodedb::SaveAll()
bool bool
llarp_nodedb::ShouldSaveToDisk(llarp_time_t now) const llarp_nodedb::ShouldSaveToDisk(llarp_time_t now) const
{ {
if(now == 0) if(now == 0s)
now = llarp::time_now_ms(); now = llarp::time_now_ms();
return m_NextSaveToDisk > 0 && m_NextSaveToDisk <= now; return m_NextSaveToDisk > 0s && m_NextSaveToDisk <= now;
} }
void void

@ -30,14 +30,6 @@ namespace llarp
} }
} // namespace llarp } // namespace llarp
struct llarp_nodedb_iter
{
void *user;
llarp::RouterContact *rc;
size_t index;
bool (*visit)(struct llarp_nodedb_iter *);
};
struct llarp_nodedb struct llarp_nodedb
{ {
explicit llarp_nodedb(std::shared_ptr< llarp::thread::ThreadPool > diskworker, explicit llarp_nodedb(std::shared_ptr< llarp::thread::ThreadPool > diskworker,
@ -55,9 +47,9 @@ struct llarp_nodedb
std::shared_ptr< llarp::thread::ThreadPool > disk; std::shared_ptr< llarp::thread::ThreadPool > disk;
mutable llarp::util::Mutex access; // protects entries mutable llarp::util::Mutex access; // protects entries
/// time for next save to disk event, 0 if never happened /// time for next save to disk event, 0 if never happened
llarp_time_t m_NextSaveToDisk = 0; llarp_time_t m_NextSaveToDisk = 0s;
/// how often to save to disk /// how often to save to disk
const llarp_time_t m_SaveInterval = 60 * 5 * 1000; const llarp_time_t m_SaveInterval = 5min;
struct NetDBEntry struct NetDBEntry
{ {
@ -82,7 +74,7 @@ struct llarp_nodedb
/// return true if we should save our nodedb to disk /// return true if we should save our nodedb to disk
bool bool
ShouldSaveToDisk(llarp_time_t now = 0) const; ShouldSaveToDisk(llarp_time_t now = 0s) const;
bool bool
Remove(const llarp::RouterID &pk) EXCLUDES(access); Remove(const llarp::RouterID &pk) EXCLUDES(access);

@ -108,7 +108,7 @@ namespace llarp
{ {
if(Expired(llarp::time_now_ms())) if(Expired(llarp::time_now_ms()))
return false; return false;
return intro.latency > 0 && _status == ePathEstablished; return intro.latency > 0s && _status == ePathEstablished;
} }
bool bool
@ -280,7 +280,8 @@ namespace llarp
} }
else if(st == ePathEstablished && _status == ePathBuilding) else if(st == ePathEstablished && _status == ePathBuilding)
{ {
LogInfo("path ", Name(), " is built, took ", now - buildStarted, " ms"); LogInfo("path ", Name(), " is built, took ",
Time_t(now - buildStarted).count(), " ms");
} }
else if(st == ePathTimeout && _status == ePathEstablished) else if(st == ePathTimeout && _status == ePathEstablished)
{ {
@ -298,7 +299,7 @@ namespace llarp
util::StatusObject util::StatusObject
PathHopConfig::ExtractStatus() const PathHopConfig::ExtractStatus() const
{ {
util::StatusObject obj{{"lifetime", lifetime}, util::StatusObject obj{{"lifetime", lifetime.count()},
{"router", rc.pubkey.ToHex()}, {"router", rc.pubkey.ToHex()},
{"txid", txID.ToHex()}, {"txid", txID.ToHex()},
{"rxid", rxID.ToHex()}}; {"rxid", rxID.ToHex()}};
@ -311,12 +312,12 @@ namespace llarp
auto now = llarp::time_now_ms(); auto now = llarp::time_now_ms();
util::StatusObject obj{{"intro", intro.ExtractStatus()}, util::StatusObject obj{{"intro", intro.ExtractStatus()},
{"lastRecvMsg", m_LastRecvMessage}, {"lastRecvMsg", m_LastRecvMessage.count()},
{"lastLatencyTest", m_LastLatencyTestTime}, {"lastLatencyTest", m_LastLatencyTestTime.count()},
{"buildStarted", buildStarted}, {"buildStarted", buildStarted.count()},
{"expired", Expired(now)}, {"expired", Expired(now)},
{"expiresSoon", ExpiresSoon(now)}, {"expiresSoon", ExpiresSoon(now)},
{"expiresAt", ExpireTime()}, {"expiresAt", ExpireTime().count()},
{"ready", IsReady()}, {"ready", IsReady()},
{"txRateCurrent", m_LastTXRate}, {"txRateCurrent", m_LastTXRate},
{"rxRateCurrent", m_LastRXRate}, {"rxRateCurrent", m_LastRXRate},
@ -383,14 +384,15 @@ namespace llarp
if(_status == ePathBuilding) if(_status == ePathBuilding)
{ {
if(buildStarted == 0) if(buildStarted == 0s)
return; return;
if(now >= buildStarted) if(now >= buildStarted)
{ {
const auto dlt = now - buildStarted; const auto dlt = now - buildStarted;
if(dlt >= path::build_timeout) if(dlt >= path::build_timeout)
{ {
LogWarn(Name(), " waited for ", dlt, "ms and no path was built"); LogWarn(Name(), " waited for ", dlt.count(),
"ms and no path was built");
r->routerProfiling().MarkPathFail(this); r->routerProfiling().MarkPathFail(this);
EnterState(ePathExpired, now); EnterState(ePathExpired, now);
return; return;
@ -411,21 +413,23 @@ namespace llarp
FlushUpstream(r); FlushUpstream(r);
return; return;
} }
if(m_LastRecvMessage && now > m_LastRecvMessage) if(m_LastRecvMessage > 0s && now > m_LastRecvMessage)
{ {
const auto delay = now - m_LastRecvMessage; const auto delay = now - m_LastRecvMessage;
if(m_CheckForDead && m_CheckForDead(shared_from_this(), delay)) if(m_CheckForDead && m_CheckForDead(shared_from_this(), delay))
{ {
LogWarn(Name(), " waited for ", dlt, "ms and path is unresponsive"); LogWarn(Name(), " waited for ", dlt.count(),
"ms and path is unresponsive");
r->routerProfiling().MarkPathFail(this); r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now); EnterState(ePathTimeout, now);
} }
} }
else if(dlt >= path::alive_timeout && m_LastRecvMessage == 0) else if(dlt >= path::alive_timeout && m_LastRecvMessage == 0s)
{ {
if(m_CheckForDead && m_CheckForDead(shared_from_this(), dlt)) if(m_CheckForDead && m_CheckForDead(shared_from_this(), dlt))
{ {
LogWarn(Name(), " waited for ", dlt, "ms and path looks dead"); LogWarn(Name(), " waited for ", dlt.count(),
"ms and path looks dead");
r->routerProfiling().MarkPathFail(this); r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now); EnterState(ePathTimeout, now);
} }
@ -701,7 +705,8 @@ namespace llarp
if(m_BuiltHook) if(m_BuiltHook)
m_BuiltHook(shared_from_this()); m_BuiltHook(shared_from_this());
m_BuiltHook = nullptr; m_BuiltHook = nullptr;
LogDebug("path latency is now ", intro.latency, " for ", Name()); LogDebug("path latency is now ", intro.latency.count(), " for ",
Name());
return true; return true;
} }
@ -793,7 +798,7 @@ namespace llarp
} }
LogInfo(Name(), " ", Endpoint(), " Rejected exit"); LogInfo(Name(), " ", Endpoint(), " Rejected exit");
MarkActive(r->Now()); MarkActive(r->Now());
return InformExitResult(msg.B); return InformExitResult(Time_t(msg.B));
} }
LogError(Name(), " got unwarranted RXM"); LogError(Name(), " got unwarranted RXM");
return false; return false;
@ -814,7 +819,7 @@ namespace llarp
_role |= ePathRoleExit; _role |= ePathRoleExit;
LogInfo(Name(), " ", Endpoint(), " Granted exit"); LogInfo(Name(), " ", Endpoint(), " Granted exit");
MarkActive(r->Now()); MarkActive(r->Now());
return InformExitResult(0); return InformExitResult(0s);
} }
LogError(Name(), " got unwarranted GXM"); LogError(Name(), " got unwarranted GXM");
return false; return false;

@ -59,7 +59,7 @@ namespace llarp
/// nonce for key exchange /// nonce for key exchange
TunnelNonce nonce; TunnelNonce nonce;
// lifetime // lifetime
llarp_time_t lifetime = default_lifetime; Time_t lifetime = default_lifetime;
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;
@ -97,7 +97,7 @@ namespace llarp
service::Introduction intro; service::Introduction intro;
llarp_time_t buildStarted = 0; llarp_time_t buildStarted = 0s;
Path(const std::vector< RouterContact >& routers, PathSet* parent, Path(const std::vector< RouterContact >& routers, PathSet* parent,
PathRole startingRoles, std::string shortName); PathRole startingRoles, std::string shortName);
@ -270,7 +270,7 @@ namespace llarp
} }
bool bool
ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5000) const override ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5s) const override
{ {
return now >= (ExpireTime() - dlt); return now >= (ExpireTime() - dlt);
} }
@ -426,8 +426,8 @@ namespace llarp
ExitClosedFunc m_ExitClosed; ExitClosedFunc m_ExitClosed;
ExitTrafficHandlerFunc m_ExitTrafficHandler; ExitTrafficHandlerFunc m_ExitTrafficHandler;
std::vector< ObtainedExitHandler > m_ObtainedExitHooks; std::vector< ObtainedExitHandler > m_ObtainedExitHooks;
llarp_time_t m_LastRecvMessage = 0; llarp_time_t m_LastRecvMessage = 0s;
llarp_time_t m_LastLatencyTestTime = 0; llarp_time_t m_LastLatencyTestTime = 0s;
uint64_t m_LastLatencyTestID = 0; uint64_t m_LastLatencyTestID = 0;
uint64_t m_UpdateExitTX = 0; uint64_t m_UpdateExitTX = 0;
uint64_t m_CloseExitTX = 0; uint64_t m_CloseExitTX = 0;

@ -168,7 +168,7 @@ namespace llarp
Builder::ResetInternalState() Builder::ResetInternalState()
{ {
buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
lastBuild = 0; lastBuild = 0s;
} }
void Builder::Tick(llarp_time_t) void Builder::Tick(llarp_time_t)
@ -181,7 +181,7 @@ namespace llarp
if(m_BuildStats.attempts > 50) if(m_BuildStats.attempts > 50)
{ {
if(m_BuildStats.SuccsessRatio() <= BuildStats::MinGoodRatio if(m_BuildStats.SuccsessRatio() <= BuildStats::MinGoodRatio
&& now - m_LastWarn > 5000) && now - m_LastWarn > 5s)
{ {
LogWarn(Name(), " has a low path build success. ", m_BuildStats); LogWarn(Name(), " has a low path build success. ", m_BuildStats);
m_LastWarn = now; m_LastWarn = now;
@ -456,7 +456,7 @@ namespace llarp
{ {
buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
m_router->routerProfiling().MarkPathSuccess(p.get()); m_router->routerProfiling().MarkPathSuccess(p.get());
LogInfo(p->Name(), " built latency=", p->intro.latency); LogInfo(p->Name(), " built latency=", p->intro.latency.count(), "ms");
m_BuildStats.success++; m_BuildStats.success++;
} }
@ -472,10 +472,12 @@ namespace llarp
Builder::DoPathBuildBackoff() Builder::DoPathBuildBackoff()
{ {
// linear backoff // linear backoff
static constexpr llarp_time_t MaxBuildInterval = 30 * 1000; static constexpr auto MaxBuildInterval = 30s;
buildIntervalLimit = std::min( buildIntervalLimit =
MIN_PATH_BUILD_INTERVAL + buildIntervalLimit, MaxBuildInterval); std::min(MIN_PATH_BUILD_INTERVAL + buildIntervalLimit,
LogWarn(Name(), " build interval is now ", buildIntervalLimit); Time_t(MaxBuildInterval));
LogWarn(Name(), " build interval is now ", buildIntervalLimit.count(),
"ms");
} }
void void

@ -12,12 +12,12 @@ namespace llarp
namespace path namespace path
{ {
// milliseconds waiting between builds on a path // milliseconds waiting between builds on a path
constexpr llarp_time_t MIN_PATH_BUILD_INTERVAL = 500; static constexpr auto MIN_PATH_BUILD_INTERVAL = 500ms;
struct Builder : public PathSet struct Builder : public PathSet
{ {
private: private:
llarp_time_t m_LastWarn = 0; llarp_time_t m_LastWarn = 0s;
protected: protected:
/// flag for PathSet::Stop() /// flag for PathSet::Stop()
@ -42,7 +42,7 @@ namespace llarp
AbstractRouter* m_router; AbstractRouter* m_router;
SecretKey enckey; SecretKey enckey;
size_t numHops; size_t numHops;
llarp_time_t lastBuild = 0; llarp_time_t lastBuild = 0s;
llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
/// construct /// construct

@ -464,8 +464,8 @@ namespace llarp
{ {
Printer printer(stream, level, spaces); Printer printer(stream, level, spaces);
printer.printAttribute("TransitHop", info); printer.printAttribute("TransitHop", info);
printer.printAttribute("started", started); printer.printAttribute("started", started.count());
printer.printAttribute("lifetime", lifetime); printer.printAttribute("lifetime", lifetime.count());
return stream; return stream;
} }

@ -89,11 +89,11 @@ namespace llarp
TransitHopInfo info; TransitHopInfo info;
SharedSecret pathKey; SharedSecret pathKey;
ShortHash nonceXOR; ShortHash nonceXOR;
llarp_time_t started = 0; llarp_time_t started = 0s;
// 10 minutes default // 10 minutes default
llarp_time_t lifetime = default_lifetime; Time_t lifetime = default_lifetime;
llarp_proto_version_t version; llarp_proto_version_t version;
llarp_time_t m_LastActivity = 0; llarp_time_t m_LastActivity = 0s;
void void
Stop(); Stop();

@ -28,7 +28,7 @@ namespace llarp
bool bool
PoW::IsValid(llarp_time_t now) const PoW::IsValid(llarp_time_t now) const
{ {
if(now - timestamp > (uint64_t(extendedLifetime) * 1000)) if(now - timestamp > extendedLifetime)
return false; return false;
ShortHash digest; ShortHash digest;
@ -44,7 +44,7 @@ namespace llarp
if(!CryptoManager::instance()->shorthash(digest, buf)) if(!CryptoManager::instance()->shorthash(digest, buf))
return false; return false;
// check bytes required // check bytes required
uint32_t required = std::floor(std::log(extendedLifetime)); uint32_t required = std::floor(std::log(extendedLifetime.count()));
for(uint32_t idx = 0; idx < required; ++idx) for(uint32_t idx = 0; idx < required; ++idx)
{ {
if(digest[idx]) if(digest[idx])
@ -58,8 +58,8 @@ namespace llarp
{ {
Printer printer(stream, level, spaces); Printer printer(stream, level, spaces);
printer.printAttribute("pow timestamp", timestamp); printer.printAttribute("pow timestamp", timestamp.count());
printer.printAttribute("lifetime", extendedLifetime); printer.printAttribute("lifetime", extendedLifetime.count());
printer.printAttribute("nonce", nonce); printer.printAttribute("nonce", nonce);
return stream; return stream;

@ -10,8 +10,8 @@ namespace llarp
struct PoW struct PoW
{ {
static constexpr size_t MaxSize = 128; static constexpr size_t MaxSize = 128;
uint64_t timestamp = 0; llarp_time_t timestamp = 0s;
uint32_t extendedLifetime = 0; llarp_time_t extendedLifetime = 0s;
AlignedBuffer< 32 > nonce; AlignedBuffer< 32 > nonce;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;

@ -19,7 +19,7 @@ namespace llarp
return false; return false;
if(!BEncodeWriteDictInt("t", connectTimeoutCount, buf)) if(!BEncodeWriteDictInt("t", connectTimeoutCount, buf))
return false; return false;
if(!BEncodeWriteDictInt("u", lastUpdated, buf)) if(!BEncodeWriteDictInt("u", lastUpdated.count(), buf))
return false; return false;
if(!BEncodeWriteDictInt("v", version, buf)) if(!BEncodeWriteDictInt("v", version, buf))
return false; return false;
@ -60,8 +60,8 @@ namespace llarp
RouterProfile::Tick() RouterProfile::Tick()
{ {
// 15 seconds // 15 seconds
static constexpr llarp_time_t updateInterval = 15 * 1000; static constexpr auto updateInterval = 15s;
const auto now = llarp::time_now_ms(); const auto now = llarp::time_now_ms();
if(lastDecay < now && now - lastDecay > updateInterval) if(lastDecay < now && now - lastDecay > updateInterval)
Decay(); Decay();
} }
@ -299,6 +299,6 @@ namespace llarp
Profiling::ShouldSave(llarp_time_t now) const Profiling::ShouldSave(llarp_time_t now) const
{ {
auto dlt = now - m_LastSave; auto dlt = now - m_LastSave;
return dlt > 60000; return dlt > 1min;
} }
} // namespace llarp } // namespace llarp

@ -18,8 +18,8 @@ namespace llarp
uint64_t connectGoodCount = 0; uint64_t connectGoodCount = 0;
uint64_t pathSuccessCount = 0; uint64_t pathSuccessCount = 0;
uint64_t pathFailCount = 0; uint64_t pathFailCount = 0;
llarp_time_t lastUpdated = 0; llarp_time_t lastUpdated = 0s;
llarp_time_t lastDecay = 0; llarp_time_t lastDecay = 0s;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
bool bool
@ -113,7 +113,7 @@ namespace llarp
BEncodeNoLock(llarp_buffer_t* buf) const REQUIRES_SHARED(m_ProfilesMutex); BEncodeNoLock(llarp_buffer_t* buf) const REQUIRES_SHARED(m_ProfilesMutex);
mutable util::Mutex m_ProfilesMutex; // protects m_Profiles mutable util::Mutex m_ProfilesMutex; // protects m_Profiles
std::map< RouterID, RouterProfile > m_Profiles GUARDED_BY(m_ProfilesMutex); std::map< RouterID, RouterProfile > m_Profiles GUARDED_BY(m_ProfilesMutex);
llarp_time_t m_LastSave = 0; llarp_time_t m_LastSave = 0s;
std::atomic< bool > m_DisableProfiling; std::atomic< bool > m_DisableProfiling;
}; };

@ -32,7 +32,7 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
constexpr uint64_t ROUTER_TICK_INTERVAL_MS = 1000; static constexpr auto ROUTER_TICK_INTERVAL = 1s;
namespace llarp namespace llarp
{ {
@ -147,9 +147,9 @@ namespace llarp
void void
Router::PumpLL() Router::PumpLL()
{ {
static constexpr size_t PumpJobThreshhold = 50; static constexpr size_t PumpJobThreshhold = 50;
static constexpr llarp_time_t PumpInterval = 25; static constexpr auto PumpInterval = 25ms;
const auto now = Now(); const auto now = Now();
if(_stopping.load()) if(_stopping.load())
return; return;
if(_logic->numPendingJobs() >= PumpJobThreshhold if(_logic->numPendingJobs() >= PumpJobThreshhold
@ -300,8 +300,8 @@ namespace llarp
Router::handle_router_ticker() Router::handle_router_ticker()
{ {
ticker_job_id = 0; ticker_job_id = 0;
LogicCall(logic(), std::bind(&Router::Tick, this)); Tick();
ScheduleTicker(ROUTER_TICK_INTERVAL_MS); ScheduleTicker(ROUTER_TICK_INTERVAL);
} }
bool bool
@ -613,12 +613,12 @@ namespace llarp
if(conf->logging.m_LogJSON) if(conf->logging.m_LogJSON)
{ {
LogContext::Instance().logStream = std::make_unique< JSONLogStream >( LogContext::Instance().logStream = std::make_unique< JSONLogStream >(
diskworker(), logfile, 100, logfile != stdout); diskworker(), logfile, 100ms, logfile != stdout);
} }
else if(logfile != stdout) else if(logfile != stdout)
{ {
LogContext::Instance().logStream = LogContext::Instance().logStream =
std::make_unique< FileLogStream >(diskworker(), logfile, 100, true); std::make_unique< FileLogStream >(diskworker(), logfile, 100ms, true);
} }
netConfig.insert(conf->dns.netConfig.begin(), conf->dns.netConfig.end()); netConfig.insert(conf->dns.netConfig.begin(), conf->dns.netConfig.end());
@ -644,7 +644,7 @@ namespace llarp
bool bool
Router::ShouldReportStats(llarp_time_t now) const Router::ShouldReportStats(llarp_time_t now) const
{ {
static constexpr llarp_time_t ReportStatsInterval = 60 * 60 * 1000; static constexpr auto ReportStatsInterval = 1h;
return now - m_LastStatsReport > ReportStatsInterval; return now - m_LastStatsReport > ReportStatsInterval;
} }
@ -658,11 +658,11 @@ namespace llarp
if(IsServiceNode()) if(IsServiceNode())
{ {
LogInfo(NumberOfConnectedClients(), " client connections"); LogInfo(NumberOfConnectedClients(), " client connections");
LogInfo(_rc.Age(now), " ms since we last updated our RC"); LogInfo(_rc.Age(now).count(), " ms since we last updated our RC");
LogInfo(_rc.TimeUntilExpires(now), " ms until our RC expires"); LogInfo(_rc.TimeUntilExpires(now).count(), " ms until our RC expires");
} }
LogInfo(now, " system time"); LogInfo(now.count(), " system time");
LogInfo(m_LastStatsReport, " last reported stats"); LogInfo(m_LastStatsReport.count(), " last reported stats");
m_LastStatsReport = now; m_LastStatsReport = now;
} }
@ -685,13 +685,13 @@ namespace llarp
ReportStats(); ReportStats();
} }
_rcGossiper.Decay(time_now()); _rcGossiper.Decay(now);
_rcLookupHandler.PeriodicUpdate(now); _rcLookupHandler.PeriodicUpdate(now);
const bool isSvcNode = IsServiceNode(); const bool isSvcNode = IsServiceNode();
if(_rc.ExpiresSoon(now, randint() % 10000) if(_rc.ExpiresSoon(now, Time_t(randint() % 10000))
|| (now - _rc.last_updated) > rcRegenInterval) || (now - _rc.last_updated) > rcRegenInterval)
{ {
LogInfo("regenerating RC"); LogInfo("regenerating RC");
@ -783,10 +783,10 @@ namespace llarp
} }
void void
Router::ScheduleTicker(uint64_t ms) Router::ScheduleTicker(llarp_time_t interval)
{ {
ticker_job_id = ticker_job_id = _logic->call_later(
_logic->call_later(ms, std::bind(&Router::handle_router_ticker, this)); interval, std::bind(&Router::handle_router_ticker, this));
} }
void void
@ -1073,7 +1073,7 @@ namespace llarp
_netloop->add_ticker(std::bind(&Router::PumpLL, this)); _netloop->add_ticker(std::bind(&Router::PumpLL, this));
ScheduleTicker(ROUTER_TICK_INTERVAL_MS); ScheduleTicker(ROUTER_TICK_INTERVAL);
_running.store(true); _running.store(true);
_startedAt = Now(); _startedAt = Now();
#if defined(WITH_SYSTEMD) #if defined(WITH_SYSTEMD)
@ -1093,9 +1093,9 @@ namespace llarp
Router::Uptime() const Router::Uptime() const
{ {
const llarp_time_t _now = Now(); const llarp_time_t _now = Now();
if(_startedAt && _now > _startedAt) if(_startedAt > 0s && _now > _startedAt)
return _now - _startedAt; return _now - _startedAt;
return 0; return 0s;
} }
void void
@ -1109,7 +1109,7 @@ namespace llarp
{ {
StopLinks(); StopLinks();
nodedb()->AsyncFlushToDisk(); nodedb()->AsyncFlushToDisk();
_logic->call_later(200, std::bind(&Router::AfterStopLinks, this)); _logic->call_later(200ms, std::bind(&Router::AfterStopLinks, this));
} }
void void
@ -1135,7 +1135,7 @@ namespace llarp
rpcServer->Stop(); rpcServer->Stop();
paths.PumpUpstream(); paths.PumpUpstream();
_linkManager.PumpLinks(); _linkManager.PumpLinks();
_logic->call_later(200, std::bind(&Router::AfterStopIssued, this)); _logic->call_later(200ms, std::bind(&Router::AfterStopIssued, this));
} }
bool bool

@ -52,7 +52,7 @@ namespace llarp
{ {
struct Router final : public AbstractRouter struct Router final : public AbstractRouter
{ {
llarp_time_t _lastPump = 0; llarp_time_t _lastPump = 0s;
bool ready; bool ready;
// transient iwp encryption key // transient iwp encryption key
fs::path transport_keyfile = "transport.key"; fs::path transport_keyfile = "transport.key";
@ -199,7 +199,7 @@ namespace llarp
uint16_t m_OutboundPort = 0; uint16_t m_OutboundPort = 0;
/// how often do we resign our RC? milliseconds. /// how often do we resign our RC? milliseconds.
// TODO: make configurable // TODO: make configurable
llarp_time_t rcRegenInterval = 60 * 60 * 1000; llarp_time_t rcRegenInterval = 1h;
// should we be sending padded messages every interval? // should we be sending padded messages every interval?
bool sendPadding = false; bool sendPadding = false;
@ -223,7 +223,7 @@ namespace llarp
return _hiddenServiceContext; return _hiddenServiceContext;
} }
llarp_time_t _lastTick = 0; llarp_time_t _lastTick = 0s;
bool bool
LooksAlive() const override LooksAlive() const override
@ -443,7 +443,7 @@ namespace llarp
/// schedule ticker to call i ms from now /// schedule ticker to call i ms from now
void void
ScheduleTicker(uint64_t i = 1000); ScheduleTicker(llarp_time_t i = 1s);
/// parse a routing message in a buffer and handle it with a handler if /// parse a routing message in a buffer and handle it with a handler if
/// successful parsing return true on parse and handle success otherwise /// successful parsing return true on parse and handle success otherwise
@ -498,7 +498,7 @@ namespace llarp
bool m_isServiceNode = false; bool m_isServiceNode = false;
llarp_time_t m_LastStatsReport = 0; llarp_time_t m_LastStatsReport = 0s;
std::shared_ptr< llarp::KeyManager > m_keyManager; std::shared_ptr< llarp::KeyManager > m_keyManager;

@ -27,16 +27,16 @@ namespace llarp
#ifdef TESTNET #ifdef TESTNET
// 1 minute for testnet // 1 minute for testnet
llarp_time_t RouterContact::Lifetime = 60 * 1000; llarp_time_t RouterContact::Lifetime = 1min;
#else #else
/// 1 day for real network /// 1 day for real network
llarp_time_t RouterContact::Lifetime = 24 * 60 * 60 * 1000; llarp_time_t RouterContact::Lifetime = 24h;
#endif #endif
/// an RC inserted long enough ago (4 hrs) is considered stale and is removed /// an RC inserted long enough ago (4 hrs) is considered stale and is removed
llarp_time_t RouterContact::StaleInsertionAge = 4 * 60 * 60 * 1000; llarp_time_t RouterContact::StaleInsertionAge = 4h;
/// update RCs shortly before they are about to expire /// update RCs shortly before they are about to expire
llarp_time_t RouterContact::UpdateInterval = llarp_time_t RouterContact::UpdateInterval =
RouterContact::StaleInsertionAge - (5 * 60 * 1000); RouterContact::StaleInsertionAge - 5min;
NetID::NetID(const byte_t *val) NetID::NetID(const byte_t *val)
{ {
@ -135,7 +135,7 @@ namespace llarp
/* write last updated */ /* write last updated */
if(!bencode_write_bytestring(buf, "u", 1)) if(!bencode_write_bytestring(buf, "u", 1))
return false; return false;
if(!bencode_write_uint64(buf, last_updated)) if(!bencode_write_uint64(buf, last_updated.count()))
return false; return false;
/* write versions */ /* write versions */
@ -166,13 +166,13 @@ namespace llarp
enckey.Zero(); enckey.Zero();
pubkey.Zero(); pubkey.Zero();
routerVersion = nonstd::optional< RouterVersion >{}; routerVersion = nonstd::optional< RouterVersion >{};
last_updated = 0; last_updated = 0s;
} }
util::StatusObject util::StatusObject
RouterContact::ExtractStatus() const RouterContact::ExtractStatus() const
{ {
util::StatusObject obj{{"lastUpdated", last_updated}, util::StatusObject obj{{"lastUpdated", last_updated.count()},
{"exit", IsExit()}, {"exit", IsExit()},
{"publicRouter", IsPublicRouter()}, {"publicRouter", IsPublicRouter()},
{"identity", pubkey.ToString()}, {"identity", pubkey.ToString()},
@ -280,13 +280,13 @@ namespace llarp
RouterContact::TimeUntilExpires(llarp_time_t now) const RouterContact::TimeUntilExpires(llarp_time_t now) const
{ {
const auto expiresAt = last_updated + Lifetime; const auto expiresAt = last_updated + Lifetime;
return now < expiresAt ? expiresAt - now : 0; return now < expiresAt ? expiresAt - now : 0s;
} }
llarp_time_t llarp_time_t
RouterContact::Age(llarp_time_t now) const RouterContact::Age(llarp_time_t now) const
{ {
return now > last_updated ? now - last_updated : 0; return now > last_updated ? now - last_updated : 0s;
} }
bool bool
@ -434,7 +434,7 @@ namespace llarp
{ {
Printer printer(stream, level, spaces); Printer printer(stream, level, spaces);
printer.printAttribute("k", pubkey); printer.printAttribute("k", pubkey);
printer.printAttribute("updated", last_updated); printer.printAttribute("updated", last_updated.count());
printer.printAttribute("netid", netID); printer.printAttribute("netid", netID);
printer.printAttribute("v", version); printer.printAttribute("v", version);
printer.printAttribute("ai", addrs); printer.printAttribute("ai", addrs);

@ -103,8 +103,8 @@ namespace llarp
/// node nickname, yw kee /// node nickname, yw kee
llarp::AlignedBuffer< NICKLEN > nickname; llarp::AlignedBuffer< NICKLEN > nickname;
uint64_t last_updated = 0; llarp_time_t last_updated = 0s;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
nonstd::optional< RouterVersion > routerVersion; nonstd::optional< RouterVersion > routerVersion;
util::StatusObject util::StatusObject
@ -179,7 +179,7 @@ namespace llarp
/// does this RC expire soon? default delta is 1 minute /// does this RC expire soon? default delta is 1 minute
bool bool
ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 60000) const; ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 1min) const;
/// returns true if this RC is expired and should be removed /// returns true if this RC is expired and should be removed
bool bool

@ -8,7 +8,7 @@ namespace llarp
{ {
namespace routing namespace routing
{ {
PathConfirmMessage::PathConfirmMessage(uint64_t lifetime) PathConfirmMessage::PathConfirmMessage(llarp_time_t lifetime)
: pathLifetime(lifetime), pathCreated(time_now_ms()) : pathLifetime(lifetime), pathCreated(time_now_ms())
{ {
} }
@ -36,11 +36,11 @@ namespace llarp
return false; return false;
if(!BEncodeWriteDictMsgType(buf, "A", "P")) if(!BEncodeWriteDictMsgType(buf, "A", "P"))
return false; return false;
if(!BEncodeWriteDictInt("L", pathLifetime, buf)) if(!BEncodeWriteDictInt("L", pathLifetime.count(), buf))
return false; return false;
if(!BEncodeWriteDictInt("S", S, buf)) if(!BEncodeWriteDictInt("S", S, buf))
return false; return false;
if(!BEncodeWriteDictInt("T", pathCreated, buf)) if(!BEncodeWriteDictInt("T", pathCreated.count(), buf))
return false; return false;
if(!BEncodeWriteDictInt("V", version, buf)) if(!BEncodeWriteDictInt("V", version, buf))
return false; return false;

@ -9,11 +9,11 @@ namespace llarp
{ {
struct PathConfirmMessage final : public IMessage struct PathConfirmMessage final : public IMessage
{ {
uint64_t pathLifetime = 0; llarp_time_t pathLifetime = 0s;
uint64_t pathCreated = 0; llarp_time_t pathCreated = 0s;
PathConfirmMessage() = default; PathConfirmMessage() = default;
PathConfirmMessage(uint64_t lifetime); PathConfirmMessage(llarp_time_t lifetime);
~PathConfirmMessage() override = default; ~PathConfirmMessage() override = default;
bool bool
@ -28,8 +28,8 @@ namespace llarp
void void
Clear() override Clear() override
{ {
pathLifetime = 0; pathLifetime = 0s;
pathCreated = 0; pathCreated = 0s;
version = 0; version = 0;
} }
}; };

@ -122,11 +122,11 @@ namespace llarp
struct CallerImpl : public ::abyss::http::JSONRPC struct CallerImpl : public ::abyss::http::JSONRPC
{ {
AbstractRouter* router; AbstractRouter* router;
llarp_time_t m_NextKeyUpdate = 0; llarp_time_t m_NextKeyUpdate = 0s;
std::string m_LastBlockHash; std::string m_LastBlockHash;
llarp_time_t m_NextPing = 0; llarp_time_t m_NextPing = 0s;
const llarp_time_t KeyUpdateInterval = 5000; const llarp_time_t KeyUpdateInterval = 5s;
const llarp_time_t PingInterval = 60 * 5 * 1000; const llarp_time_t PingInterval = 5min;
using PubkeyList_t = GetServiceNodeListHandler::PubkeyList_t; using PubkeyList_t = GetServiceNodeListHandler::PubkeyList_t;
CallerImpl(AbstractRouter* r) : ::abyss::http::JSONRPC(), router(r) CallerImpl(AbstractRouter* r) : ::abyss::http::JSONRPC(), router(r)
@ -369,7 +369,7 @@ namespace llarp
return true; return true;
}; };
router->hiddenServiceContext().ForEachService(visitor); router->hiddenServiceContext().ForEachService(visitor);
const Response resp{{"uptime", router->Uptime()}, const Response resp{{"uptime", router->Uptime().count()},
{"servicesTotal", numServices}, {"servicesTotal", numServices},
{"servicesReady", numServicesReady}, {"servicesReady", numServicesReady},
{"services", services}}; {"services", services}};
@ -429,7 +429,7 @@ namespace llarp
AbstractRouter* router; AbstractRouter* router;
ReqHandlerImpl _handler; ReqHandlerImpl _handler;
ServerImpl(AbstractRouter* r) : router(r), _handler(r, 2000) ServerImpl(AbstractRouter* r) : router(r), _handler(r, 2s)
{ {
} }

@ -77,7 +77,7 @@ namespace llarp
std::set< Introduction > I; std::set< Introduction > I;
if(!GetCurrentIntroductionsWithFilter( if(!GetCurrentIntroductionsWithFilter(
I, [now](const service::Introduction& intro) -> bool { I, [now](const service::Introduction& intro) -> bool {
return not intro.ExpiresSoon(now, 2 * 60 * 1000); return not intro.ExpiresSoon(now, 2min);
})) }))
{ {
LogWarn("could not publish descriptors for endpoint ", Name(), LogWarn("could not publish descriptors for endpoint ", Name(),
@ -196,7 +196,7 @@ namespace llarp
if(!EndpointUtil::HasPathToService(addr, m_state->m_RemoteSessions)) if(!EndpointUtil::HasPathToService(addr, m_state->m_RemoteSessions))
{ {
if(!EnsurePathToService( if(!EnsurePathToService(
addr, [](Address, OutboundContext*) {}, 10000)) addr, [](Address, OutboundContext*) {}, 10s))
{ {
LogWarn("failed to ensure path to ", addr); LogWarn("failed to ensure path to ", addr);
} }
@ -1242,7 +1242,7 @@ namespace llarp
} }
self->m_state->m_PendingTraffic.erase(addr); self->m_state->m_PendingTraffic.erase(addr);
}, },
1500); 1500ms);
} }
} }
return false; return false;

@ -22,7 +22,7 @@
// minimum time between introset shifts // minimum time between introset shifts
#ifndef MIN_SHIFT_INTERVAL #ifndef MIN_SHIFT_INTERVAL
#define MIN_SHIFT_INTERVAL (5 * 1000) #define MIN_SHIFT_INTERVAL 5s
#endif #endif
struct llarp_async_verify_rc; struct llarp_async_verify_rc;
@ -59,16 +59,16 @@ namespace llarp
}; };
using ConvoEventListener_ptr = std::shared_ptr< IConvoEventListener >; using ConvoEventListener_ptr = std::shared_ptr< IConvoEventListener >;
/// minimum interval for publishing introsets
static constexpr auto INTROSET_PUBLISH_INTERVAL =
path::default_lifetime / 4;
static constexpr auto INTROSET_PUBLISH_RETRY_INTERVAL = 5s;
struct Endpoint : public path::Builder, struct Endpoint : public path::Builder,
public ILookupHolder, public ILookupHolder,
public IDataHandler public IDataHandler
{ {
/// minimum interval for publishing introsets
static const llarp_time_t INTROSET_PUBLISH_INTERVAL =
path::default_lifetime / 4;
static const llarp_time_t INTROSET_PUBLISH_RETRY_INTERVAL = 5000;
static const size_t MAX_OUTBOUND_CONTEXT_COUNT = 4; static const size_t MAX_OUTBOUND_CONTEXT_COUNT = 4;
Endpoint(const std::string& nickname, AbstractRouter* r, Context* parent); Endpoint(const std::string& nickname, AbstractRouter* r, Context* parent);
@ -288,7 +288,7 @@ namespace llarp
/// address /// address
bool bool
EnsurePathToService(const Address remote, PathEnsureHook h, EnsurePathToService(const Address remote, PathEnsureHook h,
uint64_t timeoutMS); llarp_time_t timeoutMS);
using SNodeEnsureHook = using SNodeEnsureHook =
std::function< void(const RouterID, exit::BaseSession_ptr) >; std::function< void(const RouterID, exit::BaseSession_ptr) >;

@ -38,7 +38,7 @@ namespace llarp
{ {
const auto val = atoi(v.c_str()); const auto val = atoi(v.c_str());
if(val > 0) if(val > 0)
m_MinPathLatency = val; m_MinPathLatency = Time_t(val);
} }
if(k == "paths") if(k == "paths")
{ {
@ -116,8 +116,8 @@ namespace llarp
util::StatusObject util::StatusObject
EndpointState::ExtractStatus(util::StatusObject& obj) const EndpointState::ExtractStatus(util::StatusObject& obj) const
{ {
obj["lastPublished"] = m_LastPublish; obj["lastPublished"] = m_LastPublish.count();
obj["lastPublishAttempt"] = m_LastPublishAttempt; obj["lastPublishAttempt"] = m_LastPublishAttempt.count();
obj["introset"] = m_IntroSet.ExtractStatus(); obj["introset"] = m_IntroSet.ExtractStatus();
if(!m_Tag.IsZero()) if(!m_Tag.IsZero())

@ -76,9 +76,9 @@ namespace llarp
PendingRouters m_PendingRouters; PendingRouters m_PendingRouters;
uint64_t m_CurrentPublishTX = 0; uint64_t m_CurrentPublishTX = 0;
llarp_time_t m_LastPublish = 0; llarp_time_t m_LastPublish = 0s;
llarp_time_t m_LastPublishAttempt = 0; llarp_time_t m_LastPublishAttempt = 0s;
llarp_time_t m_MinPathLatency = (5 * 1000); llarp_time_t m_MinPathLatency = 1s;
/// our introset /// our introset
IntroSet m_IntroSet; IntroSet m_IntroSet;
/// pending remote service lookups by id /// pending remote service lookups by id

@ -8,8 +8,8 @@ namespace llarp
Introduction::ExtractStatus() const Introduction::ExtractStatus() const
{ {
util::StatusObject obj{{"router", router.ToHex()}, util::StatusObject obj{{"router", router.ToHex()},
{"expiresAt", expiresAt}, {"expiresAt", expiresAt.count()},
{"latency", latency}, {"latency", latency.count()},
{"version", uint64_t(version)}}; {"version", uint64_t(version)}};
return obj; return obj;
} }
@ -39,16 +39,16 @@ namespace llarp
if(!BEncodeWriteDictEntry("k", router, buf)) if(!BEncodeWriteDictEntry("k", router, buf))
return false; return false;
if(latency) if(latency > 0s)
{ {
if(!BEncodeWriteDictInt("l", latency, buf)) if(!BEncodeWriteDictInt("l", latency.count(), buf))
return false; return false;
} }
if(!BEncodeWriteDictEntry("p", pathID, buf)) if(!BEncodeWriteDictEntry("p", pathID, buf))
return false; return false;
if(!BEncodeWriteDictInt("v", version, buf)) if(!BEncodeWriteDictInt("v", version, buf))
return false; return false;
if(!BEncodeWriteDictInt("x", expiresAt, buf)) if(!BEncodeWriteDictInt("x", expiresAt.count(), buf))
return false; return false;
return bencode_end(buf); return bencode_end(buf);
} }
@ -58,8 +58,8 @@ namespace llarp
{ {
router.Zero(); router.Zero();
pathID.Zero(); pathID.Zero();
latency = 0; latency = 0s;
expiresAt = 0; expiresAt = 0s;
} }
std::ostream& std::ostream&
@ -67,10 +67,10 @@ namespace llarp
{ {
Printer printer(stream, level, spaces); Printer printer(stream, level, spaces);
printer.printAttribute("k", RouterID(router)); printer.printAttribute("k", RouterID(router));
printer.printAttribute("l", latency); printer.printAttribute("l", latency.count());
printer.printAttribute("p", pathID); printer.printAttribute("p", pathID);
printer.printAttribute("v", version); printer.printAttribute("v", version);
printer.printAttribute("x", expiresAt); printer.printAttribute("x", expiresAt.count());
return stream; return stream;
} }

@ -16,9 +16,9 @@ namespace llarp
{ {
PubKey router; PubKey router;
PathID_t pathID; PathID_t pathID;
uint64_t latency = 0; llarp_time_t latency = 0s;
uint64_t expiresAt = 0; llarp_time_t expiresAt = 0s;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;
@ -30,7 +30,7 @@ namespace llarp
} }
bool bool
ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 30000) const ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 30s) const
{ {
return IsExpired(now + dlt); return IsExpired(now + dlt);
} }

@ -11,7 +11,7 @@ namespace llarp
{ {
const auto sz = introsetPayload.size(); const auto sz = introsetPayload.size();
return {{"location", derivedSigningKey.ToString()}, return {{"location", derivedSigningKey.ToString()},
{"signedAt", signedAt}, {"signedAt", signedAt.count()},
{"size", sz}}; {"size", sz}};
} }
@ -24,7 +24,7 @@ namespace llarp
return false; return false;
if(not BEncodeWriteDictEntry("n", nounce, buf)) if(not BEncodeWriteDictEntry("n", nounce, buf))
return false; return false;
if(not BEncodeWriteDictInt("s", signedAt, buf)) if(not BEncodeWriteDictInt("s", signedAt.count(), buf))
return false; return false;
if(not bencode_write_bytestring(buf, "x", 1)) if(not bencode_write_bytestring(buf, "x", 1))
return false; return false;
@ -77,7 +77,7 @@ namespace llarp
Printer printer(out, levels, spaces); Printer printer(out, levels, spaces);
printer.printAttribute("d", derivedSigningKey); printer.printAttribute("d", derivedSigningKey);
printer.printAttribute("n", nounce); printer.printAttribute("n", nounce);
printer.printAttribute("s", signedAt); printer.printAttribute("s", signedAt.count());
printer.printAttribute( printer.printAttribute(
"x", "[" + std::to_string(introsetPayload.size()) + " bytes]"); "x", "[" + std::to_string(introsetPayload.size()) + " bytes]");
printer.printAttribute("z", sig); printer.printAttribute("z", sig);
@ -142,7 +142,7 @@ namespace llarp
util::StatusObject util::StatusObject
IntroSet::ExtractStatus() const IntroSet::ExtractStatus() const
{ {
util::StatusObject obj{{"published", T}}; util::StatusObject obj{{"published", T.count()}};
std::vector< util::StatusObject > introsObjs; std::vector< util::StatusObject > introsObjs;
std::transform(I.begin(), I.end(), std::back_inserter(introsObjs), std::transform(I.begin(), I.end(), std::back_inserter(introsObjs),
[](const auto& intro) -> util::StatusObject { [](const auto& intro) -> util::StatusObject {
@ -214,7 +214,7 @@ namespace llarp
return false; return false;
} }
// Timestamp published // Timestamp published
if(!BEncodeWriteDictInt("t", T, buf)) if(!BEncodeWriteDictInt("t", T.count(), buf))
return false; return false;
// write version // write version
@ -301,7 +301,7 @@ namespace llarp
llarp_time_t llarp_time_t
IntroSet::GetNewestIntroExpiration() const IntroSet::GetNewestIntroExpiration() const
{ {
llarp_time_t t = 0; llarp_time_t t = 0s;
for(const auto& intro : I) for(const auto& intro : I)
t = std::max(intro.expiresAt, t); t = std::max(intro.expiresAt, t);
return t; return t;
@ -326,7 +326,7 @@ namespace llarp
printer.printAttribute("topic", topic); printer.printAttribute("topic", topic);
} }
printer.printAttribute("T", T); printer.printAttribute("T", T.count());
if(W) if(W)
{ {
printer.printAttribute("W", W.value()); printer.printAttribute("W", W.value());

@ -22,7 +22,7 @@ namespace llarp
{ {
constexpr std::size_t MAX_INTROSET_SIZE = 4096; constexpr std::size_t MAX_INTROSET_SIZE = 4096;
// 10 seconds clock skew permitted for introset expiration // 10 seconds clock skew permitted for introset expiration
constexpr llarp_time_t MAX_INTROSET_TIME_DELTA = (10 * 1000); constexpr llarp_time_t MAX_INTROSET_TIME_DELTA = 10s;
struct IntroSet struct IntroSet
{ {
@ -30,7 +30,7 @@ namespace llarp
std::vector< Introduction > I; std::vector< Introduction > I;
PQPubKey K; PQPubKey K;
Tag topic; Tag topic;
llarp_time_t T = 0; llarp_time_t T = 0s;
nonstd::optional< PoW > W; nonstd::optional< PoW > W;
Signature Z; Signature Z;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
@ -108,7 +108,7 @@ namespace llarp
using Payload_t = std::vector< byte_t >; using Payload_t = std::vector< byte_t >;
PubKey derivedSigningKey; PubKey derivedSigningKey;
llarp_time_t signedAt = 0; llarp_time_t signedAt = 0s;
Payload_t introsetPayload; Payload_t introsetPayload;
TunnelNonce nounce; TunnelNonce nounce;
nonstd::optional< Tag > topic; nonstd::optional< Tag > topic;

@ -35,7 +35,7 @@ namespace llarp
/// determine if this request has timed out /// determine if this request has timed out
bool bool
IsTimedOut(llarp_time_t now, llarp_time_t timeout = 20000) const IsTimedOut(llarp_time_t now, llarp_time_t timeout = 20s) const
{ {
if(now <= m_created) if(now <= m_created)
return false; return false;
@ -63,7 +63,7 @@ namespace llarp
{"endpoint", endpoint.ToHex()}, {"endpoint", endpoint.ToHex()},
{"name", name}, {"name", name},
{"timedOut", IsTimedOut(now)}, {"timedOut", IsTimedOut(now)},
{"createdAt", m_created}}; {"createdAt", m_created.count()}};
return obj; return obj;
} }

@ -95,7 +95,7 @@ namespace llarp
updatingIntroSet = false; updatingIntroSet = false;
if(foundIntro.has_value()) if(foundIntro.has_value())
{ {
if(foundIntro->T == 0) if(foundIntro->T == 0s)
{ {
LogWarn(Name(), LogWarn(Name(),
" got introset with zero timestamp: ", foundIntro.value()); " got introset with zero timestamp: ", foundIntro.value());
@ -251,11 +251,11 @@ namespace llarp
auto obj = path::Builder::ExtractStatus(); auto obj = path::Builder::ExtractStatus();
obj["currentConvoTag"] = currentConvoTag.ToHex(); obj["currentConvoTag"] = currentConvoTag.ToHex();
obj["remoteIntro"] = remoteIntro.ExtractStatus(); obj["remoteIntro"] = remoteIntro.ExtractStatus();
obj["sessionCreatedAt"] = createdAt; obj["sessionCreatedAt"] = createdAt.count();
obj["lastGoodSend"] = lastGoodSend; obj["lastGoodSend"] = lastGoodSend.count();
obj["seqno"] = sequenceNo; obj["seqno"] = sequenceNo;
obj["markedBad"] = markedBad; obj["markedBad"] = markedBad;
obj["lastShift"] = lastShift; obj["lastShift"] = lastShift.count();
obj["remoteIdentity"] = remoteIdent.Addr().ToString(); obj["remoteIdentity"] = remoteIdent.Addr().ToString();
obj["currentRemoteIntroset"] = currentIntroSet.ExtractStatus(); obj["currentRemoteIntroset"] = currentIntroSet.ExtractStatus();
obj["nextIntro"] = m_NextIntro.ExtractStatus(); obj["nextIntro"] = m_NextIntro.ExtractStatus();
@ -263,9 +263,7 @@ namespace llarp
std::transform(m_BadIntros.begin(), m_BadIntros.end(), std::transform(m_BadIntros.begin(), m_BadIntros.end(),
std::back_inserter(obj["badIntros"]), std::back_inserter(obj["badIntros"]),
[](const auto& item) -> util::StatusObject { [](const auto& item) -> util::StatusObject {
return util::StatusObject{ return item.first.ExtractStatus();
{"count", item.second},
{"intro", item.first.ExtractStatus()}};
}); });
return obj; return obj;
} }
@ -297,7 +295,7 @@ namespace llarp
++itr; ++itr;
} }
// send control message if we look too quiet // send control message if we look too quiet
if(lastGoodSend) if(lastGoodSend > 0s)
{ {
if(now - lastGoodSend > (sendTimeout / 2)) if(now - lastGoodSend > (sendTimeout / 2))
{ {
@ -316,7 +314,7 @@ namespace llarp
} }
} }
// if we are dead return true so we are removed // if we are dead return true so we are removed
return lastGoodSend return lastGoodSend > 0s
? (now >= lastGoodSend && now - lastGoodSend > sendTimeout) ? (now >= lastGoodSend && now - lastGoodSend > sendTimeout)
: (now >= createdAt && now - createdAt > connectTimeout); : (now >= createdAt && now - createdAt > connectTimeout);
} }
@ -363,7 +361,7 @@ namespace llarp
and path::Builder::ShouldBuildMore(now); and path::Builder::ShouldBuildMore(now);
if(not canBuild) if(not canBuild)
return false; return false;
llarp_time_t t = 0; llarp_time_t t = 0s;
ForEachPath([&t](path::Path_ptr path) { ForEachPath([&t](path::Path_ptr path) {
if(path->IsReady()) if(path->IsReady())
t = std::max(path->ExpireTime(), t); t = std::max(path->ExpireTime(), t);

@ -124,7 +124,7 @@ namespace llarp
Introduction m_NextIntro; Introduction m_NextIntro;
std::unordered_map< Introduction, llarp_time_t, Introduction::Hash > std::unordered_map< Introduction, llarp_time_t, Introduction::Hash >
m_BadIntros; m_BadIntros;
llarp_time_t lastShift = 0; llarp_time_t lastShift = 0s;
uint16_t m_LookupFails = 0; uint16_t m_LookupFails = 0;
uint16_t m_BuildFails = 0; uint16_t m_BuildFails = 0;
}; };

@ -44,7 +44,7 @@ namespace llarp
ProtocolMessage(); ProtocolMessage();
~ProtocolMessage(); ~ProtocolMessage();
ProtocolType proto = eProtocolTrafficV4; ProtocolType proto = eProtocolTrafficV4;
llarp_time_t queued = 0; llarp_time_t queued = 0s;
std::vector< byte_t > payload; std::vector< byte_t > payload;
Introduction introReply; Introduction introReply;
ServiceInfo sender; ServiceInfo sender;

@ -22,7 +22,7 @@ namespace llarp
{ {
if(now < started) if(now < started)
return false; return false;
return now - started > 30000; return now - started > 30s;
} }
void void

@ -20,9 +20,9 @@ namespace llarp
, m_PathSet(send) , m_PathSet(send)
, m_DataHandler(ep) , m_DataHandler(ep)
, m_Endpoint(ep) , m_Endpoint(ep)
, createdAt(ep->Now())
, m_SendQueue(SendContextQueueSize) , m_SendQueue(SendContextQueueSize)
{ {
createdAt = ep->Now();
} }
bool bool
@ -117,7 +117,7 @@ namespace llarp
SendContext::AsyncEncryptAndSendTo(const llarp_buffer_t& data, SendContext::AsyncEncryptAndSendTo(const llarp_buffer_t& data,
ProtocolType protocol) ProtocolType protocol)
{ {
if(lastGoodSend != 0) if(lastGoodSend != 0s)
{ {
EncryptAndSendTo(data, protocol); EncryptAndSendTo(data, protocol);
} }

@ -44,10 +44,10 @@ namespace llarp
IDataHandler* const m_DataHandler; IDataHandler* const m_DataHandler;
Endpoint* const m_Endpoint; Endpoint* const m_Endpoint;
uint64_t sequenceNo = 0; uint64_t sequenceNo = 0;
llarp_time_t lastGoodSend = 0; llarp_time_t lastGoodSend = 0s;
llarp_time_t createdAt; const llarp_time_t createdAt;
llarp_time_t sendTimeout = 40 * 1000; llarp_time_t sendTimeout = 40s;
llarp_time_t connectTimeout = 60 * 1000; llarp_time_t connectTimeout = 60s;
bool markedBad = false; bool markedBad = false;
using Msg_ptr = std::shared_ptr< const routing::PathTransferMessage >; using Msg_ptr = std::shared_ptr< const routing::PathTransferMessage >;
using SendEvent_t = std::pair< Msg_ptr, path::Path_ptr >; using SendEvent_t = std::pair< Msg_ptr, path::Path_ptr >;

@ -7,7 +7,7 @@ namespace llarp
util::StatusObject util::StatusObject
Session::ExtractStatus() const Session::ExtractStatus() const
{ {
util::StatusObject obj{{"lastUsed", lastUsed}, util::StatusObject obj{{"lastUsed", lastUsed.count()},
{"replyIntro", replyIntro.ExtractStatus()}, {"replyIntro", replyIntro.ExtractStatus()},
{"remote", remote.Addr().ToString()}, {"remote", remote.Addr().ToString()},
{"seqno", seqno}, {"seqno", seqno},

@ -12,6 +12,8 @@ namespace llarp
{ {
namespace service namespace service
{ {
static constexpr auto SessionLifetime = path::default_lifetime * 2;
struct Session struct Session
{ {
/// the intro we have /// the intro we have
@ -22,16 +24,14 @@ namespace llarp
Introduction intro; Introduction intro;
/// the intro remoet last sent on /// the intro remoet last sent on
Introduction lastInboundIntro; Introduction lastInboundIntro;
llarp_time_t lastUsed = 0; llarp_time_t lastUsed = 0s;
uint64_t seqno = 0; uint64_t seqno = 0;
bool inbound = false; bool inbound = false;
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;
bool bool
IsExpired(llarp_time_t now, IsExpired(llarp_time_t now, Time_t lifetime = SessionLifetime) const;
llarp_time_t lifetime = (path::default_lifetime * 2)) const;
}; };
} // namespace service } // namespace service

@ -17,9 +17,9 @@ namespace llarp
struct CachedTagResult struct CachedTagResult
{ {
const static llarp_time_t TTL = 10000; static constexpr auto TTL = 10s;
llarp_time_t lastRequest = 0; llarp_time_t lastRequest = 0s;
llarp_time_t lastModified = 0; llarp_time_t lastModified = 0s;
std::set< EncryptedIntroSet > result; std::set< EncryptedIntroSet > result;
Tag tag; Tag tag;
Endpoint* m_parent; Endpoint* m_parent;

@ -88,12 +88,15 @@ namespace llarp
{ {
if(key == k) if(key == k)
{ {
if(!bencode_read_integer(buf, &i)) uint64_t read_i;
if(!bencode_read_integer(buf, &read_i))
{ {
llarp::LogWarnTag("llarp/BEncode.hpp", "failed to decode key ", k, llarp::LogWarnTag("llarp/BEncode.hpp", "failed to decode key ", k,
" for integer in dict"); " for integer in dict");
return false; return false;
} }
i = Int_t(read_i);
read = true; read = true;
} }
return true; return true;

@ -28,9 +28,8 @@ namespace llarp
template < typename T, typename GetTime, typename PutTime, typename Compare, template < typename T, typename GetTime, typename PutTime, typename Compare,
typename GetNow = GetNowSyscall, typename Mutex_t = util::Mutex, typename GetNow = GetNowSyscall, typename Mutex_t = util::Mutex,
typename Lock_t = std::lock_guard< Mutex_t >, typename Lock_t = std::lock_guard< Mutex_t >,
llarp_time_t dropMs = 5, llarp_time_t initialIntervalMs = 100, size_t MaxSize = 1024 >
size_t MaxSize = 1024 >
struct CoDelQueue struct CoDelQueue
{ {
CoDelQueue(std::string name, PutTime put, GetNow now) CoDelQueue(std::string name, PutTime put, GetNow now)
@ -65,7 +64,7 @@ namespace llarp
} }
_putTime(m_Queue[m_QueueIdx]); _putTime(m_Queue[m_QueueIdx]);
if(firstPut == 0) if(firstPut == 0s)
firstPut = _getTime(m_Queue[m_QueueIdx]); firstPut = _getTime(m_Queue[m_QueueIdx]);
++m_QueueIdx; ++m_QueueIdx;
@ -82,7 +81,7 @@ namespace llarp
T* t = &m_Queue[m_QueueIdx]; T* t = &m_Queue[m_QueueIdx];
new(t) T(std::forward< Args >(args)...); new(t) T(std::forward< Args >(args)...);
_putTime(m_Queue[m_QueueIdx]); _putTime(m_Queue[m_QueueIdx]);
if(firstPut == 0) if(firstPut == 0s)
firstPut = _getTime(m_Queue[m_QueueIdx]); firstPut = _getTime(m_Queue[m_QueueIdx]);
++m_QueueIdx; ++m_QueueIdx;
} }
@ -111,7 +110,7 @@ namespace llarp
T* t = &m_Queue[0]; T* t = &m_Queue[0];
t->~T(); t->~T();
m_QueueIdx = 0; m_QueueIdx = 0;
firstPut = 0; firstPut = 0s;
return; return;
} }
size_t idx = 0; size_t idx = 0;
@ -122,7 +121,7 @@ namespace llarp
if(f(*item)) if(f(*item))
break; break;
--m_QueueIdx; --m_QueueIdx;
auto dlt = start - _getTime(*item); const llarp_time_t dlt = start - _getTime(*item);
// llarp::LogInfo("CoDelQueue::Process - dlt ", dlt); // llarp::LogInfo("CoDelQueue::Process - dlt ", dlt);
lowest = std::min(dlt, lowest); lowest = std::min(dlt, lowest);
if(m_QueueIdx == 0) if(m_QueueIdx == 0)
@ -132,8 +131,9 @@ namespace llarp
if(lowest > dropMs) if(lowest > dropMs)
{ {
item->~T(); item->~T();
nextTickInterval += initialIntervalMs / std::sqrt(++dropNum); nextTickInterval +=
firstPut = 0; initialIntervalMs / uint64_t(std::sqrt(++dropNum));
firstPut = 0s;
nextTickAt = start + nextTickInterval; nextTickAt = start + nextTickInterval;
return; return;
} }
@ -144,14 +144,16 @@ namespace llarp
visitor(*item); visitor(*item);
item->~T(); item->~T();
} }
firstPut = 0; firstPut = 0s;
nextTickAt = start + nextTickInterval; nextTickAt = start + nextTickInterval;
} }
llarp_time_t firstPut = 0; const llarp_time_t initialIntervalMs = 5ms;
size_t dropNum = 0; const llarp_time_t dropMs = 100ms;
llarp_time_t nextTickInterval = initialIntervalMs; llarp_time_t firstPut = 0s;
llarp_time_t nextTickAt = 0; size_t dropNum = 0;
llarp_time_t nextTickInterval = initialIntervalMs;
llarp_time_t nextTickAt = 0s;
Mutex_t m_QueueMutex; Mutex_t m_QueueMutex;
size_t m_QueueIdx GUARDED_BY(m_QueueMutex); size_t m_QueueIdx GUARDED_BY(m_QueueMutex);
std::array< T, MaxSize > m_Queue GUARDED_BY(m_QueueMutex); std::array< T, MaxSize > m_Queue GUARDED_BY(m_QueueMutex);

@ -54,7 +54,7 @@ namespace llarp
std::shared_ptr< thread::ThreadPool > m_Disk; std::shared_ptr< thread::ThreadPool > m_Disk;
FILE* const m_File; FILE* const m_File;
const llarp_time_t m_FlushInterval; const llarp_time_t m_FlushInterval;
llarp_time_t m_LastFlush = 0; llarp_time_t m_LastFlush = 0s;
const bool m_Close; const bool m_Close;
}; };
} // namespace llarp } // namespace llarp

@ -8,7 +8,7 @@ namespace llarp
const std::string& nodename, const std::string msg) const std::string& nodename, const std::string msg)
{ {
json::Object obj; json::Object obj;
obj["time"] = llarp::time_now_ms(); obj["time"] = llarp::time_now_ms().count();
obj["nickname"] = nodename; obj["nickname"] = nodename;
obj["file"] = std::string(fname); obj["file"] = std::string(fname);
obj["line"] = lineno; obj["line"] = lineno;

@ -89,29 +89,3 @@ llarp_threadpool::numThreads() const
{ {
return impl ? impl->activeThreadCount() : 0; return impl ? impl->activeThreadCount() : 0;
} }
llarp_time_t
llarp_threadpool::GuessJobLatency(llarp_time_t granularity) const
{
static const llarp_time_t minimum = llarp_time_t{10};
granularity = std::max(granularity, minimum);
const llarp_time_t _jobs = llarp_time_t{pendingJobs()} * granularity;
const llarp_time_t _capacity =
std::max(llarp_time_t{size()} * granularity, granularity);
const llarp_time_t _numthreads =
std::max(llarp_time_t{numThreads()} * granularity, granularity);
// divisor = log10(granularity)
llarp_time_t divisor = 0;
do
{
granularity /= 10;
if(granularity > 0)
divisor++;
} while(granularity > 0);
// granulairuty is minimum of 10 so log10(granulairuty) is never 0
divisor *= divisor;
// job lag is pending number of jobs divided by job queue length per thread
// divided by log10(granularity) sqaured
const llarp_time_t _queue_length = _capacity / _numthreads;
return _jobs / _queue_length / divisor;
}

@ -34,10 +34,6 @@ struct llarp_threadpool
size_t size_t
numThreads() const; numThreads() const;
/// try to guess how big our job latency is on this threadpool
llarp_time_t
GuessJobLatency(llarp_time_t granulairty = 1000) const;
/// see if this thread is full given lookahead amount /// see if this thread is full given lookahead amount
bool bool
LooksFull(size_t lookahead) const LooksFull(size_t lookahead) const

@ -10,8 +10,7 @@ namespace llarp
static llarp_time_t static llarp_time_t
time_since_epoch() time_since_epoch()
{ {
return std::chrono::duration_cast< Res >(Clock::now().time_since_epoch()) return std::chrono::duration_cast< Res >(Clock::now().time_since_epoch());
.count();
} }
const static llarp_time_t started_at_system = const static llarp_time_t started_at_system =
@ -32,16 +31,16 @@ namespace llarp
Time_t Time_t
time_now() time_now()
{ {
return Time_t(time_now_ms()); return time_now_ms();
} }
llarp_time_t llarp_time_t
time_now_ms() time_now_ms()
{ {
static llarp_time_t lastTime = 0; static llarp_time_t lastTime = 0s;
auto t = time_since_started(); auto t = time_since_started();
#ifdef TESTNET_SPEED #ifdef TESTNET_SPEED
t /= TESTNET_SPEED; t /= uint64_t(TESTNET_SPEED);
#endif #endif
t += started_at_system; t += started_at_system;
@ -49,16 +48,16 @@ namespace llarp
{ {
return lastTime; return lastTime;
} }
if(lastTime == 0) if(lastTime == 0s)
{ {
lastTime = t; lastTime = t;
} }
const auto dlt = t - lastTime; const auto dlt = t - lastTime;
if(dlt > 5000) if(dlt > 5s)
{ {
// big timeskip // big timeskip
t = lastTime; t = lastTime;
lastTime = 0; lastTime = 0s;
} }
else else
{ {

@ -2,18 +2,14 @@
#define LLARP_TIME_HPP #define LLARP_TIME_HPP
#include <util/types.hpp> #include <util/types.hpp>
#include <chrono>
#include <chrono> using namespace std::chrono_literals;
namespace llarp namespace llarp
{ {
/// get time right now as milliseconds, this is monotonic /// get time right now as milliseconds, this is monotonic
llarp_time_t llarp_time_t
time_now_ms(); time_now_ms();
using Time_t = std::chrono::milliseconds;
/// get time right now as a Time_t, monotonic /// get time right now as a Time_t, monotonic
Time_t Time_t
time_now(); time_now();

@ -2,11 +2,17 @@
#define LLARP_TYPES_H #define LLARP_TYPES_H
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#include <chrono>
using byte_t = uint8_t; using byte_t = uint8_t;
using llarp_proto_version_t = std::uint8_t; using llarp_proto_version_t = std::uint8_t;
using llarp_time_t = std::uint64_t;
using llarp_seconds_t = std::uint64_t; namespace llarp
{
using Time_t = std::chrono::milliseconds;
}
using llarp_time_t = llarp::Time_t;
namespace llarp namespace llarp
{ {

@ -20,7 +20,7 @@ TEST_F(TestDhtRCNode, construct)
ASSERT_THAT(node.ID, Property(&dht::Key_t::IsZero, true)); ASSERT_THAT(node.ID, Property(&dht::Key_t::IsZero, true));
node.ID.Fill(0xCA); node.ID.Fill(0xCA);
node.rc.last_updated = 101; node.rc.last_updated = 101s;
dht::RCNode other{node}; dht::RCNode other{node};
ASSERT_EQ(node.ID, other.ID); ASSERT_EQ(node.ID, other.ID);
@ -40,10 +40,10 @@ TEST_F(TestDhtRCNode, lt)
dht::RCNode three; dht::RCNode three;
dht::RCNode eqThree; dht::RCNode eqThree;
one.rc.last_updated = 1; one.rc.last_updated = 1s;
two.rc.last_updated = 2; two.rc.last_updated = 2s;
three.rc.last_updated = 3; three.rc.last_updated = 3s;
eqThree.rc.last_updated = 3; eqThree.rc.last_updated = 3s;
// LT cases // LT cases
ASSERT_THAT(one, Lt(two)); ASSERT_THAT(one, Lt(two));
@ -93,10 +93,10 @@ TEST_F(TestDhtISNode, lt)
dht::ISNode three; dht::ISNode three;
dht::ISNode eqThree; dht::ISNode eqThree;
one.introset.signedAt = 1; one.introset.signedAt = 1s;
two.introset.signedAt = 2; two.introset.signedAt = 2s;
three.introset.signedAt = 3; three.introset.signedAt = 3s;
eqThree.introset.signedAt = 3; eqThree.introset.signedAt = 3s;
// LT cases // LT cases
ASSERT_THAT(one, Lt(two)); ASSERT_THAT(one, Lt(two));

@ -152,7 +152,7 @@ struct LinkLayerTest : public test::LlarpTest< llarp::sodium::CryptoLibSodium >
llarp::SetLogLevel(eLogTrace); llarp::SetLogLevel(eLogTrace);
oldRCLifetime = RouterContact::Lifetime; oldRCLifetime = RouterContact::Lifetime;
RouterContact::BlockBogons = false; RouterContact::BlockBogons = false;
RouterContact::Lifetime = 500; RouterContact::Lifetime = 500ms;
netLoop = llarp_make_ev_loop(); netLoop = llarp_make_ev_loop();
m_logic.reset(new Logic()); m_logic.reset(new Logic());
Alice.Setup(); Alice.Setup();
@ -174,7 +174,7 @@ struct LinkLayerTest : public test::LlarpTest< llarp::sodium::CryptoLibSodium >
void void
RunMainloop() RunMainloop()
{ {
m_logic->call_later(5000, std::bind(&LinkLayerTest::Stop, this)); m_logic->call_later(5s, std::bind(&LinkLayerTest::Stop, this));
llarp_ev_loop_run_single_process(netLoop, m_logic); llarp_ev_loop_run_single_process(netLoop, m_logic);
} }

@ -45,10 +45,10 @@ struct AbyssTestBase : public ::testing::Test
if(server->ServeAsync(loop, logic, a)) if(server->ServeAsync(loop, logic, a))
{ {
client->RunAsync(loop, a.ToString()); client->RunAsync(loop, a.ToString());
logic->call_later(1000, std::bind(&AbyssTestBase::Stop, this)); logic->call_later(1s, std::bind(&AbyssTestBase::Stop, this));
return; return;
} }
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(1s);
} }
} }
@ -127,7 +127,7 @@ struct AbyssTest : public AbyssTestBase,
AbyssTest() AbyssTest()
: AbyssTestBase() : AbyssTestBase()
, abyss::http::JSONRPC() , abyss::http::JSONRPC()
, abyss::httpd::BaseReqHandler(1000) , abyss::httpd::BaseReqHandler(1s)
{ {
client = this; client = this;
server = this; server = this;

Loading…
Cancel
Save