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 ¶
- Variables
- type Config
- type InboxMessage
- type MessageSequence
- type Order
- type OrderFilter
- type OrderStatus
- type OutboxMessage
- type OutboxStatus
- type PeerRecord
- type Secret
- type SecretCreator
- type Storage
- func (s *Storage) CleanupOldInboxMessages(olderThan int64) (int64, error)
- func (s *Storage) CleanupOldMessages(olderThan int64) (int64, error)
- func (s *Storage) Close() error
- func (s *Storage) CountOrders(status *OrderStatus) (int, error)
- func (s *Storage) CountTrades(state *TradeState) (int, error)
- func (s *Storage) CreateOrder(order *Order) error
- func (s *Storage) CreateSecret(secret *Secret) error
- func (s *Storage) CreateSwapLeg(leg *SwapLeg) error
- func (s *Storage) CreateTrade(trade *Trade) error
- func (s *Storage) DB() *sql.DB
- func (s *Storage) DeleteOrder(id string) error
- func (s *Storage) DeletePeer(peerID string) error
- func (s *Storage) DeleteSecret(id string) error
- func (s *Storage) DeleteSecretsByTradeID(tradeID string) error
- func (s *Storage) DeleteSpentUTXOs(olderThan time.Duration) (int64, error)
- func (s *Storage) DeleteSwap(tradeID string) error
- func (s *Storage) DeleteSwapLeg(id string) error
- func (s *Storage) DeleteSwapLegsByTradeID(tradeID string) error
- func (s *Storage) DeleteTrade(id string) error
- func (s *Storage) EnqueueMessage(msg *OutboxMessage) error
- func (s *Storage) ExpireOldMessages(now int64, bufferSeconds int64) error
- func (s *Storage) ExpireOldOrders() (int64, error)
- func (s *Storage) GetActiveTrades() ([]*Trade, error)
- func (s *Storage) GetAllUTXOs(chain string) ([]*WalletUTXO, error)
- func (s *Storage) GetBalanceByStatus(chain string) (confirmed, unconfirmed, pending uint64, err error)
- func (s *Storage) GetInboxMessage(messageID string) (*InboxMessage, error)
- func (s *Storage) GetMaxAddressIndex(chain string, account, change uint32) (uint32, error)
- func (s *Storage) GetMyOrders() ([]*Order, error)
- func (s *Storage) GetNextAddressIndex(chain string, account, change uint32) (uint32, error)
- func (s *Storage) GetNextLocalSequence(tradeID string) (uint64, error)
- func (s *Storage) GetOpenOrders(offerChain, requestChain string) ([]*Order, error)
- func (s *Storage) GetOrder(id string) (*Order, error)
- func (s *Storage) GetOutboxMessage(messageID string) (*OutboxMessage, error)
- func (s *Storage) GetOutboxStats() (map[OutboxStatus]int, error)
- func (s *Storage) GetPeer(peerID string) (*PeerRecord, error)
- func (s *Storage) GetPendingForPeer(peerID string) ([]*OutboxMessage, error)
- func (s *Storage) GetPendingForTrade(tradeID string) ([]*OutboxMessage, error)
- func (s *Storage) GetPendingMessages(now int64) ([]*OutboxMessage, error)
- func (s *Storage) GetPendingSwapLegs() ([]*SwapLeg, error)
- func (s *Storage) GetPendingSwaps() ([]*SwapRecord, error)
- func (s *Storage) GetSecret(id string) (*Secret, error)
- func (s *Storage) GetSecretByHash(secretHash string) (*Secret, error)
- func (s *Storage) GetSecretByTradeID(tradeID string) (*Secret, error)
- func (s *Storage) GetSequences(tradeID string) (*MessageSequence, error)
- func (s *Storage) GetSpendableUTXOs(chain string) ([]*WalletUTXO, error)
- func (s *Storage) GetSwap(tradeID string) (*SwapRecord, error)
- func (s *Storage) GetSwapLeg(id string) (*SwapLeg, error)
- func (s *Storage) GetSwapLegByTradeAndType(tradeID string, legType SwapLegType) (*SwapLeg, error)
- func (s *Storage) GetSwapLegsByTradeID(tradeID string) ([]*SwapLeg, error)
- func (s *Storage) GetSwapsNearingTimeout(currentHeight uint32, safetyMargin uint32) ([]*SwapRecord, error)
- func (s *Storage) GetSwapsPastTimeout(currentHeight uint32) ([]*SwapRecord, error)
- func (s *Storage) GetTotalBalance(chain string) (uint64, error)
- func (s *Storage) GetTrade(id string) (*Trade, error)
- func (s *Storage) GetTradeByOrderID(orderID string) (*Trade, error)
- func (s *Storage) GetUTXOsByAddress(address string) ([]*WalletUTXO, error)
- func (s *Storage) GetUnrevealedSecrets() ([]*Secret, error)
- func (s *Storage) GetWalletAddress(address string) (*WalletAddress, error)
- func (s *Storage) GetWalletAddressByPath(chain string, account, change, index uint32) (*WalletAddress, error)
- func (s *Storage) GetWalletSyncState(chain string) (*WalletSyncState, error)
- func (s *Storage) GetWalletUTXO(txid string, vout uint32) (*WalletUTXO, error)
- func (s *Storage) HasReceivedMessage(messageID string) (bool, error)
- func (s *Storage) HasSecretPreimage(secretHash string) (bool, error)
- func (s *Storage) ListOrders(filter OrderFilter) ([]*Order, error)
- func (s *Storage) ListPeers(limit int) ([]*PeerRecord, error)
- func (s *Storage) ListRecentPeers(since time.Duration, limit int) ([]*PeerRecord, error)
- func (s *Storage) ListSecretsByTrade(tradeID string) ([]*Secret, error)
- func (s *Storage) ListSwapLegs(filter SwapLegFilter) ([]*SwapLeg, error)
- func (s *Storage) ListSwaps(limit int, includeCompleted bool) ([]*SwapRecord, error)
- func (s *Storage) ListTrades(filter TradeFilter) ([]*Trade, error)
- func (s *Storage) ListWalletAddresses(chain string) ([]*WalletAddress, error)
- func (s *Storage) MarkAckSent(messageID string) error
- func (s *Storage) MarkMessageAcked(messageID string) error
- func (s *Storage) MarkMessageExpired(messageID string) error
- func (s *Storage) MarkMessageFailed(messageID string, errorMsg string) error
- func (s *Storage) MarkMessageProcessed(messageID string) error
- func (s *Storage) MarkMessageSent(messageID string) error
- func (s *Storage) MarkUTXOPendingSpend(txid string, vout uint32, spendTxID string) error
- func (s *Storage) MarkUTXOSpent(txid string, vout uint32, spendTxID string) error
- func (s *Storage) PeerCount() (int, error)
- func (s *Storage) RecordReceivedMessage(msg *InboxMessage) error
- func (s *Storage) RevealSecret(id string, preimage string) error
- func (s *Storage) RevealSecretByHash(secretHash string, preimage string) error
- func (s *Storage) RevertUTXOPendingSpend(txid string, vout uint32) error
- func (s *Storage) SaveOrder(order *Order) error
- func (s *Storage) SavePeer(peer *PeerRecord) error
- func (s *Storage) SaveSwap(swap *SwapRecord) error
- func (s *Storage) SaveWalletAddress(addr *WalletAddress) error
- func (s *Storage) SaveWalletSyncState(state *WalletSyncState) error
- func (s *Storage) SaveWalletUTXO(utxo *WalletUTXO) error
- func (s *Storage) ScheduleRetry(messageID string, nextRetryAt int64) error
- func (s *Storage) SwapCount() (pending, completed int, err error)
- func (s *Storage) UpdateOrderStatus(id string, status OrderStatus) error
- func (s *Storage) UpdatePeerConnected(peerID string) error
- func (s *Storage) UpdatePeerSeen(peerID string) error
- func (s *Storage) UpdateRemoteSequence(tradeID string, seq uint64) error
- func (s *Storage) UpdateSwapFunding(tradeID string, isLocal bool, txid string, vout uint32) error
- func (s *Storage) UpdateSwapLegConfirmations(id string, confirms uint32) error
- func (s *Storage) UpdateSwapLegFunding(id string, txID string, vout uint32, address string) error
- func (s *Storage) UpdateSwapLegMethodData(id string, methodData json.RawMessage) error
- func (s *Storage) UpdateSwapLegRedeemed(id string, redeemTxID string) error
- func (s *Storage) UpdateSwapLegRefunded(id string, refundTxID string) error
- func (s *Storage) UpdateSwapLegState(id string, state SwapLegState) error
- func (s *Storage) UpdateSwapMethodData(tradeID string, methodData json.RawMessage) error
- func (s *Storage) UpdateSwapState(tradeID string, state SwapState) error
- func (s *Storage) UpdateTradeFailure(id string, reason string) error
- func (s *Storage) UpdateTradePubKey(id string, isMaker bool, pubkey string) error
- func (s *Storage) UpdateTradeState(id string, state TradeState) error
- func (s *Storage) UpdateUTXOConfirmations(txid string, vout uint32, confirmations int64, blockHeight int64, ...) error
- type SwapLeg
- type SwapLegFilter
- type SwapLegRole
- type SwapLegState
- type SwapLegType
- type SwapRecord
- type SwapState
- type Trade
- type TradeFilter
- type TradeRole
- type TradeState
- type UTXOStatus
- type WalletAddress
- type WalletSyncState
- type WalletUTXO
Constants ¶
This section is empty.
Variables ¶
var ( ErrOrderNotFound = errors.New("order not found") ErrOrderExpired = errors.New("order expired") )
Order errors
var ( ErrSecretNotFound = errors.New("secret not found") ErrSecretAlreadyExists = errors.New("secret already exists for this trade and hash") )
Secret errors
var ( ErrSwapNotFound = errors.New("swap not found") ErrSwapExists = errors.New("swap already exists") ErrInvalidSwapState = errors.New("invalid swap state") )
Swap persistence errors
var (
ErrSwapLegNotFound = errors.New("swap leg not found")
)
Swap leg errors
var (
ErrTradeNotFound = errors.New("trade not found")
)
Trade errors
Functions ¶
This section is empty.
Types ¶
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 (*Storage) CleanupOldInboxMessages ¶
CleanupOldInboxMessages removes old inbox entries.
func (*Storage) CleanupOldMessages ¶
CleanupOldMessages removes old completed/failed messages.
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 ¶
CreateOrder creates a new order in the database.
func (*Storage) CreateSecret ¶
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 ¶
CreateSwapLeg creates a new swap leg in the database.
func (*Storage) CreateTrade ¶
CreateTrade creates a new trade in the database.
func (*Storage) DeleteOrder ¶
DeleteOrder deletes an order (use with caution).
func (*Storage) DeletePeer ¶
DeletePeer removes a peer from the database.
func (*Storage) DeleteSecret ¶
DeleteSecret deletes a secret.
func (*Storage) DeleteSecretsByTradeID ¶
DeleteSecretsByTradeID deletes all secrets for a trade.
func (*Storage) DeleteSpentUTXOs ¶
DeleteSpentUTXOs removes all spent UTXOs older than the given duration.
func (*Storage) DeleteSwap ¶
DeleteSwap removes a swap from the database. Only use for terminal states or cleanup.
func (*Storage) DeleteSwapLeg ¶
DeleteSwapLeg deletes a swap leg.
func (*Storage) DeleteSwapLegsByTradeID ¶
DeleteSwapLegsByTradeID deletes all swap legs for a trade.
func (*Storage) DeleteTrade ¶
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 ¶
ExpireOldMessages marks messages for expired swaps.
func (*Storage) ExpireOldOrders ¶
ExpireOldOrders marks expired orders as expired.
func (*Storage) GetActiveTrades ¶
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 ¶
GetMaxAddressIndex returns the highest address index for a given chain and change type.
func (*Storage) GetMyOrders ¶
GetMyOrders returns all orders created by us.
func (*Storage) GetNextAddressIndex ¶
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 ¶
GetNextLocalSequence gets and increments the local sequence for a trade.
func (*Storage) GetOpenOrders ¶
GetOpenOrders returns all open orders for a trading pair.
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 ¶
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) GetSecretByHash ¶
GetSecretByHash retrieves a secret by its hash.
func (*Storage) GetSecretByTradeID ¶
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 ¶
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 ¶
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 ¶
GetTotalBalance returns the total balance for a chain (confirmed UTXOs only).
func (*Storage) GetTradeByOrderID ¶
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 ¶
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 ¶
HasReceivedMessage checks if a message was already received.
func (*Storage) HasSecretPreimage ¶
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 ¶
ListRecentPeers returns peers seen within the given duration.
func (*Storage) ListSecretsByTrade ¶
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 ¶
MarkAckSent marks that an ACK was sent for this message.
func (*Storage) MarkMessageAcked ¶
MarkMessageAcked marks a message as successfully delivered.
func (*Storage) MarkMessageExpired ¶
MarkMessageExpired marks a message as expired (swap timed out).
func (*Storage) MarkMessageFailed ¶
MarkMessageFailed marks a message as permanently failed.
func (*Storage) MarkMessageProcessed ¶
MarkMessageProcessed marks an inbox message as processed.
func (*Storage) MarkMessageSent ¶
MarkMessageSent marks a message as sent (awaiting ACK).
func (*Storage) MarkUTXOPendingSpend ¶
MarkUTXOPendingSpend marks a UTXO as pending spend (used in a transaction).
func (*Storage) MarkUTXOSpent ¶
MarkUTXOSpent marks a UTXO as spent (confirmed in a block).
func (*Storage) RecordReceivedMessage ¶
func (s *Storage) RecordReceivedMessage(msg *InboxMessage) error
RecordReceivedMessage records a received message for deduplication.
func (*Storage) RevealSecret ¶
RevealSecret updates the secret preimage when it's discovered.
func (*Storage) RevealSecretByHash ¶
RevealSecretByHash updates the secret preimage when discovered via hash lookup.
func (*Storage) RevertUTXOPendingSpend ¶
RevertUTXOPendingSpend reverts a pending spend back to confirmed (if tx failed).
func (*Storage) SaveOrder ¶
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 ¶
ScheduleRetry schedules a message for retry at the given time.
func (*Storage) UpdateOrderStatus ¶
func (s *Storage) UpdateOrderStatus(id string, status OrderStatus) error
UpdateOrderStatus updates the status of an order.
func (*Storage) UpdatePeerConnected ¶
UpdatePeerConnected updates the last_connected time and increments connection count.
func (*Storage) UpdatePeerSeen ¶
UpdatePeerSeen updates the last_seen time.
func (*Storage) UpdateRemoteSequence ¶
UpdateRemoteSequence updates the last received sequence number.
func (*Storage) UpdateSwapFunding ¶
UpdateSwapFunding updates funding transaction info for a swap.
func (*Storage) UpdateSwapLegConfirmations ¶
UpdateSwapLegConfirmations updates the funding confirmation count.
func (*Storage) UpdateSwapLegFunding ¶
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 ¶
UpdateSwapLegRedeemed marks a swap leg as redeemed.
func (*Storage) UpdateSwapLegRefunded ¶
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 ¶
UpdateSwapState updates the state of a swap.
func (*Storage) UpdateTradeFailure ¶
UpdateTradeFailure marks a trade as failed with a reason.
func (*Storage) UpdateTradePubKey ¶
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.
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 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.