forked from global-mesh-labs/lot49
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MeshNode.cpp
executable file
·1533 lines (1303 loc) · 59.4 KB
/
MeshNode.cpp
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "MeshNode.hpp"
#include "Ledger.hpp"
#include "Utils.hpp"
#include <random>
#include <algorithm>
#include <cassert>
#include <iterator>
#include <fstream>
#include <deque>
using namespace std;
using namespace lot49;
//
// simulation parameters
//
int MeshNode::sSeed = 0;
double MeshNode::sGatewayPercent = 0.2; // percent of nodes that are also internet gateways
double MeshNode::sOriginatingPercent = 1.0;
int MeshNode::sMaxSize = 5000; // meters width
double MeshNode::sMoveRate = 85; // meters per minute
int MeshNode::sPauseTime = 5; // minutes of simulation
int MeshNode::sCurrentTime = 0; // minutes of simulation
int MeshNode::sPayloadSize = 50; // bytes
int MeshNode::sRadioRange = 1600; // radio communication range in meters
std::vector<lot49::MeshNode> MeshNode::sNodes;
std::list<lot49::MeshRoute> MeshNode::sRoutes;
std::string MeshNode::sParametersString;
//static std::default_random_engine rng(std::random_device{}());
static std::default_random_engine rng(0); // deterministic random seed
namespace lot49
{
void MeshNode::WriteStats(const std::string& inLabel, const lot49::MeshMessage& inMessage)
{
MeshNode& sender = MeshNode::FromHGID(inMessage.mSender);
MeshNode& receiver = MeshNode::FromHGID(inMessage.mReceiver);
double tx_distance = Distance(sender.mCurrentPos, receiver.mCurrentPos);
// time
_stats << sCurrentTime << ", ";
// label
_stats << inLabel << ", ";
// sender
_stats << std::hex << std::setw(4) << (int) inMessage.mSender << ", ";
// receiver
_stats << std::hex << std::setw(4) << (int) inMessage.mReceiver << ", ";
// source
_stats << std::hex << std::setw(4) << (int) inMessage.mSource << ", ";
// destination
_stats << std::hex << std::setw(4) << (int) inMessage.mDestination << ", ";
// distance
_stats << std::dec << (int) tx_distance << ", ";
// incentive_type
_stats << inMessage.mIncentive.mType << ", ";
// prepaid_tokens
_stats << std::dec << (int) inMessage.mIncentive.mPrepaidTokens << ", ";
// relay_path_size
_stats << std::dec << inMessage.mIncentive.mRelayPath.size() << ", ";
// agg_signature_size
_stats << std::dec << inMessage.mIncentive.mSignature.size() << ", ";
// is_witness
_stats << (inMessage.mIncentive.mWitness ? "witness" : (inMessage.mIncentive.mType == eSetup1 ? "setup" : "payload")) << ", ";
// payload_data_size
_stats << std::dec << inMessage.mPayloadData.size() << ", ";
// receiver_unspent_tokens, receiver_channel_state, receiver_channel_confirmed
if (receiver.HasChannel(inMessage.mReceiver, inMessage.mSender)) {
PeerChannel& channel = receiver.GetChannel(inMessage.mReceiver, inMessage.mSender);
_stats << std::dec << channel.mUnspentTokens << ", ";
_stats << std::dec << channel.mState << ", ";
_stats << (channel.mConfirmed ? "true" : "false") << std::endl;
}
else {
_stats << std::dec << "-, -, -" << std::endl;
}
}
// create mesh nodes
void MeshNode::CreateNodes(const int inCount)
{
sCurrentTime = 0;
sSeed = 0;
sNodes.clear();
sNodes.resize(inCount);
// default witness node
HGID witness_node = 0xFFFF;
//std::generate(sNodes.begin(), sNodes.end(), [&] {return MeshNode();});
// set the last node as a gateway for verifying setup transactions
int num_gateways = sNodes.size() * sGatewayPercent;
// each node corresponds with one other node
for (int i = 0; i < inCount; i++) {
MeshNode& n = MeshNode::FromIndex(i);
HGID correspondent_node = MeshNode::FromIndex((i+1) % inCount).GetHGID();
n.SetCorrespondentNode(correspondent_node);
// gateways evenly spaced in range
if ((i % (inCount/num_gateways)) == 0) {
n.mIsGateway = true;
}
_log << n;
_log << endl;
}
}
MeshNode &MeshNode::FromIndex(const int inIndex)
{
if (inIndex > sNodes.size())
{
CreateNodes(inIndex + 1);
}
return sNodes[inIndex];
}
// Lookup a node from a Hashed GID
MeshNode &MeshNode::FromHGID(const HGID &inHGID)
{
for (auto node = sNodes.begin(); node != sNodes.end(); ++node)
{
if (node->GetHGID() == inHGID) {
return *node;
}
}
throw std::invalid_argument("invalid HGID");
}
// Lookup a node from a public key
MeshNode &MeshNode::FromPublicKey(const bls::PublicKey& inPk)
{
for (auto node = sNodes.begin(); node != sNodes.end(); ++node)
{
if (node->GetPublicKey() == inPk) {
return *node;
}
}
throw std::invalid_argument("invalid Public Key");
}
void MeshNode::ClearRoutes() {
sRoutes.clear();
}
// recursively find shortest route to a node
bool MeshNode::FindRoute(const HGID inDestination, const int inDepth, MeshRoute& ioRoute, std::list<HGID>& ioVisited, double& ioDistance)
{
// at destination node
if (inDestination == GetHGID()) {
ioRoute.clear();
ioRoute.push_back(GetHGID());
return true;
}
if (inDepth <= 0) {
return false;
}
/*
// check cached routes
for (auto cached_route : sRoutes) {
if (cached_route.front() == GetHGID() && cached_route.back() == inDestination) {
// use saved sub-route
ioRoute.clear();
ioRoute.insert(ioRoute.begin(), cached_route.begin(), cached_route.end());
auto next_node = ioRoute.begin();
std::advance(next_node,1);
double distance = Distance(mCurrentPos, MeshNode::FromHGID(*next_node).mCurrentPos);
ioDistance = distance;
return true;
}
if (cached_route.front() == inDestination && cached_route.back() == GetHGID()) {
// use reverse of saved sub-route
ioRoute.clear();
cached_route.reverse();
ioRoute.insert(ioRoute.begin(), cached_route.begin(), cached_route.end());
auto next_node = ioRoute.begin();
std::advance(next_node,1);
double distance = Distance(mCurrentPos, MeshNode::FromHGID(*next_node).mCurrentPos);
ioDistance = distance;
return true;
}
}
*/
ioVisited.push_back(GetHGID());
double min_distance = std::numeric_limits<double>::max();
MeshRoute min_route;
bool found = false;
for ( auto& n : sNodes) {
// skip self
if (n.GetHGID() == GetHGID()) {
continue;
}
// find shortest distance to destination from nodes within radio range
double radio_range = Distance(mCurrentPos, n.mCurrentPos);
if (radio_range > sRadioRange) {
continue;
}
// no loops, skip routes already searched by this node or previous nodes
if (std::find(ioVisited.begin(), ioVisited.end(), n.GetHGID()) != ioVisited.end()) {
continue;
}
// find route from candidate node to destination, depth-first-search
MeshRoute route;
double distance = 0;
int depth = inDepth - 1;
if (n.FindRoute(inDestination, depth, route, ioVisited, distance) && (distance + radio_range) < min_distance) {
route.insert(route.begin(), GetHGID());
min_route = route;
min_distance = distance + radio_range;
found = true;
}
}
// remove current node from visited list ??
ioVisited.pop_back();
if (found) {
ioDistance = min_distance;
ioRoute = min_route;
}
return found;
}
bool MeshNode::IsWithinRange(HGID inNode2)
{
double distance = Distance(mCurrentPos, MeshNode::FromHGID(inNode2).mCurrentPos);
return (distance < MeshNode::sRadioRange);
}
HGID MeshNode::GetNextHop(HGID inNode, HGID inDestination, int& outHops)
{
HGID next_hop;
if (GetNextHop(inNode, inDestination, next_hop, outHops)) {
return next_hop;
}
throw std::invalid_argument("No route to destination.");
}
bool MeshNode::GetNextHop(HGID inNode, HGID inDestination, HGID& outNextHop, int& outHops)
{
// next hop along shortest depth-first search route
double distance = 0;
MeshNode& node = MeshNode::FromHGID(inNode);
MeshRoute route;
std::list<HGID> visited;
int depth = 5;
bool found = node.FindRoute(inDestination, depth, route, visited, distance);
if (found) {
auto iter = route.begin();
iter++;
outNextHop = *iter;
//_log << "Next Hop: " << std::hex << inNode << " -> " << std::hex << inDestination << " = " << std::hex << outNextHop << endl;
// only add route if not already added
if (std::find(sRoutes.begin(), sRoutes.end(), route) == sRoutes.end()) {
AddRoute(route);
}
outHops = route.size();
}
return found;
}
void MeshNode::AddGateway(const HGID inNode)
{
MeshNode::FromHGID(inNode).mIsGateway = true;
}
// configure topology
void MeshNode::AddRoute(MeshRoute inRoute)
{
// do not add if already added
if (std::find(sRoutes.begin(), sRoutes.end(), inRoute) != sRoutes.end()) {
return;
}
sRoutes.push_front(inRoute);
auto route_end = inRoute.begin();
std::advance(route_end, inRoute.size() - 1);
for (auto hgid_iter = inRoute.begin(); hgid_iter != route_end; ++hgid_iter) {
//_log << "Node " << std::hex << *hgid_iter << ", Neighbor " << *(hgid_iter+1) << endl;
auto neighbor_iter = hgid_iter;
std::advance(neighbor_iter, 1);
// propose channels with neighbors (forward)
FromHGID(*hgid_iter).ProposeChannel(*neighbor_iter);
// propose channels with neighbors (backwards)
FromHGID(*neighbor_iter).ProposeChannel(*hgid_iter);
}
}
bool MeshNode::HasNeighbor(HGID inNode, HGID inNeighbor)
{
bool found = false;
// if no simulated coordinates, check routes
for (auto route = sRoutes.begin(); !found && route != sRoutes.end(); ++route)
{
auto node_iter = std::find(route->begin(), route->end(), inNode);
auto neighbor_iter = std::find(route->begin(), route->end(), inNeighbor);
if (node_iter != route->end() && neighbor_iter != route->end()) {
// check if nodes are adjacent
found = (*(++node_iter) == inNeighbor || *(++neighbor_iter) == inNode);
}
}
return found;
}
// ctor
MeshNode::MeshNode()
{
mSeed.resize(32);
// std::generate_n(mSeed.begin(), 32, [&] { return dist(rng); });
// DEBUG
std::fill(mSeed.begin(), mSeed.end(), sSeed++);
// if no pending channel node or correspondent set, then use same hgid as node
mPendingChannelNode = GetHGID();
mCorrespondent = GetHGID();
mIsGateway = false;
// initialize position and waypoint
std::uniform_int_distribution<int> pos(-sMaxSize/2, sMaxSize/2);
mWaypoint.first = pos(rng);
mWaypoint.second = pos(rng);
mCurrentPos.first = pos(rng);
mCurrentPos.second = pos(rng);
// only pause if at waypoint
mPausedUntil = 0;
}
HGID MeshNode::GetHGID() const
{
// TODO: use hash of public key, not first two seed values
return *reinterpret_cast<const uint16_t *>(mSeed.data());
}
// access private key
const bls::PrivateKey MeshNode::GetPrivateKey() const
{
bls::PrivateKey sk = bls::PrivateKey::FromSeed(mSeed.data(), mSeed.size());
return sk;
}
// access public key
const bls::PublicKey MeshNode::GetPublicKey() const
{
bls::PrivateKey sk = bls::PrivateKey::FromSeed(mSeed.data(), mSeed.size());
return sk.GetPublicKey();
}
// initiate a payment channel if one doesn't already exist with this neighbor
void MeshNode::ProposeChannel(HGID inNeighbor)
{
if (!HasNeighbor(GetHGID(), inNeighbor)) {
assert(0);
return;
}
// has this node already proposed a channel to inNeighbor?
if (MeshNode::FromHGID(inNeighbor).HasChannel(GetHGID(), inNeighbor)) {
return;
}
_log << "Node " << GetHGID() << ", ";
_log << "ProposeChannel to " << inNeighbor << endl;
_log << "Proposing Peer: " << GetHGID() << endl;
if (HasChannel(GetHGID(), inNeighbor)) {
assert(0);
}
else {
PeerChannel theChannel;
theChannel.mFundingPeer = inNeighbor;
theChannel.mProposingPeer = GetHGID();
theChannel.mUnspentTokens = COMMITTED_TOKENS;
theChannel.mSpentTokens = 0;
theChannel.mPromisedTokens = 0;
theChannel.mLastNonce = 0;
theChannel.mState = eSetup1;
theChannel.mConfirmed = false;
mPeerChannels[make_pair(theChannel.mProposingPeer, theChannel.mFundingPeer)] = theChannel;
}
MeshMessage theMessage;
theMessage.mSource = inNeighbor;
theMessage.mSender = GetHGID();
theMessage.mReceiver = inNeighbor;
theMessage.mDestination = inNeighbor;
// initialize incentive aggregate signature by signing refund tx
theMessage.mIncentive.mType = eSetup1;
theMessage.mIncentive.mPrepaidTokens = 0;
std::vector<ImpliedTransaction> theImpliedTransactions = GetTransactions(theMessage);
bls::Signature refund_sig = SignTransaction(theImpliedTransactions.front());
theMessage.mIncentive.mSignature.resize(bls::Signature::SIGNATURE_SIZE);
refund_sig.Serialize(&theMessage.mIncentive.mSignature[0]);
WriteStats("Propose_Channel", theMessage);
SendTransmission(theMessage);
}
// return true if channel exists with this neighbor
bool MeshNode::HasChannel(HGID inProposer, HGID inFunder) const
{
return (mPeerChannels.find(make_pair(inProposer, inFunder)) != mPeerChannels.end());
}
// get existing channel
PeerChannel& MeshNode::GetChannel(HGID inProposer, HGID inFunder)
{
auto channel_iter = mPeerChannels.find(make_pair(inProposer, inFunder));
if (channel_iter == mPeerChannels.end()) {
throw std::invalid_argument("No channel exists for neighbor.");
}
return channel_iter->second;
}
const PeerChannel& MeshNode::GetChannel(HGID inProposer, HGID inFunder) const
{
auto channel_iter = mPeerChannels.find(make_pair(inProposer, inFunder));
if (channel_iter == mPeerChannels.end()) {
throw std::invalid_argument("No channel exists for neighbor.");
}
return channel_iter->second;
}
void SavePayloadHash(PeerChannel& ioChannel, const std::vector<uint8_t>& inData)
{
ioChannel.mPayloadHash.resize(bls::BLS::MESSAGE_HASH_LEN, 0);
bls::Util::Hash256(&(ioChannel.mPayloadHash[0]), reinterpret_cast<const uint8_t*>(inData.data()), inData.size());
_log << "\tSave payload hash(" << std::hex << ioChannel.mProposingPeer << ", " << ioChannel.mFundingPeer << "): [";
for (int v: ioChannel.mPayloadHash) { _log << std::hex << v; }
_log << "] ";
_log << endl;
}
void SaveWitnessHash(PeerChannel& ioChannel, const std::vector<uint8_t>& inData)
{
ioChannel.mWitnessHash.resize(bls::BLS::MESSAGE_HASH_LEN, 0);
bls::Util::Hash256(&(ioChannel.mWitnessHash[0]), reinterpret_cast<const uint8_t*>(inData.data()), inData.size());
_log << "\tSave witness hash(" << std::hex << ioChannel.mProposingPeer << ", " << ioChannel.mFundingPeer << "): [";
for (int v: ioChannel.mWitnessHash) { _log << std::hex << v; }
_log << "] ";
_log << endl;
}
// originate new message
bool MeshNode::OriginateMessage(const HGID inDestination, const std::vector<uint8_t>& inPayload)
{
std::string payload_text(reinterpret_cast<const char*>(inPayload.data()), inPayload.size());
_log << "Node " << GetHGID() << ", ";
_log << "OriginateMessage, Destination: " << inDestination << ", Payload: [" << payload_text << "]" << endl << endl;
// do not send messages if correspondent is within radio range, no incentive costs for local transmissions
if (IsWithinRange(inDestination)) {
_log << "!! within radio range, no incentives !!" << endl;
return true;
}
HGID next_hop;
int hops;
if (!GetNextHop(GetHGID(), inDestination, next_hop, hops)) {
_log << "!! No route found !!" << endl;
return false;
}
MeshMessage theMessage;
theMessage.mSender = GetHGID();
theMessage.mReceiver = next_hop;
theMessage.mSource = GetHGID();
theMessage.mDestination = inDestination;
theMessage.mPayloadData = inPayload;
PeerChannel &theChannel = GetChannel(theMessage.mReceiver, GetHGID());
//assert(theChannel.mState == eSetup2 || theChannel.mState == eReceipt2 || theChannel.mState == eReceipt1);
if (theChannel.mUnspentTokens < hops) {
_log << "!! insufficient funds, unspent tokens = " << theChannel.mUnspentTokens << " !!" << endl;
return false;
}
//theChannel.mUnspentTokens -= hops;
//theChannel.mSpentTokens += hops;
theChannel.mPromisedTokens += hops;
theChannel.mLastNonce += 1;
theChannel.mState = (theMessage.mDestination == theMessage.mReceiver) ? eNegotiate2 : eNegotiate1;
theMessage.mIncentive.mWitness = false;
theMessage.mIncentive.mPrepaidTokens = hops;
theMessage.mIncentive.mSignature = theChannel.mRefundSignature;
theMessage.mIncentive.mType = theChannel.mState;
// save a local copy of the payload hash for confirming receipt2 messages
assert(theMessage.mIncentive.mType < eReceipt1 );
SavePayloadHash(theChannel, theMessage.mPayloadData);
UpdateIncentiveHeader(theMessage);
WriteStats("Originate_Message", theMessage);
SendTransmission(theMessage);
return true;
}
// relay a message
void MeshNode::RelayMessage(const MeshMessage& inMessage)
{
_log << "Node " << GetHGID() << ", ";
_log << "RelayMessage: " << inMessage << endl;
// confirm setup transaction on the blockchain
PeerChannel &theSenderChannel = GetChannel(GetHGID(), inMessage.mSender);
if (theSenderChannel.mConfirmed == false) {
HGID gateway;
if (!GetNearestGateway(gateway)) {
_log << "!! No route to gateway !! " << endl;
}
else {
ConfirmSetupTransaction(inMessage, gateway);
}
}
assert(theSenderChannel.mConfirmed == true);
// receive payment from sender
uint8_t received_tokens = (inMessage.mIncentive.mPrepaidTokens - inMessage.mIncentive.mRelayPath.size());
//theSenderChannel.mUnspentTokens -= received_tokens;
//theSenderChannel.mSpentTokens += received_tokens;
theSenderChannel.mPromisedTokens += received_tokens;
theSenderChannel.mLastNonce += 1;
theSenderChannel.mState = inMessage.mIncentive.mType;
int hops;
HGID next_hop = GetNextHop(GetHGID(), inMessage.mDestination, hops);
// TODO: check if payment enough to reach destination
// pay next hop
uint8_t spent_tokens = (inMessage.mIncentive.mPrepaidTokens - inMessage.mIncentive.mRelayPath.size()) - 1;
PeerChannel &theChannel = GetChannel(next_hop, GetHGID());
//theChannel.mUnspentTokens -= spent_tokens;
//theChannel.mSpentTokens += spent_tokens;
theChannel.mPromisedTokens -= spent_tokens;
theChannel.mLastNonce += 1;
theChannel.mState = inMessage.mIncentive.mType;
// save a local copy of the payload hash for confirming receipt2 messages
assert ( inMessage.mIncentive.mType < eReceipt1 );
if (!inMessage.mIncentive.mWitness) {
SavePayloadHash(theChannel, inMessage.mPayloadData);
}
else {
SaveWitnessHash(theChannel, inMessage.mPayloadData);
}
// new relay message
MeshMessage outMessage = inMessage;
outMessage.mSender = GetHGID();
outMessage.mReceiver = next_hop;
if (outMessage.mReceiver == outMessage.mDestination && outMessage.mIncentive.mType == eNegotiate1 ) {
// next node is destination node
outMessage.mIncentive.mType = eNegotiate2;
theChannel.mState = eNegotiate2;
}
UpdateIncentiveHeader(outMessage);
WriteStats("Relay_Message", outMessage);
// send message to next hop
SendTransmission(outMessage);
}
// fund a channel
void MeshNode::FundChannel(const MeshMessage& inMessage)
{
_log << "Node " << GetHGID() << ", ";
_log << "FundChannel: " << inMessage << endl;
_log << "Proposing Peer: " << inMessage.mSender << endl;
// TODO: check that funds exist, etc.
if (HasChannel(inMessage.mSender, GetHGID())) {
assert(0);
}
else {
// create channel entry for peer that proposed the channel
PeerChannel theChannel;
theChannel.mFundingPeer = GetHGID();
theChannel.mProposingPeer = inMessage.mSender;
theChannel.mUnspentTokens = COMMITTED_TOKENS; // always commit default amount when funding a channel
theChannel.mSpentTokens = 0;
theChannel.mPromisedTokens = 0;
theChannel.mLastNonce = 0;
theChannel.mState = eSetup2;
theChannel.mRefundSignature = inMessage.mIncentive.mSignature;
theChannel.mConfirmed = true;
// save a local copy of the payload hash for confirming receipt2 messages
assert ( inMessage.mIncentive.mType < eReceipt1 );
SavePayloadHash(theChannel, inMessage.mPayloadData);
mPeerChannels[make_pair(theChannel.mProposingPeer, theChannel.mFundingPeer)] = theChannel;
}
}
bool MeshNode::VerifySetupTransaction(const MeshMessage& inMessage)
{
std::vector<ImpliedTransaction> theTransactions = GetTransactions(inMessage);
if (!VerifyMessage(inMessage)) {
return false;
}
// check if the setup transaction has already been confirmed
assert(theTransactions[1].GetType() == eSetup);
bool valid_setup = Ledger::sInstance.Unspent(theTransactions[1].GetHash());
if (valid_setup) {
return true;
}
// otherwise, add the transation to the ledger and confirm it is confirmed
Ledger::sInstance.Add(theTransactions);
valid_setup = Ledger::sInstance.Unspent(theTransactions[1].GetHash());
return valid_setup;
}
// receive message
void MeshNode::ReceiveMessage(const MeshMessage& inMessage)
{
_log << "Node " << GetHGID() << ", ";
_log << "ReceiveMessage: " << inMessage << endl;
/*
// confirm setup transaction on the blockchain if channel needed to relay or originate a message
PeerChannel &upstream_channel = GetChannel(GetHGID(), inMessage.mSender);
if (upstream_channel.mConfirmed == false && inMessage.mIncentive.mType != eSetup1) {
HGID gateway;
if (!GetNearestGateway(gateway)) {
_log << "!! No route to gateway !! " << endl;
}
else {
ConfirmSetupTransaction(inMessage, gateway);
}
}
assert(upstream_channel.mConfirmed == true);
*/
// channel for sending return receipt
PeerChannel& downstream_channel = GetChannel(inMessage.mSender, GetHGID());
// save a local copy of the payload hash for confirming receipt2 messages
if (!inMessage.mIncentive.mWitness) {
SavePayloadHash(downstream_channel, inMessage.mPayloadData);
}
else {
SaveWitnessHash(downstream_channel, inMessage.mPayloadData);
}
// message received and marked for signing witness node ?
if (inMessage.mIncentive.mWitness) {
assert(GetIsGateway());
// verify the setup transaction on the blockchain
MeshMessage witness_message;
witness_message.FromBytes(inMessage.mPayloadData);
bool valid_setup = VerifySetupTransaction(witness_message);
if(valid_setup) {
_log << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction CONFIRMED:" << endl << "\t" << witness_message << endl;
cout << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction CONFIRMED:" << endl << "\t" << witness_message << endl;
}
else {
_log << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction FAILED:" << endl << "\t" << witness_message << endl;
cout << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction FAILED:" << endl << "\t" << witness_message << endl;
}
}
else {
std::string payload_text(reinterpret_cast<const char*>(inMessage.mPayloadData.data()), inMessage.mPayloadData.size());
_log << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << " received message: [" << payload_text << "] !" << endl;
cout << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << " received message: [" << payload_text << "] !" << endl;
}
// send return receipt
MeshMessage theMessage = inMessage;
theMessage.mSender = GetHGID();
theMessage.mReceiver = inMessage.mSender;
theMessage.mIncentive.mType = eReceipt1;
// TODO: fix so that UpdateIncentiveHeader does not change mIncentive.mState as a side effect using value of theChannel.mState
PeerChannel &theChannel = GetChannel(theMessage.mReceiver, GetHGID());
theChannel.mState = theMessage.mIncentive.mType;
UpdateIncentiveHeader(theMessage);
// no need to send payload, hash is cached by nodes
theMessage.mPayloadData.clear();
WriteStats("Send_Receipt", theMessage);
// send proof of receipt to previous hop
SendTransmission(theMessage);
// !! update channel state(s) AFTER sending transmission because Verify() looks at current nodes channel state
// receive remaining tokens from sender
uint8_t remaining_tokens = (inMessage.mIncentive.mPrepaidTokens - inMessage.mIncentive.mRelayPath.size());
PeerChannel &upstream_channel = GetChannel(GetHGID(), inMessage.mSender);
upstream_channel.mUnspentTokens -= remaining_tokens;
upstream_channel.mSpentTokens += remaining_tokens;
upstream_channel.mLastNonce += 1;
upstream_channel.mState = inMessage.mIncentive.mType;
}
// receive delivery receipt
void MeshNode::RelayDeliveryReceipt(const MeshMessage& inMessage)
{
_log << "Node " << GetHGID() << ", ";
_log << "RelayDeliveryReceipt: " << inMessage << endl;
// destination node confirms message hash matches
if (!VerifyMessage(inMessage)) {
return;
}
if (GetHGID() != inMessage.mSource) {
// relay return receipt
MeshMessage theMessage = inMessage;
theMessage.mSender = GetHGID();
// determine next hop from the relay path, no searching
// theMessage.mReceiver = GetNextHop(GetHGID(), inMessage.mSource);
auto pos_iter = std::find(inMessage.mIncentive.mRelayPath.begin(), inMessage.mIncentive.mRelayPath.end(), GetHGID());
ptrdiff_t pos = std::distance(inMessage.mIncentive.mRelayPath.begin(), pos_iter);
HGID theNextHop = (pos > 0 ? theMessage.mIncentive.mRelayPath[pos-1] : inMessage.mSource);
_log << "Next Hop (relay path): " << std::hex << GetHGID() << " -> " << std::hex << inMessage.mSource << " = " << std::hex << theNextHop << endl;
theMessage.mReceiver = theNextHop;
// use cached hash of payload, do not resend payload with receipt
theMessage.mPayloadData.clear();
// message destination signs before relaying eReceipt1, all others just relay
assert(theMessage.mIncentive.mType == eReceipt1 || theMessage.mIncentive.mType == eReceipt2);
theMessage.mIncentive.mType = eReceipt2;
// no need to call UpdateIncentiveHeader(theMessage) because receipts don't need any extra incentives
WriteStats("Relay_Receipt", theMessage);
// send proof of receipt to previous hop
SendTransmission(theMessage);
// !! update channel state(s) AFTER sending transmission because Verify() looks at current nodes channel state
uint8_t prepaid_tokens = inMessage.mIncentive.mPrepaidTokens;
// credit payment from upstream node and update nonce
assert (GetHGID() != theMessage.mSource);
uint8_t received_tokens = prepaid_tokens - pos;
PeerChannel& upstream_channel = GetChannel(GetHGID(), theNextHop);
upstream_channel.mUnspentTokens -= received_tokens;
upstream_channel.mSpentTokens += received_tokens;
upstream_channel.mPromisedTokens -= received_tokens;
upstream_channel.mLastNonce += 1;
upstream_channel.mState = eReceipt2;
// credit payment to downstream node from this node
assert (GetHGID() != theMessage.mDestination);
uint8_t spent_tokens = received_tokens - 1;
PeerChannel& downstream_channel = GetChannel(inMessage.mSender, GetHGID());
downstream_channel.mUnspentTokens -= spent_tokens;
downstream_channel.mSpentTokens += spent_tokens;
downstream_channel.mPromisedTokens -= spent_tokens;
downstream_channel.mLastNonce += 1;
downstream_channel.mState = eReceipt2;
}
else {
if (inMessage.mIncentive.mWitness) {
_log << "Confirmation of channel setup received by relay " << std::setw(4) << std::setfill('0') << inMessage.mSource << " from Witness Node " << std::setw(4) << std::setfill('0') << inMessage.mDestination << "!" << endl;
cout << "Confirmation of channel setup received by relay " << std::setw(4) << std::setfill('0') << inMessage.mSource << " from Witness Node " << std::setw(4) << std::setfill('0') << inMessage.mDestination << "!" << endl;
// pending channel node must have been previously set
assert(mPendingChannelNode != GetHGID());
PeerChannel& pending_channel = GetChannel(GetHGID(), mPendingChannelNode);
pending_channel.mConfirmed = true;
// unset pending channel node
mPendingChannelNode = GetHGID();
}
else {
_log << "Delivery Receipt received by source " << std::setw(4) << std::setfill('0') << inMessage.mSource << " from message destination " << std::setw(4) << std::setfill('0') << inMessage.mDestination << "!" << endl;
cout << "Delivery Receipt received by source " << std::setw(4) << std::setfill('0') << inMessage.mSource << " from message destination " << std::setw(4) << std::setfill('0') << inMessage.mDestination << "!" << endl;
// TODO: keep stats on message delivery here
}
// credit payment to first hop from message originator or witness requester
PeerChannel& downstream_channel = GetChannel(inMessage.mSender, GetHGID());
uint8_t prepaid_tokens = inMessage.mIncentive.mPrepaidTokens;
downstream_channel.mUnspentTokens -= prepaid_tokens;
downstream_channel.mSpentTokens += prepaid_tokens;
downstream_channel.mPromisedTokens -= prepaid_tokens;
}
}
// confirm the setup transaction for a payment channel with a witness node (via inGateway)
void MeshNode::ConfirmSetupTransaction(const MeshMessage& inMessage, const HGID inGateway)
{
_log << "Node " << GetHGID() << ", ";
_log << "ConfirmSetupTransaction, Gateway: " << inGateway << ", Message Hash: [" << inMessage << "]" << endl << endl;
if (GetHGID() == inGateway) {
// handle special case of confirming transactions when relaying through a gateway
bool valid_setup = VerifySetupTransaction(inMessage);
if(valid_setup) {
_log << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction CONFIRMED:" << endl << "\t" << inMessage << endl;
cout << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction CONFIRMED:" << endl << "\t" << inMessage << endl;
}
else {
_log << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction FAILED:" << endl << "\t" << inMessage << endl;
cout << "Node " << std::setw(4) << std::setfill('0') << inMessage.mReceiver << ": setup transaction FAILED:" << endl << "\t" << inMessage << endl;
}
PeerChannel& theSenderChannel = GetChannel(GetHGID(), inMessage.mSender);
theSenderChannel.mConfirmed = valid_setup;
return;
}
// pending channel node should be currently unset
assert(mPendingChannelNode == GetHGID());
mPendingChannelNode = inMessage.mSender;
// if this node is not a gateway, send the setup transaction to be confirmed to a nearby gateway node, potentially via relay nodes
HGID next_hop;
int hops;
if (!GetNextHop(GetHGID(), inGateway, next_hop, hops)) {
_log << "!! No route found !!" << endl;
return;
}
MeshMessage theMessage;
theMessage.mSender = GetHGID();
theMessage.mReceiver = next_hop;
theMessage.mSource = GetHGID();
theMessage.mDestination = inGateway;
theMessage.mPayloadData = inMessage.Serialize();
PeerChannel& theChannel = GetChannel(theMessage.mReceiver, GetHGID());
// assert(theChannel.mState == eSetup2 || theChannel.mState == eReceipt2 || theChannel.mState == eReceipt1);
if (theChannel.mUnspentTokens < hops) {
_log << "!! insufficient funds, unspent tokens = " << theChannel.mUnspentTokens << " !!" << endl;
return;
}
//theChannel.mUnspentTokens -= hops;
//theChannel.mSpentTokens += hops;
theChannel.mPromisedTokens += hops;
// theChannel.mLastNonce += 1;
theChannel.mState = (theMessage.mDestination == theMessage.mReceiver ? eNegotiate2 : eNegotiate1);
theMessage.mIncentive.mWitness = true;
theMessage.mIncentive.mPrepaidTokens = hops;
theMessage.mIncentive.mSignature = theChannel.mRefundSignature;
theMessage.mIncentive.mType = theChannel.mState;
// save a local copy of the payload hash for confirming receipt2 messages
assert(theMessage.mIncentive.mType < eReceipt1 );
SaveWitnessHash(theChannel, theMessage.mPayloadData);
UpdateIncentiveHeader(theMessage);
WriteStats("Send_Witness", theMessage);
SendTransmission(theMessage);
}
bls::Signature MeshNode::GetAggregateSignature(const MeshMessage& inMessage, const bool isSigning) const
{
const MeshNode& theSigningNode = MeshNode::FromHGID(inMessage.mSender);
_log << "\t\tNode " << GetHGID() << ", ";
_log << "\t\tGetAggregateSignature, " << inMessage << endl;
// calculate aggregation info from implied transaction hashes and signing public keys
std::vector<ImpliedTransaction> theImpliedTransactions = GetTransactions(inMessage);
vector<bls::Signature> sigs;
std::deque< std::deque<bls::AggregationInfo> > aggregation_queue(1);
bls::PublicKey sender_pk = MeshNode::FromHGID(inMessage.mSender).GetPublicKey();
bool isOtherSigner = !isSigning;
bool isSkip = inMessage.mIncentive.mType < eReceipt1;
bool isSenderSigned = false;
ImpliedTransaction previous_aggregated_tx;
for (auto tx = theImpliedTransactions.rbegin(); tx != theImpliedTransactions.rend(); tx++) {
bls::PublicKey tx_signer_pk = tx->GetSigner();
isSkip &= (tx_signer_pk != sender_pk && !isSenderSigned);
if (!isSkip) {
// only add aggregation_info for previously aggregated signatures
isOtherSigner |= tx_signer_pk != theSigningNode.GetPublicKey() || tx->GetType() == eRefund;
if (isOtherSigner) {
if (!aggregation_queue.empty() && tx->GetSigner() != previous_aggregated_tx.GetSigner()) {
// group current aggregation information when signer changes
aggregation_queue.push_front(std::deque<bls::AggregationInfo>());
_log << "\t\t\t---------- " << endl;
}
aggregation_queue.front().push_front( bls::AggregationInfo::FromMsgHash(tx_signer_pk, tx->GetHash().data()) );
previous_aggregated_tx = *tx;
}
else {
// push current signature contained in the message
sigs.insert( sigs.begin(), theSigningNode.SignTransaction(*tx) );
}
}
// after sender has signed their transactions, skip any later transactions signed by other nodes
isSenderSigned |= (tx_signer_pk == theSigningNode.GetPublicKey());
_log << "\t\tSigner: " << MeshNode::FromPublicKey(tx_signer_pk).GetHGID() << " Type: " << tx->GetType() << (isSkip ? "- " : (isOtherSigner ? "* " : " "));
_log << "\t\t tx: [";
for (int v: tx->GetHash()) { _log << std::setfill('0') << setw(2) << std::hex << v; }
_log << "\t\t] ";
_log << endl;
}
// add aggregation info for destination's signature for payload message
if (inMessage.mIncentive.mType >= eReceipt2 || (inMessage.mIncentive.mType == eReceipt1 && !isSigning)) {
const MeshNode& destination = MeshNode::FromHGID(inMessage.mDestination);
bls::PublicKey pk = destination.GetPublicKey();
HGID direction_hgid = inMessage.mDestination;
if (GetHGID() == direction_hgid) {
// sending receipt back to source
direction_hgid = inMessage.mSource;
}
int hops;
HGID next_hop_hgid = GetNextHop(GetHGID(), direction_hgid, hops);
const PeerChannel& theChannel = GetChannel( next_hop_hgid, GetHGID());
std::vector<uint8_t> hash = theChannel.mPayloadHash;
if (inMessage.mIncentive.mWitness) {
hash = theChannel.mWitnessHash;
}
_log << endl << "\t\tSigner: " << inMessage.mDestination << " Type: sign_payload* ("<< std::hex << theChannel.mProposingPeer << ", " << theChannel.mFundingPeer << ") ";
_log << "hash: [";
for (int v: hash) { _log << std::hex << v; }
_log << "] ";
_log << endl;
aggregation_queue.back().push_back( bls::AggregationInfo::FromMsgHash(pk, hash.data()));
}
_log << endl;
// combine and group aggregation info in the same way as when the original signature was created
bls::AggregationInfo merged_aggregation_info = bls::AggregationInfo::MergeInfos({aggregation_queue.front().begin(), aggregation_queue.front().end()});
aggregation_queue.pop_front();
while (aggregation_queue.begin() != aggregation_queue.end()) {
vector<bls::AggregationInfo> tmp_agg_info = { merged_aggregation_info };
tmp_agg_info.insert(tmp_agg_info.end(), aggregation_queue.front().begin(), aggregation_queue.front().end());
merged_aggregation_info = bls::AggregationInfo::MergeInfos(tmp_agg_info);
aggregation_queue.pop_front();
}
// add aggregate signature from previous transactions
bls::Signature agg_sig = bls::Signature::FromBytes(inMessage.mIncentive.mSignature.data());
agg_sig.SetAggregationInfo(merged_aggregation_info);
sigs.insert(sigs.begin(), agg_sig);
// message receiver signs the payload data
if (inMessage.mIncentive.mType == eReceipt1 && isSigning) {
assert(theSigningNode.GetHGID() == GetHGID());
assert(inMessage.mSender == inMessage.mDestination);
sigs.push_back( theSigningNode.SignMessage(inMessage.mPayloadData) );
}
// update aggregate signature
try {
agg_sig = bls::Signature::AggregateSigs(sigs);
}