WIP: Progress toward Link support with example app

This commit is contained in:
Chad Attermann committed 2025-08-23 14:12:13 -06:00
1 parent 11155b5829
commit c3edde10e9
44 files changed
+1608 -939

No files matched your search

+16 -2
View File
@@ -118,10 +118,24 @@ MEM("Creating from data-move...");
return compare(bytes) > 0;
}
inline uint8_t& operator[](size_t index) {
if (!_data || index >= _data->size()) {
throw std::out_of_range("Index out of bounds");
}
return (*_data)[index];
}
inline const uint8_t& operator[](size_t index) const {
if (!_data || index >= _data->size()) {
throw std::out_of_range("Index out of bounds");
}
return (*_data)[index];
}
inline operator bool() const {
return (_data && !_data->empty());
}
inline operator Data() const {
inline operator const Data() const {
if (!_data)
return Data();
return *_data.get();
@@ -338,7 +352,7 @@ MEM("Creating from data-move...");
};
// following array function doesn't work without size since it's past as a pointer to the array sizeof() is of the pointer
// following array function doesn't work without size since it's passed as a pointer to the array so sizeof() is of the pointer
//inline Bytes bytesFromArray(const uint8_t arr[]) { return Bytes(arr, sizeof(arr)); }
//inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return Bytes(ptr, len); }
inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return {ptr, len}; }
+39
View File
@@ -47,4 +47,43 @@ namespace RNS { namespace Cryptography {
};
class AES_256_CBC {
public:
static inline const Bytes encrypt(const Bytes& plaintext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
Bytes ciphertext;
cbc.encrypt(ciphertext.writable(plaintext.size()), plaintext.data(), plaintext.size());
return ciphertext;
}
static inline const Bytes decrypt(const Bytes& ciphertext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
Bytes plaintext;
cbc.decrypt(plaintext.writable(ciphertext.size()), ciphertext.data(), ciphertext.size());
return plaintext;
}
// EXPERIMENTAL - overwrites passed buffer
static inline void inplace_encrypt(Bytes& plaintext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
cbc.encrypt((uint8_t*)plaintext.data(), plaintext.data(), plaintext.size());
}
// EXPERIMENTAL - overwrites passed buffer
static inline void inplace_decrypt(Bytes& ciphertext, const Bytes& key, const Bytes& iv) {
CBC<AES256> cbc;
cbc.setKey(key.data(), key.size());
cbc.setIV(iv.data(), iv.size());
cbc.decrypt((uint8_t*)ciphertext.data(), ciphertext.data(), ciphertext.size());
}
};
} }
-2
View File
@@ -19,8 +19,6 @@ namespace RNS { namespace Cryptography {
class Fernet {
public:
static const uint8_t FERNET_OVERHEAD = 48; // Bytes
using Ptr = std::shared_ptr<Fernet>;
public:
+162
View File
@@ -0,0 +1,162 @@
#include "Token.h"
#include "HMAC.h"
#include "PKCS7.h"
#include "AES.h"
#include "../Log.h"
#include <stdexcept>
#include <time.h>
using namespace RNS;
using namespace RNS::Cryptography;
using namespace RNS::Type::Cryptography::Token;
Token::Token(const Bytes& key, token_mode mode /*= AES*/) {
if (!key) {
throw std::invalid_argument("Token key cannot be None");
}
if (key.size() != 32) {
throw std::invalid_argument("Token key must be 32 bytes, not " + std::to_string(key.size()));
}
if (mode == MODE_AES) {
if (key.size() == 32) {
_mode = MODE_AES_128_CBC;
//p self._signing_key = key[:16]
_signing_key = key.left(16);
//p self._encryption_key = key[16:]
_encryption_key = key.mid(16);
}
else if (key.size() == 64) {
_mode = MODE_AES_256_CBC;
//p self._signing_key = key[:32]
_signing_key = key.left(32);
//p self._encryption_key = key[32:]
_encryption_key = key.mid(32);
}
else {
throw std::invalid_argument("Token key must be 32 bytes, not " + std::to_string(key.size()));
}
}
else {
throw std::invalid_argument("Invalid token mode: " + std::to_string(mode));
}
MEM("Token object created");
}
Token::~Token() {
MEM("Token object destroyed");
}
bool Token::verify_hmac(const Bytes& token) {
if (token.size() <= 32) {
throw std::invalid_argument("Cannot verify HMAC on token of only " + std::to_string(token.size()) + " bytes");
}
//received_hmac = token[-32:]
Bytes received_hmac = token.right(32);
DEBUG("Token::verify_hmac: received_hmac: " + received_hmac.toHex());
//expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
Bytes expected_hmac = HMAC::generate(_signing_key, token.left(token.size()-32))->digest();
DEBUG("Token::verify_hmac: expected_hmac: " + expected_hmac.toHex());
return (received_hmac == expected_hmac);
}
const Bytes Token::encrypt(const Bytes& data) {
DEBUG("Token::encrypt: plaintext length: " + std::to_string(data.size()));
Bytes iv = random(16);
//double current_time = OS::time();
TRACE("Token::encrypt: iv: " + iv.toHex());
TRACE("Token::encrypt: plaintext: " + data.toHex());
Bytes ciphertext;
if (_mode == MODE_AES_128_CBC) {
ciphertext = AES_128_CBC::encrypt(
PKCS7::pad(data),
_encryption_key,
iv
);
}
else if (_mode == MODE_AES_256_CBC) {
ciphertext = AES_256_CBC::encrypt(
PKCS7::pad(data),
_encryption_key,
iv
);
}
else {
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
}
DEBUG("Token::encrypt: padded ciphertext length: " + std::to_string(ciphertext.size()));
TRACE("Token::encrypt: ciphertext: " + ciphertext.toHex());
Bytes signed_parts = iv + ciphertext;
//return signed_parts + HMAC::generate(_signing_key, signed_parts)->digest();
Bytes sig(HMAC::generate(_signing_key, signed_parts)->digest());
TRACE("Token::encrypt: sig: " + sig.toHex());
Bytes token(signed_parts + sig);
DEBUG("Token::encrypt: token length: " + std::to_string(token.size()));
return token;
}
const Bytes Token::decrypt(const Bytes& token) {
DEBUG("Token::decrypt: token length: " + std::to_string(token.size()));
if (token.size() < 48) {
throw std::invalid_argument("Cannot decrypt token of only " + std::to_string(token.size()) + " bytes");
}
if (!verify_hmac(token)) {
throw std::invalid_argument("Token token HMAC was invalid");
}
//iv = token[:16]
Bytes iv = token.left(16);
TRACE("Token::decrypt: iv: " + iv.toHex());
//ciphertext = token[16:-32]
Bytes ciphertext = token.mid(16, token.size()-48);
TRACE("Token::decrypt: ciphertext: " + ciphertext.toHex());
try {
Bytes plaintext;
if (_mode == MODE_AES_128_CBC) {
plaintext = PKCS7::unpad(
AES_128_CBC::decrypt(
ciphertext,
_encryption_key,
iv
)
);
}
else if (_mode == MODE_AES_256_CBC) {
plaintext = PKCS7::unpad(
AES_256_CBC::decrypt(
ciphertext,
_encryption_key,
iv
)
);
}
else {
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
}
DEBUG("Token::encrypt: unpadded plaintext length: " + std::to_string(plaintext.size()));
TRACE("Token::decrypt: plaintext: " + plaintext.toHex());
DEBUG("Token::decrypt: plaintext length: " + std::to_string(plaintext.size()));
return plaintext;
}
catch (std::exception& e) {
WARNING("Could not decrypt Token token");
throw std::runtime_error("Could not decrypt Token token");
}
}
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include "Random.h"
#include "../Bytes.h"
#include "../Type.h"
#include <stdint.h>
namespace RNS { namespace Cryptography {
/*
This class provides a slightly modified implementation of the Fernet spec
found at: https://github.com/fernet/spec/blob/master/Spec.md
According to the spec, a Fernet token includes a one byte VERSION and
eight byte TIMESTAMP field at the start of each token. These fields are
not relevant to Reticulum. They are therefore stripped from this
implementation, since they incur overhead and leak initiator metadata.
*/
class Token {
public:
using Ptr = std::shared_ptr<Token>;
public:
static inline const Bytes generate_key(RNS::Type::Cryptography::Token::token_mode mode = RNS::Type::Cryptography::Token::MODE_AES_256_CBC) {
if (mode == RNS::Type::Cryptography::Token::MODE_AES_128_CBC) return random(32);
else if (mode == RNS::Type::Cryptography::Token::MODE_AES_256_CBC) return random(64);
else throw new std::invalid_argument("Invalid token mode: " + std::to_string(mode));
}
public:
Token(const Bytes& key, RNS::Type::Cryptography::Token::token_mode mode = RNS::Type::Cryptography::Token::MODE_AES);
~Token();
public:
bool verify_hmac(const Bytes& token);
const Bytes encrypt(const Bytes& data);
const Bytes decrypt(const Bytes& token);
private:
RNS::Type::Cryptography::Token::token_mode _mode = RNS::Type::Cryptography::Token::MODE_AES_256_CBC;
Bytes _signing_key;
Bytes _encryption_key;
};
} }
+3 -2
View File
@@ -58,7 +58,7 @@ namespace RNS {
public:
class Callbacks {
public:
using link_established = void(*)(const Link& link);
using link_established = void(*)(Link& link);
//using packet = void(*)(uint8_t* data, uint16_t data_len, Packet *packet);
using packet = void(*)(const Bytes& data, const Packet& packet);
using proof_requested = bool(*)(const Packet& packet);
@@ -237,7 +237,8 @@ namespace RNS {
//z _callback = None
//z _proofcallback = None
// CBA _link_id is expected by packet but only present in Link
// CBA LINK
// CBA _link_id is expected by Packet but only present in Link
// CBA TODO determine if Link needs to inherit from Destination or vice-versa
Bytes _link_id;
+2
View File
@@ -20,6 +20,7 @@ namespace RNS {
virtual ~FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object destroyed, this: 0x%X", this); }
protected:
virtual bool init() { return true; }
virtual bool file_exists(const char* file_path) = 0;
virtual size_t read_file(const char* file_path, Bytes& data) = 0;
virtual size_t write_file(const char* file_path, const Bytes& data) = 0;
@@ -90,6 +91,7 @@ namespace RNS {
}
public:
inline bool init() { assert(_impl); return _impl->init(); }
inline bool file_exists(const char* file_path) { assert(_impl); return _impl->file_exists(file_path); }
inline size_t read_file(const char* file_path, Bytes& data) { assert(_impl); return _impl->read_file(file_path, data); }
inline size_t write_file(const char* file_path, const Bytes& data) { assert(_impl); return _impl->write_file(file_path, data); }
+10 -10
View File
@@ -8,7 +8,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/HKDF.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include "Cryptography/Random.h"
#include <algorithm>
@@ -513,17 +513,17 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
TRACE("Identity::encrypt: shared key: " + shared_key.toHex());
Bytes derived_key = Cryptography::hkdf(
32,
DERIVED_KEY_LENGTH,
shared_key,
get_salt(),
get_context()
);
TRACE("Identity::encrypt: derived key: " + derived_key.toHex());
Cryptography::Fernet fernet(derived_key);
TRACE("Identity::encrypt: Fernet encrypting data of length " + std::to_string(plaintext.size()));
Cryptography::Token token(derived_key);
TRACE("Identity::encrypt: Token encrypting data of length " + std::to_string(plaintext.size()));
TRACE("Identity::encrypt: plaintext: " + plaintext.toHex());
Bytes ciphertext = fernet.encrypt(plaintext);
Bytes ciphertext = token.encrypt(plaintext);
TRACE("Identity::encrypt: ciphertext: " + ciphertext.toHex());
return ephemeral_pub_bytes + ciphertext;
@@ -561,21 +561,21 @@ const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
TRACE("Identity::decrypt: shared key: " + shared_key.toHex());
Bytes derived_key = Cryptography::hkdf(
32,
DERIVED_KEY_LENGTH,
shared_key,
get_salt(),
get_context()
);
TRACE("Identity::decrypt: derived key: " + derived_key.toHex());
Cryptography::Fernet fernet(derived_key);
Cryptography::Token token(derived_key);
//ciphertext = ciphertext_token[Identity.KEYSIZE//8//2:]
Bytes ciphertext(ciphertext_token.mid(Type::Identity::KEYSIZE/8/2));
TRACE("Identity::decrypt: Fernet decrypting data of length " + std::to_string(ciphertext.size()));
TRACE("Identity::decrypt: Token decrypting data of length " + std::to_string(ciphertext.size()));
TRACE("Identity::decrypt: ciphertext: " + ciphertext.toHex());
plaintext = fernet.decrypt(ciphertext);
plaintext = token.decrypt(ciphertext);
TRACE("Identity::decrypt: plaintext: " + plaintext.toHex());
//TRACE("Identity::decrypt: Fernet decrypted data of length " + std::to_string(plaintext.size()));
//TRACE("Identity::decrypt: Token decrypted data of length " + std::to_string(plaintext.size()));
}
catch (std::exception& e) {
DEBUG("Decryption by " + toString() + " failed: " + e.what());
+1 -1
View File
@@ -6,7 +6,7 @@
#include "Cryptography/Hashes.h"
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include <map>
#include <string>
+15 -2
View File
@@ -30,7 +30,7 @@ namespace RNS {
Bytes _destination;
double _time = 0;
uint8_t _hops = 0;
double _emitted = 0;
uint64_t _emitted = 0;
Bytes _raw;
};
@@ -43,6 +43,9 @@ namespace RNS {
virtual ~InterfaceImpl() { MEMF("InterfaceImpl object destroyed, this: 0x%X", this); }
protected:
virtual bool start() { return true; }
virtual void stop() {}
virtual void loop() {}
// CBA Virtual override method for custom interface to send outgoing data
virtual void send_outgoing(const Bytes& data) = 0;
@@ -71,6 +74,9 @@ namespace RNS {
Bytes _ifac_identity;
Type::Interface::modes _mode = Type::Interface::MODE_NONE;
uint32_t _bitrate = 0;
uint16_t _HW_MTU = 0;
bool _AUTOCONFIGURE_MTU = false;
bool _FIXED_MTU = false;
double _announce_allowed_at = 0;
float _announce_cap = 0.0;
std::list<AnnounceEntry> _announce_queue;
@@ -145,6 +151,9 @@ namespace RNS {
}
public:
inline bool start() { assert(_impl); return _impl->start(); }
inline void stop() { assert(_impl); return _impl->stop(); }
inline void loop() { assert(_impl); return _impl->loop(); }
inline const Bytes get_hash() const { assert(_impl); return _impl->get_hash(); }
void process_announce_queue();
@@ -158,8 +167,8 @@ namespace RNS {
// Public method to handle data coming in on interface and pass on to impl
void handle_incoming(const Bytes& data);
// getters/setters
protected:
// setters
inline void IN(bool IN) { assert(_impl); _impl->_IN = IN; }
inline void OUT(bool OUT) { assert(_impl); _impl->_OUT = OUT; }
inline void FWD(bool FWD) { assert(_impl); _impl->_FWD = FWD; }
@@ -169,6 +178,7 @@ namespace RNS {
inline void online(bool online) { assert(_impl); _impl->_online = online; }
inline void announce_allowed_at(double announce_allowed_at) { assert(_impl); _impl->_announce_allowed_at = announce_allowed_at; }
public:
// getters
inline bool IN() const { assert(_impl); return _impl->_IN; }
inline bool OUT() const { assert(_impl); return _impl->_OUT; }
inline bool FWD() const { assert(_impl); return _impl->_FWD; }
@@ -179,6 +189,9 @@ namespace RNS {
inline Type::Interface::modes mode() const { assert(_impl); return _impl->_mode; }
inline void mode(Type::Interface::modes mode) { assert(_impl); _impl->_mode = mode; }
inline uint32_t bitrate() const { assert(_impl); return _impl->_bitrate; }
inline uint16_t HW_MTU() const { assert(_impl); return _impl->_HW_MTU; }
inline bool AUTOCONFIGURE_MTU() const { assert(_impl); return _impl->_AUTOCONFIGURE_MTU; }
inline bool FIXED_MTU() const { assert(_impl); return _impl->_FIXED_MTU; }
inline double announce_allowed_at() const { assert(_impl); return _impl->_announce_allowed_at; }
inline float announce_cap() const { assert(_impl); return _impl->_announce_cap; }
inline std::list<AnnounceEntry>& announce_queue() const { assert(_impl); return _impl->_announce_queue; }
+218 -19
View File
@@ -9,7 +9,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/HKDF.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include "Cryptography/Random.h"
#define MSGPACK_DEBUGLOG_ENABLE 0
@@ -24,12 +24,16 @@ using namespace RNS::Utilities;
/*static*/ uint8_t Link::resource_strategies = ACCEPT_NONE | ACCEPT_APP | ACCEPT_ALL;
Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/) :
/*static*/ std::set<link_mode> Link::ENABLED_MODES = {MODE_AES256_CBC};
/*static*/ link_mode Link::MODE_DEFAULT = MODE_AES256_CBC;
Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/, link_mode mode /*= MODE_DEFAULT*/) :
_object(new LinkData(destination))
{
assert(_object);
_object->_owner = owner;
_object->_mode = mode;
if (destination && destination.type() != Type::Destination::SINGLE) {
throw std::logic_error("Links can only be established to the \"single\" destination type");
@@ -76,7 +80,18 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
}
if (_object->_initiator) {
_object->_request_data = _object->_pub_bytes + _object->_sig_pub_bytes;
Bytes signalling_bytes;
uint16_t nh_hw_mtu = Transport::next_hop_interface_hw_mtu(destination.hash());
if (RNS::Reticulum::link_mtu_discovery() && nh_hw_mtu) {
signalling_bytes = Link::signalling_bytes(nh_hw_mtu, _object->_mode);
DEBUGF("Signalling link MTU of %d for link", nh_hw_mtu);
}
else {
signalling_bytes = Link::signalling_bytes(RNS::Type::Reticulum::MTU, _object->_mode);
}
TRACEF("Establishing link with mode %d", _object->_mode);
//p self.request_data = self.pub_bytes+self.sig_pub_bytes+signalling_bytes
_object->_request_data = _object->_pub_bytes + _object->_sig_pub_bytes + signalling_bytes;
_object->_packet = Packet(destination, _object->_request_data, RNS::Type::Packet::LINKREQUEST);
_object->_packet.pack();
_object->_establishment_cost += _object->_packet.raw().size();
@@ -98,6 +113,65 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
}
/*static*/ Bytes Link::signalling_bytes(uint16_t mtu, link_mode mode) {
//p if not mode in Link.ENABLED_MODES: raise TypeError(f"Requested link mode {Link.MODE_DESCRIPTIONS[mode]} not enabled")
//if (!(mode & ENABLED_MODES)) throw std::runtime_error("Requested link mode "+std::to_string(mode)+" not enabled");
if (Link::ENABLED_MODES.find(mode) == Link::ENABLED_MODES.end()) throw std::runtime_error("Requested link mode "+std::to_string(mode)+" not enabled");
//p signalling_value = (mtu & Link.MTU_BYTEMASK)+(((mode<<5) & Link.MODE_BYTEMASK)<<16)
//p return struct.pack(">I", signalling_value)[1:]
uint32_t signalling_value = htonl((mtu & MTU_BYTEMASK)+(((mode<<5) & MODE_BYTEMASK)<<16));
Bytes data(((uint8_t*)&signalling_value)+1, 3);
return data;
}
/*static*/ uint16_t Link::mtu_from_lr_packet(const Packet& packet) {
if (packet.data().size() == ECPUBSIZE+LINK_MTU_SIZE) {
return (packet.data()[ECPUBSIZE] << 16) + (packet.data()[ECPUBSIZE+1] << 8) + (packet.data()[ECPUBSIZE+2]) & MTU_BYTEMASK;
}
return 0;
}
/*static*/ uint16_t Link::mtu_from_lp_packet(const Packet& packet) {
//p if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
if (packet.data().size() == RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2+LINK_MTU_SIZE) {
Bytes mtu_bytes = packet.data().mid(RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2, LINK_MTU_SIZE);
return (mtu_bytes[0] << 16) + (mtu_bytes[1] << 8) + (mtu_bytes[2]) & MTU_BYTEMASK;
}
return 0;
}
/*static*/ uint8_t Link::mode_byte(link_mode mode) {
//p if mode in Link.ENABLED_MODES: return (mode << 5) & Link.MODE_BYTEMASK
if (Link::ENABLED_MODES.find(mode) != Link::ENABLED_MODES.end()) return (mode << 5) & MODE_BYTEMASK;
throw std::runtime_error("Requested link mode {mode} not enabled");
}
/*static*/ link_mode Link::mode_from_lr_packet(const Packet& packet) {
if (packet.data().size() > ECPUBSIZE) {
link_mode mode = static_cast<link_mode>((packet.data()[ECPUBSIZE] & MODE_BYTEMASK) >> 5);
return mode;
}
return Link::MODE_DEFAULT;
}
/*static*/ link_mode Link::mode_from_lp_packet(const Packet& packet) {
if (packet.data().size() > RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
link_mode mode = static_cast<link_mode>(packet.data()[RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2] >> 5);
return mode;
}
return Link::MODE_DEFAULT;
}
/*static*/ Bytes Link::link_id_from_lr_packet(const Packet& packet) {
Bytes hashable_part = packet.get_hashable_part();
if (packet.data().size() > ECPUBSIZE) {
size_t diff = packet.data().size() - ECPUBSIZE;
//p hashable_part = hashable_part[:-diff]
hashable_part = hashable_part.left(hashable_part.size() - diff);
}
return RNS::Identity::truncated_hash(hashable_part);
}
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
if (data.size() == ECPUBSIZE) {
try {
@@ -149,7 +223,7 @@ void Link::load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_byte
void Link::set_link_id(const Packet& packet) {
assert(_object);
_object->_link_id = packet.getTruncatedHash();
_object->_link_id = Link::link_id_from_lr_packet(packet);
_object->_hash = _object->_link_id;
}
@@ -159,8 +233,13 @@ void Link::handshake() {
_object->_status = Type::Link::HANDSHAKE;
_object->_shared_key = _object->_prv->exchange(_object->_peer_pub_bytes);
uint16_t derived_key_length;
if (_object->_mode == RNS::Type::Link::MODE_AES128_CBC) derived_key_length = 32;
else if (_object->_mode == RNS::Type::Link::MODE_AES256_CBC) derived_key_length = 64;
else throw new std::invalid_argument("Invalid link mode "+std::to_string(_object->_mode)+" on "+toString());
_object->_derived_key = Cryptography::hkdf(
32,
derived_key_length,
_object->_shared_key,
get_salt(),
get_context()
@@ -173,13 +252,15 @@ void Link::handshake() {
void Link::prove() {
assert(_object);
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
Bytes signed_data =_object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes;
const Bytes signature(_object->_owner.identity().sign(signed_data));
Bytes proof_data = signature + _object->_pub_bytes;
// CBA LINK
//Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
Packet proof(_object->_link_destination, *this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
//Packet proof(_object->_link_destination, *this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
proof.send();
_object->_establishment_cost += proof.raw().size();
had_outbound();
@@ -187,6 +268,7 @@ void Link::prove() {
void Link::prove_packet(const Packet& packet) {
assert(_object);
DEBUGF("Link %s proving packet", link_id().toHex().c_str());
const Bytes signature(sign(packet.packet_hash()));
// TODO: Hardcoded as explicit proof for now
// if RNS.Reticulum.should_use_implicit_proof():
@@ -202,21 +284,41 @@ void Link::prove_packet(const Packet& packet) {
void Link::validate_proof(const Packet& packet) {
assert(_object);
DEBUGF("Link %s validating proof", link_id().toHex().c_str());
try {
if (_object->_status == Type::Link::PENDING) {
Bytes packet_data(packet.data());
TRACEF("Link %s: initiator: %d", toString().c_str(), _object->_initiator);
TRACEF("Link %s: size: %d", toString().c_str(), packet_data.size());
Bytes signalling_bytes;
uint16_t confirmed_mtu = 0;
link_mode mode = mode_from_lp_packet(packet);
DEBUGF("Validating link request proof with mode %d", mode);
if (mode != _object->_mode) throw std::runtime_error("Invalid link mode "+std::to_string(mode)+" in link request proof");
//p if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
if (packet_data.size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2+RNS::Type::Link::LINK_MTU_SIZE) {
confirmed_mtu = Link::mtu_from_lp_packet(packet);
signalling_bytes = Link::signalling_bytes(confirmed_mtu, mode);
// CBA TODO Determine best way to deal with packet.data() being read-only
//p packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
packet_data = packet_data.left(RNS::Type::Identity::SIGLENGTH/8+ECPUBSIZE/2);
DEBUGF("Destination confirmed link MTU of %d", confirmed_mtu);
}
//p if _object->_initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2:
if (_object->_initiator && packet.data().size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
if (_object->_initiator && packet_data.size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) {
//p peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2]
const Bytes peer_pub_bytes(packet.data().mid(Type::Identity::SIGLENGTH/8, ECPUBSIZE/2));
const Bytes peer_pub_bytes(packet_data.mid(Type::Identity::SIGLENGTH/8, ECPUBSIZE/2));
//p peer_sig_pub_bytes = _object->_destination.identity.get_public_key()[ECPUBSIZE//2:ECPUBSIZE]
const Bytes peer_sig_pub_bytes(_object->_destination.identity().get_public_key().mid(ECPUBSIZE/2, ECPUBSIZE/2));
TRACEF("Link %s performing handshake", link_id().toHex().c_str());
load_peer(peer_pub_bytes, peer_sig_pub_bytes);
handshake();
_object->_establishment_cost += packet.raw().size();
Bytes signed_data = _object->_link_id + _object->_peer_pub_bytes + _object->_peer_sig_pub_bytes;
const Bytes signature(packet.data().left(Type::Identity::SIGLENGTH/8));
const Bytes signature(packet_data.left(Type::Identity::SIGLENGTH/8));
TRACEF("Link %s validating identity", link_id().toHex().c_str());
if (_object->_destination.identity().validate(signature, signed_data)) {
if (_object->_status != Type::Link::HANDSHAKE) {
throw std::runtime_error("Invalid link state for proof validation: " + _object->_status);
@@ -224,6 +326,9 @@ void Link::validate_proof(const Packet& packet) {
_object->_rtt = OS::time() - _object->_request_time;
_object->_attached_interface = packet.receiving_interface();
_object->__remote_identity = _object->_destination.identity();
if (confirmed_mtu) _object->_mtu = confirmed_mtu;
else _object->_mtu = RNS::Type::Reticulum::MTU;
update_mdu();
_object->_status = Type::Link::ACTIVE;
_object->_activated_at = OS::time();
_object->_last_proof = _object->_activated_at;
@@ -239,12 +344,14 @@ void Link::validate_proof(const Packet& packet) {
MsgPack::Packer packer;
packer.serialize(_object->_rtt);
Bytes rtt_data(packer.data(), packer.size());
TRACEF("***** RTT data size: %d", rtt_data.size());
//p rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT)
Packet rtt_packet(_object->_link_destination, rtt_data, Type::Packet::DATA, Type::Packet::LRRTT);
rtt_packet.send();
had_outbound();
if (_object->_callbacks._established != nullptr) {
VERBOSEF("Link %s is established", link_id().toHex().c_str());
//p thread = threading.Thread(target=_object->_callbacks.link_established, args=(self,))
//p thread.daemon = True
//p thread.start()
@@ -255,6 +362,9 @@ void Link::validate_proof(const Packet& packet) {
DEBUGF("Invalid link proof signature received by %s. Ignoring.", toString().c_str());
}
}
else {
DEBUGF("Failed initiator/size check for link proof signature received by %s. Ignoring.", toString().c_str());
}
}
}
catch (std::exception& e) {
@@ -275,6 +385,7 @@ thus preserved. This method can be used for authentication.
*/
void Link::identify(const Identity& identity) {
assert(_object);
DEBUGF("Link %s requesting identity", link_id().toHex().c_str());
if (_object->_initiator && _object->_status == Type::Link::ACTIVE) {
const Bytes signed_data(_object->_link_id + identity.get_public_key());
const Bytes signature(identity.sign(signed_data));
@@ -298,6 +409,7 @@ Sends a request to the remote peer.
*/
const RNS::RequestReceipt Link::request(const Bytes& path, const Bytes& data /*= {Bytes::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/) {
assert(_object);
DEBUGF("Link %s sending request", link_id().toHex().c_str());
const Bytes request_path_hash(Identity::truncated_hash(path));
//p unpacked_request = [OS::time(), request_path_hash, data]
@@ -350,6 +462,13 @@ const RNS::RequestReceipt Link::request(const Bytes& path, const Bytes& data /*=
}
void Link::update_mdu() {
assert(_object);
_object->_mdu = _object->_mtu - RNS::Type::Reticulum::HEADER_MAXSIZE - RNS::Type::Reticulum::IFAC_MIN_SIZE;
//p self.mdu = math.floor((self.mtu-RNS.Reticulum.IFAC_MIN_SIZE-RNS.Reticulum.HEADER_MINSIZE-RNS.Identity.TOKEN_OVERHEAD)/RNS.Identity.AES128_BLOCKSIZE)*RNS.Identity.AES128_BLOCKSIZE - 1
_object->_mdu = std::floor((_object->_mtu-RNS::Type::Reticulum::IFAC_MIN_SIZE-RNS::Type::Reticulum::HEADER_MINSIZE-RNS::Type::Identity::TOKEN_OVERHEAD)/RNS::Type::Identity::AES128_BLOCKSIZE)*RNS::Type::Identity::AES128_BLOCKSIZE - 1;
}
void Link::rtt_packet(const Packet& packet) {
assert(_object);
try {
@@ -398,6 +517,47 @@ float Link::get_establishment_rate() {
return _object->_establishment_rate*8;
}
/*
:returns: The MTU of an established link.
*/
uint16_t Link::get_mtu() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_mtu;
}
return 0;
}
/*
:returns: The packet MDU of an established link.
*/
uint16_t Link::get_mdu() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_mdu;
}
return 0;
}
/*
:returns: The packet expected in-flight data rate of an established link.
*/
float Link::get_expected_rate() {
assert(_object);
if (_object->_status == ACTIVE) {
return _object->_expected_rate;
}
return 0.0;
}
/*
:returns: The mode of an established link.
*/
link_mode Link::get_mode() {
assert(_object);
return _object->_mode;
}
const Bytes& Link::get_salt() {
assert(_object);
return _object->_link_id;
@@ -407,6 +567,17 @@ const Bytes Link::get_context() {
return {Bytes::NONE};
}
/*
:returns: The time in seconds since this link was established.
*/
double Link::get_age() {
assert(_object);
if (_object->_activated_at) {
return OS::time() - _object->_activated_at;
}
return 0.0;
}
/*
:returns: The time in seconds since last inbound packet on the link. This includes keepalive packets.
*/
@@ -624,6 +795,8 @@ void Link::send_keepalive() {
}
void Link::handle_request(const Bytes& request_id, const ResourceRequest& resource_request) {
assert(_object);
DEBUGF("Link %s handling request", link_id().toHex().c_str());
if (_object->_status == Type::Link::ACTIVE) {
//p requested_at = unpacked_request[0]
//p path_hash = unpacked_request[1]
@@ -1085,16 +1258,16 @@ void Link::receive(const Packet& packet) {
const Bytes Link::encrypt(const Bytes& plaintext) {
assert(_object);
try {
if (!_object->_fernet) {
if (!_object->_token) {
try {
_object->_fernet.reset(new Fernet(_object->_derived_key));
_object->_token.reset(new Token(_object->_derived_key));
}
catch (std::exception& e) {
ERRORF("Could not instantiate Fernet while performin encryption on link %s. The contained exception was: %s", toString().c_str(), e.what());
ERRORF("Could not instantiate Token while performin encryption on link %s. The contained exception was: %s", toString().c_str(), e.what());
throw e;
}
}
return _object->_fernet->encrypt(plaintext);
return _object->_token->encrypt(plaintext);
}
catch (std::exception& e) {
ERRORF("Encryption on link %s failed. The contained exception was: %s", toString().c_str(), e.what());
@@ -1105,10 +1278,10 @@ const Bytes Link::encrypt(const Bytes& plaintext) {
const Bytes Link::decrypt(const Bytes& ciphertext) {
assert(_object);
try {
if (!_object->_fernet) {
_object->_fernet.reset(new Fernet(_object->_derived_key));
if (!_object->_token) {
_object->_token.reset(new Token(_object->_derived_key));
}
return _object->_fernet->decrypt(ciphertext);
return _object->_token->decrypt(ciphertext);
}
catch (std::exception& e) {
ERRORF("Decryption failed on link %s. The contained exception was: %s", toString().c_str(), e.what());
@@ -1186,7 +1359,7 @@ Sets the resource strategy for the link.
*/
void Link::set_resource_strategy(resource_strategy strategy) {
assert(_object);
if ((strategy & resource_strategies) > 0) {
if (!(strategy & resource_strategies)) {
throw std::runtime_error("Unsupported resource strategy");
}
else {
@@ -1253,6 +1426,12 @@ const Destination& Link::destination() const {
return _object->_destination;
}
// CBA LINK
const Destination& Link::link_destination() const {
assert(_object);
return _object->_link_destination;
}
const Bytes& Link::link_id() const {
assert(_object);
return _object->_link_id;
@@ -1263,6 +1442,11 @@ const Bytes& Link::hash() const {
return _object->_hash;
}
uint16_t Link::mtu() const {
assert(_object);
return _object->_mtu;
}
Type::Link::status Link::status() const {
assert(_object);
return _object->_status;
@@ -1293,6 +1477,16 @@ std::set<RNS::RequestReceipt>& Link::pending_requests() const {
return _object->_pending_requests;
}
Type::Link::teardown_reason Link::teardown_reason() const {
assert(_object);
return _object->_teardown_reason;
}
bool Link::initiator() const {
assert(_object);
return _object->_initiator;
}
// setters
void Link::destination(const Destination& destination) {
@@ -1325,6 +1519,11 @@ void Link::last_inbound(double time) {
_object->_last_inbound = time;
}
void Link::status(Type::Link::status status) {
assert(_object);
_object->_status = status;
}
//RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt /*= {Type::NONE}*/, const Resource& resource /*= {Type::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt, const Resource& resource, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
@@ -1548,7 +1747,7 @@ const Bytes& RequestReceipt::request_id() const {
return _object->_request_id;
}
const size_t RequestReceipt::response_transfer_size() const {
size_t RequestReceipt::response_transfer_size() const {
assert(_object);
return _object->_response_transfer_size;
}
+28 -5
View File
@@ -87,7 +87,7 @@ namespace RNS {
// getters
const Bytes& hash() const;
const Bytes& request_id() const;
const size_t response_transfer_size() const;
size_t response_transfer_size() const;
// setters
void response_size(size_t size);
@@ -112,8 +112,8 @@ namespace RNS {
public:
class Callbacks {
public:
using established = void(*)(const Link& link);
using closed = void(*)(const Link& link);
using established = void(*)(Link& link);
using closed = void(*)(Link& link);
using packet = void(*)(const Bytes& plaintext, const Packet& packet);
using remote_identified = void(*)(const Link& link, const Identity& remote_identity);
using resource = void(*)(const ResourceAdvertisement& resource_advertisement);
@@ -132,6 +132,8 @@ namespace RNS {
public:
static uint8_t resource_strategies;
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
static RNS::Type::Link::link_mode MODE_DEFAULT;
public:
Link(Type::NoneConstructor none) {
@@ -140,8 +142,8 @@ namespace RNS {
Link(const Link& link) : _object(link._object) {
MEM("Link object copy created");
}
Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE});
//Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE});
Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}, RNS::Type::Link::link_mode mode = MODE_DEFAULT);
//Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}, RNS::Type::Link::link_mode mode = MODE_DEFAULT);
virtual ~Link(){
MEM("Link object destroyed");
}
@@ -158,7 +160,16 @@ namespace RNS {
}
public:
static Bytes signalling_bytes(uint16_t mtu, RNS::Type::Link::link_mode mode);
static uint16_t mtu_from_lr_packet(const Packet& packet);
static uint16_t mtu_from_lp_packet(const Packet& packet);
static uint8_t mode_byte(RNS::Type::Link::link_mode mode);
static RNS::Type::Link::link_mode mode_from_lr_packet(const Packet& packet);
static RNS::Type::Link::link_mode mode_from_lp_packet(const Packet& packet);
static Bytes link_id_from_lr_packet(const Packet& packet);
static Link validate_request( const Destination& owner, const Bytes& data, const Packet& packet);
public:
void load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_bytes);
void set_link_id(const Packet& packet);
void handshake();
@@ -167,10 +178,16 @@ namespace RNS {
void validate_proof(const Packet& packet);
void identify(const Identity& identity);
const RequestReceipt request(const Bytes& path, const Bytes& data = {Bytes::NONE}, RequestReceipt::Callbacks::response response_callback = nullptr, RequestReceipt::Callbacks::failed failed_callback = nullptr, RequestReceipt::Callbacks::progress progress_callback = nullptr, double timeout = 0.0);
void update_mdu();
void rtt_packet(const Packet& packet);
float get_establishment_rate();
uint16_t get_mtu();
uint16_t get_mdu();
float get_expected_rate();
RNS::Type::Link::link_mode get_mode();
const Bytes& get_salt();
const Bytes get_context();
double get_age();
double no_inbound_for();
double no_outbound_for();
double no_data_for();
@@ -214,15 +231,20 @@ namespace RNS {
// getters
const Destination& destination() const;
// CBA LINK
const Destination& link_destination() const;
const Interface& attached_interface() const;
const Bytes& link_id() const;
const Bytes& hash() const;
uint16_t mtu() const;
Type::Link::status status() const;
double establishment_timeout() const;
uint16_t establishment_cost() const;
double request_time() const;
double last_inbound() const;
std::set<RequestReceipt>& pending_requests() const;
Type::Link::teardown_reason teardown_reason() const;
bool initiator() const;
// setters
void destination(const Destination& destination);
@@ -231,6 +253,7 @@ namespace RNS {
void establishment_cost(uint16_t cost);
void request_time(double time);
void last_inbound(double time);
void status(Type::Link::status status);
protected:
std::shared_ptr<LinkData> _object;
+12 -4
View File
@@ -10,7 +10,7 @@
#include "Destination.h"
#include "Bytes.h"
#include "Type.h"
#include "Cryptography/Fernet.h"
#include "Cryptography/Token.h"
#include <set>
@@ -18,8 +18,12 @@ namespace RNS {
class LinkData {
public:
LinkData(const Destination& destination) : _destination(destination) {}
virtual ~LinkData() {}
LinkData(const Destination& destination) : _destination(destination) {
MEM("LinkData object copy created");
}
virtual ~LinkData() {
MEM("LinkData object destroyed");
}
private:
Destination _destination;
@@ -30,7 +34,10 @@ namespace RNS {
Bytes _hash;
Type::Link::status _status = Type::Link::PENDING;
RNS::Type::Link::link_mode _mode = Link::MODE_DEFAULT;
double _rtt = 0.0;
uint16_t _mtu = RNS::Type::Reticulum::MTU;
uint16_t _mdu = 0;
uint16_t _establishment_cost = 0;
Link::Callbacks _callbacks;
Type::Link::resource_strategy _resource_strategy = Type::Link::ACCEPT_NONE;
@@ -63,9 +70,10 @@ namespace RNS {
Packet _packet = {Type::NONE};
double _request_time = 0.0;
float _establishment_rate = 0.0;
float _expected_rate = 0.0;
Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE;
Cryptography::Fernet::Ptr _fernet;
Cryptography::Token::Ptr _token;
Cryptography::X25519PrivateKey::Ptr _prv;
Bytes _prv_bytes;
+29 -7
View File
@@ -17,7 +17,7 @@ ProofDestination::ProofDestination(const Packet& packet) : Destination({Type::NO
{
}
Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/) :
Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/, context_flag context_flag /*= FLAG_UNSET*/) :
_object(new Object(destination, attached_interface))
{
@@ -33,6 +33,8 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_packet_type = packet_type;
_object->_transport_type = transport_type;
_object->_context = context;
_object->_context_flag = context_flag;
_object->_transport_id = transport_id;
_object->_data = data;
if (_object->_data.size() > MDU) {
@@ -40,6 +42,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_data.resize(MDU);
}
_object->_flags = get_packed_flags();
_object->_create_receipt = create_receipt;
}
else {
@@ -49,14 +52,32 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_fromPacked = true;
_object->_create_receipt = false;
}
/*p TODO
if destination and destination.type == RNS.Destination.LINK:
self.MTU = destination.mtu
else:
self.MTU = RNS.Reticulum.MTU
*/
// CBA LINK
if (_object->_destination && _object->_destination.type() == Type::Destination::LINK) {
// CBA TODO: Determine if this should actually be calling Link::mtu() !!!
_object->_MTU = _object->_destination.mtu();
}
MEM("Packet object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Packet::Packet(const Destination& destination, const Link& link, const Bytes& data, Type::Packet::types packet_type /*= Type::Packet::DATA*/, Type::Packet::context_types context /*= Type::Packet::CONTEXT_NONE*/) :
_object(new Object(destination, link))
// CBA LINK
//Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_type /*= Type::Packet::DATA*/, Type::Packet::context_types context /*= Type::Packet::CONTEXT_NONE*/, context_flag context_flag /*= FLAG_UNSET*/) :
/*
_object(new Object(link.destination(), link))
{
TRACE("Creating packet with link...");
_object->_MTU = link.mtu();
MEM("Packet link object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
*/
uint8_t Packet::get_packed_flags() {
@@ -287,6 +308,7 @@ void Packet::pack() {
_object->_raw << _object->_data;
}
// CBA LINK
//p elif self.packet_type == Packet.PROOF and self.destination.type == RNS.Destination.LINK:
else if (_object->_packet_type == PROOF && _object->_destination.type() == Type::Destination::LINK) {
//else if (_object->_packet_type == PROOF && _object->_destination_link) {
// Packet proofs over links are not encrypted
@@ -336,8 +358,8 @@ void Packet::pack() {
}
}
if (_object->_raw.size() > _object->_mtu) {
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_mtu) +" bytes");
if (_object->_raw.size() > _object->_MTU) {
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_MTU) +" bytes");
}
_object->_packed = true;
@@ -534,11 +556,11 @@ const Bytes Packet::get_hashable_part() const {
Bytes hashable_part;
hashable_part << (uint8_t)(_object->_raw.data()[0] & 0b00001111);
if (_object->_header_type == HEADER_2) {
//hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
//p hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
hashable_part << _object->_raw.mid((Type::Identity::TRUNCATED_HASHLENGTH/8)+2);
}
else {
//hashable_part += self.raw[2:];
//p hashable_part += self.raw[2:];
hashable_part << _object->_raw.mid(2);
}
return hashable_part;
+18 -8
View File
@@ -159,7 +159,8 @@ namespace RNS {
Type::Transport::types transport_type = Type::Transport::BROADCAST,
Type::Packet::header_types header_type = Type::Packet::HEADER_1,
const Bytes& transport_id = {Bytes::NONE},
bool create_receipt = true
bool create_receipt = true,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
);
Packet(
const Destination& destination,
@@ -169,15 +170,19 @@ namespace RNS {
Type::Transport::types transport_type = Type::Transport::BROADCAST,
Type::Packet::header_types header_type = Type::Packet::HEADER_1,
const Bytes& transport_id = {Bytes::NONE},
bool create_receipt = true
) : Packet(destination, {Type::NONE}, data, packet_type, context, transport_type, header_type, transport_id, create_receipt) {}
bool create_receipt = true,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
) : Packet(destination, {Type::NONE}, data, packet_type, context, transport_type, header_type, transport_id, create_receipt, context_flag) {}
// CBA LINK
/*
Packet(
const Destination& destination,
const Link& link,
const Bytes& data,
Type::Packet::types packet_type = Type::Packet::DATA,
Type::Packet::context_types context = Type::Packet::CONTEXT_NONE
Type::Packet::context_types context = Type::Packet::CONTEXT_NONE,
Type::Packet::context_flag context_flag = Type::Packet::FLAG_UNSET
);
*/
virtual ~Packet() {
MEM("Packet object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
@@ -242,6 +247,7 @@ namespace RNS {
inline const Bytes& transport_id() const { assert(_object); return _object->_transport_id; }
inline const Bytes& raw() const { assert(_object); return _object->_raw; }
inline const Bytes& data() const { assert(_object); return _object->_data; }
// CBA LINK
//inline const Link& destination_link() const { assert(_object); return _object->_destination_link; }
//CBA Following method is only used by Resource to access decrypted resource advertisement form Link. Consider a better way.
inline const Bytes& plaintext() { assert(_object); return _object->_plaintext; }
@@ -268,13 +274,14 @@ namespace RNS {
class Object {
public:
Object(const Destination& destination, const Interface& attached_interface) : _destination(destination), _attached_interface(attached_interface) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
// CBA LINK
//Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
virtual ~Object() { MEM("Packet::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
private:
Destination _destination = {Type::NONE};
// CBA LINK
Link _destination_link = {Type::NONE};
//Link _destination_link = {Type::NONE};
Link _link = {Type::NONE};
@@ -286,6 +293,7 @@ namespace RNS {
Type::Destination::types _destination_type = Type::Destination::SINGLE;
Type::Packet::types _packet_type = Type::Packet::DATA;
Type::Packet::context_types _context = Type::Packet::CONTEXT_NONE;
uint8_t _context_flag = Type::Packet::FLAG_UNSET;
uint8_t _flags = 0;
uint8_t _hops = 0;
@@ -299,13 +307,15 @@ namespace RNS {
bool _cached = false; // whether packet has been cached
PacketReceipt _receipt = {Type::NONE};
uint16_t _mtu = Type::Reticulum::MTU;
uint16_t _MTU = Type::Reticulum::MTU;
double _sent_at = 0;
float _rssi = 0.0;
float _snr = 0.0;
float _q = 0.0;
Bytes _packet_hash;
Bytes _ratchet_id;
Bytes _destination_hash;
Bytes _transport_id;
+2
View File
@@ -23,6 +23,8 @@ using namespace RNS::Utilities;
/*static*/ const Reticulum& Reticulum::_instance = {Type::NONE};
/*static*/ bool Reticulum::__transport_enabled = false;
/*static*/ bool Reticulum::__link_mtu_discovery = RNS::Type::Reticulum::LINK_MTU_DISCOVERY;
/*static*/ bool Reticulum::__remote_management_enabled = false;
/*static*/ bool Reticulum::__use_implicit_proof = true;
/*static*/ bool Reticulum::__allow_probes = false;
/*static*/ bool Reticulum::panic_on_interface_error = false;
+27
View File
@@ -36,6 +36,8 @@ namespace RNS {
static const Reticulum& _instance;
static bool __transport_enabled;
static bool __link_mtu_discovery;
static bool __remote_management_enabled;
static bool __use_implicit_proof;
static bool __allow_probes;
static bool panic_on_interface_error;
@@ -112,6 +114,31 @@ namespace RNS {
inline static bool transport_enabled() { return __transport_enabled; }
inline static void transport_enabled(bool transport_enabled) { __transport_enabled = transport_enabled; }
/*
Returns whether link MTU discovery is enabled for the running
instance.
When link MTU discovery is enabled, Reticulum will
automatically upgrade link MTUs to the highest supported
value, increasing transfer speed and efficiency.
:returns: True if link MTU discovery is enabled, False if not.
*/
inline static bool link_mtu_discovery() { return __link_mtu_discovery; }
inline static void link_mtu_discovery(bool link_mtu_discovery) { __link_mtu_discovery = link_mtu_discovery; }
/*
Returns whether remote management is enabled for the
running instance.
When remote management is enabled, authenticated peers
can remotely query and manage this instance.
:returns: True if remote management is enabled, False if not.
*/
inline static bool remote_management_enabled() { return __remote_management_enabled; }
inline static void remote_management_enabled(bool remote_management_enabled) { __remote_management_enabled = remote_management_enabled; }
inline static bool probe_destination_enabled() { return __allow_probes; }
inline static void probe_destination_enabled(bool allow_probes) { __allow_probes = allow_probes; }
+56 -49
View File
@@ -221,7 +221,7 @@ using namespace RNS::Utilities;
}
// TODO
/*
/*p
// Synthesize tunnels for any interfaces wanting it
for interface in Transport.interfaces:
interface.tunnel_id = None
@@ -632,7 +632,7 @@ using namespace RNS::Utilities;
//if hasattr(interface, "ifac_identity") and interface.ifac_identity != None:
if (interface.ifac_identity()) {
// TODO
/*
/*p
// Calculate packet access code
ifac = interface.ifac_identity.sign(raw)[-interface.ifac_size:]
@@ -919,7 +919,7 @@ using namespace RNS::Utilities;
if (packet.hops() > 0) {
// TODO
/*
/*p
if not hasattr(interface, "announce_cap"):
interface.announce_cap = RNS.Reticulum.ANNOUNCE_CAP
@@ -949,7 +949,7 @@ using namespace RNS::Utilities;
bool should_queue = true;
for (auto& entry : interface.announce_queue()) {
if (entry._destination == packet.destination_hash()) {
double emission_timestamp = announce_emitted(packet);
uint64_t emission_timestamp = announce_emitted(packet);
should_queue = false;
if (emission_timestamp > entry._emitted) {
entry._time = outbound_time;
@@ -1160,7 +1160,7 @@ using namespace RNS::Utilities;
}
}
// TODO
/*
/*p
// If interface access codes are enabled,
// we must authenticate each packet.
//if len(raw) > 2:
@@ -1254,7 +1254,7 @@ using namespace RNS::Utilities;
packet.hops(packet.hops() + 1);
// TODO
/*
/*p
if (interface) {
if hasattr(interface, "r_stat_rssi"):
if interface.r_stat_rssi != None:
@@ -1651,7 +1651,7 @@ using namespace RNS::Utilities;
// First, check that the announce is not for a destination
// local to this system, and that hops are less than the max
// CBA TODO determine why packet desitnation hash is being searched in destinations again since we entered this logic becuase it did not exist above
// CBA TODO determine why packet destination hash is being searched in destinations again since we entered this logic becuase it did not exist above
//if (not any(packet.destination_hash == d.hash for d in Transport.destinations) and packet.hops < Transport.PATHFINDER_M+1):
#if defined(DESTINATIONS_SET)
bool found_local = false;
@@ -1666,7 +1666,7 @@ using namespace RNS::Utilities;
auto iter = _destinations.find(packet.destination_hash());
if (iter == _destinations.end() && packet.hops() < (PATHFINDER_M+1)) {
#endif
double announce_emitted = Transport::announce_emitted(packet);
uint64_t announce_emitted = Transport::announce_emitted(packet);
//p random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
Bytes random_blob = packet.data().mid(Type::Identity::KEYSIZE/8 + Type::Identity::NAME_HASH_LENGTH/8, Type::Identity::RANDOM_HASH_LENGTH/8);
@@ -1704,11 +1704,10 @@ using namespace RNS::Utilities;
double now = OS::time();
double path_expires = destination_entry._expires;
double path_announce_emitted = 0;
uint64_t path_announce_emitted = 0;
for (const Bytes& path_random_blob : random_blobs) {
//p path_announce_emitted = max(path_announce_emitted, int.from_bytes(path_random_blob[5:10], "big"))
// CBA TODO
//z path_announce_emitted = std::max(path_announce_emitted, int.from_bytes(path_random_blob[5:10], "big"));
path_announce_emitted = std::max(path_announce_emitted, OS::from_bytes_big_endian(path_random_blob.data() + 5, 5));
if (path_announce_emitted >= announce_emitted) {
break;
}
@@ -1753,7 +1752,7 @@ using namespace RNS::Utilities;
bool rate_blocked = false;
// TODO
/*
/*p
if packet.context != RNS.Packet.PATH_RESPONSE and packet.receiving_interface.announce_rate_target != None:
if not packet.destination_hash in Transport.announce_rate_table:
rate_entry = { "last": now, "rate_violations": 0, "blocked_until": 0, "timestamps": [now]}
@@ -2019,7 +2018,7 @@ using namespace RNS::Utilities;
}
}
if (execute_callback) {
// CBA TODO Why does app data come from recall instead of from this annuonce packet?
// CBA TODO Why does app data come from recall instead of from this announce packet?
handler->received_announce(
packet.destination_hash(),
announce_identity,
@@ -2140,6 +2139,7 @@ using namespace RNS::Utilities;
// This is a link request proof, check if it
// needs to be transported
if ((Reticulum::transport_enabled() || for_local_client_link || from_local_client) && _link_table.find(packet.destination_hash()) != _link_table.end()) {
TRACE("Handling link request proof...");
LinkEntry link_entry = (*_link_table.find(packet.destination_hash())).second;
if (packet.receiving_interface() == link_entry._outbound_interface) {
try {
@@ -2181,10 +2181,15 @@ using namespace RNS::Utilities;
else {
// Check if we can deliver it to a local
// pending link
for (auto& link : _pending_links) {
TRACEF("Handling proof for link request %s", packet.destination_hash().toHex().c_str());
// CBA Must make a copy of _pending_links before traversing since it gets modified
//for (auto link : _pending_links) {
std::set<Link> pending_links(_pending_links);
for (auto& link : pending_links) {
TRACEF("Checking for link request handling by pending link %s", link.link_id().toHex().c_str());
if (link.link_id() == packet.destination_hash()) {
// TODO
//z link.validate_proof(packet);
TRACE("Requesting pending link to validate proof");
const_cast<Link&>(link).validate_proof(packet);
}
}
}
@@ -2193,8 +2198,7 @@ using namespace RNS::Utilities;
TRACE("Transport::inbound: Packet is RESOURCE PROOF");
for (auto& link : _active_links) {
if (link.link_id() == packet.destination_hash()) {
// TODO
//z link.receive(packet);
const_cast<Link&>(link).receive(packet);
}
}
}
@@ -2275,7 +2279,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::synthesize_tunnel(const Interface& interface) {
// TODO
/*
/*p
Bytes interface_hash = interface.get_hash();
Bytes public_key = _identity.get_public_key();
Bytes random_hash = Identity::get_random_hash();
@@ -2299,7 +2303,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::tunnel_synthesize_handler(const Bytes& data, const Packet& packet) {
// TODO
/*
/*p
try:
expected_length = RNS.Identity.KEYSIZE//8+RNS.Identity.HASHLENGTH//8+RNS.Reticulum.TRUNCATED_HASHLENGTH//8+RNS.Identity.SIGLENGTH//8
if len(data) == expected_length:
@@ -2326,7 +2330,7 @@ using namespace RNS::Utilities;
/*static*/ void Transport::handle_tunnel(const Bytes& tunnel_id, const Interface& interface) {
// TODO
/*
/*p
expires = time.time() + Transport.DESTINATION_TIMEOUT
if not tunnel_id in Transport.tunnels:
RNS.log("Tunnel endpoint "+RNS.prettyhexrep(tunnel_id)+" established.", RNS.LOG_DEBUG)
@@ -2388,7 +2392,7 @@ using namespace RNS::Utilities;
#elif defined(INTERFACES_MAP)
_interfaces.insert({interface.get_hash(), interface});
#endif
// CBA TODO set or add transport as listener on interface to receive incoming packets
// CBA TODO set or add transport as listener on interface to receive incoming packets?
}
/*static*/ void Transport::deregister_interface(const Interface& interface) {
@@ -2489,9 +2493,7 @@ using namespace RNS::Utilities;
#endif
}
/*static*/ void Transport::register_link(const Link& link) {
// TODO
/*
/*static*/ void Transport::register_link(Link& link) {
TRACE("Transport: Registering link " + link.toString());
if (link.initiator()) {
// CBA ACCUMULATES
@@ -2501,16 +2503,13 @@ using namespace RNS::Utilities;
// CBA ACCUMULATES
_active_links.insert(link);
}
*/
}
/*static*/ void Transport::activate_link(Link& link) {
// TODO
/*
TRACE("Transport: Activating link " + link.toString());
if (_pending_links.find(link) != _pending_links.end()) {
if (link.status() != Type::Link::ACTIVE) {
throw std::runtime_error("Invalid link state for link activation: " + link.status_string());
throw std::runtime_error("Invalid link state for link activation: " + std::to_string(link.status()));
}
_pending_links.erase(link);
// CBA ACCUMULATES
@@ -2520,7 +2519,6 @@ using namespace RNS::Utilities;
else {
ERROR("Attempted to activate a link that was not in the pending table");
}
*/
}
/*
@@ -2776,7 +2774,18 @@ Deregisters an announce handler.
return interface.bitrate();
}
else {
0;
return 0;
}
}
/*static*/ uint16_t Transport::next_hop_interface_hw_mtu(const Bytes& destination_hash) {
const Interface& interface = next_hop_interface(destination_hash);
if (interface) {
if (interface.AUTOCONFIGURE_MTU() || interface.FIXED_MTU()) return interface.HW_MTU();
else return 0;
}
else {
return 0;
}
}
@@ -2879,7 +2888,7 @@ will announce it.
///*static*/ void Transport::request_path(const Bytes& destination_hash, const Interface& on_interface /*= {Type::NONE}*/, const Bytes& tag /*= {}*/, bool recursive /*= false*/) {
/*static*/ void Transport::request_path(const Bytes& destination_hash, const Interface& on_interface, const Bytes& tag /*= {}*/, bool recursive /*= false*/) {
Bytes request_tag;
if (tag) {
if (!tag) {
request_tag = Identity::get_random_hash();
}
else {
@@ -2899,7 +2908,7 @@ will announce it.
if (on_interface && recursive) {
// TODO
/*
/*p
if not hasattr(on_interface, "announce_cap"):
on_interface.announce_cap = RNS.Reticulum.ANNOUNCE_CAP
@@ -3247,7 +3256,7 @@ will announce it.
/*static*/ void Transport::detach_interfaces() {
// TODO
/*
/*p
detachable_interfaces = []
for interface in Transport.interfaces:
@@ -3275,7 +3284,7 @@ will announce it.
/*static*/ void Transport::shared_connection_disappeared() {
// TODO
/*
/*p
for link in Transport.active_links:
link.teardown()
@@ -3294,7 +3303,7 @@ will announce it.
/*static*/ void Transport::shared_connection_reappeared() {
// TODO
/*
/*p
if Transport.owner.is_connected_to_shared_instance:
for registered_destination in Transport.destinations:
if registered_destination.type == RNS.Destination.SINGLE:
@@ -3304,7 +3313,7 @@ will announce it.
/*static*/ void Transport::drop_announce_queues() {
// TODO
/*
/*p
for interface in Transport.interfaces:
if hasattr(interface, "announce_queue") and interface.announce_queue != None:
na = len(interface.announce_queue)
@@ -3319,22 +3328,20 @@ will announce it.
*/
}
/*static*/ bool Transport::announce_emitted(const Packet& packet) {
// TODO
/*
random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
announce_emitted = int.from_bytes(random_blob[5:10], "big")
return announce_emitted
*/
// MOCK
return false;
/*static*/ uint64_t Transport::announce_emitted(const Packet& packet) {
//p random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
//p announce_emitted = int.from_bytes(random_blob[5:10], "big")
Bytes random_blob = packet.data().mid(RNS::Type::Identity::KEYSIZE/8+RNS::Type::Identity::NAME_HASH_LENGTH/8, 10);
if (random_blob) {
return OS::from_bytes_big_endian(random_blob.data() + 5, 5);
}
return 0;
}
/*static*/ void Transport::write_packet_hashlist() {
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
// TODO
/*
/*p
if not Transport.owner.is_connected_to_shared_instance:
if hasattr(Transport, "saving_packet_hashlist"):
wait_interval = 0.2
@@ -3713,7 +3720,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
/*static*/ void Transport::write_tunnel_table() {
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
// TODO
/*
/*p
if not Transport.owner.is_connected_to_shared_instance:
if hasattr(Transport, "saving_tunnel_table"):
wait_interval = 0.2
+4 -2
View File
@@ -314,7 +314,7 @@ namespace RNS {
static void deregister_interface(const Interface& interface);
static void register_destination(Destination& destination);
static void deregister_destination(const Destination& destination);
static void register_link(const Link& link);
static void register_link(Link& link);
static void activate_link(Link& link);
static void register_announce_handler(HAnnounceHandler handler);
static void deregister_announce_handler(HAnnounceHandler handler);
@@ -331,6 +331,7 @@ namespace RNS {
static Bytes next_hop(const Bytes& destination_hash);
static Interface next_hop_interface(const Bytes& destination_hash);
static uint32_t next_hop_interface_bitrate(const Bytes& destination_hash);
static uint16_t next_hop_interface_hw_mtu(const Bytes& destination_hash);
static double next_hop_per_bit_latency(const Bytes& destination_hash);
static double next_hop_per_byte_latency(const Bytes& destination_hash);
static double first_hop_timeout(const Bytes& destination_hash);
@@ -348,7 +349,7 @@ namespace RNS {
static void shared_connection_disappeared();
static void shared_connection_reappeared();
static void drop_announce_queues();
static bool announce_emitted(const Packet& packet);
static uint64_t announce_emitted(const Packet& packet);
static void write_packet_hashlist();
static bool read_path_table();
static bool write_path_table();
@@ -405,6 +406,7 @@ namespace RNS {
#elif defined(DESTINATIONS_MAP)
static std::map<Bytes, Destination> _destinations; // All active destinations
#endif
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
static std::set<Link> _pending_links; // Links that are being established
static std::set<Link> _active_links; // Links that are active
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
+79 -7
View File
@@ -1,7 +1,6 @@
#pragma once
#include "Log.h"
#include "Cryptography/Fernet.h"
#include <stdint.h>
@@ -13,12 +12,24 @@ namespace RNS { namespace Type {
};
namespace Persistence {
//static const uint16_t DOCUMENT_MAXSIZE = 1024;
static const uint16_t DOCUMENT_MAXSIZE = 8192;
//static const uint16_t DOCUMENT_MAXSIZE = 16384;
static const uint16_t BUFFER_MAXSIZE = Persistence::DOCUMENT_MAXSIZE * 1.5; // Json write buffer of 1.5 times document seems to be sufficient
}
namespace Cryptography {
namespace Fernet {
static const uint8_t FERNET_OVERHEAD = 48; // Bytes
}
namespace Token {
static const uint8_t TOKEN_OVERHEAD = 48; // Bytes
enum token_mode {
MODE_AES = 0x01,
MODE_AES_128_CBC = 0x02,
MODE_AES_256_CBC = 0x03,
};
}
}
namespace Reticulum {
@@ -38,6 +49,16 @@ namespace RNS { namespace Type {
*/
static const uint16_t MTU = 500;
/*
Whether automatic link MTU discovery is enabled by default in this
release. Link MTU discovery significantly increases throughput over
fast links, but requires all intermediary hops to also support it.
Support for this feature was added in RNS version 0.9.0. This option
will become enabled by default in the near future. Please update your
RNS instances.
*/
static const bool LINK_MTU_DISCOVERY = true;
static const uint16_t MAX_QUEUED_ANNOUNCES = 16384;
static const uint32_t QUEUED_ANNOUNCE_LIFE = 60*60*24;
@@ -104,24 +125,38 @@ namespace RNS { namespace Type {
namespace Identity {
// The curve used for Elliptic Curve DH key exchanges
//static const char CURVE[] = "Curve25519";
static constexpr const char* CURVE = "Curve25519";
// The curve used for Elliptic Curve DH key exchanges
static const uint16_t KEYSIZE = 256*2;
// X25519 key size in bits. A complete key is the concatenation of a 256 bit encryption key, and a 256 bit signing key.
static const uint16_t KEYSIZE = 256*2;
// X.25519 ratchet key size in bits.
static const uint16_t RATCHETSIZE = 256;
/*
The expiry time for received ratchets in seconds, defaults to 30 days. Reticulum will always use the most recently
announced ratchet, and remember it for up to ``RATCHET_EXPIRY`` since receiving it, after which it will be discarded.
If a newer ratchet is announced in the meantime, it will be replace the already known ratchet.
*/
static const uint32_t RATCHET_EXPIRY = 60*60*24*30;
// Non-configurable constants
static const uint8_t FERNET_OVERHEAD = Cryptography::Fernet::FERNET_OVERHEAD;
static const uint8_t TOKEN_OVERHEAD = Cryptography::Token::TOKEN_OVERHEAD;
static const uint8_t AES128_BLOCKSIZE = 16; // In bytes
static const uint16_t HASHLENGTH = Reticulum::HASHLENGTH; // In bits
static const uint16_t SIGLENGTH = KEYSIZE; // In bits
static const uint8_t NAME_HASH_LENGTH = 80;
static const uint8_t RANDOM_HASH_LENGTH = 80;
static const uint16_t TRUNCATED_HASHLENGTH = Reticulum::TRUNCATED_HASHLENGTH; // In bits
// Constant specifying the truncated hash length (in bits) used by Reticulum
// for addressable hashes and other purposes. Non-configurable.
static const uint16_t TRUNCATED_HASHLENGTH = Reticulum::TRUNCATED_HASHLENGTH; // In bits
static const uint16_t DERIVED_KEY_LENGTH = 512/8;
static const uint16_t DERIVED_KEY_LENGTH_LEGACY = 256/8;
}
@@ -169,9 +204,12 @@ namespace RNS { namespace Type {
// Timeout for link establishment in seconds per hop to destination.
static const uint8_t ESTABLISHMENT_TIMEOUT_PER_HOP = Reticulum::DEFAULT_PER_HOP_TIMEOUT;
static const uint8_t LINK_MTU_SIZE = 3;
static const uint8_t TRAFFIC_TIMEOUT_MIN_MS = 5;
// RTT timeout factor used in link timeout calculation.
static const uint16_t TRAFFIC_TIMEOUT_FACTOR = 6;
static const uint16_t KEEPALIVE_TIMEOUT_FACTOR = 4;
static const uint8_t TRAFFIC_TIMEOUT_FACTOR = 6;
static const float KEEPALIVE_MAX_RTT = 1.75;
static const uint8_t KEEPALIVE_TIMEOUT_FACTOR = 4;
// Grace period in seconds used in link timeout calculation.
static const uint8_t STALE_GRACE = 2;
// Interval for sending keep-alive packets on established links in seconds.
@@ -183,8 +221,14 @@ namespace RNS { namespace Type {
``KEEPALIVE_TIMEOUT_FACTOR`` + ``STALE_GRACE``, the link is considered timed out,
and will be torn down.
*/
static const uint8_t STALE_FACTOR = 2;
static const uint16_t STALE_TIME = 2*KEEPALIVE;
static const uint8_t WATCHDOG_MAX_SLEEP = 5;
static const uint64_t MTU_BYTEMASK = 0x1FFFFF;
static const uint8_t MODE_BYTEMASK = 0xE0;
enum status {
PENDING = 0x00,
HANDSHAKE = 0x01,
@@ -206,6 +250,28 @@ namespace RNS { namespace Type {
ACCEPT_ALL = 0x02,
};
enum link_mode {
MODE_AES128_CBC = 0x00,
MODE_AES256_CBC = 0x01,
MODE_AES256_GCM = 0x02,
MODE_OTP_RESERVED = 0x03,
MODE_PQ_RESERVED_1 = 0x04,
MODE_PQ_RESERVED_2 = 0x05,
MODE_PQ_RESERVED_3 = 0x06,
MODE_PQ_RESERVED_4 = 0x07,
};
/*
MODE_DESCRIPTIONS = {MODE_AES128_CBC: "AES_128_CBC",
MODE_AES256_CBC: "AES_256_CBC",
MODE_AES256_GCM: "MODE_AES256_GCM",
MODE_OTP_RESERVED: "MODE_OTP_RESERVED",
MODE_PQ_RESERVED_1: "MODE_PQ_RESERVED_1",
MODE_PQ_RESERVED_2: "MODE_PQ_RESERVED_2",
MODE_PQ_RESERVED_3: "MODE_PQ_RESERVED_3",
MODE_PQ_RESERVED_4: "MODE_PQ_RESERVED_4"}
*/
}
namespace RequestReceipt {
@@ -276,6 +342,12 @@ namespace RNS { namespace Type {
LRPROOF = 0xFF, // Packet is a link request proof
};
// Context flag values
enum context_flag {
FLAG_SET = 0x01,
FLAG_UNSET = 0x00,
};
// This is used to calculate allowable
// payload sizes
static const uint16_t HEADER_MAXSIZE = Reticulum::HEADER_MAXSIZE;
+9 -1
View File
@@ -70,7 +70,15 @@ namespace RNS { namespace Utilities {
//static inline double round(double 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; }
#if defined(RNS_USE_ALLOCATOR)
static inline uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
uint64_t result = 0;
for (size_t i = 0; i < len; ++i) {
result = (result << 8) | data[i];
}
return result;
}
#if defined(RNS_USE_ALLOCATOR)
static void dump_allocator_stats();
#endif