domain

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2021 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FeeAccount = iota
	WalletAccount
	UnusedAccount1
	UnusedAccount2
	UnusedAccount3
	MarketAccountStart

	ExternalChain = 0
	InternalChain = 1

	MinMilliSatPerByte = 100

	StrategyTypePluggable  StrategyType = 0
	StrategyTypeBalanced   StrategyType = 1
	StrategyTypeUnbalanced StrategyType = 2
)
View Source
const (
	Empty = iota - 1
	Undefined
	Proposal
	Accepted
	Completed
	Settled
	Expired
)

Variables

View Source
var (
	// ErrMarketFeeTooLow ...
	ErrMarketFeeTooLow = errors.New("market fee too low, must be at least 1 bp (0.01%)")
	// ErrMarketFeeTooHigh ...
	ErrMarketFeeTooHigh = errors.New("market fee too high, must be at most 9999 bp (99,99%)")
	// ErrMarketMissingBaseAsset ...
	ErrMarketMissingBaseAsset = errors.New("base asset is missing")
	// ErrMarketMissingQuoteAsset ...
	ErrMarketMissingQuoteAsset = errors.New("quote asset is missing")
	// ErrMarketTooManyAssets ...
	ErrMarketTooManyAssets = errors.New(
		"It's not possible to determine the correct asset pair of the market " +
			"because more than 2 type of assets has been found in the outpoint list",
	)
	//ErrMarketNotFunded is thrown when a market requires being funded for a change
	ErrMarketNotFunded = errors.New("market must be funded")
	//ErrMarketIsClosed is thrown when a market requires being tradable for a change
	ErrMarketIsClosed = errors.New("market is closed")
	//ErrMarketMustBeClosed is thrown when a market requires being NOT tradable for a change
	ErrMarketMustBeClosed = errors.New("market must be closed")
	//ErrMarketNotPriced is thrown when the price is still 0 (ie. not initialized)
	ErrMarketNotPriced = errors.New("price must be inserted")
	//ErrMarketInvalidBasePrice is thrown when the amount for Base price is an invalid satoshis value.
	ErrMarketInvalidBasePrice = errors.New("the amount for base price is invalid")
	//ErrMarketInvalidQuotePrice is thrown when the amount for Quote price is an invalid satoshis value.
	ErrMarketInvalidQuotePrice = errors.New("the amount for base price is invalid")
	// ErrMarketInvalidBaseAsset is thrown when non valid base asset is given
	ErrMarketInvalidBaseAsset = errors.New("invalid base asset")
	// ErrMarketInvalidQuoteAsset is thrown when non valid quote asset is given
	ErrMarketInvalidQuoteAsset = errors.New("invalid quote asset")
	// ErrInvalidFixedFee ...
	ErrInvalidFixedFee = errors.New("fixed fee must be a positive value")
	// ErrMissingFixedFee ...
	ErrMissingFixedFee = errors.New("fixed fee requires both base and quote amounts to be defined")
)

Market errors

View Source
var (
	// ErrVaultMustBeLocked is thrown when trying to change the passphrase with an unlocked wallet
	ErrVaultMustBeLocked = errors.New("wallet must be locked to perform this operation")
	// ErrVaultMustBeUnlocked is thrown when trying to make an operation that requires the wallet to be unlocked
	ErrVaultMustBeUnlocked = errors.New("wallet must be unlocked to perform this operation")
	// ErrVaultInvalidPassphrase ...
	ErrVaultInvalidPassphrase = errors.New("passphrase is not valid")
	// ErrVaultAlreadyInitialized ...
	ErrVaultAlreadyInitialized = errors.New("vault is already initialized")
	// ErrVaultNullMnemonicOrPassphrase ...
	ErrVaultNullMnemonicOrPassphrase = errors.New("mnemonic and/or passphrase must not be null")
	// ErrVaultNullNetwork ...
	ErrVaultNullNetwork = errors.New("network must not be null")
	// ErrVaultAccountNotFound ...
	ErrVaultAccountNotFound = errors.New("account not found")
)

Vault errors

