swap

package
v0.2.97 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2022 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BitcoinCsv = 1008
	LiquidCsv  = 60
)
View Source
const (
	// Default represents the default state of the system.
	Default StateType = ""

	// NoOp represents a no-op event.
	NoOp EventType = "NoOp"
)
View Source
const (
	CLAIMTYPE_PREIMAGE = iota + 1
	CLAIMTYPE_CSV
)
View Source
const (
	PEERSWAP_PROTOCOL_VERSION = 3
)
View Source
const PaymentLabelSeparator = "_"

Variables

View Source
var (
	AlreadyExistsError     = errors.New("Message already exists")
	InvalidLengthError     = errors.New("Hex string is of invalid length")
	InvalidNetworkError    = errors.New("Invalid network")
	InvalidScidError       = errors.New("Invalid Scid")
	AssetOrNetworkSetError = errors.New("Either asset or network must be set")
)
View Source
var (
	AllowedAssets       = []string{"btc", "lbtc"}
	ErrSwapDoesNotExist = errors.New("swap does not exist")
)
View Source
var (
	ErrDoesNotExist  = fmt.Errorf("does not exist")
	ErrAlreadyExists = fmt.Errorf("swap already exist")
)
View Source
var ErrDataNotAvailable = errors.New("data not in store")

ErrDataNotAvailable is the error returned when the store does not have the data stored yet

View Source
var ErrEventRejected = errors.New("event rejected")

ErrEventRejected is the error returned when the state machine cannot process an event in the state that it is in.

View Source
var ErrFsmConfig = errors.New("fsm config invalid")

ErrFsmConfig is the error returned when the fsm configuartion is invalid i.e. the fsm does not contain the next state

Functions

func ErrReceivedMessageFromUnexpectedPeer

func ErrReceivedMessageFromUnexpectedPeer(peerId string, swapId *SwapId) error

func MarshalPeerswapMessage

func MarshalPeerswapMessage(msg PeerMessage) ([]byte, int, error)

func NewBboltStore

func NewBboltStore(db *bbolt.DB) (*bboltStore, error)

func NewInvalidLengthError

func NewInvalidLengthError(paramName string, expected, actual int) error

func NewRequestedSwapsStore

func NewRequestedSwapsStore(db *bbolt.DB) (*requestedSwapsStore, error)

func SwapInReceiverStatesToMermaid

func SwapInReceiverStatesToMermaid(filename string) error

func SwapInSenderStatesToMermaid

func SwapInSenderStatesToMermaid(filename string) error

func SwapOutReceiverStatesToMermaid

func SwapOutReceiverStatesToMermaid(filename string) error

func SwapOutSenderStatesToMermaid

func SwapOutSenderStatesToMermaid(filename string) error

Types

type Action

type Action interface {
	Execute(services *SwapServices, swap *SwapData) EventType
}

Action represents the action to be executed in a given state.

type AwaitCsvAction

type AwaitCsvAction struct{}

AwaitCsvAction adds the opening tx to the txwatcher

func (*AwaitCsvAction) Execute

func (w *AwaitCsvAction) Execute(services *SwapServices, swap *SwapData) EventType

todo this will never throw an error

type AwaitFeeInvoicePayment

type AwaitFeeInvoicePayment struct{}

AwaitFeeInvoicePayment adds the opening tx to the txwatcher

func (*AwaitFeeInvoicePayment) Execute

func (w *AwaitFeeInvoicePayment) Execute(services *SwapServices, swap *SwapData) EventType

type AwaitPaymentOrCsvAction

type AwaitPaymentOrCsvAction struct{}

AwaitPaymentOrCsvAction checks if the invoice has been paid

func (*AwaitPaymentOrCsvAction) Execute

func (w *AwaitPaymentOrCsvAction) Execute(services *SwapServices, swap *SwapData) EventType

todo this will never throw an error

type AwaitTxConfirmationAction

type AwaitTxConfirmationAction struct{}

AwaitTxConfirmationAction checks the claim invoice and adds the transaction to the txwatcher.

func (*AwaitTxConfirmationAction) Execute

func (t *AwaitTxConfirmationAction) Execute(services *SwapServices, swap *SwapData) EventType

todo this will not ever throw an error

type CancelAction

type CancelAction struct{}

func (*CancelAction) Execute

func (c *CancelAction) Execute(services *SwapServices, swap *SwapData) EventType

type CancelMessage

type CancelMessage struct {
	// SwapId is the unique identifier of the swap.
	SwapId *SwapId `json:"swap_id"`
	// Message is a hint to why the swap was canceled.
	Message string `json:"message"`
}

CancelMessage is the message sent by a peer if he wants to / has to cancel the swap

func (CancelMessage) ApplyToSwapData

func (m CancelMessage) ApplyToSwapData(swap *SwapData) error

func (CancelMessage) MessageType

func (e CancelMessage) MessageType() messages.MessageType

func (CancelMessage) Validate

func (s CancelMessage) Validate(swap *SwapData) error

type CheckRequestWrapperAction

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

func (CheckRequestWrapperAction) Execute

func (a CheckRequestWrapperAction) Execute(services *SwapServices, swap *SwapData) EventType

type ClaimParams

type ClaimParams struct {
	Preimage     string
	Signer       Signer
	OpeningTxHex string

	// blinded tx stuff
	BlindingSeed              []byte
	OutputAssetBlindingFactor []byte
	EphemeralKey              *btcec.PrivateKey
}

func (*ClaimParams) String

func (o *ClaimParams) String() string

type ClaimSwapTransactionCoop

type ClaimSwapTransactionCoop struct{}

ClaimSwapTransactionWithCsv spends the opening transaction with maker and taker Signatures

