forked from litecoin-foundation/loafwallet-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BRPeerManager.c
2068 lines (1736 loc) · 87.8 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 CHECKPOINT_COUNT (sizeof(checkpoint_array)/sizeof(*checkpoint_array))
#define DNS_SEEDS_COUNT (sizeof(dns_seeds)/sizeof(*dns_seeds))
#define GENESIS_BLOCK_HASH (UInt256Reverse(u256_hex_decode(checkpoint_array[0].hash)))
#define PEER_FLAG_SYNCED 0x01
#define PEER_FLAG_NEEDSUPDATE 0x02
#if BITCOIN_TESTNET
static const struct { uint32_t height; const char *hash; uint32_t timestamp; uint32_t target; } checkpoint_array[] = {
{ 0, "4966625a4b2851d9fdee139e56211a0d88575f59ed816ff5e6a63deb4e3e29a0", 1486949366, 0x1e0ffff0 }
};
static const char *dns_seeds[] = {
"testnet-seed.ltc.xurious.com.",
"seed-b.litecoin.loshan.co.uk.",
"dnsseed-testnet.thrasher.io."
};
#else // main net
// blockchain checkpoints - these are also used as starting points for partial chain downloads, so they need to be at
// difficulty transition boundaries in order to verify the block difficulty at the immediately following transition
static const struct { uint32_t height; const char *hash; uint32_t timestamp; uint32_t target; } checkpoint_array[] = {
{ 0, "12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2", 1317972665, 0x1e0ffff0 },
{ 20160, "633036c8df655531c2449b2d09b264cc0b49d945a89be23fd3c1a97361ca198c", 1319798300, 0x1d055262 },
{ 40320, "d148cdd2cf44069cef4b63f0feaf30a8d291ca9ea9ba7e83f226b9738c1d5e9c", 1322522019, 0x1d018053 },
{ 60480, "3250f0a560d55f039c34bfaee1b71297aa5104ac6641778f9a87d73232d12c6c", 1325540574, 0x1d00e848 },
{ 80640, "bedc0a090b740b1902d870aeb6caa89040a24e7d670d46f8ef035fd9d2e9ce80", 1328779944, 0x1d00ab92 },
{ 100800, "7b0b620d15f781faaaa73b43607a49d5becb2b803ef19b4010014646cc177a61", 1331873688, 0x1d00ae9f },
{ 120960, "dbd6249f30e5690890bc03dabcc0a526c46adcde572be06af4075b6ea28aa251", 1334881566, 0x1d009e48 },
{ 141120, "5d5e15a45cecf2b9528e36e63c407167423a2f9963a96bbce3b67b75fd10be2a", 1338009318, 0x1d00d6a6 },
{ 161280, "f595c754d0abcfe3616573bfabee01b230ec0ea6b2f2894c40214ea23d772b6c", 1340918301, 0x1d008881 },
{ 181440, "d7fa3152959f3c25e33edf825f7cbef75ee651d5f9183cc4ed8d19d57b8f35a4", 1343534530, 0x1c1cd430 },
{ 201600, "d481df8e8ce144fca9ae6b3157cc706e903c6ea161a13d2c421270354a02d6d0", 1346567025, 0x1c1c89e8 },
{ 221760, "88cf3446129161a633050244f112e3041a2d53152ee9293984b20f468fbadb8a", 1349481542, 0x1c135d42 },
{ 241920, "8619aa9c734b517bd3a707278ee3632c96570f3e1fd804194bdfc0b02d1b6c4e", 1352384870, 0x1c0b39e8 },
{ 262080, "13a5d47f01fe3ab17ebf2b15b605efa41efe06b02bb685bc2ad4cec22af0b478", 1355560195, 0x1c0a01e5 },
{ 282240, "8932095fba44bd6860fd71745c0dca908769221a47166ab1fb442b6cefcd53fb", 1358801720, 0x1c0ced21 },
{ 302400, "e798d897a837bf4989d329266128754ec1cbeff1eb0c0afd67f71d2b7c44bdaa", 1361913149, 0x1c102ea7 },
{ 322560, "3e5857760633de4604d388fed7126a22ba840ea320c8cde6a84df981bc8b751d", 1364498291, 0x1c02a944 },
{ 342720, "33f62e026a202be550e8a9df37d638d38991553544e279cb264123378bf46042", 1367113967, 0x1c0095a5 },
{ 362880, "77a4b194e8c7f6600ed622b8f60cb9d96eeb0a0b837201e605de14016edfda39", 1370052623, 0x1b6929f2 },
{ 383040, "5c0a443361c1356796a7db472c69433b6ce6108d61e4403fd9a9d91e01009ce3", 1372971948, 0x1b481262 },
{ 403200, "ef78aa1925cc51ff8dc3a1e59f389c89845fb8b9e566348222e663e963e67640", 1376014028, 0x1b4b858d },
{ 423360, "7b23f9447b8078c8fc0e832e4b56f1d2afa758382e254593b6b72a8fc6020150", 1379024440, 0x1b438e6a },
{ 443520, "37d668803ed1efc24ffab4a2a90da9ac92679acf68370d7570f042c2bd6d651b", 1382034998, 0x1b3f864f },
{ 463680, "260c78e92a390b9eb4d8f5d9324a33d0222943f119b324de53452d48bd7bd7f4", 1384968613, 0x1b2ddc00 },
{ 483840, "759de6c4e6161fc8c996cf0d5e012ee0afc52a037e657dd54e85da9a9f803633", 1387792541, 0x1b167254 },
{ 504000, "97db0624d3d5137bc085f0d731607314972bb4124b85b73420ef9aa5fc10d640", 1390892377, 0x1b1aa868 },
{ 524160, "1d033d3abedb7faa15dad1bbe9c7fc7151746537cf091584be567d321e7c5cd0", 1393845878, 0x1b120577 },
{ 544320, "95ae252971d1ec9deeed1ed19fe9537e04348a82839a9e2bf8856faaa03e324e", 1396719779, 0x1b0a9622 },
{ 564480, "c876276bf12754c2b265787d9e7ab83d429e59761dc63057f728529018db7834", 1399724592, 0x1b099dce },
{ 584640, "df5454af79491c392fe740b5efd47afbe1cb53cd8d86be3ab9c97fdd2786d237", 1402630524, 0x1b065b94 },
{ 604800, "43c1a80b8abaf57817e5daea9cfdde99ea5f324705779045792ccad52d54f3d4", 1405459509, 0x1b033d34 },
{ 624960, "ccac71fafe98107b81ac3e0eed41190e4d47600962c93c49db8843b53f760bda", 1408389228, 0x1b02552d },
{ 645120, "9b7ddc3753c5138fc471accd15f9730020e828bc69058f2e382549c7c0ffba0f", 1411376787, 0x1b020a10 },
{ 665280, "163c902de2306f22922754f83edacc97a87617d1e3413af7c9808e702bf1a383", 1414354222, 0x1b01bce9 },
{ 685440, "29d2328990dda4c4870846d4e3d573785452bed68e6013930a83fc8d5fe89b09", 1417289378, 0x1b01473b },
{ 705600, "e350118d9047c1ca5f047a1b1ee400562fb0cfb8b3c8032b56b8545b456a03ab", 1420305710, 0x1b01399e },
{ 725760, "6b2ac7ffb71fc5056c00fee8404813d7ea98e5f303a5ddb26c09fb397b51b7e7", 1423407371, 0x1b01905e },
{ 745920, "04809a35ff6e5054e21d14582072605b812b7d4ae11d3450e7c03a7237e1d35d", 1426441593, 0x1b019b8c },
{ 766080, "ba9e143a958c917753785f11c143ca62f928748c33888278fcaea96f054f15d2", 1429473619, 0x1b019e8f },
{ 786240, "d1b9fa6999f7a09d1dc52511750e47d263aaa7ea4a262762fff8665890d631a5", 1432507384, 0x1b01a8ec },
{ 806400, "e2363e8b3e8f237b9b1bfc1c72ede80fef2c7bd1aabcd78afed82065a194b960", 1435516150, 0x1b019268 },
{ 826560, "e12ce49268950a38fd7f0bab0d2a5edd9799201c1f3e9441a7602428556c839d", 1438510426, 0x1b016999 },
{ 846720, "6f5d94d7cfd01f1dbf4aa631b987f8e2ec9d0c57720604787b816bafe34192a8", 1441561050, 0x1b0187a3 },
{ 866880, "72a9f3d3710fc6c96f87dd8fca0e033a1a89f69a4c2fd8944fd1d50e6772021e", 1444547836, 0x1b0157fd },
{ 887040, "089c03de0c0dd0dffaa044fd5a3b51679be2ae34b048a8d6bcc39aab664c156a", 1447578790, 0x1b015f6a },
{ 889056, "910af99e39a6f9436bf4710a09ee19483e9b9b3f131dc9bef37dbe5eac72031f", 1447887833, 0x1b016720 },
{ 901152, "cfccdf8e3830ae4879e910051ac3dc583b4fb45b83be3a38019e5d9326dfa223", 1449698771, 0x1b015b0e },
{ 913248, "9784249cbeccd4df8d7701287da3002a6de4a56618248f84f37187dbf4ec6efc", 1451495881, 0x1b014465 },
{ 921312, "ab2357460c0a20caebfab76a7939c4e64a5068eddce4fbec749089be2e88e702", 1452685882, 0x1b012ee0 },
{ 933408, "f9f3fbcbb1fa40d0f9a1724085ac7cadaa414edd97c436571d06b3b5f3b46956", 1454513411, 0x1b01386f },
{ 941472, "4fddb941d414f071c29f100da2a160cf527397fc9a7a9c9d0a849b6f67799042", 1455719547, 0x1b0133ec },
{ 953568, "e46e01cf1239cffa69408ac162d517bac5a4899972e0328fd0ba4d93e8ad3764", 1457542869, 0x1b013c91 },
{ 961632, "bfc01091cb21ea81dd079fcee6cf7910087281bfdbcb1ad9e5dbc226b5f45a86", 1458730622, 0x1b012535 },
{ 973728, "6316b454ead6c97be48c98979ec9ebb49763c21d436f47ff6918f02a58b46cec", 1460575822, 0x1b014319 },
{ 981792, "155bc8fb717564bd2dd600cedcb39d8a7a64070e3bc1b90e7be62168e7b35c82", 1461788191, 0x1b01436f },
{ 993888, "1d80e7793bd9e16e0ce84d93b105d6732ed63e1a6fe491c1b7ea310e75eb504e", 1463613744, 0x1b014cbd },
{ 1001952, "eccbede26ac99ea996377972d5bd05b9306bcc6ac1f4071f1587e3094a704dff", 1464900396, 0x1b01a29e },
{ 1058400, "76ce37c66d449a4ffbfc35674cf932da701066a001dc223754f9250dd2bdbc62", 1473296285, 0x1b013ca7 },
{ 1260000, "85a22b528d805bf7a641d1d7c6d96ef5054beda3dcab6be7b83f2e3df24b33a8", 1502976600, 0x1a25a0d3 },
{ 1411200, "92c85b76f3d4bffca76b23717e4eb1b667c77c96fd52d4dd5dd843bbee64cd73", 1524838967, 0x1a0203a7 }
};
static const char *dns_seeds[] = {
"dnsseed.litecoinpool.org.",
"seed-a.litecoin.loshan.co.uk.",
"dnsseed.thrasher.io.",
"dnsseed.koin-project.com.",
"dnsseed.litecointools.com."
};
#endif
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 {
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;
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);
}
}
static void _BRPeerManagerUpdateTx(BRPeerManager *manager, const UInt256 txHashes[], size_t txCount,
uint32_t blockHeight, uint32_t timestamp)
{
if (blockHeight != TX_UNCONFIRMED) { // remove confirmed tx from publish list and relay counts
for (size_t i = 0; i < txCount; i++) {
for (size_t j = array_count(manager->publishedTx); j > 0; j--) {
BRTransaction *tx = manager->publishedTx[j - 1].tx;
if (! UInt256Eq(txHashes[i], tx->txHash)) continue;
array_rm(manager->publishedTx, j - 1);
array_rm(manager->publishedTxHashes, j - 1);
if (! BRWalletTransactionForHash(manager->wallet, tx->txHash)) BRTransactionFree(tx);
}
for (size_t j = array_count(manager->txRelays); j > 0; j--) {
if (! UInt256Eq(txHashes[i], manager->txRelays[j - 1].txHash)) continue;
array_free(manager->txRelays[j - 1].peers);
array_rm(manager->txRelays, j - 1);
}
}
}
BRWalletUpdateTransactions(manager->wallet, txHashes, txCount, blockHeight, timestamp);
}
// 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) {
size_t txCount = BRWalletTxUnconfirmedBefore(manager->wallet, NULL, 0, TX_UNCONFIRMED);
BRTransaction *tx[(txCount < 10000) ? txCount : 10000];
txCount = BRWalletTxUnconfirmedBefore(manager->wallet, tx, sizeof(tx)/sizeof(*tx), TX_UNCONFIRMED);
for (size_t i = 0; i < txCount; i++) {
isPublishing = 0;
for (size_t j = array_count(manager->publishedTx); ! isPublishing && j > 0; j--) {
if (BRTransactionEq(manager->publishedTx[j - 1].tx, tx[i]) &&
manager->publishedTx[j - 1].callback != NULL) isPublishing = 1;
}
if (! isPublishing && _BRTxPeerListCount(manager->txRelays, tx[i]->txHash) == 0 &&
_BRTxPeerListCount(manager->txRequests, tx[i]->txHash) == 0) {
BRWalletRemoveTransaction(manager->wallet, tx[i]->txHash);
}
else if (! isPublishing && _BRTxPeerListCount(manager->txRelays, tx[i]->txHash) < manager->maxConnectCount){
// set timestamp 0 to mark as unverified
_BRPeerManagerUpdateTx(manager, &tx[i]->txHash, 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, STANDARD_PORT, 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)
{
static const uint64_t services = SERVICES_NODE_NETWORK | SERVICES_NODE_BLOOM;
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; i < DNS_SEEDS_COUNT; i++) {
info = calloc(1, sizeof(BRFindPeersInfo));
assert(info != NULL);
info->manager = manager;
info->hostname = dns_seeds[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(dns_seeds[0]); addr && ! UInt128IsZero(*addr); addr++) {
array_add(manager->peers, ((BRPeer) { *addr, STANDARD_PORT, 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 & 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 ((peer->services & SERVICES_NODE_BCASH) == SERVICES_NODE_BCASH) {
peer_log(peer, "b-cash nodes not supported");
BRPeerDisconnect(peer);
}
else if (BRPeerVersion(peer) >= 70011 && ! (peer->services & 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) 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);
void *txInfo[array_count(manager->publishedTx)];
void (*txCallback[array_count(manager->publishedTx)])(void *, int);
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));
txInfo[txCount] = manager->publishedTx[i - 1].info;
txCallback[txCount] = manager->publishedTx[i - 1].callback;
txCount++;
BRTransactionFree(manager->publishedTx[i - 1].tx);
array_rm(manager->publishedTxHashes, i - 1);
array_rm(manager->publishedTx, i - 1);
}
}
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++) {
txCallback[i](txInfo[i], 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;