View Source
var (
	// ErrTradeMustBeEmpty ...
	ErrTradeMustBeEmpty = errors.New(
		"trade must be empty for parsing a proposal",
	)
	// ErrTradeMustBeProposal ...
	ErrTradeMustBeProposal = errors.New(
		"trade must be in proposal state for being accepted",
	)
	// ErrTradeMustBeAccepted ...
	ErrTradeMustBeAccepted = errors.New(
		"trade must be in accepted state for being completed",
	)
	// ErrTradeMustBeCompleted ...
	ErrTradeMustBeCompletedOrAccepted = errors.New(
		"trade must be in completed or accepted to be settled",
	)
	// ErrTradeExpirationDateNotReached ...
	ErrTradeExpirationDateNotReached = errors.New(
		"trade must have reached the expiration date to be set expired",
	)
	// ErrTradeExpired ...
	ErrTradeExpired = errors.New("trade has expired")
	// ErrTradeNullExpirationDate ...
	ErrTradeNullExpirationDate = errors.New(
		"trade must have an expiration date set to be set expired",
	)
)

Trade errors

View Source
var (
	// EmptyStatus represent the status of an empty trade.
	EmptyStatus = Status{
		Code: Empty,
	}
	// ProposalStatus represent the status of a trade presented by some trader to
	// the daemon and not yet processed.
	ProposalStatus = Status{
		Code: Proposal,
	}
	// ProposalRejectedStatus represents the status of a trade presented by some
	// trader to the daemon and rejected for some reason.
	ProposalRejectedStatus = Status{
		Code:   Proposal,
		Failed: true,
	}
	// AcceptedStatus represents the status of a trade proposal that has been
	// accepted by the daemon
	AcceptedStatus = Status{
		Code: Accepted,
	}
	// FailedToCompleteStatus represents the status of a trade that failed to be
	// be completed for some reason.
	FailedToCompleteStatus = Status{
		Code:   Accepted,
		Failed: true,
	}
	// CompletedStatus represents the status of a trade that has been completed
	// and accepted in mempool, waiting for being published on the blockchain.
	CompletedStatus = Status{
		Code: Completed,
	}
	// FailedToSettleStatus represents the status of a trade that failed to be
	// be settled for some reason.
	FailedToSettleStatus = Status{
		Code:   Completed,
		Failed: true,
	}
	// SettledStatus represents the status of a trade that has been settled,
	// meaning that has been included into the blockchain.
	SettledStatus = Status{
		Code: Settled,
	}
	// ExpiredStatus represents the status of a trade that has been expired,
	// meaning that it was at least accepted, but not settled within the
	// expiration time frame.
	ExpiredStatus = Status{
		Code:   Expired,
		Failed: true,
	}
)
View Source
var (
	// SwapParserManager ...
	SwapParserManager SwapParser
	// PsetParserManager ...
	PsetParserManager PsetParser
)
View Source
var (
	MnemonicStoreManager MnemonicStore
	EncrypterManager     Encrypter
)

MnemonicStore can be set externally by the user of the domain, assigning it to an instance of a IMnemonicStore implementation

View Source
var (
	// ErrInvalidAccount ...
	ErrInvalidAccount = errors.New("account index must be a positive integer number")
)

Account errors

View Source
var (
	// ErrUnspentAlreadyLocked ...
	ErrUnspentAlreadyLocked = errors.New("cannot lock an already locked unspent")
)

Unspent errors

Functions

This section is empty.

Types

type AcceptArgs added in v0.3.0

type AcceptArgs struct {
	RequestMessage     []byte
	Transaction        string
	InputBlindingKeys  map[string][]byte
	OutputBlindingKeys map[string][]byte
}

AcceptArgs ...

type Account

type Account struct {
	AccountIndex           int
	LastExternalIndex      int
	LastInternalIndex      int
	DerivationPathByScript map[string]string
}

Account defines the entity data struture for a derived account of the daemon's HD wallet

func NewAccount

func NewAccount(positiveAccountIndex int) (*Account, error)

NewAccount returns an empty Account instance

type AccountAndKey

type AccountAndKey struct {
	AccountIndex int
	BlindingKey  []byte
}

type AddressInfo

type AddressInfo struct {
	AccountIndex   int
	Address        string
	BlindingKey    []byte
	DerivationPath string
	Script         string
}

type AddressesInfo added in v0.3.0

type AddressesInfo []AddressInfo

func (AddressesInfo) Addresses added in v0.3.0

func (info AddressesInfo) Addresses() []string

