Merge pull request #5108 from cfromknecht/sendtoroute-amp
channeldb+invoices: add spontaneous AMP receiving + sending via SendToRoute
This commit is contained in:
25 files changed
+3186
-1182
No files matched your search
+847
-13
@@ -8,6 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/lightningnetwork/lnd/clock"
|
"github.com/lightningnetwork/lnd/clock"
|
||||||
|
"github.com/lightningnetwork/lnd/feature"
|
||||||
"github.com/lightningnetwork/lnd/lntypes"
|
"github.com/lightningnetwork/lnd/lntypes"
|
||||||
"github.com/lightningnetwork/lnd/lnwire"
|
"github.com/lightningnetwork/lnd/lnwire"
|
||||||
"github.com/lightningnetwork/lnd/record"
|
"github.com/lightningnetwork/lnd/record"
|
||||||
@@ -16,7 +17,15 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
emptyFeatures = lnwire.NewFeatureVector(nil, lnwire.Features)
|
emptyFeatures = lnwire.NewFeatureVector(nil, lnwire.Features)
|
||||||
testNow = time.Unix(1, 0)
|
ampFeatures = lnwire.NewFeatureVector(
|
||||||
|
lnwire.NewRawFeatureVector(
|
||||||
|
lnwire.TLVOnionPayloadOptional,
|
||||||
|
lnwire.PaymentAddrOptional,
|
||||||
|
lnwire.AMPRequired,
|
||||||
|
),
|
||||||
|
lnwire.Features,
|
||||||
|
)
|
||||||
|
testNow = time.Unix(1, 0)
|
||||||
)
|
)
|
||||||
|
|
||||||
func randInvoice(value lnwire.MilliSatoshi) (*Invoice, error) {
|
func randInvoice(value lnwire.MilliSatoshi) (*Invoice, error) {
|
||||||
@@ -1208,23 +1217,30 @@ func TestInvoiceRef(t *testing.T) {
|
|||||||
// An InvoiceRef by hash should return the provided hash and a nil
|
// An InvoiceRef by hash should return the provided hash and a nil
|
||||||
// payment addr.
|
// payment addr.
|
||||||
refByHash := InvoiceRefByHash(payHash)
|
refByHash := InvoiceRefByHash(payHash)
|
||||||
require.Equal(t, payHash, refByHash.PayHash())
|
require.Equal(t, &payHash, refByHash.PayHash())
|
||||||
require.Equal(t, (*[32]byte)(nil), refByHash.PayAddr())
|
require.Equal(t, (*[32]byte)(nil), refByHash.PayAddr())
|
||||||
require.Equal(t, (*[32]byte)(nil), refByHash.SetID())
|
require.Equal(t, (*[32]byte)(nil), refByHash.SetID())
|
||||||
|
|
||||||
// An InvoiceRef by hash and addr should return the payment hash and
|
// An InvoiceRef by hash and addr should return the payment hash and
|
||||||
// payment addr passed to the constructor.
|
// payment addr passed to the constructor.
|
||||||
refByHashAndAddr := InvoiceRefByHashAndAddr(payHash, payAddr)
|
refByHashAndAddr := InvoiceRefByHashAndAddr(payHash, payAddr)
|
||||||
require.Equal(t, payHash, refByHashAndAddr.PayHash())
|
require.Equal(t, &payHash, refByHashAndAddr.PayHash())
|
||||||
require.Equal(t, &payAddr, refByHashAndAddr.PayAddr())
|
require.Equal(t, &payAddr, refByHashAndAddr.PayAddr())
|
||||||
require.Equal(t, (*[32]byte)(nil), refByHashAndAddr.SetID())
|
require.Equal(t, (*[32]byte)(nil), refByHashAndAddr.SetID())
|
||||||
|
|
||||||
// An InvoiceRef by set id should return an empty pay hash, a nil pay
|
// An InvoiceRef by set id should return an empty pay hash, a nil pay
|
||||||
// addr, and a reference to the given set id.
|
// addr, and a reference to the given set id.
|
||||||
refBySetID := InvoiceRefBySetID(setID)
|
refBySetID := InvoiceRefBySetID(setID)
|
||||||
require.Equal(t, lntypes.Hash{}, refBySetID.PayHash())
|
require.Equal(t, (*lntypes.Hash)(nil), refBySetID.PayHash())
|
||||||
require.Equal(t, (*[32]byte)(nil), refBySetID.PayAddr())
|
require.Equal(t, (*[32]byte)(nil), refBySetID.PayAddr())
|
||||||
require.Equal(t, &setID, refBySetID.SetID())
|
require.Equal(t, &setID, refBySetID.SetID())
|
||||||
|
|
||||||
|
// An InvoiceRef by pay addr should only return a pay addr, but nil for
|
||||||
|
// pay hash and set id.
|
||||||
|
refByAddr := InvoiceRefByAddr(payAddr)
|
||||||
|
require.Equal(t, (*lntypes.Hash)(nil), refByAddr.PayHash())
|
||||||
|
require.Equal(t, &payAddr, refByAddr.PayAddr())
|
||||||
|
require.Equal(t, (*[32]byte)(nil), refByAddr.SetID())
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestHTLCSet asserts that HTLCSet returns the proper set of accepted HTLCs
|
// TestHTLCSet asserts that HTLCSet returns the proper set of accepted HTLCs
|
||||||
@@ -1366,7 +1382,7 @@ func TestSetIDIndex(t *testing.T) {
|
|||||||
invoice.AmtPaid = amt
|
invoice.AmtPaid = amt
|
||||||
invoice.SettleDate = dbInvoice.SettleDate
|
invoice.SettleDate = dbInvoice.SettleDate
|
||||||
invoice.Htlcs = map[CircuitKey]*InvoiceHTLC{
|
invoice.Htlcs = map[CircuitKey]*InvoiceHTLC{
|
||||||
{HtlcID: 0}: makeAMPInvoiceHTLC(amt, *setID, preimage),
|
{HtlcID: 0}: makeAMPInvoiceHTLC(amt, *setID, payHash, &preimage),
|
||||||
}
|
}
|
||||||
|
|
||||||
// We should get back the exact same invoice that we just inserted.
|
// We should get back the exact same invoice that we just inserted.
|
||||||
@@ -1406,9 +1422,9 @@ func TestSetIDIndex(t *testing.T) {
|
|||||||
invoice.AmtPaid += 2 * amt
|
invoice.AmtPaid += 2 * amt
|
||||||
invoice.SettleDate = dbInvoice.SettleDate
|
invoice.SettleDate = dbInvoice.SettleDate
|
||||||
invoice.Htlcs = map[CircuitKey]*InvoiceHTLC{
|
invoice.Htlcs = map[CircuitKey]*InvoiceHTLC{
|
||||||
{HtlcID: 0}: makeAMPInvoiceHTLC(amt, *setID, preimage),
|
{HtlcID: 0}: makeAMPInvoiceHTLC(amt, *setID, payHash, &preimage),
|
||||||
{HtlcID: 1}: makeAMPInvoiceHTLC(amt, *setID2, preimage),
|
{HtlcID: 1}: makeAMPInvoiceHTLC(amt, *setID2, payHash, nil),
|
||||||
{HtlcID: 2}: makeAMPInvoiceHTLC(amt, *setID2, preimage),
|
{HtlcID: 2}: makeAMPInvoiceHTLC(amt, *setID2, payHash, nil),
|
||||||
}
|
}
|
||||||
|
|
||||||
// We should get back the exact same invoice that we just inserted.
|
// We should get back the exact same invoice that we just inserted.
|
||||||
@@ -1452,7 +1468,7 @@ func TestSetIDIndex(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func makeAMPInvoiceHTLC(amt lnwire.MilliSatoshi, setID [32]byte,
|
func makeAMPInvoiceHTLC(amt lnwire.MilliSatoshi, setID [32]byte,
|
||||||
preimage lntypes.Preimage) *InvoiceHTLC {
|
hash lntypes.Hash, preimage *lntypes.Preimage) *InvoiceHTLC {
|
||||||
|
|
||||||
return &InvoiceHTLC{
|
return &InvoiceHTLC{
|
||||||
Amt: amt,
|
Amt: amt,
|
||||||
@@ -1462,8 +1478,8 @@ func makeAMPInvoiceHTLC(amt lnwire.MilliSatoshi, setID [32]byte,
|
|||||||
CustomRecords: make(record.CustomSet),
|
CustomRecords: make(record.CustomSet),
|
||||||
AMP: &InvoiceHtlcAMPData{
|
AMP: &InvoiceHtlcAMPData{
|
||||||
Record: *record.NewAMP([32]byte{}, setID, 0),
|
Record: *record.NewAMP([32]byte{}, setID, 0),
|
||||||
Hash: preimage.Hash(),
|
Hash: hash,
|
||||||
Preimage: &preimage,
|
Preimage: preimage,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1480,18 +1496,23 @@ func updateAcceptAMPHtlc(id uint64, amt lnwire.MilliSatoshi,
|
|||||||
|
|
||||||
noRecords := make(record.CustomSet)
|
noRecords := make(record.CustomSet)
|
||||||
|
|
||||||
var state *InvoiceStateUpdateDesc
|
var (
|
||||||
|
state *InvoiceStateUpdateDesc
|
||||||
|
preimage *lntypes.Preimage
|
||||||
|
)
|
||||||
if accept {
|
if accept {
|
||||||
state = &InvoiceStateUpdateDesc{
|
state = &InvoiceStateUpdateDesc{
|
||||||
NewState: ContractAccepted,
|
NewState: ContractAccepted,
|
||||||
SetID: setID,
|
SetID: setID,
|
||||||
}
|
}
|
||||||
|
pre := *invoice.Terms.PaymentPreimage
|
||||||
|
preimage = &pre
|
||||||
}
|
}
|
||||||
|
|
||||||
ampData := &InvoiceHtlcAMPData{
|
ampData := &InvoiceHtlcAMPData{
|
||||||
Record: *record.NewAMP([32]byte{}, *setID, 0),
|
Record: *record.NewAMP([32]byte{}, *setID, 0),
|
||||||
Hash: invoice.Terms.PaymentPreimage.Hash(),
|
Hash: invoice.Terms.PaymentPreimage.Hash(),
|
||||||
Preimage: invoice.Terms.PaymentPreimage,
|
Preimage: preimage,
|
||||||
}
|
}
|
||||||
update := &InvoiceUpdateDesc{
|
update := &InvoiceUpdateDesc{
|
||||||
State: state,
|
State: state,
|
||||||
@@ -1526,6 +1547,792 @@ func getUpdateInvoiceAMPSettle(setID *[32]byte) InvoiceUpdateCallback {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestUnexpectedInvoicePreimage asserts that legacy or MPP invoices cannot be
|
||||||
|
// settled when referenced by payment address only. Since regular or MPP
|
||||||
|
// payments do not store the payment hash explicitly (it is stored in the
|
||||||
|
// index), this enforces that they can only be updated using a InvoiceRefByHash
|
||||||
|
// or InvoiceRefByHashOrAddr.
|
||||||
|
func TestUnexpectedInvoicePreimage(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup, err := MakeTestDB()
|
||||||
|
defer cleanup()
|
||||||
|
require.NoError(t, err, "unable to make test db")
|
||||||
|
|
||||||
|
invoice, err := randInvoice(lnwire.MilliSatoshi(100))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Add a random invoice indexed by payment hash and payment addr.
|
||||||
|
paymentHash := invoice.Terms.PaymentPreimage.Hash()
|
||||||
|
_, err = db.AddInvoice(invoice, paymentHash)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Attempt to update the invoice by pay addr only. This will fail since,
|
||||||
|
// in order to settle an MPP invoice, the InvoiceRef must present a
|
||||||
|
// payment hash against which to validate the preimage.
|
||||||
|
_, err = db.UpdateInvoice(
|
||||||
|
InvoiceRefByAddr(invoice.Terms.PaymentAddr),
|
||||||
|
getUpdateInvoice(invoice.Terms.Value),
|
||||||
|
)
|
||||||
|
|
||||||
|
//Assert that we get ErrUnexpectedInvoicePreimage.
|
||||||
|
require.Error(t, ErrUnexpectedInvoicePreimage, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type updateHTLCPreimageTestCase struct {
|
||||||
|
name string
|
||||||
|
settleSamePreimage bool
|
||||||
|
expError error
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUpdateHTLCPreimages asserts various properties of setting HTLC-level
|
||||||
|
// preimages on invoice state transitions.
|
||||||
|
func TestUpdateHTLCPreimages(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []updateHTLCPreimageTestCase{
|
||||||
|
{
|
||||||
|
name: "same preimage on settle",
|
||||||
|
settleSamePreimage: true,
|
||||||
|
expError: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "diff preimage on settle",
|
||||||
|
settleSamePreimage: false,
|
||||||
|
expError: ErrHTLCPreimageAlreadyExists,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
test := test
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
testUpdateHTLCPreimages(t, test)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUpdateHTLCPreimages(t *testing.T, test updateHTLCPreimageTestCase) {
|
||||||
|
db, cleanup, err := MakeTestDB()
|
||||||
|
defer cleanup()
|
||||||
|
require.NoError(t, err, "unable to make test db")
|
||||||
|
|
||||||
|
// We'll start out by creating an invoice and writing it to the DB.
|
||||||
|
amt := lnwire.NewMSatFromSatoshis(1000)
|
||||||
|
invoice, err := randInvoice(amt)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
preimage := *invoice.Terms.PaymentPreimage
|
||||||
|
payHash := preimage.Hash()
|
||||||
|
|
||||||
|
// Set AMP-specific features so that we can settle with HTLC-level
|
||||||
|
// preimages.
|
||||||
|
invoice.Terms.Features = ampFeatures
|
||||||
|
|
||||||
|
_, err = db.AddInvoice(invoice, payHash)
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
setID := &[32]byte{1}
|
||||||
|
|
||||||
|
// Update the invoice with an accepted HTLC that also accepts the
|
||||||
|
// invoice.
|
||||||
|
ref := InvoiceRefByAddr(invoice.Terms.PaymentAddr)
|
||||||
|
dbInvoice, err := db.UpdateInvoice(ref, updateAcceptAMPHtlc(0, amt, setID, true))
|
||||||
|
require.Nil(t, err)
|
||||||
|
|
||||||
|
htlcPreimages := make(map[CircuitKey]lntypes.Preimage)
|
||||||
|
for key := range dbInvoice.Htlcs {
|
||||||
|
// Set the either the same preimage used to accept above, or a
|
||||||
|
// blank preimage depending on the test case.
|
||||||
|
var pre lntypes.Preimage
|
||||||
|
if test.settleSamePreimage {
|
||||||
|
pre = preimage
|
||||||
|
}
|
||||||
|
htlcPreimages[key] = pre
|
||||||
|
}
|
||||||
|
|
||||||
|
updateInvoice := func(invoice *Invoice) (*InvoiceUpdateDesc, error) {
|
||||||
|
update := &InvoiceUpdateDesc{
|
||||||
|
State: &InvoiceStateUpdateDesc{
|
||||||
|
Preimage: nil,
|
||||||
|
NewState: ContractSettled,
|
||||||
|
HTLCPreimages: htlcPreimages,
|
||||||
|
SetID: setID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return update, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now settle the HTLC set and assert the resulting error.
|
||||||
|
_, err = db.UpdateInvoice(ref, updateInvoice)
|
||||||
|
require.Equal(t, test.expError, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type updateHTLCTest struct {
|
||||||
|
name string
|
||||||
|
input InvoiceHTLC
|
||||||
|
invState ContractState
|
||||||
|
setID *[32]byte
|
||||||
|
output InvoiceHTLC
|
||||||
|
expErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUpdateHTLC asserts the behavior of the updateHTLC method in various
|
||||||
|
// scenarios for MPP and AMP.
|
||||||
|
func TestUpdateHTLC(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
setID := [32]byte{0x01}
|
||||||
|
ampRecord := record.NewAMP([32]byte{0x02}, setID, 3)
|
||||||
|
preimage := lntypes.Preimage{0x04}
|
||||||
|
hash := preimage.Hash()
|
||||||
|
|
||||||
|
diffSetID := [32]byte{0x05}
|
||||||
|
fakePreimage := lntypes.Preimage{0x06}
|
||||||
|
testAlreadyNow := time.Now()
|
||||||
|
|
||||||
|
tests := []updateHTLCTest{
|
||||||
|
{
|
||||||
|
name: "MPP accept",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: nil,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "MPP settle",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: nil,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "MPP cancel",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
invState: ContractCanceled,
|
||||||
|
setID: nil,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: nil,
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP accept missing preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: nil,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: nil,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCPreimageMissing,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP accept invalid preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &fakePreimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &fakePreimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCPreimageMismatch,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP accept valid preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP accept valid preimage different htlc set",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &diffSetID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP settle missing preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: nil,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: nil,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCPreimageMissing,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP settle invalid preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &fakePreimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &fakePreimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCPreimageMismatch,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP settle valid preimage",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "AMP settle valid preimage different htlc set",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &diffSetID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "accept invoice htlc already settled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCAlreadySettled,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cancel invoice htlc already settled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractCanceled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: ErrHTLCAlreadySettled,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settle invoice htlc already settled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateSettled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cancel invoice",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: time.Time{},
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateAccepted,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractCanceled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "accept invoice htlc already canceled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractAccepted,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cancel invoice htlc already canceled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractCanceled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "settle invoice htlc already canceled",
|
||||||
|
input: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invState: ContractSettled,
|
||||||
|
setID: &setID,
|
||||||
|
output: InvoiceHTLC{
|
||||||
|
Amt: 5000,
|
||||||
|
MppTotalAmt: 5000,
|
||||||
|
AcceptHeight: 100,
|
||||||
|
AcceptTime: testNow,
|
||||||
|
ResolveTime: testAlreadyNow,
|
||||||
|
Expiry: 40,
|
||||||
|
State: HtlcStateCanceled,
|
||||||
|
CustomRecords: make(record.CustomSet),
|
||||||
|
AMP: &InvoiceHtlcAMPData{
|
||||||
|
Record: *ampRecord,
|
||||||
|
Hash: hash,
|
||||||
|
Preimage: &preimage,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expErr: nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
test := test
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
testUpdateHTLC(t, test)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUpdateHTLC(t *testing.T, test updateHTLCTest) {
|
||||||
|
htlc := test.input.Copy()
|
||||||
|
err := updateHtlc(testNow, htlc, test.invState, test.setID)
|
||||||
|
require.Equal(t, test.expErr, err)
|
||||||
|
require.Equal(t, test.output, *htlc)
|
||||||
|
}
|
||||||
|
|
||||||
// TestDeleteInvoices tests that deleting a list of invoices will succeed
|
// TestDeleteInvoices tests that deleting a list of invoices will succeed
|
||||||
// if all delete references are valid, or will fail otherwise.
|
// if all delete references are valid, or will fail otherwise.
|
||||||
func TestDeleteInvoices(t *testing.T) {
|
func TestDeleteInvoices(t *testing.T) {
|
||||||
@@ -1619,3 +2426,30 @@ func TestDeleteInvoices(t *testing.T) {
|
|||||||
assertInvoiceCount(0)
|
assertInvoiceCount(0)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestAddInvoiceInvalidFeatureDeps asserts that inserting an invoice with
|
||||||
|
// invalid transitive feature dependencies fails with the appropriate error.
|
||||||
|
func TestAddInvoiceInvalidFeatureDeps(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup, err := MakeTestDB()
|
||||||
|
require.NoError(t, err, "unable to make test db")
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
invoice, err := randInvoice(500)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
invoice.Terms.Features = lnwire.NewFeatureVector(
|
||||||
|
lnwire.NewRawFeatureVector(
|
||||||
|
lnwire.TLVOnionPayloadOptional,
|
||||||
|
lnwire.MPPOptional,
|
||||||
|
),
|
||||||
|
lnwire.Features,
|
||||||
|
)
|
||||||
|
|
||||||
|
hash := invoice.Terms.PaymentPreimage.Hash()
|
||||||
|
_, err = db.AddInvoice(invoice, hash)
|
||||||
|
require.Error(t, err, feature.NewErrMissingFeatureDep(
|
||||||
|
lnwire.PaymentAddrOptional,
|
||||||
|
))
|
||||||
|
}
|
||||||
+159
-46
@@ -6,9 +6,11 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/lightningnetwork/lnd/channeldb/kvdb"
|
"github.com/lightningnetwork/lnd/channeldb/kvdb"
|
||||||
|
"github.com/lightningnetwork/lnd/feature"
|
||||||
"github.com/lightningnetwork/lnd/htlcswitch/hop"
|
"github.com/lightningnetwork/lnd/htlcswitch/hop"
|
||||||
"github.com/lightningnetwork/lnd/lntypes"
|
"github.com/lightningnetwork/lnd/lntypes"
|
||||||
"github.com/lightningnetwork/lnd/lnwire"
|
"github.com/lightningnetwork/lnd/lnwire"
|
||||||
@@ -115,6 +117,19 @@ var (
|
|||||||
// match the invoice hash.
|
// match the invoice hash.
|
||||||
ErrInvoicePreimageMismatch = errors.New("preimage does not match")
|
ErrInvoicePreimageMismatch = errors.New("preimage does not match")
|
||||||
|
|
||||||
|
// ErrHTLCPreimageMissing is returned when trying to accept/settle an
|
||||||
|
// AMP HTLC but the HTLC-level preimage has not been set.
|
||||||
|
ErrHTLCPreimageMissing = errors.New("AMP htlc missing preimage")
|
||||||
|
|
||||||
|
// ErrHTLCPreimageMismatch is returned when trying to accept/settle an
|
||||||
|
// AMP HTLC but the HTLC-level preimage does not satisfying the
|
||||||
|
// HTLC-level payment hash.
|
||||||
|
ErrHTLCPreimageMismatch = errors.New("htlc preimage mismatch")
|
||||||
|
|
||||||
|
// ErrHTLCAlreadySettled is returned when trying to settle an invoice
|
||||||
|
// but HTLC already exists in the settled state.
|
||||||
|
ErrHTLCAlreadySettled = errors.New("htlc already settled")
|
||||||
|
|
||||||
// ErrInvoiceHasHtlcs is returned when attempting to insert an invoice
|
// ErrInvoiceHasHtlcs is returned when attempting to insert an invoice
|
||||||
// that already has HTLCs.
|
// that already has HTLCs.
|
||||||
ErrInvoiceHasHtlcs = errors.New("cannot add invoice with htlcs")
|
ErrInvoiceHasHtlcs = errors.New("cannot add invoice with htlcs")
|
||||||
@@ -122,6 +137,19 @@ var (
|
|||||||
// ErrEmptyHTLCSet is returned when attempting to accept or settle and
|
// ErrEmptyHTLCSet is returned when attempting to accept or settle and
|
||||||
// HTLC set that has no HTLCs.
|
// HTLC set that has no HTLCs.
|
||||||
ErrEmptyHTLCSet = errors.New("cannot settle/accept empty HTLC set")
|
ErrEmptyHTLCSet = errors.New("cannot settle/accept empty HTLC set")
|
||||||
|
|
||||||
|
// ErrUnexpectedInvoicePreimage is returned when an invoice-level
|
||||||
|
// preimage is provided when trying to settle an invoice that shouldn't
|
||||||
|
// have one, e.g. an AMP invoice.
|
||||||
|
ErrUnexpectedInvoicePreimage = errors.New(
|
||||||
|
"unexpected invoice preimage provided on settle",
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrHTLCPreimageAlreadyExists is returned when trying to set an
|
||||||
|
// htlc-level preimage but one is already known.
|
||||||
|
ErrHTLCPreimageAlreadyExists = errors.New(
|
||||||
|
"htlc-level preimage already exists",
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrDuplicateSetID is an error returned when attempting to adding an AMP HTLC
|
// ErrDuplicateSetID is an error returned when attempting to adding an AMP HTLC
|
||||||
@@ -198,7 +226,7 @@ type InvoiceRef struct {
|
|||||||
// payHash is the payment hash of the target invoice. All invoices are
|
// payHash is the payment hash of the target invoice. All invoices are
|
||||||
// currently indexed by payment hash. This value will be used as a
|
// currently indexed by payment hash. This value will be used as a
|
||||||
// fallback when no payment address is known.
|
// fallback when no payment address is known.
|
||||||
payHash lntypes.Hash
|
payHash *lntypes.Hash
|
||||||
|
|
||||||
// payAddr is the payment addr of the target invoice. Newer invoices
|
// payAddr is the payment addr of the target invoice. Newer invoices
|
||||||
// (0.11 and up) are indexed by payment address in addition to payment
|
// (0.11 and up) are indexed by payment address in addition to payment
|
||||||
@@ -220,7 +248,7 @@ type InvoiceRef struct {
|
|||||||
// its payment hash.
|
// its payment hash.
|
||||||
func InvoiceRefByHash(payHash lntypes.Hash) InvoiceRef {
|
func InvoiceRefByHash(payHash lntypes.Hash) InvoiceRef {
|
||||||
return InvoiceRef{
|
return InvoiceRef{
|
||||||
payHash: payHash,
|
payHash: &payHash,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,11 +259,19 @@ func InvoiceRefByHashAndAddr(payHash lntypes.Hash,
|
|||||||
payAddr [32]byte) InvoiceRef {
|
payAddr [32]byte) InvoiceRef {
|
||||||
|
|
||||||
return InvoiceRef{
|
return InvoiceRef{
|
||||||
payHash: payHash,
|
payHash: &payHash,
|
||||||
payAddr: &payAddr,
|
payAddr: &payAddr,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InvoiceRefByAddr creates an InvoiceRef that queries the payment addr index
|
||||||
|
// for an invoice with the provided payment address.
|
||||||
|
func InvoiceRefByAddr(addr [32]byte) InvoiceRef {
|
||||||
|
return InvoiceRef{
|
||||||
|
payAddr: &addr,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// InvoiceRefBySetID creates an InvoiceRef that queries the set id index for an
|
// InvoiceRefBySetID creates an InvoiceRef that queries the set id index for an
|
||||||
// invoice with the provided setID. If the invoice is not found, the query will
|
// invoice with the provided setID. If the invoice is not found, the query will
|
||||||
// not fallback to payHash or payAddr.
|
// not fallback to payHash or payAddr.
|
||||||
@@ -245,9 +281,15 @@ func InvoiceRefBySetID(setID [32]byte) InvoiceRef {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// PayHash returns the target invoice's payment hash.
|
// PayHash returns the optional payment hash of the target invoice.
|
||||||
func (r InvoiceRef) PayHash() lntypes.Hash {
|
//
|
||||||
return r.payHash
|
// NOTE: This value may be nil.
|
||||||
|
func (r InvoiceRef) PayHash() *lntypes.Hash {
|
||||||
|
if r.payHash != nil {
|
||||||
|
hash := *r.payHash
|
||||||
|
return &hash
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// PayAddr returns the optional payment address of the target invoice.
|
// PayAddr returns the optional payment address of the target invoice.
|
||||||
@@ -274,10 +316,17 @@ func (r InvoiceRef) SetID() *[32]byte {
|
|||||||
|
|
||||||
// String returns a human-readable representation of an InvoiceRef.
|
// String returns a human-readable representation of an InvoiceRef.
|
||||||
func (r InvoiceRef) String() string {
|
func (r InvoiceRef) String() string {
|
||||||
if r.payAddr != nil {
|
var ids []string
|
||||||
return fmt.Sprintf("(pay_hash=%v, pay_addr=%x)", r.payHash, *r.payAddr)
|
if r.payHash != nil {
|
||||||
|
ids = append(ids, fmt.Sprintf("pay_hash=%v", *r.payHash))
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("(pay_hash=%v)", r.payHash)
|
if r.payAddr != nil {
|
||||||
|
ids = append(ids, fmt.Sprintf("pay_addr=%x", *r.payAddr))
|
||||||
|
}
|
||||||
|
if r.setID != nil {
|
||||||
|
ids = append(ids, fmt.Sprintf("set_id=%x", *r.setID))
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("(%s)", strings.Join(ids, ", "))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ContractState describes the state the invoice is in.
|
// ContractState describes the state the invoice is in.
|
||||||
@@ -499,6 +548,21 @@ type InvoiceHTLC struct {
|
|||||||
AMP *InvoiceHtlcAMPData
|
AMP *InvoiceHtlcAMPData
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Copy makes a deep copy of the target InvoiceHTLC.
|
||||||
|
func (h *InvoiceHTLC) Copy() *InvoiceHTLC {
|
||||||
|
result := *h
|
||||||
|
|
||||||
|
// Make a copy of the CustomSet map.
|
||||||
|
result.CustomRecords = make(record.CustomSet)
|
||||||
|
for k, v := range h.CustomRecords {
|
||||||
|
result.CustomRecords[k] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
result.AMP = h.AMP.Copy()
|
||||||
|
|
||||||
|
return &result
|
||||||
|
}
|
||||||
|
|
||||||
// IsInHTLCSet returns true if this HTLC is part an HTLC set. If nil is passed,
|
// IsInHTLCSet returns true if this HTLC is part an HTLC set. If nil is passed,
|
||||||
// this method returns true if this is an MPP HTLC. Otherwise, it only returns
|
// this method returns true if this is an MPP HTLC. Otherwise, it only returns
|
||||||
// true if the AMP HTLC's set id matches the populated setID.
|
// true if the AMP HTLC's set id matches the populated setID.
|
||||||
@@ -616,6 +680,11 @@ type InvoiceStateUpdateDesc struct {
|
|||||||
// Preimage must be set to the preimage when NewState is settled.
|
// Preimage must be set to the preimage when NewState is settled.
|
||||||
Preimage *lntypes.Preimage
|
Preimage *lntypes.Preimage
|
||||||
|
|
||||||
|
// HTLCPreimages set the HTLC-level preimages stored for AMP HTLCs.
|
||||||
|
// These are only learned when settling the invoice as a whole. Must be
|
||||||
|
// set when settling an invoice with non-nil SetID.
|
||||||
|
HTLCPreimages map[CircuitKey]lntypes.Preimage
|
||||||
|
|
||||||
// SetID identifies a specific set of HTLCs destined for the same
|
// SetID identifies a specific set of HTLCs destined for the same
|
||||||
// invoice as part of a larger AMP payment. This value will be nil for
|
// invoice as part of a larger AMP payment. This value will be nil for
|
||||||
// legacy or MPP payments.
|
// legacy or MPP payments.
|
||||||
@@ -645,7 +714,17 @@ func validateInvoice(i *Invoice, paymentHash lntypes.Hash) error {
|
|||||||
return errors.New("invoice must have a feature vector")
|
return errors.New("invoice must have a feature vector")
|
||||||
}
|
}
|
||||||
|
|
||||||
if i.Terms.PaymentPreimage == nil && !i.HodlInvoice {
|
err := feature.ValidateDeps(i.Terms.Features)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AMP invoices and hodl invoices are allowed to have no preimage
|
||||||
|
// specified.
|
||||||
|
isAMP := i.Terms.Features.HasFeature(
|
||||||
|
lnwire.AMPOptional,
|
||||||
|
)
|
||||||
|
if i.Terms.PaymentPreimage == nil && !(i.HodlInvoice || isAMP) {
|
||||||
return errors.New("non-hodl invoices must have a preimage")
|
return errors.New("non-hodl invoices must have a preimage")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -879,19 +958,27 @@ func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
|
|||||||
payHash := ref.PayHash()
|
payHash := ref.PayHash()
|
||||||
payAddr := ref.PayAddr()
|
payAddr := ref.PayAddr()
|
||||||
|
|
||||||
var (
|
getInvoiceNumByHash := func() []byte {
|
||||||
invoiceNumByHash = invoiceIndex.Get(payHash[:])
|
if payHash != nil {
|
||||||
invoiceNumByAddr []byte
|
return invoiceIndex.Get(payHash[:])
|
||||||
)
|
|
||||||
if payAddr != nil {
|
|
||||||
// Only allow lookups for payment address if it is not a blank
|
|
||||||
// payment address, which is a special-cased value for legacy
|
|
||||||
// keysend invoices.
|
|
||||||
if *payAddr != BlankPayAddr {
|
|
||||||
invoiceNumByAddr = payAddrIndex.Get(payAddr[:])
|
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getInvoiceNumByAddr := func() []byte {
|
||||||
|
if payAddr != nil {
|
||||||
|
// Only allow lookups for payment address if it is not a
|
||||||
|
// blank payment address, which is a special-cased value
|
||||||
|
// for legacy keysend invoices.
|
||||||
|
if *payAddr != BlankPayAddr {
|
||||||
|
return payAddrIndex.Get(payAddr[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
invoiceNumByHash := getInvoiceNumByHash()
|
||||||
|
invoiceNumByAddr := getInvoiceNumByAddr()
|
||||||
switch {
|
switch {
|
||||||
|
|
||||||
// If payment address and payment hash both reference an existing
|
// If payment address and payment hash both reference an existing
|
||||||
@@ -903,6 +990,10 @@ func fetchInvoiceNumByRef(invoiceIndex, payAddrIndex, setIDIndex kvdb.RBucket,
|
|||||||
|
|
||||||
return invoiceNumByAddr, nil
|
return invoiceNumByAddr, nil
|
||||||
|
|
||||||
|
// Return invoices by payment addr only.
|
||||||
|
case invoiceNumByAddr != nil:
|
||||||
|
return invoiceNumByAddr, nil
|
||||||
|
|
||||||
// If we were only able to reference the invoice by hash, return the
|
// If we were only able to reference the invoice by hash, return the
|
||||||
// corresponding invoice number. This can happen when no payment address
|
// corresponding invoice number. This can happen when no payment address
|
||||||
// was provided, or if it didn't match anything in our records.
|
// was provided, or if it didn't match anything in our records.
|
||||||
@@ -1684,21 +1775,6 @@ func copySlice(src []byte) []byte {
|
|||||||
return dest
|
return dest
|
||||||
}
|
}
|
||||||
|
|
||||||
// copyInvoiceHTLC makes a deep copy of the supplied invoice HTLC.
|
|
||||||
func copyInvoiceHTLC(src *InvoiceHTLC) *InvoiceHTLC {
|
|
||||||
result := *src
|
|
||||||
|
|
||||||
// Make a copy of the CustomSet map.
|
|
||||||
result.CustomRecords = make(record.CustomSet)
|
|
||||||
for k, v := range src.CustomRecords {
|
|
||||||
result.CustomRecords[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
result.AMP = src.AMP.Copy()
|
|
||||||
|
|
||||||
return &result
|
|
||||||
}
|
|
||||||
|
|
||||||
// copyInvoice makes a deep copy of the supplied invoice.
|
// copyInvoice makes a deep copy of the supplied invoice.
|
||||||
func copyInvoice(src *Invoice) *Invoice {
|
func copyInvoice(src *Invoice) *Invoice {
|
||||||
dest := Invoice{
|
dest := Invoice{
|
||||||
@@ -1725,7 +1801,7 @@ func copyInvoice(src *Invoice) *Invoice {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for k, v := range src.Htlcs {
|
for k, v := range src.Htlcs {
|
||||||
dest.Htlcs[k] = copyInvoiceHTLC(v)
|
dest.Htlcs[k] = v.Copy()
|
||||||
}
|
}
|
||||||
|
|
||||||
return &dest
|
return &dest
|
||||||
@@ -1733,7 +1809,7 @@ func copyInvoice(src *Invoice) *Invoice {
|
|||||||
|
|
||||||
// updateInvoice fetches the invoice, obtains the update descriptor from the
|
// updateInvoice fetches the invoice, obtains the update descriptor from the
|
||||||
// callback and applies the updates in a single db transaction.
|
// callback and applies the updates in a single db transaction.
|
||||||
func (d *DB) updateInvoice(hash lntypes.Hash, invoices,
|
func (d *DB) updateInvoice(hash *lntypes.Hash, invoices,
|
||||||
settleIndex, setIDIndex kvdb.RwBucket, invoiceNum []byte,
|
settleIndex, setIDIndex kvdb.RwBucket, invoiceNum []byte,
|
||||||
callback InvoiceUpdateCallback) (*Invoice, error) {
|
callback InvoiceUpdateCallback) (*Invoice, error) {
|
||||||
|
|
||||||
@@ -1867,7 +1943,25 @@ func (d *DB) updateInvoice(hash lntypes.Hash, invoices,
|
|||||||
// the process by updating the state transitions for individual HTLCs
|
// the process by updating the state transitions for individual HTLCs
|
||||||
// and recalculate the total amount paid to the invoice.
|
// and recalculate the total amount paid to the invoice.
|
||||||
var amtPaid lnwire.MilliSatoshi
|
var amtPaid lnwire.MilliSatoshi
|
||||||
for _, htlc := range invoice.Htlcs {
|
for key, htlc := range invoice.Htlcs {
|
||||||
|
// Set the HTLC preimage for any AMP HTLCs.
|
||||||
|
if setID != nil {
|
||||||
|
preimage, ok := update.State.HTLCPreimages[key]
|
||||||
|
switch {
|
||||||
|
|
||||||
|
// If we don't already have a preiamge for this HTLC, we
|
||||||
|
// can set it now.
|
||||||
|
case ok && htlc.AMP.Preimage == nil:
|
||||||
|
htlc.AMP.Preimage = &preimage
|
||||||
|
|
||||||
|
// Otherwise, prevent over-writing an existing preimage.
|
||||||
|
// Ignore the case where the preimage is identical.
|
||||||
|
case ok && *htlc.AMP.Preimage != preimage:
|
||||||
|
return nil, ErrHTLCPreimageAlreadyExists
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// The invoice state may have changed and this could have
|
// The invoice state may have changed and this could have
|
||||||
// implications for the states of the individual htlcs. Align
|
// implications for the states of the individual htlcs. Align
|
||||||
// the htlc state with the current invoice state.
|
// the htlc state with the current invoice state.
|
||||||
@@ -1901,7 +1995,7 @@ func (d *DB) updateInvoice(hash lntypes.Hash, invoices,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// updateInvoiceState validates and processes an invoice state update.
|
// updateInvoiceState validates and processes an invoice state update.
|
||||||
func updateInvoiceState(invoice *Invoice, hash lntypes.Hash,
|
func updateInvoiceState(invoice *Invoice, hash *lntypes.Hash,
|
||||||
update InvoiceStateUpdateDesc) error {
|
update InvoiceStateUpdateDesc) error {
|
||||||
|
|
||||||
// Returning to open is never allowed from any state.
|
// Returning to open is never allowed from any state.
|
||||||
@@ -1950,9 +2044,14 @@ func updateInvoiceState(invoice *Invoice, hash lntypes.Hash,
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
|
|
||||||
|
// If an invoice-level preimage was supplied, but the InvoiceRef
|
||||||
|
// doesn't specify a hash (e.g. AMP invoices) we fail.
|
||||||
|
case update.Preimage != nil && hash == nil:
|
||||||
|
return ErrUnexpectedInvoicePreimage
|
||||||
|
|
||||||
// Validate the supplied preimage for non-AMP invoices.
|
// Validate the supplied preimage for non-AMP invoices.
|
||||||
case update.Preimage != nil:
|
case update.Preimage != nil:
|
||||||
if update.Preimage.Hash() != hash {
|
if update.Preimage.Hash() != *hash {
|
||||||
return ErrInvoicePreimageMismatch
|
return ErrInvoicePreimageMismatch
|
||||||
}
|
}
|
||||||
invoice.Terms.PaymentPreimage = update.Preimage
|
invoice.Terms.PaymentPreimage = update.Preimage
|
||||||
@@ -2027,10 +2126,25 @@ func updateHtlc(resolveTime time.Time, htlc *InvoiceHTLC,
|
|||||||
// already know the preimage is valid due to checks at
|
// already know the preimage is valid due to checks at
|
||||||
// the invoice level. For AMP HTLCs, verify that the
|
// the invoice level. For AMP HTLCs, verify that the
|
||||||
// per-HTLC preimage-hash pair is valid.
|
// per-HTLC preimage-hash pair is valid.
|
||||||
if setID != nil && !htlc.AMP.Preimage.Matches(htlc.AMP.Hash) {
|
switch {
|
||||||
return fmt.Errorf("AMP preimage mismatch, "+
|
|
||||||
"preimage=%v hash=%v", *htlc.AMP.Preimage,
|
// Non-AMP HTLCs can be settle immediately since we
|
||||||
htlc.AMP.Hash)
|
// already know the preimage is valid due to checks at
|
||||||
|
// the invoice level.
|
||||||
|
case setID == nil:
|
||||||
|
|
||||||
|
// At this popint, the setID is non-nil, meaning this is
|
||||||
|
// an AMP HTLC. We know that htlc.AMP cannot be nil,
|
||||||
|
// otherwise IsInHTLCSet would have returned false.
|
||||||
|
//
|
||||||
|
// Fail if an accepted AMP HTLC has no preimage.
|
||||||
|
case htlc.AMP.Preimage == nil:
|
||||||
|
return ErrHTLCPreimageMissing
|
||||||
|
|
||||||
|
// Fail if the accepted AMP HTLC has an invalid
|
||||||
|
// preimage.
|
||||||
|
case !htlc.AMP.Preimage.Matches(htlc.AMP.Hash):
|
||||||
|
return ErrHTLCPreimageMismatch
|
||||||
}
|
}
|
||||||
|
|
||||||
htlcState = HtlcStateSettled
|
htlcState = HtlcStateSettled
|
||||||
@@ -2059,8 +2173,7 @@ func updateHtlc(resolveTime time.Time, htlc *InvoiceHTLC,
|
|||||||
// We should never find a settled HTLC on an invoice that isn't in
|
// We should never find a settled HTLC on an invoice that isn't in
|
||||||
// ContractSettled.
|
// ContractSettled.
|
||||||
if htlc.State == HtlcStateSettled {
|
if htlc.State == HtlcStateSettled {
|
||||||
return fmt.Errorf("cannot have a settled htlc with "+
|
return ErrHTLCAlreadySettled
|
||||||
"invoice in state %v", invState)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch invState {
|
switch invState {
|
||||||
|
|||||||
@@ -51,4 +51,9 @@ var defaultSetDesc = setDesc{
|
|||||||
SetInit: {}, // I
|
SetInit: {}, // I
|
||||||
SetNodeAnn: {}, // N
|
SetNodeAnn: {}, // N
|
||||||
},
|
},
|
||||||
|
lnwire.AMPOptional: {
|
||||||
|
SetInit: {}, // I
|
||||||
|
SetNodeAnn: {}, // N
|
||||||
|
SetInvoice: {}, // 9
|
||||||
|
},
|
||||||
}
|
}
|
||||||
@@ -58,6 +58,9 @@ var deps = depDesc{
|
|||||||
lnwire.AnchorsOptional: {
|
lnwire.AnchorsOptional: {
|
||||||
lnwire.StaticRemoteKeyOptional: {},
|
lnwire.StaticRemoteKeyOptional: {},
|
||||||
},
|
},
|
||||||
|
lnwire.AMPOptional: {
|
||||||
|
lnwire.PaymentAddrOptional: {},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidateDeps asserts that a feature vector sets all features and their
|
// ValidateDeps asserts that a feature vector sets all features and their
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ func newManager(cfg Config, desc setDesc) (*Manager, error) {
|
|||||||
raw.Unset(lnwire.PaymentAddrRequired)
|
raw.Unset(lnwire.PaymentAddrRequired)
|
||||||
raw.Unset(lnwire.MPPOptional)
|
raw.Unset(lnwire.MPPOptional)
|
||||||
raw.Unset(lnwire.MPPRequired)
|
raw.Unset(lnwire.MPPRequired)
|
||||||
|
raw.Unset(lnwire.AMPOptional)
|
||||||
|
raw.Unset(lnwire.AMPRequired)
|
||||||
}
|
}
|
||||||
if cfg.NoStaticRemoteKey {
|
if cfg.NoStaticRemoteKey {
|
||||||
raw.Unset(lnwire.StaticRemoteKeyOptional)
|
raw.Unset(lnwire.StaticRemoteKeyOptional)
|
||||||
|
|||||||
@@ -119,6 +119,7 @@ func NewPayloadFromReader(r io.Reader) (*Payload, error) {
|
|||||||
amt uint64
|
amt uint64
|
||||||
cltv uint32
|
cltv uint32
|
||||||
mpp = &record.MPP{}
|
mpp = &record.MPP{}
|
||||||
|
amp = &record.AMP{}
|
||||||
)
|
)
|
||||||
|
|
||||||
tlvStream, err := tlv.NewStream(
|
tlvStream, err := tlv.NewStream(
|
||||||
@@ -126,6 +127,7 @@ func NewPayloadFromReader(r io.Reader) (*Payload, error) {
|
|||||||
record.NewLockTimeRecord(&cltv),
|
record.NewLockTimeRecord(&cltv),
|
||||||
record.NewNextHopIDRecord(&cid),
|
record.NewNextHopIDRecord(&cid),
|
||||||
mpp.Record(),
|
mpp.Record(),
|
||||||
|
amp.Record(),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -160,6 +162,12 @@ func NewPayloadFromReader(r io.Reader) (*Payload, error) {
|
|||||||
mpp = nil
|
mpp = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If no AMP field was parsed, set the MPP field on the resulting
|
||||||
|
// payload to nil.
|
||||||
|
if _, ok := parsedTypes[record.AMPOnionType]; !ok {
|
||||||
|
amp = nil
|
||||||
|
}
|
||||||
|
|
||||||
// Filter out the custom records.
|
// Filter out the custom records.
|
||||||
customRecords := NewCustomRecords(parsedTypes)
|
customRecords := NewCustomRecords(parsedTypes)
|
||||||
|
|
||||||
@@ -171,6 +179,7 @@ func NewPayloadFromReader(r io.Reader) (*Payload, error) {
|
|||||||
OutgoingCTLV: cltv,
|
OutgoingCTLV: cltv,
|
||||||
},
|
},
|
||||||
MPP: mpp,
|
MPP: mpp,
|
||||||
|
AMP: amp,
|
||||||
customRecords: customRecords,
|
customRecords: customRecords,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -207,6 +216,7 @@ func ValidateParsedPayloadTypes(parsedTypes tlv.TypeMap,
|
|||||||
_, hasLockTime := parsedTypes[record.LockTimeOnionType]
|
_, hasLockTime := parsedTypes[record.LockTimeOnionType]
|
||||||
_, hasNextHop := parsedTypes[record.NextHopOnionType]
|
_, hasNextHop := parsedTypes[record.NextHopOnionType]
|
||||||
_, hasMPP := parsedTypes[record.MPPOnionType]
|
_, hasMPP := parsedTypes[record.MPPOnionType]
|
||||||
|
_, hasAMP := parsedTypes[record.AMPOnionType]
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
|
|
||||||
@@ -243,6 +253,14 @@ func ValidateParsedPayloadTypes(parsedTypes tlv.TypeMap,
|
|||||||
Violation: IncludedViolation,
|
Violation: IncludedViolation,
|
||||||
FinalHop: isFinalHop,
|
FinalHop: isFinalHop,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Intermediate nodes should never receive AMP fields.
|
||||||
|
case !isFinalHop && hasAMP:
|
||||||
|
return ErrInvalidPayload{
|
||||||
|
Type: record.AMPOnionType,
|
||||||
|
Violation: IncludedViolation,
|
||||||
|
FinalHop: isFinalHop,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -8,14 +8,18 @@ import (
|
|||||||
"github.com/lightningnetwork/lnd/htlcswitch/hop"
|
"github.com/lightningnetwork/lnd/htlcswitch/hop"
|
||||||
"github.com/lightningnetwork/lnd/lnwire"
|
"github.com/lightningnetwork/lnd/lnwire"
|
||||||
"github.com/lightningnetwork/lnd/record"
|
"github.com/lightningnetwork/lnd/record"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const testUnknownRequiredType = 0x10
|
||||||
|
|
||||||
type decodePayloadTest struct {
|
type decodePayloadTest struct {
|
||||||
name string
|
name string
|
||||||
payload []byte
|
payload []byte
|
||||||
expErr error
|
expErr error
|
||||||
expCustomRecords map[uint64][]byte
|
expCustomRecords map[uint64][]byte
|
||||||
shouldHaveMPP bool
|
shouldHaveMPP bool
|
||||||
|
shouldHaveAMP bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var decodePayloadTests = []decodePayloadTest{
|
var decodePayloadTests = []decodePayloadTest{
|
||||||
@@ -81,21 +85,26 @@ var decodePayloadTests = []decodePayloadTest{
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "required type after omitted hop id",
|
name: "required type after omitted hop id",
|
||||||
payload: []byte{0x02, 0x00, 0x04, 0x00, 0x0a, 0x00},
|
payload: []byte{
|
||||||
|
0x02, 0x00, 0x04, 0x00,
|
||||||
|
testUnknownRequiredType, 0x00,
|
||||||
|
},
|
||||||
expErr: hop.ErrInvalidPayload{
|
expErr: hop.ErrInvalidPayload{
|
||||||
Type: 10,
|
Type: testUnknownRequiredType,
|
||||||
Violation: hop.RequiredViolation,
|
Violation: hop.RequiredViolation,
|
||||||
FinalHop: true,
|
FinalHop: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "required type after included hop id",
|
name: "required type after included hop id",
|
||||||
payload: []byte{0x02, 0x00, 0x04, 0x00, 0x06, 0x08, 0x01, 0x00,
|
payload: []byte{
|
||||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00,
|
0x02, 0x00, 0x04, 0x00, 0x06, 0x08, 0x01, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
testUnknownRequiredType, 0x00,
|
||||||
},
|
},
|
||||||
expErr: hop.ErrInvalidPayload{
|
expErr: hop.ErrInvalidPayload{
|
||||||
Type: 10,
|
Type: testUnknownRequiredType,
|
||||||
Violation: hop.RequiredViolation,
|
Violation: hop.RequiredViolation,
|
||||||
FinalHop: false,
|
FinalHop: false,
|
||||||
},
|
},
|
||||||
@@ -176,6 +185,37 @@ var decodePayloadTests = []decodePayloadTest{
|
|||||||
FinalHop: false,
|
FinalHop: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "intermediate hop with amp",
|
||||||
|
payload: []byte{
|
||||||
|
// amount
|
||||||
|
0x02, 0x00,
|
||||||
|
// cltv
|
||||||
|
0x04, 0x00,
|
||||||
|
// next hop id
|
||||||
|
0x06, 0x08,
|
||||||
|
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
// amp
|
||||||
|
0x0e, 0x41,
|
||||||
|
// amp.root_share
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
// amp.set_id
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
// amp.child_index
|
||||||
|
0x09,
|
||||||
|
},
|
||||||
|
expErr: hop.ErrInvalidPayload{
|
||||||
|
Type: record.AMPOnionType,
|
||||||
|
Violation: hop.IncludedViolation,
|
||||||
|
FinalHop: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "final hop with mpp",
|
name: "final hop with mpp",
|
||||||
payload: []byte{
|
payload: []byte{
|
||||||
@@ -194,6 +234,30 @@ var decodePayloadTests = []decodePayloadTest{
|
|||||||
expErr: nil,
|
expErr: nil,
|
||||||
shouldHaveMPP: true,
|
shouldHaveMPP: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "final hop with amp",
|
||||||
|
payload: []byte{
|
||||||
|
// amount
|
||||||
|
0x02, 0x00,
|
||||||
|
// cltv
|
||||||
|
0x04, 0x00,
|
||||||
|
// amp
|
||||||
|
0x0e, 0x41,
|
||||||
|
// amp.root_share
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
// amp.set_id
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
// amp.child_index
|
||||||
|
0x09,
|
||||||
|
},
|
||||||
|
shouldHaveAMP: true,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDecodeHopPayloadRecordValidation asserts that parsing the payloads in the
|
// TestDecodeHopPayloadRecordValidation asserts that parsing the payloads in the
|
||||||
@@ -216,6 +280,20 @@ func testDecodeHopPayloadValidation(t *testing.T, test decodePayloadTest) {
|
|||||||
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
|
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
|
||||||
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
|
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
testRootShare = [32]byte{
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12,
|
||||||
|
}
|
||||||
|
testSetID = [32]byte{
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
|
||||||
|
}
|
||||||
|
testChildIndex = uint32(9)
|
||||||
)
|
)
|
||||||
|
|
||||||
p, err := hop.NewPayloadFromReader(bytes.NewReader(test.payload))
|
p, err := hop.NewPayloadFromReader(bytes.NewReader(test.payload))
|
||||||
@@ -242,6 +320,17 @@ func testDecodeHopPayloadValidation(t *testing.T, test decodePayloadTest) {
|
|||||||
t.Fatalf("unexpected MPP payload")
|
t.Fatalf("unexpected MPP payload")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if test.shouldHaveAMP {
|
||||||
|
if p.AMP == nil {
|
||||||
|
t.Fatalf("payload should have AMP record")
|
||||||
|
}
|
||||||
|
require.Equal(t, testRootShare, p.AMP.RootShare())
|
||||||
|
require.Equal(t, testSetID, p.AMP.SetID())
|
||||||
|
require.Equal(t, testChildIndex, p.AMP.ChildIndex())
|
||||||
|
} else if p.AMP != nil {
|
||||||
|
t.Fatalf("unexpected AMP payload")
|
||||||
|
}
|
||||||
|
|
||||||
// Convert expected nil map to empty map, because we always expect an
|
// Convert expected nil map to empty map, because we always expect an
|
||||||
// initiated map from the payload.
|
// initiated map from the payload.
|
||||||
expCustomRecords := make(record.CustomSet)
|
expCustomRecords := make(record.CustomSet)
|
||||||
|
|||||||
+117
-9
@@ -377,7 +377,8 @@ func (i *InvoiceRegistry) invoiceEventLoop() {
|
|||||||
func (i *InvoiceRegistry) dispatchToSingleClients(event *invoiceEvent) {
|
func (i *InvoiceRegistry) dispatchToSingleClients(event *invoiceEvent) {
|
||||||
// Dispatch to single invoice subscribers.
|
// Dispatch to single invoice subscribers.
|
||||||
for _, client := range i.singleNotificationClients {
|
for _, client := range i.singleNotificationClients {
|
||||||
if client.invoiceRef.PayHash() != event.hash {
|
payHash := client.invoiceRef.PayHash()
|
||||||
|
if payHash == nil || *payHash != event.hash {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -524,8 +525,13 @@ func (i *InvoiceRegistry) deliverSingleBacklogEvents(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
payHash := client.invoiceRef.PayHash()
|
||||||
|
if payHash == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
err = client.notify(&invoiceEvent{
|
err = client.notify(&invoiceEvent{
|
||||||
hash: client.invoiceRef.PayHash(),
|
hash: *payHash,
|
||||||
invoice: &invoice,
|
invoice: &invoice,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -775,6 +781,67 @@ func (i *InvoiceRegistry) processKeySend(ctx invoiceUpdateCtx) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// processAMP just-in-time inserts an invoice if this htlc is a keysend
|
||||||
|
// htlc.
|
||||||
|
func (i *InvoiceRegistry) processAMP(ctx invoiceUpdateCtx) error {
|
||||||
|
// AMP payments MUST also include an MPP record.
|
||||||
|
if ctx.mpp == nil {
|
||||||
|
return errors.New("no MPP record for AMP")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create an invoice for the total amount expected, provided in the MPP
|
||||||
|
// record.
|
||||||
|
amt := ctx.mpp.TotalMsat()
|
||||||
|
|
||||||
|
// Set the TLV and MPP optional features on the invoice. We'll also make
|
||||||
|
// the AMP features required so that it can't be paid by legacy or MPP
|
||||||
|
// htlcs.
|
||||||
|
rawFeatures := lnwire.NewRawFeatureVector(
|
||||||
|
lnwire.TLVOnionPayloadOptional,
|
||||||
|
lnwire.PaymentAddrOptional,
|
||||||
|
lnwire.AMPRequired,
|
||||||
|
)
|
||||||
|
features := lnwire.NewFeatureVector(rawFeatures, lnwire.Features)
|
||||||
|
|
||||||
|
// Use the minimum block delta that we require for settling htlcs.
|
||||||
|
finalCltvDelta := i.cfg.FinalCltvRejectDelta
|
||||||
|
|
||||||
|
// Pre-check expiry here to prevent inserting an invoice that will not
|
||||||
|
// be settled.
|
||||||
|
if ctx.expiry < uint32(ctx.currentHeight+finalCltvDelta) {
|
||||||
|
return errors.New("final expiry too soon")
|
||||||
|
}
|
||||||
|
|
||||||
|
// We'll use the sender-generated payment address provided in the HTLC
|
||||||
|
// to create our AMP invoice.
|
||||||
|
payAddr := ctx.mpp.PaymentAddr()
|
||||||
|
|
||||||
|
// Create placeholder invoice.
|
||||||
|
invoice := &channeldb.Invoice{
|
||||||
|
CreationDate: i.cfg.Clock.Now(),
|
||||||
|
Terms: channeldb.ContractTerm{
|
||||||
|
FinalCltvDelta: finalCltvDelta,
|
||||||
|
Value: amt,
|
||||||
|
PaymentPreimage: nil,
|
||||||
|
PaymentAddr: payAddr,
|
||||||
|
Features: features,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert invoice into database. Ignore duplicates payment hashes and
|
||||||
|
// payment addrs, this may be a replay or a different HTLC for the AMP
|
||||||
|
// invoice.
|
||||||
|
_, err := i.AddInvoice(invoice, ctx.hash)
|
||||||
|
switch {
|
||||||
|
case err == channeldb.ErrDuplicateInvoice:
|
||||||
|
return nil
|
||||||
|
case err == channeldb.ErrDuplicatePayAddr:
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// NotifyExitHopHtlc attempts to mark an invoice as settled. The return value
|
// NotifyExitHopHtlc attempts to mark an invoice as settled. The return value
|
||||||
// describes how the htlc should be resolved.
|
// describes how the htlc should be resolved.
|
||||||
//
|
//
|
||||||
@@ -813,13 +880,24 @@ func (i *InvoiceRegistry) NotifyExitHopHtlc(rHash lntypes.Hash,
|
|||||||
// AddInvoice obtains its own lock. This is no problem, because the
|
// AddInvoice obtains its own lock. This is no problem, because the
|
||||||
// operation is idempotent.
|
// operation is idempotent.
|
||||||
if i.cfg.AcceptKeySend {
|
if i.cfg.AcceptKeySend {
|
||||||
err := i.processKeySend(ctx)
|
if ctx.amp != nil {
|
||||||
if err != nil {
|
err := i.processAMP(ctx)
|
||||||
ctx.log(fmt.Sprintf("keysend error: %v", err))
|
if err != nil {
|
||||||
|
ctx.log(fmt.Sprintf("amp error: %v", err))
|
||||||
|
|
||||||
return NewFailResolution(
|
return NewFailResolution(
|
||||||
circuitKey, currentHeight, ResultKeySendError,
|
circuitKey, currentHeight, ResultAmpError,
|
||||||
), nil
|
), nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err := i.processKeySend(ctx)
|
||||||
|
if err != nil {
|
||||||
|
ctx.log(fmt.Sprintf("keysend error: %v", err))
|
||||||
|
|
||||||
|
return NewFailResolution(
|
||||||
|
circuitKey, currentHeight, ResultKeySendError,
|
||||||
|
), nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -926,6 +1004,31 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
|
|||||||
"outcome: %v, at accept height: %v",
|
"outcome: %v, at accept height: %v",
|
||||||
res.Outcome, res.AcceptHeight))
|
res.Outcome, res.AcceptHeight))
|
||||||
|
|
||||||
|
// Some failures apply to the entire HTLC set. Break here if
|
||||||
|
// this isn't one of them.
|
||||||
|
if !res.Outcome.IsSetFailure() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also cancel any HTLCs in the HTLC set that are also in the
|
||||||
|
// canceled state with the same failure result.
|
||||||
|
setID := ctx.setID()
|
||||||
|
for key, htlc := range invoice.Htlcs {
|
||||||
|
if htlc.State != channeldb.HtlcStateCanceled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !htlc.IsInHTLCSet(setID) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
htlcFailResolution := NewFailResolution(
|
||||||
|
key, int32(htlc.AcceptHeight), res.Outcome,
|
||||||
|
)
|
||||||
|
|
||||||
|
i.notifyHodlSubscribers(htlcFailResolution)
|
||||||
|
}
|
||||||
|
|
||||||
// If the htlc was settled, we will settle any previously accepted
|
// If the htlc was settled, we will settle any previously accepted
|
||||||
// htlcs and notify our peer to settle them.
|
// htlcs and notify our peer to settle them.
|
||||||
case *HtlcSettleResolution:
|
case *HtlcSettleResolution:
|
||||||
@@ -941,13 +1044,18 @@ func (i *InvoiceRegistry) notifyExitHopHtlcLocked(
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
preimage := res.Preimage
|
||||||
|
if htlc.AMP != nil && htlc.AMP.Preimage != nil {
|
||||||
|
preimage = *htlc.AMP.Preimage
|
||||||
|
}
|
||||||
|
|
||||||
// Notify subscribers that the htlcs should be settled
|
// Notify subscribers that the htlcs should be settled
|
||||||
// with our peer. Note that the outcome of the
|
// with our peer. Note that the outcome of the
|
||||||
// resolution is set based on the outcome of the single
|
// resolution is set based on the outcome of the single
|
||||||
// htlc that we just settled, so may not be accurate
|
// htlc that we just settled, so may not be accurate
|
||||||
// for all htlcs.
|
// for all htlcs.
|
||||||
htlcSettleResolution := NewSettleResolution(
|
htlcSettleResolution := NewSettleResolution(
|
||||||
res.Preimage, key,
|
preimage, key,
|
||||||
int32(htlc.AcceptHeight), res.Outcome,
|
int32(htlc.AcceptHeight), res.Outcome,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+315
-153
@@ -1,10 +1,12 @@
|
|||||||
package invoices
|
package invoices
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
"math"
|
"math"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/lightningnetwork/lnd/amp"
|
||||||
"github.com/lightningnetwork/lnd/channeldb"
|
"github.com/lightningnetwork/lnd/channeldb"
|
||||||
"github.com/lightningnetwork/lnd/clock"
|
"github.com/lightningnetwork/lnd/clock"
|
||||||
"github.com/lightningnetwork/lnd/lntypes"
|
"github.com/lightningnetwork/lnd/lntypes"
|
||||||
@@ -29,9 +31,7 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer subscription.Cancel()
|
defer subscription.Cancel()
|
||||||
|
|
||||||
if subscription.invoiceRef.PayHash() != testInvoicePaymentHash {
|
require.Equal(t, subscription.invoiceRef.PayHash(), &testInvoicePaymentHash)
|
||||||
t.Fatalf("expected subscription for provided hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the invoice.
|
// Add the invoice.
|
||||||
addIdx, err := ctx.registry.AddInvoice(testInvoice, testInvoicePaymentHash)
|
addIdx, err := ctx.registry.AddInvoice(testInvoice, testInvoicePaymentHash)
|
||||||
@@ -77,19 +77,11 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
failResolution := checkFailResolution(
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
t, resolution, ResultExpiryTooSoon,
|
||||||
resolution)
|
)
|
||||||
}
|
require.Equal(t, testCurrentHeight, failResolution.AcceptHeight)
|
||||||
if failResolution.AcceptHeight != testCurrentHeight {
|
|
||||||
t.Fatalf("expected acceptHeight %v, but got %v",
|
|
||||||
testCurrentHeight, failResolution.AcceptHeight)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultExpiryTooSoon {
|
|
||||||
t.Fatalf("expected expiry too soon, got: %v",
|
|
||||||
failResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Settle invoice with a slightly higher amount.
|
// Settle invoice with a slightly higher amount.
|
||||||
amtPaid := lnwire.MilliSatoshi(100500)
|
amtPaid := lnwire.MilliSatoshi(100500)
|
||||||
@@ -101,15 +93,11 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
settleResolution, ok := resolution.(*HtlcSettleResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
settleResolution := checkSettleResolution(
|
||||||
t.Fatalf("expected settle resolution, got: %T",
|
t, resolution, testInvoicePreimage,
|
||||||
resolution)
|
)
|
||||||
}
|
require.Equal(t, ResultSettled, settleResolution.Outcome)
|
||||||
if settleResolution.Outcome != ResultSettled {
|
|
||||||
t.Fatalf("expected settled, got: %v",
|
|
||||||
settleResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// We expect the settled state to be sent to the single invoice
|
// We expect the settled state to be sent to the single invoice
|
||||||
// subscriber.
|
// subscriber.
|
||||||
@@ -146,15 +134,11 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
||||||
}
|
}
|
||||||
settleResolution, ok = resolution.(*HtlcSettleResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
settleResolution = checkSettleResolution(
|
||||||
t.Fatalf("expected settle resolution, got: %T",
|
t, resolution, testInvoicePreimage,
|
||||||
resolution)
|
)
|
||||||
}
|
require.Equal(t, ResultReplayToSettled, settleResolution.Outcome)
|
||||||
if settleResolution.Outcome != ResultReplayToSettled {
|
|
||||||
t.Fatalf("expected replay settled, got: %v",
|
|
||||||
settleResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to settle again with a new higher-valued htlc. This payment
|
// Try to settle again with a new higher-valued htlc. This payment
|
||||||
// should also be accepted, to prevent any change in behaviour for a
|
// should also be accepted, to prevent any change in behaviour for a
|
||||||
@@ -166,15 +150,11 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
||||||
}
|
}
|
||||||
settleResolution, ok = resolution.(*HtlcSettleResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
settleResolution = checkSettleResolution(
|
||||||
t.Fatalf("expected settle resolution, got: %T",
|
t, resolution, testInvoicePreimage,
|
||||||
resolution)
|
)
|
||||||
}
|
require.Equal(t, ResultDuplicateToSettled, settleResolution.Outcome)
|
||||||
if settleResolution.Outcome != ResultDuplicateToSettled {
|
|
||||||
t.Fatalf("expected duplicate settled, got: %v",
|
|
||||||
settleResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to settle again with a lower amount. This should fail just as it
|
// Try to settle again with a lower amount. This should fail just as it
|
||||||
// would have failed if it were the first payment.
|
// would have failed if it were the first payment.
|
||||||
@@ -185,15 +165,8 @@ func TestSettleInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
|
||||||
}
|
}
|
||||||
failResolution, ok = resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
checkFailResolution(t, resolution, ResultAmountTooLow)
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultAmountTooLow {
|
|
||||||
t.Fatalf("expected amount too low, got: %v",
|
|
||||||
failResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that settled amount is equal to the sum of values of the htlcs
|
// Check that settled amount is equal to the sum of values of the htlcs
|
||||||
// 0 and 1.
|
// 0 and 1.
|
||||||
@@ -244,9 +217,7 @@ func testCancelInvoice(t *testing.T, gc bool) {
|
|||||||
}
|
}
|
||||||
defer subscription.Cancel()
|
defer subscription.Cancel()
|
||||||
|
|
||||||
if subscription.invoiceRef.PayHash() != testInvoicePaymentHash {
|
require.Equal(t, subscription.invoiceRef.PayHash(), &testInvoicePaymentHash)
|
||||||
t.Fatalf("expected subscription for provided hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the invoice.
|
// Add the invoice.
|
||||||
amt := lnwire.MilliSatoshi(100000)
|
amt := lnwire.MilliSatoshi(100000)
|
||||||
@@ -333,27 +304,23 @@ func testCancelInvoice(t *testing.T, gc bool) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("expected settlement of a canceled invoice to succeed")
|
t.Fatal("expected settlement of a canceled invoice to succeed")
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
if failResolution.AcceptHeight != testCurrentHeight {
|
|
||||||
t.Fatalf("expected acceptHeight %v, but got %v",
|
|
||||||
testCurrentHeight, failResolution.AcceptHeight)
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the invoice has been deleted (or not present) then we expect the
|
// If the invoice has been deleted (or not present) then we expect the
|
||||||
// outcome to be ResultInvoiceNotFound instead of when the invoice is
|
// outcome to be ResultInvoiceNotFound instead of when the invoice is
|
||||||
// in our database in which case we expect ResultInvoiceAlreadyCanceled.
|
// in our database in which case we expect ResultInvoiceAlreadyCanceled.
|
||||||
|
var failResolution *HtlcFailResolution
|
||||||
if gc {
|
if gc {
|
||||||
require.Equal(t, failResolution.Outcome, ResultInvoiceNotFound)
|
failResolution = checkFailResolution(
|
||||||
|
t, resolution, ResultInvoiceNotFound,
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
require.Equal(t,
|
failResolution = checkFailResolution(
|
||||||
failResolution.Outcome,
|
t, resolution, ResultInvoiceAlreadyCanceled,
|
||||||
ResultInvoiceAlreadyCanceled,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
require.Equal(t, testCurrentHeight, failResolution.AcceptHeight)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestCancelInvoice tests cancelation of an invoice and related notifications.
|
// TestCancelInvoice tests cancelation of an invoice and related notifications.
|
||||||
@@ -404,9 +371,7 @@ func TestSettleHoldInvoice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer subscription.Cancel()
|
defer subscription.Cancel()
|
||||||
|
|
||||||
if subscription.invoiceRef.PayHash() != testInvoicePaymentHash {
|
require.Equal(t, subscription.invoiceRef.PayHash(), &testInvoicePaymentHash)
|
||||||
t.Fatalf("expected subscription for provided hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the invoice.
|
// Add the invoice.
|
||||||
_, err = registry.AddInvoice(testHodlInvoice, testInvoicePaymentHash)
|
_, err = registry.AddInvoice(testHodlInvoice, testInvoicePaymentHash)
|
||||||
@@ -480,15 +445,8 @@ func TestSettleHoldInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("expected settle to succeed but got %v", err)
|
t.Fatalf("expected settle to succeed but got %v", err)
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
checkFailResolution(t, resolution, ResultExpiryTooSoon)
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultExpiryTooSoon {
|
|
||||||
t.Fatalf("expected expiry too soon, got: %v",
|
|
||||||
failResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// We expect the accepted state to be sent to the single invoice
|
// We expect the accepted state to be sent to the single invoice
|
||||||
// subscriber. For all invoice subscribers, we don't expect an update.
|
// subscriber. For all invoice subscribers, we don't expect an update.
|
||||||
@@ -509,22 +467,12 @@ func TestSettleHoldInvoice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
htlcResolution := (<-hodlChan).(HtlcResolution)
|
htlcResolution := (<-hodlChan).(HtlcResolution)
|
||||||
settleResolution, ok := htlcResolution.(*HtlcSettleResolution)
|
require.NotNil(t, htlcResolution)
|
||||||
if !ok {
|
settleResolution := checkSettleResolution(
|
||||||
t.Fatalf("expected settle resolution, got: %T",
|
t, htlcResolution, testInvoicePreimage,
|
||||||
htlcResolution)
|
)
|
||||||
}
|
require.Equal(t, testCurrentHeight, settleResolution.AcceptHeight)
|
||||||
if settleResolution.Preimage != testInvoicePreimage {
|
require.Equal(t, ResultSettled, settleResolution.Outcome)
|
||||||
t.Fatal("unexpected preimage in hodl resolution")
|
|
||||||
}
|
|
||||||
if settleResolution.AcceptHeight != testCurrentHeight {
|
|
||||||
t.Fatalf("expected acceptHeight %v, but got %v",
|
|
||||||
testCurrentHeight, settleResolution.AcceptHeight)
|
|
||||||
}
|
|
||||||
if settleResolution.Outcome != ResultSettled {
|
|
||||||
t.Fatalf("expected result settled, got: %v",
|
|
||||||
settleResolution.Outcome)
|
|
||||||
}
|
|
||||||
|
|
||||||
// We expect a settled notification to be sent out for both all and
|
// We expect a settled notification to be sent out for both all and
|
||||||
// single invoice subscribers.
|
// single invoice subscribers.
|
||||||
@@ -610,11 +558,8 @@ func TestCancelHoldInvoice(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
htlcResolution := (<-hodlChan).(HtlcResolution)
|
htlcResolution := (<-hodlChan).(HtlcResolution)
|
||||||
_, ok := htlcResolution.(*HtlcFailResolution)
|
require.NotNil(t, htlcResolution)
|
||||||
if !ok {
|
checkFailResolution(t, htlcResolution, ResultCanceled)
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
htlcResolution)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Offering the same htlc again at a higher height should still result
|
// Offering the same htlc again at a higher height should still result
|
||||||
// in a rejection. The accept height is expected to be the original
|
// in a rejection. The accept height is expected to be the original
|
||||||
@@ -626,19 +571,11 @@ func TestCancelHoldInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("expected settle to succeed but got %v", err)
|
t.Fatalf("expected settle to succeed but got %v", err)
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
failResolution := checkFailResolution(
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
t, resolution, ResultReplayToCanceled,
|
||||||
resolution)
|
)
|
||||||
}
|
require.Equal(t, testCurrentHeight, failResolution.AcceptHeight)
|
||||||
if failResolution.AcceptHeight != testCurrentHeight {
|
|
||||||
t.Fatalf("expected acceptHeight %v, but got %v",
|
|
||||||
testCurrentHeight, failResolution.AcceptHeight)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultReplayToCanceled {
|
|
||||||
t.Fatalf("expected replay to canceled, got %v",
|
|
||||||
failResolution.Outcome)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestUnknownInvoice tests that invoice registry returns an error when the
|
// TestUnknownInvoice tests that invoice registry returns an error when the
|
||||||
@@ -661,15 +598,8 @@ func TestUnknownInvoice(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("unexpected error")
|
t.Fatal("unexpected error")
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
checkFailResolution(t, resolution, ResultInvoiceNotFound)
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultInvoiceNotFound {
|
|
||||||
t.Fatalf("expected ResultInvoiceNotFound, got: %v",
|
|
||||||
failResolution.Outcome)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestKeySend tests receiving a spontaneous payment with and without keysend
|
// TestKeySend tests receiving a spontaneous payment with and without keysend
|
||||||
@@ -721,18 +651,12 @@ func testKeySend(t *testing.T, keySendEnabled bool) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
failResolution, ok := resolution.(*HtlcFailResolution)
|
require.NotNil(t, resolution)
|
||||||
if !ok {
|
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch {
|
if !keySendEnabled {
|
||||||
case !keySendEnabled && failResolution.Outcome != ResultInvoiceNotFound:
|
checkFailResolution(t, resolution, ResultInvoiceNotFound)
|
||||||
t.Fatal("expected invoice not found outcome")
|
} else {
|
||||||
|
checkFailResolution(t, resolution, ResultKeySendError)
|
||||||
case keySendEnabled && failResolution.Outcome != ResultKeySendError:
|
|
||||||
t.Fatal("expected keysend error")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to settle invoice with a valid keysend htlc.
|
// Try to settle invoice with a valid keysend htlc.
|
||||||
@@ -752,23 +676,10 @@ func testKeySend(t *testing.T, keySendEnabled bool) {
|
|||||||
|
|
||||||
// Expect a cancel resolution if keysend is disabled.
|
// Expect a cancel resolution if keysend is disabled.
|
||||||
if !keySendEnabled {
|
if !keySendEnabled {
|
||||||
failResolution, ok = resolution.(*HtlcFailResolution)
|
checkFailResolution(t, resolution, ResultInvoiceNotFound)
|
||||||
if !ok {
|
|
||||||
t.Fatalf("expected fail resolution, got: %T",
|
|
||||||
resolution)
|
|
||||||
}
|
|
||||||
if failResolution.Outcome != ResultInvoiceNotFound {
|
|
||||||
t.Fatal("expected keysend payment not to be accepted")
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
checkResolution := func(res HtlcResolution, pimg lntypes.Preimage) {
|
|
||||||
// Otherwise we expect no error and a settle res for the htlc.
|
|
||||||
settleResolution, ok := res.(*HtlcSettleResolution)
|
|
||||||
require.True(t, ok)
|
|
||||||
require.Equal(t, settleResolution.Preimage, pimg)
|
|
||||||
}
|
|
||||||
checkSubscription := func() {
|
checkSubscription := func() {
|
||||||
// We expect a new invoice notification to be sent out.
|
// We expect a new invoice notification to be sent out.
|
||||||
newInvoice := <-allSubscriptions.NewInvoices
|
newInvoice := <-allSubscriptions.NewInvoices
|
||||||
@@ -779,7 +690,7 @@ func testKeySend(t *testing.T, keySendEnabled bool) {
|
|||||||
require.Equal(t, settledInvoice.State, channeldb.ContractSettled)
|
require.Equal(t, settledInvoice.State, channeldb.ContractSettled)
|
||||||
}
|
}
|
||||||
|
|
||||||
checkResolution(resolution, preimage)
|
checkSettleResolution(t, resolution, preimage)
|
||||||
checkSubscription()
|
checkSubscription()
|
||||||
|
|
||||||
// Replay the same keysend payment. We expect an identical resolution,
|
// Replay the same keysend payment. We expect an identical resolution,
|
||||||
@@ -789,7 +700,7 @@ func testKeySend(t *testing.T, keySendEnabled bool) {
|
|||||||
testCurrentHeight, getCircuitKey(10), hodlChan, keySendPayload,
|
testCurrentHeight, getCircuitKey(10), hodlChan, keySendPayload,
|
||||||
)
|
)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
checkResolution(resolution, preimage)
|
checkSettleResolution(t, resolution, preimage)
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case <-allSubscriptions.NewInvoices:
|
case <-allSubscriptions.NewInvoices:
|
||||||
@@ -814,7 +725,7 @@ func testKeySend(t *testing.T, keySendEnabled bool) {
|
|||||||
)
|
)
|
||||||
require.Nil(t, err)
|
require.Nil(t, err)
|
||||||
|
|
||||||
checkResolution(resolution, preimage2)
|
checkSettleResolution(t, resolution, preimage2)
|
||||||
checkSubscription()
|
checkSubscription()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1211,7 +1122,7 @@ func TestSettleInvoicePaymentAddrRequired(t *testing.T) {
|
|||||||
defer subscription.Cancel()
|
defer subscription.Cancel()
|
||||||
|
|
||||||
require.Equal(
|
require.Equal(
|
||||||
t, subscription.invoiceRef.PayHash(), testInvoicePaymentHash,
|
t, subscription.invoiceRef.PayHash(), &testInvoicePaymentHash,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Add the invoice, which requires the MPP payload to always be
|
// Add the invoice, which requires the MPP payload to always be
|
||||||
@@ -1287,7 +1198,7 @@ func TestSettleInvoicePaymentAddrRequiredOptionalGrace(t *testing.T) {
|
|||||||
defer subscription.Cancel()
|
defer subscription.Cancel()
|
||||||
|
|
||||||
require.Equal(
|
require.Equal(
|
||||||
t, subscription.invoiceRef.PayHash(), testInvoicePaymentHash,
|
t, subscription.invoiceRef.PayHash(), &testInvoicePaymentHash,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Add the invoice, which requires the MPP payload to always be
|
// Add the invoice, which requires the MPP payload to always be
|
||||||
@@ -1364,3 +1275,254 @@ func TestSettleInvoicePaymentAddrRequiredOptionalGrace(t *testing.T) {
|
|||||||
t.Fatal("no update received")
|
t.Fatal("no update received")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestAMPWithoutMPPPayload asserts that we correctly reject an AMP HTLC that
|
||||||
|
// does not include an MPP record.
|
||||||
|
func TestAMPWithoutMPPPayload(t *testing.T) {
|
||||||
|
defer timeout()()
|
||||||
|
|
||||||
|
ctx := newTestContext(t)
|
||||||
|
defer ctx.cleanup()
|
||||||
|
|
||||||
|
ctx.registry.cfg.AcceptKeySend = true
|
||||||
|
|
||||||
|
const (
|
||||||
|
shardAmt = lnwire.MilliSatoshi(10)
|
||||||
|
expiry = uint32(testCurrentHeight + 20)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Create payload with missing MPP field.
|
||||||
|
payload := &mockPayload{
|
||||||
|
amp: record.NewAMP([32]byte{}, [32]byte{}, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
hodlChan := make(chan interface{}, 1)
|
||||||
|
resolution, err := ctx.registry.NotifyExitHopHtlc(
|
||||||
|
lntypes.Hash{}, shardAmt, expiry,
|
||||||
|
testCurrentHeight, getCircuitKey(uint64(10)), hodlChan,
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// We should receive the ResultAmpError failure.
|
||||||
|
require.NotNil(t, resolution)
|
||||||
|
checkFailResolution(t, resolution, ResultAmpError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSpontaneousAmpPayment tests receiving a spontaneous AMP payment with both
|
||||||
|
// valid and invalid reconstructions.
|
||||||
|
func TestSpontaneousAmpPayment(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
keySendEnabled bool
|
||||||
|
failReconstruction bool
|
||||||
|
numShards int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "enabled valid one shard",
|
||||||
|
keySendEnabled: true,
|
||||||
|
failReconstruction: false,
|
||||||
|
numShards: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "enabled valid multiple shards",
|
||||||
|
keySendEnabled: true,
|
||||||
|
failReconstruction: false,
|
||||||
|
numShards: 3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "enabled invalid one shard",
|
||||||
|
keySendEnabled: true,
|
||||||
|
failReconstruction: true,
|
||||||
|
numShards: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "enabled invalid multiple shards",
|
||||||
|
keySendEnabled: true,
|
||||||
|
failReconstruction: true,
|
||||||
|
numShards: 3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "disabled valid multiple shards",
|
||||||
|
keySendEnabled: false,
|
||||||
|
failReconstruction: false,
|
||||||
|
numShards: 3,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
test := test
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
testSpontaneousAmpPayment(
|
||||||
|
t, test.keySendEnabled, test.failReconstruction,
|
||||||
|
test.numShards,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testSpontaneousAmpPayment runs a specific spontaneous AMP test case.
|
||||||
|
func testSpontaneousAmpPayment(
|
||||||
|
t *testing.T, keySendEnabled, failReconstruction bool, numShards int) {
|
||||||
|
|
||||||
|
defer timeout()()
|
||||||
|
|
||||||
|
ctx := newTestContext(t)
|
||||||
|
defer ctx.cleanup()
|
||||||
|
|
||||||
|
ctx.registry.cfg.AcceptKeySend = keySendEnabled
|
||||||
|
|
||||||
|
allSubscriptions, err := ctx.registry.SubscribeNotifications(0, 0)
|
||||||
|
require.Nil(t, err)
|
||||||
|
defer allSubscriptions.Cancel()
|
||||||
|
|
||||||
|
const (
|
||||||
|
totalAmt = lnwire.MilliSatoshi(360)
|
||||||
|
expiry = uint32(testCurrentHeight + 20)
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
shardAmt = totalAmt / lnwire.MilliSatoshi(numShards)
|
||||||
|
payAddr [32]byte
|
||||||
|
setID [32]byte
|
||||||
|
)
|
||||||
|
_, err = rand.Read(payAddr[:])
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = rand.Read(setID[:])
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
var sharer amp.Sharer
|
||||||
|
sharer, err = amp.NewSeedSharer()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Asserts that a new invoice is published on the NewInvoices channel.
|
||||||
|
checkOpenSubscription := func() {
|
||||||
|
t.Helper()
|
||||||
|
newInvoice := <-allSubscriptions.NewInvoices
|
||||||
|
require.Equal(t, newInvoice.State, channeldb.ContractOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asserts that a settled invoice is published on the SettledInvoices
|
||||||
|
// channel.
|
||||||
|
checkSettleSubscription := func() {
|
||||||
|
t.Helper()
|
||||||
|
settledInvoice := <-allSubscriptions.SettledInvoices
|
||||||
|
require.Equal(t, settledInvoice.State, channeldb.ContractSettled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asserts that no invoice is published on the SettledInvoices channel
|
||||||
|
// w/in two seconds.
|
||||||
|
checkNoSettleSubscription := func() {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case <-allSubscriptions.SettledInvoices:
|
||||||
|
t.Fatal("no settle ntfn expected")
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record the hodl channels of all HTLCs but the last one, which
|
||||||
|
// received its resolution directly from NotifyExistHopHtlc.
|
||||||
|
hodlChans := make(map[lntypes.Preimage]chan interface{})
|
||||||
|
for i := 0; i < numShards; i++ {
|
||||||
|
isFinalShard := i == numShards-1
|
||||||
|
|
||||||
|
hodlChan := make(chan interface{}, 1)
|
||||||
|
|
||||||
|
var child *amp.Child
|
||||||
|
if !isFinalShard {
|
||||||
|
var left amp.Sharer
|
||||||
|
left, sharer, err = sharer.Split()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
child = left.Child(uint32(i))
|
||||||
|
|
||||||
|
// Only store the first numShards-1 hodlChans.
|
||||||
|
hodlChans[child.Preimage] = hodlChan
|
||||||
|
} else {
|
||||||
|
child = sharer.Child(uint32(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send a blank share when the set should fail reconstruction,
|
||||||
|
// otherwise send the derived share.
|
||||||
|
var share [32]byte
|
||||||
|
if !failReconstruction {
|
||||||
|
share = child.Share
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := &mockPayload{
|
||||||
|
mpp: record.NewMPP(totalAmt, payAddr),
|
||||||
|
amp: record.NewAMP(share, setID, uint32(i)),
|
||||||
|
}
|
||||||
|
|
||||||
|
resolution, err := ctx.registry.NotifyExitHopHtlc(
|
||||||
|
child.Hash, shardAmt, expiry,
|
||||||
|
testCurrentHeight, getCircuitKey(uint64(i)), hodlChan,
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// When keysend is disabled all HTLC should fail with invoice
|
||||||
|
// not found, since one is not inserted before executing
|
||||||
|
// UpdateInvoice.
|
||||||
|
if !keySendEnabled {
|
||||||
|
require.NotNil(t, resolution)
|
||||||
|
checkFailResolution(t, resolution, ResultInvoiceNotFound)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that resolutions are properly formed.
|
||||||
|
if !isFinalShard {
|
||||||
|
// Non-final shares should always return a nil
|
||||||
|
// resolution, theirs will be delivered via the
|
||||||
|
// hodlChan.
|
||||||
|
require.Nil(t, resolution)
|
||||||
|
} else {
|
||||||
|
// The final share should receive a non-nil resolution.
|
||||||
|
// Also assert that it is the proper type based on the
|
||||||
|
// test case.
|
||||||
|
require.NotNil(t, resolution)
|
||||||
|
if failReconstruction {
|
||||||
|
checkFailResolution(t, resolution, ResultAmpReconstruction)
|
||||||
|
} else {
|
||||||
|
checkSettleResolution(t, resolution, child.Preimage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assert the behavior of the Open and Settle notifications.
|
||||||
|
// There should always be an open (keysend is enabled) followed
|
||||||
|
// by settle for valid AMP payments.
|
||||||
|
//
|
||||||
|
// NOTE: The cases are split in separate if conditions, rather
|
||||||
|
// than else-if, to properly handle the case when there is only
|
||||||
|
// one shard.
|
||||||
|
if i == 0 {
|
||||||
|
checkOpenSubscription()
|
||||||
|
}
|
||||||
|
if isFinalShard {
|
||||||
|
if failReconstruction {
|
||||||
|
checkNoSettleSubscription()
|
||||||
|
} else {
|
||||||
|
checkSettleSubscription()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// No need to check the hodl chans when keysend is not enabled.
|
||||||
|
if !keySendEnabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// For the non-final hodl chans, assert that they receive the expected
|
||||||
|
// failure or preimage.
|
||||||
|
for preimage, hodlChan := range hodlChans {
|
||||||
|
resolution, ok := (<-hodlChan).(HtlcResolution)
|
||||||
|
require.True(t, ok)
|
||||||
|
require.NotNil(t, resolution)
|
||||||
|
if failReconstruction {
|
||||||
|
checkFailResolution(t, resolution, ResultAmpReconstruction)
|
||||||
|
} else {
|
||||||
|
checkSettleResolution(t, resolution, preimage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -105,6 +105,13 @@ const (
|
|||||||
// ResultMppInProgress is returned when we are busy receiving a mpp
|
// ResultMppInProgress is returned when we are busy receiving a mpp
|
||||||
// payment.
|
// payment.
|
||||||
ResultMppInProgress
|
ResultMppInProgress
|
||||||
|
|
||||||
|
// ResultAmpError is returned when we receive invalid AMP parameters.
|
||||||
|
ResultAmpError
|
||||||
|
|
||||||
|
// ResultAmpReconstruction is returned when the derived child
|
||||||
|
// hash/preimage pairs were invalid for at least one HTLC in the set.
|
||||||
|
ResultAmpReconstruction
|
||||||
)
|
)
|
||||||
|
|
||||||
// String returns a string representation of the result.
|
// String returns a string representation of the result.
|
||||||
@@ -162,11 +169,34 @@ func (f FailResolutionResult) FailureString() string {
|
|||||||
case ResultMppInProgress:
|
case ResultMppInProgress:
|
||||||
return "mpp reception in progress"
|
return "mpp reception in progress"
|
||||||
|
|
||||||
|
case ResultAmpError:
|
||||||
|
return "invalid amp parameters"
|
||||||
|
|
||||||
|
case ResultAmpReconstruction:
|
||||||
|
return "amp reconstruction failed"
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return "unknown failure resolution result"
|
return "unknown failure resolution result"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsSetFailure returns true if this failure should result in the entire HTLC
|
||||||
|
// set being failed with the same result.
|
||||||
|
func (f FailResolutionResult) IsSetFailure() bool {
|
||||||
|
switch f {
|
||||||
|
case
|
||||||
|
ResultAmpReconstruction,
|
||||||
|
ResultHtlcSetTotalTooLow,
|
||||||
|
ResultHtlcSetTotalMismatch,
|
||||||
|
ResultHtlcSetOverpayment:
|
||||||
|
|
||||||
|
return true
|
||||||
|
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SettleResolutionResult provides metadata which about a htlc that was failed
|
// SettleResolutionResult provides metadata which about a htlc that was failed
|
||||||
// by the registry. It can be used to take custom actions on resolution of the
|
// by the registry. It can be used to take custom actions on resolution of the
|
||||||
// htlc.
|
// htlc.
|
||||||
|
|||||||
+48
-10
@@ -19,6 +19,7 @@ import (
|
|||||||
"github.com/lightningnetwork/lnd/lnwire"
|
"github.com/lightningnetwork/lnd/lnwire"
|
||||||
"github.com/lightningnetwork/lnd/record"
|
"github.com/lightningnetwork/lnd/record"
|
||||||
"github.com/lightningnetwork/lnd/zpay32"
|
"github.com/lightningnetwork/lnd/zpay32"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
type mockPayload struct {
|
type mockPayload struct {
|
||||||
@@ -45,6 +46,16 @@ func (p *mockPayload) CustomRecords() record.CustomSet {
|
|||||||
return p.customRecords
|
return p.customRecords
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
testHtlcExpiry = uint32(5)
|
||||||
|
|
||||||
|
testInvoiceCltvDelta = uint32(4)
|
||||||
|
|
||||||
|
testFinalCltvRejectDelta = int32(4)
|
||||||
|
|
||||||
|
testCurrentHeight = int32(1)
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
testTimeout = 5 * time.Second
|
testTimeout = 5 * time.Second
|
||||||
|
|
||||||
@@ -54,14 +65,6 @@ var (
|
|||||||
|
|
||||||
testInvoicePaymentHash = testInvoicePreimage.Hash()
|
testInvoicePaymentHash = testInvoicePreimage.Hash()
|
||||||
|
|
||||||
testHtlcExpiry = uint32(5)
|
|
||||||
|
|
||||||
testInvoiceCltvDelta = uint32(4)
|
|
||||||
|
|
||||||
testFinalCltvRejectDelta = int32(4)
|
|
||||||
|
|
||||||
testCurrentHeight = int32(1)
|
|
||||||
|
|
||||||
testPrivKeyBytes, _ = hex.DecodeString(
|
testPrivKeyBytes, _ = hex.DecodeString(
|
||||||
"e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734")
|
"e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734")
|
||||||
|
|
||||||
@@ -111,7 +114,10 @@ var (
|
|||||||
Value: testInvoiceAmt,
|
Value: testInvoiceAmt,
|
||||||
Expiry: time.Hour,
|
Expiry: time.Hour,
|
||||||
Features: lnwire.NewFeatureVector(
|
Features: lnwire.NewFeatureVector(
|
||||||
lnwire.NewRawFeatureVector(lnwire.PaymentAddrRequired),
|
lnwire.NewRawFeatureVector(
|
||||||
|
lnwire.TLVOnionPayloadOptional,
|
||||||
|
lnwire.PaymentAddrRequired,
|
||||||
|
),
|
||||||
lnwire.Features,
|
lnwire.Features,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -124,7 +130,10 @@ var (
|
|||||||
Value: testInvoiceAmt,
|
Value: testInvoiceAmt,
|
||||||
Expiry: time.Hour,
|
Expiry: time.Hour,
|
||||||
Features: lnwire.NewFeatureVector(
|
Features: lnwire.NewFeatureVector(
|
||||||
lnwire.NewRawFeatureVector(lnwire.PaymentAddrOptional),
|
lnwire.NewRawFeatureVector(
|
||||||
|
lnwire.TLVOnionPayloadOptional,
|
||||||
|
lnwire.PaymentAddrOptional,
|
||||||
|
),
|
||||||
lnwire.Features,
|
lnwire.Features,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -325,3 +334,32 @@ func generateInvoiceExpiryTestData(
|
|||||||
|
|
||||||
return testData
|
return testData
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkSettleResolution asserts the resolution is a settle with the correct
|
||||||
|
// preimage. If successful, the HtlcSettleResolution is returned in case further
|
||||||
|
// checks are desired.
|
||||||
|
func checkSettleResolution(t *testing.T, res HtlcResolution,
|
||||||
|
expPreimage lntypes.Preimage) *HtlcSettleResolution {
|
||||||
|
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
settleResolution, ok := res.(*HtlcSettleResolution)
|
||||||
|
require.True(t, ok)
|
||||||
|
require.Equal(t, expPreimage, settleResolution.Preimage)
|
||||||
|
|
||||||
|
return settleResolution
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkFailResolution asserts the resolution is a fail with the correct reason.
|
||||||
|
// If successful, the HtlcFailResolutionis returned in case further checks are
|
||||||
|
// desired.
|
||||||
|
func checkFailResolution(t *testing.T, res HtlcResolution,
|
||||||
|
expOutcome FailResolutionResult) *HtlcFailResolution {
|
||||||
|
|
||||||
|
t.Helper()
|
||||||
|
failResolution, ok := res.(*HtlcFailResolution)
|
||||||
|
require.True(t, ok)
|
||||||
|
require.Equal(t, expOutcome, failResolution.Outcome)
|
||||||
|
|
||||||
|
return failResolution
|
||||||
|
}
|
||||||
+126
-11
@@ -3,6 +3,7 @@ package invoices
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
|
"github.com/lightningnetwork/lnd/amp"
|
||||||
"github.com/lightningnetwork/lnd/channeldb"
|
"github.com/lightningnetwork/lnd/channeldb"
|
||||||
"github.com/lightningnetwork/lnd/lntypes"
|
"github.com/lightningnetwork/lnd/lntypes"
|
||||||
"github.com/lightningnetwork/lnd/lnwire"
|
"github.com/lightningnetwork/lnd/lnwire"
|
||||||
@@ -26,11 +27,16 @@ type invoiceUpdateCtx struct {
|
|||||||
// invoiceRef returns an identifier that can be used to lookup or update the
|
// invoiceRef returns an identifier that can be used to lookup or update the
|
||||||
// invoice this HTLC is targeting.
|
// invoice this HTLC is targeting.
|
||||||
func (i *invoiceUpdateCtx) invoiceRef() channeldb.InvoiceRef {
|
func (i *invoiceUpdateCtx) invoiceRef() channeldb.InvoiceRef {
|
||||||
if i.mpp != nil {
|
switch {
|
||||||
|
case i.amp != nil && i.mpp != nil:
|
||||||
|
payAddr := i.mpp.PaymentAddr()
|
||||||
|
return channeldb.InvoiceRefByAddr(payAddr)
|
||||||
|
case i.mpp != nil:
|
||||||
payAddr := i.mpp.PaymentAddr()
|
payAddr := i.mpp.PaymentAddr()
|
||||||
return channeldb.InvoiceRefByHashAndAddr(i.hash, payAddr)
|
return channeldb.InvoiceRefByHashAndAddr(i.hash, payAddr)
|
||||||
|
default:
|
||||||
|
return channeldb.InvoiceRefByHash(i.hash)
|
||||||
}
|
}
|
||||||
return channeldb.InvoiceRefByHash(i.hash)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// setID returns an identifier that identifies other possible HTLCs that this
|
// setID returns an identifier that identifies other possible HTLCs that this
|
||||||
@@ -47,7 +53,7 @@ func (i invoiceUpdateCtx) setID() *[32]byte {
|
|||||||
// log logs a message specific to this update context.
|
// log logs a message specific to this update context.
|
||||||
func (i *invoiceUpdateCtx) log(s string) {
|
func (i *invoiceUpdateCtx) log(s string) {
|
||||||
log.Debugf("Invoice%v: %v, amt=%v, expiry=%v, circuit=%v, mpp=%v, "+
|
log.Debugf("Invoice%v: %v, amt=%v, expiry=%v, circuit=%v, mpp=%v, "+
|
||||||
"amp=%v", i.hash[:], s, i.amtPaid, i.expiry, i.circuitKey,
|
"amp=%v", i.invoiceRef(), s, i.amtPaid, i.expiry, i.circuitKey,
|
||||||
i.mpp, i.amp)
|
i.mpp, i.amp)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,6 +136,14 @@ func updateMpp(ctx *invoiceUpdateCtx,
|
|||||||
CustomRecords: ctx.customRecords,
|
CustomRecords: ctx.customRecords,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ctx.amp != nil {
|
||||||
|
acceptDesc.AMP = &channeldb.InvoiceHtlcAMPData{
|
||||||
|
Record: *ctx.amp,
|
||||||
|
Hash: ctx.hash,
|
||||||
|
Preimage: nil,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Only accept payments to open invoices. This behaviour differs from
|
// Only accept payments to open invoices. This behaviour differs from
|
||||||
// non-mpp payments that are accepted even after the invoice is settled.
|
// non-mpp payments that are accepted even after the invoice is settled.
|
||||||
// Because non-mpp payments don't have a payment address, this is needed
|
// Because non-mpp payments don't have a payment address, this is needed
|
||||||
@@ -154,9 +168,18 @@ func updateMpp(ctx *invoiceUpdateCtx,
|
|||||||
return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
|
return nil, ctx.failRes(ResultHtlcSetTotalTooLow), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
htlcSet := inv.HTLCSet(setID)
|
||||||
|
|
||||||
// Check whether total amt matches other htlcs in the set.
|
// Check whether total amt matches other htlcs in the set.
|
||||||
var newSetTotal lnwire.MilliSatoshi
|
var newSetTotal lnwire.MilliSatoshi
|
||||||
for _, htlc := range inv.HTLCSet(setID) {
|
for _, htlc := range htlcSet {
|
||||||
|
// Only consider accepted mpp htlcs. It is possible that there
|
||||||
|
// are htlcs registered in the invoice database that previously
|
||||||
|
// timed out and are in the canceled state now.
|
||||||
|
if htlc.State != channeldb.HtlcStateAccepted {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if ctx.mpp.TotalMsat() != htlc.MppTotalAmt {
|
if ctx.mpp.TotalMsat() != htlc.MppTotalAmt {
|
||||||
return nil, ctx.failRes(ResultHtlcSetTotalMismatch), nil
|
return nil, ctx.failRes(ResultHtlcSetTotalMismatch), nil
|
||||||
}
|
}
|
||||||
@@ -206,15 +229,107 @@ func updateMpp(ctx *invoiceUpdateCtx,
|
|||||||
return &update, ctx.acceptRes(resultAccepted), nil
|
return &update, ctx.acceptRes(resultAccepted), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
update.State = &channeldb.InvoiceStateUpdateDesc{
|
var (
|
||||||
NewState: channeldb.ContractSettled,
|
htlcPreimages map[channeldb.CircuitKey]lntypes.Preimage
|
||||||
Preimage: inv.Terms.PaymentPreimage,
|
htlcPreimage lntypes.Preimage
|
||||||
SetID: setID,
|
)
|
||||||
|
if ctx.amp != nil {
|
||||||
|
var failRes *HtlcFailResolution
|
||||||
|
htlcPreimages, failRes = reconstructAMPPreimages(ctx, htlcSet)
|
||||||
|
if failRes != nil {
|
||||||
|
update.State = &channeldb.InvoiceStateUpdateDesc{
|
||||||
|
NewState: channeldb.ContractCanceled,
|
||||||
|
SetID: setID,
|
||||||
|
}
|
||||||
|
return &update, failRes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// The preimage for _this_ HTLC will be the one with context's
|
||||||
|
// circuit key.
|
||||||
|
htlcPreimage = htlcPreimages[ctx.circuitKey]
|
||||||
|
} else {
|
||||||
|
htlcPreimage = *inv.Terms.PaymentPreimage
|
||||||
}
|
}
|
||||||
|
|
||||||
return &update, ctx.settleRes(
|
update.State = &channeldb.InvoiceStateUpdateDesc{
|
||||||
*inv.Terms.PaymentPreimage, ResultSettled,
|
NewState: channeldb.ContractSettled,
|
||||||
), nil
|
Preimage: inv.Terms.PaymentPreimage,
|
||||||
|
HTLCPreimages: htlcPreimages,
|
||||||
|
SetID: setID,
|
||||||
|
}
|
||||||
|
|
||||||
|
return &update, ctx.settleRes(htlcPreimage, ResultSettled), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTLCSet is a map of CircuitKey to InvoiceHTLC.
|
||||||
|
type HTLCSet = map[channeldb.CircuitKey]*channeldb.InvoiceHTLC
|
||||||
|
|
||||||
|
// HTLCPreimages is a map of CircuitKey to preimage.
|
||||||
|
type HTLCPreimages = map[channeldb.CircuitKey]lntypes.Preimage
|
||||||
|
|
||||||
|
// reconstructAMPPreimages reconstructs the root seed for an AMP HTLC set and
|
||||||
|
// verifies that all derived child hashes match the payment hashes of the HTLCs
|
||||||
|
// in the set. This method is meant to be called after receiving the full amount
|
||||||
|
// committed to via mpp_total_msat. This method will return a fail resolution if
|
||||||
|
// any of the child hashes fail to matche theire corresponding HTLCs.
|
||||||
|
func reconstructAMPPreimages(ctx *invoiceUpdateCtx,
|
||||||
|
htlcSet HTLCSet) (HTLCPreimages, *HtlcFailResolution) {
|
||||||
|
|
||||||
|
// Create a slice containing all the child descriptors to be used for
|
||||||
|
// reconstruction. This should include all HTLCs currently in the HTLC
|
||||||
|
// set, plus the incoming HTLC.
|
||||||
|
childDescs := make([]amp.ChildDesc, 0, 1+len(htlcSet))
|
||||||
|
|
||||||
|
// Add the new HTLC's child descriptor at index 0.
|
||||||
|
childDescs = append(childDescs, amp.ChildDesc{
|
||||||
|
Share: ctx.amp.RootShare(),
|
||||||
|
Index: ctx.amp.ChildIndex(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Next, construct an index mapping the position in childDescs to a
|
||||||
|
// circuit key for all preexisting HTLCs.
|
||||||
|
indexToCircuitKey := make(map[int]channeldb.CircuitKey)
|
||||||
|
|
||||||
|
// Add the child descriptor for each HTLC in the HTLC set, recording
|
||||||
|
// it's position within the slice.
|
||||||
|
var htlcSetIndex int
|
||||||
|
for circuitKey, htlc := range htlcSet {
|
||||||
|
childDescs = append(childDescs, amp.ChildDesc{
|
||||||
|
Share: htlc.AMP.Record.RootShare(),
|
||||||
|
Index: htlc.AMP.Record.ChildIndex(),
|
||||||
|
})
|
||||||
|
indexToCircuitKey[htlcSetIndex] = circuitKey
|
||||||
|
htlcSetIndex++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Using the child descriptors, reconstruct the root seed and derive the
|
||||||
|
// child hash/preimage pairs for each of the HTLCs.
|
||||||
|
children := amp.ReconstructChildren(childDescs...)
|
||||||
|
|
||||||
|
// Validate that the derived child preimages match the hash of each
|
||||||
|
// HTLC's respective hash.
|
||||||
|
if ctx.hash != children[0].Hash {
|
||||||
|
return nil, ctx.failRes(ResultAmpReconstruction)
|
||||||
|
}
|
||||||
|
for idx, child := range children[1:] {
|
||||||
|
circuitKey := indexToCircuitKey[idx]
|
||||||
|
htlc := htlcSet[circuitKey]
|
||||||
|
if htlc.AMP.Hash != child.Hash {
|
||||||
|
return nil, ctx.failRes(ResultAmpReconstruction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally, construct the map of learned preimages indexed by circuit
|
||||||
|
// key, so that they can be persisted along with each HTLC when updating
|
||||||
|
// the invoice.
|
||||||
|
htlcPreimages := make(map[channeldb.CircuitKey]lntypes.Preimage)
|
||||||
|
htlcPreimages[ctx.circuitKey] = children[0].Preimage
|
||||||
|
for idx, child := range children[1:] {
|
||||||
|
circuitKey := indexToCircuitKey[idx]
|
||||||
|
htlcPreimages[circuitKey] = child.Preimage
|
||||||
|
}
|
||||||
|
|
||||||
|
return htlcPreimages, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// updateLegacy is a callback for DB.UpdateInvoice that contains the invoice
|
// updateLegacy is a callback for DB.UpdateInvoice that contains the invoice
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package invoicesrpc
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/btcsuite/btcd/btcec"
|
"github.com/btcsuite/btcd/btcec"
|
||||||
@@ -24,7 +23,7 @@ func decodePayReq(invoice *channeldb.Invoice,
|
|||||||
if paymentRequest == "" {
|
if paymentRequest == "" {
|
||||||
preimage := invoice.Terms.PaymentPreimage
|
preimage := invoice.Terms.PaymentPreimage
|
||||||
if preimage == nil {
|
if preimage == nil {
|
||||||
return nil, errors.New("cannot reconstruct pay req")
|
return &zpay32.Invoice{}, nil
|
||||||
}
|
}
|
||||||
hash := [32]byte(preimage.Hash())
|
hash := [32]byte(preimage.Hash())
|
||||||
return &zpay32.Invoice{
|
return &zpay32.Invoice{
|
||||||
@@ -51,6 +50,11 @@ func CreateRPCInvoice(invoice *channeldb.Invoice,
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var rHash []byte
|
||||||
|
if decoded.PaymentHash != nil {
|
||||||
|
rHash = decoded.PaymentHash[:]
|
||||||
|
}
|
||||||
|
|
||||||
var descHash []byte
|
var descHash []byte
|
||||||
if decoded.DescriptionHash != nil {
|
if decoded.DescriptionHash != nil {
|
||||||
descHash = decoded.DescriptionHash[:]
|
descHash = decoded.DescriptionHash[:]
|
||||||
@@ -129,7 +133,7 @@ func CreateRPCInvoice(invoice *channeldb.Invoice,
|
|||||||
rpcHtlc.Amp = &lnrpc.AMP{
|
rpcHtlc.Amp = &lnrpc.AMP{
|
||||||
RootShare: rootShare[:],
|
RootShare: rootShare[:],
|
||||||
SetId: setID[:],
|
SetId: setID[:],
|
||||||
ChildIndex: uint32(htlc.AMP.Record.ChildIndex()),
|
ChildIndex: htlc.AMP.Record.ChildIndex(),
|
||||||
Hash: htlc.AMP.Hash[:],
|
Hash: htlc.AMP.Hash[:],
|
||||||
Preimage: preimage,
|
Preimage: preimage,
|
||||||
}
|
}
|
||||||
@@ -144,8 +148,8 @@ func CreateRPCInvoice(invoice *channeldb.Invoice,
|
|||||||
}
|
}
|
||||||
|
|
||||||
rpcInvoice := &lnrpc.Invoice{
|
rpcInvoice := &lnrpc.Invoice{
|
||||||
Memo: string(invoice.Memo[:]),
|
Memo: string(invoice.Memo),
|
||||||
RHash: decoded.PaymentHash[:],
|
RHash: rHash,
|
||||||
Value: int64(satAmt),
|
Value: int64(satAmt),
|
||||||
ValueMsat: int64(invoice.Terms.Value),
|
ValueMsat: int64(invoice.Terms.Value),
|
||||||
CreationDate: invoice.CreationDate.Unix(),
|
CreationDate: invoice.CreationDate.Unix(),
|
||||||
|
|||||||
@@ -441,6 +441,23 @@
|
|||||||
],
|
],
|
||||||
"default": "IN_FLIGHT"
|
"default": "IN_FLIGHT"
|
||||||
},
|
},
|
||||||
|
"lnrpcAMPRecord": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"root_share": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "byte"
|
||||||
|
},
|
||||||
|
"set_id": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "byte"
|
||||||
|
},
|
||||||
|
"child_index": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"lnrpcChannelPoint": {
|
"lnrpcChannelPoint": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -677,7 +694,11 @@
|
|||||||
},
|
},
|
||||||
"mpp_record": {
|
"mpp_record": {
|
||||||
"$ref": "#/definitions/lnrpcMPPRecord",
|
"$ref": "#/definitions/lnrpcMPPRecord",
|
||||||
"description": "An optional TLV record that signals the use of an MPP payment. If present,\nthe receiver will enforce that that the same mpp_record is included in the\nfinal hop payload of all non-zero payments in the HTLC set. If empty, a\nregular single-shot payment is or was attempted."
|
"description": "An optional TLV record that signals the use of an MPP payment. If present,\nthe receiver will enforce that the same mpp_record is included in the final\nhop payload of all non-zero payments in the HTLC set. If empty, a regular\nsingle-shot payment is or was attempted."
|
||||||
|
},
|
||||||
|
"amp_record": {
|
||||||
|
"$ref": "#/definitions/lnrpcAMPRecord",
|
||||||
|
"description": "An optional TLV record that signals the use of an AMP payment. If present,\nthe receiver will treat all received payments including the same\n(payment_addr, set_id) pair as being part of one logical payment. The\npayment will be settled by XORing the root_share's together and deriving the\nchild hashes and preimages according to BOLT XX. Must be used in conjunction\nwith mpp_record."
|
||||||
},
|
},
|
||||||
"custom_records": {
|
"custom_records": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
|
|||||||
@@ -455,6 +455,11 @@ func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
amp, err := UnmarshalAMP(rpcHop.AmpRecord)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return &route.Hop{
|
return &route.Hop{
|
||||||
OutgoingTimeLock: rpcHop.Expiry,
|
OutgoingTimeLock: rpcHop.Expiry,
|
||||||
AmtToForward: lnwire.MilliSatoshi(rpcHop.AmtToForwardMsat),
|
AmtToForward: lnwire.MilliSatoshi(rpcHop.AmtToForwardMsat),
|
||||||
@@ -463,6 +468,7 @@ func UnmarshallHopWithPubkey(rpcHop *lnrpc.Hop, pubkey route.Vertex) (*route.Hop
|
|||||||
CustomRecords: customRecords,
|
CustomRecords: customRecords,
|
||||||
LegacyPayload: !rpcHop.TlvPayload,
|
LegacyPayload: !rpcHop.TlvPayload,
|
||||||
MPP: mpp,
|
MPP: mpp,
|
||||||
|
AMP: amp,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -895,6 +901,32 @@ func UnmarshalMPP(reqMPP *lnrpc.MPPRecord) (*record.MPP, error) {
|
|||||||
return record.NewMPP(total, addr), nil
|
return record.NewMPP(total, addr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func UnmarshalAMP(reqAMP *lnrpc.AMPRecord) (*record.AMP, error) {
|
||||||
|
if reqAMP == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
reqRootShare := reqAMP.RootShare
|
||||||
|
reqSetID := reqAMP.SetId
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case len(reqRootShare) != 32:
|
||||||
|
return nil, errors.New("AMP root_share must be 32 bytes")
|
||||||
|
|
||||||
|
case len(reqSetID) != 32:
|
||||||
|
return nil, errors.New("AMP set_id must be 32 bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
rootShare [32]byte
|
||||||
|
setID [32]byte
|
||||||
|
)
|
||||||
|
copy(rootShare[:], reqRootShare)
|
||||||
|
copy(setID[:], reqSetID)
|
||||||
|
|
||||||
|
return record.NewAMP(rootShare, setID, reqAMP.ChildIndex), nil
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
|
// MarshalHTLCAttempt constructs an RPC HTLCAttempt from the db representation.
|
||||||
func (r *RouterBackend) MarshalHTLCAttempt(
|
func (r *RouterBackend) MarshalHTLCAttempt(
|
||||||
htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
|
htlc channeldb.HTLCAttempt) (*lnrpc.HTLCAttempt, error) {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/lightningnetwork/lnd/record"
|
"github.com/lightningnetwork/lnd/record"
|
||||||
"github.com/lightningnetwork/lnd/routing"
|
"github.com/lightningnetwork/lnd/routing"
|
||||||
"github.com/lightningnetwork/lnd/routing/route"
|
"github.com/lightningnetwork/lnd/routing/route"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
"github.com/lightningnetwork/lnd/lnrpc"
|
"github.com/lightningnetwork/lnd/lnrpc"
|
||||||
)
|
)
|
||||||
@@ -239,18 +240,18 @@ func (m *mockMissionControl) GetPairHistorySnapshot(fromNode,
|
|||||||
return routing.TimedPairResult{}
|
return routing.TimedPairResult{}
|
||||||
}
|
}
|
||||||
|
|
||||||
type mppOutcome byte
|
type recordParseOutcome byte
|
||||||
|
|
||||||
const (
|
const (
|
||||||
valid mppOutcome = iota
|
valid recordParseOutcome = iota
|
||||||
invalid
|
invalid
|
||||||
nompp
|
norecord
|
||||||
)
|
)
|
||||||
|
|
||||||
type unmarshalMPPTest struct {
|
type unmarshalMPPTest struct {
|
||||||
name string
|
name string
|
||||||
mpp *lnrpc.MPPRecord
|
mpp *lnrpc.MPPRecord
|
||||||
outcome mppOutcome
|
outcome recordParseOutcome
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestUnmarshalMPP checks both positive and negative cases of UnmarshalMPP to
|
// TestUnmarshalMPP checks both positive and negative cases of UnmarshalMPP to
|
||||||
@@ -262,7 +263,7 @@ func TestUnmarshalMPP(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "nil record",
|
name: "nil record",
|
||||||
mpp: nil,
|
mpp: nil,
|
||||||
outcome: nompp,
|
outcome: norecord,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "invalid total or addr",
|
name: "invalid total or addr",
|
||||||
@@ -346,7 +347,7 @@ func testUnmarshalMPP(t *testing.T, test unmarshalMPPTest) {
|
|||||||
|
|
||||||
// Arguments that produce no MPP field should return no error and no MPP
|
// Arguments that produce no MPP field should return no error and no MPP
|
||||||
// record.
|
// record.
|
||||||
case nompp:
|
case norecord:
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failure for args resulting for no-mpp")
|
t.Fatalf("failure for args resulting for no-mpp")
|
||||||
}
|
}
|
||||||
@@ -358,3 +359,95 @@ func testUnmarshalMPP(t *testing.T, test unmarshalMPPTest) {
|
|||||||
t.Fatalf("test case has non-standard outcome")
|
t.Fatalf("test case has non-standard outcome")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type unmarshalAMPTest struct {
|
||||||
|
name string
|
||||||
|
amp *lnrpc.AMPRecord
|
||||||
|
outcome recordParseOutcome
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUnmarshalAMP asserts the behavior of decoding an RPC AMPRecord.
|
||||||
|
func TestUnmarshalAMP(t *testing.T) {
|
||||||
|
rootShare := bytes.Repeat([]byte{0x01}, 32)
|
||||||
|
setID := bytes.Repeat([]byte{0x02}, 32)
|
||||||
|
|
||||||
|
// All child indexes are valid.
|
||||||
|
childIndex := uint32(3)
|
||||||
|
|
||||||
|
tests := []unmarshalAMPTest{
|
||||||
|
{
|
||||||
|
name: "nil record",
|
||||||
|
amp: nil,
|
||||||
|
outcome: norecord,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid root share invalid set id",
|
||||||
|
amp: &lnrpc.AMPRecord{
|
||||||
|
RootShare: []byte{0x01},
|
||||||
|
SetId: []byte{0x02},
|
||||||
|
ChildIndex: childIndex,
|
||||||
|
},
|
||||||
|
outcome: invalid,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid root share invalid set id",
|
||||||
|
amp: &lnrpc.AMPRecord{
|
||||||
|
RootShare: rootShare,
|
||||||
|
SetId: []byte{0x02},
|
||||||
|
ChildIndex: childIndex,
|
||||||
|
},
|
||||||
|
outcome: invalid,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid root share valid set id",
|
||||||
|
amp: &lnrpc.AMPRecord{
|
||||||
|
RootShare: []byte{0x01},
|
||||||
|
SetId: setID,
|
||||||
|
ChildIndex: childIndex,
|
||||||
|
},
|
||||||
|
outcome: invalid,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid root share valid set id",
|
||||||
|
amp: &lnrpc.AMPRecord{
|
||||||
|
RootShare: rootShare,
|
||||||
|
SetId: setID,
|
||||||
|
ChildIndex: childIndex,
|
||||||
|
},
|
||||||
|
outcome: valid,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
test := test
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
testUnmarshalAMP(t, test)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testUnmarshalAMP(t *testing.T, test unmarshalAMPTest) {
|
||||||
|
amp, err := UnmarshalAMP(test.amp)
|
||||||
|
switch test.outcome {
|
||||||
|
case valid:
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, amp)
|
||||||
|
|
||||||
|
rootShare := amp.RootShare()
|
||||||
|
setID := amp.SetID()
|
||||||
|
require.Equal(t, test.amp.RootShare, rootShare[:])
|
||||||
|
require.Equal(t, test.amp.SetId, setID[:])
|
||||||
|
require.Equal(t, test.amp.ChildIndex, amp.ChildIndex())
|
||||||
|
|
||||||
|
case invalid:
|
||||||
|
require.Error(t, err)
|
||||||
|
require.Nil(t, amp)
|
||||||
|
|
||||||
|
case norecord:
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Nil(t, amp)
|
||||||
|
|
||||||
|
default:
|
||||||
|
t.Fatalf("test case has non-standard outcome")
|
||||||
|
}
|
||||||
|
}
|
||||||
+951
-878
File diff suppressed because it is too large.
Load diff
+21
-3
@@ -2493,12 +2493,22 @@ message Hop {
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
An optional TLV record that signals the use of an MPP payment. If present,
|
An optional TLV record that signals the use of an MPP payment. If present,
|
||||||
the receiver will enforce that that the same mpp_record is included in the
|
the receiver will enforce that the same mpp_record is included in the final
|
||||||
final hop payload of all non-zero payments in the HTLC set. If empty, a
|
hop payload of all non-zero payments in the HTLC set. If empty, a regular
|
||||||
regular single-shot payment is or was attempted.
|
single-shot payment is or was attempted.
|
||||||
*/
|
*/
|
||||||
MPPRecord mpp_record = 10;
|
MPPRecord mpp_record = 10;
|
||||||
|
|
||||||
|
/*
|
||||||
|
An optional TLV record that signals the use of an AMP payment. If present,
|
||||||
|
the receiver will treat all received payments including the same
|
||||||
|
(payment_addr, set_id) pair as being part of one logical payment. The
|
||||||
|
payment will be settled by XORing the root_share's together and deriving the
|
||||||
|
child hashes and preimages according to BOLT XX. Must be used in conjunction
|
||||||
|
with mpp_record.
|
||||||
|
*/
|
||||||
|
AMPRecord amp_record = 12;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
An optional set of key-value TLV records. This is useful within the context
|
An optional set of key-value TLV records. This is useful within the context
|
||||||
of the SendToRoute call as it allows callers to specify arbitrary K-V pairs
|
of the SendToRoute call as it allows callers to specify arbitrary K-V pairs
|
||||||
@@ -2525,6 +2535,14 @@ message MPPRecord {
|
|||||||
int64 total_amt_msat = 10;
|
int64 total_amt_msat = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message AMPRecord {
|
||||||
|
bytes root_share = 1;
|
||||||
|
|
||||||
|
bytes set_id = 2;
|
||||||
|
|
||||||
|
uint32 child_index = 3;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
A path through the channel graph which runs over one or more channels in
|
A path through the channel graph which runs over one or more channels in
|
||||||
succession. This struct carries all the information required to craft the
|
succession. This struct carries all the information required to craft the
|
||||||
|
|||||||
+22
-1
@@ -2536,6 +2536,23 @@
|
|||||||
},
|
},
|
||||||
"description": "Details specific to AMP HTLCs."
|
"description": "Details specific to AMP HTLCs."
|
||||||
},
|
},
|
||||||
|
"lnrpcAMPRecord": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"root_share": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "byte"
|
||||||
|
},
|
||||||
|
"set_id": {
|
||||||
|
"type": "string",
|
||||||
|
"format": "byte"
|
||||||
|
},
|
||||||
|
"child_index": {
|
||||||
|
"type": "integer",
|
||||||
|
"format": "int64"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"lnrpcAbandonChannelResponse": {
|
"lnrpcAbandonChannelResponse": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
},
|
},
|
||||||
@@ -4025,7 +4042,11 @@
|
|||||||
},
|
},
|
||||||
"mpp_record": {
|
"mpp_record": {
|
||||||
"$ref": "#/definitions/lnrpcMPPRecord",
|
"$ref": "#/definitions/lnrpcMPPRecord",
|
||||||
"description": "An optional TLV record that signals the use of an MPP payment. If present,\nthe receiver will enforce that that the same mpp_record is included in the\nfinal hop payload of all non-zero payments in the HTLC set. If empty, a\nregular single-shot payment is or was attempted."
|
"description": "An optional TLV record that signals the use of an MPP payment. If present,\nthe receiver will enforce that the same mpp_record is included in the final\nhop payload of all non-zero payments in the HTLC set. If empty, a regular\nsingle-shot payment is or was attempted."
|
||||||
|
},
|
||||||
|
"amp_record": {
|
||||||
|
"$ref": "#/definitions/lnrpcAMPRecord",
|
||||||
|
"description": "An optional TLV record that signals the use of an AMP payment. If present,\nthe receiver will treat all received payments including the same\n(payment_addr, set_id) pair as being part of one logical payment. The\npayment will be settled by XORing the root_share's together and deriving the\nchild hashes and preimages according to BOLT XX. Must be used in conjunction\nwith mpp_record."
|
||||||
},
|
},
|
||||||
"custom_records": {
|
"custom_records": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package itest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/btcsuite/btcutil"
|
||||||
|
"github.com/lightningnetwork/lnd/amp"
|
||||||
|
"github.com/lightningnetwork/lnd/lnrpc"
|
||||||
|
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
|
||||||
|
"github.com/lightningnetwork/lnd/lntest"
|
||||||
|
"github.com/lightningnetwork/lnd/lntypes"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testSendToRouteAMP(net *lntest.NetworkHarness, t *harnessTest) {
|
||||||
|
ctxb := context.Background()
|
||||||
|
|
||||||
|
ctx := newMppTestContext(t, net)
|
||||||
|
defer ctx.shutdownNodes()
|
||||||
|
|
||||||
|
const (
|
||||||
|
paymentAmt = btcutil.Amount(300000)
|
||||||
|
numShards = 3
|
||||||
|
shardAmt = paymentAmt / numShards
|
||||||
|
chanAmt = shardAmt * 3 / 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Set up a network with three different paths Alice <-> Bob.
|
||||||
|
// _ Eve _
|
||||||
|
// / \
|
||||||
|
// Alice -- Carol ---- Bob
|
||||||
|
// \ /
|
||||||
|
// \__ Dave ____/
|
||||||
|
//
|
||||||
|
ctx.openChannel(ctx.carol, ctx.bob, chanAmt)
|
||||||
|
ctx.openChannel(ctx.dave, ctx.bob, chanAmt)
|
||||||
|
ctx.openChannel(ctx.alice, ctx.dave, chanAmt)
|
||||||
|
ctx.openChannel(ctx.eve, ctx.bob, chanAmt)
|
||||||
|
ctx.openChannel(ctx.carol, ctx.eve, chanAmt)
|
||||||
|
|
||||||
|
// Since the channel Alice-> Carol will have to carry two
|
||||||
|
// shards, we make it larger.
|
||||||
|
ctx.openChannel(ctx.alice, ctx.carol, chanAmt+shardAmt)
|
||||||
|
|
||||||
|
defer ctx.closeChannels()
|
||||||
|
|
||||||
|
ctx.waitForChannels()
|
||||||
|
|
||||||
|
// We'll send shards along three routes from Alice.
|
||||||
|
sendRoutes := [numShards][]*lntest.HarnessNode{
|
||||||
|
{ctx.carol, ctx.bob},
|
||||||
|
{ctx.dave, ctx.bob},
|
||||||
|
{ctx.carol, ctx.eve, ctx.bob},
|
||||||
|
}
|
||||||
|
|
||||||
|
payAddr := make([]byte, 32)
|
||||||
|
_, err := rand.Read(payAddr)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
setID := make([]byte, 32)
|
||||||
|
_, err = rand.Read(setID)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
var sharer amp.Sharer
|
||||||
|
sharer, err = amp.NewSeedSharer()
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
childPreimages := make(map[lntypes.Preimage]uint32)
|
||||||
|
responses := make(chan *lnrpc.HTLCAttempt, len(sendRoutes))
|
||||||
|
for i, hops := range sendRoutes {
|
||||||
|
// Build a route for the specified hops.
|
||||||
|
r, err := ctx.buildRoute(ctxb, shardAmt, net.Alice, hops)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unable to build route: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the MPP records to indicate this is a payment shard.
|
||||||
|
hop := r.Hops[len(r.Hops)-1]
|
||||||
|
hop.TlvPayload = true
|
||||||
|
hop.MppRecord = &lnrpc.MPPRecord{
|
||||||
|
PaymentAddr: payAddr,
|
||||||
|
TotalAmtMsat: int64(paymentAmt * 1000),
|
||||||
|
}
|
||||||
|
|
||||||
|
var child *amp.Child
|
||||||
|
if i < len(sendRoutes)-1 {
|
||||||
|
var left amp.Sharer
|
||||||
|
left, sharer, err = sharer.Split()
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
child = left.Child(uint32(i))
|
||||||
|
} else {
|
||||||
|
child = sharer.Child(uint32(i))
|
||||||
|
}
|
||||||
|
childPreimages[child.Preimage] = child.Index
|
||||||
|
|
||||||
|
hop.AmpRecord = &lnrpc.AMPRecord{
|
||||||
|
RootShare: child.Share[:],
|
||||||
|
SetId: setID,
|
||||||
|
ChildIndex: child.Index,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the shard.
|
||||||
|
sendReq := &routerrpc.SendToRouteRequest{
|
||||||
|
PaymentHash: child.Hash[:],
|
||||||
|
Route: r,
|
||||||
|
}
|
||||||
|
|
||||||
|
// We'll send all shards in their own goroutine, since SendToRoute will
|
||||||
|
// block as long as the payment is in flight.
|
||||||
|
go func() {
|
||||||
|
ctxt, _ := context.WithTimeout(ctxb, defaultTimeout)
|
||||||
|
resp, err := net.Alice.RouterClient.SendToRouteV2(ctxt, sendReq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unable to send payment: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
responses <- resp
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assert that all of the child preimages are unique.
|
||||||
|
require.Equal(t.t, len(sendRoutes), len(childPreimages))
|
||||||
|
|
||||||
|
// Make a copy of the childPreimages map for validating the resulting
|
||||||
|
// invoice.
|
||||||
|
childPreimagesCopy := make(map[lntypes.Preimage]uint32)
|
||||||
|
for preimage, childIndex := range childPreimages {
|
||||||
|
childPreimagesCopy[preimage] = childIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all responses to be back, and check that they all
|
||||||
|
// succeeded.
|
||||||
|
for range sendRoutes {
|
||||||
|
var resp *lnrpc.HTLCAttempt
|
||||||
|
select {
|
||||||
|
case resp = <-responses:
|
||||||
|
case <-time.After(defaultTimeout):
|
||||||
|
t.Fatalf("response not received")
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.Failure != nil {
|
||||||
|
t.Fatalf("received payment failure : %v", resp.Failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
preimage, err := lntypes.MakePreimage(resp.Preimage)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
// Assert that the response includes one of our child preimages.
|
||||||
|
_, ok := childPreimages[preimage]
|
||||||
|
require.True(t.t, ok)
|
||||||
|
|
||||||
|
// Remove this preimage from out set so that we ensure all
|
||||||
|
// responses have a unique child preimage.
|
||||||
|
delete(childPreimages, preimage)
|
||||||
|
}
|
||||||
|
childPreimages = childPreimagesCopy
|
||||||
|
|
||||||
|
// Fetch Bob's invoices.
|
||||||
|
invoiceResp, err := net.Bob.ListInvoices(
|
||||||
|
ctxb, &lnrpc.ListInvoiceRequest{},
|
||||||
|
)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
// There should only be one invoice.
|
||||||
|
require.Equal(t.t, 1, len(invoiceResp.Invoices))
|
||||||
|
rpcInvoice := invoiceResp.Invoices[0]
|
||||||
|
|
||||||
|
// Assert that the invoice is settled for the total payment amount and
|
||||||
|
// has the correct payment address.
|
||||||
|
require.True(t.t, rpcInvoice.Settled)
|
||||||
|
require.Equal(t.t, lnrpc.Invoice_SETTLED, rpcInvoice.State)
|
||||||
|
require.Equal(t.t, int64(paymentAmt), rpcInvoice.AmtPaidSat)
|
||||||
|
require.Equal(t.t, int64(paymentAmt*1000), rpcInvoice.AmtPaidMsat)
|
||||||
|
require.Equal(t.t, payAddr, rpcInvoice.PaymentAddr)
|
||||||
|
|
||||||
|
// Finally, assert that the proper set id is recorded for each htlc, and
|
||||||
|
// that the preimage hash pair is valid.
|
||||||
|
require.Equal(t.t, numShards, len(rpcInvoice.Htlcs))
|
||||||
|
for _, htlc := range rpcInvoice.Htlcs {
|
||||||
|
require.NotNil(t.t, htlc.Amp)
|
||||||
|
require.Equal(t.t, setID, htlc.Amp.SetId)
|
||||||
|
|
||||||
|
// Parse the child hash and child preimage, and assert they are
|
||||||
|
// well-formed.
|
||||||
|
childHash, err := lntypes.MakeHash(htlc.Amp.Hash)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
childPreimage, err := lntypes.MakePreimage(htlc.Amp.Preimage)
|
||||||
|
require.NoError(t.t, err)
|
||||||
|
|
||||||
|
// Assert that the preimage actually matches the hashes.
|
||||||
|
validPreimage := childPreimage.Matches(childHash)
|
||||||
|
require.True(t.t, validPreimage)
|
||||||
|
|
||||||
|
// Assert that the HTLC includes one of our child preimages.
|
||||||
|
childIndex, ok := childPreimages[childPreimage]
|
||||||
|
require.True(t.t, ok)
|
||||||
|
|
||||||
|
// Assert that the correct child index is reflected.
|
||||||
|
require.Equal(t.t, childIndex, htlc.Amp.ChildIndex)
|
||||||
|
|
||||||
|
// Remove this preimage from our set so that we ensure all HTLCs
|
||||||
|
// have a unique child preimage.
|
||||||
|
delete(childPreimages, childPreimage)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -74,36 +74,6 @@ func testSendToRouteMultiPath(net *lntest.NetworkHarness, t *harnessTest) {
|
|||||||
|
|
||||||
payAddr := decodeResp.PaymentAddr
|
payAddr := decodeResp.PaymentAddr
|
||||||
|
|
||||||
// Helper function for Alice to build a route from pubkeys.
|
|
||||||
buildRoute := func(amt btcutil.Amount, hops []*lntest.HarnessNode) (
|
|
||||||
*lnrpc.Route, error) {
|
|
||||||
|
|
||||||
rpcHops := make([][]byte, 0, len(hops))
|
|
||||||
for _, hop := range hops {
|
|
||||||
k := hop.PubKeyStr
|
|
||||||
pubkey, err := route.NewVertexFromStr(k)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("error parsing %v: %v",
|
|
||||||
k, err)
|
|
||||||
}
|
|
||||||
rpcHops = append(rpcHops, pubkey[:])
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &routerrpc.BuildRouteRequest{
|
|
||||||
AmtMsat: int64(amt * 1000),
|
|
||||||
FinalCltvDelta: chainreg.DefaultBitcoinTimeLockDelta,
|
|
||||||
HopPubkeys: rpcHops,
|
|
||||||
}
|
|
||||||
|
|
||||||
ctxt, _ := context.WithTimeout(ctxb, defaultTimeout)
|
|
||||||
routeResp, err := net.Alice.RouterClient.BuildRoute(ctxt, req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return routeResp.Route, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// We'll send shards along three routes from Alice.
|
// We'll send shards along three routes from Alice.
|
||||||
sendRoutes := [][]*lntest.HarnessNode{
|
sendRoutes := [][]*lntest.HarnessNode{
|
||||||
{ctx.carol, ctx.bob},
|
{ctx.carol, ctx.bob},
|
||||||
@@ -114,7 +84,7 @@ func testSendToRouteMultiPath(net *lntest.NetworkHarness, t *harnessTest) {
|
|||||||
responses := make(chan *lnrpc.HTLCAttempt, len(sendRoutes))
|
responses := make(chan *lnrpc.HTLCAttempt, len(sendRoutes))
|
||||||
for _, hops := range sendRoutes {
|
for _, hops := range sendRoutes {
|
||||||
// Build a route for the specified hops.
|
// Build a route for the specified hops.
|
||||||
r, err := buildRoute(shardAmt, hops)
|
r, err := ctx.buildRoute(ctxb, shardAmt, net.Alice, hops)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("unable to build route: %v", err)
|
t.Fatalf("unable to build route: %v", err)
|
||||||
}
|
}
|
||||||
@@ -394,3 +364,34 @@ func (c *mppTestContext) waitForChannels() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function for Alice to build a route from pubkeys.
|
||||||
|
func (c *mppTestContext) buildRoute(ctxb context.Context, amt btcutil.Amount,
|
||||||
|
sender *lntest.HarnessNode, hops []*lntest.HarnessNode) (*lnrpc.Route,
|
||||||
|
error) {
|
||||||
|
|
||||||
|
rpcHops := make([][]byte, 0, len(hops))
|
||||||
|
for _, hop := range hops {
|
||||||
|
k := hop.PubKeyStr
|
||||||
|
pubkey, err := route.NewVertexFromStr(k)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error parsing %v: %v",
|
||||||
|
k, err)
|
||||||
|
}
|
||||||
|
rpcHops = append(rpcHops, pubkey[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
req := &routerrpc.BuildRouteRequest{
|
||||||
|
AmtMsat: int64(amt * 1000),
|
||||||
|
FinalCltvDelta: chainreg.DefaultBitcoinTimeLockDelta,
|
||||||
|
HopPubkeys: rpcHops,
|
||||||
|
}
|
||||||
|
|
||||||
|
ctxt, _ := context.WithTimeout(ctxb, defaultTimeout)
|
||||||
|
routeResp, err := sender.RouterClient.BuildRoute(ctxt, req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return routeResp.Route, nil
|
||||||
|
}
|
||||||
@@ -266,6 +266,10 @@ var allTestCases = []*testCase{
|
|||||||
name: "sendtoroute multi path payment",
|
name: "sendtoroute multi path payment",
|
||||||
test: testSendToRouteMultiPath,
|
test: testSendToRouteMultiPath,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "sendtoroute amp",
|
||||||
|
test: testSendToRouteAMP,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "send multi path payment",
|
name: "send multi path payment",
|
||||||
test: testSendMultiPathPayment,
|
test: testSendMultiPathPayment,
|
||||||
|
|||||||
@@ -129,6 +129,16 @@ const (
|
|||||||
// transactions, which also imply anchor commitments.
|
// transactions, which also imply anchor commitments.
|
||||||
AnchorsZeroFeeHtlcTxOptional FeatureBit = 23
|
AnchorsZeroFeeHtlcTxOptional FeatureBit = 23
|
||||||
|
|
||||||
|
// AMPRequired is a required feature bit that signals that the receiver
|
||||||
|
// of a payment supports accepts spontaneous payments, i.e.
|
||||||
|
// sender-generated preimages according to BOLT XX.
|
||||||
|
AMPRequired FeatureBit = 30
|
||||||
|
|
||||||
|
// AMPOptional is an optional feature bit that signals that the receiver
|
||||||
|
// of a payment supports accepts spontaneous payments, i.e.
|
||||||
|
// sender-generated preimages according to BOLT XX.
|
||||||
|
AMPOptional FeatureBit = 31
|
||||||
|
|
||||||
// maxAllowedSize is a maximum allowed size of feature vector.
|
// maxAllowedSize is a maximum allowed size of feature vector.
|
||||||
//
|
//
|
||||||
// NOTE: Within the protocol, the maximum allowed message size is 65535
|
// NOTE: Within the protocol, the maximum allowed message size is 65535
|
||||||
@@ -172,6 +182,8 @@ var Features = map[FeatureBit]string{
|
|||||||
AnchorsZeroFeeHtlcTxOptional: "anchors-zero-fee-htlc-tx",
|
AnchorsZeroFeeHtlcTxOptional: "anchors-zero-fee-htlc-tx",
|
||||||
WumboChannelsRequired: "wumbo-channels",
|
WumboChannelsRequired: "wumbo-channels",
|
||||||
WumboChannelsOptional: "wumbo-channels",
|
WumboChannelsOptional: "wumbo-channels",
|
||||||
|
AMPRequired: "amp",
|
||||||
|
AMPOptional: "amp",
|
||||||
}
|
}
|
||||||
|
|
||||||
// RawFeatureVector represents a set of feature bits as defined in BOLT-09. A
|
// RawFeatureVector represents a set of feature bits as defined in BOLT-09. A
|
||||||
|
|||||||
+8
-8
@@ -9,19 +9,19 @@ import (
|
|||||||
|
|
||||||
// AMPOnionType is the type used in the onion to reference the AMP fields:
|
// AMPOnionType is the type used in the onion to reference the AMP fields:
|
||||||
// root_share, set_id, and child_index.
|
// root_share, set_id, and child_index.
|
||||||
const AMPOnionType tlv.Type = 10
|
const AMPOnionType tlv.Type = 14
|
||||||
|
|
||||||
// AMP is a record that encodes the fields necessary for atomic multi-path
|
// AMP is a record that encodes the fields necessary for atomic multi-path
|
||||||
// payments.
|
// payments.
|
||||||
type AMP struct {
|
type AMP struct {
|
||||||
rootShare [32]byte
|
rootShare [32]byte
|
||||||
setID [32]byte
|
setID [32]byte
|
||||||
childIndex uint16
|
childIndex uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewAMP generate a new AMP record with the given root_share, set_id, and
|
// NewAMP generate a new AMP record with the given root_share, set_id, and
|
||||||
// child_index.
|
// child_index.
|
||||||
func NewAMP(rootShare, setID [32]byte, childIndex uint16) *AMP {
|
func NewAMP(rootShare, setID [32]byte, childIndex uint32) *AMP {
|
||||||
return &{
|
return &{
|
||||||
rootShare: rootShare,
|
rootShare: rootShare,
|
||||||
setID: setID,
|
setID: setID,
|
||||||
@@ -40,7 +40,7 @@ func (a *AMP) SetID() [32]byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ChildIndex returns the child index contained in the AMP record.
|
// ChildIndex returns the child index contained in the AMP record.
|
||||||
func (a *AMP) ChildIndex() uint16 {
|
func (a *AMP) ChildIndex() uint32 {
|
||||||
return a.childIndex
|
return a.childIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ func AMPEncoder(w io.Writer, val interface{}, buf *[8]byte) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return tlv.ETUint16T(w, v.childIndex, buf)
|
return tlv.ETUint32T(w, v.childIndex, buf)
|
||||||
}
|
}
|
||||||
return tlv.NewTypeForEncodingErr(val, "AMP")
|
return tlv.NewTypeForEncodingErr(val, "AMP")
|
||||||
}
|
}
|
||||||
@@ -69,7 +69,7 @@ const (
|
|||||||
// maxAMPLength is the maximum legnth of a serialized AMP TLV record,
|
// maxAMPLength is the maximum legnth of a serialized AMP TLV record,
|
||||||
// which occurs when the truncated endoing of a child_index takes 2
|
// which occurs when the truncated endoing of a child_index takes 2
|
||||||
// bytes.
|
// bytes.
|
||||||
maxAMPLength = 66
|
maxAMPLength = 68
|
||||||
)
|
)
|
||||||
|
|
||||||
// AMPDecoder reads the AMP record from the provided io.Reader.
|
// AMPDecoder reads the AMP record from the provided io.Reader.
|
||||||
@@ -83,7 +83,7 @@ func AMPDecoder(r io.Reader, val interface{}, buf *[8]byte, l uint64) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return tlv.DTUint16(r, &v.childIndex, buf, l-64)
|
return tlv.DTUint32(r, &v.childIndex, buf, l-minAMPLength)
|
||||||
}
|
}
|
||||||
return tlv.NewTypeForDecodingErr(val, "AMP", l, maxAMPLength)
|
return tlv.NewTypeForDecodingErr(val, "AMP", l, maxAMPLength)
|
||||||
}
|
}
|
||||||
@@ -97,7 +97,7 @@ func (a *AMP) Record() tlv.Record {
|
|||||||
|
|
||||||
// PayloadSize returns the size this record takes up in encoded form.
|
// PayloadSize returns the size this record takes up in encoded form.
|
||||||
func (a *AMP) PayloadSize() uint64 {
|
func (a *AMP) PayloadSize() uint64 {
|
||||||
return 32 + 32 + tlv.SizeTUint16(a.childIndex)
|
return 32 + 32 + tlv.SizeTUint32(a.childIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
// String returns a human-readble description of the amp payload fields.
|
// String returns a human-readble description of the amp payload fields.
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ var (
|
|||||||
testAddr = [32]byte{0x01, 0x02}
|
testAddr = [32]byte{0x01, 0x02}
|
||||||
testShare = [32]byte{0x03, 0x04}
|
testShare = [32]byte{0x03, 0x04}
|
||||||
testSetID = [32]byte{0x05, 0x06}
|
testSetID = [32]byte{0x05, 0x06}
|
||||||
testChildIndex = uint16(17)
|
testChildIndex = uint32(17)
|
||||||
)
|
)
|
||||||
|
|
||||||
var recordEncDecTests = []recordEncDecTest{
|
var recordEncDecTests = []recordEncDecTest{
|
||||||
|
|||||||
Reference in new issue
Block a user