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
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
// length of 1 genesis period
pub const GENESIS_PERIOD: u64 = 10;
// prune blocks from index after N blocks
pub const PRUNE_AFTER_BLOCKS: u64 = 20;
// max recursion when paying stakers -- number of blocks including  -- number of blocks including GTT
pub const MAX_STAKER_RECURSION: u64 = 3;
// max token supply - used in validating block #1
pub const MAX_TOKEN_SUPPLY: u64 = 1_000_000_000_000_000_000;
// minimum golden tickets required ( NUMBER_OF_TICKETS / number of preceding blocks )
pub const MIN_GOLDEN_TICKETS_NUMERATOR: u64 = 2;
// minimum golden tickets required ( number of tickets / NUMBER_OF_PRECEDING_BLOCKS )
pub const MIN_GOLDEN_TICKETS_DENOMINATOR: u64 = 6;

use crate::block::{Block, BlockType};
use crate::blockring::BlockRing;
use crate::consensus::SaitoMessage;
use crate::crypto::{SaitoHash, SaitoUTXOSetKey};
use crate::staking::Staking;
use crate::storage::Storage;
use crate::time::create_timestamp;
use crate::transaction::TransactionType;
use crate::wallet::Wallet;
use log::{error, info, trace, warn};

use async_recursion::async_recursion;

use ahash::AHashMap;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, RwLock};

pub fn bit_pack(top: u32, bottom: u32) -> u64 {
    ((top as u64) << 32) + (bottom as u64)
}
pub fn bit_unpack(packed: u64) -> (u32, u32) {
    // Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate, no need to mask this
    let bottom = packed as u32;
    let top = (packed >> 32) as u32;
    (top, bottom)
}

pub type UtxoSet = AHashMap<SaitoUTXOSetKey, u64>;

#[derive(Debug)]
pub struct Blockchain {
    pub staking: Staking,
    pub utxoset: UtxoSet,
    pub blockring: BlockRing,
    pub blocks: AHashMap<SaitoHash, Block>,
    pub wallet_lock: Arc<RwLock<Wallet>>,
    broadcast_channel_sender: Option<broadcast::Sender<SaitoMessage>>,
    genesis_block_id: u64,
    fork_id: SaitoHash,
}

impl Blockchain {
    #[allow(clippy::new_without_default)]
    pub fn new(wallet_lock: Arc<RwLock<Wallet>>) -> Self {
        Blockchain {
            staking: Staking::new(),
            utxoset: AHashMap::new(),
            blockring: BlockRing::new(),
            blocks: AHashMap::new(),
            wallet_lock,
            broadcast_channel_sender: None,
            genesis_block_id: 0,
            fork_id: [0; 32],
        }
    }

    pub fn set_broadcast_channel_sender(&mut self, bcs: broadcast::Sender<SaitoMessage>) {
        self.broadcast_channel_sender = Some(bcs);
    }

    pub fn set_fork_id(&mut self, fork_id: SaitoHash) {
        self.fork_id = fork_id;
    }

    pub fn get_fork_id(&self) -> SaitoHash {
        self.fork_id
    }