func (AddressesInfo) AddressesAndKeys added in v0.3.0

func (info AddressesInfo) AddressesAndKeys() ([]string, [][]byte)

type CompleteResult

type CompleteResult struct {
	OK    bool
	TxHex string
	TxID  string
}

CompleteResult is return type of Complete method.

type Encrypter added in v0.3.0

type Encrypter interface {
	Encrypt(mnemonic, passphrase string) (string, error)
	Decrypt(encryptedMnemonic, passphrase string) (string, error)
}

Encrypter defines the required methods to override the default encryption performed through pkg/wallet package.

type FixedFee added in v0.3.10

type FixedFee struct {
	BaseFee  int64
	QuoteFee int64
}

type Market

type Market struct {
	// AccountIndex links a market to a HD wallet account derivation.
	AccountIndex int
	BaseAsset    string
	QuoteAsset   string
	// Each Market has a different fee expressed in basis point of each swap.
	Fee      int64
	FixedFee FixedFee
	// if curretly open for trades
	Tradable bool
	// Market Making strategy
	Strategy mm.MakingStrategy
	// Pluggable Price of the asset pair.
	Price Prices
}

Market defines the Market entity data structure for holding an asset pair state

func NewMarket

func NewMarket(positiveAccountIndex int, feeInBasisPoint int64) (*Market, error)

NewMarket returns an empty market with a reference to an account index. It is also mandatory to define a fee (in BP) for the market.

func (*Market) BaseAssetPrice

func (m *Market) BaseAssetPrice() decimal.Decimal

BaseAssetPrice returns the latest price for the base asset

func (*Market) ChangeBasePrice

func (m *Market) ChangeBasePrice(price decimal.Decimal) error

ChangeBasePrice ...

func (*Market) ChangeFeeBasisPoint added in v0.3.9

func (m *Market) ChangeFeeBasisPoint(fee int64) error

ChangeFeeBasisPoint ...

func (*Market) ChangeFixedFee added in v0.3.9

func (m *Market) ChangeFixedFee(baseFee, quoteFee int64) error

ChangeFixedFee ...

func (*Market) ChangeQuotePrice

func (m *Market) ChangeQuotePrice(price decimal.Decimal) error

ChangeQuotePrice ...

func (*Market) FundMarket

func (m *Market) FundMarket(fundingTxs []OutpointWithAsset, baseAssetHash string) error

FundMarket adds the assets of market from the given array of outpoints. Since the list of outpoints can contain an infinite number of utxos with different assets, they're fistly indexed by their asset, then the market's base asset is updated if found in the list, otherwise only the very first asset type is used as the market's quote asset, discarding the others that should be manually transferred to some other address because they won't be used by the daemon.

func (*Market) IsFunded

func (m *Market) IsFunded() bool

IsFunded method returns true if the market contains a non empty funding tx outpoint for each asset

func (*Market) IsStrategyPluggable

func (m *Market) IsStrategyPluggable() bool

IsStrategyPluggable returns true if the the startegy isn't automated.

func (*Market) IsStrategyPluggableInitialized

func (m *Market) IsStrategyPluggableInitialized() bool

IsStrategyPluggableInitialized returns true if the prices have been set.

func (*Market) IsTradable

func (m *Market) IsTradable() bool

IsTradable returns true if the market is available for trading

func (*Market) MakeNotTradable

func (m *Market) MakeNotTradable() error

MakeNotTradable ...

func (*Market) MakeStrategyBalanced

func (m *Market) MakeStrategyBalanced() error

MakeStrategyBalanced makes the current market using a balanced AMM formula 50/50

func (*Market) MakeStrategyPluggable

func (m *Market) MakeStrategyPluggable() error

MakeStrategyPluggable makes the current market using a given price (ie. set via UpdateMarketPrice rpc either manually or a price feed plugin)

func (*Market) MakeTradable

func (m *Market) MakeTradable() error

MakeTradable ...

func (*Market) QuoteAssetPrice

func (m *Market) QuoteAssetPrice() decimal.Decimal

QuoteAssetPrice returns the latest price for the quote asset

type MarketRepository

