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

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

76.09
/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
        // ScriptEnforcedLeaseOptional is an optional 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
        // SimpleTaprootChannelsRequredFinal 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
252
        // feature bit to be used once the channel type is finalized.
253
        SimpleTaprootChannelsOptionalFinal = 81
254

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

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

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

282
// IsRequired returns true if the feature bit is even, and false otherwise.
283
func (b FeatureBit) IsRequired() bool {
3✔
284
        return b&0x01 == 0x00
3✔
285
}
3✔
286

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

336
// RawFeatureVector represents a set of feature bits as defined in BOLT-09.  A
337
// RawFeatureVector itself just stores a set of bit flags but can be used to
338
// construct a FeatureVector which binds meaning to each bit. Feature vectors
339
// can be serialized and deserialized to/from a byte representation that is
340
// transmitted in Lightning network messages.
341
type RawFeatureVector struct {
342
        features map[FeatureBit]struct{}
343
}
344

345
// NewRawFeatureVector creates a feature vector with all of the feature bits
346
// given as arguments enabled.
347
func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
3✔
348
        fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
3✔
349
        for _, bit := range bits {
6✔
350
                fv.Set(bit)
3✔
351
        }
3✔
352
        return fv
3✔
353
}
354

355
// IsEmpty returns whether the feature vector contains any feature bits.
356
func (fv RawFeatureVector) IsEmpty() bool {
3✔
357
        return len(fv.features) == 0
3✔
358
}
3✔
359

360
// OnlyContains determines whether only the specified feature bits are found.
361
func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
3✔
362
        if len(bits) != len(fv.features) {
6✔
363
                return false
3✔
364
        }
3✔
365
        for _, bit := range bits {
6✔
366
                if !fv.IsSet(bit) {
6✔
367
                        return false
3✔
368
                }
3✔
369
        }
370
        return true
3✔
371
}
372

373
// Equals determines whether two features vectors contain exactly the same
374
// features.
375
func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
3✔
376
        if len(fv.features) != len(other.features) {
3✔
377
                return false
×
378
        }
×
379
        for bit := range fv.features {
6✔
380
                if _, ok := other.features[bit]; !ok {
3✔
381
                        return false
×
382
                }
×
383
        }
384
        return true
3✔
385
}
386

387
// Merges sets all feature bits in other on the receiver's feature vector.
388
func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
3✔
389
        for bit := range other.features {
6✔
390
                err := fv.SafeSet(bit)
3✔
391
                if err != nil {
3✔
392
                        return err
×
393
                }
×
394
        }
395
        return nil
3✔
396
}
397

398
// ValidateUpdate checks whether a feature vector can safely be updated to the
399
// new feature vector provided, checking that it does not alter any of the
400
// "standard" features that are defined by LND. The new feature vector should
401
// be inclusive of all features in the original vector that it still wants to
402
// advertise, setting and unsetting updates as desired. Features in the vector
403
// are also checked against a maximum inclusive value, as feature vectors in
404
// different contexts have different maximum values.
405
func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
406
        maximumValue FeatureBit) error {
3✔
407

3✔
408
        // Run through the new set of features and check that we're not adding
3✔
409
        // any feature bits that are defined but not set in LND.
3✔
410
        for feature := range other.features {
6✔
411
                if fv.IsSet(feature) {
6✔
412
                        continue
3✔
413
                }
414

415
                if feature > maximumValue {
3✔
416
                        return fmt.Errorf("can't set feature bit %d: %w %v",
×
417
                                feature, ErrFeatureBitMaximum,
×
418
                                maximumValue)
×
419
                }
×
420

421
                if name, known := Features[feature]; known {
6✔
422
                        return fmt.Errorf("can't set feature "+
3✔
423
                                "bit %d (%v): %w", feature, name,
3✔
424
                                ErrFeatureStandard)
3✔
425
                }
3✔
426
        }
427

428
        // Check that the new feature vector for this set does not unset any
429
        // features that are standard in LND by comparing the features in our
430
        // current set to the omitted values in the new set.
431
        for feature := range fv.features {
6✔
432
                if other.IsSet(feature) {
6✔
433
                        continue
3✔
434
                }
435

436
                if name, known := Features[feature]; known {
3✔
437
                        return fmt.Errorf("can't unset feature "+
×
438
                                "bit %d (%v): %w", feature, name,
×
439
                                ErrFeatureStandard)
×
440
                }
×
441
        }
442

443
        return nil
3✔
444
}
445

