Documentation
¶
Index ¶
- Constants
- Variables
- func BlockBeforeSlot(db *Database, slotNumber uint64) (models.Block, error)
- func BlockBeforeSlotTxn(txn *Txn, slotNumber uint64) (models.Block, error)
- func BlockBlobKeyToPoint(key []byte) (ocommon.Point, error)
- func BlockByHash(db *Database, hash []byte) (models.Block, error)
- func BlockByHashTxn(txn *Txn, hash []byte) (models.Block, error)
- func BlockByPoint(db *Database, point ocommon.Point) (models.Block, error)
- func BlockByPointTxn(txn *Txn, point ocommon.Point) (models.Block, error)
- func BlockDeleteTxn(txn *Txn, block models.Block) error
- func BlockURL(ctx context.Context, db *Database, point ocommon.Point) (types.SignedURL, types.BlockMetadata, error)
- func BlocksAfterSlotTxn(txn *Txn, slotNumber uint64) ([]models.Block, error)
- func BlocksRecent(db *Database, count int) ([]models.Block, error)
- func BlocksRecentTxn(txn *Txn, count int) ([]models.Block, error)
- func EncodeTxOffset(offset *CborOffset) []byte
- func EncodeUtxoOffset(offset *CborOffset) []byte
- func ForEachBlockInRange(txn *Txn, startSlot, endSlot uint64, fn func(block models.Block) error) error
- func ForEachBlockInRangeDB(db *Database, startSlot, endSlot uint64, fn func(block models.Block) error) error
- func IsTxCborPartsStorage(data []byte) bool
- func IsTxOffsetStorage(data []byte) bool
- func IsUtxoOffsetStorage(data []byte) bool
- type BlobBlockIterator
- type BlobBlockResult
- type BlockIndexer
- type BlockIngestionResult
- type BlockLRUCache
- type CacheMetrics
- func (m *CacheMetrics) IncBlockLRUHit()
- func (m *CacheMetrics) IncBlockLRUMiss()
- func (m *CacheMetrics) IncColdExtraction()
- func (m *CacheMetrics) IncTxHotHit()
- func (m *CacheMetrics) IncTxHotMiss()
- func (m *CacheMetrics) IncUtxoHotHit()
- func (m *CacheMetrics) IncUtxoHotMiss()
- func (m *CacheMetrics) Register(registry prometheus.Registerer)
- type CachedBlock
- type CborCacheConfig
- type CborOffset
- type CommitTimestampError
- type Config
- type Database
- func (d *Database) ApplyPParamUpdates(slot, epoch uint64, era uint, quorum int, ...) error
- func (d *Database) Blob() blob.BlobStore
- func (d *Database) BlobTxn(readWrite bool) *Txn
- func (d *Database) BlockByIndex(blockIndex uint64, txn *Txn) (models.Block, error)
- func (d *Database) BlockCreate(block models.Block, txn *Txn) error
- func (d *Database) BlocksFromSlot(startSlot uint64) *BlobBlockIterator
- func (d *Database) BlocksInRange(startSlot, endSlot uint64) *BlobBlockIterator
- func (d *Database) CborCache() *TieredCborCache
- func (d *Database) ClearSyncState(txn *Txn) error
- func (d *Database) Close() error
- func (d *Database) ComputeAndApplyPParamUpdates(slot, epoch uint64, era uint, quorum int, ...) (lcommon.ProtocolParameters, error)
- func (d *Database) Config() *Config
- func (d *Database) DataDir() string
- func (d *Database) DeleteBlockNoncesBeforeSlot(slotNumber uint64, txn *Txn) error
- func (d *Database) DeleteBlockNoncesBeforeSlotWithoutCheckpoints(slotNumber uint64, txn *Txn) error
- func (d *Database) DeleteCertificatesAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteConstitutionsAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteEpochsAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteGovernanceProposalsAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteGovernanceVotesAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteNetworkStateAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeletePParamUpdatesAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeletePParamsAfterSlot(slot uint64, txn *Txn) error
- func (d *Database) DeleteSyncState(key string, txn *Txn) error
- func (d *Database) GetAccount(stakeKey []byte, includeInactive bool, txn *Txn) (*models.Account, error)
- func (d *Database) GetActiveCommitteeMembers(txn *Txn) ([]*models.AuthCommitteeHot, error)
- func (d *Database) GetActiveDreps(txn *Txn) ([]*models.Drep, error)
- func (d *Database) GetActiveGovernanceProposals(epoch uint64, txn *Txn) ([]*models.GovernanceProposal, error)
- func (d *Database) GetActivePoolRelays(txn *Txn) ([]models.PoolRegistrationRelay, error)
- func (d *Database) GetAddressesByStakingKey(stakingKey []byte, limit int, offset int, txn *Txn) ([]models.AddressTransaction, error)
- func (d *Database) GetBlockNonce(point ocommon.Point, txn *Txn) ([]byte, error)
- func (d *Database) GetBlockNoncesInSlotRange(startSlot uint64, endSlot uint64, txn *Txn) ([]models.BlockNonce, error)
- func (d *Database) GetCommitteeActiveCount(txn *Txn) (int, error)
- func (d *Database) GetCommitteeMember(coldKey []byte, txn *Txn) (*models.AuthCommitteeHot, error)
- func (d *Database) GetConstitution(txn *Txn) (*models.Constitution, error)
- func (d *Database) GetDRepVotingPower(drepCredential []byte, txn *Txn) (uint64, error)
- func (d *Database) GetDatum(hash []byte, txn *Txn) (*models.Datum, error)
- func (d *Database) GetDrep(cred []byte, includeInactive bool, txn *Txn) (*models.Drep, error)
- func (d *Database) GetEpoch(epochId uint64, txn *Txn) (*models.Epoch, error)
- func (d *Database) GetEpochs(txn *Txn) ([]models.Epoch, error)
- func (d *Database) GetEpochsByEra(eraId uint, txn *Txn) ([]models.Epoch, error)
- func (d *Database) GetExpiredDReps(epoch uint64, txn *Txn) ([]*models.Drep, error)
- func (d *Database) GetGovernanceProposal(txHash []byte, actionIndex uint32, txn *Txn) (*models.GovernanceProposal, error)
- func (d *Database) GetGovernanceVotes(proposalID uint, txn *Txn) ([]*models.GovernanceVote, error)
- func (d *Database) GetPParams(epoch uint64, decodeFunc func([]byte) (lcommon.ProtocolParameters, error), ...) (lcommon.ProtocolParameters, error)
- func (d *Database) GetPool(pkh lcommon.PoolKeyHash, includeInactive bool, txn *Txn) (*models.Pool, error)
- func (d *Database) GetPoolByVrfKeyHash(vrfKeyHash []byte, txn *Txn) (*models.Pool, error)
- func (d *Database) GetPoolRegistrations(poolKeyHash lcommon.PoolKeyHash, txn *Txn) ([]lcommon.PoolRegistrationCertificate, error)
- func (d *Database) GetStakeRegistrations(stakingKey []byte, txn *Txn) ([]lcommon.StakeRegistrationCertificate, error)
- func (d *Database) GetSyncState(key string, txn *Txn) (string, error)
- func (d *Database) GetTip(txn *Txn) (ochainsync.Tip, error)
- func (d *Database) GetTransactionByHash(hash []byte, txn *Txn) (*models.Transaction, error)
- func (d *Database) GetTransactionsByAddress(addr lcommon.Address, limit int, offset int, txn *Txn) ([]models.Transaction, error)
- func (d *Database) GetTransactionsByAddressKeys(paymentKey []byte, stakingKey []byte, limit int, offset int, order string, ...) ([]models.Transaction, error)
- func (d *Database) GetTransactionsByBlockHash(blockHash []byte, txn *Txn) ([]models.Transaction, error)
- func (d *Database) HasAnyGenesisCbor(slot uint64) bool
- func (d *Database) HasGenesisCbor(slot uint64, hash []byte) bool
- func (d *Database) IsCommitteeMemberResigned(coldKey []byte, txn *Txn) (bool, error)
- func (d *Database) Logger() *slog.Logger
- func (d *Database) Metadata() metadata.MetadataStore
- func (d *Database) MetadataTxn(readWrite bool) *Txn
- func (d *Database) RestoreAccountStateAtSlot(slot uint64, txn *Txn) error
- func (d *Database) RestoreDrepStateAtSlot(slot uint64, txn *Txn) error
- func (d *Database) RestorePoolStateAtSlot(slot uint64, txn *Txn) error
- func (d *Database) SetBlobStore(b blob.BlobStore)
- func (d *Database) SetBlockNonce(blockHash []byte, slotNumber uint64, nonce []byte, isCheckpoint bool, txn *Txn) error
- func (d *Database) SetConstitution(constitution *models.Constitution, txn *Txn) error
- func (d *Database) SetDatum(rawDatum []byte, addedSlot uint64, txn *Txn) error
- func (d *Database) SetEpoch(slot, epoch uint64, ...) error
- func (d *Database) SetGapBlockTransaction(tx lcommon.Transaction, point ocommon.Point, idx uint32, ...) error
- func (d *Database) SetGenesisCbor(slot uint64, hash []byte, cborData []byte, txn *Txn) error
- func (d *Database) SetGenesisStaking(pools map[string]lcommon.PoolRegistrationCertificate, ...) error
- func (d *Database) SetGenesisTransaction(txHash []byte, blockHash []byte, outputs []lcommon.Utxo, ...) error
- func (d *Database) SetGovernanceProposal(proposal *models.GovernanceProposal, txn *Txn) error
- func (d *Database) SetGovernanceVote(vote *models.GovernanceVote, txn *Txn) error
- func (d *Database) SetPParamUpdate(genesis, params []byte, slot, epoch uint64, txn *Txn) error
- func (d *Database) SetPParams(params []byte, slot, epoch uint64, era uint, txn *Txn) error
- func (d *Database) SetSyncState(key, value string, txn *Txn) error
- func (d *Database) SetTip(tip ochainsync.Tip, txn *Txn) error
- func (d *Database) SetTransaction(tx lcommon.Transaction, point ocommon.Point, idx uint32, updateEpoch uint64, ...) error
- func (d *Database) StorageMode() string
- func (d *Database) Transaction(readWrite bool) *Txn
- func (d *Database) TransactionsDeleteRolledback(slot uint64, txn *Txn) error
- func (d *Database) UpdateDRepActivity(drepCredential []byte, activityEpoch uint64, inactivityPeriod uint64, txn *Txn) error
- func (d *Database) UtxoByRef(txId []byte, outputIdx uint32, txn *Txn) (*models.Utxo, error)
- func (d *Database) UtxoByRefIncludingSpent(txId []byte, outputIdx uint32, txn *Txn) (*models.Utxo, error)
- func (d *Database) UtxosByAddress(addr ledger.Address, txn *Txn) ([]models.Utxo, error)
- func (d *Database) UtxosByAddressAtSlot(addr lcommon.Address, slot uint64, txn *Txn) ([]models.Utxo, error)
- func (d *Database) UtxosByAssets(policyId []byte, assetName []byte, txn *Txn) ([]models.Utxo, error)
- func (d *Database) UtxosDeleteConsumed(slot uint64, limit int, txn *Txn) (int, error)
- func (d *Database) UtxosDeleteRolledback(slot uint64, txn *Txn) error
- func (d *Database) UtxosUnspend(slot uint64, txn *Txn) error
- type HotCache
- type Location
- type OutputKey
- type PartialCommitError
- type PositionReader
- type TieredCborCache
- func (c *TieredCborCache) Metrics() *CacheMetrics
- func (c *TieredCborCache) ResolveTxCbor(txHash []byte) ([]byte, error)
- func (c *TieredCborCache) ResolveTxCborBatch(txHashes [][32]byte) (map[[32]byte][]byte, error)
- func (c *TieredCborCache) ResolveUtxoCbor(txId []byte, outputIdx uint32, blobTxn ...types.Txn) ([]byte, error)
- func (c *TieredCborCache) ResolveUtxoCborBatch(refs []UtxoRef) (map[UtxoRef][]byte, error)
- type TxCborParts
- type Txn
- type UtxoRef
Constants ¶
const (
BlockInitialIndex uint64 = 1
)
const CborOffsetSize = 52
CborOffsetSize is the size in bytes of an encoded CborOffset. Layout: Magic (4) + BlockSlot (8) + BlockHash (32) + ByteOffset (4) + ByteLength (4) = 52
const TxCborPartsSize = 69
TxCborPartsSize is the size in bytes of an encoded TxCborParts. Layout: Magic (4) + BlockSlot (8) + BlockHash (32) +
BodyOffset (4) + BodyLength (4) + WitnessOffset (4) + WitnessLength (4) + MetadataOffset (4) + MetadataLength (4) + IsValid (1) = 69
Variables ¶
var DefaultConfig = &Config{
BlobPlugin: "badger",
DataDir: ".dingo",
MetadataPlugin: "sqlite",
}
var ErrDatumNotFound = errors.New("datum not found")
var ErrNotImplemented = errors.New("not implemented")
ErrNotImplemented is returned when functionality is not yet implemented.
var ErrUtxoNotFound = errors.New("utxo not found")
Functions ¶
func BlockBeforeSlot ¶ added in v0.4.2
func BlockBeforeSlotTxn ¶ added in v0.4.2
func BlockBlobKeyToPoint ¶ added in v0.22.0
BlockBlobKeyToPoint extracts slot and hash from a block blob key. Key format: "bp" (2 bytes) + slot (8 bytes big-endian) + hash (32 bytes).
func BlockByHash ¶ added in v0.21.0
func BlockByHashTxn ¶ added in v0.21.0
func BlockByPoint ¶ added in v0.4.2
func BlockByPointTxn ¶ added in v0.4.2
func BlocksAfterSlotTxn ¶ added in v0.4.2
BlocksAfterSlotTxn returns all blocks after the specified slot; keep txn valid until results are consumed.
func BlocksRecent ¶ added in v0.4.2
func BlocksRecentTxn ¶ added in v0.4.2
BlocksRecentTxn returns the N most recent blocks; keep txn valid until results are consumed.
func EncodeTxOffset ¶ added in v0.22.0
func EncodeTxOffset(offset *CborOffset) []byte
EncodeTxOffset encodes a CborOffset for transaction storage. Returns a 52-byte encoded offset with magic prefix.
func EncodeUtxoOffset ¶ added in v0.22.0
func EncodeUtxoOffset(offset *CborOffset) []byte
EncodeUtxoOffset encodes a CborOffset for UTxO storage. Returns a 52-byte encoded offset with magic prefix.
func ForEachBlockInRange ¶ added in v0.22.0
func ForEachBlockInRange( txn *Txn, startSlot, endSlot uint64, fn func(block models.Block) error, ) error
ForEachBlockInRange iterates blocks in the slot range [startSlot, endSlot) from the blob store and calls fn for each block. Blocks are visited in ascending slot order. Iteration stops early if fn returns a non-nil error.
func ForEachBlockInRangeDB ¶ added in v0.22.0
func ForEachBlockInRangeDB( db *Database, startSlot, endSlot uint64, fn func(block models.Block) error, ) error
ForEachBlockInRangeDB is a convenience wrapper that creates a read-only transaction and calls ForEachBlockInRange.
func IsTxCborPartsStorage ¶ added in v0.22.0
IsTxCborPartsStorage checks if the data is TxCborParts storage. Returns true if data has the correct size and magic prefix.
func IsTxOffsetStorage ¶ added in v0.22.0
IsTxOffsetStorage checks if the data is offset-based transaction storage. Returns true if data has the correct size and magic prefix.
func IsUtxoOffsetStorage ¶ added in v0.22.0
IsUtxoOffsetStorage checks if the data is offset-based UTxO storage. Returns true if data has the correct size and magic prefix.
Types ¶
type BlobBlockIterator ¶ added in v0.22.0
type BlobBlockIterator struct {
// contains filtered or unexported fields
}
BlobBlockIterator iterates blocks from the blob store in slot order. The blob store keys are formatted as "bp" + big-endian(slot) + hash, so forward iteration naturally yields blocks in ascending slot order.
The iterator fetches block keys in batches to avoid loading the entire chain index into memory, and retrieves CBOR data on demand for each call to NextRaw.
func (*BlobBlockIterator) Close ¶ added in v0.22.0
func (it *BlobBlockIterator) Close()
Close releases any resources held by the iterator. It is safe to call Close multiple times.
func (*BlobBlockIterator) NextRaw ¶ added in v0.22.0
func (it *BlobBlockIterator) NextRaw() (*BlobBlockResult, error)
NextRaw returns the next block as raw CBOR bytes along with its metadata. When iteration is complete, it returns (nil, nil). Blocks whose CBOR cannot be fetched from the blob store are skipped with a warning log.
func (*BlobBlockIterator) Progress ¶ added in v0.22.0
func (it *BlobBlockIterator) Progress() (current, end uint64)
Progress returns the current slot being iterated and the end slot. If no end slot was specified (iterate to tip), end returns 0.
type BlobBlockResult ¶ added in v0.22.0
type BlobBlockResult struct {
Slot uint64
Hash []byte
Cbor []byte
BlockType uint
Height uint64
PrevHash []byte
}
BlobBlockResult holds the data returned by BlobBlockIterator.NextRaw.
type BlockIndexer ¶ added in v0.22.0
type BlockIndexer struct {
// contains filtered or unexported fields
}
BlockIndexer computes byte offsets for all items within a block. It uses gouroboros's ExtractTransactionOffsets for efficient offset extraction.
func NewBlockIndexer ¶ added in v0.22.0
func NewBlockIndexer(slot uint64, hash []byte) *BlockIndexer
NewBlockIndexer creates a new BlockIndexer for the given block.
func (*BlockIndexer) ComputeOffsets ¶ added in v0.22.0
func (bi *BlockIndexer) ComputeOffsets( blockCbor []byte, block ledger.Block, ) (*BlockIngestionResult, error)
ComputeOffsets extracts byte offsets for all transactions, UTxOs, datums, redeemers, and scripts within the block CBOR.
type BlockIngestionResult ¶ added in v0.22.0
type BlockIngestionResult struct {
// TxOffsets maps transaction hash to its CborOffset within the block.
// This stores only the transaction body offset for backward compatibility.
TxOffsets map[[32]byte]CborOffset
// TxParts maps transaction hash to all 4 component offsets within the block.
// This enables byte-perfect reconstruction of complete standalone transaction
// CBOR from the source block by extracting and reassembling:
// body, witness, is_valid, and metadata (optional).
TxParts map[[32]byte]TxCborParts
// UtxoOffsets maps UTxO reference to its CborOffset within the block
UtxoOffsets map[UtxoRef]CborOffset
// DatumOffsets maps datum hash to its CborOffset within the block
DatumOffsets map[[32]byte]CborOffset
// RedeemerOffsets maps redeemer key to its CborOffset within the block
RedeemerOffsets map[common.RedeemerKey]CborOffset
// ScriptOffsets maps script hash to its CborOffset within the block
ScriptOffsets map[[32]byte]CborOffset
}
BlockIngestionResult contains pre-computed offsets for all items in a block. This is computed during block ingestion and used to store offset references instead of duplicating CBOR data.
type BlockLRUCache ¶ added in v0.21.0
type BlockLRUCache struct {
// contains filtered or unexported fields
}
BlockLRUCache is a thread-safe LRU cache for recently accessed blocks. Blocks are keyed by (slot, hash) and evicted in LRU order when the cache exceeds maxEntries.
func NewBlockLRUCache ¶ added in v0.21.0
func NewBlockLRUCache(maxEntries int) *BlockLRUCache
NewBlockLRUCache creates a new BlockLRUCache with the specified maximum number of entries. If maxEntries is negative, it is treated as zero (cache disabled).
func (*BlockLRUCache) Get ¶ added in v0.21.0
func (c *BlockLRUCache) Get(slot uint64, hash [32]byte) (*CachedBlock, bool)
Get retrieves a cached block by slot and hash. Returns the block and true if found, or nil and false if not found. Accessing a block moves it to the front of the LRU list.
func (*BlockLRUCache) Put ¶ added in v0.21.0
func (c *BlockLRUCache) Put(slot uint64, hash [32]byte, block *CachedBlock)
Put adds or updates a block in the cache. The block is moved to the front of the LRU list. If the cache exceeds maxEntries, the least recently used block is evicted.
type CacheMetrics ¶ added in v0.21.0
type CacheMetrics struct {
UtxoHotHits atomic.Uint64
UtxoHotMisses atomic.Uint64
TxHotHits atomic.Uint64
TxHotMisses atomic.Uint64
BlockLRUHits atomic.Uint64
BlockLRUMisses atomic.Uint64
ColdExtractions atomic.Uint64
// contains filtered or unexported fields
}
CacheMetrics holds atomic counters for cache performance monitoring.
func (*CacheMetrics) IncBlockLRUHit ¶ added in v0.22.0
func (m *CacheMetrics) IncBlockLRUHit()
IncBlockLRUHit increments the block LRU cache hit counter.
func (*CacheMetrics) IncBlockLRUMiss ¶ added in v0.22.0
func (m *CacheMetrics) IncBlockLRUMiss()
IncBlockLRUMiss increments the block LRU cache miss counter.
func (*CacheMetrics) IncColdExtraction ¶ added in v0.22.0
func (m *CacheMetrics) IncColdExtraction()
IncColdExtraction increments the cold extraction counter.
func (*CacheMetrics) IncTxHotHit ¶ added in v0.22.0
func (m *CacheMetrics) IncTxHotHit()
IncTxHotHit increments the TX hot cache hit counter.
func (*CacheMetrics) IncTxHotMiss ¶ added in v0.22.0
func (m *CacheMetrics) IncTxHotMiss()
IncTxHotMiss increments the TX hot cache miss counter.
func (*CacheMetrics) IncUtxoHotHit ¶ added in v0.22.0
func (m *CacheMetrics) IncUtxoHotHit()
IncUtxoHotHit increments the UTxO hot cache hit counter.
func (*CacheMetrics) IncUtxoHotMiss ¶ added in v0.22.0
func (m *CacheMetrics) IncUtxoHotMiss()
IncUtxoHotMiss increments the UTxO hot cache miss counter.
func (*CacheMetrics) Register ¶ added in v0.22.0
func (m *CacheMetrics) Register(registry prometheus.Registerer)
Register registers Prometheus metrics with the given registry. If registry is nil, this is a no-op. This method is idempotent; subsequent calls after the first successful registration are no-ops.
type CachedBlock ¶ added in v0.21.0
type CachedBlock struct {
// RawBytes contains the block's raw CBOR data.
RawBytes []byte
// TxIndex maps transaction hashes to their location in RawBytes.
TxIndex map[[32]byte]Location
// OutputIndex maps UTxO output keys to their location in RawBytes.
OutputIndex map[OutputKey]Location
}
CachedBlock holds a block's raw CBOR data along with pre-computed indexes for fast extraction of transactions and UTxO outputs.
func (*CachedBlock) Extract ¶ added in v0.21.0
func (cb *CachedBlock) Extract(offset, length uint32) []byte
Extract returns a copy of RawBytes from offset to offset+length. Returns nil if the range is out of bounds. The returned slice is a defensive copy so callers may freely modify it without corrupting the cached block data.
type CborCacheConfig ¶ added in v0.21.0
type CborCacheConfig struct {
HotUtxoEntries int // Number of UTxO CBOR entries in hot cache
HotTxEntries int // Number of TX CBOR entries in hot cache
HotTxMaxBytes int64 // Memory limit for TX hot cache (0 = no limit)
BlockLRUEntries int // Number of blocks in LRU cache
}
CborCacheConfig holds configuration for the TieredCborCache.
type CborOffset ¶ added in v0.21.0
type CborOffset struct {
BlockSlot uint64 // Slot number of the block containing the CBOR
BlockHash [32]byte // Hash of the block containing the CBOR
ByteOffset uint32 // Byte offset within the block's CBOR data
ByteLength uint32 // Length of the CBOR data in bytes
}
CborOffset represents a reference to CBOR data within a block. Instead of storing duplicate CBOR data, we store an offset reference that points to the CBOR within the block's raw data.
func DecodeCborOffset ¶ added in v0.21.0
func DecodeCborOffset(data []byte) (*CborOffset, error)
DecodeCborOffset deserializes a 52-byte big-endian encoded slice into a CborOffset. Returns an error if the input data is not exactly 52 bytes or has wrong magic.
func DecodeTxOffset ¶ added in v0.22.0
func DecodeTxOffset(data []byte) (*CborOffset, error)
DecodeTxOffset decodes offset-based transaction storage data. Returns an error if the data is not exactly 52 bytes or has wrong magic.
func DecodeUtxoOffset ¶ added in v0.22.0
func DecodeUtxoOffset(data []byte) (*CborOffset, error)
DecodeUtxoOffset decodes offset-based UTxO storage data. Returns an error if the data is not exactly 52 bytes or has wrong magic.
func (*CborOffset) Encode ¶ added in v0.21.0
func (c *CborOffset) Encode() []byte
Encode serializes the CborOffset to a 52-byte big-endian encoded slice. Layout:
- bytes 0-3: Magic "DOFF" (identifies offset storage)
- bytes 4-11: BlockSlot (big-endian uint64)
- bytes 12-43: BlockHash (32 bytes)
- bytes 44-47: ByteOffset (big-endian uint32)
- bytes 48-51: ByteLength (big-endian uint32)
type CommitTimestampError ¶
CommitTimestampError contains the timestamps of the metadata and blob stores
func (CommitTimestampError) Error ¶
func (e CommitTimestampError) Error() string
Error returns the stringified error
type Config ¶ added in v0.12.1
type Config struct {
PromRegistry prometheus.Registerer
Logger *slog.Logger
BlobPlugin string
DataDir string
MetadataPlugin string
MaxConnections int // Connection pool size for metadata plugin (should match DatabaseWorkers)
StorageMode string // "core" or "api"
CacheConfig CborCacheConfig
}
Config represents the configuration for a database instance
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database represents our data storage services
func New ¶ added in v0.4.3
New creates a new database instance with optional persistence using the provided data directory. When config is nil, DefaultConfig is used (DataDir = ".dingo" for persistence). When config is provided but DataDir is empty, storage is in-memory only. When config.DataDir is non-empty, it specifies the persistent storage directory.
func (*Database) ApplyPParamUpdates ¶ added in v0.4.4
func (*Database) BlobTxn ¶ added in v0.4.3
BlobTxn starts a new blob-only database transaction and returns a handle to it
func (*Database) BlockByIndex ¶ added in v0.4.5
func (*Database) BlockCreate ¶ added in v0.4.5
func (*Database) BlocksFromSlot ¶ added in v0.22.0
func (d *Database) BlocksFromSlot(startSlot uint64) *BlobBlockIterator
BlocksFromSlot returns an iterator that yields blocks starting from startSlot, continuing through all subsequent blocks in the blob store.
func (*Database) BlocksInRange ¶ added in v0.22.0
func (d *Database) BlocksInRange( startSlot, endSlot uint64, ) *BlobBlockIterator
BlocksInRange returns an iterator for a specific slot range [start, end]. Both endpoints are inclusive.
func (*Database) CborCache ¶ added in v0.22.0
func (d *Database) CborCache() *TieredCborCache
CborCache returns the tiered CBOR cache for accessing cached CBOR data. This can be used for metrics registration or direct cache access.
func (*Database) ClearSyncState ¶ added in v0.22.0
ClearSyncState removes all sync state entries.
func (*Database) ComputeAndApplyPParamUpdates ¶ added in v0.21.0
func (d *Database) ComputeAndApplyPParamUpdates( slot, epoch uint64, era uint, quorum int, currentPParams lcommon.ProtocolParameters, decodeFunc func([]byte) (any, error), updateFunc func( lcommon.ProtocolParameters, any, ) (lcommon.ProtocolParameters, error), txn *Txn, ) (lcommon.ProtocolParameters, error)
ComputeAndApplyPParamUpdates computes the new protocol parameters by applying pending updates for the given target epoch. The epoch parameter should be the epoch where updates take effect (currentEpoch + 1 during epoch rollover). The quorum parameter specifies the minimum number of unique genesis key delegates that must have submitted update proposals for the update to be applied (from shelley-genesis.json updateQuorum). This function takes currentPParams as a value and returns the updated parameters without mutating the input. This allows callers to capture the result in a transaction and apply it to in-memory state after the transaction commits.
func (*Database) Config ¶ added in v0.12.1
Config returns the config object used for the database instance
func (*Database) DataDir ¶ added in v0.4.3
DataDir returns the path to the data directory used for storage
func (*Database) DeleteBlockNoncesBeforeSlot ¶ added in v0.11.0
DeleteBlockNoncesBeforeSlot removes all block_nonces older than the given slot number
func (*Database) DeleteBlockNoncesBeforeSlotWithoutCheckpoints ¶ added in v0.11.0
func (d *Database) DeleteBlockNoncesBeforeSlotWithoutCheckpoints( slotNumber uint64, txn *Txn, ) error
DeleteBlockNoncesBeforeSlotWithoutCheckpoints removes non-checkpoint block_nonces older than the given slot number
func (*Database) DeleteCertificatesAfterSlot ¶ added in v0.22.0
DeleteCertificatesAfterSlot removes all certificate records added after the given slot. This is used during chain rollbacks to undo certificate state changes.
func (*Database) DeleteConstitutionsAfterSlot ¶ added in v0.22.0
DeleteConstitutionsAfterSlot removes constitutions added after the given slot and clears deleted_slot for any that were soft-deleted after that slot. This is used during chain rollbacks.
func (*Database) DeleteEpochsAfterSlot ¶ added in v0.22.0
func (*Database) DeleteGovernanceProposalsAfterSlot ¶ added in v0.22.0
DeleteGovernanceProposalsAfterSlot removes governance proposals added after the given slot and clears deleted_slot for any that were soft-deleted after that slot. This is used during chain rollbacks.
func (*Database) DeleteGovernanceVotesAfterSlot ¶ added in v0.22.0
DeleteGovernanceVotesAfterSlot removes governance votes added after the given slot and clears deleted_slot for any that were soft-deleted after that slot. This is used during chain rollbacks.
func (*Database) DeleteNetworkStateAfterSlot ¶ added in v0.22.0
DeleteNetworkStateAfterSlot removes network state records added after the given slot. This is used during chain rollbacks.
func (*Database) DeletePParamUpdatesAfterSlot ¶ added in v0.22.0
DeletePParamUpdatesAfterSlot removes protocol parameter update records added after the given slot.
func (*Database) DeletePParamsAfterSlot ¶ added in v0.22.0
DeletePParamsAfterSlot removes protocol parameter records added after the given slot.
func (*Database) DeleteSyncState ¶ added in v0.22.0
DeleteSyncState removes a sync state key.
func (*Database) GetAccount ¶ added in v0.6.0
func (d *Database) GetAccount( stakeKey []byte, includeInactive bool, txn *Txn, ) (*models.Account, error)
GetAccount returns an account by staking key
func (*Database) GetActiveCommitteeMembers ¶ added in v0.22.0
func (d *Database) GetActiveCommitteeMembers( txn *Txn, ) ([]*models.AuthCommitteeHot, error)
GetActiveCommitteeMembers returns all active committee members
func (*Database) GetActiveDreps ¶ added in v0.22.0
GetActiveDreps returns all active DReps
func (*Database) GetActiveGovernanceProposals ¶ added in v0.22.0
func (d *Database) GetActiveGovernanceProposals( epoch uint64, txn *Txn, ) ([]*models.GovernanceProposal, error)
GetActiveGovernanceProposals returns all governance proposals that haven't expired
func (*Database) GetActivePoolRelays ¶ added in v0.21.0
func (d *Database) GetActivePoolRelays( txn *Txn, ) ([]models.PoolRegistrationRelay, error)
GetActivePoolRelays returns all relays from currently active pools. This is used for ledger peer discovery.
func (*Database) GetAddressesByStakingKey ¶ added in v0.22.0
func (d *Database) GetAddressesByStakingKey( stakingKey []byte, limit int, offset int, txn *Txn, ) ([]models.AddressTransaction, error)
GetAddressesByStakingKey returns distinct address mappings for a staking key.
func (*Database) GetBlockNonce ¶ added in v0.11.0
GetBlockNonce fetches the block nonce for a given chain point
func (*Database) GetBlockNoncesInSlotRange ¶ added in v0.22.0
func (d *Database) GetBlockNoncesInSlotRange( startSlot uint64, endSlot uint64, txn *Txn, ) ([]models.BlockNonce, error)
GetBlockNoncesInSlotRange fetches all block nonces in [startSlot, endSlot).
func (*Database) GetCommitteeActiveCount ¶ added in v0.22.0
GetCommitteeActiveCount returns the number of active (non-resigned) committee members.
func (*Database) GetCommitteeMember ¶ added in v0.22.0
func (d *Database) GetCommitteeMember( coldKey []byte, txn *Txn, ) (*models.AuthCommitteeHot, error)
GetCommitteeMember returns a committee member by cold key
func (*Database) GetConstitution ¶ added in v0.22.0
func (d *Database) GetConstitution(txn *Txn) (*models.Constitution, error)
GetConstitution returns the current constitution
func (*Database) GetDRepVotingPower ¶ added in v0.22.0
GetDRepVotingPower calculates the voting power for a DRep by summing the stake of all accounts delegated to it. Uses the current live UTxO set (deleted_slot = 0) for the calculation.
func (*Database) GetEpochsByEra ¶ added in v0.4.3
func (*Database) GetExpiredDReps ¶ added in v0.22.0
GetExpiredDReps returns all active DReps whose expiry epoch is at or before the given epoch.
func (*Database) GetGovernanceProposal ¶ added in v0.22.0
func (d *Database) GetGovernanceProposal( txHash []byte, actionIndex uint32, txn *Txn, ) (*models.GovernanceProposal, error)
GetGovernanceProposal returns a governance proposal by transaction hash and action index
func (*Database) GetGovernanceVotes ¶ added in v0.22.0
func (d *Database) GetGovernanceVotes( proposalID uint, txn *Txn, ) ([]*models.GovernanceVote, error)
GetGovernanceVotes returns all votes for a governance proposal
func (*Database) GetPParams ¶ added in v0.4.4
func (d *Database) GetPParams( epoch uint64, decodeFunc func([]byte) (lcommon.ProtocolParameters, error), txn *Txn, ) (lcommon.ProtocolParameters, error)
func (*Database) GetPool ¶ added in v0.17.0
func (d *Database) GetPool( pkh lcommon.PoolKeyHash, includeInactive bool, txn *Txn, ) (*models.Pool, error)
GetPool returns a pool by its key hash
func (*Database) GetPoolByVrfKeyHash ¶ added in v0.22.0
GetPoolByVrfKeyHash retrieves an active pool by its VRF key hash. Returns nil if no active pool uses this VRF key.
func (*Database) GetPoolRegistrations ¶ added in v0.4.3
func (d *Database) GetPoolRegistrations( poolKeyHash lcommon.PoolKeyHash, txn *Txn, ) ([]lcommon.PoolRegistrationCertificate, error)
GetPoolRegistrations returns a list of pool registration certificates
func (*Database) GetStakeRegistrations ¶ added in v0.4.3
func (d *Database) GetStakeRegistrations( stakingKey []byte, txn *Txn, ) ([]lcommon.StakeRegistrationCertificate, error)
GetStakeRegistrations returns a list of stake registration certificates
func (*Database) GetSyncState ¶ added in v0.22.0
GetSyncState retrieves a sync state value by key. Returns empty string if the key does not exist.
func (*Database) GetTip ¶ added in v0.4.3
func (d *Database) GetTip(txn *Txn) (ochainsync.Tip, error)
GetTip returns the current tip as represented by the protocol
func (*Database) GetTransactionByHash ¶ added in v0.21.0
func (*Database) GetTransactionsByAddress ¶ added in v0.22.0
func (d *Database) GetTransactionsByAddress( addr lcommon.Address, limit int, offset int, txn *Txn, ) ([]models.Transaction, error)
GetTransactionsByAddress returns transactions that involve a given address as either a sender (input) or receiver (output). Results are returned in descending on-chain order.
func (*Database) GetTransactionsByAddressKeys ¶ added in v0.22.0
func (d *Database) GetTransactionsByAddressKeys( paymentKey []byte, stakingKey []byte, limit int, offset int, order string, txn *Txn, ) ([]models.Transaction, error)
GetTransactionsByAddressKeys returns transactions for a payment/staking key tuple with pagination and explicit order (asc|desc).
func (*Database) GetTransactionsByBlockHash ¶ added in v0.22.0
func (d *Database) GetTransactionsByBlockHash( blockHash []byte, txn *Txn, ) ([]models.Transaction, error)
GetTransactionsByBlockHash returns all transactions for a given block hash, ordered by their position within the block.
func (*Database) HasAnyGenesisCbor ¶ added in v0.22.0
HasAnyGenesisCbor checks whether any genesis CBOR data exists at the given slot, regardless of hash. This is used to distinguish between "no genesis CBOR" (e.g., after Mithril bootstrap) and "genesis CBOR exists but with a different hash" (true network mismatch).
func (*Database) HasGenesisCbor ¶ added in v0.22.0
HasGenesisCbor checks whether genesis CBOR data exists at the expected blob key for the given slot and hash. This is used to validate that existing chain data matches the current genesis configuration.
func (*Database) IsCommitteeMemberResigned ¶ added in v0.22.0
IsCommitteeMemberResigned checks if a committee member has resigned
func (*Database) Metadata ¶
func (d *Database) Metadata() metadata.MetadataStore
Metadata returns the underlying metadata store instance
func (*Database) MetadataTxn ¶ added in v0.4.3
MetadataTxn starts a new metadata-only database transaction and returns a handle to it
func (*Database) RestoreAccountStateAtSlot ¶ added in v0.22.0
RestoreAccountStateAtSlot reverts account delegation state to the given slot. For accounts modified after the slot, this restores their Pool and Drep delegations to the state they had at the given slot, or deletes them if they were registered after that slot.
func (*Database) RestoreDrepStateAtSlot ¶ added in v0.22.0
RestoreDrepStateAtSlot reverts DRep state to the given slot. DReps registered only after the slot are deleted; remaining DReps have their anchor and active status restored.
func (*Database) RestorePoolStateAtSlot ¶ added in v0.22.0
RestorePoolStateAtSlot reverts pool state to the given slot. Pools registered only after the slot are deleted; remaining pools have their denormalized fields restored from the most recent registration at or before the slot.
func (*Database) SetBlobStore ¶ added in v0.22.0
func (*Database) SetBlockNonce ¶ added in v0.11.0
func (*Database) SetConstitution ¶ added in v0.22.0
func (d *Database) SetConstitution( constitution *models.Constitution, txn *Txn, ) error
SetConstitution saves the constitution
func (*Database) SetDatum ¶ added in v0.9.0
SetDatum saves the raw datum into the database by computing the hash before inserting.
func (*Database) SetGapBlockTransaction ¶ added in v0.22.0
func (d *Database) SetGapBlockTransaction( tx lcommon.Transaction, point ocommon.Point, idx uint32, offsets *BlockIngestionResult, txn *Txn, ) error
SetGapBlockTransaction stores a transaction from a mithril gap block. It records blob offsets (TX and UTxO) for CBOR resolution and creates a minimal metadata record, but does NOT look up or consume input UTxOs because the mithril snapshot already reflects the correct spent/unspent state.
func (*Database) SetGenesisCbor ¶ added in v0.22.0
SetGenesisCbor stores synthetic genesis CBOR data without creating a block index entry. This allows the CBOR to be retrieved for offset-based UTxO extraction while preventing the chain iterator from trying to decode it as a real block (which would fail since genesis CBOR is just concatenated UTxO data, not a valid block structure).
func (*Database) SetGenesisStaking ¶ added in v0.22.0
func (d *Database) SetGenesisStaking( pools map[string]lcommon.PoolRegistrationCertificate, stakeDelegations map[string]string, blockHash []byte, txn *Txn, ) error
SetGenesisStaking stores genesis pool registrations and stake delegations. This is metadata-only (no blob operations needed).
func (*Database) SetGenesisTransaction ¶ added in v0.22.0
func (d *Database) SetGenesisTransaction( txHash []byte, blockHash []byte, outputs []lcommon.Utxo, offsets map[UtxoRef]CborOffset, txn *Txn, ) error
SetGenesisTransaction stores a genesis transaction with its UTxO outputs. Genesis transactions have no inputs, witnesses, or fees - just outputs. The offsets map contains pre-computed byte offsets into the synthetic genesis block.
func (*Database) SetGovernanceProposal ¶ added in v0.22.0
func (d *Database) SetGovernanceProposal( proposal *models.GovernanceProposal, txn *Txn, ) error
SetGovernanceProposal creates or updates a governance proposal
func (*Database) SetGovernanceVote ¶ added in v0.22.0
func (d *Database) SetGovernanceVote( vote *models.GovernanceVote, txn *Txn, ) error
SetGovernanceVote records a vote on a governance proposal
func (*Database) SetPParamUpdate ¶ added in v0.4.4
func (*Database) SetPParams ¶ added in v0.4.4
func (*Database) SetSyncState ¶ added in v0.22.0
SetSyncState stores or updates a sync state value.
func (*Database) SetTip ¶ added in v0.4.3
func (d *Database) SetTip(tip ochainsync.Tip, txn *Txn) error
SetTip saves the current tip
func (*Database) SetTransaction ¶ added in v0.18.0
func (d *Database) SetTransaction( tx lcommon.Transaction, point ocommon.Point, idx uint32, updateEpoch uint64, pparamUpdates map[lcommon.Blake2b224]lcommon.ProtocolParameterUpdate, certDeposits map[int]uint64, offsets *BlockIngestionResult, txn *Txn, ) error
func (*Database) StorageMode ¶ added in v0.22.0
StorageMode returns the configured storage mode ("core" or "api").
func (*Database) Transaction ¶
Transaction starts a new database transaction and returns a handle to it
func (*Database) TransactionsDeleteRolledback ¶ added in v0.22.0
TransactionsDeleteRolledback deletes transaction offset blobs and metadata for transactions added after the given slot. This is used during rollback to clean up both blob storage and metadata for rolled-back transactions.
func (*Database) UpdateDRepActivity ¶ added in v0.22.0
func (d *Database) UpdateDRepActivity( drepCredential []byte, activityEpoch uint64, inactivityPeriod uint64, txn *Txn, ) error
UpdateDRepActivity updates the DRep's last activity epoch and recalculates the expiry epoch.
func (*Database) UtxoByRefIncludingSpent ¶ added in v0.22.0
func (d *Database) UtxoByRefIncludingSpent( txId []byte, outputIdx uint32, txn *Txn, ) (*models.Utxo, error)
UtxoByRefIncludingSpent returns a Utxo by reference, including spent (consumed) UTxOs.
func (*Database) UtxosByAddress ¶ added in v0.4.3
func (*Database) UtxosByAddressAtSlot ¶ added in v0.22.0
func (*Database) UtxosByAssets ¶ added in v0.21.0
func (d *Database) UtxosByAssets( policyId []byte, assetName []byte, txn *Txn, ) ([]models.Utxo, error)
UtxosByAssets returns UTxOs that contain the specified assets policyId: the policy ID of the asset (required) assetName: the asset name (pass nil to match all assets under the policy, or empty []byte{} to match assets with empty names)
func (*Database) UtxosDeleteConsumed ¶ added in v0.4.4
func (*Database) UtxosDeleteRolledback ¶ added in v0.4.3
type HotCache ¶ added in v0.21.0
type HotCache struct {
// contains filtered or unexported fields
}
HotCache provides a lock-free cache for frequently accessed CBOR data. It uses copy-on-write semantics for thread-safe concurrent access without locks. Eviction follows a Least-Frequently-Used (LFU) policy with probabilistic counting.
func NewHotCache ¶ added in v0.21.0
NewHotCache creates a new HotCache with the given size and memory limits. Set maxSize to 0 for unlimited entries (limited only by maxBytes). Set maxBytes to 0 for unlimited memory (limited only by maxSize).
func (*HotCache) Get ¶ added in v0.21.0
Get retrieves a value from the cache by key. Returns the value and true if found, nil and false otherwise. This operation is lock-free and safe for concurrent use. Access counts are updated probabilistically (1 in accessSampleRate calls) to reduce overhead while maintaining approximate LFU behavior.
type OutputKey ¶ added in v0.21.0
OutputKey uniquely identifies a transaction output within a block.
type PartialCommitError ¶ added in v0.21.0
type PartialCommitError struct {
MetadataErr error // The underlying metadata commit error
CommitTimestamp int64 // Timestamp written to the blob store
}
PartialCommitError is returned when blob commits but metadata fails. This indicates the database is in an inconsistent state requiring recovery.
func (PartialCommitError) Error ¶ added in v0.21.0
func (e PartialCommitError) Error() string
func (PartialCommitError) Is ¶ added in v0.21.0
func (e PartialCommitError) Is(target error) bool
Is allows errors.Is(err, types.ErrPartialCommit) to match this error.
func (PartialCommitError) Unwrap ¶ added in v0.21.0
func (e PartialCommitError) Unwrap() error
type PositionReader ¶ added in v0.21.0
type PositionReader struct {
// contains filtered or unexported fields
}
PositionReader wraps an io.Reader and tracks the current byte position. This is useful for tracking offsets during CBOR parsing to compute positions of transactions and UTxOs within block data.
func NewPositionReader ¶ added in v0.21.0
func NewPositionReader(r io.Reader) *PositionReader
NewPositionReader creates a new PositionReader wrapping the given reader. The initial position is 0.
func (*PositionReader) Position ¶ added in v0.21.0
func (pr *PositionReader) Position() int64
Position returns the current byte position in the reader.
type TieredCborCache ¶ added in v0.21.0
type TieredCborCache struct {
// contains filtered or unexported fields
}
TieredCborCache orchestrates the tiered cache system for CBOR data resolution. It checks hot caches first, then falls back to block extraction.
Cache tiers:
- Tier 1: Hot caches (hotUtxo for UTxO CBOR, hotTx for transaction CBOR)
- Tier 2: Block LRU cache (shared block cache with pre-computed indexes)
- Tier 3: Cold extraction from blob store
func NewTieredCborCache ¶ added in v0.21.0
func NewTieredCborCache(config CborCacheConfig, db *Database) *TieredCborCache
NewTieredCborCache creates a new TieredCborCache with the given configuration. The db parameter provides access to the blob store for cold path resolution.
func (*TieredCborCache) Metrics ¶ added in v0.21.0
func (c *TieredCborCache) Metrics() *CacheMetrics
Metrics returns the cache metrics for monitoring and observability.
func (*TieredCborCache) ResolveTxCbor ¶ added in v0.21.0
func (c *TieredCborCache) ResolveTxCbor(txHash []byte) ([]byte, error)
ResolveTxCbor resolves transaction body CBOR data by transaction hash. It checks caches in order: hot TX cache, block LRU cache, then blob store.
NOTE: This returns only the transaction BODY CBOR, not a complete standalone transaction. Cardano blocks store bodies and witnesses in separate arrays, so reconstructing a complete transaction ([body, witness, is_valid, aux_data]) would require fetching multiple components. Use tx.Cbor() from the parsed block if you need complete transaction CBOR for decoding.
func (*TieredCborCache) ResolveTxCborBatch ¶ added in v0.22.0
func (c *TieredCborCache) ResolveTxCborBatch( txHashes [][32]byte, ) (map[[32]byte][]byte, error)
ResolveTxCborBatch resolves multiple transaction CBOR entries in a single batch. It groups requests by block to minimize blob store fetches.
func (*TieredCborCache) ResolveUtxoCbor ¶ added in v0.21.0
func (c *TieredCborCache) ResolveUtxoCbor( txId []byte, outputIdx uint32, blobTxn ...types.Txn, ) ([]byte, error)
ResolveUtxoCbor resolves UTxO CBOR data by transaction ID and output index. It checks caches in order: hot UTxO cache, block LRU cache, then blob store. An optional blob transaction can be provided to see uncommitted writes within the same transaction (important for intra-batch UTxO lookups during validation).
func (*TieredCborCache) ResolveUtxoCborBatch ¶ added in v0.21.0
func (c *TieredCborCache) ResolveUtxoCborBatch( refs []UtxoRef, ) (map[UtxoRef][]byte, error)
ResolveUtxoCborBatch resolves multiple UTxO CBOR entries in a single batch. It groups requests by block to minimize blob store fetches.
type TxCborParts ¶ added in v0.22.0
type TxCborParts struct {
BlockSlot uint64 // Slot number of the block containing the transaction
BlockHash [32]byte // Hash of the block containing the transaction
BodyOffset uint32 // Byte offset of transaction body within block CBOR
BodyLength uint32 // Length of transaction body in bytes
WitnessOffset uint32 // Byte offset of witness set within block CBOR
WitnessLength uint32 // Length of witness set in bytes
MetadataOffset uint32 // Byte offset of metadata within block CBOR (0 if none)
MetadataLength uint32 // Length of metadata in bytes (0 if none)
IsValid bool // True if transaction is valid (not in invalid_txs)
}
TxCborParts stores byte offsets for all 4 components of a Cardano transaction. This enables byte-perfect reconstruction of standalone transaction CBOR from the source block.
A complete standalone transaction has the CBOR structure:
[body, witness, is_valid, metadata]
However, in Cardano blocks, these components are stored in separate arrays:
[header, [bodies...], [witnesses...], {metadata_map}, [invalid_txs]]
TxCborParts stores the location of each component so they can be extracted and reassembled into a complete transaction.
func DecodeTxCborParts ¶ added in v0.22.0
func DecodeTxCborParts(data []byte) (*TxCborParts, error)
DecodeTxCborParts deserializes a 69-byte big-endian encoded slice into TxCborParts. Returns an error if the input data is not exactly 69 bytes or has wrong magic.
func (*TxCborParts) Encode ¶ added in v0.22.0
func (t *TxCborParts) Encode() []byte
Encode serializes TxCborParts to a 69-byte big-endian encoded slice. Layout:
- bytes 0-3: Magic "DTXP"
- bytes 4-11: BlockSlot (big-endian uint64)
- bytes 12-43: BlockHash (32 bytes)
- bytes 44-47: BodyOffset (big-endian uint32)
- bytes 48-51: BodyLength (big-endian uint32)
- bytes 52-55: WitnessOffset (big-endian uint32)
- bytes 56-59: WitnessLength (big-endian uint32)
- bytes 60-63: MetadataOffset (big-endian uint32)
- bytes 64-67: MetadataLength (big-endian uint32)
- byte 68: IsValid (0 = false, 1 = true)
func (*TxCborParts) HasMetadata ¶ added in v0.22.0
func (t *TxCborParts) HasMetadata() bool
HasMetadata returns true if the transaction has metadata.
func (*TxCborParts) ReassembleTxCbor ¶ added in v0.22.0
func (t *TxCborParts) ReassembleTxCbor(blockCbor []byte) ([]byte, error)
ReassembleTxCbor extracts all transaction components from the block CBOR and reassembles them into a complete standalone transaction CBOR.
The returned CBOR has the structure: [body, witness, is_valid, metadata] where metadata is null if the transaction has no auxiliary data.
This produces byte-perfect output when the original transaction had this exact structure. Note that Cardano blocks store components in separate arrays, so the reassembled CBOR may differ from tx.Cbor() which may use a different encoding order or structure.
type Txn ¶
type Txn struct {
// contains filtered or unexported fields
}
Txn is a wrapper that coordinates both metadata and blob transactions. Metadata and blob are first-class siblings, not nested.
func NewBlobOnlyTxn ¶ added in v0.4.3
func NewMetadataOnlyTxn ¶ added in v0.4.3
func (*Txn) Do ¶
Do executes the specified function in the context of the transaction. Any errors returned will result in the transaction being rolled back. If the function panics, the transaction is rolled back and the panic is re-raised after logging.
func (*Txn) Release ¶ added in v0.21.0
func (t *Txn) Release()
Release releases transaction resources. For read-only transactions, this releases locks and resources. For read-write transactions, this is equivalent to Rollback. Use this in defer statements for clean resource cleanup. Errors are logged but not returned, making this safe for deferred calls.
Source Files
¶
- account.go
- blob_iterator.go
- block.go
- block_indexer.go
- block_lru_cache.go
- block_nonce.go
- block_range.go
- cbor_cache.go
- cbor_offset.go
- certs.go
- commit_timestamp.go
- committee.go
- constitution.go
- database.go
- datum.go
- drep.go
- epoch.go
- governance.go
- hot_cache.go
- network_state.go
- pool.go
- position_reader.go
- pparams.go
- tip.go
- transaction.go
- txn.go
- utxo.go
Directories
¶
| Path | Synopsis |
|---|---|
|
metadata/importutil
Package importutil provides shared helpers for metadata import operations across all database backends (sqlite, postgres, mysql).
|
Package importutil provides shared helpers for metadata import operations across all database backends (sqlite, postgres, mysql). |