1
1
Fork 0
mirror of https://github.com/oxen-io/lokinet synced 2023-12-14 06:53:00 +01:00

llarp_time_t is now using std::chrono

This commit is contained in:
Jeff Becker 2020-02-24 14:40:45 -05:00
parent f4520ac920
commit d2d109e92c
No known key found for this signature in database
GPG key ID: F357B3B42F6F9B05
73 changed files with 324 additions and 349 deletions

View file

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

View file

@ -4,6 +4,7 @@
#include <cstddef>
#include <util/types.hpp>
#include <util/time.hpp>
namespace llarp
{
@ -16,15 +17,14 @@ namespace llarp
/// pad messages to the nearest this many bytes
constexpr std::size_t pad_size = 128;
/// 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
constexpr llarp_time_t build_timeout = 30000;
static constexpr auto build_timeout = 30s;
/// 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
constexpr llarp_time_t alive_timeout = 60000;
static constexpr auto alive_timeout = 30s;
} // namespace path
} // namespace llarp

View file

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

View file

@ -35,7 +35,7 @@ llarp_dht_allow_transit(llarp_dht_context *ctx)
void
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

View file

@ -42,7 +42,7 @@ namespace llarp
std::transform(
timeouts.begin(), timeouts.end(), std::back_inserter(timeoutsObjs),
[](const auto& item) -> util::StatusObject {
return util::StatusObject{{"time", item.second},
return util::StatusObject{{"time", item.second.count()},
{"target", item.first.ToString()}};
});
obj["timeouts"] = timeoutsObjs;
@ -71,7 +71,7 @@ namespace llarp
void
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
void

View file

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

View file

@ -914,7 +914,7 @@ namespace libuv
newTimer->data = (void*)timer_data;
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);
}
}

View file

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

View file

@ -42,11 +42,11 @@ namespace llarp
IsExpired(llarp_time_t now) const;
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
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
void

View file

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

View file

@ -38,7 +38,7 @@ namespace llarp
BaseSession::ExtractStatus() const
{
auto obj = path::Builder::ExtractStatus();
obj["lastExitUse"] = m_LastUse;
obj["lastExitUse"] = m_LastUse.count();
auto pub = m_ExitIdentity.toPublic();
obj["exitIdentity"] = pub.ToString();
return obj;
@ -55,7 +55,7 @@ namespace llarp
{
const size_t expect = (1 + (numPaths / 2));
// 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);
}
@ -91,7 +91,7 @@ namespace llarp
bool
BaseSession::CheckPathDead(path::Path_ptr, llarp_time_t dlt)
{
return dlt >= 10000;
return dlt >= 10s;
}
void
@ -127,7 +127,7 @@ namespace llarp
bool
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());
CallPendingCallbacks(true);

View file

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

View file

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

View file

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

View file

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

View file

@ -46,7 +46,7 @@ namespace llarp
bool
OutboundMessage::ShouldFlush(llarp_time_t now) const
{
return now - m_LastFlush >= Session::TXFlushInterval;
return now - m_LastFlush >= TXFlushInterval;
}
void
@ -97,7 +97,7 @@ namespace llarp
OutboundMessage::IsTimedOut(const llarp_time_t now) const
{
// 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
@ -165,14 +165,13 @@ namespace llarp
bool
InboundMessage::ShouldSendACKS(llarp_time_t now) const
{
return now > m_LastACKSent + Session::ACKResendInterval;
return now > m_LastACKSent + ACKResendInterval;
}
bool
InboundMessage::IsTimedOut(const llarp_time_t now) const
{
return now > m_LastActiveAt
&& now - m_LastActiveAt > Session::DeliveryTimeout;
return now > m_LastActiveAt && now - m_LastActiveAt > DeliveryTimeout;
}
void

View file

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

View file

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

View file

@ -17,24 +17,24 @@ namespace llarp
ILinkSession::Packet_t
CreatePacket(Command cmd, size_t plainsize, size_t min_pad = 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,
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
static constexpr std::size_t MaxACKSInMACK = 1024 / sizeof(uint64_t);
@ -179,14 +179,14 @@ namespace llarp
PubKey m_ExpectedIdent;
PubKey m_RemoteOnionKey;
llarp_time_t m_LastTX = 0;
llarp_time_t m_LastRX = 0;
llarp_time_t m_LastTX = 0s;
llarp_time_t m_LastRX = 0s;
// accumulate for periodic rate calculation
uint64_t m_TXRate = 0;
uint64_t m_RXRate = 0;
llarp_time_t m_ResetRatesAt = 0;
llarp_time_t m_ResetRatesAt = 0s;
uint64_t m_TXID = 0;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -30,14 +30,6 @@ 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
{
explicit llarp_nodedb(std::shared_ptr< llarp::thread::ThreadPool > diskworker,
@ -55,9 +47,9 @@ struct llarp_nodedb
std::shared_ptr< llarp::thread::ThreadPool > disk;
mutable llarp::util::Mutex access; // protects entries
/// 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
const llarp_time_t m_SaveInterval = 60 * 5 * 1000;
const llarp_time_t m_SaveInterval = 5min;
struct NetDBEntry
{
@ -82,7 +74,7 @@ struct llarp_nodedb
/// return true if we should save our nodedb to disk
bool
ShouldSaveToDisk(llarp_time_t now = 0) const;
ShouldSaveToDisk(llarp_time_t now = 0s) const;
bool
Remove(const llarp::RouterID &pk) EXCLUDES(access);

View file

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

View file

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

View file

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

View file

@ -12,12 +12,12 @@ namespace llarp
namespace 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
{
private:
llarp_time_t m_LastWarn = 0;
llarp_time_t m_LastWarn = 0s;
protected:
/// flag for PathSet::Stop()
@ -42,7 +42,7 @@ namespace llarp
AbstractRouter* m_router;
SecretKey enckey;
size_t numHops;
llarp_time_t lastBuild = 0;
llarp_time_t lastBuild = 0s;
llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
/// construct

View file

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

View file

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

View file

@ -28,7 +28,7 @@ namespace llarp
bool
PoW::IsValid(llarp_time_t now) const
{
if(now - timestamp > (uint64_t(extendedLifetime) * 1000))
if(now - timestamp > extendedLifetime)
return false;
ShortHash digest;
@ -44,7 +44,7 @@ namespace llarp
if(!CryptoManager::instance()->shorthash(digest, buf))
return false;
// 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)
{
if(digest[idx])
@ -58,8 +58,8 @@ namespace llarp
{
Printer printer(stream, level, spaces);
printer.printAttribute("pow timestamp", timestamp);
printer.printAttribute("lifetime", extendedLifetime);
printer.printAttribute("pow timestamp", timestamp.count());
printer.printAttribute("lifetime", extendedLifetime.count());
printer.printAttribute("nonce", nonce);
return stream;

View file

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

View file

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

View file

@ -18,8 +18,8 @@ namespace llarp
uint64_t connectGoodCount = 0;
uint64_t pathSuccessCount = 0;
uint64_t pathFailCount = 0;
llarp_time_t lastUpdated = 0;
llarp_time_t lastDecay = 0;
llarp_time_t lastUpdated = 0s;
llarp_time_t lastDecay = 0s;
uint64_t version = LLARP_PROTO_VERSION;
bool
@ -113,7 +113,7 @@ namespace llarp
BEncodeNoLock(llarp_buffer_t* buf) const REQUIRES_SHARED(m_ProfilesMutex);
mutable util::Mutex m_ProfilesMutex; // protects m_Profiles
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;
};

View file

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

View file

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

View file

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

View file

@ -103,8 +103,8 @@ namespace llarp
/// node nickname, yw kee
llarp::AlignedBuffer< NICKLEN > nickname;
uint64_t last_updated = 0;
uint64_t version = LLARP_PROTO_VERSION;
llarp_time_t last_updated = 0s;
uint64_t version = LLARP_PROTO_VERSION;
nonstd::optional< RouterVersion > routerVersion;
util::StatusObject
@ -179,7 +179,7 @@ namespace llarp
/// does this RC expire soon? default delta is 1 minute
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
bool

View file

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

View file

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

View file

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

View file

@ -77,7 +77,7 @@ namespace llarp
std::set< Introduction > I;
if(!GetCurrentIntroductionsWithFilter(
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(),
@ -196,7 +196,7 @@ namespace llarp
if(!EndpointUtil::HasPathToService(addr, m_state->m_RemoteSessions))
{
if(!EnsurePathToService(
addr, [](Address, OutboundContext*) {}, 10000))
addr, [](Address, OutboundContext*) {}, 10s))
{
LogWarn("failed to ensure path to ", addr);
}
@ -1242,7 +1242,7 @@ namespace llarp
}
self->m_state->m_PendingTraffic.erase(addr);
},
1500);
1500ms);
}
}
return false;

View file

@ -22,7 +22,7 @@
// minimum time between introset shifts
#ifndef MIN_SHIFT_INTERVAL
#define MIN_SHIFT_INTERVAL (5 * 1000)
#define MIN_SHIFT_INTERVAL 5s
#endif
struct llarp_async_verify_rc;
@ -59,16 +59,16 @@ namespace llarp
};
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,
public ILookupHolder,
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;
Endpoint(const std::string& nickname, AbstractRouter* r, Context* parent);
@ -288,7 +288,7 @@ namespace llarp
/// address
bool
EnsurePathToService(const Address remote, PathEnsureHook h,
uint64_t timeoutMS);
llarp_time_t timeoutMS);
using SNodeEnsureHook =
std::function< void(const RouterID, exit::BaseSession_ptr) >;

View file

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

View file

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

View file

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

View file

@ -16,9 +16,9 @@ namespace llarp
{
PubKey router;
PathID_t pathID;
uint64_t latency = 0;
uint64_t expiresAt = 0;
uint64_t version = LLARP_PROTO_VERSION;
llarp_time_t latency = 0s;
llarp_time_t expiresAt = 0s;
uint64_t version = LLARP_PROTO_VERSION;
util::StatusObject
ExtractStatus() const;
@ -30,7 +30,7 @@ namespace llarp
}
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);
}

