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
use std::sync::{mpsc, Arc, Weak};

use once_cell::sync::OnceCell;

use cfx_types::{H256, U256, U64};
use diem_config::{config::NodeConfig, keys::ConfigKey};
use diem_crypto::HashValue;
use diem_types::{
    contract_event::ContractEvent,
    epoch_state::EpochState,
    reward_distribution_event::RewardDistributionEventV2,
    term_state::{DisputeEvent, UnlockEvent},
    validator_config::{ConsensusPrivateKey, ConsensusVRFPrivateKey},
};
use keccak_hash::keccak;
use primitives::pos::{NodeId, PosBlockId};
use storage_interface::{DBReaderForPoW, DbReader};

use crate::{
    genesis_block::GenesisPosState,
    pos::{
        consensus::{
            network::{
                NetworkReceivers as ConsensusNetworkReceivers,
                NetworkTask as ConsensusNetworkTask,
            },
            ConsensusDB, TestCommand,
        },
        mempool::network::{
            NetworkReceivers as MemPoolNetworkReceivers,
            NetworkTask as MempoolNetworkTask,
        },
        pos::{start_pos_consensus, PosDropHandle},
        protocol::sync_protocol::HotStuffSynchronizationProtocol,
    },
    sync::ProtocolConfiguration,
    ConsensusGraph,
};

use cached_pos_ledger_db::CachedPosLedgerDB;
use consensus_types::block::Block;
use diem_config::config::SafetyRulesTestConfig;
use diem_types::{
    account_address::from_consensus_public_key,
    block_info::{PivotBlockDecision, Round},
    chain_id::ChainId,
    epoch_state::HARDCODED_COMMITTEE_FOR_EPOCH,
    term_state::pos_state_config::{PosStateConfig, POS_STATE_CONFIG},
    transaction::TransactionPayload,
};
use network::NetworkService;
use parking_lot::Mutex;
use pos_ledger_db::PosLedgerDB;
use std::{fs, io::Read, path::PathBuf};

pub type PosVerifier = PosHandler;

/// This includes the interfaces that the PoW consensus needs from the PoS
/// consensus.
///
/// We assume the PoS service will be always available after `initialize()`
/// returns, so all the other interfaces will panic if the PoS service is not
/// ready.
pub trait PosInterface: Send + Sync {
    /// Wait for initialization.
    fn initialize(&self) -> Result<(), String>;

    /// Get a PoS block by its ID.
    ///
    /// Return `None` if the block does not exist or is not committed.
    fn get_committed_block(&self, h: &PosBlockId) -> Option<PosBlock>;

    /// Return the latest committed PoS block ID.
    /// This will become the PoS reference of the mined PoW block.
    fn latest_block(&self) -> PosBlockId;

    fn get_events(
        &self, from: &PosBlockId, to: &PosBlockId,
    ) -> Vec<ContractEvent>;

    fn get_epoch_ending_blocks(
        &self, start_epoch: u64, end_epoch: u64,
    ) -> Vec<PosBlockId>;

    fn get_reward_event(&self, epoch: u64)
        -> Option<RewardDistributionEventV2>;

    fn get_epoch_state(&self, block_id: &PosBlockId) -> EpochState;

    fn pos_ledger_db(&self) -> &Arc<PosLedgerDB>;

    fn consensus_db(&self) -> &Arc<ConsensusDB>;

    fn cached_db(&self) -> &Arc<CachedPosLedgerDB>;
}

#[allow(unused)]
pub struct PosBlock {
    hash: PosBlockId,
    epoch: u64,
    round: u64,
    pivot_decision: H256,
    version: u64,
    view: u64,
    /* parent: PosBlockId,
     * author: NodeId,
     * voters: Vec<NodeId>, */
}

pub struct PosHandler {
    pos: OnceCell<Box<dyn PosInterface>>,
    network: Mutex<Option<Arc<NetworkService>>>,
    // Keep all tokio Runtime so they will not be dropped directly.
    drop_handle: Mutex<Option<PosDropHandle>>,
    consensus_network_receiver: Mutex<Option<ConsensusNetworkReceivers>>,
    mempool_network_receiver: Mutex<Option<MemPoolNetworkReceivers>>,
    test_command_sender: Mutex<Option<channel::Sender<TestCommand>>>,
    enable_height: u64,
    hsb_protocol_handler: Option<Arc<HotStuffSynchronizationProtocol>>,
    pub conf: PosConfiguration,
}

