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

lightningnetwork / lnd / 14193549836

01 Apr 2025 10:40AM UTC coverage: 69.046% (+0.007%) from 69.039%
14193549836

Pull #9665

github

web-flow
Merge e8825f209 into b01f4e514
Pull Request #9665: kvdb: bump etcd libs to v3.5.12

133439 of 193262 relevant lines covered (69.05%)

22119.45 hits per line

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

90.23
/record/blinded_data.go
1
package record
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "io"
7

8
        "github.com/btcsuite/btcd/btcec/v2"
9
        "github.com/lightningnetwork/lnd/lnwire"
10
        "github.com/lightningnetwork/lnd/tlv"
11
)
12

13
// AverageDummyHopPayloadSize is the size of a standard blinded path dummy hop
14
// payload. In most cases, this is larger than the other payload types and so
15
// to make sure that a sender cannot use this fact to know if a dummy hop is
16
// present or not, we'll make sure to always pad all payloads to at least this
17
// size.
18
const AverageDummyHopPayloadSize = 51
19

20
// BlindedRouteData contains the information that is included in a blinded
21
// route encrypted data blob that is created by the recipient to provide
22
// forwarding information.
23
type BlindedRouteData struct {
24
        // Padding is an optional set of bytes that a recipient can use to pad
25
        // the data so that the encrypted recipient data blobs are all the same
26
        // length.
27
        Padding tlv.OptionalRecordT[tlv.TlvType1, []byte]
28

29
        // ShortChannelID is the channel ID of the next hop.
30
        ShortChannelID tlv.OptionalRecordT[tlv.TlvType2, lnwire.ShortChannelID]
31

32
        // NextNodeID is the node ID of the next node on the path. In the
33
        // context of blinded path payments, this is used to indicate the
34
        // presence of dummy hops that need to be peeled from the onion.
35
        NextNodeID tlv.OptionalRecordT[tlv.TlvType4, *btcec.PublicKey]
36

37
        // PathID is a secret set of bytes that the blinded path creator will
38
        // set so that they can check the value on decryption to ensure that the
39
        // path they created was used for the intended purpose.
40
        PathID tlv.OptionalRecordT[tlv.TlvType6, []byte]
41

42
        // NextBlindingOverride is a blinding point that should be switched
43
        // in for the next hop. This is used to combine two blinded paths into
44
        // one (which primarily is used in onion messaging, but in theory
45
        // could be used for payments as well).
46
        NextBlindingOverride tlv.OptionalRecordT[tlv.TlvType8, *btcec.PublicKey]
47

48
        // RelayInfo provides the relay parameters for the hop.
49
        RelayInfo tlv.OptionalRecordT[tlv.TlvType10, PaymentRelayInfo]
50

51
        // Constraints provides the payment relay constraints for the hop.
52
        Constraints tlv.OptionalRecordT[tlv.TlvType12, PaymentConstraints]
53

54
        // Features is the set of features the payment requires.
55
        Features tlv.OptionalRecordT[tlv.TlvType14, lnwire.FeatureVector]
56
}
57

58
// NewNonFinalBlindedRouteData creates the data that's provided for hops within
59
// a blinded route.
60
func NewNonFinalBlindedRouteData(chanID lnwire.ShortChannelID,
61
        blindingOverride *btcec.PublicKey, relayInfo PaymentRelayInfo,
62
        constraints *PaymentConstraints,
63
        features *lnwire.FeatureVector) *BlindedRouteData {
28✔
64

28✔
65
        info := &BlindedRouteData{
28✔
66
                ShortChannelID: tlv.SomeRecordT(
28✔
67
                        tlv.NewRecordT[tlv.TlvType2](chanID),
28✔
68
                ),
28✔
69
                RelayInfo: tlv.SomeRecordT(
28✔
70
                        tlv.NewRecordT[tlv.TlvType10](relayInfo),
28✔
71
                ),
28✔
72
        }
28✔
73

28✔
74
        if blindingOverride != nil {
39✔
75
                info.NextBlindingOverride = tlv.SomeRecordT(
11✔
76
                        tlv.NewPrimitiveRecord[tlv.TlvType8](blindingOverride))
11✔
77
        }
11✔
78

79
        if constraints != nil {
50✔
80
                info.Constraints = tlv.SomeRecordT(
22✔
81
                        tlv.NewRecordT[tlv.TlvType12](*constraints))
22✔
82
        }
22✔
83

84
        if features != nil {
33✔
85
                info.Features = tlv.SomeRecordT(
5✔
86
                        tlv.NewRecordT[tlv.TlvType14](*features),
5✔
87
                )
5✔
88
        }
5✔
89

90
        return info
28✔
91
}
92

