htlcnotifier.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package htlcswitch
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "time"
  7. "github.com/lightningnetwork/lnd/channeldb"
  8. "github.com/lightningnetwork/lnd/channeldb/models"
  9. "github.com/lightningnetwork/lnd/htlcswitch/hop"
  10. "github.com/lightningnetwork/lnd/lntypes"
  11. "github.com/lightningnetwork/lnd/lnwire"
  12. "github.com/lightningnetwork/lnd/subscribe"
  13. )
  14. // HtlcNotifier notifies clients of htlc forwards, failures and settles for
  15. // htlcs that the switch handles. It takes subscriptions for its events and
  16. // notifies them when htlc events occur. These are served on a best-effort
  17. // basis; events are not persisted, delivery is not guaranteed (in the event
  18. // of a crash in the switch, forward events may be lost) and some events may
  19. // be replayed upon restart. Events consumed from this package should be
  20. // de-duplicated by the htlc's unique combination of incoming+outgoing circuit
  21. // and not relied upon for critical operations.
  22. //
  23. // The htlc notifier sends the following kinds of events:
  24. // Forwarding Event:
  25. // - Represents a htlc which is forwarded onward from our node.
  26. // - Present for htlc forwards through our node and local sends.
  27. //
  28. // Link Failure Event:
  29. // - Indicates that a htlc has failed on our incoming or outgoing link,
  30. // with an incoming boolean which indicates where the failure occurred.
  31. // - Incoming link failures are present for failed attempts to pay one of
  32. // our invoices (insufficient amount or mpp timeout, for example) and for
  33. // forwards that we cannot decode to forward onwards.
  34. // - Outgoing link failures are present for forwards or local payments that
  35. // do not meet our outgoing link's policy (insufficient fees, for example)
  36. // and when we fail to forward the payment on (insufficient outgoing
  37. // capacity, or an unknown outgoing link).
  38. //
  39. // Forwarding Failure Event:
  40. // - Forwarding failures indicate that a htlc we forwarded has failed at
  41. // another node down the route.
  42. // - Present for local sends and htlc forwards which fail after they left
  43. // our node.
  44. //
  45. // Settle event:
  46. // - Settle events are present when a htlc which we added is settled through
  47. // the release of a preimage.
  48. // - Present for local receives, and successful local sends or forwards.
  49. //
  50. // Each htlc is identified by its incoming and outgoing circuit key. Htlcs,
  51. // and their subsequent settles or fails, can be identified by the combination
  52. // of incoming and outgoing circuits. Note that receives to our node will
  53. // have a zero outgoing circuit key because the htlc terminates at our
  54. // node, and sends from our node will have a zero incoming circuit key because
  55. // the send originates at our node.
  56. type HtlcNotifier struct {
  57. started sync.Once
  58. stopped sync.Once
  59. // now returns the current time, it is set in the htlcnotifier to allow
  60. // for timestamp mocking in tests.
  61. now func() time.Time
  62. ntfnServer *subscribe.Server
  63. }
  64. // NewHtlcNotifier creates a new HtlcNotifier which gets htlc forwarded,
  65. // failed and settled events from links our node has established with peers
  66. // and sends notifications to subscribing clients.
  67. func NewHtlcNotifier(now func() time.Time) *HtlcNotifier {
  68. return &HtlcNotifier{
  69. now: now,
  70. ntfnServer: subscribe.NewServer(),
  71. }
  72. }
  73. // Start starts the HtlcNotifier and all goroutines it needs to consume
  74. // events and provide subscriptions to clients.
  75. func (h *HtlcNotifier) Start() error {
  76. var err error
  77. h.started.Do(func() {
  78. log.Info("HtlcNotifier starting")
  79. err = h.ntfnServer.Start()
  80. })
  81. return err
  82. }
  83. // Stop signals the notifier for a graceful shutdown.
  84. func (h *HtlcNotifier) Stop() error {
  85. var err error
  86. h.stopped.Do(func() {
  87. log.Info("HtlcNotifier shutting down...")
  88. defer log.Debug("HtlcNotifier shutdown complete")
  89. if err = h.ntfnServer.Stop(); err != nil {
  90. log.Warnf("error stopping htlc notifier: %v", err)
  91. }
  92. })
  93. return err
  94. }
  95. // SubscribeHtlcEvents returns a subscribe.Client that will receive updates
  96. // any time the server is made aware of a new event.
  97. func (h *HtlcNotifier) SubscribeHtlcEvents() (*subscribe.Client, error) {
  98. return h.ntfnServer.Subscribe()
  99. }
  100. // HtlcKey uniquely identifies the htlc.
  101. type HtlcKey struct {
  102. // IncomingCircuit is the channel an htlc id of the incoming htlc.
  103. IncomingCircuit models.CircuitKey
  104. // OutgoingCircuit is the channel and htlc id of the outgoing htlc.
  105. OutgoingCircuit models.CircuitKey
  106. }
  107. // String returns a string representation of a htlc key.
  108. func (k HtlcKey) String() string {
  109. switch {
  110. case k.IncomingCircuit.ChanID == hop.Source:
  111. return k.OutgoingCircuit.String()
  112. case k.OutgoingCircuit.ChanID == hop.Exit:
  113. return k.IncomingCircuit.String()
  114. default:
  115. return fmt.Sprintf("%v -> %v", k.IncomingCircuit,
  116. k.OutgoingCircuit)
  117. }
  118. }
  119. // HtlcInfo provides the details of a htlc that our node has processed. For
  120. // forwards, incoming and outgoing values are set, whereas sends and receives
  121. // will only have outgoing or incoming details set.
  122. type HtlcInfo struct {
  123. // IncomingTimelock is the time lock of the htlc on our incoming
  124. // channel.
  125. IncomingTimeLock uint32
  126. // OutgoingTimelock is the time lock the htlc on our outgoing channel.
  127. OutgoingTimeLock uint32
  128. // IncomingAmt is the amount of the htlc on our incoming channel.
  129. IncomingAmt lnwire.MilliSatoshi
  130. // OutgoingAmt is the amount of the htlc on our outgoing channel.
  131. OutgoingAmt lnwire.MilliSatoshi
  132. }
  133. // String returns a string representation of a htlc.
  134. func (h HtlcInfo) String() string {
  135. var details []string
  136. // If the incoming information is not zero, as is the case for a send,
  137. // we include the incoming amount and timelock.
  138. if h.IncomingAmt != 0 || h.IncomingTimeLock != 0 {
  139. str := fmt.Sprintf("incoming amount: %v, "+
  140. "incoming timelock: %v", h.IncomingAmt,
  141. h.IncomingTimeLock)
  142. details = append(details, str)
  143. }
  144. // If the outgoing information is not zero, as is the case for a
  145. // receive, we include the outgoing amount and timelock.
  146. if h.OutgoingAmt != 0 || h.OutgoingTimeLock != 0 {
  147. str := fmt.Sprintf("outgoing amount: %v, "+
  148. "outgoing timelock: %v", h.OutgoingAmt,
  149. h.OutgoingTimeLock)
  150. details = append(details, str)
  151. }
  152. return strings.Join(details, ", ")
  153. }
  154. // HtlcEventType represents the type of event that a htlc was part of.
  155. type HtlcEventType int
  156. const (
  157. // HtlcEventTypeSend represents a htlc that was part of a send from
  158. // our node.
  159. HtlcEventTypeSend HtlcEventType = iota
  160. // HtlcEventTypeReceive represents a htlc that was part of a receive
  161. // to our node.
  162. HtlcEventTypeReceive
  163. // HtlcEventTypeForward represents a htlc that was forwarded through
  164. // our node.
  165. HtlcEventTypeForward
  166. )
  167. // String returns a string representation of a htlc event type.
  168. func (h HtlcEventType) String() string {
  169. switch h {
  170. case HtlcEventTypeSend:
  171. return "send"
  172. case HtlcEventTypeReceive:
  173. return "receive"
  174. case HtlcEventTypeForward:
  175. return "forward"
  176. default:
  177. return "unknown"
  178. }
  179. }
  180. // ForwardingEvent represents a htlc that was forwarded onwards from our node.
  181. // Sends which originate from our node will report forward events with zero
  182. // incoming circuits in their htlc key.
  183. type ForwardingEvent struct {
  184. // HtlcKey uniquely identifies the htlc, and can be used to match the
  185. // forwarding event with subsequent settle/fail events.
  186. HtlcKey
  187. // HtlcInfo contains details about the htlc.
  188. HtlcInfo
  189. // HtlcEventType classifies the event as part of a local send or
  190. // receive, or as part of a forward.
  191. HtlcEventType
  192. // Timestamp is the time when this htlc was forwarded.
  193. Timestamp time.Time
  194. }
  195. // LinkFailEvent describes a htlc that failed on our incoming or outgoing
  196. // link. The incoming bool is true for failures on incoming links, and false
  197. // for failures on outgoing links. The failure reason is provided by a lnwire
  198. // failure message which is enriched with a failure detail in the cases where
  199. // the wire failure message does not contain full information about the
  200. // failure.
  201. type LinkFailEvent struct {
  202. // HtlcKey uniquely identifies the htlc.
  203. HtlcKey
  204. // HtlcInfo contains details about the htlc.
  205. HtlcInfo
  206. // HtlcEventType classifies the event as part of a local send or
  207. // receive, or as part of a forward.
  208. HtlcEventType
  209. // LinkError is the reason that we failed the htlc.
  210. LinkError *LinkError
  211. // Incoming is true if the htlc was failed on an incoming link.
  212. // If it failed on the outgoing link, it is false.
  213. Incoming bool
  214. // Timestamp is the time when the link failure occurred.
  215. Timestamp time.Time
  216. }
  217. // ForwardingFailEvent represents a htlc failure which occurred down the line
  218. // after we forwarded a htlc onwards. An error is not included in this event
  219. // because errors returned down the route are encrypted. HtlcInfo is not
  220. // reliably available for forwarding failures, so it is omitted. These events
  221. // should be matched with their corresponding forward event to obtain this
  222. // information.
  223. type ForwardingFailEvent struct {
  224. // HtlcKey uniquely identifies the htlc, and can be used to match the
  225. // htlc with its corresponding forwarding event.
  226. HtlcKey
  227. // HtlcEventType classifies the event as part of a local send or
  228. // receive, or as part of a forward.
  229. HtlcEventType
  230. // Timestamp is the time when the forwarding failure was received.
  231. Timestamp time.Time
  232. }
  233. // SettleEvent represents a htlc that was settled. HtlcInfo is not reliably
  234. // available for forwarding failures, so it is omitted. These events should
  235. // be matched with corresponding forward events or invoices (for receives)
  236. // to obtain additional information about the htlc.
  237. type SettleEvent struct {
  238. // HtlcKey uniquely identifies the htlc, and can be used to match
  239. // forwards with their corresponding forwarding event.
  240. HtlcKey
  241. // Preimage that was released for settling the htlc.
  242. Preimage lntypes.Preimage
  243. // HtlcEventType classifies the event as part of a local send or
  244. // receive, or as part of a forward.
  245. HtlcEventType
  246. // Timestamp is the time when this htlc was settled.
  247. Timestamp time.Time
  248. }
  249. type FinalHtlcEvent struct {
  250. CircuitKey
  251. Settled bool
  252. // Offchain is indicating whether the htlc was resolved off-chain.
  253. Offchain bool
  254. // Timestamp is the time when this htlc was settled.
  255. Timestamp time.Time
  256. }
  257. // NotifyForwardingEvent notifies the HtlcNotifier than a htlc has been
  258. // forwarded.
  259. //
  260. // Note this is part of the htlcNotifier interface.
  261. func (h *HtlcNotifier) NotifyForwardingEvent(key HtlcKey, info HtlcInfo,
  262. eventType HtlcEventType) {
  263. event := &ForwardingEvent{
  264. HtlcKey: key,
  265. HtlcInfo: info,
  266. HtlcEventType: eventType,
  267. Timestamp: h.now(),
  268. }
  269. log.Tracef("Notifying forward event: %v over %v, %v", eventType, key,
  270. info)
  271. if err := h.ntfnServer.SendUpdate(event); err != nil {
  272. log.Warnf("Unable to send forwarding event: %v", err)
  273. }
  274. }
  275. // NotifyLinkFailEvent notifies that a htlc has failed on our incoming
  276. // or outgoing link.
  277. //
  278. // Note this is part of the htlcNotifier interface.
  279. func (h *HtlcNotifier) NotifyLinkFailEvent(key HtlcKey, info HtlcInfo,
  280. eventType HtlcEventType, linkErr *LinkError, incoming bool) {
  281. event := &LinkFailEvent{
  282. HtlcKey: key,
  283. HtlcInfo: info,
  284. HtlcEventType: eventType,
  285. LinkError: linkErr,
  286. Incoming: incoming,
  287. Timestamp: h.now(),
  288. }
  289. log.Tracef("Notifying link failure event: %v over %v, %v", eventType,
  290. key, info)
  291. if err := h.ntfnServer.SendUpdate(event); err != nil {
  292. log.Warnf("Unable to send link fail event: %v", err)
  293. }
  294. }
  295. // NotifyForwardingFailEvent notifies the HtlcNotifier that a htlc we
  296. // forwarded has failed down the line.
  297. //
  298. // Note this is part of the htlcNotifier interface.
  299. func (h *HtlcNotifier) NotifyForwardingFailEvent(key HtlcKey,
  300. eventType HtlcEventType) {
  301. event := &ForwardingFailEvent{
  302. HtlcKey: key,
  303. HtlcEventType: eventType,
  304. Timestamp: h.now(),
  305. }
  306. log.Tracef("Notifying forwarding failure event: %v over %v", eventType,
  307. key)
  308. if err := h.ntfnServer.SendUpdate(event); err != nil {
  309. log.Warnf("Unable to send forwarding fail event: %v", err)
  310. }
  311. }
  312. // NotifySettleEvent notifies the HtlcNotifier that a htlc that we committed
  313. // to as part of a forward or a receive to our node has been settled.
  314. //
  315. // Note this is part of the htlcNotifier interface.
  316. func (h *HtlcNotifier) NotifySettleEvent(key HtlcKey,
  317. preimage lntypes.Preimage, eventType HtlcEventType) {
  318. event := &SettleEvent{
  319. HtlcKey: key,
  320. Preimage: preimage,
  321. HtlcEventType: eventType,
  322. Timestamp: h.now(),
  323. }
  324. log.Tracef("Notifying settle event: %v over %v", eventType, key)
  325. if err := h.ntfnServer.SendUpdate(event); err != nil {
  326. log.Warnf("Unable to send settle event: %v", err)
  327. }
  328. }
  329. // NotifyFinalHtlcEvent notifies the HtlcNotifier that the final outcome for an
  330. // htlc has been determined.
  331. //
  332. // Note this is part of the htlcNotifier interface.
  333. func (h *HtlcNotifier) NotifyFinalHtlcEvent(key models.CircuitKey,
  334. info channeldb.FinalHtlcInfo) {
  335. event := &FinalHtlcEvent{
  336. CircuitKey: key,
  337. Settled: info.Settled,
  338. Offchain: info.Offchain,
  339. Timestamp: h.now(),
  340. }
  341. log.Tracef("Notifying final settle event: %v", key)
  342. if err := h.ntfnServer.SendUpdate(event); err != nil {
  343. log.Warnf("Unable to send settle event: %v", err)
  344. }
  345. }
  346. // newHtlc key returns a htlc key for the packet provided. If the packet
  347. // has a zero incoming channel ID, the packet is for one of our own sends,
  348. // which has the payment id stashed in the incoming htlc id. If this is the
  349. // case, we replace the incoming htlc id with zero so that the notifier
  350. // consistently reports zero circuit keys for events that terminate or
  351. // originate at our node.
  352. func newHtlcKey(pkt *htlcPacket) HtlcKey {
  353. htlcKey := HtlcKey{
  354. IncomingCircuit: models.CircuitKey{
  355. ChanID: pkt.incomingChanID,
  356. HtlcID: pkt.incomingHTLCID,
  357. },
  358. OutgoingCircuit: CircuitKey{
  359. ChanID: pkt.outgoingChanID,
  360. HtlcID: pkt.outgoingHTLCID,
  361. },
  362. }
  363. // If the packet has a zero incoming channel ID, it is a send that was
  364. // initiated at our node. If this is the case, our internal pid is in
  365. // the incoming htlc ID, so we overwrite it with 0 for notification
  366. // purposes.
  367. if pkt.incomingChanID == hop.Source {
  368. htlcKey.IncomingCircuit.HtlcID = 0
  369. }
  370. return htlcKey
  371. }
  372. // newHtlcInfo returns HtlcInfo for the packet provided.
  373. func newHtlcInfo(pkt *htlcPacket) HtlcInfo {
  374. return HtlcInfo{
  375. IncomingTimeLock: pkt.incomingTimeout,
  376. OutgoingTimeLock: pkt.outgoingTimeout,
  377. IncomingAmt: pkt.incomingAmount,
  378. OutgoingAmt: pkt.amount,
  379. }
  380. }
  381. // getEventType returns the htlc type based on the fields set in the htlc
  382. // packet. Sends that originate at our node have the source (zero) incoming
  383. // channel ID. Receives to our node have the exit (zero) outgoing channel ID
  384. // and forwards have both fields set.
  385. func getEventType(pkt *htlcPacket) HtlcEventType {
  386. switch {
  387. case pkt.incomingChanID == hop.Source:
  388. return HtlcEventTypeSend
  389. case pkt.outgoingChanID == hop.Exit:
  390. return HtlcEventTypeReceive
  391. default:
  392. return HtlcEventTypeForward
  393. }
  394. }