ledger

package
v0.0.0-...-76c1feb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 1, 2021 License: AGPL-3.0 Imports: 50 Imported by: 0

README

Ledger

The ledger represents the state of an Algorand node. The core state of the ledger is a sequence of blocks (the blockchain). The ledger also maintains several trackers: state machines that consume the blockchain as input. One example of a tracker is the account state tracker, which keeps track of the state of individual accounts (balance, status, etc).

The external API for the ledger (for use by callers outside of this package) is defined in ledger.go.

Blocks

The ledger exposes the following functions for managing the blocks:

  • AddBlock(block, cert) adds a new block to the ledger, along with a certificate for that block. The ledger does not check the certificate's validity. If the block is not from the correct round (i.e., latest known plus one), an error is returned. The block is added to an in-memory queue of pending blocks, and is flushed to disk in the background for performance.

  • WaitForCommit(round) waits for the block for round to be written to persistent storage. After WaitForCommit(round) returns, the ledger guarantees that the block will be present even after a crash.

  • Latest() returns the last block added to the ledger.

  • LatestCommitted() returns the last block written to durable storage as well as the round of the latest block added to the ledger.

  • Block(round) returns the block for round, or ErrNoEntry if no such block has been added. Similarly, BlockCert(round) will return the block and the associated certificate.

  • Wait(round) allows the caller to wait for a block to be added to the ledger for round, by returning a channel that will be closed when a block for round is added.

Tracker API

The ledger comes with a set of trackers. Each tracker maintains a state machine based on the blockchain contents. Trackers are logically stateless: that is, they can reconstruct their state by consuming all blocks from the beginning of the blockchain. As an optimization, the ledger allows trackers to store persistent state, so that they can reconstruct their state quickly, without considering every block.

The interface between ledger and trackers is defined in trackers.go.

Trackers have access to the ledger through a restricted API defined by ledgerForTracker. This allows trackers to access the ledger's SQLite database, to query for blocks, etc.

Conversely, the ledger accesses trackers through the ledgerTracker interface:

  • loadFromDisk(ledgerForTracker) initializes the state of the tracker. The tracker can use the ledgerForTracker argument to load persistent state (e.g., for the accounts database). The tracker can also query for recent blocks, if the tracker's state depends only on recent blocks (e.g., for the tracker that keeps track of the recently committed transactions).

  • newBlock(rnd, delta) tells the tracker about a new block added to the ledger. delta describes the changes made by this block; this will be described in more details under block evaluation later.

  • committedUpTo(rnd) tells the tracker that all blocks up to and including rnd are written to persistent storage. This call is important for trackers that store persistent state themselves, since the tracker must be able to restore its state correctly after a crash, and may need to answer queries about older blocks after a crash if some recent non-committed blocks are lost.

  • close() frees up any resources held by this tracker.

The ledger serializes all updates to the trackers with a reader-writer lock.

Trackers

An individual tracker exposes tracker-specific APIs for accessing the state maintained by that tracker. These are currently passed through the Ledger object, so that the ledger can provide appropriate reader-writer locking.

Account tracker
  • Lookup(round, address) uses the account tracker to look up the state of an account as of round.

  • AllBalances(round) uses the account tracker to return the set of all account states as of round. This is likely to be large, so it's intended for debug purposes only.

  • Totals(round) returns the totals of accounts, using the account tracker.

Time tracker
  • Timestamp(round) uses the time tracker to return the time as of round.
Recent transactions tracker
  • Committed(txnid) returns whether txid has been recently committed, using the transaction tail tracker.
Participation tracker
  • ParticipationThresholds() returns the participation thresholds, from the participation tracker.
Delegator tracker
  • DumpDelegatorsTree() returns the tree of delegators for offline rewards, from the delegator tracker, for debug purposes.
Notification tracker
  • RegisterBlockListeners(listeners) registers listeners for new blocks, based on the pools.BlockListener API.

Block evaluation

