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

lightningnetwork / lnd / 15161356083

21 May 2025 11:48AM UTC coverage: 58.614% (-10.4%) from 68.996%
15161356083

Pull #9813

github

web-flow
Merge a6343fe3a into c52a6ddeb
Pull Request #9813: lnrpc: add HtlcIndex to ForwardingEvents

39 of 55 new or added lines in 3 files covered. (70.91%)

28203 existing lines in 450 files now uncovered.

97496 of 166335 relevant lines covered (58.61%)

1.82 hits per line

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

80.93
/channeldb/forwarding_log.go
1
package channeldb
2

3
import (
4
        "bytes"
5
        "errors"
6
        "io"
7
        "sort"
8
        "time"
9

10
        "github.com/btcsuite/btcwallet/walletdb"
11
        "github.com/lightningnetwork/lnd/fn/v2"
12
        "github.com/lightningnetwork/lnd/kvdb"
13
        "github.com/lightningnetwork/lnd/lnwire"
14
)
15

16
var (
17
        // forwardingLogBucket is the bucket that we'll use to store the
18
        // forwarding log. The forwarding log contains a time series database
19
        // of the forwarding history of a lightning daemon. Each key within the
20
        // bucket is a timestamp (in nano seconds since the unix epoch), and
21
        // the value a slice of a forwarding event for that timestamp.
22
        forwardingLogBucket = []byte("circuit-fwd-log")
23
)
24

25
const (
26
        // forwardingEventSize is the size of a forwarding event. The breakdown
27
        // is as follows:
28
        //
29
        //  * 8 byte incoming chan ID || 8 byte outgoing chan ID || 8 byte value in
30
        //    || 8 byte value out || 8 byte incoming htlc id || 8 byte
31
        //    outgoing htlc id
32
        //
33
        // From the value in and value out, callers can easily compute the
34
        // total fee extract from a forwarding event.
35
        forwardingEventSize = 48
36

37
        // MaxResponseEvents is the max number of forwarding events that will
38
        // be returned by a single query response. This size was selected to
39
        // safely remain under gRPC's 4MiB message size response limit. As each
40
        // full forwarding event (including the timestamp) is 40 bytes, we can
41
        // safely return 50k entries in a single response.
42
        MaxResponseEvents = 50000
43
)
44

45
// ForwardingLog returns an instance of the ForwardingLog object backed by the
46
// target database instance.
47
func (d *DB) ForwardingLog() *ForwardingLog {
3✔
48
        return &ForwardingLog{
3✔
49
                db: d,
3✔
50
        }
3✔
51
}
3✔
52

53
// ForwardingLog is a time series database that logs the fulfillment of payment
54
// circuits by a lightning network daemon. The log contains a series of
55
// forwarding events which map a timestamp to a forwarding event. A forwarding
56
// event describes which channels were used to create+settle a circuit, and the
57
// amount involved. Subtracting the outgoing amount from the incoming amount
58
// reveals the fee charged for the forwarding service.
59
type ForwardingLog struct {
60
        db *DB
61
}
62

63
// ForwardingEvent is an event in the forwarding log's time series. Each
64
// forwarding event logs the creation and tear-down of a payment circuit. A
65
// circuit is created once an incoming HTLC has been fully forwarded, and
66
// destroyed once the payment has been settled.
67
type ForwardingEvent struct {
68
        // Timestamp is the settlement time of this payment circuit.
69
        Timestamp time.Time
70

71
        // IncomingChanID is the incoming channel ID of the payment circuit.
72
        IncomingChanID lnwire.ShortChannelID
73

74
        // OutgoingChanID is the outgoing channel ID of the payment circuit.
75
        OutgoingChanID lnwire.ShortChannelID
76

77
        // AmtIn is the amount of the incoming HTLC. Subtracting this from the
78
        // outgoing amount gives the total fees of this payment circuit.
79
        AmtIn lnwire.MilliSatoshi
80

81
        // AmtOut is the amount of the outgoing HTLC. Subtracting the incoming
82
        // amount from this gives the total fees for this payment circuit.
83
        AmtOut lnwire.MilliSatoshi
84

85
        // IncomingHtlcID is the ID of the incoming HTLC in the payment circuit.
86
        // If the HTLC ID is not set, the value will be nil.
87
        IncomingHtlcID fn.Option[uint64]
88

89
        // OutgoingHtlcID is the ID of the outgoing HTLC in the payment circuit.
90
        // If the HTLC ID is not set, the value will be nil.
91
        OutgoingHtlcID fn.Option[uint64]
92
}
93

94
// encodeForwardingEvent writes out the target forwarding event to the passed
95
// io.Writer, using the expected DB format. Note that the timestamp isn't
96
// serialized as this will be the key value within the bucket.
97
func encodeForwardingEvent(w io.Writer, f *ForwardingEvent) error {
3✔
98
        // First we write the required fields.
3✔
99
        err := WriteElements(
3✔
100
                w, f.IncomingChanID, f.OutgoingChanID, f.AmtIn, f.AmtOut,
3✔
101
        )
3✔
102
        if err != nil {
3✔
NEW
103
                return err
×
NEW
104
        }
×
105

106
        // Then we write the optional HTLC IDs if they are set.
107
        f.IncomingHtlcID.WhenSome(func(id uint64) {
6✔
108
                err = WriteElement(w, id)
3✔
109
        })
3✔
110
        if err != nil {
3✔
NEW
111
                return err
×
NEW
112
        }
×
113
        f.OutgoingHtlcID.WhenSome(func(id uint64) {
6✔
114
                err = WriteElement(w, id)
3✔
115
        })
3✔
116
        if err != nil {
3✔
NEW
117
                return err
×
NEW
118
        }
×
119

120
        return nil
3✔
121
}
122

123
// decodeForwardingEvent attempts to decode the raw bytes of a serialized
124
// forwarding event into the target ForwardingEvent. Note that the timestamp
125
// won't be decoded, as the caller is expected to set this due to the bucket
126
// structure of the forwarding log.
127
func decodeForwardingEvent(r io.Reader, f *ForwardingEvent) error {
3✔
128
        // Decode the original fields of the forwarding event.
3✔
129
        err := ReadElements(
3✔
130
                r, &f.IncomingChanID, &f.OutgoingChanID, &f.AmtIn, &f.AmtOut,
3✔
131
        )
3✔
132
        if err != nil {
3✔
NEW
133
                return err
×
NEW
134
        }
×
135

136
        // Decode the incoming and outgoing htlc IDs. For backward
137
        // compatibility with older records that don't have these fields, we
138
        // handle EOF by setting the ID to nil. Any other error is treated as
139
        // a read failure.
140
        var incomingHtlcID uint64
3✔
141
        if err := ReadElement(r, &incomingHtlcID); err != nil {
3✔
NEW
142
                if !errors.Is(err, io.EOF) {
×
NEW
143
                        return err
×
NEW
144
                }
×
NEW
145
                f.IncomingHtlcID = fn.None[uint64]()
×
146
        } else {
3✔
147
                f.IncomingHtlcID = fn.Some(incomingHtlcID)
3✔
148
        }
3✔
149

150
        var outgoingHtlcID uint64
3✔
151
        if err := ReadElement(r, &outgoingHtlcID); err != nil {
3✔
NEW
152
                if !errors.Is(err, io.EOF) {
×
NEW
153
                        return err
×
NEW
154
                }
×
NEW
155
                f.OutgoingHtlcID = fn.None[uint64]()
×
156
        } else {
3✔
157
                f.OutgoingHtlcID = fn.Some(outgoingHtlcID)
3✔
158
        }
3✔
159

160
        return nil
3✔
161
}
162

163
// AddForwardingEvents adds a series of forwarding events to the database.
164
// Before inserting, the set of events will be sorted according to their
165
// timestamp. This ensures that all writes to disk are sequential.
166
func (f *ForwardingLog) AddForwardingEvents(events []ForwardingEvent) error {
3✔
167
        // Before we create the database transaction, we'll ensure that the set
3✔
168
        // of forwarding events are properly sorted according to their
3✔
169
        // timestamp and that no duplicate timestamps exist to avoid collisions
3✔
170
        // in the key we are going to store the events under.
3✔
171
        makeUniqueTimestamps(events)
3✔
172

3✔
173
        var timestamp [8]byte
3✔
174

3✔
175
        return kvdb.Batch(f.db.Backend, func(tx kvdb.RwTx) error {
6✔
176
                // First, we'll fetch the bucket that stores our time series
3✔
177
                // log.
3✔
178
                logBucket, err := tx.CreateTopLevelBucket(
3✔
179
                        forwardingLogBucket,
3✔
180
                )
3✔
181
                if err != nil {
3✔
182
                        return err
×
183
                }
×
184

185
                // With the bucket obtained, we can now begin to write out the
186
                // series of events.
187
                for _, event := range events {
6✔
188
                        err := storeEvent(logBucket, event, timestamp[:])
3✔
189
                        if err != nil {
3✔
190
                                return err
×
191
                        }
×
192
                }
193

194
                return nil
3✔
195
        })
196
}
197

