Skip to content

Commit

Permalink
Merge 7023352 into eae45f9
Browse files Browse the repository at this point in the history
  • Loading branch information
joostjager committed Dec 14, 2019
2 parents eae45f9 + 7023352 commit 8bd26f3
Show file tree
Hide file tree
Showing 15 changed files with 1,054 additions and 760 deletions.
3 changes: 2 additions & 1 deletion channeldb/invoices.go
Expand Up @@ -222,7 +222,8 @@ type Invoice struct {
Memo []byte

// PaymentRequest is an optional field where a payment request created
// for this invoice can be stored.
// for this invoice can be stored. For spontaneous (key send) payments,
// this field will be empty.
PaymentRequest []byte

// CreationDate is the exact time the invoice was created.
Expand Down
71 changes: 41 additions & 30 deletions cmd/lncli/commands.go
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
Expand All @@ -24,6 +25,8 @@ import (
"github.com/golang/protobuf/proto"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/record"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/walletunlocker"
"github.com/urfave/cli"
Expand Down Expand Up @@ -2174,12 +2177,6 @@ var sendPaymentCommand = cli.Command{
* --amt=A
* --final_cltv_delta=T
* --payment_hash=H
The --debug_send flag is provided for usage *purely* in test
environments. If specified, then the payment hash isn't required, as
it'll use the hash of all zeroes. This mode allows one to quickly test
payment connectivity without having to create an invoice at the
destination.
`,
ArgsUsage: "dest amt payment_hash final_cltv_delta | --pay_req=[payment request]",
Flags: append(paymentFlags(),
Expand All @@ -2196,14 +2193,14 @@ var sendPaymentCommand = cli.Command{
Name: "payment_hash, r",
Usage: "the hash to use within the payment's HTLC",
},
cli.BoolFlag{
Name: "debug_send",
Usage: "use the debug rHash when sending the HTLC",
},
cli.Int64Flag{
Name: "final_cltv_delta",
Usage: "the number of blocks the last hop has to reveal the preimage",
},
cli.BoolFlag{
Name: "key_send",
Usage: "will generate a pre-image and encode it in the sphinx packet, a dest must be set [experimental]",
},
),
Action: sendPayment,
}
Expand Down Expand Up @@ -2306,11 +2303,25 @@ func sendPayment(ctx *cli.Context) error {
Amt: amount,
}

if ctx.Bool("debug_send") && (ctx.IsSet("payment_hash") || args.Present()) {
return fmt.Errorf("do not provide a payment hash with debug send")
} else if !ctx.Bool("debug_send") {
var rHash []byte
var rHash []byte

if ctx.Bool("key_send") {
if ctx.IsSet("payment_hash") {
return errors.New("cannot set payment hash when using " +
"key send")
}
var preimage lntypes.Preimage
if _, err := rand.Read(preimage[:]); err != nil {
return err
}

req.DestCustomRecords = map[uint64][]byte{
record.KeySend: preimage[:],
}

hash := preimage.Hash()
rHash = hash[:]
} else {
switch {
case ctx.IsSet("payment_hash"):
rHash, err = hex.DecodeString(ctx.String("payment_hash"))
Expand All @@ -2320,26 +2331,26 @@ func sendPayment(ctx *cli.Context) error {
default:
return fmt.Errorf("payment hash argument missing")
}
}

if err != nil {
return err
}
if len(rHash) != 32 {
return fmt.Errorf("payment hash must be exactly 32 "+
"bytes, is instead %v", len(rHash))
}
req.PaymentHash = rHash

switch {
case ctx.IsSet("final_cltv_delta"):
req.FinalCltvDelta = int32(ctx.Int64("final_cltv_delta"))
case args.Present():
delta, err := strconv.ParseInt(args.First(), 10, 64)
if err != nil {
return err
}
if len(rHash) != 32 {
return fmt.Errorf("payment hash must be exactly 32 "+
"bytes, is instead %v", len(rHash))
}
req.PaymentHash = rHash

switch {
case ctx.IsSet("final_cltv_delta"):
req.FinalCltvDelta = int32(ctx.Int64("final_cltv_delta"))
case args.Present():
delta, err := strconv.ParseInt(args.First(), 10, 64)
if err != nil {
return err
}
req.FinalCltvDelta = int32(delta)
}
req.FinalCltvDelta = int32(delta)
}

return sendPaymentRequest(ctx, req)
Expand Down
2 changes: 2 additions & 0 deletions config.go
Expand Up @@ -326,6 +326,8 @@ type config struct {

EnableUpfrontShutdown bool `long:"enable-upfront-shutdown" description:"If true, option upfront shutdown script will be enabled. If peers that we open channels with support this feature, we will automatically set the script to which cooperative closes should be paid out to on channel open. This offers the partial protection of a channel peer disconnecting from us if cooperative close is attempted with a different script."`

AcceptKeySend bool `long:"accept-key-send" description:"If true, spontaneous payments through key send will be accepted. [experimental]"`

Routing *routing.Conf `group:"routing" namespace:"routing"`

Workers *lncfg.Workers `group:"workers" namespace:"workers"`
Expand Down
92 changes: 88 additions & 4 deletions invoices/invoiceregistry.go
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/queue"
"github.com/lightningnetwork/lnd/record"
)

var (
Expand Down Expand Up @@ -67,6 +68,10 @@ type RegistryConfig struct {
// Now() and TickAfter() and is useful to stub out the clock functions
// during testing.
Clock clock.Clock

// AcceptKeySend indicates whether we want to accept spontaneous key
// send payments.
AcceptKeySend bool
}

// htlcReleaseEvent describes an htlc auto-release event. It is used to release
Expand Down Expand Up @@ -661,6 +666,68 @@ func (i *InvoiceRegistry) cancelSingleHtlc(hash lntypes.Hash,
return nil
}

// processKeySend just-in-time inserts an invoice if this htlc is a key send
// htlc.
func (i *InvoiceRegistry) processKeySend(ctx invoiceUpdateCtx,
hash lntypes.Hash) error {

// Retrieve key send record if present.
preimageSlice, ok := ctx.customRecords[record.KeySend]
if !ok {
return nil
}

// Cancel htlc is preimage is invalid.
preimage, err := lntypes.MakePreimage(preimageSlice)
if err != nil || preimage.Hash() != hash {
return errors.New("invalid key send preimage")
}

// Don't accept zero preimages as those have a special meaning in our
// database for hodl invoices.
if preimage == channeldb.UnknownPreimage {
return errors.New("invalid key send preimage")
}

// Only allow key send for non-mpp payments.
if ctx.mpp != nil {
return errors.New("no mpp key send supported")
}

// Create an invoice for the htlc amount.
amt := ctx.amtPaid

// Set tlv optional feature vector on the invoice. Otherwise we wouldn't
// be able to pay to it with key send.
rawFeatures := lnwire.NewRawFeatureVector(
lnwire.TLVOnionPayloadOptional,
)
features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)

// Use the minimum block delta that we require for settling htlcs.
finalCltvDelta := i.cfg.FinalCltvRejectDelta

// Create placeholder invoice.
invoice := &channeldb.Invoice{
CreationDate: i.cfg.Clock.Now(),
Terms: channeldb.ContractTerm{
FinalCltvDelta: finalCltvDelta,
Value: amt,
PaymentPreimage: preimage,
Features: features,
},
}

// Insert invoice into database. Ignore duplicates, because this
// may be a replay.
_, err = i.AddInvoice(invoice, hash)
if err != nil && err != channeldb.ErrDuplicateInvoice {
return err
}

return nil
}

// NotifyExitHopHtlc attempts to mark an invoice as settled. The return value
// describes how the htlc should be resolved.
//
Expand All @@ -681,16 +748,15 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
circuitKey channeldb.CircuitKey, hodlChan chan<- interface{},
payload Payload) (*HodlEvent, error) {

i.Lock()
defer i.Unlock()

mpp := payload.MultiPath()

debugLog := func(s string) {
log.Debugf("Invoice(%x): %v, amt=%v, expiry=%v, circuit=%v, "+
"mpp=%v", rHash[:], s, amtPaid, expiry, circuitKey, mpp)
}

customRecords := payload.CustomRecords()

// Create the update context containing the relevant details of the
// incoming htlc.
updateCtx := invoiceUpdateCtx{
Expand All @@ -699,10 +765,28 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
expiry: expiry,
currentHeight: currentHeight,
finalCltvRejectDelta: i.cfg.FinalCltvRejectDelta,
customRecords: payload.CustomRecords(),
customRecords: customRecords,
mpp: mpp,
}

// Process key send if present. Do this outside of the lock, because
// AddInvoice obtains its own lock. This is no problem, because the
// operation is idempotent.
if i.cfg.AcceptKeySend {
err := i.processKeySend(updateCtx, rHash)
if err != nil {
debugLog(fmt.Sprintf("key send error: %v", err))

return &HodlEvent{
CircuitKey: circuitKey,
AcceptHeight: currentHeight,
}, nil
}
}

i.Lock()
defer i.Unlock()

// We'll attempt to settle an invoice matching this rHash on disk (if
// one exists). The callback will update the invoice state and/or htlcs.
var (
Expand Down
78 changes: 77 additions & 1 deletion invoices/invoiceregistry_test.go
Expand Up @@ -559,6 +559,82 @@ func TestUnknownInvoice(t *testing.T) {
}
}

// TestKeySend tests receiving a spontaneous payment with and without key send
// enabled.
func TestKeySend(t *testing.T) {
t.Run("enabled", func(t *testing.T) {
testKeySend(t, true)
})
t.Run("disabled", func(t *testing.T) {
testKeySend(t, false)
})
}

// testKeySend is the inner test function that tests key send for a particular
// enabled state on the receiver end.
func testKeySend(t *testing.T, keySendEnabled bool) {
defer timeout()()

ctx := newTestContext(t)
defer ctx.cleanup()

ctx.registry.cfg.AcceptKeySend = keySendEnabled

allSubscriptions := ctx.registry.SubscribeNotifications(0, 0)
defer allSubscriptions.Cancel()

hodlChan := make(chan interface{}, 1)

amt := lnwire.MilliSatoshi(1000)
expiry := uint32(testCurrentHeight + 20)

// Create key for key send.
preimage := lntypes.Preimage{1, 2, 3}
hash := preimage.Hash()

keySendPayload := &mockPayload{
customRecords: map[uint64][]byte{
record.KeySend: preimage[:],
},
}

// Try to settle invoice with a key send htlc.
event, err := ctx.registry.NotifyExitHopHtlc(
hash, amt, expiry,
testCurrentHeight, getCircuitKey(10), hodlChan, keySendPayload,
)
// Expect a cancel event if key send is disabled.
if !keySendEnabled {
if err != channeldb.ErrInvoiceNotFound {
t.Fatal("expected key send payment not to be accepted")
}
return
}

// Otherwise we expect no error and a settle event for the htlc.
if err != nil {
t.Fatal(err)
}

if event.Preimage == nil || *event.Preimage != preimage {
t.Fatal("expected valid settle event")
}

// We expect a new invoice notification to be sent out.
newInvoice := <-allSubscriptions.NewInvoices
if newInvoice.State != channeldb.ContractOpen {
t.Fatalf("expected state ContractOpen, but got %v",
newInvoice.State)
}

// We expect a settled notification to be sent out.
settledInvoice := <-allSubscriptions.SettledInvoices
if settledInvoice.State != channeldb.ContractSettled {
t.Fatalf("expected state ContractOpen, but got %v",
settledInvoice.State)
}
}

// TestSettleMpp tests settling of an invoice with multiple partial payments.
func TestSettleMpp(t *testing.T) {
defer timeout()()
Expand Down Expand Up @@ -721,7 +797,7 @@ func TestInvoiceExpiryWithRegistry(t *testing.T) {
testClock.SetTime(testTime.Add(24 * time.Hour))

// Give some time to the watcher to cancel everything.
time.Sleep(testTimeout)
time.Sleep(500 * time.Millisecond)
registry.Stop()

// Create the expected cancellation set before the final check.
Expand Down
11 changes: 9 additions & 2 deletions invoices/test_utils_test.go
Expand Up @@ -21,15 +21,22 @@ import (
)

type mockPayload struct {
mpp *record.MPP
mpp *record.MPP
customRecords record.CustomSet
}

func (p *mockPayload) MultiPath() *record.MPP {
return p.mpp
}

func (p *mockPayload) CustomRecords() record.CustomSet {
return make(record.CustomSet)
// This function should always return a map instance, but for mock
// configuration we do accept nil.
if p.customRecords == nil {
return make(record.CustomSet)
}

return p.customRecords
}

var (
Expand Down

0 comments on commit 8bd26f3

Please sign in to comment.