clementine_core/database/
header_chain_prover.rs

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
//! # Header Chain Prover Related Database Operations
//!
//! This module includes database functions which are mainly used by the header
//! chain prover.

use super::{
    wrapper::{BlockHashDB, BlockHeaderDB},
    Database, DatabaseTransaction,
};
use crate::{errors::BridgeError, execute_query_with_tx, extended_rpc::ExtendedRpc};
use bitcoin::{
    block::{self, Header},
    BlockHash,
};
use eyre::Context;
use risc0_zkvm::Receipt;

impl Database {
    /// Adds a new finalized block to the database, later to be updated with a
    /// proof.
    pub async fn save_unproven_finalized_block(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        block_hash: block::BlockHash,
        block_header: block::Header,
        block_height: u64,
    ) -> Result<(), BridgeError> {
        let query = sqlx::query(
                "INSERT INTO header_chain_proofs (block_hash, block_header, prev_block_hash, height) VALUES ($1, $2, $3, $4)
                ON CONFLICT (block_hash) DO NOTHING",
            )
            .bind(BlockHashDB(block_hash)).bind(BlockHeaderDB(block_header)).bind(BlockHashDB(block_header.prev_blockhash)).bind(block_height as i64);

        execute_query_with_tx!(self.connection, tx, query, execute)?;

        Ok(())
    }

    /// Collect block info from rpc and save it to hcp table.
    async fn save_block_infos_within_range(
        &self,
        rpc: &ExtendedRpc,
        height_start: u32,
        height_end: u32,
    ) -> Result<(), BridgeError> {
        const BATCH_SIZE: u32 = 100;

        for batch_start in (height_start..=height_end).step_by(BATCH_SIZE as usize) {
            let batch_end = std::cmp::min(batch_start + BATCH_SIZE - 1, height_end);

            // Collect all block headers in this batch
            let mut block_infos = Vec::with_capacity((batch_end - batch_start + 1) as usize);
            for height in batch_start..=batch_end {
                let (block_hash, block_header) =
                    rpc.get_block_info_by_height(height as u64).await?;
                block_infos.push((block_hash, block_header, height));
            }

            // Save all blocks in this batch
            let mut db_tx = self.begin_transaction().await?;
            for (block_hash, block_header, height) in block_infos {
                self.save_unproven_finalized_block(
                    Some(&mut db_tx),
                    block_hash,
                    block_header,
                    height as u64,
                )
                .await?;
            }
            db_tx.commit().await?;
        }
        Ok(())
    }

    /// This function assumes there are no blocks or some contiguous blocks starting from 0 already in the table.
    /// Saves the block hashes and headers until given height(exclusive)
    /// as they are needed for spv and hcp proofs.
    pub async fn fetch_and_save_missing_blocks(
        &self,
        rpc: &ExtendedRpc,
        genesis_height: u32,
        until_height: u32,
    ) -> Result<(), BridgeError> {
        if until_height == 0 {
            return Ok(());
        }
        let max_height = self.get_latest_finalized_block_height(None).await?;
        if let Some(max_height) = max_height {
            if max_height < until_height as u64 {
                self.save_block_infos_within_range(rpc, max_height as u32 + 1, until_height - 1)
                    .await?;
            }
        } else {
            tracing::debug!("Saving blocks from start until {}", until_height);
            self.save_block_infos_within_range(rpc, genesis_height, until_height - 1)
                .await?;
        }
        Ok(())
    }

    /// Returns block hash and header for a given range of heights. Ranges are
    /// inclusive on both ends.
    pub async fn get_block_info_from_range(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        start_height: u64,
        end_height: u64,
    ) -> Result<Vec<(BlockHash, Header)>, BridgeError> {
        let query = sqlx::query_as(
            "SELECT block_hash, block_header
            FROM header_chain_proofs
            WHERE height >= $1 AND height <= $2
            ORDER BY height ASC;",
        )
        .bind(start_height as i64)
        .bind(end_height as i64);

        let result: Vec<(BlockHashDB, BlockHeaderDB)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_all)?;

