db

package
v0.1.1-rc2 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 78 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultNumTxRetries is the default number of times we'll retry a
	// transaction if it fails with an error that permits transaction
	// repetition.
	DefaultNumTxRetries = 10

	// DefaultInitialRetryDelay is the default initial delay between
	// retries. This will be used to generate a random delay between -50%
	// and +50% of this value, so 20 to 60 milliseconds. The retry will be
	// doubled after each attempt until we reach DefaultMaxRetryDelay. We
	// start with a random value to avoid multiple goroutines that are
	// created at the same time to effectively retry at the same time.
	DefaultInitialRetryDelay = time.Millisecond * 40

	// DefaultMaxRetryDelay is the default maximum delay between retries.
	DefaultMaxRetryDelay = time.Second * 3
)
View Source
const (
	// OORPackageDirectionIncoming marks packages received by this client.
	OORPackageDirectionIncoming = types.OORPackageDirectionIncoming

	// OORPackageDirectionOutgoing marks packages sent by this client.
	OORPackageDirectionOutgoing = types.OORPackageDirectionOutgoing
)
View Source
const (
	// OORPackageLinkKindCreatedOutput identifies bindings where the local
	// outpoint was created by the Ark transaction.
	OORPackageLinkKindCreatedOutput = types.OORPackageLinkKindCreatedOutput

	// OORPackageLinkKindConsumedInput identifies bindings where the local
	// outpoint was consumed as an OOR input.
	OORPackageLinkKindConsumedInput = types.OORPackageLinkKindConsumedInput
)
View Source
const (

	// SqliteSynchronousFull is the strictest SQLite synchronous level. It
	// fsyncs on every commit, trading throughput for the strongest
	// per-commit durability guarantee.
	SqliteSynchronousFull = "full"

	// SqliteSynchronousNormal relaxes the synchronous pragma to "normal".
	// Under WAL mode this omits the per-commit WAL fsync (syncing the WAL
	// only before a checkpoint), which is safe given our recoverable,
	// idempotent persistence stack.
	SqliteSynchronousNormal = "normal"

	// SqliteSynchronousOff disables synchronous flushing entirely. This is
	// the most aggressive (and least durable) level; a power loss may lose
	// recently committed transactions, but it never corrupts the database.
	SqliteSynchronousOff = "off"
)
View Source
const (
	// MaxTreeDeserializeDepth bounds the recursion depth allowed when
	// deserializing a tree.Tree blob. Production trees are radix-2
	// (binary) and refresh policy keeps practical depth well under
	// this; 32 is a generous safety margin that still fails fast on
	// adversarial linear-depth payloads.
	MaxTreeDeserializeDepth = 32

	// MaxTreeChildrenPerNode bounds the per-node child count read off
	// the wire before allocating the children map. The configured
	// radix is 2; this cap is a defense-in-depth ceiling that still
	// rejects a malicious uint64-shaped numChildren before it reaches
	// make().
	MaxTreeChildrenPerNode = 64
)

Tree-decode safety bounds. The wire layer feeds DeserializeTree from the durable mailbox, persisted rows, and operator-supplied indexer responses, all of which must be treated as untrusted. Without these caps, a varint-driven numChildren or a deeply nested chain could trigger a make() OOM or stack overflow that crashes the actor on every replay.

View Source
const (
	// LatestMigrationVersion is the latest migration version of the
	// database. This is used to implement downgrade protection for the
	// daemon.
	//
	// NOTE: This MUST be updated when a new migration is added.
	LatestMigrationVersion uint = 16
)
View Source
const (
	PostgresTag = "15"
)
View Source
const Subsystem = "DABS"

Subsystem defines the logging code for this subsystem.

Variables

View Source
var (
	// ErrInternalKeyPubKeyMissing is returned when a key descriptor with a
	// nil public key is registered or resolved.
	ErrInternalKeyPubKeyMissing = errors.New("internal key descriptor " +
		"has no public key")

	// ErrInternalKeyNotFound is returned when an internal key cannot be
	// resolved from the registry.
	ErrInternalKeyNotFound = errors.New("internal key not found")
)
View Source
var (
	// TargetLatest is a MigrationTarget that migrates to the latest
	// version available.
	TargetLatest = func(mig *migrate.Migrate, _ int, _ uint) error {
		return mig.Up()
	}

	// TargetVersion is a MigrationTarget that migrates to the given
	// version.
	TargetVersion = func(version uint) MigrationTarget {
		return func(mig *migrate.Migrate, _ int, _ uint) error {
			return mig.Migrate(version)
		}
	}
)
View Source
var (
	// ErrVHTLCRecoveryJobNotFound indicates the recovery row does not
	// exist.
	ErrVHTLCRecoveryJobNotFound = errors.New("vhtlc recovery job not found")

	// ErrVHTLCRecoveryIdempotencyConflict indicates an idempotent arm
	// request reused an existing key with different recovery parameters.
	ErrVHTLCRecoveryIdempotencyConflict = errors.New("vhtlc recovery " +
		"idempotency conflict")

	// ErrVHTLCRecoveryCannotEscalate indicates the recovery row exists but
	// is no longer in an armed state that can be escalated.
	ErrVHTLCRecoveryCannotEscalate = errors.New("vhtlc recovery cannot " +
		"escalate from current state")

	// ErrVHTLCRecoveryAlreadyTerminal indicates the recovery row exists
	// but is already in a terminal state (`completed`, `cancelled`, or
	// `failed`), so the requested transition is a no-op. Callers can
	// distinguish this from the missing-row case to avoid masking lost
	// updates between two racing terminal transitions.
	ErrVHTLCRecoveryAlreadyTerminal = errors.New("vhtlc recovery job is " +
		"already terminal")
)
View Source
var (
	// DefaultPostgresFixtureLifetime is the default maximum time a Postgres
	// test fixture is being kept alive. After that time the docker
	// container will be terminated forcefully, even if the tests aren't
	// fully executed yet. So this time needs to be chosen correctly to be
	// longer than the longest expected individual test run time.
	DefaultPostgresFixtureLifetime = 60 * time.Minute
)
View Source
var (
	// DefaultStoreTimeout is the default timeout used for any interaction
	// with the storage/database.
	DefaultStoreTimeout = time.Second * 10
)
View Source
var (
	// ErrCreditOperationNotFound indicates the credit operation row does
	// not exist.
	ErrCreditOperationNotFound = errors.New("credit operation row not " +
		"found")
)
View Source
var (
	// ErrOORSessionNotFound indicates the OOR session registry row does not
	// exist.
	ErrOORSessionNotFound = errors.New("oor session registry row not found")
)
View Source
var (
	// ErrResolveUnrollMaxDepthExceeded indicates resolver traversal
	// exceeded the configured depth bound.
	ErrResolveUnrollMaxDepthExceeded = errors.New("resolve unroll max " +
		"depth exceeded")
)
View Source
var (
	// ErrRetriesExceeded is returned when a transaction is retried more
	// than the max allowed valued without a success.
	ErrRetriesExceeded = errors.New("db tx retries exceeded")
)
View Source
var (
	// ErrUnilateralExitJobNotFound indicates the job row does not exist.
	ErrUnilateralExitJobNotFound = errors.New("unilateral exit job not " +
		"found")
)
View Source
var (
	// MaxValidSQLTime is the maximum valid time that can be rendered as a
	// time string and can be used for comparisons in SQL.
	MaxValidSQLTime = time.Date(9999, 12, 31, 23, 59, 59, 999999, time.UTC)
)

Functions

func AncestryFragmentKey

func AncestryFragmentKey(a vtxo.Ancestry) ([sha256.Size]byte, error)

AncestryFragmentKey returns a stable identity for one ancestry fragment: the sha256 of its commitment txid concatenated with its serialized tree path. Fragments are unique per (commitment txid, tree path) — NOT per commitment txid alone — because an OOR spend whose inputs sit at different leaves of the same commitment tree legitimately carries one fragment per leaf, each anchored at the same commitment. Callers use this key to reject true duplicates while admitting same-commitment multi-leaf ancestry.

The key deliberately excludes InputIndices (and CommitmentHeight): the indexer's grouping contract is one fragment per (commitment, tree path), with that fragment carrying EVERY input index it serves. Two fragments sharing a (commitment, path) but splitting the covered indices across rows would be a server-side grouping change; if the indexer contract ever moves that way, this key must widen with it or the second row is silently rejected as a duplicate.

func DeserializeTree

func DeserializeTree(data []byte) (*tree.Tree, error)

DeserializeTree deserializes a tree.Tree from bytes using TLV encoding.

func InsertTestdata

func InsertTestdata(t *testing.T, db *BaseDB, filePath string)

InsertTestdata reads the given file and inserts its content into the given database. The file should contain valid SQL statements.

func InternalKeyDescByIDTx

func InternalKeyDescByIDTx(ctx context.Context, qtx InternalKeyQuerier,
	id int64) (keychain.KeyDescriptor, error)

InternalKeyDescByIDTx reconstructs the internal key descriptor for a registry id within the caller's transaction/query context. It is the entry point consumer stores use to hydrate a descriptor from a referencing row's *_key_id foreign key on load.

func IsAbortedTransactionError

func IsAbortedTransactionError(err error) bool

IsAbortedTransactionError returns true if the given error reports that the transaction the statement ran in had already been aborted.

func IsDeadlockError

func IsDeadlockError(err error) bool

IsDeadlockError returns true if the given error is a deadlock error.

func IsRetryableTxError

func IsRetryableTxError(err error) bool

IsRetryableTxError returns true if the given error means the transaction it came from can be replayed from the top with a reasonable chance of a different outcome.

This is a superset of IsSerializationOrDeadlockError: it also covers the aborted-transaction state, which is what a caller that logs and swallows a serialization failure leaves behind for the next statement to trip over. Retrying on that echo costs a bounded number of replays when the underlying failure turns out to be deterministic, and recovers the transaction when it does not.

func IsSchemaError

func IsSchemaError(err error) bool

IsSchemaError returns true if the given error is a schema error.

func IsSerializationError

func IsSerializationError(err error) bool

IsSerializationError returns true if the given error is a serialization error.

func IsSerializationOrDeadlockError

func IsSerializationOrDeadlockError(err error) bool

IsSerializationOrDeadlockError returns true if the given error is either a deadlock error or a serialization error.

func IsUniqueConstraintViolation

func IsUniqueConstraintViolation(err error) bool

IsUniqueConstraintViolation returns true if the given error is a unique constraint violation.

This is deliberately not part of IsSerializationOrDeadlockError. A unique violation is not safe to retry blindly, because a retry of a plain insert that lost a creation race just loses it again. Callers that can lose such a race need to either rephrase the insert as a no-op upsert or translate the violation into a domain level "already exists", which is why the classifier is exposed separately.

func MapSQLError

func MapSQLError(err error) error

MapSQLError attempts to interpret a given error as a database agnostic SQL error.

func PgErrorConstraint

func PgErrorConstraint(err error) string

PgErrorConstraint extracts the name of the constraint that a Postgres error was raised against, if there is one. The schema carries six partial unique indexes, and without the constraint name a 23505 raised by any of them looks exactly like a 23505 raised by the table's primary key.

func PgErrorDetail

func PgErrorDetail(err error) string

PgErrorDetail extracts the Detail field of an underlying Postgres error, if there is one. The Error method of pgconn.PgError renders only the severity, the message and the SQLSTATE code, so the Detail is otherwise dropped on the floor before it ever reaches a log line.

That detail is the only thing that tells two very different 40001 aborts apart. A true serializable snapshot isolation abort carries a "Reason code" naming the transaction's role in the conflict graph, whereas an ordinary write-write conflict on the same row carries none. Once read-only transactions stop taking predicate locks, this is the signal that says whether a given write path still depends on SSI or would be equally happy at REPEATABLE READ. For a 23505 the detail names the constraint and the conflicting key values, which is what identifies a lost creation race.

func RandRetryDelay

func RandRetryDelay(attempt int) time.Duration

RandRetryDelay returns the default randomized backoff for the given retry attempt, doubling with each attempt and capped at DefaultMaxRetryDelay.

This exists so that transaction executors outside this type, such as the durable actor framework's commit transaction, can back off on exactly the same schedule instead of growing a second copy of the policy.

func RegisterInternalKeyTx

func RegisterInternalKeyTx(ctx context.Context, qtx InternalKeyQuerier,
	now int64, desc keychain.KeyDescriptor) (int64, error)

RegisterInternalKeyTx idempotently records desc within the caller's transaction/query context and returns its registry id, using now as the created_at timestamp for a freshly inserted row. It is the entry point consumer stores use to register-then-reference an internal key in the same transaction that writes the referencing row. Re-registering an identical (pubkey, key_family, key_index) triple returns the existing id.

Unlike the server registry, client keys carry no role: the canonical identity is the full (pubkey, key_family, key_index) triple, so there is no "same pubkey, different locator" conflict to surface -- a different triple is simply a different key.

func SerializeTree

func SerializeTree(t *tree.Tree) ([]byte, error)

SerializeTree serializes a tree.Tree to bytes using TLV encoding.

Types

type ActivityPersistenceStore

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

ActivityPersistenceStore persists the canonical activity log. ProjectEntry performs the atomic dual-write (upsert the current-state row, then append the transition row) that backs List and a resumable SubscribeWallet.

func NewActivityPersistenceStore

func NewActivityPersistenceStore(
	db BatchedActivityStore, clk clock.Clock,
) *ActivityPersistenceStore

NewActivityPersistenceStore creates an activity-log store using the transaction executor pattern.

func (*ActivityPersistenceStore) CountByStatus

func (s *ActivityPersistenceStore) CountByStatus(ctx context.Context,
	status int64) (int64, error)

CountByStatus returns the number of current-state rows in the given status. Unlike ListEntries it is not paginated, so it backs the wallet status summary's pending count with a true full-feed total.

func (*ActivityPersistenceStore) GetEntry

func (s *ActivityPersistenceStore) GetEntry(ctx context.Context,
	canonicalID string) (sqlc.ActivityEntry, error)

GetEntry returns one current-state row by its canonical id.

func (*ActivityPersistenceStore) ListEntries

func (s *ActivityPersistenceStore) ListEntries(ctx context.Context,
	cursorCreated int64, cursorID string, limit int32) (
	[]sqlc.ActivityEntry, error)

ListEntries returns up to limit current-state rows newest-first, starting after the (cursorCreated, cursorID) keyset. A cursorCreated of 0 starts from the newest row. The cursor is the immutable (created_at_unix, canonical_id) of the last row returned.

func (*ActivityPersistenceStore) ListEntriesByKindStatus

func (s *ActivityPersistenceStore) ListEntriesByKindStatus(ctx context.Context,
	kind, status int64, cursorID string, limit int32) ([]sqlc.ActivityEntry,
	error)

ListEntriesByKindStatus returns up to limit entries of the given kind and status, paged by canonical_id ascending after cursorID. Filtering in SQL keeps a scan for a specific kind/status (e.g. the startup rehydration of PENDING EXIT rows) proportional to the matching rows, and the unique canonical_id cursor is strictly monotonic.

func (*ActivityPersistenceStore) ProjectEntry

ProjectEntry advances the activity row to the projected state and records the transition, atomically. The entry is upserted before the event is appended so the activity_events foreign key is satisfied within the same transaction. It returns the event_seq assigned to the appended transition, or 0 when the projection was change-suppressed (no transition, so nothing to emit).

func (*ActivityPersistenceStore) PullEvents

func (s *ActivityPersistenceStore) PullEvents(ctx context.Context, cursor int64,
	limit int32) ([]sqlc.ActivityEvent, error)

PullEvents returns up to limit transition rows strictly after the event_seq cursor, in ascending event_seq order — the resumable-subscribe replay.

type ActivityProjection