93
// NewFinalHopBlindedRouteData creates the data that's provided for the final
94
// hop in a blinded route.
95
func NewFinalHopBlindedRouteData(constraints *PaymentConstraints,
96
        pathID []byte) *BlindedRouteData {
10✔
97

10✔
98
        var data BlindedRouteData
10✔
99
        if pathID != nil {
19✔
100
                data.PathID = tlv.SomeRecordT(
9✔
101
                        tlv.NewPrimitiveRecord[tlv.TlvType6](pathID),
9✔
102
                )
9✔
103
        }
9✔
104

105
        if constraints != nil {
18✔
106
                data.Constraints = tlv.SomeRecordT(
8✔
107
                        tlv.NewRecordT[tlv.TlvType12](*constraints))
8✔
108
        }
8✔
109

110
        return &data
10✔
111
}
112

113
// NewDummyHopRouteData creates the data that's provided for any hop preceding
114
// a dummy hop. The presence of such a payload indicates to the reader that
115
// they are the intended recipient and should peel the remainder of the onion.
116
func NewDummyHopRouteData(ourPubKey *btcec.PublicKey,
117
        relayInfo PaymentRelayInfo,
118
        constraints PaymentConstraints) *BlindedRouteData {
8✔
119

8✔
120
        return &BlindedRouteData{
8✔
121
                NextNodeID: tlv.SomeRecordT(
8✔
122
                        tlv.NewPrimitiveRecord[tlv.TlvType4](ourPubKey),
8✔
123
                ),
8✔
124
                RelayInfo: tlv.SomeRecordT(
8✔
125
                        tlv.NewRecordT[tlv.TlvType10](relayInfo),
8✔
126
                ),
8✔
127
                Constraints: tlv.SomeRecordT(
8✔
128
                        tlv.NewRecordT[tlv.TlvType12](constraints),
8✔
129
                ),
8✔
130
        }
8✔
131
}
8✔
132

133
// DecodeBlindedRouteData decodes the data provided within a blinded route.
134
func DecodeBlindedRouteData(r io.Reader) (*BlindedRouteData, error) {
28✔
135
        var (
28✔
136
                d BlindedRouteData
28✔
137

28✔
138
                padding          = d.Padding.Zero()
28✔
139
                scid             = d.ShortChannelID.Zero()
28✔
140
                nextNodeID       = d.NextNodeID.Zero()
28✔
141
                pathID           = d.PathID.Zero()
28✔
142
                blindingOverride = d.NextBlindingOverride.Zero()
28✔
143
                relayInfo        = d.RelayInfo.Zero()
28✔
144
                constraints      = d.Constraints.Zero()
28✔
145
                features         = d.Features.Zero()
28✔
146
        )
28✔
147

28✔
148
        var tlvRecords lnwire.ExtraOpaqueData
28✔
149
        if err := lnwire.ReadElements(r, &tlvRecords); err != nil {
28✔
150
                return nil, err
×
151
        }
×
152

153
        typeMap, err := tlvRecords.ExtractRecords(
28✔
154
                &padding, &scid, &nextNodeID, &pathID, &blindingOverride,
28✔
155
                &relayInfo, &constraints, &features,
28✔
156
        )
28✔
157
        if err != nil {
29✔
158
                return nil, err
1✔
159
        }
1✔
160

161
        val, ok := typeMap[d.Padding.TlvType()]
27✔
162
        if ok && val == nil {
39✔
163
                d.Padding = tlv.SomeRecordT(padding)
12✔
164
        }
12✔
165

166
        if val, ok := typeMap[d.ShortChannelID.TlvType()]; ok && val == nil {
46✔
167
                d.ShortChannelID = tlv.SomeRecordT(scid)
19✔
168
        }
19✔
169

170
        if val, ok := typeMap[d.NextNodeID.TlvType()]; ok && val == nil {
33✔
171
                d.NextNodeID = tlv.SomeRecordT(nextNodeID)
6✔
172
        }
6✔
173

174
        if val, ok := typeMap[d.PathID.TlvType()]; ok && val == nil {
34✔
175
                d.PathID = tlv.SomeRecordT(pathID)
7✔
176
        }
7✔
177

178
        val, ok = typeMap[d.NextBlindingOverride.TlvType()]
27✔
179
        if ok && val == nil {
35✔
180
                d.NextBlindingOverride = tlv.SomeRecordT(blindingOverride)
8✔
181
        }
8✔
182

183
        if val, ok := typeMap[d.RelayInfo.TlvType()]; ok && val == nil {
49✔
184
                d.RelayInfo = tlv.SomeRecordT(relayInfo)
22✔
185
        }
22✔
186

187
        if val, ok := typeMap[d.Constraints.TlvType()]; ok && val == nil {
46✔
188
                d.Constraints = tlv.SomeRecordT(constraints)
19✔
189
        }
19✔
190

191
        if val, ok := typeMap[d.Features.TlvType()]; ok && val == nil {
31✔
192
                d.Features = tlv.SomeRecordT(features)
4✔
193
        }
4✔
194

195
        return &d, nil
27✔
196
}
197