impl PosHandler {
    pub fn new(
        network: Option<Arc<NetworkService>>, conf: PosConfiguration,
        enable_height: u64,
    ) -> Self {
        let mut pos = Self {
            pos: OnceCell::new(),
            network: Mutex::new(network.clone()),
            drop_handle: Mutex::new(None),
            consensus_network_receiver: Mutex::new(None),
            mempool_network_receiver: Mutex::new(None),
            test_command_sender: Mutex::new(None),
            enable_height,
            hsb_protocol_handler: None,
            conf,
        };
        if let Some(network) = &network {
            // initialize hotstuff protocol handler
            let (consensus_network_task, consensus_network_receiver) =
                ConsensusNetworkTask::new();
            let (mempool_network_task, mempool_network_receiver) =
                MempoolNetworkTask::new();
            let own_node_hash = keccak(
                network.net_key_pair().expect("Error node key").public(),
            );
            let protocol_handler =
                Arc::new(HotStuffSynchronizationProtocol::new(
                    own_node_hash,
                    consensus_network_task,
                    mempool_network_task,
                    pos.conf.protocol_conf.clone(),
                ));
            protocol_handler.clone().register(network.clone()).unwrap();
            *pos.consensus_network_receiver.lock() =
                Some(consensus_network_receiver);
            *pos.mempool_network_receiver.lock() =
                Some(mempool_network_receiver);
            pos.hsb_protocol_handler = Some(protocol_handler);
        }
        pos
    }

    pub fn initialize(
        &self, consensus: Arc<ConsensusGraph>,
    ) -> Result<(), String> {
        if self.pos.get().is_some() {
            warn!("Initializing already-initialized PosHandler!");
            return Ok(());
        }
        let pos_config_path = match self.conf.diem_conf_path.as_ref() {
            Some(path) => PathBuf::from(path),
            None => bail!("No pos config!"),
        };

        POS_STATE_CONFIG
            .set(self.conf.pos_state_config.clone())
            .map_err(|e| {
                format!("Failed to set pos state config: e={:?}", e)
            })?;
        let mut pos_config = NodeConfig::load(pos_config_path)
            .map_err(|e| format!("Failed to load node config: e={:?}", e))?;
        HARDCODED_COMMITTEE_FOR_EPOCH
            .set(pos_config.consensus.hardcoded_epoch_committee.clone())
            .map_err(|e| {
                format!("Failed to set hardcoded_epoch_committee: e={:?}", e)
            })?;

        pos_config.set_data_dir(pos_config.data_dir().to_path_buf());
        let pos_genesis = read_initial_nodes_from_file(
            self.conf.pos_initial_nodes_path.as_str(),
        )?;
        let network = self.network.lock().take().expect("pos not initialized");
        let (test_command_sender, test_command_receiver) =
            channel::new_test(1024);

        pos_config.consensus.safety_rules.test = Some(SafetyRulesTestConfig {
            author: from_consensus_public_key(
                &self.conf.bls_key.public_key(),
                &self.conf.vrf_key.public_key(),
            ),
            consensus_key: Some(self.conf.bls_key.clone()),
            execution_key: Some(self.conf.bls_key.clone()),
            waypoint: Some(pos_config.base.waypoint.waypoint()),
        });
        pos_config.consensus.safety_rules.vrf_private_key =
            Some(self.conf.vrf_key.clone());
        pos_config.consensus.safety_rules.export_consensus_key = true;
        pos_config.consensus.safety_rules.vrf_proposal_threshold =
            self.conf.vrf_proposal_threshold;
        pos_config.consensus.chain_id = ChainId::new(network.network_id());

        let pos_drop_handle = start_pos_consensus(
            &pos_config,
            network,
            self.conf.protocol_conf.clone(),
            Some((
                self.conf.bls_key.public_key(),
                self.conf.vrf_key.public_key(),
            )),
            pos_genesis,
            self.consensus_network_receiver
                .lock()
                .take()
                .expect("not initialized"),
            self.mempool_network_receiver
                .lock()
                .take()
                .expect("not initialized"),
            test_command_receiver,
            self.hsb_protocol_handler.clone().expect("set in new"),
        );
        debug!("PoS initialized");
        let pos_connection = PosConnection::new(
            pos_drop_handle.pos_ledger_db.clone(),
            pos_drop_handle.consensus_db.clone(),
            pos_drop_handle.cached_db.clone(),
        );
        pos_drop_handle.pow_handler.initialize(consensus);
        if self.pos.set(Box::new(pos_connection)).is_err() {
            bail!("PoS initialized twice!");
        }
        *self.test_command_sender.lock() = Some(test_command_sender);
        *self.drop_handle.lock() = Some(pos_drop_handle);
        Ok(())
    }