type ActivityProjection struct {
	// CanonicalID is the stable identity used to update one activity row.
	CanonicalID string

	// Kind identifies the wallet activity category.
	Kind int64

	// Status is the lifecycle state being projected.
	Status int64

	// AmountSat is the signed activity amount in satoshis.
	AmountSat int64

	// FeeSat is the activity fee in satoshis.
	FeeSat int64

	// Counterparty identifies the activity destination or source.
	Counterparty string

	// Note is immutable user-facing context attached at admission.
	Note string

	// Phase identifies the current detailed lifecycle phase.
	Phase int64

	// PhaseLabel is the display label for Phase.
	PhaseLabel string

	// FailureCode identifies a terminal activity failure.
	FailureCode int64

	// FailureReason describes a terminal activity failure.
	FailureReason string

	// PendingStatus identifies the pending enum value used to reject stale
	// terminal-to-pending transitions.
	PendingStatus int64

	// PaymentHash correlates Lightning and credit payment activity.
	PaymentHash []byte

	// Txid identifies an on-chain activity transaction.
	Txid []byte

	// ConfirmationHeight is the on-chain confirmation height when known.
	ConfirmationHeight *int64

	// VtxoOutpoint identifies the Ark VTXO affected by this activity.
	VtxoOutpoint string

	// SwapSessionID correlates activity with its swap session.
	SwapSessionID []byte

	// LedgerTxid correlates activity with its credit ledger transaction.
	LedgerTxid []byte

	// BoardingAddr is the on-chain address used for a boarding deposit.
	BoardingAddr []byte

	// RequestJSON preserves the immutable activity request snapshot.
	RequestJSON string

	// EntryJSON is the protojson snapshot of the WalletEntry emitted at
	// this transition, stored verbatim on the activity_events row.
	EntryJSON string

	// CreatedAtUnix is the activity creation timestamp in Unix seconds.
	CreatedAtUnix int64

	// UpdatedAtUnix is the lifecycle update timestamp in Unix seconds.
	UpdatedAtUnix int64
}

ActivityProjection is the projector's input: a normalized snapshot of one activity row at a single lifecycle transition. The persistence store maps it to both an activity_entries upsert (current state) and an activity_events append (the transition), so the projector never touches sqlc params.

Empty BLOB handles MUST be passed as nil, never a zero-length slice, to avoid the Postgres BYTEA `x”` pitfall. ConfirmationHeight is nil until known.

type ActivityStore

type ActivityStore interface {
	UpsertActivityEntry(ctx context.Context,
		arg sqlc.UpsertActivityEntryParams) (int64, error)

	AppendActivityEvent(ctx context.Context,
		arg sqlc.AppendActivityEventParams) (int64, error)

	GetActivityEntry(ctx context.Context,
		canonicalID string) (sqlc.ActivityEntry, error)

	CountActivityEntriesByStatus(ctx context.Context,
		status int64) (int64, error)

	ListActivityEntries(ctx context.Context,
		arg sqlc.ListActivityEntriesParams) (
		[]sqlc.ActivityEntry,
		error,
	)

	ListEntriesByKindStatus(ctx context.Context,
		arg sqlc.ListEntriesByKindStatusParams) (
		[]sqlc.ActivityEntry,
		error,
	)

	PullActivityEvents(ctx context.Context,
		arg sqlc.PullActivityEventsParams) ([]sqlc.ActivityEvent, error)
}

ActivityStore groups the SQL methods needed to maintain the canonical activity log: the current-state activity_entries projection and the append-only activity_events transition log.

type BaseDB

type BaseDB struct {
	*sql.DB

	*sqlc.Queries
}

BaseDB is the base database struct that each implementation can embed to gain some common functionality.

func (*BaseDB) Backend

func (s *BaseDB) Backend() sqlc.BackendType

Backend returns the type of the database backend used.

func (*BaseDB) BeginTx

func (s *BaseDB) BeginTx(ctx context.Context, opts TxOptions) (*sql.Tx, error)

BeginTx wraps the normal sql specific BeginTx method with the TxOptions interface. This interface is then mapped to the concrete sql tx options struct.

type BaseTxOptions

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

BaseTxOptions defines the set of db txn options the database understands.

func ReadTxOption

func ReadTxOption() *BaseTxOptions

ReadTxOption returns a TxOptions that indicates a read-only transaction.

func WriteTxOption

func WriteTxOption() *BaseTxOptions

WriteTxOption returns a TxOptions that indicates a write transaction.

func (*BaseTxOptions) ReadOnly

func (a *BaseTxOptions) ReadOnly() bool

ReadOnly returns true if the transaction should be read only.

NOTE: This implements the TxOptions interface.

type BatchedActivityStore

type BatchedActivityStore interface {
	ActivityStore
	BatchedTx[ActivityStore]
}

BatchedActivityStore combines the query surface with batched transaction execution.

type BatchedBoardingStore

type BatchedBoardingStore interface {
	BoardingStore
	BatchedTx[BoardingStore]
}

BatchedBoardingStore combines BoardingStore with transaction support via the BatchedTx generic interface. This enables atomic operations across multiple queries.

type BatchedMacaroonRootKeyStore

type BatchedMacaroonRootKeyStore interface {
	MacaroonRootKeyStore
	BatchedTx[MacaroonRootKeyStore]
}

BatchedMacaroonRootKeyStore runs macaroon root key queries in transactions.

type BatchedOORArtifactStore

type BatchedOORArtifactStore interface {
	OORArtifactStore
	BatchedTx[OORArtifactStore]
}

BatchedOORArtifactStore combines OOR artifact queries with batched transaction execution.

type BatchedPendingIntentStore

type BatchedPendingIntentStore interface {
	PendingIntentStore
	BatchedTx[PendingIntentStore]
}

BatchedPendingIntentStore combines the query surface with batched transaction execution.

type BatchedQuerier

type BatchedQuerier interface {
	// Querier is the underlying query source, this is in place so we can
	// pass a BatchedQuerier implementation directly into objects that
	// create a batched version of the normal methods they need.
	sqlc.Querier

	// BeginTx creates a new database transaction given the set of
	// transaction options.
	BeginTx(ctx context.Context, options TxOptions) (*sql.Tx, error)

	// Backend returns the type of the database backend used.
	Backend() sqlc.BackendType
}

BatchedQuerier is a generic interface that allows callers to create a new database transaction based on an abstract type that implements the TxOptions interface.

type BatchedRoundStore

type BatchedRoundStore interface {
	RoundStore
	BatchedTx[RoundStore]
}

BatchedRoundStore combines RoundStore with transaction support via the BatchedTx generic interface. This enables atomic operations across multiple queries.

type BatchedSpendingReservationStore

type BatchedSpendingReservationStore interface {
	SpendingReservationStore
	BatchedTx[SpendingReservationStore]
}

BatchedSpendingReservationStore combines the query surface with batched transaction execution.

type BatchedTx

type BatchedTx[Q any] interface {
	// ExecTx will execute the passed txBody, operating upon generic
	// parameter Q (usually a storage interface) in a single transaction.
	// The set of TxOptions are passed in order to allow the caller to
	// specify if a transaction should be read-only and optionally what
	// type of concurrency control should be used.
	ExecTx(ctx context.Context, txOptions TxOptions,
		txBody func(Q) error) error

	// Backend returns the type of the database backend used.
	Backend() sqlc.BackendType
}

BatchedTx is a generic interface that represents the ability to execute several operations to a given storage interface in a single atomic transaction. Typically, Q here will be some subset of the main sqlc.Querier interface allowing it to only depend on the routines it needs to implement any additional business logic.

type BatchedUnilateralExitStore

type BatchedUnilateralExitStore interface {
	UnilateralExitStore
	BatchedTx[UnilateralExitStore]
}

BatchedUnilateralExitStore combines the query surface with transactions.

type BoardingAddrRow

type BoardingAddrRow = sqlc.BoardingAddress

type BoardingIntentKey

type BoardingIntentKey = sqlc.GetBoardingIntentParams

type BoardingIntentRow

type BoardingIntentRow = sqlc.BoardingIntent

type BoardingStore

type BoardingStore interface {
	// InternalKeyQuerier lets the boarding store register and hydrate the
	// client wallet key via the shared internal_keys registry within its
	// own transaction.
	InternalKeyQuerier

	InsertBoardingAddress(ctx context.Context, arg NewAddrParams) error

	GetBoardingAddress(ctx context.Context,
		pkScript []byte) (BoardingAddrRow, error)

	ListAllBoardingAddresses(ctx context.Context) ([]BoardingAddrRow, error)

	InsertBoardingIntent(ctx context.Context, arg NewIntentParams) error

	GetBoardingIntent(ctx context.Context,
		arg BoardingIntentKey) (BoardingIntentRow, error)

	ListBoardingIntentsByStatus(ctx context.Context,
		status string) ([]BoardingIntentRow, error)

	ListBoardingIntentsBySweepableStatuses(ctx context.Context,
		arg sqlc.ListBoardingIntentsBySweepableStatusesParams) (
		[]BoardingIntentRow, error)

	ListAllBoardingIntents(ctx context.Context) ([]BoardingIntentRow, error)

	ListBoardingIntentsByPkScript(ctx context.Context,
		pkScript []byte) ([]BoardingIntentRow, error)

	ListBoardingIntentOutpoints(ctx context.Context) ([]OutpointRow, error)

	ListBoardingIntentsByStatusAndMinHeight(ctx context.Context,
		arg IntentHeightFilter) ([]BoardingIntentRow, error)

	UpdateBoardingIntentStatus(ctx context.Context,
		arg sqlc.UpdateBoardingIntentStatusParams) error

	InsertBoardingSweep(
		ctx context.Context, arg sqlc.InsertBoardingSweepParams,
	) error

	InsertBoardingSweepInput(ctx context.Context,
		arg sqlc.InsertBoardingSweepInputParams) error

	GetBoardingSweep(ctx context.Context,
		txid []byte) (BoardingSweepRow, error)

	GetBoardingSweepByInput(ctx context.Context,
		arg sqlc.GetBoardingSweepByInputParams) (
		BoardingSweepRow,
		error,
	)

	ListBoardingSweepInputs(ctx context.Context,
		txid []byte) ([]BoardingSweepInputRow, error)

	ListBoardingSweeps(ctx context.Context,
		arg sqlc.ListBoardingSweepsParams) ([]BoardingSweepRow, error)

	ListPendingBoardingSweeps(ctx context.Context) (
		[]BoardingSweepRow,
		error,
	)

	ListPendingBoardingSweepInputs(ctx context.Context) (
		[]BoardingSweepInputRow, error)

	MarkBoardingSweepStatus(ctx context.Context,
		arg sqlc.MarkBoardingSweepStatusParams) error

	MarkBoardingSweepInputStatus(
		ctx context.Context,
		arg sqlc.MarkBoardingSweepInputStatusParams,
	) error

	MarkBoardingSweepInputsStatus(
		ctx context.Context,
		arg sqlc.MarkBoardingSweepInputsStatusParams,
	) error

	MarkBoardingSweepInputSpentByOutpoint(ctx context.Context,
		arg sqlc.MarkBoardingSweepInputSpentByOutpointParams) (
		int64,
		error,
	)

	CountUnresolvedBoardingSweepInputs(ctx context.Context,
		txid []byte) (int64, error)
}

BoardingStore is the interface that groups all boarding-related database queries. This is a subset of sqlc.Querier focused on boarding operations.

focused on a single store capability.

type BoardingSweepInputRow

type BoardingSweepInputRow = sqlc.BoardingSweepInput

BoardingSweepInputRow is the persisted per-input boarding sweep row.

type BoardingSweepRow

type BoardingSweepRow = sqlc.BoardingSweep

BoardingSweepRow is the persisted aggregate boarding sweep transaction row.

type BoardingWalletStore

type BoardingWalletStore struct {
	*PendingIntentPersistenceStore

	// Log is an optional logger for this persistence store. If None,
	// the store falls back to extracting a logger from context via
	// build.LoggerFromContext, or uses btclog.Disabled if no logger
	// is found. Matches the fn.Option[btclog.Logger] pattern used by
	// VTXOPersistenceStore and other subsystems.
	Log fn.Option[btclog.Logger]
	// contains filtered or unexported fields
}

BoardingWalletStore implements the wallet.BoardingStore interface using the BatchedTx pattern for transaction-safe operations. All methods execute within database transactions with automatic retry on serialization errors.

The embedded PendingIntentPersistenceStore contributes the generic pending-intent outbox surface (UpsertPendingIntent and friends) that wallet.BoardingStore embeds via wallet.PendingIntentStore.

func NewBoardingWalletStore

func NewBoardingWalletStore(db BatchedBoardingStore,
	intentDB BatchedPendingIntentStore, chainParams *chaincfg.Params,
	clock clock.Clock) *BoardingWalletStore

NewBoardingWalletStore creates a new boarding wallet store using the transaction executor pattern. The pending-intent executor shares the same underlying database; it is a separate argument only because the generic transaction executor is typed per query-interface.

func (*BoardingWalletStore) CreatePendingBoardingSweep

func (b *BoardingWalletStore) CreatePendingBoardingSweep(ctx context.Context,
	sweep wallet.NewBoardingSweep) error

CreatePendingBoardingSweep atomically records a sweep and moves its boarding intents into sweep_pending before the transaction is broadcast.

func (*BoardingWalletStore) FetchBoardingIntentOutpoints

func (b *BoardingWalletStore) FetchBoardingIntentOutpoints(
	ctx context.Context) ([]wire.OutPoint, error)

FetchBoardingIntentOutpoints returns just the outpoints of all boarding intents. This is more efficient than FetchBoardingIntents when only the outpoints are needed (e.g., for seenUtxos initialization).

func (*BoardingWalletStore) FetchBoardingIntents

func (b *BoardingWalletStore) FetchBoardingIntents(ctx context.Context) (
	[]wallet.BoardingIntent, error)

FetchBoardingIntents returns all boarding intents that are currently in progress (not yet completed). This is used during actor startup to resume monitoring pending boarding flows.

func (*BoardingWalletStore) FetchBoardingIntentsByStatus

func (b *BoardingWalletStore) FetchBoardingIntentsByStatus(ctx context.Context,
	status wallet.BoardingStatus) ([]wallet.BoardingIntent, error)

FetchBoardingIntentsByStatus returns all boarding intents matching the given status. This is used during startup to filter for Confirmed-but-not-Adopted intents that need to be resumed.

func (*BoardingWalletStore) FetchBoardingIntentsByStatusAndMinHeight

func (b *BoardingWalletStore) FetchBoardingIntentsByStatusAndMinHeight(
	ctx context.Context, status wallet.BoardingStatus, minHeight int32) (
	[]wallet.BoardingIntent, error)

FetchBoardingIntentsByStatusAndMinHeight returns all boarding intents matching the given status with confirmation height >= minHeight. This is used for efficient backlog delivery to newly registered notifiers.

func (*BoardingWalletStore) FetchBoardingIntentsBySweepableStatuses

func (b *BoardingWalletStore) FetchBoardingIntentsBySweepableStatuses(
	ctx context.Context, statuses []wallet.BoardingStatus) (
	[]wallet.BoardingIntent, error)

FetchBoardingIntentsBySweepableStatuses returns all boarding intents in the lifecycle states that can still represent a timeout-path sweep candidate.

The current sqlc query accepts exactly three status filters; the wallet actor always supplies confirmed/failed/expired so this guards the input length explicitly rather than padding with an inert value.

func (*BoardingWalletStore) GetBoardingSweep

func (b *BoardingWalletStore) GetBoardingSweep(ctx context.Context,
	txid chainhash.Hash) (*wallet.BoardingSweepRecord, error)

GetBoardingSweep returns the persisted aggregate boarding sweep with the given txid (including its inputs). Returns (nil, nil) when no matching sweep is recorded so callers can branch on absence without inspecting sql.ErrNoRows.

func (*BoardingWalletStore) GetIntent

func (b *BoardingWalletStore) GetIntent(ctx context.Context,
	outpoint wire.OutPoint) (*wallet.BoardingIntent, error)

GetIntent retrieves a boarding intent by its outpoint (primary key). Returns an error if the intent is not found.

