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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

94.7
/lnwire/features.go
1
package lnwire
2

3
import (
4
        "encoding/binary"
5
        "errors"
6
        "fmt"
7
        "io"
8

9
        "github.com/lightningnetwork/lnd/tlv"
10
)
11

12
var (
13
        // ErrFeaturePairExists signals an error in feature vector construction
14
        // where the opposing bit in a feature pair has already been set.
15
        ErrFeaturePairExists = errors.New("feature pair exists")
16

17
        // ErrFeatureStandard is returned when attempts to modify LND's known
18
        // set of features are made.
19
        ErrFeatureStandard = errors.New("feature is used in standard " +
20
                "protocol set")
21

22
        // ErrFeatureBitMaximum is returned when a feature bit exceeds the
23
        // maximum allowable value.
24
        ErrFeatureBitMaximum = errors.New("feature bit exceeds allowed maximum")
25
)
26

27
// FeatureBit represents a feature that can be enabled in either a local or
28
// global feature vector at a specific bit position. Feature bits follow the
29
// "it's OK to be odd" rule, where features at even bit positions must be known
30
// to a node receiving them from a peer while odd bits do not. In accordance,
31
// feature bits are usually assigned in pairs, first being assigned an odd bit
32
// position which may later be changed to the preceding even position once
33
// knowledge of the feature becomes required on the network.
34
type FeatureBit uint16
35

