pg

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2023 License: BlueOak-1.0.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DBVersion added in v0.2.0

func DBVersion(db *sql.DB) (ver uint32, err error)

DBVersion retrieves the database version from the meta table.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type Archiver

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

Archiver must implement server/db.DEXArchivist. So far: OrderArchiver, AccountArchiver.

func NewArchiver

func NewArchiver(ctx context.Context, cfg *Config) (*Archiver, error)

NewArchiver constructs a new Archiver. All tables are created, including tables for markets that may have been added since last startup. Use Close when done with the Archiver.

func NewArchiverForRead added in v0.4.0

func NewArchiverForRead(ctx context.Context, cfg *Config) (*Archiver, error)

NewArchiverForRead constructs a new Archiver without creating or modifying any data structures. This should be used for read-only applications. Use Close when done with the Archiver.

func (*Archiver) Account

func (a *Archiver) Account(aid account.AccountID, bondExpiry time.Time) (acct *account.Account, bonds []*db.Bond, legacy, legacyPaid bool)

Account retrieves the account pubkey, active bonds, and if the account has a legacy registration fee address and transaction recorded. If the account does not exist or there is in an error retrieving any data, a nil *account.Account is returned.

func (*Archiver) AccountInfo

func (a *Archiver) AccountInfo(aid account.AccountID) (*db.Account, error)

AccountInfo returns data for an account.

func (*Archiver) AccountRegAddr

func (a *Archiver) AccountRegAddr(aid account.AccountID) (string, uint32, error)

AccountRegAddr retrieves the registration fee address and the corresponding asset ID created for the the specified account.

func (*Archiver) Accounts

func (a *Archiver) Accounts() ([]*db.Account, error)

Accounts returns data for all accounts.

func (*Archiver) ActiveOrderCoins

func (a *Archiver) ActiveOrderCoins(base, quote uint32) (baseCoins, quoteCoins map[order.OrderID][]order.CoinID, err error)

ActiveOrderCoins retrieves a CoinID slice for each active order.

func (*Archiver) ActiveSwaps added in v0.2.0

func (a *Archiver) ActiveSwaps() ([]*db.SwapDataFull, error)

ActiveSwaps loads the full details for all active swaps across all markets.

func (*Archiver) ActiveUserOrderStatuses

func (a *Archiver) ActiveUserOrderStatuses(aid account.AccountID) ([]*db.OrderStatus, error)

ActiveUserOrderStatuses retrieves the statuses and filled amounts of all active orders for a user across all markets.

func (*Archiver) AddBond added in v0.6.0

func (a *Archiver) AddBond(aid account.AccountID, bond *db.Bond) error

AddBond stores a new Bond for an existing account.

func (*Archiver) AllActiveUserMatches

func (a *Archiver) AllActiveUserMatches(aid account.AccountID) ([]*db.MatchData, error)

AllActiveUserMatches retrieves a MatchData slice for active matches in all markets involving the given user. Swaps that have successfully completed or failed are not included.

func (*Archiver) BookOrder

func (a *Archiver) BookOrder(lo *order.LimitOrder) error

BookOrder updates the given LimitOrder with booked status.

func (*Archiver) BookOrders

func (a *Archiver) BookOrders(base, quote uint32) ([]*order.LimitOrder, error)

BookOrders retrieves all booked orders (with order status booked) for the specified market. This will be used to repopulate a market's book on construction of the market.

func (*Archiver) CancelOrder

func (a *Archiver) CancelOrder(lo *order.LimitOrder) error

CancelOrder updates a LimitOrder with canceled status. If the order does not exist in the Archiver, CancelOrder returns ErrUnknownOrder. To store a new limit order with canceled status, use StoreOrder.

func (*Archiver) Close

func (a *Archiver) Close() error

Close closes the underlying DB connection.

func (*Archiver) CompletedAndAtFaultMatchStats

func (a *Archiver) CompletedAndAtFaultMatchStats(aid account.AccountID, lastN int) ([]*db.MatchOutcome, error)

CompletedAndAtFaultMatchStats retrieves the outcomes of matches that were (1) successfully completed by the specified user, or (2) failed with the user being the at-fault party. Note that the MakerRedeemed match status may be either a success or failure depending on if the user was the maker or taker in the swap, respectively, and the MatchOutcome.Fail flag disambiguates this.

func (*Archiver) CompletedUserOrders