func (*ClaimSwapTransactionCoop) Execute

func (c *ClaimSwapTransactionCoop) Execute(services *SwapServices, swap *SwapData) EventType

type ClaimSwapTransactionWithCsv

type ClaimSwapTransactionWithCsv struct{}

ClaimSwapTransactionWithCsv spends the opening transaction with a signature

func (*ClaimSwapTransactionWithCsv) Execute

func (c *ClaimSwapTransactionWithCsv) Execute(services *SwapServices, swap *SwapData) EventType

type ClaimSwapTransactionWithPreimageAction

type ClaimSwapTransactionWithPreimageAction struct{}

ClaimSwapTransactionWithPreimageAction spends the opening transaction to the nodes liquid wallet

func (*ClaimSwapTransactionWithPreimageAction) Execute

todo this is very critical

type ClaimType

type ClaimType int

type CoopCloseMessage

type CoopCloseMessage struct {
	// SwapId is the unique identifier of the swap.
	SwapId *SwapId `json:"swap_id"`
	// Message is a hint to why the swap was canceled.
	Message string `json:"message"`
	// privkey is the private key to the pubkey that is used to build the opening_transaction.
	Privkey string `json:"privkey"`
}

CoopCloseMessage is the message sent by the transaction taker if he wants to cancel the swap, but allow the maker a quick close

func (CoopCloseMessage) ApplyToSwapData

func (m CoopCloseMessage) ApplyToSwapData(swap *SwapData) error

func (CoopCloseMessage) MessageType

func (c CoopCloseMessage) MessageType() messages.MessageType

func (CoopCloseMessage) Validate

func (s CoopCloseMessage) Validate(swap *SwapData) error

type CreateAndBroadcastOpeningTransaction

type CreateAndBroadcastOpeningTransaction struct{}

func (*CreateAndBroadcastOpeningTransaction) Execute

type CreateSwapOutFromRequestAction

type CreateSwapOutFromRequestAction struct{}

CreateSwapOutFromRequestAction creates the swap-out process and prepares the opening transaction

func (*CreateSwapOutFromRequestAction) Execute

func (c *CreateSwapOutFromRequestAction) Execute(services *SwapServices, swap *SwapData) EventType

type CreateSwapRequestAction

type CreateSwapRequestAction struct{}

SwapInSenderCreateSwapAction creates the swap data

func (*CreateSwapRequestAction) Execute

func (a *CreateSwapRequestAction) Execute(services *SwapServices, swap *SwapData) EventType

todo validate data

type ErrMinimumSwapSize

type ErrMinimumSwapSize uint64

func (ErrMinimumSwapSize) Error

func (u ErrMinimumSwapSize) Error() string

type ErrUnknownSwapMessageType

type ErrUnknownSwapMessageType string

func (ErrUnknownSwapMessageType) Error

type EventContext

type EventContext interface {
	ApplyToSwapData(data *SwapData) error
	Validate(data *SwapData) error
}

EventContext represents the context to be passed to the action implementation.

type EventType

type EventType string

EventType represents an extensible event type in the state machine.

const (
	Event_OnSwapOutStarted     EventType = "Event_OnSwapOutStarted"
	Event_OnFeeInvoiceReceived EventType = "Event_OnFeeInvoiceReceived"

	Event_OnTxOpenedMessage EventType = "Event_OnTxOpenedMessage"
	Event_OnTxConfirmed     EventType = "Event_OnTxConfirmed"

	// todo retrystate? failstate? refundstate?
	Event_OnRetry      EventType = "Event_OnRetry"
	Event_OnClaimedCsv EventType = "Event_OnClaimedCsv"

	Event_OnSwapOutRequestReceived EventType = "Event_OnSwapOutRequestReceived"

	Event_OnFeeInvoicePaid    EventType = "Event_OnFeeInvoicePaid"
	Event_OnClaimInvoicePaid  EventType = "Event_OnClaimInvoicePaid"
	Event_OnCsvPassed         EventType = "Event_OnCsvPassed"
	Event_OnCancelReceived    EventType = "Event_OnCancelReceived"
	Event_OnCoopCloseReceived EventType = "Event_OnCoopCloseReceived"

	Event_OnTimeout = "Event_OnTimeout"

	Event_ActionSucceeded                  EventType = "Event_ActionSucceeded"
	Event_SwapInSender_OnSwapInRequested   EventType = "Event_SwapInSender_OnSwapInRequested"
	Event_SwapInSender_OnAgreementReceived EventType = "Event_SwapInSender_OnAgreementReceived"
	Event_ActionFailed                     EventType = "Event_ActionFailed"
	Event_SwapInReceiver_OnRequestReceived EventType = "Event_SwapInReceiver_OnRequestReceived"
	Event_Done                             EventType = "Event_Done"

	Event_OnInvalid_Message EventType = "Event_Invalid_Message"
)

Events

type Events

type Events map[EventType]StateType

Events represents a mapping of events and states.

type InvoiceType

type InvoiceType int
const (
	INVOICE_CLAIM InvoiceType = iota + 1
	INVOICE_FEE
)

func (InvoiceType) String

func (i InvoiceType) String() string

type JsonAssetRequest

type JsonAssetRequest struct {
	TotalAmountSat uint64 `json:"total_amount_sat"`
	NRequests      uint64 `json:"n_requests"`
}

type JsonEnty

type JsonEnty struct {
	NodeId   string                                  `json:"node_id"`
	Requests map[string]map[string]*JsonAssetRequest `json:"requests"`
}

type LightningClient

