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

lightningnetwork / lnd / 16067982896

04 Jul 2025 07:08AM UTC coverage: 58.71%. First build
16067982896

Pull #9986

github

web-flow
Merge 775a6dd8f into 59a86b3b5
Pull Request #9986: release: create v0.19.2-rc1 branch

547 of 762 new or added lines in 39 files covered. (71.78%)

97876 of 166710 relevant lines covered (58.71%)

1.82 hits per line

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

83.33
/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 {
3✔
102
        // We check for the HTLC IDs if they are set. If they are not,
3✔
103
        // from v0.20 upward, we return an error to make it clear they are
3✔
104
        // required.
3✔
105
        incomingID, err := f.IncomingHtlcID.UnwrapOrErr(
3✔
106
                errors.New("incoming HTLC ID must be set"),
3✔
107
        )
3✔
108
        if err != nil {
3✔
NEW
109
                return err
×
NEW
110
        }
×
111

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

119
        return WriteElements(
3✔
120
                w, f.IncomingChanID, f.OutgoingChanID, f.AmtIn, f.AmtOut,
3✔
121
                incomingID, outgoingID,
3✔
122
        )
3✔
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 {
3✔
130
        // Decode the original fields of the forwarding event.
3✔
131
        err := ReadElements(
3✔
132
                r, &f.IncomingChanID, &f.OutgoingChanID, &f.AmtIn, &f.AmtOut,
3✔
133
        )
3✔
134
        if err != nil {
3✔
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, outgoingHtlcID uint64
3✔
142
        err = ReadElements(r, &incomingHtlcID, &outgoingHtlcID)
3✔
143
        switch {
3✔
144
        case err == nil:
3✔
145
                f.IncomingHtlcID = fn.Some(incomingHtlcID)
3✔
146
                f.OutgoingHtlcID = fn.Some(outgoingHtlcID)
3✔
147

3✔
148
                return nil
3✔
149

NEW
150
        case errors.Is(err, io.EOF):
×
NEW
151
                return nil
×
152

NEW
153
        default:
×
NEW
154
                return err
×
155
        }
156
}
157

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

3✔
168
        var timestamp [8]byte
3✔
169

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

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

189
                return nil
3✔
190
        })
191
}
192

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

3✔
200
        // First, we'll serialize this timestamp into our
3✔
201
        // timestamp buffer.
3✔
202
        byteOrder.PutUint64(
3✔
203
                timestampScratchSpace, uint64(event.Timestamp.UnixNano()),
3✔
204
        )
3✔
205

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

224
                // Collision, try the next nanosecond timestamp.
225
                nextNano := event.Timestamp.UnixNano() + 1
×
226
                event.Timestamp = time.Unix(0, nextNano)
×
227
                byteOrder.PutUint64(timestampScratchSpace, uint64(nextNano))
×
228
                tries++
×
229
        }
230

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

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

250
        // EndTime is the end time of the time slice.
251
        EndTime time.Time
252

253
        // IndexOffset is the offset within the time slice to start at. This
254
        // can be used to start the response at a particular record.
255
        IndexOffset uint32
256

257
        // NumMaxEvents is the max number of events to return.
258
        NumMaxEvents uint32
259
}
260

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

270
        // ForwardingEvents is the set of events in our time series that answer
271
        // the query embedded above.
272
        ForwardingEvents []ForwardingEvent
273

274
        // LastIndexOffset is the index of the last element in the set of
275
        // returned ForwardingEvents above. Callers can use this to resume
276
        // their query in the event that the time slice has too many events to
277
        // fit into a single response.
278
        LastIndexOffset uint32
279
}
280

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

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

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

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

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

323
                        // If we're not yet past the user defined offset, then
324
                        // we'll continue to seek forward.
325
                        if recordsToSkip > 0 {
6✔
326
                                recordsToSkip--
3✔
327
                                continue
3✔
328
                        }
329

330
                        currentTime := time.Unix(
3✔
331
                                0, int64(byteOrder.Uint64(timestamp)),
3✔
332
                        )
3✔
333

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

346
                                event.Timestamp = currentTime
3✔
347
                                resp.ForwardingEvents = append(resp.ForwardingEvents, event)
3✔
348

3✔
349
                                recordOffset++
3✔
350
                        }
351
                }
352

353
                return nil
3✔
354
        }, func() {
3✔
355
                resp = ForwardingLogTimeSlice{
3✔
356
                        ForwardingEventQuery: q,
3✔
357
                }
3✔
358
        })
3✔
359
        if err != nil && err != ErrNoForwardingEvents {
3✔
360
                return ForwardingLogTimeSlice{}, err
×
361
        }
×
362

363
        resp.LastIndexOffset = recordOffset
3✔
364

3✔
365
        return resp, nil
3✔
366
}
367

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

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

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