• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 16134013004

08 Jul 2025 04:31AM UTC coverage: 57.764% (-0.02%) from 57.787%
16134013004

Pull #10049

github

web-flow
Merge 149221dc3 into b815109b8
Pull Request #10049: multi: prevent duplicates for locally dispatched HTLC attempts

79 of 113 new or added lines in 4 files covered. (69.91%)

142 existing lines in 11 files now uncovered.

98480 of 170488 relevant lines covered (57.76%)

1.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.19
/htlcswitch/payment_result.go
1
package htlcswitch
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "errors"
7
        "io"
8
        "sync"
9

10
        "github.com/lightningnetwork/lnd/channeldb"
11
        "github.com/lightningnetwork/lnd/kvdb"
12
        "github.com/lightningnetwork/lnd/lnwire"
13
        "github.com/lightningnetwork/lnd/multimutex"
14
)
15

16
var (
17

18
        // networkResultStoreBucketKey is used for the root level bucket that
19
        // stores the network result for each payment ID.
20
        networkResultStoreBucketKey = []byte("network-result-store-bucket")
21

22
        // ErrPaymentIDNotFound is an error returned if the given paymentID is
23
        // not found.
24
        ErrPaymentIDNotFound = errors.New("paymentID not found")
25

26
        // ErrPaymentIDAlreadyExists is returned if we try to write a pending
27
        // payment whose paymentID already exists.
28
        ErrPaymentIDAlreadyExists = errors.New("paymentID already exists")
29
)
30

31
// PaymentResult wraps a decoded result received from the network after a
32
// payment attempt was made. This is what is eventually handed to the router
33
// for processing.
34
type PaymentResult struct {
35
        // Preimage is set by the switch in case a sent HTLC was settled.
36
        Preimage [32]byte
37

38
        // Error is non-nil in case a HTLC send failed, and the HTLC is now
39
        // irrevocably canceled. If the payment failed during forwarding, this
40
        // error will be a *ForwardingError.
41
        Error error
42
}
43

44
// networkResult is the raw result received from the network after a payment
45
// attempt has been made. Since the switch doesn't always have the necessary
46
// data to decode the raw message, we store it together with some meta data,
47
// and decode it when the router query for the final result.
48
type networkResult struct {
49
        // msg is the received result. This should be of type UpdateFulfillHTLC
50
        // or UpdateFailHTLC.
51
        msg lnwire.Message
52

53
        // unencrypted indicates whether the failure encoded in the message is
54
        // unencrypted, and hence doesn't need to be decrypted.
55
        unencrypted bool
56

57
        // isResolution indicates whether this is a resolution message, in
58
        // which the failure reason might not be included.
59
        isResolution bool
60
}
61

62
// serializeNetworkResult serializes the networkResult.
63
func serializeNetworkResult(w io.Writer, n *networkResult) error {
3✔
64
        return channeldb.WriteElements(w, n.msg, n.unencrypted, n.isResolution)
3✔
65
}
3✔
66

67
// deserializeNetworkResult deserializes the networkResult.
68
func deserializeNetworkResult(r io.Reader) (*networkResult, error) {
3✔
69
        n := &networkResult{}
3✔
70

3✔
71
        if err := channeldb.ReadElements(r,
3✔
72
                &n.msg, &n.unencrypted, &n.isResolution,
3✔
73
        ); err != nil {
3✔
74
                return nil, err
×
75
        }
×
76

77
        return n, nil
3✔
78
}
79

80
// networkResultStore is a persistent store that stores any results of HTLCs in
81
// flight on the network. Since payment results are inherently asynchronous, it
82
// is used as a common access point for senders of HTLCs, to know when a result
83
// is back. The Switch will checkpoint any received result to the store, and
84
// the store will keep results and notify the callers about them.
85
type networkResultStore struct {
86
        backend kvdb.Backend
87

88
        // results is a map from paymentIDs to channels where subscribers to
89
        // payment results will be notified.
90
        results    map[uint64][]chan *networkResult
91
        resultsMtx sync.Mutex
92

93
        // attemptIDMtx is a multimutex used to make sure the database and
94
        // result subscribers map is consistent for each attempt ID in case of
95
        // concurrent callers.
96
        attemptIDMtx *multimutex.Mutex[uint64]
97
}
98

