tapchannel

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2024 License: MIT Imports: 53 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultTimeout is the default timeout we use for RPC and database
	// operations.
	DefaultTimeout = 30 * time.Second
)
View Source
const (
	// MsgEndpointName is the name of the endpoint that we'll use to
	// register the funding controller with the peer message handler.
	MsgEndpointName = "taproot assets channel funding"
)
View Source
const Subsystem = "TCHN" // TCHN as in Taproot Assets Channels.

Subsystem defines the logging code for this subsystem.

Variables

View Source
var (
	// ErrMissingInputs is an error that is returned if no inputs were
	// provided.
	ErrMissingInputs = fmt.Errorf("no inputs provided")

	// ErrMissingAllocations is an error that is returned if no allocations
	// were provided.
	ErrMissingAllocations = fmt.Errorf("no allocations provided")

	// ErrInputOutputSumMismatch is an error that is returned if the sum of
	// the input asset proofs does not match the sum of the output
	// allocations.
	ErrInputOutputSumMismatch = fmt.Errorf("input and output sum mismatch")

	// ErrNormalAssetsOnly is an error that is returned if an allocation
	// contains an asset that is not a normal asset (e.g. a collectible).
	ErrNormalAssetsOnly = fmt.Errorf("only normal assets are supported")

	// ErrCommitmentNotSet is an error that is returned if the output
	// commitment is not set for an allocation.
	ErrCommitmentNotSet = fmt.Errorf("output commitment not set")
)
View Source
var (
	// DefaultOnChainHtlcAmount is the default amount that we consider
	// as the smallest HTLC amount that can be sent on-chain. This needs to
	// be greater than the dust limit for an HTLC.
	DefaultOnChainHtlcAmount = lnwallet.DustLimitForSize(
		input.UnknownWitnessSize,
	)
)

Functions

func ApplyHtlcView

func ApplyHtlcView(chainParams *address.ChainParams,
	chanState *channeldb.OpenChannel, prevBlob tlv.Blob,
	originalView *lnwallet.HtlcView, isOurCommit bool,
	ourBalance, theirBalance lnwire.MilliSatoshi,
	keys lnwallet.CommitmentKeyRing) (lfn.Option[tlv.Blob], error)

ApplyHtlcView serves as the state transition function for the custom channel's blob. Given the old blob, and an HTLC view, then a new blob should be returned that reflects the pending updates.

func AssignOutputCommitments

func AssignOutputCommitments(allocations []*Allocation,
	outCommitments tappsbt.OutputCommitments) error

AssignOutputCommitments assigns the output commitments keyed by the output index to the corresponding allocations.

func CreateSecondLevelHtlcTx

func CreateSecondLevelHtlcTx(chanState *channeldb.OpenChannel,
	commitTx *wire.MsgTx, htlcAmt btcutil.Amount,
	keys lnwallet.CommitmentKeyRing, chainParams *address.ChainParams,
	htlcOutputs []*cmsg.AssetOutput) (input.AuxTapLeaf, error)

CreateSecondLevelHtlcTx creates the auxiliary leaf for a successful or timed out second level HTLC transaction.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func DistributeCoins

func DistributeCoins(inputs []*proof.Proof, allocations []*Allocation,
	chainParams *address.ChainParams) ([]*tappsbt.VPacket, error)

DistributeCoins allocates a set of inputs (extracted from the given input proofs) to virtual outputs as specified by the allocations given. It returns a list of virtual packets (one for each distinct asset ID) with virtual outputs that sum up to the amounts specified in the allocations. The main purpose of this function is to deterministically re-distribute heterogeneous asset outputs (asset UTXOs of different sizes from different tranches/asset IDs) according to the distribution rules provided as "allocations".

func FakeCommitTx

func FakeCommitTx(fundingOutpoint wire.OutPoint,
	allocations []*Allocation) (*wire.MsgTx, error)

FakeCommitTx creates a fake commitment on-chain transaction from the given funding outpoint and allocations. The transaction is not signed.

func FetchLeavesFromCommit

FetchLeavesFromCommit attempts to fetch the auxiliary leaves that correspond to the passed aux blob, and an existing channel commitment.

func FetchLeavesFromRevocation

func FetchLeavesFromRevocation(
	rev *channeldb.RevocationLog) (lfn.Option[lnwallet.CommitAuxLeaves],
	error)

FetchLeavesFromRevocation attempts to fetch the auxiliary leaves from a channel revocation that stores balance + blob information.

func FetchLeavesFromView

func FetchLeavesFromView(chainParams *address.ChainParams,
	chanState *channeldb.OpenChannel, prevBlob tlv.Blob,
	originalView *lnwallet.HtlcView, isOurCommit bool, ourBalance,
	theirBalance lnwire.MilliSatoshi,
	keys lnwallet.CommitmentKeyRing) (lfn.Option[lnwallet.CommitAuxLeaves],
	lnwallet.CommitSortFunc, error)