    pub async fn add_block(&mut self, mut block: Block) {
        //
        // get missing block
        //
        if self.blockring.get_latest_block_id() > 0 {
            let mut earliest_block_id = 1;
            if self.get_latest_block_id() > GENESIS_PERIOD {
                earliest_block_id = self.get_latest_block_id() - GENESIS_PERIOD;
            }
            trace!("earliest_block_id {}", earliest_block_id);
            let earliest_block_hash = self
                .blockring
                .get_longest_chain_block_hash_by_block_id(earliest_block_id);
            trace!("earliest_block_hash {:?}", earliest_block_hash);
            let earliest_block = self.get_mut_block(&earliest_block_hash).await;

            if block.get_timestamp() > earliest_block.get_timestamp() {
                if self
                    .get_block(&block.get_previous_block_hash())
                    .await
                    .is_none()
                {
                    if block.get_id() > earliest_block_id {
                        if block.get_source_connection_id().is_some()
                            && self.broadcast_channel_sender.is_some()
                        {
                            self.broadcast_channel_sender
                                .as_ref()
                                .unwrap()
                                .send(SaitoMessage::MissingBlock {
                                    peer_id: block.get_source_connection_id().unwrap(),
                                    hash: block.get_previous_block_hash(),
                                })
                                .expect("error: MissingBlock message failed to send");
                        }
                    }
                }
            }
        }

        //
        // first things first, confirm hashes OK
        //
        block.generate_hashes();

        info!("add_block {}", &hex::encode(&block.get_hash()));
        trace!(
            " ... blockchain.add_block start: {:?} hash: {:?}, and id {}",
            create_timestamp(),
            block.get_hash(),
            block.get_id()
        );

        //
        // start by extracting some variables that we will use
        // repeatedly in the course of adding this block to the
        // blockchain and our various indices.
        //
        let block_hash = block.get_hash();
        let block_id = block.get_id();
        let previous_block_hash = self.blockring.get_latest_block_hash();

        //
        // sanity checks
        //
        if self.blocks.contains_key(&block_hash) {
            error!(
                "ERROR: block exists in blockchain {:?}",
                &hex::encode(&block.get_hash())
            );
            return;
        }

        //
        // pre-validation
        //
        // this would be a great place to put in a prevalidation check
        // once we are finished implementing Saito Classic. Goal would
        // be a fast form of lite-validation just to determine that it
        // is worth going through the more general effort of evaluating
        // this block for consensus.
        //

        //
        // save block to disk
        //
        // we have traditionally saved blocks to disk AFTER validating them
        // but this can slow down block propagation. So it may be sensible
        // to start a save earlier-on in the process so that we can relay
        // the block faster serving it off-disk instead of fetching it
        // repeatedly from memory. Exactly when to do this is left as an
        // optimization exercise.
        //

        //
        // insert block into hashmap and index
        //
        // the blockring is a BlockRing which lets us know which blocks (at which depth)
        // form part of the longest-chain. We also use the BlockRing to track information
        // on network congestion (how many block candidates exist at various depths and
        // in the future potentially the amount of work on each viable fork chain.
        //
        // we are going to transfer ownership of the block into the HashMap that stores
        // the block next, so we insert it into our BlockRing first as that will avoid
        // needing to borrow the value back for insertion into the BlockRing.
        //
        if !self
            .blockring
            .contains_block_hash_at_block_id(block_id, block_hash)
        {
            self.blockring.add_block(&block);
        }
        //
        // blocks are stored in a hashmap indexed by the block_hash. we expect all
        // all block_hashes to be unique, so simply insert blocks one-by-one on
        // arrival if they do not exist.
        //
        if !self.blocks.contains_key(&block_hash) {
            self.blocks.insert(block_hash, block);
        } else {
            error!(
                "BLOCK IS ALREADY IN THE BLOCKCHAIN, WHY ARE WE ADDING IT????? {:?}",
                block.get_hash()
            );
        }

        //
        // find shared ancestor of new_block with old_chain
        //
        let mut new_chain: Vec<[u8; 32]> = Vec::new();
        let mut old_chain: Vec<[u8; 32]> = Vec::new();
        let mut shared_ancestor_found = false;
        let mut new_chain_hash = block_hash;
        let mut old_chain_hash = previous_block_hash;

        while !shared_ancestor_found {
            if self.blocks.contains_key(&new_chain_hash) {
                if self.blocks.get(&new_chain_hash).unwrap().get_lc() {
                    shared_ancestor_found = true;
                    break;
                } else {
                    if new_chain_hash == [0; 32] {
                        break;
                    }
                }
                new_chain.push(new_chain_hash);
                new_chain_hash = self
                    .blocks
                    .get(&new_chain_hash)
                    .unwrap()
                    .get_previous_block_hash();
            } else {
                break;
            }
        }

        //
        // and get existing current chain for comparison
        //
        if shared_ancestor_found {
            loop {
                if new_chain_hash == old_chain_hash {
                    break;
                }
                if self.blocks.contains_key(&old_chain_hash) {
                    old_chain.push(old_chain_hash);
                    old_chain_hash = self
                        .blocks
                        .get(&old_chain_hash)
                        .unwrap()
                        .get_previous_block_hash();
                    if old_chain_hash == [0; 32] {
                        break;
                    }
                    if new_chain_hash == old_chain_hash {
                        break;
                    }
                }
            }
        } else {
            //
            // we have a block without a parent.
            //
            // if this is our first block, the blockring will have no entry yet
            // and block_ring_lc_pos (longest_chain_position) will be pointing
            // at None. We use this to determine if we are a new chain instead
            // of creating a separate variable to manually track entries.
            //
            if self.blockring.is_empty() {
                //
                // no need for action as fall-through will result in proper default
                // behavior. we have the comparison here to separate expected from
                // unexpected / edge-case issues around block receipt.
                //
            } else {
                //
                // TODO - implement logic to handle once nodes can connect
                //
                // if this not our first block, handle edge-case around receiving
                // block 503 before block 453 when block 453 is our expected proper
                // next block and we are getting blocks out-of-order because of
                // connection or network issues.
                //
                error!("blocks received out-of-order issue...");
            }
        }

        //
        // at this point we should have a shared ancestor or not
        //
        // find out whether this new block is claiming to require chain-validation
        //
        let am_i_the_longest_chain = self.is_new_chain_the_longest_chain(&new_chain, &old_chain);

        //
        // validate
        //
        // blockchain validate "validates" the new_chain by unwinding the old
        // and winding the new, which calling validate on any new previously-
        // unvalidated blocks. When the longest-chain status of blocks changes
        // the function on_chain_reorganization is triggered in blocks and
        // with the BlockRing. We fail if the newly-preferred chain is not
        // viable.
        //
        if am_i_the_longest_chain {
            let does_new_chain_validate = self.validate(new_chain, old_chain).await;
            if does_new_chain_validate {
                self.add_block_success(block_hash).await;

                //
                // TODO
                //
                // mutable update is hell -- we can do this but have to have
                // manually checked that the entry exists in order to pull
                // this trick. we did this check before validating.
                //
                {
                    self.blocks.get_mut(&block_hash).unwrap().set_lc(true);
                }

                if self.broadcast_channel_sender.is_some() {
                    self.broadcast_channel_sender
                        .as_ref()
                        .unwrap()
                        .send(SaitoMessage::BlockchainAddBlockSuccess { hash: block_hash })
                        .expect("error: BlockchainAddBlockSuccess message failed to send");

                    let difficulty = self.blocks.get(&block_hash).unwrap().get_difficulty();

                    self.broadcast_channel_sender
                        .as_ref()
                        .unwrap()
                        .send(SaitoMessage::BlockchainNewLongestChainBlock {
                            hash: block_hash,
                            difficulty,
                        })
                        .expect("error: BlockchainNewLongestChainBlock message failed to send");
                }
            } else {
                self.add_block_failure().await;

                if self.broadcast_channel_sender.is_some() {
                    self.broadcast_channel_sender
                        .as_ref()
                        .unwrap()
                        .send(SaitoMessage::BlockchainAddBlockFailure { hash: block_hash })
                        .expect("error: BlockchainAddBlockFailure message failed to send");
                }
            }
        } else {
            self.add_block_failure().await;

            if self.broadcast_channel_sender.is_some() {
                self.broadcast_channel_sender
                    .as_ref()
                    .unwrap()
                    .send(SaitoMessage::BlockchainAddBlockFailure { hash: block_hash })
                    .expect("error: BlockchainAddBlockFailure message failed to send");
            }
        }
    }
    pub async fn add_block_to_blockchain(blockchain_lock: Arc<RwLock<Blockchain>>, block: Block) {
        let mut blockchain = blockchain_lock.write().await;
        let res = blockchain.add_block(block).await;
        res
    }

    pub async fn add_block_success(&mut self, block_hash: SaitoHash) {
        trace!(
            " ... blockchain.add_block_success: {:?}",
            create_timestamp()
        );
        // print blockring longest_chain_block_hash infor
        self.print();

        //
        // save to disk
        //
        {
            let block = self.get_mut_block(&block_hash).await;
            if block.get_block_type() != BlockType::Header {
                Storage::write_block_to_disk(block);
            }
        }

        //
        // TODO: clean up mempool - I think we shouldn't cleanup mempool here.
        //  because that's already happening in send_blocks_to_blockchain
        //  So who is in charge here?
        //  is send_blocks_to_blockchain calling add_block or
        //  is blockchain calling mempool.on_chain_reorganization?
        //
        //
        // mempool.delete_transactions(&block.get_transactions());

        //
        // propagate block to network
        //
        if self.broadcast_channel_sender.is_some() {
            self.broadcast_channel_sender
                .as_ref()
                .unwrap()
                .send(SaitoMessage::BlockchainSavedBlock { hash: block_hash })
                .expect("error: BlockchainSavedBlock message failed to send");
        }
        trace!(" ... block save done:            {:?}", create_timestamp());

        //
        // update_genesis_period and prune old data - MOVED to on_chain_reorganization()
        //
        // self.update_genesis_period().await;

        //
        // fork id  - MOVED to on_chain_reorganization()
        //
        // let fork_id = self.generate_fork_id(block_id);
        // self.set_fork_id(fork_id);

        //
        // ensure pruning of next block OK will have the right CVs
        //
        if self.get_latest_block_id() > GENESIS_PERIOD {
            let pruned_block_hash = self.blockring.get_longest_chain_block_hash_by_block_id(
                self.get_latest_block_id() - GENESIS_PERIOD,
            );

            //
            // TODO
            //
            // handle this more efficiently - we should be able to prepare the block
            // in advance so that this doesn't take up time in block production. we
            // need to generate_metadata_hashes so that the slips know the utxo_key
            // to use to check the utxoset.
            //
            {
                let pblock = self.get_mut_block(&pruned_block_hash).await;
                pblock.upgrade_block_to_block_type(BlockType::Full).await;
            }
        }
    }