func (a *Archiver) CompletedUserOrders(aid account.AccountID, N int) (oids []order.OrderID, compTimes []int64, err error)

CompletedUserOrders retrieves the N most recently completed orders for a user across all markets.

func (*Archiver) CreateAccount

func (a *Archiver) CreateAccount(acct *account.Account, assetID uint32, regAddr string) error

CreateAccount creates an entry for a new account in the accounts table. DEPRECATED: See CreateAccountWithBond. (V0PURGE)

func (*Archiver) CreateAccountWithBond added in v0.6.0

func (a *Archiver) CreateAccountWithBond(acct *account.Account, bond *db.Bond) error

CreateAccountWithBond creates a new account with a fidelity bond.

func (*Archiver) DeleteBond added in v0.6.0

func (a *Archiver) DeleteBond(assetID uint32, coinID []byte) error

func (*Archiver) EpochOrders added in v0.2.0

func (a *Archiver) EpochOrders(base, quote uint32) ([]order.Order, error)

EpochOrders retrieves all epoch orders for the specified market returns them as a slice of order.Order.

func (*Archiver) ExecuteOrder

func (a *Archiver) ExecuteOrder(ord order.Order) error

ExecuteOrder updates the given Order with executed status.

func (*Archiver) ExecutedCancelsForUser

func (a *Archiver) ExecutedCancelsForUser(aid account.AccountID, N int) (ords []*db.CancelRecord, err error)

ExecutedCancelsForUser retrieves up to N executed cancel orders for a given user. These may be user-initiated cancels, or cancels created by the server (revokes). Executed cancel orders from all markets are returned.

func (*Archiver) FailCancelOrder

func (a *Archiver) FailCancelOrder(co *order.CancelOrder) error

FailCancelOrder updates or inserts the given CancelOrder with failed status. To update a CancelOrder with executed status, use ExecuteOrder.

func (*Archiver) Fatal

func (a *Archiver) Fatal() <-chan struct{}

Fatal returns a nil or closed channel for select use. Use LastErr to get the latest fatal error.

func (*Archiver) FlushBook

func (a *Archiver) FlushBook(base, quote uint32) (sellsRemoved, buysRemoved []order.OrderID, err error)

FlushBook revokes all booked orders for a market.

func (*Archiver) ForgiveMatchFail

func (a *Archiver) ForgiveMatchFail(mid order.MatchID) (bool, error)

ForgiveMatchFail marks the specified match as forgiven. Since this is an administrative function, the burden is on the operator to ensure the match can actually be forgiven (inactive, not already forgiven, and not in MatchComplete status).

func (*Archiver) InsertEpoch

func (a *Archiver) InsertEpoch(ed *db.EpochResults) error

InsertEpoch stores the results of a newly-processed epoch. TODO: test.

func (*Archiver) InsertMatch

func (a *Archiver) InsertMatch(match *order.Match) error

InsertMatch updates an existing match.

func (*Archiver) KeyIndex added in v0.4.0

func (a *Archiver) KeyIndex(xpub string) (uint32, error)

KeyIndex returns the current child index for the an xpub. If it is not known, this creates a new entry with index zero.

func (*Archiver) LastEpochRate added in v0.6.0

func (a *Archiver) LastEpochRate(base, quote uint32) (rate uint64, err error)

LastEpochRate gets the EndRate of the last EpochResults inserted for the market. If the database is empty, no error and a rate of zero are returned.

func (*Archiver) LastErr

func (a *Archiver) LastErr() error

LastErr returns any fatal or unexpected error encountered in a recent query. This may be used to check if the database had an unrecoverable error (disconnect, etc.).

func (*Archiver) LoadEpochStats added in v0.2.0

func (a *Archiver) LoadEpochStats(base, quote uint32, caches []*candles.Cache) error

LoadEpochStats reads all market epoch history from the database, updating the provided caches along the way.

func (*Archiver) MarketMatches added in v0.2.0

func (a *Archiver) MarketMatches(base, quote uint32) ([]*db.MatchDataWithCoins, error)

MarketMatches retrieves all active matches for a market.

func (*Archiver) MarketMatchesStreaming added in v0.2.0

func (a *Archiver) MarketMatchesStreaming(base, quote uint32, includeInactive bool, N int64, f func(*db.MatchDataWithCoins) error) (int, error)

MarketMatchesStreaming streams all active matches for a market into the provided function. If includeInactive, all matches are streamed. A limit may be specified, where <=0 means unlimited.

