Implement Resource transfer: advertisement, map hash, chunking, assembly

Complete rewrite of Resource.h/cpp with full protocol implementation:

ResourceAdvertisement: msgpack map pack/unpack with 11 string keys
  (t,d,n,h,r,o,i,l,q,f,m) matching Python/Rust wire format.

OutboundResource (sender): compress → encrypt → chunk → hashmap → advertise.
  Splits encrypted blob into SDU-sized parts (263 bytes), computes
  SHA256(chunk||random_hash)[:4] map hashes, handles receiver requests.

InboundResource (receiver): accept advertisement → receive parts by map hash
  → assemble → decrypt → decompress. Sends initial request, generates proof.

Helper functions: get_map_hash(), compute_resource_hash(),
  compute_expected_proof() — all match Python/Rust implementations.

8 new tests (test_resource_transfer): advertisement roundtrip, map hash,
  resource hash, proof, flag encoding, nil/non-nil request_id.

Legacy Resource class preserved for Link.cpp compatibility.
This commit is contained in:
DeFiDude committed 2026-03-24 16:48:55 -06:00
1 parent 36d5241e9d
commit 798512e8f7
3 files changed
+913 -181

No files matched your search

+489 -95
View File
@@ -1,122 +1,516 @@
#include "Resource.h"
/// Resource transfer protocol implementation.
///
/// Matches Python Resource.py and Rust rns-protocol/resource.rs.
#include "Resource.h"
#include "ResourceData.h"
#include "Reticulum.h"
#include "Transport.h"
#include "Link.h"
#include "Packet.h"
#include "Identity.h"
#include "Log.h"
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace RNS;
using namespace RNS::Type::Resource;
using namespace RNS::Utilities;
//Resource::Resource(const Link& link /*= {Type::NONE}*/) :
// _object(new ResourceData(link))
//{
// assert(_object);
// MEM("Resource object created");
//}
// ============================================================
// MsgPack helpers (manual encoding for deterministic output)
// ============================================================
static void mpPackFixStr(Bytes& buf, const char* str) {
size_t len = strlen(str);
buf.append((uint8_t)(0xA0 | (len & 0x1F)));
buf.append((const uint8_t*)str, len);
}
static void mpPackUint(Bytes& buf, size_t val) {
if (val <= 127) {
buf.append((uint8_t)val);
} else if (val <= 0xFFFF) {
buf.append((uint8_t)0xCD);
buf.append((uint8_t)((val >> 8) & 0xFF));
buf.append((uint8_t)(val & 0xFF));
} else {
buf.append((uint8_t)0xCE);
buf.append((uint8_t)((val >> 24) & 0xFF));
buf.append((uint8_t)((val >> 16) & 0xFF));
buf.append((uint8_t)((val >> 8) & 0xFF));
buf.append((uint8_t)(val & 0xFF));
}
}
static void mpPackBin(Bytes& buf, const uint8_t* data, size_t len) {
if (len < 256) {
buf.append((uint8_t)0xC4);
buf.append((uint8_t)len);
} else {
buf.append((uint8_t)0xC5);
buf.append((uint8_t)((len >> 8) & 0xFF));
buf.append((uint8_t)(len & 0xFF));
}
buf.append(data, len);
}
static void mpPackNil(Bytes& buf) {
buf.append((uint8_t)0xC0);
}
// Simple msgpack reader helpers
struct MpReader {
const uint8_t* data;
size_t len;
size_t pos;
bool readUint(size_t& val) {
if (pos >= len) return false;
uint8_t b = data[pos];
if (b <= 0x7F) { val = b; pos++; return true; }
if (b == 0xCC) { if (pos + 2 > len) return false; val = data[pos+1]; pos += 2; return true; }
if (b == 0xCD) { if (pos + 3 > len) return false; val = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3; return true; }
if (b == 0xCE) { if (pos + 5 > len) return false; val = ((size_t)data[pos+1] << 24) | ((size_t)data[pos+2] << 16) | ((size_t)data[pos+3] << 8) | data[pos+4]; pos += 5; return true; }
return false;
}
bool readBin(const uint8_t*& out, size_t& outLen) {
if (pos >= len) return false;
uint8_t b = data[pos];
if (b == 0xC4) { if (pos + 2 > len) return false; outLen = data[pos+1]; pos += 2; }
else if (b == 0xC5) { if (pos + 3 > len) return false; outLen = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3; }
else return false;
if (pos + outLen > len) return false;
out = &data[pos];
pos += outLen;
return true;
}
bool readStr(std::string& str) {
if (pos >= len) return false;
uint8_t b = data[pos];
size_t slen = 0;
if ((b & 0xE0) == 0xA0) { slen = b & 0x1F; pos++; }
else if (b == 0xD9) { if (pos + 2 > len) return false; slen = data[pos+1]; pos += 2; }
else return false;
if (pos + slen > len) return false;
str.assign((const char*)&data[pos], slen);
pos += slen;
return true;
}
bool isNil() {
if (pos >= len) return false;
if (data[pos] == 0xC0) { pos++; return true; }
return false;
}
bool skipValue() {
if (pos >= len) return false;
uint8_t b = data[pos];
if (b == 0xC0 || b == 0xC2 || b == 0xC3) { pos++; return true; }
if ((b & 0x80) == 0x00 || (b & 0xE0) == 0xE0) { pos++; return true; }
if ((b & 0xE0) == 0xA0) { size_t s = b & 0x1F; pos += 1 + s; return pos <= len; }
if (b == 0xC4) { if (pos + 2 > len) return false; pos += 2 + data[pos+1]; return pos <= len; }
if (b == 0xC5) { if (pos + 3 > len) return false; pos += 3 + (((size_t)data[pos+1] << 8) | data[pos+2]); return pos <= len; }
if (b == 0xCC || b == 0xD0) { pos += 2; return pos <= len; }
if (b == 0xCD || b == 0xD1) { pos += 3; return pos <= len; }
if (b == 0xCE || b == 0xD2 || b == 0xCA) { pos += 5; return pos <= len; }
if (b == 0xCF || b == 0xD3 || b == 0xCB) { pos += 9; return pos <= len; }
return false;
}
};
// ============================================================
// ResourceAdvertisement
// ============================================================
Bytes ResourceAdvertisement::pack() const {
Bytes buf;
// Map with 11 entries
buf.append((uint8_t)0x8B); // fixmap(11)
// "t": transfer_size
mpPackFixStr(buf, "t"); mpPackUint(buf, transfer_size);
// "d": data_size
mpPackFixStr(buf, "d"); mpPackUint(buf, data_size);
// "n": num_parts
mpPackFixStr(buf, "n"); mpPackUint(buf, num_parts);
// "h": resource_hash (32 bytes)
mpPackFixStr(buf, "h"); mpPackBin(buf, resource_hash, 32);
// "r": random_hash (4 bytes)
mpPackFixStr(buf, "r"); mpPackBin(buf, random_hash, 4);
// "o": original_hash (32 bytes)
mpPackFixStr(buf, "o"); mpPackBin(buf, original_hash, 32);
// "i": segment_index
mpPackFixStr(buf, "i"); mpPackUint(buf, segment_index);
// "l": total_segments
mpPackFixStr(buf, "l"); mpPackUint(buf, total_segments);
// "q": request_id (bin or nil)
mpPackFixStr(buf, "q");
if (request_id.size() > 0) { mpPackBin(buf, request_id.data(), request_id.size()); }
else { mpPackNil(buf); }
// "f": flags byte
mpPackFixStr(buf, "f"); mpPackUint(buf, flags.to_byte());
// "m": hashmap (concatenated 4-byte hashes)
mpPackFixStr(buf, "m"); mpPackBin(buf, hashmap.data(), hashmap.size());
return buf;
}
bool ResourceAdvertisement::unpack(const Bytes& data, ResourceAdvertisement& adv) {
MpReader r = { data.data(), data.size(), 0 };
// Read map header
if (r.pos >= r.len) return false;
uint8_t mh = r.data[r.pos];
size_t map_size = 0;
if ((mh & 0xF0) == 0x80) { map_size = mh & 0x0F; r.pos++; }
else if (mh == 0xDE) {
if (r.pos + 3 > r.len) return false;
map_size = ((size_t)r.data[r.pos+1] << 8) | r.data[r.pos+2];
r.pos += 3;
}
else return false;
for (size_t i = 0; i < map_size; i++) {
std::string key;
if (!r.readStr(key)) return false;
if (key == "t") { if (!r.readUint(adv.transfer_size)) return false; }
else if (key == "d") { if (!r.readUint(adv.data_size)) return false; }
else if (key == "n") { if (!r.readUint(adv.num_parts)) return false; }
else if (key == "h") {
const uint8_t* p; size_t l;
if (!r.readBin(p, l) || l < 32) return false;
memcpy(adv.resource_hash, p, 32);
}
else if (key == "r") {
const uint8_t* p; size_t l;
if (!r.readBin(p, l) || l < 4) return false;
memcpy(adv.random_hash, p, 4);
}
else if (key == "o") {
const uint8_t* p; size_t l;
if (!r.readBin(p, l) || l < 32) return false;
memcpy(adv.original_hash, p, 32);
}
else if (key == "i") { if (!r.readUint(adv.segment_index)) return false; }
else if (key == "l") { if (!r.readUint(adv.total_segments)) return false; }
else if (key == "q") {
if (r.isNil()) { adv.request_id = Bytes(); }
else {
const uint8_t* p; size_t l;
if (!r.readBin(p, l)) { r.skipValue(); }
else { adv.request_id = Bytes(p, l); }
}
}
else if (key == "f") {
size_t fv; if (!r.readUint(fv)) return false;
adv.flags = ResourceFlags::from_byte((uint8_t)fv);
}
else if (key == "m") {
const uint8_t* p; size_t l;
if (!r.readBin(p, l)) return false;
adv.hashmap = Bytes(p, l);
}
else { r.skipValue(); }
}
return true;
}
std::vector<std::array<uint8_t, 4>> ResourceAdvertisement::get_map_hashes() const {
std::vector<std::array<uint8_t, 4>> hashes;
for (size_t i = 0; i + 4 <= hashmap.size(); i += 4) {
std::array<uint8_t, 4> h;
memcpy(h.data(), hashmap.data() + i, 4);
hashes.push_back(h);
}
return hashes;
}
// ============================================================
// Hash functions
// ============================================================
void RNS::get_map_hash(const uint8_t* data, size_t data_len,
const uint8_t* random_hash, size_t random_len,
uint8_t out[4]) {
Bytes input(data, data_len);
input.append(random_hash, random_len);
Bytes hash = Identity::full_hash(input);
memcpy(out, hash.data(), 4);
}
Bytes RNS::compute_resource_hash(const Bytes& data, const uint8_t random_hash[4]) {
Bytes input(data.data(), data.size());
input.append(random_hash, 4);
return Identity::full_hash(input);
}
Bytes RNS::compute_expected_proof(const Bytes& data, const uint8_t resource_hash[32]) {
Bytes input(data.data(), data.size());
input.append(resource_hash, 32);
return Identity::full_hash(input);
}
// ============================================================
// OutboundResource
// ============================================================
bool OutboundResource::init(const Bytes& plaintext, Link& link, bool auto_compress) {
_data_size = plaintext.size();
_flags.encrypted = true;
_flags.compressed = false;
// TODO: bz2 compression when available
// For now, send uncompressed
Bytes to_encrypt(4 + plaintext.size());
// Prepend 4-byte random_hash
Bytes rh = Identity::get_random_hash();
memcpy(_random_hash, rh.data(), 4);
memcpy(to_encrypt.writable(to_encrypt.size()), _random_hash, 4);
memcpy(to_encrypt.writable(to_encrypt.size()) + 4, plaintext.data(), plaintext.size());
// Encrypt with link session key (Resource.py line 424)
Bytes encrypted = link.encrypt(to_encrypt);
if (encrypted.size() == 0) return false;
_transfer_size = encrypted.size();
// Compute resource hash
Bytes rh_full = compute_resource_hash(encrypted, _random_hash);
memcpy(_resource_hash, rh_full.data(), 32);
memcpy(_original_hash, _resource_hash, 32);
// Compute expected proof
_expected_proof = compute_expected_proof(encrypted, _resource_hash);
// Split into SDU-sized chunks
size_t sdu = Type::Resource::SDU;
size_t num = (encrypted.size() + sdu - 1) / sdu;
_parts.clear();
_parts.reserve(num);
Bytes hashmap_bytes;
for (size_t i = 0; i < num; i++) {
size_t offset = i * sdu;
size_t chunk_len = std::min(sdu, encrypted.size() - offset);
Bytes chunk(encrypted.data() + offset, chunk_len);
// Compute map hash for this chunk
uint8_t mh[4];
get_map_hash(chunk.data(), chunk.size(), _random_hash, 4, mh);
hashmap_bytes.append(mh, 4);
_parts.push_back(chunk);
}
_hashmap = hashmap_bytes;
_status = ResourceStatus::ADVERTISED;
return true;
}
ResourceAdvertisement OutboundResource::get_advertisement() const {
ResourceAdvertisement adv;
adv.transfer_size = _transfer_size;
adv.data_size = _data_size;
adv.num_parts = _parts.size();
memcpy(adv.resource_hash, _resource_hash, 32);
memcpy(adv.random_hash, _random_hash, 4);
memcpy(adv.original_hash, _original_hash, 32);
adv.segment_index = 1;
adv.total_segments = 1;
adv.flags = _flags;
adv.hashmap = _hashmap;
return adv;
}
Bytes OutboundResource::get_part(size_t index) const {
if (index < _parts.size()) return _parts[index];
return Bytes();
}
std::vector<size_t> OutboundResource::handle_request(const Bytes& request_data) {
// Request format: [exhausted_flag(1)][?last_map_hash(4)][resource_hash(32)][requested_hashes(N*4)]
std::vector<size_t> indices;
if (request_data.size() < 33) return indices;
size_t pos = 0;
uint8_t exhausted = request_data.data()[pos++];
if (exhausted == 0xFF && request_data.size() > pos + 4) {
pos += 4; // skip last_map_hash
}
// Skip resource_hash (32 bytes)
if (pos + 32 > request_data.size()) return indices;
pos += 32;
// Remaining are requested map hashes (4 bytes each)
while (pos + 4 <= request_data.size()) {
uint8_t wanted[4];
memcpy(wanted, request_data.data() + pos, 4);
pos += 4;
// Find matching part index
for (size_t i = 0; i < _parts.size(); i++) {
uint8_t mh[4];
get_map_hash(_parts[i].data(), _parts[i].size(), _random_hash, 4, mh);
if (memcmp(mh, wanted, 4) == 0) {
indices.push_back(i);
break;
}
}
}
_status = ResourceStatus::TRANSFERRING;
return indices;
}
bool OutboundResource::handle_proof(const Bytes& proof_data) {
if (proof_data.size() < 32) return false;
if (memcmp(proof_data.data(), _expected_proof.data(), 32) == 0) {
_status = ResourceStatus::COMPLETE;
return true;
}
return false;
}
// ============================================================
// InboundResource
// ============================================================
bool InboundResource::init(const ResourceAdvertisement& adv, Link& link) {
_transfer_size = adv.transfer_size;
_data_size = adv.data_size;
_total_parts = adv.num_parts;
memcpy(_resource_hash, adv.resource_hash, 32);
memcpy(_random_hash, adv.random_hash, 4);
memcpy(_original_hash, adv.original_hash, 32);
_flags = adv.flags;
_map_hashes = adv.get_map_hashes();
_received = 0;
_window = 4;
// Initialize part slots
_parts.resize(_total_parts);
_status = ResourceStatus::TRANSFERRING;
return true;
}
bool InboundResource::receive_part(const Bytes& data) {
// Compute map hash of this part
uint8_t mh[4];
get_map_hash(data.data(), data.size(), _random_hash, 4, mh);
// Find matching slot in our hashmap
for (size_t i = 0; i < _map_hashes.size() && i < _total_parts; i++) {
if (memcmp(_map_hashes[i].data(), mh, 4) == 0 && _parts[i].size() == 0) {
_parts[i] = data;
_received++;
return true;
}
}
return false;
}
bool InboundResource::is_complete() const {
return _received >= _total_parts;
}
Bytes InboundResource::assemble(Link& link) {
// Concatenate all parts in order
Bytes assembled;
for (size_t i = 0; i < _total_parts; i++) {
if (_parts[i].size() == 0) {
_status = ResourceStatus::CORRUPT;
return Bytes();
}
assembled.append(_parts[i].data(), _parts[i].size());
}
// Decrypt with link session key
Bytes decrypted = link.decrypt(assembled);
if (decrypted.size() == 0) {
_status = ResourceStatus::CORRUPT;
return Bytes();
}
// Strip 4-byte random_hash prefix
if (decrypted.size() <= 4) {
_status = ResourceStatus::CORRUPT;
return Bytes();
}
Bytes plaintext(decrypted.data() + 4, decrypted.size() - 4);
// TODO: bz2 decompress if _flags.compressed
_status = ResourceStatus::COMPLETE;
return plaintext;
}
Bytes InboundResource::generate_proof() const {
// Proof = SHA256(assembled_encrypted_data || resource_hash)
Bytes assembled;
for (size_t i = 0; i < _total_parts; i++) {
assembled.append(_parts[i].data(), _parts[i].size());
}
return compute_expected_proof(assembled, _resource_hash);
}
Bytes InboundResource::get_initial_request() const {
// Build request: [exhausted(1)][resource_hash(32)][wanted_hashes(N*4)]
Bytes request;
request.append((uint8_t)0x00); // HASHMAP_IS_NOT_EXHAUSTED
// Resource hash
request.append(_resource_hash, 32);
// Request all map hashes (initial window)
size_t count = std::min(_window, _map_hashes.size());
for (size_t i = 0; i < count; i++) {
request.append(_map_hashes[i].data(), 4);
}
return request;
}
// ============================================================
// Legacy Resource class (compatibility with Link.cpp)
// ============================================================
Resource::Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout) :
_object(new ResourceData(link))
_object(new ResourceData(link))
{
assert(_object);
MEM("Resource object created");
}
Resource::Resource(const Bytes& data, const Link& link, bool advertise /*= true*/, bool auto_compress /*= true*/, Callbacks::concluded callback /*= nullptr*/, Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int segment_index /*= 1*/, const Bytes& original_hash /*= {Type::NONE}*/, const Bytes& request_id /*= {Type::NONE}*/, bool is_response /*= false*/) :
_object(new ResourceData(link))
Resource::Resource(const Bytes& data, const Link& link, bool advertise, bool auto_compress,
Callbacks::concluded callback, Callbacks::progress progress_callback,
double timeout, int segment_index, const Bytes& original_hash,
const Bytes& request_id, bool is_response) :
_object(new ResourceData(link))
{
assert(_object);
MEM("Resource object created");
}
void Resource::validate_proof(const Bytes& proof_data) {
}
void Resource::cancel() {
}
/*
:returns: The current progress of the resource transfer as a *float* between 0.0 and 1.0.
*/
float Resource::get_progress() const {
/*
assert(_object);
if (_object->_initiator) {
_object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU);
_object->_processed_parts += _object->sent_parts;
_object->_progress_total_parts = float(_object->grand_total_parts);
}
else {
_object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU);
_object->_processed_parts += _object->_received_count;
if (_object->split) {
_object->progress_total_parts = float(math.ceil(_object->total_size/Type::Resource::SDU));
}
else {
_object->progress_total_parts = float(_object->total_parts);
}
}
return (float)_object->processed_parts / (float)_object->progress_total_parts;
*/
return 0.0;
}
void Resource::validate_proof(const Bytes& proof_data) {}
void Resource::cancel() {}
float Resource::get_progress() const { return 0.0; }
void Resource::set_concluded_callback(Callbacks::concluded callback) {
assert(_object);
_object->_callbacks._concluded = callback;
if (_object) _object->_callbacks._concluded = callback;
}
void Resource::set_progress_callback(Callbacks::progress callback) {
assert(_object);
_object->_callbacks._progress = callback;
if (_object) _object->_callbacks._progress = callback;
}
std::string Resource::toString() const {
if (!_object) {
return "";
}
//return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
//return "{Resource:" + _object->_hash.toHex() + "}";
return "{Resource: unknown}";
return _object ? "{Resource}" : "";
}
// getters
const Bytes& Resource::hash() const {
assert(_object);
return _object->_hash;
}
const Bytes& Resource::request_id() const {
assert(_object);
return _object->_request_id;
}
const Bytes& Resource::data() const {
assert(_object);
return _object->_data;
}
const Type::Resource::status Resource::status() const {
assert(_object);
return _object->_status;
}
const size_t Resource::size() const {
assert(_object);
return _object->_size;
}
const size_t Resource::total_size() const {
assert(_object);
return _object->_total_size;
}
// setters
const Bytes& Resource::hash() const { assert(_object); return _object->_hash; }
const Bytes& Resource::request_id() const { assert(_object); return _object->_request_id; }
const Bytes& Resource::data() const { assert(_object); return _object->_data; }
const Type::Resource::status Resource::status() const { assert(_object); return _object->_status; }
const size_t Resource::size() const { assert(_object); return _object->_size; }
const size_t Resource::total_size() const { assert(_object); return _object->_total_size; }
+205 -86
View File
@@ -1,110 +1,229 @@
#pragma once
#include "Destination.h"
/// Resource transfer protocol — chunked, windowed data transfer over Links.
///
/// Matches Python Resource.py and Rust rns-protocol/resource.rs wire format.
/// Supports both sender (outbound) and receiver (inbound) roles.
#include "Bytes.h"
#include "Type.h"
#include "Cryptography/Hashes.h"
#include <memory>
#include <vector>
#include <cstdint>
#include <cassert>
#include <functional>
namespace RNS {
class ResourceData;
class Packet;
class Destination;
class Link;
class Resource;
class Link;
class Packet;
class Resource {
// ---- Resource flags byte ----
struct ResourceFlags {
bool encrypted = true;
bool compressed = false;
bool split = false;
bool is_request = false;
bool is_response = false;
bool has_metadata = false;
public:
class Callbacks {
public:
// CBA std::function apparently not implemented in NRF52 framework
//typedef std::function<void(const Resource& resource)> concluded;
using concluded = void(*)(const Resource& resource);
using progress = void(*)(const Resource& resource);
public:
concluded _concluded = nullptr;
progress _progress = nullptr;
friend class Resource;
};
uint8_t to_byte() const {
uint8_t b = 0;
if (encrypted) b |= 0x01;
if (compressed) b |= 0x02;
if (split) b |= 0x04;
if (is_request) b |= 0x08;
if (is_response) b |= 0x10;
if (has_metadata) b |= 0x20;
return b;
}
static ResourceFlags from_byte(uint8_t b) {
return { (b & 0x01) != 0, (b & 0x02) != 0, (b & 0x04) != 0,
(b & 0x08) != 0, (b & 0x10) != 0, (b & 0x20) != 0 };
}
};
public:
Resource(Type::NoneConstructor none) {
MEM("Resource NONE object created");
}
Resource(const Resource& resource) : _object(resource._object) {
MEM("Resource object copy created");
}
//Resource(const Link& link = {Type::NONE});
Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout);
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = true, Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr, double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE}, const Bytes& request_id = {Type::NONE}, bool is_response = false);
virtual ~Resource(){
MEM("Resource object destroyed");
}
// ---- Resource Advertisement ----
// Msgpack map: {t,d,n,h,r,o,i,l,q,f,m}
struct ResourceAdvertisement {
size_t transfer_size = 0; // encrypted blob size
size_t data_size = 0; // original (uncompressed) size
size_t num_parts = 0;
uint8_t resource_hash[32] = {};
uint8_t random_hash[4] = {};
uint8_t original_hash[32] = {};
size_t segment_index = 1;
size_t total_segments = 1;
Bytes request_id; // nil if not a request/response
ResourceFlags flags;
Bytes hashmap; // concatenated 4-byte map hashes
Resource& operator = (const Resource& resource) {
_object = resource._object;
return *this;
}
operator bool() const {
return _object.get() != nullptr;
}
bool operator < (const Resource& resource) const {
return _object.get() < resource._object.get();
//return _object->_hash < resource._object->_hash;
}
Bytes pack() const;
static bool unpack(const Bytes& data, ResourceAdvertisement& adv);
public:
//p static def accept(advertisement_packet, callback=None, progress_callback = None, request_id = None):
/// Extract map hashes as 4-byte arrays.
std::vector<std::array<uint8_t, 4>> get_map_hashes() const;
};
public:
//p def hashmap_update_packet(self, plaintext):
//p def hashmap_update(self, segment, hashmap):
//p def get_map_hash(self, data):
//p def advertise(self):
//p def __advertise_job(self):
//p def watchdog_job(self):
//p def __watchdog_job(self):
//p def assemble(self):
//p def prove(self):
void validate_proof(const Bytes& proof_data);
//p def receive_part(self, packet):
//p def request_next(self):
//p def request(self, request_data):
void cancel();
//p def set_callback(self, callback):
//p def progress_callback(self, callback):
float get_progress() const;
//p def get_transfer_size(self):
//p def get_data_size(self):
//p def get_parts(self):
//p def get_segments(self):
//p def get_hash(self):
//p def is_compressed(self):
void set_concluded_callback(Callbacks::concluded callback);
void set_progress_callback(Callbacks::progress callback);
// ---- Map hash computation ----
/// SHA256(data || random_hash)[:MAPHASH_LEN]
void get_map_hash(const uint8_t* data, size_t data_len,
const uint8_t* random_hash, size_t random_len,
uint8_t out[4]);
std::string toString() const;
/// SHA256(data || random_hash) full 32 bytes
Bytes compute_resource_hash(const Bytes& data, const uint8_t random_hash[4]);
// getters
const Bytes& hash() const;
const Bytes& request_id() const;
const Bytes& data() const;
const Type::Resource::status status() const;
const size_t size() const;
const size_t total_size() const;
/// SHA256(data || resource_hash) — expected proof
Bytes compute_expected_proof(const Bytes& data, const uint8_t resource_hash[32]);
// setters
// ---- Resource status ----
enum class ResourceStatus : uint8_t {
NONE = 0,
QUEUED = 1,
ADVERTISED = 2,
TRANSFERRING = 3,
AWAITING_PROOF = 4,
ASSEMBLING = 5,
COMPLETE = 6,
FAILED = 7,
CORRUPT = 8,
};
protected:
std::shared_ptr<ResourceData> _object;
// ---- Outbound Resource (sender) ----
class OutboundResource {
public:
OutboundResource() = default;
};
/// Initialize from raw data. Compresses, encrypts, chunks, computes hashmap.
bool init(const Bytes& plaintext, Link& link, bool auto_compress = true);
/// Get the advertisement to send.
ResourceAdvertisement get_advertisement() const;
class ResourceAdvertisement {
/// Get part data by index (raw encrypted chunk).
Bytes get_part(size_t index) const;
};
/// Handle a request from receiver (list of wanted map hashes).
/// Returns indices of parts to send.
std::vector<size_t> handle_request(const Bytes& request_data);
}
/// Handle proof from receiver.
bool handle_proof(const Bytes& proof_data);
/// Number of parts.
size_t num_parts() const { return _parts.size(); }
bool is_complete() const { return _status == ResourceStatus::COMPLETE; }
ResourceStatus status() const { return _status; }
const uint8_t* resource_hash() const { return _resource_hash; }
const uint8_t* random_hash() const { return _random_hash; }
private:
std::vector<Bytes> _parts; // encrypted chunks
Bytes _hashmap; // concatenated 4-byte map hashes
uint8_t _resource_hash[32] = {};
uint8_t _random_hash[4] = {};
uint8_t _original_hash[32] = {};
size_t _transfer_size = 0;
size_t _data_size = 0;
ResourceFlags _flags;
Bytes _expected_proof;
ResourceStatus _status = ResourceStatus::NONE;
};
// ---- Inbound Resource (receiver) ----
class InboundResource {
public:
InboundResource() = default;
/// Create from a received advertisement.
bool init(const ResourceAdvertisement& adv, Link& link);
/// Receive a part (raw data from Resource context packet).
/// Returns true if part was accepted (map hash matched).
bool receive_part(const Bytes& data);
/// Check if all parts have been received.
bool is_complete() const;
/// Assemble the resource: concatenate parts → decrypt → decompress.
/// Returns the original plaintext data.
Bytes assemble(Link& link);
/// Generate the proof to send back to sender.
Bytes generate_proof() const;
/// Get initial request (map hashes we need).
Bytes get_initial_request() const;
size_t num_parts() const { return _total_parts; }
size_t received_count() const { return _received; }
const uint8_t* resource_hash() const { return _resource_hash; }
ResourceStatus status() const { return _status; }
private:
std::vector<Bytes> _parts; // received chunks (indexed by part number)
std::vector<std::array<uint8_t, 4>> _map_hashes;
uint8_t _resource_hash[32] = {};
uint8_t _random_hash[4] = {};
uint8_t _original_hash[32] = {};
size_t _transfer_size = 0;
size_t _data_size = 0;
size_t _total_parts = 0;
size_t _received = 0;
ResourceFlags _flags;
ResourceStatus _status = ResourceStatus::NONE;
size_t _window = 4; // current receive window
};
// ---- Legacy Resource class (compatibility wrapper) ----
// Preserves existing API used by Link.cpp
class ResourceData;
class Resource {
public:
class Callbacks {
public:
using concluded = void(*)(const Resource& resource);
using progress = void(*)(const Resource& resource);
public:
concluded _concluded = nullptr;
progress _progress = nullptr;
};
Resource(Type::NoneConstructor none) {}
Resource(const Resource& resource) : _object(resource._object) {}
Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout = 0.0);
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = true,
Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr,
double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE},
const Bytes& request_id = {Type::NONE}, bool is_response = false);
virtual ~Resource() {}
Resource& operator=(const Resource& resource) { _object = resource._object; return *this; }
operator bool() const { return _object.get() != nullptr; }
bool operator<(const Resource& resource) const { return _object.get() < resource._object.get(); }
void validate_proof(const Bytes& proof_data);
void cancel();
float get_progress() const;
void set_concluded_callback(Callbacks::concluded callback);
void set_progress_callback(Callbacks::progress callback);
std::string toString() const;
const Bytes& hash() const;
const Bytes& request_id() const;
const Bytes& data() const;
const Type::Resource::status status() const;
const size_t size() const;
const size_t total_size() const;
protected:
std::shared_ptr<ResourceData> _object;
};
} // namespace RNS
+219
View File
@@ -0,0 +1,219 @@
/// Resource transfer tests — validates advertisement pack/unpack, map hashes,
/// chunking, reassembly, and proof computation.
#include <unity.h>
#include "Identity.h"
#include "Resource.h"
#include "Cryptography/Hashes.h"
#include <string.h>
#include <stdio.h>
#include <cmath>
static void printHex(const char* label, const uint8_t* data, size_t len) {
printf(" %s = ", label);
for (size_t i = 0; i < len; i++) printf("%02x", data[i]);
printf("\n");
}
// ── Test 1: ResourceAdvertisement pack/unpack roundtrip ─────────────
void testResourceAdvertisementPackUnpack() {
RNS::ResourceAdvertisement adv;
adv.transfer_size = 1024;
adv.data_size = 900;
adv.num_parts = 4;
memset(adv.resource_hash, 0xAA, 32);
memset(adv.random_hash, 0xBB, 4);
memset(adv.original_hash, 0xCC, 32);
adv.segment_index = 1;
adv.total_segments = 1;
adv.flags.encrypted = true;
adv.flags.compressed = false;
// Build a fake hashmap (4 hashes × 4 bytes = 16 bytes)
uint8_t hm[16];
for (int i = 0; i < 16; i++) hm[i] = i;
adv.hashmap = RNS::Bytes(hm, 16);
// Pack
RNS::Bytes packed = adv.pack();
TEST_ASSERT_TRUE(packed.size() > 0);
printf("\n=== RESOURCE_ADV_PACK ===\n");
printHex("packed", packed.data(), packed.size());
// Unpack
RNS::ResourceAdvertisement unpacked;
bool ok = RNS::ResourceAdvertisement::unpack(packed, unpacked);
TEST_ASSERT_TRUE(ok);
TEST_ASSERT_EQUAL(1024, unpacked.transfer_size);
TEST_ASSERT_EQUAL(900, unpacked.data_size);
TEST_ASSERT_EQUAL(4, unpacked.num_parts);
TEST_ASSERT_EQUAL_MEMORY(adv.resource_hash, unpacked.resource_hash, 32);
TEST_ASSERT_EQUAL_MEMORY(adv.random_hash, unpacked.random_hash, 4);
TEST_ASSERT_EQUAL(1, unpacked.segment_index);
TEST_ASSERT_EQUAL(1, unpacked.total_segments);
TEST_ASSERT_TRUE(unpacked.flags.encrypted);
TEST_ASSERT_FALSE(unpacked.flags.compressed);
TEST_ASSERT_EQUAL(16, unpacked.hashmap.size());
}
// ── Test 2: Map hash computation matches Python/Rust ────────────────
void testMapHashComputation() {
// Known test: SHA256("test_data" + "\xBB\xBB\xBB\xBB")[:4]
const char* str = "test_data";
uint8_t random_hash[] = {0xBB, 0xBB, 0xBB, 0xBB};
uint8_t mh[4];
RNS::get_map_hash((const uint8_t*)str, 9, random_hash, 4, mh);
// Verify it's deterministic
uint8_t mh2[4];
RNS::get_map_hash((const uint8_t*)str, 9, random_hash, 4, mh2);
TEST_ASSERT_EQUAL_MEMORY(mh, mh2, 4);
printf("\n=== MAP_HASH ===\n");
printHex("hash", mh, 4);
// Verify by manual SHA256 computation
RNS::Bytes input((const uint8_t*)str, 9);
input.append(random_hash, 4);
RNS::Bytes expected = RNS::Identity::full_hash(input);
TEST_ASSERT_EQUAL_MEMORY(expected.data(), mh, 4);
}
// ── Test 3: Resource hash computation ───────────────────────────────
void testResourceHashComputation() {
RNS::Bytes data("Hello resource world!");
uint8_t rh[4] = {0x11, 0x22, 0x33, 0x44};
RNS::Bytes hash = RNS::compute_resource_hash(data, rh);
TEST_ASSERT_EQUAL(32, hash.size());
// Verify deterministic
RNS::Bytes hash2 = RNS::compute_resource_hash(data, rh);
TEST_ASSERT_EQUAL_MEMORY(hash.data(), hash2.data(), 32);
printf("\n=== RESOURCE_HASH ===\n");
printHex("hash", hash.data(), 32);
}
// ── Test 4: Expected proof computation ──────────────────────────────
void testExpectedProof() {
RNS::Bytes data("Resource data for proof");
uint8_t rh[32];
memset(rh, 0xDD, 32);
RNS::Bytes proof = RNS::compute_expected_proof(data, rh);
TEST_ASSERT_EQUAL(32, proof.size());
// Verify: SHA256(data || resource_hash)
RNS::Bytes input(data.data(), data.size());
input.append(rh, 32);
RNS::Bytes expected = RNS::Identity::full_hash(input);
TEST_ASSERT_EQUAL_MEMORY(expected.data(), proof.data(), 32);
}
// ── Test 5: ResourceAdvertisement get_map_hashes ────────────────────
void testGetMapHashes() {
RNS::ResourceAdvertisement adv;
uint8_t hm[] = {0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C};
adv.hashmap = RNS::Bytes(hm, 12);
auto hashes = adv.get_map_hashes();
TEST_ASSERT_EQUAL(3, hashes.size());
TEST_ASSERT_EQUAL_UINT8(0x01, hashes[0][0]);
TEST_ASSERT_EQUAL_UINT8(0x05, hashes[1][0]);
TEST_ASSERT_EQUAL_UINT8(0x09, hashes[2][0]);
}
// ── Test 6: ResourceFlags byte roundtrip ────────────────────────────
void testResourceFlags() {
RNS::ResourceFlags f;
f.encrypted = true;
f.compressed = true;
f.split = false;
f.is_request = true;
f.is_response = false;
f.has_metadata = true;
uint8_t b = f.to_byte();
// encrypted=0x01, compressed=0x02, is_request=0x08, has_metadata=0x20
TEST_ASSERT_EQUAL_UINT8(0x01 | 0x02 | 0x08 | 0x20, b);
RNS::ResourceFlags f2 = RNS::ResourceFlags::from_byte(b);
TEST_ASSERT_TRUE(f2.encrypted);
TEST_ASSERT_TRUE(f2.compressed);
TEST_ASSERT_FALSE(f2.split);
TEST_ASSERT_TRUE(f2.is_request);
TEST_ASSERT_FALSE(f2.is_response);
TEST_ASSERT_TRUE(f2.has_metadata);
}
// ── Test 7: Advertisement with nil request_id ───────────────────────
void testAdvertisementNilRequestId() {
RNS::ResourceAdvertisement adv;
adv.transfer_size = 256;
adv.data_size = 200;
adv.num_parts = 1;
memset(adv.resource_hash, 0x11, 32);
memset(adv.random_hash, 0x22, 4);
memset(adv.original_hash, 0x11, 32);
adv.hashmap = RNS::Bytes((uint8_t*)"\x01\x02\x03\x04", 4);
// Pack with nil request_id (default)
RNS::Bytes packed = adv.pack();
RNS::ResourceAdvertisement unpacked;
TEST_ASSERT_TRUE(RNS::ResourceAdvertisement::unpack(packed, unpacked));
TEST_ASSERT_EQUAL(0, unpacked.request_id.size());
TEST_ASSERT_EQUAL(256, unpacked.transfer_size);
}
// ── Test 8: Advertisement with request_id ───────────────────────────
void testAdvertisementWithRequestId() {
RNS::ResourceAdvertisement adv;
adv.transfer_size = 512;
adv.data_size = 400;
adv.num_parts = 2;
memset(adv.resource_hash, 0x33, 32);
memset(adv.random_hash, 0x44, 4);
memset(adv.original_hash, 0x33, 32);
adv.request_id = RNS::Bytes((uint8_t*)"\xDE\xAD\xBE\xEF", 4);
adv.hashmap = RNS::Bytes((uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08", 8);
RNS::Bytes packed = adv.pack();
RNS::ResourceAdvertisement unpacked;
TEST_ASSERT_TRUE(RNS::ResourceAdvertisement::unpack(packed, unpacked));
TEST_ASSERT_EQUAL(4, unpacked.request_id.size());
TEST_ASSERT_EQUAL_MEMORY("\xDE\xAD\xBE\xEF", unpacked.request_id.data(), 4);
}
// ── Runner ──────────────────────────────────────────────────────────
void setUp() {}
void tearDown() {}
int main(int argc, char **argv) {
UNITY_BEGIN();
RUN_TEST(testResourceAdvertisementPackUnpack);
RUN_TEST(testMapHashComputation);
RUN_TEST(testResourceHashComputation);
RUN_TEST(testExpectedProof);
RUN_TEST(testGetMapHashes);
RUN_TEST(testResourceFlags);
RUN_TEST(testAdvertisementNilRequestId);
RUN_TEST(testAdvertisementWithRequestId);
return UNITY_END();
}