db

package
v0.5.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2022 License: BlueOak-1.0.0 Imports: 15 Imported by: 3

Documentation

Index

Constants

View Source
const ErrNoCredentials = dex.ErrorKind("no credentials have been stored")
View Source
const ErrNoSeedGenTime = dex.ErrorKind("seed generation time has not been stored")
View Source
const (
	MatchProofVer = 2
)

MatchProofVer is the current serialization version of a MatchProof.

Variables

This section is empty.

Functions

func MatchIsActive added in v0.4.0

func MatchIsActive(match *order.UserMatch, proof *MatchProof) bool

MatchIsActive returns false (i.e. the match is inactive) if any: (1) status is complete AND (RedeemSig is set, signalling completed swap OR InitSig unset, signaling a cancel order match, which is never active), (2) the match is refunded, or (3) it is revoked and this side of the match requires no further action like refund or auto-redeem.

WARNING: Do not modify this function without preserving a version for v6Upgrade or any other upgrade that relies on a particular behavior.

Types

type AccountBackup

type AccountBackup struct {
	KeyParams []byte
	Accounts  []*AccountInfo
}

AccountBackup represents a user account backup.

func RestoreAccountBackup

func RestoreAccountBackup(path string) (*AccountBackup, error)

RestoreAccountBackup generates a user account from a backup file.

func (*AccountBackup) Save

func (ab *AccountBackup) Save(path string) error

Save persists an account backup to file.

func (*AccountBackup) Serialize

func (ab *AccountBackup) Serialize() []byte

Serialize encodes an account backup as bytes.

type AccountInfo

type AccountInfo struct {
	// Host, Cert, and DEXPubKey identify the DEX server.
	Host      string
	Cert      []byte
	DEXPubKey *secp256k1.PublicKey

	// EncKeyV2 is an encrypted private key generated deterministically from the
	// app seed.
	EncKeyV2 []byte
	// LegacyEncKey is an old-style non-hierarchical key that must be included
	// when exporting the client credentials, since it cannot be regenerated
	// automatically.
	LegacyEncKey []byte

	FeeAssetID uint32
	FeeCoin    []byte
	// Paid is set on retrieval based on whether there is an AccountProof set.
	Paid bool
}

AccountInfo is information about an account on a Decred DEX. The database is designed for one account per server.

func DecodeAccountInfo

func DecodeAccountInfo(b []byte) (*AccountInfo, error)

DecodeAccountInfo decodes the versioned blob into an *AccountInfo. The byte slice fields of AccountInfo reference the underlying buffer of the the input.

func (*AccountInfo) EncKey

func (ai *AccountInfo) EncKey() []byte

EncKey is the encrypted account private key.

func (*AccountInfo) Encode

func (ai *AccountInfo) Encode() []byte

Encode the AccountInfo as bytes.

type AccountProof

type AccountProof struct {
	Host  string
	Stamp uint64
	Sig   []byte
}

Account proof is information necessary to prove that the DEX server accepted the account's fee payment. The fee coin is not part of the proof, since it is already stored as part of the AccountInfo blob.

func DecodeAccountProof

func DecodeAccountProof(b []byte) (*AccountProof, error)

DecodeAccountProof decodes the versioned blob to a *MatchProof.

func (*AccountProof) Encode

func (p *AccountProof) Encode() []byte

Encode encodes the AccountProof to a versioned blob.

type Balance

type Balance struct {
	asset.Balance
	Stamp time.Time `json:"stamp"`
}

Balance represents a wallet's balance in various contexts.

func DecodeBalance

func DecodeBalance(b []byte) (*Balance, error)

DecodeBalance decodes the versioned blob to a *Balance.

func (*Balance) Encode

func (b *Balance) Encode() []byte

Encode encodes the Balance to a versioned blob.

type DB