type LightningClient interface {
	DecodePayreq(payreq string) (paymentHash string, amountMsat uint64, expiry int64, err error)
	PayInvoice(payreq string) (preImage string, err error)
	GetPayreq(msatAmount uint64, preimage string, swapId string, memo string, invoiceType InvoiceType, expirySeconds, expiryCltv uint64) (string, error)
	PayInvoiceViaChannel(payreq string, channel string) (preimage string, err error)
	AddPaymentCallback(f func(swapId string, invoiceType InvoiceType))
	AddPaymentNotifier(swapId string, payreq string, invoiceType InvoiceType)
	RebalancePayment(payreq string, channel string) (preimage string, err error)
}

type Messenger

type Messenger interface {
	SendMessage(peerId string, message []byte, messageType int) error
	AddMessageHandler(func(peerId string, msgType string, payload []byte) error)
}

type MessengerManager

type MessengerManager interface {
	AddSender(id string, messenger messages.StoppableMessenger) error
	RemoveSender(id string)
}

type NoOpAction

type NoOpAction struct{}

func (*NoOpAction) Execute

func (n *NoOpAction) Execute(services *SwapServices, swap *SwapData) EventType

type NoOpDoneAction

type NoOpDoneAction struct{}

func (*NoOpDoneAction) Execute

func (a *NoOpDoneAction) Execute(services *SwapServices, swap *SwapData) EventType

type OpeningParams

type OpeningParams struct {
	TakerPubkey      string
	MakerPubkey      string
	ClaimPaymentHash string
	Amount           uint64
	BlindingKey      *btcec.PrivateKey
	OpeningAddress   string
}

func (*OpeningParams) String

func (o *OpeningParams) String() string

type OpeningTxBroadcastedMessage

type OpeningTxBroadcastedMessage struct {
	// SwapId is the unique identifier of the swap.
	SwapId *SwapId `json:"swap_id"`
	// Payreq is the invoice as described in BOLT#11 that the responder is
	// requested to pay.
	Payreq string `json:"payreq"`
	// TxId is the transaction id of the opening_transaction broadcasted by the
	// initiator.
	TxId string `json:"tx_id"`
	// ScriptOut is the transaction output that contains the opening_transaction
	// output script for the swap.
	ScriptOut uint32 `json:"script_out"`
	// BlindingKey:
	// Bitcoin: Blank.
	// Liquid BitcoinNetwork: Is the 32 byte blinding key to un-blind the outputs of
	//the opening_transaction.
	BlindingKey string `json:"blinding_key"`
}

OpeningTxBroadcastedMessage is the message sent by the creator of the opening tx.

func (OpeningTxBroadcastedMessage) ApplyToSwapData

func (m OpeningTxBroadcastedMessage) ApplyToSwapData(swap *SwapData) error

func (OpeningTxBroadcastedMessage) MessageType

func (OpeningTxBroadcastedMessage) Validate

func (s OpeningTxBroadcastedMessage) Validate(swap *SwapData) error

type PayFeeInvoiceAction

type PayFeeInvoiceAction struct{}

PayFeeInvoiceAction checks the feeinvoice and pays it

func (*PayFeeInvoiceAction) Execute

func (r *PayFeeInvoiceAction) Execute(services *SwapServices, swap *SwapData) EventType

type PeerIsSuspiciousError

type PeerIsSuspiciousError string

func (PeerIsSuspiciousError) Error

func (s PeerIsSuspiciousError) Error() string

type PeerMessage

type PeerMessage interface {
	MessageType() messages.MessageType
}

type PeerNotAllowedError

type PeerNotAllowedError string

func (PeerNotAllowedError) Error

func (s PeerNotAllowedError) Error() string

type Policy

type Policy interface {
	IsPeerAllowed(peer string) bool
	IsPeerSuspicious(peer string) bool
	GetReserveOnchainMsat() uint64
	GetMinSwapAmountMsat() uint64
	NewSwapsAllowed() bool
}

type RequestedSwap

type RequestedSwap struct {
	Asset           string   `json:"asset"`
	AmountSat       uint64   `json:"amount_sat"`
	Type            SwapType `json:"swap_type"`
	RejectionReason string   `json:"rejection_reason"`
}

type RequestedSwapsPrinter

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

func NewRequestedSwapsPrinter

func NewRequestedSwapsPrinter(store RequestedSwapsStore) *RequestedSwapsPrinter

func (*RequestedSwapsPrinter) Get

func (p *RequestedSwapsPrinter) Get() ([]JsonEnty, error)

func (*RequestedSwapsPrinter) GetRaw

func (p *RequestedSwapsPrinter) GetRaw() (map[string][]RequestedSwap, error)

func (*RequestedSwapsPrinter) Write

func (p *RequestedSwapsPrinter) Write(w io.Writer)

type RequestedSwapsStore

type RequestedSwapsStore interface {
	Add(id string, reqswap RequestedSwap) error
	Get(id string) ([]RequestedSwap, error)
	GetAll() (map[string][]RequestedSwap, error)
}

type Secp256k1Signer

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

func (*Secp256k1Signer) Sign

func (s *Secp256k1Signer) Sign(hash []byte) (*ecdsa.Signature, error)

type SendCancelAction

type SendCancelAction struct{}

SendCancelAction sends a cancel message to the swap peer

func (*SendCancelAction) Execute

func (s *SendCancelAction) Execute(services *SwapServices, swap *SwapData) EventType

type SendMessageAction

type SendMessageAction struct{}

func (*SendMessageAction) Execute

func (s *SendMessageAction) Execute(services *SwapServices, swap *SwapData) EventType

type SendMessageWithRetryAction

type SendMessageWithRetryAction struct{}

func (*SendMessageWithRetryAction) Execute

