This repository has been archived by the owner on Jul 13, 2020. It is now read-only.
forked from breadwallet/breadwallet-core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BRPeerManager.c
2009 lines (1669 loc) · 82.6 KB
/
BRPeerManager.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
//
// BRPeerManager.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 "BRPeerManager.h"
#include "BRBloomFilter.h"
#include "BRSet.h"
#include "BRArray.h"
#include "BRInt.h"
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <limits.h>
#include <time.h>
#include <assert.h>
#include <pthread.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PROTOCOL_TIMEOUT 20.0
#define MAX_CONNECT_FAILURES 20 // notify user of network problems after this many connect failures in a row
#define PEER_FLAG_SYNCED 0x01
#define PEER_FLAG_NEEDSUPDATE 0x02
#define genesis_block_hash(params) UInt256Reverse((params)->checkpoints[0].hash)
typedef struct {
BRPeerManager *manager;
const char *hostname;
uint64_t services;
} BRFindPeersInfo;
typedef struct {
BRPeer *peer;
BRPeerManager *manager;
UInt256 hash;
} BRPeerCallbackInfo;
typedef struct {
BRTransaction *tx;
void *info;
void (*callback)(void *info, int error);
} BRPublishedTx;
typedef struct {
UInt256 txHash;
BRPeer *peers;
} BRTxPeerList;
// true if peer is contained in the list of peers associated with txHash
static int _BRTxPeerListHasPeer(const BRTxPeerList *list, UInt256 txHash, const BRPeer *peer)
{
for (size_t i = array_count(list); i > 0; i--) {
if (! UInt256Eq(list[i - 1].txHash, txHash)) continue;
for (size_t j = array_count(list[i - 1].peers); j > 0; j--) {
if (BRPeerEq(&list[i - 1].peers[j - 1], peer)) return 1;
}
break;
}
return 0;
}
// number of peers associated with txHash
static size_t _BRTxPeerListCount(const BRTxPeerList *list, UInt256 txHash)
{
for (size_t i = array_count(list); i > 0; i--) {
if (UInt256Eq(list[i - 1].txHash, txHash)) return array_count(list[i - 1].peers);
}
return 0;
}
// adds peer to the list of peers associated with txHash and returns the new total number of peers
static size_t _BRTxPeerListAddPeer(BRTxPeerList **list, UInt256 txHash, const BRPeer *peer)
{
for (size_t i = array_count(*list); i > 0; i--) {
if (! UInt256Eq((*list)[i - 1].txHash, txHash)) continue;
for (size_t j = array_count((*list)[i - 1].peers); j > 0; j--) {
if (BRPeerEq(&(*list)[i - 1].peers[j - 1], peer)) return array_count((*list)[i - 1].peers);
}
array_add((*list)[i - 1].peers, *peer);
return array_count((*list)[i - 1].peers);
}
array_add(*list, ((BRTxPeerList) { txHash, NULL }));
array_new((*list)[array_count(*list) - 1].peers, PEER_MAX_CONNECTIONS);
array_add((*list)[array_count(*list) - 1].peers, *peer);
return 1;
}
// removes peer from the list of peers associated with txHash, returns true if peer was found
static int _BRTxPeerListRemovePeer(BRTxPeerList *list, UInt256 txHash, const BRPeer *peer)
{
for (size_t i = array_count(list); i > 0; i--) {
if (! UInt256Eq(list[i - 1].txHash, txHash)) continue;
for (size_t j = array_count(list[i - 1].peers); j > 0; j--) {
if (! BRPeerEq(&list[i - 1].peers[j - 1], peer)) continue;
array_rm(list[i - 1].peers, j - 1);
return 1;
}
break;
}
return 0;
}
// comparator for sorting peers by timestamp, most recent first
inline static int _peerTimestampCompare(const void *peer, const void *otherPeer)
{
if (((const BRPeer *)peer)->timestamp < ((const BRPeer *)otherPeer)->timestamp) return 1;
if (((const BRPeer *)peer)->timestamp > ((const BRPeer *)otherPeer)->timestamp) return -1;
return 0;
}
// returns a hash value for a block's prevBlock value suitable for use in a hashtable
inline static size_t _BRPrevBlockHash(const void *block)
{
return (size_t)((const BRMerkleBlock *)block)->prevBlock.u32[0];
}
// true if block and otherBlock have equal prevBlock values
inline static int _BRPrevBlockEq(const void *block, const void *otherBlock)
{
return UInt256Eq(((const BRMerkleBlock *)block)->prevBlock, ((const BRMerkleBlock *)otherBlock)->prevBlock);
}
// returns a hash value for a block's height value suitable for use in a hashtable
inline static size_t _BRBlockHeightHash(const void *block)
{
// (FNV_OFFSET xor height)*FNV_PRIME
return (size_t)((0x811C9dc5 ^ ((const BRMerkleBlock *)block)->height)*0x01000193);
}
// true if block and otherBlock have equal height values
inline static int _BRBlockHeightEq(const void *block, const void *otherBlock)
{
return (((const BRMerkleBlock *)block)->height == ((const BRMerkleBlock *)otherBlock)->height);
}
struct BRPeerManagerStruct {
const BRChainParams *params;
BRWallet *wallet;
int isConnected, connectFailureCount, misbehavinCount, dnsThreadCount, maxConnectCount;
BRPeer *peers, *downloadPeer, fixedPeer, **connectedPeers;
char downloadPeerName[INET6_ADDRSTRLEN + 6];
uint32_t earliestKeyTime, syncStartHeight, filterUpdateHeight, estimatedHeight;
BRBloomFilter *bloomFilter;
double fpRate, averageTxPerBlock;
BRSet *blocks, *orphans, *checkpoints;
BRMerkleBlock *lastBlock, *lastOrphan;
BRTxPeerList *txRelays, *txRequests;
BRPublishedTx *publishedTx;
UInt256 *publishedTxHashes;
void *info;
void (*syncStarted)(void *info);
void (*syncStopped)(void *info, int error);
void (*txStatusUpdate)(void *info);
void (*saveBlocks)(void *info, int replace, BRMerkleBlock *blocks[], size_t blocksCount);
void (*savePeers)(void *info, int replace, const BRPeer peers[], size_t peersCount);
int (*networkIsReachable)(void *info);
void (*threadCleanup)(void *info);
pthread_mutex_t lock;
};
static void _BRPeerManagerPeerMisbehavin(BRPeerManager *manager, BRPeer *peer)
{
for (size_t i = array_count(manager->peers); i > 0; i--) {
if (BRPeerEq(&manager->peers[i - 1], peer)) array_rm(manager->peers, i - 1);
}
if (++manager->misbehavinCount >= 10) { // clear out stored peers so we get a fresh list from DNS for next connect
manager->misbehavinCount = 0;
array_clear(manager->peers);
}
BRPeerDisconnect(peer);
}
static void _BRPeerManagerSyncStopped(BRPeerManager *manager)
{
manager->syncStartHeight = 0;
if (manager->downloadPeer) {
// don't cancel timeout if there's a pending tx publish callback
for (size_t i = array_count(manager->publishedTx); i > 0; i--) {
if (manager->publishedTx[i - 1].callback != NULL) return;
}
BRPeerScheduleDisconnect(manager->downloadPeer, -1); // cancel sync timeout
}
}
// adds transaction to list of tx to be published, along with any unconfirmed inputs
static void _BRPeerManagerAddTxToPublishList(BRPeerManager *manager, BRTransaction *tx, void *info,
void (*callback)(void *, int))
{
if (tx && tx->blockHeight == TX_UNCONFIRMED) {
for (size_t i = array_count(manager->publishedTx); i > 0; i--) {
if (BRTransactionEq(manager->publishedTx[i - 1].tx, tx)) return;
}
array_add(manager->publishedTx, ((BRPublishedTx) { tx, info, callback }));
array_add(manager->publishedTxHashes, tx->txHash);
for (size_t i = 0; i < tx->inCount; i++) {
_BRPeerManagerAddTxToPublishList(manager, BRWalletTransactionForHash(manager->wallet, tx->inputs[i].txHash),
NULL, NULL);
}
}
}
static size_t _BRPeerManagerBlockLocators(BRPeerManager *manager, UInt256 locators[], size_t locatorsCount)
{
// append 10 most recent block hashes, decending, then continue appending, doubling the step back each time,
// finishing with the genesis block (top, -1, -2, -3, -4, -5, -6, -7, -8, -9, -11, -15, -23, -39, -71, -135, ..., 0)
BRMerkleBlock *block = manager->lastBlock;
int32_t step = 1, i = 0, j;
while (block && block->height > 0) {
if (locators && i < locatorsCount) locators[i] = block->blockHash;
if (++i >= 10) step *= 2;
for (j = 0; block && j < step; j++) {
block = BRSetGet(manager->blocks, &block->prevBlock);
}
}
if (locators && i < locatorsCount) locators[i] = genesis_block_hash(manager->params);
return ++i;
}
static void _setApplyFreeBlock(void *info, void *block)
{
BRMerkleBlockFree(block);
}
static void _BRPeerManagerLoadBloomFilter(BRPeerManager *manager, BRPeer *peer)
{
// every time a new wallet address is added, the bloom filter has to be rebuilt, and each address is only used
// for one transaction, so here we generate some spare addresses to avoid rebuilding the filter each time a
// wallet transaction is encountered during the chain sync
BRWalletUnusedAddrs(manager->wallet, NULL, SEQUENCE_GAP_LIMIT_EXTERNAL + 100, 0);
BRWalletUnusedAddrs(manager->wallet, NULL, SEQUENCE_GAP_LIMIT_INTERNAL + 100, 1);
BRSetApply(manager->orphans, NULL, _setApplyFreeBlock);
BRSetClear(manager->orphans); // clear out orphans that may have been received on an old filter
manager->lastOrphan = NULL;
manager->filterUpdateHeight = manager->lastBlock->height;
manager->fpRate = BLOOM_REDUCED_FALSEPOSITIVE_RATE;
size_t addrsCount = BRWalletAllAddrs(manager->wallet, NULL, 0);
BRAddress *addrs = malloc(addrsCount*sizeof(*addrs));
size_t utxosCount = BRWalletUTXOs(manager->wallet, NULL, 0);
BRUTXO *utxos = malloc(utxosCount*sizeof(*utxos));
uint32_t blockHeight = (manager->lastBlock->height > 100) ? manager->lastBlock->height - 100 : 0;
size_t txCount = BRWalletTxUnconfirmedBefore(manager->wallet, NULL, 0, blockHeight);
BRTransaction **transactions = malloc(txCount*sizeof(*transactions));
BRBloomFilter *filter;
assert(addrs != NULL);
assert(utxos != NULL);
assert(transactions != NULL);
addrsCount = BRWalletAllAddrs(manager->wallet, addrs, addrsCount);
utxosCount = BRWalletUTXOs(manager->wallet, utxos, utxosCount);
txCount = BRWalletTxUnconfirmedBefore(manager->wallet, transactions, txCount, blockHeight);
filter = BRBloomFilterNew(manager->fpRate, addrsCount + utxosCount + txCount + 100, (uint32_t)BRPeerHash(peer),
BLOOM_UPDATE_ALL); // BUG: XXX txCount not the same as number of spent wallet outputs
for (size_t i = 0; i < addrsCount; i++) { // add addresses to watch for tx receiveing money to the wallet
UInt160 hash = UINT160_ZERO;
BRAddressHash160(&hash, addrs[i].s);
if (! UInt160IsZero(hash) && ! BRBloomFilterContainsData(filter, hash.u8, sizeof(hash))) {
BRBloomFilterInsertData(filter, hash.u8, sizeof(hash));
}
}
free(addrs);
for (size_t i = 0; i < utxosCount; i++) { // add UTXOs to watch for tx sending money from the wallet
uint8_t o[sizeof(UInt256) + sizeof(uint32_t)];
UInt256Set(o, utxos[i].hash);
UInt32SetLE(&o[sizeof(UInt256)], utxos[i].n);
if (! BRBloomFilterContainsData(filter, o, sizeof(o))) BRBloomFilterInsertData(filter, o, sizeof(o));
}
free(utxos);
for (size_t i = 0; i < txCount; i++) { // also add TXOs spent within the last 100 blocks
for (size_t j = 0; j < transactions[i]->inCount; j++) {
BRTxInput *input = &transactions[i]->inputs[j];
BRTransaction *tx = BRWalletTransactionForHash(manager->wallet, input->txHash);
uint8_t o[sizeof(UInt256) + sizeof(uint32_t)];
if (tx && input->index < tx->outCount &&
BRWalletContainsAddress(manager->wallet, tx->outputs[input->index].address)) {
UInt256Set(o, input->txHash);
UInt32SetLE(&o[sizeof(UInt256)], input->index);
if (! BRBloomFilterContainsData(filter, o, sizeof(o))) BRBloomFilterInsertData(filter, o,sizeof(o));
}
}
}
free(transactions);
if (manager->bloomFilter) BRBloomFilterFree(manager->bloomFilter);
manager->bloomFilter = filter;
// TODO: XXX if already synced, recursively add inputs of unconfirmed receives
uint8_t data[BRBloomFilterSerialize(filter, NULL, 0)];
size_t len = BRBloomFilterSerialize(filter, data, sizeof(data));
BRPeerSendFilterload(peer, data, len);
}
static void _updateFilterRerequestDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
free(info);
if (success) {
pthread_mutex_lock(&manager->lock);
if ((peer->flags & PEER_FLAG_NEEDSUPDATE) == 0) {
UInt256 locators[_BRPeerManagerBlockLocators(manager, NULL, 0)];
size_t count = _BRPeerManagerBlockLocators(manager, locators, sizeof(locators)/sizeof(*locators));
BRPeerSendGetblocks(peer, locators, count, UINT256_ZERO);
}
pthread_mutex_unlock(&manager->lock);
}
}
static void _updateFilterLoadDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
BRPeerCallbackInfo *peerInfo;
free(info);
if (success) {
pthread_mutex_lock(&manager->lock);
BRPeerSetNeedsFilterUpdate(peer, 0);
peer->flags &= ~PEER_FLAG_NEEDSUPDATE;
if (manager->lastBlock->height < manager->estimatedHeight) { // if syncing, rerequest blocks
peerInfo = calloc(1, sizeof(*peerInfo));
assert(peerInfo != NULL);
peerInfo->peer = peer;
peerInfo->manager = manager;
BRPeerRerequestBlocks(manager->downloadPeer, manager->lastBlock->blockHash);
BRPeerSendPing(manager->downloadPeer, peerInfo, _updateFilterRerequestDone);
}
else BRPeerSendMempool(peer, NULL, 0, NULL, NULL); // if not syncing, request mempool
pthread_mutex_unlock(&manager->lock);
}
}
static void _updateFilterPingDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
BRPeerCallbackInfo *peerInfo;
if (success) {
pthread_mutex_lock(&manager->lock);
peer_log(peer, "updating filter with newly created wallet addresses");
if (manager->bloomFilter) BRBloomFilterFree(manager->bloomFilter);
manager->bloomFilter = NULL;
if (manager->lastBlock->height < manager->estimatedHeight) { // if we're syncing, only update download peer
if (manager->downloadPeer) {
_BRPeerManagerLoadBloomFilter(manager, manager->downloadPeer);
BRPeerSendPing(manager->downloadPeer, info, _updateFilterLoadDone); // wait for pong so filter is loaded
}
else free(info);
}
else {
free(info);
for (size_t i = array_count(manager->connectedPeers); i > 0; i--) {
if (BRPeerConnectStatus(manager->connectedPeers[i - 1]) != BRPeerStatusConnected) continue;
peerInfo = calloc(1, sizeof(*peerInfo));
assert(peerInfo != NULL);
peerInfo->peer = manager->connectedPeers[i - 1];
peerInfo->manager = manager;
_BRPeerManagerLoadBloomFilter(manager, peerInfo->peer);
BRPeerSendPing(peerInfo->peer, peerInfo, _updateFilterLoadDone); // wait for pong so filter is loaded
}
}
pthread_mutex_unlock(&manager->lock);
}
else free(info);
}
static void _BRPeerManagerUpdateFilter(BRPeerManager *manager)
{
BRPeerCallbackInfo *info;
if (manager->downloadPeer && (manager->downloadPeer->flags & PEER_FLAG_NEEDSUPDATE) == 0) {
BRPeerSetNeedsFilterUpdate(manager->downloadPeer, 1);
manager->downloadPeer->flags |= PEER_FLAG_NEEDSUPDATE;
peer_log(manager->downloadPeer, "filter update needed, waiting for pong");
info = calloc(1, sizeof(*info));
assert(info != NULL);
info->peer = manager->downloadPeer;
info->manager = manager;
// wait for pong so we're sure to include any tx already sent by the peer in the updated filter
BRPeerSendPing(manager->downloadPeer, info, _updateFilterPingDone);
}
}
// unconfirmed transactions that aren't in the mempools of any of connected peers have likely dropped off the network
static void _requestUnrelayedTxGetdataDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
int isPublishing;
size_t count = 0;
free(info);
pthread_mutex_lock(&manager->lock);
if (success) peer->flags |= PEER_FLAG_SYNCED;
for (size_t i = array_count(manager->connectedPeers); i > 0; i--) {
peer = manager->connectedPeers[i - 1];
if (BRPeerConnectStatus(peer) == BRPeerStatusConnected) count++;
if ((peer->flags & PEER_FLAG_SYNCED) != 0) continue;
count = 0;
break;
}
// don't remove transactions until we're connected to maxConnectCount peers, and all peers have finished
// relaying their mempools
if (count >= manager->maxConnectCount) {
UInt256 hash;
size_t txCount = BRWalletTxUnconfirmedBefore(manager->wallet, NULL, 0, TX_UNCONFIRMED);
BRTransaction *tx[(txCount*sizeof(BRTransaction *) <= 0x1000) ? txCount : 0x1000/sizeof(BRTransaction *)];
txCount = BRWalletTxUnconfirmedBefore(manager->wallet, tx, sizeof(tx)/sizeof(*tx), TX_UNCONFIRMED);
for (size_t i = txCount; i > 0; i--) {
hash = tx[i - 1]->txHash;
isPublishing = 0;
for (size_t j = array_count(manager->publishedTx); ! isPublishing && j > 0; j--) {
if (BRTransactionEq(manager->publishedTx[j - 1].tx, tx[i - 1]) &&
manager->publishedTx[j - 1].callback != NULL) isPublishing = 1;
}
if (! isPublishing && _BRTxPeerListCount(manager->txRelays, hash) == 0 &&
_BRTxPeerListCount(manager->txRequests, hash) == 0) {
peer_log(peer, "removing tx unconfirmed at: %d, txHash: %s", manager->lastBlock->height, u256hex(hash));
assert(tx[i - 1]->blockHeight == TX_UNCONFIRMED);
BRWalletRemoveTransaction(manager->wallet, hash);
}
else if (! isPublishing && _BRTxPeerListCount(manager->txRelays, hash) < manager->maxConnectCount) {
// set timestamp 0 to mark as unverified
BRWalletUpdateTransactions(manager->wallet, &hash, 1, TX_UNCONFIRMED, 0);
}
}
}
pthread_mutex_unlock(&manager->lock);
}
static void _BRPeerManagerRequestUnrelayedTx(BRPeerManager *manager, BRPeer *peer)
{
BRPeerCallbackInfo *info;
size_t hashCount = 0, txCount = BRWalletTxUnconfirmedBefore(manager->wallet, NULL, 0, TX_UNCONFIRMED);
BRTransaction *tx[txCount];
UInt256 txHashes[txCount];
txCount = BRWalletTxUnconfirmedBefore(manager->wallet, tx, txCount, TX_UNCONFIRMED);
for (size_t i = 0; i < txCount; i++) {
if (! _BRTxPeerListHasPeer(manager->txRelays, tx[i]->txHash, peer) &&
! _BRTxPeerListHasPeer(manager->txRequests, tx[i]->txHash, peer)) {
txHashes[hashCount++] = tx[i]->txHash;
_BRTxPeerListAddPeer(&manager->txRequests, tx[i]->txHash, peer);
}
}
if (hashCount > 0) {
BRPeerSendGetdata(peer, txHashes, hashCount, NULL, 0);
if ((peer->flags & PEER_FLAG_SYNCED) == 0) {
info = calloc(1, sizeof(*info));
assert(info != NULL);
info->peer = peer;
info->manager = manager;
BRPeerSendPing(peer, info, _requestUnrelayedTxGetdataDone);
}
}
else peer->flags |= PEER_FLAG_SYNCED;
}
static void _BRPeerManagerPublishPendingTx(BRPeerManager *manager, BRPeer *peer)
{
for (size_t i = array_count(manager->publishedTx); i > 0; i--) {
if (manager->publishedTx[i - 1].callback == NULL) continue;
BRPeerScheduleDisconnect(peer, PROTOCOL_TIMEOUT); // schedule publish timeout
break;
}
BRPeerSendInv(peer, manager->publishedTxHashes, array_count(manager->publishedTxHashes));
}
static void _mempoolDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
int syncFinished = 0;
free(info);
if (success) {
peer_log(peer, "mempool request finished");
pthread_mutex_lock(&manager->lock);
if (manager->syncStartHeight > 0) {
peer_log(peer, "sync succeeded");
syncFinished = 1;
_BRPeerManagerSyncStopped(manager);
}
_BRPeerManagerRequestUnrelayedTx(manager, peer);
BRPeerSendGetaddr(peer); // request a list of other bitcoin peers
pthread_mutex_unlock(&manager->lock);
if (manager->txStatusUpdate) manager->txStatusUpdate(manager->info);
if (syncFinished && manager->syncStopped) manager->syncStopped(manager->info, 0);
}
else peer_log(peer, "mempool request failed");
}
static void _loadBloomFilterDone(void *info, int success)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
pthread_mutex_lock(&manager->lock);
if (success) {
BRPeerSendMempool(peer, manager->publishedTxHashes, array_count(manager->publishedTxHashes), info,
_mempoolDone);
pthread_mutex_unlock(&manager->lock);
}
else {
free(info);
if (peer == manager->downloadPeer) {
peer_log(peer, "sync succeeded");
_BRPeerManagerSyncStopped(manager);
pthread_mutex_unlock(&manager->lock);
if (manager->syncStopped) manager->syncStopped(manager->info, 0);
}
else pthread_mutex_unlock(&manager->lock);
}
}
static void _BRPeerManagerLoadMempools(BRPeerManager *manager)
{
// after syncing, load filters and get mempools from other peers
for (size_t i = array_count(manager->connectedPeers); i > 0; i--) {
BRPeer *peer = manager->connectedPeers[i - 1];
BRPeerCallbackInfo *info;
if (BRPeerConnectStatus(peer) != BRPeerStatusConnected) continue;
info = calloc(1, sizeof(*info));
assert(info != NULL);
info->peer = peer;
info->manager = manager;
if (peer != manager->downloadPeer || manager->fpRate > BLOOM_REDUCED_FALSEPOSITIVE_RATE*5.0) {
_BRPeerManagerLoadBloomFilter(manager, peer);
_BRPeerManagerPublishPendingTx(manager, peer);
BRPeerSendPing(peer, info, _loadBloomFilterDone); // load mempool after updating bloomfilter
}
else BRPeerSendMempool(peer, manager->publishedTxHashes, array_count(manager->publishedTxHashes), info,
_mempoolDone);
}
}
// returns a UINT128_ZERO terminated array of addresses for hostname that must be freed, or NULL if lookup failed
static UInt128 *_addressLookup(const char *hostname)
{
struct addrinfo *servinfo, *p;
UInt128 *addrList = NULL;
size_t count = 0, i = 0;
if (getaddrinfo(hostname, NULL, NULL, &servinfo) == 0) {
for (p = servinfo; p != NULL; p = p->ai_next) count++;
if (count > 0) addrList = calloc(count + 1, sizeof(*addrList));
assert(addrList != NULL || count == 0);
for (p = servinfo; p != NULL; p = p->ai_next) {
if (p->ai_family == AF_INET) {
addrList[i].u16[5] = 0xffff;
addrList[i].u32[3] = ((struct sockaddr_in *)p->ai_addr)->sin_addr.s_addr;
i++;
}
else if (p->ai_family == AF_INET6) {
addrList[i++] = *(UInt128 *)&((struct sockaddr_in6 *)p->ai_addr)->sin6_addr;
}
}
freeaddrinfo(servinfo);
}
return addrList;
}
static void *_findPeersThreadRoutine(void *arg)
{
BRPeerManager *manager = ((BRFindPeersInfo *)arg)->manager;
uint64_t services = ((BRFindPeersInfo *)arg)->services;
UInt128 *addrList, *addr;
time_t now = time(NULL), age;
pthread_cleanup_push(manager->threadCleanup, manager->info);
addrList = _addressLookup(((BRFindPeersInfo *)arg)->hostname);
free(arg);
pthread_mutex_lock(&manager->lock);
for (addr = addrList; addr && ! UInt128IsZero(*addr); addr++) {
age = 24*60*60 + BRRand(2*24*60*60); // add between 1 and 3 days
array_add(manager->peers, ((BRPeer) { *addr, manager->params->standardPort, services, now - age, 0 }));
}
manager->dnsThreadCount--;
pthread_mutex_unlock(&manager->lock);
if (addrList) free(addrList);
pthread_cleanup_pop(1);
return NULL;
}
// DNS peer discovery
static void _BRPeerManagerFindPeers(BRPeerManager *manager)
{
uint64_t services = SERVICES_NODE_NETWORK | SERVICES_NODE_BLOOM | manager->params->services;
time_t now = time(NULL);
struct timespec ts;
pthread_t thread;
pthread_attr_t attr;
UInt128 *addr, *addrList;
BRFindPeersInfo *info;
if (! UInt128IsZero(manager->fixedPeer.address)) {
array_set_count(manager->peers, 1);
manager->peers[0] = manager->fixedPeer;
manager->peers[0].services = services;
manager->peers[0].timestamp = now;
}
else {
for (size_t i = 1; manager->params->dnsSeeds[i]; i++) {
info = calloc(1, sizeof(BRFindPeersInfo));
assert(info != NULL);
info->manager = manager;
info->hostname = manager->params->dnsSeeds[i];
info->services = services;
if (pthread_attr_init(&attr) == 0 && pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0 &&
pthread_create(&thread, &attr, _findPeersThreadRoutine, info) == 0) manager->dnsThreadCount++;
}
for (addr = addrList = _addressLookup(manager->params->dnsSeeds[0]); addr && ! UInt128IsZero(*addr); addr++) {
array_add(manager->peers, ((BRPeer) { *addr, manager->params->standardPort, services, now, 0 }));
}
if (addrList) free(addrList);
ts.tv_sec = 0;
ts.tv_nsec = 1;
do {
pthread_mutex_unlock(&manager->lock);
nanosleep(&ts, NULL); // pthread_yield() isn't POSIX standard :(
pthread_mutex_lock(&manager->lock);
} while (manager->dnsThreadCount > 0 && array_count(manager->peers) < PEER_MAX_CONNECTIONS);
qsort(manager->peers, array_count(manager->peers), sizeof(*manager->peers), _peerTimestampCompare);
}
}
static void _peerConnected(void *info)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
BRPeerCallbackInfo *peerInfo;
time_t now = time(NULL);
pthread_mutex_lock(&manager->lock);
if (peer->timestamp > now + 2*60*60 || peer->timestamp < now - 2*60*60) peer->timestamp = now; // sanity check
// TODO: XXX does this work with 0.11 pruned nodes?
if ((peer->services & manager->params->services) != manager->params->services) {
peer_log(peer, "unsupported node type");
BRPeerDisconnect(peer);
}
else if ((peer->services & SERVICES_NODE_NETWORK) != SERVICES_NODE_NETWORK) {
peer_log(peer, "node doesn't carry full blocks");
BRPeerDisconnect(peer);
}
else if (BRPeerLastBlock(peer) + 10 < manager->lastBlock->height) {
peer_log(peer, "node isn't synced");
BRPeerDisconnect(peer);
}
else if (BRPeerVersion(peer) >= 70011 && (peer->services & SERVICES_NODE_BLOOM) != SERVICES_NODE_BLOOM) {
peer_log(peer, "node doesn't support SPV mode");
BRPeerDisconnect(peer);
}
else if (manager->downloadPeer && // check if we should stick with the existing download peer
(BRPeerLastBlock(manager->downloadPeer) >= BRPeerLastBlock(peer) ||
manager->lastBlock->height >= BRPeerLastBlock(peer))) {
if (manager->lastBlock->height >= BRPeerLastBlock(peer)) { // only load bloom filter if we're done syncing
manager->connectFailureCount = 0; // also reset connect failure count if we're already synced
_BRPeerManagerLoadBloomFilter(manager, peer);
_BRPeerManagerPublishPendingTx(manager, peer);
peerInfo = calloc(1, sizeof(*peerInfo));
assert(peerInfo != NULL);
peerInfo->peer = peer;
peerInfo->manager = manager;
BRPeerSendPing(peer, peerInfo, _loadBloomFilterDone);
}
}
else { // select the peer with the lowest ping time to download the chain from if we're behind
// BUG: XXX a malicious peer can report a higher lastblock to make us select them as the download peer, if
// two peers agree on lastblock, use one of those two instead
for (size_t i = array_count(manager->connectedPeers); i > 0; i--) {
BRPeer *p = manager->connectedPeers[i - 1];
if (BRPeerConnectStatus(p) != BRPeerStatusConnected) continue;
if ((BRPeerPingTime(p) < BRPeerPingTime(peer) && BRPeerLastBlock(p) >= BRPeerLastBlock(peer)) ||
BRPeerLastBlock(p) > BRPeerLastBlock(peer)) peer = p;
}
if (manager->downloadPeer) {
peer_log(peer, "selecting new download peer with higher reported lastblock");
BRPeerDisconnect(manager->downloadPeer);
}
manager->downloadPeer = peer;
manager->isConnected = 1;
manager->estimatedHeight = BRPeerLastBlock(peer);
_BRPeerManagerLoadBloomFilter(manager, peer);
BRPeerSetCurrentBlockHeight(peer, manager->lastBlock->height);
_BRPeerManagerPublishPendingTx(manager, peer);
if (manager->lastBlock->height < BRPeerLastBlock(peer)) { // start blockchain sync
UInt256 locators[_BRPeerManagerBlockLocators(manager, NULL, 0)];
size_t count = _BRPeerManagerBlockLocators(manager, locators, sizeof(locators)/sizeof(*locators));
BRPeerScheduleDisconnect(peer, PROTOCOL_TIMEOUT); // schedule sync timeout
// request just block headers up to a week before earliestKeyTime, and then merkleblocks after that
// we do not reset connect failure count yet incase this request times out
if (manager->lastBlock->timestamp + 7*24*60*60 >= manager->earliestKeyTime) {
BRPeerSendGetblocks(peer, locators, count, UINT256_ZERO);
}
else BRPeerSendGetheaders(peer, locators, count, UINT256_ZERO);
}
else { // we're already synced
manager->connectFailureCount = 0; // reset connect failure count
_BRPeerManagerLoadMempools(manager);
}
}
pthread_mutex_unlock(&manager->lock);
}
static void _peerDisconnected(void *info, int error)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
BRTxPeerList *peerList;
int willSave = 0, willReconnect = 0, txError = 0;
size_t txCount = 0;
//free(info);
pthread_mutex_lock(&manager->lock);
BRPublishedTx pubTx[array_count(manager->publishedTx)];
if (error == EPROTO) { // if it's protocol error, the peer isn't following standard policy
_BRPeerManagerPeerMisbehavin(manager, peer);
}
else if (error) { // timeout or some non-protocol related network error
for (size_t i = array_count(manager->peers); i > 0; i--) {
if (BRPeerEq(&manager->peers[i - 1], peer)) array_rm(manager->peers, i - 1);
}
manager->connectFailureCount++;
// if it's a timeout and there's pending tx publish callbacks, the tx publish timed out
// BUG: XXX what if it's a connect timeout and not a publish timeout?
if (error == ETIMEDOUT && (peer != manager->downloadPeer || manager->syncStartHeight == 0 ||
array_count(manager->connectedPeers) == 1)) txError = ETIMEDOUT;
}
for (size_t i = array_count(manager->txRelays); i > 0; i--) {
peerList = &manager->txRelays[i - 1];
for (size_t j = array_count(peerList->peers); j > 0; j--) {
if (BRPeerEq(&peerList->peers[j - 1], peer)) array_rm(peerList->peers, j - 1);
}
}
if (peer == manager->downloadPeer) { // download peer disconnected
manager->isConnected = 0;
manager->downloadPeer = NULL;
if (manager->connectFailureCount > MAX_CONNECT_FAILURES) manager->connectFailureCount = MAX_CONNECT_FAILURES;
}
if (! manager->isConnected && manager->connectFailureCount == MAX_CONNECT_FAILURES) {
_BRPeerManagerSyncStopped(manager);
// clear out stored peers so we get a fresh list from DNS on next connect attempt
array_clear(manager->peers);
txError = ENOTCONN; // trigger any pending tx publish callbacks
willSave = 1;
peer_log(peer, "sync failed");
}
else if (manager->connectFailureCount < MAX_CONNECT_FAILURES) willReconnect = 1;
if (txError) {
for (size_t i = array_count(manager->publishedTx); i > 0; i--) {
if (manager->publishedTx[i - 1].callback == NULL) continue;
peer_log(peer, "transaction canceled: %s", strerror(txError));
pubTx[txCount++] = manager->publishedTx[i - 1];
manager->publishedTx[i - 1].callback = NULL;
manager->publishedTx[i - 1].info = NULL;
}
}
for (size_t i = array_count(manager->connectedPeers); i > 0; i--) {
if (manager->connectedPeers[i - 1] != peer) continue;
array_rm(manager->connectedPeers, i - 1);
break;
}
BRPeerFree(peer);
pthread_mutex_unlock(&manager->lock);
for (size_t i = 0; i < txCount; i++) {
pubTx[i].callback(pubTx[i].info, txError);
}
if (willSave && manager->savePeers) manager->savePeers(manager->info, 1, NULL, 0);
if (willSave && manager->syncStopped) manager->syncStopped(manager->info, error);
if (willReconnect) BRPeerManagerConnect(manager); // try connecting to another peer
if (manager->txStatusUpdate) manager->txStatusUpdate(manager->info);
}
static void _peerRelayedPeers(void *info, const BRPeer peers[], size_t peersCount)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
time_t now = time(NULL);
pthread_mutex_lock(&manager->lock);
peer_log(peer, "relayed %zu peer(s)", peersCount);
array_add_array(manager->peers, peers, peersCount);
qsort(manager->peers, array_count(manager->peers), sizeof(*manager->peers), _peerTimestampCompare);
// limit total to 2500 peers
if (array_count(manager->peers) > 2500) array_set_count(manager->peers, 2500);
peersCount = array_count(manager->peers);
// remove peers more than 3 hours old, or until there are only 1000 left
while (peersCount > 1000 && manager->peers[peersCount - 1].timestamp + 3*60*60 < now) peersCount--;
array_set_count(manager->peers, peersCount);
BRPeer save[peersCount];
for (size_t i = 0; i < peersCount; i++) save[i] = manager->peers[i];
pthread_mutex_unlock(&manager->lock);
// peer relaying is complete when we receive <1000
if (peersCount > 1 && peersCount < 1000 &&
manager->savePeers) manager->savePeers(manager->info, 1, save, peersCount);
}
static void _peerRelayedTx(void *info, BRTransaction *tx)
{
BRPeer *peer = ((BRPeerCallbackInfo *)info)->peer;
BRPeerManager *manager = ((BRPeerCallbackInfo *)info)->manager;
void *txInfo = NULL;
void (*txCallback)(void *, int) = NULL;
int isWalletTx = 0, hasPendingCallbacks = 0;
size_t relayCount = 0;
pthread_mutex_lock(&manager->lock);
peer_log(peer, "relayed tx: %s", u256hex(tx->txHash));
for (size_t i = array_count(manager->publishedTx); i > 0; i--) { // see if tx is in list of published tx
if (UInt256Eq(manager->publishedTxHashes[i - 1], tx->txHash)) {
txInfo = manager->publishedTx[i - 1].info;
txCallback = manager->publishedTx[i - 1].callback;
manager->publishedTx[i - 1].info = NULL;
manager->publishedTx[i - 1].callback = NULL;
relayCount = _BRTxPeerListAddPeer(&manager->txRelays, tx->txHash, peer);
}
else if (manager->publishedTx[i - 1].callback != NULL) hasPendingCallbacks = 1;
}
// cancel tx publish timeout if no publish callbacks are pending, and syncing is done or this is not downloadPeer
if (! hasPendingCallbacks && (manager->syncStartHeight == 0 || peer != manager->downloadPeer)) {
BRPeerScheduleDisconnect(peer, -1); // cancel publish tx timeout
}
if (manager->syncStartHeight == 0 || BRWalletContainsTransaction(manager->wallet, tx)) {
isWalletTx = BRWalletRegisterTransaction(manager->wallet, tx);
if (isWalletTx) tx = BRWalletTransactionForHash(manager->wallet, tx->txHash);
}
else {
BRTransactionFree(tx);
tx = NULL;
}
if (tx && isWalletTx) {
// reschedule sync timeout
if (manager->syncStartHeight > 0 && peer == manager->downloadPeer) {
BRPeerScheduleDisconnect(peer, PROTOCOL_TIMEOUT);
}
if (BRWalletAmountSentByTx(manager->wallet, tx) > 0 && BRWalletTransactionIsValid(manager->wallet, tx)) {
_BRPeerManagerAddTxToPublishList(manager, tx, NULL, NULL); // add valid send tx to mempool
}
// keep track of how many peers have or relay a tx, this indicates how likely the tx is to confirm
// (we only need to track this after syncing is complete)
if (manager->syncStartHeight == 0) relayCount = _BRTxPeerListAddPeer(&manager->txRelays, tx->txHash, peer);
_BRTxPeerListRemovePeer(manager->txRequests, tx->txHash, peer);
if (manager->bloomFilter != NULL) { // check if bloom filter is already being updated
BRAddress addrs[SEQUENCE_GAP_LIMIT_EXTERNAL + SEQUENCE_GAP_LIMIT_INTERNAL];
UInt160 hash;
// the transaction likely consumed one or more wallet addresses, so check that at least the next <gap limit>
// unused addresses are still matched by the bloom filter
BRWalletUnusedAddrs(manager->wallet, addrs, SEQUENCE_GAP_LIMIT_EXTERNAL, 0);
BRWalletUnusedAddrs(manager->wallet, addrs + SEQUENCE_GAP_LIMIT_EXTERNAL, SEQUENCE_GAP_LIMIT_INTERNAL, 1);
for (size_t i = 0; i < SEQUENCE_GAP_LIMIT_EXTERNAL + SEQUENCE_GAP_LIMIT_INTERNAL; i++) {
if (! BRAddressHash160(&hash, addrs[i].s) ||
BRBloomFilterContainsData(manager->bloomFilter, hash.u8, sizeof(hash))) continue;
if (manager->bloomFilter) BRBloomFilterFree(manager->bloomFilter);
manager->bloomFilter = NULL; // reset bloom filter so it's recreated with new wallet addresses
_BRPeerManagerUpdateFilter(manager);
break;
}
}
}
// set timestamp when tx is verified
if (tx && relayCount >= manager->maxConnectCount && tx->blockHeight == TX_UNCONFIRMED && tx->timestamp == 0) {
BRWalletUpdateTransactions(manager->wallet, &tx->txHash, 1, TX_UNCONFIRMED, (uint32_t)time(NULL));
}
pthread_mutex_unlock(&manager->lock);
if (txCallback) txCallback(txInfo, 0);
}
static void _peerHasTx(void *info, UInt256 txHash)
{