type DB interface {
	dex.Runner
	// SetPrimaryCredentials sets the initial *PrimaryCredentials.
	SetPrimaryCredentials(creds *PrimaryCredentials) error
	// PrimaryCredentials fetches the *PrimaryCredentials.
	PrimaryCredentials() (*PrimaryCredentials, error)
	// Recrypt re-encrypts the wallet passwords and account private keys, and
	// stores the new *PrimaryCredentials.
	Recrypt(creds *PrimaryCredentials, oldCrypter, newCrypter encrypt.Crypter) (
		walletUpdates map[uint32][]byte, acctUpdates map[string][]byte, err error)
	// ListAccounts returns a list of DEX URLs. The DB is designed to have a
	// single account per DEX, so the account is uniquely identified by the DEX
	// URL.
	ListAccounts() ([]string, error)
	// Accounts retrieves all accounts.
	Accounts() ([]*AccountInfo, error)
	// Account gets the AccountInfo associated with the specified DEX node.
	Account(host string) (*AccountInfo, error)
	// CreateAccount saves the AccountInfo.
	CreateAccount(ai *AccountInfo) error
	// UpdateAccountInfo updates the account info for an existing account with
	// the same Host as the parameter. If no account exists with this host,
	// an error is returned.
	UpdateAccountInfo(ai *AccountInfo) error
	// DisableAccount sets the AccountInfo disabled status to true.
	DisableAccount(host string) error
	// AccountProof retrieves the AccountPoof value specified by url.
	AccountProof(host string) (*AccountProof, error)
	// AccountPaid marks the account as paid.
	AccountPaid(proof *AccountProof) error
	// UpdateOrder saves the order information in the database. Any existing
	// order info will be overwritten without indication.
	UpdateOrder(m *MetaOrder) error
	// ActiveOrders retrieves all orders which appear to be in an active state,
	// which is either in the epoch queue or in the order book.
	ActiveOrders() ([]*MetaOrder, error)
	// AccountOrders retrieves all orders associated with the specified DEX. The
	// order count can be limited by supplying a non-zero n value. In that case
	// the newest n orders will be returned. The orders can be additionally
	// filtered by supplying a non-zero since value, corresponding to a UNIX
	// timestamp, in milliseconds. n = 0 applies no limit on number of orders
	// returned. since = 0 is equivalent to disabling the time filter, since
	// no orders were created before before 1970.
	AccountOrders(dex string, n int, since uint64) ([]*MetaOrder, error)
	// Order fetches a MetaOrder by order ID.
	Order(order.OrderID) (*MetaOrder, error)
	// Orders fetches a slice of orders, sorted by descending time, and filtered
	// with the provided OrderFilter.
	Orders(*OrderFilter) ([]*MetaOrder, error)
	// ActiveDEXOrders retrieves orders for a particular dex, specified by its
	// URL.
	ActiveDEXOrders(dex string) ([]*MetaOrder, error)
	// MarketOrders retrieves all orders for the specified DEX and market. The
	// order count can be limited by supplying a non-zero n value. In that case
	// the newest n orders will be returned. The orders can be additionally
	// filtered by supplying a non-zero since value, corresponding to a UNIX
	// timestamp, in milliseconds. n = 0 applies no limit on number of orders
	// returned. since = 0 is equivalent to disabling the time filter, since
	// no orders were created before before 1970.
	MarketOrders(dex string, base, quote uint32, n int, since uint64) ([]*MetaOrder, error)
	// UpdateOrderMetaData updates the order metadata, not including the Host.
	UpdateOrderMetaData(order.OrderID, *OrderMetaData) error
	// UpdateOrderStatus sets the order status for an order.
	UpdateOrderStatus(oid order.OrderID, status order.OrderStatus) error
	// LinkOrder sets the LinkedOrder field of the specified order's
	// OrderMetaData.
	LinkOrder(oid, linkedID order.OrderID) error
	// UpdateMatch updates the match information in the database. Any existing
	// entry for the match will be overwritten without indication.
	UpdateMatch(m *MetaMatch) error
	// ActiveMatches retrieves the matches that are in an active state, which is
	// any state except order.MatchComplete.
	ActiveMatches() ([]*MetaMatch, error)
	// DEXOrdersWithActiveMatches retrieves order IDs for any order that has
	// active matches, regardless of whether the order itself is in an active
	// state.
	DEXOrdersWithActiveMatches(dex string) ([]order.OrderID, error)
	// MatchesForOrder gets the matches for the order ID.
	MatchesForOrder(oid order.OrderID, excludeCancels bool) ([]*MetaMatch, error)
	// Update wallets adds a wallet to the database, or updates the wallet
	// credentials if the wallet already exists. A wallet is specified by the
	// pair (asset ID, account name).
	UpdateWallet(wallet *Wallet) error
	// SetWalletPassword sets the encrypted password for the wallet.
	SetWalletPassword(wid []byte, newPW []byte) error
	// UpdateBalance updates a wallet's balance.
	UpdateBalance(wid []byte, balance *Balance) error
	// Wallets lists all saved wallets.
	Wallets() ([]*Wallet, error)
	// Wallet fetches the wallet for the specified asset by wallet ID.
	Wallet(wid []byte) (*Wallet, error)
	// Backup makes a copy of the database to the default "backups" folder.
	Backup() error
	// BackupTo makes a backup of the database at the specified location,
	// optionally overwriting any existing file and compacting the database.
	BackupTo(dst string, overwrite, compact bool) error
	// SaveNotification saves the notification.
	SaveNotification(*Notification) error
	// NotificationsN reads out the N most recent notifications.
	NotificationsN(int) ([]*Notification, error)
	// AckNotification sets the acknowledgement for a notification.
	AckNotification(id []byte) error
	// DeleteInactiveOrders deletes inactive orders from the database that
	// have been updated after the supplied time. If no time is supplied
	// the current time is used. Accepts an optional function to perform on
	// deleted orders.
	DeleteInactiveOrders(ctx context.Context, olderThan *time.Time, perOrderFn func(ord *MetaOrder) error) error
	// DeleteInactiveMatches deletes inactive matches from the database
	// that have been created after the supplied time. If no time is
	// supplied the current time is used. Accepts an optional function to
	// perform on deleted matches that includes if it was a sell order.
	DeleteInactiveMatches(ctx context.Context, olderThan *time.Time, perMatchFn func(mtch *MetaMatch, isSell bool) error) error
	// SetSeedGenerationTime stores the time when the app seed was generated.
	SetSeedGenerationTime(time uint64) error
	// SeedGenerationTime fetches the time when the app seed was generated.
	SeedGenerationTime() (uint64, error)
	// DisabledRateSources retrieves disabled fiat rate sources from the
	// database.
	DisabledRateSources() ([]string, error)
	// SaveDisabledRateSources saves disabled fiat rate sources in the database.
	// A source name must not contain a comma.
	SaveDisabledRateSources(disabledSources []string) error
}

DB is an interface that must be satisfied by a DEX client persistent storage manager.

type MatchAuth

type MatchAuth struct {
	MatchSig        []byte
	MatchStamp      uint64
	InitSig         []byte
	InitStamp       uint64
	AuditSig        []byte
	AuditStamp      uint64
	RedeemSig       []byte
	RedeemStamp     uint64
	RedemptionSig   []byte
	RedemptionStamp uint64
}

MatchAuth holds the DEX signatures and timestamps associated with the messages in the negotiation process.

type MatchMetaData

type MatchMetaData struct {
	// Proof is the signatures and other verification-related data for the match.
	Proof MatchProof
	// DEX is the URL of the server that this match is associated with.
	DEX string
	// Base is the base asset of the exchange market.
	Base uint32
	// Quote is the quote asset of the exchange market.
	Quote uint32
	// Stamp is the match time (ms UNIX), according to the server's 'match'
	// request timestamp.
	Stamp uint64
}

MatchMetaData is important auxiliary information about the match.

type MatchProof

type MatchProof struct {
	ContractData    []byte
	CounterContract []byte
	CounterTxData   []byte
	SecretHash      []byte
	Secret          []byte
	MakerSwap       order.CoinID
	MakerRedeem     order.CoinID
	TakerSwap       order.CoinID
	TakerRedeem     order.CoinID
	RefundCoin      order.CoinID
	Auth            MatchAuth
	ServerRevoked   bool
	SelfRevoked     bool
}

MatchProof is information related to the progression of the swap negotiation process.

func DecodeMatchProof

func DecodeMatchProof(b []byte) (*MatchProof, uint8, error)

DecodeMatchProof decodes the versioned blob to a *MatchProof.

func (*MatchProof) Encode

func (p *MatchProof) Encode() []byte

Encode encodes the MatchProof to a versioned blob.

func (*MatchProof) IsRevoked

func (p *MatchProof) IsRevoked() bool

IsRevoked is true if either ServerRevoked or SelfRevoked is true.

type MetaMatch

type MetaMatch struct {
	// UserMatch is the match info.
	*order.UserMatch
	// MetaData is important auxiliary information about the match.
	MetaData *MatchMetaData
}

MetaMatch is a match and its metadata.

func (*MetaMatch) MatchOrderUniqueID added in v0.2.0

func (m *MetaMatch) MatchOrderUniqueID() []byte

MatchOrderUniqueID is a unique ID for the match-order pair.

type MetaOrder

type MetaOrder struct {
	// MetaData is important auxiliary information about the order.
	MetaData *OrderMetaData
	// Order is the order.
	Order order.Order
}

MetaOrder is an order and its metadata.

type Notification

type Notification struct {
	NoteType    string    `json:"type"`
	TopicID     Topic     `json:"topic"`
	SubjectText string    `json:"subject"`
	DetailText  string    `json:"details"`
	Severeness  Severity  `json:"severity"`
	TimeStamp   uint64    `json:"stamp"`
	Ack         bool      `json:"acked"`
	Id          dex.Bytes `json:"id"`
}

Notification is information for the user that is typically meant for display, and is persisted for recall across sessions.

func DecodeNotification

func DecodeNotification(b []byte) (*Notification, error)

DecodeNotification decodes the versioned blob to a *Notification.

func NewNotification

func NewNotification(noteType string, topic Topic, subject, details string, severity Severity) Notification

NewNotification is a constructor for a Notification.

func (*Notification) Acked

func (n *Notification) Acked() bool

Acked is true if the user has seen the notification. Acknowledgement is recorded with DB.AckNotification.

func (*Notification) DBNote

func (n *Notification) DBNote() *Notification

DBNote is a function to return the *Notification itself. It should really be defined on the concrete types in core, but is ubiquitous so defined here for convenience.

func (*Notification) Details

func (n *Notification) Details() string

Details should contain more detailed information.

func (*Notification) Encode

func (n *Notification) Encode() []byte

Encode encodes the Notification to a versioned blob.

func (*Notification) ID

func (n *Notification) ID() dex.Bytes

ID is a unique ID based on a hash of the notification data.

func (*Notification) Severity

func (n *Notification) Severity() Severity

Severity is the notification severity.

func (*Notification) Stamp

func (n *Notification) Stamp()

Stamp sets the notification timestamp. If NewNotification is used to construct the Notification, the timestamp will already be set.

func (*Notification) String

func (n *Notification) String() string

String generates a compact human-readable representation of the Notification that is suitable for logging. For example:

|SUCCESS| (fee payment) Fee paid - Waiting for 2 confirmations before trading at https://superdex.tld:7232
|DATA| (boring event) Subject without details

func (*Notification) Subject

func (n *Notification) Subject() string

Subject is a short description of the notification contents.

func (*Notification) Time

func (n *Notification) Time() uint64

Time is the notification timestamp. The timestamp is set in NewNotification.

func (*Notification) Topic added in v0.4.0

func (n *Notification) Topic() Topic

Topic is a language-independent unique ID for the Notification.

func (*Notification) Type

func (n *Notification) Type() string

Type is the notification type.

type OrderFilter

type OrderFilter struct {
	// N is the number of orders to return in the set.
	N int
	// Offset can be used to shift the window of the time-sorted orders such
	// that any orders that would sort to index <= the order specified by Offset
	// will be rejected.
	Offset order.OrderID
	// Hosts is a list of acceptable hosts. A zero-length Hosts means all
	// hosts are accepted.
	Hosts []string
	// Assets is a list of BIP IDs for acceptable assets. A zero-length Assets
	// means all assets are accepted.
	Assets []uint32
	// Statuses is a list of acceptable statuses. A zero-length Statuses means
	// all statuses are accepted.
	Statuses []order.OrderStatus
}

OrderFilter is used to limit the results returned by a query to (DB).Orders.

type OrderMetaData