func (s *SendMessageWithRetryAction) Execute(services *SwapServices, swap *SwapData) EventType

type SetBlindingKeyActionWrapper

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

func (*SetBlindingKeyActionWrapper) Execute

func (a *SetBlindingKeyActionWrapper) Execute(services *SwapServices, swap *SwapData) EventType

type SetStartingBlockHeightAction

type SetStartingBlockHeightAction struct{}

func (*SetStartingBlockHeightAction) Execute

func (s *SetStartingBlockHeightAction) Execute(services *SwapServices, swap *SwapData) EventType

type Signer

type Signer interface {
	Sign(hash []byte) (*btecdsa.Signature, error)
}

type State

type State struct {
	Action        Action
	Events        Events
	FailOnrecover bool
}

State binds a state with an action and a set of events it can handle.

type StateType

type StateType string

StateType represents an extensible state type in the state machine.

const (
	State_SendCancel      StateType = "State_SendCancel"
	State_SwapCanceled    StateType = "State_SwapCanceled"
	State_WaitCsv         StateType = "State_WaitCsv"
	State_ClaimedCsv      StateType = "State_ClaimedCsv"
	State_ClaimedPreimage StateType = "State_ClaimedPreimage"
	State_ClaimedCoop     StateType = "State_ClaimedCoop"
)

Shared States

const (
	State_SwapOutSender_CreateSwap                   StateType = "State_SwapOutSender_CreateSwap"
	State_SwapOutSender_SendRequest                  StateType = "State_SwapOutSender_SendRequest"
	State_SwapOutSender_AwaitAgreement               StateType = "State_SwapOutSender_AwaitAgreement"
	State_SwapOutSender_PayFeeInvoice                StateType = "State_SwapOutSender_PayFeeInvoice"
	State_SwapOutSender_AwaitTxBroadcastedMessage    StateType = "State_SwapOutSender_AwaitTxBroadcastedMessage"
	State_SwapOutSender_AwaitTxConfirmation          StateType = "State_SwapOutSender_AwaitTxConfirmation"
	State_SwapOutSender_ValidateTxAndPayClaimInvoice StateType = "State_SwapOutSender_ValidateTxAndPayClaimInvoice"
	State_SwapOutSender_ClaimSwap                    StateType = "State_SwapOutSender_ClaimSwap"
	State_SwapOutSender_SendPrivkey                  StateType = "State_SwapOutSender_SendPrivkey"
	State_SwapOutSender_SendCoopClose                StateType = "State_SwapOutSender_SendCoopClose"
)

Swap Out Sender States

const (
	State_SwapOutReceiver_CreateSwap               StateType = "State_SwapOutReceiver_CreateSwap"
	State_SwapOutReceiver_SendFeeInvoice           StateType = "State_SwapOutReceiver_SendFeeInvoice"
	State_SwapOutReceiver_AwaitFeeInvoicePayment   StateType = "State_SwapOutReceiver_AwaitFeeInvoicePayment"
	State_SwapOutReceiver_BroadcastOpeningTx       StateType = "State_SwapOutReceiver_BroadcastOpeningTx"
	State_SwapOutReceiver_SendTxBroadcastedMessage StateType = "State_SwapOutReceiver_SendTxBroadcastedMessage"
	State_SwapOutReceiver_AwaitClaimInvoicePayment StateType = "State_SwapOutReceiver_AwaitClaimInvoicePayment"
	State_SwapOutReceiver_SwapAborted              StateType = "State_SwapOutReceiver_Aborted"
	State_SwapOutReceiver_ClaimSwapCsv             StateType = "State_SwapOutReceiver_ClaimSwapCsv"
	State_SwapOutReceiver_ClaimSwapCoop            StateType = "State_SwapOutReceiver_ClaimSwapCoop"
)

Swap Out Receiver states

const (
	State_SwapInSender_CreateSwap               StateType = "State_SwapInSender_CreateSwap"
	State_SwapInSender_SendRequest              StateType = "State_SwapInSender_SendRequest"
	State_SwapInSender_AwaitAgreement           StateType = "State_SwapInSender_AwaitAgreement"
	State_SwapInSender_BroadcastOpeningTx       StateType = "State_SwapInSender_BroadcastOpeningTx"
	State_SwapInSender_SendTxBroadcastedMessage StateType = "State_SwapInSender_SendTxBroadcastedMessage"
	State_SwapInSender_AwaitClaimPayment        StateType = "State_SwapInSender_AwaitClaimPayment"
	State_SwapInSender_ClaimSwapCsv             StateType = "State_SwapInSender_ClaimSwapCsv"
	State_SwapInSender_ClaimSwapCoop            StateType = "State_SwapInSender_ClaimSwapCoop"
)

Swap In Sender States

const (
	State_SwapInReceiver_CreateSwap                   StateType = "State_SwapInReceiver_CreateSwap"
	State_SwapInReceiver_SendAgreement                StateType = "State_SwapInReceiver_SendAgreement"
	State_SwapInReceiver_AwaitTxBroadcastedMessage    StateType = "State_SwapInReceiver_AwaitTxBroadcastedMessage"
	State_SwapInReceiver_AwaitTxConfirmation          StateType = "State_SwapInReceiver_AwaitTxConfirmation"
	State_SwapInReceiver_ValidateTxAndPayClaimInvoice StateType = "State_SwapInReceiver_ValidateTxAndPayClaimInvoice"
	State_SwapInReceiver_ClaimSwap                    StateType = "State_SwapInReceiver_ClaimSwap"
	State_SwapInReceiver_SendPrivkey                  StateType = "State_SwapInReceiver_SendPrivkey"
	State_SwapInReceiver_SendCoopClose                StateType = "State_SwapInReceiver_SendCoopClose"
)

