replay

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 67 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// NumConsecutiveLeaderSlots matches Solana's NUM_CONSECUTIVE_LEADER_SLOTS
	NumConsecutiveLeaderSlots = 4
	// MaxMismatchLogsPerEpoch caps mismatch logging to avoid disk churn
	MaxMismatchLogsPerEpoch = 100
	// SampleBoundarySlots is how many slots to check at epoch boundaries
	SampleBoundarySlots = 2000
	// SampleRandomSlots is how many random slots to sample in the middle
	SampleRandomSlots = 1000
	// MaxMissingVoteCacheStakePercent is the maximum percentage of stake that can be
	// missing from VoteCache before we fail. Since local schedule is the source of truth,
	// missing VoteCache entries mean that stake is dropped from the schedule, which would
	// produce an incorrect schedule.
	// Set to 0 for zero tolerance - any missing stake is a hard failure.
	// The VoteCache rebuild from AccountsDB should ensure this never triggers.
	MaxMissingVoteCacheStakePercent = 0.0
	// DefaultVoteCacheRebuildConcurrency is the default number of concurrent workers
	// for rebuilding vote cache from AccountsDB at epoch boundaries.
	DefaultVoteCacheRebuildConcurrency = 16
)

Variables

View Source
var (
	// Per-transaction account load stats (accounts referenced by tx execution)
	TxAcctsLoaded      atomic.Uint64 // Total accounts loaded into tx contexts
	TxAcctsLoadedBytes atomic.Uint64 // Total bytes referenced by tx contexts

	// Per-transaction copy-on-write clone stats (first write in TransactionAccounts.Touch)
	TxAcctsCloned      atomic.Uint64 // Total accounts cloned on first write
	TxAcctsClonedBytes atomic.Uint64 // Total bytes cloned on first write

	// Per-transaction modification stats (touched in handleModifiedAccounts)
	TxAcctsTouched      atomic.Uint64 // Total accounts actually modified
	TxAcctsTouchedBytes atomic.Uint64 // Total bytes of modified account data

	// Transaction count for averaging
	TxCount atomic.Uint64
)

Account clone tracking for profiling copy-on-write optimization potential

View Source
var (
	TxErrInsufficientFundsForRent          = errors.New("TxErrInsufficientFundsForRent")
	TxErrMaxLoadedAccountsDataSizeExceeded = errors.New("TxErrMaxLoadedAccountsDataSizeExceeded")
	TxErrProgramAccountNotFound            = errors.New("TxErrProgramAccountNotFound")
	TxErrInvalidProgramForExecution        = errors.New("TxErrInvalidProgramForExecution")
	TxErrInvalidBlockhash                  = errors.New("TxErrInvalidBlockhash")
	TxErrSanitizeFailure                   = errors.New("TxErrSanitizeFailure")
)
View Source
var CurrentRunID string

CurrentRunID is a unique identifier for this replay session, used to correlate logs

View Source
var ErrLeaderScheduleFailed = errors.New("leader schedule fetch failed from all RPC endpoints")

ErrLeaderScheduleFailed is returned when leader schedule cannot be fetched from any endpoint

View Source
var SerializedParameterArena *arena.Arena[byte]

Functions

func BackgroundValidateAgainstRPC

func BackgroundValidateAgainstRPC(
	epoch uint64,
	epochSchedule *sealevel.SysvarEpochSchedule,
	localSchedule *leaderschedule.LeaderSchedule,
	rpcSchedule *leaderschedule.LeaderSchedule,
	localSummary *ScheduleSummary,
	logsDir string,
)

BackgroundValidateAgainstRPC optionally validates local schedule against RPC in background. This is purely for debugging and does not affect the source of truth. Computes full SHA256 hash of entire schedule (~20-50ms) for complete comparison. Always writes a validation summary file with full local summary and RPC hash. Also dumps RPC-derived validator list for comparison.

func DumpLeaderSchedule

func DumpLeaderSchedule(
	epoch uint64,
	epochSchedule *sealevel.SysvarEpochSchedule,
	schedule *leaderschedule.LeaderSchedule,
	logsDir string,
	numSlots int,
)

DumpLeaderSchedule writes the first N slots of the schedule to a file for debugging. File is written to logsDir/leader_schedule_dump_epoch<N>.txt Useful for comparing against RPC getLeaderSchedule results.

func DumpScheduleMismatch

func DumpScheduleMismatch(
	epoch uint64,
	epochSchedule *sealevel.SysvarEpochSchedule,
	localSchedule *leaderschedule.LeaderSchedule,
	rpcSchedule *leaderschedule.LeaderSchedule,
	logsDir string,
) (localPath, rpcPath string)

DumpScheduleMismatch dumps both local and RPC schedules to CSV files for analysis. Called when a hash mismatch is detected during validation. Returns paths to local and RPC slot files.

func DumpTieBreakDebug