    pub async fn add_block_failure(&mut self) {}

    pub fn generate_fork_id(&self, block_id: u64) -> SaitoHash {
        let mut fork_id = [0; 32];
        let mut current_block_id = block_id;

        //
        // roll back to last even 10 blocks
        //
        for i in 0..10 {
            if (current_block_id - i) % 10 == 0 {
                current_block_id -= i;
                break;
            }
        }

        //
        // loop backwards through blockchain
        //
        for i in 0..16 {
            if i == 0 {
                current_block_id -= 0;
            }
            if i == 1 {
                current_block_id -= 10;
            }
            if i == 2 {
                current_block_id -= 10;
            }
            if i == 3 {
                current_block_id -= 10;
            }
            if i == 4 {
                current_block_id -= 10;
            }
            if i == 5 {
                current_block_id -= 10;
            }
            if i == 6 {
                current_block_id -= 25;
            }
            if i == 7 {
                current_block_id -= 25;
            }
            if i == 8 {
                current_block_id -= 100;
            }
            if i == 9 {
                current_block_id -= 300;
            }
            if i == 10 {
                current_block_id -= 500;
            }
            if i == 11 {
                current_block_id -= 4000;
            }
            if i == 12 {
                current_block_id -= 10000;
            }
            if i == 13 {
                current_block_id -= 20000;
            }
            if i == 14 {
                current_block_id -= 50000;
            }
            if i == 15 {
                current_block_id -= 100000;
            }

            //
            // do not loop around if block id < 0
            //
            if current_block_id > block_id || current_block_id == 0 {
                break;
            }

            //
            // index to update
            //
            let idx = 2 * i;

            //
            //
            //
            let block_hash = self
                .blockring
                .get_longest_chain_block_hash_by_block_id(current_block_id);
            fork_id[idx] = block_hash[idx];
            fork_id[idx + 1] = block_hash[idx + 1];
        }

        fork_id
    }

    pub fn generate_last_shared_ancestor(
        &self,
        peer_latest_block_id: u64,
        fork_id: SaitoHash,
    ) -> u64 {
        let my_latest_block_id = self.get_latest_block_id();

        let mut pbid = peer_latest_block_id;
        let mut mbid = my_latest_block_id;

        if peer_latest_block_id >= my_latest_block_id {
            //
            // roll back to last even 10 blocks
            //
            for i in 0..10 {
                if (pbid - i) % 10 == 0 {
                    pbid -= i;
                    break;
                }
            }

            //
            // their fork id
            //
            for i in 0..16 {
                if i == 0 {
                    pbid -= 0;
                }
                if i == 1 {
                    pbid -= 10;
                }
                if i == 2 {
                    pbid -= 10;
                }
                if i == 3 {
                    pbid -= 10;
                }
                if i == 4 {
                    pbid -= 10;
                }
                if i == 5 {
                    pbid -= 10;
                }
                if i == 6 {
                    pbid -= 25;
                }
                if i == 7 {
                    pbid -= 25;
                }
                if i == 8 {
                    pbid -= 100;
                }
                if i == 9 {
                    pbid -= 300;
                }
                if i == 10 {
                    pbid -= 500;
                }
                if i == 11 {
                    pbid -= 4000;
                }
                if i == 12 {
                    pbid -= 10000;
                }
                if i == 13 {
                    pbid -= 20000;
                }
                if i == 14 {
                    pbid -= 50000;
                }
                if i == 15 {
                    pbid -= 100000;
                }

                //
                // do not loop around if block id < 0
                //
                if pbid > peer_latest_block_id || pbid == 0 {
                    return 0;
                }

                //
                // index in fork_id hash
                //
                let idx = 2 * i;

                //
                // compare input hash to my hash
                //
                if pbid <= mbid {
                    let block_hash = self
                        .blockring
                        .get_longest_chain_block_hash_by_block_id(pbid);
                    if fork_id[idx] == block_hash[idx] && fork_id[idx + 1] == block_hash[idx + 1] {
                        return pbid;
                    }
                }
            }
        } else {
            //
            // their fork id
            //
            for i in 0..16 {
                if i == 0 {
                    mbid -= 0;
                }
                if i == 1 {
                    mbid -= 10;
                }
                if i == 2 {
                    mbid -= 10;
                }
                if i == 3 {
                    mbid -= 10;
                }
                if i == 4 {
                    mbid -= 10;
                }
                if i == 5 {
                    mbid -= 10;
                }
                if i == 6 {
                    mbid -= 25;
                }
                if i == 7 {
                    mbid -= 25;
                }
                if i == 8 {
                    mbid -= 100;
                }
                if i == 9 {
                    mbid -= 300;
                }
                if i == 10 {
                    mbid -= 500;
                }
                if i == 11 {
                    mbid -= 4000;
                }
                if i == 12 {
                    mbid -= 10000;
                }
                if i == 13 {
                    mbid -= 20000;
                }
                if i == 14 {
                    mbid -= 50000;
                }
                if i == 15 {
                    mbid -= 100000;
                }

                //
                // do not loop around if block id < 0
                //
                if mbid > my_latest_block_id || mbid == 0 {
                    return 0;
                }

                //
                // index in fork_id hash
                //
                let idx = 2 * i;

                //
                // compare input hash to my hash
                //
                if pbid <= mbid {
                    let block_hash = self
                        .blockring
                        .get_longest_chain_block_hash_by_block_id(pbid);
                    if fork_id[idx] == block_hash[idx] && fork_id[idx + 1] == block_hash[idx + 1] {
                        return pbid;
                    }
                }
            }
        }

        //
        // no match? return 0 -- no shared ancestor
        //
        0
    }
    pub fn print(&self) {
        let latest_block_id = self.get_latest_block_id();
        let mut current_id = latest_block_id;

        while current_id > 0 {
            info!(
                "{} - {:?}",
                current_id,
                self.blockring
                    .get_longest_chain_block_hash_by_block_id(current_id)
            );
            current_id -= 1;
        }
    }

    pub fn get_latest_block(&self) -> Option<&Block> {
        let block_hash = self.blockring.get_latest_block_hash();
        self.blocks.get(&block_hash)
    }

    pub fn get_latest_block_hash(&self) -> SaitoHash {
        self.blockring.get_latest_block_hash()
    }

    pub fn get_latest_block_id(&self) -> u64 {
        self.blockring.get_latest_block_id()
    }

    pub fn get_block_sync(&self, block_hash: &SaitoHash) -> Option<&Block> {
        self.blocks.get(block_hash)
    }
    pub async fn get_block(&self, block_hash: &SaitoHash) -> Option<&Block> {
        self.blocks.get(block_hash)
    }

