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
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![forbid(unsafe_code)]
#![allow(clippy::too_many_arguments)]
// #![warn(clippy::cast_possible_truncation)]
#![cfg_attr(test, allow(clippy::single_element_loop))]

pub mod header;
pub use header::*;

mod helpers;
pub use helpers::*;

pub mod ratifications;
pub use ratifications::*;

pub mod ratify;
pub use ratify::*;

pub mod transaction;
pub use transaction::*;

pub mod transactions;
pub use transactions::*;

pub mod transition;
pub use transition::*;

mod bytes;
mod genesis;
mod serialize;
mod string;
mod verify;

use console::{
    account::PrivateKey,
    network::prelude::*,
    program::{Ciphertext, Record},
    types::{Field, Group, U64},
};
use ledger_authority::Authority;
use ledger_coinbase::{CoinbaseSolution, ProverSolution, PuzzleCommitment};
use ledger_committee::Committee;
use ledger_narwhal_subdag::Subdag;
use ledger_narwhal_transmission_id::TransmissionID;

#[derive(Clone, PartialEq, Eq)]
pub struct Block<N: Network> {
    /// The hash of this block.
    block_hash: N::BlockHash,
    /// The hash of the previous block.
    previous_hash: N::BlockHash,
    /// The header of this block.
    header: Header<N>,
    /// The authority for this block.
    authority: Authority<N>,
    /// The ratifications in this block.
    ratifications: Ratifications<N>,
    /// The solutions in the block.
    solutions: Option<CoinbaseSolution<N>>,
    /// The transactions in this block.
    transactions: Transactions<N>,
    /// The aborted transaction IDs in this block.
    aborted_transaction_ids: Vec<N::TransactionID>,
}

impl<N: Network> Block<N> {
    /// Initializes a new beacon block from the given previous block hash, block header,
    /// ratifications, solutions, transactions, and aborted transaction IDs.
    pub fn new_beacon<R: Rng + CryptoRng>(
        private_key: &PrivateKey<N>,
        previous_hash: N::BlockHash,
        header: Header<N>,
        ratifications: Ratifications<N>,
        solutions: Option<CoinbaseSolution<N>>,
        transactions: Transactions<N>,
        aborted_transaction_ids: Vec<N::TransactionID>,
        rng: &mut R,
    ) -> Result<Self> {
        // Compute the block hash.
        let block_hash = N::hash_bhp1024(&to_bits_le![previous_hash, header.to_root()?])?;
        // Construct the beacon authority.
        let authority = Authority::new_beacon(private_key, block_hash, rng)?;
        // Construct the block.
        Self::from(previous_hash, header, authority, ratifications, solutions, transactions, aborted_transaction_ids)
    }

    /// Initializes a new quorum block from the given previous block hash, block header,
    /// subdag, ratifications, solutions, transactions, and aborted transaction IDs.
    pub fn new_quorum(
        previous_hash: N::BlockHash,
        header: Header<N>,
        subdag: Subdag<N>,
        ratifications: Ratifications<N>,
        solutions: Option<CoinbaseSolution<N>>,
        transactions: Transactions<N>,
        aborted_transaction_ids: Vec<N::TransactionID>,
    ) -> Result<Self> {
        // Construct the beacon authority.
        let authority = Authority::new_quorum(subdag);
        // Construct the block.
        Self::from(previous_hash, header, authority, ratifications, solutions, transactions, aborted_transaction_ids)
    }

