-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmeshtastic_encoder.cpp
More file actions
615 lines (507 loc) · 17.4 KB
/
meshtastic_encoder.cpp
File metadata and controls
615 lines (507 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#include "meshtastic_encoder.h"
#include "aes_barebones.h"
#include <cstring>
#include <random>
#ifdef ARDUINO
#include <esp_random.h>
#include <Arduino.h> // For millis() and analogRead()
#else
#include <chrono>
#include <random>
// Provide millis() equivalent for non-Arduino platforms
static uint32_t millis() {
return (uint32_t)(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
#endif
const std::vector<uint8_t> MeshtasticEncoder::DEFAULT_PSK = {
0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59,
0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0x01
};
// Channel hash calculation
uint8_t MeshtasticEncoder::xorHash(const uint8_t* data, size_t len)
{
uint8_t h = 0;
for (size_t i = 0; i < len; i++)
{
h ^= data[i];
}
return h;
}
uint8_t MeshtasticEncoder::calculateChannelHash(const std::string& channel_name,
const std::vector<uint8_t>& psk)
{
// Use provided PSK or default
const std::vector<uint8_t>& key = psk.empty() ? DEFAULT_PSK : psk;
// Calculate hash: xorHash(channel_name) XOR xorHash(PSK)
uint8_t channel_hash = xorHash((const uint8_t*)channel_name.c_str(), channel_name.length());
uint8_t psk_hash = xorHash(key.data(), key.size());
return channel_hash ^ psk_hash;
}
// Protobuf encoding utilities
void MeshtasticEncoder::encodeVarint(std::vector<uint8_t>& buffer, uint64_t value)
{
while (value > 0x7F)
{
buffer.push_back((uint8_t)((value & 0x7F) | 0x80));
value >>= 7;
}
buffer.push_back((uint8_t)(value & 0x7F));
}
void MeshtasticEncoder::encodeFixed32(std::vector<uint8_t>& buffer, uint32_t value)
{
buffer.push_back((uint8_t)(value & 0xFF));
buffer.push_back((uint8_t)((value >> 8) & 0xFF));
buffer.push_back((uint8_t)((value >> 16) & 0xFF));
buffer.push_back((uint8_t)((value >> 24) & 0xFF));
}
void MeshtasticEncoder::encodeLengthDelimited(std::vector<uint8_t>& buffer,
uint32_t field_number,
const std::vector<uint8_t>& data)
{
// Field tag: (field_number << 3) | 2 (wire type 2 = length-delimited)
encodeVarint(buffer, (field_number << 3) | 2);
// Length (varint)
encodeVarint(buffer, data.size());
// Data
buffer.insert(buffer.end(), data.begin(), data.end());
}
void MeshtasticEncoder::encodeString(std::vector<uint8_t>& buffer,
uint32_t field_number,
const std::string& str)
{
std::vector<uint8_t> str_bytes(str.begin(), str.end());
encodeLengthDelimited(buffer, field_number, str_bytes);
}
void MeshtasticEncoder::encodeVarintField(std::vector<uint8_t>& buffer,
uint32_t field_number,
uint64_t value)
{
// Field tag: (field_number << 3) | 0 (wire type 0 = varint)
encodeVarint(buffer, (field_number << 3) | 0);
encodeVarint(buffer, value);
}
void MeshtasticEncoder::encodeFixed32Field(std::vector<uint8_t>& buffer,
uint32_t field_number,
uint32_t value)
{
// Field tag: (field_number << 3) | 5 (wire type 5 = fixed32)
encodeVarint(buffer, (field_number << 3) | 5);
encodeFixed32(buffer, value);
}
// Packet construction
std::vector<uint8_t> MeshtasticEncoder::buildHeader(uint32_t to_address,
uint32_t from_address,
uint32_t packet_id,
uint8_t flags,
uint8_t channel,
uint8_t next_hop,
uint8_t relay_node)
{
std::vector<uint8_t> header(16, 0);
// to_address (4 bytes, little-endian)
header[0] = to_address & 0xFF;
header[1] = (to_address >> 8) & 0xFF;
header[2] = (to_address >> 16) & 0xFF;
header[3] = (to_address >> 24) & 0xFF;
// from_address (4 bytes, little-endian)
header[4] = from_address & 0xFF;
header[5] = (from_address >> 8) & 0xFF;
header[6] = (from_address >> 16) & 0xFF;
header[7] = (from_address >> 24) & 0xFF;
// packet_id (4 bytes, little-endian)
header[8] = packet_id & 0xFF;
header[9] = (packet_id >> 8) & 0xFF;
header[10] = (packet_id >> 16) & 0xFF;
header[11] = (packet_id >> 24) & 0xFF;
// flags (1 byte)
header[12] = flags;
// channel (1 byte)
header[13] = channel;
// next_hop (1 byte)
header[14] = next_hop;
// relay_node (1 byte)
header[15] = relay_node;
return header;
}
std::vector<uint8_t> MeshtasticEncoder::buildNonce(uint32_t packet_id, uint32_t from_address)
{
std::vector<uint8_t> nonce(16, 0);
// Packet ID (4 bytes, little-endian)
nonce[0] = packet_id & 0xFF;
nonce[1] = (packet_id >> 8) & 0xFF;
nonce[2] = (packet_id >> 16) & 0xFF;
nonce[3] = (packet_id >> 24) & 0xFF;
// Zero padding (4 bytes) - already zero
// Sender Address (4 bytes, little-endian)
nonce[8] = from_address & 0xFF;
nonce[9] = (from_address >> 8) & 0xFF;
nonce[10] = (from_address >> 16) & 0xFF;
nonce[11] = (from_address >> 24) & 0xFF;
// Zero padding (4 bytes) - already zero
return nonce;
}
uint32_t MeshtasticEncoder::generatePacketId()
{
uint32_t id = 0;
#ifdef ARDUINO
// ESP32: Use hardware random number generator combined with multiple entropy sources
// 1. esp_random() - hardware RNG
// 2. millis() - time since boot (varies each boot)
// 3. ADC noise - read from floating analog pin for additional entropy
uint32_t r1 = esp_random();
uint32_t r2 = esp_random();
uint32_t r3 = esp_random();
uint32_t time_entropy = (uint32_t)millis(); // Time since boot (varies each boot)
// Read ADC noise for additional entropy
// Even reading from a connected pin (like battery) multiple times gives
// slight variations due to ADC noise, temperature, power supply ripple, etc.
// We read multiple times with delays to capture these variations
uint32_t adc_noise = 0;
for (int i = 0; i < 8; i++) {
// Read from battery pin (GPIO1) - even if connected, ADC has noise
// Multiple reads with delays capture temperature/power variations
uint16_t adc_val = analogRead(1); // Read ADC channel 1 (GPIO1 - battery)
adc_noise ^= ((uint32_t)adc_val << ((i % 4) * 8)) | ((uint32_t)adc_val >> (24 - (i % 4) * 8));
// Small delay to let ADC settle and capture different noise samples
delayMicroseconds(5);
}
// Debug output to verify randomness
Serial.printf("[PacketID] r1=0x%08X r2=0x%08X r3=0x%08X millis=%lu adc=0x%08X\n",
r1, r2, r3, (unsigned long)time_entropy, adc_noise);
// Combine all entropy sources with XOR and bit rotations
id = r1;
id ^= (r2 << 16) | (r2 >> 16); // Rotate r2
id ^= r3;
id ^= time_entropy;
id ^= (time_entropy << 16) | (time_entropy >> 16); // Rotate time_entropy
id ^= adc_noise;
id ^= (adc_noise << 8) | (adc_noise >> 24); // Rotate ADC noise
// Final mixing with another random value
id ^= esp_random();
#else
// macOS/other: Use std::random_device for randomness
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<uint32_t> dis(1, 0xFFFFFFFF);
id = dis(gen);
#endif
// Ensure non-zero
if (id == 0)
{
// If still zero, use a combination of time and a constant
id = (uint32_t)(millis() ^ 0x12345678);
if (id == 0) id = 1;
}
return id;
}
bool MeshtasticEncoder::encryptPayload(const std::vector<uint8_t>& plaintext,
std::vector<uint8_t>& ciphertext,
uint32_t packet_id,
uint32_t from_address,
const std::vector<uint8_t>& psk)
{
// Build nonce
std::vector<uint8_t> nonce = buildNonce(packet_id, from_address);
// Use provided PSK or default
const std::vector<uint8_t>& key = psk.empty() ? DEFAULT_PSK : psk;
if (key.size() != 16)
{
return false;
}
// Initialize AES
AES128Barebones aes;
aes.setKey(key.data());
// Encrypt (CTR mode - encryption and decryption are the same)
ciphertext.resize(plaintext.size());
aes.decryptCTR(plaintext.data(),
ciphertext.data(),
plaintext.size(),
nonce.data());
return true;
}
// Text message encoding
MeshtasticEncoder::EncodedPacket MeshtasticEncoder::encodeTextMessage(
const TextMessage& msg,
uint32_t from_address,
const std::string& channel_name,
const std::vector<uint8_t>& psk)
{
EncodedPacket result;
result.success = false;
// Validate input
if (msg.text.empty() || msg.text.size() > 240)
{
result.error_message = "Text message must be 1-240 characters";
return result;
}
// Generate packet ID
uint32_t packet_id = generatePacketId();
// Build protobuf payload
// Structure: 08 [port=1] 12 [length] [text_data]
std::vector<uint8_t> payload;
// Field 1: port (varint) = 1 (TEXT_MESSAGE_APP)
encodeVarintField(payload, 1, 1);
// Field 2: payload (length-delimited) containing text
std::vector<uint8_t> text_bytes(msg.text.begin(), msg.text.end());
encodeLengthDelimited(payload, 2, text_bytes);
// Field 7: request_id (fixed32) - packet_id of message being replied to
if (msg.request_id != 0)
{
encodeFixed32Field(payload, 7, msg.request_id);
}
// Field 8: reply_id (fixed32)
if (msg.reply_id != 0)
{
encodeFixed32Field(payload, 8, msg.reply_id);
}
// Field 9: want_response (bool varint)
if (msg.want_response)
{
encodeVarintField(payload, 9, 1);
}
// Encrypt payload
std::vector<uint8_t> encrypted_payload;
if (!encryptPayload(payload, encrypted_payload, packet_id, from_address, psk))
{
result.error_message = "Failed to encrypt payload";
return result;
}
// Build header
// Flags byte encoding (from Meshtastic protocol):
// Bits 0-2: current hop_limit (remaining hops)
// Bits 5-7: hop_start (original hop limit)
// For a new packet: hop_limit = hop_start = msg.hop_limit
uint8_t flags = (msg.hop_limit & 0x07) | ((msg.hop_limit & 0x07) << 5);
uint8_t next_hop = 0;
uint8_t relay_node = 0;
// Channel: Calculate hash from channel_name if provided, otherwise use msg.channel as hash
// NOTE: Channel 0 is special - it indicates PKI/private encryption (Meshtastic protocol)
// For private messages: channel=0 (PKI), encryption uses private PSK
// For public messages: channel=hash (e.g. 0x55 for "EdgeFastLow"), encryption uses public PSK
uint8_t channel;
if (!channel_name.empty()) {
// If channel_name is provided, calculate hash using the PSK (for public messages)
channel = calculateChannelHash(channel_name, psk);
} else {
// Use msg.channel directly
// Channel 0 means PKI/private encryption - keep it as 0, don't convert!
channel = msg.channel;
}
std::vector<uint8_t> header = buildHeader(msg.to_address,
from_address,
packet_id,
flags,
channel,
next_hop,
relay_node);
// Combine header + encrypted payload
result.data = header;
result.data.insert(result.data.end(),
encrypted_payload.begin(),
encrypted_payload.end());
result.success = true;
return result;
}
// NodeInfo encoding
MeshtasticEncoder::EncodedPacket MeshtasticEncoder::encodeNodeInfo(
const NodeInfo& nodeinfo,
uint32_t from_address,
const std::string& channel_name,
const std::vector<uint8_t>& psk)
{
EncodedPacket result;
result.success = false;
// Validate input
if (nodeinfo.node_id == 0)
{
result.error_message = "Node ID cannot be zero";
return result;
}
// Generate packet ID
uint32_t packet_id = generatePacketId();
// Build User protobuf message
std::vector<uint8_t> user_protobuf;
// Field 1: id (string)
if (!nodeinfo.id.empty())
{
encodeString(user_protobuf, 1, nodeinfo.id);
}
// Field 2: long_name (string)
if (!nodeinfo.long_name.empty())
{
encodeString(user_protobuf, 2, nodeinfo.long_name);
}
// Field 3: short_name (string)
if (!nodeinfo.short_name.empty())
{
encodeString(user_protobuf, 3, nodeinfo.short_name);
}
// Field 5: hw_model (varint enum)
if (nodeinfo.hw_model != 0)
{
encodeVarintField(user_protobuf, 5, nodeinfo.hw_model);
}
// Field 6: is_licensed (bool varint)
encodeVarintField(user_protobuf, 6, nodeinfo.is_licensed ? 1 : 0);
// Field 7: role (varint enum)
if (nodeinfo.role != 0)
{
encodeVarintField(user_protobuf, 7, nodeinfo.role);
}
// Field 8: public_key (bytes, 32 bytes)
std::vector<uint8_t> public_key_bytes(nodeinfo.public_key, nodeinfo.public_key + 32);
encodeLengthDelimited(user_protobuf, 8, public_key_bytes);
// Field 9: is_unmessagable (bool varint)
encodeVarintField(user_protobuf, 9, nodeinfo.is_unmessagable ? 1 : 0);
// Build Data protobuf message
// Structure: 08 [port=4] 12 [length] [user_protobuf_data]
std::vector<uint8_t> payload;
// Field 1: port (varint) = 4 (NODEINFO_APP)
encodeVarintField(payload, 1, 4);
// Field 2: payload (length-delimited) containing User protobuf
encodeLengthDelimited(payload, 2, user_protobuf);
// Encrypt payload
std::vector<uint8_t> encrypted_payload;
if (!encryptPayload(payload, encrypted_payload, packet_id, from_address, psk))
{
result.error_message = "Failed to encrypt payload";
return result;
}
// Build header
// Flags byte encoding (from Meshtastic protocol):
// Bits 0-2: current hop_limit (remaining hops)
// Bits 5-7: hop_start (original hop limit)
// For a new packet: hop_limit = hop_start = nodeinfo.hop_limit
uint8_t flags = (nodeinfo.hop_limit & 0x07) | ((nodeinfo.hop_limit & 0x07) << 5);
uint8_t next_hop = 0;
uint8_t relay_node = 0;
// Calculate channel hash from channel_name (like sivu does)
uint8_t channel = channel_name.empty() ? calculateChannelHash("EdgeFastLow", psk) : calculateChannelHash(channel_name, psk);
std::vector<uint8_t> header = buildHeader(0xFFFFFFFF, // Broadcast
from_address,
packet_id,
flags,
channel,
next_hop,
relay_node);
// Combine header + encrypted payload
result.data = header;
result.data.insert(result.data.end(),
encrypted_payload.begin(),
encrypted_payload.end());
result.success = true;
return result;
}
// Position encoding
MeshtasticEncoder::EncodedPacket MeshtasticEncoder::encodePosition(
const Position& position,
uint32_t from_address,
const std::vector<uint8_t>& psk)
{
EncodedPacket result;
result.success = false;
// Validate input
if (position.latitude < -90.0 || position.latitude > 90.0 ||
position.longitude < -180.0 || position.longitude > 180.0)
{
result.error_message = "Invalid latitude/longitude";
return result;
}
// Generate packet ID
uint32_t packet_id = generatePacketId();
// Build Position protobuf message
std::vector<uint8_t> position_protobuf;
// Field 1: latitude_i (fixed32) - latitude * 1e7
int32_t latitude_i = (int32_t)(position.latitude * 1e7);
encodeFixed32Field(position_protobuf, 1, (uint32_t)latitude_i);
// Field 2: longitude_i (fixed32) - longitude * 1e7
int32_t longitude_i = (int32_t)(position.longitude * 1e7);
encodeFixed32Field(position_protobuf, 2, (uint32_t)longitude_i);
// Field 3: altitude (int32 varint) - altitude in meters
// Note: The decoder casts directly without zigzag decoding, so we encode
// the value directly as unsigned varint (works for positive values)
// For negative altitudes, this won't work correctly, but matches decoder behavior
if (position.altitude != 0)
{
// Encode as unsigned varint (decoder expects this)
uint64_t alt_unsigned = (uint64_t)(int64_t)position.altitude;
encodeVarintField(position_protobuf, 3, alt_unsigned);
}
// Field 4: time (fixed32) - timestamp
if (position.time != 0)
{
encodeFixed32Field(position_protobuf, 4, position.time);
}
// Field 5: location_source (varint enum)
if (position.location_source != 0)
{
encodeVarintField(position_protobuf, 5, position.location_source);
}
// Field 6: altitude_source (varint enum)
if (position.altitude_source != 0)
{
encodeVarintField(position_protobuf, 6, position.altitude_source);
}
// Field 7: timestamp (fixed32) - position timestamp
if (position.timestamp != 0)
{
encodeFixed32Field(position_protobuf, 7, position.timestamp);
}
// Field 11: precision_bits (varint)
if (position.precision_bits != 0)
{
encodeVarintField(position_protobuf, 11, position.precision_bits);
}
// Field 20: sats_in_view (varint)
if (position.sats_in_view != 0)
{
encodeVarintField(position_protobuf, 20, position.sats_in_view);
}
// Field 21: ground_speed (varint) - m/s
if (position.ground_speed != 0)
{
encodeVarintField(position_protobuf, 21, position.ground_speed);
}
// Field 22: ground_track (varint) - 1/100 degrees
if (position.ground_track != 0)
{
encodeVarintField(position_protobuf, 22, position.ground_track);
}
// Build Data protobuf message
// Structure: 08 [port=3] 12 [length] [position_protobuf_data]
std::vector<uint8_t> payload;
// Field 1: port (varint) = 3 (POSITION_APP)
encodeVarintField(payload, 1, 3);
// Field 2: payload (length-delimited) containing Position protobuf
encodeLengthDelimited(payload, 2, position_protobuf);
// Encrypt payload
std::vector<uint8_t> encrypted_payload;
if (!encryptPayload(payload, encrypted_payload, packet_id, from_address, psk))
{
result.error_message = "Failed to encrypt payload";
return result;
}
// Build header
// Flags byte encoding (from Meshtastic protocol):
// Bits 0-2: current hop_limit (remaining hops)
// Bits 5-7: hop_start (original hop limit)
// For a new packet: hop_limit = hop_start = position.hop_limit
uint8_t flags = (position.hop_limit & 0x07) | ((position.hop_limit & 0x07) << 5);
uint8_t next_hop = 0;
uint8_t relay_node = 0;
std::vector<uint8_t> header = buildHeader(0xFFFFFFFF, // Broadcast
from_address,
packet_id,
flags,
0, // Default channel
next_hop,
relay_node);
// Combine header + encrypted payload
result.data = header;
result.data.insert(result.data.end(),
encrypted_payload.begin(),
encrypted_payload.end());
result.success = true;
return result;
}