interceptable_switch.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. package htlcswitch
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "sync"
  6. "github.com/go-errors/errors"
  7. "github.com/lightningnetwork/lnd/chainntnfs"
  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. )
  13. var (
  14. // ErrFwdNotExists is an error returned when the caller tries to resolve
  15. // a forward that doesn't exist anymore.
  16. ErrFwdNotExists = errors.New("forward does not exist")
  17. // ErrUnsupportedFailureCode when processing of an unsupported failure
  18. // code is attempted.
  19. ErrUnsupportedFailureCode = errors.New("unsupported failure code")
  20. errBlockStreamStopped = errors.New("block epoch stream stopped")
  21. )
  22. // InterceptableSwitch is an implementation of ForwardingSwitch interface.
  23. // This implementation is used like a proxy that wraps the switch and
  24. // intercepts forward requests. A reference to the Switch is held in order
  25. // to communicate back the interception result where the options are:
  26. // Resume - forwards the original request to the switch as is.
  27. // Settle - routes UpdateFulfillHTLC to the originating link.
  28. // Fail - routes UpdateFailHTLC to the originating link.
  29. type InterceptableSwitch struct {
  30. // htlcSwitch is the underline switch
  31. htlcSwitch *Switch
  32. // intercepted is where we stream all intercepted packets coming from
  33. // the switch.
  34. intercepted chan *interceptedPackets
  35. // resolutionChan is where we stream all responses coming from the
  36. // interceptor client.
  37. resolutionChan chan *fwdResolution
  38. onchainIntercepted chan InterceptedForward
  39. // interceptorRegistration is a channel that we use to synchronize
  40. // client connect and disconnect.
  41. interceptorRegistration chan ForwardInterceptor
  42. // requireInterceptor indicates whether processing should block if no
  43. // interceptor is connected.
  44. requireInterceptor bool
  45. // interceptor is the handler for intercepted packets.
  46. interceptor ForwardInterceptor
  47. // heldHtlcSet keeps track of outstanding intercepted forwards.
  48. heldHtlcSet *heldHtlcSet
  49. // cltvRejectDelta defines the number of blocks before the expiry of the
  50. // htlc where we no longer intercept it and instead cancel it back.
  51. cltvRejectDelta uint32
  52. // cltvInterceptDelta defines the number of blocks before the expiry of
  53. // the htlc where we don't intercept anymore. This value must be greater
  54. // than CltvRejectDelta, because we don't want to offer htlcs to the
  55. // interceptor client for which there is no time left to resolve them
  56. // anymore.
  57. cltvInterceptDelta uint32
  58. // notifier is an instance of a chain notifier that we'll use to signal
  59. // the switch when a new block has arrived.
  60. notifier chainntnfs.ChainNotifier
  61. // blockEpochStream is an active block epoch event stream backed by an
  62. // active ChainNotifier instance. This will be used to retrieve the
  63. // latest height of the chain.
  64. blockEpochStream *chainntnfs.BlockEpochEvent
  65. // currentHeight is the currently best known height.
  66. currentHeight int32
  67. wg sync.WaitGroup
  68. quit chan struct{}
  69. }
  70. type interceptedPackets struct {
  71. packets []*htlcPacket
  72. linkQuit chan struct{}
  73. isReplay bool
  74. }
  75. // FwdAction defines the various resolution types.
  76. type FwdAction int
  77. const (
  78. // FwdActionResume forwards the intercepted packet to the switch.
  79. FwdActionResume FwdAction = iota
  80. // FwdActionSettle settles the intercepted packet with a preimage.
  81. FwdActionSettle
  82. // FwdActionFail fails the intercepted packet back to the sender.
  83. FwdActionFail
  84. )
  85. // FwdResolution defines the action to be taken on an intercepted packet.
  86. type FwdResolution struct {
  87. // Key is the incoming circuit key of the htlc.
  88. Key models.CircuitKey
  89. // Action is the action to take on the intercepted htlc.
  90. Action FwdAction
  91. // Preimage is the preimage that is to be used for settling if Action is
  92. // FwdActionSettle.
  93. Preimage lntypes.Preimage
  94. // FailureMessage is the encrypted failure message that is to be passed
  95. // back to the sender if action is FwdActionFail.
  96. FailureMessage []byte
  97. // FailureCode is the failure code that is to be passed back to the
  98. // sender if action is FwdActionFail.
  99. FailureCode lnwire.FailCode
  100. }
  101. type fwdResolution struct {
  102. resolution *FwdResolution
  103. errChan chan error
  104. }
  105. // InterceptableSwitchConfig contains the configuration of InterceptableSwitch.
  106. type InterceptableSwitchConfig struct {
  107. // Switch is a reference to the actual switch implementation that
  108. // packets get sent to on resume.
  109. Switch *Switch
  110. // Notifier is an instance of a chain notifier that we'll use to signal
  111. // the switch when a new block has arrived.
  112. Notifier chainntnfs.ChainNotifier
  113. // CltvRejectDelta defines the number of blocks before the expiry of the
  114. // htlc where we auto-fail an intercepted htlc to prevent channel
  115. // force-closure.
  116. CltvRejectDelta uint32
  117. // CltvInterceptDelta defines the number of blocks before the expiry of
  118. // the htlc where we don't intercept anymore. This value must be greater
  119. // than CltvRejectDelta, because we don't want to offer htlcs to the
  120. // interceptor client for which there is no time left to resolve them
  121. // anymore.
  122. CltvInterceptDelta uint32
  123. // RequireInterceptor indicates whether processing should block if no
  124. // interceptor is connected.
  125. RequireInterceptor bool
  126. }
  127. // NewInterceptableSwitch returns an instance of InterceptableSwitch.
  128. func NewInterceptableSwitch(cfg *InterceptableSwitchConfig) (
  129. *InterceptableSwitch, error) {
  130. if cfg.CltvInterceptDelta <= cfg.CltvRejectDelta {
  131. return nil, fmt.Errorf("cltv intercept delta %v not greater "+
  132. "than cltv reject delta %v",
  133. cfg.CltvInterceptDelta, cfg.CltvRejectDelta)
  134. }
  135. return &InterceptableSwitch{
  136. htlcSwitch: cfg.Switch,
  137. intercepted: make(chan *interceptedPackets),
  138. onchainIntercepted: make(chan InterceptedForward),
  139. interceptorRegistration: make(chan ForwardInterceptor),
  140. heldHtlcSet: newHeldHtlcSet(),
  141. resolutionChan: make(chan *fwdResolution),
  142. requireInterceptor: cfg.RequireInterceptor,
  143. cltvRejectDelta: cfg.CltvRejectDelta,
  144. cltvInterceptDelta: cfg.CltvInterceptDelta,
  145. notifier: cfg.Notifier,
  146. quit: make(chan struct{}),
  147. }, nil
  148. }
  149. // SetInterceptor sets the ForwardInterceptor to be used. A nil argument
  150. // unregisters the current interceptor.
  151. func (s *InterceptableSwitch) SetInterceptor(
  152. interceptor ForwardInterceptor) {
  153. // Synchronize setting the handler with the main loop to prevent race
  154. // conditions.
  155. select {
  156. case s.interceptorRegistration <- interceptor:
  157. case <-s.quit:
  158. }
  159. }
  160. func (s *InterceptableSwitch) Start() error {
  161. blockEpochStream, err := s.notifier.RegisterBlockEpochNtfn(nil)
  162. if err != nil {
  163. return err
  164. }
  165. s.blockEpochStream = blockEpochStream
  166. s.wg.Add(1)
  167. go func() {
  168. defer s.wg.Done()
  169. err := s.run()
  170. if err != nil {
  171. log.Errorf("InterceptableSwitch stopped: %v", err)
  172. }
  173. }()
  174. return nil
  175. }
  176. func (s *InterceptableSwitch) Stop() error {
  177. close(s.quit)
  178. s.wg.Wait()
  179. s.blockEpochStream.Cancel()
  180. return nil
  181. }
  182. func (s *InterceptableSwitch) run() error {
  183. // The block epoch stream will immediately stream the current height.
  184. // Read it out here.
  185. select {
  186. case currentBlock, ok := <-s.blockEpochStream.Epochs:
  187. if !ok {
  188. return errBlockStreamStopped
  189. }
  190. s.currentHeight = currentBlock.Height
  191. case <-s.quit:
  192. return nil
  193. }
  194. log.Debugf("InterceptableSwitch running: height=%v, "+
  195. "requireInterceptor=%v", s.currentHeight, s.requireInterceptor)
  196. for {
  197. select {
  198. // An interceptor registration or de-registration came in.
  199. case interceptor := <-s.interceptorRegistration:
  200. s.setInterceptor(interceptor)
  201. case packets := <-s.intercepted:
  202. var notIntercepted []*htlcPacket
  203. for _, p := range packets.packets {
  204. intercepted, err := s.interceptForward(
  205. p, packets.isReplay,
  206. )
  207. if err != nil {
  208. return err
  209. }
  210. if !intercepted {
  211. notIntercepted = append(
  212. notIntercepted, p,
  213. )
  214. }
  215. }
  216. err := s.htlcSwitch.ForwardPackets(
  217. packets.linkQuit, notIntercepted...,
  218. )
  219. if err != nil {
  220. log.Errorf("Cannot forward packets: %v", err)
  221. }
  222. case fwd := <-s.onchainIntercepted:
  223. // For on-chain interceptions, we don't know if it has
  224. // already been offered before. This information is in
  225. // the forwarding package which isn't easily accessible
  226. // from contractcourt. It is likely though that it was
  227. // already intercepted in the off-chain flow. And even
  228. // if not, it is safe to signal replay so that we won't
  229. // unexpectedly skip over this htlc.
  230. if _, err := s.forward(fwd, true); err != nil {
  231. return err
  232. }
  233. case res := <-s.resolutionChan:
  234. res.errChan <- s.resolve(res.resolution)
  235. case currentBlock, ok := <-s.blockEpochStream.Epochs:
  236. if !ok {
  237. return errBlockStreamStopped
  238. }
  239. s.currentHeight = currentBlock.Height
  240. // A new block is appended. Fail any held htlcs that
  241. // expire at this height to prevent channel force-close.
  242. s.failExpiredHtlcs()
  243. case <-s.quit:
  244. return nil
  245. }
  246. }
  247. }
  248. func (s *InterceptableSwitch) failExpiredHtlcs() {
  249. s.heldHtlcSet.popAutoFails(
  250. uint32(s.currentHeight),
  251. func(fwd InterceptedForward) {
  252. err := fwd.FailWithCode(
  253. lnwire.CodeTemporaryChannelFailure,
  254. )
  255. if err != nil {
  256. log.Errorf("Cannot fail packet: %v", err)
  257. }
  258. },
  259. )
  260. }
  261. func (s *InterceptableSwitch) sendForward(fwd InterceptedForward) {
  262. err := s.interceptor(fwd.Packet())
  263. if err != nil {
  264. // Only log the error. If we couldn't send the packet, we assume
  265. // that the interceptor will reconnect so that we can retry.
  266. log.Debugf("Interceptor cannot handle forward: %v", err)
  267. }
  268. }
  269. func (s *InterceptableSwitch) setInterceptor(interceptor ForwardInterceptor) {
  270. s.interceptor = interceptor
  271. // Replay all currently held htlcs. When an interceptor is not required,
  272. // there may be none because they've been cleared after the previous
  273. // disconnect.
  274. if interceptor != nil {
  275. log.Debugf("Interceptor connected")
  276. s.heldHtlcSet.forEach(s.sendForward)
  277. return
  278. }
  279. // The interceptor disconnects. If an interceptor is required, keep the
  280. // held htlcs.
  281. if s.requireInterceptor {
  282. log.Infof("Interceptor disconnected, retaining held packets")
  283. return
  284. }
  285. // Interceptor is not required. Release held forwards.
  286. log.Infof("Interceptor disconnected, resolving held packets")
  287. s.heldHtlcSet.popAll(func(fwd InterceptedForward) {
  288. err := fwd.Resume()
  289. if err != nil {
  290. log.Errorf("Failed to resume hold forward %v", err)
  291. }
  292. })
  293. }
  294. func (s *InterceptableSwitch) resolve(res *FwdResolution) error {
  295. intercepted, err := s.heldHtlcSet.pop(res.Key)
  296. if err != nil {
  297. return err
  298. }
  299. switch res.Action {
  300. case FwdActionResume:
  301. return intercepted.Resume()
  302. case FwdActionSettle:
  303. return intercepted.Settle(res.Preimage)
  304. case FwdActionFail:
  305. if len(res.FailureMessage) > 0 {
  306. return intercepted.Fail(res.FailureMessage)
  307. }
  308. return intercepted.FailWithCode(res.FailureCode)
  309. default:
  310. return fmt.Errorf("unrecognized action %v", res.Action)
  311. }
  312. }
  313. // Resolve resolves an intercepted packet.
  314. func (s *InterceptableSwitch) Resolve(res *FwdResolution) error {
  315. internalRes := &fwdResolution{
  316. resolution: res,
  317. errChan: make(chan error, 1),
  318. }
  319. select {
  320. case s.resolutionChan <- internalRes:
  321. case <-s.quit:
  322. return errors.New("switch shutting down")
  323. }
  324. select {
  325. case err := <-internalRes.errChan:
  326. return err
  327. case <-s.quit:
  328. return errors.New("switch shutting down")
  329. }
  330. }
  331. // ForwardPackets attempts to forward the batch of htlcs to a connected
  332. // interceptor. If the interceptor signals the resume action, the htlcs are
  333. // forwarded to the switch. The link's quit signal should be provided to allow
  334. // cancellation of forwarding during link shutdown.
  335. func (s *InterceptableSwitch) ForwardPackets(linkQuit chan struct{}, isReplay bool,
  336. packets ...*htlcPacket) error {
  337. // Synchronize with the main event loop. This should be light in the
  338. // case where there is no interceptor.
  339. select {
  340. case s.intercepted <- &interceptedPackets{
  341. packets: packets,
  342. linkQuit: linkQuit,
  343. isReplay: isReplay,
  344. }:
  345. case <-linkQuit:
  346. log.Debugf("Forward cancelled because link quit")
  347. case <-s.quit:
  348. return errors.New("interceptable switch quit")
  349. }
  350. return nil
  351. }
  352. // ForwardPacket forwards a single htlc to the external interceptor.
  353. func (s *InterceptableSwitch) ForwardPacket(
  354. fwd InterceptedForward) error {
  355. select {
  356. case s.onchainIntercepted <- fwd:
  357. case <-s.quit:
  358. return errors.New("interceptable switch quit")
  359. }
  360. return nil
  361. }
  362. // interceptForward forwards the packet to the external interceptor after
  363. // checking the interception criteria.
  364. func (s *InterceptableSwitch) interceptForward(packet *htlcPacket,
  365. isReplay bool) (bool, error) {
  366. switch htlc := packet.htlc.(type) {
  367. case *lnwire.UpdateAddHTLC:
  368. // We are not interested in intercepting initiated payments.
  369. if packet.incomingChanID == hop.Source {
  370. return false, nil
  371. }
  372. intercepted := &interceptedForward{
  373. htlc: htlc,
  374. packet: packet,
  375. htlcSwitch: s.htlcSwitch,
  376. autoFailHeight: int32(packet.incomingTimeout -
  377. s.cltvRejectDelta),
  378. }
  379. // Handle forwards that are too close to expiry.
  380. handled, err := s.handleExpired(intercepted)
  381. if err != nil {
  382. log.Errorf("Error handling intercepted htlc "+
  383. "that expires too soon: circuit=%v, "+
  384. "incoming_timeout=%v, err=%v",
  385. packet.inKey(), packet.incomingTimeout, err)
  386. // Return false so that the packet is offered as normal
  387. // to the switch. This isn't ideal because interception
  388. // may be configured as always-on and is skipped now.
  389. // Returning true isn't great either, because the htlc
  390. // will remain stuck and potentially force-close the
  391. // channel. But in the end, we should never get here, so
  392. // the actual return value doesn't matter that much.
  393. return false, nil
  394. }
  395. if handled {
  396. return true, nil
  397. }
  398. return s.forward(intercepted, isReplay)
  399. default:
  400. return false, nil
  401. }
  402. }
  403. // forward records the intercepted htlc and forwards it to the interceptor.
  404. func (s *InterceptableSwitch) forward(
  405. fwd InterceptedForward, isReplay bool) (bool, error) {
  406. inKey := fwd.Packet().IncomingCircuit
  407. // Ignore already held htlcs.
  408. if s.heldHtlcSet.exists(inKey) {
  409. return true, nil
  410. }
  411. // If there is no interceptor currently registered, configuration and packet
  412. // replay status determine how the packet is handled.
  413. if s.interceptor == nil {
  414. // Process normally if an interceptor is not required.
  415. if !s.requireInterceptor {
  416. return false, nil
  417. }
  418. // We are in interceptor-required mode. If this is a new packet, it is
  419. // still safe to fail back. The interceptor has never seen this packet
  420. // yet. This limits the backlog of htlcs when the interceptor is down.
  421. if !isReplay {
  422. err := fwd.FailWithCode(
  423. lnwire.CodeTemporaryChannelFailure,
  424. )
  425. if err != nil {
  426. log.Errorf("Cannot fail packet: %v", err)
  427. }
  428. return true, nil
  429. }
  430. // This packet is a replay. It is not safe to fail back, because the
  431. // interceptor may still signal otherwise upon reconnect. Keep the
  432. // packet in the queue until then.
  433. if err := s.heldHtlcSet.push(inKey, fwd); err != nil {
  434. return false, err
  435. }
  436. return true, nil
  437. }
  438. // There is an interceptor registered. We can forward the packet right now.
  439. // Hold it in the queue too to track what is outstanding.
  440. if err := s.heldHtlcSet.push(inKey, fwd); err != nil {
  441. return false, err
  442. }
  443. s.sendForward(fwd)
  444. return true, nil
  445. }
  446. // handleExpired checks that the htlc isn't too close to the channel
  447. // force-close broadcast height. If it is, it is cancelled back.
  448. func (s *InterceptableSwitch) handleExpired(fwd *interceptedForward) (
  449. bool, error) {
  450. height := uint32(s.currentHeight)
  451. if fwd.packet.incomingTimeout >= height+s.cltvInterceptDelta {
  452. return false, nil
  453. }
  454. log.Debugf("Interception rejected because htlc "+
  455. "expires too soon: circuit=%v, "+
  456. "height=%v, incoming_timeout=%v",
  457. fwd.packet.inKey(), height,
  458. fwd.packet.incomingTimeout)
  459. err := fwd.FailWithCode(
  460. lnwire.CodeExpiryTooSoon,
  461. )
  462. if err != nil {
  463. return false, err
  464. }
  465. return true, nil
  466. }
  467. // interceptedForward implements the InterceptedForward interface.
  468. // It is passed from the switch to external interceptors that are interested
  469. // in holding forwards and resolve them manually.
  470. type interceptedForward struct {
  471. htlc *lnwire.UpdateAddHTLC
  472. packet *htlcPacket
  473. htlcSwitch *Switch
  474. autoFailHeight int32
  475. }
  476. // Packet returns the intercepted htlc packet.
  477. func (f *interceptedForward) Packet() InterceptedPacket {
  478. return InterceptedPacket{
  479. IncomingCircuit: models.CircuitKey{
  480. ChanID: f.packet.incomingChanID,
  481. HtlcID: f.packet.incomingHTLCID,
  482. },
  483. OutgoingChanID: f.packet.outgoingChanID,
  484. Hash: f.htlc.PaymentHash,
  485. OutgoingExpiry: f.htlc.Expiry,
  486. OutgoingAmount: f.htlc.Amount,
  487. IncomingAmount: f.packet.incomingAmount,
  488. IncomingExpiry: f.packet.incomingTimeout,
  489. CustomRecords: f.packet.customRecords,
  490. OnionBlob: f.htlc.OnionBlob,
  491. AutoFailHeight: f.autoFailHeight,
  492. }
  493. }
  494. // Resume resumes the default behavior as if the packet was not intercepted.
  495. func (f *interceptedForward) Resume() error {
  496. // Forward to the switch. A link quit channel isn't needed, because we
  497. // are on a different thread now.
  498. return f.htlcSwitch.ForwardPackets(nil, f.packet)
  499. }
  500. // Fail notifies the intention to Fail an existing hold forward with an
  501. // encrypted failure reason.
  502. func (f *interceptedForward) Fail(reason []byte) error {
  503. obfuscatedReason := f.packet.obfuscator.IntermediateEncrypt(reason)
  504. return f.resolve(&lnwire.UpdateFailHTLC{
  505. Reason: obfuscatedReason,
  506. })
  507. }
  508. // FailWithCode notifies the intention to fail an existing hold forward with the
  509. // specified failure code.
  510. func (f *interceptedForward) FailWithCode(code lnwire.FailCode) error {
  511. shaOnionBlob := func() [32]byte {
  512. return sha256.Sum256(f.htlc.OnionBlob[:])
  513. }
  514. // Create a local failure.
  515. var failureMsg lnwire.FailureMessage
  516. switch code {
  517. case lnwire.CodeInvalidOnionVersion:
  518. failureMsg = &lnwire.FailInvalidOnionVersion{
  519. OnionSHA256: shaOnionBlob(),
  520. }
  521. case lnwire.CodeInvalidOnionHmac:
  522. failureMsg = &lnwire.FailInvalidOnionHmac{
  523. OnionSHA256: shaOnionBlob(),
  524. }
  525. case lnwire.CodeInvalidOnionKey:
  526. failureMsg = &lnwire.FailInvalidOnionKey{
  527. OnionSHA256: shaOnionBlob(),
  528. }
  529. case lnwire.CodeTemporaryChannelFailure:
  530. update := f.htlcSwitch.failAliasUpdate(
  531. f.packet.incomingChanID, true,
  532. )
  533. if update == nil {
  534. // Fallback to the original, non-alias behavior.
  535. var err error
  536. update, err = f.htlcSwitch.cfg.FetchLastChannelUpdate(
  537. f.packet.incomingChanID,
  538. )
  539. if err != nil {
  540. return err
  541. }
  542. }
  543. failureMsg = lnwire.NewTemporaryChannelFailure(update)
  544. case lnwire.CodeExpiryTooSoon:
  545. update, err := f.htlcSwitch.cfg.FetchLastChannelUpdate(
  546. f.packet.incomingChanID,
  547. )
  548. if err != nil {
  549. return err
  550. }
  551. failureMsg = lnwire.NewExpiryTooSoon(*update)
  552. default:
  553. return ErrUnsupportedFailureCode
  554. }
  555. // Encrypt the failure for the first hop. This node will be the origin
  556. // of the failure.
  557. reason, err := f.packet.obfuscator.EncryptFirstHop(failureMsg)
  558. if err != nil {
  559. return fmt.Errorf("failed to encrypt failure reason %w", err)
  560. }
  561. return f.resolve(&lnwire.UpdateFailHTLC{
  562. Reason: reason,
  563. })
  564. }
  565. // Settle forwards a settled packet to the switch.
  566. func (f *interceptedForward) Settle(preimage lntypes.Preimage) error {
  567. if !preimage.Matches(f.htlc.PaymentHash) {
  568. return errors.New("preimage does not match hash")
  569. }
  570. return f.resolve(&lnwire.UpdateFulfillHTLC{
  571. PaymentPreimage: preimage,
  572. })
  573. }
  574. // resolve is used for both Settle and Fail and forwards the message to the
  575. // switch.
  576. func (f *interceptedForward) resolve(message lnwire.Message) error {
  577. pkt := &htlcPacket{
  578. incomingChanID: f.packet.incomingChanID,
  579. incomingHTLCID: f.packet.incomingHTLCID,
  580. outgoingChanID: f.packet.outgoingChanID,
  581. outgoingHTLCID: f.packet.outgoingHTLCID,
  582. isResolution: true,
  583. circuit: f.packet.circuit,
  584. htlc: message,
  585. obfuscator: f.packet.obfuscator,
  586. sourceRef: f.packet.sourceRef,
  587. }
  588. return f.htlcSwitch.mailOrchestrator.Deliver(pkt.incomingChanID, pkt)
  589. }