198
// storeEvent tries to store a forwarding event into the given bucket by trying
199
// to avoid collisions. If a key for the event timestamp already exists in the
200
// database, the timestamp is incremented in nanosecond intervals until a "free"
201
// slot is found.
202
func storeEvent(bucket walletdb.ReadWriteBucket, event ForwardingEvent,
203
        timestampScratchSpace []byte) error {
3✔
204

3✔
205
        // First, we'll serialize this timestamp into our
3✔
206
        // timestamp buffer.
3✔
207
        byteOrder.PutUint64(
3✔
208
                timestampScratchSpace, uint64(event.Timestamp.UnixNano()),
3✔
209
        )
3✔
210

3✔
211
        // Next we'll loop until we find a "free" slot in the bucket to store
3✔
212
        // the event under. This should almost never happen unless we're running
3✔
213
        // on a system that has a very bad system clock that doesn't properly
3✔
214
        // resolve to nanosecond scale. We try up to 100 times (which would come
3✔
215
        // to a maximum shift of 0.1 microsecond which is acceptable for most
3✔
216
        // use cases). If we don't find a free slot, we just give up and let
3✔
217
        // the collision happen. Something must be wrong with the data in that
3✔
218
        // case, even on a very fast machine forwarding payments _will_ take a
3✔
219
        // few microseconds at least so we should find a nanosecond slot
3✔
220
        // somewhere.
3✔
221
        const maxTries = 100
3✔
222
        tries := 0
3✔
223
        for tries < maxTries {
6✔
224
                val := bucket.Get(timestampScratchSpace)
3✔
225
                if val == nil {
6✔
226
                        break
3✔
227
                }
228

229
                // Collision, try the next nanosecond timestamp.
UNCOV
230
                nextNano := event.Timestamp.UnixNano() + 1
×
UNCOV
231
                event.Timestamp = time.Unix(0, nextNano)
×
UNCOV
232
                byteOrder.PutUint64(timestampScratchSpace, uint64(nextNano))
×
UNCOV
233
                tries++
×
234
        }
235

236
        // With the key encoded, we'll then encode the event
237
        // into our buffer, then write it out to disk.
238
        var eventBytes [forwardingEventSize]byte
3✔
239
        eventBuf := bytes.NewBuffer(eventBytes[0:0:forwardingEventSize])
3✔
240
        err := encodeForwardingEvent(eventBuf, &event)
3✔
241
        if err != nil {
3✔
242
                return err
×
243
        }
×
244
        return bucket.Put(timestampScratchSpace, eventBuf.Bytes())
3✔
245
}
246

247
// ForwardingEventQuery represents a query to the forwarding log payment
248
// circuit time series database. The query allows a caller to retrieve all
249
// records for a particular time slice, offset in that time slice, limiting the
250
// total number of responses returned.
251
type ForwardingEventQuery struct {
252
        // StartTime is the start time of the time slice.
253
        StartTime time.Time
254

255
        // EndTime is the end time of the time slice.
256
        EndTime time.Time
257

258
        // IndexOffset is the offset within the time slice to start at. This
259
        // can be used to start the response at a particular record.
260
        IndexOffset uint32
261

262
        // NumMaxEvents is the max number of events to return.
263
        NumMaxEvents uint32
264
}
265

266
// ForwardingLogTimeSlice is the response to a forwarding query. It includes
267
// the original query, the set  events that match the query, and an integer
268
// which represents the offset index of the last item in the set of returned
269
// events. This integer allows callers to resume their query using this offset
270
// in the event that the query's response exceeds the max number of returnable
271
// events.
272
type ForwardingLogTimeSlice struct {
273
        ForwardingEventQuery
274

275
        // ForwardingEvents is the set of events in our time series that answer
276
        // the query embedded above.
277
        ForwardingEvents []ForwardingEvent
278

279
        // LastIndexOffset is the index of the last element in the set of
280
        // returned ForwardingEvents above. Callers can use this to resume
281
        // their query in the event that the time slice has too many events to
282
        // fit into a single response.
283
        LastIndexOffset uint32
284
}
285