type MarketRepository interface {
	// Retrieves a market with the given account index. If not found, a new entry shall be created.
	GetOrCreateMarket(ctx context.Context, market *Market) (*Market, error)
	// Retrieves a market with a given account index.
	GetMarketByAccount(ctx context.Context, accountIndex int) (market *Market, err error)
	// Retrieves a market with a given a quote asset hash.
	GetMarketByAsset(ctx context.Context, quoteAsset string) (market *Market, accountIndex int, err error)
	// Retrieves the latest market sorted by account index
	GetLatestMarket(ctx context.Context) (market *Market, accountIndex int, err error)
	// Retrieves all the markets that are open for trading
	GetTradableMarkets(ctx context.Context) ([]Market, error)
	// Retrieves all the markets
	GetAllMarkets(ctx context.Context) ([]Market, error)
	// Updates the state of a market. In order to be flexible for many use case and to manage
	// at an higher level the possible errors, an update closure function shall be passed
	UpdateMarket(
		ctx context.Context,
		accountIndex int,
		updateFn func(m *Market) (*Market, error),
	) error
	// Open and close trading activities for a market with the given quote asset hash
	OpenMarket(ctx context.Context, quoteAsset string) error
	CloseMarket(ctx context.Context, quoteAsset string) error
	// Update only the price without touching market details
	UpdatePrices(ctx context.Context, accountIndex int, prices Prices) error
	// DeleteMarket deletes market for accountIndex
	DeleteMarket(ctx context.Context, accountIndex int) error
}

MarketRepository defines the abstraction for Market

type MnemonicStore added in v0.3.0

type MnemonicStore interface {
	Set(mnemonic string)
	Unset()
	IsSet() bool
	Get() []string
}

MnemonicStore defines the required methods to override the default storage of the plaintext mnemonic once Unlocking a Vault. At the moment this is achieved by storing the mnemonic in the in-memory pkg/config store. Soon this will be changed since this package shouldn't depend on config.

type OutpointWithAsset

type OutpointWithAsset struct {
	Asset string
	Txid  string
	Vout  int
}

OutpointWithAsset contains the transaction outpoint (tx hash and vout) along with the asset hash

type Prices

type Prices struct {
	// how much 1 base asset is valued in quote asset.
	BasePrice decimal.Decimal
	// how much 1 quote asset is valued in base asset
	QuotePrice decimal.Decimal
}

Prices ...

func (Prices) AreZero

func (p Prices) AreZero() bool

AreZero ...

func (Prices) IsZero

func (p Prices) IsZero() bool

IsZero ...

type PsetParser added in v0.3.0

type PsetParser interface {
	GetTxID(psetBase64 string) (string, error)
	GetTxHex(psetBase64 string) (string, error)
}

PsetParser defines the required methods to override the extraction of the txid and of the final transaction in hex format from the PSET one. The default one comes from go-elements.

type Status

type Status struct {
	Code   int
	Failed bool
}

Status represents the different statuses that a trade can assume.

type StrategyType

type StrategyType int32

StrategyType is the Market making strategy type

type Swap

type Swap struct {
	ID        string
	Message   []byte
	Timestamp uint64
}

Swap is the data structure that represents any of the above swaps.

func (Swap) IsZero added in v0.3.0

func (s Swap) IsZero() bool

IsZero ...

type SwapAccept added in v0.3.0

type SwapAccept interface {
	GetId() string
	GetRequestId() string
	GetTransaction() string
	GetInputBlindingKey() map[string][]byte
	GetOutputBlindingKey() map[string][]byte
}

SwapAccept is the abstracted representation of a SwapAccept message.

type SwapComplete added in v0.3.0

type SwapComplete interface {
	GetId() string
	GetAcceptId() string
	GetTransaction() string
}

SwapComplete is the abstracted representation of a SwapComplete message.

type SwapError added in v0.3.0

type SwapError struct {
	Err  error
	Code int
}

SwapError is the special error returned by the ISwapParser when serializing a swap message.

func (*SwapError) Error added in v0.3.0

func (s *SwapError) Error() string

type SwapFail added in v0.3.0

type SwapFail interface {
	GetId() string
	GetMessageId() string
	GetFailureCode() uint32
	GetFailureMessage() string
}

SwapFail is the abstracted representation of a SwapFail message.

type SwapParser added in v0.3.0