Finally, the ledger implements logic to evaluate blocks. It supports three functions:

  • Construct a new block, based on a pool of potential transactions and rewards, that will be valid. This is done by using the Ledger.StartEvaluator(hdr, txcache) method. This returns a BlockEvaluator, which can then accept tentative transactions and rewards (using BlockEvaluator.Transaction() and BlockEvaluator.Reward()). The caller can finalize the block by calling BlockEvaluator.GenerateBlock(). txcache represents a cache of previously verified transactions, to avoid repeated checking of transaction signatures.

  • Validate a block. This is done by calling Ledger.Validate(block, txcache). Under the covers, it executes the same logic using a BlockEvaluator.

  • Evaluate a block to produce a delta describing the changes that this block implies for all of the trackers. This is the delta passed to the newBlock() method of trackers.

Block evaluation also produces auxiliary state, evalAux, which describes the state needed to evaluate a block. Currently, this consists of the set of offline rewards. Computing evalAux may require access to past blocks or the old state of various state trackers (in particular, for the offline rewards, it requires access to the past state of the delegator tracker). However, given an evalAux, it is possible to evaluate the block. The BlockEvaluator computes the evalAux when first evaluating a block, and the ledger saves the evalAux state to re-evaluate the block after a crash as needed.

Documentation

Index

Constants

View Source
const (
	// CatchpointCatchupStateInactive is the common state for the catchpoint catchup - not active.
	CatchpointCatchupStateInactive = iota
	// CatchpointCatchupStateLedgerDownload indicates that we're downloading the ledger
	CatchpointCatchupStateLedgerDownload
	// CatchpointCatchupStateLastestBlockDownload indicates that we're download the latest block
	CatchpointCatchupStateLastestBlockDownload
	// CatchpointCatchupStateBlocksDownload indicates that we're downloading the blocks prior to the latest one ( total of MaxBalLookback blocks )
	CatchpointCatchupStateBlocksDownload
	// CatchpointCatchupStateSwitch indicates that we're switching to use the downloaded ledger/blocks content
	CatchpointCatchupStateSwitch
)
View Source
const (
	// BalancesPerCatchpointFileChunk defines the number of accounts that would be stored in each chunk in the catchpoint file.
	// note that the last chunk would typically be less than this number.
	BalancesPerCatchpointFileChunk = 512
)
View Source
const MaxInt = int((^uint(0)) >> 1)

MaxInt is the maximum int which might be int32 or int64

Variables

View Source
var ErrNoSpace = errors.New("block does not have space for transaction")

ErrNoSpace indicates insufficient space for transaction in block

View Source
var TrieMemoryConfig = merkletrie.MemoryConfig{
	NodesCountPerPage:         merkleCommitterNodesPerPage,
	CachedNodesCount:          trieCachedNodesCount,
	PageFillFactor:            0.95,
	MaxChildrenPagesThreshold: 64,
}

TrieMemoryConfig is the memory configuration setup used for the merkle trie.

Functions

func AcceptableCompactCertWeight

func AcceptableCompactCertWeight(votersHdr bookkeeping.BlockHeader, firstValid basics.Round, logger logging.Logger) uint64

AcceptableCompactCertWeight computes the acceptable signed weight of a compact cert if it were to appear in a transaction with a particular firstValid round. Earlier rounds require a smaller cert. votersHdr specifies the block that contains the Merkle commitment of the voters for this compact cert (and thus the compact cert is for votersHdr.Round() + CompactCertRounds).

logger must not be nil; use at least logging.Base()

func CompactCertParams

func CompactCertParams(votersHdr bookkeeping.BlockHeader, hdr bookkeeping.BlockHeader) (res compactcert.Params, err error)

CompactCertParams computes the parameters for building or verifying a compact cert for block hdr, using voters from block votersHdr.

func MakeDebugBalances

func MakeDebugBalances(l ledgerForCowBase, round basics.Round, proto protocol.ConsensusVersion, prevTimestamp int64) apply.Balances

MakeDebugBalances creates a ledger suitable for dryrun and debugger

Types

type BlockEvaluator

type BlockEvaluator struct {
	// contains filtered or unexported fields
}

BlockEvaluator represents an in-progress evaluation of a block against the ledger.

func (*BlockEvaluator) GenerateBlock

func (eval *BlockEvaluator) GenerateBlock() (*ValidatedBlock, error)