Swap In Receiver States

type States

type States map[StateType]State

States represents a mapping of states and their implementations.

type StopSendMessageWithRetryWrapperAction

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

func (StopSendMessageWithRetryWrapperAction) Execute

type Store

type Store interface {
	UpdateData(data *SwapStateMachine) error
	GetData(id string) (*SwapStateMachine, error)
	ListAll() ([]*SwapStateMachine, error)
	ListAllByPeer(peer string) ([]*SwapStateMachine, error)
}

type SwapData

type SwapData struct {
	// Swap In
	SwapInRequest   *SwapInRequestMessage   `json:"swap_in_request"`
	SwapInAgreement *SwapInAgreementMessage `json:"swap_in_agreement"`

	// Swap Out
	SwapOutRequest   *SwapOutRequestMessage   `json:"swap_out_request"`
	SwapOutAgreement *SwapOutAgreementMessage `json:"swap_out_agreement"`

	// TxOpened
	OpeningTxBroadcasted *OpeningTxBroadcastedMessage `json:"opening_tx_broadcasted"`

	// CoopClose
	CoopClose *CoopCloseMessage `json:"coop_close_message"`

	// Cancel
	Cancel *CancelMessage `json:"cancel_message_obj"`

	// cancel message
	CancelMessage string `json:"cancel_message"`

	PeerNodeId          string    `json:"peer_node_id"`
	InitiatorNodeId     string    `json:"initiator_node_id"`
	CreatedAt           int64     `json:"created_at"`
	Role                SwapRole  `json:"role"`
	FSMState            StateType `json:"fsm_state"`
	PrivkeyBytes        []byte    `json:"private_key"`
	FeePreimage         string    `json:"fee_preimage"`
	OpeningTxFee        uint64    `json:"opening_tx_fee"`
	OpeningTxHex        string    `json:"opening_tx_hex"`
	StartingBlockHeight uint32    `json:"opening_block_height"`
	ClaimTxId           string    `json:"claim_tx_id"`
	ClaimPaymentHash    string    `json:"claim_payment_hash"`
	ClaimPreimage       string    `json:"claim_preimage"`

	BlindingKeyHex string `json:"blinding_key"`

	LastMessage EventContext `json:"last_message"`

	NextMessage     []byte `json:"next_message"`
	NextMessageType int    `json:"next_message_type"`

	LastErr       error  `json:"-"`
	LastErrString string `json:"last_err,omitempty"`
	// contains filtered or unexported fields
}

SwapData holds all the data needed for a swap

func NewSwapData

func NewSwapData(swapId *SwapId, initiatorNodeId string, peerNodeId string) *SwapData

NewSwapData returns a new swap with a random hex id and the given arguments

func NewSwapDataFromRequest

func NewSwapDataFromRequest(swapId *SwapId, senderNodeId string) *SwapData

NewSwapDataFromRequest returns a new swap created from a swap request

func (*SwapData) GetAmount

func (s *SwapData) GetAmount() uint64

func (*SwapData) GetAsset

func (s *SwapData) GetAsset() string

func (*SwapData) GetCancelMessage

func (s *SwapData) GetCancelMessage() string

func (*SwapData) GetChain

func (s *SwapData) GetChain() string

func (*SwapData) GetClaimParams

func (s *SwapData) GetClaimParams() *ClaimParams

func (*SwapData) GetCurrentState

func (s *SwapData) GetCurrentState() StateType

func (*SwapData) GetId

func (s *SwapData) GetId() *SwapId

func (*SwapData) GetInvoiceCltv

func (s *SwapData) GetInvoiceCltv() uint64

func (*SwapData) GetInvoiceExpiry

func (s *SwapData) GetInvoiceExpiry() uint64

func (*SwapData) GetMakerPubkey

func (s *SwapData) GetMakerPubkey() string

func (*SwapData) GetNetwork

func (s *SwapData) GetNetwork() string

func (*SwapData) GetOpeningParams

func (s *SwapData) GetOpeningParams() *OpeningParams

func (*SwapData) GetOpeningTxId

func (s *SwapData) GetOpeningTxId() string

func (*SwapData) GetPaymentHash

func (s *SwapData) GetPaymentHash() string

func (*SwapData) GetPreimage

func (s *SwapData) GetPreimage() string

func (*SwapData) GetPrivkey

func (s *SwapData) GetPrivkey() *btcec.PrivateKey

func (*SwapData) GetProtocolVersion

func (s *SwapData) GetProtocolVersion() uint8

func (*SwapData) GetRequest

func (s *SwapData) GetRequest() PeerMessage

func (*SwapData) GetScid

func (s *SwapData) GetScid() string

func (*SwapData) GetScidInBoltFormat

func (s *SwapData) GetScidInBoltFormat() string

func (*SwapData) GetTakerPubkey

func (s *SwapData) GetTakerPubkey() string

func (*SwapData) GetType

func (s *SwapData) GetType() SwapType

func (*SwapData) HandleError

func (s *SwapData) HandleError(err error) EventType

func (*SwapData) SetState

func (s *SwapData) SetState(stateType StateType)

type SwapErrorContext

type SwapErrorContext struct {
	Err      error
	SendPeer bool
}

func (SwapErrorContext) ApplyToSwapData

func (s SwapErrorContext) ApplyToSwapData(data *SwapData) error

func (*SwapErrorContext) Validate

func (s *SwapErrorContext) Validate(data *SwapData) error

type SwapId

type SwapId [32]byte

func NewSwapId

func NewSwapId() *SwapId

func ParseSwapIdFromString

func ParseSwapIdFromString(str string) (*SwapId, error)

