storage

package
v0.0.0-...-3d75ffd Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package storage provides persistent storage using SQLite.

Package storage - Order storage operations.

Package storage - Secret storage operations for HTLC swaps.

Package storage provides persistent storage using SQLite.

Package storage - Swap leg storage operations.

Package storage - Swap state persistence for atomic swaps. This file provides CRUD operations for persisting swap state to SQLite, enabling recovery after node restart.

Package storage - Trade storage operations.

Package storage provides wallet UTXO persistence for multi-address spending.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrOrderNotFound = errors.New("order not found")
	ErrOrderExpired  = errors.New("order expired")
)

Order errors

View Source
var (
	ErrSecretNotFound      = errors.New("secret not found")
	ErrSecretAlreadyExists = errors.New("secret already exists for this trade and hash")
)

Secret errors

View Source
var (
	ErrSwapNotFound     = errors.New("swap not found")
	ErrSwapExists       = errors.New("swap already exists")
	ErrInvalidSwapState = errors.New("invalid swap state")
)

Swap persistence errors

View Source
var (
	ErrSwapLegNotFound = errors.New("swap leg not found")
)

Swap leg errors

View Source
var (
	ErrTradeNotFound = errors.New("trade not found")
)

Trade errors

Functions

This section is empty.

Types

type Config

type Config struct {
	DataDir string
}

Config holds storage configuration.

type InboxMessage

type InboxMessage struct {
	ID          int64  `json:"id"`
	MessageID   string `json:"message_id"`
	TradeID     string `json:"trade_id"`
	PeerID      string `json:"peer_id"`
	MessageType string `json:"message_type"`
	SequenceNum uint64 `json:"sequence_num"`
	ReceivedAt  int64  `json:"received_at"`
	ProcessedAt *int64 `json:"processed_at"`
	AckSent     bool   `json:"ack_sent"`
}

InboxMessage represents a received message for deduplication.

type MessageSequence

type MessageSequence struct {
	TradeID   string `json:"trade_id"`
	LocalSeq  uint64 `json:"local_seq"`
	RemoteSeq uint64 `json:"remote_seq"`
	UpdatedAt int64  `json:"updated_at"`
}

MessageSequence tracks sequence numbers for a trade.

type Order

type Order struct {
	ID      string
	PeerID  string
	Status  OrderStatus
	IsLocal bool // True if this is our order

	// Trading pair (price is implicit ratio)
	OfferChain    string
	OfferAmount   uint64
	RequestChain  string
	RequestAmount uint64

	// Preferred swap methods in priority order
	PreferredMethods []string

	// Timing
	CreatedAt time.Time
	ExpiresAt *time.Time
	UpdatedAt *time.Time

	// Ownership proof
	Signature string
}

Order represents a trade order in the database. Price is implicit: offer_amount/request_amount ratio.

type OrderFilter

type OrderFilter struct {
	Status       *OrderStatus
	OfferChain   string
	RequestChain string
	PeerID       string
	IsLocal      *bool
	Limit        int
	Offset       int
}

ListOrders lists orders matching the given filters.

type OrderStatus

type OrderStatus string

OrderStatus represents the status of an order.

const (
	OrderStatusOpen      OrderStatus = "open"
	OrderStatusMatched   OrderStatus = "matched"
	OrderStatusCompleted OrderStatus = "completed"
	OrderStatusCancelled OrderStatus = "cancelled"
	OrderStatusExpired   OrderStatus = "expired"
	OrderStatusFailed    OrderStatus = "failed"
)

type OutboxMessage

type OutboxMessage struct {
	ID           int64        `json:"id"`
	MessageID    string       `json:"message_id"`
	TradeID      string       `json:"trade_id"`
	PeerID       string       `json:"peer_id"`
	MessageType  string       `json:"message_type"`
	Payload      []byte       `json:"payload"`
	SequenceNum  uint64       `json:"sequence_num"`
	SwapTimeout  int64        `json:"swap_timeout"`
	CreatedAt    int64        `json:"created_at"`
	RetryCount   int          `json:"retry_count"`
	LastAttempt  int64        `json:"last_attempt_at"`
	NextRetryAt  int64        `json:"next_retry_at"`
	AckedAt      *int64       `json:"acked_at"`
	Status       OutboxStatus `json:"status"`
	ErrorMessage string       `json:"error_message"`
}

OutboxMessage represents a message in the outbound queue.

func (*OutboxMessage) ToJSON

func (m *OutboxMessage) ToJSON(v interface{}) error

