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
// Core CBC Casper
// Copyright (C) 2018 - 2020  Coordination Technology Ltd.
// Authors: pZ4 <pz4@protonmail.ch>,
//          Lederstrumpf,
//          h4sh3d <h4sh3d@truelevel.io>
//          roflolilolmao <q@truelevel.ch>
//
// This file is part of Core CBC Casper.
//
// Core CBC Casper is free software: you can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// Core CBC Casper is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with the Core CBC
// Rust Library. If not, see <https://www.gnu.org/licenses/>.

use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::convert::From;
use std::iter::Iterator;
use std::sync::Arc;

use serde_derive::Serialize;

use crate::estimator::Estimator;
use crate::justification::{Justification, LatestMessages, LatestMessagesHonest};
use crate::message::Message;
use crate::util::hash::Hash;
use crate::util::id::Id;
use crate::util::weight::{WeightUnit, Zero};
use crate::validator;

/// This trait must be implemented on a data type that is to be held by a [`Block<D>`].
///
/// [`Block<D>`]: ./struct.Block.html
///
/// # Example
///
/// ```
/// use core_cbc_casper::blockchain::{Block, BlockData};
/// use core_cbc_casper::validator;
///
/// type ValidatorName = i32;
///
/// #[derive(Hash, Clone, PartialEq, Eq, Default, Debug, serde_derive::Serialize)]
/// struct StringBlockData {
///     data: String,
///     validator: ValidatorName,
/// }
///
/// impl BlockData for StringBlockData {
///     type ValidatorName = ValidatorName;
///
///     fn validator_name(&self) -> &Self::ValidatorName {
///         &self.validator
///     }
/// }
///
/// assert_eq!(
///     Block::new(
///         None,
///         StringBlockData { data: "Hello, World!".to_string(), validator: 0 },
///     ).data(),
///     StringBlockData { data: "Hello, World!".to_string(), validator: 0 },
/// );
/// ```
pub trait BlockData:
    std::hash::Hash + Clone + Eq + Send + Sync + Default + serde::Serialize
{
    /// The type of validators that can produce data of this type.
    type ValidatorName: validator::ValidatorName;

    /// The name of the validator that produced the block containing this data.
    fn validator_name(&self) -> &Self::ValidatorName;
}

#[derive(Clone, Eq, PartialEq, Debug, Hash, Serialize)]
struct ProtoBlock<D: BlockData> {
    prevblock: Option<Block<D>>,
    data: D,
}

impl<D: BlockData> ProtoBlock<D> {
    pub fn new(prevblock: Option<Block<D>>, data: D) -> ProtoBlock<D> {
        ProtoBlock { prevblock, data }
    }
}

/// Simplest structure of a block with a `prevblock` pointer for running Casper on a blockchain.
/// The data contained in these blocks must implement the [`BlockData`] trait.
///
/// This structure implements the [`Estimator`] trait and uses the GHOST algorithm defined in
/// the paper for the estimate function.
///
/// [`BlockData`]: ./trait.BlockData.html
/// [`Estimator`]: ../estimator/trait.Estimator.html
///
/// # Example
///
/// Using the [`ValidatorNameBlockData`] type message type for brevity's sake.
///
/// [`ValidatorNameBlockData`]: ../struct.ValidatorNameBlockData.html
///
/// ```
/// use core_cbc_casper::blockchain::Block;
/// use core_cbc_casper::justification::Justification;
/// use core_cbc_casper::message::Message;
/// use core_cbc_casper::ValidatorNameBlockData;
///
/// let message = Message::new(
///     0,
///     Justification::empty(),
///     Block::new(None, ValidatorNameBlockData::new(1)),
/// );
/// let block_1 = Block::from(&message);
/// let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(2));
/// assert!(block_1.is_member(&block_2));
/// assert!(Block::from(&message).is_member(&block_1));
/// assert!(Block::from(&message).is_member(&block_2));
/// assert!(!block_2.is_member(&block_1));
/// assert!(!block_2.is_member(&Block::from(&message)));
/// ```
#[derive(Clone, Eq)]
pub struct Block<D: BlockData>(Arc<ProtoBlock<D>>);

impl<D: BlockData> std::fmt::Debug for Block<D> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{:?} -> {:?}",
            self.id(),
            self.prevblock()
                .as_ref()
                .map(|previous_block| previous_block.id())
                .unwrap_or_default()
        )
    }
}

impl<D: BlockData> serde::Serialize for Block<D> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut message = serializer.serialize_struct("Block", 1)?;
        message.serialize_field("prevblock", &self.prevblock())?;
        message.serialize_field("data", &self.data())?;
        message.end()
    }
}

impl<D: BlockData> Id for Block<D> {
    type ID = Hash;
}

impl<D: BlockData> std::hash::Hash for Block<D> {
    fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
        self.0.hash(hasher);
    }
}

impl<D: BlockData> PartialEq for Block<D> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(self.arc(), other.arc()) || self.id() == other.id()
    }
}

impl<D: BlockData> From<ProtoBlock<D>> for Block<D> {
    fn from(protoblock: ProtoBlock<D>) -> Self {
        Block(Arc::new(protoblock))
    }
}

impl<D: BlockData> From<&Message<Block<D>>> for Block<D> {
    fn from(message: &Message<Block<D>>) -> Self {
        message.estimate().clone()
    }
}

#[derive(Debug)]
pub struct Error;

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        writeln!(f, "Failed to get prevblock using ghost")
    }
}

impl std::error::Error for Error {}