func (*SwapId) FromString

func (s *SwapId) FromString(str string) error

func (*SwapId) MarshalJSON

func (s *SwapId) MarshalJSON() ([]byte, error)

func (*SwapId) String

func (s *SwapId) String() string

func (*SwapId) UnmarshalJSON

func (s *SwapId) UnmarshalJSON(data []byte) error

type SwapInAgreementMessage

type SwapInAgreementMessage struct {
	// ProtocolVersion is the version of the PeerSwap peer protocol the sending
	// node uses.
	ProtocolVersion uint8 `json:"protocol_version"`
	// SwapId is a randomly generated 32 byte string that must be kept the same
	// through the whole process of a swap and serves as an identifier for a
	// specific swap.
	SwapId *SwapId `json:"swap_id"`
	// Pubkey is a 33 byte compressed public key used for the spending paths in
	// the opening_transaction.
	Pubkey string `json:"pubkey"`
	// Premium is a compensation in Sats that the swap partner wants to be payed
	// in order to participate in the swap.
	Premium uint64 `json:"premium"`
}

SwapInAgreementMessage is the response by the swap-in peer if he accepts the swap.

func (SwapInAgreementMessage) ApplyToSwapData

func (s SwapInAgreementMessage) ApplyToSwapData(swap *SwapData) error

func (SwapInAgreementMessage) MessageType

func (SwapInAgreementMessage) Validate

func (s SwapInAgreementMessage) Validate(swap *SwapData) error

type SwapInReceiverInitAction

type SwapInReceiverInitAction struct{}

todo check for policy / balance SwapInReceiverInitAction creates the swap-in process

func (*SwapInReceiverInitAction) Execute

func (s *SwapInReceiverInitAction) Execute(services *SwapServices, swap *SwapData) EventType

type SwapInRequestMessage

type SwapInRequestMessage struct {
	// ProtocolVersion is the version of the PeerSwap peer protocol the sending
	// node uses.
	ProtocolVersion uint8 `json:"protocol_version"`
	// SwapId is a randomly generated 32 byte string that must be kept the same
	// through the whole process of a swap and serves as an identifier for a
	// specific swap.
	SwapId *SwapId `json:"swap_id"`
	// Network is the desired on-chain network to use. This can be:
	// Bitcoin: mainnet, testnet, signet, regtest
	// Liquid: The field is left blank as the asset id also defines the bitcoinNetwork.
	Network string `json:"network"`
	// Asset is the desired on-chain asset to use. This can be:
	// Bitcoin: The field is left blank.
	// Liquid: The asset id of the networks Bitcoin asset.
	Asset string `json:"asset"`
	// Scid is the short channel id in human readable format, defined by BOLT#7
	// with x as separator, e.g. 539268x845x1.
	Scid string `json:"scid"`
	// Amount is The amount in Sats that is asked for.
	Amount uint64 `json:"amount"`
	Pubkey string `json:"pubkey"`
}

func (SwapInRequestMessage) ApplyToSwapData

func (s SwapInRequestMessage) ApplyToSwapData(swap *SwapData) error

func (SwapInRequestMessage) MessageType

func (s SwapInRequestMessage) MessageType() messages.MessageType

func (SwapInRequestMessage) Validate

func (s SwapInRequestMessage) Validate(swap *SwapData) error

type SwapOutAgreementMessage

type SwapOutAgreementMessage struct {
	// ProtocolVersion is the version of the PeerSwap peer protocol the sending
	// node uses.
	ProtocolVersion uint8 `json:"protocol_version"`
	// SwapId is a randomly generated 32 byte string that must be kept the same
	// through the whole process of a swap and serves as an identifier for a
	// specific swap.
	SwapId *SwapId `json:"swap_id"`
	// Pubkey is a 33 byte compressed public key used for the spending paths in
	// the opening_transaction.
	Pubkey string `json:"pubkey"`
	// Payreq is a BOLT#11 invoice with an amount that covers the fee expenses
	// for the on-chain transactions.
	Payreq string
}

SwapOutAgreementMessage is the response by the swap-out peer if he accepts the swap it contains an Invoice that the swap-out initiator must pay.

func (SwapOutAgreementMessage) ApplyToSwapData

func (s SwapOutAgreementMessage) ApplyToSwapData(swap *SwapData) error

func (SwapOutAgreementMessage) MessageType

func (SwapOutAgreementMessage) Validate

func (s SwapOutAgreementMessage) Validate(swap *SwapData) error

type SwapOutRequestMessage

type SwapOutRequestMessage struct {
	// ProtocolVersion is the version of the PeerSwap peer protocol the sending
	// node uses.
	ProtocolVersion uint8 `json:"protocol_version"`
	// SwapId is a randomly generated 32 byte string that must be kept the same
	// through the whole process of a swap and serves as an identifier for a
	// specific swap.
	SwapId *SwapId `json:"swap_id"`
	// Asset is the desired on-chain asset to use. This can be:
	// Bitcoin: The field is left blank.
	// Liquid: The asset id of the networks Bitcoin asset.
	Asset string `json:"asset"`
	// Network is the desired on-chain network to use. This can be:
	// Bitcoin: mainnet, testnet, signet, regtest
	// Liquid: The field is left blank as the asset id also defines the bitcoinNetwork.
	Network string `json:"network"`
	// Scid is the short channel id in human readable format, defined by BOLT#7
	// with x as separator, e.g. 539268x845x1.
	Scid string `json:"scid"`
	// Amount is The amount in Sats that is asked for.
	Amount uint64 `json:"amount"`
	// Pubkey is a 33 byte compressed public key used for the spending paths in
	// the opening_transaction.
	Pubkey string `json:"pubkey"`
}