    /// Initializes a new block from the given previous block hash, block header,
    /// authority, ratifications, solutions, transactions, and aborted transaction IDs.
    pub fn from(
        previous_hash: N::BlockHash,
        header: Header<N>,
        authority: Authority<N>,
        ratifications: Ratifications<N>,
        solutions: Option<CoinbaseSolution<N>>,
        transactions: Transactions<N>,
        aborted_transaction_ids: Vec<N::TransactionID>,
    ) -> Result<Self> {
        // Ensure the block contains transactions.
        ensure!(!transactions.is_empty(), "Cannot create a block with zero transactions");

        // Ensure the number of transactions is within the allowed range.
        if transactions.len() > Transactions::<N>::MAX_TRANSACTIONS {
            bail!(
                "Cannot initialize a block with more than {} confirmed transactions",
                Transactions::<N>::MAX_TRANSACTIONS
            );
        }

        // Ensure the number of aborted transaction IDs is within the allowed range.
        if aborted_transaction_ids.len() > Transactions::<N>::MAX_TRANSACTIONS {
            bail!(
                "Cannot initialize a block with more than {} aborted transaction IDs",
                Transactions::<N>::MAX_TRANSACTIONS
            );
        }

        // Compute the block hash.
        let block_hash = N::hash_bhp1024(&to_bits_le![previous_hash, header.to_root()?])?;

        // Verify the authority.
        match &authority {
            Authority::Beacon(signature) => {
                // Derive the signer address.
                let address = signature.to_address();
                // Ensure the signature is valid.
                ensure!(signature.verify(&address, &[block_hash]), "Invalid signature for block {}", header.height());
            }
            Authority::Quorum(subdag) => {
                // Ensure the transmission IDs from the subdag correspond to the block.
                Self::check_subdag_transmissions(subdag, &solutions, &transactions, &aborted_transaction_ids)?;
            }
        }

        // Ensure that coinbase accumulator matches the solutions.
        let solutions_root = match &solutions {
            Some(coinbase_solution) => coinbase_solution.to_accumulator_point()?,
            None => Field::<N>::zero(),
        };
        if header.solutions_root() != solutions_root {
            bail!("The solutions root in the block does not correspond to the solutions");
        }

        // Ensure that the subdag root matches the authority.
        let subdag_root = match &authority {
            Authority::Beacon(_) => Field::<N>::zero(),
            Authority::Quorum(subdag) => subdag.to_subdag_root()?,
        };
        if header.subdag_root() != subdag_root {
            bail!("The subdag root in the block does not correspond to the authority");
        }

        // Return the block.
        Self::from_unchecked(
            block_hash.into(),
            previous_hash,
            header,
            authority,
            ratifications,
            solutions,
            transactions,
            aborted_transaction_ids,
        )
    }

    /// Initializes a new block from the given block hash, previous block hash, block header,
    /// authority, ratifications, solutions, transactions, and aborted transaction IDs.
    pub fn from_unchecked(
        block_hash: N::BlockHash,
        previous_hash: N::BlockHash,
        header: Header<N>,
        authority: Authority<N>,
        ratifications: Ratifications<N>,
        solutions: Option<CoinbaseSolution<N>>,
        transactions: Transactions<N>,
        aborted_transaction_ids: Vec<N::TransactionID>,
    ) -> Result<Self> {
        // Return the block.
        Ok(Self {
            block_hash,
            previous_hash,
            header,
            authority,
            transactions,
            ratifications,
            solutions,
            aborted_transaction_ids,
        })
    }
}

impl<N: Network> Block<N> {
    /// Returns the block hash.
    pub const fn hash(&self) -> N::BlockHash {
        self.block_hash
    }

    /// Returns the previous block hash.
    pub const fn previous_hash(&self) -> N::BlockHash {
        self.previous_hash
    }

    /// Returns the authority.
    pub const fn authority(&self) -> &Authority<N> {
        &self.authority
    }

    /// Returns the ratifications in this block.
    pub const fn ratifications(&self) -> &Ratifications<N> {
        &self.ratifications
    }

    /// Returns the solutions in the block.
    pub const fn solutions(&self) -> Option<&CoinbaseSolution<N>> {
        self.solutions.as_ref()
    }

    /// Returns the transactions in this block.
    pub const fn transactions(&self) -> &Transactions<N> {
        &self.transactions
    }

    /// Returns the aborted transaction IDs in this block.
    pub const fn aborted_transaction_ids(&self) -> &Vec<N::TransactionID> {
        &self.aborted_transaction_ids
    }
}

impl<N: Network> Block<N> {
    /// Returns the block header.
    pub const fn header(&self) -> &Header<N> {
        &self.header
    }