func (*BoardingWalletStore) InsertBoardingAddress

func (b *BoardingWalletStore) InsertBoardingAddress(ctx context.Context,
	addr *wallet.BoardingAddress) error

InsertBoardingAddress persists a boarding address when it is first created. This method is idempotent - inserting the same address multiple times is safe due to ON CONFLICT DO NOTHING in the SQL.

func (*BoardingWalletStore) InsertBoardingIntents

func (b *BoardingWalletStore) InsertBoardingIntents(ctx context.Context,
	intents ...wallet.BoardingIntent) error

InsertBoardingIntents persists one or more boarding intents. This operation is idempotent, allowing the same intent to be saved multiple times as it progresses through different states.

func (*BoardingWalletStore) ListAllBoardingAddresses

func (b *BoardingWalletStore) ListAllBoardingAddresses(ctx context.Context) (
	[]*wallet.BoardingAddress, error)

ListAllBoardingAddresses returns all persisted boarding addresses. This is used during actor startup to re-register confirmation monitoring for all addresses.

func (*BoardingWalletStore) ListBoardingSweeps

func (b *BoardingWalletStore) ListBoardingSweeps(ctx context.Context,
	status string, limit, offset int32) ([]wallet.BoardingSweepRecord,
	error)

ListBoardingSweeps returns persisted aggregate sweeps. If status is non-empty, only sweeps in that lifecycle status are returned.

func (*BoardingWalletStore) ListPendingBoardingSweeps

func (b *BoardingWalletStore) ListPendingBoardingSweeps(ctx context.Context) (
	[]wallet.BoardingSweepRecord, error)

ListPendingBoardingSweeps returns every unresolved boarding sweep with its watched inputs.

func (*BoardingWalletStore) LookupBoardingAddress

func (b *BoardingWalletStore) LookupBoardingAddress(ctx context.Context,
	pkScript []byte) (*wallet.BoardingAddress, error)

LookupBoardingAddress retrieves a boarding address by its pkScript. Returns an error if the address is not found.

func (*BoardingWalletStore) LookupIntentByScript

func (b *BoardingWalletStore) LookupIntentByScript(ctx context.Context,
	pkScript []byte) (*wallet.BoardingIntent, error)

LookupIntentByScript returns the stored intent associated with a boarding pkScript. Returns an error if none exists.

func (*BoardingWalletStore) MarkBoardingSweepFailed

func (b *BoardingWalletStore) MarkBoardingSweepFailed(ctx context.Context,
	txid chainhash.Hash, failure error) error

MarkBoardingSweepFailed restores pending boarding intents to their previous status and records a terminal local sweep failure.

func (*BoardingWalletStore) MarkBoardingSweepInputSpent

func (b *BoardingWalletStore) MarkBoardingSweepInputSpent(ctx context.Context,
	outpoint wire.OutPoint, spendingTxid chainhash.Hash,
	spendingHeight int32) (bool, error)

MarkBoardingSweepInputSpent records a confirmed spend for the watched boarding outpoint and resolves the aggregate sweep once every input is spent.

func (*BoardingWalletStore) MarkBoardingSweepPublished

func (b *BoardingWalletStore) MarkBoardingSweepPublished(ctx context.Context,
	txid chainhash.Hash) error

MarkBoardingSweepPublished marks a persisted sweep and all unresolved inputs as published after the transaction is accepted for broadcast.

func (*BoardingWalletStore) UpdateBoardingIntentStatus

func (b *BoardingWalletStore) UpdateBoardingIntentStatus(ctx context.Context,
	outpoint wire.OutPoint, status wallet.BoardingStatus) error

UpdateBoardingIntentStatus updates one boarding intent's lifecycle status.

type ClearAnchorParams

ClearAnchorParams aliases the sqlc-generated clear-by-outpoint params so call sites can spell the type concisely (the generated name exceeds the line-length cap when nested inside the CommitState transaction body).

type Config

type Config struct {
	// Backend specifies which database backend to use: "sqlite" or
	// "postgres".
	Backend string `long:"backend" choice:"sqlite" choice:"postgres"`

	// Sqlite contains SQLite-specific configuration.
	Sqlite *SqliteConfig `group:"sqlite" namespace:"sqlite"`

	// Postgres contains Postgres-specific configuration.
	Postgres *PostgresConfig `group:"postgres" namespace:"postgres"`

	// Log is an optional logger for the database store. When None, the
	// store falls back to btclog.Disabled unless the caller threads a
	// logger through explicit constructor parameters.
	Log fn.Option[btclog.Logger]
}

Config holds the configuration for the database store. It allows selecting between SQLite and Postgres backends.

func DefaultConfig

func DefaultConfig(dataDir string) *Config

DefaultConfig returns a complete default database configuration.

The default backend is SQLite, while Postgres defaults are still populated so callers can switch backend by toggling the Backend field.

type CreditOpKind

type CreditOpKind int32

CreditOpKind records the credit operation family. Values are append-only; the numeric meaning of an existing value must never shift.

const (
	// CreditOpKindPay is a sub-dust / shortfall pay (optional Ark top-up,
	// then credit or mixed pay).
	CreditOpKindPay CreditOpKind = iota + 1

	// CreditOpKindReceive is a server-owned Lightning receive that credits
	// the account.
	CreditOpKindReceive

	// CreditOpKindRedeem materializes available credits back into an Ark
	// vTXO.
	CreditOpKindRedeem
)

type CreditOpStatus

type CreditOpStatus int32

CreditOpStatus is the coordinator-facing status of one credit operation. Values are append-only.

const (
	// CreditOpStatusPending means the operation is still in flight.
	CreditOpStatusPending CreditOpStatus = iota

	// CreditOpStatusCompleted means the operation completed successfully.
	CreditOpStatusCompleted

	// CreditOpStatusFailed means the operation failed terminally.
	CreditOpStatusFailed
)

func (CreditOpStatus) IsTerminal

func (s CreditOpStatus) IsTerminal() bool

IsTerminal reports whether the operation status is terminal.

type CreditOperationRecord

type CreditOperationRecord struct {
	// OpID is the stable, unique per-admission credit operation identifier.
	OpID string

	// OpKey is the stable client idempotency key (pay:<hash> / recv:<hash>
	// / redeem:<id>) reused for the server op AND the delegated OOR
	// transfer.
	OpKey string

	// Kind records the credit operation family.
	Kind CreditOpKind

	// State is the latest FSM state string.
	State string

	// Status is the coordinator-facing operation status.
	Status CreditOpStatus

	// ServerOpID is the swap-server credit operation id, when known.
	ServerOpID string

	// PaymentHash is the BOLT-11 payment hash for pay and receive ops.
	PaymentHash []byte

	// DestinationPubkey is the server-owned Ark destination for a top-up,
	// or the wallet-owned receive destination for a redemption.
	DestinationPubkey []byte

	// OORSessionID is the delegated OOR transfer session id, when admitted.
	OORSessionID string

	// Invoice is the target invoice (pay) or server receive invoice (recv).
	Invoice string

	// AmountSat is the principal amount for the operation.
	AmountSat int64

	// TopupSat is the Ark top-up amount required to cover a pay shortfall.
	TopupSat int64

	// MaxCreditSat is the credit cap passed to StartPay for a pay op.
	MaxCreditSat int64

	// MaxFeeSat is the caller's max routing fee for a pay op.
	MaxFeeSat int64

	// LastError is the latest terminal failure reason.
	LastError string

	// SnapshotData is the TLV-encoded per-operation resume snapshot.
	SnapshotData []byte

	// SnapshotVersion is the encoding version of SnapshotData.
	SnapshotVersion int32

	// CreatedAt is when the row was first written.
	CreatedAt time.Time

	// UpdatedAt is when the row was last updated.
	UpdatedAt time.Time
}

CreditOperationRecord is one credit operation's full durable state: the queryable control-plane fields plus the opaque resume snapshot. It is the single source of truth for the client's progress through one credit flow -- the per-operation actor reads and writes it directly inside its Read/Stage/Commit phases rather than using the generic actor-delivery fsm_checkpoints blob. The server credit ledger remains authoritative for the money.

type CreditOperationStoreDB

type CreditOperationStoreDB struct {
	*TransactionExecutor[*sqlc.Queries]
	// contains filtered or unexported fields
}

CreditOperationStoreDB bridges the credit operation control-plane to the sqlc-generated queries. Every method wraps the query in ExecTx so that, when ctx carries a durable-actor transaction (actor.TxFromContext), the write joins that outer tx and commits atomically alongside the mailbox ack; from the registry actor (no ambient tx) it opens its own short transaction.

func NewCreditOperationStore

func NewCreditOperationStore(store *Store,
	clk clock.Clock) *CreditOperationStoreDB

NewCreditOperationStore creates a credit operation store from a Store.

func (*CreditOperationStoreDB) GetOperation

GetOperation loads one credit operation row by op id.

func (*CreditOperationStoreDB) ListNonTerminal

func (s *CreditOperationStoreDB) ListNonTerminal(ctx context.Context) (
	[]CreditOperationRecord, error)

ListNonTerminal loads every non-terminal credit operation row. The registry actor uses this on boot to respawn in-flight per-operation actors.

func (*CreditOperationStoreDB) ListOperations

func (s *CreditOperationStoreDB) ListOperations(ctx context.Context) (
	[]CreditOperationRecord, error)

ListOperations returns every credit operation row, terminal and non-terminal alike, for coarse diagnostic listings.

func (*CreditOperationStoreDB) LookupActiveOperationByKey

func (s *CreditOperationStoreDB) LookupActiveOperationByKey(ctx context.Context,
	key string) (*CreditOperationRecord, error)

LookupActiveOperationByKey loads the non-failed credit operation row carrying the given op_key, if any. Failed operations are excluded so a keyed retry after a failure admits a fresh operation instead of deduping against the dead one; pending and completed operations still answer for the key.

func (*CreditOperationStoreDB) UpsertOperation

func (s *CreditOperationStoreDB) UpsertOperation(ctx context.Context,
	record CreditOperationRecord) error

UpsertOperation persists or updates one credit operation row.

type DatabaseBackend

type DatabaseBackend interface {
	BatchedQuerier

	WithTx(tx *sql.Tx) *sqlc.Queries
}

DatabaseBackend is an interface that contains all methods our different database backends implement.

type ErrAbortedTransaction

type ErrAbortedTransaction struct {
	DBError error
}

ErrAbortedTransaction is an error type which represents a database agnostic error that a statement was issued against a transaction that an earlier failure had already aborted.

func (ErrAbortedTransaction) Error

func (e ErrAbortedTransaction) Error() string

Error returns the error message.

func (ErrAbortedTransaction) Unwrap

func (e ErrAbortedTransaction) Unwrap() error

Unwrap returns the wrapped error.

type ErrDatabaseConnectionError

type ErrDatabaseConnectionError struct {
	DBError error
}

ErrDatabaseConnectionError is an error type which represents a database connection error with sensitive information sanitized.

func (ErrDatabaseConnectionError) Error

Error returns a generic error message without revealing connection details.

func (ErrDatabaseConnectionError) Unwrap

func (e ErrDatabaseConnectionError) Unwrap() error

Unwrap returns the wrapped error.

type ErrDeadlockError

type ErrDeadlockError struct {
	DBError error
}

ErrDeadlockError is an error type which represents a database agnostic error where transactions have led to cyclic dependencies in lock acquisition.

func (ErrDeadlockError) Error

func (e ErrDeadlockError) Error() string

Error returns the error message.

func (ErrDeadlockError) Unwrap

func (e ErrDeadlockError) Unwrap() error

Unwrap returns the wrapped error.

type ErrSQLUniqueConstraintViolation

type ErrSQLUniqueConstraintViolation struct {
	DBError error
}

ErrSQLUniqueConstraintViolation is an error type which represents a database agnostic SQL unique constraint violation.

func (ErrSQLUniqueConstraintViolation) Error

func (ErrSQLUniqueConstraintViolation) Unwrap

Unwrap returns the wrapped error.

Without this, the mapped error is a dead end for errors.As, and the PgErrorConstraint and PgErrorDetail extractors return empty for every caller that holds the mapped error rather than the raw driver one. That is the normal case, since ExecTx returns the mapped error, and identifying which of the partial unique indexes actually fired is the whole point of surfacing the constraint name.

type ErrSchemaError

type ErrSchemaError struct {
	DBError error
}

ErrSchemaError is an error type which represents a database agnostic error that the schema of the database is incorrect for the given query.

func (ErrSchemaError) Error

func (e ErrSchemaError) Error() string

Error returns the error message.

func (ErrSchemaError) Unwrap

func (e ErrSchemaError) Unwrap() error

Unwrap returns the wrapped error.

type ErrSerializationError

type ErrSerializationError struct {
	DBError error
}

ErrSerializationError is an error type which represents a database agnostic error that a transaction couldn't be serialized with other concurrent db transactions.

func (ErrSerializationError) Error

func (e ErrSerializationError) Error() string

Error returns the error message.

func (ErrSerializationError) Unwrap

func (e ErrSerializationError) Unwrap() error

Unwrap returns the wrapped error.

type InsertRoundParams

type InsertRoundParams = sqlc.InsertRoundParams

Type aliases for sqlc generated types.

type InsertVTXOParams

type InsertVTXOParams = sqlc.InsertVTXOParams

Type aliases for sqlc generated types.

type IntentHeightFilter

IntentHeightFilter filters boarding intents by status and min conf height.

type InternalKeyQuerier

type InternalKeyQuerier interface {
	UpsertInternalKey(ctx context.Context,
		arg sqlc.UpsertInternalKeyParams) (int64, error)

	GetInternalKeyByID(ctx context.Context,
		id int64) (sqlc.InternalKey, error)
}

InternalKeyQuerier is the minimal query surface the internal-key registry helpers need. The sqlc-generated *Queries satisfies it, as does every consumer store interface (RoundStore, BoardingStore, ...) that embeds these two methods, so a store can register-then-reference an internal key inside the same transaction that writes the referencing row.

type LedgerStoreDB

type LedgerStoreDB struct {
	*TransactionExecutor[*sqlc.Queries]
}

LedgerStoreDB bridges the ledger.LedgerStore interface to the sqlc-generated queries. This adapter converts LedgerEntry to sqlc.InsertClientLedgerEntryParams and wraps all operations in ExecTx for transactional safety.

Beyond the ledger.LedgerStore interface, LedgerStoreDB also provides query methods (GetAccountBalance, ListLedgerEntries, etc.) used by the daemon RPC layer.

func NewLedgerStoreDB

func NewLedgerStoreDB(store *Store) *LedgerStoreDB

NewLedgerStoreDB creates a new LedgerStoreDB from a Store.

func (*LedgerStoreDB) CountLedgerEntries

func (s *LedgerStoreDB) CountLedgerEntries(ctx context.Context) (int64, error)

CountLedgerEntries returns the total number of ledger entries within a read transaction.

func (*LedgerStoreDB) GetAccountBalance

func (s *LedgerStoreDB) GetAccountBalance(ctx context.Context,
	accountID string) (int64, error)

GetAccountBalance returns the net balance (debits minus credits) for the given account within a read transaction.

func (*LedgerStoreDB) GetConfirmedExitCost

func (s *LedgerStoreDB) GetConfirmedExitCost(ctx context.Context,
	outpoint wire.OutPoint) (int64, error)

GetConfirmedExitCost returns the confirmed on-chain cost the ledger booked for a unilateral exit of the given VTXO outpoint (the onchain_fee_paid leg unroll emits after the final sweep confirms). Zero when no exit-cost leg exists — the exit has not confirmed, or predates exit-cost accounting.

func (*LedgerStoreDB) GetTotalOperatorFeesPaid

func (s *LedgerStoreDB) GetTotalOperatorFeesPaid(ctx context.Context) (int64,
	error)

GetTotalOperatorFeesPaid returns the cumulative satoshis debited to the fees_paid expense account within a read transaction.

