mirror of
https://github.com/ratspeak/microReticulum
synced 2026-11-22 23:10:38 +00:00
WIP: Enhancements to persistence
This commit is contained in:
1 parent
63a16a5391
commit
f415b5e0b5
14 files changed
+693
-288
No files matched your search
@@ -73,7 +73,10 @@ namespace RNS {
|
||||
virtual bool write_file(const Bytes& data, const char* file_path) { return false; }
|
||||
virtual bool remove_file(const char* file_path) { return false; }
|
||||
virtual bool rename_file(const char* from_file_path, const char* to_file_path) { return false; }
|
||||
virtual bool directory_exists(const char* directory_path) { return false; }
|
||||
virtual bool create_directory(const char* directory_path) { return false; }
|
||||
virtual bool remove_directory(const char* directory_path) { return false; }
|
||||
virtual std::list<std::string> list_directory(const char* directory_path) { return _empty; }
|
||||
|
||||
public:
|
||||
inline bool do_file_exists(const char* file_path) { assert(_object); return _object->do_file_exists(file_path); }
|
||||
@@ -81,7 +84,13 @@ namespace RNS {
|
||||
inline bool do_write_file(const Bytes& data, const char* file_path) { assert(_object); return _object->do_write_file(data, file_path); }
|
||||
inline bool do_remove_file(const char* file_path) { assert(_object); return _object->do_remove_file(file_path); }
|
||||
inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { assert(_object); return _object->do_rename_file(from_file_path, to_file_path); }
|
||||
inline bool do_directory_exists(const char* directory_path) { assert(_object); return _object->do_directory_exists(directory_path); }
|
||||
inline bool do_create_directory(const char* directory_path) { assert(_object); return _object->do_create_directory(directory_path); }
|
||||
inline bool do_remove_directory(const char* directory_path) { assert(_object); return _object->do_remove_directory(directory_path); }
|
||||
virtual std::list<std::string> do_list_directory(const char* directory_path) { assert(_object); return _object->do_list_directory(directory_path); }
|
||||
|
||||
private:
|
||||
std::list<std::string> _empty;
|
||||
|
||||
// getters/setters
|
||||
protected:
|
||||
@@ -107,11 +116,17 @@ namespace RNS {
|
||||
virtual inline bool do_write_file(const Bytes& data, const char* file_path) { if (_parent == nullptr) return false; return _parent->write_file(data, file_path); }
|
||||
virtual inline bool do_remove_file(const char* file_path) { if (_parent == nullptr) return false; return _parent->remove_file(file_path); }
|
||||
virtual inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { if (_parent == nullptr) return false; return _parent->rename_file(from_file_path, to_file_path); }
|
||||
virtual inline bool do_directory_exists(const char* directory_path) { if (_parent == nullptr) return false; return _parent->directory_exists(directory_path); }
|
||||
virtual inline bool do_create_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->create_directory(directory_path); }
|
||||
virtual inline bool do_remove_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->remove_directory(directory_path); }
|
||||
virtual inline std::list<std::string> do_list_directory(const char* directory_path) { if (_parent == nullptr) return _empty; return _parent->do_list_directory(directory_path); }
|
||||
private:
|
||||
Filesystem* _parent = nullptr;
|
||||
std::list<std::string> _empty;
|
||||
friend class Filesystem;
|
||||
};
|
||||
|
||||
private:
|
||||
std::shared_ptr<Object> _object;
|
||||
bool _creator = false;
|
||||
|
||||
|
||||
@@ -439,6 +439,16 @@ Recall last heard app_data for a destination hash.
|
||||
return false;
|
||||
}
|
||||
|
||||
/*static*/ void Identity::persist_data() {
|
||||
if (!Transport::reticulum() || !Transport::reticulum().is_connected_to_shared_instance()) {
|
||||
save_known_destinations();
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ void Identity::exit_handler() {
|
||||
persist_data();
|
||||
}
|
||||
|
||||
/*
|
||||
Encrypts information for the identity.
|
||||
|
||||
|
||||
@@ -141,6 +141,8 @@ namespace RNS {
|
||||
}
|
||||
|
||||
static bool validate_announce(const Packet& packet);
|
||||
static void persist_data();
|
||||
static void exit_handler();
|
||||
|
||||
// getters/setters
|
||||
inline const Bytes& encryptionPrivateKey() const { assert(_object); return _object->_prv_bytes; }
|
||||
|
||||
+14
-1
@@ -1,5 +1,7 @@
|
||||
#include "Log.h"
|
||||
|
||||
#include "Utilities/OS.h"
|
||||
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
@@ -10,7 +12,7 @@ using namespace RNS;
|
||||
LogLevel _level = LOG_EXTREME;
|
||||
//LogLevel _level = LOG_MEM;
|
||||
RNS::log_callback _on_log = nullptr;
|
||||
char _datetime[32];
|
||||
char _datetime[20];
|
||||
|
||||
const char* RNS::getLevelName(LogLevel level) {
|
||||
switch (level) {
|
||||
@@ -38,6 +40,16 @@ const char* RNS::getLevelName(LogLevel level) {
|
||||
}
|
||||
|
||||
const char* RNS::getTimeString() {
|
||||
#ifdef ARDUINO
|
||||
uint64_t time = Utilities::OS::ltime();
|
||||
if (time < 86400000) {
|
||||
snprintf(_datetime, sizeof(_datetime), "%02d:%02d:%02d.%03d", (int)(time/3600000), (int)((time/60000)%60), (int)((time/1000)%60), (int)(time%1000));
|
||||
}
|
||||
else {
|
||||
snprintf(_datetime, sizeof(_datetime), "%02d-%02d:%02d:%02d.%03d", (int)(time/86400000), (int)((time/3600000)%24), (int)((time/60000)%60), (int)((time/1000)%60), (int)(time%1000));
|
||||
}
|
||||
return _datetime;
|
||||
#else
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv, nullptr);
|
||||
int millis = lrint(tv.tv_usec/1000.0);
|
||||
@@ -49,6 +61,7 @@ const char* RNS::getTimeString() {
|
||||
size_t len = strftime(_datetime, sizeof(_datetime), "%Y-%m-%d %H:%M:%S", tm);
|
||||
sprintf(_datetime+len, ".%03d", millis);
|
||||
return _datetime;
|
||||
#endif
|
||||
}
|
||||
|
||||
void RNS::loglevel(LogLevel level) {
|
||||
|
||||
+4
-1
@@ -225,6 +225,8 @@ namespace RNS {
|
||||
inline uint8_t flags() const { assert(_object); return _object->_flags; }
|
||||
inline uint8_t hops() const { assert(_object); return _object->_hops; }
|
||||
inline void hops(uint8_t hops) { assert(_object); _object->_hops = hops; }
|
||||
inline const bool cached() const { assert(_object); return _object->_cached; }
|
||||
inline void cached(bool cached) { assert(_object); _object->_cached = cached; }
|
||||
inline const Bytes& packet_hash() const { assert(_object); return _object->_packet_hash; }
|
||||
inline const Bytes& destination_hash() const { assert(_object); return _object->_destination_hash; }
|
||||
inline const Bytes& transport_id() const { assert(_object); return _object->_transport_id; }
|
||||
@@ -265,7 +267,8 @@ namespace RNS {
|
||||
bool _create_receipt = false;
|
||||
bool _fromPacked = false;
|
||||
bool _truncated = false; // whether data was truncated
|
||||
bool _encrypted = false; // whether data is encrytpted
|
||||
bool _encrypted = false; // whether data is encrypted
|
||||
bool _cached = false; // whether packet has been cached
|
||||
PacketReceipt _receipt = {Type::NONE};
|
||||
|
||||
uint16_t _mtu = Type::Reticulum::MTU;
|
||||
|
||||
+106
-33
@@ -2,7 +2,6 @@
|
||||
|
||||
#include "Transport.h"
|
||||
#include "Log.h"
|
||||
#include "Utilities/OS.h"
|
||||
|
||||
#include <RNG.h>
|
||||
|
||||
@@ -13,6 +12,7 @@
|
||||
|
||||
using namespace RNS;
|
||||
using namespace RNS::Type::Reticulum;
|
||||
using namespace RNS::Utilities;
|
||||
|
||||
/*static*/ std::string Reticulum::_storagepath;
|
||||
/*static*/ std::string Reticulum::_cachepath;
|
||||
@@ -78,43 +78,13 @@ Reticulum::Reticulum() : _object(new Object()) {
|
||||
// CBA MOCK
|
||||
#ifdef ARDUINO
|
||||
_storagepath = "";
|
||||
_cachepath = "";
|
||||
_cachepath = "/cache";
|
||||
#else
|
||||
_storagepath = ".";
|
||||
_cachepath = ".";
|
||||
_cachepath = "./cache";
|
||||
#endif
|
||||
|
||||
/* TODO
|
||||
Reticulum.__transport_enabled = False
|
||||
Reticulum.__use_implicit_proof = True
|
||||
Reticulum.__allow_probes = False
|
||||
|
||||
Reticulum.panic_on_interface_error = False
|
||||
|
||||
self.local_interface_port = 37428
|
||||
self.local_control_port = 37429
|
||||
self.share_instance = True
|
||||
self.rpc_listener = None
|
||||
|
||||
self.ifac_salt = Reticulum.IFAC_SALT
|
||||
|
||||
self.requested_loglevel = loglevel
|
||||
self.requested_verbosity = verbosity
|
||||
if self.requested_loglevel != None:
|
||||
if self.requested_loglevel > RNS.LOG_EXTREME:
|
||||
self.requested_loglevel = RNS.LOG_EXTREME
|
||||
if self.requested_loglevel < RNS.LOG_CRITICAL:
|
||||
self.requested_loglevel = RNS.LOG_CRITICAL
|
||||
|
||||
RNS.loglevel = self.requested_loglevel
|
||||
|
||||
self.is_shared_instance = False
|
||||
self.is_connected_to_shared_instance = False
|
||||
self.is_standalone_instance = False
|
||||
self.jobs_thread = None
|
||||
self.last_data_persist = time.time()
|
||||
self.last_cache_clean = 0
|
||||
|
||||
if not os.path.isdir(Reticulum.storagepath):
|
||||
os.makedirs(Reticulum.storagepath)
|
||||
|
||||
@@ -167,6 +137,36 @@ Reticulum::Reticulum() : _object(new Object()) {
|
||||
mem("Reticulum default object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
}
|
||||
|
||||
/*p TODO
|
||||
@staticmethod
|
||||
def exit_handler():
|
||||
# This exit handler is called whenever Reticulum is asked to
|
||||
# shut down, and will in turn call exit handlers in other
|
||||
# classes, saving necessary information to disk and carrying
|
||||
# out cleanup operations.
|
||||
|
||||
RNS.Transport.exit_handler()
|
||||
RNS.Identity.exit_handler()
|
||||
|
||||
@staticmethod
|
||||
def sigint_handler(signal, frame):
|
||||
RNS.Transport.detach_interfaces()
|
||||
RNS.exit()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def sigterm_handler(signal, frame):
|
||||
RNS.Transport.detach_interfaces()
|
||||
RNS.exit()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def get_instance():
|
||||
"""
|
||||
Return the currently running Reticulum instance
|
||||
"""
|
||||
return Reticulum.__instance
|
||||
*/
|
||||
|
||||
void Reticulum::start() {
|
||||
Transport::start(*this);
|
||||
@@ -175,8 +175,81 @@ void Reticulum::start() {
|
||||
void Reticulum::loop() {
|
||||
assert(_object);
|
||||
if (!_object->_is_connected_to_shared_instance) {
|
||||
|
||||
if (OS::time() > (_jobs_last_run + JOB_INTERVAL)) {
|
||||
jobs();
|
||||
_jobs_last_run = OS::time();
|
||||
}
|
||||
|
||||
RNS::Transport::loop();
|
||||
}
|
||||
// Perform random number gnerator housekeeping
|
||||
RNG.loop();
|
||||
}
|
||||
|
||||
void Reticulum::jobs() {
|
||||
|
||||
double now = OS::time();
|
||||
|
||||
if (now > _last_cache_clean + CLEAN_INTERVAL) {
|
||||
clean_caches();
|
||||
_last_cache_clean = OS::time();
|
||||
}
|
||||
|
||||
if (now > _last_data_persist + PERSIST_INTERVAL) {
|
||||
persist_data();
|
||||
}
|
||||
}
|
||||
|
||||
void Reticulum::should_persist_data() {
|
||||
if (OS::time() > _last_data_persist + GRACIOUS_PERSIST_INTERVAL) {
|
||||
persist_data();
|
||||
}
|
||||
}
|
||||
|
||||
void Reticulum::persist_data() {
|
||||
Transport::persist_data();
|
||||
Identity::persist_data();
|
||||
_last_data_persist = OS::time();
|
||||
}
|
||||
|
||||
void Reticulum::clean_caches() {
|
||||
extreme("Cleaning resource and packet caches...");
|
||||
double now = OS::time();
|
||||
|
||||
/*
|
||||
// Clean resource caches
|
||||
for (auto& filename : OS::list_directory(resourcepath) {
|
||||
try {
|
||||
if (filename.length() == (Type::Identity::HASHLENGTH//8)*2) {
|
||||
std::string filepath = _resourcepath + "/" + filename;
|
||||
//p mtime = os.path.getmtime(filepath)
|
||||
//p age = now - mtime
|
||||
//p if (age > Types::Reticulum.RESOURCE_CACHE) {
|
||||
//p OS::remove_file(filepath);
|
||||
//p }
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
error("Error while cleaning resources cache, the contained exception was: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
// Clean packet caches
|
||||
for (auto& filename : OS::list_directory(_cachepath.c_str())) {
|
||||
try {
|
||||
if (filename.length() == (Type::Identity::HASHLENGTH/8)*2) {
|
||||
std::string filepath = _cachepath + "/" + filename;
|
||||
//p mtime = os.path.getmtime(filepath)
|
||||
//p age = now - mtime
|
||||
//p if (age > Types::Transport::DESTINATION_TIMEOUT) {
|
||||
//p OS::remove_file(filepath);
|
||||
//p }
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
error("Error while cleaning packet cache, the contained exception was: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "Log.h"
|
||||
#include "Type.h"
|
||||
#include "Utilities/OS.h"
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
@@ -33,6 +34,23 @@ namespace RNS {
|
||||
static bool __allow_probes;
|
||||
static bool panic_on_interface_error;
|
||||
|
||||
uint16_t _local_interface_port = 37428;
|
||||
uint16_t _local_control_port = 37429;
|
||||
bool _share_instance = true;
|
||||
//p _rpc_listener = None
|
||||
|
||||
//p _ifac_salt = Reticulum.IFAC_SALT
|
||||
|
||||
bool _is_shared_instance = false;
|
||||
bool _is_connected_to_shared_instance = false;
|
||||
bool _is_standalone_instance = false;
|
||||
//p _jobs_thread = None
|
||||
double _last_data_persist = Utilities::OS::time();
|
||||
double _last_cache_clean = 0.0;
|
||||
|
||||
// CBA
|
||||
double _jobs_last_run = Utilities::OS::time();
|
||||
|
||||
public:
|
||||
Reticulum(Type::NoneConstructor none) {
|
||||
mem("Reticulum NONE object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
@@ -60,6 +78,10 @@ namespace RNS {
|
||||
public:
|
||||
void start();
|
||||
void loop();
|
||||
void jobs();
|
||||
void should_persist_data();
|
||||
void persist_data();
|
||||
void clean_caches();
|
||||
|
||||
/*
|
||||
Returns whether proofs sent are explicit or implicit.
|
||||
|
||||
+301
-234
@@ -18,6 +18,9 @@ using namespace RNS;
|
||||
using namespace RNS::Type::Transport;
|
||||
using namespace RNS::Utilities;
|
||||
|
||||
// Imported from Crypto.cpp
|
||||
extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
|
||||
|
||||
#if defined(INTERFACES_SET)
|
||||
///*static*/ std::set<std::reference_wrapper<const Interface>, std::less<const Interface>> Transport::_interfaces;
|
||||
/*static*/ std::set<std::reference_wrapper<Interface>, std::less<Interface>> Transport::_interfaces;
|
||||
@@ -42,11 +45,11 @@ using namespace RNS::Utilities;
|
||||
/*static*/ std::map<Bytes, Transport::LinkEntry> Transport::_link_table;
|
||||
/*static*/ std::map<Bytes, Transport::AnnounceEntry> Transport::_held_announces;
|
||||
/*static*/ std::set<HAnnounceHandler> Transport::_announce_handlers;
|
||||
/*static*/ std::map<Bytes, Transport::TunnelEntry> Transport::_tunnels;
|
||||
/*static*/ std::map<Bytes, double> Transport::_path_requests;
|
||||
|
||||
/*static*/ std::map<Bytes, Transport::PathRequestEntry> Transport::_discovery_path_requests;
|
||||
/*static*/ std::set<Bytes> Transport::_discovery_pr_tags;
|
||||
/*static*/ uint16_t Transport::_max_pr_tags = 32000;
|
||||
|
||||
/*static*/ std::set<Destination> Transport::_control_destinations;
|
||||
/*static*/ std::set<Bytes> Transport::_control_hashes;
|
||||
@@ -61,22 +64,31 @@ using namespace RNS::Utilities;
|
||||
/*static*/ double Transport::_start_time = 0;
|
||||
/*static*/ bool Transport::_jobs_locked = false;
|
||||
/*static*/ bool Transport::_jobs_running = false;
|
||||
/*static*/ float Transport::_job_interval = 0.250;
|
||||
/*static*/ float Transport::_job_interval = 0.250;
|
||||
/*static*/ double Transport::_jobs_last_run = 0;
|
||||
/*static*/ double Transport::_links_last_checked = 0;
|
||||
/*static*/ float Transport::_links_check_interval = 1.0;
|
||||
/*static*/ double Transport::_receipts_last_checked = 0;
|
||||
/*static*/ float Transport::_links_check_interval = 1.0;
|
||||
/*static*/ double Transport::_receipts_last_checked = 0;
|
||||
/*static*/ float Transport::_receipts_check_interval = 1.0;
|
||||
/*static*/ double Transport::_announces_last_checked = 0;
|
||||
/*static*/ float Transport::_announces_check_interval= 1.0;
|
||||
/*static*/ double Transport::_tables_last_culled = 0;
|
||||
/*static*/ float Transport::_tables_cull_interval = 5.0;
|
||||
/*static*/ float Transport::_announces_check_interval = 1.0;
|
||||
/*static*/ double Transport::_tables_last_culled = 0.0;
|
||||
// CBA MCU
|
||||
/*static*/ //float Transport::_tables_cull_interval = 5.0;
|
||||
/*static*/ float Transport::_tables_cull_interval = 60.0;
|
||||
/*static*/ bool Transport::_saving_path_table = false;
|
||||
/*static*/ uint32_t Transport::_hashlist_maxsize = 1000000;
|
||||
// CBA MCU
|
||||
/*static*/ //uint16_t Transport::_hashlist_maxsize = 1000000;
|
||||
/*static*/ uint16_t Transport::_hashlist_maxsize = 10000;
|
||||
// CBA MCU
|
||||
/*static*/ //uint16_t Transport::_max_pr_tags = 32000;
|
||||
/*static*/ uint16_t Transport::_max_pr_tags = 320;
|
||||
|
||||
// CBA
|
||||
/*static*/ double Transport::_last_saved = 0;
|
||||
/*static*/ float Transport::_save_interval = 3600;
|
||||
/*static*/ uint16_t Transport::_path_table_maxsize = 200;
|
||||
/*static*/ double Transport::_last_saved = 0.0;
|
||||
/*static*/ float Transport::_save_interval = 3600.0;
|
||||
/*static*/ uint8_t Transport::_destination_table_crc = 0;
|
||||
|
||||
/*static*/ Reticulum Transport::_owner({Type::NONE});
|
||||
/*static*/ Identity Transport::_identity({Type::NONE});
|
||||
@@ -89,6 +101,23 @@ using namespace RNS::Utilities;
|
||||
_jobs_running = true;
|
||||
_owner = reticulum_instance;
|
||||
|
||||
// ensure required directories exist
|
||||
if (!OS::directory_exists(Reticulum::_cachepath.c_str())) {
|
||||
verbose("No cache directory, creating...");
|
||||
OS::create_directory(Reticulum::_cachepath.c_str());
|
||||
}
|
||||
|
||||
#ifdef ARDUINO
|
||||
// load time offset from file if it exists
|
||||
std::string time_offset_path = Reticulum::_storagepath + "/time_offset";
|
||||
if (OS::file_exists(time_offset_path.c_str())) {
|
||||
Bytes buf = OS::read_file(time_offset_path.c_str());
|
||||
uint64_t offset = *(uint64_t*)buf.data();
|
||||
debug("Read time offset of " + std::to_string(offset) + " from file");
|
||||
OS::setTimeOffset(offset);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!_identity) {
|
||||
std::string transport_identity_path = Reticulum::_storagepath + "/transport_identity";
|
||||
debug("Checking for transport identity...");
|
||||
@@ -205,12 +234,22 @@ using namespace RNS::Utilities;
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
_destination_table = doc.as<std::map<Bytes, DestinationEntry>>();
|
||||
RNS::extreme("Transport::start: successfully deserialized");
|
||||
#ifndef NDEBUG
|
||||
for (auto& [hash, entry] : _destination_table) {
|
||||
RNS::extreme("Transport::start: entry: " + hash.toHex() + " = " + entry.debugString());
|
||||
RNS::extreme("Transport::start: successfully deserialized path table");
|
||||
// Calculate crc for dirty-checking before write
|
||||
_destination_table_crc = crypto_crc8(0, data.data(), data.size());
|
||||
std::vector<Bytes> invalid_paths;
|
||||
for (auto& [destination_hash, destination_entry] : _destination_table) {
|
||||
RNS::extreme("Transport::start: entry: " + destination_hash.toHex() + " = " + destination_entry.debugString());
|
||||
// CBA TODO If announce packet load fails then remove destination en try (it's useless without announce packet)
|
||||
if (!destination_entry._announce_packet) {
|
||||
// remove destination
|
||||
RNS::extreme("Transport::start: removing invalid path " + destination_hash.toHex());
|
||||
invalid_paths.push_back(destination_hash);
|
||||
}
|
||||
}
|
||||
for (const auto& destination_hash : invalid_paths) {
|
||||
_destination_table.erase(destination_hash);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
RNS::extreme("Transport::start: failed to deserialize");
|
||||
@@ -310,17 +349,11 @@ using namespace RNS::Utilities;
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ void Transport::jobloop() {
|
||||
while (true) {
|
||||
jobs();
|
||||
OS::sleep(_job_interval);
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ void Transport::jobs() {
|
||||
|
||||
std::vector<Packet> outgoing;
|
||||
std::set<Bytes> path_requests;
|
||||
int count;
|
||||
_jobs_running = true;
|
||||
|
||||
try {
|
||||
@@ -348,7 +381,8 @@ using namespace RNS::Utilities;
|
||||
|
||||
if ((OS::time() - last_path_request) > Type::Transport::PATH_REQUEST_MI) {
|
||||
debug("Trying to rediscover path for " + link.destination().hash().toHex() + " since an attempted link was never established");
|
||||
if (path_requests.find(link.destination().hash()) == path_requests.end()) {
|
||||
//if (path_requests.find(link.destination().hash()) == path_requests.end()) {
|
||||
if (path_requests.count(link.destination().hash()) == 0) {
|
||||
path_requests.insert(link.destination().hash());
|
||||
}
|
||||
}
|
||||
@@ -377,17 +411,19 @@ using namespace RNS::Utilities;
|
||||
culled_receipt.check_timeout();
|
||||
}
|
||||
|
||||
// TODO (erase while iterating)
|
||||
/*
|
||||
std::list<PacketReceipt> cull_receipts;
|
||||
for (auto& receipt : _receipts) {
|
||||
receipt.check_timeout();
|
||||
if (receipt.status() != Type::PacketReceipt::SENT) {
|
||||
// CBA Can NOT modify collection while iterating!
|
||||
//z if receipt in Transport.receipts:
|
||||
//z Transport.receipts.remove(receipt)
|
||||
//p if receipt in Transport.receipts:
|
||||
//p Transport.receipts.remove(receipt)
|
||||
cull_receipts.push_back(receipt);
|
||||
}
|
||||
}
|
||||
*/
|
||||
// CBA since modifying of collection while iterating is forbidden
|
||||
for (auto& receipt : _receipts) {
|
||||
cull_receipts.remove(receipt);
|
||||
}
|
||||
|
||||
_receipts_last_checked = OS::time();
|
||||
}
|
||||
@@ -480,210 +516,225 @@ using namespace RNS::Utilities;
|
||||
_announces_last_checked = OS::time();
|
||||
}
|
||||
|
||||
// TODO
|
||||
/*
|
||||
// Cull the packet hashlist if it has reached its max size
|
||||
if len(Transport.packet_hashlist) > Transport.hashlist_maxsize:
|
||||
Transport.packet_hashlist = Transport.packet_hashlist[len(Transport.packet_hashlist)-Transport.hashlist_maxsize:len(Transport.packet_hashlist)-1]
|
||||
if (_packet_hashlist.size() > _hashlist_maxsize) {
|
||||
std::set<Bytes>::iterator iter = _packet_hashlist.begin();
|
||||
std::advance(iter, _packet_hashlist.size() - _hashlist_maxsize);
|
||||
_packet_hashlist.erase(_packet_hashlist.begin(), iter);
|
||||
}
|
||||
|
||||
// Cull the path request tags list if it has reached its max size
|
||||
if len(Transport.discovery_pr_tags) > Transport.max_pr_tags:
|
||||
Transport.discovery_pr_tags = Transport.discovery_pr_tags[len(Transport.discovery_pr_tags)-Transport.max_pr_tags:len(Transport.discovery_pr_tags)-1]
|
||||
if (_discovery_pr_tags.size() > _max_pr_tags) {
|
||||
std::set<Bytes>::iterator iter = _discovery_pr_tags.begin();
|
||||
std::advance(iter, _discovery_pr_tags.size() - _max_pr_tags);
|
||||
_discovery_pr_tags.erase(_discovery_pr_tags.begin(), iter);
|
||||
}
|
||||
|
||||
// Cull the path table if it has reached its max size
|
||||
if (_destination_table.size() > _path_table_maxsize) {
|
||||
// TODO prune by age, or better yet by last use
|
||||
std::map<Bytes, DestinationEntry>::iterator iter = _destination_table.begin();
|
||||
std::advance(iter, _destination_table.size() - _path_table_maxsize);
|
||||
_destination_table.erase(_destination_table.begin(), iter);
|
||||
}
|
||||
|
||||
if (OS::time() > (_tables_last_culled + _tables_cull_interval)) {
|
||||
|
||||
if time.time() > Transport.tables_last_culled + Transport.tables_cull_interval:
|
||||
// Cull the reverse table according to timeout
|
||||
stale_reverse_entries = []
|
||||
for truncated_packet_hash in Transport.reverse_table:
|
||||
reverse_entry = Transport.reverse_table[truncated_packet_hash]
|
||||
if time.time() > reverse_entry[2] + Transport.REVERSE_TIMEOUT:
|
||||
stale_reverse_entries.append(truncated_packet_hash)
|
||||
std::vector<Bytes> stale_reverse_entries;
|
||||
for (const auto& [packet_hash, reverse_entry] : _reverse_table) {
|
||||
if (OS::time() > (reverse_entry._timestamp + REVERSE_TIMEOUT)) {
|
||||
stale_reverse_entries.push_back(packet_hash);
|
||||
}
|
||||
}
|
||||
|
||||
// Cull the link table according to timeout
|
||||
stale_links = []
|
||||
for link_id in Transport.link_table:
|
||||
link_entry = Transport.link_table[link_id]
|
||||
std::vector<Bytes> stale_links;
|
||||
for (const auto& [link_id, link_entry] : _link_table) {
|
||||
if (link_entry._validated) {
|
||||
if (OS::time() > (link_entry._timestamp + LINK_TIMEOUT)) {
|
||||
stale_links.push_back(link_id);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (OS::time() > link_entry._proof_timeout) {
|
||||
stale_links.push_back(link_id);
|
||||
|
||||
if link_entry[7] == True:
|
||||
if time.time() > link_entry[0] + Transport.LINK_TIMEOUT:
|
||||
stale_links.append(link_id)
|
||||
else:
|
||||
if time.time() > link_entry[8]:
|
||||
stale_links.append(link_id)
|
||||
double last_path_request = 0.0;
|
||||
const auto& iter = _path_requests.find(link_entry._destination_hash);
|
||||
if (iter != _path_requests.end()) {
|
||||
last_path_request = (*iter).second;
|
||||
}
|
||||
|
||||
last_path_request = 0
|
||||
if link_entry[6] in Transport.path_requests:
|
||||
last_path_request = Transport.path_requests[link_entry[6]]
|
||||
uint8_t lr_taken_hops = link_entry._hops;
|
||||
|
||||
lr_taken_hops = link_entry[5]
|
||||
|
||||
path_request_throttle = time.time() - last_path_request < Transport.PATH_REQUEST_MI
|
||||
path_request_conditions = False
|
||||
bool path_request_throttle = (OS::time() - last_path_request) < PATH_REQUEST_MI;
|
||||
bool path_request_conditions = false;
|
||||
|
||||
// If the path has been invalidated between the time of
|
||||
// making the link request and now, try to rediscover it
|
||||
if not Transport.has_path(link_entry[6]):
|
||||
RNS.log("Trying to rediscover path for "+RNS.prettyhexrep(link_entry[6])+" since an attempted link was never established, and path is now missing", RNS.LOG_DEBUG)
|
||||
path_request_conditions =True
|
||||
if (!has_path(link_entry._destination_hash)) {
|
||||
debug("Trying to rediscover path for " + link_entry._destination_hash.toHex() + " since an attempted link was never established, and path is now missing");
|
||||
path_request_conditions = true;
|
||||
}
|
||||
|
||||
// If this link request was originated from a local client
|
||||
// attempt to rediscover a path to the destination, if this
|
||||
// has not already happened recently.
|
||||
elif not path_request_throttle and lr_taken_hops == 0:
|
||||
RNS.log("Trying to rediscover path for "+RNS.prettyhexrep(link_entry[6])+" since an attempted local client link was never established", RNS.LOG_DEBUG)
|
||||
path_request_conditions = True
|
||||
else if (!path_request_throttle && lr_taken_hops == 0) {
|
||||
debug("Trying to rediscover path for " + link_entry._destination_hash.toHex() + " since an attempted local client link was never established");
|
||||
path_request_conditions = true;
|
||||
}
|
||||
|
||||
// If the link destination was previously only 1 hop
|
||||
// away, this likely means that it was local to one
|
||||
// of our interfaces, and that it roamed somewhere else.
|
||||
// In that case, try to discover a new path.
|
||||
elif not path_request_throttle and Transport.hops_to(link_entry[6]) == 1:
|
||||
RNS.log("Trying to rediscover path for "+RNS.prettyhexrep(link_entry[6])+" since an attempted link was never established, and destination was previously local to an interface on this instance", RNS.LOG_DEBUG)
|
||||
path_request_conditions = True
|
||||
else if (!path_request_throttle && hops_to(link_entry._destination_hash) == 1) {
|
||||
debug("Trying to rediscover path for " + link_entry._destination_hash.toHex() + " since an attempted link was never established, and destination was previously local to an interface on this instance");
|
||||
path_request_conditions = true;
|
||||
}
|
||||
|
||||
// If the link destination was previously only 1 hop
|
||||
// away, this likely means that it was local to one
|
||||
// of our interfaces, and that it roamed somewhere else.
|
||||
// In that case, try to discover a new path.
|
||||
elif not path_request_throttle and lr_taken_hops == 1:
|
||||
RNS.log("Trying to rediscover path for "+RNS.prettyhexrep(link_entry[6])+" since an attempted link was never established, and link initiator is local to an interface on this instance", RNS.LOG_DEBUG)
|
||||
path_request_conditions = True
|
||||
else if ( !path_request_throttle and lr_taken_hops == 1) {
|
||||
debug("Trying to rediscover path for " + link_entry._destination_hash.toHex() + " since an attempted link was never established, and link initiator is local to an interface on this instance");
|
||||
path_request_conditions = true;
|
||||
}
|
||||
|
||||
if path_request_conditions:
|
||||
if not link_entry[6] in path_requests:
|
||||
path_requests.append(link_entry[6])
|
||||
if (path_request_conditions) {
|
||||
if (path_requests.count(link_entry._destination_hash) == 0) {
|
||||
path_requests.insert(link_entry._destination_hash);
|
||||
}
|
||||
|
||||
if not RNS.Reticulum.transport_enabled():
|
||||
if (!Reticulum::transport_enabled()) {
|
||||
// Drop current path if we are not a transport instance, to
|
||||
// allow using higher-hop count paths or reused announces
|
||||
// from newly adjacent transport instances.
|
||||
Transport.expire_path(link_entry[6])
|
||||
expire_path(link_entry._destination_hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cull the path table
|
||||
stale_paths = []
|
||||
for destination_hash in Transport.destination_table:
|
||||
destination_entry = Transport.destination_table[destination_hash]
|
||||
attached_interface = destination_entry[5]
|
||||
std::vector<Bytes> stale_paths;
|
||||
for (const auto& [destination_hash, destination_entry] : _destination_table) {
|
||||
const auto& attached_interface = destination_entry._receiving_interface;
|
||||
double destination_expiry;
|
||||
if (attached_interface && attached_interface.mode() == Type::Interface::MODE_ACCESS_POINT) {
|
||||
destination_expiry = destination_entry._timestamp + AP_PATH_TIME;
|
||||
}
|
||||
else if (attached_interface && attached_interface.mode() == Type::Interface::MODE_ROAMING) {
|
||||
destination_expiry = destination_entry._timestamp + ROAMING_PATH_TIME;
|
||||
}
|
||||
else {
|
||||
destination_expiry = destination_entry._timestamp + DESTINATION_TIMEOUT;
|
||||
}
|
||||
|
||||
if attached_interface != None and hasattr(attached_interface, "mode") and attached_interface.mode == RNS.Interfaces.Interface.Interface.MODE_ACCESS_POINT:
|
||||
destination_expiry = destination_entry[0] + Transport.AP_PATH_TIME
|
||||
elif attached_interface != None and hasattr(attached_interface, "mode") and attached_interface.mode == RNS.Interfaces.Interface.Interface.MODE_ROAMING:
|
||||
destination_expiry = destination_entry[0] + Transport.ROAMING_PATH_TIME
|
||||
else:
|
||||
destination_expiry = destination_entry[0] + Transport.DESTINATION_TIMEOUT
|
||||
|
||||
if time.time() > destination_expiry:
|
||||
stale_paths.append(destination_hash)
|
||||
RNS.log("Path to "+RNS.prettyhexrep(destination_hash)+" timed out and was removed", RNS.LOG_DEBUG)
|
||||
elif not attached_interface in Transport.interfaces:
|
||||
stale_paths.append(destination_hash)
|
||||
RNS.log("Path to "+RNS.prettyhexrep(destination_hash)+" was removed since the attached interface no longer exists", RNS.LOG_DEBUG)
|
||||
if (OS::time() > destination_expiry) {
|
||||
stale_paths.push_back(destination_hash);
|
||||
debug("Path to " + destination_hash.toHex() + " timed out and was removed");
|
||||
}
|
||||
else if (_interfaces.count(attached_interface.get_hash()) == 0) {
|
||||
stale_paths.push_back(destination_hash);
|
||||
debug("Path to " + destination_hash.toHex() + " was removed since the attached interface no longer exists");
|
||||
}
|
||||
}
|
||||
|
||||
// Cull the pending discovery path requests table
|
||||
stale_discovery_path_requests = []
|
||||
for destination_hash in Transport.discovery_path_requests:
|
||||
entry = Transport.discovery_path_requests[destination_hash]
|
||||
|
||||
if time.time() > entry["timeout"]:
|
||||
stale_discovery_path_requests.append(destination_hash)
|
||||
RNS.log("Waiting path request for "+RNS.prettyhexrep(destination_hash)+" timed out and was removed", RNS.LOG_DEBUG)
|
||||
std::vector<Bytes> stale_discovery_path_requests;
|
||||
for (const auto& [destination_hash, path_entry] : _discovery_path_requests) {
|
||||
if (OS::time() > path_entry._timeout) {
|
||||
stale_discovery_path_requests.push_back(destination_hash);
|
||||
debug("Waiting path request for " + destination_hash.toString() + " timed out and was removed");
|
||||
}
|
||||
}
|
||||
|
||||
// Cull the tunnel table
|
||||
stale_tunnels = []
|
||||
ti = 0
|
||||
for tunnel_id in Transport.tunnels:
|
||||
tunnel_entry = Transport.tunnels[tunnel_id]
|
||||
|
||||
expires = tunnel_entry[3]
|
||||
if time.time() > expires:
|
||||
stale_tunnels.append(tunnel_id)
|
||||
RNS.log("Tunnel "+RNS.prettyhexrep(tunnel_id)+" timed out and was removed", RNS.LOG_EXTREME)
|
||||
else:
|
||||
stale_tunnel_paths = []
|
||||
tunnel_paths = tunnel_entry[2]
|
||||
for tunnel_path in tunnel_paths:
|
||||
tunnel_path_entry = tunnel_paths[tunnel_path]
|
||||
|
||||
if time.time() > tunnel_path_entry[0] + Transport.DESTINATION_TIMEOUT:
|
||||
stale_tunnel_paths.append(tunnel_path)
|
||||
RNS.log("Tunnel path to "+RNS.prettyhexrep(tunnel_path)+" timed out and was removed", RNS.LOG_EXTREME)
|
||||
|
||||
for tunnel_path in stale_tunnel_paths:
|
||||
tunnel_paths.pop(tunnel_path)
|
||||
ti += 1
|
||||
|
||||
|
||||
if ti > 0:
|
||||
if ti == 1:
|
||||
RNS.log("Removed "+str(ti)+" tunnel path", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Removed "+str(ti)+" tunnel paths", RNS.LOG_EXTREME)
|
||||
|
||||
count = 0;
|
||||
std::vector<Bytes> stale_tunnels;
|
||||
for (const auto& [tunnel_id, tunnel_entry] : _tunnels) {
|
||||
if (OS::time() > tunnel_entry._expires) {
|
||||
stale_tunnels.push_back(tunnel_id);
|
||||
extreme("Tunnel " + tunnel_id.toHex() + " timed out and was removed");
|
||||
}
|
||||
else {
|
||||
std::vector<Bytes> stale_tunnel_paths;
|
||||
for (const auto& [destination_hash, destination_entry] : tunnel_entry._serialised_paths) {
|
||||
if (OS::time() > (destination_entry._timestamp + DESTINATION_TIMEOUT)) {
|
||||
stale_tunnel_paths.push_back(destination_hash);
|
||||
extreme("Tunnel path to " + destination_hash.toHex() + " timed out and was removed");
|
||||
}
|
||||
}
|
||||
|
||||
//for (const auto& destination_hash : stale_tunnel_paths) {
|
||||
for (const Bytes& destination_hash : stale_tunnel_paths) {
|
||||
const_cast<TunnelEntry&>(tunnel_entry)._serialised_paths.erase(destination_hash);
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Removed " + std::to_string(count) + " tunnel paths");
|
||||
}
|
||||
|
||||
i = 0
|
||||
for truncated_packet_hash in stale_reverse_entries:
|
||||
Transport.reverse_table.pop(truncated_packet_hash)
|
||||
i += 1
|
||||
count = 0;
|
||||
for (const auto& truncated_packet_hash : stale_reverse_entries) {
|
||||
_reverse_table.erase(truncated_packet_hash);
|
||||
++count;
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Released " + std::to_string(count) + " reverse table entries");
|
||||
}
|
||||
|
||||
if i > 0:
|
||||
if i == 1:
|
||||
RNS.log("Released "+str(i)+" reverse table entry", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Released "+str(i)+" reverse table entries", RNS.LOG_EXTREME)
|
||||
count = 0;
|
||||
for (const auto& link_id : stale_links) {
|
||||
_link_table.erase(link_id);
|
||||
++count;
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Released " + std::to_string(count) + " links");
|
||||
}
|
||||
|
||||
|
||||
count = 0;
|
||||
for (const auto& destination_hash : stale_paths) {
|
||||
//_destination_table.erase(destination_hash);
|
||||
remove_path(destination_hash);
|
||||
++count;
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Removed " + std::to_string(count) + " paths");
|
||||
}
|
||||
|
||||
i = 0
|
||||
for link_id in stale_links:
|
||||
Transport.link_table.pop(link_id)
|
||||
i += 1
|
||||
count = 0;
|
||||
for (const auto& destination_hash : stale_discovery_path_requests) {
|
||||
_discovery_path_requests.erase(destination_hash);
|
||||
++count;
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Removed " + std::to_string(count) + " waiting path requests");
|
||||
}
|
||||
|
||||
if i > 0:
|
||||
if i == 1:
|
||||
RNS.log("Released "+str(i)+" link", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Released "+str(i)+" links", RNS.LOG_EXTREME)
|
||||
count = 0;
|
||||
for (const auto& tunnel_id : stale_tunnels) {
|
||||
_tunnels.erase(tunnel_id);
|
||||
++count;
|
||||
}
|
||||
if (count > 0) {
|
||||
extreme("Removed " + std::to_string(count) + " tunnels");
|
||||
}
|
||||
|
||||
i = 0
|
||||
for destination_hash in stale_paths:
|
||||
Transport.destination_table.pop(destination_hash)
|
||||
i += 1
|
||||
|
||||
if i > 0:
|
||||
if i == 1:
|
||||
RNS.log("Removed "+str(i)+" path", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Removed "+str(i)+" paths", RNS.LOG_EXTREME)
|
||||
|
||||
i = 0
|
||||
for destination_hash in stale_discovery_path_requests:
|
||||
Transport.discovery_path_requests.pop(destination_hash)
|
||||
i += 1
|
||||
|
||||
if i > 0:
|
||||
if i == 1:
|
||||
RNS.log("Removed "+str(i)+" waiting path request", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Removed "+str(i)+" waiting path requests", RNS.LOG_EXTREME)
|
||||
|
||||
i = 0
|
||||
for tunnel_id in stale_tunnels:
|
||||
Transport.tunnels.pop(tunnel_id)
|
||||
i += 1
|
||||
|
||||
if i > 0:
|
||||
if i == 1:
|
||||
RNS.log("Removed "+str(i)+" tunnel", RNS.LOG_EXTREME)
|
||||
else:
|
||||
RNS.log("Removed "+str(i)+" tunnels", RNS.LOG_EXTREME)
|
||||
|
||||
Transport.tables_last_culled = time.time()
|
||||
*/
|
||||
_tables_last_culled = OS::time();
|
||||
}
|
||||
|
||||
// Periodically persist data
|
||||
if (OS::time() > (_last_saved + _save_interval)) {
|
||||
// CBA temporarily disabled for testing with empty destination table
|
||||
//persist_data();
|
||||
persist_data();
|
||||
_last_saved = OS::time();
|
||||
}
|
||||
}
|
||||
@@ -1067,34 +1118,26 @@ using namespace RNS::Utilities;
|
||||
|
||||
if (!queued_announces) {
|
||||
double wait_time = std::max(interface.announce_allowed_at() - OS::time(), (double)0);
|
||||
|
||||
// CBA TODO THREAD?
|
||||
//z timer = threading.Timer(wait_time, interface.process_announce_queue)
|
||||
//z timer.start()
|
||||
|
||||
std::string wait_time_str;
|
||||
if (wait_time < 1000) {
|
||||
wait_time_str = std::to_string(wait_time) + "ms";
|
||||
extreme("Added announce to queue (height " + std::to_string(interface.announce_queue().size()) + ") on " + interface.toString() + " for processing in " + std::to_string(wait_time) + "ms");
|
||||
}
|
||||
else {
|
||||
wait_time_str = std::to_string(OS::round(wait_time/1000,1)) + "s";
|
||||
extreme("Added announce to queue (height " + std::to_string(interface.announce_queue().size()) + ") on " + interface.toString() + " for processing in " + std::to_string(OS::round(wait_time/1000,1)) + "s");
|
||||
}
|
||||
|
||||
std::string ql_str = std::to_string(interface.announce_queue().size());
|
||||
extreme("Added announce to queue (height " + ql_str + ") on " + interface.toString() + " for processing in " + wait_time_str);
|
||||
}
|
||||
else {
|
||||
double wait_time = std::max(interface.announce_allowed_at() - OS::time(), (double)0);
|
||||
|
||||
std::string wait_time_str;
|
||||
if (wait_time < 1000) {
|
||||
wait_time_str = std::to_string(wait_time) + "ms";
|
||||
extreme("Added announce to queue (height " + std::to_string(interface.announce_queue().size()) + ") on " + interface.toString() + " for processing in " + std::to_string(wait_time) + "ms");
|
||||
}
|
||||
else {
|
||||
wait_time_str = std::to_string(OS::round(wait_time/1000,2)) + "s";
|
||||
extreme("Added announce to queue (height " + std::to_string(interface.announce_queue().size()) + ") on " + interface.toString() + " for processing in " + std::to_string(OS::round(wait_time/1000,2)) + "s");
|
||||
}
|
||||
|
||||
std::string ql_str = std::to_string(interface.announce_queue().size());
|
||||
extreme("Added announce to queue (height " + ql_str + ") on " + interface.toString() + " for processing in " + wait_time_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2647,23 +2690,7 @@ Deregisters an announce handler.
|
||||
if (should_cache(packet) || force_cache) {
|
||||
extreme("Saving packet " + packet.get_hash().toHex() + " to storage");
|
||||
try {
|
||||
/*p
|
||||
packet_hash = RNS.hexrep(packet.get_hash(), delimit=False)
|
||||
interface_reference = None
|
||||
if packet.receiving_interface != None:
|
||||
interface_reference = str(packet.receiving_interface)
|
||||
|
||||
file = open(RNS.Reticulum.cachepath+"/"+packet_hash, "wb")
|
||||
file.write(umsgpack.packb([packet.raw, interface_reference]))
|
||||
file.close()
|
||||
*/
|
||||
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet.get_hash().toHex();
|
||||
// CBA remporarily disabled until CachedPacket is implemented
|
||||
/*
|
||||
DynamicJsonDocument doc(1024);
|
||||
doc.set(packet);
|
||||
return Persistence::serialize(doc, packet_cache_path.c_str(), 1024);
|
||||
*/
|
||||
return Persistence::serialize(packet, packet_cache_path.c_str(), 1024);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
@@ -2674,7 +2701,7 @@ Deregisters an announce handler.
|
||||
}
|
||||
|
||||
/*static*/ Packet Transport::get_cached_packet(const Bytes& packet_hash) {
|
||||
extreme("Loading packet " + packet_hash.toHex() + " to storage");
|
||||
extreme("Loading packet " + packet_hash.toHex() + " from cache storage");
|
||||
try {
|
||||
/*p
|
||||
packet_hash = RNS.hexrep(packet_hash, delimit=False)
|
||||
@@ -2697,14 +2724,6 @@ Deregisters an announce handler.
|
||||
return None
|
||||
*/
|
||||
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex();
|
||||
// CBA remporarily disabled until CachedPacket is implemented since this results in recursive calls
|
||||
// due to Packet deserializer calling get_cached_packet()
|
||||
/*
|
||||
DynamicJsonDocument doc(1024);
|
||||
if (Persistence::deserialize(doc, packet_cache_path.c_str())) {
|
||||
return doc.as<Packet>();
|
||||
}
|
||||
*/
|
||||
//return Persistence::deserialize(packet_cache_path.c_str());
|
||||
Packet packet({Type::NONE});
|
||||
Persistence::deserialize(packet, packet_cache_path.c_str());
|
||||
@@ -2717,6 +2736,27 @@ Deregisters an announce handler.
|
||||
return {Type::NONE};
|
||||
}
|
||||
|
||||
/*static*/ bool Transport::clear_cached_packet(const Bytes& packet_hash) {
|
||||
extreme("Clearing packet " + packet_hash.toHex() + " from cache storage");
|
||||
try {
|
||||
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex();
|
||||
double start_time = OS::time();
|
||||
bool success = RNS::Utilities::OS::remove_file(packet_cache_path.c_str());
|
||||
double diff_time = OS::time() - start_time;
|
||||
if (diff_time < 1.0) {
|
||||
debug("Remove cached packet in " + std::to_string(diff_time * 1000) + " ms");
|
||||
}
|
||||
else {
|
||||
debug("Remove cached packet in " + std::to_string(diff_time) + " s");
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
error("Exception occurred while clearing cached packet.");
|
||||
error("The contained exception was: " + std::string(e.what()));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*static*/ bool Transport::cache_request_packet(const Packet& packet) {
|
||||
if (packet.data().size() == Type::Identity::HASHLENGTH/8) {
|
||||
const Packet& cached_packet = get_cached_packet(packet.data());
|
||||
@@ -2753,6 +2793,13 @@ Deregisters an announce handler.
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ bool Transport::remove_path(const Bytes& destination_hash) {
|
||||
if (_destination_table.erase(destination_hash) > 0) {
|
||||
// CBA also remove cached announce packet if exists
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
:param destination_hash: A destination hash as *bytes*.
|
||||
:returns: *True* if a path to the destination is known, otherwise *False*.
|
||||
@@ -3134,7 +3181,8 @@ will announce it.
|
||||
#elif defined(INTERFACES_MAP)
|
||||
for (auto& [hash, interface] : _interfaces) {
|
||||
#endif
|
||||
// CBA TEST consider forwarding path requests even on requestor interface
|
||||
// CBA EXPERIMENTAL forwarding path requests even on requestor interface in order to support
|
||||
// path-finding over LoRa mesh
|
||||
//if (interface != attached_interface) {
|
||||
if (true) {
|
||||
extreme("Transport::path_request: requesting path on interface " + interface.toString());
|
||||
@@ -3404,8 +3452,15 @@ will announce it.
|
||||
}
|
||||
RNS::extreme("Transport::save_path_table: serialized " + std::to_string(length) + " bytes");
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(data, destination_table_path.c_str())) {
|
||||
RNS::extreme("Transport::save_path_table: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
// Check crc to see if data has changed before writing
|
||||
uint8_t crc = crypto_crc8(0, data.data(), data.size());
|
||||
if (_destination_table_crc > 0 && crc == _destination_table_crc) {
|
||||
RNS::extreme("Transport::save_path_table: no change detected, skipping write");
|
||||
}
|
||||
else if (RNS::Utilities::OS::write_file(data, destination_table_path.c_str())) {
|
||||
RNS::extreme("Transport::save_path_table: wrote " + std::to_string(_destination_table.size()) + " entries, " + std::to_string(data.size()) + " bytes");
|
||||
_destination_table_crc = crc;
|
||||
success = true;
|
||||
}
|
||||
else {
|
||||
RNS::extreme("Transport::save_path_table: write failed");
|
||||
@@ -3415,16 +3470,28 @@ will announce it.
|
||||
RNS::extreme("Transport::save_path_table: failed to serialize");
|
||||
}
|
||||
|
||||
double save_time = OS::time() - save_start;
|
||||
std::string time_str;
|
||||
if (save_time < 1) {
|
||||
time_str = std::to_string(OS::round(save_time * 1000, 2)) + "ms";
|
||||
if (success) {
|
||||
double save_time = OS::time() - save_start;
|
||||
if (save_time < 1.0) {
|
||||
//debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(OS::round(save_time * 1000, 2)) + " ms");
|
||||
debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(save_time * 1000) + " ms");
|
||||
}
|
||||
else {
|
||||
//debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(OS::round(save_time, 2)) + " s");
|
||||
debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(save_time) + " s");
|
||||
}
|
||||
}
|
||||
else {
|
||||
time_str = std::to_string(OS::round(save_time, 2)) + "s";
|
||||
|
||||
#ifdef ARDUINO
|
||||
// write time offset to file
|
||||
{
|
||||
std::string time_offset_path = Reticulum::_storagepath + "/time_offset";
|
||||
uint64_t offset = OS::ltime();
|
||||
debug("Writing time offset of " + std::to_string(offset) + " to file");
|
||||
Bytes buf((uint8_t*)&offset, sizeof(offset));
|
||||
OS::write_file(buf, time_offset_path.c_str());
|
||||
}
|
||||
debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + time_str);
|
||||
success = true;
|
||||
#endif
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
error("Could not save path table to storage, the contained exception was: " + std::string(e.what()));
|
||||
@@ -3503,9 +3570,9 @@ will announce it.
|
||||
|
||||
save_time = time.time() - save_start
|
||||
if save_time < 1:
|
||||
time_str = str(round(save_time*1000,2))+"ms"
|
||||
time_str = str(round(save_time*1000,2))+" ms"
|
||||
else:
|
||||
time_str = str(round(save_time,2))+"s"
|
||||
time_str = str(round(save_time,2))+" s"
|
||||
RNS.log("Saved "+str(len(serialised_tunnels))+" tunnel table entries in "+time_str, RNS.LOG_DEBUG)
|
||||
except Exception as e:
|
||||
RNS.log("Could not save tunnel table to storage, the contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
+50
-4
@@ -201,10 +201,51 @@ namespace RNS {
|
||||
const Interface _requesting_interface = {Type::NONE};
|
||||
};
|
||||
|
||||
/*
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
class SerialisedEntry {
|
||||
public:
|
||||
SerialisedEntry(const Bytes& destination_hash, double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, Interface& receiving_interface, const Packet& packet) :
|
||||
_destination_hash(destination_hash),
|
||||
_timestamp(timestamp),
|
||||
_hops(announce_hops),
|
||||
_expires(expires),
|
||||
_random_blobs(random_blobs),
|
||||
_receiving_interface(receiving_interface),
|
||||
_announce_packet(packet)
|
||||
{
|
||||
}
|
||||
public:
|
||||
const Bytes _destination_hash;
|
||||
double _timestamp = 0;
|
||||
const Bytes _received_from;
|
||||
uint8_t _hops = 0;
|
||||
double _expires = 0;
|
||||
std::set<Bytes> _random_blobs;
|
||||
Interface _receiving_interface = {Type::NONE};
|
||||
Packet _announce_packet = {Type::NONE};
|
||||
};
|
||||
*/
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
class TunnelEntry {
|
||||
public:
|
||||
TunnelEntry(const Bytes& tunnel_id, const Bytes& interface_hash, double expires) :
|
||||
_tunnel_id(tunnel_id),
|
||||
_interface_hash(interface_hash),
|
||||
_expires(expires)
|
||||
{
|
||||
}
|
||||
public:
|
||||
const Bytes _tunnel_id;
|
||||
const Bytes _interface_hash;
|
||||
std::map<Bytes, DestinationEntry> _serialised_paths;
|
||||
double _expires = 0;
|
||||
};
|
||||
|
||||
public:
|
||||
static void start(const Reticulum& reticulum_instance);
|
||||
static void loop();
|
||||
static void jobloop();
|
||||
static void jobs();
|
||||
static void transmit(Interface& interface, const Bytes& raw);
|
||||
static bool outbound(Packet& packet);
|
||||
@@ -227,8 +268,10 @@ namespace RNS {
|
||||
static bool should_cache(const Packet& packet);
|
||||
static bool cache(const Packet& packet, bool force_cache = false);
|
||||
static Packet get_cached_packet(const Bytes& packet_hash);
|
||||
static bool clear_cached_packet(const Bytes& packet_hash);
|
||||
static bool cache_request_packet(const Packet& packet);
|
||||
static void cache_request(const Bytes& packet_hash, const Destination& destination);
|
||||
static bool remove_path(const Bytes& destination_hash);
|
||||
static bool has_path(const Bytes& destination_hash);
|
||||
static uint8_t hops_to(const Bytes& destination_hash);
|
||||
static Bytes next_hop(const Bytes& destination_hash);
|
||||
@@ -251,6 +294,7 @@ namespace RNS {
|
||||
static bool save_path_table();
|
||||
static void save_tunnel_table();
|
||||
static void persist_data();
|
||||
static void clean_caches();
|
||||
static void exit_handler();
|
||||
|
||||
static Destination find_destination_from_hash(const Bytes& destination_hash);
|
||||
@@ -295,13 +339,12 @@ namespace RNS {
|
||||
static std::map<Bytes, LinkEntry> _link_table; // A lookup table containing hops for links
|
||||
static std::map<Bytes, AnnounceEntry> _held_announces; // A table containing temporarily held announce-table entries
|
||||
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
|
||||
//z _tunnels = {} // A table storing tunnels to other transport instances
|
||||
static std::map<Bytes, TunnelEntry> _tunnels; // A table storing tunnels to other transport instances
|
||||
//z _announce_rate_table = {} // A table for keeping track of announce rates
|
||||
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
|
||||
|
||||
static std::map<Bytes, PathRequestEntry> _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
|
||||
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
|
||||
static uint16_t _max_pr_tags; // Maximum amount of unique path request tags to remember
|
||||
|
||||
// Transport control destinations are used
|
||||
// for control purposes like path requests
|
||||
@@ -334,11 +377,14 @@ namespace RNS {
|
||||
static double _tables_last_culled;
|
||||
static float _tables_cull_interval;
|
||||
static bool _saving_path_table;
|
||||
static uint32_t _hashlist_maxsize;
|
||||
static uint16_t _hashlist_maxsize;
|
||||
static uint16_t _max_pr_tags;
|
||||
|
||||
// CBA
|
||||
static uint16_t _path_table_maxsize;
|
||||
static double _last_saved;
|
||||
static float _save_interval;
|
||||
static uint8_t _destination_table_crc;
|
||||
|
||||
static Reticulum _owner;
|
||||
static Identity _identity;
|
||||
|
||||
+10
-4
@@ -299,9 +299,6 @@ namespace RNS { namespace Type {
|
||||
static const uint8_t PATHFINDER_R = 1; // Retransmit retries
|
||||
static const uint8_t PATHFINDER_G = 5; // Retry grace period
|
||||
static constexpr const float PATHFINDER_RW = 0.5; // Random window for announce rebroadcast
|
||||
static const uint32_t PATHFINDER_E = 60*60*24*7; // Path expiration of one week
|
||||
static const uint32_t AP_PATH_TIME = 60*60*24; // Path expiration of one day for Access Point paths
|
||||
static const uint32_t ROAMING_PATH_TIME = 60*60*6; // Path expiration of 6 hours for Roaming paths
|
||||
|
||||
// TODO: Calculate an optimal number for this in
|
||||
// various situations
|
||||
@@ -314,10 +311,19 @@ namespace RNS { namespace Type {
|
||||
|
||||
static constexpr const float LINK_TIMEOUT = Link::STALE_TIME * 1.25;
|
||||
static const uint16_t REVERSE_TIMEOUT = 30*60; // Reverse table entries are removed after 30 minutes
|
||||
static const uint32_t DESTINATION_TIMEOUT = 60*60*24*7; // Destination table entries are removed if unused for one week
|
||||
static const uint16_t MAX_RECEIPTS = 1024; // Maximum number of receipts to keep track of
|
||||
static const uint8_t MAX_RATE_TIMESTAMPS = 16; // Maximum number of announce timestamps to keep per destination
|
||||
|
||||
// CBA MCU
|
||||
//static const uint32_t DESTINATION_TIMEOUT = 60*60*24*7; // Destination table entries are removed if unused for one week
|
||||
//static const uint32_t PATHFINDER_E = 60*60*24*7; // Path expiration of one week
|
||||
//static const uint32_t AP_PATH_TIME = 60*60*24; // Path expiration of one day for Access Point paths
|
||||
//static const uint32_t ROAMING_PATH_TIME = 60*60*6; // Path expiration of 6 hours for Roaming paths
|
||||
static const uint32_t DESTINATION_TIMEOUT = 60*60*24*1; // Destination table entries are removed if unused for one day
|
||||
static const uint32_t PATHFINDER_E = 60*60*24*1; // Path expiration of one day
|
||||
static const uint32_t AP_PATH_TIME = 60*60*6; // Path expiration of 6 hours for Access Point paths
|
||||
static const uint32_t ROAMING_PATH_TIME = 60*60*1; // Path expiration of 1 hour for Roaming paths
|
||||
|
||||
}
|
||||
|
||||
} }
|
||||
@@ -6,6 +6,7 @@ using namespace RNS;
|
||||
using namespace RNS::Utilities;
|
||||
|
||||
/*static*/ Filesystem OS::filesystem = {Type::NONE};
|
||||
/*static*/ uint64_t OS::timeOffset = 0;
|
||||
|
||||
/*static*/ void OS::register_filesystem(Filesystem& filesystem) {
|
||||
extreme("Registering filesystem...");
|
||||
@@ -53,9 +54,30 @@ using namespace RNS::Utilities;
|
||||
return filesystem.do_rename_file(from_file_path, to_file_path);
|
||||
}
|
||||
|
||||
/*static*/ bool OS::directory_exists(const char* directory_path) {
|
||||
if (!filesystem) {
|
||||
throw std::runtime_error("Filesystem has not been registered");
|
||||
}
|
||||
return filesystem.do_directory_exists(directory_path);
|
||||
}
|
||||
|
||||
/*static*/ bool OS::create_directory(const char* directory_path) {
|
||||
if (!filesystem) {
|
||||
throw std::runtime_error("Filesystem has not been registered");
|
||||
}
|
||||
return filesystem.do_create_directory(directory_path);
|
||||
}
|
||||
|
||||
/*static*/ bool OS::remove_directory(const char* directory_path) {
|
||||
if (!filesystem) {
|
||||
throw std::runtime_error("Filesystem has not been registered");
|
||||
}
|
||||
return filesystem.do_remove_directory(directory_path);
|
||||
}
|
||||
|
||||
/*static*/ std::list<std::string> OS::list_directory(const char* directory_path) {
|
||||
if (!filesystem) {
|
||||
throw std::runtime_error("Filesystem has not been registered");
|
||||
}
|
||||
return filesystem.do_list_directory(directory_path);
|
||||
}
|
||||
+30
-6
@@ -21,8 +21,35 @@ namespace RNS { namespace Utilities {
|
||||
|
||||
private:
|
||||
static Filesystem filesystem;
|
||||
static uint64_t timeOffset;
|
||||
|
||||
public:
|
||||
static inline uint64_t getTimeOffset() { return timeOffset; }
|
||||
static inline void setTimeOffset(uint64_t offset) { timeOffset = offset; }
|
||||
|
||||
#ifdef ARDUINO
|
||||
// return current time in milliseconds since startup
|
||||
static inline uint64_t ltime() {
|
||||
// handle roll-over of 32-bit millis (approx. 49 days)
|
||||
static uint32_t low32, high32;
|
||||
uint32_t new_low32 = millis();
|
||||
if (new_low32 < low32) high32++;
|
||||
low32 = new_low32;
|
||||
return ((uint64_t)high32 << 32 | low32) + timeOffset;
|
||||
}
|
||||
#else
|
||||
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO
|
||||
// return current time in float seconds since startup
|
||||
static inline double time() { return (double)(ltime() / 1000.0); }
|
||||
#else
|
||||
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
||||
#endif
|
||||
|
||||
// sleep for specified milliseconds
|
||||
//static inline void sleep(float seconds) { ::sleep(seconds); }
|
||||
#ifdef ARDUINO
|
||||
@@ -32,12 +59,6 @@ namespace RNS { namespace Utilities {
|
||||
#endif
|
||||
//static inline void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
|
||||
|
||||
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
||||
|
||||
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
||||
|
||||
// round decimal number to specified precision
|
||||
//static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
//static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
@@ -51,7 +72,10 @@ namespace RNS { namespace Utilities {
|
||||
static bool write_file(const RNS::Bytes& data, const char* file_path);
|
||||
static bool remove_file(const char* file_path);
|
||||
static bool rename_file(const char* from_file_path, const char* to_file_path);
|
||||
static bool directory_exists(const char* directory_path);
|
||||
static bool create_directory(const char* directory_path);
|
||||
static bool remove_directory(const char* directory_path);
|
||||
static std::list<std::string> list_directory(const char* directory_path);
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -203,6 +203,8 @@ namespace ArduinoJson {
|
||||
//packet.set_hash(src["hash"]);
|
||||
packet.sent_at(src["sent_at"]);
|
||||
RNS::Bytes destination_hash = src["destination_hash"];
|
||||
// set cached flag since pcket was read from cache
|
||||
packet.cached(true);
|
||||
/**/
|
||||
RNS::extreme(">>> Finished deserializing packet");
|
||||
return packet;
|
||||
@@ -233,11 +235,19 @@ namespace ArduinoJson {
|
||||
else {
|
||||
dst["receiving_interface_hash"] = nullptr;
|
||||
}
|
||||
// Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately
|
||||
//dst["packet"] = src._announce_packet;
|
||||
if (src._announce_packet) {
|
||||
dst["packet_hash"] = src._announce_packet.get_hash();
|
||||
// Whenever a reference to a packet is serilized we must ensure that packet itself also gets serialized separately
|
||||
RNS::Transport::cache(src._announce_packet, true);
|
||||
// Only cache packet if not already cached
|
||||
if (!src._announce_packet.cached()) {
|
||||
if (RNS::Transport::cache(src._announce_packet, true)) {
|
||||
const_cast<RNS::Packet&>(src._announce_packet).cached(true);
|
||||
}
|
||||
}
|
||||
else {
|
||||
RNS::extreme("Destination announce packet " + src._announce_packet.get_hash().toHex() + " is already cached");
|
||||
}
|
||||
}
|
||||
else {
|
||||
dst["packet_hash"] = nullptr;
|
||||
@@ -256,14 +266,16 @@ namespace ArduinoJson {
|
||||
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
|
||||
//dst._receiving_interface = src["receiving_interface"];
|
||||
RNS::Bytes interface_hash = src["receiving_interface_hash"];
|
||||
if (interface_hash)
|
||||
if (interface_hash) {
|
||||
// Query transport for matching interface
|
||||
dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash);
|
||||
}
|
||||
//dst._announce_packet = src["packet"];
|
||||
RNS::Bytes packet_hash = src["packet_hash"];
|
||||
if (packet_hash)
|
||||
if (packet_hash) {
|
||||
// Query transport for matching packet
|
||||
dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash);
|
||||
}
|
||||
/**/
|
||||
/*
|
||||
//RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]);
|
||||
@@ -308,7 +320,7 @@ namespace RNS { namespace Persistence {
|
||||
RNS::extreme("Persistence::serialize: serialized " + std::to_string(length) + " bytes");
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(data, file_path)) {
|
||||
RNS::extreme("Persistence::serialize: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
RNS::extreme("Persistence::serialize: wrote " + std::to_string(data.size()) + " bytes");
|
||||
}
|
||||
else {
|
||||
RNS::extreme("Persistence::serialize: write failed");
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#include <unity.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/time.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// Imported from Crypto.cpp
|
||||
extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
|
||||
|
||||
void testCrc() {
|
||||
char data[32];
|
||||
uint8_t crc;
|
||||
strcpy(data, "foo");
|
||||
crc = crypto_crc8(0, data, sizeof(data));
|
||||
TEST_ASSERT_EQUAL_UINT8(174, crc);
|
||||
strcpy(data, "bar");
|
||||
crc = crypto_crc8(0, data, sizeof(data));
|
||||
TEST_ASSERT_EQUAL_UINT8(63, crc);
|
||||
strcpy(data, "foo");
|
||||
crc = crypto_crc8(0, data, sizeof(data));
|
||||
TEST_ASSERT_EQUAL_UINT8(174, crc);
|
||||
}
|
||||
|
||||
#ifndef ARDUINO
|
||||
unsigned long millis() {
|
||||
timeval time;
|
||||
::gettimeofday(&time, NULL);
|
||||
return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO
|
||||
void testsleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
|
||||
#else
|
||||
void testsleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
|
||||
#endif
|
||||
|
||||
uint64_t timeOffset = 0;
|
||||
|
||||
uint64_t ltime() {
|
||||
// handle roll-over of 32-bit millis (approx. 49 days)
|
||||
static uint32_t low32, high32;
|
||||
uint32_t new_low32 = millis();
|
||||
if (new_low32 < low32) high32++;
|
||||
low32 = new_low32;
|
||||
return ((uint64_t)high32 << 32 | low32) + timeOffset;
|
||||
}
|
||||
|
||||
void testTime() {
|
||||
//uint64_t start = RNS::Utilities::OS::ltime();
|
||||
//RNS::Utilities::OS::sleep(0.1);
|
||||
//TEST_ASSERT_TRUE((RNS::Utilities::OS::ltime() - start) > 100);
|
||||
uint64_t start = ltime();
|
||||
testsleep(0.1);
|
||||
uint64_t end = ltime();
|
||||
TEST_ASSERT_TRUE((end - start) > 50);
|
||||
TEST_ASSERT_TRUE((end - start) < 200);
|
||||
}
|
||||
|
||||
void testConvert() {
|
||||
//uint64_t time = ltime();
|
||||
//printf("time: %lld\n", time);
|
||||
|
||||
uint64_t num = 1234567890;
|
||||
TEST_ASSERT_EQUAL_UINT64(1234567890, num);
|
||||
|
||||
char str[16];
|
||||
snprintf(str, 16, "%lld", num);
|
||||
TEST_ASSERT_EQUAL_STRING("1234567890", str);
|
||||
|
||||
char* buf = (char*)#
|
||||
|
||||
//uint64_t newnum = (uint64_t)(*buf);
|
||||
uint64_t newnum = *(uint64_t*)buf;
|
||||
TEST_ASSERT_EQUAL_UINT64(1234567890, newnum);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
UNITY_BEGIN();
|
||||
//RUN_TEST(testCrc);
|
||||
//RUN_TEST(testTime);
|
||||
RUN_TEST(testConvert);
|
||||
return UNITY_END();
|
||||
}
|
||||
Reference in new issue
Block a user