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

lightningnetwork / lnd / 15635919293

13 Jun 2025 01:37PM UTC coverage: 56.351% (-2.0%) from 58.333%
15635919293

Pull #9903

github

web-flow
Merge 174181006 into 35102e7c3
Pull Request #9903: docs: add sphinx replay description

108065 of 191770 relevant lines covered (56.35%)

22781.11 hits per line

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

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

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

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

260✔
148
                return nil
260✔
149

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

153
        default:
×
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 {
5✔
162
        // Before we create the database transaction, we'll ensure that the set
5✔
163
        // of forwarding events are properly sorted according to their
5✔
164
        // timestamp and that no duplicate timestamps exist to avoid collisions
5✔
165
        // in the key we are going to store the events under.
5✔
166
        makeUniqueTimestamps(events)
5✔
167

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

5✔
170
        return kvdb.Batch(f.db.Backend, func(tx kvdb.RwTx) error {
10✔
171
                // First, we'll fetch the bucket that stores our time series
5✔
172
                // log.
5✔
173
                logBucket, err := tx.CreateTopLevelBucket(
5✔
174
                        forwardingLogBucket,
5✔
175
                )
5✔
176
                if err != nil {
5✔
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 {
365✔
183
                        err := storeEvent(logBucket, event, timestamp[:])
360✔
184
                        if err != nil {
360✔
185
                                return err
×
186
                        }
×
187
                }
188

189
                return nil
5✔
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 {
360✔
199

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

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

224
                // Collision, try the next nanosecond timestamp.
225
                nextNano := event.Timestamp.UnixNano() + 1
400✔
226
                event.Timestamp = time.Unix(0, nextNano)
400✔
227
                byteOrder.PutUint64(timestampScratchSpace, uint64(nextNano))
400✔
228
                tries++
400✔
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
360✔
234
        eventBuf := bytes.NewBuffer(eventBytes[0:0:forwardingEventSize])
360✔
235
        err := encodeForwardingEvent(eventBuf, &event)
360✔
236
        if err != nil {
360✔
237
                return err
×
238
        }
×
239
        return bucket.Put(timestampScratchSpace, eventBuf.Bytes())
360✔
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,
287
        error) {
6✔
288

6✔
289
        var resp ForwardingLogTimeSlice
6✔
290

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

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

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

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

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

333
                        // At this point, we've skipped enough records to start
334
                        // to collate our query. For each record, we'll
335
                        // increment the final record offset so the querier can
336
                        // utilize pagination to seek further.
337
                        readBuf := bytes.NewReader(eventBytes)
270✔
338
                        if readBuf.Len() == 0 {
270✔
339
                                continue
×
340
                        }
341

342
                        currentTime := time.Unix(
270✔
343
                                0, int64(byteOrder.Uint64(timestamp)),
270✔
344
                        )
270✔
345

270✔
346
                        var event ForwardingEvent
270✔
347
                        err := decodeForwardingEvent(readBuf, &event)
270✔
348
                        if err != nil {
270✔
349
                                return err
×
350
                        }
×
351

352
                        event.Timestamp = currentTime
270✔
353
                        resp.ForwardingEvents = append(
270✔
354
                                resp.ForwardingEvents, event,
270✔
355
                        )
270✔
356

270✔
357
                        recordOffset++
270✔
358
                }
359

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

370
        resp.LastIndexOffset = recordOffset
6✔
371

6✔
372
        return resp, nil
6✔
373
}
374

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

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

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