    /// Returns the previous state root from the block header.
    pub const fn previous_state_root(&self) -> N::StateRoot {
        self.header.previous_state_root()
    }

    /// Returns the transactions root in the block header.
    pub const fn transactions_root(&self) -> Field<N> {
        self.header.transactions_root()
    }

    /// Returns the finalize root in the block header.
    pub const fn finalize_root(&self) -> Field<N> {
        self.header.finalize_root()
    }

    /// Returns the ratifications root in the block header.
    pub const fn ratifications_root(&self) -> Field<N> {
        self.header.ratifications_root()
    }

    /// Returns the solutions root in the block header.
    pub const fn solutions_root(&self) -> Field<N> {
        self.header.solutions_root()
    }

    /// Returns the metadata in the block header.
    pub const fn metadata(&self) -> &Metadata<N> {
        self.header.metadata()
    }

    /// Returns the network ID of this block.
    pub const fn network(&self) -> u16 {
        self.header.network()
    }

    /// Returns the height of this block.
    pub const fn height(&self) -> u32 {
        self.header.height()
    }

    /// Returns the round number of this block.
    pub const fn round(&self) -> u64 {
        self.header.round()
    }

    /// Returns the epoch number of this block.
    pub const fn epoch_number(&self) -> u32 {
        self.height() / N::NUM_BLOCKS_PER_EPOCH
    }

    /// Returns the cumulative weight for this block.
    pub const fn cumulative_weight(&self) -> u128 {
        self.header.cumulative_weight()
    }

    /// Returns the cumulative proof target for this block.
    pub const fn cumulative_proof_target(&self) -> u128 {
        self.header.cumulative_proof_target()
    }

    /// Returns the coinbase target for this block.
    pub const fn coinbase_target(&self) -> u64 {
        self.header.coinbase_target()
    }

    /// Returns the proof target for this block.
    pub const fn proof_target(&self) -> u64 {
        self.header.proof_target()
    }

    /// Returns the coinbase target of the last coinbase.
    pub const fn last_coinbase_target(&self) -> u64 {
        self.header.last_coinbase_target()
    }

    /// Returns the block timestamp of the last coinbase.
    pub const fn last_coinbase_timestamp(&self) -> i64 {
        self.header.last_coinbase_timestamp()
    }

    /// Returns the Unix timestamp (UTC) for this block.
    pub const fn timestamp(&self) -> i64 {
        self.header.timestamp()
    }
}

impl<N: Network> Block<N> {
    /// Returns `true` if the block contains the given transition ID.
    pub fn contains_transition(&self, transition_id: &N::TransitionID) -> bool {
        self.transactions.contains_transition(transition_id)
    }

    /// Returns `true` if the block contains the given serial number.
    pub fn contains_serial_number(&self, serial_number: &Field<N>) -> bool {
        self.transactions.contains_serial_number(serial_number)
    }

    /// Returns `true` if the block contains the given commitment.
    pub fn contains_commitment(&self, commitment: &Field<N>) -> bool {
        self.transactions.contains_commitment(commitment)
    }
}

impl<N: Network> Block<N> {
    /// Returns the solution with the given solution ID, if it exists.
    pub fn get_solution(&self, puzzle_commitment: &PuzzleCommitment<N>) -> Option<&ProverSolution<N>> {
        self.solutions.as_ref().and_then(|solution| solution.get_solution(puzzle_commitment))
    }

    /// Returns the transaction with the given transaction ID, if it exists.
    pub fn get_transaction(&self, transaction_id: &N::TransactionID) -> Option<&Transaction<N>> {
        self.transactions.get(transaction_id).map(|t| t.deref())
    }

    /// Returns the confirmed transaction with the given transaction ID, if it exists.
    pub fn get_confirmed_transaction(&self, transaction_id: &N::TransactionID) -> Option<&ConfirmedTransaction<N>> {
        self.transactions.get(transaction_id)
    }
}

impl<N: Network> Block<N> {
    /// Returns the transaction with the given transition ID, if it exists.
    pub fn find_transaction_for_transition_id(&self, transition_id: &N::TransitionID) -> Option<&Transaction<N>> {
        self.transactions.find_transaction_for_transition_id(transition_id)
    }

    /// Returns the transaction with the given serial number, if it exists.
    pub fn find_transaction_for_serial_number(&self, serial_number: &Field<N>) -> Option<&Transaction<N>> {
        self.transactions.find_transaction_for_serial_number(serial_number)
    }

    /// Returns the transaction with the given commitment, if it exists.
    pub fn find_transaction_for_commitment(&self, commitment: &Field<N>) -> Option<&Transaction<N>> {
        self.transactions.find_transaction_for_commitment(commitment)
    }

    /// Returns the transition with the corresponding transition ID, if it exists.
    pub fn find_transition(&self, transition_id: &N::TransitionID) -> Option<&Transition<N>> {
        self.transactions.find_transition(transition_id)
    }

    /// Returns the transition for the given serial number, if it exists.
    pub fn find_transition_for_serial_number(&self, serial_number: &Field<N>) -> Option<&Transition<N>> {
        self.transactions.find_transition_for_serial_number(serial_number)
    }

    /// Returns the transition for the given commitment, if it exists.
    pub fn find_transition_for_commitment(&self, commitment: &Field<N>) -> Option<&Transition<N>> {
        self.transactions.find_transition_for_commitment(commitment)
    }

    /// Returns the record with the corresponding commitment, if it exists.
    pub fn find_record(&self, commitment: &Field<N>) -> Option<&Record<N, Ciphertext<N>>> {
        self.transactions.find_record(commitment)
    }
}

impl<N: Network> Block<N> {
    /// Returns the puzzle commitments in this block.
    pub fn puzzle_commitments(&self) -> Option<impl '_ + Iterator<Item = &PuzzleCommitment<N>>> {
        self.solutions.as_ref().map(|solution| solution.puzzle_commitments())
    }

    /// Returns an iterator over the transaction IDs, for all transactions in `self`.
    pub fn transaction_ids(&self) -> impl '_ + Iterator<Item = &N::TransactionID> {
        self.transactions.transaction_ids()
    }

    /// Returns an iterator over all transactions in `self` that are accepted deploy transactions.
    pub fn deployments(&self) -> impl '_ + Iterator<Item = &ConfirmedTransaction<N>> {
        self.transactions.deployments()
    }

    /// Returns an iterator over all transactions in `self` that are accepted execute transactions.
    pub fn executions(&self) -> impl '_ + Iterator<Item = &ConfirmedTransaction<N>> {
        self.transactions.executions()
    }

    /// Returns an iterator over all transitions.
    pub fn transitions(&self) -> impl '_ + Iterator<Item = &Transition<N>> {
        self.transactions.transitions()
    }

    /// Returns an iterator over the transition IDs, for all transitions.
    pub fn transition_ids(&self) -> impl '_ + Iterator<Item = &N::TransitionID> {
        self.transactions.transition_ids()
    }

    /// Returns an iterator over the transition public keys, for all transactions.
    pub fn transition_public_keys(&self) -> impl '_ + Iterator<Item = &Group<N>> {
        self.transactions.transition_public_keys()
    }

    /// Returns an iterator over the transition commitments, for all transactions.
    pub fn transition_commitments(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.transition_commitments()
    }

    /// Returns an iterator over the tags, for all transition inputs that are records.
    pub fn tags(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.tags()
    }

    /// Returns an iterator over the input IDs, for all transition inputs that are records.
    pub fn input_ids(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.input_ids()
    }

    /// Returns an iterator over the serial numbers, for all transition inputs that are records.
    pub fn serial_numbers(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.serial_numbers()
    }

    /// Returns an iterator over the output IDs, for all transition inputs that are records.
    pub fn output_ids(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.output_ids()
    }

    /// Returns an iterator over the commitments, for all transition outputs that are records.
    pub fn commitments(&self) -> impl '_ + Iterator<Item = &Field<N>> {
        self.transactions.commitments()
    }

    /// Returns an iterator over the records, for all transition outputs that are records.
    pub fn records(&self) -> impl '_ + Iterator<Item = (&Field<N>, &Record<N, Ciphertext<N>>)> {
        self.transactions.records()
    }

    /// Returns an iterator over the nonces, for all transition outputs that are records.
    pub fn nonces(&self) -> impl '_ + Iterator<Item = &Group<N>> {
        self.transactions.nonces()
    }

    /// Returns an iterator over the transaction fee amounts, for all transactions.
    pub fn transaction_fee_amounts(&self) -> impl '_ + Iterator<Item = Result<U64<N>>> {
        self.transactions.transaction_fee_amounts()
    }
}