    pub async fn get_mut_block(&mut self, block_hash: &SaitoHash) -> &mut Block {
        let block = self.blocks.get_mut(block_hash).unwrap();
        block
    }

    pub fn is_block_indexed(&self, block_hash: SaitoHash) -> bool {
        if self.blocks.contains_key(&block_hash) {
            return true;
        }
        false
    }

    pub fn contains_block_hash_at_block_id(&self, block_id: u64, block_hash: SaitoHash) -> bool {
        self.blockring
            .contains_block_hash_at_block_id(block_id, block_hash)
    }

    pub fn is_new_chain_the_longest_chain(
        &mut self,
        new_chain: &Vec<[u8; 32]>,
        old_chain: &Vec<[u8; 32]>,
    ) -> bool {
        if old_chain.len() > new_chain.len() {
            warn!("WARN: old chain length is greater than new chain length");
            return false;
        }

        if self.blockring.get_latest_block_id() >= self.blocks.get(&new_chain[0]).unwrap().get_id()
        {
            return false;
        }

        let mut old_bf: u64 = 0;
        let mut new_bf: u64 = 0;

        for hash in old_chain.iter() {
            old_bf += self.blocks.get(hash).unwrap().get_burnfee();
        }
        for hash in new_chain.iter() {
            new_bf += self.blocks.get(hash).unwrap().get_burnfee();
        }
        //
        // new chain must have more accumulated work AND be longer
        //
        old_chain.len() < new_chain.len() && old_bf <= new_bf
    }

    //
    // when new_chain and old_chain are generated the block_hashes are added
    // to their vectors from tip-to-shared-ancestors. if the shared ancestors
    // is at position [0] in our blockchain for instance, we may receive:
    //
    // new_chain --> adds the hashes in this order
    //   [5] [4] [3] [2] [1]
    //
    // old_chain --> adds the hashes in this order
    //   [4] [3] [2] [1]
    //
    // unwinding requires starting from the BEGINNING of the vector, while
    // winding requires starting from th END of the vector. the loops move
    // in opposite directions.
    //
    pub async fn validate(&mut self, new_chain: Vec<[u8; 32]>, old_chain: Vec<[u8; 32]>) -> bool {
        //
        // ensure new chain has adequate mining support to be considered as
        // a viable chain. we handle this check here as opposed to handling
        // it in wind_chain as we only need to check once for the entire chain
        //
        let mut golden_tickets_found = 0;
        let mut search_depth_idx = 0;
        let mut latest_block_hash = new_chain[0];

        for i in 0..MIN_GOLDEN_TICKETS_DENOMINATOR {
            search_depth_idx += 1;

            if let Some(block) = self.get_block_sync(&latest_block_hash) {
                if i == 0 {
                    if block.get_id() < MIN_GOLDEN_TICKETS_DENOMINATOR {
                        break;
                    }
                }

                // the latest block will not have has_golden_ticket set yet
                // so it is possible we undercount the latest block. this
                // is dealt with by manually checking for the existence of
                // a golden ticket if we only have 1 golden ticket below.
                if block.get_has_golden_ticket() {
                    golden_tickets_found += 1;
                }
                latest_block_hash = block.get_previous_block_hash();
            } else {
                break;
            }
        }

        if golden_tickets_found < MIN_GOLDEN_TICKETS_NUMERATOR
            && search_depth_idx >= MIN_GOLDEN_TICKETS_DENOMINATOR
        {
            let mut return_value = false;
            if let Some(block) = self.get_block_sync(&new_chain[0]) {
                for transaction in block.get_transactions() {
                    if transaction.get_transaction_type() == TransactionType::GoldenTicket {
                        return_value = true;
                        break;
                    }
                }
            }
            if !return_value {
                return false;
            }
        }

        if !old_chain.is_empty() {
            let res = self
                .unwind_chain(&new_chain, &old_chain, 0, true)
                //.unwind_chain(&new_chain, &old_chain, old_chain.len() - 1, true)
                .await;
            res
        } else if !new_chain.is_empty() {
            let res = self
                .wind_chain(&new_chain, &old_chain, new_chain.len() - 1, false)
                .await;
            res
        } else {
            true
        }
    }