ToJSON converts an OutboxMessage payload to the original message type.

type OutboxStatus

type OutboxStatus string

OutboxStatus represents the status of an outbound message.

const (
	OutboxStatusPending OutboxStatus = "pending" // Awaiting delivery
	OutboxStatusSent    OutboxStatus = "sent"    // Sent, awaiting ACK
	OutboxStatusAcked   OutboxStatus = "acked"   // Successfully delivered
	OutboxStatusFailed  OutboxStatus = "failed"  // Permanently failed
	OutboxStatusExpired OutboxStatus = "expired" // Swap expired before delivery
)

type PeerRecord

type PeerRecord struct {
	PeerID          string    `json:"peer_id"`
	Addresses       []string  `json:"addresses"`
	FirstSeen       time.Time `json:"first_seen"`
	LastSeen        time.Time `json:"last_seen"`
	LastConnected   time.Time `json:"last_connected"`
	ConnectionCount int       `json:"connection_count"`
	IsBootstrap     bool      `json:"is_bootstrap"`
}

PeerRecord represents a known peer in the database.

type Secret

type Secret struct {
	ID      string
	TradeID string

	// The secret hash (always known - SHA256 of secret)
	SecretHash string // 32 bytes, hex-encoded

	// The secret itself (only after reveal)
	Secret string // 32 bytes, hex-encoded

	// Who created this secret
	CreatedBy SecretCreator

	// Remote wallet addresses (received with secret hash in P2P message)
	// These are the counterparty's addresses for receiving funds
	RemoteOfferWalletAddr   string // Counterparty's address on offer chain
	RemoteRequestWalletAddr string // Counterparty's address on request chain

	// Timing
	CreatedAt  time.Time
	RevealedAt *time.Time
}

Secret represents an HTLC secret in the database.

type SecretCreator

type SecretCreator string

SecretCreator indicates who created the secret.

const (
	SecretCreatorUs   SecretCreator = "us"   // We created the secret
	SecretCreatorThem SecretCreator = "them" // Counterparty created the secret
)

type Storage

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

Storage provides persistent storage for the Klingon node.

func New

func New(cfg *Config) (*Storage, error)

New creates a new Storage instance.

func (*Storage) CleanupOldInboxMessages

func (s *Storage) CleanupOldInboxMessages(olderThan int64) (int64, error)

CleanupOldInboxMessages removes old inbox entries.

func (*Storage) CleanupOldMessages

func (s *Storage) CleanupOldMessages(olderThan int64) (int64, error)

CleanupOldMessages removes old completed/failed messages.

func (*Storage) Close

func (s *Storage) Close() error

Close closes the database connection.

func (*Storage) CountOrders

func (s *Storage) CountOrders(status *OrderStatus) (int, error)

CountOrders returns the count of orders by status.

func (*Storage) CountTrades

func (s *Storage) CountTrades(state *TradeState) (int, error)

CountTrades returns the count of trades by state.

func (*Storage) CreateOrder

func (s *Storage) CreateOrder(order *Order) error

CreateOrder creates a new order in the database.

func (*Storage) CreateSecret

func (s *Storage) CreateSecret(secret *Secret) error

CreateSecret creates a new secret entry in the database. The Secret field may be empty if we don't know the preimage yet.

func (*Storage) CreateSwapLeg

func (s *Storage) CreateSwapLeg(leg *SwapLeg) error

CreateSwapLeg creates a new swap leg in the database.

func (*Storage) CreateTrade

func (s *Storage) CreateTrade(trade *Trade) error

CreateTrade creates a new trade in the database.

func (*Storage) DB

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

DB returns the underlying database connection.

func (*Storage) DeleteOrder

func (s *Storage) DeleteOrder(id string) error

DeleteOrder deletes an order (use with caution).

func (*Storage) DeletePeer

func (s *Storage) DeletePeer(peerID string) error

DeletePeer removes a peer from the database.

func (*Storage) DeleteSecret

func (s *Storage) DeleteSecret(id string) error

DeleteSecret deletes a secret.

func (*Storage) DeleteSecretsByTradeID

func (s *Storage) DeleteSecretsByTradeID(tradeID string) error

DeleteSecretsByTradeID deletes all secrets for a trade.

func (*Storage) DeleteSpentUTXOs

func (s *Storage) DeleteSpentUTXOs(olderThan time.Duration) (int64, error)

DeleteSpentUTXOs removes all spent UTXOs older than the given duration.

func (*Storage) DeleteSwap

func (s *Storage) DeleteSwap(tradeID string) error