    pub fn config(&self) -> &PosConfiguration { &self.conf }

    fn pos(&self) -> &Box<dyn PosInterface> { self.pos.get().unwrap() }

    pub fn pos_option(&self) -> Option<&Box<dyn PosInterface>> {
        self.pos.get()
    }

    pub fn is_enabled_at_height(&self, height: u64) -> bool {
        height >= self.enable_height
    }

    pub fn is_committed(&self, h: &PosBlockId) -> bool {
        self.pos().get_committed_block(h).is_some()
    }

    /// Check if `me` is equal to or extends `preds` (parent and referees).
    ///
    /// Since committed PoS blocks form a chain, and no pos block should be
    /// skipped, we only need to check if the round of `me` is equal to or plus
    /// one compared with the predecessors' rounds.
    ///
    /// Return `false` if `me` or `preds` contains non-existent PoS blocks.
    pub fn verify_against_predecessors(
        &self, me: &PosBlockId, preds: &Vec<PosBlockId>,
    ) -> bool {
        let me_round = match self.pos().get_committed_block(me) {
            None => {
                warn!("No pos block for me={:?}", me);
                return false;
            }
            Some(b) => (b.epoch, b.round),
        };
        for p in preds {
            let p_round = match self.pos().get_committed_block(p) {
                None => {
                    warn!("No pos block for pred={:?}", p);
                    return false;
                }
                Some(b) => (b.epoch, b.round),
            };
            if me_round < p_round {
                warn!("Incorrect round: me={:?}, pred={:?}", me_round, p_round);
                return false;
            }
        }
        true
    }

    pub fn get_pivot_decision(&self, h: &PosBlockId) -> Option<H256> {
        // Return None if `pos` has not been initialized
        self.pos
            .get()?
            .get_committed_block(h)
            .map(|b| b.pivot_decision)
    }

    pub fn get_latest_pos_reference(&self) -> PosBlockId {
        self.pos().latest_block()
    }

    pub fn get_pos_view(&self, h: &PosBlockId) -> Option<u64> {
        self.pos().get_committed_block(h).map(|b| b.view)
    }

    pub fn get_unlock_nodes(
        &self, h: &PosBlockId, parent_pos_ref: &PosBlockId,
    ) -> Vec<(NodeId, u64)> {
        let unlock_event_key = UnlockEvent::event_key();
        let mut unlock_nodes = Vec::new();
        for event in self.pos().get_events(parent_pos_ref, h) {
            if *event.key() == unlock_event_key {
                let unlock_event = UnlockEvent::from_bytes(event.event_data())
                    .expect("key checked");
                let node_id = H256::from_slice(unlock_event.node_id.as_ref());
                let votes = unlock_event.unlocked;
                unlock_nodes.push((node_id, votes));
            }
        }
        unlock_nodes
    }

    pub fn get_disputed_nodes(
        &self, h: &PosBlockId, parent_pos_ref: &PosBlockId,
    ) -> Vec<NodeId> {
        let dispute_event_key = DisputeEvent::event_key();
        let mut disputed_nodes = Vec::new();
        for event in self.pos().get_events(parent_pos_ref, h) {
            if *event.key() == dispute_event_key {
                let dispute_event =
                    DisputeEvent::from_bytes(event.event_data())
                        .expect("key checked");
                disputed_nodes
                    .push(H256::from_slice(dispute_event.node_id.as_ref()));
            }
        }
        disputed_nodes
    }

    pub fn get_reward_distribution_event(
        &self, h: &PosBlockId, parent_pos_ref: &PosBlockId,
    ) -> Option<Vec<(u64, RewardDistributionEventV2)>> {
        if h == parent_pos_ref {
            return None;
        }
        let me_block = self.pos().get_committed_block(h)?;
        let parent_block = self.pos().get_committed_block(parent_pos_ref)?;
        if me_block.epoch == parent_block.epoch {
            return None;
        }
        let mut events = Vec::new();
        for epoch in parent_block.epoch..me_block.epoch {
            events.push((epoch, self.pos().get_reward_event(epoch)?));
        }
        Some(events)
    }