286
// Query allows a caller to query the forwarding event time series for a
287
// particular time slice. The caller can control the precise time as well as
288
// the number of events to be returned.
289
//
290
// TODO(roasbeef): rename?
291
func (f *ForwardingLog) Query(q ForwardingEventQuery) (ForwardingLogTimeSlice, error) {
3✔
292
        var resp ForwardingLogTimeSlice
3✔
293

3✔
294
        // If the user provided an index offset, then we'll not know how many
3✔
295
        // records we need to skip. We'll also keep track of the record offset
3✔
296
        // as that's part of the final return value.
3✔
297
        recordsToSkip := q.IndexOffset
3✔
298
        recordOffset := q.IndexOffset
3✔
299

3✔
300
        err := kvdb.View(f.db, func(tx kvdb.RTx) error {
6✔
301
                // If the bucket wasn't found, then there aren't any events to
3✔
302
                // be returned.
3✔
303
                logBucket := tx.ReadBucket(forwardingLogBucket)
3✔
304
                if logBucket == nil {
3✔
305
                        return ErrNoForwardingEvents
×
306
                }
×
307

308
                // We'll be using a cursor to seek into the database, so we'll
309
                // populate byte slices that represent the start of the key
310
                // space we're interested in, and the end.
311
                var startTime, endTime [8]byte
3✔
312
                byteOrder.PutUint64(startTime[:], uint64(q.StartTime.UnixNano()))
3✔
313
                byteOrder.PutUint64(endTime[:], uint64(q.EndTime.UnixNano()))
3✔
314

3✔
315
                // If we know that a set of log events exists, then we'll begin
3✔
316
                // our seek through the log in order to satisfy the query.
3✔
317
                // We'll continue until either we reach the end of the range,
3✔
318
                // or reach our max number of events.
3✔
319
                logCursor := logBucket.ReadCursor()
3✔
320
                timestamp, events := logCursor.Seek(startTime[:])
3✔
321
                for ; timestamp != nil && bytes.Compare(timestamp, endTime[:]) <= 0; timestamp, events = logCursor.Next() {
6✔
322
                        // If our current return payload exceeds the max number
3✔
323
                        // of events, then we'll exit now.
3✔
324
                        if uint32(len(resp.ForwardingEvents)) >= q.NumMaxEvents {
3✔
UNCOV
325
                                return nil
×
UNCOV
326
                        }
×
327

328
                        // If we're not yet past the user defined offset, then
329
                        // we'll continue to seek forward.
330
                        if recordsToSkip > 0 {
6✔
331
                                recordsToSkip--
3✔
332
                                continue
3✔
333
                        }
334

335
                        currentTime := time.Unix(
3✔
336
                                0, int64(byteOrder.Uint64(timestamp)),
3✔
337
                        )
3✔
338

3✔
339
                        // At this point, we've skipped enough records to start
3✔
340
                        // to collate our query. For each record, we'll
3✔
341
                        // increment the final record offset so the querier can
3✔
342
                        // utilize pagination to seek further.
3✔
343
                        readBuf := bytes.NewReader(events)
3✔
344
                        for readBuf.Len() != 0 {
6✔
345
                                var event ForwardingEvent
3✔
346
                                err := decodeForwardingEvent(readBuf, &event)
3✔
347
                                if err != nil {
3✔
348
                                        return err
×
349
                                }
×
350

351
                                event.Timestamp = currentTime
3✔
352
                                resp.ForwardingEvents = append(resp.ForwardingEvents, event)
3✔
353

3✔
354
                                recordOffset++
3✔
355
                        }
356
                }
357

358
                return nil
3✔
359
        }, func() {
3✔
360
                resp = ForwardingLogTimeSlice{
3✔
361
                        ForwardingEventQuery: q,
3✔
362
                }
3✔
363
        })
3✔
364
        if err != nil && err != ErrNoForwardingEvents {
3✔
365
                return ForwardingLogTimeSlice{}, err
×
366
        }
×
367

368
        resp.LastIndexOffset = recordOffset
3✔
369

3✔
370
        return resp, nil
3✔
371
}
372

373
// makeUniqueTimestamps takes a slice of forwarding events, sorts it by the
374
// event timestamps and then makes sure there are no duplicates in the
375
// timestamps. If duplicates are found, some of the timestamps are increased on
376
// the nanosecond scale until only unique values remain. This is a fix to
377
// address the problem that in some environments (looking at you, Windows) the
378
// system clock has such a bad resolution that two serial invocations of
379
// time.Now() might return the same timestamp, even if some time has elapsed
380
// between the calls.
381
func makeUniqueTimestamps(events []ForwardingEvent) {
3✔
382
        sort.Slice(events, func(i, j int) bool {
6✔
383
                return events[i].Timestamp.Before(events[j].Timestamp)
3✔
384
        })
3✔
385

386
        // Now that we know the events are sorted by timestamp, we can go
387
        // through the list and fix all duplicates until only unique values
388
        // remain.
389
        for outer := 0; outer < len(events)-1; outer++ {
6✔
390
                current := events[outer].Timestamp.UnixNano()
3✔
391
                next := events[outer+1].Timestamp.UnixNano()
3✔
392

3✔
393
                // We initially sorted the slice. So if the current is now
3✔
394
                // greater or equal to the next one, it's either because it's a
3✔
395
                // duplicate or because we increased the current in the last
3✔
396
                // iteration.
3✔
397
                if current >= next {
3✔
UNCOV
398
                        next = current + 1
×
UNCOV
399
                        events[outer+1].Timestamp = time.Unix(0, next)
×
UNCOV
400
                }
×
401
        }
402
}
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