func DumpTieBreakDebug(
	epoch uint64,
	voteAcctStakes map[solana.PublicKey]uint64,
	voteAcctMap map[solana.PublicKey]*epochstakes.VoteAccount,
	logsDir string,
)

DumpTieBreakDebug writes tie-break debugging info to a file. This verifies that equal-stake validators are sorted by pubkey DESC (Agave behavior).

func GenerateRunID

func GenerateRunID() string

GenerateRunID creates a short random hex string for log correlation

func GetCommitSlot

func GetCommitSlot() uint64

GetCommitSlot returns the slot currently being committed (0 if not in commit)

func IsCommitInProgress

func IsCommitInProgress() bool

IsCommitInProgress returns true if we're in the critical commit window. Used by panic recovery to determine if AccountsDB may be corrupted.

func NewLoadedAcctSizeAccumulatorSimd186

func NewLoadedAcctSizeAccumulatorSimd186(
	slotCtx *sealevel.SlotCtx,
	limit uint64,
	acctKeys []solana.PublicKey) *loadedAcctSizeAccumulatorSimd186

func NewTxErrInvalidSignature

func NewTxErrInvalidSignature(msg string) error

func ProcessBlock

func ProcessBlock(
	acctsDb *accountsdb.AccountsDb,
	block *b.Block,
	txParallelism int,
	dbgOpts *DebugOptions,

	pt *persistedTracker,
) (*sealevel.SlotCtx, error)

func ProcessTransaction

func ProcessTransaction(slotCtx *sealevel.SlotCtx, sigverifyWg *sync.WaitGroup, tx *solana.Transaction, txMeta *rpc.TransactionMeta, dbgOpts *DebugOptions, arena *arena.Arena[sealevel.BorrowedAccount]) (*fees.TxFeeInfo, uint64, error)

func RebuildVoteCacheFromAccountsDB

func RebuildVoteCacheFromAccountsDB(
	acctsDb *accountsdb.AccountsDb,
	slot uint64,
	voteAcctStakes map[solana.PublicKey]uint64,
	maxConcurrency int,
) error

RebuildVoteCacheFromAccountsDB rebuilds the VoteCache from AccountsDB for all vote accounts in the stake map. This ensures correctness at epoch boundaries by reading the canonical state directly from AccountsDB.

Parameters:

  • acctsDb: the AccountsDB instance
  • slot: the slot at which to read account state (typically lastSlotCtx.Slot)
  • voteAcctStakes: the stake map for the new epoch (vote account -> stake)
  • maxConcurrency: number of concurrent workers (0 = use default)

Returns error if any vote account is missing or has invalid state. This is a blocking operation and should be called before building the leader schedule.

func ResolveAddrTableLookupsForTx

func ResolveAddrTableLookupsForTx(ctx context.Context, accountsDb *accountsdb.AccountsDb, slot uint64, tx *solana.Transaction) error

ResolveAddrTableLookupsForTx resolves a single tx's address-table lookups against accountsdb at the given slot.

No-op for legacy or empty-lookup versioned txs. Returns wrapped errors so callers can map missing/invalid tables to AddressLookupTableNotFound or InvalidAddressLookupTableData.

func TopsortPlanner

func TopsortPlanner(b *block.Block) [][]int

TopsortPlanner returns a list of list of ints. The ints are indices into the b.Transactions slices. Each list of indices do not have write-after-write or read-after-write conflicts.

func TopsortPlannerStream

func TopsortPlannerStream(b *block.Block, out chan int, done chan int)

TopsortPlanner outputs ints on out channel which have had their dependencies satisfied and can be run. On completion, return the int to the done channel.

Types

type AccountSharedData

type AccountSharedData struct {
	// Lamports in the account
	Lamports uint64
	// Data held in this account
	Data []byte
	// The program that owns this account
	Owner solana.PublicKey
	// This account's data contains a loaded program (and is now read-only)
	Executable bool
	// The epoch at which this account will next owe rent
	RentEpoch uint64
}

AccountSharedData represents the data stored in an account

type AccountUpdate

type AccountUpdate struct {
	Pubkey  solana.PublicKey
	Account accounts.Account
}

AccountUpdate represents a single account update from transaction execution

type BlockFetchOpts

type BlockFetchOpts struct {
	MaxRPS          int    // Rate limit (requests per second), 0 = use default
	MaxInflight     int    // Max concurrent workers, 0 = use default
	TipPollMs       int    // Tip poll interval ms, 0 = use default
	TipSafetyMargin uint64 // Don't fetch within N slots of tip, 0 = use default

	// Mode thresholds (hysteresis)
	NearTipThreshold        int // Enter near-tip when gap <= this, 0 = use default
	CatchupThreshold        int // Exit near-tip when gap >= this, 0 = use default
	CatchupTipGateThreshold int // Only apply safety margin when gap > this, 0 = use default

	// Near-tip tuning
	NearTipPollMs    int // Faster poll interval in near-tip, 0 = use default
	NearTipLookahead int // Slots ahead to schedule in near-tip, 0 = use default
}