    //
    // when new_chain and old_chain are generated the block_hashes are added
    // to their vectors from tip-to-shared-ancestors. if the shared ancestors
    // is at position [0] for instance, we may receive:
    //
    // new_chain --> adds the hashes in this order
    //   [5] [4] [3] [2] [1]
    //
    // old_chain --> adds the hashes in this order
    //   [4] [3] [2] [1]
    //
    // unwinding requires starting from the BEGINNING of the vector, while
    // winding requires starting from the END of the vector. the loops move
    // in opposite directions. the argument current_wind_index is the
    // position in the vector NOT the ordinal number of the block_hash
    // being processed. we start winding with current_wind_index 4 not 0.
    //
    #[async_recursion]
    pub async fn wind_chain(
        &mut self,
        new_chain: &Vec<[u8; 32]>,
        old_chain: &Vec<[u8; 32]>,
        current_wind_index: usize,
        wind_failure: bool,
    ) -> bool {
        trace!(" ... blockchain.wind_chain strt: {:?}", create_timestamp());

        //
        // if we are winding a non-existent chain with a wind_failure it
        // means our wind attempt failed and we should move directly into
        // add_block_failure() by returning false.
        //
        if wind_failure && new_chain.is_empty() {
            return false;
        }

        //
        // winding the chain requires us to have certain data associated
        // with the block and the transactions, particularly the tx hashes
        // that we need to generate the slip UUIDs and create the tx sigs.
        //
        // we fetch the block mutably first in order to update these vars.
        // we cannot just send the block mutably into our regular validate()
        // function because of limitatins imposed by Rust on mutable data
        // structures. So validation is "read-only" and our "write" actions
        // happen first.
        //
        {
            let mut block = self.get_mut_block(&new_chain[current_wind_index]).await;
            block.generate_metadata();

            let latest_block_id = block.get_id();

            //
            // ensure previous blocks that may be needed to calculate the staking
            // tables or the nolan that are potentially falling off the chain have
            // full access to their transaction data.
            //
            for i in 1..MAX_STAKER_RECURSION {
                if i >= latest_block_id {
                    break;
                }
                let bid = latest_block_id - i;
                let previous_block_hash =
                    self.blockring.get_longest_chain_block_hash_by_block_id(bid);
                if self.is_block_indexed(previous_block_hash) {
                    block = self.get_mut_block(&previous_block_hash).await;
                    block.upgrade_block_to_block_type(BlockType::Full).await;
                }
            }
        }

        let block = self.blocks.get(&new_chain[current_wind_index]).unwrap();
        trace!(" ... before block.validate:      {:?}", create_timestamp());
        let does_block_validate = block.validate(&self, &self.utxoset, &self.staking).await;

        trace!(
            " ... after block.validate:       {:?} {}",
            create_timestamp(),
            does_block_validate
        );

        if does_block_validate {
            trace!(" ... before block ocr            {:?}", create_timestamp());

            // utxoset update
            block.on_chain_reorganization(&mut self.utxoset, true);

            trace!(" ... before blockring ocr:       {:?}", create_timestamp());

            // blockring update
            self.blockring
                .on_chain_reorganization(block.get_id(), block.get_hash(), true);

            // staking tables update
            let (res_spend, res_unspend, res_delete) =
                self.staking.on_chain_reorganization(block, true);

            //
            // TODO - wallet update should be optional, as core routing nodes
            // will not want to do the work of scrolling through the block and
            // updating their wallets by default. wallet processing can be
            // more efficiently handled by lite-nodes.
            //
            {
                trace!(" ... wallet processing start:    {}", create_timestamp());
                let mut wallet = self.wallet_lock.write().await;
                wallet.on_chain_reorganization(&block, true);
                trace!(" ... wallet processing stop:     {}", create_timestamp());
            }

            let block_id = block.get_id();
            self.on_chain_reorganization(block_id, true).await;

            //
            // we cannot pass the UTXOSet into the staking object to update as that would
            // require multiple mutable borrows of the blockchain object, so we receive
            // return vectors of the slips that need to be inserted, spent or deleted and
            // handle this after-the-fact. this keeps the UTXOSet up-to-date with whatever
            // is in the staking tables.
            //
            for i in 0..res_spend.len() {
                res_spend[i].on_chain_reorganization(&mut self.utxoset, true, 1);
            }
            for i in 0..res_unspend.len() {
                res_spend[i].on_chain_reorganization(&mut self.utxoset, true, 0);
            }
            for i in 0..res_delete.len() {
                res_spend[i].delete(&mut self.utxoset);
            }

            //
            // we have received the first entry in new_blocks() which means we
            // have added the latest tip. if the variable wind_failure is set
            // that indicates that we ran into an issue when winding the new_chain
            // and what we have just processed is the old_chain (being rewound)
            // so we should exit with failure.
            //
            // otherwise we have successfully wound the new chain, and exit with
            // success.
            //
            if current_wind_index == 0 {
                if wind_failure {
                    return false;
                }
                return true;
            }

            let res = self
                .wind_chain(new_chain, old_chain, current_wind_index - 1, false)
                .await;
            res
        } else {
            //
            // we have had an error while winding the chain. this requires us to
            // unwind any blocks we have already wound, and rewind any blocks we
            // have unwound.
            //
            // we set wind_failure to "true" so that when we reach the end of
            // the process of rewinding the old-chain, our wind_chain function
            // will know it has rewound the old chain successfully instead of
            // successfully added the new chain.
            //
            error!("ERROR: this block does not validate!");
            if current_wind_index == new_chain.len() - 1 {
                //
                // this is the first block we have tried to add
                // and so we can just roll out the older chain
                // again as it is known good.
                //
                // note that old and new hashes are swapped
                // and the old chain is set as null because
                // we won't move back to it. we also set the
                // resetting_flag to 1 so we know to fork
                // into addBlockToBlockchainFailure
                //
                // true -> force -> we had issues, is failure
                //
                // new_chain --> hashes are still in this order
                //   [5] [4] [3] [2] [1]
                //
                // we are at the beginning of our own vector so we have nothing
                // to unwind. Because of this, we start WINDING the old chain back
                // which requires us to start at the END of the new chain vector.
                //
                if old_chain.len() > 0 {
                    info!("old chain len: {}", old_chain.len());
                    let res = self
                        .wind_chain(old_chain, new_chain, old_chain.len() - 1, true)
                        .await;
                    res
                } else {
                    false
                }
            } else {
                let mut chain_to_unwind: Vec<[u8; 32]> = vec![];

                //
                // if we run into a problem winding our chain after we have
                // wound any blocks, we take the subset of the blocks we have
                // already pushed through on_chain_reorganization (i.e. not
                // including this block!) and put them onto a new vector we
                // will unwind in turn.
                //
                for i in current_wind_index + 1..new_chain.len() {
                    chain_to_unwind.push(new_chain[i].clone());
                }

                //
                // chain to unwind is now something like this...
                //
                //  [3] [2] [1]
                //
                // unwinding starts from the BEGINNING of the vector
                //
                let res = self
                    .unwind_chain(old_chain, &chain_to_unwind, 0, true)
                    .await;
                res
            }
        }
    }

    //
    // when new_chain and old_chain are generated the block_hashes are pushed
    // to their vectors from tip-to-shared-ancestors. if the shared ancestors
    // is at position [0] for instance, we may receive:
    //
    // new_chain --> adds the hashes in this order
    //   [5] [4] [3] [2] [1]
    //
    // old_chain --> adds the hashes in this order
    //   [4] [3] [2] [1]
    //
    // unwinding requires starting from the BEGINNING of the vector, while
    // winding requires starting from the END of the vector. the first
    // block we have to remove in the old_chain is thus at position 0, and
    // walking up the vector from there until we reach the end.
    //
    #[async_recursion]
    pub async fn unwind_chain(
        &mut self,
        new_chain: &Vec<[u8; 32]>,
        old_chain: &Vec<[u8; 32]>,
        current_unwind_index: usize,
        wind_failure: bool,
    ) -> bool {
        let block = &self.blocks[&old_chain[current_unwind_index]];

        // utxoset update
        block.on_chain_reorganization(&mut self.utxoset, false);

        // blockring update
        self.blockring
            .on_chain_reorganization(block.get_id(), block.get_hash(), false);

        // staking tables
        let (res_spend, res_unspend, res_delete) =
            self.staking.on_chain_reorganization(block, false);

        // wallet update
        {
            let mut wallet = self.wallet_lock.write().await;
            wallet.on_chain_reorganization(&block, false);
        }

        //
        // we cannot pass the UTXOSet into the staking object to update as that would
        // require multiple mutable borrows of the blockchain object, so we receive
        // return vectors of the slips that need to be inserted, spent or deleted and
        // handle this after-the-fact. this keeps the UTXOSet up-to-date with whatever
        // is in the staking tables.
        //
        for i in 0..res_spend.len() {
            res_spend[i].on_chain_reorganization(&mut self.utxoset, true, 1);
        }
        for i in 0..res_unspend.len() {
            res_spend[i].on_chain_reorganization(&mut self.utxoset, true, 0);
        }
        for i in 0..res_delete.len() {
            res_spend[i].delete(&mut self.utxoset);
        }

        if current_unwind_index == old_chain.len() - 1 {
            //
            // start winding new chain
            //
            // new_chain --> adds the hashes in this order
            //   [5] [4] [3] [2] [1]
            //
            // old_chain --> adds the hashes in this order
            //   [4] [3] [2] [1]
            //
            // winding requires starting at the END of the vector and rolling
            // backwards until we have added block #5, etc.
            //
            let res = self
                .wind_chain(new_chain, old_chain, new_chain.len() - 1, wind_failure)
                .await;
            res
        } else {
            //
            // continue unwinding,, which means
            //
            // unwinding requires moving FORWARD in our vector (and backwards in
            // the blockchain). So we increment our unwind index.
            //
            let res = self
                .unwind_chain(new_chain, old_chain, current_unwind_index + 1, wind_failure)
                .await;
            res
        }
    }