DeleteSwap removes a swap from the database. Only use for terminal states or cleanup.

func (*Storage) DeleteSwapLeg

func (s *Storage) DeleteSwapLeg(id string) error

DeleteSwapLeg deletes a swap leg.

func (*Storage) DeleteSwapLegsByTradeID

func (s *Storage) DeleteSwapLegsByTradeID(tradeID string) error

DeleteSwapLegsByTradeID deletes all swap legs for a trade.

func (*Storage) DeleteTrade

func (s *Storage) DeleteTrade(id string) error

DeleteTrade deletes a trade (use with caution - prefer state updates).

func (*Storage) EnqueueMessage

func (s *Storage) EnqueueMessage(msg *OutboxMessage) error

EnqueueMessage adds a message to the outbox for delivery.

func (*Storage) ExpireOldMessages

func (s *Storage) ExpireOldMessages(now int64, bufferSeconds int64) error

ExpireOldMessages marks messages for expired swaps.

func (*Storage) ExpireOldOrders

func (s *Storage) ExpireOldOrders() (int64, error)

ExpireOldOrders marks expired orders as expired.

func (*Storage) GetActiveTrades

func (s *Storage) GetActiveTrades() ([]*Trade, error)

GetActiveTrades returns all trades in non-terminal states.

func (*Storage) GetAllUTXOs

func (s *Storage) GetAllUTXOs(chain string) ([]*WalletUTXO, error)

GetAllUTXOs returns all UTXOs for a chain (including unconfirmed and pending).

func (*Storage) GetBalanceByStatus

func (s *Storage) GetBalanceByStatus(chain string) (confirmed, unconfirmed, pending uint64, err error)

GetBalanceByStatus returns balances grouped by status.

func (*Storage) GetInboxMessage

func (s *Storage) GetInboxMessage(messageID string) (*InboxMessage, error)

GetInboxMessage retrieves an inbox message by ID.

func (*Storage) GetMaxAddressIndex

func (s *Storage) GetMaxAddressIndex(chain string, account, change uint32) (uint32, error)

GetMaxAddressIndex returns the highest address index for a given chain and change type.

func (*Storage) GetMyOrders

func (s *Storage) GetMyOrders() ([]*Order, error)

GetMyOrders returns all orders created by us.

func (*Storage) GetNextAddressIndex

func (s *Storage) GetNextAddressIndex(chain string, account, change uint32) (uint32, error)

GetNextAddressIndex returns the next available address index for a given chain. This is the highest used index + 1, or 0 if no addresses exist.

func (*Storage) GetNextLocalSequence

func (s *Storage) GetNextLocalSequence(tradeID string) (uint64, error)

GetNextLocalSequence gets and increments the local sequence for a trade.

func (*Storage) GetOpenOrders

func (s *Storage) GetOpenOrders(offerChain, requestChain string) ([]*Order, error)

GetOpenOrders returns all open orders for a trading pair.

func (*Storage) GetOrder

func (s *Storage) GetOrder(id string) (*Order, error)

GetOrder retrieves an order by ID.

func (*Storage) GetOutboxMessage

func (s *Storage) GetOutboxMessage(messageID string) (*OutboxMessage, error)

GetOutboxMessage retrieves a single outbox message by message ID.

func (*Storage) GetOutboxStats

func (s *Storage) GetOutboxStats() (map[OutboxStatus]int, error)

GetOutboxStats returns statistics about the outbox.

func (*Storage) GetPeer

func (s *Storage) GetPeer(peerID string) (*PeerRecord, error)

GetPeer retrieves a peer record by ID.

func (*Storage) GetPendingForPeer

func (s *Storage) GetPendingForPeer(peerID string) ([]*OutboxMessage, error)

GetPendingForPeer returns pending messages for a specific peer.

func (*Storage) GetPendingForTrade

func (s *Storage) GetPendingForTrade(tradeID string) ([]*OutboxMessage, error)

GetPendingForTrade returns pending messages for a specific trade.

func (*Storage) GetPendingMessages

func (s *Storage) GetPendingMessages(now int64) ([]*OutboxMessage, error)

GetPendingMessages returns messages due for retry.

func (*Storage) GetPendingSwapLegs

func (s *Storage) GetPendingSwapLegs() ([]*SwapLeg, error)

GetPendingSwapLegs returns all swap legs that need monitoring.

func (*Storage) GetPendingSwaps

func (s *Storage) GetPendingSwaps() ([]*SwapRecord, error)

GetPendingSwaps returns all swaps that are not in a terminal state. These are swaps that need to be recovered on startup.

func (*Storage) GetSecret

func (s *Storage) GetSecret(id string) (*Secret, error)

GetSecret retrieves a secret by ID.

func (*Storage) GetSecretByHash

func (s *Storage) GetSecretByHash(secretHash string) (*Secret, error)

GetSecretByHash retrieves a secret by its hash.

func (*Storage) GetSecretByTradeID

func (s *Storage) GetSecretByTradeID(tradeID string) (*Secret, error)

GetSecretByTradeID retrieves the secret for a trade.

func (*Storage) GetSequences

func (s *Storage) GetSequences(tradeID string) (*MessageSequence, error)

GetSequences returns sequence numbers for a trade.

func (*Storage) GetSpendableUTXOs

func (s *Storage) GetSpendableUTXOs(chain string) ([]*WalletUTXO, error)

GetSpendableUTXOs returns all confirmed, unspent UTXOs for a chain.

func (*Storage) GetSwap

func (s *Storage) GetSwap(tradeID string) (*SwapRecord, error)

GetSwap retrieves a swap by trade ID.

func (*Storage) GetSwapLeg

func (s *Storage) GetSwapLeg(id string) (*SwapLeg, error)

GetSwapLeg retrieves a swap leg by ID.

func (*Storage) GetSwapLegByTradeAndType

func (s *Storage) GetSwapLegByTradeAndType(tradeID string, legType SwapLegType) (*SwapLeg, error)

GetSwapLegByTradeAndType retrieves a specific swap leg by trade ID and leg type.

func (*Storage) GetSwapLegsByTradeID

func (s *Storage) GetSwapLegsByTradeID(tradeID string) ([]*SwapLeg, error)

GetSwapLegsByTradeID retrieves all swap legs for a trade.

func (*Storage) GetSwapsNearingTimeout

func (s *Storage) GetSwapsNearingTimeout(currentHeight uint32, safetyMargin uint32) ([]*SwapRecord, error)

GetSwapsNearingTimeout returns swaps that are close to timeout. safetyMargin is the number of blocks before timeout to start looking.

func (*Storage) GetSwapsPastTimeout

func (s *Storage) GetSwapsPastTimeout(currentHeight uint32) ([]*SwapRecord, error)

GetSwapsPastTimeout returns swaps that have passed their timeout. These are candidates for automatic refund.

func (*Storage) GetTotalBalance

func (s *Storage) GetTotalBalance(chain string) (uint64, error)

GetTotalBalance returns the total balance for a chain (confirmed UTXOs only).

func (*Storage) GetTrade

func (s *Storage) GetTrade(id string) (*Trade, error)

GetTrade retrieves a trade by ID.

func (*Storage) GetTradeByOrderID

func (s *Storage) GetTradeByOrderID(orderID string) (*Trade, error)

GetTradeByOrderID retrieves a trade by its order ID.

func (*Storage) GetUTXOsByAddress

func (s *Storage) GetUTXOsByAddress(address string) ([]*WalletUTXO, error)

GetUTXOsByAddress returns all UTXOs for a specific address.

func (*Storage) GetUnrevealedSecrets

func (s *Storage) GetUnrevealedSecrets() ([]*Secret, error)

GetUnrevealedSecrets returns secrets where we know the preimage but haven't revealed yet. This is used by us (as secret creator) to track which secrets we've generated.

func (*Storage) GetWalletAddress

func (s *Storage) GetWalletAddress(address string) (*WalletAddress, error)

GetWalletAddress retrieves a wallet address by its string representation.

func (*Storage) GetWalletAddressByPath

func (s *Storage) GetWalletAddressByPath(chain string, account, change, index uint32) (*WalletAddress, error)

GetWalletAddressByPath retrieves a wallet address by derivation path.

func (*Storage) GetWalletSyncState

func (s *Storage) GetWalletSyncState(chain string) (*WalletSyncState, error)

GetWalletSyncState retrieves sync state for a chain.

func (*Storage) GetWalletUTXO

func (s *Storage) GetWalletUTXO(txid string, vout uint32) (*WalletUTXO, error)

GetWalletUTXO retrieves a specific UTXO by txid and vout.

func (*Storage) HasReceivedMessage

func (s *Storage) HasReceivedMessage(messageID string) (bool, error)

HasReceivedMessage checks if a message was already received.

func (*Storage) HasSecretPreimage

func (s *Storage) HasSecretPreimage(secretHash string) (bool, error)

HasSecretPreimage checks if we have the preimage for a secret hash.

func (*Storage) ListOrders

func (s *Storage) ListOrders(filter OrderFilter) ([]*Order, error)

ListOrders returns orders matching the filter.

func (*Storage) ListPeers

func (s *Storage) ListPeers(limit int) ([]*PeerRecord, error)

ListPeers returns peers ordered by last seen (most recent first).

func (*Storage) ListRecentPeers

func (s *Storage) ListRecentPeers(since time.Duration, limit int) ([]*PeerRecord, error)

ListRecentPeers returns peers seen within the given duration.

func (*Storage) ListSecretsByTrade

func (s *Storage) ListSecretsByTrade(tradeID string) ([]*Secret, error)

ListSecretsByTrade returns all secrets for a trade.

func (*Storage) ListSwapLegs

func (s *Storage) ListSwapLegs(filter SwapLegFilter) ([]*SwapLeg, error)

ListSwapLegs returns swap legs matching the filter.

func (*Storage) ListSwaps

func (s *Storage) ListSwaps(limit int, includeCompleted bool) ([]*SwapRecord, error)

ListSwaps returns all swaps with optional filtering.

func (*Storage) ListTrades

func (s *Storage) ListTrades(filter TradeFilter) ([]*Trade, error)

ListTrades returns trades matching the filter.

func (*Storage) ListWalletAddresses

func (s *Storage) ListWalletAddresses(chain string) ([]*WalletAddress, error)

ListWalletAddresses returns all addresses for a chain.

func (*Storage) MarkAckSent

func (s *Storage) MarkAckSent(messageID string) error

MarkAckSent marks that an ACK was sent for this message.

func (*Storage) MarkMessageAcked

func (s *Storage) MarkMessageAcked(messageID string) error

MarkMessageAcked marks a message as successfully delivered.

func (*Storage) MarkMessageExpired

func (s *Storage) MarkMessageExpired(messageID string) error

MarkMessageExpired marks a message as expired (swap timed out).

func (*Storage) MarkMessageFailed

func (s *Storage) MarkMessageFailed(messageID string, errorMsg string) error

MarkMessageFailed marks a message as permanently failed.

func (*Storage) MarkMessageProcessed

func (s *Storage) MarkMessageProcessed(messageID string) error

MarkMessageProcessed marks an inbox message as processed.

func (*Storage) MarkMessageSent

func (s *Storage) MarkMessageSent(messageID string) error

MarkMessageSent marks a message as sent (awaiting ACK).

func (*Storage) MarkUTXOPendingSpend

func (s *Storage) MarkUTXOPendingSpend(txid string, vout uint32, spendTxID string) error

MarkUTXOPendingSpend marks a UTXO as pending spend (used in a transaction).

func (*Storage) MarkUTXOSpent

func (s *Storage) MarkUTXOSpent(txid string, vout uint32, spendTxID string) error

MarkUTXOSpent marks a UTXO as spent (confirmed in a block).

func (*Storage) PeerCount

func (s *Storage) PeerCount() (int, error)

PeerCount returns the total number of known peers.

func (*Storage) RecordReceivedMessage

func (s *Storage) RecordReceivedMessage(msg *InboxMessage) error

RecordReceivedMessage records a received message for deduplication.

func (*Storage) RevealSecret

func (s *Storage) RevealSecret(id string, preimage string) error

RevealSecret updates the secret preimage when it's discovered.

func (*Storage) RevealSecretByHash

func (s *Storage) RevealSecretByHash(secretHash string, preimage string) error

RevealSecretByHash updates the secret preimage when discovered via hash lookup.

func (*Storage) RevertUTXOPendingSpend

func (s *Storage) RevertUTXOPendingSpend(txid string, vout uint32) error

RevertUTXOPendingSpend reverts a pending spend back to confirmed (if tx failed).

func (*Storage) SaveOrder

func (s *Storage) SaveOrder(order *Order) error

SaveOrder saves an order (insert or update). This is used for syncing orders from other peers.

func (*Storage) SavePeer

func (s *Storage) SavePeer(peer *PeerRecord) error

SavePeer saves or updates a peer record.

func (*Storage) SaveSwap

func (s *Storage) SaveSwap(swap *SwapRecord) error

SaveSwap saves or updates a swap record. Uses UPSERT pattern - creates if not exists, updates if exists.

func (*Storage) SaveWalletAddress

func (s *Storage) SaveWalletAddress(addr *WalletAddress) error

SaveWalletAddress saves or updates a wallet address.

func (*Storage) SaveWalletSyncState

func (s *Storage) SaveWalletSyncState(state *WalletSyncState) error

SaveWalletSyncState saves or updates sync state for a chain.

func (*Storage) SaveWalletUTXO

func (s *Storage) SaveWalletUTXO(utxo *WalletUTXO) error

SaveWalletUTXO saves or updates a UTXO.

func (*Storage) ScheduleRetry

func (s *Storage) ScheduleRetry(messageID string, nextRetryAt int64) error

ScheduleRetry schedules a message for retry at the given time.

func (*Storage) SwapCount

func (s *Storage) SwapCount() (pending, completed int, err error)

SwapCount returns count of swaps by state.

func (*Storage) UpdateOrderStatus

func (s *Storage) UpdateOrderStatus(id string, status OrderStatus) error

UpdateOrderStatus updates the status of an order.

func (*Storage) UpdatePeerConnected

func (s *Storage) UpdatePeerConnected(peerID string) error

UpdatePeerConnected updates the last_connected time and increments connection count.

func (*Storage) UpdatePeerSeen

func (s *Storage) UpdatePeerSeen(peerID string) error

UpdatePeerSeen updates the last_seen time.

func (*Storage) UpdateRemoteSequence

func (s *Storage) UpdateRemoteSequence(tradeID string, seq uint64) error

UpdateRemoteSequence updates the last received sequence number.

func (*Storage) UpdateSwapFunding

func (s *Storage) UpdateSwapFunding(tradeID string, isLocal bool, txid string, vout uint32) error

UpdateSwapFunding updates funding transaction info for a swap.

func (*Storage) UpdateSwapLegConfirmations

func (s *Storage) UpdateSwapLegConfirmations(id string, confirms uint32) error

UpdateSwapLegConfirmations updates the funding confirmation count.

func (*Storage) UpdateSwapLegFunding

func (s *Storage) UpdateSwapLegFunding(id string, txID string, vout uint32, address string) error

UpdateSwapLegFunding updates the funding information for a swap leg.

func (*Storage) UpdateSwapLegMethodData

func (s *Storage) UpdateSwapLegMethodData(id string, methodData json.RawMessage) error

UpdateSwapLegMethodData updates the method-specific data for a swap leg.

func (*Storage) UpdateSwapLegRedeemed

func (s *Storage) UpdateSwapLegRedeemed(id string, redeemTxID string) error

UpdateSwapLegRedeemed marks a swap leg as redeemed.

func (*Storage) UpdateSwapLegRefunded

func (s *Storage) UpdateSwapLegRefunded(id string, refundTxID string) error

UpdateSwapLegRefunded marks a swap leg as refunded.

func (*Storage) UpdateSwapLegState

func (s *Storage) UpdateSwapLegState(id string, state SwapLegState) error

UpdateSwapLegState updates the state of a swap leg.

func (*Storage) UpdateSwapMethodData

func (s *Storage) UpdateSwapMethodData(tradeID string, methodData json.RawMessage) error

UpdateSwapMethodData updates the method_data JSON blob for a swap.

func (*Storage) UpdateSwapState

func (s *Storage) UpdateSwapState(tradeID string, state SwapState) error

UpdateSwapState updates the state of a swap.

func (*Storage) UpdateTradeFailure

func (s *Storage) UpdateTradeFailure(id string, reason string) error

UpdateTradeFailure marks a trade as failed with a reason.

func (*Storage) UpdateTradePubKey

func (s *Storage) UpdateTradePubKey(id string, isMaker bool, pubkey string) error

UpdateTradePubKey updates a maker or taker pubkey for a trade.

func (*Storage) UpdateTradeState

func (s *Storage) UpdateTradeState(id string, state TradeState) error

UpdateTradeState updates the state of a trade.

func (*Storage) UpdateUTXOConfirmations

func (s *Storage) UpdateUTXOConfirmations(txid string, vout uint32, confirmations int64, blockHeight int64, blockHash string) error

UpdateUTXOConfirmations updates confirmation count for a UTXO.

type SwapLeg

type SwapLeg struct {
	ID      string
	TradeID string

	// Leg identification
	LegType SwapLegType
	Chain   string
	Amount  uint64

	// Our role on this leg
	OurRole SwapLegRole

	// Leg state
	State SwapLegState

	// Funding transaction
	FundingTxID     string
	FundingVout     uint32
	FundingConfirms uint32
	FundingAddress  string

	// Redeem/Refund transactions
	RedeemTxID string
	RefundTxID string

	// Timeout
	TimeoutHeight    uint32
	TimeoutTimestamp int64

	// Method-specific data (JSON blob)
	MethodData json.RawMessage

	// Timing
	CreatedAt time.Time
	UpdatedAt *time.Time
}