func (*LedgerStoreDB) InsertLedgerEntry

func (s *LedgerStoreDB) InsertLedgerEntry(ctx context.Context,
	entry ledger.LedgerEntry) error

InsertLedgerEntry persists a client-side double-entry ledger record. When ctx carries a durable-actor transaction (actor.TxFromContext), TransactionExecutor.ExecTx joins that outer tx rather than opening a fresh one, so multiple invocations from within a single actor handler commit atomically alongside the mailbox ack. The underlying InsertClientLedgerEntry query uses ON CONFLICT DO NOTHING against the partial unique indexes on round_id, session_id, and idempotency_key so redelivery of an already-persisted message silently dedupes instead of raising a constraint violation.

func (*LedgerStoreDB) ListAccounts

func (s *LedgerStoreDB) ListAccounts(ctx context.Context) ([]sqlc.Account,
	error)

ListAccounts returns all accounts in the chart of accounts within a read transaction.

func (*LedgerStoreDB) ListLedgerEntries

func (s *LedgerStoreDB) ListLedgerEntries(ctx context.Context, limit,
	offset int32) ([]sqlc.LedgerEntry, error)

ListLedgerEntries returns a paginated list of ledger entries ordered by creation time within a read transaction.

func (*LedgerStoreDB) ListLedgerEntriesByType

func (s *LedgerStoreDB) ListLedgerEntriesByType(ctx context.Context,
	eventType string, limit, offset int32) ([]sqlc.LedgerEntry, error)

ListLedgerEntriesByType returns a paginated list of ledger entries filtered by event type within a read transaction.

func (*LedgerStoreDB) ListLedgerEntriesWithFeesTotal

func (s *LedgerStoreDB) ListLedgerEntriesWithFeesTotal(ctx context.Context,
	limit, offset int32) ([]sqlc.LedgerEntry, int64, error)

ListLedgerEntriesWithFeesTotal returns a paginated list of ledger entries together with the cumulative operator-fees-paid total, both observed inside the same read transaction. Reading both in one tx guarantees the returned page and total are mutually consistent: a concurrent insert cannot land between the two queries and produce a total that already counts an entry not yet visible on the page.

func (*LedgerStoreDB) ListTransactionHistory

func (s *LedgerStoreDB) ListTransactionHistory(ctx context.Context,
	typeFilter string, fromUnixS, toUnixS int64, limit, offset int32) (
	[]sqlc.ListTransactionHistoryRow, error)

ListTransactionHistory returns a unified newest-first page of ledger-backed activity and tracked boarding sweep transactions. The type and timestamp filters are applied in SQL before pagination so a filtered request never returns an empty page just because earlier unfiltered rows did not match.

type ListRoundsPaginatedParams

type ListRoundsPaginatedParams = sqlc.ListRoundsPaginatedParams

Type aliases for sqlc generated types.

type ListRoundsQuery

type ListRoundsQuery struct {
	// Cursor is the last round id from the previous page. Use an empty
	// string to start from the first matching row.
	Cursor string

	// Limit is the maximum number of matching persisted rounds to return.
	Limit int32

	// Status restricts results to one persisted round status when set.
	Status string

	// CreatedAfter restricts results to rounds created at or after this
	// Unix timestamp when non-zero.
	CreatedAfter int64

	// CreatedBefore restricts results to rounds created at or before this
	// Unix timestamp when non-zero.
	CreatedBefore int64
}

ListRoundsQuery controls persisted round pagination and filtering.

type MacaroonRootKeyStore

type MacaroonRootKeyStore interface {
	// GetMacaroonRootKey fetches the root key for the given ID.
	GetMacaroonRootKey(ctx context.Context,
		id []byte) (sqlc.Macaroon, error)

	// InsertMacaroonRootKey persists a root key for the given ID.
	InsertMacaroonRootKey(ctx context.Context,
		arg sqlc.InsertMacaroonRootKeyParams) error
}

MacaroonRootKeyStore is the query surface needed by the macaroon root key store.

type MigrateOpt

type MigrateOpt func(*migrateOptions)

MigrateOpt is a functional option that can be passed to migrate related methods to modify behavior.

func WithLatestVersion

func WithLatestVersion(version uint) MigrateOpt

WithLatestVersion allows callers to override the default latest version setting.

func WithPostStepCallbacks

func WithPostStepCallbacks(
	postStepCallbacks map[uint]migrate.PostStepCallback) MigrateOpt

WithPostStepCallbacks is an option that can be used to set a map of PostStepCallback functions that can be used to execute a Golang based migration step after a SQL based migration step has been executed. The key is the migration version and the value is the callback function that should be run _after_ the step was executed (but before the version is marked as cleanly executed). An error returned from the callback will cause the migration to fail and the step to be marked as dirty.

type MigrationTarget

type MigrationTarget func(mig *migrate.Migrate,
	currentDBVersion int, maxMigrationVersion uint) error

MigrationTarget is a functional option that can be passed to applyMigrations to specify a target version to migrate to. `currentDBVersion` is the current (migration) version of the database, or None if unknown. `maxMigrationVersion` is the maximum migration version known to the driver, or None if unknown.

type NewAddrParams

type NewAddrParams = sqlc.InsertBoardingAddressParams

type NewIntentParams

type NewIntentParams = sqlc.InsertBoardingIntentParams

type OORArtifactPersistenceStore

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

OORArtifactPersistenceStore persists OOR artifacts and query surfaces needed for unroll package retrieval.

func NewOORArtifactPersistenceStore

func NewOORArtifactPersistenceStore(db BatchedOORArtifactStore,
	c clock.Clock) *OORArtifactPersistenceStore

NewOORArtifactPersistenceStore constructs an OOR artifact store backed by batched SQL transactions.

The returned store is safe to use across independent requests because each public method executes in its own transaction scope. If no clock is provided, a default wall-clock implementation is used.

func (*OORArtifactPersistenceStore) GetPackage

GetPackage returns the fully materialized package for one OOR session id.

func (*OORArtifactPersistenceStore) GetPackageForOutpoint

func (s *OORArtifactPersistenceStore) GetPackageForOutpoint(ctx context.Context,
	outpoint wire.OutPoint) (*OORPackageBundle, error)

GetPackageForOutpoint returns the fully materialized package linked to one local outpoint.

The response includes all persisted checkpoints, all known bindings for the session, and the specific binding row that matched the requested outpoint.

func (*OORArtifactPersistenceStore) GetRecipientCursor

func (s *OORArtifactPersistenceStore) GetRecipientCursor(ctx context.Context,
	recipientPkScript []byte) (*sqlc.OorRecipientCursor, error)

GetRecipientCursor loads the persisted recipient cursor for one script.

Callers can use this to resume polling from the last acknowledged event ID.

func (*OORArtifactPersistenceStore) ListOwnedReceiveScripts

func (s *OORArtifactPersistenceStore) ListOwnedReceiveScripts(
	ctx context.Context) ([]OwnedReceiveScriptRecord, error)

ListOwnedReceiveScripts returns all owned receive script registrations.

The result is ordered by creation time descending and is intended for worker bootstrap and operator inspection.

func (*OORArtifactPersistenceStore) ListPackages

ListPackages returns all persisted packages, optionally filtered by direction.

Each returned entry is fully materialized with checkpoints and binding rows. Callers can therefore consume the result directly without additional per-row lookups.

func (*OORArtifactPersistenceStore) ListReceivedPackages

func (s *OORArtifactPersistenceStore) ListReceivedPackages(
	ctx context.Context) ([]*OORPackageBundle, error)

ListReceivedPackages lists fully materialized incoming OOR packages.

This is a convenience wrapper around ListPackages with the incoming direction filter preselected.

func (*OORArtifactPersistenceStore) ListRecipientCursors

func (s *OORArtifactPersistenceStore) ListRecipientCursors(
	ctx context.Context) ([]sqlc.OorRecipientCursor, error)

ListRecipientCursors returns all recipient cursor rows ordered by update time.

This is primarily used by orchestration code that needs to inspect or resume polling across all tracked scripts.

func (*OORArtifactPersistenceStore) ListSentPackages

func (s *OORArtifactPersistenceStore) ListSentPackages(ctx context.Context) (
	[]*OORPackageBundle, error)

ListSentPackages lists fully materialized outgoing OOR packages.

This is a convenience wrapper around ListPackages with the outgoing direction filter preselected.

func (*OORArtifactPersistenceStore) LookupOwnedReceiveScript

func (s *OORArtifactPersistenceStore) LookupOwnedReceiveScript(
	ctx context.Context, pkScript []byte) (*OwnedReceiveScriptRecord,
	error)

LookupOwnedReceiveScript loads one owned receive script metadata row by pkScript.

This is a direct lookup path used by receive-side attribution logic.

func (*OORArtifactPersistenceStore) ResolveUnrollPackages

func (s *OORArtifactPersistenceStore) ResolveUnrollPackages(ctx context.Context,
	outpoint wire.OutPoint) (*OORUnrollPackages, error)

ResolveUnrollPackages resolves locally known OOR package artifacts needed to unroll the target outpoint.

The resolver follows checkpoint-input ancestry through locally persisted outpoint bindings. Any checkpoint input that cannot be resolved to a local package binding is returned in UnresolvedCheckpointInputs.

func (*OORArtifactPersistenceStore) UpsertBinding

func (s *OORArtifactPersistenceStore) UpsertBinding(ctx context.Context,
	outpoint wire.OutPoint, sessionID chainhash.Hash, outputIndex uint32,
	linkKind OORPackageLinkKind) error

UpsertBinding writes or updates one local outpoint-to-session binding.

Bindings are used as the primary lookup surface for unroll preparation. created_output bindings map newly received outputs, while consumed_input bindings map local outpoints spent by an outgoing transfer.

func (*OORArtifactPersistenceStore) UpsertOwnedReceiveScript

func (s *OORArtifactPersistenceStore) UpsertOwnedReceiveScript(
	ctx context.Context, rec OwnedReceiveScriptRecord) error

UpsertOwnedReceiveScript writes metadata describing one locally owned recipient script.

The metadata links a script to key-derivation context and checkpoint policy, which allows incoming event ingestion to map recipient outputs directly to local wallet ownership.

NOTE: This is receiver-side indexing metadata for polling/attribution, not sender-side transfer state.

func (*OORArtifactPersistenceStore) UpsertPackage

func (s *OORArtifactPersistenceStore) UpsertPackage(ctx context.Context,
	direction OORPackageDirection, sessionID chainhash.Hash,
	ark *psbt.Packet, checkpoints []*psbt.Packet) error

UpsertPackage writes or replaces one finalized OOR package identified by session ID.

The method persists the Ark PSBT and then rewrites the checkpoint set in contiguous index order. Existing checkpoint rows for the session are removed first so retries always converge to the latest canonical package.

func (*OORArtifactPersistenceStore) UpsertRecipientCursor

func (s *OORArtifactPersistenceStore) UpsertRecipientCursor(ctx context.Context,
	recipientPkScript []byte, lastEventID int64,
	lastSessionID *chainhash.Hash) error

UpsertRecipientCursor writes recipient polling progress for one script.

The cursor enables at-least-once recipient event ingestion. Reprocessing the same or older events is safe because artifact writes are idempotent.

NOTE: This tracks receiver-side polling state for server recipient events that can be expanded to finalized Ark/checkpoint package artifacts. TODO(oor-receive-polling): Wire runtime receiver polling to this cursor.

type OORArtifactStore

type OORArtifactStore interface {
	// InternalKeyQuerier lets the store register and hydrate the owned
	// receive-script client key via the shared internal_keys registry
	// within its own transaction.
	InternalKeyQuerier

	UpsertOORPackage(ctx context.Context,
		arg sqlc.UpsertOORPackageParams) (int64, error)

	DeleteOORPackageCheckpoints(ctx context.Context, sessionID []byte) error

	InsertOORPackageCheckpoint(ctx context.Context,
		arg sqlc.InsertOORPackageCheckpointParams) error

	GetOORPackage(ctx context.Context,
		sessionID []byte) (sqlc.OorPackage, error)

	ListOORPackageCheckpoints(ctx context.Context,
		sessionID []byte) ([]sqlc.OorPackageCheckpoint, error)

	ListOORPackages(ctx context.Context) ([]sqlc.OorPackage, error)

	ListOORPackagesByDirection(ctx context.Context,
		direction int32) ([]sqlc.OorPackage, error)

	UpsertOORVTXOBinding(ctx context.Context,
		arg sqlc.UpsertOORVTXOBindingParams) (int64, error)

	GetOORVTXOBindingByOutpoint(ctx context.Context,
		arg sqlc.GetOORVTXOBindingByOutpointParams) (
		sqlc.OorVtxoBinding, error)

	GetOORVTXOBindingByOutpointAndKind(ctx context.Context,
		arg sqlc.GetOORVTXOBindingByOutpointAndKindParams) (
		sqlc.OorVtxoBinding, error)

	GetVTXO(ctx context.Context, arg sqlc.GetVTXOParams) (sqlc.Vtxo, error)

	ListOORVTXOBindingsBySession(ctx context.Context,
		sessionID []byte) (
		[]sqlc.ListOORVTXOBindingsBySessionRow,
		error,
	)

	GetOORPackageByOutpoint(ctx context.Context,
		arg sqlc.GetOORPackageByOutpointParams) (
		sqlc.GetOORPackageByOutpointRow, error)

	GetOORPackageByOutpointAndKind(ctx context.Context,
		arg sqlc.GetOORPackageByOutpointAndKindParams) (
		sqlc.GetOORPackageByOutpointAndKindRow, error)

	UpsertOORRecipientCursor(ctx context.Context,
		arg sqlc.UpsertOORRecipientCursorParams) error

	GetOORRecipientCursor(ctx context.Context,
		recipientPkScript []byte) (sqlc.OorRecipientCursor, error)

	ListOORRecipientCursors(ctx context.Context) (
		[]sqlc.OorRecipientCursor,
		error,
	)

	UpsertOwnedReceiveScript(ctx context.Context,
		arg sqlc.UpsertOwnedReceiveScriptParams) error

	GetOwnedReceiveScript(ctx context.Context,
		pkScript []byte) (sqlc.OwnedReceiveScript, error)

	ListOwnedReceiveScripts(ctx context.Context) (
		[]sqlc.OwnedReceiveScript,
		error,
	)
}

OORArtifactStore groups SQL methods needed by OOR artifact persistence.

type OORPackageBinding

type OORPackageBinding struct {
	// Outpoint is the local VTXO outpoint linked to the package.
	Outpoint wire.OutPoint

	// SessionID is the package session identifier (Ark txid).
	SessionID chainhash.Hash

	// OutputIndex is the package output index (or enumerated input index
	// for consumed-input bindings).
	OutputIndex uint32

	// LinkKind identifies relation to the package
	// (created_output/consumed_input).
	LinkKind OORPackageLinkKind

	// RecipientPkScript is populated for created-output bindings.
	RecipientPkScript fn.Option[[]byte]

	// ValueSat is populated for created-output bindings when known.
	ValueSat fn.Option[int64]

	// CreatedAt is the binding creation timestamp.
	CreatedAt time.Time

	// UpdatedAt is the last binding update timestamp.
	UpdatedAt time.Time
}

OORPackageBinding is a local outpoint link to a stored OOR package.

type OORPackageBundle

type OORPackageBundle struct {
	// SessionID is the stable session identifier.
	SessionID chainhash.Hash

	// Direction is incoming or outgoing from the local client perspective.
	Direction OORPackageDirection

	// ArkPSBT is the persisted Ark package.
	ArkPSBT *psbt.Packet

	// FinalCheckpointPSBTs is the persisted finalized checkpoint package.
	FinalCheckpointPSBTs []*psbt.Packet

	// Bindings are all known local outpoint links for this session.
	Bindings []OORPackageBinding

	// CreatedAt is the package creation timestamp.
	CreatedAt time.Time

	// UpdatedAt is the package update timestamp.
	UpdatedAt time.Time

	// MatchedOutpointBinding is set on GetPackageForOutpoint responses.
	MatchedOutpointBinding fn.Option[OORPackageBinding]
}