BlockFetchOpts contains options for parallel block fetching

type BoundaryStakeScanResult

type BoundaryStakeScanResult struct {
	// For stake history update
	StakeHistoryEffective    uint64
	StakeHistoryActivating   uint64
	StakeHistoryDeactivating uint64
	// For epoch stakes + vote cache
	VoteAcctStakes      map[solana.PublicKey]uint64
	EffectiveStakes     map[solana.PublicKey]uint64
	TotalEffectiveStake uint64
}

BoundaryStakeScanResult holds all accumulated data from a single streaming pass over stake accounts at the epoch boundary, serving both stake history update and epoch stakes/vote cache refresh.

type CloneStats

type CloneStats struct {
	AcctsLoaded       uint64 // Accounts loaded into tx contexts
	AcctsLoadedBytes  uint64 // Bytes referenced by tx contexts
	AcctsCloned       uint64 // Accounts loaded (cloned)
	AcctsClonedBytes  uint64 // Bytes cloned
	AcctsTouched      uint64 // Accounts modified
	AcctsTouchedBytes uint64 // Bytes of modified accounts
	TxCount           uint64 // Number of transactions
}

CloneStats holds account clone/modify metrics for reporting

func GetAndResetCloneStats

func GetAndResetCloneStats() CloneStats

GetAndResetCloneStats returns current clone stats and resets counters

type CompiledInstruction

type CompiledInstruction struct {
	// ProgramIdIndex is the index into the transaction's account keys of the program
	ProgramIdIndex uint8
	// Accounts contains the indices into the transaction's account keys
	Accounts []uint8
	// Data is the instruction data
	Data []byte
	// StackHeight is the depth at which this instruction executed.
	// 1 = top-level; >=2 = CPI invoked from within another instruction.
	StackHeight uint8
}

CompiledInstruction represents a compiled instruction. StackHeight is set for inner instructions to mirror Agave's UiCompiledInstruction; top-level top-level captures leave it zero.

type ConsensusOpts

type ConsensusOpts struct {
	SkipPathMaxDepth int    // Max slots for skip-path solver (default: 64)
	UnresolvedPolicy string // "halt" or "warn" (default: "halt")
	EnforceOnSource  string // "lightbringer" or "all" (default: "lightbringer")
}

ConsensusOpts contains vote-anchored consensus configuration. Nil means use defaults (max_depth=64, policy="halt").

type DebugOptions

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

func NewDebugOptions

func NewDebugOptions(txs, acctWrites []string, dumpEpochVotingRewardDiff bool) (*DebugOptions, error)

func (*DebugOptions) DumpEpochRewardArtifacts

func (x *DebugOptions) DumpEpochRewardArtifacts() bool

func (*DebugOptions) DumpEpochVotingRewardDiff

func (x *DebugOptions) DumpEpochVotingRewardDiff() bool

func (*DebugOptions) IsDebugTx

func (x *DebugOptions) IsDebugTx(t solana.Signature) bool

func (*DebugOptions) IsDebugWriteAccount

func (x *DebugOptions) IsDebugWriteAccount(pk solana.PublicKey) bool

type ExecutedTransaction

type ExecutedTransaction struct {
	LoadedTransaction LoadedTransaction
	ExecutionDetails  TransactionExecutionDetails
	ProgramsModified  map[solana.PublicKey]bool // Programs that were modified by this transaction
}

ExecutedTransaction represents a transaction that was executed. If execution failed, all account state changes will be rolled back except deducted fees and any advanced nonces.

type FeesOnlyTransaction

type FeesOnlyTransaction struct {
	LoadedTransaction LoadedTransaction
	ExecutionError    error // The error that prevented execution
}

FeesOnlyTransaction represents a transaction that was not able to be executed but fees are able to be collected and any nonces are advanceable

type InnerInstructionsList

type InnerInstructionsList struct {
	// Index is the index of the top-level instruction that produced these inner instructions
	Index uint8
	// Instructions contains the inner instructions
	Instructions []CompiledInstruction
}

InnerInstructionsList represents the inner instructions for a single top-level instruction

func AssembleInnerInstructions

func AssembleInnerInstructions(execCtx *sealevel.ExecutionCtx) []InnerInstructionsList

AssembleInnerInstructions groups CPI captures from execCtx by their top-level instruction index and converts them into the response shape. Returns nil when no captures were recorded (e.g. simulate without innerInstructions=true, or block-replay).

Exported so the simulate RPC handler can reach into a partially-executed execCtx on the InstructionError path — Agave wire format keeps captured CPIs on tx failure even though Mithril's bifurcated processing-result type discards them via the TransactionError early-return.

