Struct grin_chain::Chain

source ·
pub struct Chain { /* private fields */ }
Expand description

Facade to the blockchain block processing pipeline and storage. Provides the current view of the TxHashSet according to the chain state. Also maintains locking for the pipeline to avoid conflicting processing.

Implementations§

source§

impl Chain

source

pub fn init( db_root: String, adapter: Arc<dyn ChainAdapter + Send + Sync>, genesis: Block, pow_verifier: fn(_: &BlockHeader) -> Result<(), Error>, archive_mode: bool ) -> Result<Chain, Error>

Initializes the blockchain and returns a new Chain instance. Does a check on the current chain head to make sure it exists and creates one based on the genesis block if necessary.

source

pub fn invalidate_header(&self, hash: Hash) -> Result<(), Error>

Add provided header hash to our “denylist”. The header corresponding to any “denied” hash will be rejected and the peer subsequently banned.

source

pub fn reset_chain_head<T: Into<Tip>>( &self, head: T, rewind_headers: bool ) -> Result<(), Error>

Reset both head and header_head to the provided header. Handles simple rewind and more complex fork scenarios. Used by the reset_chain_head owner api endpoint. Caller can choose not to rewind headers, which can be used during PIBD scenarios where it’s desirable to restart the PIBD process without re-downloading the header chain

source

pub fn reset_chain_head_to_genesis(&self) -> Result<(), Error>

wipes the chain head down to genesis, without attempting to rewind Used upon PIBD failure, where we want to keep the header chain but restart the output PMMRs from scratch

source

pub fn reset_prune_lists(&self) -> Result<(), Error>

Reset prune lists (when PIBD resets and rolls back the entire chain, the prune list needs to be manually wiped as it’s currently not included as part of rewind)

source

pub fn reset_pibd_head(&self) -> Result<(), Error>

Reset PIBD head

source

pub fn archive_mode(&self) -> bool

Are we running with archive_mode enabled?

source

pub fn header_pmmr(&self) -> Arc<RwLock<PMMRHandle<BlockHeader>>>

Return our shared header MMR handle.

source

pub fn txhashset(&self) -> Arc<RwLock<TxHashSet>>

Return our shared txhashset instance.

source

pub fn genesis(&self) -> BlockHeader

return genesis header

source

pub fn store(&self) -> Arc<ChainStore>

Shared store instance.

source

pub fn process_block( &self, b: Block, opts: Options ) -> Result<Option<Tip>, Error>

Processes a single block, then checks for orphans, processing those as well if they’re found

source

pub fn is_known(&self, header: &BlockHeader) -> Result<(), Error>

Quick check for “known” duplicate block up to and including current chain head. Returns an error if this block is “known”.

source

pub fn process_block_header( &self, bh: &BlockHeader, opts: Options ) -> Result<(), Error>

Process a block header received during “header first” propagation. Note: This will update header MMR and corresponding header_head if total work increases (on the header chain).

source

pub fn sync_block_headers( &self, headers: &[BlockHeader], sync_head: Tip, opts: Options ) -> Result<Option<Tip>, Error>

Attempt to add new headers to the header chain (or fork). This is only ever used during sync and is based on sync_head. We update header_head here if our total work increases. Returns the new sync_head (may temporarily diverge from header_head when syncing a long fork).

source

pub fn new_ctx<'a>( &self, opts: Options, batch: Batch<'a>, header_pmmr: &'a mut PMMRHandle<BlockHeader>, txhashset: &'a mut TxHashSet ) -> Result<BlockContext<'a>, Error>

Build a new block processing context.

source

pub fn is_orphan(&self, hash: &Hash) -> bool

Check if hash is for a known orphan.

source

pub fn orphans_evicted_len(&self) -> usize

Get the OrphanBlockPool accumulated evicted number of blocks

source

pub fn get_unspent( &self, commit: Commitment ) -> Result<Option<(OutputIdentifier, CommitPos)>, Error>

Returns Ok(Some((out, pos))) if output is unspent. Returns Ok(None) if output is spent. Returns Err if something went wrong beyond not finding the output.

source

pub fn get_unspent_output_at(&self, pos0: u64) -> Result<Output, Error>

Retrieves an unspent output using its PMMR position

source

pub fn validate_tx(&self, tx: &Transaction) -> Result<(), Error>

Validate the tx against the current UTXO set and recent kernels (NRD relative lock heights).