        let result = result
            .iter()
            .map(|result| (result.0 .0, result.1 .0))
            .collect::<Vec<_>>();

        Ok(result)
    }

    /// Returns the previous block hash and header for a given block hash.
    ///
    /// # Returns
    ///
    /// Returns `None` if the block hash is not found.
    ///
    /// - [`BlockHash`] - Previous block's hash
    /// - [`Header`] - Block's header
    /// - [`u32`] - Block's height
    pub async fn get_block_info_from_hash_hcp(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        block_hash: BlockHash,
    ) -> Result<Option<(BlockHash, Header, u32)>, BridgeError> {
        let query = sqlx::query_as(
            "SELECT prev_block_hash, block_header, height FROM header_chain_proofs WHERE block_hash = $1",
        )
        .bind(BlockHashDB(block_hash));
        let result: Option<(BlockHashDB, BlockHeaderDB, i64)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_optional)?;
        result
            .map(|result| -> Result<(BlockHash, Header, u32), BridgeError> {
                let height = result.2.try_into().wrap_err("Can't convert i64 to u32")?;
                Ok((result.0 .0, result.1 .0, height))
            })
            .transpose()
    }

    /// Returns latest finalized blocks height from the database.
    pub async fn get_latest_finalized_block_height(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
    ) -> Result<Option<u64>, BridgeError> {
        let query =
            sqlx::query_as("SELECT height FROM header_chain_proofs ORDER BY height DESC LIMIT 1;");

        let result: Option<(i64,)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_optional)?;

        Ok(result.map(|height| height.0 as u64))
    }

    /// Gets the first finalized block after the latest proven block (i.e. proof != null).
    /// This block will be the candidate block for the prover.
    ///
    /// # Returns
    ///
    /// Returns `None` if either no proved blocks are exists or blockchain tip
    /// is already proven.
    ///
    /// - [`BlockHash`] - Hash of the block
    /// - [`Header`] - Header of the block
    /// - [`u64`] - Height of the block
    /// - [`Receipt`] - Previous block's proof
    pub async fn get_next_unproven_block(
        &self,
        mut tx: Option<DatabaseTransaction<'_, '_>>,
    ) -> Result<Option<(BlockHash, Header, u64, Receipt)>, BridgeError> {
        let latest_proven_block_height = self
            .get_latest_proven_block_info(tx.as_deref_mut())
            .await?
            .map(|(_, _, height)| height);

        let query = sqlx::query_as(
            "SELECT h1.block_hash,
                    h1.block_header,
                    h1.height,
                    h2.proof
                FROM header_chain_proofs h1
                JOIN header_chain_proofs h2 ON h1.prev_block_hash = h2.block_hash
                WHERE h2.proof IS NOT NULL AND h1.proof IS NULL
                ORDER BY h1.height DESC
                LIMIT 1",
        );

        let result: Option<(BlockHashDB, BlockHeaderDB, i64, Vec<u8>)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_optional)?;

        let result = match result {
            Some(result) => {
                let receipt: Receipt =
                    borsh::from_slice(&result.3).wrap_err(BridgeError::BorshError)?;
                let height: u64 = result.2.try_into().wrap_err("Can't convert i64 to u64")?;
                Some((result.0 .0, result.1 .0, height, receipt))
            }
            None => None,
        };

        // If the latest block is already proven, return None instead of the old
        // unproven block.
        if let (Some((_, _, height, _)), Some(latest_proven_block_height)) =
            (&result, latest_proven_block_height)
        {
            if *height < latest_proven_block_height {
                return Ok(None);
            }
        }

        Ok(result)
    }

    /// Gets the newest n number of block's info that their previous block has
    /// proven before. These blocks will be the candidate blocks for the prover.
    ///
    /// # Returns
    ///
    /// Returns `None` if either no proved blocks are exists or blockchain tip
    /// is already proven.
    ///
    /// - [`BlockHash`] - Hash of last block in the batch
    /// - [`Header`] - Headers of the blocks
    /// - [`u64`] - Height of the last block in the batch
    /// - [`Receipt`] - Previous block's proof
    pub async fn get_next_n_non_proven_block(
        &self,
        count: u32,
    ) -> Result<Option<(Vec<(BlockHash, Header, u64)>, Receipt)>, BridgeError> {
        let Some(next_non_proven_block) = self.get_next_unproven_block(None).await? else {
            return Ok(None);
        };

        let query = sqlx::query_as(
            "SELECT block_hash,
                    block_header,
                    height
                FROM header_chain_proofs
                WHERE height >= $1
                ORDER BY height ASC
                LIMIT $2;",
        )
        .bind(next_non_proven_block.2 as i64)
        .bind(count as i64);
        let result: Vec<(BlockHashDB, BlockHeaderDB, i64)> = execute_query_with_tx!(
            self.connection,
            None::<DatabaseTransaction>,
            query,
            fetch_all
        )?;

        let blocks = result
            .iter()
            .map(|result| {
                let height = result.2.try_into().wrap_err("Can't convert i64 to u64")?;

                Ok((result.0 .0, result.1 .0, height))
            })
            .collect::<Result<Vec<_>, BridgeError>>()?;

        // If not yet enough entries are found, return `None`.
        if blocks.len() != count as usize {
            tracing::error!(
                "Non proven block count: {}, required count: {}",
                blocks.len(),
                count
            );
            return Ok(None);
        }

        Ok(Some((blocks, next_non_proven_block.3)))
    }

    /// Gets the latest block's info that it's proven.
    ///
    /// # Returns
    ///
    /// Returns `None` if no block is proven.
    ///
    /// - [`BlockHash`] - Hash of the block
    /// - [`Header`] - Header of the block
    /// - [`u64`] - Height of the block
    pub async fn get_latest_proven_block_info(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
    ) -> Result<Option<(BlockHash, Header, u64)>, BridgeError> {
        let query = sqlx::query_as(
            "SELECT block_hash, block_header, height
            FROM header_chain_proofs
            WHERE proof IS NOT NULL
            ORDER BY height DESC
            LIMIT 1;",
        );

        let result: Option<(BlockHashDB, BlockHeaderDB, i64)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_optional)?;

        let result = match result {
            Some(result) => {
                let height = result.2.try_into().wrap_err("Can't convert i64 to u64")?;
                Some((result.0 .0, result.1 .0, height))
            }
            None => None,
        };

        Ok(result)
    }

    /// Gets the latest block's info that it's proven and has height less than or equal to the given height.
    ///
    /// # Returns
    ///
    /// Returns `None` if no block is proven.
    ///
    /// - [`BlockHash`] - Hash of the block
    /// - [`Header`] - Header of the block
    /// - [`u64`] - Height of the block
    pub async fn get_latest_proven_block_info_until_height(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        height: u32,
    ) -> Result<Option<(BlockHash, Header, u64)>, BridgeError> {
        let query = sqlx::query_as(
            "SELECT block_hash, block_header, height
            FROM header_chain_proofs
            WHERE proof IS NOT NULL AND height <= $1
            ORDER BY height DESC
            LIMIT 1;",
        )
        .bind(height as i64);

        let result: Option<(BlockHashDB, BlockHeaderDB, i64)> =
            execute_query_with_tx!(self.connection, tx, query, fetch_optional)?;

        let result = match result {
            Some(result) => {
                let height = result.2.try_into().wrap_err("Can't convert i64 to u64")?;
                Some((result.0 .0, result.1 .0, height))
            }
            None => None,
        };

        Ok(result)
    }

    /// Sets an existing block's (in database) proof by referring to it by it's
    /// hash.
    pub async fn set_block_proof(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        hash: block::BlockHash,
        proof: Receipt,
    ) -> Result<(), BridgeError> {
        let proof = borsh::to_vec(&proof).wrap_err(BridgeError::BorshError)?;

        let query = sqlx::query("UPDATE header_chain_proofs SET proof = $1 WHERE block_hash = $2")
            .bind(proof)
            .bind(BlockHashDB(hash));

        execute_query_with_tx!(self.connection, tx, query, execute)?;

        Ok(())
    }

    /// Gets a block's proof by referring to it by it's hash.
    pub async fn get_block_proof_by_hash(
        &self,
        tx: Option<DatabaseTransaction<'_, '_>>,
        hash: block::BlockHash,
    ) -> Result<Option<Receipt>, BridgeError> {
        let query = sqlx::query_as("SELECT proof FROM header_chain_proofs WHERE block_hash = $1")
            .bind(BlockHashDB(hash));

        let receipt: (Option<Vec<u8>>,) =
            execute_query_with_tx!(self.connection, tx, query, fetch_one)?;
        let receipt = match receipt.0 {
            Some(r) => r,
            None => return Ok(None),
        };

        let receipt: Receipt = borsh::from_slice(&receipt).wrap_err(BridgeError::BorshError)?;

        Ok(Some(receipt))
    }
}

