auth

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2023 License: BlueOak-1.0.0 Imports: 22 Imported by: 1

Documentation

Index

Constants

View Source
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.

Variables

View Source
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.

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

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) 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) ComputeUserTier added in v0.6.0

func (auth *AuthManager) ComputeUserTier(user account.AccountID) (tier, bondTier int64)

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) 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

func (auth *AuthManager) Send(user account.AccountID, msg *msgjson.Message) error

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) UserScore added in v0.6.0

func (auth *AuthManager) UserScore(user account.AccountID) (score int32)

func (*AuthManager) UserSettlingLimit added in v0.2.0

func (auth *AuthManager) UserSettlingLimit(user account.AccountID, mkt *dex.MarketInfo) int64

UserSettlingLimit returns a user's settling amount limit for the given market in units of the base asset. The limit may be negative for accounts with poor swap history. The user must be connected.

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

	// 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

	// FeeAddress retrieves a fresh registration fee address for an asset. It
	// should return an empty string for an unsupported asset.
	FeeAddress func(assetID uint32) string
	// FeeAssets specifies the registration fee parameters for assets supported
	// for registration.
	FeeAssets map[string]*msgjson.FeeAsset
	// FeeChecker is a method for getting the registration fee output info.
	FeeChecker FeeChecker

	// 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
	// BanScore defines the penalty score when an account gets closed.
	BanScore uint32

	// InitTakerLotLimit is the number of lots per-market a new user is
	// permitted to have in active orders and swaps.
	InitTakerLotLimit uint32
	// AbsTakerLotLimit is a cap on the per-market taker lot limit regardless of
	// how good the user's swap history is.
	AbsTakerLotLimit 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 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 Signer

type Signer interface {
	Sign(hash []byte) *ecdsa.Signature
	PubKey() *secp256k1.PublicKey
}

Signer signs messages. The message must be a 32-byte hash.

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, legacy, legacyPaid bool)

	CreateAccountWithBond(acct *account.Account, bond *db.Bond) error
	AddBond(acct account.AccountID, bond *db.Bond) error
	DeleteBond(assetID uint32, coinID []byte) error

	CreateAccount(acct *account.Account, feeAsset uint32, feeAddr string) error // DEPRECATED
	AccountRegAddr(account.AccountID) (addr string, asset uint32, err error)    // DEPRECATED
	PayAccount(account.AccountID, []byte) error                                 // DEPRECATED

	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)
	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 SwapAmounts

type SwapAmounts struct {
	Swapped    int64
	StuckLong  int64
	StuckShort int64
	Spoofed    int64
}

SwapAmounts breaks down the quantities of completed swaps in four rough categories: successfully swapped (Swapped), failed with counterparty funds locked for the long/maker lock time (StuckLong), failed with counterparty funds locked for the short/taker lock time (StuckShort), and failed to initiate swap following match with no funds locked in contracts (Spoofed).

type TxDataSource added in v0.2.0

type TxDataSource func(coinID []byte) (rawTx []byte, err error)

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.

const (
	ViolationInvalid Violation = iota - 2
	ViolationForgiven
	ViolationSwapSuccess
	ViolationPreimageMiss
	ViolationNoSwapAsMaker
	ViolationNoSwapAsTaker
	ViolationNoRedeemAsMaker
	ViolationNoRedeemAsTaker
	ViolationCancelRate
)

func (Violation) Score

func (v Violation) Score() int32

Score returns the Violation's score, which is a representation of the relative severity of the infraction.

func (Violation) String

func (v Violation) String() string

String returns a description of the Violation.

Jump to

Keyboard shortcuts

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