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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
crate::ix!();

pub type Inventory = Vec<Inv>;

pub enum ControlFlow {
    Return,
    None,
    Break,
    Continue,
}

impl SendMessages for PeerManager {
    
    #[EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing)]
    fn send_messages(
        self:      Arc<Self>, 
        pto:       Amo<Box<dyn NodeInterface>>) -> bool {

        let node = pto.get();

        let peer: Amo<Peer> = {

            self.get_peer_ref(node.get_id())
        };

        if peer.is_none() {
            return false;
        }

        let consensus_params: Arc<ChainConsensusParams> 
        = self.chainparams.get_consensus();

        // We must call
        // MaybeDiscourageAndDisconnect first, to
        // ensure that we'll disconnect
        // misbehaving peers even before the
        // version handshake is complete.
        if self.clone().maybe_discourage_and_disconnect(pto.clone(),&mut peer.get_mut()) {
            return true;
        }

        // Don't send anything until the version
        // handshake is complete
        if !node.is_successfully_connected() || node.marked_for_disconnect() {
            return true;
        }

        let common_version = node.get_common_version();

        // If we get here, the outgoing message
        // serialization version is set and can't
        // change.
        let msg_maker: NetMsgMaker = NetMsgMaker::new( common_version );

        let current_time = get_datetime();

        let time_connected = node.get_n_time_connected();

        if node.is_addr_fetch_conn() 
        && current_time - time_connected > 10_i32 * AVG_ADDRESS_BROADCAST_INTERVAL 
        {
            log_print!(
                LogFlags::NET, 
                "addrfetch connection timeout; disconnecting peer=%d\n", 
                node.get_id()
            );

            node.mark_for_disconnect();

            return true;
        }

        self.clone().maybe_send_ping(pto.clone(), peer.clone(), current_time);

        // MaybeSendPing may have marked peer for
        // disconnection
        //
        if node.marked_for_disconnect() {
            return true;
        }
        
        self.clone().maybe_send_addr(
            pto.clone(), 
            peer.getopt_mut().as_mut().unwrap(), 
            current_time
        );

        {
            let mut guard = CS_MAIN.lock();

            self.clone().protected_send_messages(
                pto.clone(), 
                peer, 
                &msg_maker,
                consensus_params
            );

            //  release CS_MAIN
        }

        true
    }
}

impl PeerManager {

    fn expire_old_relay_messages(
        self:   Arc<Self>, 
        txinfo: &TxMemPoolInfo, 
        txid:   &u256,
        wtxid:  &u256) {

        let current_time = get_datetime();

        // Expire old relay messages
        while !self.inner.lock().g_relay_expiration.is_empty() 
        && self.inner.lock().g_relay_expiration[0].0 < current_time 
        {
            self.inner.lock().map_relay.remove(
                &self.inner.lock().g_relay_expiration[0].1.0
            );

            self.inner.lock().g_relay_expiration.pop_front();
        }

        let new_value = txinfo.tx.clone(); //move

        if let Some(old) = self.inner.lock().map_relay.insert(
            txid.clone(), 
            new_value.clone()) 
        {

            //nothing

        } else {

                self.inner.lock().g_relay_expiration.push_back(
                    (
                        current_time + RELAY_TX_CACHE_TIME, 

                        (Arc::new(txid.clone()), new_value.clone())
                    )
                );

            }

        // Add wtxid-based lookup into
        // mapRelay as well, so that peers
        // can request by wtxid
        if let Some(ret2) = self.inner.lock().map_relay.insert(wtxid.clone(), new_value) {

            self.inner.lock().g_relay_expiration.push_back(
                (
                    current_time + RELAY_TX_CACHE_TIME, 
                    (Arc::new(wtxid.clone()), ret2)
                )
            );
        }
    }