type KeyedAccountSharedData

type KeyedAccountSharedData struct {
	Pubkey      solana.PublicKey
	AccountData AccountSharedData
}

KeyedAccountSharedData is a tuple of (Pubkey, AccountSharedData)

type LoadAndExecuteTransactionInput

type LoadAndExecuteTransactionInput struct {
	// SlotCtx provides access to accounts and slot state (used read-only)
	SlotCtx *sealevel.SlotCtx
	// Transaction is the transaction to process
	Transaction *solana.Transaction
	// Arena for borrowed accounts (optional)
	Arena *arena.Arena[sealevel.BorrowedAccount]
	// TxMeta is the on-chain transaction metadata (optional, used for fee calculation)
	TxMeta *rpc.TransactionMeta
	// IsSimulation indicates this is a simulation (no side effects on shared state)
	IsSimulation bool
	// RecordInnerInstructions enables CPI recording. The simulate handler
	// sets this when the RPC request asks for innerInstructions.
	RecordInnerInstructions bool
}

LoadAndExecuteTransactionInput contains all the input state needed for pure transaction processing

type LoadAndExecuteTransactionOutput

type LoadAndExecuteTransactionOutput struct {
	// Result of processing the transaction. Contains either ProcessedTransaction or TransactionError
	ProcessingResult TransactionProcessingResult
	// ExecutionResult contains all the state changes from executing the transaction
	// This is only populated if ProcessingResult contains a ProcessedTransaction
	ExecutionResult *TransactionExecutionResult

	// ExecCtx is the execution context after processing. Available when accounts were
	// loaded successfully. Used by ProcessTransaction for divergence checks and state application.
	ExecCtx *sealevel.ExecutionCtx
	// PreBalances contains lamport balances for each account BEFORE fee deduction.
	// Used by ProcessTransaction for pre-balance divergence checks.
	PreBalances []uint64
	// PreAccountSnapshots holds clones of every transaction account
	// captured before fee deduction and execution. The simulate handler
	// uses these to decode pre-execution token balances; block-replay
	// callers leave it nil.
	PreAccountSnapshots []*accounts.Account
	// FeeInfo contains the calculated fee info. Set whenever fees were calculated.
	FeeInfo *fees.TxFeeInfo
	// Instrs contains the parsed instructions from the transaction.
	Instrs []sealevel.Instruction
	// ComputeBudgetLimits contains the compute budget limits computed from instructions.
	ComputeBudgetLimits *sealevel.ComputeBudgetLimits
}

LoadAndExecuteTransactionOutput is the output of loading and executing a sanitized transaction. This structure contains the complete result of transaction processing, including whether the transaction was successfully processed or encountered an error.

type LoadedTransaction

type LoadedTransaction struct {
	// Accounts contains all the accounts loaded for this transaction with their public keys
	Accounts []KeyedAccountSharedData
	// ProgramIndices contains the indices of program accounts in the Accounts array
	ProgramIndices []uint16
	// FeeDetails contains the fee calculation for this transaction
	FeeDetails fees.TxFeeInfo
	// RollbackAccounts contains the accounts that need to be rolled back if the transaction fails
	RollbackAccounts RollbackAccounts
	// ComputeBudget contains the compute unit limits and heap size for this transaction
	ComputeBudget SVMTransactionExecutionBudget
	// LoadedAccountsDataSize is the total size of all loaded account data in bytes
	LoadedAccountsDataSize uint32
}

LoadedTransaction contains all the accounts and metadata loaded for a transaction

type OnCancelWriteState

type OnCancelWriteState func(result *ReplayResult) error

OnCancelWriteState is a callback that writes state immediately on cancellation. This eliminates the timing window between bankhash persistence and state file update.

type ProcessedTransaction

type ProcessedTransaction struct {
	// TransactionType indicates whether this is an Executed or FeesOnly transaction
	TransactionType ProcessedTransactionType
	// Executed contains the execution result if TransactionType is Executed
	Executed *ExecutedTransaction
	// FeesOnly contains the fees-only result if TransactionType is FeesOnly
	FeesOnly *FeesOnlyTransaction
}

ProcessedTransaction represents a transaction that was processed, either executed or fees-only

type ProcessedTransactionType

type ProcessedTransactionType int

ProcessedTransactionType indicates the type of processed transaction

const (
	// ProcessedTransactionTypeExecuted - Transaction was executed (may have failed but all instructions ran)
	ProcessedTransactionTypeExecuted ProcessedTransactionType = iota
	// ProcessedTransactionTypeFeesOnly - Transaction was not executed but fees were collected
	ProcessedTransactionTypeFeesOnly
)

type ReplayCtx

type ReplayCtx struct {
	CurrentFeatures   *features.Features
	Capitalization    uint64
	Inflation         rewards.Inflation
	SlotsPerYear      float64
	EpochAcctsHash    []byte
	HasEpochAcctsHash bool
}

