channeldb

package
v0.2.1-alpha Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2017 License: MIT Imports: 20 Imported by: 0

README

channeldb

Build Status MIT licensed GoDoc

The channeldb implements the persistent storage engine for lnd and generically a data storage layer for the required state within the Lightning Network. The backing storage engine is boltdb, an embedded pure-go key-value store based off of LMDB.

The package implements an object-oriented storage model with queries and mutations flowing through a particular object instance rather than the database itself. The storage implemented by the objects includes: open channels, past commitment revocation states, the channel graph which includes authenticated node and channel announcements, outgoing payments, and invoices

Installation and Updating

$ go get -u github.com/lightningnetwork/lnd/channeldb

Documentation

Index

Constants

View Source
const (

	// SingleFunder represents a channel wherein one party solely funds the
	// entire capacity of the channel.
	SingleFunder = 0

	// DualFunder represents a channel wherein both parties contribute
	// funds towards the total capacity of the channel. The channel may be
	// funded symmetrically or asymmetrically.
	DualFunder = 1
)
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 is returned when a channel bucket hasn't been
	// created.
	ErrNoChanDBExists = fmt.Errorf("channel db has not yet been created")

	// ErrLinkNodesNotFound is returned when node info bucket hasn't been
	// created.
	ErrLinkNodesNotFound = fmt.Errorf("no link nodes exist")

	// ErrNoActiveChannels  is returned when there is no active (open)
	// channels within the database.
	ErrNoActiveChannels = fmt.Errorf("no active channels exist")

	// ErrNoPastDeltas is returned when the channel delta bucket hasn't been
	// created.
	ErrNoPastDeltas = fmt.Errorf("channel has no recorded deltas")

	// ErrInvoiceNotFound is returned when a targeted invoice can't be
	// found.
	ErrInvoiceNotFound = fmt.Errorf("unable to locate invoice")

	// ErrNoInvoicesCreated is returned when we don't have invoices in
	// our database to return.
	ErrNoInvoicesCreated = fmt.Errorf("there are no existing invoices")

	// ErrDuplicateInvoice is returned when an invoice with the target
	// payment hash already exists.
	ErrDuplicateInvoice = fmt.Errorf("invoice with payment hash already exists")

	// ErrNoPaymentsCreated is returned when bucket of payments hasn't been
	// created.
	ErrNoPaymentsCreated = fmt.Errorf("there are no existing payments")

	// ErrNodeNotFound is returned when node bucket exists, but node with
	// specific identity can't be found.
	ErrNodeNotFound = fmt.Errorf("link node with target identity not found")

	// ErrMetaNotFound is returned when meta bucket hasn't been
	// created.
	ErrMetaNotFound = fmt.Errorf("unable to locate meta information")

	// ErrGraphNotFound is returned when at least one of the components of
	// graph doesn't exist.
	ErrGraphNotFound = fmt.Errorf("graph bucket not initialized")

	// ErrGraphNeverPruned is returned when graph was never pruned.
	ErrGraphNeverPruned = fmt.Errorf("graph never pruned")

	// ErrSourceNodeNotSet is returned if the the source node of the graph
	// hasn't been added The source node is the center node within a
	// star-graph.
	ErrSourceNodeNotSet = fmt.Errorf("source node does not exist")

	// ErrGraphNodesNotFound is returned in case none of the nodes has
	// been added in graph node bucket.
	ErrGraphNodesNotFound = fmt.Errorf("no graph nodes exist")

	// ErrGraphNoEdgesFound is returned in case of none of the channel/edges
	// has been added in graph edge bucket.
	ErrGraphNoEdgesFound = fmt.Errorf("no graph edges exist")

	// ErrGraphNodeNotFound is returned when we're unable to find the target
	// node.
	ErrGraphNodeNotFound = fmt.Errorf("unable to find node")

	// ErrEdgeNotFound is returned when an edge for the target chanID
	// can't be found.
	ErrEdgeNotFound = fmt.Errorf("edge not found")

	// ErrEdgeAlreadyExist is returned when edge with specific
	// channel id can't be added because it already exist.
	ErrEdgeAlreadyExist = fmt.Errorf("edge already exist")

	// ErrNodeAliasNotFound is returned when alias for node can't be found.
	ErrNodeAliasNotFound = fmt.Errorf("alias for node not found")

	// ErrUnknownAddressType is returned when a node's addressType is not
	// an expected value.
	ErrUnknownAddressType = fmt.Errorf("address type cannot be resolved")
)

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 ChannelAuthProof