impl<D: BlockData> Estimator for Block<D> {
    type Error = Error;
    type ValidatorName = D::ValidatorName;

    fn estimate<U: WeightUnit>(
        latest_messages: &LatestMessagesHonest<Self>,
        validators_weights: &validator::Weights<D::ValidatorName, U>,
    ) -> Result<Self, Self::Error> {
        let prevblock = Block::optimized_ghost(latest_messages, validators_weights)?;
        Ok(Block::from(ProtoBlock::new(Some(prevblock), D::default())))
    }
}

type BlocksChildrenMap<D> = HashMap<Block<D>, HashSet<Block<D>>>;
type GenesisBlocks<D> = HashSet<Block<D>>;
type BlocksValidatorsMap<D> = HashMap<Block<D>, <D as BlockData>::ValidatorName>;

impl<D: BlockData> Block<D> {
    pub fn new(prevblock: Option<Block<D>>, data: D) -> Self {
        Block::from(ProtoBlock::new(prevblock, data))
    }

    fn arc(&self) -> &Arc<ProtoBlock<D>> {
        &self.0
    }

    /// Creates a new block from a prevblock message and an incomplete block.
    /// An incomplete_block is a block with a None prevblock (i.e., Estimator) AND is not a
    /// genesis_block
    pub fn from_prevblock_message(
        prevblock_message: Option<Message<Block<D>>>,
        incomplete_block: Block<D>,
    ) -> Self {
        let prevblock = prevblock_message.map(|message| Block::from(&message));
        Block::from(ProtoBlock {
            prevblock,
            ..((**incomplete_block.arc()).clone())
        })
    }

    /// Mathematical definition of blockchain membership.
    pub fn is_member(&self, other: &Self) -> bool {
        self == other
            || other
                .prevblock()
                .as_ref()
                .map(|prevblock| self.is_member(prevblock))
                .unwrap_or(false)
    }

    /// Direct implementation of the score function from the paper. Contrary to the paper's
    /// definition, score directly uses the latest honest messages rather than the latest honest
    /// estimates and a protocol state. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L568
    pub fn score<U: WeightUnit>(
        &self,
        latest_messages_honest: &LatestMessagesHonest<Self>,
        weights: &validator::Weights<D::ValidatorName, U>,
    ) -> U {
        latest_messages_honest
            .iter()
            .filter(|message| self.is_member(&message.estimate()))
            .fold(<U as Zero<U>>::ZERO, |acc, message| {
                match weights.weight(&message.sender()) {
                    Err(_) => acc,
                    Ok(weight) => acc + weight,
                }
            })
    }