type ReplayResult

type ReplayResult struct {
	// LastPersistedSlot is the last slot whose state was successfully persisted to AccountsDB
	LastPersistedSlot uint64
	// LastPersistedBankhash is the bankhash of the last persisted slot
	LastPersistedBankhash []byte
	// LastBlockHeight is the block height of the last persisted slot.
	LastBlockHeight uint64
	// WasCancelled indicates whether replay was interrupted by context cancellation
	WasCancelled bool
	// Error contains any error that occurred during replay
	Error error

	// Resume context - populated on graceful shutdown (Ctrl+C) for proper resume
	LastAcctsLtHash          *lthash.LtHash // LtHash at end of last persisted slot
	LastLamportsPerSignature uint64         // FeeRateGovernor.LamportsPerSignature
	LastPrevLamportsPerSig   uint64         // FeeRateGovernor.PrevLamportsPerSignature
	LastNumSignatures        uint64         // SlotCtx.NumSignatures

	// Blockhash context - required because appendvec writes are not fsynced
	LastRecentBlockhashes *sealevel.SysvarRecentBlockhashes // 150 entries, newest first
	LastEvictedBlockhash  [32]byte                          // 151st blockhash
	LastBlockhash         [32]byte                          // blockhash of last replayed slot

	// SlotHashes context - same issue, vote program needs accurate slot→hash mappings
	LastSlotHashes *sealevel.SysvarSlotHashes

	// ReplayCtx fields - for resume independence from stale manifest
	LastCapitalization uint64
	LastSlotsPerYear   float64
	LastInflation      rewards.Inflation

	// ComputedEpochStakes contains epoch stakes computed at boundaries during this run.
	// Key: epoch number (the leader schedule epoch), Value: serialized JSON
	// This must be persisted to state file for correct resume across epoch boundaries.
	ComputedEpochStakes map[uint64][]byte

	// StateWrittenOnCancel indicates that the state file was already written during
	// cancellation handling, so the caller should skip the final write
	StateWrittenOnCancel bool
}

ReplayResult contains the result of a replay operation, including shutdown state

func ReplayBlocks

func ReplayBlocks(
	ctx context.Context,
	acctsDb *accountsdb.AccountsDb,
	acctsDbPath string,
	mithrilState *state.MithrilState,
	resumeState *ResumeState,
	startSlot, endSlot uint64,
	rpcEndpoints []string,
	lightbringerEndpoint string,
	blockDir string,
	txParallelism int,
	isLive bool,
	useLightbringer bool,
	dbgOpts *DebugOptions,
	metricsWriter io.Writer,
	rpcServer SlotCtxSetter,
	blockFetchOpts *BlockFetchOpts,
	consensusOpts *ConsensusOpts,
	onCancelWriteState OnCancelWriteState,
) *ReplayResult

type ResumeState

type ResumeState struct {
	// ParentSlot is the slot of the last successfully replayed block (= state.LastSlot)
	ParentSlot uint64
	// ParentBlockHeight is the block height of the last successfully replayed block.
	ParentBlockHeight uint64
	// ParentBankhash is the bankhash of the parent slot
	ParentBankhash []byte
	// AcctsLtHash is the cumulative LtHash at the end of the parent slot
	AcctsLtHash *lthash.LtHash
	// LamportsPerSignature for reconstructing FeeRateGovernor
	LamportsPerSignature uint64
	// PrevLamportsPerSignature for reconstructing FeeRateGovernor
	PrevLamportsPerSignature uint64
	// NumSignatures is the total signature count at end of parent slot
	NumSignatures uint64

	// Blockhash context - required because appendvec writes are not fsynced
	RecentBlockhashes *sealevel.SysvarRecentBlockhashes // 150 entries, newest first
	EvictedBlockhash  [32]byte                          // 151st blockhash
	LastBlockhash     [32]byte                          // blockhash of last slot (parent for next)

	// SlotHashes context - vote program needs accurate slot→hash mappings
	SlotHashes *sealevel.SysvarSlotHashes

	// ReplayCtx fields - so resume uses fresh values instead of stale manifest
	Capitalization          uint64
	SlotsPerYear            float64
	InflationInitial        float64
	InflationTerminal       float64
	InflationTaper          float64
	InflationFoundation     float64
	InflationFoundationTerm float64

	// ComputedEpochStakes contains epoch stakes computed at boundaries.
	// Key: epoch number (the leader schedule epoch), Value: serialized JSON
	// Required for correct leader schedule computation on resume.
	ComputedEpochStakes map[uint64][]byte
}

ResumeState contains the state needed to properly configure the first block when resuming. This is passed to ReplayBlocks when resuming from a previous run.

type RollbackAccounts

type RollbackAccounts struct {
	RollbackType RollbackAccountsType
	// FeePayer is set for FeePayerOnly and SeparateNonceAndFeePayer types
	FeePayer *KeyedAccountSharedData
	// Nonce is set for SameNonceAndFeePayer and SeparateNonceAndFeePayer types
	Nonce *KeyedAccountSharedData
}

RollbackAccounts represents the accounts that need to be saved for potential rollback

type RollbackAccountsType

type RollbackAccountsType int

RollbackAccountsType indicates the type of rollback accounts

const (
	// RollbackAccountsTypeFeePayerOnly - Only the fee payer account needs rollback
	RollbackAccountsTypeFeePayerOnly RollbackAccountsType = iota
	// RollbackAccountsTypeSameNonceAndFeePayer - Nonce and fee payer are the same account
	RollbackAccountsTypeSameNonceAndFeePayer
	// RollbackAccountsTypeSeparateNonceAndFeePayer - Nonce and fee payer are separate accounts
	RollbackAccountsTypeSeparateNonceAndFeePayer
)

type SVMTransactionExecutionBudget

type SVMTransactionExecutionBudget struct {
	// ComputeUnitLimit is the number of compute units that a transaction is allowed to consume
	ComputeUnitLimit uint64
	// MaxInstructionStackDepth is the maximum program instruction invocation stack depth
	MaxInstructionStackDepth uint64
	// MaxInstructionTraceLength is the maximum cross-program invocation and instructions per transaction
	MaxInstructionTraceLength uint64
	// Sha256MaxSlices is the maximum number of slices hashed per syscall
	Sha256MaxSlices uint64
	// MaxCallDepth is the maximum SBF to BPF call depth
	MaxCallDepth uint64
	// StackFrameSize is the size of a stack frame in bytes
	StackFrameSize uint64
	// HeapSize is the program heap region size
	HeapSize uint32
}

SVMTransactionExecutionBudget contains the execution limits for a transaction

type ScheduleSummary

type ScheduleSummary struct {
	// Epoch info
	BlockEpoch    uint64
	ScheduleEpoch uint64
	FirstSlot     uint64
	SlotsInEpoch  uint64
	Repeat        uint64

	// Stake info
	TotalInputStake     uint64 // Total stake from EpochStakes (before filtering)
	FilteredStake       uint64 // Stake used in schedule (after filtering)
	MissingStake        uint64 // Stake skipped due to missing data
	MissingStakePercent float64

	// Validator counts
	ValidatorsInput    int // Total vote accounts in EpochStakes
	ValidatorsUsed     int // Validators included in schedule
	ValidatorsSkipped  int // Validators skipped (zero stake + missing + zero nodepk)
	SkippedZeroStake   int
	SkippedMissingData int // missing_vote_acct or missing_vote_cache
	SkippedZeroNodePk  int

	// Hashes
	LocalHash string
	RPCHash   string // Empty if RPC validation not enabled

	// Run info
	RunID     string
	Source    string // "snapshot" or "vote_cache"
	Timestamp time.Time
}

ScheduleSummary holds all metadata for the summary file

func PrepareLeaderScheduleLocal

func PrepareLeaderScheduleLocal(
	epoch uint64,
	epochSchedule *sealevel.SysvarEpochSchedule,
	logsDir string,
) (*ScheduleSummary, error)

PrepareLeaderScheduleLocal builds the leader schedule from local state and sets it as the source of truth. This is the primary entry point for leader schedule - no RPC dependency. Returns the schedule summary (for RPC validation) and error if schedule cannot be built.

func PrepareLeaderScheduleLocalFromVoteCache

func PrepareLeaderScheduleLocalFromVoteCache(
	epoch uint64,
	epochSchedule *sealevel.SysvarEpochSchedule,
	logsDir string,
) (*ScheduleSummary, error)

PrepareLeaderScheduleLocalFromVoteCache builds the leader schedule using vote cache for NodePubkey lookups. Used at epoch boundaries when EpochStakesVoteAccts may not have the new epoch's data yet. Returns the schedule summary (for RPC validation) and error if schedule cannot be built.

type SlotCtxSetter

type SlotCtxSetter interface {
	SetSlotCtx(slotCtx *sealevel.SlotCtx)
}

SlotCtxSetter is implemented by types that accept a SlotCtx update (e.g. RpcServer).

type StakeEntry

type StakeEntry struct {
	VoteAcct   solana.PublicKey
	NodePubkey solana.PublicKey
	Stake      uint64
	Reason     string // For skipped entries: "zero_stake", "missing_vote_acct", "zero_nodepk"
}

StakeEntry holds a vote account and its stake for logging

type TransactionError

type TransactionError struct {
	ErrorType TransactionErrorType
	// InstructionIndex is set for InstructionError type
	InstructionIndex *uint8
	// InstructionError is set for InstructionError type
	InstructionError error
	// AccountIndex is set for errors that reference a specific account
	AccountIndex *uint8
}