99
func newNetworkResultStore(db kvdb.Backend) *networkResultStore {
3✔
100
        return &networkResultStore{
3✔
101
                backend:      db,
3✔
102
                results:      make(map[uint64][]chan *networkResult),
3✔
103
                attemptIDMtx: multimutex.NewMutex[uint64](),
3✔
104
        }
3✔
105
}
3✔
106

107
// InitAttempt initializes the payment attempt with the given attemptID.
108
// If the attemptID has already been initialized, it returns an error. This
109
// method ensures that we do not create duplicate payment attempts for the same
110
// attemptID.
111
//
112
// NOTE: Subscribed clients do not receive notice of this initialization.
113
func (store *networkResultStore) InitAttempt(attemptID uint64) error {
3✔
114

3✔
115
        // We get a mutex for this attempt ID to ensure no concurrent writes
3✔
116
        // for the same attempt ID.
3✔
117
        store.attemptIDMtx.Lock(attemptID)
3✔
118
        defer store.attemptIDMtx.Unlock(attemptID)
3✔
119

3✔
120
        // Check if any attempt by this ID is already initialized or whether a
3✔
121
        // a result for the attempt exists in the store.
3✔
122
        existingResult, err := store.GetResult(attemptID)
3✔
123
        if err != nil && !errors.Is(err, ErrPaymentIDNotFound) {
3✔
NEW
124
                // If the error is anything other than "not found", return it.
×
NEW
125
                return err
×
NEW
126
        }
×
127

128
        if existingResult != nil {
3✔
NEW
129
                // If the result is already in-progress, return an error
×
NEW
130
                // indicating that the attempt already exists.
×
NEW
131
                log.Warnf("Already initialized attempt for ID=%v", attemptID)
×
NEW
132

×
NEW
133
                return ErrPaymentIDAlreadyExists
×
NEW
134
        }
×
135

136
        // Create an empty networkResult to serve as place holder until a result
137
        // from the network is received.
138
        inProgressResult := &networkResult{
3✔
139
                msg:          &lnwire.PendingNetworkResult{},
3✔
140
                unencrypted:  true,
3✔
141
                isResolution: false,
3✔
142
        }
3✔
143

3✔
144
        // This is an in-progress result, no need to notify subscribers yet.
3✔
145
        var b bytes.Buffer
3✔
146
        if err := serializeNetworkResult(&b, inProgressResult); err != nil {
3✔
NEW
147
                return err
×
NEW
148
        }
×
149

150
        var attemptIDBytes [8]byte
3✔
151
        binary.BigEndian.PutUint64(attemptIDBytes[:], attemptID)
3✔
152

3✔
153
        // Mark this an HTLC attempt with this ID as having been seen.
3✔
154
        // No network result is available yet.
3✔
155
        //
3✔
156
        // NOTE: Subscribed clients expecting to block until a network result is
3✔
157
        // available must not be notified of this initialization.
3✔
158
        err = kvdb.Batch(store.backend, func(tx kvdb.RwTx) error {
6✔
159
                networkResults, err := tx.CreateTopLevelBucket(
3✔
160
                        networkResultStoreBucketKey,
3✔
161
                )
3✔
162
                if err != nil {
3✔
NEW
163
                        return err
×
NEW
164
                }
×
165

166
                // Store the in-progress result.
167
                return networkResults.Put(attemptIDBytes[:], b.Bytes())
3✔
168
        })
169
        if err != nil {
3✔
NEW
170
                return err
×
NEW
171
        }
×
172

173
        return nil
3✔
174
}
175