OORPackageBundle is a fully materialized OOR package view.

type OORPackageDirection

type OORPackageDirection = types.OORPackageDirection

OORPackageDirection is the typed package direction enum.

type OORPackageLinkKind

type OORPackageLinkKind = types.OORPackageLinkKind

OORPackageLinkKind is the typed outpoint-binding relation enum.

type OORSessionDirection

type OORSessionDirection int32

OORSessionDirection records whether a registered OOR session was locally sent or received. Values are append-only; the numeric meaning of an existing value must never shift.

const (
	// OORSessionDirectionOutgoing marks a locally sent OOR session.
	OORSessionDirectionOutgoing OORSessionDirection = iota + 1

	// OORSessionDirectionIncoming marks a locally received OOR session.
	OORSessionDirectionIncoming
)

type OORSessionRegistryRecord

type OORSessionRegistryRecord struct {
	// SessionID is the 32-byte OOR session identifier.
	SessionID chainhash.Hash

	// ActorID is the durable per-session actor mailbox id.
	ActorID string

	// Direction records whether the session is outgoing or incoming.
	Direction OORSessionDirection

	// Phase is the latest control-plane phase string.
	Phase string

	// IdempotencyKey dedups a repeated outgoing StartTransferRequest. Empty
	// means no key (always empty for incoming sessions).
	IdempotencyKey string

	// Status is the coordinator-facing session status.
	Status OORSessionStatus

	// LastError is the latest terminal failure reason.
	LastError string

	// SnapshotData is the TLV-encoded per-session resume snapshot. Nil only
	// in the brief admission window before the first staged write.
	SnapshotData []byte

	// SnapshotVersion is the encoding version of SnapshotData.
	SnapshotVersion int32

	// FlowVersion is the permanent OOR flow version this session was
	// conducted under (distinct from SnapshotVersion, which versions only
	// the resume blob's encoding). Stamped at creation and validated on
	// load. Until a second flow exists it is always FlowVersionV1.
	FlowVersion oorpb.FlowVersion

	// CreatedAt is when the row was first written.
	CreatedAt time.Time

	// UpdatedAt is when the row was last updated.
	UpdatedAt time.Time
}

OORSessionRegistryRecord is one OOR session's full durable state: the queryable control-plane fields plus the opaque resume snapshot. It is the single source of truth for the session -- the per-session actor reads and writes it directly inside its Read/Stage/Commit phases rather than using the generic actor-delivery fsm_checkpoints blob.

type OORSessionRegistryStoreDB

type OORSessionRegistryStoreDB struct {
	*TransactionExecutor[*sqlc.Queries]
	// contains filtered or unexported fields
}

OORSessionRegistryStoreDB bridges the OOR session registry control-plane to the sqlc-generated queries. Every method wraps the query in ExecTx so that, when ctx carries a durable-actor transaction (actor.TxFromContext), the write joins that outer tx and commits atomically alongside the mailbox ack; from the registry actor (no ambient tx) it opens its own short transaction.

func NewOORSessionRegistryStore

func NewOORSessionRegistryStore(store *Store,
	clk clock.Clock) *OORSessionRegistryStoreDB

NewOORSessionRegistryStore creates an OOR session registry store from a Store.

func (*OORSessionRegistryStoreDB) GetSession

GetSession loads one OOR session registry row by session id.

func (*OORSessionRegistryStoreDB) ListNonTerminal

ListNonTerminal loads every non-terminal OOR session registry row. The registry actor uses this on boot to respawn in-flight per-session actors.

func (*OORSessionRegistryStoreDB) ListSessions

ListSessions returns every OOR session registry row, terminal and non-terminal alike, for coarse diagnostic listings.

func (*OORSessionRegistryStoreDB) LookupActiveSessionByIdempotencyKey

func (s *OORSessionRegistryStoreDB) LookupActiveSessionByIdempotencyKey(
	ctx context.Context, key string) (*OORSessionRegistryRecord, error)

LookupActiveSessionByIdempotencyKey loads the non-failed OOR session registry row carrying the given outgoing idempotency key, if any. Failed sessions are excluded so a keyed retry after a failure admits a fresh session instead of deduping against the dead one; pending and completed sessions still answer for the key.

func (*OORSessionRegistryStoreDB) UpsertSession

UpsertSession persists or updates one OOR session registry row.

type OORSessionStatus

type OORSessionStatus int32

OORSessionStatus is the coordinator-facing status of one OOR session. Values are append-only.

const (
	// OORSessionStatusPending means the session is still in flight.
	OORSessionStatusPending OORSessionStatus = iota

	// OORSessionStatusCompleted means the session completed successfully.
	OORSessionStatusCompleted

	// OORSessionStatusFailed means the session failed terminally.
	OORSessionStatusFailed
)

func (OORSessionStatus) IsTerminal

func (s OORSessionStatus) IsTerminal() bool

IsTerminal reports whether the session status is terminal.

type OORUnrollPackages

type OORUnrollPackages struct {
	// TargetOutpoint is the local outpoint requested by the caller.
	TargetOutpoint wire.OutPoint

	// Packages contains the locally known package chain ordered from the
	// farthest known ancestor package to the target package.
	Packages []*OORPackageBundle

	// UnresolvedCheckpointInputs contains checkpoint input outpoints
	// that do not currently have a locally stored package mapping.
	UnresolvedCheckpointInputs []wire.OutPoint
}

OORUnrollPackages is a local package-resolution result for one outpoint.

type OwnedReceiveScriptRecord

type OwnedReceiveScriptRecord struct {
	// PkScript is the tracked receive script.
	PkScript []byte

	// ClientKey is the local wallet key descriptor for this script.
	ClientKey keychain.KeyDescriptor

	// OperatorPubKey is the operator pubkey for this script.
	OperatorPubKey *btcec.PublicKey

	// ExitDelay is the relative CSV delay.
	ExitDelay int64

	// Source labels where this script registration came from.
	Source OwnedReceiveScriptSource

	// CreatedAt is the creation timestamp.
	CreatedAt time.Time

	// LastUsedAt tracks the last usage timestamp when available.
	LastUsedAt fn.Option[time.Time]
}

OwnedReceiveScriptRecord is a local script ownership registration row.

type OwnedReceiveScriptSource

type OwnedReceiveScriptSource int32

OwnedReceiveScriptSource is the script-registration source enum.

const (
	// OwnedReceiveScriptSourceWallet marks scripts discovered from
	// wallet state.
	OwnedReceiveScriptSourceWallet OwnedReceiveScriptSource = 0

	// OwnedReceiveScriptSourceRPC marks scripts registered from RPC/API.
	OwnedReceiveScriptSourceRPC OwnedReceiveScriptSource = 1

	// OwnedReceiveScriptSourceSync marks scripts restored from
	// sync/recovery.
	OwnedReceiveScriptSourceSync OwnedReceiveScriptSource = 2
)

func (OwnedReceiveScriptSource) String

func (s OwnedReceiveScriptSource) String() string

type PendingIntentPersistenceStore

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

PendingIntentPersistenceStore implements wallet.PendingIntentStore: the persistence half of the restart-safe intent outbox. Intents are written before the wallet publishes them to the round actor, anchors are cleared by the round-state checkpoint on adoption (see RoundPersistenceStore.CommitState), and the wallet's startup replay hook lists rows per kind to re-issue lost intents.

func NewPendingIntentPersistenceStore

func NewPendingIntentPersistenceStore(
	db BatchedPendingIntentStore) *PendingIntentPersistenceStore

NewPendingIntentPersistenceStore creates a pending-intent store using the transaction executor pattern.

func (*PendingIntentPersistenceStore) ClearPendingIntentsByKind

func (s *PendingIntentPersistenceStore) ClearPendingIntentsByKind(
	ctx context.Context, kind wallet.PendingIntentKind) error

ClearPendingIntentsByKind removes every persisted intent of the given kind (anchors, detail rows, header rows), atomically.

func (*PendingIntentPersistenceStore) DeletePendingIntent

func (s *PendingIntentPersistenceStore) DeletePendingIntent(ctx context.Context,
	id wallet.PendingIntentID) error

DeletePendingIntent removes one intent (anchors, both detail tables, then the header) atomically. The detail delete for the non-matching kind is a harmless no-op since intent IDs are unique across kinds.

func (*PendingIntentPersistenceStore) ListPendingIntents

ListPendingIntents returns every persisted intent of the given kind with its surviving anchors, ordered by requested_at_unix ascending.

func (*PendingIntentPersistenceStore) UpsertPendingIntent

func (s *PendingIntentPersistenceStore) UpsertPendingIntent(ctx context.Context,
	intent wallet.PendingIntent) error

UpsertPendingIntent atomically writes the intent header, its kind-specific detail row, and all of its anchor rows. Anchors already bound to another intent are rebound to this one (newest intent wins); any intent left anchor-less by the rebind is swept (detail + header) in the same transaction so stale parents never accumulate.

type PendingIntentStore

type PendingIntentStore interface {
	UpsertPendingIntentHeader(ctx context.Context,
		arg sqlc.UpsertPendingIntentHeaderParams) error

	UpsertPendingBoardIntent(ctx context.Context,
		arg sqlc.UpsertPendingBoardIntentParams) error

	UpsertPendingSendIntent(ctx context.Context,
		arg sqlc.UpsertPendingSendIntentParams) error

	UpsertPendingIntentAnchor(ctx context.Context,
		arg sqlc.UpsertPendingIntentAnchorParams) error

	ListPendingBoardIntents(ctx context.Context) (
		[]sqlc.ListPendingBoardIntentsRow, error)

	ListPendingSendIntents(ctx context.Context) (
		[]sqlc.ListPendingSendIntentsRow, error)

	ListPendingIntentAnchorsByKind(ctx context.Context,
		kind string) ([]sqlc.PendingIntentAnchor, error)

	ClearPendingIntentAnchorByOutpoint(ctx context.Context,
		arg sqlc.ClearPendingIntentAnchorByOutpointParams) error

	DeleteOrphanedPendingBoardIntents(ctx context.Context) error

	DeleteOrphanedPendingSendIntents(ctx context.Context) error

	DeleteOrphanedPendingIntents(ctx context.Context) error

	DeletePendingIntentAnchorsByIntentID(ctx context.Context,
		intentID []byte) error

	DeletePendingBoardIntentByID(ctx context.Context, intentID []byte) error

	DeletePendingSendIntentByID(ctx context.Context, intentID []byte) error

	DeletePendingIntentByID(ctx context.Context, intentID []byte) error

	DeletePendingIntentAnchorsByKind(ctx context.Context, kind string) error

	DeletePendingBoardIntentsAll(ctx context.Context) error

	DeletePendingSendIntentsAll(ctx context.Context) error

	DeletePendingIntentsByKind(ctx context.Context, kind string) error
}

PendingIntentStore groups the SQL methods needed to maintain the generic pending-intents outbox: a kind-agnostic header, per-kind detail tables, and the shared anchor table. One logical store spans the header, both detail tables, and the anchor table; splitting it would fragment the transaction boundary across the same table family.

type PostgresConfig

type PostgresConfig struct {
	SkipMigrations     bool          `long:"skipmigrations" description:"Skip applying migrations on startup."`
	Host               string        `long:"host" description:"Database server hostname."`
	Port               int           `long:"port" description:"Database server port."`
	User               string        `long:"user" description:"Database user."`
	Password           string        `long:"password" description:"Database user's password."` //nolint:gosec // G117: DB config field; name required for flag binding.
	DBName             string        `long:"dbname" description:"Database name to use."`
	MaxOpenConnections int           `long:"maxconnections" description:"Max open connections to keep alive to the database server."`
	MaxIdleConnections int           `long:"maxidleconnections" description:"Max number of idle connections to keep in the connection pool."`
	ConnMaxLifetime    time.Duration `` /* 139-byte string literal not displayed */
	ConnMaxIdleTime    time.Duration `` /* 137-byte string literal not displayed */
	RequireSSL         bool          `long:"requiressl" description:"Whether to require using SSL (mode: require) when connecting to the server."`

	// Log is an optional logger for the Postgres store. When None, the
	// store falls back to the explicit constructor logger.
	Log fn.Option[btclog.Logger]
}

PostgresConfig holds the postgres database configuration.

func DefaultPostgresConfig

func DefaultPostgresConfig() *PostgresConfig

DefaultPostgresConfig returns default Postgres connection settings.

Connection pool limits are left at zero to keep Go SQL defaults unless the caller explicitly configures them.

func (*PostgresConfig) DSN

func (s *PostgresConfig) DSN(hidePassword bool) string

DSN returns the dns to connect to the database.

type PostgresStore

type PostgresStore struct {
	*BaseDB
	// contains filtered or unexported fields
}

PostgresStore is a database store implementation that uses a Postgres backend.

func NewPostgresStore

func NewPostgresStore(cfg *PostgresConfig,
	explicitLog btclog.Logger) (*PostgresStore, error)

NewPostgresStore creates a new store that is backed by a Postgres database backend. The explicit logger parameter is kept for backward compatibility with existing callers; when cfg.Log is set it takes precedence.

func NewTestPostgresDB

func NewTestPostgresDB(t testing.TB) *PostgresStore

NewTestPostgresDB is a helper function that creates a Postgres database for testing.

func NewTestPostgresDBWithVersion

func NewTestPostgresDBWithVersion(t testing.TB, version uint) *PostgresStore

NewTestPostgresDBWithVersion is a helper function that creates a Postgres database for testing and migrates it to the given version.

func (*PostgresStore) ExecuteMigrations

func (s *PostgresStore) ExecuteMigrations(target MigrationTarget,
	optFuncs ...MigrateOpt) error

ExecuteMigrations runs migrations for the Postgres database, depending on the target given, either all migrations or up to a given version.

type QueryCreator

type QueryCreator[Q any] func(*sql.Tx) Q

QueryCreator is a generic function that's used to create a Querier, which is a type of interface that implements storage related methods from a database transaction. This will be used to instantiate an object callers can use to apply multiple modifications to an object interface in a single atomic transaction.

type RootKeyStore

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

RootKeyStore stores macaroon root keys in the daemon database.

func NewMacaroonRootKeyStore

func NewMacaroonRootKeyStore(db BatchedMacaroonRootKeyStore) *RootKeyStore

NewMacaroonRootKeyStore creates a macaroon root key store.

func (*RootKeyStore) Get

func (r *RootKeyStore) Get(ctx context.Context, id []byte) ([]byte, error)

Get returns the root key for the given ID.

NOTE: This implements the bakery.RootKeyStore interface.

func (*RootKeyStore) RootKey

func (r *RootKeyStore) RootKey(ctx context.Context) ([]byte, []byte, error)

RootKey returns the root key to use for creating a new macaroon, along with the ID that can be used to look it up later with Get.

NOTE: This implements the bakery.RootKeyStore interface.

type RoundBoardingIntentRow

type RoundBoardingIntentRow = sqlc.RoundBoardingIntent

Type aliases for sqlc generated types.

type RoundClientTreeRow

type RoundClientTreeRow = sqlc.RoundClientTree

Type aliases for sqlc generated types.

type RoundPersistenceStore

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

RoundPersistenceStore implements the round.RoundStore and round.VTXOStore interfaces using the BatchedTx pattern for transaction-safe operations.

func NewRoundPersistenceStore

func NewRoundPersistenceStore(
	db BatchedRoundStore, chainParams *chaincfg.Params, clk clock.Clock,
) *RoundPersistenceStore

NewRoundPersistenceStore creates a new round persistence store using the transaction executor pattern.

func (*RoundPersistenceStore) CommitState

func (s *RoundPersistenceStore) CommitState(ctx context.Context, r *round.Round,
	state round.ClientState) error

CommitState atomically persists both the round data and FSM state. This should be called at the "point of no return" when the client has sent partial signatures and the server may broadcast.