impl<N: Network> Block<N> {
    /// Returns a consuming iterator over the transaction IDs, for all transactions in `self`.
    pub fn into_transaction_ids(self) -> impl Iterator<Item = N::TransactionID> {
        self.transactions.into_transaction_ids()
    }

    /// Returns a consuming iterator over all transactions in `self` that are accepted deploy transactions.
    pub fn into_deployments(self) -> impl Iterator<Item = ConfirmedTransaction<N>> {
        self.transactions.into_deployments()
    }

    /// Returns a consuming iterator over all transactions in `self` that are accepted execute transactions.
    pub fn into_executions(self) -> impl Iterator<Item = ConfirmedTransaction<N>> {
        self.transactions.into_executions()
    }

    /// Returns a consuming iterator over all transitions.
    pub fn into_transitions(self) -> impl Iterator<Item = Transition<N>> {
        self.transactions.into_transitions()
    }

    /// Returns a consuming iterator over the transition IDs, for all transitions.
    pub fn into_transition_ids(self) -> impl Iterator<Item = N::TransitionID> {
        self.transactions.into_transition_ids()
    }

    /// Returns a consuming iterator over the transition public keys, for all transactions.
    pub fn into_transition_public_keys(self) -> impl Iterator<Item = Group<N>> {
        self.transactions.into_transition_public_keys()
    }

    /// Returns a consuming iterator over the tags, for all transition inputs that are records.
    pub fn into_tags(self) -> impl Iterator<Item = Field<N>> {
        self.transactions.into_tags()
    }

    /// Returns a consuming iterator over the serial numbers, for all transition inputs that are records.
    pub fn into_serial_numbers(self) -> impl Iterator<Item = Field<N>> {
        self.transactions.into_serial_numbers()
    }

    /// Returns a consuming iterator over the commitments, for all transition outputs that are records.
    pub fn into_commitments(self) -> impl Iterator<Item = Field<N>> {
        self.transactions.into_commitments()
    }

    /// Returns a consuming iterator over the records, for all transition outputs that are records.
    pub fn into_records(self) -> impl Iterator<Item = (Field<N>, Record<N, Ciphertext<N>>)> {
        self.transactions.into_records()
    }

    /// Returns a consuming iterator over the nonces, for all transition outputs that are records.
    pub fn into_nonces(self) -> impl Iterator<Item = Group<N>> {
        self.transactions.into_nonces()
    }
}

#[cfg(test)]
pub mod test_helpers {
    use super::*;
    use console::account::{Address, PrivateKey};
    use ledger_query::Query;
    use ledger_store::{helpers::memory::BlockMemory, BlockStore};
    use synthesizer_process::Process;

    use once_cell::sync::OnceCell;

    type CurrentNetwork = console::network::Testnet3;
    type CurrentAleo = circuit::network::AleoV0;

    /// Samples a random genesis block.
    pub(crate) fn sample_genesis_block(rng: &mut TestRng) -> Block<CurrentNetwork> {
        // Sample the genesis block and components.
        let (block, _, _) = sample_genesis_block_and_components(rng);
        // Return the block.
        block
    }

    /// Samples a random genesis block and the transaction from the genesis block.
    pub(crate) fn sample_genesis_block_and_transaction(
        rng: &mut TestRng,
    ) -> (Block<CurrentNetwork>, Transaction<CurrentNetwork>) {
        // Sample the genesis block and components.
        let (block, transaction, _) = sample_genesis_block_and_components(rng);
        // Return the block and transaction.
        (block, transaction)
    }

    /// Samples a random genesis block, the transaction from the genesis block, and the genesis private key.
    pub(crate) fn sample_genesis_block_and_components(
        rng: &mut TestRng,
    ) -> (Block<CurrentNetwork>, Transaction<CurrentNetwork>, PrivateKey<CurrentNetwork>) {
        static INSTANCE: OnceCell<(Block<CurrentNetwork>, Transaction<CurrentNetwork>, PrivateKey<CurrentNetwork>)> =
            OnceCell::new();
        INSTANCE.get_or_init(|| sample_genesis_block_and_components_raw(rng)).clone()
    }

    /// Samples a random genesis block, the transaction from the genesis block, and the genesis private key.
    fn sample_genesis_block_and_components_raw(
        rng: &mut TestRng,
    ) -> (Block<CurrentNetwork>, Transaction<CurrentNetwork>, PrivateKey<CurrentNetwork>) {
        // Sample the genesis private key.
        let private_key = PrivateKey::new(rng).unwrap();
        let address = Address::<CurrentNetwork>::try_from(private_key).unwrap();

        // Prepare the locator.
        let locator = ("credits.aleo", "transfer_public_to_private");
        // Prepare the amount for each call to the function.
        let amount = 100_000_000u64;
        // Prepare the function inputs.
        let inputs = [address.to_string(), format!("{amount}_u64")];

        // Initialize the process.
        let process = Process::load().unwrap();
        // Authorize the function.
        let authorization =
            process.authorize::<CurrentAleo, _>(&private_key, locator.0, locator.1, inputs.iter(), rng).unwrap();
        // Execute the function.
        let (_, mut trace) = process.execute::<CurrentAleo, _>(authorization, rng).unwrap();

        // Initialize a new block store.
        let block_store = BlockStore::<CurrentNetwork, BlockMemory<_>>::open(None).unwrap();

        // Prepare the assignments.
        trace.prepare(Query::from(block_store)).unwrap();
        // Compute the proof and construct the execution.
        let execution = trace.prove_execution::<CurrentAleo, _>(locator.0, rng).unwrap();
        // Convert the execution.
        // Note: This is a testing-only hack to adhere to Rust's dependency cycle rules.
        let execution = Execution::from_str(&execution.to_string()).unwrap();

        // Construct the transaction.
        let transaction = Transaction::from_execution(execution, None).unwrap();
        // Prepare the confirmed transaction.
        let confirmed = ConfirmedTransaction::accepted_execute(0, transaction.clone(), vec![]).unwrap();
        // Prepare the transactions.
        let transactions = Transactions::from_iter([confirmed].into_iter());

        // Construct the ratifications.
        let ratifications = Ratifications::try_from(vec![]).unwrap();

        // Prepare the block header.
        let header = Header::genesis(&ratifications, &transactions, vec![]).unwrap();
        // Prepare the previous block hash.
        let previous_hash = <CurrentNetwork as Network>::BlockHash::default();

        // Construct the block.
        let block =
            Block::new_beacon(&private_key, previous_hash, header, ratifications, None, transactions, vec![], rng)
                .unwrap();
        assert!(block.header().is_genesis(), "Failed to initialize a genesis block");
        // Return the block, transaction, and private key.
        (block, transaction, private_key)
    }
}

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

    use indexmap::IndexMap;

    #[test]
    fn test_find_transaction_for_transition_id() {
        let rng = &mut TestRng::default();

        let (block, transaction) = crate::test_helpers::sample_genesis_block_and_transaction(rng);
        let transactions = block.transactions();

        // Retrieve the transitions.
        let transitions = transaction.transitions().collect::<Vec<_>>();
        assert!(!transitions.is_empty());

        // Ensure the transaction is found.
        for transition in transitions {
            assert_eq!(block.find_transaction_for_transition_id(transition.id()), Some(&transaction));
            assert_eq!(transactions.find_transaction_for_transition_id(transition.id()), Some(&transaction));
        }

        // Ensure the transaction is not found.
        for _ in 0..10 {
            let transition_id = &rng.gen();
            assert_eq!(block.find_transaction_for_transition_id(transition_id), None);
            assert_eq!(transactions.find_transaction_for_transition_id(transition_id), None);
        }
    }

    #[test]
    fn test_find_transaction_for_commitment() {
        let rng = &mut TestRng::default();

        let (block, transaction) = crate::test_helpers::sample_genesis_block_and_transaction(rng);
        let transactions = block.transactions();

        // Retrieve the commitments.
        let commitments = transaction.commitments().collect::<Vec<_>>();
        assert!(!commitments.is_empty());

        // Ensure the commitments are found.
        for commitment in commitments {
            assert_eq!(block.find_transaction_for_commitment(commitment), Some(&transaction));
            assert_eq!(transactions.find_transaction_for_commitment(commitment), Some(&transaction));
        }

        // Ensure the commitments are not found.
        for _ in 0..10 {
            let commitment = &rng.gen();
            assert_eq!(block.find_transaction_for_commitment(commitment), None);
            assert_eq!(transactions.find_transaction_for_commitment(commitment), None);
        }
    }

    #[test]
    fn test_find_transition() {
        let rng = &mut TestRng::default();

        let (block, transaction) = crate::test_helpers::sample_genesis_block_and_transaction(rng);
        let transactions = block.transactions();

        // Retrieve the transitions.
        let transitions = transaction.transitions().collect::<Vec<_>>();
        assert!(!transitions.is_empty());

        // Ensure the transitions are found.
        for transition in transitions {
            assert_eq!(block.find_transition(transition.id()), Some(transition));
            assert_eq!(transactions.find_transition(transition.id()), Some(transition));
            assert_eq!(transaction.find_transition(transition.id()), Some(transition));
        }

        // Ensure the transitions are not found.
        for _ in 0..10 {
            let transition_id = &rng.gen();
            assert_eq!(block.find_transition(transition_id), None);
            assert_eq!(transactions.find_transition(transition_id), None);
            assert_eq!(transaction.find_transition(transition_id), None);
        }
    }

    #[test]
    fn test_find_transition_for_commitment() {
        let rng = &mut TestRng::default();

        let (block, transaction) = crate::test_helpers::sample_genesis_block_and_transaction(rng);
        let transactions = block.transactions();

        // Retrieve the transitions.
        let transitions = transaction.transitions().collect::<Vec<_>>();
        assert!(!transitions.is_empty());

        for transition in transitions {
            // Retrieve the commitments.
            let commitments = transition.commitments().collect::<Vec<_>>();
            assert!(!commitments.is_empty());

            // Ensure the commitments are found.
            for commitment in commitments {
                assert_eq!(block.find_transition_for_commitment(commitment), Some(transition));
                assert_eq!(transactions.find_transition_for_commitment(commitment), Some(transition));
                assert_eq!(transaction.find_transition_for_commitment(commitment), Some(transition));
            }
        }

        // Ensure the commitments are not found.
        for _ in 0..10 {
            let commitment = &rng.gen();
            assert_eq!(block.find_transition_for_commitment(commitment), None);
            assert_eq!(transactions.find_transition_for_commitment(commitment), None);
            assert_eq!(transaction.find_transition_for_commitment(commitment), None);
        }
    }

    #[test]
    fn test_find_record() {
        let rng = &mut TestRng::default();

        let (block, transaction) = crate::test_helpers::sample_genesis_block_and_transaction(rng);
        let transactions = block.transactions();

        // Retrieve the records.
        let records = transaction.records().collect::<IndexMap<_, _>>();
        assert!(!records.is_empty());

        // Ensure the records are found.
        for (commitment, record) in records {
            assert_eq!(block.find_record(commitment), Some(record));
            assert_eq!(transactions.find_record(commitment), Some(record));
            assert_eq!(transaction.find_record(commitment), Some(record));
        }

        // Ensure the records are not found.
        for _ in 0..10 {
            let commitment = &rng.gen();
            assert_eq!(block.find_record(commitment), None);
            assert_eq!(transactions.find_record(commitment), None);
            assert_eq!(transaction.find_record(commitment), None);
        }
    }
}