176
// storeResult stores the networkResult for the given attemptID, and notifies
177
// any subscribers.
178
func (store *networkResultStore) StoreResult(attemptID uint64,
179
        result *networkResult) error {
3✔
180

3✔
181
        // We get a mutex for this attempt ID. This is needed to ensure
3✔
182
        // consistency between the database state and the subscribers in case
3✔
183
        // of concurrent calls.
3✔
184
        store.attemptIDMtx.Lock(attemptID)
3✔
185
        defer store.attemptIDMtx.Unlock(attemptID)
3✔
186

3✔
187
        log.Debugf("Storing result for attemptID=%v", attemptID)
3✔
188

3✔
189
        // Handle finalized result (success or failure).
3✔
190
        var b bytes.Buffer
3✔
191
        if err := serializeNetworkResult(&b, result); err != nil {
3✔
192
                return err
×
193
        }
×
194

195
        var attemptIDBytes [8]byte
3✔
196
        binary.BigEndian.PutUint64(attemptIDBytes[:], attemptID)
3✔
197

3✔
198
        err := kvdb.Batch(store.backend, func(tx kvdb.RwTx) error {
6✔
199
                networkResults, err := tx.CreateTopLevelBucket(
3✔
200
                        networkResultStoreBucketKey,
3✔
201
                )
3✔
202
                if err != nil {
3✔
203
                        return err
×
204
                }
×
205

206
                return networkResults.Put(attemptIDBytes[:], b.Bytes())
3✔
207
        })
208
        if err != nil {
3✔
209
                return err
×
210
        }
×
211

212
        // Now that the result is stored in the database, we can notify any
213
        // active subscribers - but only if this isn't an initialized attempt
214
        // awaiting a settle/fail result from the network.
215
        if result.msg.MsgType() != lnwire.MsgPendingNetworkResult {
6✔
216
                store.resultsMtx.Lock()
3✔
217
                for _, res := range store.results[attemptID] {
6✔
218
                        res <- result
3✔
219
                }
3✔
220
                delete(store.results, attemptID)
3✔
221
                store.resultsMtx.Unlock()
3✔
222
        }
223

224
        return nil
3✔
225
}
226

227
// subscribeResult is used to get the HTLC attempt result for the given attempt
228
// ID.  It returns a channel on which the result will be delivered when ready.
229
func (store *networkResultStore) SubscribeResult(attemptID uint64) (
230
        <-chan *networkResult, error) {
3✔
231

3✔
232
        // We get a mutex for this payment ID. This is needed to ensure
3✔
233
        // consistency between the database state and the subscribers in case
3✔
234
        // of concurrent calls.
3✔
235
        store.attemptIDMtx.Lock(attemptID)
3✔
236
        defer store.attemptIDMtx.Unlock(attemptID)
3✔
237

3✔
238
        log.Debugf("Subscribing to result for attemptID=%v", attemptID)
3✔
239

3✔
240
        var (
3✔
241
                result     *networkResult
3✔
242
                resultChan = make(chan *networkResult, 1)
3✔
243
        )
3✔
244

3✔
245
        err := kvdb.View(store.backend, func(tx kvdb.RTx) error {
6✔
246
                var err error
3✔
247
                result, err = fetchResult(tx, attemptID)
3✔
248
                switch {
3✔
249

250
                // Result not yet available, we will notify once a result is
251
                // available.
UNCOV
252
                case err == ErrPaymentIDNotFound:
×
UNCOV
253
                        return nil
×
254

255
                case err != nil:
×
256
                        return err
×
257

258
                // The result was found, and will be returned immediately.
259
                default:
3✔
260
                        return nil
3✔
261
                }
262
        }, func() {
3✔
263
                result = nil
3✔
264
        })
3✔
265
        if err != nil {
3✔
266
                return nil, err
×
267
        }
×
268

269
        // If a result is back from the network, we can send it on the result
270
        // channel immemdiately. If the result is still our initialized place
271
        // holder, then treat it as not yet available.
272
        if result != nil {
6✔
273
                if result.msg.MsgType() != lnwire.MsgPendingNetworkResult {
3✔
NEW
274
                        log.Debugf("Obtained full result for attemptID=%v",
×
NEW
275
                                attemptID)
×
NEW
276

×
NEW
277
                        resultChan <- result
×
NEW
278
                        return resultChan, nil
×
NEW
279
                }
×
280

281
                log.Debugf("Awaiting result (settle/fail) for attemptID=%v",
3✔
282
                        attemptID)
3✔
283
        }
284

285
        // Otherwise we store the result channel for when the result is
286
        // available.
287
        store.resultsMtx.Lock()
3✔
288
        store.results[attemptID] = append(
3✔
289
                store.results[attemptID], resultChan,
3✔
290
        )
3✔
291
        store.resultsMtx.Unlock()
3✔
292

3✔
293
        return resultChan, nil
3✔
294
}
295

