From d2d109e92c6139b2553796c662aaafea3bcd8542 Mon Sep 17 00:00:00 2001 From: Jeff Becker Date: Mon, 24 Feb 2020 14:40:45 -0500 Subject: [PATCH] llarp_time_t is now using std::chrono --- llarp/constants/link_layer.hpp | 7 ++-- llarp/constants/path.hpp | 10 +++--- llarp/dht/context.cpp | 10 +++--- llarp/dht/dht.cpp | 2 +- llarp/dht/txholder.hpp | 4 +-- llarp/ev/ev.hpp | 6 ++-- llarp/ev/ev_libuv.cpp | 2 +- llarp/exit/endpoint.cpp | 8 ++--- llarp/exit/endpoint.hpp | 4 +-- llarp/exit/exit_messages.hpp | 2 +- llarp/exit/session.cpp | 8 ++--- llarp/exit/session.hpp | 3 +- llarp/handlers/exit.hpp | 2 +- llarp/handlers/tun.cpp | 10 +++--- llarp/handlers/tun.hpp | 2 +- llarp/iwp/message_buffer.cpp | 9 +++-- llarp/iwp/message_buffer.hpp | 10 +++--- llarp/iwp/session.cpp | 6 ++-- llarp/iwp/session.hpp | 34 +++++++++---------- llarp/link/link_manager.cpp | 2 +- llarp/link/server.cpp | 8 ++--- llarp/link/server.hpp | 2 +- llarp/messages/relay_commit.cpp | 21 ++++++------ llarp/messages/relay_commit.hpp | 4 +-- llarp/nodedb.cpp | 4 +-- llarp/nodedb.hpp | 14 ++------ llarp/path/path.cpp | 37 ++++++++++++--------- llarp/path/path.hpp | 10 +++--- llarp/path/pathbuilder.cpp | 16 +++++---- llarp/path/pathbuilder.hpp | 6 ++-- llarp/path/transit_hop.cpp | 4 +-- llarp/path/transit_hop.hpp | 6 ++-- llarp/pow.cpp | 8 ++--- llarp/pow.hpp | 4 +-- llarp/profiling.cpp | 8 ++--- llarp/profiling.hpp | 6 ++-- llarp/router/router.cpp | 46 +++++++++++++------------- llarp/router/router.hpp | 10 +++--- llarp/router_contact.cpp | 20 +++++------ llarp/router_contact.hpp | 6 ++-- llarp/routing/path_confirm_message.cpp | 6 ++-- llarp/routing/path_confirm_message.hpp | 10 +++--- llarp/rpc/rpc.cpp | 12 +++---- llarp/service/endpoint.cpp | 6 ++-- llarp/service/endpoint.hpp | 16 ++++----- llarp/service/endpoint_state.cpp | 6 ++-- llarp/service/endpoint_state.hpp | 6 ++-- llarp/service/intro.cpp | 18 +++++----- llarp/service/intro.hpp | 8 ++--- llarp/service/intro_set.cpp | 14 ++++---- llarp/service/intro_set.hpp | 6 ++-- llarp/service/lookup.hpp | 4 +-- llarp/service/outbound_context.cpp | 18 +++++----- llarp/service/outbound_context.hpp | 2 +- llarp/service/protocol.hpp | 2 +- llarp/service/router_lookup_job.hpp | 2 +- llarp/service/sendcontext.cpp | 4 +-- llarp/service/sendcontext.hpp | 8 ++--- llarp/service/session.cpp | 2 +- llarp/service/session.hpp | 8 ++--- llarp/service/tag_lookup_job.hpp | 6 ++-- llarp/util/bencode.hpp | 5 ++- llarp/util/codel.hpp | 30 +++++++++-------- llarp/util/logging/file_logger.hpp | 2 +- llarp/util/logging/json_logger.cpp | 2 +- llarp/util/thread/threadpool.cpp | 26 --------------- llarp/util/thread/threadpool.h | 4 --- llarp/util/time.cpp | 15 ++++----- llarp/util/time.hpp | 6 +--- llarp/util/types.hpp | 10 ++++-- test/dht/test_llarp_dht_node.cpp | 18 +++++----- test/link/test_llarp_link.cpp | 4 +-- test/test_libabyss.cpp | 6 ++-- 73 files changed, 324 insertions(+), 349 deletions(-) diff --git a/llarp/constants/link_layer.hpp b/llarp/constants/link_layer.hpp index 74c32950c..5637d6a55 100644 --- a/llarp/constants/link_layer.hpp +++ b/llarp/constants/link_layer.hpp @@ -1,10 +1,11 @@ #ifndef LLARP_LINK_LAYER_HPP #define LLARP_LINK_LAYER_HPP #include +#include #include -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 diff --git a/llarp/constants/path.hpp b/llarp/constants/path.hpp index f226ecc31..e7f79c74e 100644 --- a/llarp/constants/path.hpp +++ b/llarp/constants/path.hpp @@ -4,6 +4,7 @@ #include #include +#include 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 diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index 44b85c655..ec6d6c131 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -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 diff --git a/llarp/dht/dht.cpp b/llarp/dht/dht.cpp index 472f7c3f7..4f3738427 100644 --- a/llarp/dht/dht.cpp +++ b/llarp/dht/dht.cpp @@ -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 diff --git a/llarp/dht/txholder.hpp b/llarp/dht/txholder.hpp index c069bf5c0..387b7a544 100644 --- a/llarp/dht/txholder.hpp +++ b/llarp/dht/txholder.hpp @@ -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 diff --git a/llarp/ev/ev.hpp b/llarp/ev/ev.hpp index e8f853061..ad8874896 100644 --- a/llarp/ev/ev.hpp +++ b/llarp/ev/ev.hpp @@ -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 >; diff --git a/llarp/ev/ev_libuv.cpp b/llarp/ev/ev_libuv.cpp index f28e70678..58088dbc2 100644 --- a/llarp/ev/ev_libuv.cpp +++ b/llarp/ev/ev_libuv.cpp @@ -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); } } diff --git a/llarp/exit/endpoint.cpp b/llarp/exit/endpoint.cpp index a2af62245..1fe3c9bbd 100644 --- a/llarp/exit/endpoint.cpp +++ b/llarp/exit/endpoint.cpp @@ -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 diff --git a/llarp/exit/endpoint.hpp b/llarp/exit/endpoint.hpp index d72da1ea6..8a19a6381 100644 --- a/llarp/exit/endpoint.hpp +++ b/llarp/exit/endpoint.hpp @@ -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 diff --git a/llarp/exit/exit_messages.hpp b/llarp/exit/exit_messages.hpp index 6f7ffffbb..8f32b51d8 100644 --- a/llarp/exit/exit_messages.hpp +++ b/llarp/exit/exit_messages.hpp @@ -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() diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index efa5206c9..8d9f7c695 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -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); diff --git a/llarp/exit/session.hpp b/llarp/exit/session.hpp index 550173ce6..29ffa7496 100644 --- a/llarp/exit/session.hpp +++ b/llarp/exit/session.hpp @@ -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, diff --git a/llarp/handlers/exit.hpp b/llarp/handlers/exit.hpp index 2fe15738a..e26b6a6eb 100644 --- a/llarp/handlers/exit.hpp +++ b/llarp/handlers/exit.hpp @@ -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; diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index d95aef442..3bb57721a 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -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 diff --git a/llarp/handlers/tun.hpp b/llarp/handlers/tun.hpp index 21f40666e..3599b7b1f 100644 --- a/llarp/handlers/tun.hpp +++ b/llarp/handlers/tun.hpp @@ -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 >; diff --git a/llarp/iwp/message_buffer.cpp b/llarp/iwp/message_buffer.cpp index 1c143fdd4..1d2f371b9 100644 --- a/llarp/iwp/message_buffer.cpp +++ b/llarp/iwp/message_buffer.cpp @@ -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 diff --git a/llarp/iwp/message_buffer.hpp b/llarp/iwp/message_buffer.hpp index c15e484d3..78870e0e7 100644 --- a/llarp/iwp/message_buffer.hpp +++ b/llarp/iwp/message_buffer.hpp @@ -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 \ No newline at end of file +#endif diff --git a/llarp/iwp/session.cpp b/llarp/iwp/session.cpp index c5379d74f..a9085eb3e 100644 --- a/llarp/iwp/session.cpp +++ b/llarp/iwp/session.cpp @@ -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 diff --git a/llarp/iwp/session.hpp b/llarp/iwp/session.hpp index 219ed5c4f..6194afaab 100644 --- a/llarp/iwp/session.hpp +++ b/llarp/iwp/session.hpp @@ -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; diff --git a/llarp/link/link_manager.cpp b/llarp/link/link_manager.cpp index 94a9fbb81..8790b12b7 100644 --- a/llarp/link/link_manager.cpp +++ b/llarp/link/link_manager.cpp @@ -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 diff --git a/llarp/link/server.cpp b/llarp/link/server.cpp index 6025054f1..9e67a3ab6 100644 --- a/llarp/link/server.cpp +++ b/llarp/link/server.cpp @@ -7,7 +7,7 @@ #include #include -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)); diff --git a/llarp/link/server.hpp b/llarp/link/server.hpp index c975b3ca6..c46d14899 100644 --- a/llarp/link/server.hpp +++ b/llarp/link/server.hpp @@ -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; diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index 621578604..aa0a6f49b 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -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 diff --git a/llarp/messages/relay_commit.hpp b/llarp/messages/relay_commit.hpp index 8f432e320..e6b265c34 100644 --- a/llarp/messages/relay_commit.hpp +++ b/llarp/messages/relay_commit.hpp @@ -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); diff --git a/llarp/nodedb.cpp b/llarp/nodedb.cpp index ef02ffe43..6c2282a1b 100644 --- a/llarp/nodedb.cpp +++ b/llarp/nodedb.cpp @@ -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 diff --git a/llarp/nodedb.hpp b/llarp/nodedb.hpp index cefd10161..90c959a5d 100644 --- a/llarp/nodedb.hpp +++ b/llarp/nodedb.hpp @@ -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); diff --git a/llarp/path/path.cpp b/llarp/path/path.cpp index a08a91608..cad98cdcf 100644 --- a/llarp/path/path.cpp +++ b/llarp/path/path.cpp @@ -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; diff --git a/llarp/path/path.hpp b/llarp/path/path.hpp index 68b9c74c5..fe2e7817f 100644 --- a/llarp/path/path.hpp +++ b/llarp/path/path.hpp @@ -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; diff --git a/llarp/path/pathbuilder.cpp b/llarp/path/pathbuilder.cpp index 43f72b591..ac132a456 100644 --- a/llarp/path/pathbuilder.cpp +++ b/llarp/path/pathbuilder.cpp @@ -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 diff --git a/llarp/path/pathbuilder.hpp b/llarp/path/pathbuilder.hpp index 6e1a9d78d..2917d1e9f 100644 --- a/llarp/path/pathbuilder.hpp +++ b/llarp/path/pathbuilder.hpp @@ -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 diff --git a/llarp/path/transit_hop.cpp b/llarp/path/transit_hop.cpp index 9cd94272b..d797fc5b0 100644 --- a/llarp/path/transit_hop.cpp +++ b/llarp/path/transit_hop.cpp @@ -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; } diff --git a/llarp/path/transit_hop.hpp b/llarp/path/transit_hop.hpp index a9c5824bc..b962151ce 100644 --- a/llarp/path/transit_hop.hpp +++ b/llarp/path/transit_hop.hpp @@ -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(); diff --git a/llarp/pow.cpp b/llarp/pow.cpp index 7588ce5a2..93b03a403 100644 --- a/llarp/pow.cpp +++ b/llarp/pow.cpp @@ -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; diff --git a/llarp/pow.hpp b/llarp/pow.hpp index d9cfd0aee..d9a90f2f3 100644 --- a/llarp/pow.hpp +++ b/llarp/pow.hpp @@ -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; diff --git a/llarp/profiling.cpp b/llarp/profiling.cpp index 7588fe165..be1b547ee 100644 --- a/llarp/profiling.cpp +++ b/llarp/profiling.cpp @@ -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 diff --git a/llarp/profiling.hpp b/llarp/profiling.hpp index b397b4728..2edf6147d 100644 --- a/llarp/profiling.hpp +++ b/llarp/profiling.hpp @@ -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; }; diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index d0e3b73da..97fd8cb53 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -32,7 +32,7 @@ #include #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 diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index bf3ad2e07..0d4416154 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -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; diff --git a/llarp/router_contact.cpp b/llarp/router_contact.cpp index fc4c07921..614e38b97 100644 --- a/llarp/router_contact.cpp +++ b/llarp/router_contact.cpp @@ -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); diff --git a/llarp/router_contact.hpp b/llarp/router_contact.hpp index e103151a8..442394032 100644 --- a/llarp/router_contact.hpp +++ b/llarp/router_contact.hpp @@ -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 diff --git a/llarp/routing/path_confirm_message.cpp b/llarp/routing/path_confirm_message.cpp index 8d824b1cb..b0fab5f4a 100644 --- a/llarp/routing/path_confirm_message.cpp +++ b/llarp/routing/path_confirm_message.cpp @@ -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; diff --git a/llarp/routing/path_confirm_message.hpp b/llarp/routing/path_confirm_message.hpp index fc36e8a30..d51368096 100644 --- a/llarp/routing/path_confirm_message.hpp +++ b/llarp/routing/path_confirm_message.hpp @@ -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; } }; diff --git a/llarp/rpc/rpc.cpp b/llarp/rpc/rpc.cpp index 23d5f9ebb..664833e4a 100644 --- a/llarp/rpc/rpc.cpp +++ b/llarp/rpc/rpc.cpp @@ -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) { } diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 10e3b8c61..4243e4909 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -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; diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index f4dc21790..9d2f968fc 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -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) >; diff --git a/llarp/service/endpoint_state.cpp b/llarp/service/endpoint_state.cpp index d60e5d566..63339c2ec 100644 --- a/llarp/service/endpoint_state.cpp +++ b/llarp/service/endpoint_state.cpp @@ -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()) diff --git a/llarp/service/endpoint_state.hpp b/llarp/service/endpoint_state.hpp index 59f214f62..86579814d 100644 --- a/llarp/service/endpoint_state.hpp +++ b/llarp/service/endpoint_state.hpp @@ -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 diff --git a/llarp/service/intro.cpp b/llarp/service/intro.cpp index deaf49e86..0fecfa2e1 100644 --- a/llarp/service/intro.cpp +++ b/llarp/service/intro.cpp @@ -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; } diff --git a/llarp/service/intro.hpp b/llarp/service/intro.hpp index c2f0040d6..dea0e0ea8 100644 --- a/llarp/service/intro.hpp +++ b/llarp/service/intro.hpp @@ -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); } diff --git a/llarp/service/intro_set.cpp b/llarp/service/intro_set.cpp index 15ed76158..e3034b2bd 100644 --- a/llarp/service/intro_set.cpp +++ b/llarp/service/intro_set.cpp @@ -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()); diff --git a/llarp/service/intro_set.hpp b/llarp/service/intro_set.hpp index ddb5d87b3..8e223f90c 100644 --- a/llarp/service/intro_set.hpp +++ b/llarp/service/intro_set.hpp @@ -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; diff --git a/llarp/service/lookup.hpp b/llarp/service/lookup.hpp index e84df2fde..32ed65e0b 100644 --- a/llarp/service/lookup.hpp +++ b/llarp/service/lookup.hpp @@ -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; } diff --git a/llarp/service/outbound_context.cpp b/llarp/service/outbound_context.cpp index 4c999c27e..844d53554 100644 --- a/llarp/service/outbound_context.cpp +++ b/llarp/service/outbound_context.cpp @@ -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); diff --git a/llarp/service/outbound_context.hpp b/llarp/service/outbound_context.hpp index 938ddf3ce..5d8e2ace3 100644 --- a/llarp/service/outbound_context.hpp +++ b/llarp/service/outbound_context.hpp @@ -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; }; diff --git a/llarp/service/protocol.hpp b/llarp/service/protocol.hpp index c26963986..39a4b5ebc 100644 --- a/llarp/service/protocol.hpp +++ b/llarp/service/protocol.hpp @@ -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; diff --git a/llarp/service/router_lookup_job.hpp b/llarp/service/router_lookup_job.hpp index 504ad44a0..167b2dd60 100644 --- a/llarp/service/router_lookup_job.hpp +++ b/llarp/service/router_lookup_job.hpp @@ -22,7 +22,7 @@ namespace llarp { if(now < started) return false; - return now - started > 30000; + return now - started > 30s; } void diff --git a/llarp/service/sendcontext.cpp b/llarp/service/sendcontext.cpp index 813ea1701..4b230d884 100644 --- a/llarp/service/sendcontext.cpp +++ b/llarp/service/sendcontext.cpp @@ -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); } diff --git a/llarp/service/sendcontext.hpp b/llarp/service/sendcontext.hpp index 3cbb0e674..463234d18 100644 --- a/llarp/service/sendcontext.hpp +++ b/llarp/service/sendcontext.hpp @@ -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 >; diff --git a/llarp/service/session.cpp b/llarp/service/session.cpp index d7c13ce19..f93afbe29 100644 --- a/llarp/service/session.cpp +++ b/llarp/service/session.cpp @@ -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}, diff --git a/llarp/service/session.hpp b/llarp/service/session.hpp index 654bb2be0..1391e00f6 100644 --- a/llarp/service/session.hpp +++ b/llarp/service/session.hpp @@ -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 diff --git a/llarp/service/tag_lookup_job.hpp b/llarp/service/tag_lookup_job.hpp index 447ef0a77..a67ce8c8f 100644 --- a/llarp/service/tag_lookup_job.hpp +++ b/llarp/service/tag_lookup_job.hpp @@ -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; diff --git a/llarp/util/bencode.hpp b/llarp/util/bencode.hpp index e7ac81e84..8b0a74538 100644 --- a/llarp/util/bencode.hpp +++ b/llarp/util/bencode.hpp @@ -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; diff --git a/llarp/util/codel.hpp b/llarp/util/codel.hpp index e304083ab..5580548bb 100644 --- a/llarp/util/codel.hpp +++ b/llarp/util/codel.hpp @@ -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); diff --git a/llarp/util/logging/file_logger.hpp b/llarp/util/logging/file_logger.hpp index 117869295..5d7ab2736 100644 --- a/llarp/util/logging/file_logger.hpp +++ b/llarp/util/logging/file_logger.hpp @@ -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 diff --git a/llarp/util/logging/json_logger.cpp b/llarp/util/logging/json_logger.cpp index 8acb416b7..d280049e0 100644 --- a/llarp/util/logging/json_logger.cpp +++ b/llarp/util/logging/json_logger.cpp @@ -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; diff --git a/llarp/util/thread/threadpool.cpp b/llarp/util/thread/threadpool.cpp index ead887723..3ca57b035 100644 --- a/llarp/util/thread/threadpool.cpp +++ b/llarp/util/thread/threadpool.cpp @@ -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; -} diff --git a/llarp/util/thread/threadpool.h b/llarp/util/thread/threadpool.h index 2f2e71b35..a75808655 100644 --- a/llarp/util/thread/threadpool.h +++ b/llarp/util/thread/threadpool.h @@ -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 diff --git a/llarp/util/time.cpp b/llarp/util/time.cpp index 282a658f8..d7edd2dce 100644 --- a/llarp/util/time.cpp +++ b/llarp/util/time.cpp @@ -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 { diff --git a/llarp/util/time.hpp b/llarp/util/time.hpp index f9f58e228..d468b912f 100644 --- a/llarp/util/time.hpp +++ b/llarp/util/time.hpp @@ -2,18 +2,14 @@ #define LLARP_TIME_HPP #include -#include -#include +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(); diff --git a/llarp/util/types.hpp b/llarp/util/types.hpp index 2fd423b27..e01a6bc2f 100644 --- a/llarp/util/types.hpp +++ b/llarp/util/types.hpp @@ -2,11 +2,17 @@ #define LLARP_TYPES_H #include #include +#include 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 { diff --git a/test/dht/test_llarp_dht_node.cpp b/test/dht/test_llarp_dht_node.cpp index 8e462b9c9..8eedbe874 100644 --- a/test/dht/test_llarp_dht_node.cpp +++ b/test/dht/test_llarp_dht_node.cpp @@ -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)); diff --git a/test/link/test_llarp_link.cpp b/test/link/test_llarp_link.cpp index 1f9a8222e..f7c06ee6b 100644 --- a/test/link/test_llarp_link.cpp +++ b/test/link/test_llarp_link.cpp @@ -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); } diff --git a/test/test_libabyss.cpp b/test/test_libabyss.cpp index d937c1def..2eb256bea 100644 --- a/test/test_libabyss.cpp +++ b/test/test_libabyss.cpp @@ -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;