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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

94.7
/lnwire/features.go
1
package lnwire
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

174
        // QuiescenceRequired is a required feature bit that denotes that a
175
        // connection established with this node must support the quiescence
176
        // protocol if it wants to have a channel relationship.
177
        QuiescenceRequired FeatureBit = 34
178

179
        // QuiescenceOptional is an optional feature bit that denotes that a
180
        // connection established with this node is permitted to use the
181
        // quiescence protocol.
182
        QuiescenceOptional FeatureBit = 35
183

184
        // ExplicitChannelTypeRequired is a required bit that denotes that a
185
        // connection established with this node is to use explicit channel
186
        // commitment types for negotiation instead of the existing implicit
187
        // negotiation methods. With this bit, there is no longer a "default"
188
        // implicit channel commitment type, allowing a connection to
189
        // open/maintain types of several channels over its lifetime.
190
        ExplicitChannelTypeRequired = 44
191

192
        // ExplicitChannelTypeOptional is an optional bit that denotes that a
193
        // connection established with this node is to use explicit channel
194
        // commitment types for negotiation instead of the existing implicit
195
        // negotiation methods. With this bit, there is no longer a "default"
196
        // implicit channel commitment type, allowing a connection to
197
        // TODO: Decide on actual feature bit value.
198
        ExplicitChannelTypeOptional = 45
199

200
        // ScidAliasRequired is a required feature bit that signals that the
201
        // node requires understanding of ShortChannelID aliases in the TLV
202
        // segment of the channel_ready message.
203
        ScidAliasRequired FeatureBit = 46
204

205
        // ScidAliasOptional is an optional feature bit that signals that the
206
        // node understands ShortChannelID aliases in the TLV segment of the
207
        // channel_ready message.
208
        ScidAliasOptional FeatureBit = 47
209

210
        // PaymentMetadataRequired is a required bit that denotes that if an
211
        // invoice contains metadata, it must be passed along with the payment
212
        // htlc(s).
213
        PaymentMetadataRequired = 48
214

215
        // PaymentMetadataOptional is an optional bit that denotes that if an
216
        // invoice contains metadata, it may be passed along with the payment
217
        // htlc(s).
218
        PaymentMetadataOptional = 49
219

220
        // ZeroConfRequired is a required feature bit that signals that the
221
        // node requires understanding of the zero-conf channel_type.
222
        ZeroConfRequired FeatureBit = 50
223

224
        // ZeroConfOptional is an optional feature bit that signals that the
225
        // node understands the zero-conf channel type.
226
        ZeroConfOptional FeatureBit = 51
227

228
        // KeysendRequired is a required bit that indicates that the node is
229
        // able and willing to accept keysend payments.
230
        KeysendRequired = 54
231

232
        // KeysendOptional is an optional bit that indicates that the node is
233
        // able and willing to accept keysend payments.
234
        KeysendOptional = 55
235

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

245
        // ScriptEnforcedLeaseOptional is an optional feature bit that signals
246
        // that the node requires channels having zero-fee second-level HTLC
247
        // transactions, which also imply anchor commitments, along with an
248
        // additional CLTV constraint of a channel lease's expiration height
249
        // applied to all outputs that pay directly to the channel initiator.
250
        //
251
        // TODO: Decide on actual feature bit value.
252
        ScriptEnforcedLeaseOptional FeatureBit = 2023
253

254
        // SimpleTaprootChannelsRequiredFinal is a required bit that indicates
255
        // the node is able to create taproot-native channels. This is the
256
        // final feature bit to be used once the channel type is finalized.
257
        SimpleTaprootChannelsRequiredFinal = 80
258

259
        // SimpleTaprootChannelsOptionalFinal is an optional bit that indicates
260
        // the node is able to create taproot-native channels. This is the
261
        // final feature bit to be used once the channel type is finalized.
262
        SimpleTaprootChannelsOptionalFinal = 81
263

264
        // SimpleTaprootChannelsRequiredStaging is a required bit that indicates
265
        // the node is able to create taproot-native channels. This is a
266
        // feature bit used in the wild while the channel type is still being
267
        // finalized.
268
        SimpleTaprootChannelsRequiredStaging = 180
269

270
        // SimpleTaprootChannelsOptionalStaging is an optional bit that
271
        // indicates the node is able to create taproot-native channels. This
272
        // is a feature bit used in the wild while the channel type is still
273
        // being finalized.
274
        SimpleTaprootChannelsOptionalStaging = 181
275

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

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

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

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

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

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

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

377
// IsEmpty returns whether the feature vector contains any feature bits.
378
func (fv RawFeatureVector) IsEmpty() bool {
379
        return len(fv.features) == 0
25,489✔
380
}
25,489✔
381

26,652✔
382
// OnlyContains determines whether only the specified feature bits are found.
1,163✔
383
func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
1,163✔
384
        if len(bits) != len(fv.features) {
25,489✔
385
                return false
386
        }
387
        for _, bit := range bits {
388
                if !fv.IsSet(bit) {
6✔
389
                        return false
6✔
390
                }
6✔
391
        }
392
        return true
393
}
182✔
394

328✔
395
// Equals determines whether two features vectors contain exactly the same
146✔
396
// features.
146✔
397
func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
109✔
398
        if len(fv.features) != len(other.features) {
87✔
399
                return false
14✔
400
        }
14✔
401
        for bit := range fv.features {
402
                if _, ok := other.features[bit]; !ok {
22✔
403
                        return false
404
                }
405
        }
406
        return true
407
}
22✔
408

23✔
409
// Merges sets all feature bits in other on the receiver's feature vector.
1✔
410
func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
1✔
411
        for bit := range other.features {
61✔
412
                err := fv.SafeSet(bit)
41✔
413
                if err != nil {
1✔
414
                        return err
1✔
415
                }
416
        }
20✔
417
        return nil
418
}
419

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

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

437
                if feature > maximumValue {
438
                        return fmt.Errorf("can't set feature bit %d: %w %v",
15✔
439
                                feature, ErrFeatureBitMaximum,
15✔
440
                                maximumValue)
15✔
441
                }
15✔
442

38✔
443
                if name, known := Features[feature]; known {
37✔
444
                        return fmt.Errorf("can't set feature "+
14✔
445
                                "bit %d (%v): %w", feature, name,
446
                                ErrFeatureStandard)
447
                }
10✔
448
        }
1✔
449

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

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

29✔
465
        return nil
13✔
466
}
467

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

478
        return nil
479
}
480

481
// Clone makes a copy of a feature vector.
12✔
482
func (fv *RawFeatureVector) Clone() *RawFeatureVector {
30✔
483
        newFeatures := NewRawFeatureVector()
21✔
484
        for bit := range fv.features {
3✔
485
                newFeatures.Set(bit)
3✔
486
        }
487
        return newFeatures
488
}
9✔
489

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

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

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

511
        fv.Set(feature)
512
        return nil
513
}
514

515
// Unset marks a feature as disabled in the vector.
516
func (fv *RawFeatureVector) Unset(feature FeatureBit) {
124✔
517
        delete(fv.features, feature)
125✔
518
}
1✔
519

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

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

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

7,727✔
549
        return max/width + 1
4,659,039✔
550
}
4,651,312✔
551

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

565
        return fv.encode(w, length, 8)
566
}
4,199✔
567

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

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

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

594
        _, err := w.Write(data)
595
        return err
7,137✔
596
}
7,137✔
597

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

610
        return fv.decode(r, int(length), 8)
611
}
612

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

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

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

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

646
        return nil
647
}
14,697✔
648

7,778,193✔
649
// sizeFunc returns the length required to encode the feature vector.
7,763,496✔
650
func (fv *RawFeatureVector) sizeFunc() uint64 {
7,763,496✔
651
        return uint64(fv.SerializeSize())
11,482,995✔
652
}
3,719,499✔
653

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

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

204✔
672
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
673
}
674

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

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

686
                return nil
687
        }
430✔
688

430✔
689
        return tlv.NewTypeForEncodingErr(val, "lnwire.RawFeatureVector")
860✔
690
}
430✔
691

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

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

707
        if featureVector == nil {
708
                featureVector = NewRawFeatureVector()
709
        }
710
        return &FeatureVector{
711
                RawFeatureVector: featureVector,
712
                featureNames:     featureNames,
713
        }
714
}
715

21,928✔
716
// EmptyFeatureVector returns a feature vector with no bits set.
21,928✔
717
func EmptyFeatureVector() *FeatureVector {
35,716✔
718
        return NewFeatureVector(nil, Features)
13,788✔
719
}
13,788✔
720

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

737
                        return tlv.NewTypeForEncodingErr(
738
                                val, "*lnwire.FeatureVector",
27✔
739
                        )
27✔
740
                },
29✔
741
                func(r io.Reader, val interface{}, buf *[8]byte,
4✔
742
                        l uint64) error {
2✔
743

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

4✔
753
                                *f = *features
4✔
754

8✔
755
                                return nil
4✔
756
                        }
4✔
757

4✔
758
                        return tlv.NewTypeForDecodingErr(
4✔
759
                                val, "*lnwire.FeatureVector", l, l,
4✔
760
                        )
×
UNCOV
761
                },
×
762
        )
763
}
4✔
764

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

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

786
        return fv.IsSet(feature)
787
}
788

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

802
// UnknownFeatures returns a boolean if a feature vector contains *any*
1,874✔
803
// unknown features (even if they are odd).
1,874✔
804
func (fv *FeatureVector) UnknownFeatures() bool {
3,486✔
805
        for feature := range fv.features {
1,620✔
806
                if !fv.IsKnown(feature) {
8✔
807
                        return true
8✔
808
                }
809
        }
1,874✔
810

811
        return false
812
}
813

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

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

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

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

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