296
// GetResult attempts to immediately fetch the *final* network result for the
297
// given attempt ID from the store. If no result is available, or if the only
298
// entry is an initialization placeholder (e.g. created via InitAttempt),
299
// ErrPaymentIDNotFound is returned to signal that the result is not yet
300
// available.
301
//
302
// NOTE: This method does not currently acquire the result subscription mutex.
303
func (store *networkResultStore) GetResult(pid uint64) (
304
        *networkResult, error) {
3✔
305

3✔
306
        var result *networkResult
3✔
307
        err := kvdb.View(store.backend, func(tx kvdb.RTx) error {
6✔
308
                var err error
3✔
309
                result, err = fetchResult(tx, pid)
3✔
310
                if err != nil {
6✔
311
                        return err
3✔
312
                }
3✔
313

314
                // If the attempt is still in-flight, treat it as not yet
315
                // available to preserve existing expectation for the behavior
316
                // of this method.
317
                if result.msg.MsgType() == lnwire.MsgPendingNetworkResult {
6✔
318
                        return ErrPaymentIDNotFound
3✔
319
                }
3✔
320

NEW
321
                return nil
×
322
        }, func() {
3✔
323
                result = nil
3✔
324
        })
3✔
325
        if err != nil {
6✔
326
                return nil, err
3✔
327
        }
3✔
328

UNCOV
329
        return result, nil
×
330
}
331

332
func fetchResult(tx kvdb.RTx, pid uint64) (*networkResult, error) {
3✔
333
        var attemptIDBytes [8]byte
3✔
334
        binary.BigEndian.PutUint64(attemptIDBytes[:], pid)
3✔
335

3✔
336
        networkResults := tx.ReadBucket(networkResultStoreBucketKey)
3✔
337
        if networkResults == nil {
3✔
338
                return nil, ErrPaymentIDNotFound
×
339
        }
×
340

341
        // Check whether a result is already available.
342
        resultBytes := networkResults.Get(attemptIDBytes[:])
3✔
343
        if resultBytes == nil {
6✔
344
                return nil, ErrPaymentIDNotFound
3✔
345
        }
3✔
346

347
        // Decode the result we found.
348
        r := bytes.NewReader(resultBytes)
3✔
349

3✔
350
        return deserializeNetworkResult(r)
3✔
351
}
352

353
// cleanStore removes all entries from the store, except the payment IDs given.
354
// NOTE: Since every result not listed in the keep map will be deleted, care
355
// should be taken to ensure no new payment attempts are being made
356
// concurrently while this process is ongoing, as its result might end up being
357
// deleted.
358
func (store *networkResultStore) CleanStore(keep map[uint64]struct{}) error {
3✔
359
        return kvdb.Update(store.backend, func(tx kvdb.RwTx) error {
6✔
360
                networkResults, err := tx.CreateTopLevelBucket(
3✔
361
                        networkResultStoreBucketKey,
3✔
362
                )
3✔
363
                if err != nil {
3✔
364
                        return err
×
365
                }
×
366

367
                // Iterate through the bucket, deleting all items not in the
368
                // keep map.
369
                var toClean [][]byte
3✔
370
                if err := networkResults.ForEach(func(k, _ []byte) error {
6✔
371
                        pid := binary.BigEndian.Uint64(k)
3✔
372
                        if _, ok := keep[pid]; ok {
6✔
373
                                return nil
3✔
374
                        }
3✔
375

376
                        toClean = append(toClean, k)
3✔
377
                        return nil
3✔
378
                }); err != nil {
×
379
                        return err
×
380
                }
×
381

382
                for _, k := range toClean {
6✔
383
                        err := networkResults.Delete(k)
3✔
384
                        if err != nil {
3✔
385
                                return err
×
386
                        }
×
387
                }
388

389
                if len(toClean) > 0 {
6✔
390
                        log.Infof("Removed %d stale entries from network "+
3✔
391
                                "result store", len(toClean))
3✔
392
                }
3✔
393

394
                return nil
3✔
395
        }, func() {})
3✔
396
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc