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

lightningnetwork / lnd / 15300900681

28 May 2025 01:05PM UTC coverage: 68.515% (+10.2%) from 58.327%
15300900681

Pull #9813

github

web-flow
Merge f06a99c9f into bff2f2440
Pull Request #9813: lnrpc: add HtlcIndex to ForwardingEvents

43 of 53 new or added lines in 3 files covered. (81.13%)

24 existing lines in 6 files now uncovered.

134067 of 195675 relevant lines covered (68.52%)

21908.14 hits per line

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

88.6
/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 this is not set, the value will be nil. This field is added in
87
        // v0.20 and is made optional to make it backward compatible with
88
        // existing forwarding events created before it's introduction.
89
        IncomingHtlcID fn.Option[uint64]
90

91
        // OutgoingHtlcID is the ID of the outgoing HTLC in the payment circuit.
92
        // If this is not set, the value will be nil. This field is added in
93
        // v0.20 and is made optional to make it backward compatible with
94
        // existing forwarding events created before it's introduction.
95
        OutgoingHtlcID fn.Option[uint64]
96
}
97

98
// encodeForwardingEvent writes out the target forwarding event to the passed
99
// io.Writer, using the expected DB format. Note that the timestamp isn't
100
// serialized as this will be the key value within the bucket.
101
func encodeForwardingEvent(w io.Writer, f *ForwardingEvent) error {
363✔
102
        // We check for the HTLC IDs if they are set. If they are not,
363✔
103
        // from v0.20 upward, we return an error to make it clear they are
363✔
104
        // required.
363✔
105
        incomingID, err := f.IncomingHtlcID.SomeToOk(
363✔
106
                errors.New("incoming HTLC ID must be set"),
363✔
107
        ).Unpack()
363✔
108
        if err != nil {
363✔
NEW
109
                return err
×
NEW
110
        }
×
111

112
        outgoingID, err := f.OutgoingHtlcID.SomeToOk(
363✔
113
                errors.New("outgoing HTLC ID must be set"),
363✔
114
        ).Unpack()
363✔
115
        if err != nil {
363✔
NEW
116
                return err
×
NEW
117
        }
×
118

119
        return WriteElements(
363✔
120
                w, f.IncomingChanID, f.OutgoingChanID, f.AmtIn, f.AmtOut,
363✔
121
                incomingID, outgoingID,
363✔
122
        )
363✔
123
}
124

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

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

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

161
        return nil
273✔
162
}
163

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

8✔
174
        var timestamp [8]byte
8✔
175

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

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

195
                return nil
8✔
196
        })
197
}
198

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

352
                                event.Timestamp = currentTime
273✔
353
                                resp.ForwardingEvents = append(resp.ForwardingEvents, event)
273✔
354

273✔
355
                                recordOffset++
273✔
356
                        }
357
                }
358

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

369
        resp.LastIndexOffset = recordOffset
9✔
370

9✔
371
        return resp, nil
9✔
372
}
373

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

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

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