forked from breadwallet/breadwallet-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BRPeer.c
1649 lines (1403 loc) · 61.9 KB
/
BRPeer.c
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
//
// BRPeer.c
//
// Created by Aaron Voisine on 9/2/15.
// Copyright (c) 2015 breadwallet LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "BRPeer.h"
#include "BRMerkleBlock.h"
#include "BRAddress.h"
#include "BRSet.h"
#include "BRArray.h"
#include "BRCrypto.h"
#include "BRInt.h"
#include <stdlib.h>
#include <float.h>
#include <inttypes.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define HEADER_LENGTH 24
#define MAX_MSG_LENGTH 0x02000000
#define MAX_GETDATA_HASHES 50000
#define ENABLED_SERVICES 0ULL // we don't provide full blocks to remote nodes
#define PROTOCOL_VERSION 70013
#define MIN_PROTO_VERSION 70002 // peers earlier than this protocol version not supported (need v0.9 txFee relay rules)
#define LOCAL_HOST ((UInt128) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x01 })
#define CONNECT_TIMEOUT 3.0
#define MESSAGE_TIMEOUT 10.0
#define WITNESS_FLAG 0x40000000
#define PTHREAD_STACK_SIZE (512 * 1024)
// the standard blockchain download protocol works as follows (for SPV mode):
// - local peer sends getblocks
// - remote peer reponds with inv containing up to 500 block hashes
// - local peer sends getdata with the block hashes
// - remote peer responds with multiple merkleblock and tx messages
// - remote peer sends inv containg 1 hash, of the most recent block
// - local peer sends getdata with the most recent block hash
// - remote peer responds with merkleblock
// - if local peer can't connect the most recent block to the chain (because it started more than 500 blocks behind), go
// back to first step and repeat until entire chain is downloaded
//
// we modify this sequence to improve sync performance and handle adding bip32 addresses to the bloom filter as needed:
// - local peer sends getheaders
// - remote peer responds with up to 2000 headers
// - local peer immediately sends getheaders again and then processes the headers
// - previous two steps repeat until a header within a week of earliestKeyTime is reached (further headers are ignored)
// - local peer sends getblocks
// - remote peer responds with inv containing up to 500 block hashes
// - local peer sends getdata with the block hashes
// - if there were 500 hashes, local peer sends getblocks again without waiting for remote peer
// - remote peer responds with multiple merkleblock and tx messages, followed by inv containing up to 500 block hashes
// - previous two steps repeat until an inv with fewer than 500 block hashes is received
// - local peer sends just getdata for the final set of fewer than 500 block hashes
// - remote peer responds with multiple merkleblock and tx messages
// - if at any point tx messages consume enough wallet addresses to drop below the bip32 chain gap limit, more addresses
// are generated and local peer sends filterload with an updated bloom filter
// - after filterload is sent, getdata is sent to re-request recent blocks that may contain new tx matching the filter
typedef enum {
inv_undefined = 0,
inv_tx = 1,
inv_block = 2,
inv_filtered_block = 3,
inv_witness_block = inv_block | WITNESS_FLAG,
inv_witness_tx = inv_tx | WITNESS_FLAG,
inv_filtered_witness_block = inv_filtered_block | WITNESS_FLAG
} inv_type;
typedef struct {
BRPeer peer; // superstruct on top of BRPeer
uint32_t magicNumber;
char host[INET6_ADDRSTRLEN];
BRPeerStatus status;
int waitingForNetwork;
volatile int needsFilterUpdate;
uint64_t nonce, feePerKb;
char *useragent;
uint32_t version, lastblock, earliestKeyTime, currentBlockHeight;
double startTime, pingTime;
volatile double disconnectTime, mempoolTime;
int sentVerack, gotVerack, sentGetaddr, sentFilter, sentGetdata, sentMempool, sentGetblocks;
UInt256 lastBlockHash;
BRMerkleBlock *currentBlock;
UInt256 *currentBlockTxHashes, *knownBlockHashes, *knownTxHashes;
BRSet *knownTxHashSet;
volatile int socket;
void *info;
void (*connected)(void *info);
void (*disconnected)(void *info, int error);
void (*relayedPeers)(void *info, const BRPeer peers[], size_t peersCount);
void (*relayedTx)(void *info, BRTransaction *tx);
void (*hasTx)(void *info, UInt256 txHash);
void (*rejectedTx)(void *info, UInt256 txHash, uint8_t code);
void (*relayedBlock)(void *info, BRMerkleBlock *block);
void (*notfound)(void *info, const UInt256 txHashes[], size_t txCount, const UInt256 blockHashes[],
size_t blockCount);
void (*setFeePerKb)(void *info, uint64_t feePerKb);
BRTransaction *(*requestedTx)(void *info, UInt256 txHash);
int (*networkIsReachable)(void *info);
void (*threadCleanup)(void *info);
void **volatile pongInfo;
void (**volatile pongCallback)(void *info, int success);
void *volatile mempoolInfo;
void (*volatile mempoolCallback)(void *info, int success);
pthread_t thread;
pthread_mutex_t lock;
} BRPeerContext;
void BRPeerSendVersionMessage(BRPeer *peer);
void BRPeerSendVerackMessage(BRPeer *peer);
void BRPeerSendAddr(BRPeer *peer);
inline static int _BRPeerIsIPv4(const BRPeer *peer)
{
return (peer->address.u64[0] == 0 && peer->address.u16[4] == 0 && peer->address.u16[5] == 0xffff);
}
static void _BRPeerAddKnownTxHashes(const BRPeer *peer, const UInt256 txHashes[], size_t txCount)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
UInt256 *knownTxHashes = ctx->knownTxHashes;
size_t i, j;
for (i = 0; i < txCount; i++) {
if (! BRSetContains(ctx->knownTxHashSet, &txHashes[i])) {
array_add(knownTxHashes, txHashes[i]);
if (ctx->knownTxHashes != knownTxHashes) { // check if knownTxHashes was moved to a new memory location
ctx->knownTxHashes = knownTxHashes;
BRSetClear(ctx->knownTxHashSet);
for (j = array_count(knownTxHashes); j > 0; j--) BRSetAdd(ctx->knownTxHashSet, &knownTxHashes[j - 1]);
}
else BRSetAdd(ctx->knownTxHashSet, &knownTxHashes[array_count(knownTxHashes) - 1]);
}
}
}
static void _BRPeerDidConnect(BRPeer *peer)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
pthread_mutex_lock(&ctx->lock);
if (ctx->status == BRPeerStatusConnecting && ctx->sentVerack && ctx->gotVerack) {
peer_log(peer, "handshake completed");
ctx->disconnectTime = DBL_MAX;
ctx->status = BRPeerStatusConnected;
peer_log(peer, "connected with lastblock: %"PRIu32, ctx->lastblock);
pthread_mutex_unlock(&ctx->lock);
if (ctx->connected) ctx->connected(ctx->info);
}
else {
pthread_mutex_unlock(&ctx->lock);
}
}
static int _BRPeerAcceptVersionMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, strLen = 0, len = 0;
uint64_t recvServices, fromServices, nonce;
UInt128 recvAddr, fromAddr;
uint16_t recvPort, fromPort;
int r = 1;
if (85 > msgLen) {
peer_log(peer, "malformed version message, length is %zu, should be >= 85", msgLen);
r = 0;
}
else {
ctx->version = UInt32GetLE(&msg[off]);
off += sizeof(uint32_t);
peer->services = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
peer->timestamp = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
recvServices = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
recvAddr = UInt128Get(&msg[off]);
off += sizeof(UInt128);
recvPort = UInt16GetBE(&msg[off]);
off += sizeof(uint16_t);
fromServices = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
fromAddr = UInt128Get(&msg[off]);
off += sizeof(UInt128);
fromPort = UInt16GetBE(&msg[off]);
off += sizeof(uint16_t);
nonce = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
strLen = (size_t)BRVarInt(&msg[off], (off <= msgLen ? msgLen - off : 0), &len);
off += len;
if (off + strLen + sizeof(uint32_t) > msgLen) {
peer_log(peer, "malformed version message, length is %zu, should be %zu", msgLen,
off + strLen + sizeof(uint32_t));
r = 0;
}
else if (ctx->version < MIN_PROTO_VERSION) {
peer_log(peer, "protocol version %"PRIu32" not supported", ctx->version);
r = 0;
}
else {
array_clear(ctx->useragent);
array_add_array(ctx->useragent, &msg[off], strLen);
array_add(ctx->useragent, '\0');
off += strLen;
ctx->lastblock = UInt32GetLE(&msg[off]);
off += sizeof(uint32_t);
peer_log(peer, "got version %"PRIu32", services %"PRIx64", useragent:\"%s\"", ctx->version, peer->services,
ctx->useragent);
BRPeerSendVerackMessage(peer);
}
}
return r;
}
static int _BRPeerAcceptVerackMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
struct timeval tv;
int r = 1;
if (ctx->gotVerack) {
peer_log(peer, "got unexpected verack");
}
else {
gettimeofday(&tv, NULL);
ctx->pingTime = tv.tv_sec + (double)tv.tv_usec/1000000 - ctx->startTime; // use verack time as initial ping time
ctx->startTime = 0;
peer_log(peer, "got verack in %fs", ctx->pingTime);
ctx->gotVerack = 1;
_BRPeerDidConnect(peer);
}
return r;
}
// TODO: relay addresses
static int _BRPeerAcceptAddrMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, count = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off == 0 || off + count*30 > msgLen) {
peer_log(peer, "malformed addr message, length is %zu, should be %zu for %zu address(es)", msgLen,
BRVarIntSize(count) + 30*count, count);
r = 0;
}
else if (count > 1000) {
peer_log(peer, "dropping addr message, %zu is too many addresses, max is 1000", count);
}
else if (ctx->sentGetaddr) { // simple anti-tarpitting tactic, don't accept unsolicited addresses
BRPeer peers[count], p;
size_t peersCount = 0;
time_t now = time(NULL);
peer_log(peer, "got addr with %zu address(es)", count);
for (size_t i = 0; i < count; i++) {
p.timestamp = UInt32GetLE(&msg[off]);
off += sizeof(uint32_t);
p.services = UInt64GetLE(&msg[off]);
off += sizeof(uint64_t);
p.address = UInt128Get(&msg[off]);
off += sizeof(UInt128);
p.port = UInt16GetBE(&msg[off]);
off += sizeof(uint16_t);
if (! (p.services & SERVICES_NODE_NETWORK)) continue; // skip peers that don't carry full blocks
if (! _BRPeerIsIPv4(&p)) continue; // ignore IPv6 for now
// if address time is more than 10 min in the future or unknown, set to 5 days old
if (p.timestamp > now + 10*60 || p.timestamp == 0) p.timestamp = now - 5*24*60*60;
p.timestamp -= 2*60*60; // subtract two hours
peers[peersCount++] = p; // add it to the list
}
if (peersCount > 0 && ctx->relayedPeers) ctx->relayedPeers(ctx->info, peers, peersCount);
}
return r;
}
static int _BRPeerAcceptInvMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, count = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off == 0 || off + count*36 > msgLen) {
peer_log(peer, "malformed inv message, length is %zu, should be %zu for %zu item(s)", msgLen,
BRVarIntSize(count) + 36*count, count);
r = 0;
}
else if (count > MAX_GETDATA_HASHES) {
peer_log(peer, "dropping inv message, %zu is too many items, max is %d", count, MAX_GETDATA_HASHES);
}
else {
inv_type type;
const uint8_t *transactions[count], *blocks[count];
size_t i, j, txCount = 0, blockCount = 0;
peer_log(peer, "got inv with %zu item(s)", count);
for (i = 0; i < count; i++) {
type = UInt32GetLE(&msg[off]);
switch (type) { // inv messages only use inv_tx or inv_block
case inv_tx: transactions[txCount++] = &msg[off + sizeof(uint32_t)]; break;
case inv_block: blocks[blockCount++] = &msg[off + sizeof(uint32_t)]; break;
default: break;
}
off += 36;
}
if (txCount > 0 && ! ctx->sentFilter && ! ctx->sentMempool && ! ctx->sentGetblocks) {
peer_log(peer, "got inv message before loading a filter");
r = 0;
}
else if (txCount > 10000) { // sanity check
peer_log(peer, "too many transactions, disconnecting");
r = 0;
}
else if (ctx->currentBlockHeight > 0 && blockCount > 2 && blockCount < 500 &&
ctx->currentBlockHeight + array_count(ctx->knownBlockHashes) + blockCount < ctx->lastblock) {
peer_log(peer, "non-standard inv, %zu is fewer block hash(es) than expected", blockCount);
r = 0;
}
else {
if (! ctx->sentFilter && ! ctx->sentGetblocks) blockCount = 0;
if (blockCount == 1 && UInt256Eq(ctx->lastBlockHash, UInt256Get(blocks[0]))) blockCount = 0;
if (blockCount == 1) ctx->lastBlockHash = UInt256Get(blocks[0]);
UInt256 hash, blockHashes[blockCount], txHashes[txCount];
for (i = 0; i < blockCount; i++) {
blockHashes[i] = UInt256Get(blocks[i]);
// remember blockHashes in case we need to re-request them with an updated bloom filter
array_add(ctx->knownBlockHashes, blockHashes[i]);
}
while (array_count(ctx->knownBlockHashes) > MAX_GETDATA_HASHES) {
array_rm_range(ctx->knownBlockHashes, 0, array_count(ctx->knownBlockHashes)/3);
}
if (ctx->needsFilterUpdate) blockCount = 0;
for (i = 0, j = 0; i < txCount; i++) {
hash = UInt256Get(transactions[i]);
if (BRSetContains(ctx->knownTxHashSet, &hash)) {
if (ctx->hasTx) ctx->hasTx(ctx->info, hash);
}
else txHashes[j++] = hash;
}
_BRPeerAddKnownTxHashes(peer, txHashes, j);
if (j > 0 || blockCount > 0) BRPeerSendGetdata(peer, txHashes, j, blockHashes, blockCount);
// to improve chain download performance, if we received 500 block hashes, request the next 500 block hashes
if (blockCount >= 500) {
UInt256 locators[] = { blockHashes[blockCount - 1], blockHashes[0] };
BRPeerSendGetblocks(peer, locators, 2, UINT256_ZERO);
}
if (txCount > 0 && ctx->mempoolCallback) {
peer_log(peer, "got initial mempool response");
BRPeerSendPing(peer, ctx->mempoolInfo, ctx->mempoolCallback);
ctx->mempoolCallback = NULL;
pthread_mutex_lock(&ctx->lock);
ctx->mempoolTime = DBL_MAX;
pthread_mutex_unlock(&ctx->lock);
}
}
}
return r;
}
static int _BRPeerAcceptTxMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
BRTransaction *tx = BRTransactionParse(msg, msgLen);
UInt256 txHash;
int r = 1;
if (! tx) {
peer_log(peer, "malformed tx message with length: %zu", msgLen);
r = 0;
}
else if (! ctx->sentFilter && ! ctx->sentGetdata) {
peer_log(peer, "got tx message before loading filter");
BRTransactionFree(tx);
r = 0;
}
else {
txHash = tx->txHash;
peer_log(peer, "got tx: %s", u256hex(txHash));
if (ctx->relayedTx) {
ctx->relayedTx(ctx->info, tx);
}
else BRTransactionFree(tx);
if (ctx->currentBlock) { // we're collecting tx messages for a merkleblock
for (size_t i = array_count(ctx->currentBlockTxHashes); i > 0; i--) {
if (! UInt256Eq(txHash, ctx->currentBlockTxHashes[i - 1])) continue;
array_rm(ctx->currentBlockTxHashes, i - 1);
break;
}
if (array_count(ctx->currentBlockTxHashes) == 0) { // we received the entire block including all matched tx
BRMerkleBlock *block = ctx->currentBlock;
ctx->currentBlock = NULL;
if (ctx->relayedBlock) ctx->relayedBlock(ctx->info, block);
}
}
}
return r;
}
static int _BRPeerAcceptHeadersMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, count = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off == 0 || off + 81*count > msgLen) {
peer_log(peer, "malformed headers message, length is %zu, should be %zu for %zu header(s)", msgLen,
BRVarIntSize(count) + 81*count, count);
r = 0;
}
else {
peer_log(peer, "got %zu header(s)", count);
// To improve chain download performance, if this message contains 2000 headers then request the next 2000
// headers immediately, and switch to requesting blocks when we receive a header newer than earliestKeyTime
uint32_t timestamp = (count > 0) ? UInt32GetLE(&msg[off + 81*(count - 1) + 68]) : 0;
if (count >= 2000 || (timestamp > 0 && timestamp + 7*24*60*60 + BLOCK_MAX_TIME_DRIFT >= ctx->earliestKeyTime)) {
size_t last = 0;
time_t now = time(NULL);
UInt256 locators[2];
BRSHA256_2(&locators[0], &msg[off + 81*(count - 1)], 80);
BRSHA256_2(&locators[1], &msg[off], 80);
if (timestamp > 0 && timestamp + 7*24*60*60 + BLOCK_MAX_TIME_DRIFT >= ctx->earliestKeyTime) {
// request blocks for the remainder of the chain
timestamp = (++last < count) ? UInt32GetLE(&msg[off + 81*last + 68]) : 0;
while (timestamp > 0 && timestamp + 7*24*60*60 + BLOCK_MAX_TIME_DRIFT < ctx->earliestKeyTime) {
timestamp = (++last < count) ? UInt32GetLE(&msg[off + 81*last + 68]) : 0;
}
BRSHA256_2(&locators[0], &msg[off + 81*(last - 1)], 80);
BRPeerSendGetblocks(peer, locators, 2, UINT256_ZERO);
}
else BRPeerSendGetheaders(peer, locators, 2, UINT256_ZERO);
for (size_t i = 0; r && i < count; i++) {
BRMerkleBlock *block = BRMerkleBlockParse(&msg[off + 81*i], 81);
if (! block) {
peer_log(peer, "malformed headers message with length: %zu", msgLen);
r = 0;
}
else if (! BRMerkleBlockIsValid(block, (uint32_t)now)) {
peer_log(peer, "invalid block header: %s", u256hex(block->blockHash));
BRMerkleBlockFree(block);
r = 0;
}
else if (ctx->relayedBlock) {
ctx->relayedBlock(ctx->info, block);
}
else BRMerkleBlockFree(block);
}
}
else {
peer_log(peer, "non-standard headers message, %zu is fewer header(s) than expected", count);
r = 0;
}
}
return r;
}
static int _BRPeerAcceptGetaddrMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
peer_log(peer, "got getaddr");
BRPeerSendAddr(peer);
return 1;
}
static int _BRPeerAcceptGetdataMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, count = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off == 0 || off + 36*count > msgLen) {
peer_log(peer, "malformed getdata message, length is %zu, should %zu for %zu item(s)", msgLen,
BRVarIntSize(count) + 36*count, count);
r = 0;
}
else if (count > MAX_GETDATA_HASHES) {
peer_log(peer, "dropping getdata message, %zu is too many items, max is %d", count, MAX_GETDATA_HASHES);
}
else {
struct inv_item { uint8_t item[36]; } *notfound = NULL;
BRTransaction *tx = NULL;
peer_log(peer, "got getdata with %zu item(s)", count);
for (size_t i = 0; i < count; i++) {
inv_type type = UInt32GetLE(&msg[off]);
UInt256 hash = UInt256Get(&msg[off + sizeof(uint32_t)]);
switch (type) {
case inv_witness_tx: // drop through
case inv_tx:
if (ctx->requestedTx) tx = ctx->requestedTx(ctx->info, hash);
if (tx && BRTransactionVSize(tx) < TX_MAX_SIZE) {
uint8_t buf[BRTransactionSerialize(tx, NULL, 0)];
size_t bufLen = BRTransactionSerialize(tx, buf, sizeof(buf));
char txHex[bufLen*2 + 1];
for (size_t j = 0; j < bufLen; j++) {
sprintf(&txHex[j*2], "%02x", buf[j]);
}
peer_log(peer, "publishing tx: %s", txHex);
BRPeerSendMessage(peer, buf, bufLen, MSG_TX);
break;
}
// fall through
default:
if (! notfound) array_new(notfound, 1);
array_add(notfound, *(struct inv_item *)&msg[off]);
break;
}
off += 36;
}
if (notfound) {
size_t bufLen = BRVarIntSize(array_count(notfound)) + 36*array_count(notfound), o = 0;
uint8_t *buf = malloc(bufLen);
assert(buf != NULL);
o += BRVarIntSet(&buf[o], (o <= bufLen ? bufLen - o : 0), array_count(notfound));
memcpy(&buf[o], notfound, 36*array_count(notfound));
o += 36*array_count(notfound);
array_free(notfound);
BRPeerSendMessage(peer, buf, o, MSG_NOTFOUND);
free(buf);
}
}
return r;
}
static int _BRPeerAcceptNotfoundMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, count = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off == 0 || off + 36*count > msgLen) {
peer_log(peer, "malformed notfound message, length is %zu, should be %zu for %zu item(s)", msgLen,
BRVarIntSize(count) + 36*count, count);
r = 0;
}
else if (count > MAX_GETDATA_HASHES) {
peer_log(peer, "dropping notfound message, %zu is too many items, max is %d", count, MAX_GETDATA_HASHES);
}
else {
inv_type type;
UInt256 *txHashes, *blockHashes, hash;
peer_log(peer, "got notfound with %zu item(s)", count);
array_new(txHashes, 1);
array_new(blockHashes, 1);
for (size_t i = 0; i < count; i++) {
type = UInt32GetLE(&msg[off]);
hash = UInt256Get(&msg[off + sizeof(uint32_t)]);
switch (type) {
case inv_witness_tx: // drop through
case inv_tx: array_add(txHashes, hash); break;
case inv_filtered_witness_block: // drop through
case inv_witness_block: // drop through
case inv_filtered_block: // drop through
case inv_block: array_add(blockHashes, hash); break;
default: break;
}
off += 36;
}
if (ctx->notfound) {
ctx->notfound(ctx->info, txHashes, array_count(txHashes), blockHashes, array_count(blockHashes));
}
array_free(txHashes);
array_free(blockHashes);
}
return r;
}
static int _BRPeerAcceptPingMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
int r = 1;
if (sizeof(uint64_t) > msgLen) {
peer_log(peer, "malformed ping message, length is %zu, should be %zu", msgLen, sizeof(uint64_t));
r = 0;
}
else {
peer_log(peer, "got ping");
BRPeerSendMessage(peer, msg, msgLen, MSG_PONG);
}
return r;
}
static int _BRPeerAcceptPongMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
struct timeval tv;
double pingTime;
int r = 1;
if (sizeof(uint64_t) > msgLen) {
peer_log(peer, "malformed pong message, length is %zu, should be %zu", msgLen, sizeof(uint64_t));
r = 0;
}
else if (UInt64GetLE(msg) != ctx->nonce) {
peer_log(peer, "pong message has wrong nonce: %"PRIu64", expected: %"PRIu64, UInt64GetLE(msg), ctx->nonce);
r = 0;
}
else if (array_count(ctx->pongCallback) == 0) {
peer_log(peer, "got unexpected pong");
r = 0;
}
else {
if (ctx->startTime > 1) {
gettimeofday(&tv, NULL);
pingTime = tv.tv_sec + (double)tv.tv_usec/1000000 - ctx->startTime;
// 50% low pass filter on current ping time
ctx->pingTime = ctx->pingTime*0.5 + pingTime*0.5;
ctx->startTime = 0;
peer_log(peer, "got pong in %fs", pingTime);
}
else peer_log(peer, "got pong");
if (array_count(ctx->pongCallback) > 0) {
void (*pongCallback)(void *, int) = ctx->pongCallback[0];
void *pongInfo = ctx->pongInfo[0];
array_rm(ctx->pongCallback, 0);
array_rm(ctx->pongInfo, 0);
if (pongCallback) pongCallback(pongInfo, 1);
}
}
return r;
}
static int _BRPeerAcceptMerkleblockMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
// Bitcoin nodes don't support querying arbitrary transactions, only transactions not yet accepted in a block. After
// a merkleblock message, the remote node is expected to send tx messages for the tx referenced in the block. When a
// non-tx message is received we should have all the tx in the merkleblock.
BRPeerContext *ctx = (BRPeerContext *)peer;
BRMerkleBlock *block = BRMerkleBlockParse(msg, msgLen);
int r = 1;
if (! block) {
peer_log(peer, "malformed merkleblock message with length: %zu", msgLen);
r = 0;
}
else if (! BRMerkleBlockIsValid(block, (uint32_t)time(NULL))) {
peer_log(peer, "invalid merkleblock: %s", u256hex(block->blockHash));
BRMerkleBlockFree(block);
block = NULL;
r = 0;
}
else if (! ctx->sentFilter && ! ctx->sentGetdata) {
peer_log(peer, "got merkleblock message before loading a filter");
BRMerkleBlockFree(block);
block = NULL;
r = 0;
}
else {
size_t count = BRMerkleBlockTxHashes(block, NULL, 0);
UInt256 _hashes[(sizeof(UInt256)*count <= 0x1000) ? count : 0],
*hashes = (sizeof(UInt256)*count <= 0x1000) ? _hashes : malloc(count*sizeof(*hashes));
assert(hashes != NULL);
count = BRMerkleBlockTxHashes(block, hashes, count);
for (size_t i = count; i > 0; i--) { // reverse order for more efficient removal as tx arrive
if (BRSetContains(ctx->knownTxHashSet, &hashes[i - 1])) continue;
array_add(ctx->currentBlockTxHashes, hashes[i - 1]);
}
if (hashes != _hashes) free(hashes);
}
if (block) {
if (array_count(ctx->currentBlockTxHashes) > 0) { // wait til we get all tx messages before processing the block
ctx->currentBlock = block;
}
else if (ctx->relayedBlock) {
ctx->relayedBlock(ctx->info, block);
}
else BRMerkleBlockFree(block);
}
return r;
}
// described in BIP61: https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki
static int _BRPeerAcceptRejectMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
size_t off = 0, strLen = (size_t)BRVarInt(msg, msgLen, &off);
int r = 1;
if (off + strLen + sizeof(uint8_t) > msgLen) {
peer_log(peer, "malformed reject message, length is %zu, should be >= %zu", msgLen,
off + strLen + sizeof(uint8_t));
r = 0;
}
else {
char type[(strLen < 0x1000) ? strLen + 1 : 0x1000];
uint8_t code;
size_t len = 0, hashLen = 0;
strncpy(type, (const char *)&msg[off], sizeof(type) - 1);
type[sizeof(type) - 1] = '\0';
off += strLen;
code = msg[off++];
strLen = (size_t)BRVarInt(&msg[off], (off <= msgLen ? msgLen - off : 0), &len);
off += len;
if (strncmp(type, MSG_TX, sizeof(type)) == 0) hashLen = sizeof(UInt256);
if (off + strLen + hashLen > msgLen) {
peer_log(peer, "malformed reject message, length is %zu, should be >= %zu", msgLen, off + strLen + hashLen);
r = 0;
}
else {
char reason[(strLen < 0x1000) ? strLen + 1 : 0x1000];
UInt256 txHash = UINT256_ZERO;
strncpy(reason, (const char *)&msg[off], sizeof(reason) - 1);
reason[sizeof(reason) - 1] = '\0';
off += strLen;
if (hashLen == sizeof(UInt256)) txHash = UInt256Get(&msg[off]);
off += hashLen;
if (! UInt256IsZero(txHash)) {
peer_log(peer, "rejected %s code: 0x%x reason: \"%s\" txid: %s", type, code, reason, u256hex(txHash));
if (ctx->rejectedTx) ctx->rejectedTx(ctx->info, txHash, code);
}
else peer_log(peer, "rejected %s code: 0x%x reason: \"%s\"", type, code, reason);
}
}
return r;
}
// BIP133: https://github.com/bitcoin/bips/blob/master/bip-0133.mediawiki
static int _BRPeerAcceptFeeFilterMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
int r = 1;
if (sizeof(uint64_t) > msgLen) {
peer_log(peer, "malformed feefilter message, length is %zu, should be >= %zu", msgLen, sizeof(uint64_t));
r = 0;
}
else {
pthread_mutex_lock(&ctx->lock);
ctx->feePerKb = UInt64GetLE(msg);
pthread_mutex_unlock(&ctx->lock);
peer_log(peer, "got feefilter with rate %"PRIu64, ctx->feePerKb);
if (ctx->setFeePerKb) ctx->setFeePerKb(ctx->info, ctx->feePerKb);
}
return r;
}
static int _BRPeerAcceptMessage(BRPeer *peer, const uint8_t *msg, size_t msgLen, const char *type)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
int r = 1;
if (ctx->currentBlock && strncmp(MSG_TX, type, 12) != 0) { // if we receive a non-tx message, merkleblock is done
peer_log(peer, "incomplete merkleblock %s, expected %zu more tx, got %s", u256hex(ctx->currentBlock->blockHash),
array_count(ctx->currentBlockTxHashes), type);
array_clear(ctx->currentBlockTxHashes);
ctx->currentBlock = NULL;
r = 0;
}
else if (strncmp(MSG_VERSION, type, 12) == 0) r = _BRPeerAcceptVersionMessage(peer, msg, msgLen);
else if (strncmp(MSG_VERACK, type, 12) == 0) r = _BRPeerAcceptVerackMessage(peer, msg, msgLen);
else if (strncmp(MSG_ADDR, type, 12) == 0) r = _BRPeerAcceptAddrMessage(peer, msg, msgLen);
else if (strncmp(MSG_INV, type, 12) == 0) r = _BRPeerAcceptInvMessage(peer, msg, msgLen);
else if (strncmp(MSG_TX, type, 12) == 0) r = _BRPeerAcceptTxMessage(peer, msg, msgLen);
else if (strncmp(MSG_HEADERS, type, 12) == 0) r = _BRPeerAcceptHeadersMessage(peer, msg, msgLen);
else if (strncmp(MSG_GETADDR, type, 12) == 0) r = _BRPeerAcceptGetaddrMessage(peer, msg, msgLen);
else if (strncmp(MSG_GETDATA, type, 12) == 0) r = _BRPeerAcceptGetdataMessage(peer, msg, msgLen);
else if (strncmp(MSG_NOTFOUND, type, 12) == 0) r = _BRPeerAcceptNotfoundMessage(peer, msg, msgLen);
else if (strncmp(MSG_PING, type, 12) == 0) r = _BRPeerAcceptPingMessage(peer, msg, msgLen);
else if (strncmp(MSG_PONG, type, 12) == 0) r = _BRPeerAcceptPongMessage(peer, msg, msgLen);
else if (strncmp(MSG_MERKLEBLOCK, type, 12) == 0) r = _BRPeerAcceptMerkleblockMessage(peer, msg, msgLen);
else if (strncmp(MSG_REJECT, type, 12) == 0) r = _BRPeerAcceptRejectMessage(peer, msg, msgLen);
else if (strncmp(MSG_FEEFILTER, type, 12) == 0) r = _BRPeerAcceptFeeFilterMessage(peer, msg, msgLen);
else peer_log(peer, "dropping %s, length %zu, not implemented", type, msgLen);
return r;
}
static int _BRPeerOpenSocket(BRPeer *peer, int domain, double timeout, int *error)
{
BRPeerContext *ctx = (BRPeerContext *)peer;
struct sockaddr_storage addr;
struct timeval tv;
fd_set fds;
socklen_t addrLen, optLen;
int count, arg = 0, err = 0, on = 1, r = 1;
ctx->socket = socket(domain, SOCK_STREAM, 0);
if (ctx->socket < 0) {
err = errno;
r = 0;
}
else {
tv.tv_sec = 1; // one second timeout for send/receive, so thread doesn't block for too long
tv.tv_usec = 0;
setsockopt(ctx->socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(ctx->socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
setsockopt(ctx->socket, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
#ifdef SO_NOSIGPIPE // BSD based systems have a SO_NOSIGPIPE socket option to supress SIGPIPE signals
setsockopt(ctx->socket, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
#endif
arg = fcntl(ctx->socket, F_GETFL, NULL);
if (arg < 0 || fcntl(ctx->socket, F_SETFL, arg | O_NONBLOCK) < 0) r = 0; // temporarily set socket non-blocking
if (! r) err = errno;
}
if (r) {
memset(&addr, 0, sizeof(addr));
if (domain == PF_INET6) {
((struct sockaddr_in6 *)&addr)->sin6_family = AF_INET6;
((struct sockaddr_in6 *)&addr)->sin6_addr = *(struct in6_addr *)&peer->address;
((struct sockaddr_in6 *)&addr)->sin6_port = htons(peer->port);
addrLen = sizeof(struct sockaddr_in6);
}
else {
((struct sockaddr_in *)&addr)->sin_family = AF_INET;
((struct sockaddr_in *)&addr)->sin_addr = *(struct in_addr *)&peer->address.u32[3];
((struct sockaddr_in *)&addr)->sin_port = htons(peer->port);
addrLen = sizeof(struct sockaddr_in);
}
if (connect(ctx->socket, (struct sockaddr *)&addr, addrLen) < 0) err = errno;
if (err == EINPROGRESS) {
err = 0;
optLen = sizeof(err);
tv.tv_sec = timeout;
tv.tv_usec = (long)(timeout*1000000) % 1000000;
FD_ZERO(&fds);
FD_SET(ctx->socket, &fds);
count = select(ctx->socket + 1, NULL, &fds, NULL, &tv);
if (count <= 0 || getsockopt(ctx->socket, SOL_SOCKET, SO_ERROR, &err, &optLen) < 0 || err) {
if (count == 0) err = ETIMEDOUT;
if (count < 0 || ! err) err = errno;
r = 0;
}
}
else if (err && domain == PF_INET6 && _BRPeerIsIPv4(peer)) {
return _BRPeerOpenSocket(peer, PF_INET, timeout, error); // fallback to IPv4
}
else if (err) r = 0;
if (r) peer_log(peer, "socket connected");
fcntl(ctx->socket, F_SETFL, arg); // restore socket non-blocking status
}
if (! r && err) peer_log(peer, "connect error: %s", strerror(err));
if (error && err) *error = err;
return r;
}
static int _peerCheckAndGetSocket (BRPeerContext *ctx, int *socket) {
int exists;
pthread_mutex_lock(&ctx->lock);
exists = ctx->socket >= 0;
if (NULL != socket) *socket = ctx->socket;
pthread_mutex_unlock(&ctx->lock);
return exists;
}
static int _peerGetSocket (BRPeerContext *ctx) {
int socket;
pthread_mutex_lock(&ctx->lock);
socket = ctx->socket;
pthread_mutex_unlock(&ctx->lock);
return socket;
}
static double _peerGetDisconnectTime (BRPeerContext *ctx) {
double value;
pthread_mutex_lock(&ctx->lock);
value = ctx->disconnectTime;
pthread_mutex_unlock(&ctx->lock);
return value;
}
static double _peerGetMempoolTime (BRPeerContext *ctx) {
double value;
pthread_mutex_lock(&ctx->lock);
value = ctx->mempoolTime;
pthread_mutex_unlock(&ctx->lock);
return value;
}
static void *_peerThreadRoutine(void *arg)
{
BRPeer *peer = arg;
BRPeerContext *ctx = arg;
int socket, error = 0;
pthread_cleanup_push(ctx->threadCleanup, ctx->info);
if (_BRPeerOpenSocket(peer, PF_INET6, CONNECT_TIMEOUT, &error)) {
struct timeval tv;
double time = 0, msgTimeout;
uint8_t header[HEADER_LENGTH], *payload = malloc(0x1000);
size_t len = 0, payloadLen = 0x1000;
ssize_t n = 0;