-
Notifications
You must be signed in to change notification settings - Fork 1
/
Features.scala
392 lines (340 loc) · 11.8 KB
/
Features.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package scoin.ln
import scodec.bits.{BitVector, ByteVector}
import scala.jdk.CollectionConverters.CollectionHasAsScala
import scoin.ln.FeatureSupport.{Mandatory, Optional}
sealed trait FeatureSupport
object FeatureSupport {
case object Mandatory extends FeatureSupport {
override def toString: String = "mandatory"
}
case object Optional extends FeatureSupport {
override def toString: String = "optional"
}
}
/** Not a sealed trait, so it can be extended by plugins. */
trait Feature {
def rfcName: String
def mandatory: Int
def optional: Int = mandatory + 1
def supportBit(support: FeatureSupport): Int = support match {
case Mandatory => mandatory
case Optional => optional
}
override def toString = rfcName
}
/** Feature scope as defined in Bolt 9. */
/** Feature that should be advertised in init messages. */
trait InitFeature extends Feature
/** Feature that should be advertised in node announcements. */
trait NodeFeature extends Feature
/** Feature that should be advertised in invoices. */
trait InvoiceFeature extends Feature
/** Feature negotiated when opening a channel that will apply for all of the
* channel's lifetime. This doesn't include features that can be safely
* activated/deactivated without impacting the channel's operation such as
* option_dataloss_protect or option_shutdown_anysegwit.
*/
trait PermanentChannelFeature extends InitFeature // <- not in the spec
/** Permanent channel feature negotiated in the channel type. Those features
* take precedence over permanent channel features negotiated in init messages.
* For example, if the channel type is option_static_remotekey, then even if
* the option_anchor_outputs feature is supported by both peers, it won't apply
* to the channel.
*/
trait ChannelTypeFeature extends PermanentChannelFeature
case class UnknownFeature(bitIndex: Int)
case class Features[T <: Feature](
activated: Map[T, FeatureSupport],
unknown: Set[UnknownFeature] = Set.empty
) {
def isEmpty: Boolean = activated.isEmpty && unknown.isEmpty
def hasFeature(feature: T, support: Option[FeatureSupport] = None): Boolean =
support match {
case Some(s) => activated.get(feature).contains(s)
case None => activated.contains(feature)
}
def hasPluginFeature(feature: UnknownFeature): Boolean =
unknown.contains(feature)
/** NB: this method is not reflexive, see [[Features.areCompatible]] if you
* want symmetric validation.
*/
def areSupported(remoteFeatures: Features[T]): Boolean = {
// we allow unknown odd features (it's ok to be odd)
val unknownFeaturesOk = remoteFeatures.unknown.forall(_.bitIndex % 2 == 1)
// we verify that we activated every mandatory feature they require
val knownFeaturesOk = remoteFeatures.activated.forall {
case (_, Optional) => true
case (feature, Mandatory) => hasFeature(feature)
}
unknownFeaturesOk && knownFeaturesOk
}
def initFeatures(): Features[InitFeature] =
Features(activated.collect { case (f: InitFeature, s) => (f, s) }, unknown)
def nodeAnnouncementFeatures(): Features[NodeFeature] =
Features(activated.collect { case (f: NodeFeature, s) => (f, s) }, unknown)
def invoiceFeatures(): Features[InvoiceFeature] = Features(
activated.collect { case (f: InvoiceFeature, s) => (f, s) },
unknown
)
def unscoped(): Features[Feature] = Features[Feature](
activated.collect { case (f, s) => (f: Feature, s) },
unknown
)
def toByteVector: ByteVector = {
val activatedFeatureBytes = toByteVectorFromIndex(activated.map {
case (feature, support) => feature.supportBit(support)
}.toSet)
val unknownFeatureBytes = toByteVectorFromIndex(unknown.map(_.bitIndex))
val maxSize = activatedFeatureBytes.size.max(unknownFeatureBytes.size)
activatedFeatureBytes.padLeft(maxSize) | unknownFeatureBytes.padLeft(
maxSize
)
}
private def toByteVectorFromIndex(indexes: Set[Int]): ByteVector = {
if (indexes.isEmpty) return ByteVector.empty
// When converting from BitVector to ByteVector, scodec pads right instead of left, so we make sure we pad to bytes *before* setting feature bits.
var buf = BitVector.fill(indexes.max + 1)(high = false).bytes.bits
indexes.foreach { i => buf = buf.set(i) }
buf.reverse.bytes
}
override def toString: String = {
val a = activated
.map { case (feature, support) => feature.rfcName + ":" + support }
.mkString(",")
val u = unknown.map(_.bitIndex).mkString(",")
s"$a" + (if (unknown.nonEmpty) s" (unknown=$u)" else "")
}
}
object Features {
def empty[T <: Feature]: Features[T] =
Features(activated = Map.empty[T, FeatureSupport])
def apply[T <: Feature](features: (T, FeatureSupport)*): Features[T] =
Features(activated = Map.from(features))
def apply(bytes: ByteVector): Features[Feature] = apply(bytes.bits)
def apply(bits: BitVector): Features[Feature] = {
val all = bits.toIndexedSeq.reverse.zipWithIndex.collect {
case (true, idx) if knownFeatures.exists(_.optional == idx) =>
Right((knownFeatures.find(_.optional == idx).get, Optional))
case (true, idx) if knownFeatures.exists(_.mandatory == idx) =>
Right((knownFeatures.find(_.mandatory == idx).get, Mandatory))
case (true, idx) => Left(UnknownFeature(idx))
}
Features[Feature](
activated = all.collect { case Right((feature, support)) =>
feature -> support
}.toMap,
unknown = all.collect { case Left(inf) => inf }.toSet
)
}
case object DataLossProtect
extends Feature
with InitFeature
with NodeFeature {
val rfcName = "option_data_loss_protect"
val mandatory = 0
}
case object InitialRoutingSync extends Feature with InitFeature {
val rfcName = "initial_routing_sync"
// reserved but not used as per lightningnetwork/lightning-rfc/pull/178
val mandatory = 2
}
case object UpfrontShutdownScript
extends Feature
with InitFeature
with NodeFeature
with PermanentChannelFeature {
val rfcName = "option_upfront_shutdown_script"
val mandatory = 4
}
case object ChannelRangeQueries
extends Feature
with InitFeature
with NodeFeature {
val rfcName = "gossip_queries"
val mandatory = 6
}
case object VariableLengthOnion
extends Feature
with InitFeature
with NodeFeature
with InvoiceFeature {
val rfcName = "var_onion_optin"
val mandatory = 8
}
case object ChannelRangeQueriesExtended
extends Feature
with InitFeature
with NodeFeature {
val rfcName = "gossip_queries_ex"
val mandatory = 10
}
case object StaticRemoteKey
extends Feature
with InitFeature
with NodeFeature
with ChannelTypeFeature {
val rfcName = "option_static_remotekey"
val mandatory = 12
}
case object PaymentSecret
extends Feature
with InitFeature
with NodeFeature
with InvoiceFeature {
val rfcName = "payment_secret"
val mandatory = 14
}
case object BasicMultiPartPayment
extends Feature
with InitFeature
with NodeFeature
with InvoiceFeature {
val rfcName = "basic_mpp"
val mandatory = 16
}
case object Wumbo
extends Feature
with InitFeature
with NodeFeature
with PermanentChannelFeature {
val rfcName = "option_support_large_channel"
val mandatory = 18
}
case object AnchorOutputs
extends Feature
with InitFeature
with NodeFeature
with ChannelTypeFeature {
val rfcName = "option_anchor_outputs"
val mandatory = 20
}
case object AnchorOutputsZeroFeeHtlcTx
extends Feature
with InitFeature
with NodeFeature
with ChannelTypeFeature {
val rfcName = "option_anchors_zero_fee_htlc_tx"
val mandatory = 22
}
case object ShutdownAnySegwit
extends Feature
with InitFeature
with NodeFeature {
val rfcName = "option_shutdown_anysegwit"
val mandatory = 26
}
case object DualFunding
extends Feature
with InitFeature
with NodeFeature
with PermanentChannelFeature {
val rfcName = "option_dual_fund"
val mandatory = 28
}
case object OnionMessages extends Feature with InitFeature with NodeFeature {
val rfcName = "option_onion_messages"
val mandatory = 38
}
case object ChannelType extends Feature with InitFeature with NodeFeature {
val rfcName = "option_channel_type"
val mandatory = 44
}
case object ScidAlias
extends Feature
with InitFeature
with NodeFeature
with ChannelTypeFeature {
val rfcName = "option_scid_alias"
val mandatory = 46
}
case object PaymentMetadata extends Feature with InvoiceFeature {
val rfcName = "option_payment_metadata"
val mandatory = 48
}
case object ZeroConf
extends Feature
with InitFeature
with NodeFeature
with ChannelTypeFeature {
val rfcName = "option_zeroconf"
val mandatory = 50
}
case object KeySend extends Feature with NodeFeature {
val rfcName = "keysend"
val mandatory = 54
}
// TODO: @t-bast: update feature bits once spec-ed (currently reserved here: https://github.com/lightningnetwork/lightning-rfc/issues/605)
// We're not advertising these bits yet in our announcements, clients have to assume support.
// This is why we haven't added them yet to `areSupported`.
// The version of trampoline enabled by this feature bit does not match the latest spec PR: once the spec is accepted,
// we will introduce a new version of trampoline that will work in parallel to this legacy one, until we can safely
// deprecate it.
case object TrampolinePaymentPrototype
extends Feature
with InitFeature
with NodeFeature
with InvoiceFeature {
val rfcName = "trampoline_payment_prototype"
val mandatory = 148
}
val knownFeatures: Set[Feature] = Set(
DataLossProtect,
InitialRoutingSync,
UpfrontShutdownScript,
ChannelRangeQueries,
VariableLengthOnion,
ChannelRangeQueriesExtended,
PaymentSecret,
BasicMultiPartPayment,
Wumbo,
StaticRemoteKey,
AnchorOutputs,
AnchorOutputsZeroFeeHtlcTx,
ShutdownAnySegwit,
DualFunding,
OnionMessages,
ChannelType,
ScidAlias,
PaymentMetadata,
ZeroConf,
KeySend,
TrampolinePaymentPrototype
)
// Features may depend on other features, as specified in Bolt 9.
private val featuresDependency = Map(
ChannelRangeQueriesExtended -> (ChannelRangeQueries :: Nil),
PaymentSecret -> (VariableLengthOnion :: Nil),
BasicMultiPartPayment -> (PaymentSecret :: Nil),
AnchorOutputs -> (StaticRemoteKey :: Nil),
AnchorOutputsZeroFeeHtlcTx -> (StaticRemoteKey :: Nil),
TrampolinePaymentPrototype -> (PaymentSecret :: Nil),
KeySend -> (VariableLengthOnion :: Nil)
)
case class FeatureException(message: String)
extends IllegalArgumentException(message)
def validateFeatureGraph[T <: Feature](
features: Features[T]
): Option[FeatureException] = featuresDependency.collectFirst {
case (feature, dependencies)
if features.unscoped().hasFeature(feature) && dependencies
.exists(d => !features.unscoped().hasFeature(d)) =>
FeatureException(
s"$feature is set but is missing a dependency (${dependencies
.filter(d => !features.unscoped().hasFeature(d))
.mkString(" and ")})"
)
}
/** Returns true if both feature sets are compatible. */
def areCompatible[T <: Feature](
ours: Features[T],
theirs: Features[T]
): Boolean = ours.areSupported(theirs) && theirs.areSupported(ours)
/** returns true if both have at least optional support */
def canUseFeature[T <: Feature](
localFeatures: Features[T],
remoteFeatures: Features[T],
feature: T
): Boolean = {
localFeatures.hasFeature(feature) && remoteFeatures.hasFeature(feature)
}
}