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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

76.33
/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
        // SimpleTaprootOverlayChansRequired is a required bit that indicates
277
        // support for the special custom taproot overlay channel.
278
        SimpleTaprootOverlayChansOptional = 2025
279

280
        // SimpleTaprootOverlayChansRequired is a required bit that indicates
281
        // support for the special custom taproot overlay channel.
282
        SimpleTaprootOverlayChansRequired = 2026
283

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

298
// IsRequired returns true if the feature bit is even, and false otherwise.
299
func (b FeatureBit) IsRequired() bool {
2✔
300
        return b&0x01 == 0x00
2✔
301
}
2✔
302

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

356
// RawFeatureVector represents a set of feature bits as defined in BOLT-09.  A
357
// RawFeatureVector itself just stores a set of bit flags but can be used to
358
// construct a FeatureVector which binds meaning to each bit. Feature vectors
359
// can be serialized and deserialized to/from a byte representation that is
360
// transmitted in Lightning network messages.
361
type RawFeatureVector struct {
362
        features map[FeatureBit]struct{}
363
}
364

365
// NewRawFeatureVector creates a feature vector with all of the feature bits
366
// given as arguments enabled.
367
func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
2✔
368
        fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
2✔
369
        for _, bit := range bits {
4✔
370
                fv.Set(bit)
2✔
371
        }
2✔
372
        return fv
2✔
373
}
374

375
// IsEmpty returns whether the feature vector contains any feature bits.
376
func (fv RawFeatureVector) IsEmpty() bool {
2✔
377
        return len(fv.features) == 0
2✔
378
}
2✔
379

380
// OnlyContains determines whether only the specified feature bits are found.
381
func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
2✔
382
        if len(bits) != len(fv.features) {
4✔
383
                return false
2✔
384
        }
2✔
385
        for _, bit := range bits {
4✔
386
                if !fv.IsSet(bit) {
4✔
387
                        return false
2✔
388
                }
2✔
389
        }
390
        return true
2✔
391
}
392

393
// Equals determines whether two features vectors contain exactly the same
394
// features.
395
func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
2✔
396
        if len(fv.features) != len(other.features) {
2✔
UNCOV
397
                return false
×
UNCOV
398
        }
×
399
        for bit := range fv.features {
4✔
400
                if _, ok := other.features[bit]; !ok {
2✔
UNCOV
401
                        return false
×
UNCOV
402
                }
×
403
        }
404
        return true
2✔
405
}
406

407
// Merges sets all feature bits in other on the receiver's feature vector.
408
func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
2✔
409
        for bit := range other.features {
4✔
410
                err := fv.SafeSet(bit)
2✔
411
                if err != nil {
2✔
412
                        return err
×
413
                }
×
414
        }
415
        return nil
2✔
416
}
417

418
// ValidateUpdate checks whether a feature vector can safely be updated to the
419
// new feature vector provided, checking that it does not alter any of the
420
// "standard" features that are defined by LND. The new feature vector should
421
// be inclusive of all features in the original vector that it still wants to
422
// advertise, setting and unsetting updates as desired. Features in the vector
423
// are also checked against a maximum inclusive value, as feature vectors in
424
// different contexts have different maximum values.
425
func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
426
        maximumValue FeatureBit) error {
2✔
427

2✔
428
        // Run through the new set of features and check that we're not adding
2✔
429
        // any feature bits that are defined but not set in LND.
2✔
430
        for feature := range other.features {
4✔
431
                if fv.IsSet(feature) {
4✔
432
                        continue
2✔
433
                }
434

435
                if feature > maximumValue {
2✔
UNCOV
436
                        return fmt.Errorf("can't set feature bit %d: %w %v",
×
UNCOV
437
                                feature, ErrFeatureBitMaximum,
×
UNCOV
438
                                maximumValue)
×
UNCOV
439
                }
×
440

441
                if name, known := Features[feature]; known {
4✔
442
                        return fmt.Errorf("can't set feature "+
2✔
443
                                "bit %d (%v): %w", feature, name,
2✔
444
                                ErrFeatureStandard)
2✔
445
                }
2✔
446
        }
447

448
        // Check that the new feature vector for this set does not unset any
449
        // features that are standard in LND by comparing the features in our
450
        // current set to the omitted values in the new set.
451
        for feature := range fv.features {
4✔
452
                if other.IsSet(feature) {
4✔
453
                        continue
2✔
454
                }
455

456
                if name, known := Features[feature]; known {
2✔
UNCOV
457
                        return fmt.Errorf("can't unset feature "+
×
UNCOV
458
                                "bit %d (%v): %w", feature, name,
×
UNCOV
459
                                ErrFeatureStandard)
×
UNCOV
460
                }
×
461
        }
462

463
        return nil
2✔
464
}
465

466
// ValidatePairs checks each feature bit in a raw vector to ensure that the
467
// opposing bit is not set, validating that the vector has either the optional
468
// or required bit set, not both.
469
func (fv *RawFeatureVector) ValidatePairs() error {
2✔
470
        for feature := range fv.features {
4✔
471
                if _, ok := fv.features[feature^1]; ok {
2✔
UNCOV
472
                        return ErrFeaturePairExists
×
UNCOV
473
                }
×
474
        }
475

476
        return nil
2✔
477
}
478

479
// Clone makes a copy of a feature vector.
480
func (fv *RawFeatureVector) Clone() *RawFeatureVector {
2✔
481
        newFeatures := NewRawFeatureVector()
2✔
482
        for bit := range fv.features {
4✔
483
                newFeatures.Set(bit)
2✔
484
        }
2✔
485
        return newFeatures
2✔
486
}
487

488
// IsSet returns whether a particular feature bit is enabled in the vector.
489
func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
2✔
490
        _, ok := fv.features[feature]
2✔
491
        return ok
2✔
492
}
2✔
493

494
// Set marks a feature as enabled in the vector.
495
func (fv *RawFeatureVector) Set(feature FeatureBit) {
2✔
496
        fv.features[feature] = struct{}{}
2✔
497
}
2✔
498

499
// SafeSet sets the chosen feature bit in the feature vector, but returns an
500
// error if the opposing feature bit is already set. This ensures both that we
501
// are creating properly structured feature vectors, and in some cases, that
502
// peers are sending properly encoded ones, i.e. it can't be both optional and
503
// required.
504
func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
2✔
505
        if _, ok := fv.features[feature^1]; ok {
2✔
506
                return ErrFeaturePairExists
×
507
        }
×
508

509
        fv.Set(feature)
2✔
510
        return nil
2✔
511
}
512

513
// Unset marks a feature as disabled in the vector.
514
func (fv *RawFeatureVector) Unset(feature FeatureBit) {
2✔
515
        delete(fv.features, feature)
2✔
516
}
2✔
517

518
// SerializeSize returns the number of bytes needed to represent feature vector
519
// in byte format.
520
func (fv *RawFeatureVector) SerializeSize() int {
2✔
521
        // We calculate byte-length via the largest bit index.
2✔
522
        return fv.serializeSize(8)
2✔
523
}
2✔
524

525
// SerializeSize32 returns the number of bytes needed to represent feature
526
// vector in base32 format.
527
func (fv *RawFeatureVector) SerializeSize32() int {
2✔
528
        // We calculate base32-length via the largest bit index.
2✔
529
        return fv.serializeSize(5)
2✔
530
}
2✔
531

532
// serializeSize returns the number of bytes required to encode the feature
533
// vector using at most width bits per encoded byte.
534
func (fv *RawFeatureVector) serializeSize(width int) int {
2✔
535
        // Find the largest feature bit index
2✔
536
        max := -1
2✔
537
        for feature := range fv.features {
4✔
538
                index := int(feature)
2✔
539
                if index > max {
4✔
540
                        max = index
2✔
541
                }
2✔
542
        }
543
        if max == -1 {
4✔
544
                return 0
2✔
545
        }
2✔
546

547
        return max/width + 1
2✔
548
}
549

550
// Encode writes the feature vector in byte representation. Every feature
551
// encoded as a bit, and the bit vector is serialized using the least number of
552
// bytes. Since the bit vector length is variable, the first two bytes of the
553
// serialization represent the length.
554
func (fv *RawFeatureVector) Encode(w io.Writer) error {
2✔
555
        // Write length of feature vector.
2✔
556
        var l [2]byte
2✔
557
        length := fv.SerializeSize()
2✔
558
        binary.BigEndian.PutUint16(l[:], uint16(length))
2✔
559
        if _, err := w.Write(l[:]); err != nil {
2✔
560
                return err
×
561
        }
×
562

563
        return fv.encode(w, length, 8)
2✔
564
}
565

566
// EncodeBase256 writes the feature vector in base256 representation. Every
567
// feature is encoded as a bit, and the bit vector is serialized using the least
568
// number of bytes.
569
func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
2✔
570
        length := fv.SerializeSize()
2✔
571
        return fv.encode(w, length, 8)
2✔
572
}
2✔
573

574
// EncodeBase32 writes the feature vector in base32 representation. Every feature
575
// is encoded as a bit, and the bit vector is serialized using the least number of
576
// bytes.
577
func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
2✔
578
        length := fv.SerializeSize32()
2✔
579
        return fv.encode(w, length, 5)
2✔
580
}
2✔
581

582
// encode writes the feature vector
583
func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
2✔
584
        // Generate the data and write it.
2✔
585
        data := make([]byte, length)
2✔
586
        for feature := range fv.features {
4✔
587
                byteIndex := int(feature) / width
2✔
588
                bitIndex := int(feature) % width
2✔
589
                data[length-byteIndex-1] |= 1 << uint(bitIndex)
2✔
590
        }
2✔
591

592
        _, err := w.Write(data)
2✔
593
        return err
2✔
594
}
595

596
// Decode reads the feature vector from its byte representation. Every feature
597
// is encoded as a bit, and the bit vector is serialized using the least number
598
// of bytes. Since the bit vector length is variable, the first two bytes of the
599
// serialization represent the length.
600
func (fv *RawFeatureVector) Decode(r io.Reader) error {
2✔
601
        // Read the length of the feature vector.
2✔
602
        var l [2]byte
2✔
603
        if _, err := io.ReadFull(r, l[:]); err != nil {
2✔
UNCOV
604
                return err
×
UNCOV
605
        }
×
606
        length := binary.BigEndian.Uint16(l[:])
2✔
607

2✔
608
        return fv.decode(r, int(length), 8)
2✔
609
}
610

611
// DecodeBase256 reads the feature vector from its base256 representation. Every
612
// feature encoded as a bit, and the bit vector is serialized using the least
613
// number of bytes.
614
func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
2✔
615
        return fv.decode(r, length, 8)
2✔
616
}
2✔
617

618
// DecodeBase32 reads the feature vector from its base32 representation. Every
619
// feature encoded as a bit, and the bit vector is serialized using the least
620
// number of bytes.
621
func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
2✔
622
        return fv.decode(r, length, 5)
2✔
623
}
2✔
624

625
// decode reads a feature vector from the next length bytes of the io.Reader,
626
// assuming each byte has width feature bits encoded per byte.
627
func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
2✔
628
        // Read the feature vector data.
2✔
629
        data := make([]byte, length)
2✔
630
        if _, err := io.ReadFull(r, data); err != nil {
2✔
UNCOV
631
                return err
×
UNCOV
632
        }
×
633

634
        // Set feature bits from parsed data.
635
        bitsNumber := len(data) * width
2✔
636
        for i := 0; i < bitsNumber; i++ {
4✔
637
                byteIndex := int(i / width)
2✔
638
                bitIndex := uint(i % width)
2✔
639
                if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
4✔
640
                        fv.Set(FeatureBit(i))
2✔
641
                }
2✔
642
        }
643

644
        return nil
2✔
645
}
646

647
// sizeFunc returns the length required to encode the feature vector.
648
func (fv *RawFeatureVector) sizeFunc() uint64 {
2✔
649
        return uint64(fv.SerializeSize())
2✔
650
}
2✔
651

652
// Record returns a TLV record that can be used to encode/decode raw feature
653
// vectors. Note that the length of the feature vector is not included, because
654
// it is covered by the TLV record's length field.
UNCOV
655
func (fv *RawFeatureVector) Record() tlv.Record {
×
UNCOV
656
        return tlv.MakeDynamicRecord(
×
UNCOV
657
                0, fv, fv.sizeFunc, rawFeatureEncoder, rawFeatureDecoder,
×
UNCOV
658
        )
×
UNCOV
659
}
×
660

661
// rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
662
func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
2✔
663
        if v, ok := val.(*RawFeatureVector); ok {
4✔
664
                // Encode the feature bits as a byte slice without its length
2✔
665
                // prepended, as that's already taken care of by the TLV record.
2✔
666
                fv := *v
2✔
667
                return fv.encode(w, fv.SerializeSize(), 8)
2✔
668
        }
2✔
669

670
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
×
671
}
672

673
// rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
674
func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
675
        l uint64) error {
2✔
676

2✔
677
        if v, ok := val.(*RawFeatureVector); ok {
4✔
678
                fv := NewRawFeatureVector()
2✔
679
                if err := fv.decode(r, int(l), 8); err != nil {
2✔
UNCOV
680
                        return err
×
UNCOV
681
                }
×
682
                *v = *fv
2✔
683

2✔
684
                return nil
2✔
685
        }
686

687
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
×
688
}
689

690
// FeatureVector represents a set of enabled features. The set stores
691
// information on enabled flags and metadata about the feature names. A feature
692
// vector is serializable to a compact byte representation that is included in
693
// Lightning network messages.
694
type FeatureVector struct {
695
        *RawFeatureVector
696
        featureNames map[FeatureBit]string
697
}
698

699
// NewFeatureVector constructs a new FeatureVector from a raw feature vector
700
// and mapping of feature definitions. If the feature vector argument is nil, a
701
// new one will be constructed with no enabled features.
702
func NewFeatureVector(featureVector *RawFeatureVector,
703
        featureNames map[FeatureBit]string) *FeatureVector {
2✔
704

2✔
705
        if featureVector == nil {
4✔
706
                featureVector = NewRawFeatureVector()
2✔
707
        }
2✔
708
        return &FeatureVector{
2✔
709
                RawFeatureVector: featureVector,
2✔
710
                featureNames:     featureNames,
2✔
711
        }
2✔
712
}
713

714
// EmptyFeatureVector returns a feature vector with no bits set.
715
func EmptyFeatureVector() *FeatureVector {
2✔
716
        return NewFeatureVector(nil, Features)
2✔
717
}
2✔
718

719
// Record implements the RecordProducer interface for FeatureVector. Note that
720
// it uses a zero-value type is used to produce the record, as we expect this
721
// type value to be overwritten when used in generic TLV record production.
722
// This allows a single Record function to serve in the many different contexts
723
// in which feature vectors are encoded. This record wraps the encoding/
724
// decoding for our raw feature vectors so that we can directly parse fully
725
// formed feature vector types.
726
func (fv *FeatureVector) Record() tlv.Record {
2✔
727
        return tlv.MakeDynamicRecord(0, fv, fv.sizeFunc,
2✔
728
                func(w io.Writer, val interface{}, buf *[8]byte) error {
2✔
UNCOV
729
                        if f, ok := val.(*FeatureVector); ok {
×
UNCOV
730
                                return rawFeatureEncoder(
×
UNCOV
731
                                        w, f.RawFeatureVector, buf,
×
UNCOV
732
                                )
×
UNCOV
733
                        }
×
734

735
                        return tlv.NewTypeForEncodingErr(
×
736
                                val, "*lnwire.FeatureVector",
×
737
                        )
×
738
                },
739
                func(r io.Reader, val interface{}, buf *[8]byte,
UNCOV
740
                        l uint64) error {
×
UNCOV
741

×
UNCOV
742
                        if f, ok := val.(*FeatureVector); ok {
×
UNCOV
743
                                features := NewFeatureVector(nil, Features)
×
UNCOV
744
                                err := rawFeatureDecoder(
×
UNCOV
745
                                        r, features.RawFeatureVector, buf, l,
×
UNCOV
746
                                )
×
UNCOV
747
                                if err != nil {
×
748
                                        return err
×
749
                                }
×
750

UNCOV
751
                                *f = *features
×
UNCOV
752

×
UNCOV
753
                                return nil
×
754
                        }
755

756
                        return tlv.NewTypeForDecodingErr(
×
757
                                val, "*lnwire.FeatureVector", l, l,
×
758
                        )
×
759
                },
760
        )
761
}
762

763
// HasFeature returns whether a particular feature is included in the set. The
764
// feature can be seen as set either if the bit is set directly OR the queried
765
// bit has the same meaning as its corresponding even/odd bit, which is set
766
// instead. The second case is because feature bits are generally assigned in
767
// pairs where both the even and odd position represent the same feature.
768
func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
2✔
769
        return fv.IsSet(feature) ||
2✔
770
                (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
2✔
771
}
2✔
772

773
// RequiresFeature returns true if the referenced feature vector *requires*
774
// that the given required bit be set. This method can be used with both
775
// optional and required feature bits as a parameter.
776
func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
2✔
777
        // If we weren't passed a required feature bit, then we'll flip the
2✔
778
        // lowest bit to query for the required version of the feature. This
2✔
779
        // lets callers pass in both the optional and required bits.
2✔
780
        if !feature.IsRequired() {
2✔
UNCOV
781
                feature ^= 1
×
UNCOV
782
        }
×
783

784
        return fv.IsSet(feature)
2✔
785
}
786

787
// UnknownRequiredFeatures returns a list of feature bits set in the vector
788
// that are unknown and in an even bit position. Feature bits with an even
789
// index must be known to a node receiving the feature vector in a message.
790
func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
2✔
791
        var unknown []FeatureBit
2✔
792
        for feature := range fv.features {
4✔
793
                if feature%2 == 0 && !fv.IsKnown(feature) {
2✔
UNCOV
794
                        unknown = append(unknown, feature)
×
UNCOV
795
                }
×
796
        }
797
        return unknown
2✔
798
}
799

800
// UnknownFeatures returns a boolean if a feature vector contains *any*
801
// unknown features (even if they are odd).
UNCOV
802
func (fv *FeatureVector) UnknownFeatures() bool {
×
UNCOV
803
        for feature := range fv.features {
×
UNCOV
804
                if !fv.IsKnown(feature) {
×
UNCOV
805
                        return true
×
UNCOV
806
                }
×
807
        }
808

809
        return false
×
810
}
811

812
// Name returns a string identifier for the feature represented by this bit. If
813
// the bit does not represent a known feature, this returns a string indicating
814
// as such.
815
func (fv *FeatureVector) Name(bit FeatureBit) string {
2✔
816
        name, known := fv.featureNames[bit]
2✔
817
        if !known {
4✔
818
                return "unknown"
2✔
819
        }
2✔
820
        return name
2✔
821
}
822

823
// IsKnown returns whether this feature bit represents a known feature.
824
func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
2✔
825
        _, known := fv.featureNames[bit]
2✔
826
        return known
2✔
827
}
2✔
828

829
// isFeatureBitPair returns whether this feature bit and its corresponding
830
// even/odd bit both represent the same feature. This may often be the case as
831
// bits are generally assigned in pairs, first being assigned an odd bit
832
// position then being promoted to an even bit position once the network is
833
// ready.
834
func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
2✔
835
        name1, known1 := fv.featureNames[bit]
2✔
836
        name2, known2 := fv.featureNames[bit^1]
2✔
837
        return known1 && known2 && name1 == name2
2✔
838
}
2✔
839

840
// Features returns the set of raw features contained in the feature vector.
841
func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
2✔
842
        fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
2✔
843
        for b := range fv.RawFeatureVector.features {
4✔
844
                fs[b] = struct{}{}
2✔
845
        }
2✔
846
        return fs
2✔
847
}
848

849
// Clone copies a feature vector, carrying over its feature bits. The feature
850
// names are not copied.
851
func (fv *FeatureVector) Clone() *FeatureVector {
2✔
852
        features := fv.RawFeatureVector.Clone()
2✔
853
        return NewFeatureVector(features, fv.featureNames)
2✔
854
}
2✔
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