multi: fix make fmt

This commit is contained in:
yyforyongyu 2022-08-23 02:58:42 +08:00
parent 3851f286b9
commit 0735522194
No known key found for this signature in database
GPG Key ID: 9BCD95C4FF296868
77 changed files with 700 additions and 641 deletions

View File

@ -60,8 +60,8 @@ func (c *Child) String() string {
// DeriveChild computes the child preimage and child hash for a given (root,
// share, index) tuple. The derivation is defined as:
//
// child_preimage = SHA256(root || share || be32(index)),
// child_hash = SHA256(child_preimage).
// child_preimage = SHA256(root || share || be32(index)),
// child_hash = SHA256(child_preimage).
func DeriveChild(root Share, desc ChildDesc) *Child {
var (
indexBytes [4]byte

View File

@ -165,12 +165,14 @@ func ReconstructChildren(descs ...ChildDesc) []*Child {
// split splits a share into two random values, that when XOR'd reproduce the
// original share. Given a share s, the two shares are derived as:
// left <-$- random
// right = parent ^ left.
//
// left <-$- random
// right = parent ^ left.
//
// When reconstructed, we have that:
// left ^ right = left ^ parent ^ left
// = parent.
//
// left ^ right = left ^ parent ^ left
// = parent.
func split(parent *Share) (Share, Share, error) {
// Generate a random share for the left child.
var left Share

View File

@ -346,19 +346,21 @@ func EphemeralGenerator(gen func() (*btcec.PrivateKey, error)) func(*Machine) {
// itself.
//
// The acts proceeds the following order (initiator on the left):
// GenActOne() ->
// RecvActOne()
// <- GenActTwo()
// RecvActTwo()
// GenActThree() ->
// RecvActThree()
//
// GenActOne() ->
// RecvActOne()
// <- GenActTwo()
// RecvActTwo()
// GenActThree() ->
// RecvActThree()
//
// This exchange corresponds to the following Noise handshake:
// <- s
// ...
// -> e, es
// <- e, ee
// -> s, se
//
// <- s
// ...
// -> e, es
// <- e, ee
// -> s, se
type Machine struct {
sendCipher cipherState
recvCipher cipherState
@ -445,7 +447,7 @@ const (
// and the responder's static key. Future payloads are encrypted with a key
// derived from this result.
//
// -> e, es
// -> e, es
func (b *Machine) GenActOne() ([ActOneSize]byte, error) {
var actOne [ActOneSize]byte
@ -524,7 +526,7 @@ func (b *Machine) RecvActOne(actOne [ActOneSize]byte) error {
// act one, but then results in a different ECDH operation between the
// initiator's and responder's ephemeral keys.
//
// <- e, ee
// <- e, ee
func (b *Machine) GenActTwo() ([ActTwoSize]byte, error) {
var actTwo [ActTwoSize]byte
@ -601,7 +603,7 @@ func (b *Machine) RecvActTwo(actTwo [ActTwoSize]byte) error {
// the responder. This act also includes the final ECDH operation which yields
// the final session.
//
// -> s, se
// -> s, se
func (b *Machine) GenActThree() ([ActThreeSize]byte, error) {
var actThree [ActThreeSize]byte

View File

@ -37,7 +37,7 @@ const (
// running full node.
//
// TODO(roasbeef): heavily consolidate with NeutrinoNotifier code
// * maybe combine into single package?
// - maybe combine into single package?
type NeutrinoNotifier struct {
epochClientCounter uint64 // To be used atomically.

View File

@ -1405,11 +1405,11 @@ func (n *TxNotifier) dispatchSpendDetails(ntfn *SpendNtfn, details *SpendDetail)
// through every transaction and determine if it is relevant to any of its
// clients. A transaction can be relevant in either of the following two ways:
//
// 1. One of the inputs in the transaction spends an outpoint/output script
// for which we currently have an active spend registration for.
// 1. One of the inputs in the transaction spends an outpoint/output script
// for which we currently have an active spend registration for.
//
// 2. The transaction has a txid or output script for which we currently have
// an active confirmation registration for.
// 2. The transaction has a txid or output script for which we currently have
// an active confirmation registration for.
//
// In the event that the transaction is relevant, a confirmation/spend
// notification will be queued for dispatch to the relevant clients.

View File

@ -40,9 +40,9 @@ var (
)
// NoChainBackend is a mock implementation of the following interfaces:
// - chainview.FilteredChainView
// - chainntnfs.ChainNotifier
// - chainfee.Estimator
// - chainview.FilteredChainView
// - chainntnfs.ChainNotifier
// - chainfee.Estimator
type NoChainBackend struct {
}

View File

@ -1315,11 +1315,11 @@ func (c *OpenChannel) SecondCommitmentPoint() (*btcec.PublicKey, error) {
// commitment chains in the case of a last or only partially processed message.
// When the remote party receives this message one of three things may happen:
//
// 1. We're fully synced and no messages need to be sent.
// 2. We didn't get the last CommitSig message they sent, so they'll re-send
// it.
// 3. We didn't get the last RevokeAndAck message they sent, so they'll
// re-send it.
// 1. We're fully synced and no messages need to be sent.
// 2. We didn't get the last CommitSig message they sent, so they'll re-send
// it.
// 3. We didn't get the last RevokeAndAck message they sent, so they'll
// re-send it.
//
// If this is a restored channel, having status ChanStatusRestored, then we'll
// modify our typical chan sync message to ensure they force close even if

View File

@ -110,10 +110,10 @@ func checkPkgFilterRand(t *testing.T, b, p uint16) {
}
// checkPkgFilterEncodeDecode tests the serialization of a pkg filter by:
// 1) writing it to a buffer
// 2) verifying the number of bytes written matches the filter's Size()
// 3) reconstructing the filter decoding the bytes
// 4) checking that the two filters are the same according to Equal
// 1. writing it to a buffer
// 2. verifying the number of bytes written matches the filter's Size()
// 3. reconstructing the filter decoding the bytes
// 4. checking that the two filters are the same according to Equal
func checkPkgFilterEncodeDecode(t *testing.T, i uint16, f *channeldb.PkgFilter) {
var b bytes.Buffer
if err := f.Encode(&b); err != nil {

View File

@ -140,7 +140,6 @@ func (a *NodeAnnouncement) Decode(r io.Reader, pver uint32) error {
// Encode serializes the target NodeAnnouncement into the passed io.Writer
// observing the protocol version specified.
//
func (a *NodeAnnouncement) Encode(w io.Writer, pver uint32) error {
return WriteElements(w,
a.Signature,

View File

@ -9,7 +9,6 @@ import (
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
lnwire "github.com/lightningnetwork/lnd/channeldb/migration/lnwire21"
mig24 "github.com/lightningnetwork/lnd/channeldb/migration24"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"

View File

@ -4,7 +4,6 @@ import (
"fmt"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
"github.com/lightningnetwork/lnd/kvdb"
)

View File

@ -6,7 +6,6 @@ import (
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"
"github.com/lightningnetwork/lnd/kvdb"
)

View File

@ -8,7 +8,6 @@ import (
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"

View File

@ -7,7 +7,6 @@ import (
"fmt"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
"github.com/lightningnetwork/lnd/kvdb"
)

View File

@ -7,14 +7,13 @@ import (
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/channeldb/migtest"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/stretchr/testify/require"
lnwire "github.com/lightningnetwork/lnd/channeldb/migration/lnwire21"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"
"github.com/lightningnetwork/lnd/channeldb/migtest"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/stretchr/testify/require"
)
var (

View File

@ -3,12 +3,11 @@ package migration30
import (
"bytes"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chaincfg/chainhash"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/lightningnetwork/lnd/input"
)

View File

@ -6,12 +6,11 @@ import (
"io"
"math"
"github.com/btcsuite/btcd/btcutil"
mig24 "github.com/lightningnetwork/lnd/channeldb/migration24"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"
"github.com/btcsuite/btcd/btcutil"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/tlv"
@ -60,10 +59,10 @@ var (
// The actual size of each HTLCEntry varies based on its RHash and Amt(sat),
// summarized as follows,
//
// | RHash empty | Amt<=252 | Amt<=65,535 | Amt<=4,294,967,295 | otherwise |
// |:-----------:|:--------:|:-----------:|:------------------:|:---------:|
// | true | 19 | 21 | 23 | 26 |
// | false | 51 | 53 | 55 | 58 |
// | RHash empty | Amt<=252 | Amt<=65,535 | Amt<=4,294,967,295 | otherwise |
// |:-----------:|:--------:|:-----------:|:------------------:|:---------:|
// | true | 19 | 21 | 23 | 26 |
// | false | 51 | 53 | 55 | 58 |
//
// So the size varies from 19 bytes to 58 bytes, where most likely to be 23 or
// 55 bytes.

View File

@ -8,14 +8,13 @@ import (
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/shachain"
lnwire "github.com/lightningnetwork/lnd/channeldb/migration/lnwire21"
mig25 "github.com/lightningnetwork/lnd/channeldb/migration25"
mig26 "github.com/lightningnetwork/lnd/channeldb/migration26"
mig "github.com/lightningnetwork/lnd/channeldb/migration_01_to_11"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/shachain"
)
var (

View File

@ -15,12 +15,12 @@ import (
//
// Example output:
//
// map[string]interface{}{
// hex("1234"): map[string]interface{}{
// "human-readable": hex("102030"),
// hex("1111"): hex("5783492373"),
// },
// }
// map[string]interface{}{
// hex("1234"): map[string]interface{}{
// "human-readable": hex("102030"),
// hex("1111"): hex("5783492373"),
// },
// }
func DumpDB(tx kvdb.RTx, rootKey []byte) error {
bucket := tx.ReadBucket(rootKey)
if bucket == nil {

View File

@ -29,7 +29,7 @@ var (
//
// TODO(roasbeef): also add current OnionKey plus rotation schedule?
// TODO(roasbeef): add bitfield for supported services
// * possibly add a wire.NetAddress type, type
// - possibly add a wire.NetAddress type, type
type LinkNode struct {
// Network indicates the Bitcoin network that the LinkNode advertises
// for incoming channel creation.

View File

@ -47,10 +47,10 @@ var (
// The actual size of each HTLCEntry varies based on its RHash and Amt(sat),
// summarized as follows,
//
// | RHash empty | Amt<=252 | Amt<=65,535 | Amt<=4,294,967,295 | otherwise |
// |:-----------:|:--------:|:-----------:|:------------------:|:---------:|
// | true | 19 | 21 | 23 | 26 |
// | false | 51 | 53 | 55 | 58 |
// | RHash empty | Amt<=252 | Amt<=65,535 | Amt<=4,294,967,295 | otherwise |
// |:-----------:|:--------:|:-----------:|:------------------:|:---------:|
// | true | 19 | 21 | 23 | 26 |
// | false | 51 | 53 | 55 | 58 |
//
// So the size varies from 19 bytes to 58 bytes, where most likely to be 23 or
// 55 bytes.
@ -454,11 +454,11 @@ func fetchOldRevocationLog(log kvdb.RBucket,
// fetchRevocationLogCompatible finds the revocation log from both the
// revocationLogBucket and revocationLogBucketDeprecated for compatibility
// concern. It returns three values,
// - RevocationLog, if this is non-nil, it means we've found the log in the
// new bucket.
// - ChannelCommitment, if this is non-nil, it means we've found the log in the
// old bucket.
// - error, this can happen if the log cannot be found in neither buckets.
// - RevocationLog, if this is non-nil, it means we've found the log in the
// new bucket.
// - ChannelCommitment, if this is non-nil, it means we've found the log in the
// old bucket.
// - error, this can happen if the log cannot be found in neither buckets.
func fetchRevocationLogCompatible(chanBucket kvdb.RBucket,
updateNum uint64) (*RevocationLog, *ChannelCommitment, error) {

View File

@ -58,7 +58,7 @@ var (
// use this cache to detect duplicate witnesses.
//
// TODO(roasbeef): need expiry policy?
// * encrypt?
// - encrypt?
type WitnessCache struct {
db *DB
}

View File

@ -388,15 +388,16 @@ func openChannel(ctx *cli.Context) error {
// protocol involves several steps between the RPC server and the CLI client:
//
// RPC server CLI client
// | |
// | |<------open channel (stream)-----|
// | |-------ready for funding----->| |
// | |<------PSBT verify------------| |
// | |-------ready for signing----->| |
// | |<------PSBT finalize----------| |
// | |-------channel pending------->| |
// | |-------channel open------------->|
// | |
//
// | |
// | |<------open channel (stream)-----|
// | |-------ready for funding----->| |
// | |<------PSBT verify------------| |
// | |-------ready for signing----->| |
// | |<------PSBT finalize----------| |
// | |-------channel pending------->| |
// | |-------channel open------------->|
// | |
func openChannelPsbt(rpcCtx context.Context, ctx *cli.Context,
client lnrpc.LightningClient,
req *lnrpc.OpenChannelRequest) error {

View File

@ -4,10 +4,10 @@
package main
import (
"strconv"
"github.com/lightningnetwork/lnd/lnrpc/neutrinorpc"
"github.com/urfave/cli"
"strconv"
)
func getNeutrinoKitClient(ctx *cli.Context) (neutrinorpc.NeutrinoKitClient, func()) {

View File

@ -1,3 +1,4 @@
//go:build !neutrinorpc
// +build !neutrinorpc
package main

View File

@ -642,10 +642,10 @@ func DefaultConfig() Config {
// line options.
//
// The configuration proceeds as follows:
// 1) Start with a default config with sane settings
// 2) Pre-parse the command line to check for an alternative config file
// 3) Load configuration file overwriting defaults with any specified options
// 4) Parse CLI options and overwrite/add any specified options
// 1. Start with a default config with sane settings
// 2. Pre-parse the command line to check for an alternative config file
// 3. Load configuration file overwriting defaults with any specified options
// 4. Parse CLI options and overwrite/add any specified options
func LoadConfig(interceptor signal.Interceptor) (*Config, error) {
// Pre-parse the command line options to pick up an alternative config
// file.

View File

@ -53,13 +53,13 @@ func newIncomingContestResolver(
// Resolve attempts to resolve this contract. As we don't yet know of the
// preimage for the contract, we'll wait for one of two things to happen:
//
// 1. We learn of the preimage! In this case, we can sweep the HTLC incoming
// and ensure that if this was a multi-hop HTLC we are made whole. In this
// case, an additional ContractResolver will be returned to finish the
// job.
// 1. We learn of the preimage! In this case, we can sweep the HTLC incoming
// and ensure that if this was a multi-hop HTLC we are made whole. In this
// case, an additional ContractResolver will be returned to finish the
// job.
//
// 2. The HTLC expires. If this happens, then the contract is fully resolved
// as we have no remaining actions left at our disposal.
// 2. The HTLC expires. If this happens, then the contract is fully resolved
// as we have no remaining actions left at our disposal.
//
// NOTE: Part of the ContractResolver interface.
func (h *htlcIncomingContestResolver) Resolve() (ContractResolver, error) {

View File

@ -38,12 +38,12 @@ func newOutgoingContestResolver(res lnwallet.OutgoingHtlcResolution,
// Resolve commences the resolution of this contract. As this contract hasn't
// yet timed out, we'll wait for one of two things to happen
//
// 1. The HTLC expires. In this case, we'll sweep the funds and send a clean
// up cancel message to outside sub-systems.
// 1. The HTLC expires. In this case, we'll sweep the funds and send a clean
// up cancel message to outside sub-systems.
//
// 2. The remote party sweeps this HTLC on-chain, in which case we'll add the
// pre-image to our global cache, then send a clean up settle message
// backwards.
// 2. The remote party sweeps this HTLC on-chain, in which case we'll add the
// pre-image to our global cache, then send a clean up settle message
// backwards.
//
// When either of these two things happens, we'll create a new resolver which
// is able to handle the final resolution of the contract. We're only the pivot

View File

@ -1191,7 +1191,7 @@ func (u *UtxoNursery) closeAndRemoveIfMature(chanPoint *wire.OutPoint) error {
// be used to spend the CSV output contained in the timeout txn.
//
// TODO(roasbeef): re-rename to timeout tx
// * create CltvCsvSpendableOutput
// - create CltvCsvSpendableOutput
type babyOutput struct {
// expiry is the absolute block height at which the secondLevelTx
// should be broadcast to the network.

View File

@ -277,7 +277,7 @@ func (c *ChannelGraphBootstrapper) Name() string {
// interface which implements peer bootstrapping via a special DNS seed as
// defined in BOLT-0010. For further details concerning Lightning's current DNS
// boot strapping protocol, see this link:
// * https://github.com/lightningnetwork/lightning-rfc/blob/master/10-dns-bootstrap.md
// - https://github.com/lightningnetwork/lightning-rfc/blob/master/10-dns-bootstrap.md
type DNSSeedBootstrapper struct {
// dnsSeeds is an array of two tuples we'll use for bootstrapping. The
// first item in the tuple is the primary host we'll use to attempt the

View File

@ -202,8 +202,8 @@ func (m *SyncManager) Stop() {
// 2. Finding new peers to receive graph updates from to ensure we don't only
// receive them from the same set of peers.
// 3. Finding new peers to force a historical sync with to ensure we have as
// much of the public network as possible.
// 3. Finding new peers to force a historical sync with to ensure we have as
// much of the public network as possible.
//
// NOTE: This must be run as a goroutine.
func (m *SyncManager) syncerHandler() {

View File

@ -1608,13 +1608,15 @@ func TestGossipSyncerDelayDOS(t *testing.T) {
// rate-limiting. The provided chanSeries should belong to syncer2.
//
// The state transition performed is the following:
// syncer1 -- QueryShortChanIDs --> syncer2
// chanSeries.FetchChanAnns()
// syncer1 <-- ReplyShortChanIDsEnd -- syncer2
//
// syncer1 -- QueryShortChanIDs --> syncer2
// chanSeries.FetchChanAnns()
// syncer1 <-- ReplyShortChanIDsEnd -- syncer2
//
// If expDelayResponse is true, this method will assert that the call the
// FetchChanAnns happens between:
// [delayedQueryInterval-delayTolerance, delayedQueryInterval+delayTolerance].
//
// [delayedQueryInterval-delayTolerance, delayedQueryInterval+delayTolerance].
func queryBatch(t *testing.T,
msgChan1, msgChan2 chan []lnwire.Message,
syncer1, syncer2 *GossipSyncer,

View File

@ -88,9 +88,9 @@ type SphinxErrorEncrypter struct {
// should be used to deserialize an encoded SphinxErrorEncrypter. Since the
// actual encrypter is not stored in plaintext while at rest, reconstructing the
// error encrypter requires:
// 1) Decode: to deserialize the ephemeral public key.
// 2) Reextract: to "unlock" the actual error encrypter using an active
// OnionProcessor.
// 1. Decode: to deserialize the ephemeral public key.
// 2. Reextract: to "unlock" the actual error encrypter using an active
// OnionProcessor.
func NewSphinxErrorEncrypter() *SphinxErrorEncrypter {
return &SphinxErrorEncrypter{
OnionErrorEncrypter: nil,

View File

@ -28,26 +28,26 @@ import (
// - Present for htlc forwards through our node and local sends.
//
// Link Failure Event:
// - Indicates that a htlc has failed on our incoming or outgoing link,
// with an incoming boolean which indicates where the failure occurred.
// - Incoming link failures are present for failed attempts to pay one of
// our invoices (insufficient amount or mpp timeout, for example) and for
// forwards that we cannot decode to forward onwards.
// - Outgoing link failures are present for forwards or local payments that
// do not meet our outgoing link's policy (insufficient fees, for example)
// and when we fail to forward the payment on (insufficient outgoing
// capacity, or an unknown outgoing link).
// - Indicates that a htlc has failed on our incoming or outgoing link,
// with an incoming boolean which indicates where the failure occurred.
// - Incoming link failures are present for failed attempts to pay one of
// our invoices (insufficient amount or mpp timeout, for example) and for
// forwards that we cannot decode to forward onwards.
// - Outgoing link failures are present for forwards or local payments that
// do not meet our outgoing link's policy (insufficient fees, for example)
// and when we fail to forward the payment on (insufficient outgoing
// capacity, or an unknown outgoing link).
//
// Forwarding Failure Event:
// - Forwarding failures indicate that a htlc we forwarded has failed at
// another node down the route.
// - Present for local sends and htlc forwards which fail after they left
// our node.
// - Forwarding failures indicate that a htlc we forwarded has failed at
// another node down the route.
// - Present for local sends and htlc forwards which fail after they left
// our node.
//
// Settle event:
// - Settle events are present when a htlc which we added is settled through
// the release of a preimage.
// - Present for local receives, and successful local sends or forwards.
// - Settle events are present when a htlc which we added is settled through
// the release of a preimage.
// - Present for local receives, and successful local sends or forwards.
//
// Each htlc is identified by its incoming and outgoing circuit key. Htlcs,
// and their subsequent settles or fails, can be identified by the combination

View File

@ -142,20 +142,19 @@ type ChannelUpdateHandler interface {
// incoming htlc requests, applying the changes to the channel, and also
// propagating/forwarding it to htlc switch.
//
// abstraction level
// ^
// |
// | - - - - - - - - - - - - Lightning - - - - - - - - - - - - -
// |
// | (Switch) (Switch) (Switch)
// | Alice <-- channel link --> Bob <-- channel link --> Carol
// |
// | - - - - - - - - - - - - - TCP - - - - - - - - - - - - - - -
// |
// | (Peer) (Peer) (Peer)
// | Alice <----- tcp conn --> Bob <---- tcp conn -----> Carol
// |
//
// abstraction level
// ^
// |
// | - - - - - - - - - - - - Lightning - - - - - - - - - - - - -
// |
// | (Switch) (Switch) (Switch)
// | Alice <-- channel link --> Bob <-- channel link --> Carol
// |
// | - - - - - - - - - - - - - TCP - - - - - - - - - - - - - - -
// |
// | (Peer) (Peer) (Peer)
// | Alice <----- tcp conn --> Bob <---- tcp conn -----> Carol
// |
type ChannelLink interface {
// TODO(roasbeef): modify interface to embed mail boxes?

View File

@ -168,11 +168,12 @@ func createInterceptorFunc(prefix, receiver string, messages []expectedMessage,
// Specifically, this tests the following scenario:
//
// A B
// <----add-----
// -----add---->
// <----sig-----
// -----rev----x
// -----sig----x
//
// <----add-----
// -----add---->
// <----sig-----
// -----rev----x
// -----sig----x
func TestChannelLinkRevThenSig(t *testing.T) {
t.Parallel()
@ -301,11 +302,12 @@ func TestChannelLinkRevThenSig(t *testing.T) {
// Specifically, this tests the following scenario:
//
// A B
// <----add-----
// -----add---->
// -----sig----x
// <----sig-----
// -----rev----x
//
// <----add-----
// -----add---->
// -----sig----x
// <----sig-----
// -----rev----x
func TestChannelLinkSigThenRev(t *testing.T) {
t.Parallel()

View File

@ -1012,11 +1012,11 @@ func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
// parseFailedPayment determines the appropriate failure message to return to
// a user initiated payment. The three cases handled are:
// 1) An unencrypted failure, which should already plaintext.
// 2) A resolution from the chain arbitrator, which possibly has no failure
// reason attached.
// 3) A failure from the remote party, which will need to be decrypted using
// the payment deobfuscator.
// 1. An unencrypted failure, which should already plaintext.
// 2. A resolution from the chain arbitrator, which possibly has no failure
// reason attached.
// 3. A failure from the remote party, which will need to be decrypted using
// the payment deobfuscator.
func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
attemptID uint64, paymentHash lntypes.Hash, unencrypted,
isResolution bool, htlc *lnwire.UpdateFailHTLC) error {

View File

@ -941,15 +941,19 @@ func createClusterChannels(aliceToBob, bobToCarol btcutil.Amount) (
// newThreeHopNetwork function creates the following topology and returns the
// control object to manage this cluster:
//
// alice bob carol
// server - <-connection-> - server - - <-connection-> - - - server
// | | |
// alice htlc bob htlc carol htlc
// switch switch \ switch
// | | \ |
// | | \ |
// alice first bob second bob carol
// channel link channel link channel link channel link
// alice bob carol
// server - <-connection-> - server - - <-connection-> - - - server
//
// | | |
//
// alice htlc bob htlc carol htlc
// switch switch \ switch
//
// | | \ |
// | | \ |
//
// alice first bob second bob carol
// channel link channel link channel link channel link
//
// This function takes server options which can be used to apply custom
// settings to alice, bob and carol.
@ -1210,16 +1214,19 @@ type twoHopNetwork struct {
// newTwoHopNetwork function creates the following topology and returns the
// control object to manage this cluster:
//
// alice bob
// server - <-connection-> - server
// | |
// alice htlc bob htlc
// switch switch
// | |
// | |
// alice bob
// channel link channel link
// alice bob
// server - <-connection-> - server
//
// | |
//
// alice htlc bob htlc
// switch switch
//
// | |
// | |
//
// alice bob
// channel link channel link.
func newTwoHopNetwork(t testing.TB,
aliceChannel, bobChannel *lnwallet.LightningChannel,
startingHeight uint32) *twoHopNetwork {

View File

@ -203,36 +203,40 @@ func Ripemd160H(d []byte) []byte {
// output payment for the sender's version of the commitment transaction. The
// possible script paths from this output include:
//
// * The sender timing out the HTLC using the second level HTLC timeout
// transaction.
// * The receiver of the HTLC claiming the output on-chain with the payment
// preimage.
// * The receiver of the HTLC sweeping all the funds in the case that a
// revoked commitment transaction bearing this HTLC was broadcast.
// - The sender timing out the HTLC using the second level HTLC timeout
// transaction.
// - The receiver of the HTLC claiming the output on-chain with the payment
// preimage.
// - The receiver of the HTLC sweeping all the funds in the case that a
// revoked commitment transaction bearing this HTLC was broadcast.
//
// If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
// cases, to allow sweeping only after confirmation.
//
// Possible Input Scripts:
// SENDR: <0> <sendr sig> <recvr sig> <0> (spend using HTLC timeout transaction)
// RECVR: <recvr sig> <preimage>
// REVOK: <revoke sig> <revoke key>
// * receiver revoke
//
// OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
// OP_IF
// OP_CHECKSIG
// OP_ELSE
// <recv htlc key>
// OP_SWAP OP_SIZE 32 OP_EQUAL
// OP_NOTIF
// OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG
// OP_ELSE
// OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
// OP_CHECKSIG
// OP_ENDIF
// [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed spend only.
// OP_ENDIF
// SENDR: <0> <sendr sig> <recvr sig> <0> (spend using HTLC timeout transaction)
// RECVR: <recvr sig> <preimage>
// REVOK: <revoke sig> <revoke key>
// * receiver revoke
//
// Offered HTLC Output Script:
//
// OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
// OP_IF
// OP_CHECKSIG
// OP_ELSE
// <recv htlc key>
// OP_SWAP OP_SIZE 32 OP_EQUAL
// OP_NOTIF
// OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG
// OP_ELSE
// OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
// OP_CHECKSIG
// OP_ENDIF
// [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
// spend only.
// OP_ENDIF
func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
revocationKey *btcec.PublicKey, paymentHash []byte,
confirmedSpend bool) ([]byte, error) {
@ -442,37 +446,40 @@ func SenderHtlcSpendTimeout(receiverSig Signature,
// ReceiverHTLCScript constructs the public key script for an incoming HTLC
// output payment for the receiver's version of the commitment transaction. The
// possible execution paths from this script include:
// * The receiver of the HTLC uses its second level HTLC transaction to
// - The receiver of the HTLC uses its second level HTLC transaction to
// advance the state of the HTLC into the delay+claim state.
// * The sender of the HTLC sweeps all the funds of the HTLC as a breached
// - The sender of the HTLC sweeps all the funds of the HTLC as a breached
// commitment was broadcast.
// * The sender of the HTLC sweeps the HTLC on-chain after the timeout period
// - The sender of the HTLC sweeps the HTLC on-chain after the timeout period
// of the HTLC has passed.
//
// If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
// cases, to allow sweeping only after confirmation.
//
// Possible Input Scripts:
// RECVR: <0> <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction)
// REVOK: <sig> <key>
// SENDR: <sig> 0
//
// RECVR: <0> <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction)
// REVOK: <sig> <key>
// SENDR: <sig> 0
//
// OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
// OP_IF
// OP_CHECKSIG
// OP_ELSE
// <sendr htlc key>
// OP_SWAP OP_SIZE 32 OP_EQUAL
// OP_IF
// OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
// 2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG
// OP_ELSE
// OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
// OP_CHECKSIG
// OP_ENDIF
// [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed spend only.
// OP_ENDIF
// Received HTLC Output Script:
//
// OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
// OP_IF
// OP_CHECKSIG
// OP_ELSE
// <sendr htlc key>
// OP_SWAP OP_SIZE 32 OP_EQUAL
// OP_IF
// OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
// 2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG
// OP_ELSE
// OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
// OP_CHECKSIG
// OP_ENDIF
// [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
// spend only.
// OP_ENDIF
func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
receiverHtlcKey, revocationKey *btcec.PublicKey,
paymentHash []byte, confirmedSpend bool) ([]byte, error) {
@ -714,26 +721,29 @@ func ReceiverHtlcSpendTimeout(signer Signer, signDesc *SignDescriptor,
// spent in a particular way, and to a particular output.
//
// Possible Input Scripts:
// * To revoke an HTLC output that has been transitioned to the claim+delay
// state:
// * <revoke sig> 1
//
// * To claim and HTLC output, either with a pre-image or due to a timeout:
// * <delay sig> 0
// - To revoke an HTLC output that has been transitioned to the claim+delay
// state:
// <revoke sig> 1
//
// OP_IF
// <revoke key>
// OP_ELSE
// <delay in blocks>
// OP_CHECKSEQUENCEVERIFY
// OP_DROP
// <delay key>
// OP_ENDIF
// OP_CHECKSIG
// - To claim and HTLC output, either with a pre-image or due to a timeout:
// <delay sig> 0
//
// Output Script:
//
// OP_IF
// <revoke key>
// OP_ELSE
// <delay in blocks>
// OP_CHECKSEQUENCEVERIFY
// OP_DROP
// <delay key>
// OP_ENDIF
// OP_CHECKSIG
//
// TODO(roasbeef): possible renames for second-level
// * transition?
// * covenant output
// - transition?
// - covenant output
func SecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
csvDelay uint32) ([]byte, error) {
@ -780,25 +790,28 @@ func SecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
// spent in a particular way, and to a particular output.
//
// Possible Input Scripts:
// * To revoke an HTLC output that has been transitioned to the claim+delay
// state:
// * <revoke sig> 1
//
// * To claim an HTLC output, either with a pre-image or due to a timeout:
// * <delay sig> 0
// - To revoke an HTLC output that has been transitioned to the claim+delay
// state:
// <revoke sig> 1
//
// OP_IF
// <revoke key>
// OP_ELSE
// <lease maturity in blocks>
// OP_CHECKLOCKTIMEVERIFY
// OP_DROP
// <delay in blocks>
// OP_CHECKSEQUENCEVERIFY
// OP_DROP
// <delay key>
// OP_ENDIF
// OP_CHECKSIG.
// - To claim an HTLC output, either with a pre-image or due to a timeout:
// <delay sig> 0
//
// Output Script:
//
// OP_IF
// <revoke key>
// OP_ELSE
// <lease maturity in blocks>
// OP_CHECKLOCKTIMEVERIFY
// OP_DROP
// <delay in blocks>
// OP_CHECKSEQUENCEVERIFY
// OP_DROP
// <delay key>
// OP_ENDIF
// OP_CHECKSIG.
func LeaseSecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
csvDelay, cltvExpiry uint32) ([]byte, error) {
@ -944,7 +957,7 @@ func HtlcSecondLevelSpend(signer Signer, signDesc *SignDescriptor,
// LockTimeToSequence converts the passed relative locktime to a sequence
// number in accordance to BIP-68.
// See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
// * (Compatibility)
// - (Compatibility)
func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
if !isSeconds {
// The locktime is to be expressed in confirmations.
@ -964,17 +977,19 @@ func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
// can claim all the settled funds in the channel, plus the unsettled funds.
//
// Possible Input Scripts:
// REVOKE: <sig> 1
// SENDRSWEEP: <sig> <emptyvector>
//
// REVOKE: <sig> 1
// SENDRSWEEP: <sig> <emptyvector>
//
// Output Script:
// OP_IF
// <revokeKey>
// OP_ELSE
// <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
// <timeKey>
// OP_ENDIF
// OP_CHECKSIG
//
// OP_IF
// <revokeKey>
// OP_ELSE
// <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
// <timeKey>
// OP_ENDIF
// OP_CHECKSIG
func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *btcec.PublicKey) ([]byte, error) {
// This script is spendable under two conditions: either the
// 'csvTimeout' has passed and we can redeem our funds, or they can
@ -1015,18 +1030,20 @@ func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *btcec.PublicKey)
// can claim all the settled funds in the channel, plus the unsettled funds.
//
// Possible Input Scripts:
// REVOKE: <sig> 1
// SENDRSWEEP: <sig> <emptyvector>
//
// REVOKE: <sig> 1
// SENDRSWEEP: <sig> <emptyvector>
//
// Output Script:
// OP_IF
// <revokeKey>
// OP_ELSE
// <absoluteLeaseExpiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
// <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
// <timeKey>
// OP_ENDIF
// OP_CHECKSIG
//
// OP_IF
// <revokeKey>
// OP_ELSE
// <absoluteLeaseExpiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
// <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
// <timeKey>
// OP_ENDIF
// OP_CHECKSIG
func LeaseCommitScriptToSelf(selfKey, revokeKey *btcec.PublicKey,
csvTimeout, leaseExpiry uint32) ([]byte, error) {
@ -1194,9 +1211,11 @@ func CommitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error) {
// transaction. The money can only be spend after one confirmation.
//
// Possible Input Scripts:
// SWEEP: <sig>
//
// SWEEP: <sig>
//
// Output Script:
//
// <key> OP_CHECKSIGVERIFY
// 1 OP_CHECKSEQUENCEVERIFY
func CommitScriptToRemoteConfirmed(key *btcec.PublicKey) ([]byte, error) {
@ -1218,12 +1237,14 @@ func CommitScriptToRemoteConfirmed(key *btcec.PublicKey) ([]byte, error) {
// transaction. The money can only be spend after one confirmation.
//
// Possible Input Scripts:
// SWEEP: <sig>
//
// SWEEP: <sig>
//
// Output Script:
// <key> OP_CHECKSIGVERIFY
// <lease maturity in blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
// 1 OP_CHECKSEQUENCEVERIFY
//
// <key> OP_CHECKSIGVERIFY
// <lease maturity in blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
// 1 OP_CHECKSEQUENCEVERIFY
func LeaseCommitScriptToRemoteConfirmed(key *btcec.PublicKey,
leaseExpiry uint32) ([]byte, error) {
@ -1278,10 +1299,12 @@ func CommitSpendToRemoteConfirmed(signer Signer, signDesc *SignDescriptor,
// the given key immediately, or by anyone after 16 confirmations.
//
// Possible Input Scripts:
// By owner: <sig>
// By anyone (after 16 conf): <emptyvector>
//
// By owner: <sig>
// By anyone (after 16 conf): <emptyvector>
//
// Output Script:
//
// <funding_pubkey> OP_CHECKSIG OP_IFDUP
// OP_NOTIF
// OP_16 OP_CSV
@ -1348,7 +1371,7 @@ func CommitSpendAnchorAnyone(script []byte) (wire.TxWitness, error) {
// the pay/delay base point. The end end results is that the basePoint is
// tweaked as follows:
//
// * key = basePoint + sha256(commitPoint || basePoint)*G
// - key = basePoint + sha256(commitPoint || basePoint)*G
func SingleTweakBytes(commitPoint, basePoint *btcec.PublicKey) []byte {
h := sha256.New()
h.Write(commitPoint.SerializeCompressed())
@ -1363,15 +1386,15 @@ func SingleTweakBytes(commitPoint, basePoint *btcec.PublicKey) []byte {
// The opposite applies for when tweaking remote keys. Precisely, the following
// operation is used to "tweak" public keys:
//
// tweakPub := basePoint + sha256(commitPoint || basePoint) * G
// := G*k + sha256(commitPoint || basePoint)*G
// := G*(k + sha256(commitPoint || basePoint))
// tweakPub := basePoint + sha256(commitPoint || basePoint) * G
// := G*k + sha256(commitPoint || basePoint)*G
// := G*(k + sha256(commitPoint || basePoint))
//
// Therefore, if a party possess the value k, the private key of the base
// point, then they are able to derive the proper private key for the
// revokeKey by computing:
//
// revokePriv := k + sha256(commitPoint || basePoint) mod N
// revokePriv := k + sha256(commitPoint || basePoint) mod N
//
// Where N is the order of the sub-group.
//
@ -1415,7 +1438,7 @@ func TweakPubKeyWithTweak(pubKey *btcec.PublicKey,
// revoked state. Precisely, the following operation is used to derive a
// tweaked private key:
//
// * tweakPriv := basePriv + sha256(commitment || basePub) mod N
// - tweakPriv := basePriv + sha256(commitment || basePub) mod N
//
// Where N is the order of the sub-group.
func TweakPrivKey(basePriv *btcec.PrivateKey,
@ -1436,24 +1459,24 @@ func TweakPrivKey(basePriv *btcec.PrivateKey,
// revoked commitment transaction, then if the other party knows the revocation
// preimage, then they'll be able to derive the corresponding private key to
// this private key by exploiting the homomorphism in the elliptic curve group:
// * https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups
// - https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups
//
// The derivation is performed as follows:
//
// revokeKey := revokeBase * sha256(revocationBase || commitPoint) +
// commitPoint * sha256(commitPoint || revocationBase)
// revokeKey := revokeBase * sha256(revocationBase || commitPoint) +
// commitPoint * sha256(commitPoint || revocationBase)
//
// := G*(revokeBasePriv * sha256(revocationBase || commitPoint)) +
// G*(commitSecret * sha256(commitPoint || revocationBase))
// := G*(revokeBasePriv * sha256(revocationBase || commitPoint)) +
// G*(commitSecret * sha256(commitPoint || revocationBase))
//
// := G*(revokeBasePriv * sha256(revocationBase || commitPoint) +
// commitSecret * sha256(commitPoint || revocationBase))
// := G*(revokeBasePriv * sha256(revocationBase || commitPoint) +
// commitSecret * sha256(commitPoint || revocationBase))
//
// Therefore, once we divulge the revocation secret, the remote peer is able to
// compute the proper private key for the revokeKey by computing:
//
// revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
// (commitSecret * sha256(commitPoint || revocationBase)) mod N
// revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
// (commitSecret * sha256(commitPoint || revocationBase)) mod N
//
// Where N is the order of the sub-group.
func DeriveRevocationPubkey(revokeBase,
@ -1505,8 +1528,9 @@ func DeriveRevocationPubkey(revokeBase,
// a previously revoked commitment transaction.
//
// The private key is derived as follows:
// revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
// (commitSecret * sha256(commitPoint || revocationBase)) mod N
//
// revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
// (commitSecret * sha256(commitPoint || revocationBase)) mod N
//
// Where N is the order of the sub-group.
func DeriveRevocationPrivKey(revokeBasePriv *btcec.PrivateKey,

View File

@ -159,14 +159,14 @@ func makeWitnessTestCase(t *testing.T,
//
// The following cases are exercised by this test:
// sender script:
// * receiver spends
// * revoke w/ sig
// * HTLC with invalid preimage size
// * HTLC with valid preimage size + sig
// * sender spends
// * invalid lock-time for CLTV
// * invalid sequence for CSV
// * valid lock-time+sequence, valid sig
// - receiver spends
// - revoke w/ sig
// - HTLC with invalid preimage size
// - HTLC with valid preimage size + sig
// - sender spends
// - invalid lock-time for CLTV
// - invalid sequence for CSV
// - valid lock-time+sequence, valid sig
func TestHTLCSenderSpendValidation(t *testing.T) {
t.Parallel()
@ -559,14 +559,14 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
// incoming HTLC.
//
// The following cases are exercised by this test:
// * receiver spends
// * HTLC redemption w/ invalid preimage size
// * HTLC redemption w/ invalid sequence
// * HTLC redemption w/ valid preimage size
// * sender spends
// * revoke w/ sig
// * refund w/ invalid lock time
// * refund w/ valid lock time
// - receiver spends
// 1. HTLC redemption w/ invalid preimage size
// 2. HTLC redemption w/ invalid sequence
// 3. HTLC redemption w/ valid preimage size
// - sender spends
// 1. revoke w/ sig
// 2. refund w/ invalid lock time
// 3. refund w/ valid lock time
func TestHTLCReceiverSpendValidation(t *testing.T) {
t.Parallel()

View File

@ -383,7 +383,7 @@ func (b *BtcWalletKeyRing) DerivePrivKey(keyDesc KeyDescriptor) (
// k is our private key, and P is the public key, we perform the following
// operation:
//
// sx := k*P s := sha256(sx.SerializeCompressed())
// sx := k*P s := sha256(sx.SerializeCompressed())
//
// NOTE: This is part of the keychain.ECDHRing interface.
func (b *BtcWalletKeyRing) ECDH(keyDesc KeyDescriptor,

View File

@ -63,7 +63,7 @@ var (
// The key derivation in this file follows the following hierarchy based on
// BIP43:
//
// * m/1017'/coinType'/keyFamily'/0/index
// - m/1017'/coinType'/keyFamily'/0/index
type KeyFamily uint32
const (
@ -143,7 +143,7 @@ var VersionZeroKeyFamilies = []KeyFamily{
// Version 0 of our key derivation schema uses the following BIP43-like
// derivation:
//
// * m/1017'/coinType'/keyFamily'/0/index
// - m/1017'/coinType'/keyFamily'/0/index
//
// Our purpose is 1017 (chosen arbitrary for now), and the coin type will vary
// based on which coin/chain the channels are being created on. The key family

View File

@ -37,8 +37,8 @@ func (p *PubKeyECDH) PubKey() *btcec.PublicKey {
// k is our private key, and P is the public key, we perform the following
// operation:
//
// sx := k*P
// s := sha256(sx.SerializeCompressed())
// sx := k*P
// s := sha256(sx.SerializeCompressed())
//
// NOTE: This is part of the SingleKeyECDH interface.
func (p *PubKeyECDH) ECDH(pubKey *btcec.PublicKey) ([32]byte, error) {
@ -67,8 +67,8 @@ func (p *PrivKeyECDH) PubKey() *btcec.PublicKey {
// k is our private key, and P is the public key, we perform the following
// operation:
//
// sx := k*P
// s := sha256(sx.SerializeCompressed())
// sx := k*P
// s := sha256(sx.SerializeCompressed())
//
// NOTE: This is part of the SingleKeyECDH interface.
func (p *PrivKeyECDH) ECDH(pub *btcec.PublicKey) ([32]byte, error) {

View File

@ -4,14 +4,14 @@
//
// Labels for transactions broadcast by lnd have two set fields followed by an
// optional set labelled data values, all separated by colons.
// - Label version: an integer that indicates the version lnd used
// - Label type: the type of transaction we are labelling
// - {field name}-{value}: a named field followed by its value, these items are
// optional, and there may be more than field present.
// - Label version: an integer that indicates the version lnd used
// - Label type: the type of transaction we are labelling
// - {field name}-{value}: a named field followed by its value, these items are
// optional, and there may be more than field present.
//
// For version 0 we have the following optional data fields defined:
// - shortchanid: the short channel ID that a transaction is associated with,
// with its value set to the uint64 short channel id.
// - shortchanid: the short channel ID that a transaction is associated with,
// with its value set to the uint64 short channel id.
package labels
import (

View File

@ -150,10 +150,11 @@ func IsUnix(addr net.Addr) bool {
}
// IsPrivate returns true if the address is private. The definitions are,
// https://en.wikipedia.org/wiki/Link-local_address
// https://en.wikipedia.org/wiki/Multicast_address
// Local IPv4 addresses, https://tools.ietf.org/html/rfc1918
// Local IPv6 addresses, https://tools.ietf.org/html/rfc4193
//
// https://en.wikipedia.org/wiki/Link-local_address
// https://en.wikipedia.org/wiki/Multicast_address
// Local IPv4 addresses, https://tools.ietf.org/html/rfc1918
// Local IPv6 addresses, https://tools.ietf.org/html/rfc4193
func IsPrivate(addr net.Addr) bool {
switch addr := addr.(type) {
case *net.TCPAddr:

View File

@ -676,10 +676,10 @@ func newSelectHopHintsCfg(invoicesCfg *AddInvoiceConfig) *SelectHopHintsCfg {
// sufficientHints checks whether we have sufficient hop hints, based on the
// following criteria:
// - Hop hint count: limit to a set number of hop hints, regardless of whether
// we've reached our invoice amount or not.
// - Total incoming capacity: limit to our invoice amount * scaling factor to
// allow for some of our links going offline.
// - Hop hint count: limit to a set number of hop hints, regardless of whether
// we've reached our invoice amount or not.
// - Total incoming capacity: limit to our invoice amount * scaling factor to
// allow for some of our links going offline.
//
// We limit our number of hop hints like this to keep our invoice size down,
// and to avoid leaking all our private channels when we don't need to.

View File

@ -8,16 +8,13 @@ import (
"errors"
"fmt"
"google.golang.org/grpc"
"gopkg.in/macaroon-bakery.v2/bakery"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/lightningnetwork/lnd/lnrpc"
"google.golang.org/grpc"
"gopkg.in/macaroon-bakery.v2/bakery"
)
const (

View File

@ -288,17 +288,18 @@ func (cfg *BaseNodeConfig) GenArgs() []string {
// policyUpdateMap defines a type to store channel policy updates. It has the
// format,
// {
// "chanPoint1": {
// "advertisingNode1": [
// policy1, policy2, ...
// ],
// "advertisingNode2": [
// policy1, policy2, ...
// ]
// },
// "chanPoint2": ...
// }.
//
// {
// "chanPoint1": {
// "advertisingNode1": [
// policy1, policy2, ...
// ],
// "advertisingNode2": [
// policy1, policy2, ...
// ]
// },
// "chanPoint2": ...
// }.
type policyUpdateMap map[string]map[string][]*lnrpc.RoutingPolicy
// HarnessNode represents an instance of lnd running within our test network

View File

@ -25,8 +25,9 @@ import (
// testCommitmentTransactionDeadline tests that the anchor sweep transaction is
// taking account of the deadline of the commitment transaction. It tests two
// scenarios:
// 1) when the CPFP is skipped, checks that the deadline is not used.
// 2) when the CPFP is used, checks that the deadline is applied.
// 1. when the CPFP is skipped, checks that the deadline is not used.
// 2. when the CPFP is used, checks that the deadline is applied.
//
// Note that whether the deadline is used or not is implicitly checked by its
// corresponding fee rates.
func testCommitmentTransactionDeadline(net *lntest.NetworkHarness,

View File

@ -199,11 +199,11 @@ func testForwardInterceptorDedupHtlc(net *lntest.NetworkHarness, t *harnessTest)
// Alice sends 4 different payments to Carol while the interceptor handles
// differently the htlcs.
// The test ensures that:
// 1. Intercepted failed htlcs result in no payment (invoice is not settled).
// 2. Intercepted resumed htlcs result in a payment (invoice is settled).
// 3. Intercepted held htlcs result in no payment (invoice is not settled).
// 4. When Interceptor disconnects it resumes all held htlcs, which result in
// valid payment (invoice is settled).
// 1. Intercepted failed htlcs result in no payment (invoice is not settled).
// 2. Intercepted resumed htlcs result in a payment (invoice is settled).
// 3. Intercepted held htlcs result in no payment (invoice is not settled).
// 4. When Interceptor disconnects it resumes all held htlcs, which result in
// valid payment (invoice is settled).
func testForwardInterceptorBasic(net *lntest.NetworkHarness, t *harnessTest) {
// Initialize the test context with 3 connected nodes.
alice := net.NewNode(t.t, "alice", nil)

View File

@ -61,7 +61,9 @@ var singleHopSendToRouteCases = []singleHopSendToRouteCase{
// testSingleHopSendToRoute tests that payments are properly processed through a
// provided route with a single hop. We'll create the following network
// topology:
// Carol --100k--> Dave
//
// Carol --100k--> Dave
//
// We'll query the daemon for routes from Carol to Dave and then send payments
// by feeding the route back into the various SendToRoute RPC methods. Here we
// test all three SendToRoute endpoints, forcing each to perform both a regular
@ -428,7 +430,9 @@ func testSingleHopSendToRouteCase(net *lntest.NetworkHarness, t *harnessTest,
// testMultiHopSendToRoute tests that payments are properly processed
// through a provided route. We'll create the following network topology:
// Alice --100k--> Bob --100k--> Carol
//
// Alice --100k--> Bob --100k--> Carol
//
// We'll query the daemon for routes from Alice to Carol and then
// send payments through the routes.
func testMultiHopSendToRoute(net *lntest.NetworkHarness, t *harnessTest) {
@ -446,7 +450,9 @@ func testMultiHopSendToRoute(net *lntest.NetworkHarness, t *harnessTest) {
// runMultiHopSendToRoute tests that payments are properly processed
// through a provided route. We'll create the following network topology:
// Alice --100k--> Bob --100k--> Carol
//
// Alice --100k--> Bob --100k--> Carol
//
// We'll query the daemon for routes from Alice to Carol and then
// send payments through the routes.
func runMultiHopSendToRoute(net *lntest.NetworkHarness, t *harnessTest,
@ -1429,7 +1435,9 @@ func computeFee(baseFee, feeRate, amt lnwire.MilliSatoshi) lnwire.MilliSatoshi {
// testQueryRoutes checks the response of queryroutes.
// We'll create the following network topology:
// Alice --> Bob --> Carol --> Dave
//
// Alice --> Bob --> Carol --> Dave
//
// and query the daemon for routes from Alice to Dave.
func testQueryRoutes(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background()

View File

@ -18,9 +18,9 @@ import (
// forward a response back from the receiver once back online.
//
// The general flow of this test:
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. X X X Bob restart sender and intermediaries
// 3. Carol <-- Dave <-- Alice <-- Bob expect settle to propagate
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. X X X Bob restart sender and intermediaries
// 3. Carol <-- Dave <-- Alice <-- Bob expect settle to propagate
func testSwitchCircuitPersistence(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background()
@ -291,10 +291,10 @@ func testSwitchCircuitPersistence(net *lntest.NetworkHarness, t *harnessTest) {
// online.
//
// The general flow of this test:
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol <-- Dave <-- Alice --- Bob reconnect, expect settle to propagate
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol <-- Dave <-- Alice --- Bob reconnect, expect settle to propagate
func testSwitchOfflineDelivery(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background()
@ -608,11 +608,11 @@ func testSwitchOfflineDelivery(net *lntest.NetworkHarness, t *harnessTest) {
// disk, and transmitted as soon as the intermediaries are reconnected.
//
// The general flow of this test:
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol --- Dave X X Bob restart Alice
// 5. Carol <-- Dave <-- Alice --- Bob expect settle to propagate
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol --- Dave X X Bob restart Alice
// 5. Carol <-- Dave <-- Alice --- Bob expect settle to propagate
func testSwitchOfflineDeliveryPersistence(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background()
@ -895,11 +895,11 @@ func testSwitchOfflineDeliveryPersistence(net *lntest.NetworkHarness, t *harness
// disk, and transmitted as soon as the intermediaries are reconnected.
//
// The general flow of this test:
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol --- Dave X X shutdown Bob, restart Alice
// 5. Carol <-- Dave <-- Alice X expect settle to propagate
// 1. Carol --> Dave --> Alice --> Bob forward payment
// 2. Carol --- Dave X Alice --- Bob disconnect intermediaries
// 3. Carol --- Dave X Alice <-- Bob settle last hop
// 4. Carol --- Dave X X shutdown Bob, restart Alice
// 5. Carol <-- Dave <-- Alice X expect settle to propagate
func testSwitchOfflineDeliveryOutgoingOffline(
net *lntest.NetworkHarness, t *harnessTest) {

View File

@ -19,11 +19,11 @@ type pendingChan *lnrpc.PendingChannelsResponse_PendingChannel
// packages of that particular channel are deleted. The test creates a
// topology as Alice -> Bob -> Carol, and sends payments from Alice to Carol
// through Bob. It then performs the test in two steps,
// - Bob force closes the channel Alice->Bob, and checks from both Bob's
// PoV(local force close) and Alice's Pov(remote close) that the forwarding
// packages are wiped.
// - Bob coop closes the channel Bob->Carol, and checks from both Bob PoVs that
// the forwarding packages are wiped.
// - Bob force closes the channel Alice->Bob, and checks from both Bob's
// PoV(local force close) and Alice's Pov(remote close) that the forwarding
// packages are wiped.
// - Bob coop closes the channel Bob->Carol, and checks from both Bob PoVs that
// the forwarding packages are wiped.
func testWipeForwardingPackages(net *lntest.NetworkHarness,
t *harnessTest) {

View File

@ -229,7 +229,7 @@ func (u updateType) String() string {
// the original added HTLC.
//
// TODO(roasbeef): LogEntry interface??
// * need to separate attrs for cancel/add/settle/feeupdate
// - need to separate attrs for cancel/add/settle/feeupdate
type PaymentDescriptor struct {
// RHash is the payment hash for this HTLC. The HTLC can be settled iff
// the preimage to this hash is presented.
@ -1038,8 +1038,8 @@ func (s *commitmentChain) hasUnackedCommitment() bool {
//
// TODO(roasbeef): create lightning package, move commitment and update to
// package?
// * also move state machine, separate from lnwallet package
// * possible embed updateLog within commitmentChain.
// - also move state machine, separate from lnwallet package
// - possible embed updateLog within commitmentChain.
type updateLog struct {
// logIndex is a monotonically increasing integer that tracks the total
// number of update entries ever applied to the log. When sending new
@ -1235,18 +1235,18 @@ func compactLogs(ourLog, theirLog *updateLog,
// preimages in order to populate their revocation window for the remote party.
//
// 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
// - .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.
@ -3844,10 +3844,10 @@ func (lc *LightningChannel) SignNextCommitment() (lnwire.Sig, []lnwire.Sig,
//
// One of two message sets will be returned:
//
// * CommitSig+Updates: if we have a pending remote commit which they claim to
// have not received
// * RevokeAndAck: if we sent a revocation message that they claim to have
// not received
// - CommitSig+Updates: if we have a pending remote commit which they claim to
// have not received
// - RevokeAndAck: if we sent a revocation message that they claim to have
// not received
//
// If we detect a scenario where we need to send a CommitSig+Updates, this
// method also returns two sets channeldb.CircuitKeys identifying the circuits
@ -4836,14 +4836,14 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, []c
// commitment, and a log compaction is attempted.
//
// The returned values correspond to:
// 1. The forwarding package corresponding to the remote commitment height
// that was revoked.
// 2. The PaymentDescriptor of any Add HTLCs that were locked in by this
// revocation.
// 3. The PaymentDescriptor of any Settle/Fail HTLCs that were locked in by
// this revocation.
// 4. The set of HTLCs present on the current valid commitment transaction
// for the remote party.
// 1. The forwarding package corresponding to the remote commitment height
// that was revoked.
// 2. The PaymentDescriptor of any Add HTLCs that were locked in by this
// revocation.
// 3. The PaymentDescriptor of any Settle/Fail HTLCs that were locked in by
// this revocation.
// 4. The set of HTLCs present on the current valid commitment transaction
// for the remote party.
func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) (
*channeldb.FwdPkg, []*PaymentDescriptor, []*PaymentDescriptor,
[]channeldb.HTLC, error) {
@ -5377,20 +5377,21 @@ func (lc *LightningChannel) ReceiveHTLC(htlc *lnwire.UpdateAddHTLC) (uint64, err
// is invalid, an error is returned.
//
// The additional arguments correspond to:
// * sourceRef: specifies the location of the Add HTLC within a forwarding
// package that this HTLC is settling. Every Settle fails exactly one Add,
// so this should never be empty in practice.
//
// * destRef: specifies the location of the Settle HTLC within another
// channel's forwarding package. This value can be nil if the corresponding
// Add HTLC was never locked into an outgoing commitment txn, or this
// HTLC does not originate as a response from the peer on the outgoing
// link, e.g. on-chain resolutions.
// - sourceRef: specifies the location of the Add HTLC within a forwarding
// package that this HTLC is settling. Every Settle fails exactly one Add,
// so this should never be empty in practice.
//
// * closeKey: identifies the circuit that should be deleted after this Settle
// HTLC is included in a commitment txn. This value should only be nil if
// the HTLC was settled locally before committing a circuit to the circuit
// map.
// - destRef: specifies the location of the Settle HTLC within another
// channel's forwarding package. This value can be nil if the corresponding
// Add HTLC was never locked into an outgoing commitment txn, or this
// HTLC does not originate as a response from the peer on the outgoing
// link, e.g. on-chain resolutions.
//
// - closeKey: identifies the circuit that should be deleted after this Settle
// HTLC is included in a commitment txn. This value should only be nil if
// the HTLC was settled locally before committing a circuit to the circuit
// map.
//
// NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit
// testing the wallet.
@ -5487,20 +5488,21 @@ func (lc *LightningChannel) ReceiveHTLCSettle(preimage [32]byte, htlcIndex uint6
// _incoming_ HTLC.
//
// The additional arguments correspond to:
// * sourceRef: specifies the location of the Add HTLC within a forwarding
// package that this HTLC is failing. Every Fail fails exactly one Add, so
// this should never be empty in practice.
//
// * destRef: specifies the location of the Fail HTLC within another channel's
// forwarding package. This value can be nil if the corresponding Add HTLC
// was never locked into an outgoing commitment txn, or this HTLC does not
// originate as a response from the peer on the outgoing link, e.g.
// on-chain resolutions.
// - sourceRef: specifies the location of the Add HTLC within a forwarding
// package that this HTLC is failing. Every Fail fails exactly one Add, so
// this should never be empty in practice.
//
// * closeKey: identifies the circuit that should be deleted after this Fail
// HTLC is included in a commitment txn. This value should only be nil if
// the HTLC was failed locally before committing a circuit to the circuit
// map.
// - destRef: specifies the location of the Fail HTLC within another channel's
// forwarding package. This value can be nil if the corresponding Add HTLC
// was never locked into an outgoing commitment txn, or this HTLC does not
// originate as a response from the peer on the outgoing link, e.g.
// on-chain resolutions.
//
// - closeKey: identifies the circuit that should be deleted after this Fail
// HTLC is included in a commitment txn. This value should only be nil if
// the HTLC was failed locally before committing a circuit to the circuit
// map.
//
// NOTE: It is okay for sourceRef, destRef, and closeKey to be nil when unit
// testing the wallet.

View File

@ -316,8 +316,8 @@ func testAddSettleWorkflow(t *testing.T, tweakless bool) {
//
// TODO(roasbeef): write higher level framework to exercise various states of
// the state machine
// * DSL language perhaps?
// * constructed via input/output files
// - DSL language perhaps?
// - constructed via input/output files
func TestSimpleAddSettleWorkflow(t *testing.T) {
t.Parallel()
@ -335,17 +335,18 @@ func TestSimpleAddSettleWorkflow(t *testing.T) {
// The full state transition of this test is:
//
// Alice Bob
// -----add------>
// -----sig------>
// <----rev-------
// <----sig-------
// -----rev------>
// <---settle-----
// <----sig-------
// -----rev------>
// *alice dies*
// <----add-------
// x----sig-------
//
// -----add------>
// -----sig------>
// <----rev-------
// <----sig-------
// -----rev------>
// <---settle-----
// <----sig-------
// -----rev------>
// *alice dies*
// <----add-------
// x----sig-------
//
// The last sig will be rejected if addCommitHeightLocal is not set for the
// initial add that Alice sent. This test checks that this behavior does
@ -5804,7 +5805,9 @@ func TestMaxAcceptedHTLCs(t *testing.T) {
// fail) an HTLC from Alice when exchanging asynchronous payments. We want to
// mimic the following case where Bob's commitment transaction is full before
// starting:
// Alice Bob
//
// Alice Bob
//
// 1. <---settle/fail---
// 2. <-------sig-------
// 3. --------sig------> (covers an add sent before step 1)
@ -8799,20 +8802,21 @@ func TestProcessAddRemoveEntry(t *testing.T) {
// The full state transition of this test is:
//
// Alice Bob
// -----add----->
// -----sig----->
// <----rev------
// <----sig------
// -----rev----->
// <----fail-----
// <----sig------
// -----rev----->
// -----sig-----X (does not reach Bob! Alice dies!)
//
// -----sig----->
// <----rev------
// <----add------
// <----sig------
// -----add----->
// -----sig----->
// <----rev------
// <----sig------
// -----rev----->
// <----fail-----
// <----sig------
// -----rev----->
// -----sig-----X (does not reach Bob! Alice dies!)
//
// -----sig----->
// <----rev------
// <----add------
// <----sig------
//
// The last sig was rejected with the old behavior of deleting unsigned
// acked updates from the database after signing for them. The current
@ -8915,16 +8919,17 @@ func TestChannelUnsignedAckedFailure(t *testing.T) {
// The full state transition is:
//
// Alice Bob
// <----add-----
// <----sig-----
// -----rev---->
// -----sig---->
// <----rev-----
// ----fail---->
// -----sig---->
// <----rev-----
// *reconnect*
// <----sig-----
//
// <----add-----
// <----sig-----
// -----rev---->
// -----sig---->
// <----rev-----
// ----fail---->
// -----sig---->
// <----rev-----
// *reconnect*
// <----sig-----
//
// Alice should reject the last signature since the settle is not restored
// into the local update log and thus calculates Bob's signature as invalid.
@ -9000,22 +9005,22 @@ func TestChannelLocalUnsignedUpdatesFailure(t *testing.T) {
// The full state transition of this test is:
//
// Alice Bob
// <----add-------
// <----sig-------
// -----rev------>
// -----sig------>
// <----rev-------
// ----settle---->
// -----sig------>
// <----rev-------
// <----sig-------
// -----add------>
// -----sig------>
// <----rev-------
// *restarts*
// -----rev------>
// <----sig-------
//
// <----add-------
// <----sig-------
// -----rev------>
// -----sig------>
// <----rev-------
// ----settle---->
// -----sig------>
// <----rev-------
// <----sig-------
// -----add------>
// -----sig------>
// <----rev-------
// *restarts*
// -----rev------>
// <----sig-------
func TestChannelSignedAckRegression(t *testing.T) {
t.Parallel()

View File

@ -137,25 +137,25 @@ func (c *ChannelContribution) toChanConfig() channeldb.ChannelConfig {
// The reservation workflow consists of the following three steps:
// 1. lnwallet.InitChannelReservation
// * One requests the wallet to allocate the necessary resources for a
// channel reservation. These resources are put in limbo for the lifetime
// of a reservation.
// channel reservation. These resources are 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 necessary items to allow the remote party to build both
// the funding, and commitment transactions.
// accessible via the .OurContribution() method. This contribution
// contains the necessary 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.
// 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.
// 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 transaction, as well
// as a signature to our version of the commitment transaction.
// signatures for all their inputs to the funding transaction, 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".
// channel "open".
type ChannelReservation struct {
// This mutex MUST be held when either reading or modifying any of the
// fields below.

View File

@ -383,8 +383,8 @@ func (r *RPCKeyRing) DeriveKey(
// sha256 of the resulting shared point serialized in compressed format. If k is
// our private key, and P is the public key, we perform the following operation:
//
// sx := k*P
// s := sha256(sx.SerializeCompressed())
// sx := k*P
// s := sha256(sx.SerializeCompressed())
//
// NOTE: This method is part of the keychain.ECDHRing interface.
func (r *RPCKeyRing) ECDH(keyDesc keychain.KeyDescriptor,

View File

@ -43,7 +43,7 @@ var (
//
// In order to spend the HTLC output, the witness for the passed transaction
// should be:
// * <0> <sender sig> <recvr sig> <preimage>
// - <0> <sender sig> <recvr sig> <preimage>
func CreateHtlcSuccessTx(chanType channeldb.ChannelType, initiator bool,
htlcOutput wire.OutPoint, htlcAmt btcutil.Amount, csvDelay,
leaseExpiry uint32, revocationKey, delayKey *btcec.PublicKey) (

View File

@ -711,10 +711,10 @@ func testSpendValidation(t *testing.T, tweakless bool) {
// the commitment transaction.
//
// The following spending cases are covered by this test:
// * Alice's spend from the delayed output on her commitment transaction.
// * Bob's spend from Alice's delayed output when she broadcasts a revoked
// - Alice's spend from the delayed output on her commitment transaction.
// - Bob's spend from Alice's delayed output when she broadcasts a revoked
// commitment transaction.
// * Bob's spend from his unencumbered output within Alice's commitment
// - Bob's spend from his unencumbered output within Alice's commitment
// transaction.
func TestCommitmentSpendValidation(t *testing.T) {
t.Parallel()

View File

@ -160,7 +160,6 @@ var _ Message = (*OpenChannel)(nil)
// Encode serializes the target OpenChannel into the passed io.Writer
// implementation. Serialization will observe the rules defined by the passed
// protocol version.
//
func (o *OpenChannel) Encode(w *bytes.Buffer, pver uint32) error {
recordProducers := []tlv.RecordProducer{&o.UpfrontShutdownScript}
if o.ChannelType != nil {

View File

@ -250,8 +250,9 @@ func (svc *Service) CreateUnlock(password *[]byte) error {
}
// NewMacaroon wraps around the function Oven.NewMacaroon with the defaults,
// - version is always bakery.LatestVersion;
// - caveats is always nil.
// - version is always bakery.LatestVersion;
// - caveats is always nil.
//
// In addition, it takes a rootKeyID parameter, and puts it into the context.
// The context is passed through Oven.NewMacaroon(), in which calls the function
// RootKey(), that reads the context for rootKeyID.

View File

@ -24,6 +24,7 @@ var lndStarted int32
//
// extraArgs can be used to pass command line arguments to lnd that will
// override what is found in the config file. Example:
//
// extraArgs = "--bitcoin.testnet --lnddir=\"/tmp/folder name/\" --profile=5050"
//
// The rpcReady is called lnd is ready to accept RPC calls.

View File

@ -133,7 +133,8 @@ type ChanStatusManager struct {
// NewChanStatusManager initializes a new ChanStatusManager using the given
// configuration. An error is returned if the timeouts and sample interval fail
// to meet do not satisfy the equation:
// ChanEnableTimeout + ChanStatusSampleInterval > ChanDisableTimeout.
//
// ChanEnableTimeout + ChanStatusSampleInterval > ChanDisableTimeout.
func NewChanStatusManager(cfg *ChanStatusConfig) (*ChanStatusManager, error) {
// Assert that the config timeouts are properly formed. We require the
// enable_timeout + sample_interval to be less than or equal to the
@ -260,16 +261,17 @@ func (m *ChanStatusManager) RequestEnable(outpoint wire.OutPoint,
// ChanStatusManuallyDisabled, depending on the passed-in value of manual. In
// particular, note the following state transitions:
//
// current state | manual | new state
// ---------------------------------------------------
// Disabled | false | Disabled
// ManuallyDisabled | false | ManuallyDisabled (*)
// Disabled | true | ManuallyDisabled
// ManuallyDisabled | true | ManuallyDisabled
// current state | manual | new state
// ---------------------------------------------------
// Disabled | false | Disabled
// ManuallyDisabled | false | ManuallyDisabled (*)
// Disabled | true | ManuallyDisabled
// ManuallyDisabled | true | ManuallyDisabled
//
// (*) If a channel was manually disabled, subsequent automatic / background
// requests to disable the channel do not change the fact that the channel
// was manually disabled.
//
// requests to disable the channel do not change the fact that the channel
// was manually disabled.
func (m *ChanStatusManager) RequestDisable(outpoint wire.OutPoint,
manual bool) error {
@ -367,13 +369,13 @@ func (m *ChanStatusManager) statusManager() {
// processEnableRequest attempts to enable the given outpoint.
//
// * If the channel is not active at the time of the request,
// ErrEnableInactiveChan will be returned.
// * If the channel was in the ManuallyDisabled state and manual = false,
// the request will be ignored and ErrEnableManuallyDisabledChan will be
// returned.
// * Otherwise, the status of the channel in chanStates will be
// ChanStatusEnabled and the method will return nil.
// - If the channel is not active at the time of the request,
// ErrEnableInactiveChan will be returned.
// - If the channel was in the ManuallyDisabled state and manual = false,
// the request will be ignored and ErrEnableManuallyDisabledChan will be
// returned.
// - Otherwise, the status of the channel in chanStates will be
// ChanStatusEnabled and the method will return nil.
//
// An update will be broadcast only if the channel is currently disabled,
// otherwise no update will be sent on the network.

View File

@ -105,35 +105,35 @@ var (
// client with a macaroon that contains a custom caveat that is supported by one
// of the registered middlewares.
//
// |
// | gRPC request from client
// |
// +---v--------------------------------+
// | InterceptorChain |
// +-+----------------------------------+
// | Log Interceptor |
// +----------------------------------+
// | RPC State Interceptor |
// +----------------------------------+
// | Macaroon Interceptor |
// +----------------------------------+--------> +---------------------+
// | RPC Macaroon Middleware Handler |<-------- | External Middleware |
// +----------------------------------+ | - modify request |
// | Prometheus Interceptor | +---------------------+
// +-+--------------------------------+
// | validated gRPC request from client
// +---v--------------------------------+
// | main gRPC server |
// +---+--------------------------------+
// |
// | original gRPC request to client
// |
// +---v--------------------------------+--------> +---------------------+
// | RPC Macaroon Middleware Handler |<-------- | External Middleware |
// +---+--------------------------------+ | - modify response |
// | +---------------------+
// | edited gRPC request to client
// v
// |
// | gRPC request from client
// |
// +---v--------------------------------+
// | InterceptorChain |
// +-+----------------------------------+
// | Log Interceptor |
// +----------------------------------+
// | RPC State Interceptor |
// +----------------------------------+
// | Macaroon Interceptor |
// +----------------------------------+--------> +---------------------+
// | RPC Macaroon Middleware Handler |<-------- | External Middleware |
// +----------------------------------+ | - modify request |
// | Prometheus Interceptor | +---------------------+
// +-+--------------------------------+
// | validated gRPC request from client
// +---v--------------------------------+
// | main gRPC server |
// +---+--------------------------------+
// |
// | original gRPC request to client
// |
// +---v--------------------------------+--------> +---------------------+
// | RPC Macaroon Middleware Handler |<-------- | External Middleware |
// +---+--------------------------------+ | - modify response |
// | +---------------------+
// | edited gRPC request to client
// v
type InterceptorChain struct {
// lastRequestID is the ID of the last gRPC request or stream that was
// intercepted by the middleware interceptor.

View File

@ -5936,7 +5936,7 @@ func (r *rpcServer) GetNodeInfo(ctx context.Context,
// within the HTLC.
//
// TODO(roasbeef): should return a slice of routes in reality
// * create separate PR to send based on well formatted route
// - create separate PR to send based on well formatted route
func (r *rpcServer) QueryRoutes(ctx context.Context,
in *lnrpc.QueryRoutesRequest) (*lnrpc.QueryRoutesResponse, error) {

View File

@ -111,19 +111,18 @@ func newIndex(v uint64) index {
// 6. 2(0b010) -> 2, 3
// 7. 1(0b001) -> 1
//
// ^ bucket number
// |
// 3 | x
// | |
// 2 | | x
// | | |
// 1 | | x | x
// | | | | |
// 0 | | x | x | x | x
// | | | | | | | | |
// +---|---|---|---|---|---|---|---|---> index
// 0 1 2 3 4 5 6 7
//
// ^ bucket number
// |
// 3 | x
// | |
// 2 | | x
// | | |
// 1 | | x | x
// | | | | |
// 0 | | x | x | x | x
// | | | | | | | | |
// +---|---|---|---|---|---|---|---|---> index
// 0 1 2 3 4 5 6 7
func (from index) deriveBitTransformations(to index) ([]uint8, error) {
var positions []uint8

View File

@ -11,8 +11,9 @@ import (
// bitsToIndex is a helper function which takes 'n' last bits as input and
// create shachain index.
// Example:
// Input: 0,1,1,0,0
// Output: 0b000000000000000000000000000000000000000[01100] == 12
//
// Input: 0,1,1,0,0
// Output: 0b000000000000000000000000000000000000000[01100] == 12
func bitsToIndex(bs ...uint64) (index, error) {
if len(bs) > 64 {
return 0, errors.New("number of elements should be lower then" +

View File

@ -1517,10 +1517,10 @@ func (s *UtxoSweeper) UpdateParams(input wire.OutPoint,
// fee preference to ensure it will properly create a replacement transaction.
//
// TODO(wilmer):
// * Validate fee preference to ensure we'll create a valid replacement
// - Validate fee preference to ensure we'll create a valid replacement
// transaction to allow the new fee rate to propagate throughout the
// network.
// * Ensure we don't combine this input with any other unconfirmed inputs that
// - Ensure we don't combine this input with any other unconfirmed inputs that
// did not exist in the original sweep transaction, resulting in an invalid
// replacement transaction.
func (s *UtxoSweeper) handleUpdateReq(req *updateReq, bestHeight int32) (

View File

@ -7,23 +7,23 @@ import "time"
//
// Example of resuming ticker:
//
// ticker.Resume() // can remove to keep inactive at first
// defer ticker.Stop()
// for {
// select {
// case <-ticker.Tick():
// if shouldGoInactive {
// ticker.Pause()
// continue
// }
// ...
// ticker.Resume() // can remove to keep inactive at first
// defer ticker.Stop()
// for {
// select {
// case <-ticker.Tick():
// if shouldGoInactive {
// ticker.Pause()
// continue
// }
// ...
//
// case <-otherEvent:
// ...
// if shouldGoActive {
// ticker.Resume()
// }
// }
// case <-otherEvent:
// ...
// if shouldGoActive {
// ticker.Resume()
// }
// }
//
// NOTE: ONE DOES NOT SIMPLY assume that Tickers are safe for concurrent access.
type Ticker interface {

View File

@ -75,9 +75,10 @@ func MustNewStream(records ...Record) *Stream {
//
// The stream is constructed by concatenating the individual, serialized Records
// where each record has the following format:
// [varint: type]
// [varint: length]
// [length: value]
//
// [varint: type]
// [varint: length]
// [length: value]
//
// An error is returned if the io.Writer fails to accept bytes from the
// encoding, and nothing else. The ordering of the Records is asserted upon the
@ -117,15 +118,16 @@ func (s *Stream) Encode(w io.Writer) error {
// record.
//
// Each record has the following format:
// [varint: type]
// [varint: length]
// [length: value]
//
// [varint: type]
// [varint: length]
// [length: value]
//
// A series of (possibly zero) records are concatenated into a stream, this
// example contains two records:
//
// (t: 0x01, l: 0x04, v: 0xff, 0xff, 0xff, 0xff)
// (t: 0x02, l: 0x01, v: 0x01)
// (t: 0x01, l: 0x04, v: 0xff, 0xff, 0xff, 0xff)
// (t: 0x02, l: 0x01, v: 0x01)
//
// This method asserts that the byte stream is canonical, namely that each
// record is unique and that all records are sorted in ascending order. An

View File

@ -186,6 +186,7 @@ func (c *Controller) prepareAddOnion(cfg AddOnionConfig) (string, error) {
// - the onion service is removed via `DEL_ONION`.
// - the Tor daemon terminates.
// - the controller connection that originated the `ADD_ONION` is closed.
//
// Each connection can only see its own ephemeral services. If a service needs
// to survive beyond current controller connection, use the "Detach" flag when
// creating new service via `ADD_ONION`.

View File

@ -99,9 +99,9 @@ var (
// proceeding to send commands. Otherwise, the connection will be closed.
//
// TODO:
// * if adding support for more commands, extend this with a command queue?
// * place under sub-package?
// * support async replies from the server
// - if adding support for more commands, extend this with a command queue?
// - place under sub-package?
// - support async replies from the server
type Controller struct {
// started is used atomically in order to prevent multiple calls to
// Start.
@ -269,21 +269,22 @@ func (c *Controller) sendCommand(command string) (int, string, error) {
// readResponse reads the replies from Tor to the controller. The reply has the
// following format,
//
// Reply = SyncReply / AsyncReply
// SyncReply = *(MidReplyLine / DataReplyLine) EndReplyLine
// AsyncReply = *(MidReplyLine / DataReplyLine) EndReplyLine
// Reply = SyncReply / AsyncReply
// SyncReply = *(MidReplyLine / DataReplyLine) EndReplyLine
// AsyncReply = *(MidReplyLine / DataReplyLine) EndReplyLine
//
// MidReplyLine = StatusCode "-" ReplyLine
// DataReplyLine = StatusCode "+" ReplyLine CmdData
// EndReplyLine = StatusCode SP ReplyLine
// ReplyLine = [ReplyText] CRLF
// ReplyText = XXXX
// StatusCode = 3DIGIT
// MidReplyLine = StatusCode "-" ReplyLine
// DataReplyLine = StatusCode "+" ReplyLine CmdData
// EndReplyLine = StatusCode SP ReplyLine
// ReplyLine = [ReplyText] CRLF
// ReplyText = XXXX
// StatusCode = 3DIGIT
//
// Unless specified otherwise, multiple lines in a single reply from Tor daemon
// to the controller are guaranteed to share the same status code. Read more on
// this topic:
// https://gitweb.torproject.org/torspec.git/tree/control-spec.txt#n158
//
// https://gitweb.torproject.org/torspec.git/tree/control-spec.txt#n158
//
// NOTE: this code is influenced by https://github.com/Yawning/bulb.
func (c *Controller) readResponse(expected int) (int, string, error) {
@ -618,6 +619,7 @@ func computeHMAC256(key, message []byte) []byte {
// supportsV3 is a helper function that parses the current version of the Tor
// server and determines whether it supports creating v3 onion services through
// Tor's control port. The version string should be of the format:
//
// major.minor.revision.build
func supportsV3(version string) error {
// We'll split the minimum Tor version that's supported and the given

View File

@ -52,8 +52,9 @@ func (k BreachKey) String() string {
// NewBreachHintAndKeyFromHash derives a BreachHint and BreachKey from a given
// txid in a single pass. The hint and key are computed as:
// hint = SHA256(txid)
// key = SHA256(txid || txid)
//
// hint = SHA256(txid)
// key = SHA256(txid || txid)
func NewBreachHintAndKeyFromHash(hash *chainhash.Hash) (BreachHint, BreachKey) {
var (
hint BreachHint

View File

@ -43,9 +43,10 @@ const (
)
// Size returns the size of the encoded-and-encrypted blob in bytes.
// nonce: 24 bytes
// enciphered plaintext: n bytes
// MAC: 16 bytes
//
// nonce: 24 bytes
// enciphered plaintext: n bytes
// MAC: 16 bytes
func Size(blobType Type) int {
return NonceSize + PlaintextSize(blobType) + CiphertextExpansion
}
@ -173,7 +174,8 @@ func (b *JusticeKit) CommitToLocalWitnessScript() ([]byte, error) {
// CommitToLocalRevokeWitnessStack constructs a witness stack spending the
// revocation clause of the commitment to-local output.
// <revocation-sig> 1
//
// <revocation-sig> 1
func (b *JusticeKit) CommitToLocalRevokeWitnessStack() ([][]byte, error) {
toLocalSig, err := b.CommitToLocalSig.ToSignature()
if err != nil {
@ -220,7 +222,8 @@ func (b *JusticeKit) CommitToRemoteWitnessScript() ([]byte, error) {
// CommitToRemoteWitnessStack returns a witness stack spending the commitment
// to-remote output, which consists of a single signature satisfying either the
// legacy or anchor witness scripts.
// <to-remote-sig>
//
// <to-remote-sig>
func (b *JusticeKit) CommitToRemoteWitnessStack() ([][]byte, error) {
toRemoteSig, err := b.CommitToRemoteSig.ToSignature()
if err != nil {
@ -345,14 +348,15 @@ func (b *JusticeKit) decode(r io.Reader, blobType Type) error {
// constant-size plaintext size of 274 bytes.
//
// blob version 0 plaintext encoding:
// sweep address length: 1 byte
// padded sweep address: 42 bytes
// revocation pubkey: 33 bytes
// local delay pubkey: 33 bytes
// csv delay: 4 bytes
// commit to-local revocation sig: 64 bytes
// commit to-remote pubkey: 33 bytes, maybe blank
// commit to-remote sig: 64 bytes, maybe blank
//
// sweep address length: 1 byte
// padded sweep address: 42 bytes
// revocation pubkey: 33 bytes
// local delay pubkey: 33 bytes
// csv delay: 4 bytes
// commit to-local revocation sig: 64 bytes
// commit to-remote pubkey: 33 bytes, maybe blank
// commit to-remote sig: 64 bytes, maybe blank
func (b *JusticeKit) encodeV0(w io.Writer) error {
// Assert the sweep address length is sane.
if len(b.SweepAddress) > MaxSweepAddrSize {
@ -416,14 +420,15 @@ func (b *JusticeKit) encodeV0(w io.Writer) error {
// to-remote output.
//
// blob version 0 plaintext encoding:
// sweep address length: 1 byte
// padded sweep address: 42 bytes
// revocation pubkey: 33 bytes
// local delay pubkey: 33 bytes
// csv delay: 4 bytes
// commit to-local revocation sig: 64 bytes
// commit to-remote pubkey: 33 bytes, maybe blank
// commit to-remote sig: 64 bytes, maybe blank
//
// sweep address length: 1 byte
// padded sweep address: 42 bytes
// revocation pubkey: 33 bytes
// local delay pubkey: 33 bytes
// csv delay: 4 bytes
// commit to-local revocation sig: 64 bytes
// commit to-remote pubkey: 33 bytes, maybe blank
// commit to-remote sig: 64 bytes, maybe blank
func (b *JusticeKit) decodeV0(r io.Reader) error {
// Read the sweep address length as a single byte.
var sweepAddrLen uint8

View File

@ -603,11 +603,11 @@ func (c *TowerClient) RegisterChannel(chanID lnwire.ChannelID) error {
// BackupState initiates a request to back up a particular revoked state. If the
// method returns nil, the backup is guaranteed to be successful unless the:
// - client is force quit,
// - justice transaction would create dust outputs when trying to abide by the
// negotiated policy, or
// - breached outputs contain too little value to sweep at the target sweep fee
// rate.
// - client is force quit,
// - justice transaction would create dust outputs when trying to abide by the
// negotiated policy, or
// - breached outputs contain too little value to sweep at the target sweep fee
// rate.
func (c *TowerClient) BackupState(chanID *lnwire.ChannelID,
breachInfo *lnwallet.BreachRetribution,
chanType channeldb.ChannelType) error {

View File

@ -57,8 +57,8 @@ func (m *SecretKeyRing) DeriveKey(
// sha256 of the resulting shared point serialized in compressed format. If k is
// our private key, and P is the public key, we perform the following operation:
//
// sx := k*P
// s := sha256(sx.SerializeCompressed())
// sx := k*P
// s := sha256(sx.SerializeCompressed())
//
// NOTE: This is part of the wtclient.ECDHKeyRing interface.
func (m *SecretKeyRing) ECDH(keyDesc keychain.KeyDescriptor,

View File

@ -203,8 +203,8 @@ func (s *Server) peerHandler() {
// handleClient processes a series watchtower messages sent by a client. The
// client may either send:
// * a single CreateSession message.
// * a series of StateUpdate messages.
// - a single CreateSession message.
// - a series of StateUpdate messages.
//
// This method uses the server's peer map to ensure at most one peer using the
// same session id can enter the main event loop. The connection will be