pool

package module
v0.6.4-beta Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2023 License: MIT Imports: 69 Imported by: 2

README

Lightning Pool

Lightning Pool is a non-custodial, peer-to-peer marketplace that allows node operators that need inbound liquidity to pay node operators with available capital to open channels in their direction while retaining full custody of their funds. Pool’s first product is a Lightning Channel Lease - an inbound channel with a pre-agreed duration.

Efficient capital allocation is one of the most widely felt pain points when using the Lightning Network. Existing node operators do not have access to pricing signals to help determine where in the network their outbound liquidity should be allocated, and new node operators have no way to signal that they need new inbound liquidity. Lightning Pool brings these two sides together into a single market while allowing them to maintain custody of their funds.

Checkout our documentation to learn more. For more technical details, check out the technical white paper.

How it works

Lightning Pool is a non-custodial auction for liquidity where bids are kept private and trades clear periodically. Key aspects of Pool include:

  • Periodic clearing - Market does not clear continuously, instead, it clears every block (or after multiple blocks, if there are no bids that match with existing asks).

  • Non-custodial - Clients maintain an on-chain account that is a timelocked, 2-of-2 multisig with the auctioneer. These funds are fully in the user’s control at all times.

  • Sealed-bid - All orders are submitted off-chain to the auctioneer, so bidders don’t have visibility into the bids of other participants

  • Uniform clearing price - All participants in a batch clear at the same price. If your ask is for 2% annualized interest, you will receive >=2%. If you bid 5%, you will pay <=5%.

  • Batched execution - Due to the account structure, the auctioneer is able to batch all completed orders into a single transaction, greatly reducing individual chain fees.

Installation

Download the latest binaries from the releases page.

LND

Note that Pool requires lnd to be built with all of its subservers and requires running at least v0.15.4. Download the latest official release binary or build lnd from source by following the installation instructions. If you choose to build lnd from source, use the following command to enable all the relevant subservers:

make install tags="signrpc walletrpc chainrpc invoicesrpc"

Usage

Read our quickstart guide to learn more about how to use Pool.

Marketplace Fee

Fees are calculated based on the amount of liquidity purchased. During the mainnet alpha, fees will range from 5-25 basis points of the matched amount.

Development

The Pool client is currently in early alpha and offers a simple command line application.

The Pool daemon exposes a gRPC API and REST API.

Troubleshooting

Join us on Slack and we'd be happy to help in any way we can. In the meantime please see our FAQs.

Build from source

If you’d prefer to compile from source code, you’ll need at least go 1.18 and make.

Run the following commands to download the code, compile and install Pool:

$ git clone https://github.com/lightninglabs/pool
$ cd pool
$ make install

This will install the binaries into your $GOPATH/bin directory.

Compatibility

Lightning Pool requires lnd version 0.15.4-beta or higher (v0.16.0-beta or later is recommended).

Documentation

Overview

As this file is very similar in every package, ignore the linter here. nolint:dupl,interfacer

Package pool is a generated GoMock package.

Index

Constants

View Source
const (
	MainnetServer = "pool.lightning.finance:12010"
	TestnetServer = "test.pool.lightning.finance:12010"
)
View Source
const Subsystem = "POOL"

Variables

View Source
var (
	// DefaultBaseDir is the default root data directory where pool will
	// store all its data. On UNIX like systems this will resolve to
	// ~/.pool. Below this directory the logs and network directory will be
	// created.
	DefaultBaseDir = btcutil.AppDataDir("pool", false)

	// DefaultNetwork is the default bitcoin network pool runs on.
	DefaultNetwork = "mainnet"

	// DefaultLogFilename is the default name that is given to the pool log
	// file.
	DefaultLogFilename = "poold.log"

	// DefaultTLSCertFilename is the default file name for the autogenerated
	// TLS certificate.
	DefaultTLSCertFilename = "tls.cert"

	// DefaultTLSKeyFilename is the default file name for the autogenerated
	// TLS key.
	DefaultTLSKeyFilename = "tls.key"

	// DefaultTLSCertPath is the default full path of the autogenerated TLS
	// certificate.
	DefaultTLSCertPath = filepath.Join(
		DefaultBaseDir, DefaultNetwork, DefaultTLSCertFilename,
	)

	// DefaultTLSKeyPath is the default full path of the autogenerated TLS
	// key.
	DefaultTLSKeyPath = filepath.Join(
		DefaultBaseDir, DefaultNetwork, DefaultTLSKeyFilename,
	)

	// DefaultMacaroonFilename is the default file name for the
	// autogenerated pool macaroon.
	DefaultMacaroonFilename = "pool.macaroon"

	// DefaultMacaroonPath is the default full path of the base pool
	// macaroon.
	DefaultMacaroonPath = filepath.Join(
		DefaultBaseDir, DefaultNetwork, DefaultMacaroonFilename,
	)

	// DefaultLndDir is the default location where we look for lnd's tls and
	// macaroon files.
	DefaultLndDir = btcutil.AppDataDir("lnd", false)

	// DefaultLndMacaroonPath is the default location where we look for a
	// macaroon to use when connecting to lnd.
	DefaultLndMacaroonPath = filepath.Join(
		DefaultLndDir, "data", "chain", "bitcoin", DefaultNetwork,
		defaultLndMacaroon,
	)

	// DefaultAutogenValidity is the default validity of a self-signed
	// certificate. The value corresponds to 14 months
	// (14 months * 30 days * 24 hours).
	DefaultAutogenValidity = 14 * 30 * 24 * time.Hour
)
View Source
var Commit string