198
// EncodeBlindedRouteData encodes the blinded route data provided.
199
func EncodeBlindedRouteData(data *BlindedRouteData) ([]byte, error) {
2,635✔
200
        var (
2,635✔
201
                e               lnwire.ExtraOpaqueData
2,635✔
202
                recordProducers = make([]tlv.RecordProducer, 0, 5)
2,635✔
203
        )
2,635✔
204

2,635✔
205
        data.Padding.WhenSome(func(p tlv.RecordT[tlv.TlvType1, []byte]) {
5,247✔
206
                recordProducers = append(recordProducers, &p)
2,612✔
207
        })
2,612✔
208

209
        data.ShortChannelID.WhenSome(func(scid tlv.RecordT[tlv.TlvType2,
2,635✔
210
                lnwire.ShortChannelID]) {
2,664✔
211

29✔
212
                recordProducers = append(recordProducers, &scid)
29✔
213
        })
29✔
214

215
        data.NextNodeID.WhenSome(func(f tlv.RecordT[tlv.TlvType4,
2,635✔
216
                *btcec.PublicKey]) {
2,647✔
217

12✔
218
                recordProducers = append(recordProducers, &f)
12✔
219
        })
12✔
220

221
        data.PathID.WhenSome(func(pathID tlv.RecordT[tlv.TlvType6, []byte]) {
2,676✔
222
                recordProducers = append(recordProducers, &pathID)
41✔
223
        })
41✔
224

225
        data.NextBlindingOverride.WhenSome(func(pk tlv.RecordT[tlv.TlvType8,
2,635✔
226
                *btcec.PublicKey]) {
2,648✔
227

13✔
228
                recordProducers = append(recordProducers, &pk)
13✔
229
        })
13✔
230

231
        data.RelayInfo.WhenSome(func(r tlv.RecordT[tlv.TlvType10,
2,635✔
232
                PaymentRelayInfo]) {
2,673✔
233

38✔
234
                recordProducers = append(recordProducers, &r)
38✔
235
        })
38✔
236

237
        data.Constraints.WhenSome(func(cs tlv.RecordT[tlv.TlvType12,
2,635✔
238
                PaymentConstraints]) {
2,676✔
239

41✔
240
                recordProducers = append(recordProducers, &cs)
41✔
241
        })
41✔
242

243
        data.Features.WhenSome(func(f tlv.RecordT[tlv.TlvType14,
2,635✔
244
                lnwire.FeatureVector]) {
2,637✔
245

2✔
246
                recordProducers = append(recordProducers, &f)
2✔
247
        })
2✔
248

249
        if err := e.PackRecords(recordProducers...); err != nil {
2,635✔
250
                return nil, err
×
251
        }
×
252

253
        return e[:], nil
2,635✔
254
}
255

256
// PadBy adds "n" padding bytes to the BlindedRouteData using the Padding field.
257
// Callers should be aware that the total payload size will change by more than
258
// "n" since the "n" bytes will be prefixed by BigSize type and length fields.
259
// Callers may need to call PadBy iteratively until each encrypted data packet
260
// is the same size and so each call will overwrite the Padding record.
261
// Note that calling PadBy with an n value of 0 will still result in a zero
262
// length TLV entry being added.
263
func (b *BlindedRouteData) PadBy(n int) {
2,599✔
264
        b.Padding = tlv.SomeRecordT(
2,599✔
265
                tlv.NewPrimitiveRecord[tlv.TlvType1](make([]byte, n)),
2,599✔
266
        )
2,599✔
267
}
2,599✔
268

269
// PaymentRelayInfo describes the relay policy for a blinded path.
270
type PaymentRelayInfo struct {
271
        // CltvExpiryDelta is the expiry delta for the payment.
272
        CltvExpiryDelta uint16
273

274
        // FeeRate is the fee rate that will be charged per millionth of a
275
        // satoshi.
276
        FeeRate uint32
277

278
        // BaseFee is the per-htlc fee charged in milli-satoshis.
279
        BaseFee lnwire.MilliSatoshi
280
}
281

282
// Record creates a tlv.Record that encodes the payment relay (type 10) type for
283
// an encrypted blob payload.
284
func (i *PaymentRelayInfo) Record() tlv.Record {
63✔
285
        return tlv.MakeDynamicRecord(
63✔
286
                10, &i, func() uint64 {
101✔
287
                        // uint16 + uint32 + tuint32
38✔
288
                        return 2 + 4 + tlv.SizeTUint32(uint32(i.BaseFee))
38✔
289
                }, encodePaymentRelay, decodePaymentRelay,
38✔
290
        )
291
}
292

293
func encodePaymentRelay(w io.Writer, val interface{}, buf *[8]byte) error {
38✔
294
        if t, ok := val.(**PaymentRelayInfo); ok {
76✔
295
                relayInfo := *t
38✔
296

38✔
297
                // Just write our first 6 bytes directly.
38✔
298
                binary.BigEndian.PutUint16(buf[:2], relayInfo.CltvExpiryDelta)
38✔
299
                binary.BigEndian.PutUint32(buf[2:6], relayInfo.FeeRate)
38✔
300
                if _, err := w.Write(buf[0:6]); err != nil {
38✔
301
                        return err
×
302
                }
×
303

304
                baseFee := uint32(relayInfo.BaseFee)
38✔
305

38✔
306
                // We can safely reuse buf here because we overwrite its
38✔
307
                // contents.
38✔
308
                return tlv.ETUint32(w, &baseFee, buf)
38✔
309
        }
310

311
        return tlv.NewTypeForEncodingErr(val, "**hop.PaymentRelayInfo")
×
312
}
313

314
func decodePaymentRelay(r io.Reader, val interface{}, buf *[8]byte,
315
        l uint64) error {
22✔
316

22✔
317
        if t, ok := val.(**PaymentRelayInfo); ok && l <= 10 {
44✔
318
                scratch := make([]byte, l)
22✔
319

22✔
320
                n, err := io.ReadFull(r, scratch)
22✔
321
                if err != nil {
22✔
322
                        return err
×
323
                }
×
324

325
                // We expect at least 6 bytes, because we have 2 bytes for
326
                // cltv delta and 4 bytes for fee rate.
327
                if n < 6 {
22✔
328
                        return tlv.NewTypeForDecodingErr(val,
×
329
                                "*hop.paymentRelayInfo", uint64(n), 6)
×
330
                }
×
331

332
                relayInfo := *t
22✔
333

22✔
334
                relayInfo.CltvExpiryDelta = binary.BigEndian.Uint16(
22✔
335
                        scratch[0:2],
22✔
336
                )
22✔
337
                relayInfo.FeeRate = binary.BigEndian.Uint32(scratch[2:6])
22✔
338

22✔
339
                // To be able to re-use the DTUint32 function we create a
22✔
340
                // buffer with just the bytes holding the variable length u32.
22✔
341
                // If the base fee is zero, this will be an empty buffer, which
22✔
342
                // is okay.
22✔
343
                b := bytes.NewBuffer(scratch[6:])
22✔
344

22✔
345
                var baseFee uint32
22✔
346
                err = tlv.DTUint32(b, &baseFee, buf, l-6)
22✔
347
                if err != nil {
22✔
348
                        return err
×
349
                }
×
350

351
                relayInfo.BaseFee = lnwire.MilliSatoshi(baseFee)
22✔
352

22✔
353
                return nil
22✔
354
        }
355

356
        return tlv.NewTypeForDecodingErr(val, "*hop.paymentRelayInfo", l, 10)
×
357
}
358

359
// PaymentConstraints is a set of restrictions on a payment.
360
type PaymentConstraints struct {
361
        // MaxCltvExpiry is the maximum expiry height for the payment.
362
        MaxCltvExpiry uint32
363

364
        // HtlcMinimumMsat is the minimum htlc size for the payment.
365
        HtlcMinimumMsat lnwire.MilliSatoshi
366
}
367

368
func (p *PaymentConstraints) Record() tlv.Record {
66✔
369
        return tlv.MakeDynamicRecord(
66✔
370
                12, &p, func() uint64 {
107✔
371
                        // uint32 + tuint64.
41✔
372
                        return 4 + tlv.SizeTUint64(uint64(
41✔
373
                                p.HtlcMinimumMsat,
41✔
374
                        ))
41✔
375
                },
41✔
376
                encodePaymentConstraints, decodePaymentConstraints,
377
        )
378
}
379

380
func encodePaymentConstraints(w io.Writer, val interface{},
381
        buf *[8]byte) error {
41✔
382

41✔
383
        if c, ok := val.(**PaymentConstraints); ok {
82✔
384
                constraints := *c
41✔
385

41✔
386
                binary.BigEndian.PutUint32(buf[:4], constraints.MaxCltvExpiry)
41✔
387
                if _, err := w.Write(buf[:4]); err != nil {
41✔
388
                        return err
×
389
                }
×
390

391
                // We can safely re-use buf here because we overwrite its
392
                // contents.
393
                htlcMsat := uint64(constraints.HtlcMinimumMsat)
41✔
394

41✔
395
                return tlv.ETUint64(w, &htlcMsat, buf)
41✔
396
        }
397

398
        return tlv.NewTypeForEncodingErr(val, "**PaymentConstraints")
×
399
}
400

401
func decodePaymentConstraints(r io.Reader, val interface{}, buf *[8]byte,
402
        l uint64) error {
19✔
403

19✔
404
        if c, ok := val.(**PaymentConstraints); ok && l <= 12 {
38✔
405
                scratch := make([]byte, l)
19✔
406

19✔
407
                n, err := io.ReadFull(r, scratch)
19✔
408
                if err != nil {
19✔
409
                        return err
×
410
                }
×
411

412
                // We expect at least 4 bytes for our uint32.
413
                if n < 4 {
19✔
414
                        return tlv.NewTypeForDecodingErr(val,
×
415
                                "*paymentConstraints", uint64(n), 4)
×
416
                }
×
417

418
                payConstraints := *c
19✔
419

19✔
420
                payConstraints.MaxCltvExpiry = binary.BigEndian.Uint32(
19✔
421
                        scratch[:4],
19✔
422
                )
19✔
423

19✔
424
                // This could be empty if our minimum is zero, that's okay.
19✔
425
                var (
19✔
426
                        b       = bytes.NewBuffer(scratch[4:])
19✔
427
                        minHtlc uint64
19✔
428
                )
19✔
429

19✔
430
                err = tlv.DTUint64(b, &minHtlc, buf, l-4)
19✔
431
                if err != nil {
19✔
432
                        return err
×
433
                }
×
434
                payConstraints.HtlcMinimumMsat = lnwire.MilliSatoshi(minHtlc)
19✔
435

19✔
436
                return nil
19✔
437
        }
438

439
        return tlv.NewTypeForDecodingErr(val, "**PaymentConstraints", l, l)
×
440
}
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