source

pub fn validate_inputs( &self, inputs: &Inputs ) -> Result<Vec<(OutputIdentifier, CommitPos)>, Error>

Validates inputs against the current utxo. Each input must spend an unspent output. Returns the vec of output identifiers and their pos of the outputs that would be spent by the inputs.

source

pub fn verify_coinbase_maturity(&self, inputs: &Inputs) -> Result<(), Error>

Verify we are not attempting to spend a coinbase output that has not yet sufficiently matured.

source

pub fn verify_tx_lock_height(&self, tx: &Transaction) -> Result<(), Error>

Verify that the tx has a lock_height that is less than or equal to the height of the next block.

source

pub fn validate(&self, fast_validation: bool) -> Result<(), Error>

Validate the current chain state.

source

pub fn set_prev_root_only(&self, header: &mut BlockHeader) -> Result<(), Error>

Sets prev_root on a brand new block header by applying the previous header to the header MMR.

source

pub fn set_txhashset_roots(&self, b: &mut Block) -> Result<(), Error>

Sets the txhashset roots on a brand new block by applying the block on the current txhashset state.

source

pub fn get_merkle_proof<T: AsRef<OutputIdentifier>>( &self, out_id: T, header: &BlockHeader ) -> Result<MerkleProof, Error>

Return a Merkle proof for the given commitment from the store.

source

pub fn get_merkle_proof_for_pos( &self, commit: Commitment ) -> Result<MerkleProof, Error>

Return a merkle proof valid for the current output pmmr state at the given pos

source

pub fn txhashset_read(&self, h: Hash) -> Result<(u64, u64, File), Error>

Provides a reading view into the current txhashset state as well as the required indexes for a consumer to rewind to a consistent state at the provided block hash.

source

pub fn segmenter(&self) -> Result<Segmenter, Error>

The segmenter is responsible for generation PIBD segments. We cache a segmenter instance based on the current archve period (new period every 12 hours). This allows us to efficiently generate bitmap segments for the current archive period.

It is a relatively expensive operation to initializa and cache a new segmenter instance as this involves rewinding the txhashet by approx 720 blocks (12 hours).

Caller is responsible for only doing this when required. Caller should verify a peer segment request is valid before calling this for example.

source

pub fn desegmenter( &self, archive_header: &BlockHeader ) -> Result<Arc<RwLock<Option<Desegmenter>>>, Error>

instantiate desegmenter (in same lazy fashion as segmenter, though this should not be as expensive an operation)

source

pub fn txhashset_archive_header(&self) -> Result<BlockHeader, Error>

To support the ability to download the txhashset from multiple peers in parallel, the peers must all agree on the exact binary representation of the txhashset. This means compacting and rewinding to the exact same header. Since compaction is a heavy operation, peers can agree to compact every 12 hours, and no longer support requesting arbitrary txhashsets. Here we return the header of the txhashset we are currently offering to peers.

source

pub fn txhashset_archive_header_header_only(&self) -> Result<BlockHeader, Error>

Return the Block Header at the txhashset horizon, considering only the contents of the header PMMR

source

pub fn fork_point(&self) -> Result<BlockHeader, Error>

Finds the “fork point” where header chain diverges from full block chain. If we are syncing this will correspond to the last full block where the next header is known but we do not yet have the full block. i.e. This is the last known full block and all subsequent blocks are missing.

source

pub fn check_txhashset_needed( &self, fork_point: &BlockHeader ) -> Result<bool, Error>

Compare fork point to our horizon. If beyond the horizon then we cannot sync via recent full blocks and we need a state (txhashset) sync.

source

pub fn clean_txhashset_sandbox(&self)

Clean the temporary sandbox folder

source

pub fn get_tmp_dir(&self) -> PathBuf

Specific tmp dir. Normally it’s ~/.grin/main/tmp for mainnet or ~/.grin/test/tmp for Testnet

source

pub fn get_tmpfile_pathname(&self, tmpfile_name: String) -> PathBuf

Get a tmp file path in above specific tmp dir (create tmp dir if not exist) Delete file if tmp file already exists

source

pub fn txhashset_write( &self, h: Hash, txhashset_data: File, status: &dyn TxHashsetWriteStatus ) -> Result<bool, Error>