type OrderMetaData struct {
	// Status is the last known order status.
	Status order.OrderStatus
	// Host is the hostname of the server that this order is associated with.
	Host string
	// Proof is the signatures and other verification-related data for the order.
	Proof OrderProof
	// ChangeCoin is a change coin from a match. Change coins are "daisy-chained"
	// for matches. All funding coins go into the first match, and the change coin
	// from the initiation transaction is used to fund the next match. The
	// change from that matches ini tx funds the next match, etc.
	ChangeCoin order.CoinID
	// LinkedOrder is used to specify the cancellation order for a trade, or
	// vice-versa.
	LinkedOrder order.OrderID
	// SwapFeesPaid is the sum of the actual fees paid for all swaps.
	SwapFeesPaid uint64
	// RedemptionFeesPaid is the sum of the actual fees paid for all
	// redemptions.
	RedemptionFeesPaid uint64
	// MaxFeeRate is the dex.Asset.MaxFeeRate at the time of ordering. The rates
	// assigned to matches will be validated against this value.
	MaxFeeRate uint64
	// RedeemMaxFeeRate is the dex.Asset.MaxFeeRate for the redemption asset at
	// the time of ordering. This rate is used to reserve funds for redemption,
	// and therefore this rate can be used when actually submitting a redemption
	// transaction.
	RedeemMaxFeeRate uint64
	// FromVersion is the version of the from asset.
	FromVersion uint32
	// ToVersion is the version of the to asset.
	ToVersion uint32
	// Options are the options offered by the wallet and selected by the user.
	Options map[string]string
	// RedemptionReserves is the amount of funds reserved by the wallet to pay
	// the transaction fees for all the possible redemptions in this order.
	// The amount that should be locked at any point can be determined by
	// checking the status of the order and the status of all matches related
	// to this order, and determining how many more possible redemptions there
	// could be.
	RedemptionReserves uint64
	// RedemptionRefunds is the amount of funds reserved by the wallet to pay
	// the transaction fees for all the possible refunds in this order.
	// The amount that should be locked at any point can be determined by
	// checking the status of the order and the status of all matches related
	// to this order, and determining how many more possible refunds there
	// could be.
	RefundReserves uint64
	// AccelerationCoins keeps track of all the change coins generated from doing
	// accelerations on this order.
	AccelerationCoins []order.CoinID
}

OrderMetaData is important auxiliary information about an order.

type OrderProof

type OrderProof struct {
	DEXSig   []byte
	Preimage []byte
}

OrderProof is information related to order authentication and matching.

func DecodeOrderProof

func DecodeOrderProof(b []byte) (*OrderProof, error)

DecodeOrderProof decodes the versioned blob to an *OrderProof.

func (*OrderProof) Encode

func (p *OrderProof) Encode() []byte

Encode encodes the OrderProof to a versioned blob.

type PrimaryCredentials added in v0.4.0

type PrimaryCredentials struct {
	// EncSeed is the root seed used to create a hierarchical deterministic
	// key chain (see also dcrd/hdkeychain.NewMaster/ExtendedKey).
	EncSeed []byte
	// EncInnerKey is an encrypted encryption key. The inner key will never
	// change. The inner key is encrypted with the outer key, which itself is
	// based on the user's password.
	EncInnerKey []byte
	// InnerKeyParams are the key parameters for the inner key.
	InnerKeyParams []byte
	// OuterKeyParams are the key parameters for the outer key.
	OuterKeyParams []byte
}

PrimaryCredentials should be created during app initialization. Both the seed and the inner key (and technically the other two fields) should be generated with a cryptographically-secure prng.

type Severity

type Severity uint8

Severity indicates the level of required action for a notification. The DEX db only stores notifications with Severity >= Success.

const (
	Ignorable Severity = iota
	// Data notifications are not meant for display to the user. These
	// notifications are used only for communication of information necessary for
	// UI updates or other high-level state changes.
	Data
	// Poke notifications are not persistent across sessions. These should be
	// displayed if the user has a live notification feed. They are not stored in
	// the database.
	Poke
	// Success and higher are stored and can be recalled using DB.NotificationsN.
	Success
	WarningLevel
	ErrorLevel
)

func (Severity) String

func (s Severity) String() string

String satisfies fmt.Stringer for Severity.

type Topic added in v0.4.0

type Topic string

Topic is a language-independent unique ID for a Notification.

type Wallet

type Wallet struct {
	AssetID     uint32
	Type        string
	Settings    map[string]string
	Balance     *Balance
	EncryptedPW []byte
	Address     string
}

Wallet is information necessary to create an asset.Wallet.

func DecodeWallet

func DecodeWallet(b []byte) (*Wallet, error)

DecodeWallet decodes the versioned blob to a *Wallet. The Balance is NOT set; the caller must retrieve it. See for example makeWallet and DecodeBalance.

func (*Wallet) Encode

func (w *Wallet) Encode() []byte

Encode encodes the Wallet to a versioned blob.

func (*Wallet) ID

func (w *Wallet) ID() []byte

ID is the byte-encoded asset ID for this wallet.

func (*Wallet) SID

func (w *Wallet) SID() string

SID is a string respresentation of the wallet's asset ID.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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