type ChannelAuthProof struct {
	// NodeSig1 is the signature using the identity key of the node that is
	// first in a lexicographical ordering of the serialized public keys of
	// the two nodes that created the channel.
	NodeSig1 *btcec.Signature

	// NodeSig2 is the signature using the identity key of the node that is
	// second in a lexicographical ordering of the serialized public keys
	// of the two nodes that created the channel.
	NodeSig2 *btcec.Signature

	// BitcoinSig1 is the signature using the public key of the first node
	// that was used in the channel's multi-sig output.
	BitcoinSig1 *btcec.Signature

	// BitcoinSig2 is the signature using the public key of the second node
	// that was used in the channel's multi-sig output.
	BitcoinSig2 *btcec.Signature
}

ChannelAuthProof is the authentication proof (the signature portion) for a channel. Using the four signatures contained in the struct, and some axillary knowledge (the funding script, node identities, and outpoint) nodes on the network are able to validate the authenticity and existence of a channel. Each of these signatures signs the following digest: chanID || nodeID1 || nodeID2 || bitcoinKey1|| bitcoinKey2 || 2-byte-feature-len || features.

func (*ChannelAuthProof) IsEmpty

func (p *ChannelAuthProof) IsEmpty() bool

IsEmpty check is the authentication proof is empty Proof is empty if at least one of the signatures are equal to nil.

type ChannelDelta