TransactionError represents all possible transaction-level errors that can occur before or during transaction processing. These match the Solana error codes.

func (*TransactionError) MarshalJSON

func (e *TransactionError) MarshalJSON() ([]byte, error)

MarshalJSON renders TransactionError in Agave's wire format: bare string for unit variants, single-key object for tuple variants such as {"InstructionError":[idx, inner]}.

type TransactionErrorType

type TransactionErrorType int

TransactionErrorType represents the type of transaction error

const (
	// TransactionErrorAccountInUse - An account is already being processed in another transaction
	TransactionErrorAccountInUse TransactionErrorType = iota
	// TransactionErrorAccountLoadedTwice - A Pubkey appears twice in the transaction's account_keys
	TransactionErrorAccountLoadedTwice
	// TransactionErrorAccountNotFound - Attempt to debit an account but found no record of a prior credit
	TransactionErrorAccountNotFound
	// TransactionErrorProgramAccountNotFound - Attempt to load a program that does not exist
	TransactionErrorProgramAccountNotFound
	// TransactionErrorInsufficientFundsForFee - The from Pubkey does not have sufficient balance to pay the fee
	TransactionErrorInsufficientFundsForFee
	// TransactionErrorInvalidAccountForFee - This account may not be used to pay transaction fees
	TransactionErrorInvalidAccountForFee
	// TransactionErrorAlreadyProcessed - The bank has seen this transaction before
	TransactionErrorAlreadyProcessed
	// TransactionErrorBlockhashNotFound - The bank has not seen the given recent_blockhash
	TransactionErrorBlockhashNotFound
	// TransactionErrorInstructionError - An error occurred while processing an instruction
	TransactionErrorInstructionError
	// TransactionErrorCallChainTooDeep - Loader call chain is too deep
	TransactionErrorCallChainTooDeep
	// TransactionErrorMissingSignatureForFee - Transaction requires a fee but has no signature present
	TransactionErrorMissingSignatureForFee
	// TransactionErrorInvalidAccountIndex - Transaction contains an invalid account reference
	TransactionErrorInvalidAccountIndex
	// TransactionErrorSignatureFailure - Transaction did not pass signature verification
	TransactionErrorSignatureFailure
	// TransactionErrorInvalidProgramForExecution - This program may not be used for executing instructions
	TransactionErrorInvalidProgramForExecution
	// TransactionErrorSanitizeFailure - Transaction failed to sanitize accounts offsets correctly
	TransactionErrorSanitizeFailure
	// TransactionErrorClusterMaintenance - Cluster is in maintenance mode
	TransactionErrorClusterMaintenance
	// TransactionErrorAccountBorrowOutstanding - Transaction processing left an account with an outstanding borrowed reference
	TransactionErrorAccountBorrowOutstanding
	// TransactionErrorWouldExceedMaxBlockCostLimit - Transaction would exceed max Block Cost Limit
	TransactionErrorWouldExceedMaxBlockCostLimit
	// TransactionErrorUnsupportedVersion - Transaction version is unsupported
	TransactionErrorUnsupportedVersion
	// TransactionErrorInvalidWritableAccount - Transaction loads a writable account that cannot be written
	TransactionErrorInvalidWritableAccount
	// TransactionErrorWouldExceedMaxAccountCostLimit - Transaction would exceed max account limit within the block
	TransactionErrorWouldExceedMaxAccountCostLimit
	// TransactionErrorWouldExceedAccountDataBlockLimit - Transaction would exceed account data limit within the block
	TransactionErrorWouldExceedAccountDataBlockLimit
	// TransactionErrorTooManyAccountLocks - Transaction locked too many accounts
	TransactionErrorTooManyAccountLocks
	// TransactionErrorAddressLookupTableNotFound - Address lookup table not found
	TransactionErrorAddressLookupTableNotFound
	// TransactionErrorInvalidAddressLookupTableOwner - Attempted to lookup addresses from an account owned by the wrong program
	TransactionErrorInvalidAddressLookupTableOwner
	// TransactionErrorInvalidAddressLookupTableData - Attempted to lookup addresses from an invalid account
	TransactionErrorInvalidAddressLookupTableData
	// TransactionErrorInvalidAddressLookupTableIndex - Address table lookup uses an invalid index
	TransactionErrorInvalidAddressLookupTableIndex
	// TransactionErrorInvalidRentPayingAccount - Transaction leaves an account with a lower balance than rent-exempt minimum
	TransactionErrorInvalidRentPayingAccount
	// TransactionErrorWouldExceedMaxVoteCostLimit - Transaction would exceed max Vote Cost Limit
	TransactionErrorWouldExceedMaxVoteCostLimit
	// TransactionErrorWouldExceedAccountDataTotalLimit - Transaction would exceed total account data limit
	TransactionErrorWouldExceedAccountDataTotalLimit
	// TransactionErrorDuplicateInstruction - Transaction contains a duplicate instruction that is not allowed
	TransactionErrorDuplicateInstruction
	// TransactionErrorInsufficientFundsForRent - Transaction results in an account with insufficient funds for rent
	TransactionErrorInsufficientFundsForRent
	// TransactionErrorMaxLoadedAccountsDataSizeExceeded - Transaction exceeded max loaded accounts data size cap
	TransactionErrorMaxLoadedAccountsDataSizeExceeded
	// TransactionErrorInvalidLoadedAccountsDataSizeLimit - LoadedAccountsDataSizeLimit set for transaction must be greater than 0
	TransactionErrorInvalidLoadedAccountsDataSizeLimit
	// TransactionErrorResanitizationNeeded - Sanitized transaction differed before/after feature activation
	TransactionErrorResanitizationNeeded
	// TransactionErrorProgramExecutionTemporarilyRestricted - Program execution is temporarily restricted on an account
	TransactionErrorProgramExecutionTemporarilyRestricted
	// TransactionErrorUnbalancedTransaction - The total balance before the transaction does not equal the total balance after the transaction
	TransactionErrorUnbalancedTransaction
	// TransactionErrorProgramCacheHitMaxLimit - Program cache hit max limit
	TransactionErrorProgramCacheHitMaxLimit
)

