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

lightningnetwork / lnd / 12033440129

26 Nov 2024 03:03PM UTC coverage: 48.738% (-10.3%) from 58.999%
12033440129

Pull #9309

github

yyforyongyu
gomod: update `btcd` for shutdown fix
Pull Request #9309: chainntnfs: fix `TestHistoricalConfDetailsTxIndex`

97664 of 200385 relevant lines covered (48.74%)

0.52 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
        // ExperimentalEndorsementRequired is a required feature bit that
267
        // indicates that the node will relay experimental endorsement signals.
268
        ExperimentalEndorsementRequired FeatureBit = 260
269

270
        // ExperimentalEndorsementOptional is an optional feature bit that
271
        // indicates that the node will relay experimental endorsement signals.
272
        ExperimentalEndorsementOptional FeatureBit = 261
273

274
        // Bolt11BlindedPathsRequired is a required feature bit that indicates
275
        // that the node is able to understand the blinded path tagged field in
276
        // a BOLT 11 invoice.
277
        Bolt11BlindedPathsRequired = 262
278

279
        // Bolt11BlindedPathsOptional is an optional feature bit that indicates
280
        // that the node is able to understand the blinded path tagged field in
281
        // a BOLT 11 invoice.
282
        Bolt11BlindedPathsOptional = 263
283

284
        // SimpleTaprootOverlayChansRequired is a required bit that indicates
285
        // support for the special custom taproot overlay channel.
286
        SimpleTaprootOverlayChansOptional = 2025
287

288
        // SimpleTaprootOverlayChansRequired is a required bit that indicates
289
        // support for the special custom taproot overlay channel.
290
        SimpleTaprootOverlayChansRequired = 2026
291

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

306
// IsRequired returns true if the feature bit is even, and false otherwise.
307
func (b FeatureBit) IsRequired() bool {
1✔
308
        return b&0x01 == 0x00
1✔
309
}
1✔
310

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

366
// RawFeatureVector represents a set of feature bits as defined in BOLT-09.  A
367
// RawFeatureVector itself just stores a set of bit flags but can be used to
368
// construct a FeatureVector which binds meaning to each bit. Feature vectors
369
// can be serialized and deserialized to/from a byte representation that is
370
// transmitted in Lightning network messages.
371
type RawFeatureVector struct {
372
        features map[FeatureBit]struct{}
373
}
374

375
// NewRawFeatureVector creates a feature vector with all of the feature bits
376
// given as arguments enabled.
377
func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
1✔
378
        fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
1✔
379
        for _, bit := range bits {
2✔
380
                fv.Set(bit)
1✔
381
        }
1✔
382
        return fv
1✔
383
}
384

385
// IsEmpty returns whether the feature vector contains any feature bits.
386
func (fv RawFeatureVector) IsEmpty() bool {
1✔
387
        return len(fv.features) == 0
1✔
388
}
1✔
389

390
// OnlyContains determines whether only the specified feature bits are found.
391
func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
1✔
392
        if len(bits) != len(fv.features) {
2✔
393
                return false
1✔
394
        }
1✔
395
        for _, bit := range bits {
2✔
396
                if !fv.IsSet(bit) {
2✔
397
                        return false
1✔
398
                }
1✔
399
        }
400
        return true
1✔
401
}
402

403
// Equals determines whether two features vectors contain exactly the same
404
// features.
405
func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
1✔
406
        if len(fv.features) != len(other.features) {
1✔
407
                return false
×
408
        }
×
409
        for bit := range fv.features {
2✔
410
                if _, ok := other.features[bit]; !ok {
1✔
411
                        return false
×
412
                }
×
413
        }
414
        return true
1✔
415
}
416

417
// Merges sets all feature bits in other on the receiver's feature vector.
418
func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
1✔
419
        for bit := range other.features {
2✔
420
                err := fv.SafeSet(bit)
1✔
421
                if err != nil {
1✔
422
                        return err
×
423
                }
×
424
        }
425
        return nil
1✔
426
}
427

428
// ValidateUpdate checks whether a feature vector can safely be updated to the
429
// new feature vector provided, checking that it does not alter any of the
430
// "standard" features that are defined by LND. The new feature vector should
431
// be inclusive of all features in the original vector that it still wants to
432
// advertise, setting and unsetting updates as desired. Features in the vector
433
// are also checked against a maximum inclusive value, as feature vectors in
434
// different contexts have different maximum values.
435
func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
436
        maximumValue FeatureBit) error {
1✔
437

1✔
438
        // Run through the new set of features and check that we're not adding
1✔
439
        // any feature bits that are defined but not set in LND.
1✔
440
        for feature := range other.features {
2✔
441
                if fv.IsSet(feature) {
2✔
442
                        continue
1✔
443
                }
444

445
                if feature > maximumValue {
1✔
446
                        return fmt.Errorf("can't set feature bit %d: %w %v",
×
447
                                feature, ErrFeatureBitMaximum,
×
448
                                maximumValue)
×
449
                }
×
450

451
                if name, known := Features[feature]; known {
2✔
452
                        return fmt.Errorf("can't set feature "+
1✔
453
                                "bit %d (%v): %w", feature, name,
1✔
454
                                ErrFeatureStandard)
1✔
455
                }
1✔
456
        }
457

458
        // Check that the new feature vector for this set does not unset any
459
        // features that are standard in LND by comparing the features in our
460
        // current set to the omitted values in the new set.
461
        for feature := range fv.features {
2✔
462
                if other.IsSet(feature) {
2✔
463
                        continue
1✔
464
                }
465

466
                if name, known := Features[feature]; known {
1✔
467
                        return fmt.Errorf("can't unset feature "+
×
468
                                "bit %d (%v): %w", feature, name,
×
469
                                ErrFeatureStandard)
×
470
                }
×
471
        }
472

473
        return nil
1✔
474
}
475

476
// ValidatePairs checks each feature bit in a raw vector to ensure that the
477
// opposing bit is not set, validating that the vector has either the optional
478
// or required bit set, not both.
479
func (fv *RawFeatureVector) ValidatePairs() error {
1✔
480
        for feature := range fv.features {
2✔
481
                if _, ok := fv.features[feature^1]; ok {
1✔
482
                        return ErrFeaturePairExists
×
483
                }
×
484
        }
485

486
        return nil
1✔
487
}
488

489
// Clone makes a copy of a feature vector.
490
func (fv *RawFeatureVector) Clone() *RawFeatureVector {
1✔
491
        newFeatures := NewRawFeatureVector()
1✔
492
        for bit := range fv.features {
2✔
493
                newFeatures.Set(bit)
1✔
494
        }
1✔
495
        return newFeatures
1✔
496
}
497

498
// IsSet returns whether a particular feature bit is enabled in the vector.
499
func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
1✔
500
        _, ok := fv.features[feature]
1✔
501
        return ok
1✔
502
}
1✔
503

504
// Set marks a feature as enabled in the vector.
505
func (fv *RawFeatureVector) Set(feature FeatureBit) {
1✔
506
        fv.features[feature] = struct{}{}
1✔
507
}
1✔
508

509
// SafeSet sets the chosen feature bit in the feature vector, but returns an
510
// error if the opposing feature bit is already set. This ensures both that we
511
// are creating properly structured feature vectors, and in some cases, that
512
// peers are sending properly encoded ones, i.e. it can't be both optional and
513
// required.
514
func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
1✔
515
        if _, ok := fv.features[feature^1]; ok {
1✔
516
                return ErrFeaturePairExists
×
517
        }
×
518

519
        fv.Set(feature)
1✔
520
        return nil
1✔
521
}
522

523
// Unset marks a feature as disabled in the vector.
524
func (fv *RawFeatureVector) Unset(feature FeatureBit) {
1✔
525
        delete(fv.features, feature)
1✔
526
}
1✔
527

528
// SerializeSize returns the number of bytes needed to represent feature vector
529
// in byte format.
530
func (fv *RawFeatureVector) SerializeSize() int {
1✔
531
        // We calculate byte-length via the largest bit index.
1✔
532
        return fv.serializeSize(8)
1✔
533
}
1✔
534

535
// SerializeSize32 returns the number of bytes needed to represent feature
536
// vector in base32 format.
537
func (fv *RawFeatureVector) SerializeSize32() int {
1✔
538
        // We calculate base32-length via the largest bit index.
1✔
539
        return fv.serializeSize(5)
1✔
540
}
1✔
541

542
// serializeSize returns the number of bytes required to encode the feature
543
// vector using at most width bits per encoded byte.
544
func (fv *RawFeatureVector) serializeSize(width int) int {
1✔
545
        // Find the largest feature bit index
1✔
546
        max := -1
1✔
547
        for feature := range fv.features {
2✔
548
                index := int(feature)
1✔
549
                if index > max {
2✔
550
                        max = index
1✔
551
                }
1✔
552
        }
553
        if max == -1 {
2✔
554
                return 0
1✔
555
        }
1✔
556

557
        return max/width + 1
1✔
558
}
559

560
// Encode writes the feature vector in byte representation. Every feature
561
// encoded as a bit, and the bit vector is serialized using the least number of
562
// bytes. Since the bit vector length is variable, the first two bytes of the
563
// serialization represent the length.
564
func (fv *RawFeatureVector) Encode(w io.Writer) error {
1✔
565
        // Write length of feature vector.
1✔
566
        var l [2]byte
1✔
567
        length := fv.SerializeSize()
1✔
568
        binary.BigEndian.PutUint16(l[:], uint16(length))
1✔
569
        if _, err := w.Write(l[:]); err != nil {
1✔
570
                return err
×
571
        }
×
572

573
        return fv.encode(w, length, 8)
1✔
574
}
575

576
// EncodeBase256 writes the feature vector in base256 representation. Every
577
// feature is encoded as a bit, and the bit vector is serialized using the least
578
// number of bytes.
579
func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
1✔
580
        length := fv.SerializeSize()
1✔
581
        return fv.encode(w, length, 8)
1✔
582
}
1✔
583

584
// EncodeBase32 writes the feature vector in base32 representation. Every feature
585
// is encoded as a bit, and the bit vector is serialized using the least number of
586
// bytes.
587
func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
1✔
588
        length := fv.SerializeSize32()
1✔
589
        return fv.encode(w, length, 5)
1✔
590
}
1✔
591

592
// encode writes the feature vector
593
func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
1✔
594
        // Generate the data and write it.
1✔
595
        data := make([]byte, length)
1✔
596
        for feature := range fv.features {
2✔
597
                byteIndex := int(feature) / width
1✔
598
                bitIndex := int(feature) % width
1✔
599
                data[length-byteIndex-1] |= 1 << uint(bitIndex)
1✔
600
        }
1✔
601

602
        _, err := w.Write(data)
1✔
603
        return err
1✔
604
}
605

606
// Decode reads the feature vector from its byte representation. Every feature
607
// is encoded as a bit, and the bit vector is serialized using the least number
608
// of bytes. Since the bit vector length is variable, the first two bytes of the
609
// serialization represent the length.
610
func (fv *RawFeatureVector) Decode(r io.Reader) error {
1✔
611
        // Read the length of the feature vector.
1✔
612
        var l [2]byte
1✔
613
        if _, err := io.ReadFull(r, l[:]); err != nil {
1✔
614
                return err
×
615
        }
×
616
        length := binary.BigEndian.Uint16(l[:])
1✔
617

1✔
618
        return fv.decode(r, int(length), 8)
1✔
619
}
620

621
// DecodeBase256 reads the feature vector from its base256 representation. Every
622
// feature encoded as a bit, and the bit vector is serialized using the least
623
// number of bytes.
624
func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
1✔
625
        return fv.decode(r, length, 8)
1✔
626
}
1✔
627

628
// DecodeBase32 reads the feature vector from its base32 representation. Every
629
// feature encoded as a bit, and the bit vector is serialized using the least
630
// number of bytes.
631
func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
1✔
632
        return fv.decode(r, length, 5)
1✔
633
}
1✔
634

635
// decode reads a feature vector from the next length bytes of the io.Reader,
636
// assuming each byte has width feature bits encoded per byte.
637
func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
1✔
638
        // Read the feature vector data.
1✔
639
        data := make([]byte, length)
1✔
640
        if _, err := io.ReadFull(r, data); err != nil {
1✔
641
                return err
×
642
        }
×
643

644
        // Set feature bits from parsed data.
645
        bitsNumber := len(data) * width
1✔
646
        for i := 0; i < bitsNumber; i++ {
2✔
647
                byteIndex := int(i / width)
1✔
648
                bitIndex := uint(i % width)
1✔
649
                if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
2✔
650
                        fv.Set(FeatureBit(i))
1✔
651
                }
1✔
652
        }
653

654
        return nil
1✔
655
}
656

657
// sizeFunc returns the length required to encode the feature vector.
658
func (fv *RawFeatureVector) sizeFunc() uint64 {
1✔
659
        return uint64(fv.SerializeSize())
1✔
660
}
1✔
661

662
// Record returns a TLV record that can be used to encode/decode raw feature
663
// vectors. Note that the length of the feature vector is not included, because
664
// it is covered by the TLV record's length field.
665
func (fv *RawFeatureVector) Record() tlv.Record {
×
666
        return tlv.MakeDynamicRecord(
×
667
                0, fv, fv.sizeFunc, rawFeatureEncoder, rawFeatureDecoder,
×
668
        )
×
669
}
×
670

671
// rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
672
func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
1✔
673
        if v, ok := val.(*RawFeatureVector); ok {
2✔
674
                // Encode the feature bits as a byte slice without its length
1✔
675
                // prepended, as that's already taken care of by the TLV record.
1✔
676
                fv := *v
1✔
677
                return fv.encode(w, fv.SerializeSize(), 8)
1✔
678
        }
1✔
679

680
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
×
681
}
682

683
// rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
684
func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
685
        l uint64) error {
1✔
686

1✔
687
        if v, ok := val.(*RawFeatureVector); ok {
2✔
688
                fv := NewRawFeatureVector()
1✔
689
                if err := fv.decode(r, int(l), 8); err != nil {
1✔
690
                        return err
×
691
                }
×
692
                *v = *fv
1✔
693

1✔
694
                return nil
1✔
695
        }
696

697
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
×
698
}
699

700
// FeatureVector represents a set of enabled features. The set stores
701
// information on enabled flags and metadata about the feature names. A feature
702
// vector is serializable to a compact byte representation that is included in
703
// Lightning network messages.
704
type FeatureVector struct {
705
        *RawFeatureVector
706
        featureNames map[FeatureBit]string
707
}
708

709
// NewFeatureVector constructs a new FeatureVector from a raw feature vector
710
// and mapping of feature definitions. If the feature vector argument is nil, a
711
// new one will be constructed with no enabled features.
712
func NewFeatureVector(featureVector *RawFeatureVector,
713
        featureNames map[FeatureBit]string) *FeatureVector {
1✔
714

1✔
715
        if featureVector == nil {
2✔
716
                featureVector = NewRawFeatureVector()
1✔
717
        }
1✔
718
        return &FeatureVector{
1✔
719
                RawFeatureVector: featureVector,
1✔
720
                featureNames:     featureNames,
1✔
721
        }
1✔
722
}
723

724
// EmptyFeatureVector returns a feature vector with no bits set.
725
func EmptyFeatureVector() *FeatureVector {
1✔
726
        return NewFeatureVector(nil, Features)
1✔
727
}
1✔
728

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

745
                        return tlv.NewTypeForEncodingErr(
×
746
                                val, "*lnwire.FeatureVector",
×
747
                        )
×
748
                },
749
                func(r io.Reader, val interface{}, buf *[8]byte,
750
                        l uint64) error {
×
751

×
752
                        if f, ok := val.(*FeatureVector); ok {
×
753
                                features := NewFeatureVector(nil, Features)
×
754
                                err := rawFeatureDecoder(
×
755
                                        r, features.RawFeatureVector, buf, l,
×
756
                                )
×
757
                                if err != nil {
×
758
                                        return err
×
759
                                }
×
760

761
                                *f = *features
×
762

×
763
                                return nil
×
764
                        }
765

766
                        return tlv.NewTypeForDecodingErr(
×
767
                                val, "*lnwire.FeatureVector", l, l,
×
768
                        )
×
769
                },
770
        )
771
}
772

773
// HasFeature returns whether a particular feature is included in the set. The
774
// feature can be seen as set either if the bit is set directly OR the queried
775
// bit has the same meaning as its corresponding even/odd bit, which is set
776
// instead. The second case is because feature bits are generally assigned in
777
// pairs where both the even and odd position represent the same feature.
778
func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
1✔
779
        return fv.IsSet(feature) ||
1✔
780
                (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
1✔
781
}
1✔
782

783
// RequiresFeature returns true if the referenced feature vector *requires*
784
// that the given required bit be set. This method can be used with both
785
// optional and required feature bits as a parameter.
786
func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
1✔
787
        // If we weren't passed a required feature bit, then we'll flip the
1✔
788
        // lowest bit to query for the required version of the feature. This
1✔
789
        // lets callers pass in both the optional and required bits.
1✔
790
        if !feature.IsRequired() {
1✔
791
                feature ^= 1
×
792
        }
×
793

794
        return fv.IsSet(feature)
1✔
795
}
796

797
// UnknownRequiredFeatures returns a list of feature bits set in the vector
798
// that are unknown and in an even bit position. Feature bits with an even
799
// index must be known to a node receiving the feature vector in a message.
800
func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
1✔
801
        var unknown []FeatureBit
1✔
802
        for feature := range fv.features {
2✔
803
                if feature%2 == 0 && !fv.IsKnown(feature) {
1✔
804
                        unknown = append(unknown, feature)
×
805
                }
×
806
        }
807
        return unknown
1✔
808
}
809

810
// UnknownFeatures returns a boolean if a feature vector contains *any*
811
// unknown features (even if they are odd).
812
func (fv *FeatureVector) UnknownFeatures() bool {
×
813
        for feature := range fv.features {
×
814
                if !fv.IsKnown(feature) {
×
815
                        return true
×
816
                }
×
817
        }
818

819
        return false
×
820
}
821

822
// Name returns a string identifier for the feature represented by this bit. If
823
// the bit does not represent a known feature, this returns a string indicating
824
// as such.
825
func (fv *FeatureVector) Name(bit FeatureBit) string {
1✔
826
        name, known := fv.featureNames[bit]
1✔
827
        if !known {
2✔
828
                return "unknown"
1✔
829
        }
1✔
830
        return name
1✔
831
}
832

833
// IsKnown returns whether this feature bit represents a known feature.
834
func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
1✔
835
        _, known := fv.featureNames[bit]
1✔
836
        return known
1✔
837
}
1✔
838

839
// isFeatureBitPair returns whether this feature bit and its corresponding
840
// even/odd bit both represent the same feature. This may often be the case as
841
// bits are generally assigned in pairs, first being assigned an odd bit
842
// position then being promoted to an even bit position once the network is
843
// ready.
844
func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
1✔
845
        name1, known1 := fv.featureNames[bit]
1✔
846
        name2, known2 := fv.featureNames[bit^1]
1✔
847
        return known1 && known2 && name1 == name2
1✔
848
}
1✔
849

850
// Features returns the set of raw features contained in the feature vector.
851
func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
1✔
852
        fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
1✔
853
        for b := range fv.RawFeatureVector.features {
2✔
854
                fs[b] = struct{}{}
1✔
855
        }
1✔
856
        return fs
1✔
857
}
858

859
// Clone copies a feature vector, carrying over its feature bits. The feature
860
// names are not copied.
861
func (fv *FeatureVector) Clone() *FeatureVector {
1✔
862
        features := fv.RawFeatureVector.Clone()
1✔
863
        return NewFeatureVector(features, fv.featureNames)
1✔
864
}
1✔
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