View file

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

View file

@ -22,7 +22,7 @@ namespace llarp
{
constexpr std::size_t MAX_INTROSET_SIZE = 4096;
// 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
{
@ -30,7 +30,7 @@ namespace llarp
std::vector< Introduction > I;
PQPubKey K;
Tag topic;
llarp_time_t T = 0;
llarp_time_t T = 0s;
nonstd::optional< PoW > W;
Signature Z;
uint64_t version = LLARP_PROTO_VERSION;
@ -108,7 +108,7 @@ namespace llarp
using Payload_t = std::vector< byte_t >;
PubKey derivedSigningKey;
llarp_time_t signedAt = 0;
llarp_time_t signedAt = 0s;
Payload_t introsetPayload;
TunnelNonce nounce;
nonstd::optional< Tag > topic;

View file

@ -35,7 +35,7 @@ namespace llarp
/// determine if this request has timed out
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)
return false;
@ -63,7 +63,7 @@ namespace llarp
{"endpoint", endpoint.ToHex()},
{"name", name},
{"timedOut", IsTimedOut(now)},
{"createdAt", m_created}};
{"createdAt", m_created.count()}};
return obj;
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -88,12 +88,15 @@ namespace llarp
{
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,
" for integer in dict");
return false;
}
i = Int_t(read_i);
read = true;
}
return true;

View file

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

View file

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

View file

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

View file

@ -89,29 +89,3 @@ llarp_threadpool::numThreads() const
{
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;
}

View file

@ -34,10 +34,6 @@ struct llarp_threadpool
size_t
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
bool
LooksFull(size_t lookahead) const

View file

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

View file

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

View file

@ -2,11 +2,17 @@
#define LLARP_TYPES_H
#include <cstdint>
#include <string>
#include <chrono>
using byte_t = 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
{

View file

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

View file

@ -152,7 +152,7 @@ struct LinkLayerTest : public test::LlarpTest< llarp::sodium::CryptoLibSodium >
llarp::SetLogLevel(eLogTrace);
oldRCLifetime = RouterContact::Lifetime;
RouterContact::BlockBogons = false;
RouterContact::Lifetime = 500;
RouterContact::Lifetime = 500ms;
netLoop = llarp_make_ev_loop();
m_logic.reset(new Logic());
Alice.Setup();
@ -174,7 +174,7 @@ struct LinkLayerTest : public test::LlarpTest< llarp::sodium::CryptoLibSodium >
void
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);
}

View file

@ -45,10 +45,10 @@ struct AbyssTestBase : public ::testing::Test
if(server->ServeAsync(loop, logic, a))
{
client->RunAsync(loop, a.ToString());
logic->call_later(1000, std::bind(&AbyssTestBase::Stop, this));
logic->call_later(1s, std::bind(&AbyssTestBase::Stop, this));
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()
: AbyssTestBase()
, abyss::http::JSONRPC()
, abyss::httpd::BaseReqHandler(1000)
, abyss::httpd::BaseReqHandler(1s)
{
client = this;
server = this;