    /// keeps any blockchain variables like fork_id or genesis_period
    /// tracking variables updated as the chain gets new blocks. also
    /// pre-loads any blocks needed to improve performance.
    async fn on_chain_reorganization(&mut self, block_id: u64, longest_chain: bool) {
        //
        // skip out if earlier than we need to be vis-a-vis last_block_id
        //
        if self.get_latest_block_id() >= block_id {
            return;
        }

        if longest_chain {
            //
            // update genesis period, purge old data
            //
            self.update_genesis_period().await;

            //
            // generate fork_id
            //
            let fork_id = self.generate_fork_id(block_id);
            self.set_fork_id(fork_id);
        }

        self.downgrade_blockchain_data().await;
    }

    pub async fn update_genesis_period(&mut self) {
        //
        // we need to make sure this is not a random block that is disconnected
        // from our previous genesis_id. If there is no connection between it
        // and us, then we cannot delete anything as otherwise the provision of
        // the block may be an attack on us intended to force us to discard
        // actually useful data.
        //
        // so we check that our block is the head of the longest-chain and only
        // update the genesis period when that is the case.
        //
        let latest_block_id = self.get_latest_block_id();
        if latest_block_id >= ((GENESIS_PERIOD * 2) + 1) {
            //
            // prune blocks
            //
            let purge_bid = latest_block_id - (GENESIS_PERIOD * 2);
            self.genesis_block_id = latest_block_id - GENESIS_PERIOD;

            //
            // in either case, we are OK to throw out everything below the
            // lowest_block_id that we have found. we use the purge_id to
            // handle purges.
            //
            self.delete_blocks(purge_bid).await;
        }

        //TODO: we already had in update_genesis_period() in self method - maybe no need to call here?
        // self.downgrade_blockchain_data().await;
    }

    //
    // deletes all blocks at a single block_id
    //
    pub async fn delete_blocks(&mut self, delete_block_id: u64) {
        trace!(
            "removing data including from disk at id {}",
            delete_block_id
        );

        let mut block_hashes_copy: Vec<SaitoHash> = vec![];

        {
            let block_hashes = self.blockring.get_block_hashes_at_block_id(delete_block_id);
            for hash in block_hashes {
                block_hashes_copy.push(hash.clone());
            }
        }

        trace!("number of hashes to remove {}", block_hashes_copy.len());

        for hash in block_hashes_copy {
            self.delete_block(delete_block_id, hash).await;
        }
    }

    //
    // deletes a single block
    //
    pub async fn delete_block(&mut self, delete_block_id: u64, delete_block_hash: SaitoHash) {
        //
        // ask block to delete itself / utxo-wise
        //
        {
            let pblock = self.blocks.get(&delete_block_hash).unwrap();
            let pblock_filename = Storage::generate_block_filename(pblock);

            //
            // remove slips from wallet
            //
            let mut wallet = self.wallet_lock.write().await;
            wallet.delete_block(pblock);

            //
            // removes utxoset data
            //
            pblock.delete(&mut self.utxoset).await;

            //
            // deletes block from disk
            //
            Storage::delete_block_from_disk(pblock_filename).await;
        }

        //
        // ask blockring to remove
        //
        self.blockring
            .delete_block(delete_block_id, delete_block_hash);

        //
        // remove from block index
        //
        if self.blocks.contains_key(&delete_block_hash) {
            self.blocks.remove_entry(&delete_block_hash);
        }
    }

    pub async fn downgrade_blockchain_data(&mut self) {
        //
        // downgrade blocks still on the chain
        //
        if PRUNE_AFTER_BLOCKS > self.get_latest_block_id() {
            return;
        }
        let prune_blocks_at_block_id = self.get_latest_block_id() - PRUNE_AFTER_BLOCKS;

        let mut block_hashes_copy: Vec<SaitoHash> = vec![];

        {
            let block_hashes = self
                .blockring
                .get_block_hashes_at_block_id(prune_blocks_at_block_id);
            for hash in block_hashes {
                block_hashes_copy.push(hash.clone());
            }
        }

        for hash in block_hashes_copy {
            //
            // ask the block to remove its transactions
            //
            {
                let pblock = self.get_mut_block(&hash).await;
                pblock
                    .downgrade_block_to_block_type(BlockType::Pruned)
                    .await;
            }
        }
    }
}

// This function is called on initialization to setup the sending
// and receiving channels for asynchronous loops or message checks
pub async fn run(
    blockchain_lock: Arc<RwLock<Blockchain>>,
    broadcast_channel_sender: broadcast::Sender<SaitoMessage>,
    mut broadcast_channel_receiver: broadcast::Receiver<SaitoMessage>,
) -> crate::Result<()> {
    let (_blockchain_channel_sender, mut blockchain_channel_receiver): (
        tokio::sync::mpsc::Sender<SaitoMessage>,
        tokio::sync::mpsc::Receiver<SaitoMessage>,
    ) = mpsc::channel(4);

    //
    // blockchain takes global broadcast channel
    //
    {
        let mut blockchain = blockchain_lock.write().await;
        blockchain.set_broadcast_channel_sender(broadcast_channel_sender.clone());
    }

    //
    // receive broadcast messages
    //
    loop {
        tokio::select! {

        //
        // local broadcast messages
        //
            Some(message) = blockchain_channel_receiver.recv() => {
                match message {
                    _ => {},
                }
            }

        //
        // global broadcast messages
        //
            Ok(message) = broadcast_channel_receiver.recv() => {
                match message {
                    SaitoMessage::BlockchainSavedBlock { hash: _hash } => {
                        println!("Blockchain aware network has received new block! -- we might use for this congestion tracking");
                    },
                    _ => {},
                }
            }
        }
    }
}

#[cfg(test)]

mod tests {
    use super::*;
    use crate::test_utilities::test_manager::TestManager;

    #[test]
    //
    // code that packs/unpacks two 32-bit values into one 64-bit variable
    //
    fn bit_pack_test() {
        let top = 157171715;
        let bottom = 11661612;
        let packed = bit_pack(top, bottom);
        assert_eq!(packed, 157171715 * (u64::pow(2, 32)) + 11661612);
        let (new_top, new_bottom) = bit_unpack(packed);
        assert_eq!(top, new_top);
        assert_eq!(bottom, new_bottom);

        let top = u32::MAX;
        let bottom = u32::MAX;
        let packed = bit_pack(top, bottom);
        let (new_top, new_bottom) = bit_unpack(packed);
        assert_eq!(top, new_top);
        assert_eq!(bottom, new_bottom);

        let top = 0;
        let bottom = 1;
        let packed = bit_pack(top, bottom);
        let (new_top, new_bottom) = bit_unpack(packed);
        assert_eq!(top, new_top);
        assert_eq!(bottom, new_bottom);
    }