func (*Archiver) MatchByID

func (a *Archiver) MatchByID(mid order.MatchID, base, quote uint32) (*db.MatchData, error)

MatchByID retrieves the match for the given MatchID.

func (*Archiver) MatchStatuses

func (a *Archiver) MatchStatuses(aid account.AccountID, base, quote uint32, matchIDs []order.MatchID) ([]*db.MatchStatus, error)

MatchStatuses retrieves a *db.MatchStatus for every match in matchIDs for which there is data, and for which the user is at least one of the parties. It is not an error if a match ID in matchIDs does not match, i.e. the returned slice need not be the same length as matchIDs.

func (*Archiver) NewArchivedCancel added in v0.4.0

func (a *Archiver) NewArchivedCancel(ord *order.CancelOrder, epochID, epochDur int64) error

NewArchivedCancel stores a cancel order directly in the executed state. This is used for orders that are canceled when the market is suspended, and therefore do not need to be matched.

func (*Archiver) NewEpochOrder

func (a *Archiver) NewEpochOrder(ord order.Order, epochIdx, epochDur int64, epochGap int32) error

NewEpochOrder stores the given order with epoch status. This is equivalent to StoreOrder with OrderStatusEpoch.

func (*Archiver) Order

func (a *Archiver) Order(oid order.OrderID, base, quote uint32) (order.Order, order.OrderStatus, error)

Order retrieves an order with the given OrderID, stored for the market specified by the given base and quote assets. A non-nil error will be returned if the market is not recognized. If the order is not found, the error value is ErrUnknownOrder, and the type is order.OrderStatusUnknown. The only recognized order types are market, limit, and cancel.

func (*Archiver) OrderPreimage

func (a *Archiver) OrderPreimage(ord order.Order) (order.Preimage, error)

func (*Archiver) OrderStatus

func (a *Archiver) OrderStatus(ord order.Order) (order.OrderStatus, order.OrderType, int64, error)

OrderStatus gets the status, ID, and filled amount of the given order. See also OrderStatusByID.

func (*Archiver) OrderStatusByID

func (a *Archiver) OrderStatusByID(oid order.OrderID, base, quote uint32) (order.OrderStatus, order.OrderType, int64, error)

OrderStatusByID gets the status, type, and filled amount of the order with the given OrderID in the market specified by a base and quote asset. See also OrderStatus. If the order is not found, the error value is ErrUnknownOrder, and the type is order.OrderStatusUnknown.

func (*Archiver) OrderWithCommit

func (a *Archiver) OrderWithCommit(ctx context.Context, commit order.Commitment) (found bool, oid order.OrderID, err error)

OrderWithCommit searches all markets' trade and cancel orders, both active and archived, for an order with the given Commitment.

func (*Archiver) PayAccount

func (a *Archiver) PayAccount(aid account.AccountID, coinID []byte) error

PayAccount sets the registration fee payment details for the account, effectively completing the registration process.

func (*Archiver) PreimageStats

func (a *Archiver) PreimageStats(user account.AccountID, lastN int) ([]*db.PreimageResult, error)

PreimageStats retrieves results of the N most recent preimage requests for the user across all markets.

func (*Archiver) RevokeOrder

func (a *Archiver) RevokeOrder(ord order.Order) (cancelID order.OrderID, timeStamp time.Time, err error)

RevokeOrder updates an Order with revoked status, which is used for DEX-revoked orders rather than orders matched with a user's CancelOrder. If the order does not exist in the Archiver, RevokeOrder returns ErrUnknownOrder. This may change orders with status executed to revoked, which may be unexpected.

func (*Archiver) RevokeOrderUncounted

func (a *Archiver) RevokeOrderUncounted(ord order.Order) (cancelID order.OrderID, timeStamp time.Time, err error)

RevokeOrderUncounted is like RevokeOrder except that the generated cancel order will not be counted against the user. i.e. ExecutedCancelsForUser should not return the cancel orders created this way.

func (*Archiver) SaveAuditAckSigA

func (a *Archiver) SaveAuditAckSigA(mid db.MarketMatchID, sig []byte) error

SaveAuditAckSigA records party A's signature acknowledging their audit of B's swap contract.

func (*Archiver) SaveAuditAckSigB

func (a *Archiver) SaveAuditAckSigB(mid db.MarketMatchID, sig []byte) error

SaveAuditAckSigB records party B's signature acknowledging their audit of A's swap contract.