func (TransactionErrorType) String

func (t TransactionErrorType) String() string

String returns the Agave-compatible TransactionError variant name (the const name with the TransactionError prefix stripped). Used by simulate callers that need a wire-format string when no InstructionError is set.

type TransactionExecutionDetails

type TransactionExecutionDetails struct {
	// Status is the execution result (nil for success, error for failure)
	Status error
	// LogMessages contains the log messages produced during execution (if logging is enabled)
	LogMessages []string
	// InnerInstructions contains the inner instructions executed via CPI
	InnerInstructions []InnerInstructionsList
	// ReturnData contains the return data from the last instruction
	ReturnData *TransactionReturnData
	// ExecutedUnits is the number of compute units consumed
	ExecutedUnits uint64
	// AccountsDataLenDelta is the change in accounts data len for this transaction (only valid if Status is nil)
	AccountsDataLenDelta int64
}

TransactionExecutionDetails contains the execution result and metadata

type TransactionExecutionResult

type TransactionExecutionResult struct {
	// AccountUpdates contains all account updates (modified accounts)
	AccountUpdates []AccountUpdate
	// WritableAccounts contains the pubkeys of all writable accounts (slice for ordered iteration)
	WritableAccounts []solana.PublicKey
	// WritableAccountSet is the same as WritableAccounts but as a set for O(1) lookups
	WritableAccountSet map[solana.PublicKey]struct{}
	// ModifiedStakeAccounts contains stake accounts that were modified
	ModifiedStakeAccounts []solana.PublicKey
	// ModifiedVoteAccounts contains vote accounts that were modified
	ModifiedVoteAccounts map[solana.PublicKey]*sealevel.VoteStateVersions
}

TransactionExecutionResult contains all the updates from executing a transaction

type TransactionProcessingResult

type TransactionProcessingResult struct {
	// ProcessedTransaction contains the execution result if successful
	ProcessedTransaction *ProcessedTransaction
	// TransactionError contains the error if processing failed
	TransactionError *TransactionError
}

TransactionProcessingResult represents the result of processing a transaction

type TransactionReturnData

type TransactionReturnData struct {
	ProgramId solana.PublicKey
	Data      []byte
}

TransactionReturnData represents data returned from a program

type TxErrInvalidSignature

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

func (*TxErrInvalidSignature) Error

func (err *TxErrInvalidSignature) Error() string

type ValidationStats

type ValidationStats struct {
	SkippedZeroStake            int
	SkippedMissingNodePk        int
	SkippedMissingNodePkStake   uint64 // Stake dropped due to zero NodePubkey
	SkippedMissingVoteAcct      int
	SkippedMissingVoteAcctStake uint64 // Stake dropped due to missing VoteCache entries
	TotalVoteAccts              int
	TotalStake                  uint64
	MinStake                    uint64
	MaxStake                    uint64
	ValidatorCount              int // Validators with non-zero stake and valid NodePubkey
	MismatchCount               int
	Capped                      bool
	TopStakes                   []StakeEntry // Top 10 by stake
	BottomStakes                []StakeEntry // Bottom 10 by stake
	MissingVoteAccts            []StakeEntry // First few missing vote accounts (for debugging)
	ZeroNodePkAccts             []StakeEntry // First few zero NodePubkey accounts
}

ValidationStats holds statistics from schedule validation

type VoteCacheRebuildError

type VoteCacheRebuildError struct {
	VoteAcct solana.PublicKey
	Stake    uint64
	Reason   string
	Err      error
}

VoteCacheRebuildError holds info about a failed vote account for logging

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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