    #[tokio::test]
    #[serial_test::serial]
    //
    // test we can produce five blocks in a row
    //
    async fn add_five_good_blocks() {
        let wallet_lock = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock = Arc::new(RwLock::new(Blockchain::new(wallet_lock.clone())));
        let mut test_manager = TestManager::new(blockchain_lock.clone(), wallet_lock.clone());

        let current_timestamp = create_timestamp();

        // BLOCK 1
        test_manager
            .add_block(current_timestamp, 3, 0, false, vec![])
            .await;

        // BLOCK 2
        test_manager
            .add_block(current_timestamp + 120000, 0, 1, false, vec![])
            .await;

        // BLOCK 3
        test_manager
            .add_block(current_timestamp + 240000, 0, 1, false, vec![])
            .await;

        // BLOCK 4
        test_manager
            .add_block(current_timestamp + 360000, 0, 1, false, vec![])
            .await;

        // BLOCK 5
        test_manager
            .add_block(current_timestamp + 480000, 0, 1, false, vec![])
            .await;

        let blockchain = blockchain_lock.read().await;

        assert_eq!(5, blockchain.get_latest_block_id());

        test_manager.check_utxoset().await;
        test_manager.check_token_supply().await;
    }

    #[tokio::test]
    #[serial_test::serial]
    //
    // test we do not add blocks 6 and 7 because of insuffient mining
    //
    async fn add_seven_good_blocks_but_no_golden_tickets() {
        let wallet_lock = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock = Arc::new(RwLock::new(Blockchain::new(wallet_lock.clone())));
        let mut test_manager = TestManager::new(blockchain_lock.clone(), wallet_lock.clone());

        let current_timestamp = create_timestamp();

        // BLOCK 1
        test_manager
            .add_block(current_timestamp, 3, 0, false, vec![])
            .await;

        // BLOCK 2
        test_manager
            .add_block(current_timestamp + 120000, 0, 1, false, vec![])
            .await;

        // BLOCK 3
        test_manager
            .add_block(current_timestamp + 240000, 0, 1, false, vec![])
            .await;

        // BLOCK 4
        test_manager
            .add_block(current_timestamp + 360000, 0, 1, false, vec![])
            .await;

        // BLOCK 5
        test_manager
            .add_block(current_timestamp + 480000, 0, 1, false, vec![])
            .await;

        // BLOCK 6
        test_manager
            .add_block(current_timestamp + 600000, 0, 1, false, vec![])
            .await;

        // BLOCK 7
        test_manager
            .add_block(current_timestamp + 720000, 0, 1, false, vec![])
            .await;

        let blockchain = blockchain_lock.read().await;

        assert_eq!(5, blockchain.get_latest_block_id());
        assert_ne!(7, blockchain.get_latest_block_id());

        test_manager.check_utxoset().await;
        test_manager.check_token_supply().await;
    }

    #[tokio::test]
    #[serial_test::serial]
    //
    // test we add blocks 6 and 7 because of suffient mining
    //
    async fn add_seven_good_blocks_and_two_golden_tickets() {
        let wallet_lock = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock = Arc::new(RwLock::new(Blockchain::new(wallet_lock.clone())));
        let mut test_manager = TestManager::new(blockchain_lock.clone(), wallet_lock.clone());

        let current_timestamp = create_timestamp();

        // BLOCK 1
        test_manager
            .add_block(current_timestamp, 3, 0, false, vec![])
            .await;

        // BLOCK 2
        test_manager
            .add_block(current_timestamp + 120000, 0, 1, false, vec![])
            .await;

        // BLOCK 3
        test_manager
            .add_block(current_timestamp + 240000, 0, 1, true, vec![])
            .await;

        // BLOCK 4
        test_manager
            .add_block(current_timestamp + 360000, 0, 1, false, vec![])
            .await;

        // BLOCK 5
        test_manager
            .add_block(current_timestamp + 480000, 0, 1, false, vec![])
            .await;

        // BLOCK 6
        test_manager
            .add_block(current_timestamp + 600000, 0, 1, true, vec![])
            .await;

        // BLOCK 7
        test_manager
            .add_block(current_timestamp + 720000, 0, 1, false, vec![])
            .await;

        let blockchain = blockchain_lock.read().await;

        assert_eq!(7, blockchain.get_latest_block_id());
        assert_ne!(5, blockchain.get_latest_block_id());

        test_manager.check_utxoset().await;
        test_manager.check_token_supply().await;
    }

    #[tokio::test]
    #[serial_test::serial]
    //
    // add 10 blocks including chain reorganization and sufficient mining
    //
    async fn add_ten_blocks_including_five_block_chain_reorg() {
        let wallet_lock = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock = Arc::new(RwLock::new(Blockchain::new(wallet_lock.clone())));
        let mut test_manager = TestManager::new(blockchain_lock.clone(), wallet_lock.clone());

        let current_timestamp = create_timestamp();
        let block5_hash;
        let block9_hash;

        // BLOCK 1
        test_manager
            .add_block(current_timestamp, 3, 0, false, vec![])
            .await;

        // BLOCK 2
        test_manager
            .add_block(current_timestamp + 120000, 0, 1, false, vec![])
            .await;

        // BLOCK 3
        test_manager
            .add_block(current_timestamp + 240000, 0, 1, true, vec![])
            .await;

        // BLOCK 4
        test_manager
            .add_block(current_timestamp + 360000, 0, 1, false, vec![])
            .await;

        // BLOCK 5
        // note - we set GT to true so that the staking payout won't regress
        // since the test_manager produces from known state of wallet rather
        // that the state at block 5.
        test_manager
            .add_block(current_timestamp + 480000, 0, 1, true, vec![])
            .await;

        {
            // check that block 5 is indeed the latest block
            let blockchain = blockchain_lock.read().await;
            assert_eq!(5, blockchain.get_latest_block_id());
            block5_hash = blockchain.get_latest_block_hash();
        }

        //
        // produce the next four blocks, which we will reorg eventually
        //

        // BLOCK 6
        test_manager
            .add_block(current_timestamp + 600000, 0, 1, true, vec![])
            .await;

        // BLOCK 7
        test_manager
            .add_block(current_timestamp + 720000, 0, 1, false, vec![])
            .await;

        // BLOCK 8
        test_manager
            .add_block(current_timestamp + 840000, 0, 1, true, vec![])
            .await;

        // BLOCK 9
        test_manager
            .add_block(current_timestamp + 960000, 0, 1, false, vec![])
            .await;

        {
            let blockchain = blockchain_lock.read().await;
            // check that block 9 is indeed the latest block
            assert_eq!(9, blockchain.get_latest_block_id());
            block9_hash = blockchain.get_latest_block_hash();
        }

        //
        // start a separate fork that reorgs from block 5
        //
        // note that we have to run generate_metadata, as we cannot
        // calculate some dynamic variables like the appropriate
        // difficulty without being able to check if the previous
        // block has golden tickets, etc. which is calculated in
        // generate_metadata(). this is not a problem in production
        // as blocks are built off the longest-chain.
        //

        // BLOCK 6-2
        let block6_2 = test_manager
            .generate_block_and_metadata(
                block5_hash,
                current_timestamp + 600000,
                0,
                0,
                true,
                vec![],
            )
            .await;
        let block6_2_hash = block6_2.get_hash();
        Blockchain::add_block_to_blockchain(blockchain_lock.clone(), block6_2).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(9, blockchain.get_latest_block_id());
            assert_eq!(block9_hash, blockchain.get_latest_block_hash());
        }