func (*RoundPersistenceStore) FailForfeitIntents

func (s *RoundPersistenceStore) FailForfeitIntents(ctx context.Context,
	outpoints []wire.OutPoint, reason string,
	code round.RoundFailureCode) error

FailForfeitIntents terminally fails the pending send intents anchored to the given forfeited VTXO outpoints, recording the reason and typed failure code, all in one write transaction. It is the terminal-failure counterpart to the anchor clear CommitState performs on the success path: when a round fails terminally (e.g. the operator cannot fund the commitment tx) the originating job must not keep replaying into the same wall. Marking (rather than deleting) the intent both stops the replay — ListPendingSendIntents skips non-pending rows — and leaves a durable, anchor-correlatable record the activity projection surfaces as failed with the reason. It is a no-op for an empty outpoint set.

func (*RoundPersistenceStore) FetchState

FetchState retrieves a round and its FSM state by round ID. Returns (round, state, err) atomically to ensure consistency.

func (*RoundPersistenceStore) FinalizeRound

func (s *RoundPersistenceStore) FinalizeRound(ctx context.Context,
	roundID round.RoundID, txid chainhash.Hash,
	confInfo round.ConfInfo) error

FinalizeRound marks a round as complete and archives it. The confInfo contains the block height and hash at which the commitment tx was confirmed.

func (*RoundPersistenceStore) GetRoundSummary

func (s *RoundPersistenceStore) GetRoundSummary(ctx context.Context,
	roundID string) (*RoundSummary, error)

GetRoundSummary returns one persisted round summary by round id.

func (*RoundPersistenceStore) GetVTXO

func (s *RoundPersistenceStore) GetVTXO(ctx context.Context,
	outpoint wire.OutPoint) (*round.ClientVTXO, error)

GetVTXO retrieves a specific VTXO by its outpoint. Returns an error if not found.

func (*RoundPersistenceStore) ListActiveRounds

func (s *RoundPersistenceStore) ListActiveRounds(ctx context.Context) (
	[]*round.Round, error)

ListActiveRounds returns all rounds that are in progress (commitment tx broadcast but not yet confirmed or expired).

func (*RoundPersistenceStore) ListConfirmedRounds

func (s *RoundPersistenceStore) ListConfirmedRounds(ctx context.Context) (
	[]*round.Round, error)

ListConfirmedRounds returns all rounds that have been confirmed on-chain.

func (*RoundPersistenceStore) ListRoundsPaginated

func (s *RoundPersistenceStore) ListRoundsPaginated(ctx context.Context,
	query ListRoundsQuery) ([]RoundSummary, error)

ListRoundsPaginated returns a page of persisted round summaries ordered by round_id using cursor-based pagination. Filters are applied before ordering and limiting, so every returned page is filled from matching rows only.

func (*RoundPersistenceStore) ListVTXOs

func (s *RoundPersistenceStore) ListVTXOs(ctx context.Context) (
	[]*round.ClientVTXO, error)

ListVTXOs returns all VTXOs currently owned by the client.

func (*RoundPersistenceStore) LookupRoundByCommitmentTx

func (s *RoundPersistenceStore) LookupRoundByCommitmentTx(ctx context.Context,
	txid chainhash.Hash) (*round.Round, error)

LookupRoundByCommitmentTx finds the round associated with a commitment transaction TXID. Used to route commitment tx confirmations to the correct round FSM.

func (*RoundPersistenceStore) MarkVTXOSpent

func (s *RoundPersistenceStore) MarkVTXOSpent(ctx context.Context,
	outpoint wire.OutPoint) error

MarkVTXOSpent marks a VTXO as spent (either via OOR transaction or forfeit). This prevents double-spending and records when the spend occurred.

func (*RoundPersistenceStore) SaveVTXOs

func (s *RoundPersistenceStore) SaveVTXOs(ctx context.Context,
	vtxos []*round.ClientVTXO) error

SaveVTXOs persists one or more VTXOs after a round confirms. Each VTXO includes its extracted tree path for unilateral exit.

type RoundRow

type RoundRow = sqlc.Round

Type aliases for sqlc generated types.

type RoundStore

type RoundStore interface {
	// InternalKeyQuerier lets the round and VTXO stores register and
	// hydrate wallet keys via the shared internal_keys registry within
	// their own transactions.
	InternalKeyQuerier

	InsertRound(ctx context.Context, arg InsertRoundParams) error

	GetRound(ctx context.Context, roundID string) (RoundRow, error)

	GetRoundByCommitmentTxid(ctx context.Context,
		txid []byte) (RoundRow, error)

	ListActiveRounds(ctx context.Context) ([]RoundRow, error)

	ListRoundsByStatus(ctx context.Context,
		status string) ([]RoundRow, error)

	UpdateRoundStatus(
		ctx context.Context, arg sqlc.UpdateRoundStatusParams,
	) error

	FinalizeRound(ctx context.Context, arg sqlc.FinalizeRoundParams) error

	InsertRoundBoardingIntent(ctx context.Context,
		arg sqlc.InsertRoundBoardingIntentParams) error

	GetRoundBoardingIntents(ctx context.Context,
		roundID string) ([]RoundBoardingIntentRow, error)

	InsertRoundVtxoRequest(ctx context.Context,
		arg sqlc.InsertRoundVtxoRequestParams) error

	GetRoundVtxoRequests(ctx context.Context,
		roundID string) ([]RoundVtxoRequestRow, error)

	InsertRoundClientTree(ctx context.Context,
		arg sqlc.InsertRoundClientTreeParams) error

	GetRoundClientTrees(ctx context.Context,
		roundID string) ([]RoundClientTreeRow, error)

	InsertClientTreeTxid(ctx context.Context,
		arg sqlc.InsertClientTreeTxidParams) error

	GetClientTreeByTxid(ctx context.Context,
		txid []byte) (RoundClientTreeRow, error)

	InsertVTXO(ctx context.Context, arg InsertVTXOParams) error

	GetVTXO(ctx context.Context, arg sqlc.GetVTXOParams) (VTXORow, error)

	ListUnspentVTXOs(ctx context.Context) ([]VTXORow, error)

	MarkVTXOSpent(ctx context.Context, arg sqlc.MarkVTXOSpentParams) error

	// VTXO lifecycle status queries.
	ListLiveVTXOs(ctx context.Context) ([]VTXORow, error)

	// ListRecoverableVTXOs returns the non-terminal set plus expired
	// VTXOs, whose actors must still be restored so their value can be
	// reclaimed by forfeiting them in a round.
	ListRecoverableVTXOs(ctx context.Context) ([]VTXORow, error)

	ListVTXOsByStatus(ctx context.Context,
		status int32) ([]sqlc.ListVTXOsByStatusRow, error)

	// ListVTXOSelectionCandidatesByStatus returns the lightweight
	// (outpoint, amount, pkScript) projection coin selection runs on,
	// avoiding the full descriptor decode on the per-payment hot path.
	ListVTXOSelectionCandidatesByStatus(ctx context.Context,
		status int32) (
		[]sqlc.ListVTXOSelectionCandidatesByStatusRow,
		error,
	)

	UpdateVTXOStatus(
		ctx context.Context, arg sqlc.UpdateVTXOStatusParams,
	) error

	// DeleteSpendingReservation removes a spending-reservation row so the
	// VTXO store can atomically update a VTXO's status and drop its
	// reservation in the same transaction when it leaves SpendingState.
	DeleteSpendingReservation(ctx context.Context,
		arg sqlc.DeleteSpendingReservationParams) error

	MarkVTXOForfeiting(
		ctx context.Context, arg sqlc.MarkVTXOForfeitingParams,
	) error

	// ListForfeitingVTXOsByRound returns the Forfeiting VTXOs bound to a
	// round, used to rebuild a reloaded round's forfeit set on restart.
	ListForfeitingVTXOsByRound(ctx context.Context,
		forfeitRoundID sql.NullString) (
		[]sqlc.ListForfeitingVTXOsByRoundRow, error)

	GetVTXOForfeitTx(ctx context.Context,
		arg sqlc.GetVTXOForfeitTxParams) (
		sqlc.GetVTXOForfeitTxRow,
		error,
	)

	MarkVTXOForfeited(
		ctx context.Context, arg sqlc.MarkVTXOForfeitedParams,
	) error

	DeleteVTXO(ctx context.Context, arg sqlc.DeleteVTXOParams) error

	// Per-VTXO ancestry-paths side table (multi-tree ancestry for OOR).
	InsertVTXOAncestryPath(ctx context.Context,
		arg sqlc.InsertVTXOAncestryPathParams) error

	DeleteVTXOAncestryPaths(ctx context.Context,
		arg sqlc.DeleteVTXOAncestryPathsParams) error

	ListVTXOAncestryPaths(ctx context.Context,
		arg sqlc.ListVTXOAncestryPathsParams) (
		[]sqlc.VtxoAncestryPath,
		error,
	)

	// Batched ancestry queries used by the list paths to avoid an
	// N+1 ListVTXOAncestryPaths call per VTXO row.
	ListLiveVTXOAncestryPaths(ctx context.Context) (
		[]sqlc.VtxoAncestryPath,
		error,
	)

	ListVTXOAncestryPathsByStatus(ctx context.Context,
		status int32) ([]sqlc.VtxoAncestryPath, error)

	ListUnspentVTXOAncestryPaths(ctx context.Context) (
		[]sqlc.VtxoAncestryPath, error)

	// Include BoardingStore methods for fetching boarding intent details.
	GetBoardingIntent(ctx context.Context,
		arg BoardingIntentKey) (BoardingIntentRow, error)

	GetBoardingAddress(ctx context.Context,
		pkScript []byte) (BoardingAddrRow, error)

	UpdateBoardingIntentStatus(ctx context.Context,
		arg sqlc.UpdateBoardingIntentStatusParams) error

	// ClearPendingIntentAnchorByOutpoint deletes the pending-intent
	// anchor row bound to one outpoint. Called from CommitState in the
	// same transaction that records the round adopting the anchored
	// intent (boarding outpoints for Board, forfeit VTXO outpoints for
	// SendOnChain), so a persisted intent can never be replayed after
	// the round it landed in has durably checkpointed.
	ClearPendingIntentAnchorByOutpoint(ctx context.Context,
		arg sqlc.ClearPendingIntentAnchorByOutpointParams) error

	// DeleteOrphanedPendingBoardIntents / DeleteOrphanedPendingSendIntents
	// sweep per-kind detail rows whose anchors have all been cleared.
	// Detail rows foreign-key the header, so they must be deleted before
	// DeleteOrphanedPendingIntents removes the now-anchorless headers.
	DeleteOrphanedPendingBoardIntents(ctx context.Context) error

	DeleteOrphanedPendingSendIntents(ctx context.Context) error

	// DeleteOrphanedPendingIntents sweeps pending-intent header rows
	// whose anchors have all been cleared. Called from CommitState after
	// the anchor clears (and detail sweeps) above so fully-adopted
	// intents vanish in the same transaction.
	DeleteOrphanedPendingIntents(ctx context.Context) error

	// MarkPendingSendIntentFailedByOutpoint terminally fails the pending
	// send intent anchored to one outpoint, recording the reason and typed
	// code. Called from FailForfeitIntents when a round fails terminally so
	// the intent stops replaying and its activity entry can surface as
	// failed. Anchors are retained so the failed job stays correlatable by
	// its consumed outpoint.
	MarkPendingSendIntentFailedByOutpoint(ctx context.Context,
		arg sqlc.MarkPendingSendIntentFailedByOutpointParams) error

	ListRoundsPaginated(ctx context.Context,
		arg ListRoundsPaginatedParams) ([]RoundRow, error)

	ListVTXOsByRound(ctx context.Context, roundID string) ([]VTXORow, error)
}

RoundStore is the interface that groups all round-related database queries. This is a subset of sqlc.Querier focused on round operations.

type RoundSummary

type RoundSummary struct {
	// RoundID is the unique identifier for this round.
	RoundID round.RoundID

	// Status is the persisted status string (e.g. "input_sig_sent",
	// "confirmed").
	Status string

	// CommitmentTxID is the commitment transaction id when persisted.
	CommitmentTxID fn.Option[chainhash.Hash]

	// ConfirmationHeight is the block height that confirmed the commitment
	// transaction when known.
	ConfirmationHeight fn.Option[int32]

	// CreationTime is the Unix timestamp when this round row was created.
	CreationTime int64

	// LastUpdateTime is the Unix timestamp when this round row was last
	// updated.
	LastUpdateTime int64

	// InputOutpoints are locally known round inputs. Today this is limited
	// to persisted boarding inputs because refresh and leave inputs are
	// not yet modeled as first-class persisted round input rows.
	InputOutpoints []wire.OutPoint

	// VTXOs lists the outpoints and amounts of VTXOs created in this
	// round.
	VTXOs []VTXOSummary
}

RoundSummary is a lightweight round descriptor returned by paginated queries.

type RoundVtxoRequestRow

type RoundVtxoRequestRow = sqlc.RoundVtxoRequest

Type aliases for sqlc generated types.

type SQLiteOpenConfig

type SQLiteOpenConfig struct {
	// DatabaseFileName is the native filename or logical browser OPFS name.
	DatabaseFileName string

	// Pragmas are applied by the selected driver at open time when
	// possible.
	Pragmas []SQLitePragma

	// TxLockImmediate requests immediate write transactions when the driver
	// supports that mode.
	TxLockImmediate bool

	// MaxOpenConns bounds the database/sql connection pool.
	MaxOpenConns int

	// MaxIdleConns bounds idle connections in the database/sql pool.
	MaxIdleConns int

	// ConnMaxLifetime limits how long one SQL connection is reused.
	ConnMaxLifetime time.Duration
}

SQLiteOpenConfig contains the driver-neutral SQLite open settings shared by the native and browser-backed database handles.

type SQLiteOpenResult

type SQLiteOpenResult struct {
	DB         *sql.DB
	DriverName string
	DSN        string
}

SQLiteOpenResult returns the opened SQL handle and driver details useful for logging and tests.

func OpenSQLiteDatabase

func OpenSQLiteDatabase(cfg SQLiteOpenConfig) (*SQLiteOpenResult, error)

OpenSQLiteDatabase opens a SQLite handle using the driver selected for the current build target.

type SQLitePragma

type SQLitePragma struct {
	Name  string
	Value string
}

SQLitePragma is one PRAGMA setting applied when a SQLite database opens.

type SpendingReservationPersistenceStore

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

SpendingReservationPersistenceStore persists the durable index of VTXO outpoints reserved by an active spend owner (e.g. an outgoing OOR session). A row exists IFF the owning session was durably checkpointed, so a startup sweep can deterministically release orphaned Spending VTXOs that have no reservation row.

func NewSpendingReservationPersistenceStore

func NewSpendingReservationPersistenceStore(
	db BatchedSpendingReservationStore, clk clock.Clock,
) *SpendingReservationPersistenceStore

NewSpendingReservationPersistenceStore creates a spending-reservation store using the transaction executor pattern.

func (*SpendingReservationPersistenceStore) ListReservedOutpoints

func (s *SpendingReservationPersistenceStore) ListReservedOutpoints(
	ctx context.Context) ([]wire.OutPoint, error)

ListReservedOutpoints returns every reserved outpoint. Used by the startup sweep to build the set of live reservations.

func (*SpendingReservationPersistenceStore) UpsertReservation

func (s *SpendingReservationPersistenceStore) UpsertReservation(
	ctx context.Context, outpoint wire.OutPoint, ownerKind int,
	ownerID chainhash.Hash,
) error

UpsertReservation records (or refreshes) the reservation for one outpoint.

type SpendingReservationStore

type SpendingReservationStore interface {
	UpsertSpendingReservation(ctx context.Context,
		arg sqlc.UpsertSpendingReservationParams) error

	ListSpendingReservationOutpoints(ctx context.Context) (
		[]sqlc.ListSpendingReservationOutpointsRow, error)
}

SpendingReservationStore groups the SQL methods needed to maintain the durable spending-reservation index.

type SqliteConfig

type SqliteConfig struct {
	// SkipMigrations if true, then all the tables will be created on start
	// up if they don't already exist.
	SkipMigrations bool `long:"skipmigrations" description:"Skip applying migrations on startup."`

	// SkipMigrationDBBackup if true, then a backup of the database will not
	// be created before applying migrations.
	SkipMigrationDBBackup bool `long:"skipmigrationdbbackup" description:"Skip creating a backup of the database before applying migrations."`

	// DatabaseFileName is the full file path where the database file can be
	// found.
	DatabaseFileName string `long:"dbfile" description:"The full path to the database."`

	// Synchronous controls the SQLite synchronous pragma, which governs
	// commit durability. Valid values are "full", "normal", and "off".
	// When empty it defaults to "normal", which under WAL mode omits the
	// per-commit WAL fsync of "full" (the WAL is synced only before a
	// checkpoint).
	Synchronous string `long:"synchronous" description:"The SQLite synchronous (commit durability) level. One of: full, normal, off."`

	// NoFullfsync disables the SQLite fullfsync pragma. The pragma only
	// matters on macOS, where a regular fsync does not guarantee the data
	// reached stable storage; with synchronous=normal it governs the WAL
	// checkpoint sync. Checkpoints fire continuously under a sustained
	// write load and F_FULLFSYNC waits on a full hardware cache flush, so
	// write-heavy deployments that accept the weaker flush guarantee can
	// disable it for substantially better throughput. The default keeps
	// fullfsync enabled.
	NoFullfsync bool `` /* 181-byte string literal not displayed */

	// Log is an optional logger for the SQLite store. When None, the store
	// falls back to the explicit constructor logger.
	Log fn.Option[btclog.Logger]
}

SqliteConfig holds all the config arguments needed to interact with our sqlite DB.

func DefaultSqliteConfig

func DefaultSqliteConfig(dataDir string) *SqliteConfig

DefaultSqliteConfig returns the default SQLite configuration values.

The default database file is placed under the provided data directory.

type SqliteStore

type SqliteStore struct {
	*BaseDB
	// contains filtered or unexported fields
}

SqliteStore is a sqlite3 based database for the daemon.

func NewSqliteStore

func NewSqliteStore(cfg *SqliteConfig,
	explicitLog btclog.Logger) (*SqliteStore, error)

NewSqliteStore attempts to open a new sqlite database based on the passed config. The explicit logger parameter is kept for backward compatibility with existing callers; when cfg.Log is set it takes precedence.

func NewTestDB

func NewTestDB(t testing.TB) *SqliteStore

NewTestDB is a helper function that creates an SQLite database for testing.

func NewTestDBHandleFromPath

func NewTestDBHandleFromPath(t testing.TB, dbPath string) *SqliteStore

NewTestDBHandleFromPath is a helper function that creates a new handle to an existing SQLite database for testing.

func NewTestDBWithVersion

func NewTestDBWithVersion(t testing.TB, version uint) *SqliteStore

NewTestDBWithVersion is a helper function that creates an SQLite database for testing and migrates it to the given version.

func NewTestSqliteDB

func NewTestSqliteDB(t testing.TB) *SqliteStore

NewTestSqliteDB is a helper function that creates an SQLite database for testing.

func NewTestSqliteDBHandleFromPath

func NewTestSqliteDBHandleFromPath(t testing.TB, dbPath string,
	log btclog.Logger) *SqliteStore

NewTestSqliteDBHandleFromPath is a helper function that creates a SQLite database handle given a database file path.

func NewTestSqliteDBWithVersion

func NewTestSqliteDBWithVersion(t testing.TB, version uint) *SqliteStore

NewTestSqliteDBWithVersion is a helper function that creates an SQLite database for testing and migrates it to the given version.

func (*SqliteStore) ExecuteMigrations

func (s *SqliteStore) ExecuteMigrations(target MigrationTarget,
	optFuncs ...MigrateOpt) error

ExecuteMigrations runs migrations for the sqlite database, depending on the target given, either all migrations or up to a given version.

type Store

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

Store is the unified SQL-based storage implementation that wraps all repository types (events, rounds, vtxos, offchain txs).

func NewStore

func NewStore(db *sql.DB, queries *sqlc.Queries, backend sqlc.BackendType,
	explicitLog btclog.Logger) *Store

NewStore constructs the unified SQL store wrapper from initialized DB primitives.

Callers are expected to provide backend-specific connections and sqlc query adapters that already completed migration and connectivity setup. The explicit logger parameter is kept for backward compatibility; callers that prefer the fn.Option pattern should set Config.Log instead.

func NewStoreFromConfig

func NewStoreFromConfig(cfg *Config,
	explicitLog btclog.Logger) (*Store, error)

NewStoreFromConfig builds and initializes a store from backend config.

The method dispatches to backend-specific constructors and returns a unified Store wrapper over the resulting SQL handle and query adapter. The explicit logger parameter is kept for backward compatibility; when cfg.Log is set it takes precedence.

func (*Store) Backend

func (s *Store) Backend() sqlc.BackendType

Backend reports which storage backend is active for this store instance.

func (*Store) BaseDB

func (s *Store) BaseDB() *BaseDB

BaseDB returns the shared BaseDB used by transaction executors.

Repository constructors use this helper to create typed transactional stores without duplicating base wiring.

func (*Store) Close

func (s *Store) Close() error

Close releases the underlying SQL connection pool.

Close is idempotent: calling it on a store with no DB handle is a no-op.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying shared SQL handle.

The returned handle can be used for low-level integration points that are not yet wrapped by repository helpers.

func (*Store) NewActivityStore

func (s *Store) NewActivityStore(clk clock.Clock) *ActivityPersistenceStore

NewActivityStore builds the canonical activity-log persistence store with transactional query execution.

The activity store is the source of truth for the wallet activity feed: a current-state activity_entries projection read by List and an append-only activity_events transition log read by a resumable SubscribeWallet.

func (*Store) NewBoardingStore

func (s *Store) NewBoardingStore(chainParams *chaincfg.Params,
	clk clock.Clock) *BoardingWalletStore

NewBoardingStore builds a boarding wallet store with transactional execution semantics.

This keeps boarding persistence behavior consistent with other typed stores that use the shared transaction executor pattern.

func (*Store) NewMacaroonRootKeyStore

func (s *Store) NewMacaroonRootKeyStore() *RootKeyStore

NewMacaroonRootKeyStore creates a macaroon root key store for this Store.

func (*Store) NewOORArtifactStore

func (s *Store) NewOORArtifactStore(
	clk clock.Clock) *OORArtifactPersistenceStore

NewOORArtifactStore builds the OOR artifact persistence store with transactional query execution.

The artifact store provides package/binding/cursor APIs used by OOR receive persistence and unroll package resolution paths.

func (*Store) NewOORSessionRegistryStore

func (s *Store) NewOORSessionRegistryStore(
	clk clock.Clock) *OORSessionRegistryStoreDB

NewOORSessionRegistryStore builds the OOR session registry control-plane store with transactional query execution.

func (*Store) NewRoundStore

func (s *Store) NewRoundStore(chainParams *chaincfg.Params,
	clk clock.Clock) *RoundPersistenceStore

NewRoundStore builds a round persistence store with transactional execution.

The returned store wraps sqlc round queries in the generic transaction executor so multi-query round updates can run atomically.

func (*Store) NewSpendingReservationStore

func (s *Store) NewSpendingReservationStore(
	clk clock.Clock) *SpendingReservationPersistenceStore

NewSpendingReservationStore builds the spending-reservation persistence store with transactional query execution.

The reservation store maintains a durable index of VTXO outpoints reserved by an active spend owner so a startup sweep can release orphaned Spending VTXOs that have no live reservation.

func (*Store) NewUnilateralExitStore

func (s *Store) NewUnilateralExitStore(
	clk clock.Clock) *UnilateralExitPersistenceStore

NewUnilateralExitStore builds the unilateral-exit persistence store with transactional query execution.

func (*Store) NewVHTLCRecoveryStore

func (s *Store) NewVHTLCRecoveryStore(clk clock.Clock) *VHTLCRecoveryStoreDB

NewVHTLCRecoveryStore builds the vHTLC recovery persistence store with transactional execution.

func (*Store) NewVTXOStore

func (s *Store) NewVTXOStore(clk clock.Clock) *VTXOPersistenceStore

NewVTXOStore builds a VTXO persistence store with transactional query execution.

The returned store wraps sqlc VTXO queries in the generic transaction executor so multi-query VTXO updates can run atomically.

func (*Store) Queries

func (s *Store) Queries() *sqlc.Queries

Queries returns the underlying sqlc query adapter.

This is mainly used when a caller needs direct access to generated query methods outside repository wrappers.

type TestPgFixture

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

TestPgFixture is a test fixture that starts a Postgres 15 instance in a docker container.

func NewTestPgFixture

func NewTestPgFixture(t testing.TB, expiry time.Duration,
	autoRemove bool) *TestPgFixture

NewTestPgFixture constructs a new TestPgFixture starting up a docker container running Postgres 15. The started container will expire in after the passed duration.

func (*TestPgFixture) ClearDB

func (f *TestPgFixture) ClearDB(t testing.TB)

ClearDB clears the database.

func (*TestPgFixture) GetConfig

func (f *TestPgFixture) GetConfig() *PostgresConfig

GetConfig returns the full config of the Postgres node.

func (*TestPgFixture) GetDSN

func (f *TestPgFixture) GetDSN() string

GetDSN returns the DSN (Data Source Name) for the started Postgres node.

func (*TestPgFixture) TearDown

func (f *TestPgFixture) TearDown(t testing.TB)

TearDown stops the underlying docker container.

type TransactionExecutor

type TransactionExecutor[Query any] struct {
	BatchedQuerier
	// contains filtered or unexported fields
}

TransactionExecutor is a generic struct that abstracts away from the type of query a type needs to run under a database transaction, and also the set of options for that transaction. The QueryCreator is used to create a query given a database transaction created by the BatchedQuerier.

func NewTransactionExecutor

func NewTransactionExecutor[Querier any](db BatchedQuerier,
	createQuery QueryCreator[Querier], log btclog.Logger,
	opts ...TxExecutorOption) *TransactionExecutor[Querier]

NewTransactionExecutor creates a new instance of a TransactionExecutor given a Querier query object and a concrete type for the type of transactions the Querier understands.

func (*TransactionExecutor[Q]) Backend

func (t *TransactionExecutor[Q]) Backend() sqlc.BackendType

Backend returns the type of the database backend used.

func (*TransactionExecutor[Q]) ExecTx

func (t *TransactionExecutor[Q]) ExecTx(ctx context.Context,
	txOptions TxOptions, txBody func(Q) error) error

ExecTx is a wrapper for txBody to abstract the creation and commit of a db transaction. The db transaction is embedded in a `*Queries` that txBody needs to use when executing each one of the queries that need to be applied atomically. This can be used by other storage interfaces to parameterize the type of query and options run, in order to have access to batched operations related to a storage object.

type Tx

type Tx interface {
	// Commit commits the database transaction, an error should be returned
	// if the commit isn't possible.
	Commit() error

	// Rollback rolls back an incomplete database transaction.
	// Transactions that were able to be committed can still call this as a
	// noop.
	Rollback() error
}

Tx represents a database transaction that can be committed or rolled back.

type TxExecutorOption

type TxExecutorOption func(*txExecutorOptions)

TxExecutorOption is a functional option that allows us to pass in optional argument when creating the executor.

func WithTxRetries

func WithTxRetries(numRetries int) TxExecutorOption

WithTxRetries is a functional option that allows us to specify the number of times a transaction should be retried if it fails with a repeatable error.

func WithTxRetryDelay

func WithTxRetryDelay(delay time.Duration) TxExecutorOption

WithTxRetryDelay is a functional option that allows us to specify the delay to wait before a transaction is retried.

type TxOptions

type TxOptions interface {
	// ReadOnly returns true if the transaction should be read-only.
	ReadOnly() bool
}

TxOptions represents a set of options one can use to control what type of database transaction is created. Transaction can either be read or write.

type UTXOAuditStoreDB

type UTXOAuditStoreDB struct {
	*TransactionExecutor[*sqlc.Queries]
}

UTXOAuditStoreDB bridges the ledger.UTXOAuditStore interface to the sqlc-generated queries. This adapter converts UTXOAuditEntry to sqlc.InsertWalletUTXOLogParams and wraps all operations in ExecTx for transactional safety.

Beyond the ledger.UTXOAuditStore interface, UTXOAuditStoreDB also provides query methods (ListUTXOAuditEntries, etc.) used by the daemon RPC layer.

func NewUTXOAuditStoreDB

func NewUTXOAuditStoreDB(store *Store) *UTXOAuditStoreDB

NewUTXOAuditStoreDB creates a new UTXOAuditStoreDB from a Store.

func (*UTXOAuditStoreDB) CountUTXOAuditEntries

func (s *UTXOAuditStoreDB) CountUTXOAuditEntries(ctx context.Context) (int64,
	error)

CountUTXOAuditEntries returns the total number of UTXO audit entries within a read transaction.

func (*UTXOAuditStoreDB) InsertUTXOAuditEntry

func (s *UTXOAuditStoreDB) InsertUTXOAuditEntry(ctx context.Context,
	entry ledger.UTXOAuditEntry) error

InsertUTXOAuditEntry persists a UTXO audit log record within a database transaction.

func (*UTXOAuditStoreDB) ListUTXOAuditEntries

func (s *UTXOAuditStoreDB) ListUTXOAuditEntries(ctx context.Context, limit,
	offset int32) ([]sqlc.WalletUtxoLog, error)

ListUTXOAuditEntries returns a paginated list of UTXO audit entries ordered by creation time within a read transaction.

func (*UTXOAuditStoreDB) ListUTXOAuditEntriesByBlock

func (s *UTXOAuditStoreDB) ListUTXOAuditEntriesByBlock(ctx context.Context,
	blockHeight int32) ([]sqlc.WalletUtxoLog, error)

ListUTXOAuditEntriesByBlock returns all UTXO audit entries for a given block height within a read transaction.

func (*UTXOAuditStoreDB) ListUTXOAuditEntriesByClassification

func (s *UTXOAuditStoreDB) ListUTXOAuditEntriesByClassification(
	ctx context.Context, classification string, limit, offset int32) (
	[]sqlc.WalletUtxoLog, error)

ListUTXOAuditEntriesByClassification returns a paginated list of entries filtered by classification within a read transaction.

type UnilateralExitJobRecord