GenerateBlock produces a complete block from the BlockEvaluator. This is used during proposal to get an actual block that will be proposed, after feeding in tentative transactions into this block evaluator.

After a call to GenerateBlock, the BlockEvaluator can still be used to accept transactions. However, to guard against reuse, subsequent calls to GenerateBlock on the same BlockEvaluator will fail.

func (*BlockEvaluator) ResetTxnBytes

func (eval *BlockEvaluator) ResetTxnBytes()

ResetTxnBytes resets the number of bytes tracked by the BlockEvaluator to zero. This is a specialized operation used by the transaction pool to simulate the effect of putting pending transactions in multiple blocks.

func (*BlockEvaluator) Round

func (eval *BlockEvaluator) Round() basics.Round

Round returns the round number of the block being evaluated by the BlockEvaluator.

func (*BlockEvaluator) TestTransactionGroup

func (eval *BlockEvaluator) TestTransactionGroup(txgroup []transactions.SignedTxn) error

TestTransactionGroup performs basic duplicate detection and well-formedness checks on a transaction group, but does not actually add the transactions to the block evaluator, or modify the block evaluator state in any other visible way.

func (*BlockEvaluator) Transaction

func (eval *BlockEvaluator) Transaction(txn transactions.SignedTxn, ad transactions.ApplyData) error

Transaction tentatively adds a new transaction as part of this block evaluation. If the transaction cannot be added to the block without violating some constraints, an error is returned and the block evaluator state is unchanged.

func (*BlockEvaluator) TransactionGroup

func (eval *BlockEvaluator) TransactionGroup(txads []transactions.SignedTxnWithAD) error

TransactionGroup tentatively adds a new transaction group as part of this block evaluation. If the transaction group cannot be added to the block without violating some constraints, an error is returned and the block evaluator state is unchanged.

func (*BlockEvaluator) TxnCounter

func (eval *BlockEvaluator) TxnCounter() int

TxnCounter returns the number of transactions that have been added to the block evaluator so far.

type BlockListener

type BlockListener interface {
	OnNewBlock(block bookkeeping.Block, delta ledgercore.StateDelta)
}

BlockListener represents an object that needs to get notified on new blocks.

type CatchpointCatchupAccessor

type CatchpointCatchupAccessor interface {
	// GetState returns the current state of the catchpoint catchup
	GetState(ctx context.Context) (state CatchpointCatchupState, err error)

	// SetState set the state of the catchpoint catchup
	SetState(ctx context.Context, state CatchpointCatchupState) (err error)

	// GetLabel returns the current catchpoint catchup label
	GetLabel(ctx context.Context) (label string, err error)

	// SetLabel set the catchpoint catchup label
	SetLabel(ctx context.Context, label string) (err error)

	// ResetStagingBalances resets the current staging balances, preparing for a new set of balances to be added
	ResetStagingBalances(ctx context.Context, newCatchup bool) (err error)

	// ProgressStagingBalances deserialize the given bytes as a temporary staging balances
	ProgressStagingBalances(ctx context.Context, sectionName string, bytes []byte, progress *CatchpointCatchupAccessorProgress) (err error)

	// BuildMerkleTrie inserts the account hashes into the merkle trie
	BuildMerkleTrie(ctx context.Context, progressUpdates func(uint64)) (err error)

	// GetCatchupBlockRound returns the latest block round matching the current catchpoint
	GetCatchupBlockRound(ctx context.Context) (round basics.Round, err error)

	// VerifyCatchpoint verifies that the catchpoint is valid by reconstructing the label.
	VerifyCatchpoint(ctx context.Context, blk *bookkeeping.Block) (err error)

	// StoreBalancesRound calculates the balances round based on the first block and the associated consensus parameters, and
	// store that to the database
	StoreBalancesRound(ctx context.Context, blk *bookkeeping.Block) (err error)

	// StoreFirstBlock stores a single block to the blocks database.
	StoreFirstBlock(ctx context.Context, blk *bookkeeping.Block) (err error)

	// StoreBlock stores a single block to the blocks database.
	StoreBlock(ctx context.Context, blk *bookkeeping.Block) (err error)

	// FinishBlocks concludes the catchup of the blocks database.
	FinishBlocks(ctx context.Context, applyChanges bool) (err error)

	// EnsureFirstBlock ensure that we have a single block in the staging block table, and returns that block
	EnsureFirstBlock(ctx context.Context) (blk bookkeeping.Block, err error)

	// CompleteCatchup completes the catchpoint catchup process by switching the databases tables around
	// and reloading the ledger.
	CompleteCatchup(ctx context.Context) (err error)
}