#[cfg(test)]
mod tests {
    use crate::database::Database;
    use crate::test::common::*;
    use bitcoin::block::{self, Header, Version};
    use bitcoin::hashes::Hash;
    use bitcoin::{BlockHash, CompactTarget, TxMerkleNode};
    use borsh::BorshDeserialize;
    use risc0_zkvm::Receipt;

    #[tokio::test]
    async fn save_get_new_block() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();

        assert!(db
            .get_latest_finalized_block_height(None)
            .await
            .unwrap()
            .is_none());

        // Set first block, so that get_non_proven_block won't return error.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0,
                bits: CompactTarget::default(),
                nonce: 0,
            },
            txdata: vec![],
        };
        let block_hash = block.block_hash();
        let height = 1;
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();
        assert_eq!(
            db.get_latest_finalized_block_height(None)
                .await
                .unwrap()
                .unwrap(),
            height
        );
        let receipt = Receipt::try_from_slice(include_bytes!("../test/data/first_1.bin")).unwrap();
        db.set_block_proof(None, block_hash, receipt).await.unwrap();
        let latest_proven_block = db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(latest_proven_block.0, block_hash);
        assert_eq!(latest_proven_block.1, block.header);
        assert_eq!(latest_proven_block.2, height);

        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 1,
                bits: CompactTarget::default(),
                nonce: 1,
            },
            txdata: vec![],
        };
        let block_hash = block.block_hash();
        let height = 2;
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();

        let (read_block_hash, read_block_header, _, _) =
            db.get_next_unproven_block(None).await.unwrap().unwrap();
        assert_eq!(block_hash, read_block_hash);
        assert_eq!(block.header, read_block_header);
    }

    #[tokio::test]
    #[serial_test::serial]
    pub async fn save_get_block_proof() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();

        // Save dummy block.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45,
            },
            txdata: vec![],
        };
        let block_hash = block.block_hash();
        let height = 0x45;
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();

        // Requesting proof for an existing block without a proof should
        // return `None`.
        let read_receipt = db.get_block_proof_by_hash(None, block_hash).await.unwrap();
        assert!(read_receipt.is_none());

        // Update it with a proof.
        let receipt = Receipt::try_from_slice(include_bytes!("../test/data/first_1.bin")).unwrap();
        db.set_block_proof(None, block_hash, receipt.clone())
            .await
            .unwrap();

        let read_receipt = db
            .get_block_proof_by_hash(None, block_hash)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(receipt.journal, read_receipt.journal);
        assert_eq!(receipt.metadata, read_receipt.metadata);
    }

    #[tokio::test]
    #[serial_test::serial]
    pub async fn get_non_proven_block() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();

        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        let base_height = 0x45;

        // Save initial block without a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45,
            },
            txdata: vec![],
        };
        let block_hash = block.block_hash();
        let height = base_height;
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        // Save second block with a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45 + 1,
            },
            txdata: vec![],
        };
        let block_hash1 = block.block_hash();
        let height1 = base_height + 1;
        db.save_unproven_finalized_block(None, block_hash1, block.header, height1)
            .await
            .unwrap();
        let receipt = Receipt::try_from_slice(include_bytes!("../test/data/first_1.bin")).unwrap();
        db.set_block_proof(None, block_hash1, receipt.clone())
            .await
            .unwrap();
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        let latest_proven_block = db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(latest_proven_block.0, block_hash1);
        assert_eq!(latest_proven_block.1, block.header);
        assert_eq!(latest_proven_block.2 as u64, height1);

        // Save third block without a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash1,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45 + 3,
            },
            txdata: vec![],
        };
        let block_hash2 = block.block_hash();
        let height2 = base_height + 2;
        db.save_unproven_finalized_block(None, block_hash2, block.header, height2)
            .await
            .unwrap();

        // This time, `get_non_proven_block` should return third block's details.
        let res = db.get_next_unproven_block(None).await.unwrap().unwrap();
        assert_eq!(res.0, block_hash2);
        assert_eq!(res.2 as u64, height2);

        // Save fourth block with a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash1,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45 + 4,
            },
            txdata: vec![],
        };
        let block_hash3 = block.block_hash();
        let height3 = base_height + 3;
        db.save_unproven_finalized_block(None, block_hash3, block.header, height3)
            .await
            .unwrap();
        db.set_block_proof(None, block_hash3, receipt.clone())
            .await
            .unwrap();

        // This time, `get_non_proven_block` shouldn't return any block because latest is proved.
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());

        // Save fifth block without a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash1,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45 + 5,
            },
            txdata: vec![],
        };
        let block_hash4 = block.block_hash();
        let height4 = base_height + 4;
        db.save_unproven_finalized_block(None, block_hash4, block.header, height4)
            .await
            .unwrap();

        // This time, `get_non_proven_block` should return fifth block's details.
        let res = db.get_next_unproven_block(None).await.unwrap().unwrap();
        assert_eq!(res.2 as u64, height4);
        assert_eq!(res.0, block_hash4);
    }

    #[tokio::test]
    #[serial_test::serial]
    pub async fn get_non_proven_blocks() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();

        let batch_size = config.protocol_paramset().header_chain_proof_batch_size;

        assert!(db
            .get_next_n_non_proven_block(batch_size)
            .await
            .unwrap()
            .is_none());
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        let mut height = 0x45;

        // Save initial block without a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45,
            },
            txdata: vec![],
        };
        let block_hash = block.block_hash();
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();
        assert!(db
            .get_next_n_non_proven_block(batch_size)
            .await
            .unwrap()
            .is_none());
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        // Save second block with a proof.
        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: block_hash,
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45 + 1,
            },
            txdata: vec![],
        };
        let block_hash1 = block.block_hash();
        height += 1;
        db.save_unproven_finalized_block(None, block_hash1, block.header, height)
            .await
            .unwrap();
        let receipt = Receipt::try_from_slice(include_bytes!("../test/data/first_1.bin")).unwrap();
        db.set_block_proof(None, block_hash1, receipt.clone())
            .await
            .unwrap();
        assert!(db
            .get_next_n_non_proven_block(batch_size)
            .await
            .unwrap()
            .is_none());
        assert!(db.get_next_unproven_block(None).await.unwrap().is_none());
        let latest_proven_block = db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(latest_proven_block.0, block_hash1);
        assert_eq!(latest_proven_block.1, block.header);
        assert_eq!(latest_proven_block.2 as u64, height);

        // Save next blocks without a proof.
        let mut blocks: Vec<(BlockHash, u32)> = Vec::new();
        let mut prev_block_hash = block_hash1;
        for i in 0..batch_size {
            let block = block::Block {
                header: Header {
                    version: Version::TWO,
                    prev_blockhash: prev_block_hash,
                    merkle_root: TxMerkleNode::all_zeros(),
                    time: 0x1F,
                    bits: CompactTarget::default(),
                    nonce: 0x45 + 2 + i,
                },
                txdata: vec![],
            };
            let block_hash = block.block_hash();

            height += 1;
            prev_block_hash = block_hash;

            db.save_unproven_finalized_block(None, block_hash, block.header, height)
                .await
                .unwrap();

            blocks.push((block_hash, height.try_into().unwrap()));
        }

        // This time, `get_non_proven_block` should return third block's details.
        let res = db
            .get_next_n_non_proven_block(batch_size)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(res.0.len(), batch_size as usize);
        for i in 0..batch_size {
            let i = i as usize;
            assert_eq!(res.0[i].2, blocks[i].1 as u64);
            assert_eq!(res.0[i].0, blocks[i].0);
        }
    }

    #[tokio::test]
    async fn get_block_info_from_range() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();

        let start_height = 0x45;
        let end_height = 0x55;
        assert!(db
            .get_block_info_from_range(None, start_height, end_height)
            .await
            .unwrap()
            .is_empty());

        let mut infos = Vec::new();

        for height in start_height..end_height {
            let block = block::Block {
                header: Header {
                    version: Version::TWO,
                    prev_blockhash: BlockHash::all_zeros(),
                    merkle_root: TxMerkleNode::all_zeros(),
                    time: 0x1F,
                    bits: CompactTarget::default(),
                    nonce: height as u32,
                },
                txdata: vec![],
            };
            let block_hash = block.block_hash();

            db.save_unproven_finalized_block(None, block_hash, block.header, height)
                .await
                .unwrap();
            infos.push((block_hash, block.header));

            let res = db
                .get_block_info_from_range(None, start_height, height)
                .await
                .unwrap();
            assert_eq!(res.len() as u64, height - start_height + 1);
            assert_eq!(infos, res);
        }
    }

    #[tokio::test]
    async fn get_latest_proven_block_info() {
        let config = create_test_config_with_thread_name().await;
        let db = Database::new(&config).await.unwrap();
        let proof = Receipt::try_from_slice(include_bytes!("../test/data/first_1.bin")).unwrap();

        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        let block = block::Block {
            header: Header {
                version: Version::TWO,
                prev_blockhash: BlockHash::all_zeros(),
                merkle_root: TxMerkleNode::all_zeros(),
                time: 0x1F,
                bits: CompactTarget::default(),
                nonce: 0x45,
            },
            txdata: vec![],
        };
        let mut block_hash = block.block_hash();
        let mut height = 0x45;
        db.save_unproven_finalized_block(None, block_hash, block.header, height)
            .await
            .unwrap();
        assert!(db
            .get_latest_proven_block_info(None)
            .await
            .unwrap()
            .is_none());

        for i in 0..3 {
            let block = block::Block {
                header: Header {
                    version: Version::TWO,
                    prev_blockhash: block_hash,
                    merkle_root: TxMerkleNode::all_zeros(),
                    time: 0x1F,
                    bits: CompactTarget::default(),
                    nonce: 0x45 + i,
                },
                txdata: vec![],
            };
            block_hash = block.block_hash();
            height += 1;

            db.save_unproven_finalized_block(None, block_hash, block.header, height)
                .await
                .unwrap();
            db.set_block_proof(None, block_hash, proof.clone())
                .await
                .unwrap();

            let latest_proven_block = db
                .get_latest_proven_block_info(None)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(latest_proven_block.0, block_hash);
            assert_eq!(latest_proven_block.1, block.header);
            assert_eq!(latest_proven_block.2, height);
        }
    }
}