    pub fn pos_ledger_db(&self) -> &Arc<PosLedgerDB> {
        self.pos().pos_ledger_db()
    }

    pub fn consensus_db(&self) -> &Arc<ConsensusDB> {
        self.pos().consensus_db()
    }

    pub fn cached_db(&self) -> &Arc<CachedPosLedgerDB> {
        self.pos().cached_db()
    }

    pub fn stop(&self) -> Option<(Weak<PosLedgerDB>, Weak<ConsensusDB>)> {
        self.network.lock().take();
        self.consensus_network_receiver.lock().take();
        self.mempool_network_receiver.lock().take();
        self.drop_handle.lock().take().map(|pos_drop_handle| {
            let pos_ledger_db = pos_drop_handle.pos_ledger_db.clone();
            let consensus_db = pos_drop_handle.consensus_db.clone();
            (
                Arc::downgrade(&pos_ledger_db),
                Arc::downgrade(&consensus_db),
            )
        })
    }
}

/// The functions used in tests to construct attack cases
impl PosHandler {
    pub fn force_vote_proposal(&self, block_id: H256) -> anyhow::Result<()> {
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::ForceVoteProposal(h256_to_diem_hash(
                &block_id,
            )))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))
    }

    pub fn force_propose(
        &self, round: U64, parent_block_id: H256,
        payload: Vec<TransactionPayload>,
    ) -> anyhow::Result<()> {
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::ForcePropose {
                round: round.as_u64(),
                parent_id: h256_to_diem_hash(&parent_block_id),
                payload,
            })
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))
    }

    pub fn trigger_timeout(&self, timeout_type: String) -> anyhow::Result<()> {
        let command = match timeout_type.as_str() {
            "local" => TestCommand::LocalTimeout,
            "proposal" => TestCommand::ProposalTimeOut,
            "new_round" => TestCommand::NewRoundTimeout,
            _ => anyhow::bail!("Unknown timeout type"),
        };
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(command)
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))
    }

    pub fn force_sign_pivot_decision(
        &self, pivot_decision: PivotBlockDecision,
    ) -> anyhow::Result<()> {
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::BroadcastPivotDecision(pivot_decision))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))
    }

    pub fn get_chosen_proposal(&self) -> anyhow::Result<Option<Block>> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::GetChosenProposal(tx))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))?;
        rx.recv().map_err(|e| anyhow::anyhow!("recv: err={:?}", e))
    }

    pub fn stop_election(&self) -> anyhow::Result<Option<Round>> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::StopElection(tx))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))?;
        rx.recv().map_err(|e| anyhow::anyhow!("recv: err={:?}", e))
    }

    pub fn start_voting(&self, initialize: bool) -> anyhow::Result<()> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::StartVoting((initialize, tx)))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))?;
        rx.recv()?
    }

    pub fn stop_voting(&self) -> anyhow::Result<()> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::StopVoting(tx))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))?;
        rx.recv()?
    }

    pub fn voting_status(&self) -> anyhow::Result<bool> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.test_command_sender
            .lock()
            .as_mut()
            .ok_or(anyhow::anyhow!("Pos not initialized!"))?
            .try_send(TestCommand::GetVotingStatus(tx))
            .map_err(|e| anyhow::anyhow!("try_send: err={:?}", e))?;
        Ok(rx.recv()?)
    }
}

pub struct PosConnection {
    pos_storage: Arc<PosLedgerDB>,
    consensus_db: Arc<ConsensusDB>,
    pos_cache_db: Arc<CachedPosLedgerDB>,
}

impl PosConnection {
    pub fn new(
        pos_storage: Arc<PosLedgerDB>, consensus_db: Arc<ConsensusDB>,
        pos_cache_db: Arc<CachedPosLedgerDB>,
    ) -> Self {
        Self {
            pos_storage,
            consensus_db,
            pos_cache_db,
        }
    }
}

impl PosInterface for PosConnection {
    fn initialize(&self) -> Result<(), String> { Ok(()) }