Writes a reading view on a txhashset state that’s been provided to us. If we’re willing to accept that new state, the data stream will be read as a zip file, unzipped and the resulting state files should be rewound to the provided indexes.

source

pub fn compact(&self) -> Result<(), Error>

Triggers chain compaction.

  • compacts the txhashset based on current prune_list
  • removes historical blocks and associated data from the db (unless archive mode)
source

pub fn get_last_n_output(&self, distance: u64) -> Vec<(Hash, OutputIdentifier)>

returns the last n nodes inserted into the output sum tree

source

pub fn get_last_n_rangeproof(&self, distance: u64) -> Vec<(Hash, RangeProof)>

as above, for rangeproofs

source

pub fn get_last_n_kernel(&self, distance: u64) -> Vec<(Hash, TxKernel)>

as above, for kernels

source

pub fn get_output_pos(&self, commit: &Commitment) -> Result<u64, Error>

Return Commit’s MMR position

source

pub fn unspent_outputs_by_pmmr_index( &self, start_index: u64, max_count: u64, max_pmmr_index: Option<u64> ) -> Result<(u64, u64, Vec<Output>), Error>

outputs by insertion index

source

pub fn block_height_range_to_pmmr_indices( &self, start_block_height: u64, end_block_height: Option<u64> ) -> Result<(u64, u64), Error>

Return unspent outputs as above, but bounded between a particular range of blocks

source

pub fn orphans_len(&self) -> usize

Orphans pool size

source

pub fn head(&self) -> Result<Tip, Error>

Tip (head) of the block chain.

source

pub fn tail(&self) -> Result<Tip, Error>

Tail of the block chain in this node after compact (cross-block cut-through)

source

pub fn header_head(&self) -> Result<Tip, Error>

Tip (head) of the header chain.

source

pub fn head_header(&self) -> Result<BlockHeader, Error>

Block header for the chain head

source

pub fn get_block(&self, h: &Hash) -> Result<Block, Error>

Gets a block by hash

source

pub fn get_tail(&self) -> Result<Tip, Error>

Gets the earliest stored block (tail)

source

pub fn get_block_header(&self, h: &Hash) -> Result<BlockHeader, Error>

Gets a block header by hash

source

pub fn get_previous_header( &self, header: &BlockHeader ) -> Result<BlockHeader, Error>

Get previous block header.

source

pub fn get_block_sums(&self, h: &Hash) -> Result<BlockSums, Error>

Get block_sums by header hash.

source

pub fn get_header_by_height(&self, height: u64) -> Result<BlockHeader, Error>

Gets the block header at the provided height. Note: Takes a read lock on the header_pmmr.

source

pub fn get_header_for_output( &self, commit: Commitment ) -> Result<BlockHeader, Error>

Gets the block header in which a given output appears in the txhashset.

source

pub fn get_kernel_height( &self, excess: &Commitment, min_height: Option<u64>, max_height: Option<u64> ) -> Result<Option<(TxKernel, u64, u64)>, Error>

Gets the kernel with a given excess and the block height it is included in.

source

pub fn get_header_for_kernel_index( &self, kernel_mmr_index: u64, min_height: Option<u64>, max_height: Option<u64> ) -> Result<BlockHeader, Error>

Gets the block header in which a given kernel mmr index appears in the txhashset.

source

pub fn get_locator_hashes( &self, sync_head: Tip, heights: &[u64] ) -> Result<Vec<Hash>, Error>

Gets multiple headers at the provided heights. Note: This is based on the provided sync_head to support syncing against a fork.

source

pub fn difficulty_iter(&self) -> Result<DifficultyIter<'_>, Error>

Builds an iterator on blocks starting from the current chain head and running backward. Specialized to return information pertaining to block difficulty calculation (timestamp and previous difficulties).

source

pub fn block_exists(&self, h: Hash) -> Result<bool, Error>

Check whether we have a block without reading it

Auto Trait Implementations§

§

impl Freeze for Chain

§

impl !RefUnwindSafe for Chain

§

impl Send for Chain

§

impl Sync for Chain

§

impl Unpin for Chain

§

impl !UnwindSafe for Chain

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> SafeBorrow<T> for T
where T: ?Sized,

source§

fn borrow_replacement(ptr: &T) -> &T

Given ptr, which was obtained from a prior call to Self::borrow(), return a value with the same nominal lifetime which is guaranteed to survive mutations to Self. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> UnsafeAny for T
where T: Any,