channeldb

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: 18 Imported by: 242

Documentation

Index

Constants

View Source
const (
	// MaxMemoSize is maximum size of the memo field within invoices stored
	// in the database.
	MaxMemoSize = 1024

	// MaxReceiptSize is the maximum size of the payment receipt stored
	// within the database along side incoming/outgoing invoices.
	MaxReceiptSize = 1024
)

Variables

View Source
var (
	ErrNoChanDBExists = fmt.Errorf("channel db has not yet been created")

	ErrNoActiveChannels = fmt.Errorf("no active channels exist")
	ErrChannelNoExist   = fmt.Errorf("this channel does not exist")
	ErrNoPastDeltas     = fmt.Errorf("channel has no recorded deltas")

	ErrInvoiceNotFound   = fmt.Errorf("unable to locate invoice")
	ErrNoInvoicesCreated = fmt.Errorf("there are no existing invoices")
	ErrDuplicateInvoice  = fmt.Errorf("invoice with payment hash already exists")
)

Functions

func DisableLog

func DisableLog()

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

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 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 ChannelDelta

type ChannelDelta struct {
	LocalBalance  btcutil.Amount
	RemoteBalance btcutil.Amount
	UpdateNum     uint32

	Htlcs []*HTLC
}

ChannelDelta is a snapshot of the commitment state at a particular point in the commitment chain. With each state transition, a snapshot of the current state along with all non-settled HTLC's are recorded.

type ChannelSnapshot

type ChannelSnapshot struct {
	RemoteID [wire.HashSize]byte

	ChannelPoint *wire.OutPoint

	Capacity      btcutil.Amount
	LocalBalance  btcutil.Amount
	RemoteBalance btcutil.Amount

	NumUpdates uint64

	TotalSatoshisSent     uint64
	TotalSatoshisReceived uint64

	Htlcs []HTLC
}

ChannelSnapshot is a frozen snapshot of the current channel state. A snapshot is detached from the original channel that generated it, providing read-only access to the current or prior state of an active channel.

type ContractTerm

type ContractTerm struct {
	// PaymentPreimage is the preimage which is to be revealed in the
	// occasion that an HTLC paying to the hash of this preimage is
	// extended.
	PaymentPreimage [32]byte

	// Value is the expected amount to be payed to an HTLC which can be
	// satisfied by the above preimage.
	Value btcutil.Amount

	// Settled indicates if this particular contract term has been fully
	// settled by the payer.
	Settled bool
}

ContractTerm is a companion struct to the Invoice struct. This struct houses the necessary conditions required before the invoice can be considered fully settled by the payee.

type DB

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

DB is the primary datastore for the LND daemon. The database stores information related to nodes, routing data, open/closed channels, fee schedules, and reputation data.

func Open

func Open(dbPath string, netParams *chaincfg.Params) (*DB, error)

Open opens an existing channeldb created under the passed namespace with sensitive data encrypted by the passed EncryptorDecryptor implementation. TODO(roasbeef): versioning?

func (*DB) AddInvoice

func (d *DB) AddInvoice(i *Invoice) error

AddInvoice inserts the targeted invoice into the database. If the invoice has *any* payment hashes which already exists within the database, then the insertion will be aborted and rejected due to the strict policy banning any duplicate payment hashes.

func (*DB) Close

func (d *DB) Close() error

Close terminates the underlying database handle manually.

func (*DB) FetchAllInvoices

func (d *DB) FetchAllInvoices(pendingOnly bool) ([]*Invoice, error)

FetchAllInvoices returns all invoices currently stored within the database. If the pendingOnly param is true, then only unsettled invoices will be returned, skipping all invoices that are fully settled.

func (*DB) FetchOpenChannels

func (d *DB) FetchOpenChannels(nodeID *wire.ShaHash) ([]*OpenChannel, error)

FetchOpenChannel returns all stored currently active/open channels associated with the target nodeID. In the case that no active channels are known to have been created with this node, then a zero-length slice is returned.

func (*DB) GetIdAdr

func (d *DB) GetIdAdr() (*btcutil.AddressPubKeyHash, error)

GetIdKey returns the hash160 of the public key used for out identity within the Lightning Network as a p2pkh bitcoin address.

func (*DB) LookupInvoice

func (d *DB) LookupInvoice(paymentHash [32]byte) (*Invoice, error)

LookupInvoice attempts to look up an invoice according to it's 32 byte payment hash. In an invoice which can settle the HTLC identified by the passed payment hash isnt't found, then an error is returned. Otherwise, the full invoice is returned. Before setting the incoming HTLC, the values SHOULD be checked to ensure the payer meets the agreed upon contractual terms of the payment.

func (*DB) PutIdKey

func (d *DB) PutIdKey(pkh []byte) error

PutIdKey saves the hash160 of the public key used for our identity within the Lightning Network.

func (*DB) SettleInvoice

func (d *DB) SettleInvoice(paymentHash [32]byte) error

SettleInvoice attempts to mark an invoice corresponding to the passed payment hash as fully settled. If an invoice matching the passed payment hash doesn't existing within the database, then the action will fail with a "not found" error.

func (*DB) Wipe

func (d *DB) Wipe() error

Wipe completely deletes all saved state within all used buckets within the database. The deletion is done in a single transaction, therefore this operation is fully atomic.

type HTLC

type HTLC struct {
	// Incoming denotes whether we're the receiver or the sender of this
	// HTLC.
	Incoming bool

	// Amt is the amount of satoshis this HTLC escrows.
	Amt btcutil.Amount

	// RHash is the payment hash of the HTLC.
	RHash [32]byte

	// RefundTimeout is the absolute timeout on the HTLC that the sender
	// must wait before reclaiming the funds in limbo.
	RefundTimeout uint32

	// RevocationDelay is the relative timeout the party who broadcasts
	// the commitment transaction must wait before being able to fully
	// sweep the funds on-chain in the case of a unilateral channel
	// closure.
	RevocationDelay uint32
}

HTLC is the on-disk representation of a hash time-locked contract. HTLC's are contained within ChannelDeltas which encode the current state of the commitment between state updates.

func (*HTLC) Copy

func (h *HTLC) Copy() HTLC

Copy returns a full copy of the target HTLC.

type Invoice

type Invoice struct {
	// Memo is an optional memo to be stored along side an invoice.  The
	// memo may contain further details pertaining to the invoice itself,
	// or any other message which fits within the size constraints.
	Memo []byte

	// Receipt is an optional field dedicated for storing a
	// cryptographically binding receipt of payment.
	//
	// TODO(roasbeef): document scheme.
	Receipt []byte

	// CreationDate is the exact time the invoice was created.
	CreationDate time.Time

	// Terms are the contractual payment terms of the invoice. Once
	// all the terms have been satisfied by the payer, then the invoice can
	// be considered fully fulfilled.
	//
	// TODO(roasbeef): later allow for multiple terms to fulfill the final
	// invoice: payment fragmentation, etc.
	Terms ContractTerm
}

Invoice is a payment invoice generated by a payee in order to request payment for some good or service. The inclusion of invoices within Lightning creates a payment work flow for merchants very similar to that of the existing financial system within PayPal, etc. Invoices are added to the database when a payment is requested, then can be settled manually once the payment is received at the upper layer. For record keeping purposes, invoices are never deleted from the database, instead a bit is toggled denoting the invoice has been fully settled. Within the database, all invoices must have a unique payment hash which is generated by taking the sha256 of the payment preimage.

type OpenChannel

type OpenChannel struct {
	// Hash? or Their current pubKey?
	TheirLNID [wire.HashSize]byte

	// The ID of a channel is the txid of the funding transaction.
	ChanID      *wire.OutPoint
	MinFeePerKb btcutil.Amount

	// Keys for both sides to be used for the commitment transactions.
	OurCommitKey   *btcec.PublicKey
	TheirCommitKey *btcec.PublicKey

	// Tracking total channel capacity, and the amount of funds allocated
	// to each side.
	Capacity     btcutil.Amount
	OurBalance   btcutil.Amount
	TheirBalance btcutil.Amount

	// Our current commitment transaction along with their signature for
	// our commitment transaction.
	OurCommitTx  *wire.MsgTx
	OurCommitSig []byte

	// The outpoint of the final funding transaction.
	FundingOutpoint *wire.OutPoint

	OurMultiSigKey      *btcec.PublicKey
	TheirMultiSigKey    *btcec.PublicKey
	FundingRedeemScript []byte

	// In blocks
	LocalCsvDelay  uint32
	RemoteCsvDelay uint32

	// Current revocation for their commitment transaction. However, since
	// this the derived public key, we don't yet have the pre-image so we
	// aren't yet able to verify that it's actually in the hash chain.
	TheirCurrentRevocation     *btcec.PublicKey
	TheirCurrentRevocationHash [32]byte
	LocalElkrem                *elkrem.ElkremSender
	RemoteElkrem               *elkrem.ElkremReceiver

	// The pkScript for both sides to be used for final delivery in the case
	// of a cooperative close.
	OurDeliveryScript   []byte
	TheirDeliveryScript []byte

	NumUpdates            uint64
	TotalSatoshisSent     uint64
	TotalSatoshisReceived uint64
	TotalNetFees          uint64    // TODO(roasbeef): total fees paid too?
	CreationTime          time.Time // TODO(roasbeef): last update time?

	Htlcs []*HTLC

	// TODO(roasbeef): eww
	Db *DB

	sync.RWMutex
}

OpenChannel encapsulates the persistent and dynamic state of an open channel with a remote node. An open channel supports several options for on-disk serialization depending on the exact context. Full (upon channel creation) state commitments, and partial (due to a commitment update) writes are supported. Each partial write due to a state update appends the new update to an on-disk log, which can then subsequently be queried in order to "time-travel" to a prior state.

func (*OpenChannel) AppendToRevocationLog

func (c *OpenChannel) AppendToRevocationLog(delta *ChannelDelta) error

AppendToRevocationLog records the new state transition within an on-disk append-only log which records all state transitions by the remote peer. In the case of an uncooperative broadcast of a prior state by the remote peer, this log can be consulted in order to reconstruct the state needed to rectify the situation.

func (*OpenChannel) CloseChannel

func (c *OpenChannel) CloseChannel() error

CloseChannel closes a previously active lightning channel. Closing a channel entails deleting all saved state within the database concerning this channel, as well as created a small channel summary for record keeping purposes. TODO(roasbeef): delete on-disk set of HTLC's

func (*OpenChannel) FindPreviousState

func (c *OpenChannel) FindPreviousState(updateNum uint64) (*ChannelDelta, error)

FindPreviousState scans through the append-only log in an attempt to recover the previous channel state indicated by the update number. This method is intended to be used for obtaining the relevant data needed to claim all funds rightfully spendable in the case of an on-chain broadcast of the commitment transaction.

func (*OpenChannel) FullSync

func (c *OpenChannel) FullSync() error

FullSync serializes, and writes to disk the *full* channel state, using both the active channel bucket to store the prefixed column fields, and the remote node's ID to store the remainder of the channel state.

NOTE: This method requires an active EncryptorDecryptor to be registered in order to encrypt sensitive information.

func (*OpenChannel) Snapshot

func (c *OpenChannel) Snapshot() *ChannelSnapshot

Snapshot returns a read-only snapshot of the current channel state. This snapshot includes information concerning the current settled balance within the channel, meta-data detailing total flows, and any outstanding HTLCs.

func (*OpenChannel) UpdateCommitment

func (c *OpenChannel) UpdateCommitment(newCommitment *wire.MsgTx,
	newSig []byte, delta *ChannelDelta) error

UpdateCommitment updates the on-disk state of our currently broadcastable commitment state. This method is to be called once we have revoked our prior commitment state, accepting the new state as defined by the passed parameters.

Jump to

Keyboard shortcuts

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