CatchpointCatchupAccessor is an interface for the accessor wrapping the database storage for the catchpoint catchup functionality.

func MakeCatchpointCatchupAccessor

func MakeCatchpointCatchupAccessor(ledger *Ledger, log logging.Logger) CatchpointCatchupAccessor

MakeCatchpointCatchupAccessor creates a CatchpointCatchupAccessor given a ledger

type CatchpointCatchupAccessorImpl

type CatchpointCatchupAccessorImpl struct {
	// contains filtered or unexported fields
}

CatchpointCatchupAccessorImpl is the concrete implementation of the CatchpointCatchupAccessor interface

func (*CatchpointCatchupAccessorImpl) BuildMerkleTrie

func (c *CatchpointCatchupAccessorImpl) BuildMerkleTrie(ctx context.Context, progressUpdates func(uint64)) (err error)

BuildMerkleTrie would process the catchpointpendinghashes and insert all the items in it into the merkle trie

func (*CatchpointCatchupAccessorImpl) CompleteCatchup

func (c *CatchpointCatchupAccessorImpl) CompleteCatchup(ctx context.Context) (err error)

CompleteCatchup completes the catchpoint catchup process by switching the databases tables around and reloading the ledger.

func (*CatchpointCatchupAccessorImpl) EnsureFirstBlock

func (c *CatchpointCatchupAccessorImpl) EnsureFirstBlock(ctx context.Context) (blk bookkeeping.Block, err error)

EnsureFirstBlock ensure that we have a single block in the staging block table, and returns that block

func (*CatchpointCatchupAccessorImpl) FinishBlocks

func (c *CatchpointCatchupAccessorImpl) FinishBlocks(ctx context.Context, applyChanges bool) (err error)

FinishBlocks concludes the catchup of the blocks database.

func (*CatchpointCatchupAccessorImpl) GetCatchupBlockRound

func (c *CatchpointCatchupAccessorImpl) GetCatchupBlockRound(ctx context.Context) (round basics.Round, err error)

GetCatchupBlockRound returns the latest block round matching the current catchpoint

func (*CatchpointCatchupAccessorImpl) GetLabel

func (c *CatchpointCatchupAccessorImpl) GetLabel(ctx context.Context) (label string, err error)

GetLabel returns the current catchpoint catchup label

func (*CatchpointCatchupAccessorImpl) GetState

GetState returns the current state of the catchpoint catchup

func (*CatchpointCatchupAccessorImpl) ProgressStagingBalances

func (c *CatchpointCatchupAccessorImpl) ProgressStagingBalances(ctx context.Context, sectionName string, bytes []byte, progress *CatchpointCatchupAccessorProgress) (err error)

ProgressStagingBalances deserialize the given bytes as a temporary staging balances

func (*CatchpointCatchupAccessorImpl) ResetStagingBalances

func (c *CatchpointCatchupAccessorImpl) ResetStagingBalances(ctx context.Context, newCatchup bool) (err error)

ResetStagingBalances resets the current staging balances, preparing for a new set of balances to be added

func (*CatchpointCatchupAccessorImpl) SetLabel

func (c *CatchpointCatchupAccessorImpl) SetLabel(ctx context.Context, label string) (err error)

SetLabel set the catchpoint catchup label

func (*CatchpointCatchupAccessorImpl) SetState

SetState set the state of the catchpoint catchup

func (*CatchpointCatchupAccessorImpl) StoreBalancesRound

func (c *CatchpointCatchupAccessorImpl) StoreBalancesRound(ctx context.Context, blk *bookkeeping.Block) (err error)

StoreBalancesRound calculates the balances round based on the first block and the associated consensus parameters, and store that to the database

func (*CatchpointCatchupAccessorImpl) StoreBlock