SwapLeg represents a swap leg in the database.

type SwapLegFilter

type SwapLegFilter struct {
	TradeID string
	Chain   string
	State   *SwapLegState
	OurRole *SwapLegRole
	LegType *SwapLegType
	Limit   int
	Offset  int
}

SwapLegFilter defines filters for listing swap legs.

type SwapLegRole

type SwapLegRole string

SwapLegRole indicates our role on this specific leg.

const (
	SwapLegRoleSender   SwapLegRole = "sender"   // We send funds on this leg
	SwapLegRoleReceiver SwapLegRole = "receiver" // We receive funds on this leg
)

type SwapLegState

type SwapLegState string

SwapLegState represents the current state of a swap leg.

const (
	SwapLegStateInit     SwapLegState = "init"     // Leg initialized
	SwapLegStatePending  SwapLegState = "pending"  // Waiting for funding
	SwapLegStateFunding  SwapLegState = "funding"  // Funding tx broadcast
	SwapLegStateFunded   SwapLegState = "funded"   // Funding confirmed
	SwapLegStateRedeemed SwapLegState = "redeemed" // Successfully redeemed
	SwapLegStateRefunded SwapLegState = "refunded" // Refunded after timeout
	SwapLegStateFailed   SwapLegState = "failed"   // Failed
)

type SwapLegType

type SwapLegType string

SwapLegType identifies which side of the swap.

const (
	SwapLegTypeOffer   SwapLegType = "offer"   // The offer chain leg
	SwapLegTypeRequest SwapLegType = "request" // The request chain leg
)

type SwapRecord

type SwapRecord struct {
	// Identity
	TradeID string `json:"trade_id"`
	OrderID string `json:"order_id"`

	// Participants
	MakerPeerID string `json:"maker_peer_id"`
	TakerPeerID string `json:"taker_peer_id"`

	// Our role in this swap
	OurRole string `json:"our_role"` // "maker" or "taker"
	IsMaker bool   `json:"is_maker"`

	// Swap details
	OfferChain    string `json:"offer_chain"`
	OfferAmount   uint64 `json:"offer_amount"`
	RequestChain  string `json:"request_chain"`
	RequestAmount uint64 `json:"request_amount"`

	// State
	State SwapState `json:"state"`

	// MuSig2 data (JSON blob - contains keys, nonces, etc.)
	// This is the critical data for recovery
	MethodData json.RawMessage `json:"method_data"`

	// Funding info
	LocalFundingTxID  string `json:"local_funding_txid,omitempty"`
	LocalFundingVout  uint32 `json:"local_funding_vout"`
	RemoteFundingTxID string `json:"remote_funding_txid,omitempty"`
	RemoteFundingVout uint32 `json:"remote_funding_vout"`

	// Timeout tracking (separate for each chain)
	TimeoutHeight        uint32 `json:"timeout_height"`         // Offer chain timeout
	RequestTimeoutHeight uint32 `json:"request_timeout_height"` // Request chain timeout
	TimeoutTimestamp     int64  `json:"timeout_timestamp"`

	// Result
	RedeemTxID    string `json:"redeem_txid,omitempty"`
	RefundTxID    string `json:"refund_txid,omitempty"`
	FailureReason string `json:"failure_reason,omitempty"`

	// Timing
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	CompletedAt time.Time `json:"completed_at,omitempty"`
}

SwapRecord represents a persisted swap in the database. This contains all data needed to recover a swap after restart.

type SwapState

type SwapState string

SwapState represents the current state of a swap.

const (
	SwapStateInit      SwapState = "init"
	SwapStateFunding   SwapState = "funding"
	SwapStateFunded    SwapState = "funded"
	SwapStateSigning   SwapState = "signing"
	SwapStateRedeemed  SwapState = "redeemed"
	SwapStateRefunded  SwapState = "refunded"
	SwapStateFailed    SwapState = "failed"
	SwapStateCancelled SwapState = "cancelled"
)

type Trade

