lnwallet

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2016 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxPendingPayments is the max number of pending HTLC's permitted on
	// a channel.
	// TODO(roasbeef): make not random value + enforce
	//  * should be tuned to account for max tx "cost"
	MaxPendingPayments = 100

	// InitialRevocationWindow is the number of unrevoked commitment
	// transactions allowed within the commitment chain. This value allows
	// a greater degree of desynchronization by allowing either parties to
	// extend the other's commitment chain non-interactively, and also
	// serves as a flow control mechanism to a degree.
	InitialRevocationWindow = 4
)
View Source
const (
	Add updateType = iota
	Timeout
	Settle
)

Variables

View Source
var (
	ErrChanClosing = fmt.Errorf("channel is being closed, operation disallowed")
	ErrNoWindow    = fmt.Errorf("unable to sign new commitment, the current" +
		" revocation window is exhausted")
)
View Source
var (
	// TODO(roasbeef): remove these and use the one's defined in txscript
	// within testnet-L.
	SequenceLockTimeSeconds      = uint32(1 << 22)
	SequenceLockTimeMask         = uint32(0x0000ffff)
	OP_CHECKSEQUENCEVERIFY  byte = txscript.OP_NOP3
)
View Source
var ErrNotMine = errors.New("the passed output doesn't belong to the wallet")

ErrNotMine is an error denoting that a WalletController instance is unable to spend a specifid output.

Functions

func CommitSpendTimeout

func CommitSpendTimeout(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

CommitSpendTimeout constructs a valid witness allowing the owner of a particular commitment transaction to spend the output returning settled funds back to themselves after a relative block timeout. In order to properly spend the transaction, the target input's sequence number should be set accordingly based off of the target relative block timeout within the redeem script. Additionally, OP_CSV requires that the version of the transaction spending a pkscript with OP_CSV within it *must* be >= 2.

func CreateCommitTx

func CreateCommitTx(fundingOutput *wire.TxIn, selfKey, theirKey *btcec.PublicKey,
	revokeKey *btcec.PublicKey, csvTimeout uint32, amountToSelf,
	amountToThem btcutil.Amount) (*wire.MsgTx, error)

CreateCommitTx creates a commitment transaction, spending from specified funding output. The commitment transaction contains two outputs: one paying to the "owner" of the commitment transaction which can be spent after a relative block delay or revocation event, and the other paying the the counter-party within the channel, which can be spent immediately.

func CreateCooperativeCloseTx

func CreateCooperativeCloseTx(fundingTxIn *wire.TxIn,
	ourBalance, theirBalance btcutil.Amount,
	ourDeliveryScript, theirDeliveryScript []byte,
	initiator bool) *wire.MsgTx

CreateCooperativeCloseTx creates a transaction which if signed by both parties, then broadcast cooperatively closes an active channel. The creation of the closure transaction is modified by a boolean indicating if the party constructing the channel is the initiator of the closure. Currently it is expected that the initiator pays the transaction fees for the closing transaction in full.

func DeriveRevocationPrivKey

func DeriveRevocationPrivKey(commitPrivKey *btcec.PrivateKey,
	revokePreimage []byte) *btcec.PrivateKey

DeriveRevocationPrivKey derives the revocation private key given a node's commitment private key, and the pre-image to a previously seen revocation hash. Using this derived private key, a node is able to claim the output within the commitment transaction of a node in the case that they broadcast a previously revoked commitment transaction.

The private key is derived as follwos:

revokePriv := commitPriv + revokePreimage mod N

Where N is the order of the sub-group.

func DeriveRevocationPubkey

func DeriveRevocationPubkey(commitPubKey *btcec.PublicKey,
	revokePreimage []byte) *btcec.PublicKey

DeriveRevocationPubkey derives the revocation public key given the counter-party's commitment key, and revocation pre-image derived via a pseudo-random-function. In the event that we (for some reason) broadcast a revoked commitment transaction, then if the other party knows the revocation pre-image, then they'll be able to derive the corresponding private key to this private key by exploting the homomorphism in the elliptic curve group:

The derivation is performed as follows:

revokeKey := commitKey + revokePoint
          := G*k + G*h
          := G * (k+h)

Therefore, once we divulge the revocation pre-image, the remote peer is able to compute the proper private key for the revokeKey by computing:

revokePriv := commitPriv + revokePreimge mod N

Where N is the order of the sub-group.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until either UseLogger or SetLogWriter are called.

func FindScriptOutputIndex

func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32)

findScriptOutputIndex finds the index of the public key script output matching 'script'. Additionally, a boolean is returned indicating if a matching output was found at all. NOTE: The search stops after the first matching script is found. TODO(roasbeef): shouldn't be public?

func GenFundingPkScript

func GenFundingPkScript(aPub, bPub []byte, amt int64) ([]byte, *wire.TxOut, error)

GenFundingPkScript creates a redeem script, and its matching p2wsh output for the funding transaction.

func RegisterWallet

func RegisterWallet(driver *WalletDriver) error

