features.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. package lnwire
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "github.com/lightningnetwork/lnd/tlv"
  8. )
  9. var (
  10. // ErrFeaturePairExists signals an error in feature vector construction
  11. // where the opposing bit in a feature pair has already been set.
  12. ErrFeaturePairExists = errors.New("feature pair exists")
  13. // ErrFeatureStandard is returned when attempts to modify LND's known
  14. // set of features are made.
  15. ErrFeatureStandard = errors.New("feature is used in standard " +
  16. "protocol set")
  17. // ErrFeatureBitMaximum is returned when a feature bit exceeds the
  18. // maximum allowable value.
  19. ErrFeatureBitMaximum = errors.New("feature bit exceeds allowed maximum")
  20. )
  21. // FeatureBit represents a feature that can be enabled in either a local or
  22. // global feature vector at a specific bit position. Feature bits follow the
  23. // "it's OK to be odd" rule, where features at even bit positions must be known
  24. // to a node receiving them from a peer while odd bits do not. In accordance,
  25. // feature bits are usually assigned in pairs, first being assigned an odd bit
  26. // position which may later be changed to the preceding even position once
  27. // knowledge of the feature becomes required on the network.
  28. type FeatureBit uint16
  29. const (
  30. // DataLossProtectRequired is a feature bit that indicates that a peer
  31. // *requires* the other party know about the data-loss-protect optional
  32. // feature. If the remote peer does not know of such a feature, then
  33. // the sending peer SHOULD disconnect them. The data-loss-protect
  34. // feature allows a peer that's lost partial data to recover their
  35. // settled funds of the latest commitment state.
  36. DataLossProtectRequired FeatureBit = 0
  37. // DataLossProtectOptional is an optional feature bit that indicates
  38. // that the sending peer knows of this new feature and can activate it
  39. // it. The data-loss-protect feature allows a peer that's lost partial
  40. // data to recover their settled funds of the latest commitment state.
  41. DataLossProtectOptional FeatureBit = 1
  42. // InitialRoutingSync is a local feature bit meaning that the receiving
  43. // node should send a complete dump of routing information when a new
  44. // connection is established.
  45. InitialRoutingSync FeatureBit = 3
  46. // UpfrontShutdownScriptRequired is a feature bit which indicates that a
  47. // peer *requires* that the remote peer accept an upfront shutdown script to
  48. // which payout is enforced on cooperative closes.
  49. UpfrontShutdownScriptRequired FeatureBit = 4
  50. // UpfrontShutdownScriptOptional is an optional feature bit which indicates
  51. // that the peer will accept an upfront shutdown script to which payout is
  52. // enforced on cooperative closes.
  53. UpfrontShutdownScriptOptional FeatureBit = 5
  54. // GossipQueriesRequired is a feature bit that indicates that the
  55. // receiving peer MUST know of the set of features that allows nodes to
  56. // more efficiently query the network view of peers on the network for
  57. // reconciliation purposes.
  58. GossipQueriesRequired FeatureBit = 6
  59. // GossipQueriesOptional is an optional feature bit that signals that
  60. // the setting peer knows of the set of features that allows more
  61. // efficient network view reconciliation.
  62. GossipQueriesOptional FeatureBit = 7
  63. // TLVOnionPayloadRequired is a feature bit that indicates a node is
  64. // able to decode the new TLV information included in the onion packet.
  65. TLVOnionPayloadRequired FeatureBit = 8
  66. // TLVOnionPayloadOptional is an optional feature bit that indicates a
  67. // node is able to decode the new TLV information included in the onion
  68. // packet.
  69. TLVOnionPayloadOptional FeatureBit = 9
  70. // StaticRemoteKeyRequired is a required feature bit that signals that
  71. // within one's commitment transaction, the key used for the remote
  72. // party's non-delay output should not be tweaked.
  73. StaticRemoteKeyRequired FeatureBit = 12
  74. // StaticRemoteKeyOptional is an optional feature bit that signals that
  75. // within one's commitment transaction, the key used for the remote
  76. // party's non-delay output should not be tweaked.
  77. StaticRemoteKeyOptional FeatureBit = 13
  78. // PaymentAddrRequired is a required feature bit that signals that a
  79. // node requires payment addresses, which are used to mitigate probing
  80. // attacks on the receiver of a payment.
  81. PaymentAddrRequired FeatureBit = 14
  82. // PaymentAddrOptional is an optional feature bit that signals that a
  83. // node supports payment addresses, which are used to mitigate probing
  84. // attacks on the receiver of a payment.
  85. PaymentAddrOptional FeatureBit = 15
  86. // MPPRequired is a required feature bit that signals that the receiver
  87. // of a payment requires settlement of an invoice with more than one
  88. // HTLC.
  89. MPPRequired FeatureBit = 16
  90. // MPPOptional is an optional feature bit that signals that the receiver
  91. // of a payment supports settlement of an invoice with more than one
  92. // HTLC.
  93. MPPOptional FeatureBit = 17
  94. // WumboChannelsRequired is a required feature bit that signals that a
  95. // node is willing to accept channels larger than 2^24 satoshis.
  96. WumboChannelsRequired FeatureBit = 18
  97. // WumboChannelsOptional is an optional feature bit that signals that a
  98. // node is willing to accept channels larger than 2^24 satoshis.
  99. WumboChannelsOptional FeatureBit = 19
  100. // AnchorsRequired is a required feature bit that signals that the node
  101. // requires channels to be made using commitments having anchor
  102. // outputs.
  103. AnchorsRequired FeatureBit = 20
  104. // AnchorsOptional is an optional feature bit that signals that the
  105. // node supports channels to be made using commitments having anchor
  106. // outputs.
  107. AnchorsOptional FeatureBit = 21
  108. // AnchorsZeroFeeHtlcTxRequired is a required feature bit that signals
  109. // that the node requires channels having zero-fee second-level HTLC
  110. // transactions, which also imply anchor commitments.
  111. AnchorsZeroFeeHtlcTxRequired FeatureBit = 22
  112. // AnchorsZeroFeeHtlcTxOptional is an optional feature bit that signals
  113. // that the node supports channels having zero-fee second-level HTLC
  114. // transactions, which also imply anchor commitments.
  115. AnchorsZeroFeeHtlcTxOptional FeatureBit = 23
  116. // RouteBlindingRequired is a required feature bit that signals that
  117. // the node supports blinded payments.
  118. RouteBlindingRequired FeatureBit = 24
  119. // RouteBlindingOptional is an optional feature bit that signals that
  120. // the node supports blinded payments.
  121. RouteBlindingOptional FeatureBit = 25
  122. // ShutdownAnySegwitRequired is an required feature bit that signals
  123. // that the sender is able to properly handle/parse segwit witness
  124. // programs up to version 16. This enables utilization of Taproot
  125. // addresses for cooperative closure addresses.
  126. ShutdownAnySegwitRequired FeatureBit = 26
  127. // ShutdownAnySegwitOptional is an optional feature bit that signals
  128. // that the sender is able to properly handle/parse segwit witness
  129. // programs up to version 16. This enables utilization of Taproot
  130. // addresses for cooperative closure addresses.
  131. ShutdownAnySegwitOptional FeatureBit = 27
  132. // AMPRequired is a required feature bit that signals that the receiver
  133. // of a payment supports accepts spontaneous payments, i.e.
  134. // sender-generated preimages according to BOLT XX.
  135. AMPRequired FeatureBit = 30
  136. // AMPOptional is an optional feature bit that signals that the receiver
  137. // of a payment supports accepts spontaneous payments, i.e.
  138. // sender-generated preimages according to BOLT XX.
  139. AMPOptional FeatureBit = 31
  140. // ExplicitChannelTypeRequired is a required bit that denotes that a
  141. // connection established with this node is to use explicit channel
  142. // commitment types for negotiation instead of the existing implicit
  143. // negotiation methods. With this bit, there is no longer a "default"
  144. // implicit channel commitment type, allowing a connection to
  145. // open/maintain types of several channels over its lifetime.
  146. ExplicitChannelTypeRequired = 44
  147. // ExplicitChannelTypeOptional is an optional bit that denotes that a
  148. // connection established with this node is to use explicit channel
  149. // commitment types for negotiation instead of the existing implicit
  150. // negotiation methods. With this bit, there is no longer a "default"
  151. // implicit channel commitment type, allowing a connection to
  152. // TODO: Decide on actual feature bit value.
  153. ExplicitChannelTypeOptional = 45
  154. // ScidAliasRequired is a required feature bit that signals that the
  155. // node requires understanding of ShortChannelID aliases in the TLV
  156. // segment of the channel_ready message.
  157. ScidAliasRequired FeatureBit = 46
  158. // ScidAliasOptional is an optional feature bit that signals that the
  159. // node understands ShortChannelID aliases in the TLV segment of the
  160. // channel_ready message.
  161. ScidAliasOptional FeatureBit = 47
  162. // PaymentMetadataRequired is a required bit that denotes that if an
  163. // invoice contains metadata, it must be passed along with the payment
  164. // htlc(s).
  165. PaymentMetadataRequired = 48
  166. // PaymentMetadataOptional is an optional bit that denotes that if an
  167. // invoice contains metadata, it may be passed along with the payment
  168. // htlc(s).
  169. PaymentMetadataOptional = 49
  170. // ZeroConfRequired is a required feature bit that signals that the
  171. // node requires understanding of the zero-conf channel_type.
  172. ZeroConfRequired FeatureBit = 50
  173. // ZeroConfOptional is an optional feature bit that signals that the
  174. // node understands the zero-conf channel type.
  175. ZeroConfOptional FeatureBit = 51
  176. // KeysendRequired is a required bit that indicates that the node is
  177. // able and willing to accept keysend payments.
  178. KeysendRequired = 54
  179. // KeysendOptional is an optional bit that indicates that the node is
  180. // able and willing to accept keysend payments.
  181. KeysendOptional = 55
  182. // ScriptEnforcedLeaseOptional is an optional feature bit that signals
  183. // that the node requires channels having zero-fee second-level HTLC
  184. // transactions, which also imply anchor commitments, along with an
  185. // additional CLTV constraint of a channel lease's expiration height
  186. // applied to all outputs that pay directly to the channel initiator.
  187. //
  188. // TODO: Decide on actual feature bit value.
  189. ScriptEnforcedLeaseRequired FeatureBit = 2022
  190. // ScriptEnforcedLeaseOptional is an optional feature bit that signals
  191. // that the node requires channels having zero-fee second-level HTLC
  192. // transactions, which also imply anchor commitments, along with an
  193. // additional CLTV constraint of a channel lease's expiration height
  194. // applied to all outputs that pay directly to the channel initiator.
  195. //
  196. // TODO: Decide on actual feature bit value.
  197. ScriptEnforcedLeaseOptional FeatureBit = 2023
  198. // SimpleTaprootChannelsRequredFinal is a required bit that indicates
  199. // the node is able to create taproot-native channels. This is the
  200. // final feature bit to be used once the channel type is finalized.
  201. SimpleTaprootChannelsRequiredFinal = 80
  202. // SimpleTaprootChannelsOptionalFinal is an optional bit that indicates
  203. // the node is able to create taproot-native channels. This is the
  204. // final
  205. // feature bit to be used once the channel type is finalized.
  206. SimpleTaprootChannelsOptionalFinal = 81
  207. // SimpleTaprootChannelsRequredStaging is a required bit that indicates
  208. // the node is able to create taproot-native channels. This is a
  209. // feature bit used in the wild while the channel type is still being
  210. // finalized.
  211. SimpleTaprootChannelsRequiredStaging = 180
  212. // SimpleTaprootChannelsOptionalStaging is an optional bit that
  213. // indicates the node is able to create taproot-native channels. This
  214. // is a feature
  215. // bit used in the wild while the channel type is still being
  216. // finalized.
  217. SimpleTaprootChannelsOptionalStaging = 181
  218. // MaxBolt11Feature is the maximum feature bit value allowed in bolt 11
  219. // invoices.
  220. //
  221. // The base 32 encoded tagged fields in invoices are limited to 10 bits
  222. // to express the length of the field's data.
  223. //nolint:lll
  224. // See: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#tagged-fields
  225. //
  226. // With a maximum length field of 1023 (2^10 -1) and 5 bit encoding,
  227. // the highest feature bit that can be expressed is:
  228. // 1023 * 5 - 1 = 5114.
  229. MaxBolt11Feature = 5114
  230. )
  231. // IsRequired returns true if the feature bit is even, and false otherwise.
  232. func (b FeatureBit) IsRequired() bool {
  233. return b&0x01 == 0x00
  234. }
  235. // Features is a mapping of known feature bits to a descriptive name. All known
  236. // feature bits must be assigned a name in this mapping, and feature bit pairs
  237. // must be assigned together for correct behavior.
  238. var Features = map[FeatureBit]string{
  239. DataLossProtectRequired: "data-loss-protect",
  240. DataLossProtectOptional: "data-loss-protect",
  241. InitialRoutingSync: "initial-routing-sync",
  242. UpfrontShutdownScriptRequired: "upfront-shutdown-script",
  243. UpfrontShutdownScriptOptional: "upfront-shutdown-script",
  244. GossipQueriesRequired: "gossip-queries",
  245. GossipQueriesOptional: "gossip-queries",
  246. TLVOnionPayloadRequired: "tlv-onion",
  247. TLVOnionPayloadOptional: "tlv-onion",
  248. StaticRemoteKeyOptional: "static-remote-key",
  249. StaticRemoteKeyRequired: "static-remote-key",
  250. PaymentAddrOptional: "payment-addr",
  251. PaymentAddrRequired: "payment-addr",
  252. MPPOptional: "multi-path-payments",
  253. MPPRequired: "multi-path-payments",
  254. AnchorsRequired: "anchor-commitments",
  255. AnchorsOptional: "anchor-commitments",
  256. AnchorsZeroFeeHtlcTxRequired: "anchors-zero-fee-htlc-tx",
  257. AnchorsZeroFeeHtlcTxOptional: "anchors-zero-fee-htlc-tx",
  258. WumboChannelsRequired: "wumbo-channels",
  259. WumboChannelsOptional: "wumbo-channels",
  260. AMPRequired: "amp",
  261. AMPOptional: "amp",
  262. PaymentMetadataOptional: "payment-metadata",
  263. PaymentMetadataRequired: "payment-metadata",
  264. ExplicitChannelTypeOptional: "explicit-commitment-type",
  265. ExplicitChannelTypeRequired: "explicit-commitment-type",
  266. KeysendOptional: "keysend",
  267. KeysendRequired: "keysend",
  268. ScriptEnforcedLeaseRequired: "script-enforced-lease",
  269. ScriptEnforcedLeaseOptional: "script-enforced-lease",
  270. ScidAliasRequired: "scid-alias",
  271. ScidAliasOptional: "scid-alias",
  272. ZeroConfRequired: "zero-conf",
  273. ZeroConfOptional: "zero-conf",
  274. RouteBlindingRequired: "route-blinding",
  275. RouteBlindingOptional: "route-blinding",
  276. ShutdownAnySegwitRequired: "shutdown-any-segwit",
  277. ShutdownAnySegwitOptional: "shutdown-any-segwit",
  278. SimpleTaprootChannelsRequiredFinal: "simple-taproot-chans",
  279. SimpleTaprootChannelsOptionalFinal: "simple-taproot-chans",
  280. SimpleTaprootChannelsRequiredStaging: "simple-taproot-chans-x",
  281. SimpleTaprootChannelsOptionalStaging: "simple-taproot-chans-x",
  282. }
  283. // RawFeatureVector represents a set of feature bits as defined in BOLT-09. A
  284. // RawFeatureVector itself just stores a set of bit flags but can be used to
  285. // construct a FeatureVector which binds meaning to each bit. Feature vectors
  286. // can be serialized and deserialized to/from a byte representation that is
  287. // transmitted in Lightning network messages.
  288. type RawFeatureVector struct {
  289. features map[FeatureBit]struct{}
  290. }
  291. // NewRawFeatureVector creates a feature vector with all of the feature bits
  292. // given as arguments enabled.
  293. func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
  294. fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
  295. for _, bit := range bits {
  296. fv.Set(bit)
  297. }
  298. return fv
  299. }
  300. // IsEmpty returns whether the feature vector contains any feature bits.
  301. func (fv RawFeatureVector) IsEmpty() bool {
  302. return len(fv.features) == 0
  303. }
  304. // OnlyContains determines whether only the specified feature bits are found.
  305. func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
  306. if len(bits) != len(fv.features) {
  307. return false
  308. }
  309. for _, bit := range bits {
  310. if !fv.IsSet(bit) {
  311. return false
  312. }
  313. }
  314. return true
  315. }
  316. // Equals determines whether two features vectors contain exactly the same
  317. // features.
  318. func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
  319. if len(fv.features) != len(other.features) {
  320. return false
  321. }
  322. for bit := range fv.features {
  323. if _, ok := other.features[bit]; !ok {
  324. return false
  325. }
  326. }
  327. return true
  328. }
  329. // Merges sets all feature bits in other on the receiver's feature vector.
  330. func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
  331. for bit := range other.features {
  332. err := fv.SafeSet(bit)
  333. if err != nil {
  334. return err
  335. }
  336. }
  337. return nil
  338. }
  339. // ValidateUpdate checks whether a feature vector can safely be updated to the
  340. // new feature vector provided, checking that it does not alter any of the
  341. // "standard" features that are defined by LND. The new feature vector should
  342. // be inclusive of all features in the original vector that it still wants to
  343. // advertise, setting and unsetting updates as desired. Features in the vector
  344. // are also checked against a maximum inclusive value, as feature vectors in
  345. // different contexts have different maximum values.
  346. func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
  347. maximumValue FeatureBit) error {
  348. // Run through the new set of features and check that we're not adding
  349. // any feature bits that are defined but not set in LND.
  350. for feature := range other.features {
  351. if fv.IsSet(feature) {
  352. continue
  353. }
  354. if feature > maximumValue {
  355. return fmt.Errorf("can't set feature bit %d: %w %v",
  356. feature, ErrFeatureBitMaximum,
  357. maximumValue)
  358. }
  359. if name, known := Features[feature]; known {
  360. return fmt.Errorf("can't set feature "+
  361. "bit %d (%v): %w", feature, name,
  362. ErrFeatureStandard)
  363. }
  364. }
  365. // Check that the new feature vector for this set does not unset any
  366. // features that are standard in LND by comparing the features in our
  367. // current set to the omitted values in the new set.
  368. for feature := range fv.features {
  369. if other.IsSet(feature) {
  370. continue
  371. }
  372. if name, known := Features[feature]; known {
  373. return fmt.Errorf("can't unset feature "+
  374. "bit %d (%v): %w", feature, name,
  375. ErrFeatureStandard)
  376. }
  377. }
  378. return nil
  379. }
  380. // ValidatePairs checks each feature bit in a raw vector to ensure that the
  381. // opposing bit is not set, validating that the vector has either the optional
  382. // or required bit set, not both.
  383. func (fv *RawFeatureVector) ValidatePairs() error {
  384. for feature := range fv.features {
  385. if _, ok := fv.features[feature^1]; ok {
  386. return ErrFeaturePairExists
  387. }
  388. }
  389. return nil
  390. }
  391. // Clone makes a copy of a feature vector.
  392. func (fv *RawFeatureVector) Clone() *RawFeatureVector {
  393. newFeatures := NewRawFeatureVector()
  394. for bit := range fv.features {
  395. newFeatures.Set(bit)
  396. }
  397. return newFeatures
  398. }
  399. // IsSet returns whether a particular feature bit is enabled in the vector.
  400. func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
  401. _, ok := fv.features[feature]
  402. return ok
  403. }
  404. // Set marks a feature as enabled in the vector.
  405. func (fv *RawFeatureVector) Set(feature FeatureBit) {
  406. fv.features[feature] = struct{}{}
  407. }
  408. // SafeSet sets the chosen feature bit in the feature vector, but returns an
  409. // error if the opposing feature bit is already set. This ensures both that we
  410. // are creating properly structured feature vectors, and in some cases, that
  411. // peers are sending properly encoded ones, i.e. it can't be both optional and
  412. // required.
  413. func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
  414. if _, ok := fv.features[feature^1]; ok {
  415. return ErrFeaturePairExists
  416. }
  417. fv.Set(feature)
  418. return nil
  419. }
  420. // Unset marks a feature as disabled in the vector.
  421. func (fv *RawFeatureVector) Unset(feature FeatureBit) {
  422. delete(fv.features, feature)
  423. }
  424. // SerializeSize returns the number of bytes needed to represent feature vector
  425. // in byte format.
  426. func (fv *RawFeatureVector) SerializeSize() int {
  427. // We calculate byte-length via the largest bit index.
  428. return fv.serializeSize(8)
  429. }
  430. // SerializeSize32 returns the number of bytes needed to represent feature
  431. // vector in base32 format.
  432. func (fv *RawFeatureVector) SerializeSize32() int {
  433. // We calculate base32-length via the largest bit index.
  434. return fv.serializeSize(5)
  435. }
  436. // serializeSize returns the number of bytes required to encode the feature
  437. // vector using at most width bits per encoded byte.
  438. func (fv *RawFeatureVector) serializeSize(width int) int {
  439. // Find the largest feature bit index
  440. max := -1
  441. for feature := range fv.features {
  442. index := int(feature)
  443. if index > max {
  444. max = index
  445. }
  446. }
  447. if max == -1 {
  448. return 0
  449. }
  450. return max/width + 1
  451. }
  452. // Encode writes the feature vector in byte representation. Every feature
  453. // encoded as a bit, and the bit vector is serialized using the least number of
  454. // bytes. Since the bit vector length is variable, the first two bytes of the
  455. // serialization represent the length.
  456. func (fv *RawFeatureVector) Encode(w io.Writer) error {
  457. // Write length of feature vector.
  458. var l [2]byte
  459. length := fv.SerializeSize()
  460. binary.BigEndian.PutUint16(l[:], uint16(length))
  461. if _, err := w.Write(l[:]); err != nil {
  462. return err
  463. }
  464. return fv.encode(w, length, 8)
  465. }
  466. // EncodeBase256 writes the feature vector in base256 representation. Every
  467. // feature is encoded as a bit, and the bit vector is serialized using the least
  468. // number of bytes.
  469. func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
  470. length := fv.SerializeSize()
  471. return fv.encode(w, length, 8)
  472. }
  473. // EncodeBase32 writes the feature vector in base32 representation. Every feature
  474. // is encoded as a bit, and the bit vector is serialized using the least number of
  475. // bytes.
  476. func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
  477. length := fv.SerializeSize32()
  478. return fv.encode(w, length, 5)
  479. }
  480. // encode writes the feature vector
  481. func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
  482. // Generate the data and write it.
  483. data := make([]byte, length)
  484. for feature := range fv.features {
  485. byteIndex := int(feature) / width
  486. bitIndex := int(feature) % width
  487. data[length-byteIndex-1] |= 1 << uint(bitIndex)
  488. }
  489. _, err := w.Write(data)
  490. return err
  491. }
  492. // Decode reads the feature vector from its byte representation. Every feature
  493. // is encoded as a bit, and the bit vector is serialized using the least number
  494. // of bytes. Since the bit vector length is variable, the first two bytes of the
  495. // serialization represent the length.
  496. func (fv *RawFeatureVector) Decode(r io.Reader) error {
  497. // Read the length of the feature vector.
  498. var l [2]byte
  499. if _, err := io.ReadFull(r, l[:]); err != nil {
  500. return err
  501. }
  502. length := binary.BigEndian.Uint16(l[:])
  503. return fv.decode(r, int(length), 8)
  504. }
  505. // DecodeBase256 reads the feature vector from its base256 representation. Every
  506. // feature encoded as a bit, and the bit vector is serialized using the least
  507. // number of bytes.
  508. func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
  509. return fv.decode(r, length, 8)
  510. }
  511. // DecodeBase32 reads the feature vector from its base32 representation. Every
  512. // feature encoded as a bit, and the bit vector is serialized using the least
  513. // number of bytes.
  514. func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
  515. return fv.decode(r, length, 5)
  516. }
  517. // decode reads a feature vector from the next length bytes of the io.Reader,
  518. // assuming each byte has width feature bits encoded per byte.
  519. func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
  520. // Read the feature vector data.
  521. data := make([]byte, length)
  522. if _, err := io.ReadFull(r, data); err != nil {
  523. return err
  524. }
  525. // Set feature bits from parsed data.
  526. bitsNumber := len(data) * width
  527. for i := 0; i < bitsNumber; i++ {
  528. byteIndex := int(i / width)
  529. bitIndex := uint(i % width)
  530. if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
  531. fv.Set(FeatureBit(i))
  532. }
  533. }
  534. return nil
  535. }
  536. // sizeFunc returns the length required to encode the feature vector.
  537. func (fv *RawFeatureVector) sizeFunc() uint64 {
  538. return uint64(fv.SerializeSize())
  539. }
  540. // Record returns a TLV record that can be used to encode/decode raw feature
  541. // vectors. Note that the length of the feature vector is not included, because
  542. // it is covered by the TLV record's length field.
  543. func (fv *RawFeatureVector) Record(recordType tlv.Type) tlv.Record {
  544. return tlv.MakeDynamicRecord(
  545. recordType, fv, fv.sizeFunc, rawFeatureEncoder,
  546. rawFeatureDecoder,
  547. )
  548. }
  549. // rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
  550. func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
  551. if f, ok := val.(*RawFeatureVector); ok {
  552. return f.encode(w, f.SerializeSize(), 8)
  553. }
  554. return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
  555. }
  556. // rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
  557. func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
  558. l uint64) error {
  559. if f, ok := val.(*RawFeatureVector); ok {
  560. return f.decode(r, int(l), 8)
  561. }
  562. return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
  563. }
  564. // FeatureVector represents a set of enabled features. The set stores
  565. // information on enabled flags and metadata about the feature names. A feature
  566. // vector is serializable to a compact byte representation that is included in
  567. // Lightning network messages.
  568. type FeatureVector struct {
  569. *RawFeatureVector
  570. featureNames map[FeatureBit]string
  571. }
  572. // NewFeatureVector constructs a new FeatureVector from a raw feature vector
  573. // and mapping of feature definitions. If the feature vector argument is nil, a
  574. // new one will be constructed with no enabled features.
  575. func NewFeatureVector(featureVector *RawFeatureVector,
  576. featureNames map[FeatureBit]string) *FeatureVector {
  577. if featureVector == nil {
  578. featureVector = NewRawFeatureVector()
  579. }
  580. return &FeatureVector{
  581. RawFeatureVector: featureVector,
  582. featureNames: featureNames,
  583. }
  584. }
  585. // EmptyFeatureVector returns a feature vector with no bits set.
  586. func EmptyFeatureVector() *FeatureVector {
  587. return NewFeatureVector(nil, Features)
  588. }
  589. // Record implements the RecordProducer interface for FeatureVector. Note that
  590. // it uses a zero-value type is used to produce the record, as we expect this
  591. // type value to be overwritten when used in generic TLV record production.
  592. // This allows a single Record function to serve in the many different contexts
  593. // in which feature vectors are encoded. This record wraps the encoding/
  594. // decoding for our raw feature vectors so that we can directly parse fully
  595. // formed feature vector types.
  596. func (fv *FeatureVector) Record() tlv.Record {
  597. return tlv.MakeDynamicRecord(0, fv, fv.sizeFunc,
  598. func(w io.Writer, val interface{}, buf *[8]byte) error {
  599. if f, ok := val.(*FeatureVector); ok {
  600. return rawFeatureEncoder(
  601. w, f.RawFeatureVector, buf,
  602. )
  603. }
  604. return tlv.NewTypeForEncodingErr(
  605. val, "*lnwire.FeatureVector",
  606. )
  607. },
  608. func(r io.Reader, val interface{}, buf *[8]byte,
  609. l uint64) error {
  610. if f, ok := val.(*FeatureVector); ok {
  611. features := NewFeatureVector(nil, Features)
  612. err := rawFeatureDecoder(
  613. r, features.RawFeatureVector, buf, l,
  614. )
  615. if err != nil {
  616. return err
  617. }
  618. *f = *features
  619. return nil
  620. }
  621. return tlv.NewTypeForDecodingErr(
  622. val, "*lnwire.FeatureVector", l, l,
  623. )
  624. },
  625. )
  626. }
  627. // HasFeature returns whether a particular feature is included in the set. The
  628. // feature can be seen as set either if the bit is set directly OR the queried
  629. // bit has the same meaning as its corresponding even/odd bit, which is set
  630. // instead. The second case is because feature bits are generally assigned in
  631. // pairs where both the even and odd position represent the same feature.
  632. func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
  633. return fv.IsSet(feature) ||
  634. (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
  635. }
  636. // RequiresFeature returns true if the referenced feature vector *requires*
  637. // that the given required bit be set. This method can be used with both
  638. // optional and required feature bits as a parameter.
  639. func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
  640. // If we weren't passed a required feature bit, then we'll flip the
  641. // lowest bit to query for the required version of the feature. This
  642. // lets callers pass in both the optional and required bits.
  643. if !feature.IsRequired() {
  644. feature ^= 1
  645. }
  646. return fv.IsSet(feature)
  647. }
  648. // UnknownRequiredFeatures returns a list of feature bits set in the vector
  649. // that are unknown and in an even bit position. Feature bits with an even
  650. // index must be known to a node receiving the feature vector in a message.
  651. func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
  652. var unknown []FeatureBit
  653. for feature := range fv.features {
  654. if feature%2 == 0 && !fv.IsKnown(feature) {
  655. unknown = append(unknown, feature)
  656. }
  657. }
  658. return unknown
  659. }
  660. // UnknownFeatures returns a boolean if a feature vector contains *any*
  661. // unknown features (even if they are odd).
  662. func (fv *FeatureVector) UnknownFeatures() bool {
  663. for feature := range fv.features {
  664. if !fv.IsKnown(feature) {
  665. return true
  666. }
  667. }
  668. return false
  669. }
  670. // Name returns a string identifier for the feature represented by this bit. If
  671. // the bit does not represent a known feature, this returns a string indicating
  672. // as such.
  673. func (fv *FeatureVector) Name(bit FeatureBit) string {
  674. name, known := fv.featureNames[bit]
  675. if !known {
  676. return "unknown"
  677. }
  678. return name
  679. }
  680. // IsKnown returns whether this feature bit represents a known feature.
  681. func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
  682. _, known := fv.featureNames[bit]
  683. return known
  684. }
  685. // isFeatureBitPair returns whether this feature bit and its corresponding
  686. // even/odd bit both represent the same feature. This may often be the case as
  687. // bits are generally assigned in pairs, first being assigned an odd bit
  688. // position then being promoted to an even bit position once the network is
  689. // ready.
  690. func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
  691. name1, known1 := fv.featureNames[bit]
  692. name2, known2 := fv.featureNames[bit^1]
  693. return known1 && known2 && name1 == name2
  694. }
  695. // Features returns the set of raw features contained in the feature vector.
  696. func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
  697. fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
  698. for b := range fv.RawFeatureVector.features {
  699. fs[b] = struct{}{}
  700. }
  701. return fs
  702. }
  703. // Clone copies a feature vector, carrying over its feature bits. The feature
  704. // names are not copied.
  705. func (fv *FeatureVector) Clone() *FeatureVector {
  706. features := fv.RawFeatureVector.Clone()
  707. return NewFeatureVector(features, fv.featureNames)
  708. }