36
const (
37
        // DataLossProtectRequired is a feature bit that indicates that a peer
38
        // *requires* the other party know about the data-loss-protect optional
39
        // feature. If the remote peer does not know of such a feature, then
40
        // the sending peer SHOULD disconnect them. The data-loss-protect
41
        // feature allows a peer that's lost partial data to recover their
42
        // settled funds of the latest commitment state.
43
        DataLossProtectRequired FeatureBit = 0
44

45
        // DataLossProtectOptional is an optional feature bit that indicates
46
        // that the sending peer knows of this new feature and can activate it
47
        // it. The data-loss-protect feature allows a peer that's lost partial
48
        // data to recover their settled funds of the latest commitment state.
49
        DataLossProtectOptional FeatureBit = 1
50

51
        // InitialRoutingSync is a local feature bit meaning that the receiving
52
        // node should send a complete dump of routing information when a new
53
        // connection is established.
54
        InitialRoutingSync FeatureBit = 3
55

56
        // UpfrontShutdownScriptRequired is a feature bit which indicates that a
57
        // peer *requires* that the remote peer accept an upfront shutdown script to
58
        // which payout is enforced on cooperative closes.
59
        UpfrontShutdownScriptRequired FeatureBit = 4
60

61
        // UpfrontShutdownScriptOptional is an optional feature bit which indicates
62
        // that the peer will accept an upfront shutdown script to which payout is
63
        // enforced on cooperative closes.
64
        UpfrontShutdownScriptOptional FeatureBit = 5
65

66
        // GossipQueriesRequired is a feature bit that indicates that the
67
        // receiving peer MUST know of the set of features that allows nodes to
68
        // more efficiently query the network view of peers on the network for
69
        // reconciliation purposes.
70
        GossipQueriesRequired FeatureBit = 6
71

72
        // GossipQueriesOptional is an optional feature bit that signals that
73
        // the setting peer knows of the set of features that allows more
74
        // efficient network view reconciliation.
75
        GossipQueriesOptional FeatureBit = 7
76

77
        // TLVOnionPayloadRequired is a feature bit that indicates a node is
78
        // able to decode the new TLV information included in the onion packet.
79
        TLVOnionPayloadRequired FeatureBit = 8
80

81
        // TLVOnionPayloadOptional is an optional feature bit that indicates a
82
        // node is able to decode the new TLV information included in the onion
83
        // packet.
84
        TLVOnionPayloadOptional FeatureBit = 9
85

86
        // StaticRemoteKeyRequired is a required feature bit that signals that
87
        // within one's commitment transaction, the key used for the remote
88
        // party's non-delay output should not be tweaked.
89
        StaticRemoteKeyRequired FeatureBit = 12
90

91
        // StaticRemoteKeyOptional is an optional feature bit that signals that
92
        // within one's commitment transaction, the key used for the remote
93
        // party's non-delay output should not be tweaked.
94
        StaticRemoteKeyOptional FeatureBit = 13
95

96
        // PaymentAddrRequired is a required feature bit that signals that a
97
        // node requires payment addresses, which are used to mitigate probing
98
        // attacks on the receiver of a payment.
99
        PaymentAddrRequired FeatureBit = 14
100

101
        // PaymentAddrOptional is an optional feature bit that signals that a
102
        // node supports payment addresses, which are used to mitigate probing
103
        // attacks on the receiver of a payment.
104
        PaymentAddrOptional FeatureBit = 15
105

106
        // MPPRequired is a required feature bit that signals that the receiver
107
        // of a payment requires settlement of an invoice with more than one
108
        // HTLC.
109
        MPPRequired FeatureBit = 16
110

111
        // MPPOptional is an optional feature bit that signals that the receiver
112
        // of a payment supports settlement of an invoice with more than one
113
        // HTLC.
114
        MPPOptional FeatureBit = 17
115

116
        // WumboChannelsRequired is a required feature bit that signals that a
117
        // node is willing to accept channels larger than 2^24 satoshis.
118
        WumboChannelsRequired FeatureBit = 18
119

120
        // WumboChannelsOptional is an optional feature bit that signals that a
121
        // node is willing to accept channels larger than 2^24 satoshis.
122
        WumboChannelsOptional FeatureBit = 19
123

124
        // AnchorsRequired is a required feature bit that signals that the node
125
        // requires channels to be made using commitments having anchor
126
        // outputs.
127
        AnchorsRequired FeatureBit = 20
128

129
        // AnchorsOptional is an optional feature bit that signals that the
130
        // node supports channels to be made using commitments having anchor
131
        // outputs.
132
        AnchorsOptional FeatureBit = 21
133

134
        // AnchorsZeroFeeHtlcTxRequired is a required feature bit that signals
135
        // that the node requires channels having zero-fee second-level HTLC
136
        // transactions, which also imply anchor commitments.
137
        AnchorsZeroFeeHtlcTxRequired FeatureBit = 22
138

139
        // AnchorsZeroFeeHtlcTxOptional is an optional feature bit that signals
140
        // that the node supports channels having zero-fee second-level HTLC
141
        // transactions, which also imply anchor commitments.
142
        AnchorsZeroFeeHtlcTxOptional FeatureBit = 23
143

144
        // RouteBlindingRequired is a required feature bit that signals that
145
        // the node supports blinded payments.
146
        RouteBlindingRequired FeatureBit = 24
147

148
        // RouteBlindingOptional is an optional feature bit that signals that
149
        // the node supports blinded payments.
150
        RouteBlindingOptional FeatureBit = 25
151

152
        // ShutdownAnySegwitRequired is an required feature bit that signals
153
        // that the sender is able to properly handle/parse segwit witness
154
        // programs up to version 16. This enables utilization of Taproot
155
        // addresses for cooperative closure addresses.
156
        ShutdownAnySegwitRequired FeatureBit = 26
157

158
        // ShutdownAnySegwitOptional is an optional feature bit that signals
159
        // that the sender is able to properly handle/parse segwit witness
160
        // programs up to version 16. This enables utilization of Taproot
161
        // addresses for cooperative closure addresses.
162
        ShutdownAnySegwitOptional FeatureBit = 27
163

164
        // AMPRequired is a required feature bit that signals that the receiver
165
        // of a payment supports accepts spontaneous payments, i.e.
166
        // sender-generated preimages according to BOLT XX.
167
        AMPRequired FeatureBit = 30
168

169
        // AMPOptional is an optional feature bit that signals that the receiver
170
        // of a payment supports accepts spontaneous payments, i.e.
171
        // sender-generated preimages according to BOLT XX.
172
        AMPOptional FeatureBit = 31
173

174
        // ExplicitChannelTypeRequired is a required bit that denotes that a
175
        // connection established with this node is to use explicit channel
176
        // commitment types for negotiation instead of the existing implicit
177
        // negotiation methods. With this bit, there is no longer a "default"
178
        // implicit channel commitment type, allowing a connection to
179
        // open/maintain types of several channels over its lifetime.
180
        ExplicitChannelTypeRequired = 44
181

182
        // ExplicitChannelTypeOptional is an optional bit that denotes that a
183
        // connection established with this node is to use explicit channel
184
        // commitment types for negotiation instead of the existing implicit
185
        // negotiation methods. With this bit, there is no longer a "default"
186
        // implicit channel commitment type, allowing a connection to
187
        // TODO: Decide on actual feature bit value.
188
        ExplicitChannelTypeOptional = 45
189

190
        // ScidAliasRequired is a required feature bit that signals that the
191
        // node requires understanding of ShortChannelID aliases in the TLV
192
        // segment of the channel_ready message.
193
        ScidAliasRequired FeatureBit = 46
194

195
        // ScidAliasOptional is an optional feature bit that signals that the
196
        // node understands ShortChannelID aliases in the TLV segment of the
197
        // channel_ready message.
198
        ScidAliasOptional FeatureBit = 47
199

200
        // PaymentMetadataRequired is a required bit that denotes that if an
201
        // invoice contains metadata, it must be passed along with the payment
202
        // htlc(s).
203
        PaymentMetadataRequired = 48
204

205
        // PaymentMetadataOptional is an optional bit that denotes that if an
206
        // invoice contains metadata, it may be passed along with the payment
207
        // htlc(s).
208
        PaymentMetadataOptional = 49
209

210
        // ZeroConfRequired is a required feature bit that signals that the
211
        // node requires understanding of the zero-conf channel_type.
212
        ZeroConfRequired FeatureBit = 50
213

214
        // ZeroConfOptional is an optional feature bit that signals that the
215
        // node understands the zero-conf channel type.
216
        ZeroConfOptional FeatureBit = 51
217

218
        // KeysendRequired is a required bit that indicates that the node is
219
        // able and willing to accept keysend payments.
220
        KeysendRequired = 54
221

222
        // KeysendOptional is an optional bit that indicates that the node is
223
        // able and willing to accept keysend payments.
224
        KeysendOptional = 55
225

226
        // ScriptEnforcedLeaseRequired is a required feature bit that signals
227
        // that the node requires channels having zero-fee second-level HTLC
228
        // transactions, which also imply anchor commitments, along with an
229
        // additional CLTV constraint of a channel lease's expiration height
230
        // applied to all outputs that pay directly to the channel initiator.
231
        //
232
        // TODO: Decide on actual feature bit value.
233
        ScriptEnforcedLeaseRequired FeatureBit = 2022
234

235
        // ScriptEnforcedLeaseOptional is an optional feature bit that signals
236
        // that the node requires channels having zero-fee second-level HTLC
237
        // transactions, which also imply anchor commitments, along with an
238
        // additional CLTV constraint of a channel lease's expiration height
239
        // applied to all outputs that pay directly to the channel initiator.
240
        //
241
        // TODO: Decide on actual feature bit value.
242
        ScriptEnforcedLeaseOptional FeatureBit = 2023
243

244
        // SimpleTaprootChannelsRequiredFinal is a required bit that indicates
245
        // the node is able to create taproot-native channels. This is the
246
        // final feature bit to be used once the channel type is finalized.
247
        SimpleTaprootChannelsRequiredFinal = 80
248

249
        // SimpleTaprootChannelsOptionalFinal is an optional bit that indicates
250
        // the node is able to create taproot-native channels. This is the
251
        // final feature bit to be used once the channel type is finalized.
252
        SimpleTaprootChannelsOptionalFinal = 81
253

254
        // SimpleTaprootChannelsRequiredStaging is a required bit that indicates
255
        // the node is able to create taproot-native channels. This is a
256
        // feature bit used in the wild while the channel type is still being
257
        // finalized.
258
        SimpleTaprootChannelsRequiredStaging = 180
259

260
        // SimpleTaprootChannelsOptionalStaging is an optional bit that
261
        // indicates the node is able to create taproot-native channels. This
262
        // is a feature bit used in the wild while the channel type is still
263
        // being finalized.
264
        SimpleTaprootChannelsOptionalStaging = 181
265

266
        // Bolt11BlindedPathsRequired is a required feature bit that indicates
267
        // that the node is able to understand the blinded path tagged field in
268
        // a BOLT 11 invoice.
269
        Bolt11BlindedPathsRequired = 262
270

271
        // Bolt11BlindedPathsOptional is an optional feature bit that indicates
272
        // that the node is able to understand the blinded path tagged field in
273
        // a BOLT 11 invoice.
274
        Bolt11BlindedPathsOptional = 263
275

276
        // MaxBolt11Feature is the maximum feature bit value allowed in bolt 11
277
        // invoices.
278
        //
279
        // The base 32 encoded tagged fields in invoices are limited to 10 bits
280
        // to express the length of the field's data.
281
        //nolint:lll
282
        // See: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#tagged-fields
283
        //
284
        // With a maximum length field of 1023 (2^10 -1) and 5 bit encoding,
285
        // the highest feature bit that can be expressed is:
286
        // 1023 * 5 - 1 = 5114.
287
        MaxBolt11Feature = 5114
288
)
289

