github.com/decred/dcrlnd@v0.7.6/lnwire/features.go (about)

     1  package lnwire
     2  
     3  import (
     4  	"encoding/binary"
     5  	"errors"
     6  	"io"
     7  )
     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  )
    14  
    15  // FeatureBit represents a feature that can be enabled in either a local or
    16  // global feature vector at a specific bit position. Feature bits follow the
    17  // "it's OK to be odd" rule, where features at even bit positions must be known
    18  // to a node receiving them from a peer while odd bits do not. In accordance,
    19  // feature bits are usually assigned in pairs, first being assigned an odd bit
    20  // position which may later be changed to the preceding even position once
    21  // knowledge of the feature becomes required on the network.
    22  type FeatureBit uint16
    23  
    24  const (
    25  	// DataLossProtectRequired is a feature bit that indicates that a peer
    26  	// *requires* the other party know about the data-loss-protect optional
    27  	// feature. If the remote peer does not know of such a feature, then
    28  	// the sending peer SHOLUD disconnect them. The data-loss-protect
    29  	// feature allows a peer that's lost partial data to recover their
    30  	// settled funds of the latest commitment state.
    31  	DataLossProtectRequired FeatureBit = 0
    32  
    33  	// DataLossProtectOptional is an optional feature bit that indicates
    34  	// that the sending peer knows of this new feature and can activate it
    35  	// it. The data-loss-protect feature allows a peer that's lost partial
    36  	// data to recover their settled funds of the latest commitment state.
    37  	DataLossProtectOptional FeatureBit = 1
    38  
    39  	// InitialRoutingSync is a local feature bit meaning that the receiving
    40  	// node should send a complete dump of routing information when a new
    41  	// connection is established.
    42  	InitialRoutingSync FeatureBit = 3
    43  
    44  	// UpfrontShutdownScriptRequired is a feature bit which indicates that a
    45  	// peer *requires* that the remote peer accept an upfront shutdown script to
    46  	// which payout is enforced on cooperative closes.
    47  	UpfrontShutdownScriptRequired FeatureBit = 4
    48  
    49  	// UpfrontShutdownScriptOptional is an optional feature bit which indicates
    50  	// that the peer will accept an upfront shutdown script to which payout is
    51  	// enforced on cooperative closes.
    52  	UpfrontShutdownScriptOptional FeatureBit = 5
    53  
    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  
    60  	// GossipQueriesOptional is an optional feature bit that signals that
    61  	// the setting peer knows of the set of features that allows more
    62  	// efficient network view reconciliation.
    63  	GossipQueriesOptional FeatureBit = 7
    64  
    65  	// TLVOnionPayloadRequired is a feature bit that indicates a node is
    66  	// able to decode the new TLV information included in the onion packet.
    67  	TLVOnionPayloadRequired FeatureBit = 8
    68  
    69  	// TLVOnionPayloadOptional is an optional feature bit that indicates a
    70  	// node is able to decode the new TLV information included in the onion
    71  	// packet.
    72  	TLVOnionPayloadOptional FeatureBit = 9
    73  
    74  	// StaticRemoteKeyRequired is a required 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  	StaticRemoteKeyRequired FeatureBit = 12
    78  
    79  	// StaticRemoteKeyOptional is an optional feature bit that signals that
    80  	// within one's commitment transaction, the key used for the remote
    81  	// party's non-delay output should not be tweaked.
    82  	StaticRemoteKeyOptional FeatureBit = 13
    83  
    84  	// PaymentAddrRequired is a required feature bit that signals that a
    85  	// node requires payment addresses, which are used to mitigate probing
    86  	// attacks on the receiver of a payment.
    87  	PaymentAddrRequired FeatureBit = 14
    88  
    89  	// PaymentAddrOptional is an optional feature bit that signals that a
    90  	// node supports payment addresses, which are used to mitigate probing
    91  	// attacks on the receiver of a payment.
    92  	PaymentAddrOptional FeatureBit = 15
    93  
    94  	// MPPRequired is a required feature bit that signals that the receiver
    95  	// of a payment requires settlement of an invoice with more than one
    96  	// HTLC.
    97  	MPPRequired FeatureBit = 16
    98  
    99  	// MPPOptional is an optional feature bit that signals that the receiver
   100  	// of a payment supports settlement of an invoice with more than one
   101  	// HTLC.
   102  	MPPOptional FeatureBit = 17
   103  
   104  	// WumboChannelsRequired is a required feature bit that signals that a
   105  	// node is willing to accept channels larger than 2^24 satoshis.
   106  	WumboChannelsRequired FeatureBit = 18
   107  
   108  	// WumboChannelsOptional is an optional feature bit that signals that a
   109  	// node is willing to accept channels larger than 2^24 satoshis.
   110  	WumboChannelsOptional FeatureBit = 19
   111  
   112  	// AnchorsRequired is a required feature bit that signals that the node
   113  	// requires channels to be made using commitments having anchor
   114  	// outputs.
   115  	AnchorsRequired FeatureBit = 20
   116  
   117  	// AnchorsOptional is an optional feature bit that signals that the
   118  	// node supports channels to be made using commitments having anchor
   119  	// outputs.
   120  	AnchorsOptional FeatureBit = 21
   121  
   122  	// AnchorsZeroFeeHtlcTxRequired is a required feature bit that signals
   123  	// that the node requires channels having zero-fee second-level HTLC
   124  	// transactions, which also imply anchor commitments.
   125  	AnchorsZeroFeeHtlcTxRequired FeatureBit = 22
   126  
   127  	// AnchorsZeroFeeHtlcTxOptional is an optional feature bit that signals
   128  	// that the node supports channels having zero-fee second-level HTLC
   129  	// transactions, which also imply anchor commitments.
   130  	AnchorsZeroFeeHtlcTxOptional FeatureBit = 23
   131  
   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  
   137  	// AMPOptional is an optional feature bit that signals that the receiver
   138  	// of a payment supports accepts spontaneous payments, i.e.
   139  	// sender-generated preimages according to BOLT XX.
   140  	AMPOptional FeatureBit = 31
   141  
   142  	// ExplicitChannelTypeRequired is a required bit that denotes that a
   143  	// connection established with this node is to use explicit channel
   144  	// commitment types for negotiation instead of the existing implicit
   145  	// negotiation methods. With this bit, there is no longer a "default"
   146  	// implicit channel commitment type, allowing a connection to
   147  	// open/maintain types of several channels over its lifetime.
   148  	ExplicitChannelTypeRequired = 44
   149  
   150  	// ExplicitChannelTypeOptional is an optional bit that denotes that a
   151  	// connection established with this node is to use explicit channel
   152  	// commitment types for negotiation instead of the existing implicit
   153  	// negotiation methods. With this bit, there is no longer a "default"
   154  	// implicit channel commitment type, allowing a connection to
   155  	// TODO: Decide on actual feature bit value.
   156  	ExplicitChannelTypeOptional = 45
   157  
   158  	// ScriptEnforcedLeaseOptional is an optional feature bit that signals
   159  	// that the node requires channels having zero-fee second-level HTLC
   160  	// transactions, which also imply anchor commitments, along with an
   161  	// additional CLTV constraint of a channel lease's expiration height
   162  	// applied to all outputs that pay directly to the channel initiator.
   163  	//
   164  	// TODO: Decide on actual feature bit value.
   165  	ScriptEnforcedLeaseRequired FeatureBit = 2022
   166  
   167  	// ScriptEnforcedLeaseOptional is a required feature bit that signals
   168  	// that the node requires channels having zero-fee second-level HTLC
   169  	// transactions, which also imply anchor commitments, along with an
   170  	// additional CLTV constraint of a channel lease's expiration height
   171  	// applied to all outputs that pay directly to the channel initiator.
   172  	//
   173  	// TODO: Decide on actual feature bit value.
   174  	ScriptEnforcedLeaseOptional FeatureBit = 2023
   175  )
   176  
   177  // IsRequired returns true if the feature bit is even, and false otherwise.
   178  func (b FeatureBit) IsRequired() bool {
   179  	return b&0x01 == 0x00
   180  }
   181  
   182  // Features is a mapping of known feature bits to a descriptive name. All known
   183  // feature bits must be assigned a name in this mapping, and feature bit pairs
   184  // must be assigned together for correct behavior.
   185  var Features = map[FeatureBit]string{
   186  	DataLossProtectRequired:       "data-loss-protect",
   187  	DataLossProtectOptional:       "data-loss-protect",
   188  	InitialRoutingSync:            "initial-routing-sync",
   189  	UpfrontShutdownScriptRequired: "upfront-shutdown-script",
   190  	UpfrontShutdownScriptOptional: "upfront-shutdown-script",
   191  	GossipQueriesRequired:         "gossip-queries",
   192  	GossipQueriesOptional:         "gossip-queries",
   193  	TLVOnionPayloadRequired:       "tlv-onion",
   194  	TLVOnionPayloadOptional:       "tlv-onion",
   195  	StaticRemoteKeyOptional:       "static-remote-key",
   196  	StaticRemoteKeyRequired:       "static-remote-key",
   197  	PaymentAddrOptional:           "payment-addr",
   198  	PaymentAddrRequired:           "payment-addr",
   199  	MPPOptional:                   "multi-path-payments",
   200  	MPPRequired:                   "multi-path-payments",
   201  	AnchorsRequired:               "anchor-commitments",
   202  	AnchorsOptional:               "anchor-commitments",
   203  	AnchorsZeroFeeHtlcTxRequired:  "anchors-zero-fee-htlc-tx",
   204  	AnchorsZeroFeeHtlcTxOptional:  "anchors-zero-fee-htlc-tx",
   205  	WumboChannelsRequired:         "wumbo-channels",
   206  	WumboChannelsOptional:         "wumbo-channels",
   207  	AMPRequired:                   "amp",
   208  	AMPOptional:                   "amp",
   209  	ExplicitChannelTypeOptional:   "explicit-commitment-type",
   210  	ExplicitChannelTypeRequired:   "explicit-commitment-type",
   211  	ScriptEnforcedLeaseRequired:   "script-enforced-lease",
   212  	ScriptEnforcedLeaseOptional:   "script-enforced-lease",
   213  }
   214  
   215  // RawFeatureVector represents a set of feature bits as defined in BOLT-09.  A
   216  // RawFeatureVector itself just stores a set of bit flags but can be used to
   217  // construct a FeatureVector which binds meaning to each bit. Feature vectors
   218  // can be serialized and deserialized to/from a byte representation that is
   219  // transmitted in Lightning network messages.
   220  type RawFeatureVector struct {
   221  	features map[FeatureBit]struct{}
   222  }
   223  
   224  // NewRawFeatureVector creates a feature vector with all of the feature bits
   225  // given as arguments enabled.
   226  func NewRawFeatureVector(bits ...FeatureBit) *RawFeatureVector {
   227  	fv := &RawFeatureVector{features: make(map[FeatureBit]struct{})}
   228  	for _, bit := range bits {
   229  		fv.Set(bit)
   230  	}
   231  	return fv
   232  }
   233  
   234  // IsEmpty returns whether the feature vector contains any feature bits.
   235  func (fv RawFeatureVector) IsEmpty() bool {
   236  	return len(fv.features) == 0
   237  }
   238  
   239  // OnlyContains determines whether only the specified feature bits are found.
   240  func (fv RawFeatureVector) OnlyContains(bits ...FeatureBit) bool {
   241  	if len(bits) != len(fv.features) {
   242  		return false
   243  	}
   244  	for _, bit := range bits {
   245  		if !fv.IsSet(bit) {
   246  			return false
   247  		}
   248  	}
   249  	return true
   250  }
   251  
   252  // Equals determines whether two features vectors contain exactly the same
   253  // features.
   254  func (fv RawFeatureVector) Equals(other *RawFeatureVector) bool {
   255  	if len(fv.features) != len(other.features) {
   256  		return false
   257  	}
   258  	for bit := range fv.features {
   259  		if _, ok := other.features[bit]; !ok {
   260  			return false
   261  		}
   262  	}
   263  	return true
   264  }
   265  
   266  // Merges sets all feature bits in other on the receiver's feature vector.
   267  func (fv *RawFeatureVector) Merge(other *RawFeatureVector) error {
   268  	for bit := range other.features {
   269  		err := fv.SafeSet(bit)
   270  		if err != nil {
   271  			return err
   272  		}
   273  	}
   274  	return nil
   275  }
   276  
   277  // Clone makes a copy of a feature vector.
   278  func (fv *RawFeatureVector) Clone() *RawFeatureVector {
   279  	newFeatures := NewRawFeatureVector()
   280  	for bit := range fv.features {
   281  		newFeatures.Set(bit)
   282  	}
   283  	return newFeatures
   284  }
   285  
   286  // IsSet returns whether a particular feature bit is enabled in the vector.
   287  func (fv *RawFeatureVector) IsSet(feature FeatureBit) bool {
   288  	_, ok := fv.features[feature]
   289  	return ok
   290  }
   291  
   292  // Set marks a feature as enabled in the vector.
   293  func (fv *RawFeatureVector) Set(feature FeatureBit) {
   294  	fv.features[feature] = struct{}{}
   295  }
   296  
   297  // SafeSet sets the chosen feature bit in the feature vector, but returns an
   298  // error if the opposing feature bit is already set. This ensures both that we
   299  // are creating properly structured feature vectors, and in some cases, that
   300  // peers are sending properly encoded ones, i.e. it can't be both optional and
   301  // required.
   302  func (fv *RawFeatureVector) SafeSet(feature FeatureBit) error {
   303  	if _, ok := fv.features[feature^1]; ok {
   304  		return ErrFeaturePairExists
   305  	}
   306  
   307  	fv.Set(feature)
   308  	return nil
   309  }
   310  
   311  // Unset marks a feature as disabled in the vector.
   312  func (fv *RawFeatureVector) Unset(feature FeatureBit) {
   313  	delete(fv.features, feature)
   314  }
   315  
   316  // SerializeSize returns the number of bytes needed to represent feature vector
   317  // in byte format.
   318  func (fv *RawFeatureVector) SerializeSize() int {
   319  	// We calculate byte-length via the largest bit index.
   320  	return fv.serializeSize(8)
   321  }
   322  
   323  // SerializeSize32 returns the number of bytes needed to represent feature
   324  // vector in base32 format.
   325  func (fv *RawFeatureVector) SerializeSize32() int {
   326  	// We calculate base32-length via the largest bit index.
   327  	return fv.serializeSize(5)
   328  }
   329  
   330  // serializeSize returns the number of bytes required to encode the feature
   331  // vector using at most width bits per encoded byte.
   332  func (fv *RawFeatureVector) serializeSize(width int) int {
   333  	// Find the largest feature bit index
   334  	max := -1
   335  	for feature := range fv.features {
   336  		index := int(feature)
   337  		if index > max {
   338  			max = index
   339  		}
   340  	}
   341  	if max == -1 {
   342  		return 0
   343  	}
   344  
   345  	return max/width + 1
   346  }
   347  
   348  // Encode writes the feature vector in byte representation. Every feature
   349  // encoded as a bit, and the bit vector is serialized using the least number of
   350  // bytes. Since the bit vector length is variable, the first two bytes of the
   351  // serialization represent the length.
   352  func (fv *RawFeatureVector) Encode(w io.Writer) error {
   353  	// Write length of feature vector.
   354  	var l [2]byte
   355  	length := fv.SerializeSize()
   356  	binary.BigEndian.PutUint16(l[:], uint16(length))
   357  	if _, err := w.Write(l[:]); err != nil {
   358  		return err
   359  	}
   360  
   361  	return fv.encode(w, length, 8)
   362  }
   363  
   364  // EncodeBase256 writes the feature vector in base256 representation. Every
   365  // feature is encoded as a bit, and the bit vector is serialized using the least
   366  // number of bytes.
   367  func (fv *RawFeatureVector) EncodeBase256(w io.Writer) error {
   368  	length := fv.SerializeSize()
   369  	return fv.encode(w, length, 8)
   370  }
   371  
   372  // EncodeBase32 writes the feature vector in base32 representation. Every feature
   373  // is encoded as a bit, and the bit vector is serialized using the least number of
   374  // bytes.
   375  func (fv *RawFeatureVector) EncodeBase32(w io.Writer) error {
   376  	length := fv.SerializeSize32()
   377  	return fv.encode(w, length, 5)
   378  }
   379  
   380  // encode writes the feature vector
   381  func (fv *RawFeatureVector) encode(w io.Writer, length, width int) error {
   382  	// Generate the data and write it.
   383  	data := make([]byte, length)
   384  	for feature := range fv.features {
   385  		byteIndex := int(feature) / width
   386  		bitIndex := int(feature) % width
   387  		data[length-byteIndex-1] |= 1 << uint(bitIndex)
   388  	}
   389  
   390  	_, err := w.Write(data)
   391  	return err
   392  }
   393  
   394  // Decode reads the feature vector from its byte representation. Every feature
   395  // is encoded as a bit, and the bit vector is serialized using the least number
   396  // of bytes. Since the bit vector length is variable, the first two bytes of the
   397  // serialization represent the length.
   398  func (fv *RawFeatureVector) Decode(r io.Reader) error {
   399  	// Read the length of the feature vector.
   400  	var l [2]byte
   401  	if _, err := io.ReadFull(r, l[:]); err != nil {
   402  		return err
   403  	}
   404  	length := binary.BigEndian.Uint16(l[:])
   405  
   406  	return fv.decode(r, int(length), 8)
   407  }
   408  
   409  // DecodeBase256 reads the feature vector from its base256 representation. Every
   410  // feature encoded as a bit, and the bit vector is serialized using the least
   411  // number of bytes.
   412  func (fv *RawFeatureVector) DecodeBase256(r io.Reader, length int) error {
   413  	return fv.decode(r, length, 8)
   414  }
   415  
   416  // DecodeBase32 reads the feature vector from its base32 representation. Every
   417  // feature encoded as a bit, and the bit vector is serialized using the least
   418  // number of bytes.
   419  func (fv *RawFeatureVector) DecodeBase32(r io.Reader, length int) error {
   420  	return fv.decode(r, length, 5)
   421  }
   422  
   423  // decode reads a feature vector from the next length bytes of the io.Reader,
   424  // assuming each byte has width feature bits encoded per byte.
   425  func (fv *RawFeatureVector) decode(r io.Reader, length, width int) error {
   426  	// Read the feature vector data.
   427  	data := make([]byte, length)
   428  	if _, err := io.ReadFull(r, data); err != nil {
   429  		return err
   430  	}
   431  
   432  	// Set feature bits from parsed data.
   433  	bitsNumber := len(data) * width
   434  	for i := 0; i < bitsNumber; i++ {
   435  		byteIndex := i / width
   436  		bitIndex := uint(i % width)
   437  		if (data[length-byteIndex-1]>>bitIndex)&1 == 1 {
   438  			fv.Set(FeatureBit(i))
   439  		}
   440  	}
   441  
   442  	return nil
   443  }
   444  
   445  // FeatureVector represents a set of enabled features. The set stores
   446  // information on enabled flags and metadata about the feature names. A feature
   447  // vector is serializable to a compact byte representation that is included in
   448  // Lightning network messages.
   449  type FeatureVector struct {
   450  	*RawFeatureVector
   451  	featureNames map[FeatureBit]string
   452  }
   453  
   454  // NewFeatureVector constructs a new FeatureVector from a raw feature vector
   455  // and mapping of feature definitions. If the feature vector argument is nil, a
   456  // new one will be constructed with no enabled features.
   457  func NewFeatureVector(featureVector *RawFeatureVector,
   458  	featureNames map[FeatureBit]string) *FeatureVector {
   459  
   460  	if featureVector == nil {
   461  		featureVector = NewRawFeatureVector()
   462  	}
   463  	return &FeatureVector{
   464  		RawFeatureVector: featureVector,
   465  		featureNames:     featureNames,
   466  	}
   467  }
   468  
   469  // EmptyFeatureVector returns a feature vector with no bits set.
   470  func EmptyFeatureVector() *FeatureVector {
   471  	return NewFeatureVector(nil, Features)
   472  }
   473  
   474  // HasFeature returns whether a particular feature is included in the set. The
   475  // feature can be seen as set either if the bit is set directly OR the queried
   476  // bit has the same meaning as its corresponding even/odd bit, which is set
   477  // instead. The second case is because feature bits are generally assigned in
   478  // pairs where both the even and odd position represent the same feature.
   479  func (fv *FeatureVector) HasFeature(feature FeatureBit) bool {
   480  	return fv.IsSet(feature) ||
   481  		(fv.isFeatureBitPair(feature) && fv.IsSet(feature^1))
   482  }
   483  
   484  // RequiresFeature returns true if the referenced feature vector *requires*
   485  // that the given required bit be set. This method can be used with both
   486  // optional and required feature bits as a parameter.
   487  func (fv *FeatureVector) RequiresFeature(feature FeatureBit) bool {
   488  	// If we weren't passed a required feature bit, then we'll flip the
   489  	// lowest bit to query for the required version of the feature. This
   490  	// lets callers pass in both the optional and required bits.
   491  	if !feature.IsRequired() {
   492  		feature ^= 1
   493  	}
   494  
   495  	return fv.IsSet(feature)
   496  }
   497  
   498  // UnknownRequiredFeatures returns a list of feature bits set in the vector
   499  // that are unknown and in an even bit position. Feature bits with an even
   500  // index must be known to a node receiving the feature vector in a message.
   501  func (fv *FeatureVector) UnknownRequiredFeatures() []FeatureBit {
   502  	var unknown []FeatureBit
   503  	for feature := range fv.features {
   504  		if feature%2 == 0 && !fv.IsKnown(feature) {
   505  			unknown = append(unknown, feature)
   506  		}
   507  	}
   508  	return unknown
   509  }
   510  
   511  // Name returns a string identifier for the feature represented by this bit. If
   512  // the bit does not represent a known feature, this returns a string indicating
   513  // as such.
   514  func (fv *FeatureVector) Name(bit FeatureBit) string {
   515  	name, known := fv.featureNames[bit]
   516  	if !known {
   517  		return "unknown"
   518  	}
   519  	return name
   520  }
   521  
   522  // IsKnown returns whether this feature bit represents a known feature.
   523  func (fv *FeatureVector) IsKnown(bit FeatureBit) bool {
   524  	_, known := fv.featureNames[bit]
   525  	return known
   526  }
   527  
   528  // isFeatureBitPair returns whether this feature bit and its corresponding
   529  // even/odd bit both represent the same feature. This may often be the case as
   530  // bits are generally assigned in pairs, first being assigned an odd bit
   531  // position then being promoted to an even bit position once the network is
   532  // ready.
   533  func (fv *FeatureVector) isFeatureBitPair(bit FeatureBit) bool {
   534  	name1, known1 := fv.featureNames[bit]
   535  	name2, known2 := fv.featureNames[bit^1]
   536  	return known1 && known2 && name1 == name2
   537  }
   538  
   539  // Features returns the set of raw features contained in the feature vector.
   540  func (fv *FeatureVector) Features() map[FeatureBit]struct{} {
   541  	fs := make(map[FeatureBit]struct{}, len(fv.RawFeatureVector.features))
   542  	for b := range fv.RawFeatureVector.features {
   543  		fs[b] = struct{}{}
   544  	}
   545  	return fs
   546  }
   547  
   548  // Clone copies a feature vector, carrying over its feature bits. The feature
   549  // names are not copied.
   550  func (fv *FeatureVector) Clone() *FeatureVector {
   551  	features := fv.RawFeatureVector.Clone()
   552  	return NewFeatureVector(features, fv.featureNames)
   553  }