RegisterWallet registers a WalletDriver which is capable of driving a concrete WalletController interface. In the case that this driver has already been registered, an error is returned.

NOTE: This function is safe for concurrent access.

func SetLogWriter

func SetLogWriter(w io.Writer, level string) error

SetLogWriter uses a specified io.Writer to output package logging info. This allows a caller to direct package logging output without needing a dependency on seelog. If the caller is also using btclog, UseLogger should be used instead.

func SpendMultiSig

func SpendMultiSig(redeemScript, pubA, sigA, pubB, sigB []byte) [][]byte

SpendMultiSig generates the witness stack required to redeem the 2-of-2 p2wsh multi-sig output.

func SupportedWallets

func SupportedWallets() []string

SupportedWallets returns a slice of strings that represents the walelt drivers that have been registered and are therefore supported.

NOTE: This function is safe for concurrent access.

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.

Types

type AddressType

type AddressType uint8

AddressType is a enum-like type which denotes the possible address types WalletController supports.

const (
	// WitnessPubKey represents a p2wkh address.
	WitnessPubKey AddressType = iota

	// NestedWitnessPubKey represents a p2sh output which is itself a
	// nested p2wkh output.
	NestedWitnessPubKey

	// PublicKey represents a regular p2pkh output.
	PubKeyHash
)

type BlockChainIO

type BlockChainIO interface {
	// GetCurrentHeight returns the current height of the valid most-work
	// chain the implementation is aware of.
	GetCurrentHeight() (int32, error)

	// GetTxOut returns the original output referenced by the passed
	// outpoint.
	GetUtxo(txid *wire.ShaHash, index uint32) (*wire.TxOut, error)

	// GetTransaction returns the full transaction identified by the passed
	// transaction ID.
	GetTransaction(txid *wire.ShaHash) (*wire.MsgTx, error)
}

BlockChainIO is a dedicated source which will be used to obtain queries related to the current state of the blockchain. The data returned by each of the defined methods within this interface should always return the most up to date data possible.

TODO(roasbeef): move to diff package perhaps? TODO(roasbeef): move publish txn here?

type ChannelContribution

type ChannelContribution struct {
	// FundingOutpoint is the amount of funds contributed to the funding
	// transaction.
	FundingAmount btcutil.Amount

	// Inputs to the funding transaction.
	Inputs []*wire.TxIn

	// ChangeOutputs are the Outputs to be used in the case that the total
	// value of the fund ing inputs is greater than the total potential
	// channel capacity.
	ChangeOutputs []*wire.TxOut

	// MultiSigKey is the the key to be used for the funding transaction's
	// P2SH multi-sig 2-of-2 output.
	// TODO(roasbeef): replace with CDP
	MultiSigKey *btcec.PublicKey

	// CommitKey is the key to be used for this party's version of the
	// commitment transaction.
	CommitKey *btcec.PublicKey

	// DeliveryAddress is the address to be used for delivery of cleared
	// channel funds in the scenario of a cooperative channel closure.
	DeliveryAddress btcutil.Address

	// RevocationKey is the key to be used in the revocation clause for the
	// initial version of this party's commitment transaction.
	RevocationKey *btcec.PublicKey

	// CsvDelay The delay (in blocks) to be used for the pay-to-self output
	// in this party's version of the commitment transaction.
	CsvDelay uint32
}

ChannelContribution is the primary constituent of the funding workflow within lnwallet. Each side first exchanges their respective contributions along with channel specific paramters like the min fee/KB. Once contributions have been exchanged, each side will then produce signatures for all their inputs to the funding transactions, and finally a signature for the other party's version of the commitment transaction.

type ChannelReservation

type ChannelReservation struct {
	// This mutex MUST be held when either reading or modifying any of the
	// fields below.
	sync.RWMutex
	// contains filtered or unexported fields
}

ChannelReservation represents an intent to open a lightning payment channel a counterpaty. The funding proceses from reservation to channel opening is a 3-step process. In order to allow for full concurrency during the reservation workflow, resources consumed by a contribution are "locked" themselves. This prevents a number of race conditions such as two funding transactions double-spending the same input. A reservation can also be cancelled, which removes the resources from limbo, allowing another reservation to claim them.

The reservation workflow consists of the following three steps:

  1. lnwallet.InitChannelReservation * One requests the wallet to allocate the neccessary resources for a channel reservation. These resources a put in limbo for the lifetime of a reservation. * Once completed the reservation will have the wallet's contribution accessible via the .OurContribution() method. This contribution contains the neccessary items to allow the remote party to build both the funding, and commitment transactions.
  2. ChannelReservation.ProcessContribution/ChannelReservation.ProcessSingleContribution * The counterparty presents their contribution to the payment channel. This allows us to build the funding, and commitment transactions ourselves. * We're now able to sign our inputs to the funding transactions, and the counterparty's version of the commitment transaction. * All signatures crafted by us, are now available via .OurSignatures().
  3. ChannelReservation.CompleteReservation/ChannelReservation.CompleteReservationSingle * The final step in the workflow. The counterparty presents the signatures for all their inputs to the funding transation, as well as a signature to our version of the commitment transaction. * We then verify the validity of all signatures before considering the channel "open".

func NewChannelReservation

func NewChannelReservation(capacity, fundingAmt btcutil.Amount, minFeeRate btcutil.Amount,
	wallet *LightningWallet, id uint64, numConfs uint16) *ChannelReservation

NewChannelReservation creates a new channel reservation. This function is used only internally by lnwallet. In order to concurrent safety, the creation of all channel reservations should be carried out via the lnwallet.InitChannelReservation interface.

func (*ChannelReservation) Cancel

func (r *ChannelReservation) Cancel() error

Cancel abandons this channel reservation. This method should be called in the scenario that communications with the counterparty break down. Upon cancellation, all resources previously reserved for this pending payment channel are returned to the free pool, allowing subsequent reservations to utilize the now freed resources.

func (*ChannelReservation) CompleteReservation

func (r *ChannelReservation) CompleteReservation(fundingInputScripts []*InputScript,
	commitmentSig []byte) error

CompleteFundingReservation finalizes the pending channel reservation, transitioning from a pending payment channel, to an open payment channel. All passed signatures to the counterparty's inputs to the funding transaction will be fully verified. Signatures are expected to be passed in sorted order according to BIP-69: https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki. Additionally, verification is performed in order to ensure that the counterparty supplied a valid signature to our version of the commitment transaction. Once this method returns, caller's should then call .WaitForChannelOpen() which will block until the funding transaction obtains the configured number of confirmations. Once the method unblocks, a LightningChannel instance is returned, marking the channel available for updates.

func (*ChannelReservation) CompleteReservationSingle

func (r *ChannelReservation) CompleteReservationSingle(revocationKey *btcec.PublicKey,
	fundingPoint *wire.OutPoint, commitSig []byte) error

CompleteReservationSingle finalizes the pending single funder channel reservation. Using the funding outpoint of the constructed funding transaction, and the initiator's signature for our version of the commitment transaction, we are able to verify the correctness of our committment transaction as crafted by the initiator. Once this method returns, our signature for the initiator's version of the commitment transaction is available via the .OurSignatures() method. As this method should only be called as a response to a single funder channel, only a commitment signature will be populated.

func (*ChannelReservation) DispatchChan

func (r *ChannelReservation) DispatchChan() <-chan *LightningChannel

DispatchChan returns a channel which will be sent on once the funding transaction for this pending payment channel obtains the configured number of confirmations. Once confirmations have been obtained, a fully initialized LightningChannel instance is returned, allowing for channel updates.

NOTE: If this method is called before .CompleteReservation(), it will block indefinitely.

func (*ChannelReservation) FinalFundingTx

func (r *ChannelReservation) FinalFundingTx() *wire.MsgTx

FinalFundingTx returns the finalized, fully signed funding transaction for this reservation.

NOTE: If this reservation was created as the non-initiator to a single funding workflow, then the full funding transaction will not be available. Instead we will only have the final outpoint of the funding transaction.

func (*ChannelReservation) FinalizeReservation

func (r *ChannelReservation) FinalizeReservation() (*LightningChannel, error)

FinalizeReservation completes the pending reservation, returning an active open LightningChannel. This method should be called after the responder to the single funder workflow receives and verifies a proof from the initiator of an open channel.

NOTE: This method should *only* be called as the last step when one is the responder to an initiated single funder workflow.

func (*ChannelReservation) FundingOutpoint

func (r *ChannelReservation) FundingOutpoint() *wire.OutPoint

FundingOutpoint returns the outpoint of the funding transaction.

NOTE: The pointer returned will only be set once the .ProcesContribution() method is called in the case of the initiator of a single funder workflow, and after the .CompleteReservationSingle() method is called in the case of a responder to a single funder workflow.

func (*ChannelReservation) FundingRedeemScript

func (r *ChannelReservation) FundingRedeemScript() []byte

FundingRedeemScript returns the fully populated funding redeem script.

NOTE: This method will only return a non-nil value after either ProcesContribution or ProcessSingleContribution have been executed and returned without error.

func (*ChannelReservation) LocalCommitTx

func (r *ChannelReservation) LocalCommitTx() *wire.MsgTx

LocalCommitTx returns the commitment transaction for the local node involved in this funding reservation.

func (*ChannelReservation) OurContribution

func (r *ChannelReservation) OurContribution() *ChannelContribution

OurContribution returns the wallet's fully populated contribution to the pending payment channel. See 'ChannelContribution' for further details regarding the contents of a contribution. NOTE: This SHOULD NOT be modified. TODO(roasbeef): make copy?

func (*ChannelReservation) OurSignatures

func (r *ChannelReservation) OurSignatures() ([]*InputScript, []byte)

OurSignatures retrieves the wallet's signatures to all inputs to the funding transaction belonging to itself, and also a signature for the counterparty's version of the commitment transaction. The signatures for the wallet's inputs to the funding transaction are returned in sorted order according to BIP-69: https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki. NOTE: These signatures will only be populated after a call to .ProcesContribution()

func (*ChannelReservation) ProcessContribution

func (r *ChannelReservation) ProcessContribution(theirContribution *ChannelContribution) error

ProcesContribution verifies the counterparty's contribution to the pending payment channel. As a result of this incoming message, lnwallet is able to build the funding transaction, and both commitment transactions. Once this message has been processed, all signatures to inputs to the funding transaction belonging to the wallet are available. Additionally, the wallet will generate a signature to the counterparty's version of the commitment transaction.

func (*ChannelReservation) ProcessSingleContribution

func (r *ChannelReservation) ProcessSingleContribution(theirContribution *ChannelContribution) error

ProcessSingleContribution verifies, and records the initiator's contribution to this pending single funder channel. Internally, no further action is taken other than recording the initiator's contribution to the single funder channel.

func (*ChannelReservation) TheirContribution

func (r *ChannelReservation) TheirContribution() *ChannelContribution

TheirContribution returns the counterparty's pending contribution to the payment channel. See 'ChannelContribution' for further details regarding the contents of a contribution. This attribute will ONLY be available after a call to .ProcesContribution(). NOTE: This SHOULD NOT be modified.

func (*ChannelReservation) TheirSignatures

func (r *ChannelReservation) TheirSignatures() ([]*InputScript, []byte)

OurSignatures returns the counterparty's signatures to all inputs to the funding transaction belonging to them, as well as their signature for the wallet's version of the commitment transaction. This methods is provided for additional verification, such as needed by tests. NOTE: These attributes will be unpopulated before a call to .CompleteReservation().

type Config

type Config struct {
}

Config..

type ErrInsufficientFunds

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

ErrInsufficientFunds is a type matching the error interface which is returned when coin selection for a new funding transaction fails to due having an insufficient amount of confirmed funds.

func (*ErrInsufficientFunds) Error

func (e *ErrInsufficientFunds) Error() string

type ForceCloseSummary

type ForceCloseSummary struct {
	// CloseTx is the transaction which closed the channel on-chain. If we
	// initiate the force close, then this'll be our latest commitment
	// state. Otherwise, this'll be the state that the remote peer
	// broadcasted on-chain.
	CloseTx *wire.MsgTx

	// SelfOutpoint is the output created by the above close tx which is
	// spendable by us after a relative time delay.
	SelfOutpoint wire.OutPoint

	// SelfOutputMaturity is the relative maturity period before the above
	// output can be claimed.
	SelfOutputMaturity uint32

	// SelfOutputSignDesc is a fully populated sign descriptor capable of
	// generating a valid signature to swee the self output.
	SelfOutputSignDesc *SignDescriptor
}

ForceCloseSummary describes the final commitment state before the channel is locked-down to initiate a force closure by broadcasting the latest state on-chain. The summary includes all the information required to claim all rightfully owned outputs. TODO(roasbeef): generalize, add HTLC info, revocatio info, etc.

type InputScript

type InputScript struct {
	Witness   [][]byte
	ScriptSig []byte
}

InputScripts represents any script inputs required to redeem a previous output. This struct is used rather than just a witness, or scripSig in order to accomdate nested p2sh which utilizes both types of input scripts.

type LightningChannel

type LightningChannel struct {
	sync.RWMutex

	Capacity btcutil.Amount

	LocalDeliveryScript  []byte
	RemoteDeliveryScript []byte

	FundingRedeemScript []byte

	// ForceCloseSignal is a channel that is closed to indicate that a
	// local system has initiated a force close by broadcasting the current
	// commitment transaction directly on-chain.
	ForceCloseSignal chan struct{}

	// UnilateralCloseSignal is a channel that is closed to indicate that
	// the remote party has performed a unilateral close by broadcasting
	// their version of the commitment transaction on-chain.
	UnilateralCloseSignal chan struct{}
	// contains filtered or unexported fields
}

LightningChannel implements the state machine which corresponds to the current commitment protocol wire spec. The state machine implemented allows for asynchronous fully desynchronized, batched+pipelined updates to commitment transactions allowing for a high degree of non-blocking bi-directional payment throughput.

In order to allow updates to be fully non-blocking, either side is able to create multiple new commitment states up to a pre-determined window size. This window size is encoded within InitialRevocationWindow. Before the start of a session, both side should send out revocation messages with nil preimages in order to populate their revocation window for the remote party. Ths method .ExtendRevocationWindow() is used to extend the revocation window by a single revocation.

The state machine has for main methods:

  • .SignNextCommitment()
  • Called one one wishes to sign the next commitment, either initiating a new state update, or responding to a received commitment.

/ * .ReceiveNewCommitment()

  • Called upon receipt of a new commitment from the remote party. If the new commitment is valid, then a revocation should immediately be generated and sent.
  • .RevokeCurrentCommitment()
  • Revokes the current commitment. Should be called directly after receiving a new commitment.
  • .ReceiveRevocation()
  • Processes a revocation from the remote party. If successful creates a new defacto broadcastable state.

See the individual comments within the above methods for further details.

func NewLightningChannel

func NewLightningChannel(signer Signer, bio BlockChainIO,
	events chainntnfs.ChainNotifier,
	state *channeldb.OpenChannel) (*LightningChannel, error)

NewLightningChannel creates a new, active payment channel given an implementation of the chain notifier, channel database, and the current settled channel state. Throughout state transitions, then channel will automatically persist pertinent state to the database in an efficient manner.

func (*LightningChannel) AddHTLC

func (lc *LightningChannel) AddHTLC(htlc *lnwire.HTLCAddRequest) uint32

AddHTLC adds an HTLC to the state machine's local update log. This method should be called when preparing to send an outgoing HTLC. TODO(roasbeef): check for duplicates below? edge case during restart w/ HTLC persistence

func (*LightningChannel) ChannelPoint

func (lc *LightningChannel) ChannelPoint() *wire.OutPoint

ChannelPoint returns the outpoint of the original funding transaction which created this active channel. This outpoint is used throughout various sub-systems to uniquely identify an open channel.

func (*LightningChannel) CompleteCooperativeClose

func (lc *LightningChannel) CompleteCooperativeClose(remoteSig []byte) (*wire.MsgTx, error)

CompleteCooperativeClose completes the cooperative closure of the target active lightning channel. This method should be called in response to the remote node initating a cooperative channel closure. A fully signed closure transaction is returned. It is the duty of the responding node to broadcast a signed+valid closure transaction to the network.

NOTE: The passed remote sig is expected to the a fully complete signature including the proper sighash byte.

func (*LightningChannel) DeleteState

func (lc *LightningChannel) DeleteState() error

DeleteState deletes all state concerning the channel from the underlying database, only leaving a small summary describing meta-data of the channel's lifetime.

func (*LightningChannel) ExtendRevocationWindow

func (lc *LightningChannel) ExtendRevocationWindow() (*lnwire.CommitRevocation, error)

ExtendRevocationWindow extends our revocation window by a single revocation, increasing the number of new commitment updates the remote party can initiate without our cooperation.

func (*LightningChannel) ForceClose

func (lc *LightningChannel) ForceClose() (*ForceCloseSummary, error)

ForceClose executes a unilateral closure of the transaction at the current lowest commitment height of the channel. Following a force closure, all state transitions, or modifications to the state update logs will be rejected. Additionally, this function also returns a ForceCloseSummary which includes the necessary details required to sweep all the time-locked within the commitment transaction.

TODO(roasbeef): all methods need to abort if in dispute state TODO(roasbeef): method to generate CloseSummaries for when the remote peer does a unilateral close

func (*LightningChannel) InitCooperativeClose

func (lc *LightningChannel) InitCooperativeClose() ([]byte, *wire.ShaHash, error)

InitCooperativeClose initiates a cooperative closure of an active lightning channel. This method should only be executed once all pending HTLCs (if any) on the channel have been cleared/removed. Upon completion, the source channel will shift into the "closing" state, which indicates that all incoming/outgoing HTLC requests should be rejected. A signature for the closing transaction, and the txid of the closing transaction are returned. The initiator of the channel closure should then watch the blockchain for a confirmation of the closing transaction before considering the channel terminated. In the case of an unresponsive remote party, the initiator can either choose to execute a force closure, or backoff for a period of time, and retry the cooperative closure. TODO(roasbeef): caller should initiate signal to reject all incoming HTLCs, settle any inflight.

func (*LightningChannel) PendingUpdates

func (lc *LightningChannel) PendingUpdates() bool

PendingUpdates returns a boolean value reflecting if there are any pending updates which need to be committed. The state machine has pending updates if the local log index on the local and remote chain tip aren't identical. This indicates that either we have pending updates they need to commit, or vice versa.

func (*LightningChannel) ReceiveHTLC

func (lc *LightningChannel) ReceiveHTLC(htlc *lnwire.HTLCAddRequest) uint32

ReceiveHTLC adds an HTLC to the state machine's remote update log. This method should be called in response to receiving a new HTLC from the remote party.

func (*LightningChannel) ReceiveHTLCSettle

func (lc *LightningChannel) ReceiveHTLCSettle(preimage [32]byte, logIndex uint32) error

ReceiveHTLCSettle attempts to settle an existing outgoing HTLC indexed by an index into the local log. If the specified index doesn't exist within the log, and error is returned. Similarly if the preimage is invalid w.r.t to the referenced of then a distinct error is returned.

func (*LightningChannel) ReceiveNewCommitment

func (lc *LightningChannel) ReceiveNewCommitment(rawSig []byte,
	ourLogIndex uint32) error

ReceiveNewCommitment processs a signature for a new commitment state sent by the remote party. This method will should be called in response to the remote party initiating a new change, or when the remote party sends a signature fully accepting a new state we've initiated. If we are able to succesfully validate the signature, then the generated commitment is added to our local commitment chain. Once we send a revocation for our prior state, then this newly added commitment becomes our current accepted channel state.

func (*LightningChannel) ReceiveRevocation

func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.CommitRevocation) ([]*PaymentDescriptor, error)

ReceiveRevocation processes a revocation sent by the remote party for the lowest unrevoked commitment within their commitment chain. We receive a revocation either during the initial session negotiation wherein revocation windows are extended, or in response to a state update that we initiate. If successful, then the remote commitment chain is advanced by a single commitment, and a log compaction is attempted. In addition, a slice of HTLC's which can be forwarded upstream are returned.

func (*LightningChannel) RevokeCurrentCommitment

func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.CommitRevocation, error)

RevokeCurrentCommitment revokes the next lowest unrevoked commitment transaction in the local commitment chain. As a result the edge of our revocation window is extended by one, and the tail of our local commitment chain is advanced by a single commitment. This now lowest unrevoked commitment becomes our currently accepted state within the channel.

func (*LightningChannel) SettleHTLC

func (lc *LightningChannel) SettleHTLC(preimage [32]byte) (uint32, error)

SettleHTLC attempst to settle an existing outstanding received HTLC. The remote log index of the HTLC settled is returned in order to facilitate creating the corresponding wire message. In the case the supplied pre-image is invalid, an error is returned.

func (*LightningChannel) SignNextCommitment

func (lc *LightningChannel) SignNextCommitment() ([]byte, uint32, error)

SignNextCommitment signs a new commitment which includes any previous unsettled HTLCs, any new HTLCs, and any modifications to prior HTLCs committed in previous commitment updates. Signing a new commitment decrements the available revocation window by 1. After a successful method call, the remote party's commitment chain is extended by a new commitment which includes all updates to the HTLC log prior to this method invocation.

func (*LightningChannel) StateSnapshot

func (lc *LightningChannel) StateSnapshot() *channeldb.ChannelSnapshot

StateSnapshot returns a snapshot of the current fully committed state within the channel.

func (*LightningChannel) TimeoutHTLC

func (lc *LightningChannel) TimeoutHTLC() error

TimeoutHTLC...

type LightningWallet

type LightningWallet struct {

	// A wrapper around a namespace within boltdb reserved for ln-based
	// wallet meta-data. See the 'channeldb' package for further
	// information.
	ChannelDB *channeldb.DB

	// wallet is the the core wallet, all non Lightning Network specific
	// interaction is proxied to the internal wallet.
	WalletController

	// Signer is the wallet's current Signer implementation. This Signer is
	// used to generate signature for all inputs to potential funding
	// transactions, as well as for spends from the funding transaction to
	// update the commitment state.
	Signer Signer
	// contains filtered or unexported fields
}

LightningWallet is a domain specific, yet general Bitcoin wallet capable of executing workflow required to interact with the Lightning Network. It is domain specific in the sense that it understands all the fancy scripts used within the Lightning Network, channel lifetimes, etc. However, it embedds a general purpose Bitcoin wallet within it. Therefore, it is also able to serve as a regular Bitcoin wallet which uses HD keys. The wallet is highly concurrent internally. All communication, and requests towards the wallet are dispatched as messages over channels, ensuring thread safety across all operations. Interaction has been designed independant of any peer-to-peer communication protocol, allowing the wallet to be self-contained and embeddable within future projects interacting with the Lightning Network. NOTE: At the moment the wallet requires a btcd full node, as it's dependant on btcd's websockets notifications as even triggers during the lifetime of a channel. However, once the chainntnfs package is complete, the wallet will be compatible with multiple RPC/notification services such as Electrum, Bitcoin Core + ZeroMQ, etc. Eventually, the wallet won't require a full-node at all, as SPV support is integrated inot btcwallet.

func NewLightningWallet

func NewLightningWallet(cdb *channeldb.DB, notifier chainntnfs.ChainNotifier,
	wallet WalletController, signer Signer, bio BlockChainIO,
	netParams *chaincfg.Params) (*LightningWallet, error)

NewLightningWallet creates/opens and initializes a LightningWallet instance. If the wallet has never been created (according to the passed dataDir), first-time setup is executed.

NOTE: The passed channeldb, and ChainNotifier should already be fully initialized/started before being passed as a function arugment.

func (*LightningWallet) ActiveReservations

func (l *LightningWallet) ActiveReservations() []*ChannelReservation

ActiveReservations returns a slice of all the currently active (non-cancalled) reservations.

func (*LightningWallet) GetIdentitykey

func (l *LightningWallet) GetIdentitykey() (*btcec.PrivateKey, error)

GetIdentitykey returns the identity private key of the wallet. TODO(roasbeef): should be moved elsewhere

func (*LightningWallet) InitChannelReservation

func (l *LightningWallet) InitChannelReservation(capacity,
	ourFundAmt btcutil.Amount, theirID [32]byte, numConfs uint16,
	csvDelay uint32) (*ChannelReservation, error)

InitChannelReservation kicks off the 3-step workflow required to succesfully open a payment channel with a remote node. As part of the funding reservation, the inputs selected for the funding transaction are 'locked'. This ensures that multiple channel reservations aren't double spending the same inputs in the funding transaction. If reservation initialization is succesful, a ChannelReservation containing our completed contribution is returned. Our contribution contains all the items neccessary to allow the counter party to build the funding transaction, and both versions of the commitment transaction. Otherwise, an error occured a nil pointer along with an error are returned.

Once a ChannelReservation has been obtained, two additional steps must be processed before a payment channel can be considered 'open'. The second step validates, and processes the counterparty's channel contribution. The third, and final step verifies all signatures for the inputs of the funding transaction, and that the signature we records for our version of the commitment transaction is valid.

func (*LightningWallet) LockedOutpoints

func (l *LightningWallet) LockedOutpoints() []*wire.OutPoint

LockOutpoints returns a list of all currently locked outpoint.

func (*LightningWallet) ResetReservations

func (l *LightningWallet) ResetReservations()

ResetReservations reset the volatile wallet state which trakcs all currently active reservations.

func (*LightningWallet) Shutdown

func (l *LightningWallet) Shutdown() error

Shutdown gracefully stops the wallet, and all active goroutines.

func (*LightningWallet) Startup

func (l *LightningWallet) Startup() error

Startup establishes a connection to the RPC source, and spins up all goroutines required to handle incoming messages.

type PaymentDescriptor

type PaymentDescriptor struct {
	sync.RWMutex

	// RHash is the payment hash for this HTLC. The HTLC can be settled iff
	// the preimage to this hash is presented.
	RHash PaymentHash

	// RPreimage is the preimage that settles the HTLC pointed to wthin the
	// log by the ParentIndex.
	RPreimage PaymentHash

	// Timeout is the absolute timeout in blocks, afterwhich this HTLC
	// expires.
	Timeout uint32

	// Amount is the HTLC amount in satoshis.
	Amount btcutil.Amount

	// Index is the log entry number that his HTLC update has within the
	// log. Depending on if IsIncoming is true, this is either an entry the
	// remote party added, or one that we added locally.
	Index uint32

	// ParentIndex is the index of the log entry that this HTLC update
	// settles or times out.
	ParentIndex uint32

	// Payload is an opaque blob which is used to complete multi-hop routing.
	Payload []byte

	// Type denotes the exact type of the PaymentDescriptor. In the case of
	// a Timeout, or Settle type, then the Parent field will point into the
	// log to the HTLC being modified.
	EntryType updateType
	// contains filtered or unexported fields
}

PaymentDescriptor represents a commitment state update which either adds, settles, or removes an HTLC. PaymentDescriptors encapsulate all necessary meta-data w.r.t to an HTLC, and additional data pairing a settle message to the original added HTLC. TODO(roasbeef): LogEntry interface??

  • need to separate attrs for cancel/add/settle

type PaymentHash

type PaymentHash [32]byte

PaymentHash represents the sha256 of a random value. This hash is used to uniquely track incoming/outgoing payments within this channel, as well as payments requested by the wallet/daemon.

type SignDescriptor

type SignDescriptor struct {
	// Pubkey is the public key to which the signature should be generated
	// over. The Signer should then generate a signature with the private
	// key corresponding to this public key.
	PubKey *btcec.PublicKey

	// RedeemScript is the full script required to properly redeem the
	// output. This field will only be populated if a p2wsh or a p2sh
	// output is being signed.
	RedeemScript []byte

	// Output is the target output which should be signed. The PkScript and
	// Value fields within the output should be properly populated,
	// otherwise an invalid signature may be generated.
	Output *wire.TxOut

	// HashType is the target sighash type that should be used when
	// generating the final sighash, and signature.
	HashType txscript.SigHashType

	// SigHashes is the pre-computed sighash midstate to be used when
	// generating the final sighash for signing.
	SigHashes *txscript.TxSigHashes

	// InputIndex is the target input within the transaction that should be
	// signed.
	InputIndex int
}

SignDescriptor houses the necessary information required to succesfully sign a given output. This struct is used by the Signer interface in order to gain access to critial data needed to generate a valid signature.

type Signer

type Signer interface {
	// SignOutputRaw generates a signature for the passed transaction
	// according to the data within the passed SignDescriptor.
	//
	// NOTE: The resulting signature should be void of a sighash byte.
	SignOutputRaw(tx *wire.MsgTx, signDesc *SignDescriptor) ([]byte, error)

	// ComputeInputScript generates a complete InputIndex for the passed
	// transaction with the signature as defined within the passed
	// SignDescriptor. This method should be capable of generating the
	// proper input script for both regular p2wkh output and p2wkh outputs
	// nested within a regualr p2sh output.
	ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor) (*InputScript, error)
}

Signer represents an abstract object capable of generating raw signatures as well as full complete input scripts given a valid SignDescriptor and transaction. This interface fully abstracts away signing paving the way for Signer implementations such as hardware wallets, hardware tokens, HSM's, or simply a regular wallet.

type Utxo

type Utxo struct {
	Value btcutil.Amount
	wire.OutPoint
}

Utxo is an unspent output denoted by its outpoint, and output value of the original output.

type WalletController

type WalletController interface {
	// FetchInputInfo queries for the WalletController's knowledge of the
	// passed outpoint. If the base wallet determines this output is under
	// its control, then the original txout should be returned. Otherwise,
	// a non-nil error value of ErrNotMine should be returned instead.
	FetchInputInfo(prevOut *wire.OutPoint) (*wire.TxOut, error)

	// ConfirmedBalance returns the sum of all the wallet's unspent outputs
	// that have at least confs confirmations. If confs is set to zero,
	// then all unspent outputs, including those currently in the mempool
	// will be included in the final sum.
	ConfirmedBalance(confs int32, witness bool) (btcutil.Amount, error)

	// NewAddress returns the next external or internal address for the
	// wallet dicatated by the value of the `change` paramter. If change is
	// true, then an internal address should be used, otherwise an external
	// address should be returned. The type of address returned is dictated
	// by the wallet's capabilities, and may be of type: p2sh, p2pkh,
	// p2wkh, p2wsh, etc.
	NewAddress(addrType AddressType, change bool) (btcutil.Address, error)

	// GetPrivKey retrives the underlying private key associated with the
	// passed address. If the wallet is unable to locate this private key
	// due to the address not being under control of the wallet, then an
	// error should be returned.
	// TODO(roasbeef): should instead take tadge's derivation scheme in
	GetPrivKey(a btcutil.Address) (*btcec.PrivateKey, error)

	// NewRawKey returns a raw private key controlled by the wallet. These
	// keys are used for the 2-of-2 multi-sig outputs for funding
	// transactions, as well as the pub key used for commitment transactions.
	// TODO(roasbeef): may be scrapped, see above TODO
	NewRawKey() (*btcec.PublicKey, error)

	// FetchRootKey returns a root key which will be used by the
	// LightningWallet to deterministically generate secrets. The private
	// key returned by this method should remain constant in-between
	// WalletController restarts.
	FetchRootKey() (*btcec.PrivateKey, error)

	// SendOutputs funds, signs, and broadcasts a Bitcoin transaction
	// paying out to the specified outputs. In the case the wallet has
	// insufficient funds, or the outputs are non-standard, and error
	// should be returned.
	SendOutputs(outputs []*wire.TxOut) (*wire.ShaHash, error)

	// ListUnspentWitness returns all unspent outputs which are version 0
	// witness programs. The 'confirms' parameter indicates the minimum
	// number of confirmations an output needs in order to be returned by
	// this method. Passing -1 as 'confirms' indicates that even
	// unconfirmed outputs should be returned.
	ListUnspentWitness(confirms int32) ([]*Utxo, error)

	// LockOutpoint marks an outpoint as locked meaning it will no longer
	// be deemed as eligible for coin selection. Locking outputs are
	// utilized in order to avoid race conditions when selecting inputs for
	// usage when funding a channel.
	LockOutpoint(o wire.OutPoint)

	// UnlockOutpoint unlocks an previously locked output, marking it
	// eligible for coin seleciton.
	UnlockOutpoint(o wire.OutPoint)

	// PublishTransaction performs cursory validation (dust checks, etc),
	// then finally broadcasts the passed transaction to the Bitcoin network.
	PublishTransaction(tx *wire.MsgTx) error

	// Start initializes the wallet, making any neccessary connections,
	// starting up required goroutines etc.
	Start() error

	// Stop signals the wallet for shutdown. Shutdown may entail closing
	// any active sockets, database handles, stopping goroutines, etc.
	Stop() error
}

WalletController defines an abstract interface for controlling a local Pure Go wallet, a local or remote wallet via an RPC mechanism, or possibly even a daemon assisted hardware wallet. This interface serves the purpose of allowing LightningWallet to be seamlessly compatible with several wallets such as: uspv, btcwallet, Bitcoin Core, Electrum, etc. This interface then serves as a "base wallet", with Lightning Network awareness taking place at a "higher" level of abstraction. Essentially, an overlay wallet. Implementors of this interface must closely adhere to the documented behavior of all interface methods in order to ensure identical behavior across all concrete implementations.

type WalletDriver

type WalletDriver struct {
	// WalletType is a string which uniquely identifes the WalletController
	// that this driver, drives.
	WalletType string

	// New creates a new instance of a concrete WalletController
	// implementation given a variadic set up arguments. The function takes
	// a varidaic number of interface paramters in order to provide
	// initialization flexibility, thereby accomodating several potential
	// WalletController implementations.
	New func(args ...interface{}) (WalletController, error)
}

WalletDriver represents a "driver" for a particular concrete WalletController implementation. A driver is indentified by a globally unique string identifier along with a 'New()' method which is responsible for initializing a particular WalletController concrete implementation.

func RegisteredWallets

func RegisteredWallets() []*WalletDriver

RegisteredWallets returns a slice of all currently registered notifiers.

NOTE: This function is safe for concurrent access.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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