func (c *CatchpointCatchupAccessorImpl) StoreBlock(ctx context.Context, blk *bookkeeping.Block) (err error)

StoreBlock stores a single block to the blocks database.

func (*CatchpointCatchupAccessorImpl) StoreFirstBlock

func (c *CatchpointCatchupAccessorImpl) StoreFirstBlock(ctx context.Context, blk *bookkeeping.Block) (err error)

StoreFirstBlock stores a single block to the blocks database.

func (*CatchpointCatchupAccessorImpl) VerifyCatchpoint

func (c *CatchpointCatchupAccessorImpl) VerifyCatchpoint(ctx context.Context, blk *bookkeeping.Block) (err error)

VerifyCatchpoint verifies that the catchpoint is valid by reconstructing the label.

type CatchpointCatchupAccessorProgress

type CatchpointCatchupAccessorProgress struct {
	TotalAccounts     uint64
	ProcessedAccounts uint64
	ProcessedBytes    uint64
	TotalChunks       uint64
	SeenHeader        bool
	// contains filtered or unexported fields
}

CatchpointCatchupAccessorProgress is used by the caller of ProgressStagingBalances to obtain progress information

type CatchpointCatchupState

type CatchpointCatchupState int32

CatchpointCatchupState is the state of the current catchpoint catchup process

func (CatchpointCatchupState) CanMarshalMsg

func (_ CatchpointCatchupState) CanMarshalMsg(z interface{}) bool

func (*CatchpointCatchupState) CanUnmarshalMsg

func (_ *CatchpointCatchupState) CanUnmarshalMsg(z interface{}) bool

func (CatchpointCatchupState) MarshalMsg

func (z CatchpointCatchupState) MarshalMsg(b []byte) (o []byte)

MarshalMsg implements msgp.Marshaler

func (CatchpointCatchupState) MsgIsZero

func (z CatchpointCatchupState) MsgIsZero() bool

MsgIsZero returns whether this is a zero value

func (CatchpointCatchupState) Msgsize

func (z CatchpointCatchupState) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*CatchpointCatchupState) UnmarshalMsg

func (z *CatchpointCatchupState) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type CatchpointFileHeader

type CatchpointFileHeader struct {
	Version           uint64                   `codec:"version"`
	BalancesRound     basics.Round             `codec:"balancesRound"`
	BlocksRound       basics.Round             `codec:"blocksRound"`
	Totals            ledgercore.AccountTotals `codec:"accountTotals"`
	TotalAccounts     uint64                   `codec:"accountsCount"`
	TotalChunks       uint64                   `codec:"chunksCount"`
	Catchpoint        string                   `codec:"catchpoint"`
	BlockHeaderDigest crypto.Digest            `codec:"blockHeaderDigest"`
	// contains filtered or unexported fields
}

CatchpointFileHeader is the content we would have in the "content.msgpack" file in the catchpoint tar archive. we need it to be public, as it's being decoded externally by the catchpointdump utility.

func (*CatchpointFileHeader) CanMarshalMsg

func (_ *CatchpointFileHeader) CanMarshalMsg(z interface{}) bool

func (*CatchpointFileHeader) CanUnmarshalMsg

func (_ *CatchpointFileHeader) CanUnmarshalMsg(z interface{}) bool

func (*CatchpointFileHeader) MarshalMsg

func (z *CatchpointFileHeader) MarshalMsg(b []byte) (o []byte)

MarshalMsg implements msgp.Marshaler

func (*CatchpointFileHeader) MsgIsZero

func (z *CatchpointFileHeader) MsgIsZero() bool

MsgIsZero returns whether this is a zero value

func (*CatchpointFileHeader) Msgsize

func (z *CatchpointFileHeader) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*CatchpointFileHeader) UnmarshalMsg

func (z *CatchpointFileHeader) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type InitState

type InitState struct {
	Block       bookkeeping.Block
	Accounts    map[basics.Address]basics.AccountData
	GenesisHash crypto.Digest
}

InitState structure defines blockchain init params

type InputEvaluator

type InputEvaluator struct {
}

type Ledger

type Ledger struct {
	// contains filtered or unexported fields
}

Ledger is a database storing the contents of the ledger.

func OpenLedger