FetchLeavesFromView attempts to fetch the auxiliary leaves that correspond to the passed aux blob, and pending fully evaluated HTLC view.

func FilterByType

func FilterByType(allocType AllocationType) func(a *Allocation) bool

FilterByType returns a filter function that can be used to filter a list of allocations by the given allocation type.

func FilterByTypeExclude

func FilterByTypeExclude(
	excludeAllocType AllocationType) func(a *Allocation) bool

FilterByTypeExclude returns a filter function that can be used to filter a list of allocations by excluding the given allocation type.

func InPlaceAllocationSort

func InPlaceAllocationSort(allocations []*Allocation)

InPlaceAllocationSort performs an in-place sort of output allocations.

The sort applied is a modified BIP69 sort, that uses the CLTV values of HTLCs as a tiebreaker in case two HTLC outputs have an identical amount and pkScript. The pkScripts can be the same if they share the same payment hash, but since the CLTV is enforced via the nLockTime of the second-layer transactions, the script does not directly commit to them. Instead, the CLTVs must be supplied separately to act as a tie-breaker, otherwise we may produce invalid HTLC signatures if the receiver produces an alternative ordering during verification.

NOTE: Commitment and commitment anchor outputs should have a 0 CLTV value.

func InPlaceCustomCommitSort

func InPlaceCustomCommitSort(tx *wire.MsgTx, cltvs []uint32,
	htlcIndexes []input.HtlcIndex, allocations []*Allocation) error

InPlaceCustomCommitSort performs an in-place sort of a transaction, given a list of allocations. The sort is applied to the transaction outputs, using the allocation's OutputIndex. The transaction inputs are sorted by the default BIP69 sort.

func LeavesFromTapscriptScriptTree

func LeavesFromTapscriptScriptTree(
	scriptTree input.ScriptDescriptor) ([]txscript.TapLeaf,
	input.ScriptTree, error)

LeavesFromTapscriptScriptTree creates a tapscript sibling from a commit script tree.

func NonAssetExclusionProofs

func NonAssetExclusionProofs(
	allocations []*Allocation) tapsend.ExclusionProofGenerator

NonAssetExclusionProofs returns an exclusion proof generator that creates exclusion proofs for non-asset P2TR outputs in the given allocations.

func PackSigs

func PackSigs(sigBlob []lfn.Option[tlv.Blob]) (lfn.Option[tlv.Blob], error)

PackSigs takes a series of aux signatures and packs them into a single blob that can be sent alongside the CommitSig messages.

func SanityCheckAmounts

func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount,
	ourAssetBalance, theirAssetBalance uint64, view *DecodedView,
	chanType channeldb.ChannelType, isOurs bool,
	dustLimit btcutil.Amount) (bool, bool, error)

SanityCheckAmounts makes sure that any output that carries an asset has a non-dust satoshi balance. It also checks and returns whether we need a local and/or remote anchor output.

func ToCommitment

func ToCommitment(allocations []*Allocation,
	vPackets []*tappsbt.VPacket) (*cmsg.Commitment, error)

ToCommitment converts the allocations to a Commitment struct.

func UnpackSigs

func UnpackSigs(blob lfn.Option[tlv.Blob]) ([]lfn.Option[tlv.Blob], error)

UnpackSigs takes a packed blob of signatures and returns the original signatures for each HTLC, keyed by HTLC index.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

func VerifySecondLevelSigs

func VerifySecondLevelSigs(chainParams *address.ChainParams,
	chanState *channeldb.OpenChannel, commitTx *wire.MsgTx,
	verifyJobs []lnwallet.AuxVerifyJob) error

VerifySecondLevelSigs attempts to synchronously verify a batch of aux sig jobs.

Types

type Allocation