    fn get_committed_block(&self, h: &PosBlockId) -> Option<PosBlock> {
        debug!("get_committed_block: {:?}", h);
        let block_hash = h256_to_diem_hash(h);
        let committed_block = self
            .pos_storage
            .get_committed_block_by_hash(&block_hash)
            .ok()?;

        /*
        let parent;
        let author;
        if *h == PosBlockId::default() {
            // genesis has no block, and its parent/author will not be used.
            parent = PosBlockId::default();
            author = NodeId::default();
        } else {
            let block = self
                .pos_consensus_db
                .get_ledger_block(&block_hash)
                .map_err(|e| {
                    warn!("get_committed_block: err={:?}", e);
                    e
                })
                .ok()??;
            debug_assert_eq!(block.id(), block_hash);
            parent = diem_hash_to_h256(&block.parent_id());
            // NIL block has no author.
            author = H256::from_slice(block.author().unwrap_or(Default::default()).as_ref());
        }
         */
        debug!("pos_handler gets committed_block={:?}", committed_block);
        Some(PosBlock {
            hash: *h,
            epoch: committed_block.epoch,
            round: committed_block.round,
            pivot_decision: committed_block.pivot_decision.block_hash,
            view: committed_block.view,
            /* parent,
             * author,
             * voters: ledger_info
             *     .signatures()
             *     .keys()
             *     .map(|author| H256::from_slice(author.as_ref()))
             *     .collect(), */
            version: committed_block.version,
        })
    }

    fn latest_block(&self) -> PosBlockId {
        diem_hash_to_h256(
            &self
                .pos_storage
                .get_latest_ledger_info_option()
                .expect("Initialized")
                .ledger_info()
                .consensus_block_id(),
        )
    }

    fn get_events(
        &self, from: &PosBlockId, to: &PosBlockId,
    ) -> Vec<ContractEvent> {
        let start_version = self
            .pos_storage
            .get_committed_block_by_hash(&h256_to_diem_hash(from))
            .expect("err reading ledger info for from")
            .version;
        let end_version = self
            .pos_storage
            .get_committed_block_by_hash(&h256_to_diem_hash(to))
            .expect("err reading ledger info for to")
            .version;
        self.pos_storage
            .get_events_by_version(start_version, end_version)
            .expect("err reading events")
    }

    fn get_epoch_ending_blocks(
        &self, start_epoch: u64, end_epoch: u64,
    ) -> Vec<PosBlockId> {
        self.pos_storage
            .get_epoch_ending_blocks(start_epoch, end_epoch)
            .expect("err reading epoch ending blocks")
            .into_iter()
            .map(|h| diem_hash_to_h256(&h))
            .collect()
    }

    fn get_reward_event(
        &self, epoch: u64,
    ) -> Option<RewardDistributionEventV2> {
        self.pos_storage.get_reward_event(epoch).ok()
    }

    fn get_epoch_state(&self, block_id: &PosBlockId) -> EpochState {
        self.pos_storage
            .get_pos_state(&h256_to_diem_hash(block_id))
            .expect("parent of an ending_epoch block")
            .epoch_state()
            .clone()
    }

    fn pos_ledger_db(&self) -> &Arc<PosLedgerDB> { &self.pos_storage }

    fn consensus_db(&self) -> &Arc<ConsensusDB> { &self.consensus_db }

    fn cached_db(&self) -> &Arc<CachedPosLedgerDB> { &self.pos_cache_db }
}

pub struct PosConfiguration {
    pub bls_key: ConfigKey<ConsensusPrivateKey>,
    pub vrf_key: ConfigKey<ConsensusVRFPrivateKey>,
    pub diem_conf_path: Option<String>,
    pub protocol_conf: ProtocolConfiguration,
    pub pos_initial_nodes_path: String,
    pub vrf_proposal_threshold: U256,
    pub pos_state_config: PosStateConfig,
}

fn diem_hash_to_h256(h: &HashValue) -> PosBlockId { H256::from(h.as_ref()) }
fn h256_to_diem_hash(h: &PosBlockId) -> HashValue {
    HashValue::new(h.to_fixed_bytes())
}

pub fn save_initial_nodes_to_file(path: &str, genesis_nodes: GenesisPosState) {
    fs::write(path, serde_json::to_string(&genesis_nodes).unwrap()).unwrap();
}

pub fn read_initial_nodes_from_file(
    path: &str,
) -> Result<GenesisPosState, String> {
    let mut file = fs::File::open(path)
        .map_err(|e| format!("failed to open initial nodes file: {:?}", e))?;

    let mut nodes_str = String::new();
    file.read_to_string(&mut nodes_str)
        .map_err(|e| format!("failed to read initial nodes file: {:?}", e))?;

    serde_json::from_str(nodes_str.as_str())
        .map_err(|e| format!("failed to parse initial nodes file: {:?}", e))
}