290
// IsRequired returns true if the feature bit is even, and false otherwise.
291
func (b FeatureBit) IsRequired() bool {
292
        return b&0x01 == 0x00
293
}
294

295
// Features is a mapping of known feature bits to a descriptive name. All known
296
// feature bits must be assigned a name in this mapping, and feature bit pairs
297
// must be assigned together for correct behavior.
298
var Features = map[FeatureBit]string{
299
        DataLossProtectRequired:              "data-loss-protect",
3,559✔
300
        DataLossProtectOptional:              "data-loss-protect",
3,559✔
301
        InitialRoutingSync:                   "initial-routing-sync",
3,559✔
302
        UpfrontShutdownScriptRequired:        "upfront-shutdown-script",
303
        UpfrontShutdownScriptOptional:        "upfront-shutdown-script",
304
        GossipQueriesRequired:                "gossip-queries",
305
        GossipQueriesOptional:                "gossip-queries",
306
        TLVOnionPayloadRequired:              "tlv-onion",
307
        TLVOnionPayloadOptional:              "tlv-onion",
308
        StaticRemoteKeyOptional:              "static-remote-key",
309
        StaticRemoteKeyRequired:              "static-remote-key",
310
        PaymentAddrOptional:                  "payment-addr",
311
        PaymentAddrRequired:                  "payment-addr",
312
        MPPOptional:                          "multi-path-payments",
313
        MPPRequired:                          "multi-path-payments",
314
        AnchorsRequired:                      "anchor-commitments",
315
        AnchorsOptional:                      "anchor-commitments",
316
        AnchorsZeroFeeHtlcTxRequired:         "anchors-zero-fee-htlc-tx",
317
        AnchorsZeroFeeHtlcTxOptional:         "anchors-zero-fee-htlc-tx",
318
        WumboChannelsRequired:                "wumbo-channels",
319
        WumboChannelsOptional:                "wumbo-channels",
320
        AMPRequired:                          "amp",
321
        AMPOptional:                          "amp",
322
        PaymentMetadataOptional:              "payment-metadata",
323
        PaymentMetadataRequired:              "payment-metadata",
324
        ExplicitChannelTypeOptional:          "explicit-commitment-type",
325
        ExplicitChannelTypeRequired:          "explicit-commitment-type",
326
        KeysendOptional:                      "keysend",
327
        KeysendRequired:                      "keysend",
328
        ScriptEnforcedLeaseRequired:          "script-enforced-lease",
329
        ScriptEnforcedLeaseOptional:          "script-enforced-lease",
330
        ScidAliasRequired:                    "scid-alias",
331
        ScidAliasOptional:                    "scid-alias",
332
        ZeroConfRequired:                     "zero-conf",
333
        ZeroConfOptional:                     "zero-conf",
334
        RouteBlindingRequired:                "route-blinding",
335
        RouteBlindingOptional:                "route-blinding",
336
        ShutdownAnySegwitRequired:            "shutdown-any-segwit",
337
        ShutdownAnySegwitOptional:            "shutdown-any-segwit",
338
        SimpleTaprootChannelsRequiredFinal:   "simple-taproot-chans",
339
        SimpleTaprootChannelsOptionalFinal:   "simple-taproot-chans",
340
        SimpleTaprootChannelsRequiredStaging: "simple-taproot-chans-x",
341
        SimpleTaprootChannelsOptionalStaging: "simple-taproot-chans-x",
342
        Bolt11BlindedPathsOptional:           "bolt-11-blinded-paths",
343
        Bolt11BlindedPathsRequired:           "bolt-11-blinded-paths",
344
}
345