type Allocation struct {
	// Type is the type of the asset allocation.
	Type AllocationType

	// OutputIndex is the output index of the on-chain transaction which
	// the asset allocation is meant for.
	OutputIndex uint32

	// SplitRoot indicates whether the virtual output(s) created for the
	// allocation should house the split root asset.
	SplitRoot bool

	// InternalKey is the internal key used for the on-chain transaction
	// output.
	InternalKey *btcec.PublicKey

	// NonAssetLeaves is the full list of TapLeaf nodes that aren't any
	// asset commitments. This is used to construct the tapscript sibling
	// for the asset commitment. If this is a non-asset allocation and the
	// list of leaves is empty, then we assume a BIP-0086 output.
	NonAssetLeaves []txscript.TapLeaf

	// ScriptKey is the Taproot tweaked key encoding the different spend
	// conditions possible for the asset allocation.
	ScriptKey asset.ScriptKey

	// Amount is the amount of units that should be allocated in total.
	// Available units from different UTXOs are distributed up to this total
	// amount in a deterministic way.
	Amount uint64

	// AssetVersion is the version that the asset allocation should use.
	AssetVersion asset.Version

	// BtcAmount is the amount of BTC that should be sent to the output
	// address of the anchor transaction.
	BtcAmount btcutil.Amount

	// SortTaprootKeyBytes is the Schnorr serialized Taproot output key of
	// the on-chain P2TR output that would be created if there was no asset
	// commitment present. This field should be used for sorting purposes.
	SortTaprootKeyBytes []byte

	// CLTV is the CLTV timeout for the asset allocation. This is only
	// relevant for sorting purposes and is expected to be zero for any
	// non-HTLC allocation.
	CLTV uint32

	// Sequence is the CSV value for the asset allocation. This is only
	// relevant for HTLC second level transactions.
	Sequence uint32

	// HtlcIndex is the index of the HTLC that the allocation is for. This
	// is only relevant for HTLC allocations.
	HtlcIndex input.HtlcIndex

	// OutputCommitment is the taproot output commitment that is set after
	// fully distributing the coins and creating the asset and TAP trees.
	OutputCommitment *commitment.TapCommitment

	// ProofDeliveryAddress is the address the proof courier should use to
	// upload the proof for this allocation.
	ProofDeliveryAddress *url.URL
}

Allocation is a struct that tracks how many units of assets should be allocated to a specific output of an on-chain transaction. An allocation can be seen as a recipe/instruction to distribute a certain number of asset units to a specific output of an on-chain transaction. The output is mainly identified by its output index but also carries along additional information that is required for making sure the resulting on-chain outputs can be sorted in a deterministic way (that is almost but not exactly following the BIP-69 rules for sorting transaction outputs).

func CreateAllocations

func CreateAllocations(chanState *channeldb.OpenChannel, ourBalance,
	theirBalance btcutil.Amount, ourAssetBalance, theirAssetBalance uint64,
	wantLocalCommitAnchor, wantRemoteCommitAnchor bool,
	filteredView *DecodedView, isOurCommit bool,
	keys lnwallet.CommitmentKeyRing,
	nonAssetView *lnwallet.HtlcView) ([]*Allocation, error)

CreateAllocations creates the allocations for the channel state.

func CreateSecondLevelHtlcPackets

func CreateSecondLevelHtlcPackets(chanState *channeldb.OpenChannel,
	commitTx *wire.MsgTx, htlcAmt btcutil.Amount,
	keys lnwallet.CommitmentKeyRing, chainParams *address.ChainParams,
	htlcOutputs []*cmsg.AssetOutput) ([]*tappsbt.VPacket, []*Allocation,
	error)

CreateSecondLevelHtlcPackets creates the virtual packets for the second level HTLC transaction.

func GenerateCommitmentAllocations

func GenerateCommitmentAllocations(prevState *cmsg.Commitment,
	chanState *channeldb.OpenChannel, chanAssetState *cmsg.OpenChannel,
	isOurCommit bool, ourBalance, theirBalance lnwire.MilliSatoshi,
	originalView *lnwallet.HtlcView, chainParams *address.ChainParams,
	keys lnwallet.CommitmentKeyRing) ([]*Allocation, *cmsg.Commitment,
	error)

GenerateCommitmentAllocations generates allocations for a channel commitment.

func (*Allocation) AuxLeaf

func (a *Allocation) AuxLeaf() (txscript.TapLeaf, error)

AuxLeaf returns the auxiliary leaf for the allocation. If the output commitment is not set, ErrCommitmentNotSet is returned.

func (*Allocation) MatchesOutput

func (a *Allocation) MatchesOutput(pkScript []byte, value int64, cltv uint32,
	htlcIndex input.HtlcIndex) (bool, error)

MatchesOutput returns true if the unique identifying characteristics of an on-chain commitment output match this allocation. The pkScript is calculated from the internal key, tapscript sibling and merkle root of the output commitment. If the output commitment is not set an error is returned.

type AllocationType

type AllocationType uint8

AllocationType is an enum that defines the different types of asset allocations that can be created.

const (
	// AllocationTypeNoAssets is the default allocation type that is used
	// when the allocation type is not important or the allocation does not
	// carry any assets.
	AllocationTypeNoAssets AllocationType = 0

	// CommitAllocationToLocal is an allocation type that is used for
	// allocating assets to the local party.
	CommitAllocationToLocal AllocationType = 1

	// CommitAllocationToRemote is an allocation type that is used for
	// allocating assets to the remote party.
	CommitAllocationToRemote AllocationType = 2

	// CommitAllocationHtlcIncoming is an allocation type that is used for
	// allocating assets to an incoming HTLC output.
	CommitAllocationHtlcIncoming AllocationType = 3

	// CommitAllocationHtlcOutgoing is an allocation type that is used for
	// allocating assets to an outgoing HTLC output.
	CommitAllocationHtlcOutgoing AllocationType = 4

	// SecondLevelHtlcAllocation is an allocation type that is used for
	// allocating assets to a second level HTLC output (HTLC-success for
	// HTLCs accepted by the local node, HTLC-timeout for HTLCs offered by
	// the local node).
	SecondLevelHtlcAllocation AllocationType = 5
)

type AssetChanIntent

type AssetChanIntent interface {
	// FundingPsbt is the original PsbtTemplate, plus the P2TR funding
	// output that'll create the channel.
	FundingPsbt() (*psbt.Packet, error)

	// BindPsbt accepts a new *unsigned* PSBT with any additional inputs or
	// outputs (for change) added. This PSBT is still unsigned. This step
	// performs final verification to ensure the PSBT is crafted in a manner
	// that'll properly open the channel once broadcaster.
	BindPsbt(context.Context, *psbt.Packet) error
}

AssetChanIntent is a handle returned by the PsbtChannelFunder that can be used to drive the new asset channel to completion. The intent includes the PSBT template returned by lnd which has the funding output for the new channel already populated.

type AssetSyncer

type AssetSyncer interface {
	// QueryAssetInfo attempts to locate asset genesis information by
	// querying geneses already known to this node. If asset issuance was
	// not previously verified, we then query universes in our federation
	// for issuance proofs.
	QueryAssetInfo(ctx context.Context,
		id asset.ID) (*asset.AssetGroup, error)
}

AssetSyncer is used to ensure that we know of the set of assets that'll be used as funding input to an accepted channel.

type AuxChanCloser

type AuxChanCloser struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

AuxChanCloser is used to implement asset-aware co-op close for channels.

func NewAuxChanCloser

func NewAuxChanCloser(cfg AuxChanCloserCfg) *AuxChanCloser

NewAuxChanCloser creates a new instance of the auxiliary channel closer.

func (*AuxChanCloser) AuxCloseOutputs

AuxCloseOutputs returns the set of close outputs to use for this co-op close attempt. We'll add some extra outputs to the co-op close transaction, and also give the caller a custom sorting routine.

NOTE: This method is part of the chancloser.AuxChanCloser interface.

func (*AuxChanCloser) FinalizeClose

func (a *AuxChanCloser) FinalizeClose(desc chancloser.AuxCloseDesc,
	closeTx *wire.MsgTx) error

FinalizeClose is called once the co-op close transaction has been agreed upon. We'll finalize the exclusion proofs, then send things off to the custodian or porter to finish sending/receiving the proofs.

NOTE: This method is part of the chancloser.AuxChanCloser interface.

func (*AuxChanCloser) ShutdownBlob

ShutdownBlob returns the set of custom records that should be included in the shutdown message.

NOTE: This method is part of the chancloser.AuxChanCloser interface.

type AuxChanCloserCfg

type AuxChanCloserCfg struct {
	// ChainParams describes the params for the chain we're on.
	ChainParams *address.ChainParams

	// AddrBook is what we'll use to generate new keys for the co-op close
	// transaction, and also import proof for our settled outputs as the
	// non-initiator.
	AddrBook *address.Book

	// TxSender is what we'll use to broadcast a transaction to the
	// network, while ensuring we also update all our asset and UTXO state
	// on disk (insert a proper transfer, etc., etc.).
	TxSender tapfreighter.Porter

	// DefaultCourierAddr is the default address we'll use to send/receive
	// proofs for the co-op close process
	DefaultCourierAddr *url.URL

	// ProofFetcher is used to fetch proofs needed to properly import the
	// funding output into the database as our own.
	ProofFetcher proof.CourierDispatch

	// ProofArchive is used to store import funding output proofs.
	ProofArchive proof.Archiver

	// HeaderVerifier is used to verify headers in a proof.
	HeaderVerifier proof.HeaderVerifier

	// GroupVerifier is used to verify group keys in a proof.
	GroupVerifier proof.GroupVerifier

	// ChainBridge is used to fetch blocks from the main chain.
	ChainBridge tapgarden.ChainBridge
}

AuxChanCloserCfg houses the configuration for the auxiliary channel closer.

type AuxInvoiceManager

type AuxInvoiceManager struct {

	// ContextGuard provides a wait group and main quit channel that can be
	// used to create guarded contexts.
	*fn.ContextGuard
	// contains filtered or unexported fields
}

AuxInvoiceManager is a Taproot Asset auxiliary invoice manager that can be used to make invoices to receive Taproot Assets.

func NewAuxInvoiceManager

func NewAuxInvoiceManager(cfg *InvoiceManagerConfig) *AuxInvoiceManager

NewAuxInvoiceManager creates a new Taproot Asset auxiliary invoice manager based on the passed config.

func (*AuxInvoiceManager) Start

func (s *AuxInvoiceManager) Start() error

Start attempts to start a new aux invoice manager.

func (*AuxInvoiceManager) Stop

func (s *AuxInvoiceManager) Stop() error

Stop signals for an aux invoice manager to gracefully exit.

type AuxLeafSigner

type AuxLeafSigner struct {

	// ContextGuard provides a wait group and main quit channel that can be
	// used to create guarded contexts.
	*fn.ContextGuard
	// contains filtered or unexported fields
}

AuxLeafSigner is a Taproot Asset auxiliary leaf signer that can be used to sign auxiliary leaves for Taproot Asset channels.

func NewAuxLeafSigner

func NewAuxLeafSigner(cfg *LeafSignerConfig) *AuxLeafSigner

NewAuxLeafSigner creates a new Taproot Asset auxiliary leaf signer based on the passed config.

func (*AuxLeafSigner) Start

func (s *AuxLeafSigner) Start() error

Start attempts to start a new aux leaf signer.

func (*AuxLeafSigner) Stop

func (s *AuxLeafSigner) Stop() error

Stop signals for a aux leaf signer to gracefully exit.

func (*AuxLeafSigner) SubmitSecondLevelSigBatch

func (s *AuxLeafSigner) SubmitSecondLevelSigBatch(
	chanState *channeldb.OpenChannel, commitTx *wire.MsgTx,
	jobs []lnwallet.AuxSigJob) error

SubmitSecondLevelSigBatch takes a batch of aux sign jobs and processes them asynchronously.

type AuxSweeper

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

AuxSweeper is used to sweep funds from a commitment transaction that has been broadcast on chain (a force close). This subsystem interacts with the contract resolution and sweeping subsystems of lnd.

func NewAuxSweeper

func NewAuxSweeper(cfg *AuxSweeperCfg) *AuxSweeper

NewAuxSweeper creates a new instance of the AuxSweeper from the specified config.

func (*AuxSweeper) DeriveSweepAddr

func (a *AuxSweeper) DeriveSweepAddr(inputs []input.Input,
	change lnwallet.AddrWithKey) lfn.Result[sweep.SweepOutput]

DeriveSweepAddr takes a set of inputs, and the change address we'd use to sweep them, and maybe results an extra sweep output that we should add to the sweeping transaction.

func (*AuxSweeper) NotifyBroadcast

func (a *AuxSweeper) NotifyBroadcast(req *sweep.BumpRequest,
	tx *wire.MsgTx, fee btcutil.Amount) error

NotifyBroadcast is used to notify external callers of the broadcast of a sweep transaction, generated by the passed BumpRequest.

func (*AuxSweeper) ResolveContract

func (a *AuxSweeper) ResolveContract(
	req lnwallet.ResolutionReq) lfn.Result[tlv.Blob]

ResolveContract attempts to obtain a resolution blob for the specified contract.

func (*AuxSweeper) Start

func (a *AuxSweeper) Start() error

Start starts the AuxSweeper.

func (*AuxSweeper) Stop

func (a *AuxSweeper) Stop() error

Stop stops the AuxSweeper.

type AuxSweeperCfg

type AuxSweeperCfg struct {
	// AddrBook is the address book that the signer will use to generate
	// new script and internal keys for sweeping purposes.
	AddrBook *address.Book

	// ChainParams are the chain parameters of the network the signer is
	// operating on.
	ChainParams address.ChainParams

	// Signer is the backing wallet that can sign virtual packets.
	Signer VirtualPacketSigner

	// TxSender is what we'll use to broadcast a transaction to the
	// network, while ensuring we also update all our asset and UTXO state
	// on disk (insert a proper transfer, etc., etc.).
	TxSender tapfreighter.Porter

	// DefaultCourierAddr is the default address the funding controller uses
	// to deliver the funding output proofs to the channel peer.
	DefaultCourierAddr *url.URL

	// ProofFetcher is used to fetch proofs needed to properly import the
	// funding output into the database as our own.
	ProofFetcher proof.CourierDispatch

	// ProofArchive is used to store import funding output proofs.
	ProofArchive proof.Archiver

	// HeaderVerifier is used to verify headers in a proof.
	HeaderVerifier proof.HeaderVerifier

	// GroupVerifier is used to verify group keys in a proof.
	GroupVerifier proof.GroupVerifier

	// ChainBridge is used to fetch blocks from the main chain.
	ChainBridge tapgarden.ChainBridge
}

AuxSweeperCfg holds the configuration for the AuxSweeper.

type AuxTrafficShaper

type AuxTrafficShaper struct {

	// ContextGuard provides a wait group and main quit channel that can be
	// used to create guarded contexts.
	*fn.ContextGuard
	// contains filtered or unexported fields
}

AuxTrafficShaper is a Taproot Asset auxiliary traffic shaper that can be used to make routing decisions for Taproot Asset channels.

func NewAuxTrafficShaper

func NewAuxTrafficShaper(cfg *TrafficShaperConfig) *AuxTrafficShaper

NewAuxTrafficShaper creates a new Taproot Asset auxiliary traffic shaper based on the passed config.

func (*AuxTrafficShaper) HandleTraffic

func (s *AuxTrafficShaper) HandleTraffic(_ lnwire.ShortChannelID,
	fundingBlob lfn.Option[tlv.Blob]) (bool, error)

HandleTraffic is called in order to check if the channel identified by the provided channel ID is handled by the traffic shaper implementation. If it is handled by the traffic shaper, then the normal bandwidth calculation can be skipped and the bandwidth returned by PaymentBandwidth should be used instead.

func (*AuxTrafficShaper) PaymentBandwidth

func (s *AuxTrafficShaper) PaymentBandwidth(htlcBlob,
	commitmentBlob lfn.Option[tlv.Blob],
	linkBandwidth lnwire.MilliSatoshi) (lnwire.MilliSatoshi, error)

PaymentBandwidth returns the available bandwidth for a custom channel decided by the given channel aux blob and HTLC blob. A return value of 0 means there is no bandwidth available. To find out if a channel is a custom channel that should be handled by the traffic shaper, the HandleTraffic method should be called first.

func (*AuxTrafficShaper) ProduceHtlcExtraData

func (s *AuxTrafficShaper) ProduceHtlcExtraData(totalAmount lnwire.MilliSatoshi,
	htlcCustomRecords lnwire.CustomRecords) (lnwire.MilliSatoshi, tlv.Blob,
	error)

ProduceHtlcExtraData is a function that, based on the previous custom record blob of an HTLC, may produce a different blob or modify the amount of bitcoin this HTLC should carry.

func (*AuxTrafficShaper) Start

func (s *AuxTrafficShaper) Start() error

Start attempts to start a new aux traffic shaper.

func (*AuxTrafficShaper) Stop

func (s *AuxTrafficShaper) Stop() error

Stop signals for an aux traffic shaper to gracefully exit.

type DecodedDescriptor

type DecodedDescriptor struct {
	// PaymentDescriptor is the original payment descriptor.
	*lnwallet.PaymentDescriptor

	// AssetBalances is the decoded asset balances of the HTLC.
	AssetBalances []*rfqmsg.AssetBalance
}

DecodedDescriptor is a wrapper around a PaymentDescriptor that also includes the decoded asset balances of the HTLC to avoid multiple decoding round trips.

type DecodedView

type DecodedView struct {
	// OurUpdates is a list of decoded descriptors for our updates.
	OurUpdates []*DecodedDescriptor

	// TheirUpdates is a list of decoded descriptors for their updates.
	TheirUpdates []*DecodedDescriptor

	// FeePerKw is the current commitment fee rate.
	FeePerKw chainfee.SatPerKWeight
}

DecodedView is a copy of the original HTLC view, but with the asset balances of the HTLCs decoded.

func ComputeView

func ComputeView(ourBalance, theirBalance uint64, isOurCommit bool,
	original *lnwallet.HtlcView) (uint64, uint64, *DecodedView,
	*lnwallet.HtlcView, error)

ComputeView processes all update entries in both HTLC update logs, producing a final view which is the result of properly applying all adds, settles, timeouts and fee updates found in both logs. The resulting view returned reflects the current state of HTLCs within the remote or local commitment chain, and the current commitment fee rate.

type ErrorReporter

type ErrorReporter interface {
	// ReportError reports an error that occurred during the funding
	// process.
	ReportError(ctx context.Context, peer btcec.PublicKey,
		pid funding.PendingChanID, err error)
}

ErrorReporter is used to report an error back to the caller and/or peer that we're communicating with.

type FundReq

type FundReq struct {
	// PeerPub is the public key of the peer that we're funding a channel
	// with.
	//
	// TODO(roasbeef): also need p2p address?
	PeerPub btcec.PublicKey

	// AssetID is the asset that we're funding the channel with.
	AssetID asset.ID

	// AssetAmount is the amount of the asset that we're funding the channel
	// with.
	AssetAmount uint64

	// FeeRate is the fee rate that we'll use to fund the channel.
	FeeRate chainfee.SatPerVByte

	// PushAmount is the amount of satoshis that we'll push to the remote
	// party.
	PushAmount btcutil.Amount
	// contains filtered or unexported fields
}

FundReq is a message that's sent to the funding controller to request a new asset channel funding.

type FundingController

type FundingController struct {

	// ContextGuard provides a wait group and main quit channel that can be
	// used to create guarded contexts.
	*fn.ContextGuard
	// contains filtered or unexported fields
}

FundingController is used to drive TAP aware channel funding using a backing lnd node and an active connection to a tapd instance.

func NewFundingController

func NewFundingController(cfg FundingControllerCfg) *FundingController

NewFundingController creates a new instance of the FundingController.

func (*FundingController) CanHandle

func (f *FundingController) CanHandle(msg protofsm.PeerMsg) bool

CanHandle returns true if the target message can be routed to this endpoint.

func (*FundingController) ChannelFinalized

func (f *FundingController) ChannelFinalized(pid funding.PendingChanID) error

ChannelFinalized is called once lnd has received a valid commit signature for our local commitment. At this point, it's safe to broadcast the funding transaction.

func (*FundingController) ChannelReady

func (f *FundingController) ChannelReady(channel *channeldb.OpenChannel) error

ChannelReady is called when a channel has been fully opened and is ready to be used. This can be used to perform any final setup or cleanup.

func (*FundingController) DeriveTapscriptRoot

func (f *FundingController) DeriveTapscriptRoot(
	pid funding.PendingChanID) (lfn.Option[chainhash.Hash], error)

DeriveTapscriptRoot returns the tapscript root for the channel identified by the pid. If we don't have any information about the channel, we return None.

func (*FundingController) DescFromPendingChanID

func (f *FundingController) DescFromPendingChanID(pid funding.PendingChanID,
	openChan *channeldb.OpenChannel, localKeyRing,
	remoteKeyRing lnwallet.CommitmentKeyRing,
	initiator bool) (lfn.Option[lnwallet.AuxFundingDesc], error)

DescFromPendingChanID takes a pending channel ID, that may already be known due to prior custom channel messages, and maybe returns an aux funding desc which can be used to modify how a channel is funded.

func (*FundingController) FundChannel

func (f *FundingController) FundChannel(ctx context.Context,
	req FundReq) (*wire.OutPoint, error)

FundChannel attempts to fund a new channel with the backing lnd node based on the passed funding request. If successful, the TXID of the funding transaction is returned.

func (*FundingController) Name

func (f *FundingController) Name() string

Name returns the name of this endpoint. This MUST be unique across all registered endpoints.

func (*FundingController) SendMessage

func (f *FundingController) SendMessage(msg protofsm.PeerMsg) bool

SendMessage handles the target message, and returns true if the message was able being processed.

func (*FundingController) Start

func (f *FundingController) Start() error

Start starts the funding controller.

func (*FundingController) Stop

func (f *FundingController) Stop() error

Stop stops the funding controller.

type FundingControllerCfg

type FundingControllerCfg struct {
	// HeaderVerifier is used to verify headers in a proof.
	HeaderVerifier proof.HeaderVerifier

	// GroupVerifier is used to verify group keys in a proof.
	GroupVerifier proof.GroupVerifier

	// ErrReporter is used to report errors back to the caller and/or peer.
	ErrReporter ErrorReporter

	// AssetWallet is the wallet that we'll use to handle the asset
	// specific steps of the funding process.
	AssetWallet tapfreighter.Wallet

	// CoinSelector is used to select assets for funding.
	CoinSelector tapfreighter.CoinSelector

	// AddrBook is used to manage script keys and addresses.
	AddrBook *tapdb.TapAddressBook

	// ChainParams is the chain params of the chain we operate on.
	ChainParams address.ChainParams

	// ChainBridge provides access to the chain for confirmation
	// notification, and other block related actions.
	ChainBridge tapfreighter.ChainBridge

	// GroupKeyIndex is used to query the group key for an asset ID.
	GroupKeyIndex tapsend.AssetGroupQuerier

	// PeerMessenger is used to send messages to a remote peer.
	PeerMessenger PeerMessenger

	// ChannelFunder is used to fund a new channel using a PSBT template.
	ChannelFunder PsbtChannelFunder

	// TxPublisher is used to publish transactions.
	TxPublisher TxPublisher

	// ChainWallet is the wallet that we'll use to handle the chain
	// specific
	ChainWallet tapfreighter.WalletAnchor

	// TxSender is what we'll use to broadcast a transaction to the
	// network, while ensuring we also update all our asset and UTXO state
	// on disk (insert a proper transfer, etc., etc.).
	TxSender tapfreighter.Porter

	// RfqManager is used to manage RFQs.
	RfqManager *rfq.Manager

	// DefaultCourierAddr is the default address the funding controller uses
	// to deliver the funding output proofs to the channel peer.
	DefaultCourierAddr *url.URL

	// AssetSyncer is used to ensure that we've already verified the asset
	// genesis for any assets used within channels.
	AssetSyncer AssetSyncer
}

FundingControllerCfg is a configuration struct that houses the necessary abstractions needed to drive funding.

type FundingScriptTree

type FundingScriptTree struct {
	input.ScriptTree
}

FundingScriptTree is a struct that contains the funding script tree for a custom channel.

func NewFundingScriptTree

func NewFundingScriptTree() *FundingScriptTree

NewFundingScriptTree creates a new funding script tree for a custom channel asset-level script key. The script tree is constructed with a simple OP_TRUE script that allows anyone to spend the output. This simplifies the funding process as no signatures for the asset-level witnesses need to be exchanged. This is still safe because the BTC level multi-sig output is still protected by a 2-of-2 MuSig2 output.

type InvoiceHtlcModifier

type InvoiceHtlcModifier interface {
	// HtlcModifier is a bidirectional streaming RPC that allows a client to
	// intercept and modify the HTLCs that attempt to settle the given
	// invoice. The server will send HTLCs of invoices to the client and the
	// client can modify some aspects of the HTLC in order to pass the
	// invoice acceptance tests.
	HtlcModifier(ctx context.Context,
		handler lndclient.InvoiceHtlcModifyHandler) error
}

InvoiceHtlcModifier is an interface that abstracts the invoice HTLC modification functionality required by the auxiliary invoice manager.

type InvoiceManagerConfig

type InvoiceManagerConfig struct {
	// ChainParams are the chain parameters of the chain we're operating on.
	ChainParams *address.ChainParams

	// InvoiceHtlcModifier is the HTLC modifier that will be used to
	// intercept and modify the HTLCs that attempt to settle a given
	// invoice.
	InvoiceHtlcModifier InvoiceHtlcModifier

	// RfqManager is the RFQ manager that will be used to retrieve the
	// accepted quotes for determining the incoming value of invoice related
	// HTLCs.
	RfqManager *rfq.Manager
}

InvoiceManagerConfig defines the configuration for the auxiliary invoice manager.

type LeafSignerConfig

type LeafSignerConfig struct {
	// ChainParams are the chain parameters of the network the signer is
	// operating on.
	ChainParams *address.ChainParams

	// Signer is the backing wallet that can sign virtual packets.
	Signer VirtualPacketSigner
}

LeafSignerConfig defines the configuration for the auxiliary leaf signer.

type OpenChanReq

type OpenChanReq struct {
	// ChanAmt is the amount of BTC to put into the channel. Some BTC is
	// required atm to pay on chain fees for the channel. Note that
	// additional fees can be added in the event of a force close by using
	// CPFP with the channel anchor outputs.
	ChanAmt btcutil.Amount

	// PushAmt is the amount of BTC to push to the remote peer.
	PushAmt btcutil.Amount

	// PeerPub is the identity public key of the remote peer we wish to
	// open the channel with.
	PeerPub btcec.PublicKey

	// TempPID is the temporary channel ID to use for this channel.
	TempPID funding.PendingChanID

	// PsbtTemplate is the PSBT template that we'll use to fund the channel.
	// This should already have all the inputs spending asset UTXOs added.
	PsbtTemplate *psbt.Packet
}

OpenChanReq is a request to open a new asset channel with a remote peer.

type PeerMessenger

type PeerMessenger interface {
	// SendMessage sends a message to a remote peer.
	SendMessage(ctx context.Context, peer btcec.PublicKey,
		msg lnwire.Message) error
}

PeerMessenger is an interface that allows us to send messages to a remote LN peer.

type PsbtChannelFunder

type PsbtChannelFunder interface {
	// OpenChannel attempts to open a new asset holding private channel
	// using the backing lnd node. The PSBT flow is by default. An
	// AssetChanIntent is returned that includes the updated PSBT template
	// that includes the funding output. Once all other inputs+outputs have
	// been added, then BindPsbt should be called to progress the funding
	// process. Afterward, the funding transaction should be signed and
	// broadcast.
	OpenChannel(context.Context, OpenChanReq) (AssetChanIntent, error)
}

PsbtChannelFunder is an interface that abstracts the necessary steps needed fund a PSBT channel on using lnd.

type TrafficShaperConfig

type TrafficShaperConfig struct {
	ChainParams *address.ChainParams

	RfqManager *rfq.Manager
}

TrafficShaperConfig defines the configuration for the auxiliary traffic shaper.

type TxPublisher

type TxPublisher interface {
	// PublishTransaction attempts to publish a new transaction to the
	// network.
	PublishTransaction(context.Context, *wire.MsgTx) error
}

TxPublisher is an interface used to publish transactions.

type VirtualPacketSigner

type VirtualPacketSigner interface {
	// SignVirtualPacket signs the virtual transaction of the given packet
	// and returns the input indexes that were signed.
	SignVirtualPacket(vPkt *tappsbt.VPacket,
		signOpts ...tapfreighter.SignVirtualPacketOption) ([]uint32,
		error)
}

VirtualPacketSigner is an interface that can be used to sign virtual packets.

Jump to

Keyboard shortcuts

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