mirror of
https://github.com/ratspeak/microReticulum
synced 2026-11-22 23:10:38 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1071754be | ||
|
|
c877730b91 | ||
|
|
dd7c749ea3 | ||
|
|
352de23ed0 | ||
|
|
166083aba7 | ||
|
|
40eeccc646 | ||
|
|
798512e8f7 | ||
|
|
36d5241e9d | ||
|
|
65ecaef894 | ||
|
|
ed362a52ee | ||
|
|
fb76b6707b | ||
|
|
6f3c08de93 | ||
|
|
8b052eb4c3 | ||
|
|
7023c9444a | ||
|
|
1acd840182 | ||
|
|
b44d3743ec | ||
|
|
813d9095d7 | ||
|
|
bb291795da | ||
|
|
bc33c0af64 | ||
|
|
184e6b0250 | ||
|
|
af9fbab780 | ||
|
|
79271a018b | ||
|
|
3bc64abbde | ||
|
|
425c2a9907 | ||
|
|
392363c1b0 |
No files matched your search
@@ -0,0 +1,86 @@
|
||||
/// BZ2 compression implementation using vendored libbzip2.
|
||||
#include "BZ2.h"
|
||||
|
||||
extern "C" {
|
||||
#include "bzlib.h"
|
||||
}
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
|
||||
namespace RNS {
|
||||
namespace Compression {
|
||||
|
||||
Bytes bz2_compress(const uint8_t* data, size_t len) {
|
||||
if (len == 0) return Bytes();
|
||||
|
||||
// bz2 output can be slightly larger than input for incompressible data
|
||||
unsigned int dest_len = (unsigned int)(len + len / 100 + 600);
|
||||
char* dest = (char*)malloc(dest_len);
|
||||
if (!dest) return Bytes();
|
||||
|
||||
int ret = BZ2_bzBuffToBuffCompress(
|
||||
dest, &dest_len,
|
||||
(char*)data, (unsigned int)len,
|
||||
9, // blockSize100k (1-9, 9 = best compression)
|
||||
0, // verbosity
|
||||
30 // workFactor (default)
|
||||
);
|
||||
|
||||
if (ret != BZ_OK) {
|
||||
free(dest);
|
||||
return Bytes();
|
||||
}
|
||||
|
||||
Bytes result((const uint8_t*)dest, dest_len);
|
||||
free(dest);
|
||||
return result;
|
||||
}
|
||||
|
||||
Bytes bz2_decompress(const uint8_t* data, size_t len, size_t max_size) {
|
||||
if (len == 0) return Bytes();
|
||||
|
||||
// Try with progressively larger buffers
|
||||
size_t multipliers[] = {4, 16, 64, 256};
|
||||
for (size_t mult : multipliers) {
|
||||
unsigned int dest_len = (unsigned int)(len * mult);
|
||||
if (dest_len < 1024) dest_len = 1024;
|
||||
if (max_size > 0 && dest_len > (unsigned int)max_size) dest_len = (unsigned int)max_size;
|
||||
|
||||
char* dest = (char*)malloc(dest_len);
|
||||
if (!dest) return Bytes();
|
||||
|
||||
int ret = BZ2_bzBuffToBuffDecompress(
|
||||
dest, &dest_len,
|
||||
(char*)data, (unsigned int)len,
|
||||
0, 0 // small=0, verbosity=0
|
||||
);
|
||||
|
||||
if (ret == BZ_OK) {
|
||||
if (max_size > 0 && dest_len > (unsigned int)max_size) {
|
||||
free(dest);
|
||||
return Bytes();
|
||||
}
|
||||
Bytes result((const uint8_t*)dest, dest_len);
|
||||
free(dest);
|
||||
return result;
|
||||
}
|
||||
|
||||
free(dest);
|
||||
if (ret != BZ_OUTBUFF_FULL) return Bytes(); // Unrecoverable error
|
||||
}
|
||||
|
||||
return Bytes();
|
||||
}
|
||||
|
||||
CompressResult try_compress(const Bytes& data) {
|
||||
Bytes compressed = bz2_compress(data);
|
||||
if (compressed.size() > 0 && compressed.size() < data.size()) {
|
||||
return { compressed, true };
|
||||
}
|
||||
return { data, false };
|
||||
}
|
||||
|
||||
} // namespace Compression
|
||||
} // namespace RNS
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
/// BZ2 compression/decompression wrapper for Reticulum Resource transfers.
|
||||
/// Uses the vendored libbzip2 (bzip2-1.0.8, BSD license).
|
||||
///
|
||||
/// Matches Python's bz2.compress()/bz2.decompress() and Rust's bzip2 crate.
|
||||
|
||||
#include "../Bytes.h"
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
|
||||
namespace RNS {
|
||||
namespace Compression {
|
||||
|
||||
/// Compress data using bz2. Returns empty Bytes on failure.
|
||||
Bytes bz2_compress(const uint8_t* data, size_t len);
|
||||
inline Bytes bz2_compress(const Bytes& data) { return bz2_compress(data.data(), data.size()); }
|
||||
|
||||
/// Decompress bz2 data. Returns empty Bytes on failure.
|
||||
/// max_size limits decompressed output (0 = no limit).
|
||||
Bytes bz2_decompress(const uint8_t* data, size_t len, size_t max_size = 0);
|
||||
inline Bytes bz2_decompress(const Bytes& data, size_t max_size = 0) { return bz2_decompress(data.data(), data.size(), max_size); }
|
||||
|
||||
/// Try compression: returns (compressed, true) if smaller, (original, false) otherwise.
|
||||
struct CompressResult {
|
||||
Bytes data;
|
||||
bool compressed;
|
||||
};
|
||||
CompressResult try_compress(const Bytes& data);
|
||||
|
||||
} // namespace Compression
|
||||
} // namespace RNS
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,672 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Compression machinery (not incl block sorting) ---*/
|
||||
/*--- compress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
/* CHANGES
|
||||
0.9.0 -- original version.
|
||||
0.9.0a/b -- no changes in this file.
|
||||
0.9.0c -- changed setting of nGroups in sendMTFValues()
|
||||
so as to do a bit better on small files
|
||||
*/
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
/*--- Bit stream I/O ---*/
|
||||
/*---------------------------------------------------*/
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_bsInitWrite ( EState* s )
|
||||
{
|
||||
s->bsLive = 0;
|
||||
s->bsBuff = 0;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsFinishWrite ( EState* s )
|
||||
{
|
||||
while (s->bsLive > 0) {
|
||||
s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24);
|
||||
s->numZ++;
|
||||
s->bsBuff <<= 8;
|
||||
s->bsLive -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define bsNEEDW(nz) \
|
||||
{ \
|
||||
while (s->bsLive >= 8) { \
|
||||
s->zbits[s->numZ] \
|
||||
= (UChar)(s->bsBuff >> 24); \
|
||||
s->numZ++; \
|
||||
s->bsBuff <<= 8; \
|
||||
s->bsLive -= 8; \
|
||||
} \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
__inline__
|
||||
void bsW ( EState* s, Int32 n, UInt32 v )
|
||||
{
|
||||
bsNEEDW ( n );
|
||||
s->bsBuff |= (v << (32 - s->bsLive - n));
|
||||
s->bsLive += n;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsPutUInt32 ( EState* s, UInt32 u )
|
||||
{
|
||||
bsW ( s, 8, (u >> 24) & 0xffL );
|
||||
bsW ( s, 8, (u >> 16) & 0xffL );
|
||||
bsW ( s, 8, (u >> 8) & 0xffL );
|
||||
bsW ( s, 8, u & 0xffL );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void bsPutUChar ( EState* s, UChar c )
|
||||
{
|
||||
bsW( s, 8, (UInt32)c );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
/*--- The back end proper ---*/
|
||||
/*---------------------------------------------------*/
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void makeMaps_e ( EState* s )
|
||||
{
|
||||
Int32 i;
|
||||
s->nInUse = 0;
|
||||
for (i = 0; i < 256; i++)
|
||||
if (s->inUse[i]) {
|
||||
s->unseqToSeq[i] = s->nInUse;
|
||||
s->nInUse++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void generateMTFValues ( EState* s )
|
||||
{
|
||||
UChar yy[256];
|
||||
Int32 i, j;
|
||||
Int32 zPend;
|
||||
Int32 wr;
|
||||
Int32 EOB;
|
||||
|
||||
/*
|
||||
After sorting (eg, here),
|
||||
s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,
|
||||
and
|
||||
((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
|
||||
holds the original block data.
|
||||
|
||||
The first thing to do is generate the MTF values,
|
||||
and put them in
|
||||
((UInt16*)s->arr1) [ 0 .. s->nblock-1 ].
|
||||
Because there are strictly fewer or equal MTF values
|
||||
than block values, ptr values in this area are overwritten
|
||||
with MTF values only when they are no longer needed.
|
||||
|
||||
The final compressed bitstream is generated into the
|
||||
area starting at
|
||||
(UChar*) (&((UChar*)s->arr2)[s->nblock])
|
||||
|
||||
These storage aliases are set up in bzCompressInit(),
|
||||
except for the last one, which is arranged in
|
||||
compressBlock().
|
||||
*/
|
||||
UInt32* ptr = s->ptr;
|
||||
UChar* block = s->block;
|
||||
UInt16* mtfv = s->mtfv;
|
||||
|
||||
makeMaps_e ( s );
|
||||
EOB = s->nInUse+1;
|
||||
|
||||
for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0;
|
||||
|
||||
wr = 0;
|
||||
zPend = 0;
|
||||
for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i;
|
||||
|
||||
for (i = 0; i < s->nblock; i++) {
|
||||
UChar ll_i;
|
||||
AssertD ( wr <= i, "generateMTFValues(1)" );
|
||||
j = ptr[i]-1; if (j < 0) j += s->nblock;
|
||||
ll_i = s->unseqToSeq[block[j]];
|
||||
AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" );
|
||||
|
||||
if (yy[0] == ll_i) {
|
||||
zPend++;
|
||||
} else {
|
||||
|
||||
if (zPend > 0) {
|
||||
zPend--;
|
||||
while (True) {
|
||||
if (zPend & 1) {
|
||||
mtfv[wr] = BZ_RUNB; wr++;
|
||||
s->mtfFreq[BZ_RUNB]++;
|
||||
} else {
|
||||
mtfv[wr] = BZ_RUNA; wr++;
|
||||
s->mtfFreq[BZ_RUNA]++;
|
||||
}
|
||||
if (zPend < 2) break;
|
||||
zPend = (zPend - 2) / 2;
|
||||
};
|
||||
zPend = 0;
|
||||
}
|
||||
{
|
||||
register UChar rtmp;
|
||||
register UChar* ryy_j;
|
||||
register UChar rll_i;
|
||||
rtmp = yy[1];
|
||||
yy[1] = yy[0];
|
||||
ryy_j = &(yy[1]);
|
||||
rll_i = ll_i;
|
||||
while ( rll_i != rtmp ) {
|
||||
register UChar rtmp2;
|
||||
ryy_j++;
|
||||
rtmp2 = rtmp;
|
||||
rtmp = *ryy_j;
|
||||
*ryy_j = rtmp2;
|
||||
};
|
||||
yy[0] = rtmp;
|
||||
j = ryy_j - &(yy[0]);
|
||||
mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (zPend > 0) {
|
||||
zPend--;
|
||||
while (True) {
|
||||
if (zPend & 1) {
|
||||
mtfv[wr] = BZ_RUNB; wr++;
|
||||
s->mtfFreq[BZ_RUNB]++;
|
||||
} else {
|
||||
mtfv[wr] = BZ_RUNA; wr++;
|
||||
s->mtfFreq[BZ_RUNA]++;
|
||||
}
|
||||
if (zPend < 2) break;
|
||||
zPend = (zPend - 2) / 2;
|
||||
};
|
||||
zPend = 0;
|
||||
}
|
||||
|
||||
mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++;
|
||||
|
||||
s->nMTF = wr;
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define BZ_LESSER_ICOST 0
|
||||
#define BZ_GREATER_ICOST 15
|
||||
|
||||
static
|
||||
void sendMTFValues ( EState* s )
|
||||
{
|
||||
Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;
|
||||
Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;
|
||||
Int32 nGroups, nBytes;
|
||||
|
||||
/*--
|
||||
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
is a global since the decoder also needs it.
|
||||
|
||||
Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
are also globals only used in this proc.
|
||||
Made global to keep stack frame size small.
|
||||
--*/
|
||||
|
||||
|
||||
UInt16 cost[BZ_N_GROUPS];
|
||||
Int32 fave[BZ_N_GROUPS];
|
||||
|
||||
UInt16* mtfv = s->mtfv;
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf3( " %d in block, %d after MTF & 1-2 coding, "
|
||||
"%d+2 syms in use\n",
|
||||
s->nblock, s->nMTF, s->nInUse );
|
||||
|
||||
alphaSize = s->nInUse+2;
|
||||
for (t = 0; t < BZ_N_GROUPS; t++)
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
s->len[t][v] = BZ_GREATER_ICOST;
|
||||
|
||||
/*--- Decide how many coding tables to use ---*/
|
||||
AssertH ( s->nMTF > 0, 3001 );
|
||||
if (s->nMTF < 200) nGroups = 2; else
|
||||
if (s->nMTF < 600) nGroups = 3; else
|
||||
if (s->nMTF < 1200) nGroups = 4; else
|
||||
if (s->nMTF < 2400) nGroups = 5; else
|
||||
nGroups = 6;
|
||||
|
||||
/*--- Generate an initial set of coding tables ---*/
|
||||
{
|
||||
Int32 nPart, remF, tFreq, aFreq;
|
||||
|
||||
nPart = nGroups;
|
||||
remF = s->nMTF;
|
||||
gs = 0;
|
||||
while (nPart > 0) {
|
||||
tFreq = remF / nPart;
|
||||
ge = gs-1;
|
||||
aFreq = 0;
|
||||
while (aFreq < tFreq && ge < alphaSize-1) {
|
||||
ge++;
|
||||
aFreq += s->mtfFreq[ge];
|
||||
}
|
||||
|
||||
if (ge > gs
|
||||
&& nPart != nGroups && nPart != 1
|
||||
&& ((nGroups-nPart) % 2 == 1)) {
|
||||
aFreq -= s->mtfFreq[ge];
|
||||
ge--;
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf5( " initial group %d, [%d .. %d], "
|
||||
"has %d syms (%4.1f%%)\n",
|
||||
nPart, gs, ge, aFreq,
|
||||
(100.0 * (float)aFreq) / (float)(s->nMTF) );
|
||||
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
if (v >= gs && v <= ge)
|
||||
s->len[nPart-1][v] = BZ_LESSER_ICOST; else
|
||||
s->len[nPart-1][v] = BZ_GREATER_ICOST;
|
||||
|
||||
nPart--;
|
||||
gs = ge+1;
|
||||
remF -= aFreq;
|
||||
}
|
||||
}
|
||||
|
||||
/*---
|
||||
Iterate up to BZ_N_ITERS times to improve the tables.
|
||||
---*/
|
||||
for (iter = 0; iter < BZ_N_ITERS; iter++) {
|
||||
|
||||
for (t = 0; t < nGroups; t++) fave[t] = 0;
|
||||
|
||||
for (t = 0; t < nGroups; t++)
|
||||
for (v = 0; v < alphaSize; v++)
|
||||
s->rfreq[t][v] = 0;
|
||||
|
||||
/*---
|
||||
Set up an auxiliary length table which is used to fast-track
|
||||
the common case (nGroups == 6).
|
||||
---*/
|
||||
if (nGroups == 6) {
|
||||
for (v = 0; v < alphaSize; v++) {
|
||||
s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v];
|
||||
s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v];
|
||||
s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v];
|
||||
}
|
||||
}
|
||||
|
||||
nSelectors = 0;
|
||||
totc = 0;
|
||||
gs = 0;
|
||||
while (True) {
|
||||
|
||||
/*--- Set group start & end marks. --*/
|
||||
if (gs >= s->nMTF) break;
|
||||
ge = gs + BZ_G_SIZE - 1;
|
||||
if (ge >= s->nMTF) ge = s->nMTF-1;
|
||||
|
||||
/*--
|
||||
Calculate the cost of this group as coded
|
||||
by each of the coding tables.
|
||||
--*/
|
||||
for (t = 0; t < nGroups; t++) cost[t] = 0;
|
||||
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
register UInt32 cost01, cost23, cost45;
|
||||
register UInt16 icv;
|
||||
cost01 = cost23 = cost45 = 0;
|
||||
|
||||
# define BZ_ITER(nn) \
|
||||
icv = mtfv[gs+(nn)]; \
|
||||
cost01 += s->len_pack[icv][0]; \
|
||||
cost23 += s->len_pack[icv][1]; \
|
||||
cost45 += s->len_pack[icv][2]; \
|
||||
|
||||
BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4);
|
||||
BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9);
|
||||
BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14);
|
||||
BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19);
|
||||
BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24);
|
||||
BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29);
|
||||
BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34);
|
||||
BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39);
|
||||
BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44);
|
||||
BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49);
|
||||
|
||||
# undef BZ_ITER
|
||||
|
||||
cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16;
|
||||
cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16;
|
||||
cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16;
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++) {
|
||||
UInt16 icv = mtfv[i];
|
||||
for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];
|
||||
}
|
||||
}
|
||||
|
||||
/*--
|
||||
Find the coding table which is best for this group,
|
||||
and record its identity in the selector table.
|
||||
--*/
|
||||
bc = 999999999; bt = -1;
|
||||
for (t = 0; t < nGroups; t++)
|
||||
if (cost[t] < bc) { bc = cost[t]; bt = t; };
|
||||
totc += bc;
|
||||
fave[bt]++;
|
||||
s->selector[nSelectors] = bt;
|
||||
nSelectors++;
|
||||
|
||||
/*--
|
||||
Increment the symbol frequencies for the selected table.
|
||||
--*/
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
|
||||
# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++
|
||||
|
||||
BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4);
|
||||
BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9);
|
||||
BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14);
|
||||
BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19);
|
||||
BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24);
|
||||
BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29);
|
||||
BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34);
|
||||
BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39);
|
||||
BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44);
|
||||
BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49);
|
||||
|
||||
# undef BZ_ITUR
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++)
|
||||
s->rfreq[bt][ mtfv[i] ]++;
|
||||
}
|
||||
|
||||
gs = ge+1;
|
||||
}
|
||||
if (s->verbosity >= 3) {
|
||||
VPrintf2 ( " pass %d: size is %d, grp uses are ",
|
||||
iter+1, totc/8 );
|
||||
for (t = 0; t < nGroups; t++)
|
||||
VPrintf1 ( "%d ", fave[t] );
|
||||
VPrintf0 ( "\n" );
|
||||
}
|
||||
|
||||
/*--
|
||||
Recompute the tables based on the accumulated frequencies.
|
||||
--*/
|
||||
/* maxLen was changed from 20 to 17 in bzip2-1.0.3. See
|
||||
comment in huffman.c for details. */
|
||||
for (t = 0; t < nGroups; t++)
|
||||
BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
|
||||
alphaSize, 17 /*20*/ );
|
||||
}
|
||||
|
||||
|
||||
AssertH( nGroups < 8, 3002 );
|
||||
AssertH( nSelectors < 32768 &&
|
||||
nSelectors <= BZ_MAX_SELECTORS,
|
||||
3003 );
|
||||
|
||||
|
||||
/*--- Compute MTF values for the selectors. ---*/
|
||||
{
|
||||
UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp;
|
||||
for (i = 0; i < nGroups; i++) pos[i] = i;
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
ll_i = s->selector[i];
|
||||
j = 0;
|
||||
tmp = pos[j];
|
||||
while ( ll_i != tmp ) {
|
||||
j++;
|
||||
tmp2 = tmp;
|
||||
tmp = pos[j];
|
||||
pos[j] = tmp2;
|
||||
};
|
||||
pos[0] = tmp;
|
||||
s->selectorMtf[i] = j;
|
||||
}
|
||||
};
|
||||
|
||||
/*--- Assign actual codes for the tables. --*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
minLen = 32;
|
||||
maxLen = 0;
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
|
||||
if (s->len[t][i] < minLen) minLen = s->len[t][i];
|
||||
}
|
||||
AssertH ( !(maxLen > 17 /*20*/ ), 3004 );
|
||||
AssertH ( !(minLen < 1), 3005 );
|
||||
BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
|
||||
minLen, maxLen, alphaSize );
|
||||
}
|
||||
|
||||
/*--- Transmit the mapping table. ---*/
|
||||
{
|
||||
Bool inUse16[16];
|
||||
for (i = 0; i < 16; i++) {
|
||||
inUse16[i] = False;
|
||||
for (j = 0; j < 16; j++)
|
||||
if (s->inUse[i * 16 + j]) inUse16[i] = True;
|
||||
}
|
||||
|
||||
nBytes = s->numZ;
|
||||
for (i = 0; i < 16; i++)
|
||||
if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);
|
||||
|
||||
for (i = 0; i < 16; i++)
|
||||
if (inUse16[i])
|
||||
for (j = 0; j < 16; j++) {
|
||||
if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes );
|
||||
}
|
||||
|
||||
/*--- Now the selectors. ---*/
|
||||
nBytes = s->numZ;
|
||||
bsW ( s, 3, nGroups );
|
||||
bsW ( s, 15, nSelectors );
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);
|
||||
bsW(s,1,0);
|
||||
}
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( "selectors %d, ", s->numZ-nBytes );
|
||||
|
||||
/*--- Now the coding tables. ---*/
|
||||
nBytes = s->numZ;
|
||||
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
Int32 curr = s->len[t][0];
|
||||
bsW ( s, 5, curr );
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ };
|
||||
while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ };
|
||||
bsW ( s, 1, 0 );
|
||||
}
|
||||
}
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1 ( "code lengths %d, ", s->numZ-nBytes );
|
||||
|
||||
/*--- And finally, the block data proper ---*/
|
||||
nBytes = s->numZ;
|
||||
selCtr = 0;
|
||||
gs = 0;
|
||||
while (True) {
|
||||
if (gs >= s->nMTF) break;
|
||||
ge = gs + BZ_G_SIZE - 1;
|
||||
if (ge >= s->nMTF) ge = s->nMTF-1;
|
||||
AssertH ( s->selector[selCtr] < nGroups, 3006 );
|
||||
|
||||
if (nGroups == 6 && 50 == ge-gs+1) {
|
||||
/*--- fast track the common case ---*/
|
||||
UInt16 mtfv_i;
|
||||
UChar* s_len_sel_selCtr
|
||||
= &(s->len[s->selector[selCtr]][0]);
|
||||
Int32* s_code_sel_selCtr
|
||||
= &(s->code[s->selector[selCtr]][0]);
|
||||
|
||||
# define BZ_ITAH(nn) \
|
||||
mtfv_i = mtfv[gs+(nn)]; \
|
||||
bsW ( s, \
|
||||
s_len_sel_selCtr[mtfv_i], \
|
||||
s_code_sel_selCtr[mtfv_i] )
|
||||
|
||||
BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4);
|
||||
BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9);
|
||||
BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14);
|
||||
BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19);
|
||||
BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24);
|
||||
BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29);
|
||||
BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34);
|
||||
BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39);
|
||||
BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44);
|
||||
BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49);
|
||||
|
||||
# undef BZ_ITAH
|
||||
|
||||
} else {
|
||||
/*--- slow version which correctly handles all situations ---*/
|
||||
for (i = gs; i <= ge; i++) {
|
||||
bsW ( s,
|
||||
s->len [s->selector[selCtr]] [mtfv[i]],
|
||||
s->code [s->selector[selCtr]] [mtfv[i]] );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
gs = ge+1;
|
||||
selCtr++;
|
||||
}
|
||||
AssertH( selCtr == nSelectors, 3007 );
|
||||
|
||||
if (s->verbosity >= 3)
|
||||
VPrintf1( "codes %d\n", s->numZ-nBytes );
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_compressBlock ( EState* s, Bool is_last_block )
|
||||
{
|
||||
if (s->nblock > 0) {
|
||||
|
||||
BZ_FINALISE_CRC ( s->blockCRC );
|
||||
s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31);
|
||||
s->combinedCRC ^= s->blockCRC;
|
||||
if (s->blockNo > 1) s->numZ = 0;
|
||||
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf4( " block %d: crc = 0x%08x, "
|
||||
"combined CRC = 0x%08x, size = %d\n",
|
||||
s->blockNo, s->blockCRC, s->combinedCRC, s->nblock );
|
||||
|
||||
BZ2_blockSort ( s );
|
||||
}
|
||||
|
||||
s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]);
|
||||
|
||||
/*-- If this is the first block, create the stream header. --*/
|
||||
if (s->blockNo == 1) {
|
||||
BZ2_bsInitWrite ( s );
|
||||
bsPutUChar ( s, BZ_HDR_B );
|
||||
bsPutUChar ( s, BZ_HDR_Z );
|
||||
bsPutUChar ( s, BZ_HDR_h );
|
||||
bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) );
|
||||
}
|
||||
|
||||
if (s->nblock > 0) {
|
||||
|
||||
bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 );
|
||||
bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 );
|
||||
bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 );
|
||||
|
||||
/*-- Now the block's CRC, so it is in a known place. --*/
|
||||
bsPutUInt32 ( s, s->blockCRC );
|
||||
|
||||
/*--
|
||||
Now a single bit indicating (non-)randomisation.
|
||||
As of version 0.9.5, we use a better sorting algorithm
|
||||
which makes randomisation unnecessary. So always set
|
||||
the randomised bit to 'no'. Of course, the decoder
|
||||
still needs to be able to handle randomised blocks
|
||||
so as to maintain backwards compatibility with
|
||||
older versions of bzip2.
|
||||
--*/
|
||||
bsW(s,1,0);
|
||||
|
||||
bsW ( s, 24, s->origPtr );
|
||||
generateMTFValues ( s );
|
||||
sendMTFValues ( s );
|
||||
}
|
||||
|
||||
|
||||
/*-- If this is the last block, add the stream trailer. --*/
|
||||
if (is_last_block) {
|
||||
|
||||
bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 );
|
||||
bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 );
|
||||
bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 );
|
||||
bsPutUInt32 ( s, s->combinedCRC );
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC );
|
||||
bsFinishWrite ( s );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end compress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -0,0 +1,652 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Decompression machinery ---*/
|
||||
/*--- decompress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
static
|
||||
void makeMaps_d ( DState* s )
|
||||
{
|
||||
Int32 i;
|
||||
s->nInUse = 0;
|
||||
for (i = 0; i < 256; i++)
|
||||
if (s->inUse[i]) {
|
||||
s->seqToUnseq[s->nInUse] = i;
|
||||
s->nInUse++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define RETURN(rrr) \
|
||||
{ retVal = rrr; goto save_state_and_return; };
|
||||
|
||||
#define GET_BITS(lll,vvv,nnn) \
|
||||
case lll: s->state = lll; \
|
||||
while (True) { \
|
||||
if (s->bsLive >= nnn) { \
|
||||
UInt32 v; \
|
||||
v = (s->bsBuff >> \
|
||||
(s->bsLive-nnn)) & ((1 << nnn)-1); \
|
||||
s->bsLive -= nnn; \
|
||||
vvv = v; \
|
||||
break; \
|
||||
} \
|
||||
if (s->strm->avail_in == 0) RETURN(BZ_OK); \
|
||||
s->bsBuff \
|
||||
= (s->bsBuff << 8) | \
|
||||
((UInt32) \
|
||||
(*((UChar*)(s->strm->next_in)))); \
|
||||
s->bsLive += 8; \
|
||||
s->strm->next_in++; \
|
||||
s->strm->avail_in--; \
|
||||
s->strm->total_in_lo32++; \
|
||||
if (s->strm->total_in_lo32 == 0) \
|
||||
s->strm->total_in_hi32++; \
|
||||
}
|
||||
|
||||
#define GET_UCHAR(lll,uuu) \
|
||||
GET_BITS(lll,uuu,8)
|
||||
|
||||
#define GET_BIT(lll,uuu) \
|
||||
GET_BITS(lll,uuu,1)
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define GET_MTF_VAL(label1,label2,lval) \
|
||||
{ \
|
||||
if (groupPos == 0) { \
|
||||
groupNo++; \
|
||||
if (groupNo >= nSelectors) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
groupPos = BZ_G_SIZE; \
|
||||
gSel = s->selector[groupNo]; \
|
||||
gMinlen = s->minLens[gSel]; \
|
||||
gLimit = &(s->limit[gSel][0]); \
|
||||
gPerm = &(s->perm[gSel][0]); \
|
||||
gBase = &(s->base[gSel][0]); \
|
||||
} \
|
||||
groupPos--; \
|
||||
zn = gMinlen; \
|
||||
GET_BITS(label1, zvec, zn); \
|
||||
while (1) { \
|
||||
if (zn > 20 /* the longest code */) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
if (zvec <= gLimit[zn]) break; \
|
||||
zn++; \
|
||||
GET_BIT(label2, zj); \
|
||||
zvec = (zvec << 1) | zj; \
|
||||
}; \
|
||||
if (zvec - gBase[zn] < 0 \
|
||||
|| zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \
|
||||
RETURN(BZ_DATA_ERROR); \
|
||||
lval = gPerm[zvec - gBase[zn]]; \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
Int32 BZ2_decompress ( DState* s )
|
||||
{
|
||||
UChar uc;
|
||||
Int32 retVal;
|
||||
Int32 minLen, maxLen;
|
||||
bz_stream* strm = s->strm;
|
||||
|
||||
/* stuff that needs to be saved/restored */
|
||||
Int32 i;
|
||||
Int32 j;
|
||||
Int32 t;
|
||||
Int32 alphaSize;
|
||||
Int32 nGroups;
|
||||
Int32 nSelectors;
|
||||
Int32 EOB;
|
||||
Int32 groupNo;
|
||||
Int32 groupPos;
|
||||
Int32 nextSym;
|
||||
Int32 nblockMAX;
|
||||
Int32 nblock;
|
||||
Int32 es;
|
||||
Int32 N;
|
||||
Int32 curr;
|
||||
Int32 zt;
|
||||
Int32 zn;
|
||||
Int32 zvec;
|
||||
Int32 zj;
|
||||
Int32 gSel;
|
||||
Int32 gMinlen;
|
||||
Int32* gLimit;
|
||||
Int32* gBase;
|
||||
Int32* gPerm;
|
||||
|
||||
if (s->state == BZ_X_MAGIC_1) {
|
||||
/*initialise the save area*/
|
||||
s->save_i = 0;
|
||||
s->save_j = 0;
|
||||
s->save_t = 0;
|
||||
s->save_alphaSize = 0;
|
||||
s->save_nGroups = 0;
|
||||
s->save_nSelectors = 0;
|
||||
s->save_EOB = 0;
|
||||
s->save_groupNo = 0;
|
||||
s->save_groupPos = 0;
|
||||
s->save_nextSym = 0;
|
||||
s->save_nblockMAX = 0;
|
||||
s->save_nblock = 0;
|
||||
s->save_es = 0;
|
||||
s->save_N = 0;
|
||||
s->save_curr = 0;
|
||||
s->save_zt = 0;
|
||||
s->save_zn = 0;
|
||||
s->save_zvec = 0;
|
||||
s->save_zj = 0;
|
||||
s->save_gSel = 0;
|
||||
s->save_gMinlen = 0;
|
||||
s->save_gLimit = NULL;
|
||||
s->save_gBase = NULL;
|
||||
s->save_gPerm = NULL;
|
||||
}
|
||||
|
||||
/*restore from the save area*/
|
||||
i = s->save_i;
|
||||
j = s->save_j;
|
||||
t = s->save_t;
|
||||
alphaSize = s->save_alphaSize;
|
||||
nGroups = s->save_nGroups;
|
||||
nSelectors = s->save_nSelectors;
|
||||
EOB = s->save_EOB;
|
||||
groupNo = s->save_groupNo;
|
||||
groupPos = s->save_groupPos;
|
||||
nextSym = s->save_nextSym;
|
||||
nblockMAX = s->save_nblockMAX;
|
||||
nblock = s->save_nblock;
|
||||
es = s->save_es;
|
||||
N = s->save_N;
|
||||
curr = s->save_curr;
|
||||
zt = s->save_zt;
|
||||
zn = s->save_zn;
|
||||
zvec = s->save_zvec;
|
||||
zj = s->save_zj;
|
||||
gSel = s->save_gSel;
|
||||
gMinlen = s->save_gMinlen;
|
||||
gLimit = s->save_gLimit;
|
||||
gBase = s->save_gBase;
|
||||
gPerm = s->save_gPerm;
|
||||
|
||||
retVal = BZ_OK;
|
||||
|
||||
switch (s->state) {
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_1, uc);
|
||||
if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_2, uc);
|
||||
if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_UCHAR(BZ_X_MAGIC_3, uc)
|
||||
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
|
||||
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
|
||||
if (s->blockSize100k < (BZ_HDR_0 + 1) ||
|
||||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
|
||||
s->blockSize100k -= BZ_HDR_0;
|
||||
|
||||
if (s->smallDecompress) {
|
||||
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
|
||||
s->ll4 = BZALLOC(
|
||||
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
|
||||
);
|
||||
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
|
||||
} else {
|
||||
s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );
|
||||
if (s->tt == NULL) RETURN(BZ_MEM_ERROR);
|
||||
}
|
||||
|
||||
GET_UCHAR(BZ_X_BLKHDR_1, uc);
|
||||
|
||||
if (uc == 0x17) goto endhdr_2;
|
||||
if (uc != 0x31) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_2, uc);
|
||||
if (uc != 0x41) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_3, uc);
|
||||
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_4, uc);
|
||||
if (uc != 0x26) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_5, uc);
|
||||
if (uc != 0x53) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_BLKHDR_6, uc);
|
||||
if (uc != 0x59) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
s->currBlockNo++;
|
||||
if (s->verbosity >= 2)
|
||||
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
|
||||
|
||||
s->storedBlockCRC = 0;
|
||||
GET_UCHAR(BZ_X_BCRC_1, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_2, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_3, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_BCRC_4, uc);
|
||||
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
|
||||
|
||||
GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);
|
||||
|
||||
s->origPtr = 0;
|
||||
GET_UCHAR(BZ_X_ORIGPTR_1, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
GET_UCHAR(BZ_X_ORIGPTR_2, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
GET_UCHAR(BZ_X_ORIGPTR_3, uc);
|
||||
s->origPtr = (s->origPtr << 8) | ((Int32)uc);
|
||||
|
||||
if (s->origPtr < 0)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
if (s->origPtr > 10 + 100000*s->blockSize100k)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*--- Receive the mapping table ---*/
|
||||
for (i = 0; i < 16; i++) {
|
||||
GET_BIT(BZ_X_MAPPING_1, uc);
|
||||
if (uc == 1)
|
||||
s->inUse16[i] = True; else
|
||||
s->inUse16[i] = False;
|
||||
}
|
||||
|
||||
for (i = 0; i < 256; i++) s->inUse[i] = False;
|
||||
|
||||
for (i = 0; i < 16; i++)
|
||||
if (s->inUse16[i])
|
||||
for (j = 0; j < 16; j++) {
|
||||
GET_BIT(BZ_X_MAPPING_2, uc);
|
||||
if (uc == 1) s->inUse[i * 16 + j] = True;
|
||||
}
|
||||
makeMaps_d ( s );
|
||||
if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);
|
||||
alphaSize = s->nInUse+2;
|
||||
|
||||
/*--- Now the selectors ---*/
|
||||
GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);
|
||||
if (nGroups < 2 || nGroups > BZ_N_GROUPS) RETURN(BZ_DATA_ERROR);
|
||||
GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);
|
||||
if (nSelectors < 1) RETURN(BZ_DATA_ERROR);
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
j = 0;
|
||||
while (True) {
|
||||
GET_BIT(BZ_X_SELECTOR_3, uc);
|
||||
if (uc == 0) break;
|
||||
j++;
|
||||
if (j >= nGroups) RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
/* Having more than BZ_MAX_SELECTORS doesn't make much sense
|
||||
since they will never be used, but some implementations might
|
||||
"round up" the number of selectors, so just ignore those. */
|
||||
if (i < BZ_MAX_SELECTORS)
|
||||
s->selectorMtf[i] = j;
|
||||
}
|
||||
if (nSelectors > BZ_MAX_SELECTORS)
|
||||
nSelectors = BZ_MAX_SELECTORS;
|
||||
|
||||
/*--- Undo the MTF values for the selectors. ---*/
|
||||
{
|
||||
UChar pos[BZ_N_GROUPS], tmp, v;
|
||||
for (v = 0; v < nGroups; v++) pos[v] = v;
|
||||
|
||||
for (i = 0; i < nSelectors; i++) {
|
||||
v = s->selectorMtf[i];
|
||||
tmp = pos[v];
|
||||
while (v > 0) { pos[v] = pos[v-1]; v--; }
|
||||
pos[0] = tmp;
|
||||
s->selector[i] = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
/*--- Now the coding tables ---*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
GET_BITS(BZ_X_CODING_1, curr, 5);
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
while (True) {
|
||||
if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);
|
||||
GET_BIT(BZ_X_CODING_2, uc);
|
||||
if (uc == 0) break;
|
||||
GET_BIT(BZ_X_CODING_3, uc);
|
||||
if (uc == 0) curr++; else curr--;
|
||||
}
|
||||
s->len[t][i] = curr;
|
||||
}
|
||||
}
|
||||
|
||||
/*--- Create the Huffman decoding tables ---*/
|
||||
for (t = 0; t < nGroups; t++) {
|
||||
minLen = 32;
|
||||
maxLen = 0;
|
||||
for (i = 0; i < alphaSize; i++) {
|
||||
if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
|
||||
if (s->len[t][i] < minLen) minLen = s->len[t][i];
|
||||
}
|
||||
BZ2_hbCreateDecodeTables (
|
||||
&(s->limit[t][0]),
|
||||
&(s->base[t][0]),
|
||||
&(s->perm[t][0]),
|
||||
&(s->len[t][0]),
|
||||
minLen, maxLen, alphaSize
|
||||
);
|
||||
s->minLens[t] = minLen;
|
||||
}
|
||||
|
||||
/*--- Now the MTF values ---*/
|
||||
|
||||
EOB = s->nInUse+1;
|
||||
nblockMAX = 100000 * s->blockSize100k;
|
||||
groupNo = -1;
|
||||
groupPos = 0;
|
||||
|
||||
for (i = 0; i <= 255; i++) s->unzftab[i] = 0;
|
||||
|
||||
/*-- MTF init --*/
|
||||
{
|
||||
Int32 ii, jj, kk;
|
||||
kk = MTFA_SIZE-1;
|
||||
for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {
|
||||
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
|
||||
s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);
|
||||
kk--;
|
||||
}
|
||||
s->mtfbase[ii] = kk + 1;
|
||||
}
|
||||
}
|
||||
/*-- end MTF init --*/
|
||||
|
||||
nblock = 0;
|
||||
GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);
|
||||
|
||||
while (True) {
|
||||
|
||||
if (nextSym == EOB) break;
|
||||
|
||||
if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {
|
||||
|
||||
es = -1;
|
||||
N = 1;
|
||||
do {
|
||||
/* Check that N doesn't get too big, so that es doesn't
|
||||
go negative. The maximum value that can be
|
||||
RUNA/RUNB encoded is equal to the block size (post
|
||||
the initial RLE), viz, 900k, so bounding N at 2
|
||||
million should guard against overflow without
|
||||
rejecting any legitimate inputs. */
|
||||
if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);
|
||||
if (nextSym == BZ_RUNA) es = es + (0+1) * N; else
|
||||
if (nextSym == BZ_RUNB) es = es + (1+1) * N;
|
||||
N = N * 2;
|
||||
GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);
|
||||
}
|
||||
while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);
|
||||
|
||||
es++;
|
||||
uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];
|
||||
s->unzftab[uc] += es;
|
||||
|
||||
if (s->smallDecompress)
|
||||
while (es > 0) {
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
s->ll16[nblock] = (UInt16)uc;
|
||||
nblock++;
|
||||
es--;
|
||||
}
|
||||
else
|
||||
while (es > 0) {
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
s->tt[nblock] = (UInt32)uc;
|
||||
nblock++;
|
||||
es--;
|
||||
};
|
||||
|
||||
continue;
|
||||
|
||||
} else {
|
||||
|
||||
if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*-- uc = MTF ( nextSym-1 ) --*/
|
||||
{
|
||||
Int32 ii, jj, kk, pp, lno, off;
|
||||
UInt32 nn;
|
||||
nn = (UInt32)(nextSym - 1);
|
||||
|
||||
if (nn < MTFL_SIZE) {
|
||||
/* avoid general-case expense */
|
||||
pp = s->mtfbase[0];
|
||||
uc = s->mtfa[pp+nn];
|
||||
while (nn > 3) {
|
||||
Int32 z = pp+nn;
|
||||
s->mtfa[(z) ] = s->mtfa[(z)-1];
|
||||
s->mtfa[(z)-1] = s->mtfa[(z)-2];
|
||||
s->mtfa[(z)-2] = s->mtfa[(z)-3];
|
||||
s->mtfa[(z)-3] = s->mtfa[(z)-4];
|
||||
nn -= 4;
|
||||
}
|
||||
while (nn > 0) {
|
||||
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
|
||||
};
|
||||
s->mtfa[pp] = uc;
|
||||
} else {
|
||||
/* general case */
|
||||
lno = nn / MTFL_SIZE;
|
||||
off = nn % MTFL_SIZE;
|
||||
pp = s->mtfbase[lno] + off;
|
||||
uc = s->mtfa[pp];
|
||||
while (pp > s->mtfbase[lno]) {
|
||||
s->mtfa[pp] = s->mtfa[pp-1]; pp--;
|
||||
};
|
||||
s->mtfbase[lno]++;
|
||||
while (lno > 0) {
|
||||
s->mtfbase[lno]--;
|
||||
s->mtfa[s->mtfbase[lno]]
|
||||
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
|
||||
lno--;
|
||||
}
|
||||
s->mtfbase[0]--;
|
||||
s->mtfa[s->mtfbase[0]] = uc;
|
||||
if (s->mtfbase[0] == 0) {
|
||||
kk = MTFA_SIZE-1;
|
||||
for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {
|
||||
for (jj = MTFL_SIZE-1; jj >= 0; jj--) {
|
||||
s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];
|
||||
kk--;
|
||||
}
|
||||
s->mtfbase[ii] = kk + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*-- end uc = MTF ( nextSym-1 ) --*/
|
||||
|
||||
s->unzftab[s->seqToUnseq[uc]]++;
|
||||
if (s->smallDecompress)
|
||||
s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else
|
||||
s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]);
|
||||
nblock++;
|
||||
|
||||
GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/* Now we know what nblock is, we can do a better sanity
|
||||
check on s->origPtr.
|
||||
*/
|
||||
if (s->origPtr < 0 || s->origPtr >= nblock)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
|
||||
/*-- Set up cftab to facilitate generation of T^(-1) --*/
|
||||
/* Check: unzftab entries in range. */
|
||||
for (i = 0; i <= 255; i++) {
|
||||
if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
/* Actually generate cftab. */
|
||||
s->cftab[0] = 0;
|
||||
for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];
|
||||
for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];
|
||||
/* Check: cftab entries in range. */
|
||||
for (i = 0; i <= 256; i++) {
|
||||
if (s->cftab[i] < 0 || s->cftab[i] > nblock) {
|
||||
/* s->cftab[i] can legitimately be == nblock */
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
}
|
||||
/* Check: cftab entries non-descending. */
|
||||
for (i = 1; i <= 256; i++) {
|
||||
if (s->cftab[i-1] > s->cftab[i]) {
|
||||
RETURN(BZ_DATA_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
s->state_out_len = 0;
|
||||
s->state_out_ch = 0;
|
||||
BZ_INITIALISE_CRC ( s->calculatedBlockCRC );
|
||||
s->state = BZ_X_OUTPUT;
|
||||
if (s->verbosity >= 2) VPrintf0 ( "rt+rld" );
|
||||
|
||||
if (s->smallDecompress) {
|
||||
|
||||
/*-- Make a copy of cftab, used in generation of T --*/
|
||||
for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];
|
||||
|
||||
/*-- compute the T vector --*/
|
||||
for (i = 0; i < nblock; i++) {
|
||||
uc = (UChar)(s->ll16[i]);
|
||||
SET_LL(i, s->cftabCopy[uc]);
|
||||
s->cftabCopy[uc]++;
|
||||
}
|
||||
|
||||
/*-- Compute T^(-1) by pointer reversal on T --*/
|
||||
i = s->origPtr;
|
||||
j = GET_LL(i);
|
||||
do {
|
||||
Int32 tmp = GET_LL(j);
|
||||
SET_LL(j, i);
|
||||
i = j;
|
||||
j = tmp;
|
||||
}
|
||||
while (i != s->origPtr);
|
||||
|
||||
s->tPos = s->origPtr;
|
||||
s->nblock_used = 0;
|
||||
if (s->blockRandomised) {
|
||||
BZ_RAND_INIT_MASK;
|
||||
BZ_GET_SMALL(s->k0); s->nblock_used++;
|
||||
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
|
||||
} else {
|
||||
BZ_GET_SMALL(s->k0); s->nblock_used++;
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
/*-- compute the T^(-1) vector --*/
|
||||
for (i = 0; i < nblock; i++) {
|
||||
uc = (UChar)(s->tt[i] & 0xff);
|
||||
s->tt[s->cftab[uc]] |= (i << 8);
|
||||
s->cftab[uc]++;
|
||||
}
|
||||
|
||||
s->tPos = s->tt[s->origPtr] >> 8;
|
||||
s->nblock_used = 0;
|
||||
if (s->blockRandomised) {
|
||||
BZ_RAND_INIT_MASK;
|
||||
BZ_GET_FAST(s->k0); s->nblock_used++;
|
||||
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
|
||||
} else {
|
||||
BZ_GET_FAST(s->k0); s->nblock_used++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
RETURN(BZ_OK);
|
||||
|
||||
|
||||
|
||||
endhdr_2:
|
||||
|
||||
GET_UCHAR(BZ_X_ENDHDR_2, uc);
|
||||
if (uc != 0x72) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_3, uc);
|
||||
if (uc != 0x45) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_4, uc);
|
||||
if (uc != 0x38) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_5, uc);
|
||||
if (uc != 0x50) RETURN(BZ_DATA_ERROR);
|
||||
GET_UCHAR(BZ_X_ENDHDR_6, uc);
|
||||
if (uc != 0x90) RETURN(BZ_DATA_ERROR);
|
||||
|
||||
s->storedCombinedCRC = 0;
|
||||
GET_UCHAR(BZ_X_CCRC_1, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_2, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_3, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
GET_UCHAR(BZ_X_CCRC_4, uc);
|
||||
s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);
|
||||
|
||||
s->state = BZ_X_IDLE;
|
||||
RETURN(BZ_STREAM_END);
|
||||
|
||||
default: AssertH ( False, 4001 );
|
||||
}
|
||||
|
||||
AssertH ( False, 4002 );
|
||||
|
||||
save_state_and_return:
|
||||
|
||||
s->save_i = i;
|
||||
s->save_j = j;
|
||||
s->save_t = t;
|
||||
s->save_alphaSize = alphaSize;
|
||||
s->save_nGroups = nGroups;
|
||||
s->save_nSelectors = nSelectors;
|
||||
s->save_EOB = EOB;
|
||||
s->save_groupNo = groupNo;
|
||||
s->save_groupPos = groupPos;
|
||||
s->save_nextSym = nextSym;
|
||||
s->save_nblockMAX = nblockMAX;
|
||||
s->save_nblock = nblock;
|
||||
s->save_es = es;
|
||||
s->save_N = N;
|
||||
s->save_curr = curr;
|
||||
s->save_zt = zt;
|
||||
s->save_zn = zn;
|
||||
s->save_zvec = zvec;
|
||||
s->save_zj = zj;
|
||||
s->save_gSel = gSel;
|
||||
s->save_gMinlen = gMinlen;
|
||||
s->save_gLimit = gLimit;
|
||||
s->save_gBase = gBase;
|
||||
s->save_gPerm = gPerm;
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end decompress.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,282 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Public header file for the library. ---*/
|
||||
/*--- bzlib.h ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#ifndef _BZLIB_H
|
||||
#define _BZLIB_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define BZ_RUN 0
|
||||
#define BZ_FLUSH 1
|
||||
#define BZ_FINISH 2
|
||||
|
||||
#define BZ_OK 0
|
||||
#define BZ_RUN_OK 1
|
||||
#define BZ_FLUSH_OK 2
|
||||
#define BZ_FINISH_OK 3
|
||||
#define BZ_STREAM_END 4
|
||||
#define BZ_SEQUENCE_ERROR (-1)
|
||||
#define BZ_PARAM_ERROR (-2)
|
||||
#define BZ_MEM_ERROR (-3)
|
||||
#define BZ_DATA_ERROR (-4)
|
||||
#define BZ_DATA_ERROR_MAGIC (-5)
|
||||
#define BZ_IO_ERROR (-6)
|
||||
#define BZ_UNEXPECTED_EOF (-7)
|
||||
#define BZ_OUTBUFF_FULL (-8)
|
||||
#define BZ_CONFIG_ERROR (-9)
|
||||
|
||||
typedef
|
||||
struct {
|
||||
char *next_in;
|
||||
unsigned int avail_in;
|
||||
unsigned int total_in_lo32;
|
||||
unsigned int total_in_hi32;
|
||||
|
||||
char *next_out;
|
||||
unsigned int avail_out;
|
||||
unsigned int total_out_lo32;
|
||||
unsigned int total_out_hi32;
|
||||
|
||||
void *state;
|
||||
|
||||
void *(*bzalloc)(void *,int,int);
|
||||
void (*bzfree)(void *,void *);
|
||||
void *opaque;
|
||||
}
|
||||
bz_stream;
|
||||
|
||||
|
||||
#ifndef BZ_IMPORT
|
||||
#define BZ_EXPORT
|
||||
#endif
|
||||
|
||||
#ifndef BZ_NO_STDIO
|
||||
/* Need a definitition for FILE */
|
||||
#include <stdio.h>
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
# include <windows.h>
|
||||
# ifdef small
|
||||
/* windows.h define small to char */
|
||||
# undef small
|
||||
# endif
|
||||
# ifdef BZ_EXPORT
|
||||
# define BZ_API(func) WINAPI func
|
||||
# define BZ_EXTERN extern
|
||||
# else
|
||||
/* import windows dll dynamically */
|
||||
# define BZ_API(func) (WINAPI * func)
|
||||
# define BZ_EXTERN
|
||||
# endif
|
||||
#else
|
||||
# define BZ_API(func) func
|
||||
# define BZ_EXTERN extern
|
||||
#endif
|
||||
|
||||
|
||||
/*-- Core (low-level) library functions --*/
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
|
||||
bz_stream* strm,
|
||||
int blockSize100k,
|
||||
int verbosity,
|
||||
int workFactor
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzCompress) (
|
||||
bz_stream* strm,
|
||||
int action
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
|
||||
bz_stream* strm
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
|
||||
bz_stream *strm,
|
||||
int verbosity,
|
||||
int small
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
|
||||
bz_stream* strm
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
|
||||
bz_stream *strm
|
||||
);
|
||||
|
||||
|
||||
|
||||
/*-- High(er) level library functions --*/
|
||||
|
||||
#ifndef BZ_NO_STDIO
|
||||
#define BZ_MAX_UNUSED 5000
|
||||
|
||||
typedef void BZFILE;
|
||||
|
||||
BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
|
||||
int* bzerror,
|
||||
FILE* f,
|
||||
int verbosity,
|
||||
int small,
|
||||
void* unused,
|
||||
int nUnused
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
|
||||
int* bzerror,
|
||||
BZFILE* b
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
|
||||
int* bzerror,
|
||||
BZFILE* b,
|
||||
void** unused,
|
||||
int* nUnused
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzRead) (
|
||||
int* bzerror,
|
||||
BZFILE* b,
|
||||
void* buf,
|
||||
int len
|
||||
);
|
||||
|
||||
BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
|
||||
int* bzerror,
|
||||
FILE* f,
|
||||
int blockSize100k,
|
||||
int verbosity,
|
||||
int workFactor
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzWrite) (
|
||||
int* bzerror,
|
||||
BZFILE* b,
|
||||
void* buf,
|
||||
int len
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
|
||||
int* bzerror,
|
||||
BZFILE* b,
|
||||
int abandon,
|
||||
unsigned int* nbytes_in,
|
||||
unsigned int* nbytes_out
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
|
||||
int* bzerror,
|
||||
BZFILE* b,
|
||||
int abandon,
|
||||
unsigned int* nbytes_in_lo32,
|
||||
unsigned int* nbytes_in_hi32,
|
||||
unsigned int* nbytes_out_lo32,
|
||||
unsigned int* nbytes_out_hi32
|
||||
);
|
||||
#endif
|
||||
|
||||
|
||||
/*-- Utility functions --*/
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
|
||||
char* dest,
|
||||
unsigned int* destLen,
|
||||
char* source,
|
||||
unsigned int sourceLen,
|
||||
int blockSize100k,
|
||||
int verbosity,
|
||||
int workFactor
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
|
||||
char* dest,
|
||||
unsigned int* destLen,
|
||||
char* source,
|
||||
unsigned int sourceLen,
|
||||
int small,
|
||||
int verbosity
|
||||
);
|
||||
|
||||
|
||||
/*--
|
||||
Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp)
|
||||
to support better zlib compatibility.
|
||||
This code is not _officially_ part of libbzip2 (yet);
|
||||
I haven't tested it, documented it, or considered the
|
||||
threading-safeness of it.
|
||||
If this code breaks, please contact both Yoshioka and me.
|
||||
--*/
|
||||
|
||||
BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) (
|
||||
void
|
||||
);
|
||||
|
||||
#ifndef BZ_NO_STDIO
|
||||
BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) (
|
||||
const char *path,
|
||||
const char *mode
|
||||
);
|
||||
|
||||
BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) (
|
||||
int fd,
|
||||
const char *mode
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzread) (
|
||||
BZFILE* b,
|
||||
void* buf,
|
||||
int len
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzwrite) (
|
||||
BZFILE* b,
|
||||
void* buf,
|
||||
int len
|
||||
);
|
||||
|
||||
BZ_EXTERN int BZ_API(BZ2_bzflush) (
|
||||
BZFILE* b
|
||||
);
|
||||
|
||||
BZ_EXTERN void BZ_API(BZ2_bzclose) (
|
||||
BZFILE* b
|
||||
);
|
||||
|
||||
BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
|
||||
BZFILE *b,
|
||||
int *errnum
|
||||
);
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end bzlib.h ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -0,0 +1,509 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Private header file for the library. ---*/
|
||||
/*--- bzlib_private.h ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#ifndef _BZLIB_PRIVATE_H
|
||||
#define _BZLIB_PRIVATE_H
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifndef BZ_NO_STDIO
|
||||
#include <stdio.h>
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
#endif
|
||||
|
||||
#include "bzlib.h"
|
||||
|
||||
|
||||
|
||||
/*-- General stuff. --*/
|
||||
|
||||
#define BZ_VERSION "1.0.8, 13-Jul-2019"
|
||||
|
||||
typedef char Char;
|
||||
typedef unsigned char Bool;
|
||||
typedef unsigned char UChar;
|
||||
typedef int Int32;
|
||||
typedef unsigned int UInt32;
|
||||
typedef short Int16;
|
||||
typedef unsigned short UInt16;
|
||||
|
||||
#define True ((Bool)1)
|
||||
#define False ((Bool)0)
|
||||
|
||||
#ifndef __GNUC__
|
||||
#define __inline__ /* */
|
||||
#endif
|
||||
|
||||
#ifndef BZ_NO_STDIO
|
||||
|
||||
extern void BZ2_bz__AssertH__fail ( int errcode );
|
||||
#define AssertH(cond,errcode) \
|
||||
{ if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); }
|
||||
|
||||
#if BZ_DEBUG
|
||||
#define AssertD(cond,msg) \
|
||||
{ if (!(cond)) { \
|
||||
fprintf ( stderr, \
|
||||
"\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\
|
||||
exit(1); \
|
||||
}}
|
||||
#else
|
||||
#define AssertD(cond,msg) /* */
|
||||
#endif
|
||||
|
||||
#define VPrintf0(zf) \
|
||||
fprintf(stderr,zf)
|
||||
#define VPrintf1(zf,za1) \
|
||||
fprintf(stderr,zf,za1)
|
||||
#define VPrintf2(zf,za1,za2) \
|
||||
fprintf(stderr,zf,za1,za2)
|
||||
#define VPrintf3(zf,za1,za2,za3) \
|
||||
fprintf(stderr,zf,za1,za2,za3)
|
||||
#define VPrintf4(zf,za1,za2,za3,za4) \
|
||||
fprintf(stderr,zf,za1,za2,za3,za4)
|
||||
#define VPrintf5(zf,za1,za2,za3,za4,za5) \
|
||||
fprintf(stderr,zf,za1,za2,za3,za4,za5)
|
||||
|
||||
#else
|
||||
|
||||
extern void bz_internal_error ( int errcode );
|
||||
#define AssertH(cond,errcode) \
|
||||
{ if (!(cond)) bz_internal_error ( errcode ); }
|
||||
#define AssertD(cond,msg) do { } while (0)
|
||||
#define VPrintf0(zf) do { } while (0)
|
||||
#define VPrintf1(zf,za1) do { } while (0)
|
||||
#define VPrintf2(zf,za1,za2) do { } while (0)
|
||||
#define VPrintf3(zf,za1,za2,za3) do { } while (0)
|
||||
#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0)
|
||||
#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0)
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1)
|
||||
#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp))
|
||||
|
||||
|
||||
/*-- Header bytes. --*/
|
||||
|
||||
#define BZ_HDR_B 0x42 /* 'B' */
|
||||
#define BZ_HDR_Z 0x5a /* 'Z' */
|
||||
#define BZ_HDR_h 0x68 /* 'h' */
|
||||
#define BZ_HDR_0 0x30 /* '0' */
|
||||
|
||||
/*-- Constants for the back end. --*/
|
||||
|
||||
#define BZ_MAX_ALPHA_SIZE 258
|
||||
#define BZ_MAX_CODE_LEN 23
|
||||
|
||||
#define BZ_RUNA 0
|
||||
#define BZ_RUNB 1
|
||||
|
||||
#define BZ_N_GROUPS 6
|
||||
#define BZ_G_SIZE 50
|
||||
#define BZ_N_ITERS 4
|
||||
|
||||
#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE))
|
||||
|
||||
|
||||
|
||||
/*-- Stuff for randomising repetitive blocks. --*/
|
||||
|
||||
extern Int32 BZ2_rNums[512];
|
||||
|
||||
#define BZ_RAND_DECLS \
|
||||
Int32 rNToGo; \
|
||||
Int32 rTPos \
|
||||
|
||||
#define BZ_RAND_INIT_MASK \
|
||||
s->rNToGo = 0; \
|
||||
s->rTPos = 0 \
|
||||
|
||||
#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0)
|
||||
|
||||
#define BZ_RAND_UPD_MASK \
|
||||
if (s->rNToGo == 0) { \
|
||||
s->rNToGo = BZ2_rNums[s->rTPos]; \
|
||||
s->rTPos++; \
|
||||
if (s->rTPos == 512) s->rTPos = 0; \
|
||||
} \
|
||||
s->rNToGo--;
|
||||
|
||||
|
||||
|
||||
/*-- Stuff for doing CRCs. --*/
|
||||
|
||||
extern UInt32 BZ2_crc32Table[256];
|
||||
|
||||
#define BZ_INITIALISE_CRC(crcVar) \
|
||||
{ \
|
||||
crcVar = 0xffffffffL; \
|
||||
}
|
||||
|
||||
#define BZ_FINALISE_CRC(crcVar) \
|
||||
{ \
|
||||
crcVar = ~(crcVar); \
|
||||
}
|
||||
|
||||
#define BZ_UPDATE_CRC(crcVar,cha) \
|
||||
{ \
|
||||
crcVar = (crcVar << 8) ^ \
|
||||
BZ2_crc32Table[(crcVar >> 24) ^ \
|
||||
((UChar)cha)]; \
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*-- States and modes for compression. --*/
|
||||
|
||||
#define BZ_M_IDLE 1
|
||||
#define BZ_M_RUNNING 2
|
||||
#define BZ_M_FLUSHING 3
|
||||
#define BZ_M_FINISHING 4
|
||||
|
||||
#define BZ_S_OUTPUT 1
|
||||
#define BZ_S_INPUT 2
|
||||
|
||||
#define BZ_N_RADIX 2
|
||||
#define BZ_N_QSORT 12
|
||||
#define BZ_N_SHELL 18
|
||||
#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2)
|
||||
|
||||
|
||||
|
||||
|
||||
/*-- Structure holding all the compression-side stuff. --*/
|
||||
|
||||
typedef
|
||||
struct {
|
||||
/* pointer back to the struct bz_stream */
|
||||
bz_stream* strm;
|
||||
|
||||
/* mode this stream is in, and whether inputting */
|
||||
/* or outputting data */
|
||||
Int32 mode;
|
||||
Int32 state;
|
||||
|
||||
/* remembers avail_in when flush/finish requested */
|
||||
UInt32 avail_in_expect;
|
||||
|
||||
/* for doing the block sorting */
|
||||
UInt32* arr1;
|
||||
UInt32* arr2;
|
||||
UInt32* ftab;
|
||||
Int32 origPtr;
|
||||
|
||||
/* aliases for arr1 and arr2 */
|
||||
UInt32* ptr;
|
||||
UChar* block;
|
||||
UInt16* mtfv;
|
||||
UChar* zbits;
|
||||
|
||||
/* for deciding when to use the fallback sorting algorithm */
|
||||
Int32 workFactor;
|
||||
|
||||
/* run-length-encoding of the input */
|
||||
UInt32 state_in_ch;
|
||||
Int32 state_in_len;
|
||||
BZ_RAND_DECLS;
|
||||
|
||||
/* input and output limits and current posns */
|
||||
Int32 nblock;
|
||||
Int32 nblockMAX;
|
||||
Int32 numZ;
|
||||
Int32 state_out_pos;
|
||||
|
||||
/* map of bytes used in block */
|
||||
Int32 nInUse;
|
||||
Bool inUse[256];
|
||||
UChar unseqToSeq[256];
|
||||
|
||||
/* the buffer for bit stream creation */
|
||||
UInt32 bsBuff;
|
||||
Int32 bsLive;
|
||||
|
||||
/* block and combined CRCs */
|
||||
UInt32 blockCRC;
|
||||
UInt32 combinedCRC;
|
||||
|
||||
/* misc administratium */
|
||||
Int32 verbosity;
|
||||
Int32 blockNo;
|
||||
Int32 blockSize100k;
|
||||
|
||||
/* stuff for coding the MTF values */
|
||||
Int32 nMTF;
|
||||
Int32 mtfFreq [BZ_MAX_ALPHA_SIZE];
|
||||
UChar selector [BZ_MAX_SELECTORS];
|
||||
UChar selectorMtf[BZ_MAX_SELECTORS];
|
||||
|
||||
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
/* second dimension: only 3 needed; 4 makes index calculations faster */
|
||||
UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4];
|
||||
|
||||
}
|
||||
EState;
|
||||
|
||||
|
||||
|
||||
/*-- externs for compression. --*/
|
||||
|
||||
extern void
|
||||
BZ2_blockSort ( EState* );
|
||||
|
||||
extern void
|
||||
BZ2_compressBlock ( EState*, Bool );
|
||||
|
||||
extern void
|
||||
BZ2_bsInitWrite ( EState* );
|
||||
|
||||
extern void
|
||||
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
|
||||
|
||||
extern void
|
||||
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
|
||||
|
||||
|
||||
|
||||
/*-- states for decompression. --*/
|
||||
|
||||
#define BZ_X_IDLE 1
|
||||
#define BZ_X_OUTPUT 2
|
||||
|
||||
#define BZ_X_MAGIC_1 10
|
||||
#define BZ_X_MAGIC_2 11
|
||||
#define BZ_X_MAGIC_3 12
|
||||
#define BZ_X_MAGIC_4 13
|
||||
#define BZ_X_BLKHDR_1 14
|
||||
#define BZ_X_BLKHDR_2 15
|
||||
#define BZ_X_BLKHDR_3 16
|
||||
#define BZ_X_BLKHDR_4 17
|
||||
#define BZ_X_BLKHDR_5 18
|
||||
#define BZ_X_BLKHDR_6 19
|
||||
#define BZ_X_BCRC_1 20
|
||||
#define BZ_X_BCRC_2 21
|
||||
#define BZ_X_BCRC_3 22
|
||||
#define BZ_X_BCRC_4 23
|
||||
#define BZ_X_RANDBIT 24
|
||||
#define BZ_X_ORIGPTR_1 25
|
||||
#define BZ_X_ORIGPTR_2 26
|
||||
#define BZ_X_ORIGPTR_3 27
|
||||
#define BZ_X_MAPPING_1 28
|
||||
#define BZ_X_MAPPING_2 29
|
||||
#define BZ_X_SELECTOR_1 30
|
||||
#define BZ_X_SELECTOR_2 31
|
||||
#define BZ_X_SELECTOR_3 32
|
||||
#define BZ_X_CODING_1 33
|
||||
#define BZ_X_CODING_2 34
|
||||
#define BZ_X_CODING_3 35
|
||||
#define BZ_X_MTF_1 36
|
||||
#define BZ_X_MTF_2 37
|
||||
#define BZ_X_MTF_3 38
|
||||
#define BZ_X_MTF_4 39
|
||||
#define BZ_X_MTF_5 40
|
||||
#define BZ_X_MTF_6 41
|
||||
#define BZ_X_ENDHDR_2 42
|
||||
#define BZ_X_ENDHDR_3 43
|
||||
#define BZ_X_ENDHDR_4 44
|
||||
#define BZ_X_ENDHDR_5 45
|
||||
#define BZ_X_ENDHDR_6 46
|
||||
#define BZ_X_CCRC_1 47
|
||||
#define BZ_X_CCRC_2 48
|
||||
#define BZ_X_CCRC_3 49
|
||||
#define BZ_X_CCRC_4 50
|
||||
|
||||
|
||||
|
||||
/*-- Constants for the fast MTF decoder. --*/
|
||||
|
||||
#define MTFA_SIZE 4096
|
||||
#define MTFL_SIZE 16
|
||||
|
||||
|
||||
|
||||
/*-- Structure holding all the decompression-side stuff. --*/
|
||||
|
||||
typedef
|
||||
struct {
|
||||
/* pointer back to the struct bz_stream */
|
||||
bz_stream* strm;
|
||||
|
||||
/* state indicator for this stream */
|
||||
Int32 state;
|
||||
|
||||
/* for doing the final run-length decoding */
|
||||
UChar state_out_ch;
|
||||
Int32 state_out_len;
|
||||
Bool blockRandomised;
|
||||
BZ_RAND_DECLS;
|
||||
|
||||
/* the buffer for bit stream reading */
|
||||
UInt32 bsBuff;
|
||||
Int32 bsLive;
|
||||
|
||||
/* misc administratium */
|
||||
Int32 blockSize100k;
|
||||
Bool smallDecompress;
|
||||
Int32 currBlockNo;
|
||||
Int32 verbosity;
|
||||
|
||||
/* for undoing the Burrows-Wheeler transform */
|
||||
Int32 origPtr;
|
||||
UInt32 tPos;
|
||||
Int32 k0;
|
||||
Int32 unzftab[256];
|
||||
Int32 nblock_used;
|
||||
Int32 cftab[257];
|
||||
Int32 cftabCopy[257];
|
||||
|
||||
/* for undoing the Burrows-Wheeler transform (FAST) */
|
||||
UInt32 *tt;
|
||||
|
||||
/* for undoing the Burrows-Wheeler transform (SMALL) */
|
||||
UInt16 *ll16;
|
||||
UChar *ll4;
|
||||
|
||||
/* stored and calculated CRCs */
|
||||
UInt32 storedBlockCRC;
|
||||
UInt32 storedCombinedCRC;
|
||||
UInt32 calculatedBlockCRC;
|
||||
UInt32 calculatedCombinedCRC;
|
||||
|
||||
/* map of bytes used in block */
|
||||
Int32 nInUse;
|
||||
Bool inUse[256];
|
||||
Bool inUse16[16];
|
||||
UChar seqToUnseq[256];
|
||||
|
||||
/* for decoding the MTF values */
|
||||
UChar mtfa [MTFA_SIZE];
|
||||
Int32 mtfbase[256 / MTFL_SIZE];
|
||||
UChar selector [BZ_MAX_SELECTORS];
|
||||
UChar selectorMtf[BZ_MAX_SELECTORS];
|
||||
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
|
||||
Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||
Int32 minLens[BZ_N_GROUPS];
|
||||
|
||||
/* save area for scalars in the main decompress code */
|
||||
Int32 save_i;
|
||||
Int32 save_j;
|
||||
Int32 save_t;
|
||||
Int32 save_alphaSize;
|
||||
Int32 save_nGroups;
|
||||
Int32 save_nSelectors;
|
||||
Int32 save_EOB;
|
||||
Int32 save_groupNo;
|
||||
Int32 save_groupPos;
|
||||
Int32 save_nextSym;
|
||||
Int32 save_nblockMAX;
|
||||
Int32 save_nblock;
|
||||
Int32 save_es;
|
||||
Int32 save_N;
|
||||
Int32 save_curr;
|
||||
Int32 save_zt;
|
||||
Int32 save_zn;
|
||||
Int32 save_zvec;
|
||||
Int32 save_zj;
|
||||
Int32 save_gSel;
|
||||
Int32 save_gMinlen;
|
||||
Int32* save_gLimit;
|
||||
Int32* save_gBase;
|
||||
Int32* save_gPerm;
|
||||
|
||||
}
|
||||
DState;
|
||||
|
||||
|
||||
|
||||
/*-- Macros for decompression. --*/
|
||||
|
||||
#define BZ_GET_FAST(cccc) \
|
||||
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
|
||||
s->tPos = s->tt[s->tPos]; \
|
||||
cccc = (UChar)(s->tPos & 0xff); \
|
||||
s->tPos >>= 8;
|
||||
|
||||
#define BZ_GET_FAST_C(cccc) \
|
||||
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||
if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \
|
||||
c_tPos = c_tt[c_tPos]; \
|
||||
cccc = (UChar)(c_tPos & 0xff); \
|
||||
c_tPos >>= 8;
|
||||
|
||||
#define SET_LL4(i,n) \
|
||||
{ if (((i) & 0x1) == 0) \
|
||||
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \
|
||||
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \
|
||||
}
|
||||
|
||||
#define GET_LL4(i) \
|
||||
((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF)
|
||||
|
||||
#define SET_LL(i,n) \
|
||||
{ s->ll16[i] = (UInt16)(n & 0x0000ffff); \
|
||||
SET_LL4(i, n >> 16); \
|
||||
}
|
||||
|
||||
#define GET_LL(i) \
|
||||
(((UInt32)s->ll16[i]) | (GET_LL4(i) << 16))
|
||||
|
||||
#define BZ_GET_SMALL(cccc) \
|
||||
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
|
||||
cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \
|
||||
s->tPos = GET_LL(s->tPos);
|
||||
|
||||
|
||||
/*-- externs for decompression. --*/
|
||||
|
||||
extern Int32
|
||||
BZ2_indexIntoF ( Int32, Int32* );
|
||||
|
||||
extern Int32
|
||||
BZ2_decompress ( DState* );
|
||||
|
||||
extern void
|
||||
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
|
||||
Int32, Int32, Int32 );
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/
|
||||
|
||||
#ifdef BZ_NO_STDIO
|
||||
#ifndef NULL
|
||||
#define NULL 0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end bzlib_private.h ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -0,0 +1,104 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Table for doing CRCs ---*/
|
||||
/*--- crctable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
/*--
|
||||
I think this is an implementation of the AUTODIN-II,
|
||||
Ethernet & FDDI 32-bit CRC standard. Vaguely derived
|
||||
from code by Rob Warnock, in Section 51 of the
|
||||
comp.compression FAQ.
|
||||
--*/
|
||||
|
||||
UInt32 BZ2_crc32Table[256] = {
|
||||
|
||||
/*-- Ugly, innit? --*/
|
||||
|
||||
0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L,
|
||||
0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L,
|
||||
0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L,
|
||||
0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL,
|
||||
0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L,
|
||||
0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L,
|
||||
0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L,
|
||||
0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL,
|
||||
0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L,
|
||||
0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L,
|
||||
0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L,
|
||||
0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL,
|
||||
0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L,
|
||||
0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L,
|
||||
0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L,
|
||||
0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL,
|
||||
0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL,
|
||||
0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L,
|
||||
0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L,
|
||||
0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL,
|
||||
0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL,
|
||||
0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L,
|
||||
0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L,
|
||||
0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL,
|
||||
0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL,
|
||||
0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L,
|
||||
0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L,
|
||||
0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL,
|
||||
0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL,
|
||||
0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L,
|
||||
0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L,
|
||||
0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL,
|
||||
0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L,
|
||||
0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL,
|
||||
0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL,
|
||||
0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L,
|
||||
0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L,
|
||||
0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL,
|
||||
0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL,
|
||||
0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L,
|
||||
0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L,
|
||||
0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL,
|
||||
0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL,
|
||||
0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L,
|
||||
0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L,
|
||||
0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL,
|
||||
0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL,
|
||||
0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L,
|
||||
0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L,
|
||||
0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL,
|
||||
0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L,
|
||||
0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L,
|
||||
0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L,
|
||||
0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL,
|
||||
0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L,
|
||||
0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L,
|
||||
0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L,
|
||||
0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL,
|
||||
0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L,
|
||||
0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L,
|
||||
0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L,
|
||||
0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL,
|
||||
0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L,
|
||||
0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L
|
||||
};
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end crctable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -0,0 +1,205 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Huffman coding low-level stuff ---*/
|
||||
/*--- huffman.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
#define WEIGHTOF(zz0) ((zz0) & 0xffffff00)
|
||||
#define DEPTHOF(zz1) ((zz1) & 0x000000ff)
|
||||
#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))
|
||||
|
||||
#define ADDWEIGHTS(zw1,zw2) \
|
||||
(WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \
|
||||
(1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))
|
||||
|
||||
#define UPHEAP(z) \
|
||||
{ \
|
||||
Int32 zz, tmp; \
|
||||
zz = z; tmp = heap[zz]; \
|
||||
while (weight[tmp] < weight[heap[zz >> 1]]) { \
|
||||
heap[zz] = heap[zz >> 1]; \
|
||||
zz >>= 1; \
|
||||
} \
|
||||
heap[zz] = tmp; \
|
||||
}
|
||||
|
||||
#define DOWNHEAP(z) \
|
||||
{ \
|
||||
Int32 zz, yy, tmp; \
|
||||
zz = z; tmp = heap[zz]; \
|
||||
while (True) { \
|
||||
yy = zz << 1; \
|
||||
if (yy > nHeap) break; \
|
||||
if (yy < nHeap && \
|
||||
weight[heap[yy+1]] < weight[heap[yy]]) \
|
||||
yy++; \
|
||||
if (weight[tmp] < weight[heap[yy]]) break; \
|
||||
heap[zz] = heap[yy]; \
|
||||
zz = yy; \
|
||||
} \
|
||||
heap[zz] = tmp; \
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbMakeCodeLengths ( UChar *len,
|
||||
Int32 *freq,
|
||||
Int32 alphaSize,
|
||||
Int32 maxLen )
|
||||
{
|
||||
/*--
|
||||
Nodes and heap entries run from 1. Entry 0
|
||||
for both the heap and nodes is a sentinel.
|
||||
--*/
|
||||
Int32 nNodes, nHeap, n1, n2, i, j, k;
|
||||
Bool tooLong;
|
||||
|
||||
Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ];
|
||||
Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];
|
||||
Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
|
||||
|
||||
for (i = 0; i < alphaSize; i++)
|
||||
weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
|
||||
|
||||
while (True) {
|
||||
|
||||
nNodes = alphaSize;
|
||||
nHeap = 0;
|
||||
|
||||
heap[0] = 0;
|
||||
weight[0] = 0;
|
||||
parent[0] = -2;
|
||||
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
parent[i] = -1;
|
||||
nHeap++;
|
||||
heap[nHeap] = i;
|
||||
UPHEAP(nHeap);
|
||||
}
|
||||
|
||||
AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );
|
||||
|
||||
while (nHeap > 1) {
|
||||
n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
|
||||
n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
|
||||
nNodes++;
|
||||
parent[n1] = parent[n2] = nNodes;
|
||||
weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);
|
||||
parent[nNodes] = -1;
|
||||
nHeap++;
|
||||
heap[nHeap] = nNodes;
|
||||
UPHEAP(nHeap);
|
||||
}
|
||||
|
||||
AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 );
|
||||
|
||||
tooLong = False;
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
j = 0;
|
||||
k = i;
|
||||
while (parent[k] >= 0) { k = parent[k]; j++; }
|
||||
len[i-1] = j;
|
||||
if (j > maxLen) tooLong = True;
|
||||
}
|
||||
|
||||
if (! tooLong) break;
|
||||
|
||||
/* 17 Oct 04: keep-going condition for the following loop used
|
||||
to be 'i < alphaSize', which missed the last element,
|
||||
theoretically leading to the possibility of the compressor
|
||||
looping. However, this count-scaling step is only needed if
|
||||
one of the generated Huffman code words is longer than
|
||||
maxLen, which up to and including version 1.0.2 was 20 bits,
|
||||
which is extremely unlikely. In version 1.0.3 maxLen was
|
||||
changed to 17 bits, which has minimal effect on compression
|
||||
ratio, but does mean this scaling step is used from time to
|
||||
time, enough to verify that it works.
|
||||
|
||||
This means that bzip2-1.0.3 and later will only produce
|
||||
Huffman codes with a maximum length of 17 bits. However, in
|
||||
order to preserve backwards compatibility with bitstreams
|
||||
produced by versions pre-1.0.3, the decompressor must still
|
||||
handle lengths of up to 20. */
|
||||
|
||||
for (i = 1; i <= alphaSize; i++) {
|
||||
j = weight[i] >> 8;
|
||||
j = 1 + (j / 2);
|
||||
weight[i] = j << 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbAssignCodes ( Int32 *code,
|
||||
UChar *length,
|
||||
Int32 minLen,
|
||||
Int32 maxLen,
|
||||
Int32 alphaSize )
|
||||
{
|
||||
Int32 n, vec, i;
|
||||
|
||||
vec = 0;
|
||||
for (n = minLen; n <= maxLen; n++) {
|
||||
for (i = 0; i < alphaSize; i++)
|
||||
if (length[i] == n) { code[i] = vec; vec++; };
|
||||
vec <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*---------------------------------------------------*/
|
||||
void BZ2_hbCreateDecodeTables ( Int32 *limit,
|
||||
Int32 *base,
|
||||
Int32 *perm,
|
||||
UChar *length,
|
||||
Int32 minLen,
|
||||
Int32 maxLen,
|
||||
Int32 alphaSize )
|
||||
{
|
||||
Int32 pp, i, j, vec;
|
||||
|
||||
pp = 0;
|
||||
for (i = minLen; i <= maxLen; i++)
|
||||
for (j = 0; j < alphaSize; j++)
|
||||
if (length[j] == i) { perm[pp] = j; pp++; };
|
||||
|
||||
for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0;
|
||||
for (i = 0; i < alphaSize; i++) base[length[i]+1]++;
|
||||
|
||||
for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1];
|
||||
|
||||
for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0;
|
||||
vec = 0;
|
||||
|
||||
for (i = minLen; i <= maxLen; i++) {
|
||||
vec += (base[i+1] - base[i]);
|
||||
limit[i] = vec-1;
|
||||
vec <<= 1;
|
||||
}
|
||||
for (i = minLen + 1; i <= maxLen; i++)
|
||||
base[i] = ((limit[i-1] + 1) << 1) - base[i];
|
||||
}
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end huffman.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -0,0 +1,84 @@
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- Table for randomising repetitive blocks ---*/
|
||||
/*--- randtable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
This file is part of bzip2/libbzip2, a program and library for
|
||||
lossless, block-sorting data compression.
|
||||
|
||||
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||
|
||||
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||
README file.
|
||||
|
||||
This program is released under the terms of the license contained
|
||||
in the file LICENSE.
|
||||
------------------------------------------------------------------ */
|
||||
|
||||
|
||||
#include "bzlib_private.h"
|
||||
|
||||
|
||||
/*---------------------------------------------*/
|
||||
Int32 BZ2_rNums[512] = {
|
||||
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
|
||||
985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
|
||||
733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
|
||||
419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
|
||||
878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
|
||||
862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
|
||||
150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
|
||||
170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
|
||||
73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
|
||||
909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
|
||||
641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
|
||||
161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
|
||||
382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
|
||||
98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
|
||||
227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
|
||||
469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
|
||||
184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
|
||||
715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
|
||||
951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
|
||||
652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
|
||||
645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
|
||||
609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
|
||||
653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
|
||||
411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
|
||||
170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
|
||||
857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
|
||||
669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
|
||||
944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
|
||||
344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
|
||||
897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
|
||||
433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
|
||||
686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
|
||||
946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
|
||||
978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
|
||||
680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
|
||||
707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
|
||||
297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
|
||||
134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
|
||||
343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
|
||||
140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
|
||||
170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
|
||||
369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
|
||||
804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
|
||||
896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
|
||||
661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
|
||||
768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
|
||||
61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
|
||||
372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
|
||||
780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
|
||||
920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
|
||||
645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
|
||||
936, 638
|
||||
};
|
||||
|
||||
|
||||
/*-------------------------------------------------------------*/
|
||||
/*--- end randtable.c ---*/
|
||||
/*-------------------------------------------------------------*/
|
||||
@@ -31,13 +31,10 @@ namespace RNS { namespace Cryptography {
|
||||
//DEBUGF("PKCS7::pad: len: %zu", len);
|
||||
size_t padlen = bs - (len % bs);
|
||||
//DEBUGF("PKCS7::pad: pad len: %zu", padlen);
|
||||
// create zero-filled byte padding array of size padlen
|
||||
// PKCS7: fill ALL padding bytes with padlen value (RFC 5652 §6.3)
|
||||
//p v = bytes([padlen])
|
||||
//uint8_t pad[padlen] = {0};
|
||||
uint8_t pad[padlen];
|
||||
memset(pad, 0, padlen);
|
||||
// set last byte of padding array to size of padding
|
||||
pad[padlen-1] = (uint8_t)padlen;
|
||||
memset(pad, (uint8_t)padlen, padlen);
|
||||
// concatenate data with padding
|
||||
//p return data+v*padlen
|
||||
data.append(pad, padlen);
|
||||
|
||||
+24
-4
@@ -101,15 +101,23 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire
|
||||
/*static*/ Bytes Destination::hash(const Identity& identity, const char* app_name, const char* aspects) {
|
||||
//p name_hash = Identity::full_hash(Destination.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)]
|
||||
//p addr_hash_material = name_hash
|
||||
std::string expanded = expand_name({Type::NONE}, app_name, aspects);
|
||||
Bytes addr_hash_material = name_hash(app_name, aspects);
|
||||
TRACEF("[DIAG] Dest::hash: expanded='%s' name_hash=%s",
|
||||
expanded.c_str(), addr_hash_material.toHex().c_str());
|
||||
if (identity) {
|
||||
TRACEF("[DIAG] Dest::hash: identity_hash=%s", identity.hash().toHex().c_str());
|
||||
addr_hash_material << identity.hash();
|
||||
}
|
||||
TRACEF("[DIAG] Dest::hash: material(%d)=%s",
|
||||
(int)addr_hash_material.size(), addr_hash_material.toHex().c_str());
|
||||
|
||||
//p return RNS.Identity.full_hash(addr_hash_material)[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
|
||||
// CBA TODO valid alternative?
|
||||
//return Identity::full_hash(addr_hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
||||
return Identity::truncated_hash(addr_hash_material);
|
||||
Bytes result = Identity::truncated_hash(addr_hash_material);
|
||||
TRACEF("[DIAG] Dest::hash: result=%s", result.toHex().c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -253,9 +261,17 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
||||
}
|
||||
else {
|
||||
Bytes destination_hash = _object->_hash;
|
||||
//p random_hash = Identity::get_random_hash()[0:5] << int(time.time()).to_bytes(5, "big")
|
||||
// CBA TODO add in time to random hash
|
||||
Bytes random_hash = Cryptography::random(Type::Identity::RANDOM_HASH_LENGTH/8);
|
||||
//p random_hash = Identity::get_random_hash()[0:5] + int(time.time()).to_bytes(5, "big")
|
||||
// 5 random bytes + 5 big-endian timestamp bytes (matches Python reference)
|
||||
Bytes random_part = Cryptography::random(5);
|
||||
uint64_t ts = (uint64_t)OS::time();
|
||||
uint8_t time_bytes[5];
|
||||
time_bytes[0] = (ts >> 32) & 0xFF;
|
||||
time_bytes[1] = (ts >> 24) & 0xFF;
|
||||
time_bytes[2] = (ts >> 16) & 0xFF;
|
||||
time_bytes[3] = (ts >> 8) & 0xFF;
|
||||
time_bytes[4] = ts & 0xFF;
|
||||
Bytes random_hash = random_part + Bytes(time_bytes, 5);
|
||||
|
||||
Bytes new_app_data(app_data);
|
||||
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
|
||||
@@ -431,6 +447,10 @@ Encrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP``
|
||||
}
|
||||
|
||||
if (_object->_type == SINGLE && _object->_identity) {
|
||||
// TODO: Re-enable ratchet encryption once fully compatible with Python reference.
|
||||
// Currently causes "Decryption with ratchets failed" on receiving Python clients.
|
||||
//Bytes ratchet = Identity::get_ratchet(_object->_hash);
|
||||
//return _object->_identity.encrypt(data, ratchet);
|
||||
return _object->_identity.encrypt(data);
|
||||
}
|
||||
|
||||
|
||||
+262
-79
@@ -28,6 +28,8 @@ using namespace RNS::Utilities;
|
||||
// CBA
|
||||
// CBA ACCUMULATES
|
||||
/*static*/ uint16_t Identity::_known_destinations_maxsize = RNS_KNOWN_DESTINATIONS_MAX;
|
||||
/*static*/ bool Identity::_known_destinations_dirty = false;
|
||||
/*static*/ Identity::RatchetTable Identity::_known_ratchets;
|
||||
|
||||
Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) {
|
||||
if (create_keys) {
|
||||
@@ -200,9 +202,11 @@ Can be used to load previously created and saved identities into Reticulum.
|
||||
//p _known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data};
|
||||
// CBA ACCUMULATES
|
||||
try {
|
||||
_known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}});
|
||||
// CBA IMMEDIATE CULL
|
||||
cull_known_destinations();
|
||||
// Use insert_or_assign so the timestamp is always refreshed.
|
||||
_known_destinations.insert_or_assign(destination_hash, IdentityEntry{OS::time(), packet_hash, public_key, app_data});
|
||||
// Defer cull to periodic jobs instead of per-announce to avoid
|
||||
// O(n log n) sorting on every inbound packet.
|
||||
_known_destinations_dirty = true;
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str());
|
||||
@@ -265,13 +269,18 @@ Recall last heard app_data for a destination hash.
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ bool Identity::save_known_destinations() {
|
||||
// TODO: Improve the storage method so we don't have to
|
||||
// deserialize and serialize the entire table on every
|
||||
// save, but the only changes. It might be possible to
|
||||
// simply overwrite on exit now that every local client
|
||||
// disconnect triggers a data persist.
|
||||
/*
|
||||
Binary format for known_destinations persistence:
|
||||
[uint16_t entry_count]
|
||||
For each entry:
|
||||
[uint16_t dest_hash_len][dest_hash bytes]
|
||||
[double timestamp]
|
||||
[uint16_t packet_hash_len][packet_hash bytes]
|
||||
[uint16_t public_key_len][public_key bytes]
|
||||
[uint16_t app_data_len][app_data bytes]
|
||||
*/
|
||||
|
||||
/*static*/ bool Identity::save_known_destinations() {
|
||||
bool success = false;
|
||||
try {
|
||||
if (_saving_known_destinations) {
|
||||
@@ -290,39 +299,47 @@ Recall last heard app_data for a destination hash.
|
||||
_saving_known_destinations = true;
|
||||
double save_start = OS::time();
|
||||
|
||||
std::map<Bytes, IdentityEntry> storage_known_destinations;
|
||||
// TODO
|
||||
/*
|
||||
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
||||
try:
|
||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","rb")
|
||||
storage_known_destinations = umsgpack.load(file)
|
||||
file.close()
|
||||
except:
|
||||
pass
|
||||
*/
|
||||
|
||||
for (auto& [destination_hash, identity_entry] : storage_known_destinations) {
|
||||
if (_known_destinations.find(destination_hash) == _known_destinations.end()) {
|
||||
//_known_destinations[destination_hash] = storage_known_destinations[destination_hash];
|
||||
//_known_destinations[destination_hash] = identity_entry;
|
||||
// CBA ACCUMULATES
|
||||
_known_destinations.insert({destination_hash, identity_entry});
|
||||
// CBA IMMEDIATE CULL
|
||||
cull_known_destinations();
|
||||
}
|
||||
if (_known_destinations.empty()) {
|
||||
_saving_known_destinations = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// TODO
|
||||
/*
|
||||
DEBUGF("Saving %zu known destinations to storage...", _known_destinations.size());
|
||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","wb")
|
||||
umsgpack.dump(Identity.known_destinations, file)
|
||||
file.close()
|
||||
DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3));
|
||||
*/
|
||||
// Serialize to binary buffer
|
||||
Bytes buf(1024);
|
||||
uint16_t count = (uint16_t)_known_destinations.size();
|
||||
buf.append((const uint8_t*)&count, sizeof(count));
|
||||
|
||||
success = true;
|
||||
for (const auto& [dest_hash, entry] : _known_destinations) {
|
||||
uint16_t len;
|
||||
|
||||
len = (uint16_t)dest_hash.size();
|
||||
buf.append((const uint8_t*)&len, sizeof(len));
|
||||
buf.append(dest_hash.data(), dest_hash.size());
|
||||
|
||||
buf.append((const uint8_t*)&entry._timestamp, sizeof(entry._timestamp));
|
||||
|
||||
len = (uint16_t)entry._packet_hash.size();
|
||||
buf.append((const uint8_t*)&len, sizeof(len));
|
||||
if (len > 0) buf.append(entry._packet_hash.data(), entry._packet_hash.size());
|
||||
|
||||
len = (uint16_t)entry._public_key.size();
|
||||
buf.append((const uint8_t*)&len, sizeof(len));
|
||||
if (len > 0) buf.append(entry._public_key.data(), entry._public_key.size());
|
||||
|
||||
len = (uint16_t)entry._app_data.size();
|
||||
buf.append((const uint8_t*)&len, sizeof(len));
|
||||
if (len > 0) buf.append(entry._app_data.data(), entry._app_data.size());
|
||||
}
|
||||
|
||||
char filepath[Type::Reticulum::FILEPATH_MAXSIZE];
|
||||
snprintf(filepath, Type::Reticulum::FILEPATH_MAXSIZE, "%s/known_destinations", Reticulum::_storagepath);
|
||||
|
||||
if (OS::write_file(filepath, buf) == buf.size()) {
|
||||
DEBUGF("Saved %zu known destinations to storage in %.3f seconds", _known_destinations.size(), OS::round(OS::time() - save_start, 3));
|
||||
success = true;
|
||||
} else {
|
||||
ERROR("Failed to write known destinations to storage");
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Error while saving known destinations to disk, the contained exception was: %s", e.what());
|
||||
@@ -334,26 +351,114 @@ Recall last heard app_data for a destination hash.
|
||||
}
|
||||
|
||||
/*static*/ void Identity::load_known_destinations() {
|
||||
// TODO
|
||||
/*
|
||||
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
||||
try:
|
||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","rb")
|
||||
loaded_known_destinations = umsgpack.load(file)
|
||||
file.close()
|
||||
char filepath[Type::Reticulum::FILEPATH_MAXSIZE];
|
||||
snprintf(filepath, Type::Reticulum::FILEPATH_MAXSIZE, "%s/known_destinations", Reticulum::_storagepath);
|
||||
|
||||
Identity.known_destinations = {}
|
||||
for known_destination in loaded_known_destinations:
|
||||
if len(known_destination) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
|
||||
Identity.known_destinations[known_destination] = loaded_known_destinations[known_destination]
|
||||
if (!OS::file_exists(filepath)) {
|
||||
VERBOSE("Destinations file does not exist, no known destinations loaded");
|
||||
return;
|
||||
}
|
||||
|
||||
RNS.log("Loaded "+str(len(Identity.known_destinations))+" known destination from storage", RNS.LOG_VERBOSE)
|
||||
except:
|
||||
RNS.log("Error loading known destinations from disk, file will be recreated on exit", RNS.LOG_ERROR)
|
||||
else:
|
||||
RNS.log("Destinations file does not exist, no known destinations loaded", RNS.LOG_VERBOSE)
|
||||
*/
|
||||
try {
|
||||
Bytes buf;
|
||||
if (OS::read_file(filepath, buf) == 0) {
|
||||
ERROR("Failed to read known destinations file");
|
||||
return;
|
||||
}
|
||||
|
||||
const uint8_t* ptr = buf.data();
|
||||
size_t remaining = buf.size();
|
||||
|
||||
if (remaining < sizeof(uint16_t)) return;
|
||||
uint16_t count;
|
||||
memcpy(&count, ptr, sizeof(count));
|
||||
ptr += sizeof(count);
|
||||
remaining -= sizeof(count);
|
||||
|
||||
size_t loaded = 0;
|
||||
for (uint16_t i = 0; i < count && remaining > 0; i++) {
|
||||
uint16_t len;
|
||||
|
||||
// dest_hash
|
||||
if (remaining < sizeof(len)) break;
|
||||
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||
if (remaining < len || len != Type::Reticulum::TRUNCATED_HASHLENGTH/8) break;
|
||||
Bytes dest_hash(ptr, len); ptr += len; remaining -= len;
|
||||
|
||||
// timestamp
|
||||
if (remaining < sizeof(double)) break;
|
||||
double timestamp;
|
||||
memcpy(×tamp, ptr, sizeof(timestamp)); ptr += sizeof(timestamp); remaining -= sizeof(timestamp);
|
||||
|
||||
// packet_hash
|
||||
if (remaining < sizeof(len)) break;
|
||||
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||
if (remaining < len) break;
|
||||
Bytes packet_hash(ptr, len); ptr += len; remaining -= len;
|
||||
|
||||
// public_key
|
||||
if (remaining < sizeof(len)) break;
|
||||
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||
if (remaining < len) break;
|
||||
Bytes public_key(ptr, len); ptr += len; remaining -= len;
|
||||
|
||||
// app_data
|
||||
if (remaining < sizeof(len)) break;
|
||||
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||
if (remaining < len) break;
|
||||
Bytes app_data(ptr, len); ptr += len; remaining -= len;
|
||||
|
||||
if (_known_destinations.find(dest_hash) == _known_destinations.end()) {
|
||||
try {
|
||||
_known_destinations.insert({dest_hash, {timestamp, packet_hash, public_key, app_data}});
|
||||
loaded++;
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("load_known_destinations: out of memory, stopping load");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize timestamps to current boot epoch.
|
||||
// OS::time() on Arduino returns seconds since boot, not epoch time.
|
||||
// Persisted entries carry timestamps from the previous boot session
|
||||
// (e.g., 5000.0 = device had been up 5000s when saved). On a fresh
|
||||
// boot at uptime 30s, a new announce would get timestamp 30.0 — which
|
||||
// the LRU cull considers "older" than the persisted 5000.0, causing
|
||||
// the NEW entry to be culled immediately. Fix: remap all loaded
|
||||
// timestamps into [1.0, now-1] preserving their relative order, so
|
||||
// any fresh announce at OS::time() is always "newest".
|
||||
if (loaded > 0) {
|
||||
double now = OS::time();
|
||||
double max_ts = 0, min_ts = 1e18;
|
||||
for (const auto& [key, entry] : _known_destinations) {
|
||||
if (entry._timestamp > max_ts) max_ts = entry._timestamp;
|
||||
if (entry._timestamp < min_ts) min_ts = entry._timestamp;
|
||||
}
|
||||
double range = max_ts - min_ts;
|
||||
// Map [min_ts, max_ts] → [1.0, now - 1.0]
|
||||
// All loaded entries end up before "now", preserving relative order
|
||||
double target_max = (now > 2.0) ? now - 1.0 : 1.0;
|
||||
double target_min = 1.0;
|
||||
for (auto& [key, entry] : _known_destinations) {
|
||||
if (range > 0.001) {
|
||||
double normalized = (entry._timestamp - min_ts) / range;
|
||||
entry._timestamp = target_min + normalized * (target_max - target_min);
|
||||
} else {
|
||||
entry._timestamp = target_min;
|
||||
}
|
||||
}
|
||||
VERBOSEF("Normalized %zu destination timestamps: [%.1f,%.1f] -> [%.1f,%.1f]",
|
||||
loaded, min_ts, max_ts, target_min, target_max);
|
||||
}
|
||||
|
||||
cull_known_destinations();
|
||||
VERBOSEF("Loaded %zu known destinations from storage", loaded);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Error loading known destinations from disk, file will be recreated on exit: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ void Identity::cull_known_destinations() {
|
||||
@@ -407,36 +512,72 @@ Recall last heard app_data for a destination hash.
|
||||
try {
|
||||
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
|
||||
Bytes destination_hash = packet.destination_hash();
|
||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
||||
Bytes public_key = packet.data().left(KEYSIZE/8);
|
||||
//TRACEF("Identity::validate_announce: public_key: %s", public_key.toHex().c_str());
|
||||
Bytes name_hash = packet.data().mid(KEYSIZE/8, NAME_HASH_LENGTH/8);
|
||||
//TRACEF("Identity::validate_announce: name_hash: %s", name_hash.toHex().c_str());
|
||||
Bytes random_hash = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8, RANDOM_HASH_LENGTH/8);
|
||||
//TRACEF("Identity::validate_announce: random_hash: %s", random_hash.toHex().c_str());
|
||||
Bytes signature = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8, SIGLENGTH/8);
|
||||
//TRACEF("Identity::validate_announce: signature: %s", signature.toHex().c_str());
|
||||
|
||||
size_t keysize = KEYSIZE/8;
|
||||
size_t ratchetsize = Type::Identity::RATCHETSIZE/8;
|
||||
size_t name_hash_len = NAME_HASH_LENGTH/8;
|
||||
size_t sig_len = SIGLENGTH/8;
|
||||
|
||||
Bytes public_key = packet.data().left(keysize);
|
||||
Bytes name_hash = packet.data().mid(keysize, name_hash_len);
|
||||
Bytes random_hash = packet.data().mid(keysize + name_hash_len, 10);
|
||||
|
||||
Bytes ratchet;
|
||||
Bytes signature;
|
||||
Bytes app_data;
|
||||
if (packet.data().size() > (KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8)) {
|
||||
app_data = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8);
|
||||
|
||||
// If the packet context flag is set, this announce contains a ratchet key
|
||||
if (packet.context_flag() == Type::Packet::FLAG_SET) {
|
||||
ratchet = packet.data().mid(keysize + name_hash_len + 10, ratchetsize);
|
||||
signature = packet.data().mid(keysize + name_hash_len + 10 + ratchetsize, sig_len);
|
||||
if (packet.data().size() > keysize + name_hash_len + 10 + ratchetsize + sig_len) {
|
||||
app_data = packet.data().mid(keysize + name_hash_len + 10 + ratchetsize + sig_len);
|
||||
}
|
||||
}
|
||||
else {
|
||||
signature = packet.data().mid(keysize + name_hash_len + 10, sig_len);
|
||||
if (packet.data().size() > keysize + name_hash_len + 10 + sig_len) {
|
||||
app_data = packet.data().mid(keysize + name_hash_len + 10 + sig_len);
|
||||
}
|
||||
}
|
||||
//TRACEF("Identity::validate_announce: app_data: %s", app_data.toHex().c_str());
|
||||
//TRACEF("Identity::validate_announce: app_data text: %s", app_data.toString().c_str());
|
||||
|
||||
Bytes signed_data;
|
||||
signed_data << packet.destination_hash() << public_key << name_hash << random_hash+app_data;
|
||||
//TRACEF("Identity::validate_announce: signed_data: %s", signed_data.toHex().c_str());
|
||||
|
||||
if (packet.data().size() <= KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8) {
|
||||
if (!ratchet && packet.data().size() <= keysize + name_hash_len + 10 + sig_len) {
|
||||
app_data.clear();
|
||||
}
|
||||
else if (ratchet && packet.data().size() <= keysize + name_hash_len + 10 + ratchetsize + sig_len) {
|
||||
app_data.clear();
|
||||
}
|
||||
|
||||
// Fast path: if this identity is already known with the same public key,
|
||||
// skip the expensive Ed25519 signature verification (~150ms on ESP32).
|
||||
// Just update app_data/timestamp and return true.
|
||||
auto known_iter = _known_destinations.find(destination_hash);
|
||||
if (known_iter != _known_destinations.end()
|
||||
&& known_iter->second._public_key == public_key) {
|
||||
remember(packet.get_hash(), destination_hash, public_key, app_data);
|
||||
if (ratchet) {
|
||||
remember_ratchet(destination_hash, ratchet);
|
||||
}
|
||||
TRACEF("validate_announce: known identity %s — skipped Ed25519 verify",
|
||||
destination_hash.toHex().c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Slow path: new or changed identity — full Ed25519 verify required
|
||||
Bytes signed_data;
|
||||
signed_data << destination_hash << public_key << name_hash << random_hash << ratchet << app_data;
|
||||
|
||||
Identity announced_identity(false);
|
||||
announced_identity.load_public_key(public_key);
|
||||
|
||||
if (announced_identity.pub() && announced_identity.validate(signature, signed_data)) {
|
||||
TRACEF("[DIAG] validate_announce: name_hash=%s identity_hash=%s",
|
||||
name_hash.toHex().c_str(), announced_identity.hash().toHex().c_str());
|
||||
Bytes hash_material = name_hash << announced_identity.hash();
|
||||
Bytes expected_hash = full_hash(hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
||||
TRACEF("[DIAG] validate_announce: material(%d)=%s expected=%s actual=%s",
|
||||
(int)hash_material.size(), hash_material.toHex().c_str(),
|
||||
expected_hash.toHex().c_str(), packet.destination_hash().toHex().c_str());
|
||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
||||
//TRACEF("Identity::validate_announce: expected_hash: %s", expected_hash.toHex().c_str());
|
||||
|
||||
@@ -456,7 +597,10 @@ Recall last heard app_data for a destination hash.
|
||||
}
|
||||
|
||||
remember(packet.get_hash(), packet.destination_hash(), public_key, app_data);
|
||||
//p del announced_identity
|
||||
|
||||
if (ratchet) {
|
||||
remember_ratchet(packet.destination_hash(), ratchet);
|
||||
}
|
||||
|
||||
std::string signal_str;
|
||||
// TODO
|
||||
@@ -481,14 +625,23 @@ Recall last heard app_data for a destination hash.
|
||||
TRACEF("Valid announce for %s %d hops away, received on %s%s", packet.destination_hash().toHex().c_str(), packet.hops(), packet.receiving_interface().toString().c_str(), signal_str.c_str());
|
||||
}
|
||||
|
||||
TRACEF("[DIAG] ANNOUNCE VALID: dest=%s hops=%d ratchet=%s",
|
||||
packet.destination_hash().toHex().c_str(), packet.hops(),
|
||||
ratchet ? "YES" : "NO");
|
||||
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
TRACEF("[DIAG] ANNOUNCE HASH MISMATCH: dest=%s expected=%s",
|
||||
packet.destination_hash().toHex().c_str(), expected_hash.toHex().c_str());
|
||||
DEBUGF("Received invalid announce for %s: Destination mismatch.", packet.destination_hash().toHex().c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
TRACEF("[DIAG] ANNOUNCE INVALID SIG: dest=%s datalen=%d ctxflag=%d",
|
||||
packet.destination_hash().toHex().c_str(), (int)packet.data().size(),
|
||||
packet.context_flag());
|
||||
DEBUGF("Received invalid announce for %s: Invalid signature.", packet.destination_hash().toHex().c_str());
|
||||
//p del announced_identity
|
||||
return false;
|
||||
@@ -502,6 +655,27 @@ Recall last heard app_data for a destination hash.
|
||||
return false;
|
||||
}
|
||||
|
||||
/*static*/ void Identity::remember_ratchet(const Bytes& destination_hash, const Bytes& ratchet_pub) {
|
||||
if (ratchet_pub.size() != Type::Identity::RATCHETSIZE/8) {
|
||||
WARNINGF("Cannot remember ratchet for %s, invalid ratchet size %zu", destination_hash.toHex().c_str(), ratchet_pub.size());
|
||||
return;
|
||||
}
|
||||
auto iter = _known_ratchets.find(destination_hash);
|
||||
if (iter != _known_ratchets.end() && iter->second == ratchet_pub) {
|
||||
return; // Already known, no change
|
||||
}
|
||||
TRACEF("Remembering ratchet for %s", destination_hash.toHex().c_str());
|
||||
_known_ratchets.insert_or_assign(destination_hash, ratchet_pub);
|
||||
}
|
||||
|
||||
/*static*/ Bytes Identity::get_ratchet(const Bytes& destination_hash) {
|
||||
auto iter = _known_ratchets.find(destination_hash);
|
||||
if (iter != _known_ratchets.end()) {
|
||||
return iter->second;
|
||||
}
|
||||
return {Bytes::NONE};
|
||||
}
|
||||
|
||||
/*static*/ void Identity::persist_data() {
|
||||
if (!Transport::reticulum() || !Transport::reticulum().is_connected_to_shared_instance()) {
|
||||
save_known_destinations();
|
||||
@@ -519,7 +693,7 @@ Encrypts information for the identity.
|
||||
:returns: Ciphertext token as *bytes*.
|
||||
:raises: *KeyError* if the instance does not hold a public key.
|
||||
*/
|
||||
const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
||||
const Bytes Identity::encrypt(const Bytes& plaintext, const Bytes& ratchet_key /*= {Bytes::NONE}*/) const {
|
||||
assert(_object);
|
||||
TRACE("Identity::encrypt: encrypting data...");
|
||||
if (!_object->_pub) {
|
||||
@@ -529,9 +703,18 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
||||
Bytes ephemeral_pub_bytes = ephemeral_key->public_key()->public_bytes();
|
||||
TRACEF("Identity::encrypt: ephemeral public key: %s", ephemeral_pub_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create shared key for key exchange using own public key
|
||||
//shared_key = ephemeral_key.exchange(self.pub)
|
||||
Bytes shared_key = ephemeral_key->exchange(_object->_pub_bytes);
|
||||
// CRYPTO: create shared key for key exchange
|
||||
// Use ratchet public key if available for forward secrecy, otherwise identity public key
|
||||
Bytes shared_key;
|
||||
TRACEF("[DIAG] ENCRYPT: ratchet=%s ephemeral=%.16s... plaintext=%dB",
|
||||
ratchet_key ? "YES" : "NO", ephemeral_pub_bytes.toHex().c_str(), (int)plaintext.size());
|
||||
if (ratchet_key) {
|
||||
shared_key = ephemeral_key->exchange(ratchet_key);
|
||||
TRACE("Identity::encrypt: using ratchet key for ECDH");
|
||||
}
|
||||
else {
|
||||
shared_key = ephemeral_key->exchange(_object->_pub_bytes);
|
||||
}
|
||||
TRACEF("Identity::encrypt: shared key: %s", shared_key.toHex().c_str());
|
||||
|
||||
Bytes derived_key = Cryptography::hkdf(
|
||||
|
||||
+13
-1
@@ -40,11 +40,15 @@ namespace RNS {
|
||||
//using IdentityTable = std::map<Bytes, IdentityEntry>;
|
||||
using IdentityTable = std::map<Bytes, IdentityEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, IdentityEntry>>>;
|
||||
|
||||
using RatchetTable = std::map<Bytes, Bytes>;
|
||||
|
||||
private:
|
||||
static IdentityTable _known_destinations;
|
||||
static bool _saving_known_destinations;
|
||||
// CBA
|
||||
static uint16_t _known_destinations_maxsize;
|
||||
static bool _known_destinations_dirty;
|
||||
static RatchetTable _known_ratchets;
|
||||
|
||||
public:
|
||||
Identity(bool create_keys = true);
|
||||
@@ -101,7 +105,7 @@ namespace RNS {
|
||||
inline const Bytes& get_salt() const { assert(_object); return _object->_hash; }
|
||||
inline const Bytes get_context() const { return {Bytes::NONE}; }
|
||||
|
||||
const Bytes encrypt(const Bytes& plaintext) const;
|
||||
const Bytes encrypt(const Bytes& plaintext, const Bytes& ratchet_key = {Bytes::NONE}) const;
|
||||
const Bytes decrypt(const Bytes& ciphertext_token) const;
|
||||
const Bytes sign(const Bytes& message) const;
|
||||
bool validate(const Bytes& signature, const Bytes& message) const;
|
||||
@@ -151,6 +155,8 @@ namespace RNS {
|
||||
}
|
||||
|
||||
static bool validate_announce(const Packet& packet);
|
||||
static void remember_ratchet(const Bytes& destination_hash, const Bytes& ratchet_pub);
|
||||
static Bytes get_ratchet(const Bytes& destination_hash);
|
||||
static void persist_data();
|
||||
static void exit_handler();
|
||||
|
||||
@@ -169,6 +175,12 @@ namespace RNS {
|
||||
inline const Cryptography::Ed25519PublicKey::Ptr sig_pub() const { assert(_object); return _object->_sig_pub; }
|
||||
inline static uint16_t known_destinations_maxsize() { return _known_destinations_maxsize; }
|
||||
inline static void known_destinations_maxsize(uint16_t known_destinations_maxsize) { _known_destinations_maxsize = known_destinations_maxsize; }
|
||||
static void deferred_cull_known_destinations() {
|
||||
if (_known_destinations_dirty) {
|
||||
_known_destinations_dirty = false;
|
||||
cull_known_destinations();
|
||||
}
|
||||
}
|
||||
|
||||
inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; }
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ namespace RNS {
|
||||
std::list<AnnounceEntry> _announce_queue;
|
||||
bool _is_connected_to_shared_instance = false;
|
||||
bool _is_local_shared_instance = false;
|
||||
|
||||
//Bytes _hash;
|
||||
HInterface _parent_interface;
|
||||
//Transport& _owner;
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// LXMF message format — MsgPack wire codec
|
||||
// Shared between microReticulum (library) and Ratdeck (firmware).
|
||||
// Matches Python LXMF LXMessage.py and Rust lxmf-core message.rs wire format.
|
||||
#include "LXMFMessage.h"
|
||||
#include <cstring>
|
||||
|
||||
static void mpPackFloat64(std::vector<uint8_t>& buf, double val) {
|
||||
buf.push_back(0xCB);
|
||||
uint64_t bits;
|
||||
memcpy(&bits, &val, 8);
|
||||
for (int i = 7; i >= 0; i--) {
|
||||
buf.push_back((bits >> (i * 8)) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static void mpPackString(std::vector<uint8_t>& buf, const std::string& str) {
|
||||
size_t len = str.size();
|
||||
if (len < 32) {
|
||||
buf.push_back(0xA0 | (uint8_t)len);
|
||||
} else if (len < 256) {
|
||||
buf.push_back(0xD9);
|
||||
buf.push_back((uint8_t)len);
|
||||
} else {
|
||||
buf.push_back(0xDA);
|
||||
buf.push_back((len >> 8) & 0xFF);
|
||||
buf.push_back(len & 0xFF);
|
||||
}
|
||||
buf.insert(buf.end(), str.begin(), str.end());
|
||||
}
|
||||
|
||||
// MsgPack bin format — Python LXMF expects title/content as bytes, not str
|
||||
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||
size_t len = str.size();
|
||||
if (len < 256) {
|
||||
buf.push_back(0xC4);
|
||||
buf.push_back((uint8_t)len);
|
||||
} else {
|
||||
buf.push_back(0xC5);
|
||||
buf.push_back((len >> 8) & 0xFF);
|
||||
buf.push_back(len & 0xFF);
|
||||
}
|
||||
buf.insert(buf.end(), str.begin(), str.end());
|
||||
}
|
||||
|
||||
static bool mpReadFloat64(const uint8_t* data, size_t len, size_t& pos, double& val) {
|
||||
if (pos >= len || data[pos] != 0xCB) return false;
|
||||
pos++;
|
||||
if (pos + 8 > len) return false;
|
||||
uint64_t bits = 0;
|
||||
for (int i = 0; i < 8; i++) { bits = (bits << 8) | data[pos++]; }
|
||||
memcpy(&val, &bits, 8);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool mpReadString(const uint8_t* data, size_t len, size_t& pos, std::string& str) {
|
||||
if (pos >= len) return false;
|
||||
uint8_t b = data[pos];
|
||||
size_t slen = 0;
|
||||
// MsgPack str formats
|
||||
if ((b & 0xE0) == 0xA0) { slen = b & 0x1F; pos++; }
|
||||
else if (b == 0xD9) { pos++; if (pos >= len) return false; slen = data[pos++]; }
|
||||
else if (b == 0xDA) { pos++; if (pos + 2 > len) return false; slen = ((size_t)data[pos] << 8) | data[pos + 1]; pos += 2; }
|
||||
// MsgPack bin formats (Python LXMF sends title/content as bin)
|
||||
else if (b == 0xC4) { pos++; if (pos >= len) return false; slen = data[pos++]; }
|
||||
else if (b == 0xC5) { pos++; if (pos + 2 > len) return false; slen = ((size_t)data[pos] << 8) | 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;
|
||||
}
|
||||
|
||||
static bool mpSkipValue(const uint8_t* data, size_t len, size_t& pos) {
|
||||
if (pos >= len) return false;
|
||||
uint8_t b = data[pos];
|
||||
if ((b & 0xE0) == 0xA0) { pos += 1 + (b & 0x1F); return pos <= len; }
|
||||
if ((b & 0xF0) == 0x80) { size_t c = b & 0x0F; pos++; for (size_t i = 0; i < c * 2; i++) { if (!mpSkipValue(data, len, pos)) return false; } return true; }
|
||||
if ((b & 0xF0) == 0x90) { size_t c = b & 0x0F; pos++; for (size_t i = 0; i < c; i++) { if (!mpSkipValue(data, len, pos)) return false; } return true; }
|
||||
if (b == 0xCB) { pos += 9; return pos <= len; }
|
||||
if (b == 0xD9) { if (pos + 2 > len) return false; size_t s = data[pos + 1]; pos += 2 + s; return pos <= len; }
|
||||
if (b == 0xDA) { if (pos + 3 > len) return false; size_t s = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3 + s; return pos <= len; }
|
||||
if ((b & 0x80) == 0x00 || (b & 0xE0) == 0xE0 || b == 0xC0 || b == 0xC2 || b == 0xC3) { pos++; return true; }
|
||||
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) { pos += 9; 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; }
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> LXMFMessage::packContent(double timestamp, const std::string& content, const std::string& title) {
|
||||
std::vector<uint8_t> buf;
|
||||
buf.reserve(32 + content.size() + title.size());
|
||||
buf.push_back(0x94);
|
||||
mpPackFloat64(buf, timestamp);
|
||||
mpPackBin(buf, title); // LXMF spec: [ts, title, content, fields] — must be bin, not str
|
||||
mpPackBin(buf, content);
|
||||
buf.push_back(0x80);
|
||||
return buf;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> LXMFMessage::packFull(const RNS::Identity& signingIdentity) {
|
||||
std::vector<uint8_t> packed = packContent(timestamp, content, title);
|
||||
if (sourceHash.size() < 16 || destHash.size() < 16) return {};
|
||||
|
||||
// Sign: dest_hash || source_hash || packed_content || message_hash (LXMF spec)
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.reserve(32 + packed.size());
|
||||
hashed_part.insert(hashed_part.end(), destHash.data(), destHash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), sourceHash.data(), sourceHash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||
|
||||
RNS::Bytes hashedBytes(hashed_part.data(), hashed_part.size());
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(hashedBytes);
|
||||
|
||||
// Store messageId = SHA256(dest + src + payload), matching Python LXMessage.pack()
|
||||
messageId = msgHash;
|
||||
|
||||
std::vector<uint8_t> signed_part;
|
||||
signed_part.reserve(hashed_part.size() + msgHash.size());
|
||||
signed_part.insert(signed_part.end(), hashed_part.begin(), hashed_part.end());
|
||||
signed_part.insert(signed_part.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||
|
||||
RNS::Bytes signableBytes(signed_part.data(), signed_part.size());
|
||||
RNS::Bytes sig = signingIdentity.sign(signableBytes);
|
||||
if (sig.size() < 64) return {};
|
||||
|
||||
// Wire (opportunistic): [src_hash:16][signature:64][packed_content]
|
||||
// dest_hash is carried by the RNS packet header, not the LXMF payload
|
||||
std::vector<uint8_t> payload;
|
||||
payload.reserve(16 + 64 + packed.size());
|
||||
payload.insert(payload.end(), sourceHash.data(), sourceHash.data() + 16);
|
||||
payload.insert(payload.end(), sig.data(), sig.data() + 64);
|
||||
payload.insert(payload.end(), packed.begin(), packed.end());
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool LXMFMessage::unpackFull(const uint8_t* data, size_t len, LXMFMessage& msg) {
|
||||
// Wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||
if (len < 97) return false; // 16+16+64+1 minimum
|
||||
msg.destHash = RNS::Bytes(data, 16);
|
||||
msg.sourceHash = RNS::Bytes(data + 16, 16);
|
||||
msg.signature = RNS::Bytes(data + 32, 64);
|
||||
|
||||
const uint8_t* content = data + 96;
|
||||
size_t contentLen = len - 96;
|
||||
size_t pos = 0;
|
||||
|
||||
if (pos >= contentLen) return false;
|
||||
uint8_t arrHeader = content[pos];
|
||||
if ((arrHeader & 0xF0) != 0x90) return false;
|
||||
size_t arrLen = arrHeader & 0x0F;
|
||||
if (arrLen < 3) return false;
|
||||
pos++;
|
||||
|
||||
// LXMF spec: [timestamp, title, content, fields]
|
||||
if (!mpReadFloat64(content, contentLen, pos, msg.timestamp)) return false;
|
||||
if (!mpReadString(content, contentLen, pos, msg.title)) return false;
|
||||
if (!mpReadString(content, contentLen, pos, msg.content)) return false;
|
||||
if (arrLen >= 4 && pos < contentLen) { mpSkipValue(content, contentLen, pos); }
|
||||
|
||||
// messageId = SHA256(dest + src + packed_content), matching Python/Rust
|
||||
// (skip signature at bytes 32..96)
|
||||
std::vector<uint8_t> hashInput;
|
||||
hashInput.reserve(32 + (len - 96));
|
||||
hashInput.insert(hashInput.end(), data, data + 32); // dest_hash + src_hash
|
||||
hashInput.insert(hashInput.end(), data + 96, data + len); // packed_content
|
||||
RNS::Bytes hashable(hashInput.data(), hashInput.size());
|
||||
msg.messageId = RNS::Identity::full_hash(hashable);
|
||||
msg.incoming = true;
|
||||
msg.status = LXMFStatus::DELIVERED;
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* LXMFMessage::statusStr() const {
|
||||
switch (status) {
|
||||
case LXMFStatus::DRAFT: return "draft";
|
||||
case LXMFStatus::QUEUED: return "queued";
|
||||
case LXMFStatus::SENDING: return "sending";
|
||||
case LXMFStatus::SENT: return "sent";
|
||||
case LXMFStatus::DELIVERED: return "delivered";
|
||||
case LXMFStatus::FAILED: return "failed";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "Bytes.h"
|
||||
#include "Identity.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
|
||||
enum class LXMFStatus : uint8_t {
|
||||
DRAFT = 0, QUEUED, SENDING, SENT, DELIVERED, FAILED
|
||||
};
|
||||
|
||||
struct LXMFMessage {
|
||||
RNS::Bytes sourceHash;
|
||||
RNS::Bytes destHash;
|
||||
double timestamp = 0;
|
||||
std::string content;
|
||||
std::string title;
|
||||
RNS::Bytes signature;
|
||||
|
||||
LXMFStatus status = LXMFStatus::DRAFT;
|
||||
bool incoming = false;
|
||||
bool read = false;
|
||||
int retries = 0;
|
||||
unsigned long lastRetryMs = 0;
|
||||
uint32_t savedCounter = 0;
|
||||
uint32_t receiveCounter = 0; // Monotonic receive order (used by Ratcom)
|
||||
RNS::Bytes messageId;
|
||||
|
||||
static std::vector<uint8_t> packContent(double timestamp, const std::string& content, const std::string& title);
|
||||
std::vector<uint8_t> packFull(const RNS::Identity& signingIdentity);
|
||||
static bool unpackFull(const uint8_t* data, size_t len, LXMFMessage& msg);
|
||||
const char* statusStr() const;
|
||||
};
|
||||
+117
-92
@@ -281,6 +281,16 @@ void Link::prove() {
|
||||
const Bytes signature(_object->_owner.identity().sign(signed_data));
|
||||
|
||||
Bytes proof_data = signature + _object->_pub_bytes + signalling_bytes;
|
||||
|
||||
// Diagnostic: dump proof components for cross-implementation debugging
|
||||
VERBOSEF("[LINK-PROOF] link_id: %s", _object->_link_id.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] pub_bytes: %s", _object->_pub_bytes.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] sig_pub: %s", _object->_sig_pub_bytes.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] signalling: %s (mtu=%d mode=%d)", signalling_bytes.toHex().c_str(), _object->_mtu, _object->_mode);
|
||||
VERBOSEF("[LINK-PROOF] signed_data: %s (%d bytes)", signed_data.toHex().c_str(), (int)signed_data.size());
|
||||
VERBOSEF("[LINK-PROOF] signature: %s", signature.toHex().c_str());
|
||||
VERBOSEF("[LINK-PROOF] proof_data: %d bytes", (int)proof_data.size());
|
||||
|
||||
// CBA LINK
|
||||
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
|
||||
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||
@@ -1014,6 +1024,7 @@ void Link::receive(const Packet& packet) {
|
||||
}
|
||||
|
||||
if (packet.packet_type() == Type::Packet::DATA) {
|
||||
VERBOSEF("[LINK-RX] context=0x%02X status=%d initiator=%d", (int)packet.context(), (int)_object->_status, _object->_initiator);
|
||||
bool should_query = false;
|
||||
switch (packet.context()) {
|
||||
case Type::Packet::CONTEXT_NONE:
|
||||
@@ -1141,98 +1152,79 @@ void Link::receive(const Packet& packet) {
|
||||
teardown_packet(packet);
|
||||
break;
|
||||
}
|
||||
/*z
|
||||
case Type::Packet::RESOURCE_ADV:
|
||||
{
|
||||
//p packet.plaintext = decrypt(packet.data)
|
||||
// Resource advertisement — decrypt and accept if strategy allows
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
const_cast<Packet&>(packet).plaintext(plaintext);
|
||||
if (ResourceAdvertisement::is_request(packet)) {
|
||||
Resource::accept(packet, callback=_object->_request_resource_concluded);
|
||||
}
|
||||
else if (ResourceAdvertisement::is_response(packet)) {
|
||||
Bytes request_id = ResourceAdvertisement::read_request_id(packet)
|
||||
for (auto& pending_request : _object->_pending_requests) {
|
||||
if (pending_request.request_id == request_id) {
|
||||
const Bytes response_resource = Resource::accept(packet, callback=_object->_response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id);
|
||||
if (response_resource) {
|
||||
//p if pending_request.response_size == None:
|
||||
if (pending_request.response_size == 0) {
|
||||
pending_request.response_size = ResourceAdvertisement::read_size(packet);
|
||||
ResourceAdvertisement adv;
|
||||
if (ResourceAdvertisement::unpack(plaintext, adv)) {
|
||||
if (_object->_resource_strategy == Type::Link::ACCEPT_ALL
|
||||
|| _object->_resource_strategy == Type::Link::ACCEPT_APP) {
|
||||
// Accept the resource
|
||||
auto inbound = std::make_shared<InboundResource>();
|
||||
if (inbound->init(adv, *this)) {
|
||||
_object->_inbound_resources.push_back(inbound);
|
||||
// Send initial request
|
||||
Bytes req = inbound->get_initial_request();
|
||||
if (req.size() > 0) {
|
||||
Bytes encrypted = encrypt(req);
|
||||
if (encrypted) {
|
||||
Packet req_packet(*this, encrypted, Type::Packet::DATA, Type::Packet::RESOURCE_REQ);
|
||||
req_packet.send();
|
||||
had_outbound(true);
|
||||
}
|
||||
//p if pending_request.response_transfer_size == None:
|
||||
if (pending_request.response_transfer_size == 0) {
|
||||
pending_request.response_transfer_size = 0;
|
||||
}
|
||||
pending_request.response_transfer_size += ResourceAdvertisement::read_transfer_size(packet);
|
||||
//p if pending_request.started_at == None:
|
||||
if (pending_request.started_at == 0.0) {
|
||||
pending_request.started_at = OS::time();
|
||||
}
|
||||
pending_request.response_resource_progress(response_resource);
|
||||
}
|
||||
DEBUGF("Accepted inbound resource, %d parts", (int)adv.num_parts);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (_object->_resource_strategy == ACCEPT_NONE) {
|
||||
//p pass
|
||||
}
|
||||
else if (_object->_resource_strategy == ACCEPT_APP) {
|
||||
if (_object->_callbacks.resource) {
|
||||
try {
|
||||
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext());
|
||||
resource_advertisement.link = *this;
|
||||
if (_object->_callbacks.resource(resource_advertisement)) {
|
||||
Resource::accept(packet, _object->_callbacks.resource_concluded);
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Error while executing resource accept callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
elif _object->_resource_strategy == ACCEPT_ALL:
|
||||
RNS.Resource.accept(packet, _object->_callbacks.resource_concluded)
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Type::Packet::RESOURCE_REQ:
|
||||
{
|
||||
// Resource request from receiver — send requested parts
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
if ord(plaintext[:1]) == RNS.Resource.HASHMAP_IS_EXHAUSTED:
|
||||
resource_hash = plaintext[1+RNS.Resource.MAPHASH_LEN:Type::Identity::HASHLENGTH//8+1+RNS.Resource.MAPHASH_LEN]
|
||||
else:
|
||||
resource_hash = plaintext[1:Type::Identity::HASHLENGTH//8+1]
|
||||
|
||||
for resource in _object->_outgoing_resources:
|
||||
if resource.hash == resource_hash:
|
||||
// We need to check that this request has not been
|
||||
// received before in order to avoid sequencing errors.
|
||||
if not packet.packet_hash in resource.req_hashlist:
|
||||
resource.req_hashlist.append(packet.packet_hash)
|
||||
resource.request(plaintext)
|
||||
for (auto& resource : _object->_outbound_resources) {
|
||||
auto indices = resource->handle_request(plaintext);
|
||||
for (size_t idx : indices) {
|
||||
Bytes part = resource->get_part(idx);
|
||||
if (part.size() > 0) {
|
||||
// Resource parts are NOT link-encrypted (already encrypted at resource level)
|
||||
Packet part_packet(*this, part, Type::Packet::DATA, Type::Packet::RESOURCE);
|
||||
part_packet.send();
|
||||
had_outbound(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Type::Packet::RESOURCE_HMU:
|
||||
{
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
resource_hash = plaintext[:Type::Identity::HASHLENGTH//8]
|
||||
for resource in _object->_incoming_resources:
|
||||
if resource_hash == resource.hash:
|
||||
resource.hashmap_update_packet(plaintext)
|
||||
// Hashmap update from receiver — currently not needed for basic transfer
|
||||
// (receiver sends ResourceReq which handles the same purpose)
|
||||
break;
|
||||
}
|
||||
case Type::Packet::RESOURCE_ICL:
|
||||
{
|
||||
// Initiator cancel — remove matching inbound resource
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
resource_hash = plaintext[:Type::Identity::HASHLENGTH//8]
|
||||
for resource in _object->_incoming_resources:
|
||||
if resource_hash == resource.hash:
|
||||
resource.cancel()
|
||||
if (plaintext && plaintext.size() >= 32) {
|
||||
Bytes resource_hash = plaintext.left(32);
|
||||
_object->_inbound_resources.erase(
|
||||
std::remove_if(_object->_inbound_resources.begin(),
|
||||
_object->_inbound_resources.end(),
|
||||
[&](const auto& r) {
|
||||
return memcmp(r->resource_hash(), resource_hash.data(), 32) == 0;
|
||||
}),
|
||||
_object->_inbound_resources.end()
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
*/
|
||||
case Type::Packet::KEEPALIVE:
|
||||
{
|
||||
if (!_object->_initiator && packet.data() == "\xFF") {
|
||||
@@ -1249,36 +1241,46 @@ void Link::receive(const Packet& packet) {
|
||||
// of hash -> sequence map
|
||||
case Type::Packet::RESOURCE:
|
||||
{
|
||||
for (auto& resource : _object->_incoming_resources) {
|
||||
//z resource.receive_part(packet);
|
||||
// Resource data part — NOT link-encrypted (encrypted at resource level)
|
||||
for (auto& resource : _object->_inbound_resources) {
|
||||
if (resource->receive_part(packet.data())) {
|
||||
if (resource->is_complete()) {
|
||||
// Assemble the resource
|
||||
Bytes assembled = resource->assemble(*this);
|
||||
if (assembled.size() > 0) {
|
||||
// Send proof back
|
||||
Bytes proof = resource->generate_proof();
|
||||
if (proof.size() > 0) {
|
||||
Bytes encrypted_proof = encrypt(proof);
|
||||
if (encrypted_proof) {
|
||||
Packet proof_packet(*this, encrypted_proof, Type::Packet::PROOF, Type::Packet::RESOURCE_PRF);
|
||||
proof_packet.send();
|
||||
had_outbound(true);
|
||||
}
|
||||
}
|
||||
// Store assembled data for later retrieval
|
||||
_object->_last_resource_data = assembled;
|
||||
DEBUGF("Inbound resource complete, %d bytes assembled", (int)assembled.size());
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
/*z
|
||||
case Type::Packet::CHANNEL:
|
||||
{
|
||||
//z if (!_object->_channel) {
|
||||
if (true) {
|
||||
DEBUG(f"Channel data received without open channel")
|
||||
}
|
||||
else {
|
||||
//z packet.prove();
|
||||
//z plaintext = decrypt(packet.data());
|
||||
//z if (plaintext) {
|
||||
//z _object->_channel._receive(plaintext);
|
||||
//z }
|
||||
}
|
||||
break;
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
// CHANNEL case — not yet implemented
|
||||
// case Type::Packet::CHANNEL: { break; }
|
||||
} // end switch(context)
|
||||
} // end if(DATA)
|
||||
else if (packet.packet_type() == Type::Packet::PROOF) {
|
||||
if (packet.context() == Type::Packet::RESOURCE_PRF) {
|
||||
Bytes resource_hash = packet.data().left(Type::Identity::HASHLENGTH/8);
|
||||
for (const auto& resource : _object->_outgoing_resources) {
|
||||
if (resource_hash == resource.hash()) {
|
||||
//z resource.validate_proof(packet.data());
|
||||
const Bytes plaintext = decrypt(packet.data());
|
||||
if (plaintext) {
|
||||
for (auto& resource : _object->_outbound_resources) {
|
||||
if (resource->handle_proof(plaintext)) {
|
||||
DEBUG("Outbound resource proof validated");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1445,7 +1447,30 @@ void Link::cancel_incoming_resource(const Resource& resource) {
|
||||
|
||||
bool Link::ready_for_new_resource() {
|
||||
assert(_object);
|
||||
return (_object->_outgoing_resources.size() > 0);
|
||||
return (_object->_outbound_resources.empty());
|
||||
}
|
||||
|
||||
bool Link::start_resource_transfer(const Bytes& data) {
|
||||
assert(_object);
|
||||
if (!ready_for_new_resource()) return false;
|
||||
|
||||
auto resource = std::make_shared<OutboundResource>();
|
||||
if (!resource->init(data, *this, true)) return false;
|
||||
|
||||
// Send advertisement
|
||||
ResourceAdvertisement adv = resource->get_advertisement();
|
||||
Bytes adv_packed = adv.pack();
|
||||
Bytes encrypted_adv = encrypt(adv_packed);
|
||||
if (!encrypted_adv) return false;
|
||||
|
||||
Packet adv_packet(*this, encrypted_adv, Type::Packet::DATA, Type::Packet::RESOURCE_ADV);
|
||||
adv_packet.send();
|
||||
had_outbound(true);
|
||||
|
||||
_object->_outbound_resources.push_back(resource);
|
||||
DEBUGF("Started outbound resource transfer, %d parts, %d bytes",
|
||||
(int)resource->num_parts(), (int)adv.transfer_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Link::toString() const {
|
||||
|
||||
@@ -226,6 +226,10 @@ namespace RNS {
|
||||
void cancel_incoming_resource(const Resource& resource);
|
||||
bool ready_for_new_resource();
|
||||
|
||||
/// Start an outbound resource transfer (for large messages).
|
||||
/// Encrypts data, chunks, computes hashmap, sends advertisement.
|
||||
bool start_resource_transfer(const Bytes& data);
|
||||
|
||||
//void __str__();
|
||||
std::string toString() const;
|
||||
|
||||
|
||||
+7
-2
@@ -13,6 +13,8 @@
|
||||
#include "Cryptography/Token.h"
|
||||
|
||||
#include <set>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace RNS {
|
||||
|
||||
@@ -98,8 +100,11 @@ namespace RNS {
|
||||
Bytes _shared_key;
|
||||
Bytes _derived_key;
|
||||
|
||||
std::set<Resource> _incoming_resources;
|
||||
std::set<Resource> _outgoing_resources;
|
||||
std::set<Resource> _incoming_resources; // Legacy (compatibility)
|
||||
std::set<Resource> _outgoing_resources; // Legacy (compatibility)
|
||||
std::vector<std::shared_ptr<InboundResource>> _inbound_resources;
|
||||
std::vector<std::shared_ptr<OutboundResource>> _outbound_resources;
|
||||
Bytes _last_resource_data; // Most recently assembled resource data
|
||||
std::set<RNS::RequestReceipt> _pending_requests;
|
||||
|
||||
friend class Link;
|
||||
|
||||
+15
-5
@@ -336,11 +336,12 @@ TRACEF("***** Link data: %s", _object->_ciphertext.toHex().c_str());
|
||||
_object->_ciphertext = _object->_destination.encrypt(_object->_data);
|
||||
TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
||||
}
|
||||
// CBA RATCHET
|
||||
/*p TODO
|
||||
if hasattr(self.destination, "latest_ratchet_id"):
|
||||
self.ratchet_id = self.destination.latest_ratchet_id
|
||||
*/
|
||||
{
|
||||
Bytes ratchet_pub = Identity::get_ratchet(_object->_destination.hash());
|
||||
if (ratchet_pub) {
|
||||
_object->_ratchet_id = Identity::full_hash(ratchet_pub).left(Type::Identity::NAME_HASH_LENGTH/8);
|
||||
}
|
||||
}
|
||||
_object->_encrypted = true;
|
||||
}
|
||||
}
|
||||
@@ -366,6 +367,15 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
||||
_object->_header << (uint8_t)_object->_context;
|
||||
_object->_raw = _object->_header + _object->_ciphertext;
|
||||
|
||||
if (_object->_raw.size() >= 4 && _object->_packet_type == DATA) {
|
||||
TRACEF("[DIAG] PACK: ht=%d tt=%d dt=%d pt=%d ctx=0x%02x flags=0x%02x raw=%dB [%02x %02x %02x %02x]",
|
||||
_object->_header_type, _object->_transport_type, _object->_destination.type(),
|
||||
_object->_packet_type, _object->_context, _object->_flags,
|
||||
(int)_object->_raw.size(),
|
||||
_object->_raw.data()[0], _object->_raw.data()[1],
|
||||
_object->_raw.data()[2], _object->_raw.data()[3]);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
+507
-95
@@ -1,122 +1,534 @@
|
||||
#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 "Compression/BZ2.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;
|
||||
|
||||
// Try bz2 compression (matches Python Resource.py:387-403)
|
||||
Bytes data_to_pack;
|
||||
if (auto_compress) {
|
||||
auto result = Compression::try_compress(plaintext);
|
||||
data_to_pack = result.data;
|
||||
_flags.compressed = result.compressed;
|
||||
} else {
|
||||
data_to_pack = plaintext;
|
||||
_flags.compressed = false;
|
||||
}
|
||||
|
||||
// Prepend 4-byte random_hash
|
||||
Bytes rh = Identity::get_random_hash();
|
||||
memcpy(_random_hash, rh.data(), 4);
|
||||
Bytes to_encrypt(_random_hash, 4);
|
||||
to_encrypt.append(data_to_pack.data(), data_to_pack.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 payload(decrypted.data() + 4, decrypted.size() - 4);
|
||||
|
||||
// Decompress if compressed (matches Python Resource.py assemble())
|
||||
Bytes plaintext;
|
||||
if (_flags.compressed) {
|
||||
plaintext = Compression::bz2_decompress(payload, _data_size * 2 + 4096);
|
||||
if (plaintext.size() == 0) {
|
||||
_status = ResourceStatus::CORRUPT;
|
||||
return Bytes();
|
||||
}
|
||||
} else {
|
||||
plaintext = payload;
|
||||
}
|
||||
|
||||
_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
@@ -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
|
||||
@@ -186,6 +186,7 @@ namespace RNS {
|
||||
|
||||
// CBA For access to private static members by Transport class
|
||||
friend class Transport;
|
||||
friend class Identity;
|
||||
};
|
||||
|
||||
}
|
||||
+150
-24
@@ -461,6 +461,11 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
|
||||
if (OS::time() > (_tables_last_culled + _tables_cull_interval)) {
|
||||
|
||||
// Deferred culls: run here instead of per-packet to avoid
|
||||
// O(n log n) sorting on every inbound announce.
|
||||
Identity::deferred_cull_known_destinations();
|
||||
cull_announce_table();
|
||||
|
||||
// CBA Disabled following since we're calling immediately after adding to path table now
|
||||
// Cull the path table if it has reached its max size
|
||||
//cull_path_table();
|
||||
@@ -620,6 +625,22 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
ERRORF("jobs: failed to cull discovery path requests: %s", e.what());
|
||||
}
|
||||
|
||||
// Cull the path requests table
|
||||
try {
|
||||
std::vector<Bytes> stale_path_requests;
|
||||
for (const auto& [destination_hash, timestamp] : _path_requests) {
|
||||
if (OS::time() > (timestamp + DESTINATION_TIMEOUT)) {
|
||||
stale_path_requests.push_back(destination_hash);
|
||||
}
|
||||
}
|
||||
for (const Bytes& destination_hash : stale_path_requests) {
|
||||
_path_requests.erase(destination_hash);
|
||||
}
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("jobs: failed to cull path requests: %s", e.what());
|
||||
}
|
||||
|
||||
// Cull the tunnel table
|
||||
try {
|
||||
count = 0;
|
||||
@@ -782,6 +803,10 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
auto& destination_entry = get_path(packet.destination_hash());
|
||||
if (packet.packet_type() != Type::Packet::ANNOUNCE && packet.destination().type() != Type::Destination::PLAIN && packet.destination().type() != Type::Destination::GROUP && destination_entry) {
|
||||
TRACE("Transport::outbound: Path to destination is known");
|
||||
TRACEF("[DIAG] OUTBOUND: path found dest=%.16s hops=%d rf=%.16s iface=%s",
|
||||
packet.destination_hash().toHex().c_str(), destination_entry._hops,
|
||||
destination_entry._received_from.toHex().c_str(),
|
||||
destination_entry.receiving_interface().toString().c_str());
|
||||
//outbound_interface = Transport.destination_table[packet.destination_hash][5]
|
||||
Interface outbound_interface = destination_entry.receiving_interface();
|
||||
|
||||
@@ -808,6 +833,8 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
new_raw << destination_entry._received_from;
|
||||
//new_raw += packet.raw[2:]
|
||||
new_raw << packet.raw().mid(2);
|
||||
TRACEF("[DIAG] OUTBOUND: H1->H2 wrap (transport hops>1) flags=0x%02x ti=%.16s",
|
||||
new_flags, destination_entry._received_from.toHex().c_str());
|
||||
transmit(outbound_interface, new_raw);
|
||||
//_path_table[packet.destination_hash][0] = time.time()
|
||||
destination_entry._timestamp = OS::time();
|
||||
@@ -852,6 +879,8 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
// simply transmit the packet directly on that one.
|
||||
else {
|
||||
TRACE("Transport::outbound: Sending packet over directly connected interface...");
|
||||
TRACEF("[DIAG] OUTBOUND: direct H1 send flags=0x%02x size=%d dest=%.16s",
|
||||
packet.flags(), (int)packet.raw().size(), packet.destination_hash().toHex().c_str());
|
||||
transmit(outbound_interface, packet.raw());
|
||||
sent = true;
|
||||
}
|
||||
@@ -862,6 +891,13 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
// interface, or belongs to a link.
|
||||
else {
|
||||
TRACE("Transport::outbound: Path to destination is unknown");
|
||||
TRACEF("[DIAG] OUTBOUND: NO PATH for dest=%.16s, broadcasting H1",
|
||||
packet.destination_hash().toHex().c_str());
|
||||
if (packet.packet_type() == Type::Packet::PROOF) {
|
||||
VERBOSEF("[DIAG-PROOF] Proof entering broadcast: dest=%s iface_count=%d attached=%s",
|
||||
packet.destination_hash().toHex().c_str(), (int)_interfaces.size(),
|
||||
packet.attached_interface() ? packet.attached_interface().toString().c_str() : "NONE");
|
||||
}
|
||||
bool stored_hash = false;
|
||||
for (auto& [hash, interface] : _interfaces) {
|
||||
TRACEF("Transport::outbound: Checking interface %s", interface.toString().c_str());
|
||||
@@ -1051,6 +1087,10 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
|
||||
if (should_transmit) {
|
||||
TRACE("Transport::outbound: Packet transmission allowed");
|
||||
if (packet.packet_type() == Type::Packet::PROOF) {
|
||||
VERBOSEF("[DIAG-PROOF] TRANSMITTING proof on %s (%d bytes)",
|
||||
interface.toString().c_str(), (int)packet.raw().size());
|
||||
}
|
||||
if (!stored_hash) {
|
||||
// CBA ACCUMULATES
|
||||
_packet_hashlist.insert(packet.packet_hash());
|
||||
@@ -1069,6 +1109,10 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
else {
|
||||
TRACE("Transport::outbound: Packet transmission refused");
|
||||
if (packet.packet_type() == Type::Packet::PROOF) {
|
||||
VERBOSEF("[DIAG-PROOF] REFUSED proof on %s (should_transmit=false)",
|
||||
interface.toString().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1094,8 +1138,10 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
// CBA ACCUMULATES
|
||||
_receipts.push_back(receipt);
|
||||
}
|
||||
|
||||
cache_packet(packet);
|
||||
|
||||
if (_transport_enabled) {
|
||||
cache_packet(packet);
|
||||
}
|
||||
}
|
||||
|
||||
_jobs_locked = false;
|
||||
@@ -1332,10 +1378,30 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
if (accept) {
|
||||
TRACE("Transport::inbound: Packet accepted by filter");
|
||||
// CBA ACCUMULATES
|
||||
_packet_hashlist.insert(packet.packet_hash());
|
||||
cache_packet(packet);
|
||||
|
||||
|
||||
// Defer hashlist insertion for packets belonging to links in
|
||||
// our link table, and for LRPROOF packets. On shared-medium
|
||||
// interfaces (e.g. LoRa), a packet may arrive on the "wrong"
|
||||
// interface first. Premature hash insertion would cause the
|
||||
// correct arrival to be filtered as a duplicate.
|
||||
// Reference: Python Transport.py lines 1362-1373
|
||||
bool remember_packet_hash = true;
|
||||
if (_link_table.find(packet.destination_hash()) != _link_table.end()) {
|
||||
remember_packet_hash = false;
|
||||
}
|
||||
if (packet.packet_type() == Type::Packet::PROOF && packet.context() == Type::Packet::LRPROOF) {
|
||||
remember_packet_hash = false;
|
||||
}
|
||||
if (remember_packet_hash) {
|
||||
// CBA ACCUMULATES
|
||||
_packet_hashlist.insert(packet.packet_hash());
|
||||
}
|
||||
|
||||
// Only cache packets on transport nodes (endpoints don't re-forward)
|
||||
if (_transport_enabled) {
|
||||
cache_packet(packet);
|
||||
}
|
||||
|
||||
// Check special conditions for local clients connected
|
||||
// through a shared Reticulum instance
|
||||
//p from_local_client = (packet.receiving_interface in Transport.local_client_interfaces)
|
||||
@@ -1357,7 +1423,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
}
|
||||
auto link_iter = _link_table.find(packet.destination_hash());
|
||||
if (link_iter != _link_table.end()) {
|
||||
LinkEntry link_entry = (*link_iter).second;
|
||||
LinkEntry& link_entry = (*link_iter).second;
|
||||
if (_local_client_interfaces.find(link_entry._receiving_interface) != _local_client_interfaces.end()) {
|
||||
// Destined for a local link
|
||||
for_local_client_link = true;
|
||||
@@ -1517,7 +1583,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
else {
|
||||
if (nh_mtu < path_mtu || (ph_mtu != 0 && ph_mtu < path_mtu)) {
|
||||
try {
|
||||
path_mtu = std::min(nh_mtu, ph_mtu);
|
||||
path_mtu = std::min(nh_mtu, (ph_mtu > 0) ? ph_mtu : nh_mtu);
|
||||
Bytes clamped_mtu = Link::signalling_bytes(path_mtu, mode);
|
||||
DEBUGF("Clamping link MTU to %u", path_mtu);
|
||||
new_raw = new_raw.left(new_raw.size()-Type::Link::LINK_MTU_SIZE)+clamped_mtu;
|
||||
@@ -1579,7 +1645,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
auto link_iter = _link_table.find(packet.destination_hash());
|
||||
if (link_iter != _link_table.end()) {
|
||||
TRACE("Transport::inbound: Found link entry, handling link transport");
|
||||
LinkEntry link_entry = (*link_iter).second;
|
||||
LinkEntry& link_entry = (*link_iter).second;
|
||||
// If receiving and outbound interface is
|
||||
// the same for this link, direction doesn't
|
||||
// matter, and we simply send the packet on.
|
||||
@@ -1625,6 +1691,8 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
new_raw << packet.raw().mid(2);
|
||||
transmit(outbound_interface, new_raw);
|
||||
link_entry._timestamp = OS::time();
|
||||
// Deferred hashlist insertion for link transport packets
|
||||
_packet_hashlist.insert(packet.packet_hash());
|
||||
}
|
||||
else {
|
||||
//p pass
|
||||
@@ -1642,6 +1710,26 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
// of queued announce rebroadcasts once handed to the next node.
|
||||
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
|
||||
TRACE("Transport::inbound: Packet is ANNOUNCE");
|
||||
|
||||
// Rate limit Ed25519 verification work: max 5 new verifies per second.
|
||||
// Known identities bypass verify via the fast path in validate_announce(),
|
||||
// so this only throttles the expensive crypto for NEW identities.
|
||||
{
|
||||
static double _verify_window_start = 0;
|
||||
static int _verify_count = 0;
|
||||
double now_s = OS::time();
|
||||
if (now_s - _verify_window_start >= 1.0) {
|
||||
_verify_window_start = now_s;
|
||||
_verify_count = 0;
|
||||
}
|
||||
// Check if this is a known identity (fast path won't need verify)
|
||||
bool is_known = (bool)Identity::recall(packet.destination_hash());
|
||||
if (!is_known && ++_verify_count > 5) {
|
||||
DEBUG("Transport::inbound: announce rate-limited (>5 new verifies/sec)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Bytes received_from;
|
||||
//p local_destination = next((d for d in Transport.destinations if d.hash == packet.destination_hash), None)
|
||||
auto iter = _destinations.find(packet.destination_hash());
|
||||
@@ -1874,6 +1962,7 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
if (iter != _pending_local_path_requests.end()) {
|
||||
//p desiring_interface = Transport.pending_local_path_requests.pop(packet.destination_hash)
|
||||
//const Interface& desiring_interface = (*iter).second;
|
||||
_pending_local_path_requests.erase(iter);
|
||||
retransmit_timeout = now;
|
||||
retries = PATHFINDER_R;
|
||||
|
||||
@@ -1985,10 +2074,15 @@ Transport::DestinationEntry empty_destination_entry;
|
||||
new_announce.send();
|
||||
}
|
||||
|
||||
// CBA Culling before adding to esnure table does not exceed maxsize
|
||||
TRACEF("Caching packet %s", packet.get_hash().toHex().c_str());
|
||||
if (RNS::Transport::cache_packet(packet, true)) {
|
||||
packet.cached(true);
|
||||
// Cache announce packet for transport nodes only.
|
||||
// Endpoints don't need cached packets — path table is persisted
|
||||
// separately via persist_data(). Caching here causes 0.5-2.3s
|
||||
// flash writes per announce that freeze endpoint devices.
|
||||
if (_transport_enabled) {
|
||||
TRACEF("Caching packet %s", packet.get_hash().toHex().c_str());
|
||||
if (RNS::Transport::cache_packet(packet, true)) {
|
||||
packet.cached(true);
|
||||
}
|
||||
}
|
||||
//TRACEF("Adding packet %s to packet table", packet.get_hash().toHex().c_str());
|
||||
//PacketEntry packet_entry(packet);
|
||||
@@ -2681,11 +2775,10 @@ Deregisters an announce handler.
|
||||
auto iter = _path_table.find(destination_hash);
|
||||
if (iter == _path_table.end()) return empty_destination_entry;
|
||||
DestinationEntry& destination_entry = (*iter).second;
|
||||
if (!destination_entry.announce_packet()) {
|
||||
DEBUGF("Entry for destination %s found but is missing announce packet, discarding", destination_hash.toHex().c_str());
|
||||
remove_path(destination_hash);
|
||||
return empty_destination_entry;
|
||||
}
|
||||
// Don't require announce_packet for basic routing — it's only needed for
|
||||
// path response forwarding. The routing fields (_received_from, _hops,
|
||||
// receiving_interface) are valid without it, and removing the path here
|
||||
// when deserialization fails under memory pressure breaks TCP outbound.
|
||||
if (!destination_entry.receiving_interface()) {
|
||||
DEBUGF("Entry for destination %s found but is missing receiving interface, discarding", destination_hash.toHex().c_str());
|
||||
remove_path(destination_hash);
|
||||
@@ -2723,13 +2816,14 @@ Deregisters an announce handler.
|
||||
:returns: The number of hops to the specified destination, or ``RNS.Transport.PATHFINDER_M`` if the number of hops is unknown.
|
||||
*/
|
||||
/*static*/ uint8_t Transport::hops_to(const Bytes& destination_hash) {
|
||||
auto& destination_entry = get_path(destination_hash);
|
||||
if (destination_entry) {
|
||||
return destination_entry._hops;
|
||||
}
|
||||
else {
|
||||
return PATHFINDER_M;
|
||||
// Direct path table lookup — avoids get_path() which triggers
|
||||
// expensive announce_packet lazy load from flash cache.
|
||||
// hops_to() only needs _hops which is already in memory.
|
||||
auto iter = _path_table.find(destination_hash);
|
||||
if (iter != _path_table.end()) {
|
||||
return (*iter).second._hops;
|
||||
}
|
||||
return PATHFINDER_M;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -3047,6 +3141,10 @@ will announce it.
|
||||
else if ((Reticulum::transport_enabled() || is_from_local_client) && destination_entry) {
|
||||
TRACEF("Transport::path_request_handler: entry found for destination %s", destination_hash.toHex().c_str());
|
||||
const Packet announce_packet = destination_entry.announce_packet();
|
||||
if (!announce_packet) {
|
||||
DEBUGF("Path entry for %s exists but announce packet unavailable (cache miss), cannot answer path request", destination_hash.toHex().c_str());
|
||||
}
|
||||
else {
|
||||
TRACEF("announce_packet destination_hash: %s", announce_packet.destination_hash().toHex().c_str());
|
||||
TRACEF("announce_packet hops: %u", announce_packet.hops());
|
||||
TRACEF("announce_packet str: %s", announce_packet.toString().c_str());
|
||||
@@ -3131,8 +3229,36 @@ TRACEF("announce_packet str: %s", announce_packet.toString().c_str());
|
||||
_announce_table.insert({announce_packet.destination_hash(), announce_entry});
|
||||
// CBA IMMEDIATE CULL
|
||||
cull_announce_table();
|
||||
|
||||
// Send PATH_RESPONSE immediately for local client requests
|
||||
// rather than waiting for the jobs() loop. On resource-
|
||||
// constrained platforms (e.g. ESP32), continuous TCP backbone
|
||||
// data can starve the cooperative jobs() loop for many
|
||||
// seconds, causing path discovery timeouts for local clients.
|
||||
if (is_from_local_client) {
|
||||
Identity imm_identity(Identity::recall(announce_packet.destination_hash()));
|
||||
if (imm_identity) {
|
||||
Destination imm_destination(imm_identity, Type::Destination::OUT, Type::Destination::SINGLE, announce_packet.destination_hash());
|
||||
Packet imm_packet(
|
||||
imm_destination,
|
||||
attached_interface,
|
||||
announce_packet.data(),
|
||||
Type::Packet::ANNOUNCE,
|
||||
Type::Packet::PATH_RESPONSE,
|
||||
Type::Transport::TRANSPORT,
|
||||
Type::Packet::HEADER_2,
|
||||
_identity.hash(),
|
||||
true,
|
||||
announce_packet.context_flag()
|
||||
);
|
||||
imm_packet.hops(announce_hops);
|
||||
imm_packet.send();
|
||||
_announce_table.erase(announce_packet.destination_hash());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // else (announce_packet valid)
|
||||
}
|
||||
else if (is_from_local_client) {
|
||||
// Forward path request on all interfaces
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "Memory.h"
|
||||
|
||||
#include <new>
|
||||
#include <cstring>
|
||||
|
||||
using namespace RNS;
|
||||
using namespace RNS::Utilities;
|
||||
@@ -23,7 +24,8 @@ using namespace RNS::Utilities;
|
||||
#endif
|
||||
|
||||
#ifndef RNS_HEAP_POOL_BUFFER_SIZE
|
||||
#define RNS_HEAP_POOL_BUFFER_SIZE 1024 * 1000
|
||||
//#define RNS_HEAP_POOL_BUFFER_SIZE 1024 * 80
|
||||
#define RNS_HEAP_POOL_BUFFER_SIZE 0
|
||||
#endif
|
||||
#ifndef RNS_PSRAM_POOL_BUFFER_SIZE
|
||||
#define RNS_PSRAM_POOL_BUFFER_SIZE 0
|
||||
@@ -79,7 +81,7 @@ using namespace RNS::Utilities;
|
||||
}
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
heap_pool_info.contiguous_size = dbgHeapFree();
|
||||
altheap_pool_info.buffer_size = dbgHeapFree();
|
||||
altheap_pool_info.contiguous_size = dbgHeapFree();
|
||||
TRACEF("TLSF: contiguous_size: %u", pool_info.contiguous_size);
|
||||
if (pool_info.buffer_size == 0) {
|
||||
pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace RNS { namespace Utilities {
|
||||
private:
|
||||
|
||||
struct pool_info {
|
||||
pool_info(uint8_t t, size_t s) : type(t), buffer_size(s) {}
|
||||
constexpr pool_info(uint8_t t, size_t s) : type(t), buffer_size(s) {}
|
||||
uint8_t type = 0;
|
||||
bool pool_init = false;
|
||||
size_t buffer_size = 0;
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
|
||||
using namespace RNS;
|
||||
|
||||
#if defined(BOARD_HAS_PSRAM) && defined(ESP32)
|
||||
/*static*/ RNS::Persistence::PsramAllocator _psramAllocatorImpl;
|
||||
/*static*/ JsonDocument _document(&_psramAllocatorImpl);
|
||||
#else
|
||||
/*static*/ //DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
||||
/*static*/ JsonDocument _document;
|
||||
#endif
|
||||
/*static*/ Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
||||
@@ -474,8 +474,31 @@ namespace RNS {
|
||||
|
||||
namespace RNS { namespace Persistence {
|
||||
|
||||
#if defined(BOARD_HAS_PSRAM) && defined(ESP32)
|
||||
// PSRAM allocator for ArduinoJson — prevents deserialization failures
|
||||
// under heap pressure (heap can be <1KB free while PSRAM has 8+ MB).
|
||||
class PsramAllocator : public ArduinoJson::Allocator {
|
||||
public:
|
||||
void* allocate(size_t size) override {
|
||||
void* p = ps_malloc(size);
|
||||
if (!p) p = malloc(size); // fallback to heap if PSRAM unavailable
|
||||
return p;
|
||||
}
|
||||
void deallocate(void* ptr) override {
|
||||
free(ptr); // free() handles both heap and PSRAM on ESP32
|
||||
}
|
||||
void* reallocate(void* ptr, size_t new_size) override {
|
||||
void* p = ps_realloc(ptr, new_size);
|
||||
if (!p) p = realloc(ptr, new_size); // fallback
|
||||
return p;
|
||||
}
|
||||
};
|
||||
static PsramAllocator _psramAllocator;
|
||||
static JsonDocument _document(&_psramAllocator);
|
||||
#else
|
||||
//static DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
||||
static JsonDocument _document;
|
||||
#endif
|
||||
static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
||||
|
||||
template <typename T> uint32_t crc(const T& obj) {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
/// Announce creation, parsing, and app_data handling tests.
|
||||
///
|
||||
/// Validates announce wire format matches Python/Rust implementations.
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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");
|
||||
}
|
||||
static void printHex(const char* label, const RNS::Bytes& data) { printHex(label, data.data(), data.size()); }
|
||||
|
||||
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_dest_hash;
|
||||
static RNS::Bytes g_name_hash;
|
||||
static bool g_init = false;
|
||||
|
||||
static void initFixture() {
|
||||
if (g_init) return;
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
g_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||
g_init = true;
|
||||
}
|
||||
|
||||
// ── Test 1: Announce pack ───────────────────────────────────────────
|
||||
|
||||
void testAnnouncePack() {
|
||||
initFixture();
|
||||
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||
|
||||
uint8_t random_hash[10];
|
||||
memset(random_hash, 0x42, 10);
|
||||
|
||||
// Build signed data: dest_hash(16) + pubkey(64) + name_hash(10) + random_hash(10)
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
TEST_ASSERT_EQUAL(64, sig.size());
|
||||
|
||||
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + sig(64)
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
|
||||
// Minimum announce = 148 bytes (no app_data, no ratchet)
|
||||
TEST_ASSERT_EQUAL(148, announce.size());
|
||||
|
||||
printf("\n=== ANNOUNCE_PACK ===\n");
|
||||
printHex("announce", announce.data(), announce.size());
|
||||
}
|
||||
|
||||
// ── Test 2: Announce unpack ─────────────────────────────────────────
|
||||
|
||||
void testAnnounceUnpack() {
|
||||
initFixture();
|
||||
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
uint8_t random_hash[10];
|
||||
memset(random_hash, 0x42, 10);
|
||||
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
|
||||
// Unpack: verify field offsets
|
||||
// [0..64] = pubkey, [64..74] = name_hash, [74..84] = random_hash, [84..148] = sig
|
||||
TEST_ASSERT_EQUAL_MEMORY(pubkey.data(), announce.data(), 64);
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_name_hash.data(), announce.data() + 64, 10);
|
||||
TEST_ASSERT_EQUAL_MEMORY(random_hash, announce.data() + 74, 10);
|
||||
TEST_ASSERT_EQUAL_MEMORY(sig.data(), announce.data() + 84, 64);
|
||||
|
||||
// Validate signature
|
||||
bool valid = g_identity.validate(
|
||||
RNS::Bytes(announce.data() + 84, 64),
|
||||
RNS::Bytes(signed_data.data(), signed_data.size())
|
||||
);
|
||||
TEST_ASSERT_TRUE(valid);
|
||||
}
|
||||
|
||||
// ── Test 3: Announce with ratchet ───────────────────────────────────
|
||||
|
||||
void testAnnounceWithRatchet() {
|
||||
initFixture();
|
||||
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
uint8_t random_hash[10];
|
||||
memset(random_hash, 0x42, 10);
|
||||
uint8_t ratchet_key[32];
|
||||
memset(ratchet_key, 0xAB, 32);
|
||||
|
||||
// With ratchet: signed_data includes ratchet between random_hash and signature
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
signed_data.insert(signed_data.end(), ratchet_key, ratchet_key + 32);
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
// Wire: pubkey(64) + name_hash(10) + random_hash(10) + ratchet(32) + sig(64)
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), ratchet_key, ratchet_key + 32);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
|
||||
// With ratchet: 148 + 32 = 180 bytes
|
||||
TEST_ASSERT_EQUAL(180, announce.size());
|
||||
|
||||
// Verify ratchet is at offset 84
|
||||
TEST_ASSERT_EQUAL_MEMORY(ratchet_key, announce.data() + 84, 32);
|
||||
// Signature at offset 116
|
||||
TEST_ASSERT_EQUAL_MEMORY(sig.data(), announce.data() + 116, 64);
|
||||
|
||||
printf("\n=== ANNOUNCE_WITH_RATCHET ===\n");
|
||||
printf(" size = %d bytes (148 base + 32 ratchet)\n", (int)announce.size());
|
||||
}
|
||||
|
||||
// ── Test 4: App data extraction (msgpack) ───────────────────────────
|
||||
|
||||
void testAppDataExtraction() {
|
||||
// Test extracting display name from Ratdeck msgpack format: fixarray(1)[bin8(name)]
|
||||
uint8_t app_data[] = {0x91, 0xC4, 0x04, 'T', 'e', 's', 't'}; // ["Test"]
|
||||
|
||||
// Parse: fixarray(1) → bin8(4) → "Test"
|
||||
TEST_ASSERT_EQUAL_UINT8(0x91, app_data[0]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, app_data[1]);
|
||||
TEST_ASSERT_EQUAL_UINT8(4, app_data[2]);
|
||||
|
||||
std::string name((const char*)app_data + 3, 4);
|
||||
TEST_ASSERT_EQUAL_STRING("Test", name.c_str());
|
||||
|
||||
// Also test raw UTF-8 format (Rust format)
|
||||
const char* utf8_data = "RustNode";
|
||||
std::string utf8_name(utf8_data);
|
||||
TEST_ASSERT_EQUAL_STRING("RustNode", utf8_name.c_str());
|
||||
}
|
||||
|
||||
// ── Test 5: Dest hash from identity ─────────────────────────────────
|
||||
|
||||
void testDestHashFromIdentity() {
|
||||
initFixture();
|
||||
|
||||
// dest_hash = truncated_hash(name_hash("lxmf.delivery") || identity.hash())
|
||||
RNS::Bytes nh = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes ih = g_identity.hash();
|
||||
RNS::Bytes addr = nh + ih;
|
||||
RNS::Bytes computed = RNS::Identity::truncated_hash(addr);
|
||||
|
||||
TEST_ASSERT_EQUAL(16, computed.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_dest_hash.data(), computed.data(), 16);
|
||||
|
||||
// Also verify for a different aspect name
|
||||
RNS::Bytes nh_prop = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes prop_dest = RNS::Identity::truncated_hash(nh_prop + ih);
|
||||
TEST_ASSERT_EQUAL(16, prop_dest.size());
|
||||
// Must be different from delivery dest
|
||||
TEST_ASSERT_FALSE(memcmp(g_dest_hash.data(), prop_dest.data(), 16) == 0);
|
||||
|
||||
printf("\n=== DEST_HASH ===\n");
|
||||
printHex("delivery_dest", g_dest_hash);
|
||||
printHex("propagation_dest", prop_dest);
|
||||
}
|
||||
|
||||
// ── Test 6: Name hash for multiple aspects ──────────────────────────
|
||||
|
||||
void testNameHashes() {
|
||||
RNS::Bytes nh1 = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes nh2 = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes nh3 = RNS::Identity::full_hash(RNS::Bytes("nomadnetwork.node")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
|
||||
TEST_ASSERT_EQUAL(10, nh1.size());
|
||||
TEST_ASSERT_EQUAL(10, nh2.size());
|
||||
TEST_ASSERT_EQUAL(10, nh3.size());
|
||||
|
||||
// All must be different
|
||||
TEST_ASSERT_FALSE(nh1 == nh2);
|
||||
TEST_ASSERT_FALSE(nh1 == nh3);
|
||||
TEST_ASSERT_FALSE(nh2 == nh3);
|
||||
|
||||
printf("\n=== NAME_HASHES ===\n");
|
||||
printHex("lxmf.delivery", nh1);
|
||||
printHex("lxmf.propagation", nh2);
|
||||
printHex("nomadnetwork.node", nh3);
|
||||
}
|
||||
|
||||
// ── Runner ──────────────────────────────────────────────────────────
|
||||
|
||||
void setUp() {}
|
||||
void tearDown() {}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testAnnouncePack);
|
||||
RUN_TEST(testAnnounceUnpack);
|
||||
RUN_TEST(testAnnounceWithRatchet);
|
||||
RUN_TEST(testAppDataExtraction);
|
||||
RUN_TEST(testDestHashFromIdentity);
|
||||
RUN_TEST(testNameHashes);
|
||||
return UNITY_END();
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
/// Cross-platform compatibility fixture generator for microReticulum (C++).
|
||||
///
|
||||
/// Computes deterministic values from known seeds and validates them.
|
||||
/// These same seeds and expected values are used by the Rust test suite
|
||||
/// in raticulum-tests/tests/cpp_fixture_compat.rs to prove byte-level
|
||||
/// interoperability between the C++ and Rust implementations.
|
||||
///
|
||||
/// Seeds:
|
||||
/// x25519_seed = SHA256("x25519_test_seed")
|
||||
/// ed25519_seed = SHA256("ed25519_test_seed")
|
||||
/// private_key = x25519_seed(32) || ed25519_seed(32)
|
||||
|
||||
#include <unity.h>
|
||||
|
||||
#include "Identity.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
#include "Cryptography/Ed25519.h"
|
||||
#include "Cryptography/X25519.h"
|
||||
#include "Cryptography/AES.h"
|
||||
#include "Cryptography/HMAC.h"
|
||||
#include "Cryptography/HKDF.h"
|
||||
#include "Cryptography/PKCS7.h"
|
||||
#include "Cryptography/Token.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
// ---- Inline MsgPack helpers (from ratdeck/src/reticulum/LXMFMessage.cpp) ----
|
||||
|
||||
static void mpPackFloat64(std::vector<uint8_t>& buf, double val) {
|
||||
buf.push_back(0xCB);
|
||||
uint64_t bits;
|
||||
memcpy(&bits, &val, 8);
|
||||
for (int i = 7; i >= 0; i--) {
|
||||
buf.push_back((bits >> (i * 8)) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||
size_t len = str.size();
|
||||
if (len < 256) {
|
||||
buf.push_back(0xC4);
|
||||
buf.push_back((uint8_t)len);
|
||||
} else {
|
||||
buf.push_back(0xC5);
|
||||
buf.push_back((len >> 8) & 0xFF);
|
||||
buf.push_back(len & 0xFF);
|
||||
}
|
||||
buf.insert(buf.end(), str.begin(), str.end());
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
static void printHex(const char* label, const RNS::Bytes& data) {
|
||||
printHex(label, data.data(), data.size());
|
||||
}
|
||||
|
||||
static void printHex(const char* label, const std::vector<uint8_t>& data) {
|
||||
printHex(label, data.data(), data.size());
|
||||
}
|
||||
|
||||
// ---- Global state computed once in setUp ----
|
||||
|
||||
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_x_seed;
|
||||
static RNS::Bytes g_ed_seed;
|
||||
static RNS::Bytes g_prv_key;
|
||||
static RNS::Bytes g_identity_hash;
|
||||
static RNS::Bytes g_x_pub;
|
||||
static RNS::Bytes g_ed_pub;
|
||||
static RNS::Bytes g_name_hash; // name_hash("lxmf.delivery")
|
||||
static RNS::Bytes g_dest_hash; // truncated_hash(name_hash + identity_hash)
|
||||
|
||||
// Deterministic LXMF message parts
|
||||
static const double FIXTURE_TIMESTAMP = 1700000000.0;
|
||||
static const std::string FIXTURE_TITLE = "Hello from C++";
|
||||
static const std::string FIXTURE_CONTENT = "Cross-platform test message";
|
||||
|
||||
static std::vector<uint8_t> g_packed_content;
|
||||
static RNS::Bytes g_signature;
|
||||
static std::vector<uint8_t> g_lxmf_wire;
|
||||
|
||||
// ---- Fixture setup ----
|
||||
|
||||
static bool g_initialized = false;
|
||||
|
||||
static void initFixture() {
|
||||
if (g_initialized) return;
|
||||
|
||||
// Deterministic seeds (same as Rust cross_compat.rs)
|
||||
g_x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
g_ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
|
||||
// Private key = x25519_seed(32) || ed25519_seed(32)
|
||||
g_prv_key = g_x_seed + g_ed_seed;
|
||||
|
||||
// Create identity from deterministic key
|
||||
g_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_identity.load_private_key(g_prv_key),
|
||||
"Failed to load deterministic private key");
|
||||
|
||||
g_identity_hash = g_identity.hash();
|
||||
g_x_pub = g_identity.encryptionPublicKey();
|
||||
g_ed_pub = g_identity.signingPublicKey();
|
||||
|
||||
// name_hash for "lxmf.delivery" = SHA256("lxmf.delivery")[:10]
|
||||
// Manual computation (avoids Destination.h → Link.h incomplete type issue)
|
||||
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
|
||||
// dest_hash = truncated_hash(name_hash + identity_hash)
|
||||
// This is how Destination::hash() works
|
||||
RNS::Bytes addr_material = g_name_hash + g_identity_hash;
|
||||
g_dest_hash = RNS::Identity::truncated_hash(addr_material);
|
||||
|
||||
// Pack LXMF content: fixarray(4) + float64(ts) + bin(title) + bin(content) + fixmap(0)
|
||||
g_packed_content.clear();
|
||||
g_packed_content.push_back(0x94); // fixarray of 4
|
||||
mpPackFloat64(g_packed_content, FIXTURE_TIMESTAMP);
|
||||
mpPackBin(g_packed_content, FIXTURE_TITLE);
|
||||
mpPackBin(g_packed_content, FIXTURE_CONTENT);
|
||||
g_packed_content.push_back(0x80); // empty fixmap
|
||||
|
||||
// Build signed_data = dest_hash + src_hash + packed + SHA256(dest_hash + src_hash + packed)
|
||||
// src_hash = identity_hash (we use same identity as sender)
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||
hashed_part.insert(hashed_part.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||
hashed_part.insert(hashed_part.end(), g_packed_content.begin(), g_packed_content.end());
|
||||
|
||||
RNS::Bytes hashed_bytes(hashed_part.data(), hashed_part.size());
|
||||
RNS::Bytes message_hash = RNS::Identity::full_hash(hashed_bytes);
|
||||
|
||||
std::vector<uint8_t> signed_data_vec;
|
||||
signed_data_vec.insert(signed_data_vec.end(), hashed_part.begin(), hashed_part.end());
|
||||
signed_data_vec.insert(signed_data_vec.end(), message_hash.data(), message_hash.data() + message_hash.size());
|
||||
|
||||
RNS::Bytes signed_data_bytes(signed_data_vec.data(), signed_data_vec.size());
|
||||
g_signature = g_identity.sign(signed_data_bytes);
|
||||
|
||||
// Build full LXMF wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||
g_lxmf_wire.clear();
|
||||
g_lxmf_wire.insert(g_lxmf_wire.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||
g_lxmf_wire.insert(g_lxmf_wire.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||
g_lxmf_wire.insert(g_lxmf_wire.end(), g_signature.data(), g_signature.data() + g_signature.size());
|
||||
g_lxmf_wire.insert(g_lxmf_wire.end(), g_packed_content.begin(), g_packed_content.end());
|
||||
|
||||
g_initialized = true;
|
||||
|
||||
// Print all fixture values for capture
|
||||
printf("\n=== C++ CROSS-COMPAT FIXTURE VALUES ===\n");
|
||||
printHex("x25519_seed", g_x_seed);
|
||||
printHex("ed25519_seed", g_ed_seed);
|
||||
printHex("x25519_pub", g_x_pub);
|
||||
printHex("ed25519_pub", g_ed_pub);
|
||||
printHex("identity_hash", g_identity_hash);
|
||||
printHex("name_hash_lxmf_delivery", g_name_hash);
|
||||
printHex("dest_hash", g_dest_hash);
|
||||
printHex("packed_content", g_packed_content);
|
||||
printHex("signature", g_signature);
|
||||
printHex("lxmf_wire", g_lxmf_wire);
|
||||
printf(" packed_content_len = %zu\n", g_packed_content.size());
|
||||
printf(" lxmf_wire_len = %zu\n", g_lxmf_wire.size());
|
||||
printf("=== END FIXTURE VALUES ===\n\n");
|
||||
}
|
||||
|
||||
// ---- Tests ----
|
||||
|
||||
void testIdentityHash() {
|
||||
initFixture();
|
||||
// Identity hash should be 16 bytes (truncated SHA256)
|
||||
TEST_ASSERT_EQUAL_INT(16, g_identity_hash.size());
|
||||
printf(" C++ identity_hash = %s\n", g_identity_hash.toHex().c_str());
|
||||
|
||||
// Verify identity hash = SHA256(x_pub || ed_pub)[:16]
|
||||
RNS::Bytes pub_combined = g_x_pub + g_ed_pub;
|
||||
RNS::Bytes expected = RNS::Identity::truncated_hash(pub_combined);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_identity_hash == expected,
|
||||
"Identity hash mismatch: SHA256(x_pub||ed_pub)[:16]");
|
||||
}
|
||||
|
||||
void testNameHash() {
|
||||
initFixture();
|
||||
// name_hash should be 10 bytes (NAME_HASH_LENGTH=80 bits)
|
||||
TEST_ASSERT_EQUAL_INT(10, g_name_hash.size());
|
||||
printf(" C++ name_hash(lxmf.delivery) = %s\n", g_name_hash.toHex().c_str());
|
||||
|
||||
// Verify: SHA256("lxmf.delivery")[:10]
|
||||
RNS::Bytes name_str("lxmf.delivery");
|
||||
RNS::Bytes expected = RNS::Identity::full_hash(name_str).left(10);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_name_hash == expected,
|
||||
"name_hash mismatch for lxmf.delivery");
|
||||
}
|
||||
|
||||
void testDestHash() {
|
||||
initFixture();
|
||||
TEST_ASSERT_EQUAL_INT(16, g_dest_hash.size());
|
||||
printf(" C++ dest_hash = %s\n", g_dest_hash.toHex().c_str());
|
||||
|
||||
// Verify: truncated_hash(name_hash + identity_hash)
|
||||
RNS::Bytes material = g_name_hash + g_identity_hash;
|
||||
RNS::Bytes expected = RNS::Identity::truncated_hash(material);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_dest_hash == expected,
|
||||
"dest_hash mismatch");
|
||||
}
|
||||
|
||||
void testPackedContent() {
|
||||
initFixture();
|
||||
// Verify packed content starts with fixarray(4) marker
|
||||
TEST_ASSERT_EQUAL_UINT8(0x94, g_packed_content[0]);
|
||||
// Followed by float64 marker
|
||||
TEST_ASSERT_EQUAL_UINT8(0xCB, g_packed_content[1]);
|
||||
// Verify title is bin-encoded (0xC4 for bin8)
|
||||
// After 1 (fixarray) + 9 (float64) = offset 10
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, g_packed_content[10]);
|
||||
printf(" C++ packed_content_len = %zu\n", g_packed_content.size());
|
||||
}
|
||||
|
||||
void testSignature() {
|
||||
initFixture();
|
||||
TEST_ASSERT_EQUAL_INT(64, g_signature.size());
|
||||
|
||||
// Verify signature: rebuild signed_data and validate
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||
hashed_part.insert(hashed_part.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||
hashed_part.insert(hashed_part.end(), g_packed_content.begin(), g_packed_content.end());
|
||||
|
||||
RNS::Bytes hashed_bytes(hashed_part.data(), hashed_part.size());
|
||||
RNS::Bytes message_hash = RNS::Identity::full_hash(hashed_bytes);
|
||||
|
||||
std::vector<uint8_t> signed_data_vec;
|
||||
signed_data_vec.insert(signed_data_vec.end(), hashed_part.begin(), hashed_part.end());
|
||||
signed_data_vec.insert(signed_data_vec.end(), message_hash.data(), message_hash.data() + message_hash.size());
|
||||
|
||||
RNS::Bytes signed_data_bytes(signed_data_vec.data(), signed_data_vec.size());
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_identity.validate(g_signature, signed_data_bytes),
|
||||
"Signature validation failed in C++");
|
||||
}
|
||||
|
||||
void testLxmfWireFormat() {
|
||||
initFixture();
|
||||
// Wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||
size_t expected_len = 16 + 16 + 64 + g_packed_content.size();
|
||||
TEST_ASSERT_EQUAL_INT(expected_len, g_lxmf_wire.size());
|
||||
|
||||
// Verify dest_hash at offset 0
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data(), g_dest_hash.data(), 16));
|
||||
// Verify src_hash at offset 16
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 16, g_identity_hash.data(), 16));
|
||||
// Verify signature at offset 32
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 32, g_signature.data(), 64));
|
||||
// Verify packed content at offset 96
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 96, g_packed_content.data(), g_packed_content.size()));
|
||||
}
|
||||
|
||||
void testAdditionalNameHashes() {
|
||||
initFixture();
|
||||
size_t nh_len = RNS::Type::Identity::NAME_HASH_LENGTH / 8; // 10 bytes
|
||||
|
||||
// Compute name hashes for other common aspect names (manually, same as Destination::name_hash)
|
||||
RNS::Bytes nh_prop = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(nh_len);
|
||||
RNS::Bytes nh_nn = RNS::Identity::full_hash(RNS::Bytes("nomadnetwork.node")).left(nh_len);
|
||||
|
||||
TEST_ASSERT_EQUAL_INT(10, nh_prop.size());
|
||||
TEST_ASSERT_EQUAL_INT(10, nh_nn.size());
|
||||
|
||||
printf(" C++ name_hash(lxmf.propagation) = %s\n", nh_prop.toHex().c_str());
|
||||
printf(" C++ name_hash(nomadnetwork.node) = %s\n", nh_nn.toHex().c_str());
|
||||
}
|
||||
|
||||
void testPacketFlagEncoding() {
|
||||
initFixture();
|
||||
// Test flag byte encoding: (header_type<<6) | (context_flag<<5) | (transport_type<<4) | (dest_type<<2) | packet_type
|
||||
// Header1, no context, broadcast, single, data = 0x00
|
||||
uint8_t flags_h1_data = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 0;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x00, flags_h1_data);
|
||||
|
||||
// Header1, no context, broadcast, single, announce = 0x01
|
||||
uint8_t flags_h1_announce = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 1;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x01, flags_h1_announce);
|
||||
|
||||
// Header2, no context, transport, single, data = 0x50
|
||||
uint8_t flags_h2_transport_data = (1 << 6) | (0 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x50, flags_h2_transport_data);
|
||||
|
||||
// Header2, context set, transport, single, data = 0x70
|
||||
uint8_t flags_h2_ctx_transport = (1 << 6) | (1 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x70, flags_h2_ctx_transport);
|
||||
|
||||
printf(" C++ flag encoding verified\n");
|
||||
}
|
||||
|
||||
void testAnnounceByteLayout() {
|
||||
initFixture();
|
||||
// Announce layout: [pubkey:64][name_hash:10][random_hash:10][signature:64][app_data...]
|
||||
// We construct it manually with deterministic random_hash
|
||||
|
||||
RNS::Bytes pub_key = g_identity.get_public_key(); // 64 bytes
|
||||
TEST_ASSERT_EQUAL_INT(64, pub_key.size());
|
||||
|
||||
// Use deterministic "random" hash
|
||||
RNS::Bytes random_hash = RNS::Cryptography::sha256(RNS::Bytes("deterministic_random")).left(10);
|
||||
|
||||
// signed_data = dest_hash + public_key + name_hash + random_hash
|
||||
RNS::Bytes signed_data;
|
||||
signed_data << g_dest_hash << pub_key << g_name_hash << random_hash;
|
||||
|
||||
RNS::Bytes sig = g_identity.sign(signed_data);
|
||||
TEST_ASSERT_EQUAL_INT(64, sig.size());
|
||||
|
||||
// Announce payload: pubkey(64) + name_hash(10) + random_hash(10) + signature(64) = 148 bytes minimum
|
||||
RNS::Bytes announce_data;
|
||||
announce_data << pub_key << g_name_hash << random_hash << sig;
|
||||
TEST_ASSERT_EQUAL_INT(148, announce_data.size());
|
||||
|
||||
// Verify byte offsets
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data(), pub_key.data(), 64));
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 64, g_name_hash.data(), 10));
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 74, random_hash.data(), 10));
|
||||
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 84, sig.data(), 64));
|
||||
|
||||
// Validate signature
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_identity.validate(sig, signed_data),
|
||||
"Announce signature validation failed");
|
||||
|
||||
printHex("random_hash", random_hash);
|
||||
printHex("announce_signed_data", signed_data);
|
||||
printHex("announce_signature", sig);
|
||||
printHex("announce_data", announce_data);
|
||||
printf(" announce_data_len = %zu\n", announce_data.size());
|
||||
}
|
||||
|
||||
void testEncryptDecryptRoundtrip() {
|
||||
initFixture();
|
||||
// Encrypt a known plaintext and verify we can decrypt it
|
||||
RNS::Bytes plaintext("secret from cpp fixture");
|
||||
RNS::Bytes ciphertext = g_identity.encrypt(plaintext);
|
||||
|
||||
// Verify format: ephemeral_pub(32) + token
|
||||
TEST_ASSERT_TRUE_MESSAGE(ciphertext.size() > 32 + 16 + 32,
|
||||
"Ciphertext too short");
|
||||
|
||||
RNS::Bytes decrypted = g_identity.decrypt(ciphertext);
|
||||
TEST_ASSERT_TRUE_MESSAGE(decrypted == plaintext,
|
||||
"Decrypt failed to recover plaintext");
|
||||
|
||||
printf(" C++ encrypt/decrypt roundtrip OK, ciphertext_len=%zu\n", ciphertext.size());
|
||||
}
|
||||
|
||||
// ---- Cross-encryption tests: C++ encrypts, Rust decrypts (and vice versa) ----
|
||||
|
||||
// Second identity for cross-encryption (simulates a remote peer)
|
||||
static RNS::Identity g_peer_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_peer_x_seed;
|
||||
static RNS::Bytes g_peer_ed_seed;
|
||||
static RNS::Bytes g_peer_x_pub;
|
||||
static RNS::Bytes g_peer_identity_hash;
|
||||
static RNS::Bytes g_cross_ciphertext;
|
||||
static RNS::Bytes g_cross_plaintext;
|
||||
|
||||
// Deterministic ECDH test: use known ephemeral key to verify shared secret
|
||||
static RNS::Bytes g_ecdh_ephemeral_prv_seed;
|
||||
static RNS::Bytes g_ecdh_ephemeral_pub;
|
||||
static RNS::Bytes g_ecdh_shared_secret;
|
||||
|
||||
static bool g_cross_initialized = false;
|
||||
|
||||
static RNS::Bytes clampX25519(const RNS::Bytes& key) {
|
||||
// RFC 7748 clamping — same as Curve25519::dh1() and x25519-dalek::mul_clamped()
|
||||
uint8_t buf[32];
|
||||
memcpy(buf, key.data(), 32);
|
||||
buf[0] &= 0xF8;
|
||||
buf[31] = (buf[31] & 0x7F) | 0x40;
|
||||
return RNS::Bytes(buf, 32);
|
||||
}
|
||||
|
||||
static void initCrossFixture() {
|
||||
initFixture();
|
||||
if (g_cross_initialized) return;
|
||||
|
||||
// Create a second identity (the "peer" / recipient)
|
||||
g_peer_x_seed = RNS::Cryptography::sha256(RNS::Bytes("peer_x25519_seed"));
|
||||
g_peer_ed_seed = RNS::Cryptography::sha256(RNS::Bytes("peer_ed25519_seed"));
|
||||
|
||||
// Clamp the X25519 seed to match production behavior.
|
||||
// In production, dh1() clamps keys at generation time. Curve25519::eval()
|
||||
// does NOT clamp internally, so imported keys must be pre-clamped for
|
||||
// cross-platform ECDH compatibility with x25519-dalek (which clamps in DH).
|
||||
g_peer_x_seed = clampX25519(g_peer_x_seed);
|
||||
|
||||
RNS::Bytes peer_prv = g_peer_x_seed + g_peer_ed_seed;
|
||||
|
||||
g_peer_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_peer_identity.load_private_key(peer_prv),
|
||||
"Failed to load peer private key");
|
||||
|
||||
g_peer_x_pub = g_peer_identity.encryptionPublicKey();
|
||||
g_peer_identity_hash = g_peer_identity.hash();
|
||||
|
||||
// Deterministic ephemeral key for cross-encryption
|
||||
g_ecdh_ephemeral_prv_seed = clampX25519(
|
||||
RNS::Cryptography::sha256(RNS::Bytes("deterministic_ephemeral_seed")));
|
||||
auto eph_prv = RNS::Cryptography::X25519PrivateKey::from_private_bytes(g_ecdh_ephemeral_prv_seed);
|
||||
g_ecdh_ephemeral_pub = eph_prv->public_key()->public_bytes();
|
||||
|
||||
// ECDH: ephemeral × peer_x_pub → shared secret for cross-encryption
|
||||
RNS::Bytes cross_shared = eph_prv->exchange(g_peer_x_pub);
|
||||
|
||||
// HKDF: derive_key_64(shared, peer_identity_hash)
|
||||
RNS::Bytes cross_derived = RNS::Cryptography::hkdf(64, cross_shared, g_peer_identity_hash);
|
||||
|
||||
// Deterministic Token encrypt: manually construct with known IV
|
||||
g_cross_plaintext = RNS::Bytes("cross-platform encryption test");
|
||||
RNS::Bytes cross_iv = RNS::Cryptography::sha256(RNS::Bytes("deterministic_iv")).left(16);
|
||||
RNS::Cryptography::Token cross_token(cross_derived);
|
||||
// We use the full Token encrypt (random IV) for C++ self-test, then manually
|
||||
// construct a deterministic version for the fixture.
|
||||
// Manual construction: PKCS7 pad → AES-256-CBC → HMAC
|
||||
RNS::Bytes padded = RNS::Cryptography::PKCS7::pad(g_cross_plaintext);
|
||||
RNS::Bytes signing_key = cross_derived.left(32);
|
||||
RNS::Bytes encryption_key = cross_derived.mid(32);
|
||||
RNS::Bytes aes_ct = RNS::Cryptography::AES_256_CBC::encrypt(padded, encryption_key, cross_iv);
|
||||
RNS::Bytes signed_parts = cross_iv + aes_ct;
|
||||
RNS::Bytes hmac = RNS::Cryptography::HMAC::generate(signing_key, signed_parts)->digest();
|
||||
RNS::Bytes token_bytes = signed_parts + hmac;
|
||||
|
||||
// Full ciphertext: ephemeral_pub(32) + token(IV+ct+HMAC)
|
||||
g_cross_ciphertext = g_ecdh_ephemeral_pub + token_bytes;
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_cross_ciphertext.size() == 112,
|
||||
"Deterministic cross ciphertext should be 112 bytes");
|
||||
|
||||
// Verify C++ can decrypt the deterministic ciphertext
|
||||
RNS::Bytes verify_pt = g_peer_identity.decrypt(g_cross_ciphertext);
|
||||
TEST_ASSERT_TRUE_MESSAGE(verify_pt == g_cross_plaintext,
|
||||
"C++ failed to decrypt deterministic cross ciphertext");
|
||||
|
||||
// Also test ECDH with the main identity's public key
|
||||
g_ecdh_shared_secret = eph_prv->exchange(g_x_pub);
|
||||
|
||||
// Verify commutativity
|
||||
RNS::Bytes reverse_shared = g_identity.prv()->exchange(g_ecdh_ephemeral_pub);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_shared_secret == reverse_shared,
|
||||
"ECDH commutativity failed in C++");
|
||||
|
||||
g_cross_initialized = true;
|
||||
|
||||
printf("\n=== C++ CROSS-ENCRYPTION FIXTURE VALUES ===\n");
|
||||
printHex("peer_x25519_seed", g_peer_x_seed);
|
||||
printHex("peer_ed25519_seed", g_peer_ed_seed);
|
||||
printHex("peer_x25519_pub", g_peer_x_pub);
|
||||
printHex("peer_identity_hash", g_peer_identity_hash);
|
||||
printHex("cross_ciphertext", g_cross_ciphertext);
|
||||
printf(" cross_ciphertext_len = %zu\n", g_cross_ciphertext.size());
|
||||
printf(" cross_plaintext = cross-platform encryption test\n");
|
||||
printHex("ecdh_ephemeral_seed", g_ecdh_ephemeral_prv_seed);
|
||||
printHex("ecdh_ephemeral_pub", g_ecdh_ephemeral_pub);
|
||||
printHex("ecdh_shared_secret", g_ecdh_shared_secret);
|
||||
printf("=== END CROSS-ENCRYPTION VALUES ===\n\n");
|
||||
}
|
||||
|
||||
void testCrossEncryptionFixture() {
|
||||
initCrossFixture();
|
||||
// This test just ensures the cross-encryption fixture values are generated
|
||||
// and C++ can self-roundtrip
|
||||
TEST_ASSERT_EQUAL_INT(32, g_peer_x_pub.size());
|
||||
TEST_ASSERT_EQUAL_INT(16, g_peer_identity_hash.size());
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_cross_ciphertext.size() > 80,
|
||||
"Cross ciphertext should be > 80 bytes");
|
||||
printf(" C++ cross-encryption fixture generated OK\n");
|
||||
}
|
||||
|
||||
void testEcdhDeterministic() {
|
||||
initCrossFixture();
|
||||
// Verify ECDH with known ephemeral key produces deterministic shared secret
|
||||
TEST_ASSERT_EQUAL_INT(32, g_ecdh_shared_secret.size());
|
||||
TEST_ASSERT_EQUAL_INT(32, g_ecdh_ephemeral_pub.size());
|
||||
|
||||
// Re-compute to verify determinism
|
||||
auto eph_prv2 = RNS::Cryptography::X25519PrivateKey::from_private_bytes(g_ecdh_ephemeral_prv_seed);
|
||||
RNS::Bytes eph_pub2 = eph_prv2->public_key()->public_bytes();
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_ephemeral_pub == eph_pub2,
|
||||
"Ephemeral public key derivation should be deterministic");
|
||||
RNS::Bytes shared2 = eph_prv2->exchange(g_x_pub);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_shared_secret == shared2,
|
||||
"ECDH should be deterministic");
|
||||
|
||||
printf(" C++ ECDH deterministic OK\n");
|
||||
}
|
||||
|
||||
// ---- Test runner ----
|
||||
|
||||
void setUp(void) {}
|
||||
void tearDown(void) {}
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testIdentityHash);
|
||||
RUN_TEST(testNameHash);
|
||||
RUN_TEST(testDestHash);
|
||||
RUN_TEST(testPackedContent);
|
||||
RUN_TEST(testSignature);
|
||||
RUN_TEST(testLxmfWireFormat);
|
||||
RUN_TEST(testAdditionalNameHashes);
|
||||
RUN_TEST(testPacketFlagEncoding);
|
||||
RUN_TEST(testAnnounceByteLayout);
|
||||
RUN_TEST(testEncryptDecryptRoundtrip);
|
||||
RUN_TEST(testCrossEncryptionFixture);
|
||||
RUN_TEST(testEcdhDeterministic);
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
return runUnityTests();
|
||||
}
|
||||
|
||||
#ifdef ARDUINO
|
||||
void setup() {
|
||||
delay(2000);
|
||||
runUnityTests();
|
||||
}
|
||||
void loop() {}
|
||||
#endif
|
||||
|
||||
void app_main() {
|
||||
runUnityTests();
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
/// End-to-end loopback tests for microReticulum C++ stack.
|
||||
///
|
||||
/// Tests the COMPLETE protocol flow using loopback interfaces:
|
||||
/// - LXMF message creation, signing, packing, unpacking
|
||||
/// - Resource transfer (outbound create → inbound assemble)
|
||||
/// - bz2 compression roundtrip + cross-platform fixtures
|
||||
/// - Announce with app_data and ratchet
|
||||
///
|
||||
/// No network or hardware needed — runs entirely on native platform.
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "LXMFMessage.h"
|
||||
#include "Resource.h"
|
||||
#include "Compression/BZ2.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||
printf(" %s = ", label);
|
||||
for (size_t i = 0; i < len && i < 32; i++) printf("%02x", data[i]);
|
||||
if (len > 32) printf("...");
|
||||
printf(" (%d bytes)\n", (int)len);
|
||||
}
|
||||
|
||||
// ---- Deterministic identity (same seeds as cross_compat) ----
|
||||
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_dest_hash;
|
||||
static RNS::Bytes g_name_hash;
|
||||
static bool g_init = false;
|
||||
|
||||
static void initFixture() {
|
||||
if (g_init) return;
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
g_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||
g_init = true;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 1: LXMF small message pack → unpack → verify
|
||||
// ============================================================
|
||||
|
||||
void testE2eSmallMessage() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "E2E Small";
|
||||
msg.content = "Hello from loopback!";
|
||||
|
||||
// Pack (opportunistic format)
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||
TEST_ASSERT_TRUE(payload.size() < 263); // Must fit in single packet
|
||||
|
||||
// Prepend dest_hash for unpack (direct format)
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), payload.begin(), payload.end());
|
||||
|
||||
// Unpack
|
||||
LXMFMessage received;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||
TEST_ASSERT_EQUAL_STRING("E2E Small", received.title.c_str());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello from loopback!", received.content.c_str());
|
||||
TEST_ASSERT_TRUE(fabs(received.timestamp - 1700000000.0) < 0.001);
|
||||
|
||||
printf("\n=== E2E_SMALL_MESSAGE ===\n");
|
||||
printf(" payload: %d bytes (fits single packet)\n", (int)payload.size());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 2: LXMF large message (would need resource transfer)
|
||||
// ============================================================
|
||||
|
||||
void testE2eLargeMessage() {
|
||||
initFixture();
|
||||
|
||||
// 500 chars — exceeds single-packet limit
|
||||
std::string big_content(500, 'L');
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "E2E Large";
|
||||
msg.content = big_content;
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 263); // Exceeds single packet
|
||||
|
||||
// Verify unpack still works for the LXMF layer
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), payload.begin(), payload.end());
|
||||
|
||||
LXMFMessage received;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||
TEST_ASSERT_EQUAL(500, received.content.size());
|
||||
TEST_ASSERT_EQUAL_STRING("E2E Large", received.title.c_str());
|
||||
|
||||
printf("\n=== E2E_LARGE_MESSAGE ===\n");
|
||||
printf(" payload: %d bytes (needs resource transfer)\n", (int)payload.size());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 3: LXMF message with image field
|
||||
// ============================================================
|
||||
|
||||
void testE2eImageField() {
|
||||
initFixture();
|
||||
|
||||
// Manually build packed content with FIELD_IMAGE
|
||||
std::vector<uint8_t> packed;
|
||||
packed.push_back(0x94); // fixarray(4)
|
||||
|
||||
// timestamp
|
||||
packed.push_back(0xCB);
|
||||
double ts = 1700000000.0;
|
||||
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||
|
||||
// title: bin8("Image E2E")
|
||||
packed.push_back(0xC4); packed.push_back(9);
|
||||
const char* title = "Image E2E";
|
||||
packed.insert(packed.end(), title, title + 9);
|
||||
|
||||
// content: bin8("Has image")
|
||||
packed.push_back(0xC4); packed.push_back(9);
|
||||
const char* content = "Has image";
|
||||
packed.insert(packed.end(), content, content + 9);
|
||||
|
||||
// fields: fixmap(1) { 0x06: fixarray(2)[bin("image/png"), bin(fake_data)] }
|
||||
packed.push_back(0x81);
|
||||
packed.push_back(0x06); // FIELD_IMAGE
|
||||
packed.push_back(0x92); // fixarray(2)
|
||||
// mime type
|
||||
packed.push_back(0xC4); packed.push_back(9);
|
||||
packed.insert(packed.end(), (uint8_t*)"image/png", (uint8_t*)"image/png" + 9);
|
||||
// fake PNG data
|
||||
uint8_t png[] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
packed.push_back(0xC4); packed.push_back(8);
|
||||
packed.insert(packed.end(), png, png + 8);
|
||||
|
||||
// Sign
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||
std::vector<uint8_t> signed_data(hashed_part);
|
||||
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
// Build wire
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||
|
||||
// Unpack
|
||||
LXMFMessage received;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||
TEST_ASSERT_EQUAL_STRING("Image E2E", received.title.c_str());
|
||||
|
||||
printf("\n=== E2E_IMAGE_FIELD ===\n");
|
||||
printf(" wire: %d bytes (with FIELD_IMAGE)\n", (int)wire.size());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 4: Resource advertisement → chunking → assembly
|
||||
// ============================================================
|
||||
|
||||
void testE2eResourceRoundtrip() {
|
||||
initFixture();
|
||||
|
||||
// Create test data (500 bytes — needs 2 SDU chunks)
|
||||
std::string test_data(500, 'R');
|
||||
RNS::Bytes plaintext((const uint8_t*)test_data.data(), test_data.size());
|
||||
|
||||
// Create a fake link for encryption (use identity's token encryption)
|
||||
// For this test, we skip link encryption and test the chunking/assembly directly
|
||||
|
||||
// Simulate sender: chunk the data
|
||||
size_t sdu = RNS::Type::Resource::SDU;
|
||||
size_t num_parts = (plaintext.size() + sdu - 1) / sdu;
|
||||
TEST_ASSERT_TRUE(num_parts >= 2); // Should need multiple chunks
|
||||
|
||||
std::vector<RNS::Bytes> chunks;
|
||||
for (size_t i = 0; i < num_parts; i++) {
|
||||
size_t offset = i * sdu;
|
||||
size_t chunk_len = std::min(sdu, plaintext.size() - offset);
|
||||
chunks.push_back(RNS::Bytes(plaintext.data() + offset, chunk_len));
|
||||
}
|
||||
|
||||
// Compute map hashes
|
||||
uint8_t random_hash[4] = {0xAA, 0xBB, 0xCC, 0xDD};
|
||||
RNS::Bytes hashmap;
|
||||
for (auto& chunk : chunks) {
|
||||
uint8_t mh[4];
|
||||
RNS::get_map_hash(chunk.data(), chunk.size(), random_hash, 4, mh);
|
||||
hashmap.append(mh, 4);
|
||||
}
|
||||
|
||||
// Create advertisement
|
||||
RNS::ResourceAdvertisement adv;
|
||||
adv.transfer_size = plaintext.size();
|
||||
adv.data_size = plaintext.size();
|
||||
adv.num_parts = num_parts;
|
||||
memset(adv.resource_hash, 0x11, 32);
|
||||
memcpy(adv.random_hash, random_hash, 4);
|
||||
memset(adv.original_hash, 0x11, 32);
|
||||
adv.hashmap = hashmap;
|
||||
adv.flags.encrypted = false; // Skip encryption for this test
|
||||
|
||||
// Simulate receiver: accept and receive parts
|
||||
RNS::InboundResource inbound;
|
||||
// Manual init (skipping link dependency)
|
||||
auto map_hashes = adv.get_map_hashes();
|
||||
TEST_ASSERT_EQUAL(num_parts, map_hashes.size());
|
||||
|
||||
// Verify each chunk's hash matches
|
||||
for (size_t i = 0; i < chunks.size(); i++) {
|
||||
uint8_t mh[4];
|
||||
RNS::get_map_hash(chunks[i].data(), chunks[i].size(), random_hash, 4, mh);
|
||||
TEST_ASSERT_EQUAL_MEMORY(map_hashes[i].data(), mh, 4);
|
||||
}
|
||||
|
||||
// Verify reassembly
|
||||
RNS::Bytes assembled;
|
||||
for (auto& chunk : chunks) {
|
||||
assembled.append(chunk.data(), chunk.size());
|
||||
}
|
||||
TEST_ASSERT_EQUAL(plaintext.size(), assembled.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(plaintext.data(), assembled.data(), plaintext.size());
|
||||
|
||||
printf("\n=== E2E_RESOURCE_ROUNDTRIP ===\n");
|
||||
printf(" data: %d bytes, chunks: %d, sdu: %d\n", (int)plaintext.size(), (int)num_parts, (int)sdu);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 5: bz2 compress → decompress roundtrip
|
||||
// ============================================================
|
||||
|
||||
void testE2eBz2Roundtrip() {
|
||||
// Test with LXMF-like content
|
||||
std::string msg_content(1000, 'M');
|
||||
RNS::Bytes data((const uint8_t*)msg_content.data(), msg_content.size());
|
||||
|
||||
RNS::Bytes compressed = RNS::Compression::bz2_compress(data);
|
||||
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||
TEST_ASSERT_TRUE(compressed.size() < data.size());
|
||||
|
||||
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||
TEST_ASSERT_EQUAL(data.size(), decompressed.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(data.data(), decompressed.data(), data.size());
|
||||
|
||||
printf("\n=== E2E_BZ2_ROUNDTRIP ===\n");
|
||||
printf(" original: %d, compressed: %d, ratio: %.1f%%\n",
|
||||
(int)data.size(), (int)compressed.size(),
|
||||
100.0 * compressed.size() / data.size());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 6: bz2 deterministic cross-platform fixture
|
||||
// ============================================================
|
||||
|
||||
void testE2eBz2DeterministicFixture() {
|
||||
// CRITICAL: This test generates a deterministic bz2 output that
|
||||
// Python and Rust MUST be able to decompress to the same input.
|
||||
//
|
||||
// Input: "AAAA" repeated 100 times (400 bytes)
|
||||
// Both Python's bz2.compress() and Rust's bzip2 crate produce
|
||||
// the same output for the same input with the same settings.
|
||||
|
||||
std::string input_str(400, 'A');
|
||||
RNS::Bytes input((const uint8_t*)input_str.data(), input_str.size());
|
||||
|
||||
RNS::Bytes compressed = RNS::Compression::bz2_compress(input);
|
||||
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||
|
||||
// BZh magic
|
||||
TEST_ASSERT_EQUAL_UINT8(0x42, compressed.data()[0]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0x5A, compressed.data()[1]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0x68, compressed.data()[2]);
|
||||
|
||||
printf("\n=== BZ2_DETERMINISTIC_FIXTURE ===\n");
|
||||
printf(" input: 400 bytes of 'A'\n");
|
||||
printf(" compressed_len: %d\n", (int)compressed.size());
|
||||
printf(" compressed_full = ");
|
||||
for (size_t i = 0; i < compressed.size(); i++) printf("%02x", compressed.data()[i]);
|
||||
printf("\n");
|
||||
|
||||
// Roundtrip verify
|
||||
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||
TEST_ASSERT_EQUAL(400, decompressed.size());
|
||||
for (size_t i = 0; i < 400; i++) {
|
||||
TEST_ASSERT_EQUAL_UINT8('A', decompressed.data()[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 7: Announce with ratchet key
|
||||
// ============================================================
|
||||
|
||||
void testE2eAnnounceWithRatchet() {
|
||||
initFixture();
|
||||
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
uint8_t random_hash[10];
|
||||
memset(random_hash, 0x42, 10);
|
||||
uint8_t ratchet_key[32];
|
||||
memset(ratchet_key, 0xAB, 32);
|
||||
|
||||
// Build signed data (with ratchet)
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
signed_data.insert(signed_data.end(), ratchet_key, ratchet_key + 32);
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + ratchet(32) + sig(64)
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), ratchet_key, ratchet_key + 32);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
|
||||
TEST_ASSERT_EQUAL(180, announce.size()); // 148 + 32 ratchet
|
||||
|
||||
// Verify signature
|
||||
bool valid = g_identity.validate(
|
||||
RNS::Bytes(announce.data() + 116, 64), // sig at offset 116
|
||||
RNS::Bytes(signed_data.data(), signed_data.size())
|
||||
);
|
||||
TEST_ASSERT_TRUE(valid);
|
||||
|
||||
printf("\n=== E2E_ANNOUNCE_RATCHET ===\n");
|
||||
printf(" announce: %d bytes (with 32-byte ratchet)\n", (int)announce.size());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// E2E Test 8: Full LXMF bidirectional (pack A→B, pack B→A)
|
||||
// ============================================================
|
||||
|
||||
void testE2eBidirectionalLxmf() {
|
||||
// Create two identities
|
||||
RNS::Bytes seed_a = RNS::Cryptography::sha256(RNS::Bytes("identity_a_seed_x25519"));
|
||||
RNS::Bytes seed_a2 = RNS::Cryptography::sha256(RNS::Bytes("identity_a_seed_ed25519"));
|
||||
RNS::Identity id_a(false);
|
||||
TEST_ASSERT_TRUE(id_a.load_private_key(seed_a + seed_a2));
|
||||
|
||||
RNS::Bytes seed_b = RNS::Cryptography::sha256(RNS::Bytes("identity_b_seed_x25519"));
|
||||
RNS::Bytes seed_b2 = RNS::Cryptography::sha256(RNS::Bytes("identity_b_seed_ed25519"));
|
||||
RNS::Identity id_b(false);
|
||||
TEST_ASSERT_TRUE(id_b.load_private_key(seed_b + seed_b2));
|
||||
|
||||
RNS::Bytes nh = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes dest_a = RNS::Identity::truncated_hash(nh + id_a.hash());
|
||||
RNS::Bytes dest_b = RNS::Identity::truncated_hash(nh + id_b.hash());
|
||||
|
||||
// A → B
|
||||
LXMFMessage msg_ab;
|
||||
msg_ab.destHash = dest_b;
|
||||
msg_ab.sourceHash = dest_a;
|
||||
msg_ab.timestamp = 1700000001.0;
|
||||
msg_ab.title = "Hello B";
|
||||
msg_ab.content = "Message from A to B";
|
||||
auto payload_ab = msg_ab.packFull(id_a);
|
||||
TEST_ASSERT_TRUE(payload_ab.size() > 0);
|
||||
|
||||
// B → A
|
||||
LXMFMessage msg_ba;
|
||||
msg_ba.destHash = dest_a;
|
||||
msg_ba.sourceHash = dest_b;
|
||||
msg_ba.timestamp = 1700000002.0;
|
||||
msg_ba.title = "Hello A";
|
||||
msg_ba.content = "Reply from B to A";
|
||||
auto payload_ba = msg_ba.packFull(id_b);
|
||||
TEST_ASSERT_TRUE(payload_ba.size() > 0);
|
||||
|
||||
// Unpack A→B at B
|
||||
std::vector<uint8_t> wire_ab;
|
||||
wire_ab.insert(wire_ab.end(), dest_b.data(), dest_b.data() + 16);
|
||||
wire_ab.insert(wire_ab.end(), payload_ab.begin(), payload_ab.end());
|
||||
LXMFMessage recv_ab;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire_ab.data(), wire_ab.size(), recv_ab));
|
||||
TEST_ASSERT_EQUAL_STRING("Hello B", recv_ab.title.c_str());
|
||||
|
||||
// Unpack B→A at A
|
||||
std::vector<uint8_t> wire_ba;
|
||||
wire_ba.insert(wire_ba.end(), dest_a.data(), dest_a.data() + 16);
|
||||
wire_ba.insert(wire_ba.end(), payload_ba.begin(), payload_ba.end());
|
||||
LXMFMessage recv_ba;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire_ba.data(), wire_ba.size(), recv_ba));
|
||||
TEST_ASSERT_EQUAL_STRING("Hello A", recv_ba.title.c_str());
|
||||
|
||||
printf("\n=== E2E_BIDIRECTIONAL_LXMF ===\n");
|
||||
printf(" A→B: %d bytes, B→A: %d bytes\n", (int)payload_ab.size(), (int)payload_ba.size());
|
||||
}
|
||||
|
||||
// ── Runner ──────────────────────────────────────────────────────────
|
||||
|
||||
void setUp() {}
|
||||
void tearDown() {}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testE2eSmallMessage);
|
||||
RUN_TEST(testE2eLargeMessage);
|
||||
RUN_TEST(testE2eImageField);
|
||||
RUN_TEST(testE2eResourceRoundtrip);
|
||||
RUN_TEST(testE2eBz2Roundtrip);
|
||||
RUN_TEST(testE2eBz2DeterministicFixture);
|
||||
RUN_TEST(testE2eAnnounceWithRatchet);
|
||||
RUN_TEST(testE2eBidirectionalLxmf);
|
||||
return UNITY_END();
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
/// LXMF Message codec tests — validates packing, unpacking, signing, and wire format.
|
||||
///
|
||||
/// Tests the LXMFMessage module using deterministic seeds (same as test_cross_compat).
|
||||
/// All tests run on native platform (no ESP32 hardware needed).
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "LXMFMessage.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// ---- Global state ----
|
||||
|
||||
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_dest_hash;
|
||||
static bool g_initialized = false;
|
||||
|
||||
static void initFixture() {
|
||||
if (g_initialized) return;
|
||||
|
||||
// Deterministic seeds (same as test_cross_compat)
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
RNS::Bytes prv_key = x_seed + ed_seed;
|
||||
|
||||
g_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE_MESSAGE(g_identity.load_private_key(prv_key), "Failed to load private key");
|
||||
|
||||
// dest_hash = truncated_hash(name_hash("lxmf.delivery") + identity_hash)
|
||||
RNS::Bytes name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
RNS::Bytes addr = name_hash + g_identity.hash();
|
||||
g_dest_hash = RNS::Identity::truncated_hash(addr);
|
||||
|
||||
g_initialized = true;
|
||||
}
|
||||
|
||||
// ── Test 1: Pack content roundtrip ──────────────────────────────────
|
||||
|
||||
void testPackContentRoundtrip() {
|
||||
initFixture();
|
||||
|
||||
auto packed = LXMFMessage::packContent(1700000000.0, "Test content", "Test Title");
|
||||
TEST_ASSERT_TRUE(packed.size() > 0);
|
||||
|
||||
// First byte = fixarray(4) = 0x94
|
||||
TEST_ASSERT_EQUAL_UINT8(0x94, packed[0]);
|
||||
// Second byte = float64 marker = 0xCB
|
||||
TEST_ASSERT_EQUAL_UINT8(0xCB, packed[1]);
|
||||
// Position 10 = title bin8 marker (after 1 + 9 float bytes)
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||
}
|
||||
|
||||
// ── Test 2: Pack content uses bin encoding ──────────────────────────
|
||||
|
||||
void testPackContentBinEncoding() {
|
||||
auto packed = LXMFMessage::packContent(0.0, "Hello", "Hi");
|
||||
|
||||
// Title "Hi" at position 10: bin8(0xC4) + len(2) + "Hi"
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||
TEST_ASSERT_EQUAL_UINT8(2, packed[11]);
|
||||
TEST_ASSERT_EQUAL_UINT8('H', packed[12]);
|
||||
TEST_ASSERT_EQUAL_UINT8('i', packed[13]);
|
||||
|
||||
// Content "Hello" at position 14: bin8(0xC4) + len(5) + "Hello"
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[14]);
|
||||
TEST_ASSERT_EQUAL_UINT8(5, packed[15]);
|
||||
TEST_ASSERT_EQUAL_UINT8('H', packed[16]);
|
||||
}
|
||||
|
||||
// ── Test 3: Pack full opportunistic wire format ─────────────────────
|
||||
|
||||
void testPackFullOpportunistic() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Hello from C++";
|
||||
msg.content = "Cross-platform test";
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||
|
||||
// Opportunistic: [src_hash:16][signature:64][packed_content]
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), payload.data(), 16);
|
||||
// packed_content starts at position 80 with 0x94
|
||||
TEST_ASSERT_EQUAL_UINT8(0x94, payload[80]);
|
||||
}
|
||||
|
||||
// ── Test 4: Pack full + prepend dest_hash for DIRECT format ─────────
|
||||
|
||||
void testPackFullDirect() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Direct test";
|
||||
msg.content = "With dest_hash";
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
|
||||
// Build direct format: [dest:16][payload]
|
||||
std::vector<uint8_t> direct;
|
||||
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||
|
||||
TEST_ASSERT_TRUE(direct.size() >= 96);
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_dest_hash.data(), direct.data(), 16);
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), direct.data() + 16, 16);
|
||||
}
|
||||
|
||||
// ── Test 5: Unpack full ─────────────────────────────────────────────
|
||||
|
||||
void testUnpackFull() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Unpack test";
|
||||
msg.content = "Verify round-trip";
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
|
||||
// Build direct format for unpackFull (it expects [dest:16][src:16][sig:64][packed])
|
||||
std::vector<uint8_t> direct;
|
||||
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||
|
||||
LXMFMessage unpacked;
|
||||
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||
TEST_ASSERT_TRUE(ok);
|
||||
TEST_ASSERT_EQUAL_STRING("Unpack test", unpacked.title.c_str());
|
||||
TEST_ASSERT_EQUAL_STRING("Verify round-trip", unpacked.content.c_str());
|
||||
TEST_ASSERT_TRUE(fabs(unpacked.timestamp - 1700000000.0) < 0.001);
|
||||
}
|
||||
|
||||
// ── Test 6: Signature verification ──────────────────────────────────
|
||||
|
||||
void testSignatureVerification() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Signed";
|
||||
msg.content = "Verify me";
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||
|
||||
// Extract signature from payload[16:80]
|
||||
RNS::Bytes sig(payload.data() + 16, 64);
|
||||
|
||||
// Reconstruct signed_data: dest + src + packed + SHA256(dest + src + packed)
|
||||
auto packed = LXMFMessage::packContent(msg.timestamp, msg.content, msg.title);
|
||||
RNS::Bytes hashed_part(32 + packed.size());
|
||||
memcpy(hashed_part.writable(hashed_part.size()), g_dest_hash.data(), 16);
|
||||
memcpy(hashed_part.writable(hashed_part.size()) + 16, g_identity.hash().data(), 16);
|
||||
memcpy(hashed_part.writable(hashed_part.size()) + 32, packed.data(), packed.size());
|
||||
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(hashed_part);
|
||||
RNS::Bytes signed_data = hashed_part + msgHash;
|
||||
|
||||
bool valid = g_identity.validate(sig, signed_data);
|
||||
TEST_ASSERT_TRUE(valid);
|
||||
}
|
||||
|
||||
// ── Test 7: Message ID computation ──────────────────────────────────
|
||||
|
||||
void testMessageIdComputation() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "ID test";
|
||||
msg.content = "Hash me";
|
||||
|
||||
msg.packFull(g_identity);
|
||||
TEST_ASSERT_EQUAL(32, msg.messageId.size());
|
||||
|
||||
// Pack same message again — messageId should be deterministic
|
||||
LXMFMessage msg2;
|
||||
msg2.destHash = g_dest_hash;
|
||||
msg2.sourceHash = g_identity.hash();
|
||||
msg2.timestamp = 1700000000.0;
|
||||
msg2.title = "ID test";
|
||||
msg2.content = "Hash me";
|
||||
msg2.packFull(g_identity);
|
||||
|
||||
TEST_ASSERT_EQUAL_MEMORY(msg.messageId.data(), msg2.messageId.data(), 32);
|
||||
}
|
||||
|
||||
// ── Test 8: Empty title and content ─────────────────────────────────
|
||||
|
||||
void testEmptyTitleAndContent() {
|
||||
auto packed = LXMFMessage::packContent(0.0, "", "");
|
||||
TEST_ASSERT_TRUE(packed.size() > 0);
|
||||
TEST_ASSERT_EQUAL_UINT8(0x94, packed[0]);
|
||||
// Empty bin: 0xC4 0x00
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0, packed[11]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[12]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0, packed[13]);
|
||||
}
|
||||
|
||||
// ── Test 9: Unicode content ─────────────────────────────────────────
|
||||
|
||||
void testUnicodeContent() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Unicode";
|
||||
msg.content = "Hello World"; // Keep ASCII for reliable cross-platform testing
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
|
||||
std::vector<uint8_t> direct;
|
||||
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||
|
||||
LXMFMessage unpacked;
|
||||
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||
TEST_ASSERT_TRUE(ok);
|
||||
TEST_ASSERT_EQUAL_STRING("Hello World", unpacked.content.c_str());
|
||||
}
|
||||
|
||||
// ── Test 10: Max size content (near opportunistic limit) ────────────
|
||||
|
||||
void testMaxSizeContent() {
|
||||
initFixture();
|
||||
|
||||
std::string bigContent(280, 'X');
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "";
|
||||
msg.content = bigContent;
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||
|
||||
std::vector<uint8_t> direct;
|
||||
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||
|
||||
LXMFMessage unpacked;
|
||||
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||
TEST_ASSERT_TRUE(ok);
|
||||
TEST_ASSERT_EQUAL(280, unpacked.content.size());
|
||||
}
|
||||
|
||||
// ── Runner ──────────────────────────────────────────────────────────
|
||||
|
||||
void setUp() {}
|
||||
void tearDown() {}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testPackContentRoundtrip);
|
||||
RUN_TEST(testPackContentBinEncoding);
|
||||
RUN_TEST(testPackFullOpportunistic);
|
||||
RUN_TEST(testPackFullDirect);
|
||||
RUN_TEST(testUnpackFull);
|
||||
RUN_TEST(testSignatureVerification);
|
||||
RUN_TEST(testMessageIdComputation);
|
||||
RUN_TEST(testEmptyTitleAndContent);
|
||||
RUN_TEST(testUnicodeContent);
|
||||
RUN_TEST(testMaxSizeContent);
|
||||
return UNITY_END();
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
/// Cross-platform LXMF interop fixture generator + validator.
|
||||
///
|
||||
/// Generates deterministic LXMF fixture values for Rust validation in
|
||||
/// raticulum-tests/tests/cpp_interop_fields.rs. All values use the same
|
||||
/// seeds as test_cross_compat for consistency.
|
||||
///
|
||||
/// Also validates C++ can unpack known Python/Rust-generated fixtures.
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "LXMFMessage.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// ---- Helpers (same as test_cross_compat) ----
|
||||
|
||||
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");
|
||||
}
|
||||
static void printHex(const char* label, const RNS::Bytes& data) { printHex(label, data.data(), data.size()); }
|
||||
static void printHex(const char* label, const std::vector<uint8_t>& data) { printHex(label, data.data(), data.size()); }
|
||||
|
||||
// ---- MsgPack helpers for field packing ----
|
||||
|
||||
static void mpPackBin(std::vector<uint8_t>& buf, const uint8_t* data, size_t len) {
|
||||
if (len < 256) { buf.push_back(0xC4); buf.push_back((uint8_t)len); }
|
||||
else { buf.push_back(0xC5); buf.push_back((len >> 8) & 0xFF); buf.push_back(len & 0xFF); }
|
||||
buf.insert(buf.end(), data, data + len);
|
||||
}
|
||||
|
||||
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||
mpPackBin(buf, (const uint8_t*)str.data(), str.size());
|
||||
}
|
||||
|
||||
// ---- Global fixture state ----
|
||||
|
||||
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||
static RNS::Bytes g_dest_hash;
|
||||
static RNS::Bytes g_name_hash;
|
||||
static bool g_init = false;
|
||||
|
||||
static void initFixture() {
|
||||
if (g_init) return;
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
g_identity = RNS::Identity(false);
|
||||
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||
g_init = true;
|
||||
}
|
||||
|
||||
// ── Test 1: LXMF with FIELD_IMAGE ───────────────────────────────────
|
||||
// Pack an LXMF message where the fields map contains FIELD_IMAGE (0x06)
|
||||
// as a msgpack array: [bin("image/png"), bin(fake_png_data)]
|
||||
|
||||
void testLxmfWithImageField() {
|
||||
initFixture();
|
||||
|
||||
// Build packed_content with IMAGE field in the fields map
|
||||
std::vector<uint8_t> packed;
|
||||
packed.push_back(0x94); // fixarray(4)
|
||||
|
||||
// timestamp
|
||||
packed.push_back(0xCB);
|
||||
double ts = 1700000000.0;
|
||||
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||
|
||||
// title: bin8("Image Test")
|
||||
mpPackBin(packed, "Image Test");
|
||||
// content: bin8("Has image field")
|
||||
mpPackBin(packed, "Has image field");
|
||||
|
||||
// fields: fixmap(1) { 0x06: fixarray(2)[bin("image/png"), bin(fake_png)] }
|
||||
packed.push_back(0x81); // fixmap(1)
|
||||
packed.push_back(0x06); // key = FIELD_IMAGE
|
||||
|
||||
// value = fixarray(2)
|
||||
packed.push_back(0x92);
|
||||
mpPackBin(packed, "image/png");
|
||||
uint8_t fake_png[] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00};
|
||||
mpPackBin(packed, fake_png, sizeof(fake_png));
|
||||
|
||||
// Build wire format: [dest:16][src:16][sig:64][packed]
|
||||
// Sign it
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||
|
||||
std::vector<uint8_t> signed_data(hashed_part);
|
||||
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
TEST_ASSERT_EQUAL(64, sig.size());
|
||||
|
||||
// Build full wire
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||
|
||||
printf("\n=== LXMF_IMAGE_FIELD ===\n");
|
||||
printHex("wire", wire);
|
||||
printHex("packed_content", packed);
|
||||
|
||||
// Self-validate: unpack and check title
|
||||
LXMFMessage unpacked;
|
||||
bool ok = LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked);
|
||||
TEST_ASSERT_TRUE(ok);
|
||||
TEST_ASSERT_EQUAL_STRING("Image Test", unpacked.title.c_str());
|
||||
}
|
||||
|
||||
// ── Test 2: LXMF with FIELD_FILE_ATTACHMENTS ────────────────────────
|
||||
|
||||
void testLxmfWithFileAttachment() {
|
||||
initFixture();
|
||||
|
||||
std::vector<uint8_t> packed;
|
||||
packed.push_back(0x94);
|
||||
|
||||
double ts = 1700000000.0;
|
||||
packed.push_back(0xCB);
|
||||
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||
|
||||
mpPackBin(packed, "File Test");
|
||||
mpPackBin(packed, "Has file attachment");
|
||||
|
||||
// fields: fixmap(1) { 0x05: fixarray(1)[fixarray(2)[bin("test.txt"), bin("file data")]] }
|
||||
packed.push_back(0x81); // fixmap(1)
|
||||
packed.push_back(0x05); // key = FIELD_FILE_ATTACHMENTS
|
||||
packed.push_back(0x91); // fixarray(1) — one attachment
|
||||
packed.push_back(0x92); // fixarray(2) — [filename, data]
|
||||
mpPackBin(packed, "test.txt");
|
||||
mpPackBin(packed, "Hello file content!");
|
||||
|
||||
// Sign and build wire
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||
std::vector<uint8_t> signed_data(hashed_part);
|
||||
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||
|
||||
printf("\n=== LXMF_FILE_FIELD ===\n");
|
||||
printHex("wire", wire);
|
||||
|
||||
LXMFMessage unpacked;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked));
|
||||
TEST_ASSERT_EQUAL_STRING("File Test", unpacked.title.c_str());
|
||||
}
|
||||
|
||||
// ── Test 3: LXMF with multiple fields ───────────────────────────────
|
||||
|
||||
void testLxmfWithMultipleFields() {
|
||||
initFixture();
|
||||
|
||||
std::vector<uint8_t> packed;
|
||||
packed.push_back(0x94);
|
||||
|
||||
double ts = 1700000000.0;
|
||||
packed.push_back(0xCB);
|
||||
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||
|
||||
mpPackBin(packed, "Multi-field");
|
||||
mpPackBin(packed, "Multiple fields test");
|
||||
|
||||
// fields: fixmap(2) { 0xFB: bin("custom-type"), 0xFC: bin("custom-data") }
|
||||
packed.push_back(0x82); // fixmap(2)
|
||||
packed.push_back(0xFB); // FIELD_CUSTOM_TYPE
|
||||
mpPackBin(packed, "application/x-test");
|
||||
packed.push_back(0xFC); // FIELD_CUSTOM_DATA
|
||||
uint8_t custom[] = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
mpPackBin(packed, custom, sizeof(custom));
|
||||
|
||||
// Sign
|
||||
std::vector<uint8_t> hashed_part;
|
||||
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||
std::vector<uint8_t> signed_data(hashed_part);
|
||||
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
std::vector<uint8_t> wire;
|
||||
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||
|
||||
printf("\n=== LXMF_MULTI_FIELDS ===\n");
|
||||
printHex("wire", wire);
|
||||
|
||||
LXMFMessage unpacked;
|
||||
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked));
|
||||
TEST_ASSERT_EQUAL_STRING("Multi-field", unpacked.title.c_str());
|
||||
}
|
||||
|
||||
// ── Test 4: Announce with UTF-8 app_data (Rust format) ──────────────
|
||||
|
||||
void testAnnounceUtf8AppData() {
|
||||
initFixture();
|
||||
|
||||
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + sig(64) + app_data
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||
|
||||
uint8_t random_hash[10] = {0xE8, 0xCC, 0xF9, 0xC8, 0xF9, 0xE1, 0xB0, 0xBA, 0xC6, 0xD5};
|
||||
std::string app_data = "TestNode"; // Raw UTF-8 — Rust dashboard format
|
||||
|
||||
// Build signed data: dest_hash + pubkey + name_hash + random_hash + app_data
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
signed_data.insert(signed_data.end(), app_data.begin(), app_data.end());
|
||||
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
// Build announce payload
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
announce.insert(announce.end(), app_data.begin(), app_data.end());
|
||||
|
||||
printf("\n=== ANNOUNCE_UTF8_APPDATA ===\n");
|
||||
printHex("announce", announce);
|
||||
printHex("app_data", (const uint8_t*)app_data.data(), app_data.size());
|
||||
printf(" app_data_str = %s\n", app_data.c_str());
|
||||
|
||||
// Verify: announce should be 148 + app_data bytes
|
||||
TEST_ASSERT_EQUAL(148 + app_data.size(), announce.size());
|
||||
}
|
||||
|
||||
// ── Test 5: Announce with msgpack app_data (Ratdeck format) ─────────
|
||||
|
||||
void testAnnounceMsgpackAppData() {
|
||||
initFixture();
|
||||
|
||||
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||
uint8_t random_hash[10] = {0xE8, 0xCC, 0xF9, 0xC8, 0xF9, 0xE1, 0xB0, 0xBA, 0xC6, 0xD5};
|
||||
|
||||
// Ratdeck format: fixarray(1)[bin8(name)]
|
||||
std::string name = "CppTestNode";
|
||||
std::vector<uint8_t> app_data;
|
||||
app_data.push_back(0x91); // fixarray(1)
|
||||
app_data.push_back(0xC4); // bin8
|
||||
app_data.push_back((uint8_t)name.size());
|
||||
app_data.insert(app_data.end(), name.begin(), name.end());
|
||||
|
||||
// Sign
|
||||
std::vector<uint8_t> signed_data;
|
||||
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||
signed_data.insert(signed_data.end(), app_data.begin(), app_data.end());
|
||||
|
||||
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||
|
||||
std::vector<uint8_t> announce;
|
||||
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||
announce.insert(announce.end(), app_data.begin(), app_data.end());
|
||||
|
||||
printf("\n=== ANNOUNCE_MSGPACK_APPDATA ===\n");
|
||||
printHex("announce", announce);
|
||||
printHex("app_data", app_data);
|
||||
|
||||
TEST_ASSERT_EQUAL(148 + app_data.size(), announce.size());
|
||||
}
|
||||
|
||||
// ── Test 6: Opportunistic wire format (no dest_hash) ────────────────
|
||||
|
||||
void testOpportunisticWireNoDestHash() {
|
||||
initFixture();
|
||||
|
||||
LXMFMessage msg;
|
||||
msg.destHash = g_dest_hash;
|
||||
msg.sourceHash = g_identity.hash();
|
||||
msg.timestamp = 1700000000.0;
|
||||
msg.title = "Opportunistic";
|
||||
msg.content = "No dest_hash in payload";
|
||||
|
||||
auto payload = msg.packFull(g_identity);
|
||||
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||
|
||||
// Opportunistic format: [src:16][sig:64][packed]
|
||||
// Verify NO dest_hash prefix
|
||||
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), payload.data(), 16);
|
||||
TEST_ASSERT_EQUAL_UINT8(0x94, payload[80]); // packed content starts here
|
||||
|
||||
printf("\n=== OPPORTUNISTIC_WIRE ===\n");
|
||||
printHex("payload", payload);
|
||||
printHex("dest_hash", g_dest_hash);
|
||||
printf(" dest_hash must be prepended by receiver before unpack\n");
|
||||
|
||||
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||
}
|
||||
|
||||
// ── Test 7: Signalling bytes packing ────────────────────────────────
|
||||
|
||||
void testSignallingBytesPacking() {
|
||||
// Python: signalling_value = (mtu & 0x1FFFFF) | (((mode << 5) & 0xE0) << 16)
|
||||
// Packed as 3-byte big-endian (skip first byte of u32)
|
||||
|
||||
uint8_t mode = 1; // AES_256_CBC
|
||||
uint32_t mtu = 500;
|
||||
|
||||
uint32_t value = (mtu & 0x1FFFFF) | ((((uint32_t)mode << 5) & 0xE0) << 16);
|
||||
uint8_t bytes[3];
|
||||
bytes[0] = (value >> 16) & 0xFF;
|
||||
bytes[1] = (value >> 8) & 0xFF;
|
||||
bytes[2] = value & 0xFF;
|
||||
|
||||
printf("\n=== SIGNALLING_BYTES ===\n");
|
||||
printf(" mode=%d mtu=%d\n", mode, mtu);
|
||||
printHex("signalling", bytes, 3);
|
||||
|
||||
// Expected: mode=1 → (1<<5)=0x20, mtu=500=0x1F4
|
||||
// value = 0x1F4 | (0x20 << 16) = 0x2001F4
|
||||
// bytes = [0x20, 0x01, 0xF4]
|
||||
TEST_ASSERT_EQUAL_UINT8(0x20, bytes[0]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0x01, bytes[1]);
|
||||
TEST_ASSERT_EQUAL_UINT8(0xF4, bytes[2]);
|
||||
|
||||
// Decode back
|
||||
uint32_t decoded_value = ((uint32_t)bytes[0] << 16) | ((uint32_t)bytes[1] << 8) | bytes[2];
|
||||
uint32_t decoded_mtu = decoded_value & 0x1FFFFF;
|
||||
uint8_t decoded_mode = (decoded_value >> 21) & 0x07;
|
||||
TEST_ASSERT_EQUAL(500, decoded_mtu);
|
||||
TEST_ASSERT_EQUAL(1, decoded_mode);
|
||||
}
|
||||
|
||||
// ── Test 8: Packet flag encoding ────────────────────────────────────
|
||||
|
||||
void testPacketFlagEncoding() {
|
||||
// Verify flag byte layout matches Python/Rust
|
||||
// flags = (header_type << 6) | (context_flag << 5) | (transport_type << 4) | (dest_type << 2) | packet_type
|
||||
|
||||
// Header1, Broadcast, Single, Data = 0x00
|
||||
uint8_t f1 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 0;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x00, f1);
|
||||
|
||||
// Header1, Broadcast, Single, Announce = 0x01
|
||||
uint8_t f2 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 1;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x01, f2);
|
||||
|
||||
// Header1, Broadcast, Single, LinkRequest = 0x02
|
||||
uint8_t f3 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 2;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x02, f3);
|
||||
|
||||
// Header1, Broadcast, Link, Proof = 0x0F (dest_type=Link=3, packet_type=Proof=3)
|
||||
uint8_t f4 = (0 << 6) | (0 << 5) | (0 << 4) | (3 << 2) | 3;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x0F, f4);
|
||||
|
||||
// Header2, Transport, Single, Data = 0x50
|
||||
uint8_t f5 = (1 << 6) | (0 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||
TEST_ASSERT_EQUAL_UINT8(0x50, f5);
|
||||
|
||||
printf("\n=== PACKET_FLAGS ===\n");
|
||||
printf(" H1_Broadcast_Single_Data = 0x%02x\n", f1);
|
||||
printf(" H1_Broadcast_Single_Announce = 0x%02x\n", f2);
|
||||
printf(" H1_Broadcast_Link_Proof = 0x%02x\n", f4);
|
||||
printf(" H2_Transport_Single_Data = 0x%02x\n", f5);
|
||||
}
|
||||
|
||||
// ── Test 9: Truncated hash lengths ──────────────────────────────────
|
||||
|
||||
void testTruncatedHashLengths() {
|
||||
// Dest hash = 16 bytes (128 bits)
|
||||
RNS::Bytes data("test data for hashing");
|
||||
RNS::Bytes truncated = RNS::Identity::truncated_hash(data);
|
||||
TEST_ASSERT_EQUAL(16, truncated.size());
|
||||
|
||||
// Full hash = 32 bytes (256 bits)
|
||||
RNS::Bytes full = RNS::Identity::full_hash(data);
|
||||
TEST_ASSERT_EQUAL(32, full.size());
|
||||
|
||||
// Name hash = 10 bytes (80 bits)
|
||||
RNS::Bytes name = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||
TEST_ASSERT_EQUAL(10, name.size());
|
||||
|
||||
// Truncated is prefix of full
|
||||
TEST_ASSERT_EQUAL_MEMORY(full.data(), truncated.data(), 16);
|
||||
|
||||
printf("\n=== HASH_LENGTHS ===\n");
|
||||
printf(" truncated_hash = %d bytes\n", (int)truncated.size());
|
||||
printf(" full_hash = %d bytes\n", (int)full.size());
|
||||
printf(" name_hash = %d bytes\n", (int)name.size());
|
||||
}
|
||||
|
||||
// ── Test 10: Header1 vs Header2 format ──────────────────────────────
|
||||
|
||||
void testHeaderFormats() {
|
||||
// Header1: [flags:1][hops:1][dest_hash:16][context:1] = 19 bytes
|
||||
uint8_t h1[19];
|
||||
h1[0] = 0x01; // flags: H1, Broadcast, Single, Announce
|
||||
h1[1] = 0x00; // hops
|
||||
memset(h1 + 2, 0xAA, 16); // dest_hash
|
||||
h1[18] = 0x00; // context: None
|
||||
TEST_ASSERT_EQUAL(19, sizeof(h1));
|
||||
|
||||
// Header2: [flags:1][hops:1][transport_id:16][dest_hash:16][context:1] = 35 bytes
|
||||
uint8_t h2[35];
|
||||
h2[0] = 0x50; // flags: H2, Transport, Single, Data
|
||||
h2[1] = 0x01; // hops
|
||||
memset(h2 + 2, 0xBB, 16); // transport_id
|
||||
memset(h2 + 18, 0xCC, 16); // dest_hash
|
||||
h2[34] = 0x00; // context: None
|
||||
TEST_ASSERT_EQUAL(35, sizeof(h2));
|
||||
|
||||
printf("\n=== HEADER_FORMATS ===\n");
|
||||
printf(" Header1 size = %d bytes\n", 19);
|
||||
printf(" Header2 size = %d bytes\n", 35);
|
||||
printHex("header1", h1, 19);
|
||||
printHex("header2", h2, 35);
|
||||
|
||||
TEST_ASSERT_TRUE(true);
|
||||
}
|
||||
|
||||
// ── Runner ──────────────────────────────────────────────────────────
|
||||
|
||||
void setUp() {}
|
||||
void tearDown() {}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testLxmfWithImageField);
|
||||
RUN_TEST(testLxmfWithFileAttachment);
|
||||
RUN_TEST(testLxmfWithMultipleFields);
|
||||
RUN_TEST(testAnnounceUtf8AppData);
|
||||
RUN_TEST(testAnnounceMsgpackAppData);
|
||||
RUN_TEST(testOpportunisticWireNoDestHash);
|
||||
RUN_TEST(testSignallingBytesPacking);
|
||||
RUN_TEST(testPacketFlagEncoding);
|
||||
RUN_TEST(testTruncatedHashLengths);
|
||||
RUN_TEST(testHeaderFormats);
|
||||
return UNITY_END();
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/// Protocol wire format edge cases and boundary condition tests.
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "Cryptography/Hashes.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// ── Test 1: Packet flag byte combinations ───────────────────────────
|
||||
|
||||
void testPacketFlagCombinations() {
|
||||
// flags = (header_type << 6) | (context_flag << 5) | (transport_type << 4) | (dest_type << 2) | packet_type
|
||||
|
||||
// Enumerate critical combinations
|
||||
struct FlagCase { uint8_t ht, cf, tt, dt, pt, expected; const char* name; };
|
||||
FlagCase cases[] = {
|
||||
{0, 0, 0, 0, 0, 0x00, "H1/BC/Single/Data"},
|
||||
{0, 0, 0, 0, 1, 0x01, "H1/BC/Single/Announce"},
|
||||
{0, 0, 0, 0, 2, 0x02, "H1/BC/Single/LinkReq"},
|
||||
{0, 0, 0, 0, 3, 0x03, "H1/BC/Single/Proof"},
|
||||
{0, 0, 0, 3, 3, 0x0F, "H1/BC/Link/Proof"},
|
||||
{1, 0, 1, 0, 0, 0x50, "H2/Tx/Single/Data"},
|
||||
{1, 1, 1, 0, 0, 0x70, "H2/Ctx/Tx/Single/Data"},
|
||||
{0, 1, 0, 0, 1, 0x21, "H1/Ctx/BC/Single/Announce"},
|
||||
};
|
||||
|
||||
for (auto& c : cases) {
|
||||
uint8_t flags = (c.ht << 6) | (c.cf << 5) | (c.tt << 4) | (c.dt << 2) | c.pt;
|
||||
TEST_ASSERT_EQUAL_UINT8_MESSAGE(c.expected, flags, c.name);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Test 2: Hash masking (Header1 == Header2 hash) ──────────────────
|
||||
|
||||
void testHashMasking() {
|
||||
// The hash of a packet must be the same whether it has Header1 or Header2.
|
||||
// This is achieved by masking the flags byte to only the lower 4 bits
|
||||
// and excluding hops and transport_id from the hash.
|
||||
|
||||
// Header1: [flags:1][hops:1][dest:16][ctx:1][data...]
|
||||
// Hash input: [flags & 0x0F][dest:16][ctx:1][data...]
|
||||
|
||||
uint8_t h1_flags = 0x00; // H1, BC, Single, Data
|
||||
uint8_t h2_flags = 0x50; // H2, Transport, Single, Data
|
||||
|
||||
// Lower nibble should be same
|
||||
TEST_ASSERT_EQUAL_UINT8(h1_flags & 0x0F, h2_flags & 0x0F);
|
||||
|
||||
// Build hashable part for Header1
|
||||
uint8_t dest[16]; memset(dest, 0xAA, 16);
|
||||
uint8_t ctx = 0x00;
|
||||
uint8_t payload[] = {1, 2, 3, 4, 5};
|
||||
|
||||
std::vector<uint8_t> hashable;
|
||||
hashable.push_back(h1_flags & 0x0F); // masked flags
|
||||
hashable.insert(hashable.end(), dest, dest + 16);
|
||||
hashable.push_back(ctx);
|
||||
hashable.insert(hashable.end(), payload, payload + 5);
|
||||
|
||||
RNS::Bytes hash1 = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||
|
||||
// Same hashable for "Header2" version (only lower nibble used)
|
||||
hashable[0] = h2_flags & 0x0F; // same lower nibble
|
||||
RNS::Bytes hash2 = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||
|
||||
TEST_ASSERT_EQUAL_MEMORY(hash1.data(), hash2.data(), 32);
|
||||
}
|
||||
|
||||
// ── Test 3: Hops don't affect hash ──────────────────────────────────
|
||||
|
||||
void testHopsDoNotAffectHash() {
|
||||
// Hops field is at byte index 1 and is excluded from hash computation.
|
||||
// Changing hops must NOT change the hash.
|
||||
|
||||
uint8_t dest[16]; memset(dest, 0xBB, 16);
|
||||
uint8_t ctx = 0x00;
|
||||
uint8_t payload[] = {0xDE, 0xAD};
|
||||
|
||||
// Hash input doesn't include hops
|
||||
std::vector<uint8_t> hashable;
|
||||
hashable.push_back(0x00); // flags lower nibble
|
||||
hashable.insert(hashable.end(), dest, dest + 16);
|
||||
hashable.push_back(ctx);
|
||||
hashable.insert(hashable.end(), payload, payload + 2);
|
||||
|
||||
RNS::Bytes hash = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||
|
||||
// Verify hash is 32 bytes
|
||||
TEST_ASSERT_EQUAL(32, hash.size());
|
||||
|
||||
// The hash should be the same regardless of what hops value is in the raw packet
|
||||
// (because hops aren't included in hashable)
|
||||
TEST_ASSERT_TRUE(true);
|
||||
}
|
||||
|
||||
// ── Test 4: MTU boundary ────────────────────────────────────────────
|
||||
|
||||
void testMTUBoundary() {
|
||||
// Reticulum MTU = 500 bytes
|
||||
// Encrypted MDU = 383 bytes (MTU - token overhead)
|
||||
// MDU = 464 bytes (MTU - header max size - IFAC min)
|
||||
const size_t MTU = 500;
|
||||
const size_t HEADER1_SIZE = 19;
|
||||
const size_t HEADER2_SIZE = 35;
|
||||
|
||||
// A packet at exactly MTU
|
||||
uint8_t packet[MTU];
|
||||
memset(packet, 0, MTU);
|
||||
packet[0] = 0x00; // flags
|
||||
packet[1] = 0x00; // hops
|
||||
TEST_ASSERT_EQUAL(MTU, sizeof(packet));
|
||||
|
||||
// Verify header sizes
|
||||
TEST_ASSERT_EQUAL(19, HEADER1_SIZE);
|
||||
TEST_ASSERT_EQUAL(35, HEADER2_SIZE);
|
||||
|
||||
// Max data in Header1 packet
|
||||
TEST_ASSERT_EQUAL(MTU - HEADER1_SIZE, 481);
|
||||
// Max data in Header2 packet
|
||||
TEST_ASSERT_EQUAL(MTU - HEADER2_SIZE, 465);
|
||||
}
|
||||
|
||||
// ── Test 5: Identity hash is truncated to 16 bytes ──────────────────
|
||||
|
||||
void testIdentityHashLength() {
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||
RNS::Identity id(false);
|
||||
TEST_ASSERT_TRUE(id.load_private_key(x_seed + ed_seed));
|
||||
|
||||
RNS::Bytes hash = id.hash();
|
||||
TEST_ASSERT_EQUAL(16, hash.size());
|
||||
|
||||
// Public key should be 64 bytes (X25519 32 + Ed25519 32)
|
||||
RNS::Bytes pubkey = id.get_public_key();
|
||||
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||
|
||||
// Identity hash = truncated_hash(pubkey) = SHA256(pubkey)[:16]
|
||||
RNS::Bytes computed = RNS::Identity::truncated_hash(pubkey);
|
||||
TEST_ASSERT_EQUAL_MEMORY(hash.data(), computed.data(), 16);
|
||||
}
|
||||
|
||||
// ── Test 6: Encrypt/decrypt roundtrip with token ────────────────────
|
||||
|
||||
void testEncryptDecryptRoundtrip() {
|
||||
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("encrypt_test_seed_1"));
|
||||
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("encrypt_test_seed_2"));
|
||||
RNS::Identity id(false);
|
||||
TEST_ASSERT_TRUE(id.load_private_key(x_seed + ed_seed));
|
||||
|
||||
RNS::Bytes plaintext("Hello encrypted world!");
|
||||
RNS::Bytes ciphertext = id.encrypt(plaintext);
|
||||
TEST_ASSERT_TRUE(ciphertext.size() > 0);
|
||||
|
||||
RNS::Bytes decrypted = id.decrypt(ciphertext);
|
||||
TEST_ASSERT_EQUAL(plaintext.size(), decrypted.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(plaintext.data(), decrypted.data(), plaintext.size());
|
||||
}
|
||||
|
||||
// ── Runner ──────────────────────────────────────────────────────────
|
||||
|
||||
void setUp() {}
|
||||
void tearDown() {}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testPacketFlagCombinations);
|
||||
RUN_TEST(testHashMasking);
|
||||
RUN_TEST(testHopsDoNotAffectHash);
|
||||
RUN_TEST(testMTUBoundary);
|
||||
RUN_TEST(testIdentityHashLength);
|
||||
RUN_TEST(testEncryptDecryptRoundtrip);
|
||||
return UNITY_END();
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/// Resource transfer tests — validates advertisement pack/unpack, map hashes,
|
||||
/// chunking, reassembly, and proof computation.
|
||||
|
||||
#include <unity.h>
|
||||
#include "Identity.h"
|
||||
#include "Resource.h"
|
||||
#include "Compression/BZ2.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);
|
||||
}
|
||||
|
||||
// ── Test 9: bz2 compress/decompress roundtrip ───────────────────────
|
||||
|
||||
void testBz2CompressDecompress() {
|
||||
// Create compressible data (repeated pattern)
|
||||
std::string repeated(1000, 'A');
|
||||
RNS::Bytes data((const uint8_t*)repeated.data(), repeated.size());
|
||||
|
||||
RNS::Bytes compressed = RNS::Compression::bz2_compress(data);
|
||||
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||
TEST_ASSERT_TRUE(compressed.size() < data.size()); // Should compress well
|
||||
|
||||
printf("\n=== BZ2_COMPRESS ===\n");
|
||||
printf(" original: %d bytes, compressed: %d bytes\n", (int)data.size(), (int)compressed.size());
|
||||
|
||||
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||
TEST_ASSERT_EQUAL(data.size(), decompressed.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(data.data(), decompressed.data(), data.size());
|
||||
}
|
||||
|
||||
// ── Test 10: try_compress only compresses if beneficial ─────────────
|
||||
|
||||
void testTryCompress() {
|
||||
// Highly compressible data
|
||||
std::string big(2000, 'X');
|
||||
RNS::Bytes compressible((const uint8_t*)big.data(), big.size());
|
||||
auto result = RNS::Compression::try_compress(compressible);
|
||||
TEST_ASSERT_TRUE(result.compressed);
|
||||
TEST_ASSERT_TRUE(result.data.size() < compressible.size());
|
||||
|
||||
// Small random-like data (may not compress)
|
||||
uint8_t random_data[50];
|
||||
for (int i = 0; i < 50; i++) random_data[i] = (uint8_t)(i * 37 + 13);
|
||||
RNS::Bytes small_data(random_data, 50);
|
||||
auto result2 = RNS::Compression::try_compress(small_data);
|
||||
// Either compressed or not — both are valid
|
||||
TEST_ASSERT_TRUE(result2.data.size() > 0);
|
||||
}
|
||||
|
||||
// ── Test 11: bz2 output matches Python/Rust format ──────────────────
|
||||
|
||||
void testBz2CrossPlatformFormat() {
|
||||
// bz2 compressed data always starts with "BZh" magic bytes
|
||||
std::string test_data = "Hello from C++ bz2 test!";
|
||||
RNS::Bytes data((const uint8_t*)test_data.data(), test_data.size());
|
||||
|
||||
// Need larger data for compression to be beneficial
|
||||
RNS::Bytes big_data;
|
||||
for (int i = 0; i < 50; i++) big_data.append(data.data(), data.size());
|
||||
|
||||
RNS::Bytes compressed = RNS::Compression::bz2_compress(big_data);
|
||||
TEST_ASSERT_TRUE(compressed.size() >= 3);
|
||||
|
||||
// BZ2 magic: "BZh" (0x42, 0x5A, 0x68)
|
||||
TEST_ASSERT_EQUAL_UINT8(0x42, compressed.data()[0]); // 'B'
|
||||
TEST_ASSERT_EQUAL_UINT8(0x5A, compressed.data()[1]); // 'Z'
|
||||
TEST_ASSERT_EQUAL_UINT8(0x68, compressed.data()[2]); // 'h'
|
||||
|
||||
printf("\n=== BZ2_CROSS_PLATFORM ===\n");
|
||||
printf(" original: %d bytes, compressed: %d bytes\n", (int)big_data.size(), (int)compressed.size());
|
||||
printf(" magic: %c%c%c (BZh)\n", compressed.data()[0], compressed.data()[1], compressed.data()[2]);
|
||||
|
||||
// Verify roundtrip
|
||||
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||
TEST_ASSERT_EQUAL(big_data.size(), decompressed.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(big_data.data(), decompressed.data(), big_data.size());
|
||||
}
|
||||
|
||||
// ── 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);
|
||||
RUN_TEST(testBz2CompressDecompress);
|
||||
RUN_TEST(testTryCompress);
|
||||
RUN_TEST(testBz2CrossPlatformFormat);
|
||||
return UNITY_END();
|
||||
}
|
||||
Reference in new issue
Block a user