type SwapParser interface {
	SerializeRequest(r SwapRequest) ([]byte, *SwapError)
	SerializeAccept(args AcceptArgs) (string, []byte, *SwapError)
	SerializeComplete(accMsg []byte, tx string) (string, []byte, *SwapError)
	SerializeFail(id string, code int, msg string) (string, []byte)

	DeserializeRequest(msg []byte) (SwapRequest, error)
	DeserializeAccept(msg []byte) (SwapAccept, error)
	DeserializeComplete(msg []byte) (SwapComplete, error)
	DeserializeFail(msg []byte) (SwapFail, error)
}

SwapParser defines the required methods to override the default swap message parser, which is grpc-proto.

type SwapRequest added in v0.3.0

type SwapRequest interface {
	GetId() string
	GetAssetP() string
	GetAmountP() uint64
	GetAssetR() string
	GetAmountR() uint64
	GetTransaction() string
	GetInputBlindingKey() map[string][]byte
	GetOutputBlindingKey() map[string][]byte
}

SwapRequest is the abstracted representation of a SwapRequest message.

type Trade

type Trade struct {
	ID                  uuid.UUID
	MarketQuoteAsset    string
	MarketPrice         Prices
	MarketFee           int64
	MarketFixedBaseFee  int64
	MarketFixedQuoteFee int64
	TraderPubkey        []byte
	Status              Status
	PsetBase64          string
	TxID                string
	TxHex               string
	ExpiryTime          uint64
	SettlementTime      uint64
	SwapRequest         Swap
	SwapAccept          Swap
	SwapComplete        Swap
	SwapFail            Swap
}

Trade is the data structure representing a trade entity.

func NewTrade

func NewTrade() *Trade

NewTrade returns a trade with a new id and Empty status.

func (*Trade) Accept

func (t *Trade) Accept(
	psetBase64 string,
	inputBlindingKeys,
	outputBlindingKeys map[string][]byte,
	expiryDuration uint64,
) (bool, error)

Accept brings a trade from the Proposal to the Accepted status by validating the provided arguemtn against the the SwapRequest message and sets its expiration time.

func (*Trade) Complete

func (t *Trade) Complete(tx string) (*CompleteResult, error)

Complete brings a trade from the Accepted to the Completed status by checiking that the given PSET completes the one of the SwapAccept message and by finalizing it and extracting the raw tx in hex format. Complete must be called before the trade expires, otherwise it won't be possible to actually complete an accepted trade.

func (*Trade) ContainsSwap

func (t *Trade) ContainsSwap(swapID string) bool

ContainsSwap returns whether a swap identified by its id belongs to the current trade.

func (*Trade) Expire added in v0.3.0

func (t *Trade) Expire() (bool, error)

Expire brings the trade to the Expired status if its expiration date was previosly set. This infers that it must be in any of the Accepted, Completed, or related failed statuses. This method makes also sure that the expiration date has passed before changing the status.

func (*Trade) Fail

func (t *Trade) Fail(swapID string, errCode int, errMsg string)

Fail marks the current status of the trade as Failed and adds the SwapFail message.

func (*Trade) IsAccepted

func (t *Trade) IsAccepted() bool

IsAccepted returns whether the trade is in Accepted status.

func (*Trade) IsCompleted

func (t *Trade) IsCompleted() bool

IsCompleted returns whether the trade is in Completed status.

func (*Trade) IsEmpty

func (t *Trade) IsEmpty() bool

IsEmpty returns whether the Trade is empty.

func (*Trade) IsExpired

func (t *Trade) IsExpired() bool

IsExpired returns whether the trade has is in Expired status, or if its expiration date has passed.

func (*Trade) IsProposal

func (t *Trade) IsProposal() bool

IsProposal returns whether the trade is in Proposal status.

func (*Trade) IsRejected

func (t *Trade) IsRejected() bool

IsRejected returns whether the trade has failed.

func (*Trade) IsSettled added in v0.3.0

func (t *Trade) IsSettled() bool

IsSettled returns whether the trade is in Settled status.

func (*Trade) Propose

func (t *Trade) Propose(
	swapRequest SwapRequest,
	marketQuoteAsset string,
	marketFee, fixedBaseFee, fixedQuoteFee int64,
	traderPubkey []byte,
) (bool, error)

Propose brings an Empty trade to the Propose status by first validating the provided arguments.

func (*Trade) Settle added in v0.1.2

func (t *Trade) Settle(settlementTime uint64) (bool, error)

Settle brings the trade from the Completed to the Settled status, unsets the expiration time and adds the timestamp of the settlement (it must be a blocktime).

func (*Trade) SwapAcceptMessage

func (t *Trade) SwapAcceptMessage() SwapAccept

SwapAcceptMessage returns the deserialized swap accept message, if defined.

func (*Trade) SwapCompleteMessage

func (t *Trade) SwapCompleteMessage() SwapComplete

SwapCompleteMessage returns the deserialized swap complete message, if defined.

func (*Trade) SwapFailMessage

func (t *Trade) SwapFailMessage() SwapFail

SwapFailMessage returns the deserialized swap fail message, if defined.

func (*Trade) SwapRequestMessage

func (t *Trade) SwapRequestMessage() SwapRequest

SwapRequestMessage returns the deserialized swap request message.

type TradeRepository

type TradeRepository interface {
	// // GetOrCreateVault returns the trade with the given tradeID, or create a
	// new empty one if not found.
	GetOrCreateTrade(ctx context.Context, tradeID *uuid.UUID) (*Trade, error)
	// GetAllTrades returns all the trades stored in the repository.
	GetAllTrades(ctx context.Context) ([]*Trade, error)
	// GetAllTradesByMarket returns all the trades filtered by a market
	// identified by its quote asset.
	GetAllTradesByMarket(ctx context.Context, marketQuoteAsset string) ([]*Trade, error)
	// GetCompletedTradesByMarket returns all the Completed or Settled trades
	// for the provided market identified by its quote asset.
	GetCompletedTradesByMarket(ctx context.Context, marketQuoteAsset string) ([]*Trade, error)
	// GetTradeBySwapAcceptID returns the trade that contains the SwapAccept
	// message matching the given id.
	GetTradeBySwapAcceptID(ctx context.Context, swapAcceptID string) (*Trade, error)
	// GetTradeByTxID returns the trade which transaction matches the given
	// transaction id.
	GetTradeByTxID(ctx context.Context, txID string) (*Trade, error)
	// UpdateTrade allowa to commit multiple changes to the same trade in a
	// transactional way.
	UpdateTrade(
		ctx context.Context,
		tradeID *uuid.UUID,
		updateFn func(t *Trade) (*Trade, error),
	) error
}

TradeRepository is the abstraction for any kind of database intended to persist Trades.

type Unspent

type Unspent struct {
	TxID            string
	VOut            uint32
	Value           uint64
	AssetHash       string
	ValueCommitment string
	AssetCommitment string
	ValueBlinder    []byte
	AssetBlinder    []byte
	ScriptPubKey    []byte
	Nonce           []byte
	RangeProof      []byte
	SurjectionProof []byte
	Address         string
	Spent           bool
	Locked          bool
	LockedBy        *uuid.UUID
	Confirmed       bool
}

Unspent is the data structure representing an Elements based UTXO with some other information like whether it is spent/unspent, confirmed/unconfirmed or locked/unlocked.

func (*Unspent) Confirm

func (u *Unspent) Confirm()

Confirm marks the unspents as confirmed.

func (*Unspent) IsConfirmed

func (u *Unspent) IsConfirmed() bool

IsConfirmed returns whether the unspent is already confirmed.

func (*Unspent) IsKeyEqual

func (u *Unspent) IsKeyEqual(key UnspentKey) bool

IsKeyEqual returns whether the provided UnspentKey matches that or the current unspent.

func (*Unspent) IsLocked

func (u *Unspent) IsLocked() bool

IsLocked returns whether the unspent is already locked - used in some not yet broadcasted trade.

func (*Unspent) IsSpent

func (u *Unspent) IsSpent() bool

IsSpent returns whether the unspent is already spent.

func (*Unspent) Key

func (u *Unspent) Key() UnspentKey

Key returns the UnspentKey of the current unspent.

func (*Unspent) Lock

func (u *Unspent) Lock(tradeID *uuid.UUID) error

Lock marks the current unspent as locked, referring to some trade by its UUID.

func (*Unspent) Spend

func (u *Unspent) Spend()

Spend marks the unspents as spent.

func (*Unspent) ToOutpointWithAsset added in v0.3.0