func (*Archiver) SaveContractA

func (a *Archiver) SaveContractA(mid db.MarketMatchID, contract []byte, coinID []byte, timestamp int64) error

SaveContractA records party A's swap contract script and the coinID (e.g. transaction output) containing the contract on chain X. Note that this contract contains the secret hash.

func (*Archiver) SaveContractB

func (a *Archiver) SaveContractB(mid db.MarketMatchID, contract []byte, coinID []byte, timestamp int64) error

SaveContractB records party B's swap contract script and the coinID (e.g. transaction output) containing the contract on chain Y.

func (*Archiver) SaveMatchAckSigA

func (a *Archiver) SaveMatchAckSigA(mid db.MarketMatchID, sig []byte) error

SaveMatchAckSigA records the match data acknowledgement signature from swap party A (the initiator), which is the maker in the DEX.

func (*Archiver) SaveMatchAckSigB

func (a *Archiver) SaveMatchAckSigB(mid db.MarketMatchID, sig []byte) error

SaveMatchAckSigB records the match data acknowledgement signature from swap party B (the participant), which is the taker in the DEX.

func (*Archiver) SaveRedeemA

func (a *Archiver) SaveRedeemA(mid db.MarketMatchID, coinID, secret []byte, timestamp int64) error

SaveRedeemA records party A's redemption coinID (e.g. transaction output), which spends party B's swap contract on chain Y, and the secret revealed by the signature script of the input spending the contract. Note that this transaction will contain the secret, which party B extracts.

func (*Archiver) SaveRedeemAckSigB

func (a *Archiver) SaveRedeemAckSigB(mid db.MarketMatchID, sig []byte) error

SaveRedeemAckSigB records party B's signature acknowledging party A's redemption, which spent their swap contract on chain Y and revealed the secret. Since this may be the final step in match negotiation, the match is also flagged as inactive (not the same as archival or even status of MatchComplete, which is set by SaveRedeemB) if the initiators's redeem ack signature is already set.

func (*Archiver) SaveRedeemB

func (a *Archiver) SaveRedeemB(mid db.MarketMatchID, coinID []byte, timestamp int64) error

SaveRedeemB records party B's redemption coinID (e.g. transaction output), which spends party A's swap contract on chain X.

func (*Archiver) SetKeyIndex added in v0.4.0

func (a *Archiver) SetKeyIndex(idx uint32, xpub string) error

SetKeyIndex records the child index for an xpub. An error is returned unless exactly 1 row is updated or created.

func (*Archiver) SetMatchInactive

func (a *Archiver) SetMatchInactive(mid db.MarketMatchID, forgive bool) error

SetMatchInactive flags the match as done/inactive. This is not necessary if SaveRedeemAckSigB is run for the match since it will flag the match as done.

func (*Archiver) SetOrderCompleteTime

func (a *Archiver) SetOrderCompleteTime(ord order.Order, compTimeMs int64) error

SetOrderCompleteTime sets the successful swap completion time for an existing order. It is an error if the order is not in executed status.

func (*Archiver) StoreOrder

func (a *Archiver) StoreOrder(ord order.Order, epochIdx, epochDur int64, status order.OrderStatus) error

StoreOrder stores an order for the specified epoch ID (idx:dur) with the provided status. The market is determined from the Order. A non-nil error will be returned if the market is not recognized. All orders are validated via server/db.ValidateOrder to ensure only sensible orders reach persistent storage. Updating orders should be done via one of the update functions such as UpdateOrderStatus.

func (*Archiver) StorePreimage

func (a *Archiver) StorePreimage(ord order.Order, pi order.Preimage) error

StorePreimage stores the preimage associated with an existing order.

func (*Archiver) SwapData

func (a *Archiver) SwapData(mid db.MarketMatchID) (order.MatchStatus, *db.SwapData, error)

SwapData retrieves the match status and all the SwapData for a match.

func (*Archiver) UpdateOrderFilled

func (a *Archiver) UpdateOrderFilled(ord *order.LimitOrder) error

UpdateOrderFilled updates the filled amount of the given order. Both the market and new filled amount are determined from the Order. OrderStatusByID is used to locate the existing order. This function applies only to limit orders, not market or cancel orders. Market orders may only be updated by ExecuteOrder since their filled amount only changes when their status changes. See also UpdateOrderFilledByID.

func (*Archiver) UpdateOrderFilledByID