346
// RawFeatureVector represents a set of feature bits as defined in BOLT-09.  A
347
// RawFeatureVector itself just stores a set of bit flags but can be used to
348
// construct a FeatureVector which binds meaning to each bit. Feature vectors
349
// can be serialized and deserialized to/from a byte representation that is
350
// transmitted in Lightning network messages.
351
type RawFeatureVector struct {
352
        features map[FeatureBit]struct{}
353
}
354

355
// NewRawFeatureVector creates a feature vector with all of the feature bits
356
// given as arguments enabled.
357
func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
358
        fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
359
        for _, bit := range bits {
360
                fv.Set(bit)
361
        }
362
        return fv
363
}
364

365
// IsEmpty returns whether the feature vector contains any feature bits.
366
func (fv RawFeatureVector) IsEmpty() bool {
367
        return len(fv.features) == 0
25,480✔
368
}
25,480✔
369

26,646✔
370
// OnlyContains determines whether only the specified feature bits are found.
1,166✔
371
func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
1,166✔
372
        if len(bits) != len(fv.features) {
25,480✔
373
                return false
374
        }
375
        for _, bit := range bits {
376
                if !fv.IsSet(bit) {
8✔
377
                        return false
8✔
378
                }
8✔
379
        }
380
        return true
381
}
184✔
382

332✔
383
// Equals determines whether two features vectors contain exactly the same
148✔
384
// features.
148✔
385
func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
113✔
386
        if len(fv.features) != len(other.features) {
91✔
387
                return false
16✔
388
        }
16✔
389
        for bit := range fv.features {
390
                if _, ok := other.features[bit]; !ok {
24✔
391
                        return false
392
                }
393
        }
394
        return true
395
}
24✔
396

25✔
397
// Merges sets all feature bits in other on the receiver's feature vector.
1✔
398
func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
1✔
399
        for bit := range other.features {
64✔
400
                err := fv.SafeSet(bit)
42✔
401
                if err != nil {
1✔
402
                        return err
1✔
403
                }
404
        }
22✔
405
        return nil
406
}
407

408
// ValidateUpdate checks whether a feature vector can safely be updated to the
5✔
409
// new feature vector provided, checking that it does not alter any of the
13✔
410
// "standard" features that are defined by LND. The new feature vector should
8✔
411
// be inclusive of all features in the original vector that it still wants to
8✔
412
// advertise, setting and unsetting updates as desired. Features in the vector
×
413
// are also checked against a maximum inclusive value, as feature vectors in
×
414
// different contexts have different maximum values.
415
func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
5✔
416
        maximumValue FeatureBit) error {
417

418
        // Run through the new set of features and check that we're not adding
419
        // any feature bits that are defined but not set in LND.
420
        for feature := range other.features {
421
                if fv.IsSet(feature) {
422
                        continue
423
                }
424

425
                if feature > maximumValue {
426
                        return fmt.Errorf("can't set feature bit %d: %w %v",
16✔
427
                                feature, ErrFeatureBitMaximum,
16✔
428
                                maximumValue)
16✔
429
                }
16✔
430

41✔
431
                if name, known := Features[feature]; known {
41✔
432
                        return fmt.Errorf("can't set feature "+
16✔
433
                                "bit %d (%v): %w", feature, name,
434
                                ErrFeatureStandard)
435
                }
12✔
436
        }
1✔
437

1✔
438
        // Check that the new feature vector for this set does not unset any
1✔
439
        // features that are standard in LND by comparing the features in our
1✔
440
        // current set to the omitted values in the new set.
441
        for feature := range fv.features {
13✔
442
                if other.IsSet(feature) {
3✔
443
                        continue
3✔
444
                }
3✔
445

3✔
446
                if name, known := Features[feature]; known {
447
                        return fmt.Errorf("can't unset feature "+
448
                                "bit %d (%v): %w", feature, name,
449
                                ErrFeatureStandard)
450
                }
451
        }
31✔
452

31✔
453
        return nil
14✔
454
}
455

456
// ValidatePairs checks each feature bit in a raw vector to ensure that the
6✔
457
// opposing bit is not set, validating that the vector has either the optional
1✔
458
// or required bit set, not both.
1✔
459
func (fv *RawFeatureVector) ValidatePairs() error {
1✔
460
        for feature := range fv.features {
1✔
461
                if _, ok := fv.features[feature^1]; ok {
462
                        return ErrFeaturePairExists
463
                }
13✔
464
        }
465

466
        return nil
467
}
468

469
// Clone makes a copy of a feature vector.
13✔
470
func (fv *RawFeatureVector) Clone() *RawFeatureVector {
32✔
471
        newFeatures := NewRawFeatureVector()
22✔
472
        for bit := range fv.features {
3✔
473
                newFeatures.Set(bit)
3✔
474
        }
475
        return newFeatures
476
}
10✔
477

478
// IsSet returns whether a particular feature bit is enabled in the vector.
479
func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
480
        _, ok := fv.features[feature]
2,732✔
481
        return ok
2,732✔
482
}
3,267✔
483

535✔
484
// Set marks a feature as enabled in the vector.
535✔
485
func (fv *RawFeatureVector) Set(feature FeatureBit) {
2,732✔
486
        fv.features[feature] = struct{}{}
487
}
488

489
// SafeSet sets the chosen feature bit in the feature vector, but returns an
29,970✔
490
// error if the opposing feature bit is already set. This ensures both that we
29,970✔
491
// are creating properly structured feature vectors, and in some cases, that
29,970✔
492
// peers are sending properly encoded ones, i.e. it can't be both optional and
29,970✔
493
// required.
494
func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
495
        if _, ok := fv.features[feature^1]; ok {
7,319,023✔
496
                return ErrFeaturePairExists
7,319,023✔
497
        }
7,319,023✔
498

499
        fv.Set(feature)
500
        return nil
501
}
502

503
// Unset marks a feature as disabled in the vector.
504
func (fv *RawFeatureVector) Unset(feature FeatureBit) {
125✔
505
        delete(fv.features, feature)
126✔
506
}
1✔
507

1✔
508
// SerializeSize returns the number of bytes needed to represent feature vector
509
// in byte format.
124✔
510
func (fv *RawFeatureVector) SerializeSize() int {
124✔
511
        // We calculate byte-length via the largest bit index.
512
        return fv.serializeSize(8)
513
}
514

164✔
515
// SerializeSize32 returns the number of bytes needed to represent feature
164✔
516
// vector in base32 format.
164✔
517
func (fv *RawFeatureVector) SerializeSize32() int {
518
        // We calculate base32-length via the largest bit index.
519
        return fv.serializeSize(5)
520
}
7,499✔
521

7,499✔
522
// serializeSize returns the number of bytes required to encode the feature
7,499✔
523
// vector using at most width bits per encoded byte.
7,499✔
524
func (fv *RawFeatureVector) serializeSize(width int) int {
525
        // Find the largest feature bit index
526
        max := -1
527
        for feature := range fv.features {
195✔
528
                index := int(feature)
195✔
529
                if index > max {
195✔
530
                        max = index
195✔
531
                }
532
        }
533
        if max == -1 {
534
                return 0
7,692✔
535
        }
7,692✔
536

7,692✔
537
        return max/width + 1
4,725,475✔
538
}
4,717,783✔
539

4,732,005✔
540
// Encode writes the feature vector in byte representation. Every feature
14,222✔
541
// encoded as a bit, and the bit vector is serialized using the least number of
14,222✔
542
// bytes. Since the bit vector length is variable, the first two bytes of the
543
// serialization represent the length.
12,613✔
544
func (fv *RawFeatureVector) Encode(w io.Writer) error {
4,921✔
545
        // Write length of feature vector.
4,921✔
546
        var l [2]byte
547
        length := fv.SerializeSize()
2,773✔
548
        binary.BigEndian.PutUint16(l[:], uint16(length))
549
        if _, err := w.Write(l[:]); err != nil {
550
                return err
551
        }
552

553
        return fv.encode(w, length, 8)
554
}
4,193✔
555

4,193✔
556
// EncodeBase256 writes the feature vector in base256 representation. Every
4,193✔
557
// feature is encoded as a bit, and the bit vector is serialized using the least
4,193✔
558
// number of bytes.
4,193✔
559
func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
4,193✔
560
        length := fv.SerializeSize()
×
561
        return fv.encode(w, length, 8)
×
562
}
563

4,193✔
564
// EncodeBase32 writes the feature vector in base32 representation. Every feature
565
// is encoded as a bit, and the bit vector is serialized using the least number of
566
// bytes.
567
func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
568
        length := fv.SerializeSize32()
569
        return fv.encode(w, length, 5)
2,502✔
570
}
2,502✔
571

2,502✔
572
// encode writes the feature vector
2,502✔
573
func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
574
        // Generate the data and write it.
575
        data := make([]byte, length)
576
        for feature := range fv.features {
577
                byteIndex := int(feature) / width
22✔
578
                bitIndex := int(feature) % width
22✔
579
                data[length-byteIndex-1] |= 1 << uint(bitIndex)
22✔
580
        }
22✔
581

582
        _, err := w.Write(data)
583
        return err
7,116✔
584
}
7,116✔
585

7,116✔
586
// Decode reads the feature vector from its byte representation. Every feature
3,653,225✔
587
// is encoded as a bit, and the bit vector is serialized using the least number
3,646,109✔
588
// of bytes. Since the bit vector length is variable, the first two bytes of the
3,646,109✔
589
// serialization represent the length.
3,646,109✔
590
func (fv *RawFeatureVector) Decode(r io.Reader) error {
3,646,109✔
591
        // Read the length of the feature vector.
592
        var l [2]byte
7,116✔
593
        if _, err := io.ReadFull(r, l[:]); err != nil {
7,116✔
594
                return err
595
        }
596
        length := binary.BigEndian.Uint16(l[:])
597

598
        return fv.decode(r, int(length), 8)
599
}
600

10,640✔
601
// DecodeBase256 reads the feature vector from its base256 representation. Every
10,640✔
602
// feature encoded as a bit, and the bit vector is serialized using the least
10,640✔
603
// number of bytes.
10,653✔
604
func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
13✔
605
        return fv.decode(r, length, 8)
13✔
606
}
10,627✔
607

10,627✔
608
// DecodeBase32 reads the feature vector from its base32 representation. Every
10,627✔
609
// feature encoded as a bit, and the bit vector is serialized using the least
610
// number of bytes.
611
func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
612
        return fv.decode(r, length, 5)
613
}
614

3,554✔
615
// decode reads a feature vector from the next length bytes of the io.Reader,
3,554✔
616
// assuming each byte has width feature bits encoded per byte.
3,554✔
617
func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
618
        // Read the feature vector data.
619
        data := make([]byte, length)
620
        if _, err := io.ReadFull(r, data); err != nil {
621
                return err
36✔
622
        }
36✔
623

36✔
624
        // Set feature bits from parsed data.
625
        bitsNumber := len(data) * width
626
        for i := 0; i < bitsNumber; i++ {
627
                byteIndex := int(i / width)
14,720✔
628
                bitIndex := uint(i % width)
14,720✔
629
                if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
14,720✔
630
                        fv.Set(FeatureBit(i))
14,732✔
631
                }
12✔
632
        }
12✔
633

634
        return nil
635
}
14,708✔
636

7,857,150✔
637
// sizeFunc returns the length required to encode the feature vector.
7,842,442✔
638
func (fv *RawFeatureVector) sizeFunc() uint64 {
7,842,442✔
639
        return uint64(fv.SerializeSize())
11,599,601✔
640
}
3,757,159✔
641

3,757,159✔
642
// Record returns a TLV record that can be used to encode/decode raw feature
643
// vectors. Note that the length of the feature vector is not included, because
644
// it is covered by the TLV record's length field.
14,708✔
645
func (fv *RawFeatureVector) Record() tlv.Record {
646
        return tlv.MakeDynamicRecord(
647
                0, fv, fv.sizeFunc, rawFeatureEncoder, rawFeatureDecoder,
648
        )
350✔
649
}
350✔
650

350✔
651
// rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
652
func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
653
        if v, ok := val.(*RawFeatureVector); ok {
654
                // Encode the feature bits as a byte slice without its length
655
                // prepended, as that's already taken care of by the TLV record.
204✔
656
                fv := *v
204✔
657
                return fv.encode(w, fv.SerializeSize(), 8)
204✔
658
        }
204✔
659

204✔
660
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
661
}
662

350✔
663
// rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
700✔
664
func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
350✔
665
        l uint64) error {
350✔
666

350✔
667
        if v, ok := val.(*RawFeatureVector); ok {
350✔
668
                fv := NewRawFeatureVector()
350✔
669
                if err := fv.decode(r, int(l), 8); err != nil {
670
                        return err
×
671
                }
672
                *v = *fv
673

674
                return nil
675
        }
454✔
676

454✔
677
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
908✔
678
}
454✔
679

457✔
680
// FeatureVector represents a set of enabled features. The set stores
3✔
681
// information on enabled flags and metadata about the feature names. A feature
3✔
682
// vector is serializable to a compact byte representation that is included in
451✔
683
// Lightning network messages.
451✔
684
type FeatureVector struct {
451✔
685
        *RawFeatureVector
686
        featureNames map[FeatureBit]string
687
}
×
688

689
// NewFeatureVector constructs a new FeatureVector from a raw feature vector
690
// and mapping of feature definitions. If the feature vector argument is nil, a
691
// new one will be constructed with no enabled features.
692
func NewFeatureVector(featureVector *RawFeatureVector,
693
        featureNames map[FeatureBit]string) *FeatureVector {
694

695
        if featureVector == nil {
696
                featureVector = NewRawFeatureVector()
697
        }
698
        return &FeatureVector{
699
                RawFeatureVector: featureVector,
700
                featureNames:     featureNames,
701
        }
702
}
703

21,912✔
704
// EmptyFeatureVector returns a feature vector with no bits set.
21,912✔
705
func EmptyFeatureVector() *FeatureVector {
35,696✔
706
        return NewFeatureVector(nil, Features)
13,784✔
707
}
13,784✔
708

21,912✔
709
// Record implements the RecordProducer interface for FeatureVector. Note that
21,912✔
710
// it uses a zero-value type is used to produce the record, as we expect this
21,912✔
711
// type value to be overwritten when used in generic TLV record production.
21,912✔
712
// This allows a single Record function to serve in the many different contexts
713
// in which feature vectors are encoded. This record wraps the encoding/
714
// decoding for our raw feature vectors so that we can directly parse fully
715
// formed feature vector types.
12,615✔
716
func (fv *FeatureVector) Record() tlv.Record {
12,615✔
717
        return tlv.MakeDynamicRecord(0, fv, fv.sizeFunc,
12,615✔
718
                func(w io.Writer, val interface{}, buf *[8]byte) error {
719
                        if f, ok := val.(*FeatureVector); ok {
720
                                return rawFeatureEncoder(
721
                                        w, f.RawFeatureVector, buf,
722
                                )
723
                        }
724

725
                        return tlv.NewTypeForEncodingErr(
726
                                val, "*lnwire.FeatureVector",
29✔
727
                        )
29✔
728
                },
31✔
729
                func(r io.Reader, val interface{}, buf *[8]byte,
4✔
730
                        l uint64) error {
2✔
731

2✔
732
                        if f, ok := val.(*FeatureVector); ok {
2✔
733
                                features := NewFeatureVector(nil, Features)
2✔
734
                                err := rawFeatureDecoder(
735
                                        r, features.RawFeatureVector, buf, l,
×
736
                                )
×
737
                                if err != nil {
×
738
                                        return err
739
                                }
740

4✔
741
                                *f = *features
4✔
742

8✔
743
                                return nil
4✔
744
                        }
4✔
745

4✔
746
                        return tlv.NewTypeForDecodingErr(
4✔
747
                                val, "*lnwire.FeatureVector", l, l,
4✔
748
                        )
×
749
                },
×
750
        )
751
}
4✔
752

4✔
753
// HasFeature returns whether a particular feature is included in the set. The
4✔
754
// feature can be seen as set either if the bit is set directly OR the queried
755
// bit has the same meaning as its corresponding even/odd bit, which is set
756
// instead. The second case is because feature bits are generally assigned in
×
757
// pairs where both the even and odd position represent the same feature.
×
758
func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
×
759
        return fv.IsSet(feature) ||
760
                (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
761
}
762

763
// RequiresFeature returns true if the referenced feature vector *requires*
764
// that the given required bit be set. This method can be used with both
765
// optional and required feature bits as a parameter.
766
func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
767
        // If we weren't passed a required feature bit, then we'll flip the
768
        // lowest bit to query for the required version of the feature. This
14,591✔
769
        // lets callers pass in both the optional and required bits.
14,591✔
770
        if !feature.IsRequired() {
14,591✔
771
                feature ^= 1
14,591✔
772
        }
773

774
        return fv.IsSet(feature)
775
}
776

1,990✔
777
// UnknownRequiredFeatures returns a list of feature bits set in the vector
1,990✔
778
// that are unknown and in an even bit position. Feature bits with an even
1,990✔
779
// index must be known to a node receiving the feature vector in a message.
1,990✔
780
func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
1,992✔
781
        var unknown []FeatureBit
2✔
782
        for feature := range fv.features {
2✔
783
                if feature%2 == 0 && !fv.IsKnown(feature) {
784
                        unknown = append(unknown, feature)
1,990✔
785
                }
786
        }
787
        return unknown
788
}
789

790
// UnknownFeatures returns a boolean if a feature vector contains *any*
1,868✔
791
// unknown features (even if they are odd).
1,868✔
792
func (fv *FeatureVector) UnknownFeatures() bool {
3,470✔
793
        for feature := range fv.features {
1,610✔
794
                if !fv.IsKnown(feature) {
8✔
795
                        return true
8✔
796
                }
797
        }
1,868✔
798

799
        return false
800
}
801

802
// Name returns a string identifier for the feature represented by this bit. If
1✔
803
// the bit does not represent a known feature, this returns a string indicating
2✔
804
// as such.
2✔
805
func (fv *FeatureVector) Name(bit FeatureBit) string {
1✔
806
        name, known := fv.featureNames[bit]
1✔
807
        if !known {
808
                return "unknown"
809
        }
×
810
        return name
811
}
812

813
// IsKnown returns whether this feature bit represents a known feature.
814
func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
815
        _, known := fv.featureNames[bit]
10✔
816
        return known
10✔
817
}
16✔
818

6✔
819
// isFeatureBitPair returns whether this feature bit and its corresponding
6✔
820
// even/odd bit both represent the same feature. This may often be the case as
6✔
821
// bits are generally assigned in pairs, first being assigned an odd bit
822
// position then being promoted to an even bit position once the network is
823
// ready.
824
func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
633✔
825
        name1, known1 := fv.featureNames[bit]
633✔
826
        name2, known2 := fv.featureNames[bit^1]
633✔
827
        return known1 && known2 && name1 == name2
633✔
828
}
829

830
// Features returns the set of raw features contained in the feature vector.
831
func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
832
        fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
833
        for b := range fv.RawFeatureVector.features {
834
                fs[b] = struct{}{}
13,784✔
835
        }
13,784✔
836
        return fs
13,784✔
837
}
13,784✔
838

13,784✔
839
// Clone copies a feature vector, carrying over its feature bits. The feature
840
// names are not copied.
841
func (fv *FeatureVector) Clone() *FeatureVector {
3,292✔
842
        features := fv.RawFeatureVector.Clone()
3,292✔
843
        return NewFeatureVector(features, fv.featureNames)
3,930✔
844
}
638✔
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