type ChannelDelta struct {
	// LocalBalance is our current balance at this particular update
	// number.
	LocalBalance btcutil.Amount

	// RemoteBalanceis the balance of the remote node at this particular
	// update number.
	RemoteBalance btcutil.Amount

	// UpdateNum is the update number that this ChannelDelta represents the
	// total number of commitment updates to this point. This can be viewed
	// as sort of a "commitment height" as this number is monotonically
	// increasing.
	UpdateNum uint64

	// Htlcs is the set of HTLC's that are pending at this particular
	// commitment height.
	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 HTLCs are recorded. These snapshots detail the state of the _remote_ party's commitment at a particular state number. For ourselves (the local node) we ONLY store our most recent (unrevoked) state for safety purposes.

type ChannelEdgeInfo

type ChannelEdgeInfo struct {
	// ChannelID is the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// NodeKey1 is the identity public key of the "first" node that was
	// involved in the creation of this channel. A node is considered
	// "first" if the lexicographical ordering the its serialized public
	// key is "smaller" than that of the other node involved in channel
	// creation.
	NodeKey1 *btcec.PublicKey

	// NodeKey2 is the identity public key of the "second" node that was
	// involved in the creation of this channel. A node is considered
	// "second" if the lexicographical ordering the its serialized public
	// key is "larger" than that of the other node involved in channel
	// creation.
	NodeKey2 *btcec.PublicKey

	// BitcoinKey1 is the Bitcoin multi-sig key belonging to the first
	// node, that was involved in the funding transaction that originally
	// created the channel that this struct represents.
	BitcoinKey1 *btcec.PublicKey

	// BitcoinKey2 is the Bitcoin multi-sig key belonging to the second
	// node, that was involved in the funding transaction that originally
	// created the channel that this struct represents.
	BitcoinKey2 *btcec.PublicKey

	// Features is an opaque byte slice that encodes the set of channel
	// specific features that this channel edge supports.
	Features []byte

	// AuthProof is the authentication proof for this channel. This proof
	// contains a set of signatures binding four identities, which attests
	// to the legitimacy of the advertised channel.
	AuthProof *ChannelAuthProof

	// ChannelPoint is the funding outpoint of the channel. This can be
	// used to uniquely identify the channel within the channel graph.
	ChannelPoint wire.OutPoint

	// Capacity is the total capacity of the channel, this is determined by
	// the value output in the outpoint that created this channel.
	Capacity btcutil.Amount
}

ChannelEdgeInfo represents a fully authenticated channel along with all its unique attributes. Once an authenticated channel announcement has been processed on the network, then a instance of ChannelEdgeInfo encapsulating the channels attributes is stored. The other portions relevant to routing policy of a channel are stored within a ChannelEdgePolicy for each direction of the channel.

type ChannelEdgePolicy

type ChannelEdgePolicy struct {
	// Signature is a channel announcement signature, which is needed for
	// proper edge policy announcement.
	Signature *btcec.Signature

	// ChannelID is the unique channel ID for the channel. The first 3
	// bytes are the block height, the next 3 the index within the block,
	// and the last 2 bytes are the output index for the channel.
	ChannelID uint64

	// LastUpdate is the last time an authenticated edge for this channel
	// was received.
	LastUpdate time.Time

	// Flags is a bitfield which signals the capabilities of the channel as
	// well as the directed edge this update applies to.
	// TODO(roasbeef):  make into wire struct
	Flags uint16

	// TimeLockDelta is the number of blocks this node will subtract from
	// the expiry of an incoming HTLC. This value expresses the time buffer
	// the node would like to HTLC exchanges.
	TimeLockDelta uint16

	// MinHTLC is the smallest value HTLC this node will accept, expressed
	// in millisatoshi.
	MinHTLC btcutil.Amount

	// FeeBaseMSat is the base HTLC fee that will be charged for forwarding
	// ANY HTLC, expressed in mSAT's.
	FeeBaseMSat btcutil.Amount

	// FeeProportionalMillionths is the rate that the node will charge for
	// HTLCs for each millionth of a satoshi forwarded.
	FeeProportionalMillionths btcutil.Amount

	// Node is the LightningNode that this directed edge leads to. Using
	// this pointer the channel graph can further be traversed.
	Node *LightningNode
	// contains filtered or unexported fields
}

ChannelEdgePolicy represents a *directed* edge within the channel graph. For each channel in the database, there are two distinct edges: one for each possible direction of travel along the channel. The edges themselves hold information concerning fees, and minimum time-lock information which is utilized during path finding.

type ChannelGraph

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

ChannelGraph is a persistent, on-disk graph representation of the Lightning Network. This struct can be used to implement path finding algorithms on top of, and also to update a node's view based on information received from the p2p network. Internally, the graph is stored using a modified adjacency list representation with some added object interaction possible with each serialized edge/node. The graph is stored is directed, meaning that are two edges stored for each channel: an inbound/outbound edge for each node pair. Nodes, edges, and edge information can all be added to the graph independently. Edge removal results in the deletion of all edge information for that edge.

func (*ChannelGraph) AddChannelEdge

func (c *ChannelGraph) AddChannelEdge(edge *ChannelEdgeInfo) error

AddChannelEdge adds a new (undirected, blank) edge to the graph database. An undirected edge from the two target nodes are created. The information stored denotes the static attributes of the channel, such as the channelID, the keys involved in creation of the channel, and the set of features that the channel supports. The chanPoint and chanID are used to uniquely identify the edge globally within the database.

func (*ChannelGraph) AddLightningNode

func (c *ChannelGraph) AddLightningNode(node *LightningNode) error

AddLightningNode adds a new (unconnected) vertex/node to the graph database. When adding an edge, each node must be added before the edge can be inserted. Afterwards the edge information can then be updated. TODO(roasbeef): also need sig of announcement

func (*ChannelGraph) ChannelID

func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error)

ChannelID attempt to lookup the 8-byte compact channel ID which maps to the passed channel point (outpoint). If the passed channel doesn't exist within the database, then ErrEdgeNotFound is returned.

func (*ChannelGraph) DeleteChannelEdge

func (c *ChannelGraph) DeleteChannelEdge(chanPoint *wire.OutPoint) error

DeleteChannelEdge removes an edge from the database as identified by it's funding outpoint. If the edge does not exist within the database, then this

func (*ChannelGraph) DeleteLightningNode

func (c *ChannelGraph) DeleteLightningNode(nodePub *btcec.PublicKey) error

DeleteLightningNode removes a vertex/node from the database according to the node's public key.

func (*ChannelGraph) FetchChannelEdgesByID

func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (*ChannelEdgeInfo, *ChannelEdgePolicy, *ChannelEdgePolicy, error)

FetchChannelEdgesByID attempts to lookup the two directed edges for the channel identified by the channel ID. If the channel can't be found, then ErrEdgeNotFound is returned. A struct which houses the general information for the channel itself is returned as well as two structs that contain the routing policies for the channel in either direction.

func (*ChannelGraph) FetchChannelEdgesByOutpoint

func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (*ChannelEdgeInfo, *ChannelEdgePolicy, *ChannelEdgePolicy, error)

FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for the channel identified by the funding outpoint. If the channel can't be found, then ErrEdgeNotFound is returned. A struct which houses the general information for the channel itself is returned as well as two structs that contain the routing policies for the channel in either direction.

func (*ChannelGraph) FetchLightningNode

func (c *ChannelGraph) FetchLightningNode(pub *btcec.PublicKey) (*LightningNode, error)

FetchLightningNode attempts to look up a target node by its identity public key. If the node isn't found in the database, then ErrGraphNodeNotFound is returned.

func (*ChannelGraph) ForEachChannel

ForEachChannel iterates through all the channel edges stored within the graph and invokes the passed callback for each edge. The callback takes two edges as since this is a directed graph, both the in/out edges are visited. If the callback returns an error, then the transaction is aborted and the iteration stops early.

NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer for that particular channel edge routing policy will be passed into the callback.

func (*ChannelGraph) ForEachNode

func (c *ChannelGraph) ForEachNode(cb func(*LightningNode) error) error

ForEachNode iterates through all the stored vertices/nodes in the graph, executing the passed callback with each node encountered. If the callback returns an error, then the transaction is aborted and the iteration stops early.

func (*ChannelGraph) HasChannelEdge

func (c *ChannelGraph) HasChannelEdge(chanID uint64) (time.Time, time.Time, bool, error)

HasChannelEdge returns true if the database knows of a channel edge with the passed channel ID, and false otherwise. If the an edge with that ID is found within the graph, then two time stamps representing the last time the edge was updated for both directed edges are returned along with the boolean.

func (*ChannelGraph) HasLightningNode

func (c *ChannelGraph) HasLightningNode(pub *btcec.PublicKey) (time.Time, bool, error)

HasLightningNode determines if the graph has a vertex identified by the target node identity public key. If the node exists in the database, a timestamp of when the data for the node was lasted updated is returned along with a true boolean. Otherwise, an empty time.Time is returned with a false boolean.

func (*ChannelGraph) LookupAlias

func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error)

LookupAlias attempts to return the alias as advertised by the target node. TODO(roasbeef): currently assumes that aliases are unique...

func (*ChannelGraph) NewChannelEdgePolicy

func (c *ChannelGraph) NewChannelEdgePolicy() *ChannelEdgePolicy

NewChannelEdgePolicy returns a new blank ChannelEdgePolicy.

func (*ChannelGraph) PruneGraph

func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint,
	blockHash *chainhash.Hash, blockHeight uint32) ([]*ChannelEdgeInfo, error)

PruneGraph prunes newly closed channels from the channel graph in response to a new block being solved on the network. Any transactions which spend the funding output of any known channels within he graph will be deleted. Additionally, the "prune tip", or the last block which has been used to prune the graph is stored so callers can ensure the graph is fully in sync with the current UTXO state. A slice of channels that have been closed by the target block are returned if the function succeeds without error.

func (*ChannelGraph) PruneTip

func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error)

PruneTip returns the block height and hash of the latest block that has been used to prune channels in the graph. Knowing the "prune tip" allows callers to tell if the graph is currently in sync with the current best known UTXO state.

func (*ChannelGraph) SetSourceNode

func (c *ChannelGraph) SetSourceNode(node *LightningNode) error

SetSourceNode sets the source node within the graph database. The source node is to be used as the center of a star-graph within path finding algorithms.

func (*ChannelGraph) SourceNode

func (c *ChannelGraph) SourceNode() (*LightningNode, error)

SourceNode returns the source node of the graph. The source node is treated as the center node within a star-graph. This method may be used to kick off a path finding algorithm in order to explore the reachability of another node based off the source node.

func (*ChannelGraph) UpdateChannelEdge

func (c *ChannelGraph) UpdateChannelEdge(edge *ChannelEdgeInfo) error

UpdateChannelEdge retrieves and update edge of the graph database. Method only reserved for updating an edge info after it's already been created. In order to maintain this constraints, we return an error in the scenario that an edge info hasn't yet been created yet, but someone attempts to update it.

func (*ChannelGraph) UpdateEdgePolicy

func (c *ChannelGraph) UpdateEdgePolicy(edge *ChannelEdgePolicy) error

UpdateEdgePolicy updates the edge routing policy for a single directed edge within the database for the referenced channel. The `flags` attribute within the ChannelEdgePolicy determines which of the directed edges are being updated. If the flag is 1, then the first node's information is being updated, otherwise it's the second node's information. The node ordering is determined tby the lexicographical ordering of the identity public keys of the nodes on either side of the channel.

type ChannelSnapshot

type ChannelSnapshot struct {
	RemoteIdentity btcec.PublicKey

	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 ChannelType

type ChannelType uint8

ChannelType is an enum-like type that describes one of several possible channel types. Each open channel is associated with a particular type as the channel type may determine how higher level operations are conducted such as fee negotiation, channel closing, the format of HTLCs, etc. TODO(roasbeef): split up per-chain?

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 {
	*bolt.DB
	// 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) (*DB, error)

Open opens an existing channeldb. Any necessary schemas migrations due to updates will take place as necessary.

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) AddPayment

func (db *DB) AddPayment(payment *OutgoingPayment) error

AddPayment saves a successful payment to the database. It is assumed that all payment are sent using unique payment hashes.

func (*DB) ChannelGraph

func (d *DB) ChannelGraph() *ChannelGraph

ChannelGraph returns a new instance of the directed channel graph.

func (*DB) DeleteAllPayments

func (db *DB) DeleteAllPayments() error

DeleteAllPayments deletes all payments from DB.

func (*DB) FetchAllChannels

func (d *DB) FetchAllChannels() ([]*OpenChannel, error)

FetchAllChannels attempts to retrieve all open channels currently stored within the database.

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) FetchAllLinkNodes

func (db *DB) FetchAllLinkNodes() ([]*LinkNode, error)

FetchAllLinkNodes attempts to fetch all active LinkNodes from the database. If there haven't been any channels explicitly linked to LinkNodes written to the database, then this function will return an empty slice.

func (*DB) FetchAllPayments

func (db *DB) FetchAllPayments() ([]*OutgoingPayment, error)

FetchAllPayments returns all outgoing payments in DB.

func (*DB) FetchLinkNode

func (db *DB) FetchLinkNode(identity *btcec.PublicKey) (*LinkNode, error)

FetchLinkNode attempts to lookup the data for a LinkNode based on a target identity public key. If a particular LinkNode for the passed identity public key cannot be found, then ErrNodeNotFound if returned.

func (*DB) FetchMeta

func (d *DB) FetchMeta(tx *bolt.Tx) (*Meta, error)

FetchMeta fetches the meta data from boltdb and returns filled meta structure.

func (*DB) FetchOpenChannels

func (d *DB) FetchOpenChannels(nodeID *btcec.PublicKey) ([]*OpenChannel, error)

FetchOpenChannels 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) FetchPendingChannels

func (d *DB) FetchPendingChannels() ([]*OpenChannel, error)

FetchPendingChannels will return channels that have completed the process of generating and broadcasting funding transactions, but whose funding transactions have yet to be confirmed on the blockchain.

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 isn'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) MarkChannelAsOpen

func (d *DB) MarkChannelAsOpen(outpoint *wire.OutPoint) error

MarkChannelAsOpen records the finalization of the funding process and marks a channel as available for use.

func (*DB) NewLinkNode

func (db *DB) NewLinkNode(bitNet wire.BitcoinNet, pub *btcec.PublicKey,
	addr *net.TCPAddr) *LinkNode

NewLinkNode creates a new LinkNode from the provided parameters, which is backed by an instance of channeldb.

func (*DB) PutMeta

func (d *DB) PutMeta(meta *Meta) error

PutMeta writes the passed instance of the database met-data struct to disk.

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

	// OutputIndex is the output index for this particular HTLC output
	// within the commitment transaction.
	OutputIndex uint16
}

HTLC is the on-disk representation of a hash time-locked contract. HTLCs 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 LightningNode

type LightningNode struct {
	// LastUpdate is the last time the vertex information for this node has
	// been updated.
	LastUpdate time.Time

	// Address is the TCP address this node is reachable over.
	Addresses []net.Addr

	// PubKey is the node's long-term identity public key. This key will be
	// used to authenticated any advertisements/updates sent by the node.
	PubKey *btcec.PublicKey

	// Color is the selected color for the node.
	Color color.RGBA

	// Alias is a nick-name for the node. The alias can be used to confirm
	// a node's identity or to serve as a short ID for an address book.
	Alias string

	// AuthSig is a signature under the advertised public key which serves
	// to authenticate the attributes announced by this node.
	//
	// TODO(roasbeef): hook into serialization once full verification is in
	AuthSig *btcec.Signature

	// Features is the list of protocol features supported by this node.
	Features *lnwire.FeatureVector
	// contains filtered or unexported fields
}

LightningNode represents an individual vertex/node within the channel graph. A node is connected to other nodes by one or more channel edges emanating from it. As the graph is directed, a node will also have an incoming edge attached to it for each outgoing edge.

func (*LightningNode) ForEachChannel

func (l *LightningNode) ForEachChannel(tx *bolt.Tx, cb func(*ChannelEdgeInfo, *ChannelEdgePolicy) error) error

ForEachChannel iterates through all the outgoing channel edges from this node, executing the passed callback with each edge as its sole argument. If the callback returns an error, then the iteration is halted with the error propagated back up to the caller. If the caller wishes to re-use an existing boltdb transaction, then it should be passed as the first argument. Otherwise the first argument should be nil and a fresh transaction will be created to execute the graph traversal.

type LinkNode

type LinkNode struct {
	// Network indicates the Bitcoin network that the LinkNode advertises
	// for incoming channel creation.
	Network wire.BitcoinNet

	// IdentityPub is the node's current identity public key. Any
	// channel/topology related information received by this node MUST be
	// signed by this public key.
	IdentityPub *btcec.PublicKey

	// LastSeen tracks the last time this node was seen within the network.
	// A node should be marked as seen if the daemon either is able to
	// establish an outgoing connection to the node or receives a new
	// incoming connection from the node. This timestamp (stored in unix
	// epoch) may be used within a heuristic which aims to determine when a
	// channel should be unilaterally closed due to inactivity.
	//
	// TODO(roasbeef): replace with block hash/height?
	//  * possibly add a time-value metric into the heuristic?
	LastSeen time.Time

	// Addresses is a list of IP address in which either we were able to
	// reach the node over in the past, OR we received an incoming
	// authenticated connection for the stored identity public key.
	//
	// TODO(roasbeef): also need to support hidden service addrs
	Addresses []*net.TCPAddr
	// contains filtered or unexported fields
}

LinkNode stores metadata related to node's that we have/had a direct channel open with. Information such as the Bitcoin network the node advertised, and its identity public key are also stored. Additionally, this struct and the bucket its stored within have store data similar to that of Bitcion's addrmanager. The TCP address information stored within the struct can be used to establish persistent connections will all channel counterparties on daemon startup.

TODO(roasbeef): also add current OnionKey plus rotation schedule? TODO(roasbeef): add bitfield for supported services

  • possibly add a wire.NetAddress type, type

func (*LinkNode) AddAddress

func (l *LinkNode) AddAddress(addr *net.TCPAddr) error

AddAddress appends the specified TCP address to the list of known addresses this node is/was known to be reachable at.

func (*LinkNode) Sync

func (l *LinkNode) Sync() error

Sync performs a full database sync which writes the current up-to-date data within the struct to the database.

func (*LinkNode) UpdateLastSeen

func (l *LinkNode) UpdateLastSeen(lastSeen time.Time) error

UpdateLastSeen updates the last time this node was directly encountered on the Lightning Network.

type Meta

type Meta struct {
	// DbVersionNumber is the current schema version of the database.
	DbVersionNumber uint32
}

Meta structure holds the database meta information.

type OpenChannel

type OpenChannel struct {
	// IdentityPub is the identity public key of the remote node this
	// channel has been established with.
	IdentityPub *btcec.PublicKey

	// ChanID is an identifier that uniquely identifies this channel
	// globally within the blockchain.
	ChanID *wire.OutPoint

	// MinFeePerKb is the min BTC/KB that should be paid within the
	// commitment transaction for the entire duration of the channel's
	// lifetime. This field may be updated during normal operation of the
	// channel as on-chain conditions change.
	MinFeePerKb btcutil.Amount

	// TheirDustLimit is the threshold below which no HTLC output should be
	// generated for their commitment transaction; ie. HTLCs below
	// this amount are not enforceable onchain from their point of view.
	TheirDustLimit btcutil.Amount

	// OurDustLimit is the threshold below which no HTLC output should be
	// generated for our commitment transaction; ie. HTLCs below
	// this amount are not enforceable onchain from out point of view.
	OurDustLimit btcutil.Amount

	// OurCommitKey is the key to be used within our commitment transaction
	// to generate the scripts for outputs paying to ourself, and
	// revocation clauses.
	OurCommitKey *btcec.PublicKey

	// TheirCommitKey is the key to be used within our commitment
	// transaction to generate the scripts for outputs paying to ourself,
	// and revocation clauses.
	TheirCommitKey *btcec.PublicKey

	// Capacity is the total capacity of this channel.
	// TODO(roasbeef): need another field to mark how much fees have been
	// allocated independent of capacity.
	Capacity btcutil.Amount

	// OurBalance is the current available settled balance within the
	// channel directly spendable by us.
	OurBalance btcutil.Amount

	// TheirBalance is the current available settled balance within the
	// channel directly spendable by the remote node.
	TheirBalance btcutil.Amount

	// OurCommitKey is the latest version of the commitment state,
	// broadcast able by us.
	OurCommitTx *wire.MsgTx

	// OurCommitSig is one half of the signature required to fully complete
	// the script for the commitment transaction above.
	OurCommitSig []byte

	// StateHintObsfucator are the btyes selected by the initiator (derived
	// from their shachain root) to obsfucate the state-hint encoded within
	// the commitment transaction.
	StateHintObsfucator [6]byte

	// ChanType denotes which type of channel this is.
	ChanType ChannelType

	// IsInitiator is a bool which indicates if we were the original
	// initiator for the channel. This value may affect how higher levels
	// negotiate fees, or close the channel.
	IsInitiator bool

	// IsPending indicates whether a channel's funding transaction has been
	// confirmed.
	IsPending bool

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

	// OurMultiSigKey is the multi-sig key used within the funding
	// transaction that we control.
	OurMultiSigKey *btcec.PublicKey

	// TheirMultiSigKey is the multi-sig key used within the funding
	// transaction for the remote party.
	TheirMultiSigKey *btcec.PublicKey

	// FundingWitnessScript is the full witness script used within the
	// funding transaction.
	FundingWitnessScript []byte

	// NumConfsRequired is the number of confirmations a channel's funding
	// transaction must have received in order to be considered available for
	// normal transactional use.
	NumConfsRequired uint16

	// LocalCsvDelay is the delay to be used in outputs paying to us within
	// the commitment transaction. This value is to be always expressed in
	// terms of relative blocks.
	LocalCsvDelay uint32

	// RemoteCsvDelay is the delay to be used in outputs paying to the
	// remote party. This value is to be always expressed in terms of
	// relative blocks.
	RemoteCsvDelay uint32

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

	// RevocationProducer is used to generate the revocation in such a way
	// that remote side might store it efficiently and have the ability to
	// restore the revocation by index if needed. Current implementation of
	// secret producer is shachain producer.
	RevocationProducer shachain.Producer

	// RevocationStore is used to efficiently store the revocations for
	// previous channels states sent to us by remote side. Current
	// implementation of secret store is shachain store.
	RevocationStore shachain.Store

	// OurDeliveryScript is the script to be used to pay to us in
	// cooperative closes.
	OurDeliveryScript []byte

	// OurDeliveryScript is the script to be used to pay to the remote
	// party in cooperative closes.
	TheirDeliveryScript []byte

	// NumUpdates is the total number of updates conducted within this
	// channel.
	NumUpdates uint64

	// TotalSatoshisSent is the total number of satoshis we've sent within
	// this channel.
	TotalSatoshisSent uint64

	// TotalSatoshisReceived is the total number of satoshis we've received
	// within this channel.
	TotalSatoshisReceived uint64

	// CreationTime is the time this channel was initially created.
	CreationTime time.Time

	// Htlcs is the list of active, uncleared HTLCs currently pending
	// within the channel.
	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.

func (*OpenChannel) CommitmentHeight

func (c *OpenChannel) CommitmentHeight() (uint64, error)

CommitmentHeight returns the current commitment height. The commitment height represents the number of updates to the commitment state to data. This value is always monotonically increasing. This method is provided in order to allow multiple instances of a particular open channel to obtain a consistent view of the number of channel updates to data.

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.

func (*OpenChannel) RevocationLogTail

func (c *OpenChannel) RevocationLogTail() (*ChannelDelta, error)

RevocationLogTail returns the "tail", or the end of the current revocation log. This entry represents the last previous state for the remote node's commitment chain. The ChannelDelta returned by this method will always lag one state behind the most current (unrevoked) state of the remote node's commitment chain.

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, metadata detailing total flows, and any outstanding HTLCs.

func (*OpenChannel) SyncPending

func (c *OpenChannel) SyncPending(addr *net.TCPAddr) error

SyncPending writes the contents of the channel to the database while it's in the pending (waiting for funding confirmation) state. The IsPending flag will be set to true. When the channel's funding transaction is confirmed, the channel should be marked as "open" and the IsPending flag set to false. Note that this function also creates a LinkNode relationship between this newly created channel and a new LinkNode instance. This allows listing all channels in the database globally, or according to the LinkNode they were created with.

TODO(roasbeef): addr param should eventually be a lnwire.NetAddress type that includes service bits.

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.

type OutgoingPayment

type OutgoingPayment struct {
	Invoice

	// Fee is the total fee paid for the payment in satoshis.
	Fee btcutil.Amount

	// TotalTimeLock is the total cumulative time-lock in the HTLC extended
	// from the second-to-last hop to the destination.
	TimeLockLength uint32

	// Path encodes the path the payment took throuhg the network. The path
	// excludes the outgoing node and consists of the hex-encoded
	// compressed public key of each of the nodes involved in the payment.
	Path [][33]byte

	// PaymentHash is the payment hash (r-hash) used to send the payment.
	//
	// TODO(roasbeef): weave through preimage on payment success to can
	// store only supplemental info the embedded Invoice
	PaymentHash [32]byte
}

OutgoingPayment represents a successful payment between the daemon and a remote node. Details such as the total fee paid, and the time of the payment are stored.

Jump to

Keyboard shortcuts

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