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

lightningnetwork / lnd / 12199391122

06 Dec 2024 01:10PM UTC coverage: 49.807% (-9.1%) from 58.933%
12199391122

push

github

web-flow
Merge pull request #9337 from Guayaba221/patch-1

chore: fix typo in ruby.md

100137 of 201051 relevant lines covered (49.81%)

2.07 hits per line

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

83.08
/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 {
4✔
64

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

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

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

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

90
        return info
4✔
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 {
4✔
97

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

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

110
        return &data
4✔
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 {
4✔
119

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

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

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

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

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

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

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

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

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

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

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

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

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

195
        return &d, nil
4✔
196
}
197

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

4✔
205
        data.Padding.WhenSome(func(p tlv.RecordT[tlv.TlvType1, []byte]) {
8✔
206
                recordProducers = append(recordProducers, &p)
4✔
207
        })
4✔
208

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

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

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

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

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

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

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

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

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

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

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

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

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

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

253
        return e[:], nil
4✔
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) {
4✔
264
        b.Padding = tlv.SomeRecordT(
4✔
265
                tlv.NewPrimitiveRecord[tlv.TlvType1](make([]byte, n)),
4✔
266
        )
4✔
267
}
4✔
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 {
4✔
285
        return tlv.MakeDynamicRecord(
4✔
286
                10, &i, func() uint64 {
8✔
287
                        // uint16 + uint32 + tuint32
4✔
288
                        return 2 + 4 + tlv.SizeTUint32(uint32(i.BaseFee))
4✔
289
                }, encodePaymentRelay, decodePaymentRelay,
4✔
290
        )
291
}
292

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

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

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

4✔
306
                // We can safely reuse buf here because we overwrite its
4✔
307
                // contents.
4✔
308
                return tlv.ETUint32(w, &baseFee, buf)
4✔
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 {
4✔
316

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

4✔
320
                n, err := io.ReadFull(r, scratch)
4✔
321
                if err != nil {
4✔
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 {
4✔
328
                        return tlv.NewTypeForDecodingErr(val,
×
329
                                "*hop.paymentRelayInfo", uint64(n), 6)
×
330
                }
×
331

332
                relayInfo := *t
4✔
333

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

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

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

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

4✔
353
                return nil
4✔
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 {
4✔
369
        return tlv.MakeDynamicRecord(
4✔
370
                12, &p, func() uint64 {
8✔
371
                        // uint32 + tuint64.
4✔
372
                        return 4 + tlv.SizeTUint64(uint64(
4✔
373
                                p.HtlcMinimumMsat,
4✔
374
                        ))
4✔
375
                },
4✔
376
                encodePaymentConstraints, decodePaymentConstraints,
377
        )
378
}
379

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

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

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

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

4✔
395
                return tlv.ETUint64(w, &htlcMsat, buf)
4✔
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 {
4✔
403

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

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

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

418
                payConstraints := *c
4✔
419

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

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

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

4✔
436
                return nil
4✔
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