Commit stores the current commit hash of this build, this should be set using the -ldflags during compilation.

Functions

func ContextWithInitiator

func ContextWithInitiator(ctx context.Context,
	initiator string) context.Context

ContextWithInitiator creates a new context with the given initiator string added (provided it is not empty).

func DBOrderStateToRPCState

func DBOrderStateToRPCState(state order.State) (auctioneerrpc.OrderState,
	error)

DBOrderStateToRPCState maps the order state as stored in the database to the corresponding RPC enum type.

func InitiatorFromContext

func InitiatorFromContext(ctx context.Context) string

InitiatorFromContext attempts to read the initiator string from a context and returns it if successful. If no initiator string can be found then the empty string is returned.

func MarshallAccount

func MarshallAccount(a *account.Account) (*poolrpc.Account, error)

MarshallAccount returns the RPC representation of an account.

func NewMarshaler

func NewMarshaler(cfg *marshalerConfig) *marshaler

NewMarshaler returns an internal type that implements the Marshaler interface.

func Run

func Run(cfg *Config) error

Run starts the trader daemon and blocks until it's shut down again.

func SetAgentName

func SetAgentName(newAgentName string)

SetAgentName overwrites the default agent name which can be used to identify the software Pool is bundled in (for example LiT). This function panics if the agent name contains characters outside of the allowed semantic alphabet.

func SetupLoggers

func SetupLoggers(root *build.RotatingLogWriter, intercept signal.Interceptor)

SetupLoggers initializes all package-global logger variables.

func UserAgent

func UserAgent(initiator string) string

UserAgent returns the full user agent string that identifies the software that is submitting swaps to the loop server.

func Validate

func Validate(cfg *Config) error

Validate cleans up paths in the config provided and validates it.

func Version

func Version() string

Version returns the application version as a properly formed string per the semantic versioning 2.0.0 spec (http://semver.org/) and the commit it was built on.

Types

type AutoAcceptorConfig

type AutoAcceptorConfig struct {
	// Provider denotes if the negotiator is the provider or not.
	Provider bool

	// ProviderBid is the provider's bid template.
	ProviderBid *order.Bid

	// ProviderAccount points to the active account of the provider of the
	// ticket.
	ProviderAccount *account.Account

	// StartingPkt is the starting packet, or the starting state from the
	// PoV of the negotiator.
	StartingPkt *SidecarPacket

	// Drive contains functionality needed to drive a new sidecar ticket
	// towards completion.
	Driver SidecarDriver

	// MailBox is used to allow negotiators to send messages back and forth
	// to each other.
	MailBox MailBox
}

AutoAcceptorConfig houses all the functionality the sidecar negotiator needs to carry out its duties.

type ChannelAcceptor

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

ChannelAcceptor is a type that adds an RPC level interceptor for accepting channels in lnd. Its main task is to validate the self channel balance (or as it's known in the LN lingo: push amount) of incoming channels against the expected (and paid for!) amount in the order.

func NewChannelAcceptor

func NewChannelAcceptor(lightning lndclient.LightningClient) *ChannelAcceptor

NewChannelAcceptor creates a new channel acceptor with the given lnd client.

func (*ChannelAcceptor) ShimRegistered

func (s *ChannelAcceptor) ShimRegistered(bid *order.Bid, pid [32]byte)

ShimRegistered is a function that should be called whenever a funding shim is created for a bid order where we expect an incoming channel at any moment.

func (*ChannelAcceptor) ShimRemoved

func (s *ChannelAcceptor) ShimRemoved(bid *order.Bid)

ShimRemoved is a function that should be called whenever a funding shim is cleaned up and we no longer expect an incoming channel for it.

func (*ChannelAcceptor) Start

func (s *ChannelAcceptor) Start(errChan chan error) error

Start starts the channel acceptor and subscribes to receive all incoming channel events of lnd.

func (*ChannelAcceptor) Stop

func (s *ChannelAcceptor) Stop()

Stop shuts down the channel acceptor.

type Config

type Config struct {
	ShowVersion    bool   `long:"version" description:"Display version information and exit"`
	Insecure       bool   `long:"insecure" description:"disable tls"`
	Network        string `long:"network" description:"network to run on" choice:"regtest" choice:"testnet" choice:"mainnet" choice:"simnet"`
	AuctionServer  string `long:"auctionserver" description:"auction server address host:port"`
	Proxy          string `` /* 131-byte string literal not displayed */
	TLSPathAuctSrv string `long:"tlspathauctserver" description:"Path to auction server tls certificate"`
	RPCListen      string `long:"rpclisten" description:"Address to listen on for gRPC clients"`
	RESTListen     string `long:"restlisten" description:"Address to listen on for REST clients"`
	BaseDir        string `` /* 168-byte string literal not displayed */

	LogDir         string `long:"logdir" description:"Directory to log output."`
	MaxLogFiles    int    `long:"maxlogfiles" description:"Maximum logfiles to keep (0 for no rotation)"`
	MaxLogFileSize int    `long:"maxlogfilesize" description:"Maximum logfile size in MB"`

	MinBackoff time.Duration `long:"minbackoff" description:"Shortest backoff when reconnecting to the server. Valid time units are {s, m, h}."`
	MaxBackoff time.Duration `long:"maxbackoff" description:"Longest backoff when reconnecting to the server. Valid time units are {s, m, h}."`
	DebugLevel string        `` /* 265-byte string literal not displayed */

	TLSCertPath        string   `long:"tlscertpath" description:"Path to write the TLS certificate for pool's RPC and REST services."`
	TLSKeyPath         string   `long:"tlskeypath" description:"Path to write the TLS private key for pool's RPC and REST services."`
	TLSExtraIPs        []string `long:"tlsextraip" description:"Adds an extra IP to the generated certificate."`
	TLSExtraDomains    []string `long:"tlsextradomain" description:"Adds an extra domain to the generated certificate."`
	TLSAutoRefresh     bool     `long:"tlsautorefresh" description:"Re-generate TLS certificate and key if the IPs or domains are changed."`
	TLSDisableAutofill bool     `` /* 174-byte string literal not displayed */

	MacaroonPath string `long:"macaroonpath" description:"Path to write the macaroon for pool's RPC and REST services if it doesn't exist."`

	NewNodesOnly bool `` /* 145-byte string literal not displayed */

	LsatMaxRoutingFee btcutil.Amount `` /* 194-byte string literal not displayed */

	Profile  string `long:"profile" description:"Enable HTTP profiling on given ip:port -- NOTE port must be between 1024 and 65535"`
	FakeAuth bool   `` /* 145-byte string literal not displayed */

	TxLabelPrefix string `` /* 140-byte string literal not displayed */

	Lnd *LndConfig `group:"lnd" namespace:"lnd"`

	// RPCListener is a network listener that can be set if poold should be
	// used as a library and listen on the given listener instead of what is
	// configured in the --rpclisten parameter. Setting this will also
	// disable REST.
	RPCListener net.Listener

	// AuctioneerDialOpts is a list of dial options that should be used when
	// dialing the auctioneer server.
	AuctioneerDialOpts []grpc.DialOption

	// DebugConfig is a set of debug options used for development and
	// testing only.
	DebugConfig *DebugConfig `group:"debug" namespace:"debug" hidden:"true"`

	// ShutdownInterceptor is the custom shutdown signal interceptor that
	// the server is going to use to listen for (and issue) shutdown
	// commands on.
	ShutdownInterceptor signal.Interceptor

	// RequestShutdown is a call-back function that can be called in order
	// to indicate that pool has received a critical error and needs to shut
	// down.
	RequestShutdown func()
}

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default value for the Config struct.

type DebugConfig

type DebugConfig struct {
	BatchVersion int32 `long:"batchversion" description:"The batch version to use -- NOTE: for testing purposes only, don't use on mainnet"`
}

DebugConfig is a set of debug options used for development and testing only.

type Interceptor

type Interceptor interface {
	// UnaryInterceptor intercepts normal, non-streaming requests from the
	// client to the server.
	UnaryInterceptor(context.Context, string, interface{}, interface{},
		*grpc.ClientConn, grpc.UnaryInvoker, ...grpc.CallOption) error

	// StreamInterceptor intercepts streaming requests from the client to
	// the server.
	StreamInterceptor(context.Context, *grpc.StreamDesc, *grpc.ClientConn,
		string, grpc.Streamer, ...grpc.CallOption) (grpc.ClientStream,
		error)
}

Interceptor is the interface a client side gRPC interceptor has to implement.

type LndConfig

type LndConfig struct {
	Host string `long:"host" description:"lnd instance rpc address"`

	// MacaroonDir is the directory that contains all the macaroon files
	// required for the remote connection.
	MacaroonDir string `long:"macaroondir" description:"DEPRECATED: Use macaroonpath."`

	// MacaroonPath is the path to the single macaroon that should be used
	// instead of needing to specify the macaroon directory that contains
	// all of lnd's macaroons. The specified macaroon MUST have all
	// permissions that all the subservers use, otherwise permission errors
	// will occur.
	MacaroonPath string `` /* 304-byte string literal not displayed */

	TLSPath string `long:"tlspath" description:"Path to lnd tls certificate"`
}

type MailBox

type MailBox interface {
	// RecvSidecarPkt attempts to receive a new sidecar packet from the
	// relevant mailbox defined by the ticket and sidecar ticket role.
	RecvSidecarPkt(ctx context.Context, pkt *sidecar.Ticket,
		provider bool) (*sidecar.Ticket, error)

	// SendSidecarPkt attempts to send the specified sidecar ticket to the
	// party designated by the provider bool.
	SendSidecarPkt(ctx context.Context, pkt *sidecar.Ticket,
		provider bool) error

	// InitSidecarMailbox attempts to create the mailbox with the given
	// stream ID using the sidecar ticket authentication mechanism. If the
	// mailbox already exists, then a nil error is to be returned.
	InitSidecarMailbox(streamID [64]byte, ticket *sidecar.Ticket) error

	// DelSidecarMailbox tears down the mailbox the sidecar ticket
	// recipient used to communicate with the provider.
	DelSidecarMailbox(streamID [64]byte, ticket *sidecar.Ticket) error

	// InitAcctMailbox attempts to create the mailbox with the given stream
	// ID using account signature authentication mechanism. If the mailbox
	// already exists, then a nil error is to be returned.
	InitAcctMailbox(streamID [64]byte, pubKey *keychain.KeyDescriptor) error

	// DelAcctMailbox tears down the mailbox that the sidecar ticket
	// provider used to communicate with the recipient.
	DelAcctMailbox(streamID [64]byte, pubKey *keychain.KeyDescriptor) error
}

MailBox is an interface that abstracts over the HashMail functionality to represent a generic mailbox that both sides will use to communicate with each other.

type Marshaler

type Marshaler interface {
	// MarshallAccountsWithAvailableBalance returns the RPC representation
	// of an account with the account.AvailableBalance value populated.
	MarshallAccountsWithAvailableBalance(ctx context.Context,
		accounts []*account.Account) ([]*poolrpc.Account, error)
}

Marshaler interface to transform internal types to decorated RPC ones.

type MockMarshaler

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

MockMarshaler is a mock of Marshaler interface.

func NewMockMarshaler

func NewMockMarshaler(ctrl *gomock.Controller) *MockMarshaler

NewMockMarshaler creates a new mock instance.

func (*MockMarshaler) EXPECT

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockMarshaler) MarshallAccountsWithAvailableBalance

func (m *MockMarshaler) MarshallAccountsWithAvailableBalance(ctx context.Context, accounts []*account.Account) ([]*poolrpc.Account, error)

MarshallAccountsWithAvailableBalance mocks base method.

type MockMarshalerMockRecorder

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

MockMarshalerMockRecorder is the mock recorder for MockMarshaler.

func (*MockMarshalerMockRecorder) MarshallAccountsWithAvailableBalance

func (mr *MockMarshalerMockRecorder) MarshallAccountsWithAvailableBalance(ctx, accounts interface{}) *gomock.Call

MarshallAccountsWithAvailableBalance indicates an expected call of MarshallAccountsWithAvailableBalance.

type Server

type Server struct {

	// AuctioneerClient is the wrapper around the connection from the trader
	// client to the auctioneer server. It is exported so we can replace
	// the connection with a new one in the itest, if the server is
	// restarted.
	AuctioneerClient *auctioneer.Client

	// GetIdentity returns the current LSAT identification of the trader
	// client or an error if none has been established yet.
	GetIdentity func() (*lsat.TokenID, error)
	// contains filtered or unexported fields
}

Server is the main poold trader server.

func NewServer

func NewServer(cfg *Config) *Server

NewServer creates a new trader server.

func (Server) AccountModificationFees

func (s Server) AccountModificationFees(ctx context.Context,
	req *poolrpc.AccountModificationFeesRequest) (
	*poolrpc.AccountModificationFeesResponse, error)

AccountModificationFees returns a map from account key to an ordered list of account modifying action fees.

func (Server) AuctionFee

func (s Server) AuctionFee(ctx context.Context,
	_ *poolrpc.AuctionFeeRequest) (*poolrpc.AuctionFeeResponse, error)

AuctionFee returns the current fee rate charged for matched orders within the auction.

func (Server) BatchSnapshot

BatchSnapshot returns information about a target batch including the clearing price of the batch, and the set of orders matched within the batch.

func (Server) BatchSnapshots

BatchSnapshots returns a list of batch snapshots starting at the start batch ID and going back through the history of batches, returning at most the number of specified batches. A maximum of 100 snapshots can be queried in one call. If no start batch ID is provided, the most recent finalized batch is used as the starting point to go back from.

func (Server) BumpAccountFee

func (s Server) BumpAccountFee(ctx context.Context,
	req *poolrpc.BumpAccountFeeRequest) (*poolrpc.BumpAccountFeeResponse,
	error)

BumpAccountFee attempts to bump the fee of an account's transaction through child-pays-for-parent (CPFP). Since the CPFP is performed through the backing lnd node, the account transaction must contain an output under its control for a successful bump. If a CPFP has already been performed for an account, and this RPC is invoked again, then a replacing transaction (RBF) of the child will be broadcast.

func (Server) CancelOrder

func (s Server) CancelOrder(ctx context.Context,
	req *poolrpc.CancelOrderRequest) (*poolrpc.CancelOrderResponse, error)

CancelOrder cancels the order on the server and updates the state of the local order accordingly.

func (Server) CancelSidecar

func (s Server) CancelSidecar(ctx context.Context,
	req *poolrpc.CancelSidecarRequest) (*poolrpc.CancelSidecarResponse,
	error)

CancelSidecar cancels the execution of a specific sidecar ticket. Depending on the state of the sidecar ticket its associated bid order might be canceled as well (if this ticket was offered by our node).

func (Server) CloseAccount

func (s Server) CloseAccount(ctx context.Context,
	req *poolrpc.CloseAccountRequest) (*poolrpc.CloseAccountResponse, error)

CloseAccount handles a trader's request to close the specified account.

func (Server) DecodeSidecarTicket

func (s Server) DecodeSidecarTicket(ctx context.Context,
	req *poolrpc.SidecarTicket) (*poolrpc.DecodedSidecarTicket, error)

DecodeSidecarTicket decodes the base58 encoded sidecar ticket into its individual data fields for a more human-readable representation.

func (Server) DepositAccount

func (s Server) DepositAccount(ctx context.Context,
	req *poolrpc.DepositAccountRequest) (*poolrpc.DepositAccountResponse,
	error)

DepositAccount handles a trader's request to deposit funds into the specified account by spending the specified inputs.

func (Server) ExpectSidecarChannel

func (s Server) ExpectSidecarChannel(ctx context.Context,
	req *poolrpc.ExpectSidecarChannelRequest) (
	*poolrpc.ExpectSidecarChannelResponse, error)

ExpectSidecarChannel is step 4/4 of the sidecar negotiation between the provider (the trader submitting the bid order) and the recipient (the trader receiving the sidecar channel). This step must be run by the recipient once the provider has submitted the bid order for the sidecar channel. From this point onwards the Pool trader daemon of both the provider as well as the recipient need to be online to receive and react to match making events from the server.

func (Server) GetInfo

func (s Server) GetInfo(ctx context.Context,
	_ *poolrpc.GetInfoRequest) (*poolrpc.GetInfoResponse, error)

GetInfo returns general information about the state of the Pool trader daemon.

func (Server) GetLsatTokens

func (s Server) GetLsatTokens(_ context.Context,
	_ *poolrpc.TokensRequest) (*poolrpc.TokensResponse, error)

GetLsatTokens returns all tokens that are contained in the LSAT token store.

func (Server) InitAccount

func (s Server) InitAccount(ctx context.Context,
	req *poolrpc.InitAccountRequest) (*poolrpc.Account, error)

func (Server) LeaseDurations

func (s Server) LeaseDurations(ctx context.Context,
	_ *poolrpc.LeaseDurationRequest) (*poolrpc.LeaseDurationResponse, error)

LeaseDurations returns the current set of valid lease duration in the market as is, and also information w.r.t if the market is currently active.

func (Server) Leases

func (s Server) Leases(ctx context.Context,
	req *poolrpc.LeasesRequest) (*poolrpc.LeasesResponse, error)

Leases returns the list of channels that were either purchased or sold by the trader within the auction.

func (Server) ListAccounts

func (s Server) ListAccounts(ctx context.Context,
	req *poolrpc.ListAccountsRequest) (*poolrpc.ListAccountsResponse, error)

func (Server) ListOrders

func (s Server) ListOrders(ctx context.Context,
	req *poolrpc.ListOrdersRequest) (*poolrpc.ListOrdersResponse, error)

ListOrders returns a list of all orders that is currently known to the trader client's local store. The state of each order is queried on the auction server and returned as well.

func (Server) ListSidecars

func (s Server) ListSidecars(_ context.Context,
	req *poolrpc.ListSidecarsRequest) (*poolrpc.ListSidecarsResponse,
	error)

ListSidecars lists all sidecar tickets currently in the local database. This includes tickets offered by our node as well as tickets that our node is the recipient of. Optionally a ticket ID can be provided to filter the tickets.

func (Server) NextBatchInfo

func (s Server) NextBatchInfo(ctx context.Context,
	_ *poolrpc.NextBatchInfoRequest) (*poolrpc.NextBatchInfoResponse, error)

NextBatchInfo returns information about the next batch the auctioneer will perform.

func (Server) NodeRatings

func (s Server) NodeRatings(ctx context.Context,
	req *poolrpc.NodeRatingRequest) (*poolrpc.NodeRatingResponse, error)

NodeRatings returns rating information about the target node. This can be used to query the rating of your own node, or other nodes to determine which asks/bids might be filled based on a target min node tier.

func (Server) OfferSidecar

func (s Server) OfferSidecar(ctx context.Context,
	req *poolrpc.OfferSidecarRequest) (*poolrpc.SidecarTicket, error)

OfferSidecar is step 1/4 of the sidecar negotiation between the provider (the trader submitting the bid order) and the recipient (the trader receiving the sidecar channel). This step must be run by the provider. The result is a sidecar ticket with an offer to lease a sidecar channel for the recipient. The offer will be signed with the provider's lnd node public key. The ticket returned by this call will have the state "offered".

func (Server) QuoteAccount

func (s Server) QuoteAccount(ctx context.Context,
	req *poolrpc.QuoteAccountRequest) (*poolrpc.QuoteAccountResponse, error)

func (Server) QuoteOrder

func (s Server) QuoteOrder(ctx context.Context,
	req *poolrpc.QuoteOrderRequest) (*poolrpc.QuoteOrderResponse, error)

QuoteOrder calculates the premium, execution fees and max batch fee rate for an order based on the given order parameters.

func (Server) RecoverAccounts

func (s Server) RecoverAccounts(ctx context.Context,
	req *poolrpc.RecoverAccountsRequest) (*poolrpc.RecoverAccountsResponse,
	error)

func (Server) RegisterSidecar

func (s Server) RegisterSidecar(ctx context.Context,
	req *poolrpc.RegisterSidecarRequest) (*poolrpc.SidecarTicket, error)

RegisterSidecar is step 2/4 of the sidecar negotiation between the provider (the trader submitting the bid order) and the recipient (the trader receiving the sidecar channel). This step must be run by the recipient. The result is a sidecar ticket with the recipient's node information and channel funding multisig pubkey filled in. The ticket returned by this call will have the state "registered".

func (Server) RenewAccount

func (s Server) RenewAccount(ctx context.Context,
	req *poolrpc.RenewAccountRequest) (*poolrpc.RenewAccountResponse,
	error)

RenewAccount updates the expiration of an open/expired account. This will always require a signature from the auctioneer, even after the account has expired, to ensure the auctioneer is aware the account is being renewed.

func (*Server) Start

func (s *Server) Start() error

Start runs poold in daemon mode. It will listen for grpc connections, execute commands and pass back auction status information.

func (*Server) StartAsSubserver

func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient,
	lndGrpc *lndclient.GrpcLndServices, withMacaroonService bool) error

StartAsSubserver is an alternative start method where the RPC server does not create its own gRPC server but registers on an existing one.

func (*Server) Stop

func (s *Server) Stop() error

Stop shuts down the server, including the auction server connection, all client connections and network listeners.

func (Server) StopDaemon

func (s Server) StopDaemon(_ context.Context,
	_ *poolrpc.StopDaemonRequest) (*poolrpc.StopDaemonResponse, error)

StopDaemon gracefully shuts down the Pool trader daemon.

func (Server) SubmitOrder

func (s Server) SubmitOrder(ctx context.Context,
	req *poolrpc.SubmitOrderRequest) (*poolrpc.SubmitOrderResponse, error)

SubmitOrder assembles all the information that is required to submit an order from the trader's lnd node, signs it and then sends the order to the server to be included in the auctioneer's order book.

func (*Server) ValidateMacaroon

func (s *Server) ValidateMacaroon(ctx context.Context,
	requiredPermissions []bakery.Op, fullMethod string) error

ValidateMacaroon extracts the macaroon from the context's gRPC metadata, checks its signature, makes sure all specified permissions for the called method are contained within and finally ensures all caveat conditions are met. A non-nil error is returned if any of the checks fail. This method is needed to enable poold running as an external subserver in the same process as lnd but still validate its own macaroons.

func (Server) WithdrawAccount

func (s Server) WithdrawAccount(ctx context.Context,
	req *poolrpc.WithdrawAccountRequest) (*poolrpc.WithdrawAccountResponse,
	error)

WithdrawAccount handles a trader's request to withdraw funds from the specified account by spending the current account output to the specified outputs.

type SidecarAcceptor

type SidecarAcceptor struct {
	sync.Mutex
	// contains filtered or unexported fields
}

SidecarAcceptor is a type that is exclusively responsible for managing the recipient's tasks of executing a sidecar channel. The two tasks are:

  1. Verify a sidecar ticket and the offer contained within then add the recipient node information to the ticket so it can be returned to the sidecar provider. This is step 2/4 of the entire sidecar execution protocol.
  2. Interact with the auction server and connect out to an asker's node in the right moment then accept the incoming channel. This is step 4/4 of the entire sidecar execution protocol.

The code for these two tasks are kept separate from the default funding manager to make it easier to extract a standalone sidecar acceptor client later on. It also makes it easier to see what code would need to be re- implemented in another language to integrate just the acceptor part.

func NewSidecarAcceptor

func NewSidecarAcceptor(cfg *SidecarAcceptorConfig) *SidecarAcceptor

NewSidecarAcceptor creates a new sidecar acceptor.

func (*SidecarAcceptor) AutoAcceptSidecar

func (a *SidecarAcceptor) AutoAcceptSidecar(ticket *sidecar.Ticket) error

AutoAcceptSidecar signals to the acceptor that the recipient of a potential sidecar channel request automated acceptance of the sidecar channel. We'll use the cipher box of the provider of the ticket (and a new one we'll create for the reply side) to finalize negotiation, resulting in a bid order.

func (*SidecarAcceptor) CoordinateSidecar

func (a *SidecarAcceptor) CoordinateSidecar(ticket *sidecar.Ticket,
	bid *order.Bid, acct *account.Account) error

CoordinateSidecar signals to the sidecar acceptor that it should attempt to automatically coordinate the negotiation of the ultimate order to be produced by the sidecar ticket with the recipient.

func (*SidecarAcceptor) DelAcctMailbox

func (a *SidecarAcceptor) DelAcctMailbox(streamID [64]byte,
	pubKey *keychain.KeyDescriptor) error

DelAcctMailbox tears down the mailbox that the sidecar ticket provider used to communicate with the recipient.

func (*SidecarAcceptor) DelSidecarMailbox

func (a *SidecarAcceptor) DelSidecarMailbox(streamID [64]byte,
	ticket *sidecar.Ticket) error

DelSidecarMailbox tears down the mailbox the sidecar ticket recipient used to communicate with the provider.

func (*SidecarAcceptor) ExpectChannel

func (a *SidecarAcceptor) ExpectChannel(ctx context.Context,
	t *sidecar.Ticket) error

ExpectChannel informs the acceptor that a new bid order was submitted for the given sidecar ticket. We subscribe to auction events using the multisig key we gave out when we registered the ticket.

func (*SidecarAcceptor) FinalizeTicket

func (a *SidecarAcceptor) FinalizeTicket(t *sidecar.Ticket)

FinalizeTicket is called by the main batch processing logic of the provider of a ticket to signal to the underlying auto state machine (if on exists) that the channel has been finalized.

func (*SidecarAcceptor) InitAcctMailbox

func (a *SidecarAcceptor) InitAcctMailbox(streamID [64]byte,
	traderKey *keychain.KeyDescriptor) error

InitAcctMailbox attempts to create the mailbox with the given stream ID using account signature authentication mechanism. If the mailbox already exists, then a nil error is to be returned.

func (*SidecarAcceptor) InitSidecarMailbox

func (a *SidecarAcceptor) InitSidecarMailbox(streamID [64]byte,
	tkt *sidecar.Ticket) error

InitSidecarMailbox attempts to create the mailbox with the given stream ID using the sidecar ticket authentication mechanism. If the mailbox already exists, then a nil error is to be returned.

func (*SidecarAcceptor) RecvSidecarPkt

func (a *SidecarAcceptor) RecvSidecarPkt(pCtx context.Context,
	ticket *sidecar.Ticket, provider bool) (*sidecar.Ticket, error)

RecvSidecarPkt attempts to receive a new sidecar packet from the opposite party using their registered cipherbox stream.

func (*SidecarAcceptor) RegisterSidecar

func (a *SidecarAcceptor) RegisterSidecar(ctx context.Context,
	ticket sidecar.Ticket) (*sidecar.Ticket, error)

RegisterSidecar derives a new multisig key for a potential future channel bought over a sidecar order and adds that to the offered ticket. If successful, the updated ticket is added to the local database.

func (*SidecarAcceptor) SendSidecarPkt

func (a *SidecarAcceptor) SendSidecarPkt(ctx context.Context, pkt *sidecar.Ticket,
	provider bool) error

SendSidecarPkt attempts to send a sidecar packet to the opposite party using their registered cipherbox stream.

func (*SidecarAcceptor) Start

func (a *SidecarAcceptor) Start(errChan chan error) error

Start starts the sidecar acceptor.

func (*SidecarAcceptor) Stop

func (a *SidecarAcceptor) Stop() error

Stop stops the sidecar acceptor.

func (*SidecarAcceptor) SubmitSidecarOrder

func (a *SidecarAcceptor) SubmitSidecarOrder(ticket *sidecar.Ticket, bid *order.Bid,
	acct *account.Account) (*sidecar.Ticket, error)

SubmitSidecarOrder attempts to submit a new bid that's bound to a finalized sidecar ticket that's in the registered phase. If this method returns successfully, then the ticket will have transitioned to the sidecar.StateOrdered state.

func (*SidecarAcceptor) UpdateSidecar

func (a *SidecarAcceptor) UpdateSidecar(tkt *sidecar.Ticket) error

UpdateSidecar writes the passed sidecar ticket to persistent storage.

func (*SidecarAcceptor) ValidateOrderedTicket

func (a *SidecarAcceptor) ValidateOrderedTicket(tkt *sidecar.Ticket) error

ValidateOrderedTicket ctx attempts to validate that a given ticket has properly transitioned to the ordered state.

type SidecarAcceptorConfig

type SidecarAcceptorConfig struct {
	SidecarDB sidecar.Store

	AcctDB account.Store

	Signer lndclient.SignerClient

	Wallet lndclient.WalletKitClient

	BaseClient funding.BaseClient

	Acceptor *ChannelAcceptor

	NodePubKey *btcec.PublicKey

	ClientCfg auctioneer.Config

	PrepareOrder orderPreparer

	FundingManager *funding.Manager

	FetchSidecarBid func(*sidecar.Ticket) (*order.Bid, error)
}

SidecarAcceptorConfig holds all the configuration information that sidecar acceptor needs in order to carry out its duties.

type SidecarDriver

type SidecarDriver interface {
	// ValidateOrderedTicket attempts to validate that a given ticket
	// has properly transitioned to the ordered state.
	ValidateOrderedTicket(tkt *sidecar.Ticket) error

	// ExpectChannel is called by the receiver of a channel once the
	// negotiation process has been finalized, and they need to await a new
	// channel funding flow initiated by the auctioneer server.
	ExpectChannel(ctx context.Context, tkt *sidecar.Ticket) error

	// UpdateSidecar writes the passed sidecar ticket to persistent
	// storage.
	UpdateSidecar(tkt *sidecar.Ticket) error

	// SubmitSidecarOrder submits a bid derived from the sidecar ticket,
	// account, and bid template to the auctioneer.
	SubmitSidecarOrder(*sidecar.Ticket, *order.Bid,
		*account.Account) (*sidecar.Ticket, error)
}

SidecarDriver houses a series of methods needed to drive a given sidecar channel towards completion.

type SidecarNegotiator

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

SidecarNegotiator is a sub-system that uses a mailbox abstraction between a provider and recipient of a sidecar channel to complete the manual steps in automated manner.

func NewSidecarNegotiator

func NewSidecarNegotiator(cfg AutoAcceptorConfig) *SidecarNegotiator

NewSidecarNegotiator returns a new instance of the sidecar negotiator given a valid config.

func (*SidecarNegotiator) CurrentState

func (a *SidecarNegotiator) CurrentState() sidecar.State

CurrentState returns the current state of the sidecar negotiator.

func (*SidecarNegotiator) Start

func (a *SidecarNegotiator) Start() error

Start kicks off the set of goroutines needed for the sidecar channel to be negotiated.

func (*SidecarNegotiator) Stop

func (a *SidecarNegotiator) Stop()

Stop signals all goroutines to enter a graceful shutdown.

func (*SidecarNegotiator) TicketExecuted

func (a *SidecarNegotiator) TicketExecuted(state sidecar.State, otherSide bool)

TicketExecuted is a clean up function that should be called once the ticket has been executed, meaning a channel defined by it was confirmed in a batch on chain.

type SidecarPacket

type SidecarPacket struct {
	// CurrentState is the current state of the negotiator.
	CurrentState sidecar.State

	// ReceiverTicket is the current ticket of the receiver.
	ReceiverTicket *sidecar.Ticket

	// ProviderTicket is the current ticket of the provider.
	ProviderTicket *sidecar.Ticket
}

SidecarPacket encapsulates the current state of an auto sidecar negotiator. Note that the state of the negotiator, and the ticket may differ, this is what will trigger a state transition.

Directories

Path Synopsis
Package account is a generated GoMock package.
Package account is a generated GoMock package.
cmd
internal
test
Package test is a generated GoMock package.
Package test is a generated GoMock package.
Package order is a generated GoMock package.
Package order is a generated GoMock package.
Package poolrpc is a reverse proxy.
Package poolrpc is a reverse proxy.
Package sidecar is a generated GoMock package.
Package sidecar is a generated GoMock package.

Jump to

Keyboard shortcuts

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