        // BLOCK 7-2
        let block7_2 = test_manager
            .generate_block_and_metadata(
                block6_2_hash,
                current_timestamp + 720000,
                0,
                0,
                true,
                vec![],
            )
            .await;
        let block7_2_hash = block7_2.get_hash();
        Blockchain::add_block_to_blockchain(blockchain_lock.clone(), block7_2).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(9, blockchain.get_latest_block_id());
            assert_eq!(block9_hash, blockchain.get_latest_block_hash());
        }

        // BLOCK 8-2
        let block8_2 = test_manager
            .generate_block_and_metadata(
                block7_2_hash,
                current_timestamp + 840000,
                0,
                0,
                true,
                vec![],
            )
            .await;
        let block8_2_hash = block8_2.get_hash();
        Blockchain::add_block_to_blockchain(blockchain_lock.clone(), block8_2).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(9, blockchain.get_latest_block_id());
            assert_eq!(block9_hash, blockchain.get_latest_block_hash());
        }

        // BLOCK 9-2
        let block9_2 = test_manager
            .generate_block_and_metadata(
                block8_2_hash,
                current_timestamp + 960000,
                0,
                0,
                true,
                vec![],
            )
            .await;
        let block9_2_hash = block9_2.get_hash();
        Blockchain::add_block_to_blockchain(blockchain_lock.clone(), block9_2).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(9, blockchain.get_latest_block_id());
            assert_eq!(block9_hash, blockchain.get_latest_block_hash());
        }

        // BLOCK 10-2
        let block10_2 = test_manager
            .generate_block_and_metadata(
                block9_2_hash,
                current_timestamp + 1080000,
                0,
                0,
                true,
                vec![],
            )
            .await;
        let block10_2_hash = block10_2.get_hash();
        Blockchain::add_block_to_blockchain(blockchain_lock.clone(), block10_2).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(10, blockchain.get_latest_block_id());
            assert_eq!(block10_2_hash, blockchain.get_latest_block_hash());
        }

        test_manager.check_utxoset().await;
        test_manager.check_token_supply().await;
    }

    #[tokio::test]
    #[serial_test::serial]
    //
    // use test_manager to generate blockchains and reorgs and test
    //
    async fn test_manager_blockchain_fork_test() {
        let wallet_lock = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock = Arc::new(RwLock::new(Blockchain::new(wallet_lock.clone())));
        let mut test_manager = TestManager::new(blockchain_lock.clone(), wallet_lock.clone());

        // 5 initial blocks
        test_manager.generate_blockchain(5, [0; 32]).await;

        let block5_hash;

        {
            let blockchain = blockchain_lock.read().await;
            block5_hash = blockchain.get_latest_block_hash();

            assert_eq!(
                blockchain
                    .blockring
                    .get_longest_chain_block_hash_by_block_id(5),
                block5_hash
            );
            assert_eq!(blockchain.get_latest_block_hash(), block5_hash);
        }

        // 5 block reorg with 10 block fork
        let block10_hash = test_manager.generate_blockchain(5, block5_hash).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(
                blockchain
                    .blockring
                    .get_longest_chain_block_hash_by_block_id(10),
                block10_hash
            );
            assert_eq!(blockchain.get_latest_block_hash(), block10_hash);
        }

        let block15_hash = test_manager.generate_blockchain(10, block5_hash).await;

        {
            let blockchain = blockchain_lock.read().await;
            assert_eq!(
                blockchain
                    .blockring
                    .get_longest_chain_block_hash_by_block_id(15),
                block15_hash
            );
            assert_eq!(blockchain.get_latest_block_hash(), block15_hash);
        }
    }

    /// Loading blocks into a blockchain which was were created from another blockchain instance
    #[tokio::test]
    #[serial_test::serial]
    async fn load_blocks_from_another_blockchain_test() {
        let wallet_lock1 = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock1 = Arc::new(RwLock::new(Blockchain::new(wallet_lock1.clone())));
        let mut test_manager1 = TestManager::new(blockchain_lock1.clone(), wallet_lock1.clone());

        let current_timestamp = create_timestamp();

        let block1_hash = test_manager1
            .add_block(current_timestamp + 100000, 0, 10, false, vec![])
            .await;
        let block2_hash = test_manager1
            .add_block(current_timestamp + 200000, 0, 20, true, vec![])
            .await;

        let wallet_lock2 = Arc::new(RwLock::new(Wallet::new()));
        let blockchain_lock2 = Arc::new(RwLock::new(Blockchain::new(wallet_lock2.clone())));
        let _test_manager2 = TestManager::new(blockchain_lock2.clone(), wallet_lock2.clone());

        Storage::load_blocks_from_disk(blockchain_lock2.clone()).await;

        {
            let blockchain1 = blockchain_lock1.read().await;
            let blockchain2 = blockchain_lock2.read().await;

            let block1_chain1 = blockchain1.get_block(&block1_hash).await.unwrap();
            let block1_chain2 = blockchain2.get_block(&block1_hash).await.unwrap();

            let block2_chain1 = blockchain1.get_block(&block2_hash).await.unwrap();
            let block2_chain2 = blockchain2.get_block(&block2_hash).await.unwrap();

            for (block_new, block_old) in &[
                (block1_chain2, block1_chain1),
                (block2_chain2, block2_chain1),
            ] {
                assert_eq!(block_new.get_hash(), block_old.get_hash());
                assert_eq!(block_new.has_golden_ticket, block_old.has_golden_ticket);
                assert_eq!(
                    block_new.get_previous_block_hash(),
                    block_old.get_previous_block_hash()
                );
                assert_eq!(block_new.get_block_type(), block_old.get_block_type());
                assert_eq!(block_new.get_signature(), block_old.get_signature());
            }
        }
    }
}