func (a *Archiver) UpdateOrderFilledByID(oid order.OrderID, base, quote uint32, filled int64) error

UpdateOrderFilledByID updates the filled amount of the order with the given OrderID in the market specified by a base and quote asset. This function applies only to market and limit orders, not cancel orders. OrderStatusByID is used to locate the existing order. If the order is not found, the error value is ErrUnknownOrder, and the type is order.OrderStatusUnknown. See also UpdateOrderFilled. To also update the order status, use UpdateOrderStatusByID or UpdateOrderStatus.

func (*Archiver) UpdateOrderStatus

func (a *Archiver) UpdateOrderStatus(ord order.Order, status order.OrderStatus) error

UpdateOrderStatus updates the status and filled amount of the given order. Both the market and new filled amount are determined from the Order. OrderStatusByID is used to locate the existing order. See also UpdateOrderStatusByID.

func (*Archiver) UpdateOrderStatusByID

func (a *Archiver) UpdateOrderStatusByID(oid order.OrderID, base, quote uint32, status order.OrderStatus, filled int64) error

UpdateOrderStatusByID updates the status and filled amount of the order with the given OrderID in the market specified by a base and quote asset. If filled is -1, the filled amount is unchanged. For cancel orders, the filled amount is ignored. OrderStatusByID is used to locate the existing order. If the order is not found, the error value is ErrUnknownOrder, and the type is market/order.OrderStatusUnknown. See also UpdateOrderStatus.

func (*Archiver) UserMatches

func (a *Archiver) UserMatches(aid account.AccountID, base, quote uint32) ([]*db.MatchData, error)

UserMatches retrieves all matches involving a user on the given market. TODO: consider a time limited version of this to retrieve recent matches.

func (*Archiver) UserOrderStatuses

func (a *Archiver) UserOrderStatuses(aid account.AccountID, base, quote uint32, oids []order.OrderID) ([]*db.OrderStatus, error)

UserOrderStatuses retrieves the statuses and filled amounts of the orders with the provided order IDs for the given account in the market specified by a base and quote asset. The number and ordering of the returned statuses is not necessarily the same as the number and ordering of the provided order IDs. It is not an error if any or all of the provided order IDs cannot be found for the given account in the specified market.

func (*Archiver) UserOrders

func (a *Archiver) UserOrders(ctx context.Context, aid account.AccountID, base, quote uint32) ([]order.Order, []order.OrderStatus, error)

UserOrders retrieves all orders for the given account in the market specified by a base and quote asset.

type Config

type Config struct {
	Host, Port, User, Pass, DBName string
	ShowPGConfig                   bool
	QueryTimeout                   time.Duration

	// MarketCfg specifies all of the markets that the Archiver should prepare.
	MarketCfg []*dex.MarketInfo
}

Config holds the Archiver's configuration.

type DetailedError

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

DetailedError pairs an Error with details.

func NewDetailedError

func NewDetailedError(err error, detail string) DetailedError

NewDetailedError wraps the provided Error with details in a DetailedError, facilitating the use of errors.Is and errors.As via errors.Unwrap.

func (DetailedError) Error

func (e DetailedError) Error() string

Error satisfies the error interface, combining the wrapped error message with the details.

func (DetailedError) Unwrap

func (e DetailedError) Unwrap() error

Unwrap returns the wrapped error, allowing errors.Is and errors.As to work.

type Driver

type Driver struct{}

Driver implements db.Driver.

func (*Driver) Open

func (d *Driver) Open(ctx context.Context, cfg interface{}) (db.DEXArchivist, error)

Open creates the DB backend, returning a DEXArchivist.

func (*Driver) UseLogger

func (*Driver) UseLogger(logger dex.Logger)

UseLogger sets the package-wide logger for the registered DB Driver.

type PGSetting

type PGSetting struct {
	Name, Setting, Unit, ShortDesc, Source, SourceFile, SourceLine string
}

PGSetting describes a PostgreSQL setting scanned from pg_settings.

type PGSettings

type PGSettings map[string]PGSetting

PGSettings facilitates looking up a PGSetting based on a setting's Name.

func (PGSettings) String

func (pgs PGSettings) String() string

String implements the Stringer interface, generating a table of the settings where the Setting and Unit fields are merged into a single column. The rows of the table are sorted by the PGSettings string key (the setting's Name). This function is not thread-safe, so do not modify PGSettings concurrently.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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