446
// ValidatePairs checks each feature bit in a raw vector to ensure that the
447
// opposing bit is not set, validating that the vector has either the optional
448
// or required bit set, not both.
449
func (fv *RawFeatureVector) ValidatePairs() error {
3✔
450
        for feature := range fv.features {
6✔
451
                if _, ok := fv.features[feature^1]; ok {
3✔
452
                        return ErrFeaturePairExists
×
453
                }
×
454
        }
455

456
        return nil
3✔
457
}
458

459
// Clone makes a copy of a feature vector.
460
func (fv *RawFeatureVector) Clone() *RawFeatureVector {
3✔
461
        newFeatures := NewRawFeatureVector()
3✔
462
        for bit := range fv.features {
6✔
463
                newFeatures.Set(bit)
3✔
464
        }
3✔
465
        return newFeatures
3✔
466
}
467

468
// IsSet returns whether a particular feature bit is enabled in the vector.
469
func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
3✔
470
        _, ok := fv.features[feature]
3✔
471
        return ok
3✔
472
}
3✔
473

474
// Set marks a feature as enabled in the vector.
475
func (fv *RawFeatureVector) Set(feature FeatureBit) {
3✔
476
        fv.features[feature] = struct{}{}
3✔
477
}
3✔
478

479
// SafeSet sets the chosen feature bit in the feature vector, but returns an
480
// error if the opposing feature bit is already set. This ensures both that we
481
// are creating properly structured feature vectors, and in some cases, that
482
// peers are sending properly encoded ones, i.e. it can't be both optional and
483
// required.
484
func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
3✔
485
        if _, ok := fv.features[feature^1]; ok {
3✔
486
                return ErrFeaturePairExists
×
487
        }
×
488

489
        fv.Set(feature)
3✔
490
        return nil
3✔
491
}
492

493
// Unset marks a feature as disabled in the vector.
494
func (fv *RawFeatureVector) Unset(feature FeatureBit) {
3✔
495
        delete(fv.features, feature)
3✔
496
}
3✔
497

498
// SerializeSize returns the number of bytes needed to represent feature vector
499
// in byte format.
500
func (fv *RawFeatureVector) SerializeSize() int {
3✔
501
        // We calculate byte-length via the largest bit index.
3✔
502
        return fv.serializeSize(8)
3✔
503
}
3✔
504

505
// SerializeSize32 returns the number of bytes needed to represent feature
506
// vector in base32 format.
507
func (fv *RawFeatureVector) SerializeSize32() int {
3✔
508
        // We calculate base32-length via the largest bit index.
3✔
509
        return fv.serializeSize(5)
3✔
510
}
3✔
511

512
// serializeSize returns the number of bytes required to encode the feature
513
// vector using at most width bits per encoded byte.
514
func (fv *RawFeatureVector) serializeSize(width int) int {
3✔
515
        // Find the largest feature bit index
3✔
516
        max := -1
3✔
517
        for feature := range fv.features {
6✔
518
                index := int(feature)
3✔
519
                if index > max {
6✔
520
                        max = index
3✔
521
                }
3✔
522
        }
523
        if max == -1 {
6✔
524
                return 0
3✔
525
        }
3✔
526

527
        return max/width + 1
3✔
528
}
529

530
// Encode writes the feature vector in byte representation. Every feature
531
// encoded as a bit, and the bit vector is serialized using the least number of
532
// bytes. Since the bit vector length is variable, the first two bytes of the
533
// serialization represent the length.
534
func (fv *RawFeatureVector) Encode(w io.Writer) error {
3✔
535
        // Write length of feature vector.
3✔
536
        var l [2]byte
3✔
537
        length := fv.SerializeSize()
3✔
538
        binary.BigEndian.PutUint16(l[:], uint16(length))
3✔
539
        if _, err := w.Write(l[:]); err != nil {
3✔
540
                return err
×
541
        }
×
542

543
        return fv.encode(w, length, 8)
3✔
544
}
545

546
// EncodeBase256 writes the feature vector in base256 representation. Every
547
// feature is encoded as a bit, and the bit vector is serialized using the least
548
// number of bytes.
549
func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
3✔
550
        length := fv.SerializeSize()
3✔
551
        return fv.encode(w, length, 8)
3✔
552
}
3✔
553

554
// EncodeBase32 writes the feature vector in base32 representation. Every feature
555
// is encoded as a bit, and the bit vector is serialized using the least number of
556
// bytes.
557
func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
3✔
558
        length := fv.SerializeSize32()
3✔
559
        return fv.encode(w, length, 5)
3✔
560
}
3✔
561

562
// encode writes the feature vector
563
func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
3✔
564
        // Generate the data and write it.
3✔
565
        data := make([]byte, length)
3✔
566
        for feature := range fv.features {
6✔
567
                byteIndex := int(feature) / width
3✔
568
                bitIndex := int(feature) % width
3✔
569
                data[length-byteIndex-1] |= 1 << uint(bitIndex)
3✔
570
        }
3✔
571

572
        _, err := w.Write(data)
3✔
573
        return err
3✔
574
}
575

576
// Decode reads the feature vector from its byte representation. Every feature
577
// is encoded as a bit, and the bit vector is serialized using the least number
578
// of bytes. Since the bit vector length is variable, the first two bytes of the
579
// serialization represent the length.
580
func (fv *RawFeatureVector) Decode(r io.Reader) error {
3✔
581
        // Read the length of the feature vector.
3✔
582
        var l [2]byte
3✔
583
        if _, err := io.ReadFull(r, l[:]); err != nil {
3✔
584
                return err
×
585
        }
×
586
        length := binary.BigEndian.Uint16(l[:])
3✔
587

3✔
588
        return fv.decode(r, int(length), 8)
3✔
589
}
590

591
// DecodeBase256 reads the feature vector from its base256 representation. Every
592
// feature encoded as a bit, and the bit vector is serialized using the least
593
// number of bytes.
594
func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
3✔
595
        return fv.decode(r, length, 8)
3✔
596
}
3✔
597

598
// DecodeBase32 reads the feature vector from its base32 representation. Every
599
// feature encoded as a bit, and the bit vector is serialized using the least
600
// number of bytes.
601
func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
3✔
602
        return fv.decode(r, length, 5)
3✔
603
}
3✔
604

605
// decode reads a feature vector from the next length bytes of the io.Reader,
606
// assuming each byte has width feature bits encoded per byte.
607
func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
3✔
608
        // Read the feature vector data.
3✔
609
        data := make([]byte, length)
3✔
610
        if _, err := io.ReadFull(r, data); err != nil {
3✔
611
                return err
×
612
        }
×
613

614
        // Set feature bits from parsed data.
615
        bitsNumber := len(data) * width
3✔
616
        for i := 0; i < bitsNumber; i++ {
6✔
617
                byteIndex := int(i / width)
3✔
618
                bitIndex := uint(i % width)
3✔
619
                if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
6✔
620
                        fv.Set(FeatureBit(i))
3✔
621
                }
3✔
622
        }
623

624
        return nil
3✔
625
}
626

627
// sizeFunc returns the length required to encode the feature vector.
628
func (fv *RawFeatureVector) sizeFunc() uint64 {
3✔
629
        return uint64(fv.SerializeSize())
3✔
630
}
3✔
631

632
// Record returns a TLV record that can be used to encode/decode raw feature
633
// vectors. Note that the length of the feature vector is not included, because
634
// it is covered by the TLV record's length field.
635
func (fv *RawFeatureVector) Record(recordType tlv.Type) tlv.Record {
×
636
        return tlv.MakeDynamicRecord(
×
637
                recordType, fv, fv.sizeFunc, rawFeatureEncoder,
×
638
                rawFeatureDecoder,
×
639
        )
×
640
}
×
641

642
// rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
643
func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
3✔
644
        if f, ok := val.(*RawFeatureVector); ok {
6✔
645
                return f.encode(w, f.SerializeSize(), 8)
3✔
646
        }
3✔
647

648
        return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
×
649
}
650

651
// rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
652
func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
653
        l uint64) error {
3✔
654

3✔
655
        if f, ok := val.(*RawFeatureVector); ok {
6✔
656
                return f.decode(r, int(l), 8)
3✔
657
        }
3✔
658

659
        return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
×
660
}
661

662
// FeatureVector represents a set of enabled features. The set stores
663
// information on enabled flags and metadata about the feature names. A feature
664
// vector is serializable to a compact byte representation that is included in
665
// Lightning network messages.
666
type FeatureVector struct {
667
        *RawFeatureVector
668
        featureNames map[FeatureBit]string
669
}
670

671
// NewFeatureVector constructs a new FeatureVector from a raw feature vector
672
// and mapping of feature definitions. If the feature vector argument is nil, a
673
// new one will be constructed with no enabled features.
674
func NewFeatureVector(featureVector *RawFeatureVector,
675
        featureNames map[FeatureBit]string) *FeatureVector {
3✔
676

3✔
677
        if featureVector == nil {
6✔
678
                featureVector = NewRawFeatureVector()
3✔
679
        }
3✔
680
        return &FeatureVector{
3✔
681
                RawFeatureVector: featureVector,
3✔
682
                featureNames:     featureNames,
3✔
683
        }
3✔
684
}
685

686
// EmptyFeatureVector returns a feature vector with no bits set.
687
func EmptyFeatureVector() *FeatureVector {
3✔
688
        return NewFeatureVector(nil, Features)
3✔
689
}
3✔
690

691
// Record implements the RecordProducer interface for FeatureVector. Note that
692
// it uses a zero-value type is used to produce the record, as we expect this
693
// type value to be overwritten when used in generic TLV record production.
694
// This allows a single Record function to serve in the many different contexts
695
// in which feature vectors are encoded. This record wraps the encoding/
696
// decoding for our raw feature vectors so that we can directly parse fully
697
// formed feature vector types.
698
func (fv *FeatureVector) Record() tlv.Record {
3✔
699
        return tlv.MakeDynamicRecord(0, fv, fv.sizeFunc,
3✔
700
                func(w io.Writer, val interface{}, buf *[8]byte) error {
3✔
701
                        if f, ok := val.(*FeatureVector); ok {
×
702
                                return rawFeatureEncoder(
×
703
                                        w, f.RawFeatureVector, buf,
×
704
                                )
×
705
                        }
×
706

707
                        return tlv.NewTypeForEncodingErr(
×
708
                                val, "*lnwire.FeatureVector",
×
709
                        )
×
710
                },
711
                func(r io.Reader, val interface{}, buf *[8]byte,
712
                        l uint64) error {
×
713

×
714
                        if f, ok := val.(*FeatureVector); ok {
×
715
                                features := NewFeatureVector(nil, Features)
×
716
                                err := rawFeatureDecoder(
×
717
                                        r, features.RawFeatureVector, buf, l,
×
718
                                )
×
719
                                if err != nil {
×
720
                                        return err
×
721
                                }
×
722

723
                                *f = *features
×
724

×
725
                                return nil
×
726
                        }
727

728
                        return tlv.NewTypeForDecodingErr(
×
729
                                val, "*lnwire.FeatureVector", l, l,
×
730
                        )
×
731
                },
732
        )
733
}
734

735
// HasFeature returns whether a particular feature is included in the set. The
736
// feature can be seen as set either if the bit is set directly OR the queried
737
// bit has the same meaning as its corresponding even/odd bit, which is set
738
// instead. The second case is because feature bits are generally assigned in
739
// pairs where both the even and odd position represent the same feature.
740
func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
3✔
741
        return fv.IsSet(feature) ||
3✔
742
                (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
3✔
743
}
3✔
744

745
// RequiresFeature returns true if the referenced feature vector *requires*
746
// that the given required bit be set. This method can be used with both
747
// optional and required feature bits as a parameter.
748
func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
3✔
749
        // If we weren't passed a required feature bit, then we'll flip the
3✔
750
        // lowest bit to query for the required version of the feature. This
3✔
751
        // lets callers pass in both the optional and required bits.
3✔
752
        if !feature.IsRequired() {
3✔
753
                feature ^= 1
×
754
        }
×
755

756
        return fv.IsSet(feature)
3✔
757
}
758

759
// UnknownRequiredFeatures returns a list of feature bits set in the vector
760
// that are unknown and in an even bit position. Feature bits with an even
761
// index must be known to a node receiving the feature vector in a message.
762
func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
3✔
763
        var unknown []FeatureBit
3✔
764
        for feature := range fv.features {
6✔
765
                if feature%2 == 0 && !fv.IsKnown(feature) {
3✔
766
                        unknown = append(unknown, feature)
×
767
                }
×
768
        }
769
        return unknown
3✔
770
}
771

772
// UnknownFeatures returns a boolean if a feature vector contains *any*
773
// unknown features (even if they are odd).
774
func (fv *FeatureVector) UnknownFeatures() bool {
×
775
        for feature := range fv.features {
×
776
                if !fv.IsKnown(feature) {
×
777
                        return true
×
778
                }
×
779
        }
780

781
        return false
×
782
}
783

784
// Name returns a string identifier for the feature represented by this bit. If
785
// the bit does not represent a known feature, this returns a string indicating
786
// as such.
787
func (fv *FeatureVector) Name(bit FeatureBit) string {
3✔
788
        name, known := fv.featureNames[bit]
3✔
789
        if !known {
6✔
790
                return "unknown"
3✔
791
        }
3✔
792
        return name
3✔
793
}
794

795
// IsKnown returns whether this feature bit represents a known feature.
796
func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
3✔
797
        _, known := fv.featureNames[bit]
3✔
798
        return known
3✔
799
}
3✔
800

801
// isFeatureBitPair returns whether this feature bit and its corresponding
802
// even/odd bit both represent the same feature. This may often be the case as
803
// bits are generally assigned in pairs, first being assigned an odd bit
804
// position then being promoted to an even bit position once the network is
805
// ready.
806
func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
3✔
807
        name1, known1 := fv.featureNames[bit]
3✔
808
        name2, known2 := fv.featureNames[bit^1]
3✔
809
        return known1 && known2 && name1 == name2
3✔
810
}
3✔
811

812
// Features returns the set of raw features contained in the feature vector.
813
func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
3✔
814
        fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
3✔
815
        for b := range fv.RawFeatureVector.features {
6✔
816
                fs[b] = struct{}{}
3✔
817
        }
3✔
818
        return fs
3✔
819
}
820

821
// Clone copies a feature vector, carrying over its feature bits. The feature
822
// names are not copied.
823
func (fv *FeatureVector) Clone() *FeatureVector {
3✔
824
        features := fv.RawFeatureVector.Clone()
3✔
825
        return NewFeatureVector(features, fv.featureNames)
3✔
826
}
3✔
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