SwapOutRequestMessage gets send when a peer wants to start a new swap.

func (SwapOutRequestMessage) ApplyToSwapData

func (s SwapOutRequestMessage) ApplyToSwapData(swap *SwapData) error

func (SwapOutRequestMessage) MessageType

func (s SwapOutRequestMessage) MessageType() messages.MessageType

func (SwapOutRequestMessage) Validate

func (s SwapOutRequestMessage) Validate(swap *SwapData) error

type SwapRole

type SwapRole int
const (
	SWAPROLE_SENDER SwapRole = iota + 1
	SWAPROLE_RECEIVER
)

func (SwapRole) String

func (s SwapRole) String() string

type SwapService

type SwapService struct {
	BitcoinEnabled bool
	LiquidEnabled  bool
	sync.RWMutex
	// contains filtered or unexported fields
}

SwapService contains the logic for swaps

func NewSwapService

func NewSwapService(services *SwapServices) *SwapService

func (*SwapService) AddActiveSwap

func (s *SwapService) AddActiveSwap(swapId string, swap *SwapStateMachine)

AddActiveSwap adds a swap to the active swaps

func (*SwapService) GetActiveSwap

func (s *SwapService) GetActiveSwap(swapId string) (*SwapStateMachine, error)

GetActiveSwap returns the active swap, or an error if it does not exist

func (*SwapService) GetSwap

func (s *SwapService) GetSwap(swapId string) (*SwapStateMachine, error)

func (*SwapService) HasActiveSwaps

func (s *SwapService) HasActiveSwaps() (bool, error)

func (*SwapService) ListActiveSwaps

func (s *SwapService) ListActiveSwaps() ([]*SwapStateMachine, error)

func (*SwapService) ListSwaps

func (s *SwapService) ListSwaps() ([]*SwapStateMachine, error)

ListSwaps returns all swaps stored

func (*SwapService) ListSwapsByPeer

func (s *SwapService) ListSwapsByPeer(peer string) ([]*SwapStateMachine, error)

ListSwapsByPeer only returns the swaps that are done with a specific peer

func (*SwapService) OnCancelReceived

func (s *SwapService) OnCancelReceived(swapId *SwapId, cancelMsg *CancelMessage) error

OnCancelReceived sends the CancelReceived event to the corresponding swap state machine

func (*SwapService) OnClaimInvoiceNotification

func (s *SwapService) OnClaimInvoiceNotification(swapId *SwapId) error

OnClaimInvoiceNotification sends the ClaimInvoicePaid event to the corresponding swap state machine

func (*SwapService) OnCoopCloseReceived

func (s *SwapService) OnCoopCloseReceived(swapId *SwapId, coopCloseMessage *CoopCloseMessage) error

OnCoopCloseReceived sends the CoopMessage event to the corresponding swap state mahcine

func (*SwapService) OnCsvPassed

func (s *SwapService) OnCsvPassed(swapId string) error

OnCsvPassed sends the csvpassed event to the corresponding swap

func (*SwapService) OnFeeInvoiceNotification

func (s *SwapService) OnFeeInvoiceNotification(swapId *SwapId) error

OnFeeInvoiceNotification sends the FeeInvoicePaid event to the corresponding swap state machine

func (*SwapService) OnMessageReceived

func (s *SwapService) OnMessageReceived(peerId string, msgTypeString string, payload []byte) error

OnMessageReceived handles incoming valid peermessages

func (*SwapService) OnPayment

func (s *SwapService) OnPayment(swapIdStr string, invoiceType InvoiceType)

OnPayment handles incoming payments and if it corresponds to a claim or fee invoice passes the dater to the corresponding function

func (*SwapService) OnSwapInAgreementReceived

func (s *SwapService) OnSwapInAgreementReceived(msg *SwapInAgreementMessage) error

OnSwapInAgreementReceived sends the agreementreceived event to the corresponding swap state machine

func (*SwapService) OnSwapInRequestReceived

func (s *SwapService) OnSwapInRequestReceived(swapId *SwapId, peerId string, message *SwapInRequestMessage) error

OnSwapInRequestReceived creates a new swap-in process and sends the event to the swap statemachine

func (*SwapService) OnSwapOutAgreementReceived

func (s *SwapService) OnSwapOutAgreementReceived(message *SwapOutAgreementMessage) error

OnSwapOutAgreementReceived sends the FeeInvoiceReceived event to the corresponding swap state machine

func (*SwapService) OnSwapOutRequestReceived

func (s *SwapService) OnSwapOutRequestReceived(swapId *SwapId, peerId string, message *SwapOutRequestMessage) error

OnSwapInRequestReceived creates a new swap-out process and sends the event to the swap statemachine

func (*SwapService) OnTxConfirmed

func (s *SwapService) OnTxConfirmed(swapId string, txHex string) error

OnTxConfirmed sends the txconfirmed event to the corresponding swap

func (*SwapService) OnTxOpenedMessage

func (s *SwapService) OnTxOpenedMessage(message *OpeningTxBroadcastedMessage) error

OnTxOpenedMessage sends the TxOpenedMessage event to the corresponding swap state machine

func (*SwapService) RecoverSwaps

func (s *SwapService) RecoverSwaps() error

RecoverSwaps tries to recover swaps that are not yet finished

func (*SwapService) RemoveActiveSwap

func (s *SwapService) RemoveActiveSwap(swapId string)

RemoveActiveSwap removes a swap from the active swap map

func (*SwapService) ResendLastMessage

func (s *SwapService) ResendLastMessage(swapId string) error

func (*SwapService) SenderOnTxConfirmed