func (u *Unspent) ToOutpointWithAsset() OutpointWithAsset

func (*Unspent) ToUtxo

func (u *Unspent) ToUtxo() explorer.Utxo

ToUtxo returns the current unpsent as an explorer.Utxo interface

func (*Unspent) Unlock added in v0.3.0

func (u *Unspent) Unlock()

Unlock marks the current locked unspent as unlocked.

type UnspentKey

type UnspentKey struct {
	TxID string
	VOut uint32
}

UnspentKey represent the ID of an Unspent, composed by its txid and vout.

type UnspentRepository

type UnspentRepository interface {
	// AddUnspents adds the provided unspents to the repository. Those already
	// existing won't be re-added
	AddUnspents(ctx context.Context, unspents []Unspent) error
	// GetAllUnspents returns the entire UTXO set, included those locked or
	// already spent.
	GetAllUnspents(ctx context.Context) []Unspent
	// GetAvailableUnspents returns all unlocked unspent UTXOs.
	GetAvailableUnspents(ctx context.Context) ([]Unspent, error)
	// GetAllUnspentsForAddresses returns the entire UTXO set (locked and spent
	// included) for the provided list of addresses.
	GetAllUnspentsForAddresses(ctx context.Context, addresses []string) ([]Unspent, error)
	// GetUnspentsForAddresses returns the list of all unspent UTXOs for the
	// provided list of address (locked unspents included).
	GetUnspentsForAddresses(ctx context.Context, addresses []string) ([]Unspent, error)
	// GetAvailableUnspentsForAddresses returns the list of spendable UTXOs for the
	// provided list of addresses (locked unspents excluded).
	GetAvailableUnspentsForAddresses(ctx context.Context, addresses []string) ([]Unspent, error)
	// GetUnspentWithKey returns all the info about an UTXO, if existing in the
	// repository.
	GetUnspentWithKey(ctx context.Context, unspentKey UnspentKey) (*Unspent, error)
	// GetBalance returns the current balance of a certain asset for the provided
	// list of addresses (locked unspents included)
	GetBalance(ctx context.Context, addresses []string, assetHash string) (uint64, error)
	// GetUnlockedBalance returns the current balance of a certain asset for the
	// provided list of addresses (locked unspents exlcuded).
	GetUnlockedBalance(ctx context.Context, addresses []string, assetHash string) (uint64, error)
	// SpendUnspents let mark the provided list of unspent UTXOs (identified by their
	// keys) as spent.
	SpendUnspents(ctx context.Context, unspentKeys []UnspentKey) (int, error)
	// ConfirmUnspents let mark the provided list of unconfirmed unspent UTXOs as
	// confirmed.
	ConfirmUnspents(ctx context.Context, unspentKeys []UnspentKey) (int, error)
	// LockUnspents let lock the provided list of unlocked, unspent UTXOs,
	// referring to a certain trade by its UUID.
	LockUnspents(ctx context.Context, unspentKeys []UnspentKey, tradeID uuid.UUID) (int, error)
	// UnlockUnspents let unlock the provided list of locked, unspent UTXOs.
	UnlockUnspents(ctx context.Context, unspentKeys []UnspentKey) (int, error)
}

UnspentRepository is the abstraction for any kind of database intended to persist Unspents.

type Vault

type Vault struct {
	EncryptedMnemonic      string
	PassphraseHash         []byte
	Accounts               map[int]*Account
	AccountAndKeyByAddress map[string]AccountAndKey
	Network                *network.Network
}

func NewVault

func NewVault(mnemonic []string, passphrase string, net *network.Network) (*Vault, error)

NewVault encrypts the provided mnemonic with the passhrase and returns a new Vault initialized with the encrypted mnemonic and the hash of the passphrase. The Vault is locked by default since it is initialized without the mnemonic in plain text

func (*Vault) AccountByAddress

func (v *Vault) AccountByAddress(addr string) (*Account, int, error)

AccountByAddress returns the account to which the provided address belongs

func (*Vault) AccountByIndex

func (v *Vault) AccountByIndex(accountIndex int) (*Account, error)

AccountByIndex returns the account with the given index

func (*Vault) AllDerivedAddressesInfo

func (v *Vault) AllDerivedAddressesInfo() AddressesInfo

AllDerivedAddressesInfo returns the info of all the external and internal addresses derived by the daemon. This method does not require the Vault to be unlocked since it does not make use of the mnemonic in plain text. The info returned for each address are the account index, the derivation path, and the private blinding key.

func (*Vault) AllDerivedAddressesInfoForAccount added in v0.3.0

func (v *Vault) AllDerivedAddressesInfoForAccount(
	accountIndex int,
) (AddressesInfo, error)

AllDerivedAddressesInfoForAccount returns info about all the external and internal addresses derived for the provided account.

func (*Vault) AllDerivedExternalAddressesInfoForAccount added in v0.3.0

func (v *Vault) AllDerivedExternalAddressesInfoForAccount(
	accountIndex int,
) (AddressesInfo, error)

AllDerivedExternalAddressesInfoForAccount returns info about all external addresses derived for the provided account.

func (*Vault) ChangePassphrase

func (v *Vault) ChangePassphrase(currentPassphrase, newPassphrase string) error

ChangePassphrase attempts to unlock the

func (*Vault) DeriveNextExternalAddressForAccount

func (v *Vault) DeriveNextExternalAddressForAccount(accountIndex int) (*AddressInfo, error)

DeriveNextExternalAddressForAccount returns the next unused address, the corresponding output script, the blinding key.

func (*Vault) DeriveNextInternalAddressForAccount

func (v *Vault) DeriveNextInternalAddressForAccount(accountIndex int) (*AddressInfo, error)

DeriveNextInternalAddressForAccount returns the next unused change address for the provided account and the corresponding output script

func (*Vault) GetMnemonicSafe

func (v *Vault) GetMnemonicSafe() ([]string, error)

GetMnemonicSafe is getter for Vault's mnemonic in plain text

func (*Vault) InitAccount

func (v *Vault) InitAccount(accountIndex int)

InitAccount creates a new account in the current Vault if not existing

func (*Vault) IsInitialized added in v0.3.0

func (v *Vault) IsInitialized() bool

IsInitialized returnes whether the Vault has been inizitialized

func (*Vault) IsLocked added in v0.3.0

func (v *Vault) IsLocked() bool

IsLocked returns whether the Vault is initialized and locked

func (*Vault) IsZero

func (v *Vault) IsZero() bool

IsZero returns whether the Vault is initialized without holding any data

func (*Vault) Lock

func (v *Vault) Lock()

Lock locks the Vault by wiping its mnemonic field

func (*Vault) Unlock

func (v *Vault) Unlock(passphrase string) error

Unlock attempts to decrypt the mnemonic with the provided passphrase

type VaultRepository

type VaultRepository interface {
	// GetOrCreateVault returns the Vault stored in the repo. If not yet created,
	// a new one is created the provided mnemonic, passphrase, and network.
	GetOrCreateVault(
		ctx context.Context,
		mnemonic []string,
		passphrase string,
		network *network.Network,
	) (*Vault, error)
	// GetAccountByIndex returns the account with the given index, if it
	// exists.
	GetAccountByIndex(ctx context.Context, accountIndex int) (*Account, error)
	// GetAccountByAddress returns the account with the given index, if it
	// exists.
	GetAccountByAddress(ctx context.Context, addr string) (*Account, int, error)
	// GetAllDerivedAddressesInfoForAccount returns the list of info about all
	// external and internal (change) addresses derived for the provided account.
	GetAllDerivedAddressesInfoForAccount(
		ctx context.Context,
		accountIndex int,
	) (AddressesInfo, error)
	// GetDerivationPathByScript returns the derivation paths for the given account
	// index and the given list of scripts.
	GetDerivationPathByScript(
		ctx context.Context,
		accountIndex int,
		scripts []string,
	) (map[string]string, error)
	// GetAllDerivedExternalAddressesInfoForAccount returns info about all receiving
	// addresses derived for the provided account so far.
	GetAllDerivedExternalAddressesInfoForAccount(
		ctx context.Context,
		accountIndex int,
	) (AddressesInfo, error)
	// UpdateVault is the method allowing to make multiple changes to a vault in
	// a transactional way.
	UpdateVault(
		ctx context.Context,
		updateFn func(v *Vault) (*Vault, error),
	) error
}

VaultRepository is the abstraction for any kind of database intended to persist a Vault.

Jump to

Keyboard shortcuts

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