type Trade struct {
	ID          string
	OrderID     string
	MakerPeerID string
	TakerPeerID string
	MakerPubKey string // Hex-encoded compressed pubkey
	TakerPubKey string // Hex-encoded compressed pubkey
	OurRole     TradeRole
	Method      string // musig2, htlc_bitcoin, htlc_evm, etc.
	State       TradeState

	// Actual amounts for this trade
	OfferChain    string
	OfferAmount   uint64
	RequestChain  string
	RequestAmount uint64

	// Timing
	CreatedAt   time.Time
	UpdatedAt   *time.Time
	CompletedAt *time.Time

	// Failure tracking
	FailureReason string
}

Trade represents a trade in the database.

type TradeFilter

type TradeFilter struct {
	State       *TradeState
	OurRole     *TradeRole
	Method      string
	MakerPeerID string
	TakerPeerID string
	Limit       int
	Offset      int
}

TradeFilter defines filters for listing trades.

type TradeRole

type TradeRole string

TradeRole indicates our role in the trade.

const (
	TradeRoleMaker TradeRole = "maker" // We created the order
	TradeRoleTaker TradeRole = "taker" // We took the order
)

type TradeState

type TradeState string

TradeState represents the current state of a trade.

const (
	TradeStateInit     TradeState = "init"     // Trade initiated
	TradeStateAccepted TradeState = "accepted" // Both parties agreed
	TradeStateFunding  TradeState = "funding"  // Funding in progress
	TradeStateFunded   TradeState = "funded"   // Both sides funded
	TradeStateRedeemed TradeState = "redeemed" // Successfully completed
	TradeStateRefunded TradeState = "refunded" // Refunded due to timeout
	TradeStateFailed   TradeState = "failed"   // Failed for other reasons
	TradeStateAborted  TradeState = "aborted"  // Aborted before funding
)

type UTXOStatus

type UTXOStatus string

UTXOStatus represents the status of a UTXO.

const (
	UTXOStatusUnconfirmed  UTXOStatus = "unconfirmed"
	UTXOStatusConfirmed    UTXOStatus = "confirmed"
	UTXOStatusPendingSpend UTXOStatus = "pending_spend"
	UTXOStatusSpent        UTXOStatus = "spent"
)

type WalletAddress

type WalletAddress struct {
	Address      string `json:"address"`
	Chain        string `json:"chain"`
	Account      uint32 `json:"account"`
	Change       uint32 `json:"change"` // 0=external, 1=change
	AddressIndex uint32 `json:"address_index"`
	AddressType  string `json:"address_type"` // p2wpkh, p2tr, p2pkh

	// Usage stats
	TxCount       int64 `json:"tx_count"`
	TotalReceived int64 `json:"total_received"`
	TotalSent     int64 `json:"total_sent"`

	// Timestamps
	CreatedAt   int64 `json:"created_at"`
	FirstSeenAt int64 `json:"first_seen_at,omitempty"`
	LastSeenAt  int64 `json:"last_seen_at,omitempty"`
}

WalletAddress represents a derived wallet address with its derivation path.

type WalletSyncState

type WalletSyncState struct {
	Chain             string `json:"chain"`
	LastExternalIndex uint32 `json:"last_external_index"`
	LastChangeIndex   uint32 `json:"last_change_index"`
	GapLimit          uint32 `json:"gap_limit"`
	LastSyncAt        int64  `json:"last_sync_at,omitempty"`
	LastBlockHeight   int64  `json:"last_block_height,omitempty"`
	SyncStatus        string `json:"sync_status"`
}

WalletSyncState represents the sync state for a chain.

type WalletUTXO

type WalletUTXO struct {
	TxID string `json:"txid"`
	Vout uint32 `json:"vout"`

	// Amount in smallest units
	Amount uint64 `json:"amount"`

	// Address info
	Address     string `json:"address"`
	Chain       string `json:"chain"`
	AddressType string `json:"address_type"`

	// Derivation path (for key derivation during signing)
	Account      uint32 `json:"account"`
	Change       uint32 `json:"change"`
	AddressIndex uint32 `json:"address_index"`

	// Script
	ScriptPubKey string `json:"script_pubkey,omitempty"`

	// Status
	Status        UTXOStatus `json:"status"`
	BlockHeight   int64      `json:"block_height,omitempty"`
	BlockHash     string     `json:"block_hash,omitempty"`
	Confirmations int64      `json:"confirmations"`

	// Spending info
	SpentTxID string `json:"spent_txid,omitempty"`
	SpentAt   int64  `json:"spent_at,omitempty"`

	// Timestamps
	CreatedAt int64 `json:"created_at"`
	UpdatedAt int64 `json:"updated_at"`
}

WalletUTXO represents a UTXO with its derivation path for signing.

Jump to

Keyboard shortcuts

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