    fn protected_send_messages(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>, 
        peer:             Amo<Peer>, 
        msg_maker:        &NetMsgMaker,
        consensus_params: Arc<ChainConsensusParams>,
    ) -> ControlFlow {

        let current_time = get_datetime();

        let node = pnode.get();

        let pstate: Amo<NodeState> 
        = create_state(node.get_id());

        // Start block sync
        if PINDEX_BEST_HEADER.lock().is_none() {

            self.clone().start_block_sync();
        }

        // Download if this is a nice peer, or we
        // have no nice peers and this one might
        // do.
        let fetch: bool 
        = pstate.get().preferred_download.load(atomic::Ordering::Relaxed) 
        || (
            N_PREFERRED_DOWNLOAD.load(atomic::Ordering::Relaxed) == 0 
            && !node.is_client() && !node.is_addr_fetch_conn()
        );

        let state = pstate.get();

        if !state.sync_started.load(atomic::Ordering::Relaxed) 
        && !node.is_client() 
        && !IMPORTING.load(atomic::Ordering::Relaxed) 
        && !REINDEX.load(atomic::Ordering::Relaxed) 
        {
            self.clone().handle_not_sync_started(
                pnode.clone(),
                pstate.clone(),
                msg_maker,
                fetch,
                consensus_params.clone()
            );
        }

        self.clone().try_sending_block_announcements_via_headers(
            pnode.clone(),
            pstate.clone(),
            peer.clone(),
            &msg_maker,
            consensus_params.clone()
        );

        //  Message: inventory
        let mut inventory = self.clone().handle_message_inventory(
            pnode.clone(),
            peer.get(),
            msg_maker
        );

        if node.has_tx_relay() {

            self.clone().handle_tx_relay(
                &mut pnode.get_mut(), 
                pstate.clone(), 
                &mut inventory, 
                msg_maker
            );
        }

        if !inventory.is_empty() {

            self.connman.get_mut()
                .push_message(
                    &mut *pnode.get_mut(), 
                    msg_maker.make(NetMsgType::INV, 
                        &[
                            &inventory
                        ]
                    )
                );
        }

        if pstate.get().detect_stalling(current_time) {

            node.disconnect_on_stall();

            return ControlFlow::Return;
        }

        // In case there is a block that has been
        // in flight from this peer for
        // block_interval * (1 + 0.5 * N) (with
        // N the number of peers from which we're
        // downloading validated blocks),
        // disconnect due to timeout.
        //
        // We compensate for other peers to
        // prevent killing off peers due to our
        // own downstream link being saturated. We
        // only count validated in-flight blocks
        // so peers can't advertise non-existing
        // blockhashes to unreasonably increase
        // our timeout.
        if pstate.get().blocks_in_flight.len() > 0 {

            match self.clone().disconnect_timedout_blocks_in_flight(
                pnode.clone(),
                pstate.clone(),
                consensus_params.clone()
            ) {
                ControlFlow::Return => return ControlFlow::Return,
                ControlFlow::None   => {}
                _                   => panic!("unexpected control flow")
            }
        }

        self.clone().check_for_headers_sync_timeouts(
            pnode.clone(),
            pstate.clone()
        );

        // Check that outbound peers have
        // reasonable chains
        //
        // GetTime() is used by this anti-DoS
        // logic so we can test this using
        // mocktime
        self.clone().consider_eviction(
            pnode.clone(),
            get_datetime()
        );

        // Message: getdata (blocks)
        //
        let mut get_data: Vec<Inv> = vec![];

        if !node.is_client() 
        && ((fetch && !node.is_limited_node()) || !self.chainman.get().active_chainstate().is_initial_block_download()) 
        && pstate.get().n_blocks_in_flight.load(atomic::Ordering::Relaxed) < MAX_BLOCKS_IN_TRANSIT_PER_PEER {

            self.clone().handle_message_getdata_blocks(pnode.clone(),pstate.clone(),&mut get_data);
        }

        // Message: getdata (transactions)
        //
        self.clone().handle_message_getdata_transactions(
            pnode.clone(),
            msg_maker,
            &mut get_data
        );

        self.maybe_send_feefilter(
            pnode.clone(), 
            current_time
        );

        ControlFlow::None
    }

    fn handle_not_sync_started(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>,
        pstate:           Amo<NodeState>,
        msg_maker:        &NetMsgMaker,
        fetch:            bool,
        consensus_params: Arc<ChainConsensusParams>,
    ) {

        let current_time = get_datetime();

        // Only actively request headers from
        // a single peer, unless we're close to
        // today.
        if (self.inner.lock().n_sync_started == 0 && fetch) 
        || (*PINDEX_BEST_HEADER.lock()).as_ref().unwrap().get_block_time() > get_adjusted_time() - 24 * 60 * 60 
        {
            pstate.get().sync_started.store(true, atomic::Ordering::Relaxed);

            // Convert
            // HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER
            // to microseconds before
            // scaling to maintain
            // precision
            pstate.get_mut().headers_sync_timeout 
                = Some(
                    current_time 
                    + HEADERS_DOWNLOAD_TIMEOUT_BASE 
                    + {
                        let timeout    = HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER;
                        let block_time = (*PINDEX_BEST_HEADER.lock()).as_ref().unwrap().get_block_time();
                        let time       = get_adjusted_time() - block_time;
                        let spacing: i32    = consensus_params.n_pow_target_spacing.try_into().unwrap();

                        timeout.checked_mul(time.try_into().unwrap()).unwrap() / spacing
                    }
                );

            {
                let old = self.inner.lock().n_sync_started;
                self.inner.lock().n_sync_started += 1;
                old
            };

            let mut pindex_start: Option<Arc<BlockIndex>> = PINDEX_BEST_HEADER.lock().clone();

            /*
             | If possible, start at the block preceding
             | the currently best known header. This
             | ensures that we always get a non-empty
             | list of headers back as long as the peer
             | is up-to-date. With a non-empty response,
             | we can initialise the peer's known best
             | block. This wouldn't be possible if
             | we requested starting at pindexBestHeader
             | and got back an empty response.
             |
             */
            if pindex_start.as_ref().unwrap().pprev.is_some() {

                pindex_start = pindex_start.as_ref().unwrap().pprev.clone();
            }

            log_print!(
                LogFlags::NET, 
                "initial getheaders (%d) to peer=%d (startheight:%d)\n", 
                pindex_start.unwrap().lock().n_height, 
                (*pto).get_id(), 
                peer.as_ref().unwrap().starting_height
            );

            self.connman.get_mut().push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make(
                    NetMsgType::GETHEADERS, 
                    &[
                        &self.chainman.get().active_chain().get_locator(pindex_start), 
                        &u256::default()
                    ]
                )
            );
        }
    }

    fn handle_message_inventory<'a>(
        self:      Arc<Self>, 
        pnode:     Amo<Box<dyn NodeInterface>>,
        peer:      AmoReadGuard<'a, Peer>,
        msg_maker: &NetMsgMaker
    ) -> Inventory {

        let mut inventory: Vec<Inv> = vec![];

        let mut guard = peer.block_inv_mutex.lock();

        inventory.reserve(
            max(
                peer.block_inv_mutex.lock().blocks_for_inv_relay.len(),
                (*INVENTORY_BROADCAST_MAX).try_into().unwrap()
            )
        );

        //  Add blocks
        for hash in peer.block_inv_mutex.lock().blocks_for_inv_relay.iter() {

            inventory.push(Inv::new(GetDataMsg::MSG_BLOCK.bits(),hash));

            if inventory.len() == MAX_INV_SZ.try_into().unwrap() {

                self.connman.get_mut().push_message(
                    &mut *pnode.get_mut(), 
                    msg_maker.make(
                        NetMsgType::INV, 
                        &[
                            &inventory
                        ]
                    )
                );

                inventory.clear();
            }
        }

        peer
            .block_inv_mutex.lock()
            .blocks_for_inv_relay.clear();

        inventory
    }

    fn handle_tx_relay(
        self:      Arc<Self>, 
        node:      &mut AmoWriteGuard<Box<dyn NodeInterface>>, 
        pstate:    Amo<NodeState>,
        inventory: &mut Vec<Inv>,
        msg_maker: &NetMsgMaker,
    ) {

        let current_time = get_datetime();

        let (send_trickle, send_mempool) = {

            let mut tx_relay = node.get_tx_relay_mut();

            let tx_inventory_guard = tx_relay.cs_tx_inventory.lock();

            // Check whether periodic sends should
            // happen
            let mut send_trickle: bool = node.has_permission(NetPermissionFlags::NoBan);

            let n_next_inv_send = tx_relay.n_next_inv_send.lock().unwrap();

            if n_next_inv_send < current_time {

                self.clone().update_n_next_inv_send(
                    node,
                    &mut send_trickle
                );
            }

            // Time to send but the peer has requested
            // we not relay transactions.
            if send_trickle {

                let mut filter_guard = tx_relay.cs_filter.lock();

                if !filter_guard.relay_txes {
                    tx_relay.set_inventory_tx_to_send.lock().clear();
                }
            }

            let send_mempool = tx_inventory_guard.send_mempool.clone();

            (send_trickle, send_mempool)
        };

        // Respond to BIP35 mempool requests
        if send_trickle && send_mempool {

            self.clone().respond_to_bip35_mempool_requests(
                node,
                pstate.clone(),
                inventory,
                msg_maker
            );
        }

        // Determine transactions to relay
        if send_trickle {

            self.determine_transactions_to_relay(
                node,
                pstate.clone(),
                inventory,
                msg_maker
            );
        }
    }

    fn update_n_next_inv_send(
        self:         Arc<Self>, 
        node:         &AmoWriteGuard<Box<dyn NodeInterface>>, 
        send_trickle: &mut bool) {

        let current_time = get_datetime();

        *send_trickle = true;

        if node.is_inbound_conn() {

            let tx_relay = node.get_tx_relay_mut();

            let mut n_next_inv_send = tx_relay.n_next_inv_send.lock();

            *n_next_inv_send = Some(
                self.connman.get_mut()
                .poisson_next_send_inbound(
                    current_time, 
                    INBOUND_INVENTORY_BROADCAST_INTERVAL
                )
            );

        } else {

            let tx_relay = node.get_tx_relay_mut();

            let mut n_next_inv_send = tx_relay.n_next_inv_send.lock();

            *n_next_inv_send = Some(
                poisson_next_send(
                    current_time,
                    OUTBOUND_INVENTORY_BROADCAST_INTERVAL
                )
            );
        }
    }

    fn handle_message_getdata_transactions(
        self:      Arc<Self>, 
        pnode:     Amo<Box<dyn NodeInterface>>,
        msg_maker: &NetMsgMaker,
        get_data:  &mut Vec<Inv>,
    ) {

        let current_time = get_datetime();

        let mut expired: Amo<Vec<(NodeId,GenTxId)>> = Amo::from(vec![]);

        let requestable = self.inner.lock().txrequest.lock().get_requestable(
            pnode.get().get_id(), 
            current_time, 
            expired.clone()
        );

        for entry in expired.get().iter() {

            log_print!(
                LogFlags::NET, 
                "timeout of inflight %s %s from peer=%d\n", 
                match entry.second.is_wtxid() {
                    true   => "wtx",
                    false  => "tx"
                }, 
                entry.second().get_hash().to_string(), 
                entry.first
            );
        }

        for gtxid in requestable.iter() {

            if !self.clone().already_have_tx(gtxid) {

                self.clone().download_txn(
                    pnode.clone(), 
                    msg_maker, 
                    get_data, 
                    &gtxid
                );

            } else {

                // We have already seen this
                // transaction, no need to
                // download. This is just
                // a belt-and-suspenders, as this
                // should already be called
                // whenever a transaction becomes
                // AlreadyHaveTx().
                self.inner.lock().txrequest.lock().forget_tx_hash(gtxid.get_hash());
            }
        }

        if !get_data.is_empty() {

            self.connman.get_mut().push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make(
                    NetMsgType::GETDATA, 
                    &[
                        get_data
                    ]
                )
            );
        }
    }

    fn handle_message_getdata_blocks(
        self:     Arc<Self>, 
        pnode:    Amo<Box<dyn NodeInterface>>, 
        pstate:   Amo<NodeState>,
        get_data: &mut Vec<Inv>,
    ) {
        let current_time = get_datetime();

        let mut to_download: Vec<Option<Arc<BlockIndex>>> = vec![];

        let mut staller: NodeId = -1;

        self.clone().find_next_blocks_to_download(
            pnode.get().get_id(), 
            (MAX_BLOCKS_IN_TRANSIT_PER_PEER - pstate.get().n_blocks_in_flight.load(atomic::Ordering::Relaxed)).try_into().unwrap(), 
            &mut to_download, 
            &mut staller
        );

        for pindex in to_download.iter() {

            let n_fetch_flags: GetDataMsg 
                = get_fetch_flags(&**pnode.get());

            get_data.push(
                Inv::new(
                    (GetDataMsg::MSG_BLOCK | n_fetch_flags).bits(),
                    &pindex.clone().unwrap().get_block_hash()
                )
            );

            self.clone().block_requested(
                pnode.get().get_id(), 
                pindex.clone(),
                amo_none()
            );

            log_print!(
                LogFlags::NET, 
                "Requesting block %s (%d) peer=%d\n", 
                pindex.unwrap().get_block_hash().to_string(), 
                pindex.unwrap().n_height, 
                (*pto).get_id()
            );
        }

        if pstate.get().n_blocks_in_flight.load(atomic::Ordering::Relaxed) == 0 && staller != -1 {

            let state = create_state(staller);

            if pstate.get().stalling_since == OffsetDateTime::from_unix_timestamp(0).ok() {

                state.get_mut().stalling_since = Some(current_time);

                log_print!(
                    LogFlags::NET, 
                    "Stall started peer=%d\n", 
                    staller
                );
            }
        }
    }

    fn download_txn(
        self:      Arc<Self>, 
        pnode:     Amo<Box<dyn NodeInterface>>,
        msg_maker: &NetMsgMaker,
        get_data:  &mut Vec<Inv>,
        gtxid:     &GenTxId,
    ) {

        let current_time = get_datetime();

        log_print!(
            LogFlags::NET, 
            "Requesting %s %s peer=%d\n", 
            match gtxid.is_wtxid() {
                true   => "wtx",
                false  => "tx"
            }, 
            gtxid.get_hash().to_string(), (*pto).get_id()
        );

        get_data.push(
            Inv::new(
                match gtxid.is_wtxid() {
                    true   => GetDataMsg::MSG_WTX.bits(),
                    false  => {
                        let msg_tx = GetDataMsg::MSG_TX;
                        let flags  = get_fetch_flags(&**pnode.get());
                        (msg_tx | flags).bits()
                    }
                }, 
                gtxid.get_hash()
            )
        );

        if get_data.len() >= MAX_GETDATA_SZ.try_into().unwrap() {

            self.connman.get_mut().push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make(
                    NetMsgType::GETDATA, 
                    &[
                        get_data
                    ]
                )
            );

            get_data.clear();
        }

        self.inner.lock().txrequest.lock().requested_tx(
            pnode.get().get_id(), 
            gtxid.get_hash(), 
            current_time + GETDATA_TX_INTERVAL
        );
    }

    fn check_for_headers_sync_timeouts(
        self:   Arc<Self>, 
        pnode:  Amo<Box<dyn NodeInterface>>,
        pstate: Amo<NodeState>) 
    {
        // Check for headers sync timeouts
        if pstate.get().sync_started.load(atomic::Ordering::Relaxed) 
        && pstate.get().headers_sync_timeout.is_some() {

            // Detect whether this is a stalling
            // initial-headers-sync peer
            if (*PINDEX_BEST_HEADER.lock()).as_ref().unwrap().get_block_time() <= get_adjusted_time() - 24 * 60 * 60 {

                self.handle_stalling_initial_headers_sync_peer(pnode,pstate);

            } else {

                // After we've caught up once,
                // reset the timeout so we can't
                // trigger disconnect later.
                pstate.get_mut().headers_sync_timeout = None;
            }
        }
    }

    fn handle_stalling_initial_headers_sync_peer(
        self:   Arc<Self>, 
        pnode:  Amo<Box<dyn NodeInterface>>,
        pstate: Amo<NodeState>) {

        let current_time = get_datetime();

        if current_time > pstate.get().headers_sync_timeout.unwrap() 
        && self.inner.lock().n_sync_started == 1 
        && {

            let n_preferred_dl = N_PREFERRED_DOWNLOAD.load(atomic::Ordering::Relaxed);

            let state_preferred_dl = match pstate.get().preferred_download.load(atomic::Ordering::Relaxed) { true => 1, false => 0 };

            (n_preferred_dl - state_preferred_dl) >= 1
        }
        {
            self.disconnect_peer_if_it_is_our_only_sync_peer_and_we_have_others_we_could_be_using_instead(pnode,pstate);
        }
    }

    fn disconnect_peer_if_it_is_our_only_sync_peer_and_we_have_others_we_could_be_using_instead(
        self:   Arc<Self>, 
        pnode:  Amo<Box<dyn NodeInterface>>, 
        pstate: Amo<NodeState>) -> ControlFlow {

        let node = pnode.get();

        // Disconnect a peer (without
        // NetPermissionFlags::NoBan permission)
        // if it is our only sync peer, and we
        // have others we could be using instead.
        //
        // Note: If all our peers are inbound,
        // then we won't disconnect our sync peer
        // for stalling; we have bigger problems
        // if we can't get any outbound peers.
        if !node.has_permission(NetPermissionFlags::NoBan) {

            log_printf!(
                "Timeout downloading headers from peer=%d, disconnecting\n", 
                (*pto).get_id()
            );

            node.mark_for_disconnect();

            return ControlFlow::Return;

        } else {

            log_printf!(
                "Timeout downloading headers from noban peer=%d, not disconnecting\n", 
                (*pto).get_id()
            );

            // Reset the headers sync state so
            // that we have a chance to try
            // downloading from a different peer.
            //
            // Note: this will also result in at
            // least one more getheaders message
            // to be sent to this peer
            // (eventually).
            pstate.get().sync_started.store(false, atomic::Ordering::Relaxed);

            {
                let old = self.inner.lock().n_sync_started;
                self.inner.lock().n_sync_started -= 1;
                old
            };

            pstate.get_mut()
                .headers_sync_timeout 
                = Some(OffsetDateTime::from_unix_timestamp(0).unwrap());
        }

        ControlFlow::None
    }

    fn start_block_sync(self: Arc<Self>) {

        PINDEX_BEST_HEADER.lock().replace(
            self.chainman.get().active_chain().tip().clone().unwrap()
        );
    }

    fn respond_to_bip35_mempool_requests(
        self:      Arc<Self>, 
        mut node:  &mut AmoWriteGuard<Box<dyn NodeInterface>>, 
        pstate:    Amo<NodeState>,
        inventory: &mut Vec<Inv>,
        msg_maker: &NetMsgMaker
    ) {

        let current_time = get_datetime();

        let vtxinfo = self.mempool.get().info_all();

        node.get_tx_relay_mut().cs_tx_inventory.lock().send_mempool = false;

        let filterrate: FeeRate 
        = FeeRate::new(
            node.get_tx_relay().min_fee_filter.load(atomic::Ordering::Relaxed)
        );

        for txinfo in vtxinfo.iter() {

            let tx = txinfo.tx.get();

            let hash: &u256 = match pstate.get().wtxid_relay.load(atomic::Ordering::Relaxed) {
                true   => tx.get_witness_hash(),
                false  => tx.get_hash()
            };

            let inv: Inv = Inv::new(
                match pstate.get().wtxid_relay.load(atomic::Ordering::Relaxed) {
                    true   => GetDataMsg::MSG_WTX.bits(),
                    false  => GetDataMsg::MSG_TX.bits()
                }, 
                hash
            );

            node.get_tx_relay().set_inventory_tx_to_send.lock().remove(hash);

            // Don't send transactions
            // that peers will not put
            // into their mempool
            if txinfo.fee < filterrate.get_fee(txinfo.vsize.try_into().unwrap()) {
                continue;
            }

            let pfilter = node.get_tx_relay().cs_filter.lock().pfilter.clone();

            if pfilter.is_some()
            {
                if !pfilter.unwrap()
                    .is_relevant_and_update(&txinfo.tx.get()) 
                {
                    continue;
                }
            }

            node.get_tx_relay_mut()
                .cs_tx_inventory
                .lock()
                .filter_inventory_known
                .insert_key(hash.as_slice());

            // Responses to MEMPOOL requests
            // bypass the
            // m_recently_announced_invs filter.
            inventory.push(inv);

            if inventory.len() == MAX_INV_SZ.try_into().unwrap() {

                self.connman.get_mut()
                    .push_message(
                        &mut *node, 
                        msg_maker.make(
                            NetMsgType::INV, 
                            &[
                                inventory
                            ]
                        )
                    );

                inventory.clear();
            }
        }

        node.get_tx_relay()
            .last_mempool_req.store(
                Some(current_time), 
                atomic::Ordering::Relaxed
            );

    }

    fn determine_transactions_to_relay(
        self:      Arc<Self>, 
        mut node:  &mut AmoWriteGuard<Box<dyn NodeInterface>>, 
        pstate:    Amo<NodeState>,
        inventory: &mut Vec<Inv>,
        msg_maker: &NetMsgMaker
    ) {

        // Produce a vector with all candidates
        // for sending
        let mut inv_tx: Vec<u256> = vec![];

        inv_tx.reserve(
            node.get_tx_relay()
                .set_inventory_tx_to_send.lock().len()
        );

        {
            let tx_relay = node.get_tx_relay();

            let inv_lock = tx_relay
                .set_inventory_tx_to_send
                .lock();

            for it in inv_lock.iter() {
                inv_tx.push(it.clone());
            }
        }

        let filterrate: FeeRate = 
        FeeRate::new(
            node.get_tx_relay()
                .min_fee_filter
                .load(atomic::Ordering::Relaxed)
        );

        // Topologically and fee-rate sort the
        // inventory we send for privacy and
        // priority reasons.
        //
        // A heap is used so that not all items
        // need sorting if only a few are being
        // sent.
        let compare_inv_mempool_order: CompareInvMempoolOrder 
        = CompareInvMempoolOrder::new(
            self.mempool.clone(), 
            pstate.get().wtxid_relay.load(atomic::Ordering::Relaxed)
        );

        let mut inv_tx: MaxHeap<u256, CompareInvMempoolOrder> = {

            let mut builder 
            = MaxHeap::with_comparator(
                compare_inv_mempool_order
            );

            builder.extend(
                inv_tx.iter().cloned().collect::<Vec<u256>>()
            );

            builder
        };

        // No reason to drain out at many times
        // the network's capacity, especially
        // since we have many peers and some will
        // draw much shorter delays.
        let mut n_relayed_transactions: u32 = 0;

        while !inv_tx.is_empty() && n_relayed_transactions < *INVENTORY_BROADCAST_MAX {

            // Fetch the top element from the heap
            let it = inv_tx.pop();

            let hash: u256 = it.unwrap();

            let inv: Inv = Inv::new(
                match pstate.get().wtxid_relay.load(atomic::Ordering::Relaxed) {
                    true   => GetDataMsg::MSG_WTX.bits(),
                    false  => GetDataMsg::MSG_TX.bits()
                }, 
                &hash
            );

            // Remove it from the to-be-sent set
            node.get_tx_relay_mut()
                .set_inventory_tx_to_send
                .lock()
                .remove(&hash);

            // Check if not in the filter already
            if node.get_tx_relay()
                .cs_tx_inventory.lock()
                .filter_inventory_known
                .contains_key(hash.as_slice()) 
            {
                continue;
            }

            // Not in the mempool anymore? don't bother sending it.
            let txinfo = self.mempool.get().info(
                &(inv.clone()).into()
            );

            if txinfo.tx.is_none() {
                continue;
            }

            let tx = txinfo.tx.get();

            let txid  = tx.get_hash();
            let wtxid = tx.get_witness_hash();

            // Peer told you to not send
            // transactions at that feerate? Don't
            // bother sending it.
            if txinfo.fee < filterrate.get_fee(txinfo.vsize.try_into().unwrap()) {
                continue;
            }

            if let Some(ref mut filter) = node.get_tx_relay().cs_filter.lock().pfilter {

                if !filter.is_relevant_and_update(&txinfo.tx.get()) {
                    continue;
                }
            }

            let id = node.get_id();

            // Send
            create_state(id)
                .get_mut()
                .recently_announced_invs
                .insert_key(hash.as_slice());

            inventory.push(inv);

            n_relayed_transactions += 1;

            {
                self.clone().expire_old_relay_messages(&txinfo,&txid,&wtxid);
            }

            if inventory.len() == MAX_INV_SZ.try_into().unwrap() {

                self.connman.get_mut()
                    .push_message(
                        &mut *node, 
                        msg_maker.make(
                            NetMsgType::INV, 
                            &[
                                inventory
                            ]
                        )
                    );

                inventory.clear();
            }

            node.get_tx_relay()
                .cs_tx_inventory.lock()
                .filter_inventory_known
                .insert_key(hash.as_slice());

            if hash != *txid {

                // Insert txid into
                // filterInventoryKnown,
                // even for wtxidrelay
                // peers. This
                // prevents re-adding
                // of unconfirmed
                // parents to the
                // recently_announced
                // filter, when
                // a child tx is
                // requested. See
                // ProcessGetData().
                node.get_tx_relay()
                    .cs_tx_inventory.lock()
                    .filter_inventory_known
                    .insert_key(txid.as_slice());
            }
        }
    }

    fn disconnect_timedout_blocks_in_flight(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>, 
        pstate:           Amo<NodeState>,
        consensus_params: Arc<ChainConsensusParams>,
    ) -> ControlFlow {

        let current_time = get_datetime();

        let node = pnode.get();

        let queued_block: &mut QueuedBlock = &mut pstate.get_mut().blocks_in_flight[0];

        let inner = self.inner.lock();

        let n_other_peers_with_validated_downloads: i32 = inner.peers_downloading_from.load(atomic::Ordering::Relaxed) - 1;

        if current_time > 
        pstate.get().downloading_since 
        + Duration::seconds(consensus_params.n_pow_target_spacing) * 
        (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * (n_other_peers_with_validated_downloads as f64))
        {
            log_printf!(
                "Timeout downloading block %s from peer=%d, disconnecting\n", 
                (*queued_block.pindex()).get_block_hash().to_string(), 
                (*pto).get_id()
            );

            node.mark_for_disconnect();

            return ControlFlow::Return;
        }

        ControlFlow::None
    }

    fn process_headers_prefer_headers(
        self:       Arc<Self>, 
        pnode:      Amo<Box<dyn NodeInterface>>,
        pstate:     Amo<NodeState>,
        msg_maker:  &NetMsgMaker,
        headers:    &Vec<BlockHeader>,
        best_index: Option<Arc<BlockIndex>>,
    ) {

        if headers.len() > 1 {

            log_print!(
                LogFlags::NET, 
                "%s: %u headers, range (%s, %s), to peer=%d\n", 
                func, 
                headers.len(), 
                headers.front().get_hash().to_string(), 
                headers.back().get_hash().to_string(), 
                (*pto).get_id()
            );

        } else {

            log_print!(
                LogFlags::NET, 
                "%s: sending header %s to peer=%d\n", 
                func, 
                headers.front().get_hash().to_string(), 
                (*pto).get_id()
            );
        }

        self.connman.get_mut()
            .push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make(
                    NetMsgType::HEADERS, 
                    &[
                        headers
                    ]
                )
            );

        pstate.get_mut().pindex_best_header_sent = best_index;
    }

    fn process_headers_prefer_headers_and_ids(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>,
        pstate:           Amo<NodeState>,
        msg_maker:        &NetMsgMaker,
        best_index:       Option<Arc<BlockIndex>>,
        consensus_params: Arc<ChainConsensusParams>) 
    {
        // We only send up to
        // 1 block as header-and-ids, as otherwise
        // probably means we're doing an
        // initial-ish-sync or they're slow
        log_print!(
            LogFlags::NET,
            "%s sending header-and-ids %s to peer=%d\n",
            func,
            headers.front().get_hash().to_string(),
            (*pto).get_id()
        );

        let n_send_flags: i32 = match pstate.get().wants_cmpct_witness.load(atomic::Ordering::Relaxed) {
            true   => 0,
            false  => SERIALIZE_TRANSACTION_NO_WITNESS
        };

        let mut got_block_from_cache: bool = false;

        {
            let mut guard = CS_MOST_RECENT_BLOCK.get();

            if *MOST_RECENT_BLOCK_HASH.get() == best_index.as_ref().unwrap().get_block_hash() {

                self.clone().handle_most_recent_blockhash_is_best_index(
                    pnode.clone(), 
                    pstate.clone(), 
                    n_send_flags, 
                    msg_maker
                );

                got_block_from_cache = true;
            }
        }

        if !got_block_from_cache {

            self.clone().handle_noblock_from_cache(
                pnode.clone(), 
                pstate.clone(), 
                best_index.clone(), 
                consensus_params.clone(), 
                n_send_flags, 
                msg_maker
            );
        }

        pstate.get_mut().pindex_best_header_sent = best_index;
    }

    fn process_headers(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>,
        pstate:           Amo<NodeState>,
        msg_maker:        &NetMsgMaker,
        headers:          &Vec<BlockHeader>,
        best_index:       Option<Arc<BlockIndex>>,
        consensus_params: Arc<ChainConsensusParams>,
        revert_to_inv:    &mut bool) 
    {
        if headers.len() == 1 && pstate.get().prefer_header_and_ids.load(atomic::Ordering::Relaxed) {

            self.process_headers_prefer_headers_and_ids(
                pnode,
                pstate,
                msg_maker,
                best_index,
                consensus_params,
            );

        } else {

            if pstate.get().prefer_headers.load(atomic::Ordering::Relaxed) {

                self.process_headers_prefer_headers(
                    pnode, 
                    pstate, 
                    msg_maker, 
                    headers, 
                    best_index
                );

            } else {
                *revert_to_inv = true;
            }
        }
    }

    fn handle_no_starting_header(
        self:                  Arc<Self>, 
        pindex:                Arc<BlockIndex>,
        pstate:                Amo<NodeState>,
        headers:               &mut Vec<BlockHeader>,
        revert_to_inv:         &mut bool,
        found_starting_header: &mut bool) -> ControlFlow 
    {
        if peer_has_header_with_amo(&pstate.get(),pindex.clone()) {

            // keep looking for the first new
            // block
            return ControlFlow::Continue;

        } else {

            if pindex.pprev.is_none() 
            || peer_has_header_with_amo(&pstate.get(),pindex.pprev.clone().unwrap()) {

                // Peer doesn't have this header
                // but they do have the prior one.
                //
                // Start sending headers.
                *found_starting_header = true;

                headers.push(pindex.get_block_header());

            } else {

                // Peer doesn't have this header
                // or the prior one -- nothing
                // will connect, so bail out.
                *revert_to_inv = true;

                return ControlFlow::Break;
            }
        }

        ControlFlow::None
    }

    fn handle_most_recent_blockhash_is_best_index(
        self:         Arc<Self>, 
        pnode:        Amo<Box<dyn NodeInterface>>,
        pstate:       Amo<NodeState>,
        n_send_flags: i32,
        msg_maker:    &NetMsgMaker
    ) {

        if pstate.get().wants_cmpct_witness.load(atomic::Ordering::Relaxed) 
        || !WITNESSES_PRESENT_IN_MOST_RECENT_COMPACT_BLOCK.load(atomic::Ordering::Relaxed) 
        {
            self.connman.get_mut().push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make_with_flags(
                    n_send_flags, 
                    NetMsgType::CMPCTBLOCK, 
                    &[
                        &MOST_RECENT_COMPACT_BLOCK.get()
                    ]
                )
            );

        } else {

            let cmpctblock: BlockHeaderAndShortTxIDs 
            = BlockHeaderAndShortTxIDs::new(
                MOST_RECENT_BLOCK.clone(), 
                pstate.get().wants_cmpct_witness.load(atomic::Ordering::Relaxed)
            );

            self.connman.get_mut().push_message(
                &mut *pnode.get_mut(), 
                msg_maker.make_with_flags(
                    n_send_flags, 
                    NetMsgType::CMPCTBLOCK, 
                    &[
                        &cmpctblock
                    ]
                )
            );
        }
    }

    fn handle_noblock_from_cache(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>,
        pstate:           Amo<NodeState>,
        best_index:       Option<Arc<BlockIndex>>,
        consensus_params: Arc<ChainConsensusParams>,
        n_send_flags:     i32,
        msg_maker:        &NetMsgMaker
    ) {
        let mut block = Amo::<Block>::from(Block::default());

        let ret: bool = read_block_from_disk_with_blockindex(
            &mut block.get_mut(),
            best_index.as_ref().unwrap().clone(),
            &consensus_params
        );

        assert!(ret);

        let cmpctblock: BlockHeaderAndShortTxIDs = BlockHeaderAndShortTxIDs::new(
            block.clone(), 
            pstate.get().wants_cmpct_witness.load(atomic::Ordering::Relaxed)
        );

        self.connman.get_mut().push_message(
            &mut *pnode.get_mut(), 
            msg_maker.make_with_flags(
                n_send_flags, 
                NetMsgType::CMPCTBLOCK, 
                &[
                    &cmpctblock
                ]
            )
        );
    }

    fn try_find_starting_header(
        self:          Arc<Self>,
        peer:          Amo<Peer>,
        pstate:        Amo<NodeState>,
        best_index:    &mut Option<Arc<BlockIndex>>,
        headers:       &mut Vec<BlockHeader>,
        revert_to_inv: &mut bool,
    ) {

        let mut found_starting_header: bool = false;

        // Try to find first header that our peer
        // doesn't have, and then send all headers
        // past that one.  If we come across any
        // headers that aren't on
        // m_chainman.ActiveChain(), give up.
        for hash in peer.get().block_inv_mutex.lock().blocks_for_headers_relay.iter() {

            let pindex: Option<Arc<BlockIndex>> 
            = self.chainman.get()
                .inner
                .blockman
                .lookup_block_index(hash);

            assert!(pindex.is_some());

            if self.chainman.get().active_chain()[pindex.as_ref().unwrap().n_height] != pindex {
                //  Bail out if we reorged away from this block
                *revert_to_inv = true;
                break;
            }

            if best_index.is_some() 
            && pindex.as_ref().unwrap().pprev.as_ref().unwrap() != best_index.as_ref().unwrap() {

                //  This means that the list of
                //  blocks to announce don't
                //  connect to each other.
                //
                //  This shouldn't really be
                //  possible to hit during regular
                //  operation (because reorgs
                //  should take us to a chain that
                //  has some block not on the
                //  prior chain, which should be
                //  caught by the prior check),
                //  but one way this could happen
                //  is by using invalidateblock
                //  / reconsiderblock repeatedly
                //  on the tip, causing it to be
                //  added multiple times to
                //  m_blocks_for_headers_relay.
                //
                //  Robustly deal with this rare
                //  situation by reverting to an
                //  inv.
                *revert_to_inv = true;
                break;
            }

            *best_index = pindex.clone();

            if found_starting_header {

                // add this to the headers message
                headers.push(pindex.as_ref().unwrap().get_block_header());

            } else {

                self.clone().handle_no_starting_header(
                    pindex.as_ref().unwrap().clone(),
                    pstate.clone(),
                    headers,
                    revert_to_inv,
                    &mut found_starting_header
                );
            }
        }
    }

    fn try_to_inv_the_tip(
        self:   Arc<Self>, 
        pstate: Amo<NodeState>,
        peer:   AmoReadGuard<Peer>
    ) {

        // If falling back to using an inv, just
        // try to inv the tip.
        //
        // The last entry in
        // m_blocks_for_headers_relay was our tip
        // at some point in the past.
        if !peer.block_inv_mutex.lock().blocks_for_headers_relay.is_empty() {

            let block_inv_guard = peer.block_inv_mutex.lock();

            let hash_to_announce: &u256 = 
                block_inv_guard
                .blocks_for_headers_relay
                .last()
                .unwrap();

            let pindex: Option<Arc<BlockIndex>> 
            = self.chainman.get()
                .inner
                .blockman
                .lookup_block_index(hash_to_announce);

            assert!(pindex.is_some());

            // Warn if we're announcing a block
            // that is not on the main chain.
            //
            // This should be very rare and could
            // be optimized out.
            //
            // Just log for now.
            if self.chainman.get().active_chain()[pindex.as_ref().unwrap().n_height] != pindex {
                log_print!(
                    LogFlags::NET, 
                    "Announcing block %s not on main chain (tip=%s)\n", 
                    hash_to_announce.to_string(), 
                    (*self.chainman.active_chain().tip()).get_block_hash().to_string()
                );
            }

            // If the peer's chain has this block,
            // don't inv it back.
            if !peer_has_header_with_amo(&pstate.get(),pindex.unwrap()) {

                peer 
                    .block_inv_mutex.lock()
                    .blocks_for_inv_relay.push(hash_to_announce.clone());

                log_print!(
                    LogFlags::NET, 
                    "%s: sending inv peer=%d hash=%s\n", 
                    func, 
                    (*pto).get_id(), 
                    hash_to_announce.to_string()
                );
            }
        }
    }

    // Try sending block announcements via headers
    #[EXCLUSIVE_LOCKS_REQUIRED(pto->cs_sendProcessing)]
    fn try_sending_block_announcements_via_headers(
        self:             Arc<Self>, 
        pnode:            Amo<Box<dyn NodeInterface>>, 
        pstate:           Amo<NodeState>,
        peer:             Amo<Peer>,
        msg_maker:        &NetMsgMaker,
        consensus_params: Arc<ChainConsensusParams>,
    ) {

        // If we have less than
        // MAX_BLOCKS_TO_ANNOUNCE in our
        // list of block hashes we're
        // relaying, and our peer wants
        // headers announcements, then
        // find the first header not yet
        // known to our peer but would
        // connect, and send.
        //
        // If no header would connect, or
        // if we have too many blocks, or
        // if the peer doesn't want
        // headers, just add all to the
        // inv queue.
        let mut guard = peer.get();

        let mut block_inv_mutex = guard.block_inv_mutex.lock();

        let mut headers: Vec<BlockHeader> = vec![];

        let mut revert_to_inv: bool = 
        (
            !pstate.get().prefer_headers.load(atomic::Ordering::Relaxed) && (!pstate.get().prefer_header_and_ids.load(atomic::Ordering::Relaxed) 
            || peer.get().block_inv_mutex.lock().blocks_for_headers_relay.len() > 1)
        ) 
        || peer.get().block_inv_mutex.lock().blocks_for_headers_relay.len() > (MAX_BLOCKS_TO_ANNOUNCE as usize);

        // last header queued for delivery
        let mut best_index: Option<Arc<BlockIndex>> = None;

        //  ensure pindexBestKnownBlock is up-to-date
        self.clone().process_block_availability(pnode.get().get_id());

        if !revert_to_inv {

            self.clone().try_find_starting_header(
                peer.clone(),
                pstate.clone(),
                &mut best_index,
                &mut headers,
                &mut revert_to_inv
            );
        }

        if !revert_to_inv && !headers.is_empty() {

            self.clone().process_headers(
                pnode,
                pstate.clone(),
                &msg_maker,
                &headers,
                best_index.clone(),
                consensus_params,
                &mut revert_to_inv
            );
        }

        if revert_to_inv {

            self.clone().try_to_inv_the_tip(
                pstate.clone(),
                peer.get()
            );
        }

        peer.get().block_inv_mutex.lock().blocks_for_headers_relay.clear();
    }
}