    /// Direct implementation of the children function from the paper. Contrary to the paper's
    /// definition, we are directly parsing blocks to filter children out of rather than taking
    /// the estimates out of messages. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L578
    pub fn children<'z>(&self, protocol_state: &HashSet<&'z Self>) -> HashSet<&'z Self> {
        protocol_state
            .iter()
            .cloned()
            .filter(|block| block.prevblock() == Some(self.clone()))
            .collect()
    }

    /// Direct implementation of the argmax function from the paper. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L395
    fn argmax<'z, F, U>(items: HashSet<&'z Block<D>>, scoring_function: F) -> HashSet<&'z Block<D>>
    where
        F: std::ops::Fn(&Block<D>) -> U,
        U: WeightUnit + std::cmp::PartialOrd,
    {
        let mut iterator = items.iter();

        let item = iterator.next();
        if item == None {
            return HashSet::new();
        }

        let item = item.unwrap();

        let mut max_score = scoring_function(item);
        let mut max = HashSet::new();
        max.insert(*item);

        for item in iterator {
            let block_score = scoring_function(*item);

            match block_score.partial_cmp(&max_score) {
                Some(Ordering::Equal) => {
                    max.insert(*item);
                }
                Some(Ordering::Greater) => max.clear(),
                Some(Ordering::Less) | None => (),
            };

            if max.is_empty() {
                max.insert(*item);
                max_score = block_score;
            }
        }

        max
    }

    /// Direct implementation of the best children function from the paper. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L587
    pub fn best_children<'z, U: WeightUnit + std::cmp::PartialOrd>(
        &self,
        protocol_state: &HashSet<&'z Self>,
        latest_messages_honest: &LatestMessagesHonest<Self>,
        weights: &validator::Weights<D::ValidatorName, U>,
    ) -> HashSet<&'z Self> {
        let scoring_function = |block: &Self| block.score(latest_messages_honest, weights);
        Block::argmax(self.children(&protocol_state), &scoring_function)
    }

    /// This function reconstructs the blocks tree from `latest_messages_honest` and uses those to
    /// return the block with highest score according to the definition 4.30 of the paper. Contrary
    /// to the paper's definition, it does not return a set in case of a tie but uses the blocks
    /// hashes to tie break. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L596
    pub fn mathematical_ghost<U: WeightUnit + std::cmp::PartialOrd>(
        latest_messages_honest: &LatestMessagesHonest<Self>,
        weights: &validator::Weights<D::ValidatorName, U>,
    ) -> Result<Self, Error> {
        fn internal<'z, D, U, F>(
            blocks: HashSet<&'z Block<D>>,
            protocol_state: &HashSet<&'z Block<D>>,
            scoring_function: F,
        ) -> HashSet<&'z Block<D>>
        where
            D: BlockData,
            U: WeightUnit + std::cmp::PartialOrd,
            F: std::ops::Fn(&Block<D>) -> U + Copy,
        {
            let children: HashMap<&Block<D>, HashSet<&Block<D>>> = blocks
                .iter()
                .map(|block| (*block, block.children(&protocol_state)))
                .collect();

            let mut indirect_best_leaves = HashSet::new();
            let mut direct_child_leaves = HashSet::new();

            for block in blocks.iter() {
                if children.get(*block).unwrap().is_empty() {
                    direct_child_leaves.insert(*block);
                } else {
                    internal(
                        Block::argmax(
                            children.get(*block).unwrap().iter().cloned().collect(),
                            scoring_function,
                        ),
                        protocol_state,
                        scoring_function,
                    )
                    .into_iter()
                    .for_each(|block| {
                        indirect_best_leaves.insert(block);
                    });
                }
            }

            indirect_best_leaves
                .union(&direct_child_leaves)
                .cloned()
                .collect()
        }

        let scoring_function = |block: &Self| block.score(latest_messages_honest, weights);

        let protocol_state = Self::find_all_accessible_blocks(latest_messages_honest);
        let genesis_blocks = protocol_state
            .iter()
            .filter(|block| block.prev_block_as_ref().is_none())
            .collect();

        // Tie breaker uses the blocks hashes.
        internal(
            genesis_blocks,
            &protocol_state.iter().collect(),
            scoring_function,
        )
        .into_iter()
        .max_by(|left, right| right.id().cmp(&left.id()))
        .cloned()
        .ok_or(Error)
    }

    /// This function reconstructs the blocks tree from `latest_messages_honest` and uses those to
    /// return the block with highest score according to the definition 4.30 of the paper. Contrary
    /// to the paper's definition, it does not return a set in case of a tie but uses the blocks
    /// hashes to tie break. It is an optimized version of `mathematical_ghost`.
    pub fn optimized_ghost<U: WeightUnit + std::cmp::PartialOrd>(
        latest_messages_honest: &LatestMessagesHonest<Self>,
        weights: &validator::Weights<D::ValidatorName, U>,
    ) -> Result<Self, Error> {
        let protocol_state = Self::find_all_accessible_blocks(latest_messages_honest);
        let genesis_blocks: HashSet<&Block<D>> = protocol_state
            .iter()
            .filter(|block| block.prev_block_as_ref().is_none())
            .collect();

        // Generating a hashset for each block containing each latest honest message child of
        // that block. This will let us compute the scores of each block easily since the score is
        // the sum of the validators having a latest message child of that block.
        let mut latest_messages_validators = HashMap::new();
        for message in latest_messages_honest.iter() {
            let mut iterator = message.estimate().clone();
            while let Some(prev_block) = iterator.prevblock() {
                let entry = latest_messages_validators
                    .entry(iterator)
                    .or_insert_with(HashSet::new);
                entry.insert(message.sender().clone());

                iterator = prev_block;
            }
            let entry = latest_messages_validators
                .entry(iterator)
                .or_insert_with(HashSet::new);
            entry.insert(message.sender().clone());
        }

        let scores: HashMap<&Block<D>, U> = latest_messages_validators
            .iter()
            .map(|(block, validators)| {
                (
                    protocol_state.get(block).unwrap(),
                    weights.sum_weight_validators(&validators),
                )
            })
            .collect();

        let scoring_function = |block: &Self| *scores.get(&block).unwrap();

        let mut stack = vec![genesis_blocks.into_iter().next().unwrap()];
        let mut result = HashSet::new();

        // This while loop is an iterative ghost.
        while let Some(block) = stack.pop() {
            let children = block.children(&protocol_state.iter().collect());

            if children.is_empty() {
                result.insert(block.clone());
            } else {
                Block::argmax(children, scoring_function)
                    .into_iter()
                    .for_each(|block| {
                        stack.push(block);
                    });
            }
        }

        // Tie breaker uses the blocks hashes.
        result
            .into_iter()
            .max_by(|left, right| right.id().cmp(&left.id()))
            .ok_or(Error)
    }

    pub fn safety_oracles<U: WeightUnit>(
        block: Block<D>,
        latest_messages_honest: &LatestMessagesHonest<Self>,
        equivocators: &HashSet<D::ValidatorName>,
        safety_oracle_threshold: U,
        weights: &validator::Weights<D::ValidatorName, U>,
    ) -> HashSet<BTreeSet<D::ValidatorName>> {
        fn latest_in_justification<D: BlockData>(
            justification: &Justification<Block<D>>,
            equivocators: &HashSet<D::ValidatorName>,
        ) -> HashMap<D::ValidatorName, Message<Block<D>>> {
            LatestMessagesHonest::from_latest_messages(
                &LatestMessages::from(justification),
                equivocators,
            )
            .iter()
            .map(|message| (message.sender().clone(), message.clone()))
            .collect()
        }

        let latest_containing_block: HashSet<&Message<Block<D>>> = latest_messages_honest
            .iter()
            .filter(|&message| block.is_member(&Block::from(message)))
            .collect();

        let latest_agreeing_in_validator_view: HashMap<_, HashMap<_, Message<Block<D>>>> =
            latest_containing_block
                .iter()
                .map(|message| {
                    (
                        message.sender().clone(),
                        latest_in_justification(message.justification(), equivocators)
                            .into_iter()
                            .filter(|(_validator, message)| block.is_member(&Block::from(message)))
                            .collect(),
                    )
                })
                .collect();

        let neighbours: HashMap<&D::ValidatorName, HashSet<&D::ValidatorName>> =
            latest_agreeing_in_validator_view
                .iter()
                .map(|(validator, seen_agreeing)| {
                    (
                        validator,
                        seen_agreeing
                            .keys()
                            .filter(|validatorb| {
                                if latest_agreeing_in_validator_view.contains_key(validatorb) {
                                    latest_agreeing_in_validator_view[validatorb]
                                        .contains_key(&validator.clone())
                                } else {
                                    false
                                }
                            })
                            .collect(),
                    )
                })
                .collect();

        fn bron_kerbosch<D: BlockData>(
            r: HashSet<&D::ValidatorName>,
            p: HashSet<&D::ValidatorName>,
            x: HashSet<&D::ValidatorName>,
            mx_clqs: &mut HashSet<BTreeSet<D::ValidatorName>>,
            neighbours: HashMap<&D::ValidatorName, HashSet<&D::ValidatorName>>,
        ) {
            if p.is_empty() && x.is_empty() {
                let rnew: BTreeSet<D::ValidatorName> = r.into_iter().cloned().collect();
                mx_clqs.insert(rnew);
            } else {
                let piter = p.clone();
                let mut p = p;
                let mut x = x;
                piter.into_iter().for_each(|i| {
                    p.remove(i);
                    let mut rnew = r.clone();
                    rnew.insert(i);
                    let pnew: HashSet<&D::ValidatorName> =
                        p.intersection(&neighbours[i]).cloned().collect();
                    let xnew: HashSet<&D::ValidatorName> =
                        x.intersection(&neighbours[i]).cloned().collect();
                    x.insert(i);
                    bron_kerbosch::<D>(rnew, pnew, xnew, mx_clqs, neighbours.clone())
                })
            }
        }

        let p = neighbours
            .iter()
            .fold(HashSet::new(), |acc, (_validator, x)| {
                acc.union(x).cloned().collect()
            });

        let mut mx_clqs = HashSet::new();

        bron_kerbosch::<D>(HashSet::new(), p, HashSet::new(), &mut mx_clqs, neighbours);

        mx_clqs
            .into_iter()
            .filter(|x| {
                x.iter().fold(<U as Zero<U>>::ZERO, |acc, validator| {
                    // Having a non existing validator would be a fault we can not recover from
                    // since we cannot know or invent the weight of an arbitrary validator.
                    acc + weights.weight(validator).unwrap()
                }) > safety_oracle_threshold
            })
            .collect()
    }

    /// Contrary to the paper's definition 4.24, this does not return Self for a genesis block but
    /// None. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L525
    pub fn prevblock(&self) -> Option<Self> {
        self.arc().prevblock.as_ref().cloned()
    }

    pub fn prev_block_as_ref(&self) -> Option<&Self> {
        self.arc().prevblock.as_ref()
    }

    pub fn data(&self) -> D {
        self.arc().data.clone()
    }

    /// Contrary to the paper's definition 4.25, this does not return Self for a genesis block but
    /// None. Source:
    /// https://github.com/cbc-casper/cbc-casper-paper/blob/acc66e2ba4461a005262e2d5f434fd2e30ef0ff3/examples.tex#L544
    pub fn ncestor(&self, n: u32) -> Option<Self> {
        if n == 0 {
            return Some(self.clone());
        }

        match self.prevblock() {
            Some(block) => Block::ncestor(&block, n - 1),
            None => None,
        }
    }

    /// Parses latest_messages to return a tuple containing:
    /// * a HashMap mapping blocks to their children;
    /// * a HashSet containing blocks with None as their prevblock (aka genesis blocks or finalized
    /// blocks);
    /// * a HashMap mapping blocks to their senders.
    pub fn parse_blockchains(
        latest_messages: &LatestMessagesHonest<Self>,
    ) -> (
        BlocksChildrenMap<D>,
        GenesisBlocks<D>,
        BlocksValidatorsMap<D>,
    ) {
        let latest_blocks: HashMap<Block<D>, D::ValidatorName> = latest_messages
            .iter()
            .map(|message| (Block::from(message), message.sender().clone()))
            .collect();
        // start at the tip of the blockchain
        let mut visited_parents: HashMap<Block<D>, HashSet<Block<D>>> = latest_messages
            .iter()
            .map(|message| {
                let parent = Block::from(message);
                let children = HashSet::new();
                (parent, children)
            })
            .collect();

        let mut queue: VecDeque<Block<D>> = visited_parents.keys().cloned().collect();
        let mut genesis: HashSet<Block<D>> = HashSet::new();
        let mut was_empty = false;

        // while there are still unvisited blocks
        while let Some(child) = queue.pop_front() {
            match (child.prevblock(), was_empty && genesis.is_empty()) {
                // if the prevblock is set, update the visited_parents map
                (Some(parent), false) => {
                    if queue.is_empty() {
                        was_empty = true
                    }
                    if visited_parents.contains_key(&parent) {
                        // visited parent before, fork found, add new child and don't add parent to
                        // queue (since it is already in the queue)
                        if let Some(parents_children) = visited_parents.get_mut(&parent) {
                            parents_children.insert(child);
                        }
                    } else {
                        // didn't visit parent before, add it with known child, and push to queue
                        let mut parents_children = HashSet::new();
                        parents_children.insert(child);
                        visited_parents.insert(parent.clone(), parents_children);
                        queue.push_back(parent);
                    }
                }
                // if not, update the genesis set, as a None prevblock indicates the genesis
                _ => {
                    genesis.insert(child);
                }
            };
        }
        (visited_parents, genesis, latest_blocks)
    }

    pub fn find_all_accessible_blocks(
        latest_messages: &LatestMessagesHonest<Self>,
    ) -> HashSet<Block<D>> {
        let mut blocks = HashSet::new();

        for message in latest_messages.iter() {
            let mut block = message.estimate().clone();

            while let Some(prev_block) = block.prevblock() {
                if blocks.contains(&block) {
                    break;
                }

                blocks.insert(block);
                block = prev_block.clone();
            }

            blocks.insert(block);
        }

        blocks
    }

    /// Collects the validators that produced blocks for each side of a fork.
    fn collect_validators(
        block: &Block<D>,
        visited: &HashMap<Block<D>, HashSet<Block<D>>>,
        latest_blocks: &HashMap<Block<D>, D::ValidatorName>,
        b_in_lms_validators: &mut HashMap<Block<D>, HashSet<D::ValidatorName>>,
    ) -> HashSet<D::ValidatorName> {
        let mut validators = HashSet::new();
        // Collect this validator if this block is his proposed one from his latest message.
        latest_blocks
            .get(block)
            .map(|validator| validators.insert(validator.clone()));
        let res = visited
            .get(block)
            .map(|children| {
                children.iter().fold(validators.clone(), |acc, child| {
                    let res = Self::collect_validators(
                        child,
                        visited,
                        latest_blocks,
                        b_in_lms_validators,
                    );
                    res.union(&acc).cloned().collect()
                })
            })
            .unwrap_or_else(|| validators);
        b_in_lms_validators.insert(block.clone(), res.clone());
        res
    }

    /// Find heaviest block.
    fn pick_heaviest<U: WeightUnit>(
        blocks: &HashSet<Block<D>>,
        visited: &HashMap<Block<D>, HashSet<Block<D>>>,
        weights: &validator::Weights<D::ValidatorName, U>,
        latest_blocks: &HashMap<Block<D>, D::ValidatorName>,
        b_in_lms_validators: &mut HashMap<Block<D>, HashSet<D::ValidatorName>>,
    ) -> Option<(Option<Self>, U, HashSet<Self>)> {
        let init = Some((None, <U as Zero<U>>::ZERO, HashSet::new()));
        let heaviest_child = match blocks.len() {
            // only one choice, no need to compute anything
            length if length == 1 => blocks.iter().next().cloned().and_then(|block| {
                visited
                    .get(&block)
                    .map(|children| (Some(block), <U as Zero<U>>::ZERO, children.clone()))
            }),
            // fork, need to find best block
            length if length > 1 => blocks.iter().fold(init, |best, block| {
                let best_children =
                    best.and_then(|best| visited.get(&block).map(|children| (best, children)));
                best_children.and_then(|((b_block, b_weight, b_children), children)| {
                    let referred_validators = match b_in_lms_validators.get(block).cloned() {
                        Some(rs) => rs,
                        None => Self::collect_validators(
                            block,
                            visited,
                            latest_blocks,
                            b_in_lms_validators,
                        ),
                    };
                    let weight = weights.sum_weight_validators(&referred_validators);
                    let res = Some((Some(block.clone()), weight, children.clone()));
                    let b_res = Some((b_block.clone(), b_weight, b_children));
                    match weight.partial_cmp(&b_weight) {
                        Some(Ordering::Greater) => res,
                        Some(Ordering::Less) => b_res,
                        Some(Ordering::Equal) | None => {
                            // break ties with blockhash
                            let ord = b_block.as_ref().map(|b| b.id().cmp(&block.id()));
                            match ord {
                                Some(Ordering::Greater) => res,
                                Some(Ordering::Less) => b_res,
                                Some(Ordering::Equal) => b_res,
                                None => None,
                            }
                        }
                    }
                })
            }),
            _ => None,
        };
        heaviest_child.and_then(|(b_block, b_weight, b_children)| {
            if b_children.is_empty() {
                // base case
                Some((b_block, b_weight, b_children))
            } else {
                // recurse
                Self::pick_heaviest(
                    &b_children,
                    visited,
                    &weights,
                    latest_blocks,
                    b_in_lms_validators,
                )
            }
        })
    }

    pub fn old_ghost<U: WeightUnit>(
        latest_messages: &LatestMessagesHonest<Self>,
        validators_weights: &validator::Weights<D::ValidatorName, U>,
    ) -> Result<Self, Error> {
        let (visited, genesis, latest_blocks) = Self::parse_blockchains(latest_messages);

        let mut b_in_lms_validators = HashMap::<Block<D>, HashSet<D::ValidatorName>>::new();

        Block::pick_heaviest(
            &genesis,
            &visited,
            validators_weights,
            &latest_blocks,
            &mut b_in_lms_validators,
        )
        .and_then(|(opt_block, ..)| opt_block)
        .ok_or(Error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::collections::{BTreeSet, HashSet};
    use std::iter;
    use std::iter::FromIterator;

    use crate::justification::{Justification, LatestMessages, LatestMessagesHonest};
    use crate::validator;

    use crate::ValidatorNameBlockData;

    #[test]
    fn ncestor() {
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(5));

        assert_eq!(genesis.ncestor(0), Some(genesis.clone()));
        assert_eq!(genesis.ncestor(1), None);

        assert_eq!(block_2.ncestor(0), Some(block_2.clone()));
        assert_eq!(block_2.ncestor(1), Some(block_1));
        assert_eq!(block_2.ncestor(2), Some(genesis));
        assert_eq!(block_2.ncestor(3), None);
    }

    #[test]
    fn from_prevblock_message() {
        let incomplete_block = Block::new(None, ValidatorNameBlockData::new(0));
        let message = Message::new(
            1,
            Justification::empty(),
            Block::from(ProtoBlock::new(None, ValidatorNameBlockData::new(2))),
        );

        assert_eq!(
            Block::from_prevblock_message(Some(message.clone()), incomplete_block),
            Block::new(Some(Block::from(&message)), ValidatorNameBlockData::new(0)),
        );
    }

    #[test]
    fn from_prevblock_message_none() {
        let incomplete_block = Block::new(None, ValidatorNameBlockData::new(0));

        assert_eq!(
            Block::from_prevblock_message(None, incomplete_block),
            Block::new(None, ValidatorNameBlockData::new(0)),
        );
    }

    #[test]
    fn is_member_self() {
        let block = Block::new(
            Some(Block::from(&Message::new(
                0,
                Justification::empty(),
                Block::new(None, ValidatorNameBlockData::new(1)),
            ))),
            ValidatorNameBlockData::new(2),
        );
        assert!(block.is_member(&block));
        assert!(Block::new(None, ValidatorNameBlockData::new(0))
            .is_member(&Block::new(None, ValidatorNameBlockData::new(0))));
        assert!(!Block::new(None, ValidatorNameBlockData::new(0))
            .is_member(&Block::new(None, ValidatorNameBlockData::new(1))));
    }

    #[test]
    fn is_member_ancestor() {
        let message = Message::new(
            0,
            Justification::empty(),
            Block::new(None, ValidatorNameBlockData::new(1)),
        );
        let block_1 = Block::from(&message);
        let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(2));

        assert!(block_1.is_member(&block_2));
        assert!(Block::from(&message).is_member(&block_1));
        assert!(Block::from(&message).is_member(&block_2));

        assert!(!block_2.is_member(&block_1));
        assert!(!block_2.is_member(&Block::from(&message)));
    }

    #[test]
    fn score() {
        let weights = validator::Weights::new(
            vec![(0, 1.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 16.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(block_3.clone()), ValidatorNameBlockData::new(0));
        let block_5 = Block::new(Some(block_4.clone()), ValidatorNameBlockData::new(4));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis.clone()));
        justification.insert(Message::new(1, justification.clone(), block_1.clone()));
        justification.insert(Message::new(2, justification.clone(), block_2.clone()));
        justification.insert(Message::new(3, justification.clone(), block_3.clone()));
        justification.insert(Message::new(0, justification.clone(), block_4.clone()));
        justification.insert(Message::new(4, justification.clone(), block_5.clone()));
        let latest_messages = LatestMessages::from(&justification);

        float_eq!(
            genesis.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            31.0
        );
        float_eq!(
            block_1.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            31.0
        );
        float_eq!(
            block_2.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            4.0
        );
        float_eq!(
            block_3.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            25.0
        );
        float_eq!(
            block_4.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            17.0
        );
        float_eq!(
            block_5.score(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights
            ),
            16.0
        );
    }

    #[test]
    fn children() {
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(block_3.clone()), ValidatorNameBlockData::new(0));

        assert_eq!(
            genesis.children(
                &vec![&genesis, &block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>()
            ),
            vec![&block_1].into_iter().collect::<HashSet<_>>()
        );
        assert_eq!(
            block_1.children(
                &vec![&genesis, &block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>()
            ),
            vec![&block_2, &block_3].into_iter().collect::<HashSet<_>>()
        );
        assert_eq!(
            block_2.children(
                &vec![&genesis, &block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>()
            ),
            vec![].into_iter().collect::<HashSet<_>>()
        );
        assert_eq!(
            block_3.children(
                &vec![&genesis, &block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>()
            ),
            vec![&block_4].into_iter().collect::<HashSet<_>>()
        );
    }

    #[test]
    fn children_missing_children_are_not_included() {
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(block_3), ValidatorNameBlockData::new(0));

        assert_eq!(
            block_1.children(&vec![&block_2, &block_4].into_iter().collect::<HashSet<_>>()),
            vec![&block_2].into_iter().collect::<HashSet<_>>()
        );
    }

    #[test]
    fn best_children_trivial() {
        let weights = validator::Weights::new(
            vec![(0, 3.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 1.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(4));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis.clone()));
        justification.insert(Message::new(1, justification.clone(), block_1.clone()));
        justification.insert(Message::new(2, justification.clone(), block_2.clone()));
        justification.insert(Message::new(3, justification.clone(), block_3.clone()));
        justification.insert(Message::new(4, justification.clone(), block_4.clone()));
        let latest_messages = LatestMessages::from(&justification);

        assert_eq!(
            genesis.best_children(
                &vec![&block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>(),
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            ),
            vec![&block_3].into_iter().collect::<HashSet<_>>()
        );
    }

    #[test]
    fn best_children_indirect() {
        let weights = validator::Weights::new(
            vec![(0, 1.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 10.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(4));
        let block_5 = Block::new(Some(block_4.clone()), ValidatorNameBlockData::new(0));
        let block_6 = Block::new(Some(block_2.clone()), ValidatorNameBlockData::new(3));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis.clone()));
        justification.insert(Message::new(1, justification.clone(), block_1.clone()));
        justification.insert(Message::new(2, justification.clone(), block_2.clone()));
        justification.insert(Message::new(3, justification.clone(), block_3.clone()));
        justification.insert(Message::new(4, justification.clone(), block_4.clone()));
        justification.insert(Message::new(0, justification.clone(), block_5));
        justification.insert(Message::new(3, justification.clone(), block_6));
        let latest_messages = LatestMessages::from(&justification);

        assert_eq!(
            genesis.best_children(
                &vec![&block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>(),
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            ),
            vec![&block_2].into_iter().collect::<HashSet<_>>()
        );
    }

    #[test]
    fn best_children_tie() {
        let weights = validator::Weights::new(
            vec![(0, 1.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 10.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(4));
        let block_5 = Block::new(Some(block_2.clone()), ValidatorNameBlockData::new(0));
        let block_6 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(3));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis.clone()));
        justification.insert(Message::new(1, justification.clone(), block_1.clone()));
        justification.insert(Message::new(2, justification.clone(), block_2.clone()));
        justification.insert(Message::new(3, justification.clone(), block_3.clone()));
        justification.insert(Message::new(4, justification.clone(), block_4.clone()));
        justification.insert(Message::new(0, justification.clone(), block_5));
        justification.insert(Message::new(3, justification.clone(), block_6));
        let latest_messages = LatestMessages::from(&justification);

        assert_eq!(
            genesis.best_children(
                &vec![&block_1, &block_2, &block_3, &block_4]
                    .into_iter()
                    .collect::<HashSet<_>>(),
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            ),
            vec![&block_1, &block_4].into_iter().collect::<HashSet<_>>()
        );
    }

    #[test]
    fn best_children_empty() {
        let weights = validator::Weights::new(vec![(0, 1.0)].into_iter().collect());
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        assert_eq!(
            genesis.best_children(
                &HashSet::new(),
                &LatestMessagesHonest::from_latest_messages(
                    &LatestMessages::empty(),
                    &HashSet::new()
                ),
                &weights,
            ),
            HashSet::new()
        );
    }

    #[test]
    fn ghost() {
        let weights = validator::Weights::new(
            vec![(0, 1.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 16.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(4));

        let block_5 = Block::new(Some(block_4.clone()), ValidatorNameBlockData::new(0));
        let block_6 = Block::new(Some(block_2.clone()), ValidatorNameBlockData::new(3));

        let block_7 = Block::new(Some(block_5.clone()), ValidatorNameBlockData::new(2));
        let block_8 = Block::new(Some(block_6.clone()), ValidatorNameBlockData::new(4));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis));
        justification.insert(Message::new(1, justification.clone(), block_1));
        justification.insert(Message::new(2, justification.clone(), block_2));
        justification.insert(Message::new(3, justification.clone(), block_3));
        justification.insert(Message::new(4, justification.clone(), block_4));
        justification.insert(Message::new(0, justification.clone(), block_5));
        justification.insert(Message::new(3, justification.clone(), block_6));
        justification.insert(Message::new(2, justification.clone(), block_7));
        justification.insert(Message::new(4, justification.clone(), block_8.clone()));
        let latest_messages = LatestMessages::from(&justification);

        assert_eq!(
            Block::mathematical_ghost(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            )
            .unwrap(),
            block_8,
        );
        assert_eq!(
            Block::optimized_ghost(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            )
            .unwrap(),
            block_8,
        );
        assert_eq!(
            Block::old_ghost(
                &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new()),
                &weights,
            )
            .unwrap(),
            block_8,
        );
    }

    #[test]
    fn ghost_tie() {
        let weights = validator::Weights::new(
            vec![(0, 1.0), (1, 2.0), (2, 4.0), (3, 8.0), (4, 10.0), (5, 0.0)]
                .into_iter()
                .collect(),
        );
        let genesis = Block::new(None, ValidatorNameBlockData::new(0));
        let block_1 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(1));
        let block_2 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(2));
        let block_3 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(3));
        let block_4 = Block::new(Some(genesis.clone()), ValidatorNameBlockData::new(4));
        let block_5 = Block::new(Some(block_2.clone()), ValidatorNameBlockData::new(0));
        let block_6 = Block::new(Some(block_1.clone()), ValidatorNameBlockData::new(3));
        let block_7 = Block::new(Some(block_6.clone()), ValidatorNameBlockData::new(5));

        let mut justification = Justification::empty();
        justification.insert(Message::new(0, justification.clone(), genesis));
        justification.insert(Message::new(1, justification.clone(), block_1));
        justification.insert(Message::new(2, justification.clone(), block_2));
        justification.insert(Message::new(3, justification.clone(), block_3));
        justification.insert(Message::new(4, justification.clone(), block_4.clone()));
        justification.insert(Message::new(0, justification.clone(), block_5));
        justification.insert(Message::new(3, justification.clone(), block_6));
        justification.insert(Message::new(5, justification.clone(), block_7));
        let latest_messages = LatestMessages::from(&justification);
        let latest_honest_messages =
            &LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new());

        // block_4 and block_7 are tied but the hash based tie breaker chooses block_4.
        assert_eq!(
            Block::mathematical_ghost(latest_honest_messages, &weights,).unwrap(),
            block_4,
        );
        assert_eq!(
            Block::optimized_ghost(latest_honest_messages, &weights,).unwrap(),
            block_4,
        );
        assert_eq!(
            Block::old_ghost(latest_honest_messages, &weights,).unwrap(),
            block_4,
        );
    }

    #[test]
    fn from_message() {
        let block_1 = Block::new(
            Some(Block::new(None, ValidatorNameBlockData::new(0))),
            ValidatorNameBlockData::new(1),
        );
        let message = Message::new(0, Justification::empty(), block_1.clone());
        let block_2 = Block::from(&message);

        assert_eq!(block_1, block_2);
    }

    #[test]
    fn parse_blockchains() {
        let genesis = Message::new(
            0,
            Justification::empty(),
            Block::new(None, ValidatorNameBlockData::new(0)),
        );
        let mut justification = Justification::empty();
        justification.insert(genesis.clone());
        let block_1 = Message::new(
            1,
            justification.clone(),
            Block::new(
                Some(genesis.estimate().clone()),
                ValidatorNameBlockData::new(3),
            ),
        );
        let block_2 = Message::new(
            2,
            justification,
            Block::new(
                Some(genesis.estimate().clone()),
                ValidatorNameBlockData::new(4),
            ),
        );

        let mut latest_messages = LatestMessages::empty();
        latest_messages.update(&genesis);
        latest_messages.update(&block_1);
        latest_messages.update(&block_2);
        let latest_messages_honest =
            LatestMessagesHonest::from_latest_messages(&latest_messages, &HashSet::new());

        let (children_map, genesis_set, senders_map) =
            Block::parse_blockchains(&latest_messages_honest);

        assert_eq!(
            children_map,
            vec![
                (
                    genesis.estimate().clone(),
                    HashSet::from_iter(vec![
                        block_1.estimate().clone(),
                        block_2.estimate().clone()
                    ])
                ),
                (block_1.estimate().clone(), HashSet::new()),
                (block_2.estimate().clone(), HashSet::new()),
            ]
            .into_iter()
            .collect(),
        );
        assert_eq!(
            genesis_set,
            HashSet::from_iter(vec![genesis.estimate().clone()]),
        );

        assert_eq!(
            senders_map,
            vec![
                (genesis.estimate().clone(), 0),
                (block_1.estimate().clone(), 1),
                (block_2.estimate().clone(), 2)
            ]
            .into_iter()
            .collect(),
        );
    }

    #[test]
    fn safety_oracles() {
        let nodes = 3;
        let validators: Vec<u32> = (0..nodes).collect();

        let validators_weights =
            validator::Weights::new(validators.iter().cloned().zip(iter::repeat(1.0)).collect());

        let mut state = validator::State::new(
            validators_weights.clone(),
            0.0,
            LatestMessages::empty(),
            1.0,
            HashSet::new(),
        );

        // block dag
        let proto_b0 = Block::from(ProtoBlock::new(None, ValidatorNameBlockData::new(0)));
        let latest_messages = Justification::empty();
        let m0 = Message::new(validators[0], latest_messages, proto_b0.clone());

        let proto_b1 = Block::new(Some(proto_b0.clone()), ValidatorNameBlockData::new(0));
        state.update(&[&m0]);
        let m1 = Message::from_validator_state(validators[1], &state).unwrap();

        let proto_b2 = Block::new(Some(proto_b1.clone()), ValidatorNameBlockData::new(0));
        state.update(&[&m1]);
        let m2 = Message::from_validator_state(validators[0], &state).unwrap();

        // no clique yet, since validators[1] has not seen validators[0] seeing validators[1]
        // having proto_b0 in the chain
        assert_eq!(
            Block::safety_oracles(
                proto_b0.clone(),
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                2.0,
                &validators_weights
            ),
            HashSet::new()
        );

        state.update(&[&m2]);
        let m3 = Message::from_validator_state(validators[1], &state).unwrap();

        // clique, since both validators have seen each other having proto_b0 in the chain
        assert_eq!(
            Block::safety_oracles(
                proto_b0.clone(),
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![BTreeSet::from_iter(vec![
                validators[0],
                validators[1]
            ])])
        );

        state.update(&[&m3]);
        let m4 = Message::from_validator_state(validators[2], &state).unwrap();

        state.update(&[&m4]);
        let m5 = Message::from_validator_state(validators[1], &state).unwrap();

        // no second clique yet, since validators[2] has not seen validators[1] seeing
        // validators[2] having proto_b0.clone() in the chain
        assert_eq!(
            Block::safety_oracles(
                proto_b0.clone(),
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![BTreeSet::from_iter(vec![
                validators[0],
                validators[1]
            ])])
        );

        state.update(&[&m5]);
        let m6 = Message::from_validator_state(validators[2], &state).unwrap();

        // have two cliques on proto_b0 now
        assert_eq!(
            Block::safety_oracles(
                proto_b0.clone(),
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![
                BTreeSet::from_iter(vec![validators[0], validators[1]]),
                BTreeSet::from_iter(vec![validators[1], validators[2]]),
            ])
        );

        // also have two cliques on proto_b1
        assert_eq!(
            Block::safety_oracles(
                proto_b1,
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![
                BTreeSet::from_iter(vec![validators[0], validators[1]]),
                BTreeSet::from_iter(vec![validators[1], validators[2]]),
            ])
        );

        // on proto_b2, only have clique {1, 2}
        assert_eq!(
            Block::safety_oracles(
                proto_b2.clone(),
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![BTreeSet::from_iter(vec![
                validators[1],
                validators[2]
            ])])
        );

        state.update(&[&m6]);
        let m7 = Message::from_validator_state(validators[0], &state).unwrap();

        state.update(&[&m7]);
        let m8 = Message::from_validator_state(validators[2], &state).unwrap();

        state.update(&[&m8]);
        let _ = Message::from_validator_state(validators[0], &state).unwrap();

        // now entire network is clique
        assert_eq!(
            Block::safety_oracles(
                proto_b0,
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![BTreeSet::from_iter(vec![
                validators[0],
                validators[1],
                validators[2],
            ])])
        );
        assert_eq!(
            Block::safety_oracles(
                proto_b2,
                &LatestMessagesHonest::from_latest_messages(
                    state.latests_messages(),
                    state.equivocators()
                ),
                state.equivocators(),
                1.0,
                &validators_weights
            ),
            HashSet::from_iter(vec![BTreeSet::from_iter(vec![
                validators[0],
                validators[1],
                validators[2],
            ])])
        );
    }
}