type UnilateralExitJobRecord struct {
	TargetOutpoint wire.OutPoint
	ActorID        string
	Status         UnilateralExitJobStatus
	Trigger        UnilateralExitJobTrigger
	ExitPolicyKind string
	ExitPolicyRef  string
	LastError      string
	SweepTxid      []byte
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

UnilateralExitJobRecord is one manager-faced job control-plane row.

type UnilateralExitJobStatus

type UnilateralExitJobStatus int32

UnilateralExitJobStatus is the manager-facing status of one target job.

const (
	// UnilateralExitJobStatusPending means the job row exists
	// but work has not started materially.
	UnilateralExitJobStatusPending UnilateralExitJobStatus = iota

	// UnilateralExitJobStatusMaterializing means proof nodes
	// are still being materialized.
	UnilateralExitJobStatusMaterializing

	// UnilateralExitJobStatusCSVPending means the target is
	// confirmed and the job is waiting for CSV maturity.
	UnilateralExitJobStatusCSVPending

	// UnilateralExitJobStatusSweeping means the final sweep has been
	// broadcast and the job is awaiting its confirmation.
	UnilateralExitJobStatusSweeping

	// UnilateralExitJobStatusCompleted means the job completed
	// successfully.
	UnilateralExitJobStatusCompleted

	// UnilateralExitJobStatusFailed means the job failed terminally.
	UnilateralExitJobStatusFailed

	// UnilateralExitJobStatusSweepBroadcasting means the final sweep
	// has been built and persisted but has not yet been submitted for
	// broadcast. Appended after the original enum so existing rows at
	// status=3 continue to decode as "sweep broadcast, awaiting conf".
	UnilateralExitJobStatusSweepBroadcasting

	// UnilateralExitJobStatusFailedRecoverable means the job failed
	// terminally WITHOUT leaving any on-chain footprint (no proof or
	// sweep tx was broadcast), so the target VTXO is still live from the
	// operator's perspective and is safe to roll back to live. It is a
	// separate status from UnilateralExitJobStatusFailed (which implies
	// the exit has begun on-chain) so boot-time reconciliation can decide
	// whether to recover the VTXO (wavelength#602).
	UnilateralExitJobStatusFailedRecoverable
)

func (UnilateralExitJobStatus) IsTerminal

func (s UnilateralExitJobStatus) IsTerminal() bool

IsTerminal reports whether the control-plane job status is terminal.

type UnilateralExitJobTrigger

type UnilateralExitJobTrigger int32

UnilateralExitJobTrigger records what started an exit job.

const (
	// UnilateralExitJobTriggerManual is an operator-triggered start.
	UnilateralExitJobTriggerManual UnilateralExitJobTrigger = iota

	// UnilateralExitJobTriggerCriticalExpiry is a VTXO expiry handoff.
	UnilateralExitJobTriggerCriticalExpiry

	// UnilateralExitJobTriggerRestart marks a restored in-flight job.
	UnilateralExitJobTriggerRestart

	// UnilateralExitJobTriggerFraudSpend is reserved for active-job spend
	// escalation.
	UnilateralExitJobTriggerFraudSpend
)

type UnilateralExitPersistenceStore

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

UnilateralExitPersistenceStore persists immutable proofs and manager-facing job rows for the unilateral-exit subsystem.

func NewUnilateralExitPersistenceStore

func NewUnilateralExitPersistenceStore(
	db BatchedUnilateralExitStore, clk clock.Clock,
) *UnilateralExitPersistenceStore

NewUnilateralExitPersistenceStore creates a unilateral-exit store.

func (*UnilateralExitPersistenceStore) FundingAddress

func (s *UnilateralExitPersistenceStore) FundingAddress(ctx context.Context,
	target wire.OutPoint,
	newAddress func(context.Context) (string, error)) (string, error)

FundingAddress returns the persisted exit funding address for target, deriving and persisting a new one via newAddress on a miss. The derived address is stable across daemon restarts because it is keyed by the target VTXO outpoint, so polling an exit plan (or restarting the daemon) always hands the user back the same address rather than demanding a fresh deposit for the same VTXO (wavelength#893).

Derivation happens outside the DB transaction on purpose: newAddress reaches into the backing wallet, which must not run under an open SQL write tx. The INSERT uses ON CONFLICT DO NOTHING so a concurrent poller that wins the race keeps its address; this reload-after-insert step returns whichever address actually landed in the row.

func (*UnilateralExitPersistenceStore) GetJob

GetJob loads one manager-facing job control-plane row.

func (*UnilateralExitPersistenceStore) ListNonTerminalJobs

ListNonTerminalJobs loads all non-terminal manager-facing job rows.

func (*UnilateralExitPersistenceStore) MarkJobTerminal

func (s *UnilateralExitPersistenceStore) MarkJobTerminal(ctx context.Context,
	target wire.OutPoint, status UnilateralExitJobStatus, reason string,
	sweepTxid []byte) error

MarkJobTerminal updates one job row to a terminal status.

func (*UnilateralExitPersistenceStore) UpsertJob

UpsertJob persists or updates one manager-facing job record. NOTE: The proof-related methods (UpsertProof, GetProof, MarkProofFailed) have been removed. Proofs are now derived on demand from the authoritative VTXO descriptor and OOR artifact data via the ProofAssembler.

type UnilateralExitStore

type UnilateralExitStore interface {
	UpsertUnilateralExitJob(ctx context.Context,
		arg sqlc.UpsertUnilateralExitJobParams) error

	GetUnilateralExitJob(ctx context.Context,
		arg sqlc.GetUnilateralExitJobParams) (
		sqlc.UnilateralExitJob,
		error,
	)

	ListNonTerminalUnilateralExitJobs(ctx context.Context) (
		[]sqlc.UnilateralExitJob, error)

	MarkUnilateralExitJobTerminal(ctx context.Context,
		arg sqlc.MarkUnilateralExitJobTerminalParams) error

	GetExitFundingAddress(ctx context.Context,
		arg sqlc.GetExitFundingAddressParams) (
		sqlc.ExitFundingAddress,
		error,
	)

	InsertExitFundingAddress(ctx context.Context,
		arg sqlc.InsertExitFundingAddressParams) error
}

UnilateralExitStore groups SQL methods needed by the unilateral-exit job store. Proof persistence has been removed — proofs are derived on demand from the VTXO descriptor and OOR artifact data.

type VHTLCRecoveryStoreDB

type VHTLCRecoveryStoreDB struct {
	*TransactionExecutor[*sqlc.Queries]
	// contains filtered or unexported fields
}

VHTLCRecoveryStoreDB persists vHTLC recovery jobs.

func NewVHTLCRecoveryStore

func NewVHTLCRecoveryStore(store *Store,
	clk clock.Clock) *VHTLCRecoveryStoreDB

NewVHTLCRecoveryStore creates a vHTLC recovery store from the shared DB.

func (*VHTLCRecoveryStoreDB) ArmRecovery

ArmRecovery stores an armed recovery job or returns the existing idempotent row. A retry can return a terminal row when the original recovery already completed, failed, or was cancelled; callers must inspect IsTerminal before deciding whether to escalate or short-circuit.

func (*VHTLCRecoveryStoreDB) CancelRecovery

func (s *VHTLCRecoveryStoreDB) CancelRecovery(ctx context.Context, id,
	reason string, cooperativeTxid []byte) error

CancelRecovery marks a non-terminal recovery job as cancelled.

func (*VHTLCRecoveryStoreDB) CompleteRecovery

func (s *VHTLCRecoveryStoreDB) CompleteRecovery(ctx context.Context,
	id string) error

CompleteRecovery marks a non-terminal recovery job as completed.

func (*VHTLCRecoveryStoreDB) EscalateRecovery

func (s *VHTLCRecoveryStoreDB) EscalateRecovery(ctx context.Context, id string,
	claimPreimage []byte) error

EscalateRecovery marks an armed recovery job as active. The optional claim preimage is written in the same transaction so cross-process claim recovery can restart after escalation without depending on the caller process.

func (*VHTLCRecoveryStoreDB) FailRecovery

func (s *VHTLCRecoveryStoreDB) FailRecovery(ctx context.Context, id string,
	failure error) error

FailRecovery marks a non-terminal recovery job as failed.

func (*VHTLCRecoveryStoreDB) GetRecovery

GetRecovery loads one recovery job row.

func (*VHTLCRecoveryStoreDB) ListNonTerminalRecoveries

func (s *VHTLCRecoveryStoreDB) ListNonTerminalRecoveries(ctx context.Context) (
	[]vhtlcrecovery.RecoveryJob, error)

ListNonTerminalRecoveries loads every active recovery job.

func (*VHTLCRecoveryStoreDB) ListRecoveries

func (s *VHTLCRecoveryStoreDB) ListRecoveries(ctx context.Context) (
	[]vhtlcrecovery.RecoveryJob, error)

ListRecoveries loads every recovery job in newest-updated order.

type VTXOPersistenceStore

type VTXOPersistenceStore struct {

	// Log is an optional logger for this persistence store. If None,
	// the store falls back to extracting a logger from context via
	// build.LoggerFromContext, or uses btclog.Disabled if no logger
	// is found. Matches the fn.Option[btclog.Logger] pattern used by
	// other subsystems (indexer.SyncClient, oor.Actor, etc.).
	Log fn.Option[btclog.Logger]
	// contains filtered or unexported fields
}

VTXOPersistenceStore implements the vtxo.VTXOStore interface using the BatchedTx pattern for transaction-safe VTXO lifecycle operations.

func NewVTXOPersistenceStore

func NewVTXOPersistenceStore(
	db BatchedRoundStore, c clock.Clock,
) *VTXOPersistenceStore

NewVTXOPersistenceStore creates a new VTXO persistence store using the transaction executor pattern. The logger is unset by default; to route rehydrate-path diagnostics (e.g. expiry drift warnings) through the daemon's subsystem logger, set Log to fn.Some(logger) after construction or use NewVTXOPersistenceStoreWithLogger.

func NewVTXOPersistenceStoreWithLogger

func NewVTXOPersistenceStoreWithLogger(db BatchedRoundStore, c clock.Clock,
	log fn.Option[btclog.Logger]) *VTXOPersistenceStore

NewVTXOPersistenceStoreWithLogger constructs a VTXO persistence store with an explicit logger attached.

func (*VTXOPersistenceStore) DeleteVTXO

func (s *VTXOPersistenceStore) DeleteVTXO(
	ctx context.Context, outpoint wire.OutPoint,
) error

DeleteVTXO removes a VTXO from storage. Used for cleanup after terminal states are reached and the VTXO is no longer needed.

func (*VTXOPersistenceStore) GetForfeitTx

func (s *VTXOPersistenceStore) GetForfeitTx(ctx context.Context,
	outpoint wire.OutPoint) (*wire.MsgTx, error)

GetForfeitTx retrieves the persisted forfeit transaction for a VTXO. Used during recovery to restore the ForfeitingState with its tx. Returns nil if no forfeit tx is stored for this outpoint.

func (*VTXOPersistenceStore) GetVTXO

func (s *VTXOPersistenceStore) GetVTXO(ctx context.Context,
	outpoint wire.OutPoint) (*vtxo.Descriptor, error)

GetVTXO retrieves a VTXO by its outpoint. Used for actor recovery on startup. Returns vtxo.ErrVTXONotFound if the outpoint is not stored.

func (*VTXOPersistenceStore) ListLiveVTXOs

func (s *VTXOPersistenceStore) ListLiveVTXOs(ctx context.Context) (
	[]*vtxo.Descriptor, error)

ListLiveVTXOs returns all VTXOs not in a terminal state. Used during startup to recover active VTXO actors after restart. Issues exactly two queries — the parent VTXO list and a batched ancestry-paths fetch — so descriptor rehydration runs in O(2) round-trips rather than O(N).

func (*VTXOPersistenceStore) ListLiveVTXOsLight

func (s *VTXOPersistenceStore) ListLiveVTXOsLight(ctx context.Context) (
	[]*vtxo.Descriptor, error)

ListLiveVTXOsLight returns the same descriptors as ListLiveVTXOs with a nil Ancestry on every entry. The ancestry side table's TLV tree fragments grow with OOR chain depth, and the batched join sorts those blobs through SQLite's external sorter on every call, so consumers that never walk the lineage (the ListVTXOs RPC response carries no ancestry) skip the side table entirely.

func (*VTXOPersistenceStore) ListRecoverableVTXOs

func (s *VTXOPersistenceStore) ListRecoverableVTXOs(ctx context.Context) (
	[]*vtxo.Descriptor, error)

ListRecoverableVTXOs returns every VTXO whose actor must be restored at startup: the ListLiveVTXOs set plus expired ones.

Expired VTXOs are excluded from ListLiveVTXOs because they hold no spendable value until reissued, but their actors must still exist so the value can be reclaimed by forfeiting them in an ordinary round.

func (*VTXOPersistenceStore) ListRecoverableVTXOsLight

func (s *VTXOPersistenceStore) ListRecoverableVTXOsLight(ctx context.Context) (
	[]*vtxo.Descriptor, error)

ListRecoverableVTXOsLight returns the recoverable set without the ancestry join, for callers that only need each descriptor's amount.

func (*VTXOPersistenceStore) ListSelectionCandidatesByStatus

func (s *VTXOPersistenceStore) ListSelectionCandidatesByStatus(
	ctx context.Context, status vtxo.VTXOStatus) ([]vtxo.SelectedVTXO,
	error)

ListSelectionCandidatesByStatus returns the lightweight projection coin selection runs on: outpoint, amount, and pkScript per VTXO in the given status. Selection happens on every payment and needs only these fields, so this path skips the full descriptor decode (pubkey parsing, taproot script reconstruction, policy template decode) and the batched ancestry query entirely.

func (*VTXOPersistenceStore) ListVTXOsByStatus

func (s *VTXOPersistenceStore) ListVTXOsByStatus(ctx context.Context,
	status vtxo.VTXOStatus) ([]*vtxo.Descriptor, error)

ListVTXOsByStatus returns all VTXOs matching the given status. This enables the ListVTXOs RPC to query terminal states (spent, forfeited) directly from the database instead of filtering in memory. Like ListLiveVTXOs, the ancestry side table is loaded via a single batched query rather than per-row.

func (*VTXOPersistenceStore) ListVTXOsByStatusLight

func (s *VTXOPersistenceStore) ListVTXOsByStatusLight(ctx context.Context,
	status vtxo.VTXOStatus) ([]*vtxo.Descriptor, error)

ListVTXOsByStatusLight returns the same descriptors as ListVTXOsByStatus with a nil Ancestry on every entry. See ListLiveVTXOsLight for why listing-only consumers skip the ancestry side table.

func (*VTXOPersistenceStore) MarkForfeited

func (s *VTXOPersistenceStore) MarkForfeited(
	ctx context.Context, outpoint wire.OutPoint, forfeitTxID chainhash.Hash,
) error

MarkForfeited marks a VTXO as forfeited and records the forfeit transaction ID. This is called when the new round's commitment transaction confirms.

func (*VTXOPersistenceStore) MarkForfeiting

func (s *VTXOPersistenceStore) MarkForfeiting(
	ctx context.Context, outpoint wire.OutPoint, roundID string,
	forfeitTx *wire.MsgTx,
) error

MarkForfeiting transitions a VTXO to forfeiting state and persists the signed forfeit transaction for crash recovery. Called when entering the forfeit flow before the new round's commitment confirms.

func (*VTXOPersistenceStore) SaveVTXO

func (s *VTXOPersistenceStore) SaveVTXO(
	ctx context.Context, desc *vtxo.Descriptor,
) error

SaveVTXO persists a new VTXO to storage. Called when a VTXO actor is created. Returns error if a VTXO with the same outpoint already exists.

func (*VTXOPersistenceStore) UpdateVTXOStatus

func (s *VTXOPersistenceStore) UpdateVTXOStatus(
	ctx context.Context, outpoint wire.OutPoint, status vtxo.VTXOStatus,
) error

UpdateVTXOStatus atomically updates a VTXO's status. This is the primary method for state transitions that don't require additional data.

func (*VTXOPersistenceStore) UpdateVTXOStatusReleasingReservation

func (s *VTXOPersistenceStore) UpdateVTXOStatusReleasingReservation(
	ctx context.Context, outpoint wire.OutPoint, status vtxo.VTXOStatus,
) error

UpdateVTXOStatusReleasingReservation updates a VTXO's status and deletes its spending-reservation row in the same transaction. It is used for transitions that move a VTXO out of SpendingState so the durable index never retains a stale row that could mask a future orphan on the same outpoint. Deleting a non-existent row is a no-op, so this is safe on outpoints that were never reserved.

type VTXORow

type VTXORow = sqlc.Vtxo

Type aliases for sqlc generated types.

type VTXOSummary

type VTXOSummary struct {
	// Outpoint is the VTXO's outpoint.
	Outpoint wire.OutPoint

	// Amount is the VTXO value in satoshis.
	Amount btcutil.Amount
}

VTXOSummary is a lightweight VTXO descriptor containing only the outpoint and amount.

Directories

Path Synopsis
Package actordelivery provides an isolated SQL integration surface for durable actor mailbox persistence.
Package actordelivery provides an isolated SQL integration surface for durable actor mailbox persistence.

Jump to

Keyboard shortcuts

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