func OpenLedger(
	log logging.Logger, dbPathPrefix string, dbMem bool, genesisInitState InitState, cfg config.Local,
) (*Ledger, error)

OpenLedger creates a Ledger object, using SQLite database filenames based on dbPathPrefix (in-memory if dbMem is true). genesisInitState.Blocks and genesisInitState.Accounts specify the initial blocks and accounts to use if the database wasn't initialized before.

func (*Ledger) AddBlock

func (l *Ledger) AddBlock(blk bookkeeping.Block, cert agreement.Certificate) error

AddBlock adds a new block to the ledger. The block is stored in an in-memory queue and is written to the disk in the background. An error is returned if this is not the expected next block number.

func (*Ledger) AddValidatedBlock

func (l *Ledger) AddValidatedBlock(vb ValidatedBlock, cert agreement.Certificate) error

AddValidatedBlock adds a new block to the ledger, after the block has been validated by calling Ledger.Validate(). This saves the cost of having to re-compute the effect of the block on the ledger state, if the block has previously been validated. Otherwise, AddValidatedBlock behaves like AddBlock.

func (*Ledger) Block

func (l *Ledger) Block(rnd basics.Round) (blk bookkeeping.Block, err error)

Block returns the block for round rnd.

func (*Ledger) BlockCert

func (l *Ledger) BlockCert(rnd basics.Round) (blk bookkeeping.Block, cert agreement.Certificate, err error)

BlockCert returns the block and the certificate of the block for round rnd.

func (*Ledger) BlockHdr

func (l *Ledger) BlockHdr(rnd basics.Round) (blk bookkeeping.BlockHeader, err error)

BlockHdr returns the BlockHeader of the block for round rnd.

func (*Ledger) CheckDup

func (l *Ledger) CheckDup(currentProto config.ConsensusParams, current basics.Round, firstValid basics.Round, lastValid basics.Round, txid transactions.Txid, txl TxLease) error

CheckDup return whether a transaction is a duplicate one.

func (*Ledger) Close

func (l *Ledger) Close()

Close reclaims resources used by the ledger (namely, the database connection and goroutines used by trackers).

func (*Ledger) CompactCertVoters

func (l *Ledger) CompactCertVoters(rnd basics.Round) (voters *VotersForRound, err error)

CompactCertVoters returns the top online accounts at round rnd. The result might be nil, even with err=nil, if there are no voters for that round because compact certs were not enabled.

func (*Ledger) EncodedBlockCert

func (l *Ledger) EncodedBlockCert(rnd basics.Round) (blk []byte, cert []byte, err error)

EncodedBlockCert returns the encoded block and the corresponding encoded certificate of the block for round rnd.

func (*Ledger) GenesisHash

func (l *Ledger) GenesisHash() crypto.Digest

GenesisHash returns the genesis hash for this ledger.

func (*Ledger) GenesisProto

func (l *Ledger) GenesisProto() config.ConsensusParams

GenesisProto returns the initial protocol for this ledger.

func (*Ledger) GetCatchpointCatchupState

func (l *Ledger) GetCatchpointCatchupState(ctx context.Context) (state CatchpointCatchupState, err error)

GetCatchpointCatchupState returns the current state of the catchpoint catchup.

func (*Ledger) GetCatchpointStream

func (l *Ledger) GetCatchpointStream(round basics.Round) (ReadCloseSizer, error)

GetCatchpointStream returns a ReadCloseSizer file stream from which the catchpoint file for the provided round could be retrieved. If no such stream can be generated, a non-nil error is returned. The io.ReadCloser and the error are mutually exclusive - if error is returned, the file stream is guaranteed to be nil, and vice versa, if the file stream is not nil, the error is guaranteed to be nil.

func (*Ledger) GetCreator

func (l *Ledger) GetCreator(cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error)

GetCreator is like GetCreatorForRound, but for the latest round and race-free with respect to ledger.Latest()

func (*Ledger) GetCreatorForRound

func (l *Ledger) GetCreatorForRound(rnd basics.Round, cidx basics.CreatableIndex, ctype basics.CreatableType) (creator basics.Address, ok bool, err error)

GetCreatorForRound takes a CreatableIndex and a CreatableType and tries to look up a creator address, setting ok to false if the query succeeded but no creator was found.

func (*Ledger) GetLastCatchpointLabel

func (l *Ledger) GetLastCatchpointLabel() string

GetLastCatchpointLabel returns the latest catchpoint label that was written to the database.

func (*Ledger) GetRoundTxIds

func (l *Ledger) GetRoundTxIds(rnd basics.Round) (txMap map[transactions.Txid]bool)

GetRoundTxIds returns a map of the transactions ids that we have for the given round this function is currently not being used, but remains here as it might be useful in the future.

func (*Ledger) IsWritingCatchpointFile

func (l *Ledger) IsWritingCatchpointFile() bool

IsWritingCatchpointFile returns true when a catchpoint file is being generated. The function is used by the catchup service to avoid memory pressure until the catchpoint file writing is complete.

func (*Ledger) Latest

func (l *Ledger) Latest() basics.Round

Latest returns the latest known block round added to the ledger.

func (*Ledger) LatestCommitted

func (l *Ledger) LatestCommitted() (basics.Round, basics.Round)

LatestCommitted returns the last block round number written to persistent storage. This block, and all previous blocks, are guaranteed to be available after a crash. In addition, it returns the latest block round number added to the ledger ( which will be flushed to persistent storage later on )

func (*Ledger) ListApplications

func (l *Ledger) ListApplications(maxAppIdx basics.AppIndex, maxResults uint64) (results []basics.CreatableLocator, err error)

ListApplications takes a maximum app index and maximum result length, and returns up to that many CreatableLocators from the database where app idx is less than or equal to the maximum.

func (*Ledger) ListAssets

func (l *Ledger) ListAssets(maxAssetIdx basics.AssetIndex, maxResults uint64) (results []basics.CreatableLocator, err error)

ListAssets takes a maximum asset index and maximum result length, and returns up to that many CreatableLocators from the database where app idx is less than or equal to the maximum.

func (*Ledger) Lookup

func (l *Ledger) Lookup(rnd basics.Round, addr basics.Address) (basics.AccountData, error)

Lookup uses the accounts tracker to return the account state for a given account in a particular round. The account values reflect the changes of all blocks up to and including rnd.

func (*Ledger) LookupWithoutRewards

func (l *Ledger) LookupWithoutRewards(rnd basics.Round, addr basics.Address) (basics.AccountData, basics.Round, error)

LookupWithoutRewards is like Lookup but does not apply pending rewards up to the requested round rnd.

func (*Ledger) RegisterBlockListeners

func (l *Ledger) RegisterBlockListeners(listeners []BlockListener)

RegisterBlockListeners registers listeners that will be called when a new block is added to the ledger.

func (*Ledger) StartEvaluator

func (l *Ledger) StartEvaluator(hdr bookkeeping.BlockHeader, paysetHint int) (*BlockEvaluator, error)

StartEvaluator creates a BlockEvaluator, given a ledger and a block header of the block that the caller is planning to evaluate. If the length of the payset being evaluated is known in advance, a paysetHint >= 0 can be passed, avoiding unnecessary payset slice growth.

func (*Ledger) Timestamp

func (l *Ledger) Timestamp(r basics.Round) (int64, error)

Timestamp uses the timestamp tracker to return the timestamp from block r.

func (*Ledger) Totals

func (l *Ledger) Totals(rnd basics.Round) (ledgercore.AccountTotals, error)

Totals returns the totals of all accounts at the end of round rnd.

func (*Ledger) Validate

func (l *Ledger) Validate(ctx context.Context, blk bookkeeping.Block, executionPool execpool.BacklogPool) (*ValidatedBlock, error)

Validate uses the ledger to validate block blk as a candidate next block. It returns an error if blk is not the expected next block, or if blk is not a valid block (e.g., it has duplicate transactions, overspends some account, etc).

func (*Ledger) VerifiedTransactionCache

func (l *Ledger) VerifiedTransactionCache() verify.VerifiedTransactionCache

VerifiedTransactionCache returns the verify.VerifiedTransactionCache

func (*Ledger) Wait

func (l *Ledger) Wait(r basics.Round) chan struct{}

