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

lightningnetwork / lnd / 14511230428

17 Apr 2025 08:16AM UTC coverage: 58.579% (-10.5%) from 69.035%
14511230428

Pull #9356

github

web-flow
Merge ab5387622 into 24fdae7df
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

37 of 40 new or added lines in 2 files covered. (92.5%)

28194 existing lines in 452 files now uncovered.

97172 of 165882 relevant lines covered (58.58%)

1.82 hits per line

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

86.81
/channeldb/forwarding_log.go
1
package channeldb
2

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

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

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

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

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

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

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

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

69
        // IncomingChanID is the incoming channel ID of the payment circuit.
70
        IncomingChanID lnwire.ShortChannelID
71

72
        // OutgoingChanID is the outgoing channel ID of the payment circuit.
73
        OutgoingChanID lnwire.ShortChannelID
74

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

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

84
// encodeForwardingEvent writes out the target forwarding event to the passed
85
// io.Writer, using the expected DB format. Note that the timestamp isn't
86
// serialized as this will be the key value within the bucket.
87
func encodeForwardingEvent(w io.Writer, f *ForwardingEvent) error {
3✔
88
        return WriteElements(
3✔
89
                w, f.IncomingChanID, f.OutgoingChanID, f.AmtIn, f.AmtOut,
3✔
90
        )
3✔
91
}
3✔
92

93
// decodeForwardingEvent attempts to decode the raw bytes of a serialized
94
// forwarding event into the target ForwardingEvent. Note that the timestamp
95
// won't be decoded, as the caller is expected to set this due to the bucket
96
// structure of the forwarding log.
97
func decodeForwardingEvent(r io.Reader, f *ForwardingEvent) error {
3✔
98
        return ReadElements(
3✔
99
                r, &f.IncomingChanID, &f.OutgoingChanID, &f.AmtIn, &f.AmtOut,
3✔
100
        )
3✔
101
}
3✔
102

103
// AddForwardingEvents adds a series of forwarding events to the database.
104
// Before inserting, the set of events will be sorted according to their
105
// timestamp. This ensures that all writes to disk are sequential.
106
func (f *ForwardingLog) AddForwardingEvents(events []ForwardingEvent) error {
3✔
107
        // Before we create the database transaction, we'll ensure that the set
3✔
108
        // of forwarding events are properly sorted according to their
3✔
109
        // timestamp and that no duplicate timestamps exist to avoid collisions
3✔
110
        // in the key we are going to store the events under.
3✔
111
        makeUniqueTimestamps(events)
3✔
112

3✔
113
        var timestamp [8]byte
3✔
114

3✔
115
        return kvdb.Batch(f.db.Backend, func(tx kvdb.RwTx) error {
6✔
116
                // First, we'll fetch the bucket that stores our time series
3✔
117
                // log.
3✔
118
                logBucket, err := tx.CreateTopLevelBucket(
3✔
119
                        forwardingLogBucket,
3✔
120
                )
3✔
121
                if err != nil {
3✔
122
                        return err
×
123
                }
×
124

125
                // With the bucket obtained, we can now begin to write out the
126
                // series of events.
127
                for _, event := range events {
6✔
128
                        err := storeEvent(logBucket, event, timestamp[:])
3✔
129
                        if err != nil {
3✔
130
                                return err
×
131
                        }
×
132
                }
133

134
                return nil
3✔
135
        })
136
}
137

138
// storeEvent tries to store a forwarding event into the given bucket by trying
139
// to avoid collisions. If a key for the event timestamp already exists in the
140
// database, the timestamp is incremented in nanosecond intervals until a "free"
141
// slot is found.
142
func storeEvent(bucket walletdb.ReadWriteBucket, event ForwardingEvent,
143
        timestampScratchSpace []byte) error {
3✔
144

3✔
145
        // First, we'll serialize this timestamp into our
3✔
146
        // timestamp buffer.
3✔
147
        byteOrder.PutUint64(
3✔
148
                timestampScratchSpace, uint64(event.Timestamp.UnixNano()),
3✔
149
        )
3✔
150

3✔
151
        // Next we'll loop until we find a "free" slot in the bucket to store
3✔
152
        // the event under. This should almost never happen unless we're running
3✔
153
        // on a system that has a very bad system clock that doesn't properly
3✔
154
        // resolve to nanosecond scale. We try up to 100 times (which would come
3✔
155
        // to a maximum shift of 0.1 microsecond which is acceptable for most
3✔
156
        // use cases). If we don't find a free slot, we just give up and let
3✔
157
        // the collision happen. Something must be wrong with the data in that
3✔
158
        // case, even on a very fast machine forwarding payments _will_ take a
3✔
159
        // few microseconds at least so we should find a nanosecond slot
3✔
160
        // somewhere.
3✔
161
        const maxTries = 100
3✔
162
        tries := 0
3✔
163
        for tries < maxTries {
6✔
164
                val := bucket.Get(timestampScratchSpace)
3✔
165
                if val == nil {
6✔
166
                        break
3✔
167
                }
168

169
                // Collision, try the next nanosecond timestamp.
UNCOV
170
                nextNano := event.Timestamp.UnixNano() + 1
×
UNCOV
171
                event.Timestamp = time.Unix(0, nextNano)
×
UNCOV
172
                byteOrder.PutUint64(timestampScratchSpace, uint64(nextNano))
×
UNCOV
173
                tries++
×
174
        }
175

176
        // With the key encoded, we'll then encode the event
177
        // into our buffer, then write it out to disk.
178
        var eventBytes [forwardingEventSize]byte
3✔
179
        eventBuf := bytes.NewBuffer(eventBytes[0:0:forwardingEventSize])
3✔
180
        err := encodeForwardingEvent(eventBuf, &event)
3✔
181
        if err != nil {
3✔
182
                return err
×
183
        }
×
184
        return bucket.Put(timestampScratchSpace, eventBuf.Bytes())
3✔
185
}
186

187
// ForwardingEventQuery represents a query to the forwarding log payment
188
// circuit time series database. The query allows a caller to retrieve all
189
// records for a particular time slice, offset in that time slice, limiting the
190
// total number of responses returned.
191
type ForwardingEventQuery struct {
192
        // StartTime is the start time of the time slice.
193
        StartTime time.Time
194

195
        // EndTime is the end time of the time slice.
196
        EndTime time.Time
197

198
        // IndexOffset is the offset within the time slice to start at. This
199
        // can be used to start the response at a particular record.
200
        IndexOffset uint32
201

202
        // NumMaxEvents is the max number of events to return.
203
        NumMaxEvents uint32
204

205
        // IncomingChanIds is the list of channels to filter HTLCs being
206
        // received from a particular channel.
207
        // If the list is empty, then it is ignored.
208
        IncomingChanIDs fn.Set[uint64]
209

210
        // OutgoingChanIds is the list of channels to filter HTLCs being
211
        // forwarded to a particular channel.
212
        // If the list is empty, then it is ignored.
213
        OutgoingChanIDs fn.Set[uint64]
214
}
215

216
// ForwardingLogTimeSlice is the response to a forwarding query. It includes
217
// the original query, the set  events that match the query, and an integer
218
// which represents the offset index of the last item in the set of returned
219
// events. This integer allows callers to resume their query using this offset
220
// in the event that the query's response exceeds the max number of returnable
221
// events.
222
type ForwardingLogTimeSlice struct {
223
        ForwardingEventQuery
224

225
        // ForwardingEvents is the set of events in our time series that answer
226
        // the query embedded above.
227
        ForwardingEvents []ForwardingEvent
228

229
        // LastIndexOffset is the index of the last element in the set of
230
        // returned ForwardingEvents above. Callers can use this to resume
231
        // their query in the event that the time slice has too many events to
232
        // fit into a single response.
233
        LastIndexOffset uint32
234
}
235

236
// Query allows a caller to query the forwarding event time series for a
237
// particular time slice. The caller can control the precise time as well as
238
// the number of events to be returned.
239
//
240
// TODO(roasbeef): rename?
241
func (f *ForwardingLog) Query(q ForwardingEventQuery) (ForwardingLogTimeSlice, error) {
3✔
242
        var resp ForwardingLogTimeSlice
3✔
243

3✔
244
        // If the user provided an index offset, then we'll not know how many
3✔
245
        // records we need to skip. We'll also keep track of the record offset
3✔
246
        // as that's part of the final return value.
3✔
247
        recordsToSkip := q.IndexOffset
3✔
248
        recordOffset := q.IndexOffset
3✔
249

3✔
250
        err := kvdb.View(f.db, func(tx kvdb.RTx) error {
6✔
251
                // If the bucket wasn't found, then there aren't any events to
3✔
252
                // be returned.
3✔
253
                logBucket := tx.ReadBucket(forwardingLogBucket)
3✔
254
                if logBucket == nil {
3✔
255
                        return ErrNoForwardingEvents
×
256
                }
×
257

258
                // We'll be using a cursor to seek into the database, so we'll
259
                // populate byte slices that represent the start of the key
260
                // space we're interested in, and the end.
261
                var startTime, endTime [8]byte
3✔
262
                byteOrder.PutUint64(startTime[:], uint64(q.StartTime.UnixNano()))
3✔
263
                byteOrder.PutUint64(endTime[:], uint64(q.EndTime.UnixNano()))
3✔
264

3✔
265
                // If we know that a set of log events exists, then we'll begin
3✔
266
                // our seek through the log in order to satisfy the query.
3✔
267
                // We'll continue until either we reach the end of the range,
3✔
268
                // or reach our max number of events.
3✔
269
                logCursor := logBucket.ReadCursor()
3✔
270
                timestamp, events := logCursor.Seek(startTime[:])
3✔
271
                for ; timestamp != nil && bytes.Compare(timestamp, endTime[:]) <= 0; timestamp, events = logCursor.Next() {
6✔
272
                        // If our current return payload exceeds the max number
3✔
273
                        // of events, then we'll exit now.
3✔
274
                        if uint32(len(resp.ForwardingEvents)) >= q.NumMaxEvents {
3✔
UNCOV
275
                                return nil
×
UNCOV
276
                        }
×
277

278
                        // If no incoming or outgoing channel IDs were provided
279
                        // and we're not yet past the user defined offset, then
280
                        // we'll continue to seek forward.
281
                        if recordsToSkip > 0 &&
3✔
282
                                q.IncomingChanIDs.IsEmpty() &&
3✔
283
                                q.OutgoingChanIDs.IsEmpty() {
6✔
284

3✔
285
                                recordsToSkip--
3✔
286
                                continue
3✔
287
                        }
288

289
                        currentTime := time.Unix(
3✔
290
                                0, int64(byteOrder.Uint64(timestamp)),
3✔
291
                        )
3✔
292

3✔
293
                        // At this point, we've skipped enough records to start
3✔
294
                        // to collate our query. For each record, we'll
3✔
295
                        // increment the final record offset so the querier can
3✔
296
                        // utilize pagination to seek further.
3✔
297
                        readBuf := bytes.NewReader(events)
3✔
298
                        for readBuf.Len() != 0 {
6✔
299
                                var event ForwardingEvent
3✔
300
                                err := decodeForwardingEvent(readBuf, &event)
3✔
301
                                if err != nil {
3✔
302
                                        return err
×
303
                                }
×
304

305
                                // Check if the incoming channel ID matches the
306
                                // filter criteria. Either no filtering is
307
                                // applied (IsEmpty), or the ID is explicitly
308
                                // included.
309
                                incomingMatch := q.IncomingChanIDs.IsEmpty() ||
3✔
310
                                        q.IncomingChanIDs.Contains(
3✔
311
                                                event.IncomingChanID.ToUint64(),
3✔
312
                                        )
3✔
313

3✔
314
                                // Check if the outgoing channel ID matches the
3✔
315
                                // filter criteria. Either no filtering is
3✔
316
                                // applied (IsEmpty), or  the ID is explicitly
3✔
317
                                // included.
3✔
318
                                outgoingMatch := q.OutgoingChanIDs.IsEmpty() ||
3✔
319
                                        q.OutgoingChanIDs.Contains(
3✔
320
                                                event.OutgoingChanID.ToUint64(),
3✔
321
                                        )
3✔
322

3✔
323
                                // Skip this event if it doesn't match the
3✔
324
                                // filters.
3✔
325
                                if !incomingMatch || !outgoingMatch {
3✔
NEW
326
                                        continue
×
327
                                }
328
                                // If we're not yet past the user defined offset
329
                                // then we'll continue to seek forward.
330
                                if recordsToSkip > 0 {
3✔
NEW
331
                                        recordsToSkip--
×
NEW
332
                                        continue
×
333
                                }
334

335
                                event.Timestamp = currentTime
3✔
336
                                resp.ForwardingEvents = append(
3✔
337
                                        resp.ForwardingEvents,
3✔
338
                                        event,
3✔
339
                                )
3✔
340
                                recordOffset++
3✔
341
                        }
342
                }
343

344
                return nil
3✔
345
        }, func() {
3✔
346
                resp = ForwardingLogTimeSlice{
3✔
347
                        ForwardingEventQuery: q,
3✔
348
                }
3✔
349
        })
3✔
350
        if err != nil && err != ErrNoForwardingEvents {
3✔
351
                return ForwardingLogTimeSlice{}, err
×
352
        }
×
353

354
        resp.LastIndexOffset = recordOffset
3✔
355

3✔
356
        return resp, nil
3✔
357
}
358

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

372
        // Now that we know the events are sorted by timestamp, we can go
373
        // through the list and fix all duplicates until only unique values
374
        // remain.
375
        for outer := 0; outer < len(events)-1; outer++ {
6✔
376
                current := events[outer].Timestamp.UnixNano()
3✔
377
                next := events[outer+1].Timestamp.UnixNano()
3✔
378

3✔
379
                // We initially sorted the slice. So if the current is now
3✔
380
                // greater or equal to the next one, it's either because it's a
3✔
381
                // duplicate or because we increased the current in the last
3✔
382
                // iteration.
3✔
383
                if current >= next {
3✔
UNCOV
384
                        next = current + 1
×
UNCOV
385
                        events[outer+1].Timestamp = time.Unix(0, next)
×
UNCOV
386
                }
×
387
        }
388
}
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