func (s *SwapService) SenderOnTxConfirmed(swapId string) error

OnTxOpenedMessage sends the TxConfirmed event to the corresponding swap state machine

func (*SwapService) Start

func (s *SwapService) Start() error

Start adds callback to the messenger, txwatcher services and lightning client

func (*SwapService) SwapIn

func (s *SwapService) SwapIn(peer string, chain string, channelId string, initiator string, amtSat uint64) (*SwapStateMachine, error)

todo check prerequisites SwapIn starts a new swap in process

func (*SwapService) SwapOut

func (s *SwapService) SwapOut(peer string, chain string, channelId string, initiator string, amtSat uint64) (*SwapStateMachine, error)

todo move wallet and chain / channel validation logic here SwapOut starts a new swap out process

type SwapServices

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

func NewSwapServices

func NewSwapServices(
	swapStore Store,
	requestedSwapsStore RequestedSwapsStore,
	lightning LightningClient,
	messenger Messenger,
	messengerManager MessengerManager,
	policy Policy,
	bitcoinEnabled bool,
	bitcoinWallet Wallet,
	bitcoinValidator Validator,
	bitcoinTxWatcher TxWatcher,
	liquidEnabled bool,
	liquidWallet Wallet,
	liquidValidator Validator,
	liquidTxWatcher TxWatcher) *SwapServices

type SwapStateMachine

type SwapStateMachine struct {
	// Id holds the unique Id for the store
	SwapId *SwapId `json:"swap_id"`

	// Data holds the statemachine metadata
	Data *SwapData `json:"data"`

	// Type holds the SwapType
	Type SwapType `json:"type"`

	// Role holds the local Role
	Role SwapRole `json:"role"`

	// Previous represents the previous state.
	Previous StateType `json:"previous"`

	// Current represents the current state.
	Current StateType `json:"current"`

	// States holds the configuration of states and events handled by the state machine.
	States States `json:"-"`
	// contains filtered or unexported fields
}

SwapStateMachine represents the state machine.

func (*SwapStateMachine) EventIsValid

func (s *SwapStateMachine) EventIsValid(event EventType) bool

EventIsValid returns true if the event is valid for the current statemachine transition

func (*SwapStateMachine) Infof

func (s *SwapStateMachine) Infof(format string, v ...interface{})

func (*SwapStateMachine) IsFinished

func (s *SwapStateMachine) IsFinished() bool

IsFinished returns true if the swap is already finished

func (*SwapStateMachine) Recover

func (s *SwapStateMachine) Recover() (bool, error)

Recover tries to continue from the current state, by doing the associated Action

func (*SwapStateMachine) SendEvent

func (s *SwapStateMachine) SendEvent(event EventType, eventCtx EventContext) (bool, error)

SendEvent sends an event to the state machine.

type SwapType

type SwapType int
const (
	SWAPTYPE_IN SwapType = iota + 1
	SWAPTYPE_OUT
)

SwapType in means the initiator wants to pay lbtc to rebalance the channel to his side swap out means the initiator wants to pay an invoice to rebalance the the channel to his peer

func (SwapType) JsonFieldValue

func (s SwapType) JsonFieldValue() string

func (SwapType) String

func (s SwapType) String() string

type TakerSendPrivkeyAction

type TakerSendPrivkeyAction struct{}

TakerSendPrivkeyAction builds the sighash to send the maker for cooperatively closing the swap

func (*TakerSendPrivkeyAction) Execute

func (s *TakerSendPrivkeyAction) Execute(services *SwapServices, swap *SwapData) EventType

type TimeOutService

type TimeOutService interface {
	// contains filtered or unexported methods
}

type TxWatcher

type TxWatcher interface {
	AddWaitForConfirmationTx(swapId, txId string, vout, startingHeight uint32, scriptpubkey []byte)
	AddWaitForCsvTx(swapId, txId string, vout uint32, startingHeight uint32, scriptpubkey []byte)
	AddConfirmationCallback(func(swapId string, txHex string) error)
	AddCsvCallback(func(swapId string) error)
	GetBlockHeight() (uint32, error)
}

type ValidateTxAndPayClaimInvoiceAction

type ValidateTxAndPayClaimInvoiceAction struct{}

ValidateTxAndPayClaimInvoiceAction pays the claim invoice

func (*ValidateTxAndPayClaimInvoiceAction) Execute

type Validator

type Validator interface {
	TxIdFromHex(txHex string) (string, error)
	ValidateTx(swapParams *OpeningParams, txHex string) (bool, error)
	GetCSVHeight() uint32
}

type Wallet

type Wallet interface {
	CreateOpeningTransaction(swapParams *OpeningParams) (unpreparedTxHex string, fee uint64, vout uint32, err error)
	BroadcastOpeningTx(unpreparedTxHex string) (txId, txHex string, error error)
	CreatePreimageSpendingTransaction(swapParams *OpeningParams, claimParams *ClaimParams) (string, string, error)
	CreateCsvSpendingTransaction(swapParams *OpeningParams, claimParams *ClaimParams) (txId, txHex string, error error)
	CreateCoopSpendingTransaction(swapParams *OpeningParams, claimParams *ClaimParams, takerSigner Signer) (txId, txHex string, error error)
	GetOutputScript(params *OpeningParams) ([]byte, error)
	NewAddress() (string, error)
	GetRefundFee() (uint64, error)
	GetFlatSwapOutFee() (uint64, error)
	GetAsset() string
	GetNetwork() string
	GetOnchainBalance() (uint64, error)
}

type WrongAssetError

type WrongAssetError string

func (WrongAssetError) Error

func (e WrongAssetError) Error() string

Jump to

Keyboard shortcuts

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