Documentation ¶
Index ¶
- Constants
- Variables
- func DisableLog()
- func UseLogger(logger slog.Logger)
- type AuthManager
- func (auth *AuthManager) AccountMatchOutcomesN(user account.AccountID, n int) ([]*MatchOutcome, error)
- func (auth *AuthManager) AcctStatus(user account.AccountID) (connected bool, tier int64)
- func (auth *AuthManager) Auth(user account.AccountID, msg, sig []byte) error
- func (auth *AuthManager) ComputeUserReputation(user account.AccountID) *account.Reputation
- func (auth *AuthManager) CreatePrepaidBonds(n int, strength uint32, durSecs int64) ([][]byte, error)
- func (auth *AuthManager) ExpectUsers(users map[account.AccountID]struct{}, within time.Duration)
- func (auth *AuthManager) ForgiveMatchFail(user account.AccountID, mid order.MatchID) (forgiven, unbanned bool, err error)
- func (auth *AuthManager) GraceLimit() int
- func (auth *AuthManager) Inaction(user account.AccountID, misstep NoActionStep, mmid db.MarketMatchID, ...)
- func (auth *AuthManager) MissedPreimage(user account.AccountID, epochEnd time.Time, oid order.OrderID)
- func (auth *AuthManager) Notify(acctID account.AccountID, msg *msgjson.Message)
- func (auth *AuthManager) Penalize(user account.AccountID, lastRule account.Rule, extraDetails string)
- func (auth *AuthManager) PreimageSuccess(user account.AccountID, epochEnd time.Time, oid order.OrderID)
- func (auth *AuthManager) RecordCancel(user account.AccountID, oid, target order.OrderID, epochGap int32, t time.Time)
- func (auth *AuthManager) RecordCompletedOrder(user account.AccountID, oid order.OrderID, t time.Time)
- func (auth *AuthManager) Request(user account.AccountID, msg *msgjson.Message, ...) error
- func (auth *AuthManager) RequestWithTimeout(user account.AccountID, msg *msgjson.Message, ...) error
- func (auth *AuthManager) Route(route string, handler func(account.AccountID, *msgjson.Message) *msgjson.Error)
- func (auth *AuthManager) Run(ctx context.Context)
- func (auth *AuthManager) Send(user account.AccountID, msg *msgjson.Message) error
- func (auth *AuthManager) Sign(signables ...msgjson.Signable)
- func (auth *AuthManager) SignMsg(msg []byte) []byte
- func (auth *AuthManager) SwapSuccess(user account.AccountID, mmid db.MarketMatchID, value uint64, ...)
- func (auth *AuthManager) UserMatchFails(user account.AccountID, n int) ([]*MatchFail, error)
- func (auth *AuthManager) UserReputation(user account.AccountID) (tier int64, score, maxScore int32, err error)
- func (auth *AuthManager) UserScore(user account.AccountID) (score int32, err error)
- type BondCoinChecker
- type BondTxParser
- type Config
- type FeeChecker
- type MatchFail
- type MatchOutcome
- type NoActionStep
- type Signer
- type Storage
- type TxDataSource
- type Violation
Constants ¶
const (
DefaultPenaltyThreshold = 20
)
violation badness
const DefaultRequestTimeout = 30 * time.Second
DefaultRequestTimeout is the default timeout for requests to wait for responses from connected users after the request is successfully sent.
const (
ScoringMatchLimit = 60 // last N matches (success or at-fault fail) to be considered in swap inaction scoring
)
Variables ¶
var (
ErrUserNotConnected = dex.ErrorKind("user not connected")
)
Functions ¶
func DisableLog ¶
func DisableLog()
DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.
Types ¶
type AuthManager ¶
type AuthManager struct {
// contains filtered or unexported fields
}
AuthManager handles authentication-related tasks, including validating client signatures, maintaining association between accounts and `comms.Link`s, and signing messages with the DEX's private key. AuthManager manages requests to the 'connect' route.
func NewAuthManager ¶
func NewAuthManager(cfg *Config) *AuthManager
NewAuthManager is the constructor for an AuthManager.
func (*AuthManager) AccountMatchOutcomesN ¶ added in v1.0.0
func (auth *AuthManager) AccountMatchOutcomesN(user account.AccountID, n int) ([]*MatchOutcome, error)
AccountMatchOutcomesN generates a list of recent match outcomes for a user.
func (*AuthManager) AcctStatus ¶ added in v0.6.0
func (auth *AuthManager) AcctStatus(user account.AccountID) (connected bool, tier int64)
AcctStatus indicates if the user is presently connected and their tier.
func (*AuthManager) Auth ¶
func (auth *AuthManager) Auth(user account.AccountID, msg, sig []byte) error
Auth validates the signature/message pair with the users public key.
func (*AuthManager) ComputeUserReputation ¶ added in v1.0.0
func (auth *AuthManager) ComputeUserReputation(user account.AccountID) *account.Reputation
ComputeUserTier computes the user's tier from their active bonds and conduct score. The bondTier is also returned. The DB is always consulted for computing the conduct score. Summing bond amounts may access the DB if the user is not presently connected. The tier for an unknown user is -1.
func (*AuthManager) CreatePrepaidBonds ¶ added in v1.0.0
func (auth *AuthManager) CreatePrepaidBonds(n int, strength uint32, durSecs int64) ([][]byte, error)
CreatePrepaidBonds generates pre-paid bonds.
func (*AuthManager) ExpectUsers ¶
func (auth *AuthManager) ExpectUsers(users map[account.AccountID]struct{}, within time.Duration)
ExpectUsers specifies which users are expected to connect within a certain time or have their orders unbooked (revoked). This should be run prior to starting the AuthManager. This is not part of the constructor since it is convenient to obtain this information from the Market's Books, and Market requires the AuthManager. The same information could be pulled from storage, but the Market is the authoritative book. The AuthManager should be started via Run immediately after calling ExpectUsers so the users can connect.
func (*AuthManager) ForgiveMatchFail ¶
func (auth *AuthManager) ForgiveMatchFail(user account.AccountID, mid order.MatchID) (forgiven, unbanned bool, err error)
ForgiveMatchFail forgives a user for a specific match failure, potentially allowing them to resume trading if their score becomes passing. NOTE: This may become deprecated with mesh, unless matches may be forgiven in some automatic network reconciliation process.
func (*AuthManager) GraceLimit ¶
func (auth *AuthManager) GraceLimit() int
GraceLimit returns the number of initial orders allowed for a new user before the cancellation rate threshold is enforced.
func (*AuthManager) Inaction ¶
func (auth *AuthManager) Inaction(user account.AccountID, misstep NoActionStep, mmid db.MarketMatchID, matchValue uint64, refTime time.Time, oid order.OrderID)
Inaction registers an inaction violation by the user at the given step. The refTime is time to which the at-fault user's inaction deadline for the match is referenced. e.g. For a swap that failed in TakerSwapCast, refTime would be the maker's redeem time, which is recorded in the DB when the server validates the maker's redemption and informs the taker, and is roughly when the actor was first able to take the missed action. TODO: provide lots instead of value, or convert to lots somehow. But, Swapper has no clue about lot size, and neither does DB!
func (*AuthManager) MissedPreimage ¶
func (auth *AuthManager) MissedPreimage(user account.AccountID, epochEnd time.Time, oid order.OrderID)
MissedPreimage registers a missed preimage violation by the user.
func (*AuthManager) Notify ¶
func (auth *AuthManager) Notify(acctID account.AccountID, msg *msgjson.Message)
Notify sends a message to a client. The message should be a notification. See msgjson.NewNotification.
func (*AuthManager) Penalize ¶
func (auth *AuthManager) Penalize(user account.AccountID, lastRule account.Rule, extraDetails string)
Penalize unbooks all of their orders, and notifies them of this action while citing the provided rule that corresponds to their most recent infraction. This method is to be used when a user's tier drops below 1. NOTE: There is now a 'tierchange' route for *any* tier change, but this method still handles unbooking of the user's orders.
func (*AuthManager) PreimageSuccess ¶
func (auth *AuthManager) PreimageSuccess(user account.AccountID, epochEnd time.Time, oid order.OrderID)
PreimageSuccess registers an accepted preimage for the user.
func (*AuthManager) RecordCancel ¶
func (auth *AuthManager) RecordCancel(user account.AccountID, oid, target order.OrderID, epochGap int32, t time.Time)
RecordCancel records a user's executed cancel order, including the canceled order ID, and the time when the cancel was executed.
func (*AuthManager) RecordCompletedOrder ¶
func (auth *AuthManager) RecordCompletedOrder(user account.AccountID, oid order.OrderID, t time.Time)
RecordCompletedOrder records a user's completed order, where completed means a swap involving the order was successfully completed and the order is no longer on the books if it ever was.
func (*AuthManager) Request ¶
func (auth *AuthManager) Request(user account.AccountID, msg *msgjson.Message, f func(comms.Link, *msgjson.Message)) error
Request sends the Request-type msgjson.Message to the client identified by the specified account ID. The user must respond within DefaultRequestTimeout of the request. Late responses are not handled.
func (*AuthManager) RequestWithTimeout ¶
func (auth *AuthManager) RequestWithTimeout(user account.AccountID, msg *msgjson.Message, f func(comms.Link, *msgjson.Message), expireTimeout time.Duration, expire func()) error
RequestWithTimeout sends the Request-type msgjson.Message to the client identified by the specified account ID. If the user responds within expireTime of the request, the response handler is called, otherwise the expire function is called. If the response handler is called, it is guaranteed that the request Message.ID is equal to the response Message.ID (see handleResponse).
func (*AuthManager) Route ¶
func (auth *AuthManager) Route(route string, handler func(account.AccountID, *msgjson.Message) *msgjson.Error)
Route wraps the comms.Route function, storing the response handler with the associated clientInfo, and sending the message on the current comms.Link for the client.
func (*AuthManager) Run ¶
func (auth *AuthManager) Run(ctx context.Context)
Run runs the AuthManager until the context is canceled. Satisfies the dex.Runner interface.
func (*AuthManager) Send ¶
Send sends the non-Request-type msgjson.Message to the client identified by the specified account ID. The message is sent asynchronously, so an error is only generated if the specified user is not connected and authorized, if the message fails marshalling, or if the link is in a failing state. See dex/ws.(*WSLink).Send for more information.
func (*AuthManager) Sign ¶
func (auth *AuthManager) Sign(signables ...msgjson.Signable)
Sign signs the msgjson.Signables with the DEX private key.
func (*AuthManager) SignMsg ¶ added in v0.4.2
func (auth *AuthManager) SignMsg(msg []byte) []byte
SignMsg signs the message with the DEX private key, returning the DER encoded signature. SHA256 is used to hash the message before signing it.
func (*AuthManager) SwapSuccess ¶
func (auth *AuthManager) SwapSuccess(user account.AccountID, mmid db.MarketMatchID, value uint64, redeemTime time.Time)
SwapSuccess registers the successful completion of a swap by the given user. TODO: provide lots instead of value, or convert to lots somehow. But, Swapper has no clue about lot size, and neither does DB!
func (*AuthManager) UserMatchFails ¶ added in v1.0.0
func (*AuthManager) UserReputation ¶ added in v1.0.0
func (auth *AuthManager) UserReputation(user account.AccountID) (tier int64, score, maxScore int32, err error)
UserReputation calculates some quantities related to the user's reputation. UserReputation satisfies market.AuthManager.
type BondCoinChecker ¶ added in v0.6.0
type BondCoinChecker func(ctx context.Context, assetID uint32, ver uint16, coinID []byte) (amt, lockTime, confs int64, acct account.AccountID, err error)
BondCoinChecker is a function for locating an unspent bond, and extracting the amount, lockTime, and account ID. The confirmations of the bond transaction are also provided.
type BondTxParser ¶ added in v0.6.0
type BondTxParser func(assetID uint32, ver uint16, rawTx []byte) (bondCoinID []byte, amt int64, lockTime int64, acct account.AccountID, err error)
BondTxParser parses a dex fidelity bond transaction and the redeem script of the first output of the transaction, which must be the actual bond output. The returned account ID is from the second output. This will become a multi-asset checker.
NOTE: For DCR, and possibly all assets, the bond script is reconstructed from the null data output, and it is verified that the bond output pays to this script. As such, there is no provided bondData (redeem script for UTXO assets), but this may need for other assets.
type Config ¶
type Config struct { // Storage is an interface for storing and retrieving account-related info. Storage Storage // Signer is an interface that signs messages. In practice, Signer is // satisfied by a secp256k1.PrivateKey. Signer Signer Route func(route string, handler comms.MsgHandler) // BondExpiry is the time in seconds left until a bond's LockTime is reached // that defines when a bond is considered expired. BondExpiry uint64 // BondAssets indicates the supported bond assets and parameters. BondAssets map[string]*msgjson.BondAsset // BondTxParser performs rudimentary validation of a raw time-locked // fidelity bond transaction. e.g. dcr.ParseBondTx BondTxParser BondTxParser // BondChecker locates an unspent bond, and extracts the amount, lockTime, // and account ID, plus txn confirmations. BondChecker BondCoinChecker // TxDataSources are sources of tx data for a coin ID. TxDataSources map[uint32]TxDataSource // UserUnbooker is a function for unbooking all of a user's orders. UserUnbooker func(account.AccountID) // MiaUserTimeout is how long after a user disconnects until UserUnbooker is // called for that user. MiaUserTimeout time.Duration CancelThreshold float64 FreeCancels bool // PenaltyThreshold defines the score deficit at which a user's bond is // revoked. PenaltyThreshold uint32 }
Config is the configuration settings for the AuthManager, and the only argument to its constructor.
type FeeChecker ¶
type FeeChecker func(assetID uint32, coinID []byte) (addr string, val uint64, confs int64, err error)
FeeChecker is a function for retrieving the details for a fee payment txn.
type MatchOutcome ¶ added in v1.0.0
type MatchOutcome struct { ID dex.Bytes `json:"matchID"` Status string `json:"status"` Fail bool `json:"failed"` Stamp int64 `json:"stamp"` Value uint64 `json:"value"` BaseID uint32 `json:"baseID"` Quote uint32 `json:"quoteID"` }
MatchOutcome is a JSON-friendly version of db.MatchOutcome.
type NoActionStep ¶
type NoActionStep uint8
NoActionStep is the action that the user failed to take. This is used to define valid inputs to the Inaction method.
const ( SwapSuccess NoActionStep = iota // success included for accounting purposes NoSwapAsMaker NoSwapAsTaker NoRedeemAsMaker NoRedeemAsTaker )
func (NoActionStep) String ¶
func (step NoActionStep) String() string
String returns the description of the NoActionStep's corresponding Violation.
func (NoActionStep) Violation ¶
func (step NoActionStep) Violation() Violation
Violation returns the corresponding Violation for the misstep represented by the NoActionStep.
type Storage ¶
type Storage interface { // Account retrieves account info for the specified account ID and lock time // threshold, which determines when a bond is considered expired. Account(account.AccountID, time.Time) (acct *account.Account, bonds []*db.Bond) CreateAccountWithBond(acct *account.Account, bond *db.Bond) error AddBond(acct account.AccountID, bond *db.Bond) error DeleteBond(assetID uint32, coinID []byte) error FetchPrepaidBond(bondCoinID []byte) (strength uint32, lockTime int64, err error) DeletePrepaidBond(coinID []byte) error StorePrepaidBonds(coinIDs [][]byte, strength uint32, lockTime int64) error AccountInfo(aid account.AccountID) (*db.Account, error) UserOrderStatuses(aid account.AccountID, base, quote uint32, oids []order.OrderID) ([]*db.OrderStatus, error) ActiveUserOrderStatuses(aid account.AccountID) ([]*db.OrderStatus, error) CompletedUserOrders(aid account.AccountID, N int) (oids []order.OrderID, compTimes []int64, err error) ExecutedCancelsForUser(aid account.AccountID, N int) ([]*db.CancelRecord, error) CompletedAndAtFaultMatchStats(aid account.AccountID, lastN int) ([]*db.MatchOutcome, error) UserMatchFails(aid account.AccountID, lastN int) ([]*db.MatchFail, error) ForgiveMatchFail(mid order.MatchID) (bool, error) PreimageStats(user account.AccountID, lastN int) ([]*db.PreimageResult, error) AllActiveUserMatches(aid account.AccountID) ([]*db.MatchData, error) MatchStatuses(aid account.AccountID, base, quote uint32, matchIDs []order.MatchID) ([]*db.MatchStatus, error) }
Storage updates and fetches account-related data from what is presumably a database.
type TxDataSource ¶ added in v0.2.0
TxDataSource retrieves the raw transaction for a coin ID.
type Violation ¶
type Violation int32
Violation represents a specific infraction. For example, not broadcasting a swap contract transaction by the deadline as the maker.