Wait returns a channel that closes once a given round is stored durably in the ledger. When <-l.Wait(r) finishes, ledger is guaranteed to have round r, and will not lose round r after a crash. This makes it easy to use in a select{} statement.

func (*Ledger) WaitForCommit

func (l *Ledger) WaitForCommit(r basics.Round)

WaitForCommit waits until block r (and block before r) are durably written to disk.

type MerkleCommitter

type MerkleCommitter struct {
	// contains filtered or unexported fields
}

MerkleCommitter todo

func MakeMerkleCommitter

func MakeMerkleCommitter(tx *sql.Tx, staging bool) (mc *MerkleCommitter, err error)

MakeMerkleCommitter creates a MerkleCommitter object that implements the merkletrie.Committer interface allowing storing and loading merkletrie pages from a sqlite database.

func (*MerkleCommitter) LoadPage

func (mc *MerkleCommitter) LoadPage(page uint64) (content []byte, err error)

LoadPage is the merkletrie.Committer interface implementation, load a single page from a sqlite database table.

func (*MerkleCommitter) StorePage

func (mc *MerkleCommitter) StorePage(page uint64, content []byte) error

StorePage is the merkletrie.Committer interface implementation, stores a single page in a sqlite database table.

type MismatchingDatabaseRoundError

type MismatchingDatabaseRoundError struct {
	// contains filtered or unexported fields
}

MismatchingDatabaseRoundError is generated when we detect that the database round is different than the accountUpdates in-memory dbRound. This could happen normally when the database and the in-memory dbRound aren't synchronized. However, when we work in non-sync mode, we expect the database to be always synchronized with the in-memory data. When that condition is violated, this error is generated.

func (*MismatchingDatabaseRoundError) Error

type ReadCloseSizer

type ReadCloseSizer interface {
	io.ReadCloser
	Size() (int64, error)
}

ReadCloseSizer interface implements the standard io.Reader and io.Closer as well as supporting the Size() function that let the caller know what the size of the stream would be (in bytes).

type RoundOffsetError

type RoundOffsetError struct {
	// contains filtered or unexported fields
}

RoundOffsetError is an error for when requested round is behind earliest stored db entry

func (*RoundOffsetError) Error

func (e *RoundOffsetError) Error() string

type StaleDatabaseRoundError

type StaleDatabaseRoundError struct {
	// contains filtered or unexported fields
}

StaleDatabaseRoundError is generated when we detect that the database round is behind the accountUpdates in-memory dbRound. This should never happen, since we update the database first, and only upon a successful update we update the in-memory dbRound.

func (*StaleDatabaseRoundError) Error

func (e *StaleDatabaseRoundError) Error() string

type TxLease

type TxLease struct {
	ledgercore.Txlease
}

TxLease is an exported version of txlease

type ValidatedBlock

type ValidatedBlock struct {
	// contains filtered or unexported fields
}

ValidatedBlock represents the result of a block validation. It can be used to efficiently add the block to the ledger, without repeating the work of applying the block's changes to the ledger state.

func (ValidatedBlock) Block

func (vb ValidatedBlock) Block() bookkeeping.Block

Block returns the underlying Block for a ValidatedBlock.

func (ValidatedBlock) WithSeed

WithSeed returns a copy of the ValidatedBlock with a modified seed.

type VotersForRound

type VotersForRound struct {

	// Proto is the ConsensusParams for the round whose balances are reflected
	// in participants.
	Proto config.ConsensusParams

	// Participants is the array of top #CompactCertVoters online accounts
	// in this round, sorted by normalized balance (to make sure heavyweight
	// accounts are biased to the front).
	Participants participantsArray

	// AddrToPos specifies the position of a given account address (if present)
	// in the Participants array.  This allows adding a vote from a given account
	// to the certificate builder.
	AddrToPos map[basics.Address]uint64

	// Tree is a constructed Merkle tree of the Participants array.
	Tree *merklearray.Tree

	// TotalWeight is the sum of the weights from the Participants array.
	TotalWeight basics.MicroAlgos
	// contains filtered or unexported fields
}

VotersForRound tracks the top online voting accounts as of a particular round, along with a Merkle tree commitment to those voting accounts.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL