features.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. // ScriptEnforcedLeaseRequired is a required 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. // SimpleTaprootChannelsRequiredFinal 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 feature bit to be used once the channel type is finalized.
  205. SimpleTaprootChannelsOptionalFinal = 81
  206. // SimpleTaprootChannelsRequiredStaging is a required bit that indicates
  207. // the node is able to create taproot-native channels. This is a
  208. // feature bit used in the wild while the channel type is still being
  209. // finalized.
  210. SimpleTaprootChannelsRequiredStaging = 180
  211. // SimpleTaprootChannelsOptionalStaging is an optional bit that
  212. // indicates the node is able to create taproot-native channels. This
  213. // is a feature bit used in the wild while the channel type is still
  214. // being finalized.
  215. SimpleTaprootChannelsOptionalStaging = 181
  216. // Bolt11BlindedPathsRequired is a required feature bit that indicates
  217. // that the node is able to understand the blinded path tagged field in
  218. // a BOLT 11 invoice.
  219. Bolt11BlindedPathsRequired = 262
  220. // Bolt11BlindedPathsOptional is an optional feature bit that indicates
  221. // that the node is able to understand the blinded path tagged field in
  222. // a BOLT 11 invoice.
  223. Bolt11BlindedPathsOptional = 263
  224. // MaxBolt11Feature is the maximum feature bit value allowed in bolt 11
  225. // invoices.
  226. //
  227. // The base 32 encoded tagged fields in invoices are limited to 10 bits
  228. // to express the length of the field's data.
  229. //nolint:lll
  230. // See: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md#tagged-fields
  231. //
  232. // With a maximum length field of 1023 (2^10 -1) and 5 bit encoding,
  233. // the highest feature bit that can be expressed is:
  234. // 1023 * 5 - 1 = 5114.
  235. MaxBolt11Feature = 5114
  236. )
  237. // IsRequired returns true if the feature bit is even, and false otherwise.
  238. func (b FeatureBit) IsRequired() bool {
  239. return b&0x01 == 0x00
  240. }
  241. // Features is a mapping of known feature bits to a descriptive name. All known
  242. // feature bits must be assigned a name in this mapping, and feature bit pairs
  243. // must be assigned together for correct behavior.
  244. var Features = map[FeatureBit]string{
  245. DataLossProtectRequired: "data-loss-protect",
  246. DataLossProtectOptional: "data-loss-protect",
  247. InitialRoutingSync: "initial-routing-sync",
  248. UpfrontShutdownScriptRequired: "upfront-shutdown-script",
  249. UpfrontShutdownScriptOptional: "upfront-shutdown-script",
  250. GossipQueriesRequired: "gossip-queries",
  251. GossipQueriesOptional: "gossip-queries",
  252. TLVOnionPayloadRequired: "tlv-onion",
  253. TLVOnionPayloadOptional: "tlv-onion",
  254. StaticRemoteKeyOptional: "static-remote-key",
  255. StaticRemoteKeyRequired: "static-remote-key",
  256. PaymentAddrOptional: "payment-addr",
  257. PaymentAddrRequired: "payment-addr",
  258. MPPOptional: "multi-path-payments",
  259. MPPRequired: "multi-path-payments",
  260. AnchorsRequired: "anchor-commitments",
  261. AnchorsOptional: "anchor-commitments",
  262. AnchorsZeroFeeHtlcTxRequired: "anchors-zero-fee-htlc-tx",
  263. AnchorsZeroFeeHtlcTxOptional: "anchors-zero-fee-htlc-tx",
  264. WumboChannelsRequired: "wumbo-channels",
  265. WumboChannelsOptional: "wumbo-channels",
  266. AMPRequired: "amp",
  267. AMPOptional: "amp",
  268. PaymentMetadataOptional: "payment-metadata",
  269. PaymentMetadataRequired: "payment-metadata",
  270. ExplicitChannelTypeOptional: "explicit-commitment-type",
  271. ExplicitChannelTypeRequired: "explicit-commitment-type",
  272. KeysendOptional: "keysend",
  273. KeysendRequired: "keysend",
  274. ScriptEnforcedLeaseRequired: "script-enforced-lease",
  275. ScriptEnforcedLeaseOptional: "script-enforced-lease",
  276. ScidAliasRequired: "scid-alias",
  277. ScidAliasOptional: "scid-alias",
  278. ZeroConfRequired: "zero-conf",
  279. ZeroConfOptional: "zero-conf",
  280. RouteBlindingRequired: "route-blinding",
  281. RouteBlindingOptional: "route-blinding",
  282. ShutdownAnySegwitRequired: "shutdown-any-segwit",
  283. ShutdownAnySegwitOptional: "shutdown-any-segwit",
  284. SimpleTaprootChannelsRequiredFinal: "simple-taproot-chans",
  285. SimpleTaprootChannelsOptionalFinal: "simple-taproot-chans",
  286. SimpleTaprootChannelsRequiredStaging: "simple-taproot-chans-x",
  287. SimpleTaprootChannelsOptionalStaging: "simple-taproot-chans-x",
  288. Bolt11BlindedPathsOptional: "bolt-11-blinded-paths",
  289. Bolt11BlindedPathsRequired: "bolt-11-blinded-paths",
  290. }
  291. // RawFeatureVector represents a set of feature bits as defined in BOLT-09. A
  292. // RawFeatureVector itself just stores a set of bit flags but can be used to
  293. // construct a FeatureVector which binds meaning to each bit. Feature vectors
  294. // can be serialized and deserialized to/from a byte representation that is
  295. // transmitted in Lightning network messages.
  296. type RawFeatureVector struct {
  297. features map[FeatureBit]struct{}
  298. }
  299. // NewRawFeatureVector creates a feature vector with all of the feature bits
  300. // given as arguments enabled.
  301. func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
  302. fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
  303. for _, bit := range bits {
  304. fv.Set(bit)
  305. }
  306. return fv
  307. }
  308. // IsEmpty returns whether the feature vector contains any feature bits.
  309. func (fv RawFeatureVector) IsEmpty() bool {
  310. return len(fv.features) == 0
  311. }
  312. // OnlyContains determines whether only the specified feature bits are found.
  313. func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
  314. if len(bits) != len(fv.features) {
  315. return false
  316. }
  317. for _, bit := range bits {
  318. if !fv.IsSet(bit) {
  319. return false
  320. }
  321. }
  322. return true
  323. }
  324. // Equals determines whether two features vectors contain exactly the same
  325. // features.
  326. func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
  327. if len(fv.features) != len(other.features) {
  328. return false
  329. }
  330. for bit := range fv.features {
  331. if _, ok := other.features[bit]; !ok {
  332. return false
  333. }
  334. }
  335. return true
  336. }
  337. // Merges sets all feature bits in other on the receiver's feature vector.
  338. func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
  339. for bit := range other.features {
  340. err := fv.SafeSet(bit)
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. return nil
  346. }
  347. // ValidateUpdate checks whether a feature vector can safely be updated to the
  348. // new feature vector provided, checking that it does not alter any of the
  349. // "standard" features that are defined by LND. The new feature vector should
  350. // be inclusive of all features in the original vector that it still wants to
  351. // advertise, setting and unsetting updates as desired. Features in the vector
  352. // are also checked against a maximum inclusive value, as feature vectors in
  353. // different contexts have different maximum values.
  354. func (fv *RawFeatureVector) ValidateUpdate(other *RawFeatureVector,
  355. maximumValue FeatureBit) error {
  356. // Run through the new set of features and check that we're not adding
  357. // any feature bits that are defined but not set in LND.
  358. for feature := range other.features {
  359. if fv.IsSet(feature) {
  360. continue
  361. }
  362. if feature > maximumValue {
  363. return fmt.Errorf("can't set feature bit %d: %w %v",
  364. feature, ErrFeatureBitMaximum,
  365. maximumValue)
  366. }
  367. if name, known := Features[feature]; known {
  368. return fmt.Errorf("can't set feature "+
  369. "bit %d (%v): %w", feature, name,
  370. ErrFeatureStandard)
  371. }
  372. }
  373. // Check that the new feature vector for this set does not unset any
  374. // features that are standard in LND by comparing the features in our
  375. // current set to the omitted values in the new set.
  376. for feature := range fv.features {
  377. if other.IsSet(feature) {
  378. continue
  379. }
  380. if name, known := Features[feature]; known {
  381. return fmt.Errorf("can't unset feature "+
  382. "bit %d (%v): %w", feature, name,
  383. ErrFeatureStandard)
  384. }
  385. }
  386. return nil
  387. }
  388. // ValidatePairs checks each feature bit in a raw vector to ensure that the
  389. // opposing bit is not set, validating that the vector has either the optional
  390. // or required bit set, not both.
  391. func (fv *RawFeatureVector) ValidatePairs() error {
  392. for feature := range fv.features {
  393. if _, ok := fv.features[feature^1]; ok {
  394. return ErrFeaturePairExists
  395. }
  396. }
  397. return nil
  398. }
  399. // Clone makes a copy of a feature vector.
  400. func (fv *RawFeatureVector) Clone() *RawFeatureVector {
  401. newFeatures := NewRawFeatureVector()
  402. for bit := range fv.features {
  403. newFeatures.Set(bit)
  404. }
  405. return newFeatures
  406. }
  407. // IsSet returns whether a particular feature bit is enabled in the vector.
  408. func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
  409. _, ok := fv.features[feature]
  410. return ok
  411. }
  412. // Set marks a feature as enabled in the vector.
  413. func (fv *RawFeatureVector) Set(feature FeatureBit) {
  414. fv.features[feature] = struct{}{}
  415. }
  416. // SafeSet sets the chosen feature bit in the feature vector, but returns an
  417. // error if the opposing feature bit is already set. This ensures both that we
  418. // are creating properly structured feature vectors, and in some cases, that
  419. // peers are sending properly encoded ones, i.e. it can't be both optional and
  420. // required.
  421. func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
  422. if _, ok := fv.features[feature^1]; ok {
  423. return ErrFeaturePairExists
  424. }
  425. fv.Set(feature)
  426. return nil
  427. }
  428. // Unset marks a feature as disabled in the vector.
  429. func (fv *RawFeatureVector) Unset(feature FeatureBit) {
  430. delete(fv.features, feature)
  431. }
  432. // SerializeSize returns the number of bytes needed to represent feature vector
  433. // in byte format.
  434. func (fv *RawFeatureVector) SerializeSize() int {
  435. // We calculate byte-length via the largest bit index.
  436. return fv.serializeSize(8)
  437. }
  438. // SerializeSize32 returns the number of bytes needed to represent feature
  439. // vector in base32 format.
  440. func (fv *RawFeatureVector) SerializeSize32() int {
  441. // We calculate base32-length via the largest bit index.
  442. return fv.serializeSize(5)
  443. }
  444. // serializeSize returns the number of bytes required to encode the feature
  445. // vector using at most width bits per encoded byte.
  446. func (fv *RawFeatureVector) serializeSize(width int) int {
  447. // Find the largest feature bit index
  448. max := -1
  449. for feature := range fv.features {
  450. index := int(feature)
  451. if index > max {
  452. max = index
  453. }
  454. }
  455. if max == -1 {
  456. return 0
  457. }
  458. return max/width + 1
  459. }
  460. // Encode writes the feature vector in byte representation. Every feature
  461. // encoded as a bit, and the bit vector is serialized using the least number of
  462. // bytes. Since the bit vector length is variable, the first two bytes of the
  463. // serialization represent the length.
  464. func (fv *RawFeatureVector) Encode(w io.Writer) error {
  465. // Write length of feature vector.
  466. var l [2]byte
  467. length := fv.SerializeSize()
  468. binary.BigEndian.PutUint16(l[:], uint16(length))
  469. if _, err := w.Write(l[:]); err != nil {
  470. return err
  471. }
  472. return fv.encode(w, length, 8)
  473. }
  474. // EncodeBase256 writes the feature vector in base256 representation. Every
  475. // feature is encoded as a bit, and the bit vector is serialized using the least
  476. // number of bytes.
  477. func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
  478. length := fv.SerializeSize()
  479. return fv.encode(w, length, 8)
  480. }
  481. // EncodeBase32 writes the feature vector in base32 representation. Every feature
  482. // is encoded as a bit, and the bit vector is serialized using the least number of
  483. // bytes.
  484. func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
  485. length := fv.SerializeSize32()
  486. return fv.encode(w, length, 5)
  487. }
  488. // encode writes the feature vector
  489. func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
  490. // Generate the data and write it.
  491. data := make([]byte, length)
  492. for feature := range fv.features {
  493. byteIndex := int(feature) / width
  494. bitIndex := int(feature) % width
  495. data[length-byteIndex-1] |= 1 << uint(bitIndex)
  496. }
  497. _, err := w.Write(data)
  498. return err
  499. }
  500. // Decode reads the feature vector from its byte representation. Every feature
  501. // is encoded as a bit, and the bit vector is serialized using the least number
  502. // of bytes. Since the bit vector length is variable, the first two bytes of the
  503. // serialization represent the length.
  504. func (fv *RawFeatureVector) Decode(r io.Reader) error {
  505. // Read the length of the feature vector.
  506. var l [2]byte
  507. if _, err := io.ReadFull(r, l[:]); err != nil {
  508. return err
  509. }
  510. length := binary.BigEndian.Uint16(l[:])
  511. return fv.decode(r, int(length), 8)
  512. }
  513. // DecodeBase256 reads the feature vector from its base256 representation. Every
  514. // feature encoded as a bit, and the bit vector is serialized using the least
  515. // number of bytes.
  516. func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
  517. return fv.decode(r, length, 8)
  518. }
  519. // DecodeBase32 reads the feature vector from its base32 representation. Every
  520. // feature encoded as a bit, and the bit vector is serialized using the least
  521. // number of bytes.
  522. func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
  523. return fv.decode(r, length, 5)
  524. }
  525. // decode reads a feature vector from the next length bytes of the io.Reader,
  526. // assuming each byte has width feature bits encoded per byte.
  527. func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
  528. // Read the feature vector data.
  529. data := make([]byte, length)
  530. if _, err := io.ReadFull(r, data); err != nil {
  531. return err
  532. }
  533. // Set feature bits from parsed data.
  534. bitsNumber := len(data) * width
  535. for i := 0; i < bitsNumber; i++ {
  536. byteIndex := int(i / width)
  537. bitIndex := uint(i % width)
  538. if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
  539. fv.Set(FeatureBit(i))
  540. }
  541. }
  542. return nil
  543. }
  544. // sizeFunc returns the length required to encode the feature vector.
  545. func (fv *RawFeatureVector) sizeFunc() uint64 {
  546. return uint64(fv.SerializeSize())
  547. }
  548. // Record returns a TLV record that can be used to encode/decode raw feature
  549. // vectors. Note that the length of the feature vector is not included, because
  550. // it is covered by the TLV record's length field.
  551. func (fv *RawFeatureVector) Record(recordType tlv.Type) tlv.Record {
  552. return tlv.MakeDynamicRecord(
  553. recordType, fv, fv.sizeFunc, rawFeatureEncoder,
  554. rawFeatureDecoder,
  555. )
  556. }
  557. // rawFeatureEncoder is a custom TLV encoder for raw feature vectors.
  558. func rawFeatureEncoder(w io.Writer, val interface{}, _ *[8]byte) error {
  559. if f, ok := val.(*RawFeatureVector); ok {
  560. return f.encode(w, f.SerializeSize(), 8)
  561. }
  562. return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
  563. }
  564. // rawFeatureDecoder is a custom TLV decoder for raw feature vectors.
  565. func rawFeatureDecoder(r io.Reader, val interface{}, _ *[8]byte,
  566. l uint64) error {
  567. if f, ok := val.(*RawFeatureVector); ok {
  568. return f.decode(r, int(l), 8)
  569. }
  570. return tlv.NewTypeForEncodingErr(val, "*lnwire.RawFeatureVector")
  571. }
  572. // FeatureVector represents a set of enabled features. The set stores
  573. // information on enabled flags and metadata about the feature names. A feature
  574. // vector is serializable to a compact byte representation that is included in
  575. // Lightning network messages.
  576. type FeatureVector struct {
  577. *RawFeatureVector
  578. featureNames map[FeatureBit]string
  579. }
  580. // NewFeatureVector constructs a new FeatureVector from a raw feature vector
  581. // and mapping of feature definitions. If the feature vector argument is nil, a
  582. // new one will be constructed with no enabled features.
  583. func NewFeatureVector(featureVector *RawFeatureVector,
  584. featureNames map[FeatureBit]string) *FeatureVector {
  585. if featureVector == nil {
  586. featureVector = NewRawFeatureVector()
  587. }
  588. return &FeatureVector{
  589. RawFeatureVector: featureVector,
  590. featureNames: featureNames,
  591. }
  592. }
  593. // EmptyFeatureVector returns a feature vector with no bits set.
  594. func EmptyFeatureVector() *FeatureVector {
  595. return NewFeatureVector(nil, Features)
  596. }
  597. // Record implements the RecordProducer interface for FeatureVector. Note that
  598. // it uses a zero-value type is used to produce the record, as we expect this
  599. // type value to be overwritten when used in generic TLV record production.
  600. // This allows a single Record function to serve in the many different contexts
  601. // in which feature vectors are encoded. This record wraps the encoding/
  602. // decoding for our raw feature vectors so that we can directly parse fully
  603. // formed feature vector types.
  604. func (fv *FeatureVector) Record() tlv.Record {
  605. return tlv.MakeDynamicRecord(0, fv, fv.sizeFunc,
  606. func(w io.Writer, val interface{}, buf *[8]byte) error {
  607. if f, ok := val.(*FeatureVector); ok {
  608. return rawFeatureEncoder(
  609. w, f.RawFeatureVector, buf,
  610. )
  611. }
  612. return tlv.NewTypeForEncodingErr(
  613. val, "*lnwire.FeatureVector",
  614. )
  615. },
  616. func(r io.Reader, val interface{}, buf *[8]byte,
  617. l uint64) error {
  618. if f, ok := val.(*FeatureVector); ok {
  619. features := NewFeatureVector(nil, Features)
  620. err := rawFeatureDecoder(
  621. r, features.RawFeatureVector, buf, l,
  622. )
  623. if err != nil {
  624. return err
  625. }
  626. *f = *features
  627. return nil
  628. }
  629. return tlv.NewTypeForDecodingErr(
  630. val, "*lnwire.FeatureVector", l, l,
  631. )
  632. },
  633. )
  634. }
  635. // HasFeature returns whether a particular feature is included in the set. The
  636. // feature can be seen as set either if the bit is set directly OR the queried
  637. // bit has the same meaning as its corresponding even/odd bit, which is set
  638. // instead. The second case is because feature bits are generally assigned in
  639. // pairs where both the even and odd position represent the same feature.
  640. func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
  641. return fv.IsSet(feature) ||
  642. (fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
  643. }
  644. // RequiresFeature returns true if the referenced feature vector *requires*
  645. // that the given required bit be set. This method can be used with both
  646. // optional and required feature bits as a parameter.
  647. func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
  648. // If we weren't passed a required feature bit, then we'll flip the
  649. // lowest bit to query for the required version of the feature. This
  650. // lets callers pass in both the optional and required bits.
  651. if !feature.IsRequired() {
  652. feature ^= 1
  653. }
  654. return fv.IsSet(feature)
  655. }
  656. // UnknownRequiredFeatures returns a list of feature bits set in the vector
  657. // that are unknown and in an even bit position. Feature bits with an even
  658. // index must be known to a node receiving the feature vector in a message.
  659. func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
  660. var unknown []FeatureBit
  661. for feature := range fv.features {
  662. if feature%2 == 0 && !fv.IsKnown(feature) {
  663. unknown = append(unknown, feature)
  664. }
  665. }
  666. return unknown
  667. }
  668. // UnknownFeatures returns a boolean if a feature vector contains *any*
  669. // unknown features (even if they are odd).
  670. func (fv *FeatureVector) UnknownFeatures() bool {
  671. for feature := range fv.features {
  672. if !fv.IsKnown(feature) {
  673. return true
  674. }
  675. }
  676. return false
  677. }
  678. // Name returns a string identifier for the feature represented by this bit. If
  679. // the bit does not represent a known feature, this returns a string indicating
  680. // as such.
  681. func (fv *FeatureVector) Name(bit FeatureBit) string {
  682. name, known := fv.featureNames[bit]
  683. if !known {
  684. return "unknown"
  685. }
  686. return name
  687. }
  688. // IsKnown returns whether this feature bit represents a known feature.
  689. func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
  690. _, known := fv.featureNames[bit]
  691. return known
  692. }
  693. // isFeatureBitPair returns whether this feature bit and its corresponding
  694. // even/odd bit both represent the same feature. This may often be the case as
  695. // bits are generally assigned in pairs, first being assigned an odd bit
  696. // position then being promoted to an even bit position once the network is
  697. // ready.
  698. func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
  699. name1, known1 := fv.featureNames[bit]
  700. name2, known2 := fv.featureNames[bit^1]
  701. return known1 && known2 && name1 == name2
  702. }
  703. // Features returns the set of raw features contained in the feature vector.
  704. func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
  705. fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
  706. for b := range fv.RawFeatureVector.features {
  707. fs[b] = struct{}{}
  708. }
  709. return fs
  710. }
  711. // Clone copies a feature vector, carrying over its feature bits. The feature
  712. // names are not copied.
  713. func (fv *FeatureVector) Clone() *FeatureVector {
  714. features := fv.RawFeatureVector.Clone()
  715. return NewFeatureVector(features, fv.featureNames)
  716. }