-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpeermon.cpp
1380 lines (1138 loc) · 45.7 KB
/
peermon.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
#define VERSION "1.31"
#include <sodium.h>
#include <iostream>
#include <string_view>
#include <string>
#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#include <time.h>
#include <stdio.h>
#include <secp256k1.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "libbase58.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <stdint.h>
#include <set>
#include <map>
#include <utility>
#include "ripple.pb.h"
#include "stlookup.h"
#include <netdb.h>
#include <pwd.h>
#include "sha-256.h"
#include "xd.h"
#define DEBUG 1
#define PACKET_STACK_BUFFER_SIZE 2048
//#define PACKET_STACK_BUFFER_SIZE 10
#define TLS_LISTEN_CERT "listen.cert"
#define TLS_LISTEN_KEY "listen.key"
void print_cert_help_then_exit()
{
fprintf(stderr, "openssl req -nodes -new -x509 -keyout %s -out %s\n", TLS_LISTEN_KEY, TLS_LISTEN_CERT);
exit(1);
}
int stricmp(const char *a, const char *b)
{
int ca, cb;
do {
ca = (unsigned char) *a++;
cb = (unsigned char) *b++;
ca = tolower(toupper(ca));
cb = tolower(toupper(cb));
} while (ca == cb && ca != '\0');
return ca - cb;
}
std::string peer;
time_t time_start;
// these are defaults set at startup according to cmdline flags
int use_cls = 1, no_dump = 0, slow = 0, manifests_only = 0, raw_hex = 0, no_stats = 0, no_http = 0, no_hex = 0;
int stricmp(const uint8_t* a, const uint8_t* b)
{
int ca, cb;
do {
ca = (unsigned char) *a++;
cb = (unsigned char) *b++;
ca = tolower(toupper(ca));
cb = tolower(toupper(cb));
} while (ca == cb && ca != '\0');
return ca - cb;
}
int strnicmp(const uint8_t* a, const uint8_t* b, int n)
{
int ca, cb;
do {
ca = (unsigned char) *a++;
cb = (unsigned char) *b++;
ca = tolower(toupper(ca));
cb = tolower(toupper(cb));
} while (ca == cb && ca != '\0' && --n > 0);
return ca - cb;
}
void print_sto(const std::string& st)
{
// hacky way to add \0 to the end due to bug in deserializer
uint8_t* input = (uint8_t*)malloc(st.size() + 1);
int i = 0;
for (unsigned char c : st)
input[i++] = c;
input[i] = '\0';
uint8_t* output = 0;
if (!deserialize(&output, input, st.size() + 1, 0, 0, 0))
{
fprintf(stderr, "Could not deserialize\n");
return;
}
printf("%s\n", output);
free(output);
free(input);
}
void print_hex(void const* packet_buffer_raw, int packet_len)
{
uint8_t* packet_buffer = (uint8_t*)packet_buffer_raw;
if (no_hex)
return;
for (int j = 0; j < packet_len; j++)
{
if (j % 16 == 0 && !raw_hex)
printf("0x%08X:\t", j);
printf("%02X%s", packet_buffer[j],
(raw_hex ? "" :
(j % 16 == 15 ? "\n" :
(j % 4 == 3 ? " " :
(j % 2 == 1 ? " " : "")))));
}
printf("\n");
}
template<class... Args>
int printd(Args ... args)
{
(std::cerr << ... << args) << "\n";
return 1;
}
int connect_peer(std::string_view ip_port, int listen_mode)
{
auto x = ip_port.find_last_of(":");
if (x == std::string_view::npos)
return printd("[DBG] Could not find port in ", ip_port), -1;
std::string ip { ip_port.substr(0, x) };
long port = strtol(ip_port.substr(x+1).data(), 0, 10);
if (port <= 0)
return printd("[DBG] Port of ", ip_port, " parsed to 0 or neg"), -1;
int sockfd = 0;
struct sockaddr_in serv_addr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return printd("[DBG] Could not create socket for ", ip_port, "\n"), -1;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
if(inet_pton(AF_INET, ip.c_str(), &serv_addr.sin_addr)<=0)
return printd("[DBG] Could not create socket for ", ip_port," inet_pton error occured"), -1;
if (listen_mode)
{
if (access(TLS_LISTEN_CERT, F_OK) != 0)
{
fprintf(stderr, "Could not open ./%s\nTry: ", TLS_LISTEN_CERT);
print_cert_help_then_exit();
}
if (access(TLS_LISTEN_KEY, F_OK) != 0)
{
return fprintf(stderr, "Could not open ./%s\nTry: ", TLS_LISTEN_KEY);
print_cert_help_then_exit();
}
if (bind(sockfd, (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
return fprintf(stderr, "Could not bind to ip and port\n");
if (listen(sockfd, 1) < 0)
return fprintf(stderr, "Could not listen on ip and port\n");
printf("Waiting for an incoming connection on %s %d\n", ip.c_str(), port);
struct sockaddr client_addr;
unsigned int address_len = sizeof(client_addr);
sockfd = accept(sockfd, (struct sockaddr*)&client_addr, &address_len);
struct sockaddr_in* pV4Addr = (struct sockaddr_in*)&client_addr;
struct in_addr ipAddr = pV4Addr->sin_addr;
char str[INET_ADDRSTRLEN];
for (int i = 0; i < INET_ADDRSTRLEN; ++i)
str[0] = 0;
inet_ntop( AF_INET, &ipAddr, str, INET_ADDRSTRLEN );
printf("Received connection from: %s\n", str);
// fall through
}
else
{
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
return fprintf(stderr, "Could not connect to ip and port\n");
}
return sockfd;
}
int generate_node_keys(
secp256k1_context* ctx,
unsigned char* outsec32,
unsigned char* outpubraw64,
unsigned char* outpubcompressed33,
char* outnodekeyb58,
size_t* outnodekeyb58size)
{
// create secp256k1 context and randomize it
int rndfd = open("/dev/urandom", O_RDONLY);
if (rndfd < 0) {
fprintf(stderr, "[FATAL] Could not open /dev/urandom for reading\n");
exit(1);
}
unsigned char seed[32];
auto result = read(rndfd, seed, 32);
if (result != 32) {
fprintf(stderr, "[FATAL] Could not read 32 bytes from /dev/urandom\n");
exit(2);
}
if (!secp256k1_context_randomize(ctx, seed)) {
fprintf(stderr, "[FATAL] Could not randomize secp256k1 context\n");
exit(3);
}
// fixed key mode
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
char keyfn[256];
strcpy(keyfn, homedir);
strcat(keyfn, "/.peermon");
int keyfd = open(keyfn, O_RDONLY);
if (!(keyfd >= 0 && read(keyfd, outsec32, 32) == 32))
{
printf("Random key\n");
result = read(rndfd, outsec32, 32);
if (result != 32) {
fprintf(stderr, "[FATAL] Could not read 32 bytes from /dev/urandom\n");
exit(4);
}
}
secp256k1_pubkey* pubkey = (secp256k1_pubkey*)((void*)(outpubraw64));
if (!secp256k1_ec_pubkey_create(ctx, pubkey, (const unsigned char*)outsec32)) {
fprintf(stderr, "[FATAL] Could not generate secp256k1 keypair\n");
exit(5);
}
size_t out_size = 33;
secp256k1_ec_pubkey_serialize(ctx, outpubcompressed33, &out_size, pubkey, SECP256K1_EC_COMPRESSED);
unsigned char outpubcompressed38[38];
// copy into the 38 byte check version
for(int i = 0; i < 33; ++i) outpubcompressed38[i+1] = outpubcompressed33[i];
// clean up
close(rndfd);
// pub key must start with magic type 0x1C
outpubcompressed38[0] = 0x1C;
// generate the double sha256
unsigned char hash[crypto_hash_sha256_BYTES];
crypto_hash_sha256(hash, outpubcompressed38, 34);
unsigned char hash2[crypto_hash_sha256_BYTES];
crypto_hash_sha256(hash2, hash, crypto_hash_sha256_BYTES);
// copy checksum bytes to the end of the compressed key
for (int i = 0; i < 4; ++i)
outpubcompressed38[34+i] = hash2[i];
// generate base58 encoding
b58enc(outnodekeyb58, outnodekeyb58size, outpubcompressed38, 38);
uint8_t* fin = (uint8_t*)outnodekeyb58 + (*outnodekeyb58size);
*fin = '\0';
return 1;
}
//todo: clean up and optimise, check for overrun
SSL* ssl_handshake_and_upgrade(secp256k1_context* secp256k1ctx, int fd, SSL_CTX** outctx, int listen_mode)
{
const SSL_METHOD *method =
listen_mode ? SSLv23_server_method() : TLS_client_method();
SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX_set_ecdh_auto(ctx, 1);
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
if (listen_mode)
{
if (access(TLS_LISTEN_CERT, F_OK) != 0 ||
SSL_CTX_use_certificate_file(ctx, TLS_LISTEN_CERT, SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stderr);
fprintf(stderr, "Could not open ./%s\n Try: ", TLS_LISTEN_CERT);
print_cert_help_then_exit();
}
if (access(TLS_LISTEN_KEY, F_OK) != 0 ||
SSL_CTX_use_PrivateKey_file(ctx, TLS_LISTEN_KEY, SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stderr);
fprintf(stderr, "Could not open ./%s\nTry: ", TLS_LISTEN_KEY);
print_cert_help_then_exit();
}
}
*outctx = ctx;
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, fd);
int status = -100;
if (listen_mode)
status = SSL_accept(ssl);
else
status = SSL_connect(ssl);
if (status != 1)
{
status = SSL_get_error(ssl, status);
fprintf(stderr, "[FATAL] SSL_connect failed with SSL_get_error code %d\n", status);
return NULL;
}
unsigned char buffer[1024];
size_t len = SSL_get_finished(ssl, buffer, 1024);
if (len < 12)
{
fprintf(stderr, "[FATAL] Could not SSL_get_finished\n");
return NULL;
}
// SHA512 SSL_get_finished to create cookie 1
unsigned char cookie1[64];
crypto_hash_sha512(cookie1, buffer, len);
len = SSL_get_peer_finished(ssl, buffer, 1024);
if (len < 12) {
fprintf(stderr, "[FATAL] Could not SSL_get_peer_finished\n");
return NULL;
}
// SHA512 SSL_get_peer_finished to create cookie 2
unsigned char cookie2[64];
crypto_hash_sha512(cookie2, buffer, len);
// xor cookie2 onto cookie1
for (int i = 0; i < 64; ++i) cookie1[i] ^= cookie2[i];
// the first half of cookie2 is the true cookie
crypto_hash_sha512(cookie2, cookie1, 64);
// generate keys
unsigned char sec[32], pub[64], pubc[33];
char b58[100];
size_t b58size = 100;
generate_node_keys(secp256k1ctx, sec, pub, pubc, b58, &b58size);
secp256k1_ecdsa_signature sig;
secp256k1_ecdsa_sign(secp256k1ctx, &sig, cookie2, sec, NULL, NULL);
unsigned char buf[200];
size_t buflen = 200;
secp256k1_ecdsa_signature_serialize_der(secp256k1ctx, buf, &buflen, &sig);
char buf2[200];
size_t buflen2 = 200;
sodium_bin2base64(buf2, buflen2, buf, buflen, sodium_base64_VARIANT_ORIGINAL);
buf2[buflen2] = '\0';
char buf3[2048];
size_t buf3len = 0;
if (listen_mode)
{
// we could read their incoming request first, but it probably doesn't matter full duplex ftw
unsigned char buffer[PACKET_STACK_BUFFER_SIZE];
size_t bufferlen = PACKET_STACK_BUFFER_SIZE;
bufferlen = SSL_read(ssl, buffer, PACKET_STACK_BUFFER_SIZE);
if (bufferlen == 0)
{
fprintf(stderr, "Server stopped responding while we waited for upgrade request\n");
exit(1);
}
buffer[bufferlen] = '\0';
if (!no_http)
printf("Received:\n%s", buffer);
uint8_t* default_protocol = (uint8_t*)"XRPL/2.1";
uint8_t* protocol = default_protocol;
// hacky way to grab which protocol to upgrade to, RH TODO: make this sensible
int find_comma = 0;
for (int i = 0; i < bufferlen - 10; ++i) //`Upgrade: `
{
if (find_comma && (buffer[i] == ',' || buffer[i] == '\r'))
{
buffer[i] = '\0';
break;
}
if (!find_comma && memcmp(buffer + i, "Upgrade: ", 9) == 0)
{
protocol = buffer + i + 9;
find_comma = 1;
}
}
buf3len = snprintf(buf3, 2047,
"HTTP/1.1 101 Switching Protocols\r\n"
"Connection: Upgrade\r\n"
"Upgrade: %s\r\n"
"Connect-As: Peer\r\n"
"Server: rippled-2.2.2\r\n"
"Crawl: private\r\n"
"Public-Key: %s\r\n"
"Session-Signature: %s\r\n\r\n", protocol, b58, buf2);
}
else
{
buf3len = snprintf(buf3, 2047,
"GET / HTTP/1.1\r\n"
"User-Agent: rippled-2.2.2\r\n"
"Upgrade: XRPL/2.1\r\n"
"Connection: Upgrade\r\n"
"Connect-As: Peer\r\n"
"Crawl: private\r\n"
"Session-Signature: %s\r\n"
"Public-Key: %s\r\n\r\n", buf2, b58);
}
if (!no_http)
printf("Sending:\n%s", buf3);
if (SSL_write(ssl, buf3, buf3len) <= 0) {
fprintf(stderr, "[FATAL] Failed to write bytes to openssl fd\n");
return NULL;
}
if (listen_mode)
{
// send a ping immediately after handshake
/*
message TMPing
{
enum pingType {
ptPING = 0; // we want a reply
ptPONG = 1; // this is a reply
}
required pingType type = 1;
optional uint32 seq = 2; // detect stale replies, ensure other side is reading
optional uint64 pingTime = 3; // know when we think we sent the ping
optional uint64 netTime = 4;
}
*/
uint8_t packet_buffer[512];
int packet_len = sizeof(packet_buffer);
protocol::TMPing ping;
printf("%u mtPING - sending out\n");
ping.set_type(protocol::TMPing_pingType_ptPING);
//unsigned char* buf = (unsigned char*) malloc(ping.ByteSizeLong());
ping.SerializeToArray(packet_buffer, packet_len);
uint32_t reply_len = packet_len;
uint16_t reply_type = 3;
// write reply header
unsigned char header[6];
header[0] = (reply_len >> 24) & 0xff;
header[1] = (reply_len >> 16) & 0xff;
header[2] = (reply_len >> 8) & 0xff;
header[3] = reply_len & 0xff;
header[4] = (reply_type >> 8) & 0xff;
header[5] = reply_type & 0xff;
SSL_write(ssl, header, 6);
SSL_write(ssl, packet_buffer, packet_len);
}
return ssl;
}
const char* mtUNKNOWN = "mtUNKNOWN_PACKET";
const char* packet_name(
int packet_type, int padded)
{
switch(packet_type)
{
case 2: return (padded ? "mtMANIFESTS " : "mtMANIFESTS");
case 3: return (padded ? "mtPING " : "mtPING");
case 5: return (padded ? "mtCLUSTER " : "mtCLUSTER");
case 15: return (padded ? "mtENDPOINTS " : "mtENDPOINTS");
case 30: return (padded ? "mtTRANSACTION " : "mtTRANSACTION");
case 31: return (padded ? "mtGET_LEDGER " : "mtGET_LEDGER");
case 32: return (padded ? "mtLEDGER_DATA " : "mtLEDGER_DATA");
case 33: return (padded ? "mtPROPOSE_LEDGER " : "mtPROPOSE_LEDGER");
case 34: return (padded ? "mtSTATUS_CHANGE " : "mtSTATUS_CHANGE");
case 35: return (padded ? "mtHAVE_SET " : "mtHAVE_SET");
case 41: return (padded ? "mtVALIDATION " : "mtVALIDATION");
case 42: return (padded ? "mtGET_OBJECTS " : "mtGET_OBJECTS");
case 50: return (padded ? "mtGET_SHARD_INFO " : "mtGET_SHARD_INFO");
case 51: return (padded ? "mtSHARD_INFO " : "mtSHARD_INFO");
case 52: return (padded ? "mtGET_PEER_SHARD_INFO " : "mtGET_PEER_SHARD_INFO");
case 53: return (padded ? "mtPEER_SHARD_INFO " : "mtPEER_SHARD_INFO");
case 54: return (padded ? "mtVALIDATORLIST " : "mtVALIDATORLIST");
case 55: return (padded ? "mtSQUELCH " : "mtSQUELCH");
case 56: return (padded ? "mtVALIDATORLISTCOLLECTION " : "mtVALIDATORLISTCOLLECTION");
case 57: return (padded ? "mtPROOF_PATH_REQ " : "mtPROOF_PATH_REQ");
case 58: return (padded ? "mtPROOF_PATH_RESPONSE " : "mtPROOF_PATH_RESPONSE");
case 59: return (padded ? "mtREPLAY_DELTA_REQ " : "mtREPLAY_DELTA_REQ");
case 60: return (padded ? "mtREPLAY_DELTA_RESPONSE " : "mtREPLAY_DELTA_RESPONSE");
case 61: return (padded ? "mtGET_PEER_SHARD_INFO_V2 " : "mtGET_PEER_SHARD_INFO_V2");
case 62: return (padded ? "mtPEER_SHARD_INFO_V2 " : "mtPEER_SHARD_INFO_V2");
case 63: return (padded ? "mtHAVE_TRANSACTIONS " : "mtHAVE_TRANSACTIONS");
case 64: return (padded ? "mtTRANSACTIONS " : "mtTRANSACTIONS");
case 65: return (padded ? "mtRESOURCE_REPORT " : "mtRESOURCE_REPORT");
default: return (padded ? "mtUNKNOWN_PACKET " : mtUNKNOWN);
}
}
int32_t packet_id(char* packet_name)
{
if (stricmp("mtMANIFESTS", packet_name) == 0) return 2;
if (stricmp("mtPING", packet_name) == 0) return 3;
if (stricmp("mtCLUSTER", packet_name) == 0) return 5;
if (stricmp("mtENDPOINTS", packet_name) == 0) return 15;
if (stricmp("mtTRANSACTION", packet_name) == 0) return 30;
if (stricmp("mtGET_LEDGER", packet_name) == 0) return 31;
if (stricmp("mtLEDGER_DATA", packet_name) == 0) return 32;
if (stricmp("mtPROPOSE_LEDGER", packet_name) == 0) return 33;
if (stricmp("mtSTATUS_CHANGE", packet_name) == 0) return 34;
if (stricmp("mtHAVE_SET", packet_name) == 0) return 35;
if (stricmp("mtVALIDATION", packet_name) == 0) return 41;
if (stricmp("mtGET_OBJECTS", packet_name) == 0) return 42;
if (stricmp("mtGET_SHARD_INFO", packet_name) == 0) return 50;
if (stricmp("mtSHARD_INFO", packet_name) == 0) return 51;
if (stricmp("mtGET_PEER_SHARD_INFO", packet_name) == 0) return 52;
if (stricmp("mtPEER_SHARD_INFO", packet_name) == 0) return 53;
if (stricmp("mtVALIDATORLIST", packet_name) == 0) return 54;
if (stricmp("mtSQUELCH", packet_name) == 0) return 55;
if (stricmp("mtVALIDATORLISTCOLLECTION", packet_name) == 0) return 56;
if (stricmp("mtPROOF_PATH_REQ", packet_name) == 0) return 57;
if (stricmp("mtPROOF_PATH_RESPONSE", packet_name) == 0) return 58;
if (stricmp("mtREPLAY_DELTA_REQ", packet_name) == 0) return 59;
if (stricmp("mtREPLAY_DELTA_RESPONSE", packet_name) == 0) return 60;
if (stricmp("mtGET_PEER_SHARD_INFO_V2", packet_name) == 0) return 61;
if (stricmp("mtPEER_SHARD_INFO_V2", packet_name) == 0) return 62;
if (stricmp("mtHAVE_TRANSACTIONS", packet_name) == 0) return 63;
if (stricmp("mtTRANSACTIONS", packet_name) == 0) return 64;
if (stricmp("mtRESOURCE_REPORT", packet_name) == 0) return 65;
return -1;
}
std::map<int, std::pair<uint64_t, uint64_t>> counters; // packet type => [ packet_count, total_bytes ];
void rpad(char* output, int padding_chars)
{
int i = strlen(output);
while (padding_chars -i > 0)
output[i++] = ' ';
output[i] = '\0';
}
void human_readable_double(double bytes, char* output, char* end)
{
char* suffix[] = {"B", "K", "M", "G", "T"};
char length = sizeof(suffix) / sizeof(suffix[0]);
int i = 0;
while (bytes > 1024 && i < length - 1)
{
bytes /= 1024;
i++;
}
sprintf(output, "%.02lf %s%s", bytes, suffix[i], (end ? end : ""), i);
}
void human_readable(uint64_t bytes, char* output, char* end)
{
human_readable_double(bytes, output, end);
}
#define PAD 20
time_t last_print = 0;
std::set<int> show; // if this is set then only show these packets
std::set<int> hide; // if this is set then only show packets other than these packets, this is mut excl with above
void process_packet(
SSL* ssl,
int packet_type,
unsigned char* packet_buffer,
size_t packet_len,
int compressed,
uint32_t uncompressed_size)
{
time_t time_now = time(NULL);
int display = (slow ? 0 : 1);
if (slow && time_now - last_print >= 5)
{
last_print = time_now;
display = 1;
}
if (counters.find(packet_type) == counters.end())
counters.emplace(std::pair<int, std::pair<uint64_t, uint64_t>>{packet_type, std::pair<uint64_t, uint64_t>{1,packet_len}});
else
{
auto& p = counters[packet_type];
p.first++;
p.second += packet_len;
}
if (packet_type == 3) //mtPing
{
protocol::TMPing ping;
bool success = ping.ParseFromArray( packet_buffer, packet_len ) ;
if (!no_dump && display)
printf("%u mtPING - replying PONG\n");
ping.set_type(protocol::TMPing_pingType_ptPONG);
//unsigned char* buf = (unsigned char*) malloc(ping.ByteSizeLong());
ping.SerializeToArray(packet_buffer, packet_len);
uint32_t reply_len = packet_len;
uint16_t reply_type = 3;
// write reply header
unsigned char header[6];
header[0] = (reply_len >> 24) & 0xff;
header[1] = (reply_len >> 16) & 0xff;
header[2] = (reply_len >> 8) & 0xff;
header[3] = reply_len & 0xff;
header[4] = (reply_type >> 8) & 0xff;
header[5] = reply_type & 0xff;
SSL_write(ssl, header, 6);
SSL_write(ssl, packet_buffer, packet_len);
return;
}
if (!no_dump && display &&
((show.size() > 0 && show.find(packet_type) != show.end()) ||
(hide.size() > 0 && hide.find(packet_type) == hide.end()) ||
(show.size() == 0 && hide.size() == 0)))
{
switch (packet_type)
{
case 2: // mtMANIFESTS
{
protocol::TMManifests mans;
bool success = mans.ParseFromArray(packet_buffer, packet_len);
printf("parsed manifests: %s\n", (success ? "yes" : "no"));
printf("mtManifests contains %d manifests\n", mans.list_size());
for (int i = 0; i < mans.list_size(); ++i)
{
protocol::TMManifest const& man = mans.list(i);
const std::string& sto = man.stobject();
printf("Manifest %d is %d bytes:\n", i, sto.size());
const unsigned char* x = (const unsigned char*)(sto.c_str());
print_hex(x, sto.size());
}
break;
}
case 5: // mtCLUSTER
{
break;
}
case 15: // mtENDPOINTS
{
break;
}
case 30: // mtTRANSACTION
{ //rawTransaction
protocol::TMTransaction txn;
bool success = txn.ParseFromArray( packet_buffer, packet_len );
printf("%lu mtTRANSACTION %s\n", time(NULL), (success ? "" : "<error parsing>") );
const std::string& st = txn.rawtransaction();
print_hex(st.c_str(), st.size());
if (success)
print_sto(st);
break;
break;
}
case 31: // mtGET_LEDGER
{
protocol::TMGetLedger gl;
bool success = gl.ParseFromArray( packet_buffer, packet_len );
uint32_t info_type = gl.itype();
uint32_t ledger_type = gl.ltype();
uint8_t* ledger_hash = (uint8_t*)(gl.ledgerhash().c_str());
uint32_t ledger_seq = gl.ledgerseq();
uint32_t len = gl.nodeids_size();
printf("%lu mtGET_LEDGER seq=%u hash=", time(NULL), ledger_seq);
for (int i = 0; i < 32; ++i)
printf("%02X", ledger_hash[i]);
printf(" itype=%d ltype=%d\n", info_type, ledger_type);
/*
for (int i = 0; i < len; ++i)
{
const std::string& id = gl.nodeids(i);
}
*/
break;
}
case 32: // mtLEDGER_DATA
{
break;
}
/*
message TMProposeSet
{
required uint32 proposeSeq = 1;
required bytes currentTxHash = 2; // the hash of the ledger we are proposing
required bytes nodePubKey = 3;
required uint32 closeTime = 4;
required bytes signature = 5; // signature of above fields
required bytes previousledger = 6;
repeated bytes addedTransactions = 10; // not required if number is large
repeated bytes removedTransactions = 11; // not required if number is large
// node vouches signature is correct
optional bool checkedSignature = 7 [deprecated=true];
// Number of hops traveled
optional uint32 hops = 12 [deprecated=true];
}
*/
//1636450323 mtPROPOSE_LEDGER seq=0 set= ctime=6897655230000000000000000000000000000000000000000000000000000000000000000 pub=034E305DEEEF38A71F800EB48D80F8FDA50D3948E8BBD60C7D802A7CDD707FC286
case 33: // mtPROPOSE_LEDGER
{
protocol::TMProposeSet ps;
bool success = ps.ParseFromArray( packet_buffer, packet_len );
uint8_t* set_hash = (uint8_t*)(ps.currenttxhash().c_str());
uint8_t* node_pub = (uint8_t*)(ps.nodepubkey().c_str());
printf("%lu mtPROPOSE_LEDGER seq=%u set=", time(NULL), ps.proposeseq());
for (int i = 0 ; i < 32; ++i)
printf("%02X", set_hash[i]);
printf(" pub=");
for (int i = 0; i < ps.nodepubkey().size(); ++i)
printf("%02X", node_pub[i]);
printf(" ctime=%u", ps.closetime());
printf("\n");
break;
}
case 34: // mtSTATUS_CHANGE
{
/*
enum NodeStatus
{
nsCONNECTING = 1; // acquiring connections
nsCONNECTED = 2; // convinced we are connected to the real network
nsMONITORING = 3; // we know what the previous ledger is
nsVALIDATING = 4; // we have the full ledger contents
nsSHUTTING = 5; // node is shutting down
}
enum NodeEvent
{
neCLOSING_LEDGER = 1; // closing a ledger because its close time has come
neACCEPTED_LEDGER = 2; // accepting a closed ledger, we have finished computing it
neSWITCHED_LEDGER = 3; // changing due to network consensus
neLOST_SYNC = 4;
}
*/
protocol::TMStatusChange status;
bool success = status.ParseFromArray(packet_buffer, packet_len);
printf("%d mtSTATUS_CHANGE %s", time(NULL), (success ? "": "<error parsing>"));
if (status.has_newstatus())
{
int s = status.newstatus();
printf(" stat=%d %s", s,
(s == 1 ? "CONNECTING" :
(s == 2 ? "CONNECTED" :
(s == 3 ? "MONITORING" :
(s == 4 ? "VALIDATING" :
(s == 5 ? "SHUTTING" : "UNKNOWN_STATUS"))))));
}
if (status.has_newevent())
{
int e = status.newevent();
printf(" evnt=%d %s", e,
(e == 1 ? "CLOSING_LEDGER" :
(e == 2 ? "ACCEPTED_LEDGER" :
(e == 3 ? "SWITCHED_LEDGER" :
(e == 4 ? "LOST_SYNC" : "UNKNOWN_EVENT")))));
}
if (status.has_ledgerseq())
printf(" seq=%d", status.ledgerseq());
if (status.has_ledgerhash())
{
uint8_t* ledger_hash = (uint8_t*)(status.ledgerhash().c_str());
printf(" hash=");
for (int i = 0; i < 32; ++i)
printf("%02X", ledger_hash[i]);
}
if (status.has_ledgerhashprevious())
{
uint8_t* prev_hash = (uint8_t*)(status.ledgerhashprevious().c_str());
printf(" prev=");
for (int i = 0; i < 32; ++i)
printf("%02X", prev_hash[i]);
}
/*
message TMStatusChange
{
optional NodeStatus newStatus = 1;
optional NodeEvent newEvent = 2;
optional uint32 ledgerSeq = 3;
optional bytes ledgerHash = 4;
optional bytes ledgerHashPrevious = 5;
optional uint64 networkTime = 6;
optional uint32 firstSeq = 7;
optional uint32 lastSeq = 8;
}
*/
if (status.has_networktime())
printf(" time=%lu", status.networktime());
if (status.has_firstseq())
printf(" fseq=%u", status.firstseq());
if (status.has_lastseq())
printf(" lseq=%u", status.lastseq());
printf("\n");
break;
}
case 35: // mtHAVE_SET
{
break;
}
case 41: // mtVALIDATION
{
protocol::TMValidation validation;
bool success = validation.ParseFromArray( packet_buffer, packet_len );
const std::string& stvalidation = validation.validation();
printf("%d mtVALIDATION %s\n", time(NULL), (success ? "":"<error parsing>"));
print_hex(stvalidation.c_str(), stvalidation.size());
if (success)
print_sto(stvalidation);
break;
}
case 42: // mtGET_OBJECTS
{
break;
}
case 50: // mtGET_SHARD_INFO
{
break;
}
case 51: // mtSHARD_INFO
{
break;
}
case 52: // mtGET_PEER_SHARD_INFO
{
break;
}
case 53: // mtPEER_SHARD_INFO
{
break;
}
case 54: // mtVALIDATORLIST
{
break;
}
case 55: // mtSQUELCH
{
break;
}
case 56: // mtVALIDATORLISTCOLLECTION
{
break;
}
case 57: // mtPROOF_PATH_REQ
{
break;
}
case 58: // mtPROOF_PATH_RESPONSE
{
break;
}
case 59: // mtREPLAY_DELTA_REQ
{
break;
}
case 60: // mtREPLAY_DELTA_RESPONSE
{
break;
}
case 61: // mtGET_PEER_SHARD_INFO_V2
{
break;
}
case 62: // mtPEER_SHARD_INFO_V2
{
break;
}
case 63: // mtHAVE_TRANSACTIONS
{
break;
}
case 64: // mtTRANSACTIONS
{
break;
}
case 65: // mtRESOURCE_REPORT
{
protocol::TMResourceReport report;
bool success = report.ParseFromArray( packet_buffer, packet_len );
printf("%d mtRESOURCE_REPORT: %s\n", time(NULL), (success ? report.DebugString().data() : "<error parsing>"));
break;
}
default:
{
printf("mtUnknown [%d] size = %d, %s (print capped at 128):\n", packet_type, packet_len,
(compressed ? "compressed" : "uncompressed"));
print_hex(packet_buffer, packet_len);
}
}