switch.go 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044
  1. package htlcswitch
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  11. "github.com/btcsuite/btcd/btcutil"
  12. "github.com/btcsuite/btcd/wire"
  13. "github.com/davecgh/go-spew/spew"
  14. "github.com/lightningnetwork/lnd/chainntnfs"
  15. "github.com/lightningnetwork/lnd/channeldb"
  16. "github.com/lightningnetwork/lnd/channeldb/models"
  17. "github.com/lightningnetwork/lnd/clock"
  18. "github.com/lightningnetwork/lnd/contractcourt"
  19. "github.com/lightningnetwork/lnd/htlcswitch/hop"
  20. "github.com/lightningnetwork/lnd/kvdb"
  21. "github.com/lightningnetwork/lnd/lntypes"
  22. "github.com/lightningnetwork/lnd/lnwallet"
  23. "github.com/lightningnetwork/lnd/lnwallet/chainfee"
  24. "github.com/lightningnetwork/lnd/lnwire"
  25. "github.com/lightningnetwork/lnd/ticker"
  26. )
  27. const (
  28. // DefaultFwdEventInterval is the duration between attempts to flush
  29. // pending forwarding events to disk.
  30. DefaultFwdEventInterval = 15 * time.Second
  31. // DefaultLogInterval is the duration between attempts to log statistics
  32. // about forwarding events.
  33. DefaultLogInterval = 10 * time.Second
  34. // DefaultAckInterval is the duration between attempts to ack any settle
  35. // fails in a forwarding package.
  36. DefaultAckInterval = 15 * time.Second
  37. // DefaultMailboxDeliveryTimeout is the duration after which Adds will
  38. // be cancelled if they could not get added to an outgoing commitment.
  39. DefaultMailboxDeliveryTimeout = time.Minute
  40. )
  41. var (
  42. // ErrChannelLinkNotFound is used when channel link hasn't been found.
  43. ErrChannelLinkNotFound = errors.New("channel link not found")
  44. // ErrDuplicateAdd signals that the ADD htlc was already forwarded
  45. // through the switch and is locked into another commitment txn.
  46. ErrDuplicateAdd = errors.New("duplicate add HTLC detected")
  47. // ErrUnknownErrorDecryptor signals that we were unable to locate the
  48. // error decryptor for this payment. This is likely due to restarting
  49. // the daemon.
  50. ErrUnknownErrorDecryptor = errors.New("unknown error decryptor")
  51. // ErrSwitchExiting signaled when the switch has received a shutdown
  52. // request.
  53. ErrSwitchExiting = errors.New("htlcswitch shutting down")
  54. // ErrNoLinksFound is an error returned when we attempt to retrieve the
  55. // active links in the switch for a specific destination.
  56. ErrNoLinksFound = errors.New("no channel links found")
  57. // ErrUnreadableFailureMessage is returned when the failure message
  58. // cannot be decrypted.
  59. ErrUnreadableFailureMessage = errors.New("unreadable failure message")
  60. // ErrLocalAddFailed signals that the ADD htlc for a local payment
  61. // failed to be processed.
  62. ErrLocalAddFailed = errors.New("local add HTLC failed")
  63. // errDustThresholdExceeded is only surfaced to callers of SendHTLC and
  64. // signals that sending the HTLC would exceed the outgoing link's dust
  65. // threshold.
  66. errDustThresholdExceeded = errors.New("dust threshold exceeded")
  67. // DefaultDustThreshold is the default threshold after which we'll fail
  68. // payments if they are dust. This is currently set to 500m msats.
  69. DefaultDustThreshold = lnwire.MilliSatoshi(500_000_000)
  70. )
  71. // plexPacket encapsulates switch packet and adds error channel to receive
  72. // error from request handler.
  73. type plexPacket struct {
  74. pkt *htlcPacket
  75. err chan error
  76. }
  77. // ChanClose represents a request which close a particular channel specified by
  78. // its id.
  79. type ChanClose struct {
  80. // CloseType is a variable which signals the type of channel closure the
  81. // peer should execute.
  82. CloseType contractcourt.ChannelCloseType
  83. // ChanPoint represent the id of the channel which should be closed.
  84. ChanPoint *wire.OutPoint
  85. // TargetFeePerKw is the ideal fee that was specified by the caller.
  86. // This value is only utilized if the closure type is CloseRegular.
  87. // This will be the starting offered fee when the fee negotiation
  88. // process for the cooperative closure transaction kicks off.
  89. TargetFeePerKw chainfee.SatPerKWeight
  90. // MaxFee is the highest fee the caller is willing to pay.
  91. //
  92. // NOTE: This field is only respected if the caller is the initiator of
  93. // the channel.
  94. MaxFee chainfee.SatPerKWeight
  95. // DeliveryScript is an optional delivery script to pay funds out to.
  96. DeliveryScript lnwire.DeliveryAddress
  97. // Updates is used by request creator to receive the notifications about
  98. // execution of the close channel request.
  99. Updates chan interface{}
  100. // Err is used by request creator to receive request execution error.
  101. Err chan error
  102. }
  103. // Config defines the configuration for the service. ALL elements within the
  104. // configuration MUST be non-nil for the service to carry out its duties.
  105. type Config struct {
  106. // FwdingLog is an interface that will be used by the switch to log
  107. // forwarding events. A forwarding event happens each time a payment
  108. // circuit is successfully completed. So when we forward an HTLC, and a
  109. // settle is eventually received.
  110. FwdingLog ForwardingLog
  111. // LocalChannelClose kicks-off the workflow to execute a cooperative or
  112. // forced unilateral closure of the channel initiated by a local
  113. // subsystem.
  114. LocalChannelClose func(pubKey []byte, request *ChanClose)
  115. // DB is the database backend that will be used to back the switch's
  116. // persistent circuit map.
  117. DB kvdb.Backend
  118. // FetchAllOpenChannels is a function that fetches all currently open
  119. // channels from the channel database.
  120. FetchAllOpenChannels func() ([]*channeldb.OpenChannel, error)
  121. // FetchAllChannels is a function that fetches all pending open, open,
  122. // and waiting close channels from the database.
  123. FetchAllChannels func() ([]*channeldb.OpenChannel, error)
  124. // FetchClosedChannels is a function that fetches all closed channels
  125. // from the channel database.
  126. FetchClosedChannels func(
  127. pendingOnly bool) ([]*channeldb.ChannelCloseSummary, error)
  128. // SwitchPackager provides access to the forwarding packages of all
  129. // active channels. This gives the switch the ability to read arbitrary
  130. // forwarding packages, and ack settles and fails contained within them.
  131. SwitchPackager channeldb.FwdOperator
  132. // ExtractErrorEncrypter is an interface allowing switch to reextract
  133. // error encrypters stored in the circuit map on restarts, since they
  134. // are not stored directly within the database.
  135. ExtractErrorEncrypter hop.ErrorEncrypterExtracter
  136. // FetchLastChannelUpdate retrieves the latest routing policy for a
  137. // target channel. This channel will typically be the outgoing channel
  138. // specified when we receive an incoming HTLC. This will be used to
  139. // provide payment senders our latest policy when sending encrypted
  140. // error messages.
  141. FetchLastChannelUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error)
  142. // Notifier is an instance of a chain notifier that we'll use to signal
  143. // the switch when a new block has arrived.
  144. Notifier chainntnfs.ChainNotifier
  145. // HtlcNotifier is an instance of a htlcNotifier which we will pipe htlc
  146. // events through.
  147. HtlcNotifier htlcNotifier
  148. // FwdEventTicker is a signal that instructs the htlcswitch to flush any
  149. // pending forwarding events.
  150. FwdEventTicker ticker.Ticker
  151. // LogEventTicker is a signal instructing the htlcswitch to log
  152. // aggregate stats about it's forwarding during the last interval.
  153. LogEventTicker ticker.Ticker
  154. // AckEventTicker is a signal instructing the htlcswitch to ack any settle
  155. // fails in forwarding packages.
  156. AckEventTicker ticker.Ticker
  157. // AllowCircularRoute is true if the user has configured their node to
  158. // allow forwards that arrive and depart our node over the same channel.
  159. AllowCircularRoute bool
  160. // RejectHTLC is a flag that instructs the htlcswitch to reject any
  161. // HTLCs that are not from the source hop.
  162. RejectHTLC bool
  163. // Clock is a time source for the switch.
  164. Clock clock.Clock
  165. // MailboxDeliveryTimeout is the interval after which Adds will be
  166. // cancelled if they have not been yet been delivered to a link. The
  167. // computed deadline will expiry this long after the Adds are added to
  168. // a mailbox via AddPacket.
  169. MailboxDeliveryTimeout time.Duration
  170. // DustThreshold is the threshold in milli-satoshis after which we'll
  171. // fail incoming or outgoing dust payments for a particular channel.
  172. DustThreshold lnwire.MilliSatoshi
  173. // SignAliasUpdate is used when sending FailureMessages backwards for
  174. // option_scid_alias channels. This avoids a potential privacy leak by
  175. // replacing the public, confirmed SCID with the alias in the
  176. // ChannelUpdate.
  177. SignAliasUpdate func(u *lnwire.ChannelUpdate) (*ecdsa.Signature,
  178. error)
  179. // IsAlias returns whether or not a given SCID is an alias.
  180. IsAlias func(scid lnwire.ShortChannelID) bool
  181. }
  182. // Switch is the central messaging bus for all incoming/outgoing HTLCs.
  183. // Connected peers with active channels are treated as named interfaces which
  184. // refer to active channels as links. A link is the switch's message
  185. // communication point with the goroutine that manages an active channel. New
  186. // links are registered each time a channel is created, and unregistered once
  187. // the channel is closed. The switch manages the hand-off process for multi-hop
  188. // HTLCs, forwarding HTLCs initiated from within the daemon, and finally
  189. // notifies users local-systems concerning their outstanding payment requests.
  190. type Switch struct {
  191. started int32 // To be used atomically.
  192. shutdown int32 // To be used atomically.
  193. // bestHeight is the best known height of the main chain. The links will
  194. // be used this information to govern decisions based on HTLC timeouts.
  195. // This will be retrieved by the registered links atomically.
  196. bestHeight uint32
  197. wg sync.WaitGroup
  198. quit chan struct{}
  199. // cfg is a copy of the configuration struct that the htlc switch
  200. // service was initialized with.
  201. cfg *Config
  202. // networkResults stores the results of payments initiated by the user.
  203. // The store is used to later look up the payments and notify the
  204. // user of the result when they are complete. Each payment attempt
  205. // should be given a unique integer ID when it is created, otherwise
  206. // results might be overwritten.
  207. networkResults *networkResultStore
  208. // circuits is storage for payment circuits which are used to
  209. // forward the settle/fail htlc updates back to the add htlc initiator.
  210. circuits CircuitMap
  211. // mailOrchestrator manages the lifecycle of mailboxes used throughout
  212. // the switch, and facilitates delayed delivery of packets to links that
  213. // later come online.
  214. mailOrchestrator *mailOrchestrator
  215. // indexMtx is a read/write mutex that protects the set of indexes
  216. // below.
  217. indexMtx sync.RWMutex
  218. // pendingLinkIndex holds links that have not had their final, live
  219. // short_chan_id assigned.
  220. pendingLinkIndex map[lnwire.ChannelID]ChannelLink
  221. // links is a map of channel id and channel link which manages
  222. // this channel.
  223. linkIndex map[lnwire.ChannelID]ChannelLink
  224. // forwardingIndex is an index which is consulted by the switch when it
  225. // needs to locate the next hop to forward an incoming/outgoing HTLC
  226. // update to/from.
  227. //
  228. // TODO(roasbeef): eventually add a NetworkHop mapping before the
  229. // ChannelLink
  230. forwardingIndex map[lnwire.ShortChannelID]ChannelLink
  231. // interfaceIndex maps the compressed public key of a peer to all the
  232. // channels that the switch maintains with that peer.
  233. interfaceIndex map[[33]byte]map[lnwire.ChannelID]ChannelLink
  234. // linkStopIndex stores the currently stopping ChannelLinks,
  235. // represented by their ChannelID. The key is the link's ChannelID and
  236. // the value is a chan that is closed when the link has fully stopped.
  237. // This map is only added to if RemoveLink is called and is not added
  238. // to when the Switch is shutting down and calls Stop() on each link.
  239. //
  240. // MUST be used with the indexMtx.
  241. linkStopIndex map[lnwire.ChannelID]chan struct{}
  242. // htlcPlex is the channel which all connected links use to coordinate
  243. // the setup/teardown of Sphinx (onion routing) payment circuits.
  244. // Active links forward any add/settle messages over this channel each
  245. // state transition, sending new adds/settles which are fully locked
  246. // in.
  247. htlcPlex chan *plexPacket
  248. // chanCloseRequests is used to transfer the channel close request to
  249. // the channel close handler.
  250. chanCloseRequests chan *ChanClose
  251. // resolutionMsgs is the channel that all external contract resolution
  252. // messages will be sent over.
  253. resolutionMsgs chan *resolutionMsg
  254. // pendingFwdingEvents is the set of forwarding events which have been
  255. // collected during the current interval, but hasn't yet been written
  256. // to the forwarding log.
  257. fwdEventMtx sync.Mutex
  258. pendingFwdingEvents []channeldb.ForwardingEvent
  259. // blockEpochStream is an active block epoch event stream backed by an
  260. // active ChainNotifier instance. This will be used to retrieve the
  261. // latest height of the chain.
  262. blockEpochStream *chainntnfs.BlockEpochEvent
  263. // pendingSettleFails is the set of settle/fail entries that we need to
  264. // ack in the forwarding package of the outgoing link. This was added to
  265. // make pipelining settles more efficient.
  266. pendingSettleFails []channeldb.SettleFailRef
  267. // resMsgStore is used to store the set of ResolutionMsg that come from
  268. // contractcourt. This is used so the Switch can properly forward them,
  269. // even on restarts.
  270. resMsgStore *resolutionStore
  271. // aliasToReal is a map used for option-scid-alias feature-bit links.
  272. // The alias SCID is the key and the real, confirmed SCID is the value.
  273. // If the channel is unconfirmed, there will not be a mapping for it.
  274. // Since channels can have multiple aliases, this map is essentially a
  275. // N->1 mapping for a channel. This MUST be accessed with the indexMtx.
  276. aliasToReal map[lnwire.ShortChannelID]lnwire.ShortChannelID
  277. // baseIndex is a map used for option-scid-alias feature-bit links.
  278. // The value is the SCID of the link's ShortChannelID. This value may
  279. // be an alias for zero-conf channels or a confirmed SCID for
  280. // non-zero-conf channels with the option-scid-alias feature-bit. The
  281. // key includes the value itself and also any other aliases. This MUST
  282. // be accessed with the indexMtx.
  283. baseIndex map[lnwire.ShortChannelID]lnwire.ShortChannelID
  284. }
  285. // New creates the new instance of htlc switch.
  286. func New(cfg Config, currentHeight uint32) (*Switch, error) {
  287. resStore := newResolutionStore(cfg.DB)
  288. circuitMap, err := NewCircuitMap(&CircuitMapConfig{
  289. DB: cfg.DB,
  290. FetchAllOpenChannels: cfg.FetchAllOpenChannels,
  291. FetchClosedChannels: cfg.FetchClosedChannels,
  292. ExtractErrorEncrypter: cfg.ExtractErrorEncrypter,
  293. CheckResolutionMsg: resStore.checkResolutionMsg,
  294. })
  295. if err != nil {
  296. return nil, err
  297. }
  298. s := &Switch{
  299. bestHeight: currentHeight,
  300. cfg: &cfg,
  301. circuits: circuitMap,
  302. linkIndex: make(map[lnwire.ChannelID]ChannelLink),
  303. forwardingIndex: make(map[lnwire.ShortChannelID]ChannelLink),
  304. interfaceIndex: make(map[[33]byte]map[lnwire.ChannelID]ChannelLink),
  305. pendingLinkIndex: make(map[lnwire.ChannelID]ChannelLink),
  306. linkStopIndex: make(map[lnwire.ChannelID]chan struct{}),
  307. networkResults: newNetworkResultStore(cfg.DB),
  308. htlcPlex: make(chan *plexPacket),
  309. chanCloseRequests: make(chan *ChanClose),
  310. resolutionMsgs: make(chan *resolutionMsg),
  311. resMsgStore: resStore,
  312. quit: make(chan struct{}),
  313. }
  314. s.aliasToReal = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
  315. s.baseIndex = make(map[lnwire.ShortChannelID]lnwire.ShortChannelID)
  316. s.mailOrchestrator = newMailOrchestrator(&mailOrchConfig{
  317. forwardPackets: s.ForwardPackets,
  318. clock: s.cfg.Clock,
  319. expiry: s.cfg.MailboxDeliveryTimeout,
  320. failMailboxUpdate: s.failMailboxUpdate,
  321. })
  322. return s, nil
  323. }
  324. // resolutionMsg is a struct that wraps an existing ResolutionMsg with a done
  325. // channel. We'll use this channel to synchronize delivery of the message with
  326. // the caller.
  327. type resolutionMsg struct {
  328. contractcourt.ResolutionMsg
  329. errChan chan error
  330. }
  331. // ProcessContractResolution is called by active contract resolvers once a
  332. // contract they are watching over has been fully resolved. The message carries
  333. // an external signal that *would* have been sent if the outgoing channel
  334. // didn't need to go to the chain in order to fulfill a contract. We'll process
  335. // this message just as if it came from an active outgoing channel.
  336. func (s *Switch) ProcessContractResolution(msg contractcourt.ResolutionMsg) error {
  337. errChan := make(chan error, 1)
  338. select {
  339. case s.resolutionMsgs <- &resolutionMsg{
  340. ResolutionMsg: msg,
  341. errChan: errChan,
  342. }:
  343. case <-s.quit:
  344. return ErrSwitchExiting
  345. }
  346. select {
  347. case err := <-errChan:
  348. return err
  349. case <-s.quit:
  350. return ErrSwitchExiting
  351. }
  352. }
  353. // GetAttemptResult returns the result of the payment attempt with the given
  354. // attemptID. The paymentHash should be set to the payment's overall hash, or
  355. // in case of AMP payments the payment's unique identifier.
  356. //
  357. // The method returns a channel where the payment result will be sent when
  358. // available, or an error is encountered during forwarding. When a result is
  359. // received on the channel, the HTLC is guaranteed to no longer be in flight.
  360. // The switch shutting down is signaled by closing the channel. If the
  361. // attemptID is unknown, ErrPaymentIDNotFound will be returned.
  362. func (s *Switch) GetAttemptResult(attemptID uint64, paymentHash lntypes.Hash,
  363. deobfuscator ErrorDecrypter) (<-chan *PaymentResult, error) {
  364. var (
  365. nChan <-chan *networkResult
  366. err error
  367. inKey = CircuitKey{
  368. ChanID: hop.Source,
  369. HtlcID: attemptID,
  370. }
  371. )
  372. // If the payment is not found in the circuit map, check whether a
  373. // result is already available.
  374. // Assumption: no one will add this payment ID other than the caller.
  375. if s.circuits.LookupCircuit(inKey) == nil {
  376. res, err := s.networkResults.getResult(attemptID)
  377. if err != nil {
  378. return nil, err
  379. }
  380. c := make(chan *networkResult, 1)
  381. c <- res
  382. nChan = c
  383. } else {
  384. // The payment was committed to the circuits, subscribe for a
  385. // result.
  386. nChan, err = s.networkResults.subscribeResult(attemptID)
  387. if err != nil {
  388. return nil, err
  389. }
  390. }
  391. resultChan := make(chan *PaymentResult, 1)
  392. // Since the payment was known, we can start a goroutine that can
  393. // extract the result when it is available, and pass it on to the
  394. // caller.
  395. s.wg.Add(1)
  396. go func() {
  397. defer s.wg.Done()
  398. var n *networkResult
  399. select {
  400. case n = <-nChan:
  401. case <-s.quit:
  402. // We close the result channel to signal a shutdown. We
  403. // don't send any result in this case since the HTLC is
  404. // still in flight.
  405. close(resultChan)
  406. return
  407. }
  408. log.Debugf("Received network result %T for attemptID=%v", n.msg,
  409. attemptID)
  410. // Extract the result and pass it to the result channel.
  411. result, err := s.extractResult(
  412. deobfuscator, n, attemptID, paymentHash,
  413. )
  414. if err != nil {
  415. e := fmt.Errorf("unable to extract result: %w", err)
  416. log.Error(e)
  417. resultChan <- &PaymentResult{
  418. Error: e,
  419. }
  420. return
  421. }
  422. resultChan <- result
  423. }()
  424. return resultChan, nil
  425. }
  426. // CleanStore calls the underlying result store, telling it is safe to delete
  427. // all entries except the ones in the keepPids map. This should be called
  428. // preiodically to let the switch clean up payment results that we have
  429. // handled.
  430. func (s *Switch) CleanStore(keepPids map[uint64]struct{}) error {
  431. return s.networkResults.cleanStore(keepPids)
  432. }
  433. // SendHTLC is used by other subsystems which aren't belong to htlc switch
  434. // package in order to send the htlc update. The attemptID used MUST be unique
  435. // for this HTLC, and MUST be used only once, otherwise the switch might reject
  436. // it.
  437. func (s *Switch) SendHTLC(firstHop lnwire.ShortChannelID, attemptID uint64,
  438. htlc *lnwire.UpdateAddHTLC) error {
  439. // Generate and send new update packet, if error will be received on
  440. // this stage it means that packet haven't left boundaries of our
  441. // system and something wrong happened.
  442. packet := &htlcPacket{
  443. incomingChanID: hop.Source,
  444. incomingHTLCID: attemptID,
  445. outgoingChanID: firstHop,
  446. htlc: htlc,
  447. amount: htlc.Amount,
  448. }
  449. // Attempt to fetch the target link before creating a circuit so that
  450. // we don't leave dangling circuits. The getLocalLink method does not
  451. // require the circuit variable to be set on the *htlcPacket.
  452. link, linkErr := s.getLocalLink(packet, htlc)
  453. if linkErr != nil {
  454. // Notify the htlc notifier of a link failure on our outgoing
  455. // link. Incoming timelock/amount values are not set because
  456. // they are not present for local sends.
  457. s.cfg.HtlcNotifier.NotifyLinkFailEvent(
  458. newHtlcKey(packet),
  459. HtlcInfo{
  460. OutgoingTimeLock: htlc.Expiry,
  461. OutgoingAmt: htlc.Amount,
  462. },
  463. HtlcEventTypeSend,
  464. linkErr,
  465. false,
  466. )
  467. return linkErr
  468. }
  469. // Evaluate whether this HTLC would increase our exposure to dust. If
  470. // it does, don't send it out and instead return an error.
  471. if s.evaluateDustThreshold(link, htlc.Amount, false) {
  472. // Notify the htlc notifier of a link failure on our outgoing
  473. // link. We use the FailTemporaryChannelFailure in place of a
  474. // more descriptive error message.
  475. linkErr := NewLinkError(
  476. &lnwire.FailTemporaryChannelFailure{},
  477. )
  478. s.cfg.HtlcNotifier.NotifyLinkFailEvent(
  479. newHtlcKey(packet),
  480. HtlcInfo{
  481. OutgoingTimeLock: htlc.Expiry,
  482. OutgoingAmt: htlc.Amount,
  483. },
  484. HtlcEventTypeSend,
  485. linkErr,
  486. false,
  487. )
  488. return errDustThresholdExceeded
  489. }
  490. circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
  491. actions, err := s.circuits.CommitCircuits(circuit)
  492. if err != nil {
  493. log.Errorf("unable to commit circuit in switch: %v", err)
  494. return err
  495. }
  496. // Drop duplicate packet if it has already been seen.
  497. switch {
  498. case len(actions.Drops) == 1:
  499. return ErrDuplicateAdd
  500. case len(actions.Fails) == 1:
  501. return ErrLocalAddFailed
  502. }
  503. // Give the packet to the link's mailbox so that HTLC's are properly
  504. // canceled back if the mailbox timeout elapses.
  505. packet.circuit = circuit
  506. return link.handleSwitchPacket(packet)
  507. }
  508. // UpdateForwardingPolicies sends a message to the switch to update the
  509. // forwarding policies for the set of target channels, keyed in chanPolicies.
  510. //
  511. // NOTE: This function is synchronous and will block until either the
  512. // forwarding policies for all links have been updated, or the switch shuts
  513. // down.
  514. func (s *Switch) UpdateForwardingPolicies(
  515. chanPolicies map[wire.OutPoint]models.ForwardingPolicy) {
  516. log.Tracef("Updating link policies: %v", newLogClosure(func() string {
  517. return spew.Sdump(chanPolicies)
  518. }))
  519. s.indexMtx.RLock()
  520. // Update each link in chanPolicies.
  521. for targetLink, policy := range chanPolicies {
  522. cid := lnwire.NewChanIDFromOutPoint(targetLink)
  523. link, ok := s.linkIndex[cid]
  524. if !ok {
  525. log.Debugf("Unable to find ChannelPoint(%v) to update "+
  526. "link policy", targetLink)
  527. continue
  528. }
  529. link.UpdateForwardingPolicy(policy)
  530. }
  531. s.indexMtx.RUnlock()
  532. }
  533. // IsForwardedHTLC checks for a given channel and htlc index if it is related
  534. // to an opened circuit that represents a forwarded payment.
  535. func (s *Switch) IsForwardedHTLC(chanID lnwire.ShortChannelID,
  536. htlcIndex uint64) bool {
  537. circuit := s.circuits.LookupOpenCircuit(models.CircuitKey{
  538. ChanID: chanID,
  539. HtlcID: htlcIndex,
  540. })
  541. return circuit != nil && circuit.Incoming.ChanID != hop.Source
  542. }
  543. // ForwardPackets adds a list of packets to the switch for processing. Fails
  544. // and settles are added on a first past, simultaneously constructing circuits
  545. // for any adds. After persisting the circuits, another pass of the adds is
  546. // given to forward them through the router. The sending link's quit channel is
  547. // used to prevent deadlocks when the switch stops a link in the midst of
  548. // forwarding.
  549. func (s *Switch) ForwardPackets(linkQuit chan struct{},
  550. packets ...*htlcPacket) error {
  551. var (
  552. // fwdChan is a buffered channel used to receive err msgs from
  553. // the htlcPlex when forwarding this batch.
  554. fwdChan = make(chan error, len(packets))
  555. // numSent keeps a running count of how many packets are
  556. // forwarded to the switch, which determines how many responses
  557. // we will wait for on the fwdChan..
  558. numSent int
  559. )
  560. // No packets, nothing to do.
  561. if len(packets) == 0 {
  562. return nil
  563. }
  564. // Setup a barrier to prevent the background tasks from processing
  565. // responses until this function returns to the user.
  566. var wg sync.WaitGroup
  567. wg.Add(1)
  568. defer wg.Done()
  569. // Before spawning the following goroutine to proxy our error responses,
  570. // check to see if we have already been issued a shutdown request. If
  571. // so, we exit early to avoid incrementing the switch's waitgroup while
  572. // it is already in the process of shutting down.
  573. select {
  574. case <-linkQuit:
  575. return nil
  576. case <-s.quit:
  577. return nil
  578. default:
  579. // Spawn a goroutine to log the errors returned from failed packets.
  580. s.wg.Add(1)
  581. go s.logFwdErrs(&numSent, &wg, fwdChan)
  582. }
  583. // Make a first pass over the packets, forwarding any settles or fails.
  584. // As adds are found, we create a circuit and append it to our set of
  585. // circuits to be written to disk.
  586. var circuits []*PaymentCircuit
  587. var addBatch []*htlcPacket
  588. for _, packet := range packets {
  589. switch htlc := packet.htlc.(type) {
  590. case *lnwire.UpdateAddHTLC:
  591. circuit := newPaymentCircuit(&htlc.PaymentHash, packet)
  592. packet.circuit = circuit
  593. circuits = append(circuits, circuit)
  594. addBatch = append(addBatch, packet)
  595. default:
  596. err := s.routeAsync(packet, fwdChan, linkQuit)
  597. if err != nil {
  598. return fmt.Errorf("failed to forward packet %w",
  599. err)
  600. }
  601. numSent++
  602. }
  603. }
  604. // If this batch did not contain any circuits to commit, we can return
  605. // early.
  606. if len(circuits) == 0 {
  607. return nil
  608. }
  609. // Write any circuits that we found to disk.
  610. actions, err := s.circuits.CommitCircuits(circuits...)
  611. if err != nil {
  612. log.Errorf("unable to commit circuits in switch: %v", err)
  613. }
  614. // Split the htlc packets by comparing an in-order seek to the head of
  615. // the added, dropped, or failed circuits.
  616. //
  617. // NOTE: This assumes each list is guaranteed to be a subsequence of the
  618. // circuits, and that the union of the sets results in the original set
  619. // of circuits.
  620. var addedPackets, failedPackets []*htlcPacket
  621. for _, packet := range addBatch {
  622. switch {
  623. case len(actions.Adds) > 0 && packet.circuit == actions.Adds[0]:
  624. addedPackets = append(addedPackets, packet)
  625. actions.Adds = actions.Adds[1:]
  626. case len(actions.Drops) > 0 && packet.circuit == actions.Drops[0]:
  627. actions.Drops = actions.Drops[1:]
  628. case len(actions.Fails) > 0 && packet.circuit == actions.Fails[0]:
  629. failedPackets = append(failedPackets, packet)
  630. actions.Fails = actions.Fails[1:]
  631. }
  632. }
  633. // Now, forward any packets for circuits that were successfully added to
  634. // the switch's circuit map.
  635. for _, packet := range addedPackets {
  636. err := s.routeAsync(packet, fwdChan, linkQuit)
  637. if err != nil {
  638. return fmt.Errorf("failed to forward packet %w", err)
  639. }
  640. numSent++
  641. }
  642. // Lastly, for any packets that failed, this implies that they were
  643. // left in a half added state, which can happen when recovering from
  644. // failures.
  645. if len(failedPackets) > 0 {
  646. var failure lnwire.FailureMessage
  647. incomingID := failedPackets[0].incomingChanID
  648. // If the incoming channel is an option_scid_alias channel,
  649. // then we'll need to replace the SCID in the ChannelUpdate.
  650. update := s.failAliasUpdate(incomingID, true)
  651. if update == nil {
  652. // Fallback to the original non-option behavior.
  653. update, err := s.cfg.FetchLastChannelUpdate(
  654. incomingID,
  655. )
  656. if err != nil {
  657. failure = &lnwire.FailTemporaryNodeFailure{}
  658. } else {
  659. failure = lnwire.NewTemporaryChannelFailure(
  660. update,
  661. )
  662. }
  663. } else {
  664. // This is an option_scid_alias channel.
  665. failure = lnwire.NewTemporaryChannelFailure(update)
  666. }
  667. linkError := NewDetailedLinkError(
  668. failure, OutgoingFailureIncompleteForward,
  669. )
  670. for _, packet := range failedPackets {
  671. // We don't handle the error here since this method
  672. // always returns an error.
  673. _ = s.failAddPacket(packet, linkError)
  674. }
  675. }
  676. return nil
  677. }
  678. // logFwdErrs logs any errors received on `fwdChan`.
  679. func (s *Switch) logFwdErrs(num *int, wg *sync.WaitGroup, fwdChan chan error) {
  680. defer s.wg.Done()
  681. // Wait here until the outer function has finished persisting
  682. // and routing the packets. This guarantees we don't read from num until
  683. // the value is accurate.
  684. wg.Wait()
  685. numSent := *num
  686. for i := 0; i < numSent; i++ {
  687. select {
  688. case err := <-fwdChan:
  689. if err != nil {
  690. log.Errorf("Unhandled error while reforwarding htlc "+
  691. "settle/fail over htlcswitch: %v", err)
  692. }
  693. case <-s.quit:
  694. log.Errorf("unable to forward htlc packet " +
  695. "htlc switch was stopped")
  696. return
  697. }
  698. }
  699. }
  700. // routeAsync sends a packet through the htlc switch, using the provided err
  701. // chan to propagate errors back to the caller. The link's quit channel is
  702. // provided so that the send can be canceled if either the link or the switch
  703. // receive a shutdown requuest. This method does not wait for a response from
  704. // the htlcForwarder before returning.
  705. func (s *Switch) routeAsync(packet *htlcPacket, errChan chan error,
  706. linkQuit chan struct{}) error {
  707. command := &plexPacket{
  708. pkt: packet,
  709. err: errChan,
  710. }
  711. select {
  712. case s.htlcPlex <- command:
  713. return nil
  714. case <-linkQuit:
  715. return ErrLinkShuttingDown
  716. case <-s.quit:
  717. return errors.New("htlc switch was stopped")
  718. }
  719. }
  720. // getLocalLink handles the addition of a htlc for a send that originates from
  721. // our node. It returns the link that the htlc should be forwarded outwards on,
  722. // and a link error if the htlc cannot be forwarded.
  723. func (s *Switch) getLocalLink(pkt *htlcPacket, htlc *lnwire.UpdateAddHTLC) (
  724. ChannelLink, *LinkError) {
  725. // Try to find links by node destination.
  726. s.indexMtx.RLock()
  727. link, err := s.getLinkByShortID(pkt.outgoingChanID)
  728. defer s.indexMtx.RUnlock()
  729. if err != nil {
  730. // If the link was not found for the outgoingChanID, an outside
  731. // subsystem may be using the confirmed SCID of a zero-conf
  732. // channel. In this case, we'll consult the Switch maps to see
  733. // if an alias exists and use the alias to lookup the link.
  734. // This extra step is a consequence of not updating the Switch
  735. // forwardingIndex when a zero-conf channel is confirmed. We
  736. // don't need to change the outgoingChanID since the link will
  737. // do that upon receiving the packet.
  738. baseScid, ok := s.baseIndex[pkt.outgoingChanID]
  739. if !ok {
  740. log.Errorf("Link %v not found", pkt.outgoingChanID)
  741. return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
  742. }
  743. // The base SCID was found, so we'll use that to fetch the
  744. // link.
  745. link, err = s.getLinkByShortID(baseScid)
  746. if err != nil {
  747. log.Errorf("Link %v not found", baseScid)
  748. return nil, NewLinkError(&lnwire.FailUnknownNextPeer{})
  749. }
  750. }
  751. if !link.EligibleToForward() {
  752. log.Errorf("Link %v is not available to forward",
  753. pkt.outgoingChanID)
  754. // The update does not need to be populated as the error
  755. // will be returned back to the router.
  756. return nil, NewDetailedLinkError(
  757. lnwire.NewTemporaryChannelFailure(nil),
  758. OutgoingFailureLinkNotEligible,
  759. )
  760. }
  761. // Ensure that the htlc satisfies the outgoing channel policy.
  762. currentHeight := atomic.LoadUint32(&s.bestHeight)
  763. htlcErr := link.CheckHtlcTransit(
  764. htlc.PaymentHash, htlc.Amount, htlc.Expiry, currentHeight,
  765. )
  766. if htlcErr != nil {
  767. log.Errorf("Link %v policy for local forward not "+
  768. "satisfied", pkt.outgoingChanID)
  769. return nil, htlcErr
  770. }
  771. return link, nil
  772. }
  773. // handleLocalResponse processes a Settle or Fail responding to a
  774. // locally-initiated payment. This is handled asynchronously to avoid blocking
  775. // the main event loop within the switch, as these operations can require
  776. // multiple db transactions. The guarantees of the circuit map are stringent
  777. // enough such that we are able to tolerate reordering of these operations
  778. // without side effects. The primary operations handled are:
  779. // 1. Save the payment result to the pending payment store.
  780. // 2. Notify subscribers about the payment result.
  781. // 3. Ack settle/fail references, to avoid resending this response internally
  782. // 4. Teardown the closing circuit in the circuit map
  783. //
  784. // NOTE: This method MUST be spawned as a goroutine.
  785. func (s *Switch) handleLocalResponse(pkt *htlcPacket) {
  786. defer s.wg.Done()
  787. attemptID := pkt.incomingHTLCID
  788. // The error reason will be unencypted in case this a local
  789. // failure or a converted error.
  790. unencrypted := pkt.localFailure || pkt.convertedError
  791. n := &networkResult{
  792. msg: pkt.htlc,
  793. unencrypted: unencrypted,
  794. isResolution: pkt.isResolution,
  795. }
  796. // Store the result to the db. This will also notify subscribers about
  797. // the result.
  798. if err := s.networkResults.storeResult(attemptID, n); err != nil {
  799. log.Errorf("Unable to complete payment for pid=%v: %v",
  800. attemptID, err)
  801. return
  802. }
  803. // First, we'll clean up any fwdpkg references, circuit entries, and
  804. // mark in our db that the payment for this payment hash has either
  805. // succeeded or failed.
  806. //
  807. // If this response is contained in a forwarding package, we'll start by
  808. // acking the settle/fail so that we don't continue to retransmit the
  809. // HTLC internally.
  810. if pkt.destRef != nil {
  811. if err := s.ackSettleFail(*pkt.destRef); err != nil {
  812. log.Warnf("Unable to ack settle/fail reference: %s: %v",
  813. *pkt.destRef, err)
  814. return
  815. }
  816. }
  817. // Next, we'll remove the circuit since we are about to complete an
  818. // fulfill/fail of this HTLC. Since we've already removed the
  819. // settle/fail fwdpkg reference, the response from the peer cannot be
  820. // replayed internally if this step fails. If this happens, this logic
  821. // will be executed when a provided resolution message comes through.
  822. // This can only happen if the circuit is still open, which is why this
  823. // ordering is chosen.
  824. if err := s.teardownCircuit(pkt); err != nil {
  825. log.Warnf("Unable to teardown circuit %s: %v",
  826. pkt.inKey(), err)
  827. return
  828. }
  829. // Finally, notify on the htlc failure or success that has been handled.
  830. key := newHtlcKey(pkt)
  831. eventType := getEventType(pkt)
  832. switch htlc := pkt.htlc.(type) {
  833. case *lnwire.UpdateFulfillHTLC:
  834. s.cfg.HtlcNotifier.NotifySettleEvent(key, htlc.PaymentPreimage,
  835. eventType)
  836. case *lnwire.UpdateFailHTLC:
  837. s.cfg.HtlcNotifier.NotifyForwardingFailEvent(key, eventType)
  838. }
  839. }
  840. // extractResult uses the given deobfuscator to extract the payment result from
  841. // the given network message.
  842. func (s *Switch) extractResult(deobfuscator ErrorDecrypter, n *networkResult,
  843. attemptID uint64, paymentHash lntypes.Hash) (*PaymentResult, error) {
  844. switch htlc := n.msg.(type) {
  845. // We've received a settle update which means we can finalize the user
  846. // payment and return successful response.
  847. case *lnwire.UpdateFulfillHTLC:
  848. return &PaymentResult{
  849. Preimage: htlc.PaymentPreimage,
  850. }, nil
  851. // We've received a fail update which means we can finalize the
  852. // user payment and return fail response.
  853. case *lnwire.UpdateFailHTLC:
  854. // TODO(yy): construct deobfuscator here to avoid creating it
  855. // in paymentLifecycle even for settled HTLCs.
  856. paymentErr := s.parseFailedPayment(
  857. deobfuscator, attemptID, paymentHash, n.unencrypted,
  858. n.isResolution, htlc,
  859. )
  860. return &PaymentResult{
  861. Error: paymentErr,
  862. }, nil
  863. default:
  864. return nil, fmt.Errorf("received unknown response type: %T",
  865. htlc)
  866. }
  867. }
  868. // parseFailedPayment determines the appropriate failure message to return to
  869. // a user initiated payment. The three cases handled are:
  870. // 1. An unencrypted failure, which should already plaintext.
  871. // 2. A resolution from the chain arbitrator, which possibly has no failure
  872. // reason attached.
  873. // 3. A failure from the remote party, which will need to be decrypted using
  874. // the payment deobfuscator.
  875. func (s *Switch) parseFailedPayment(deobfuscator ErrorDecrypter,
  876. attemptID uint64, paymentHash lntypes.Hash, unencrypted,
  877. isResolution bool, htlc *lnwire.UpdateFailHTLC) error {
  878. switch {
  879. // The payment never cleared the link, so we don't need to
  880. // decrypt the error, simply decode it them report back to the
  881. // user.
  882. case unencrypted:
  883. r := bytes.NewReader(htlc.Reason)
  884. failureMsg, err := lnwire.DecodeFailure(r, 0)
  885. if err != nil {
  886. // If we could not decode the failure reason, return a link
  887. // error indicating that we failed to decode the onion.
  888. linkError := NewDetailedLinkError(
  889. // As this didn't even clear the link, we don't
  890. // need to apply an update here since it goes
  891. // directly to the router.
  892. lnwire.NewTemporaryChannelFailure(nil),
  893. OutgoingFailureDecodeError,
  894. )
  895. log.Errorf("%v: (hash=%v, pid=%d): %v",
  896. linkError.FailureDetail.FailureString(),
  897. paymentHash, attemptID, err)
  898. return linkError
  899. }
  900. // If we successfully decoded the failure reason, return it.
  901. return NewLinkError(failureMsg)
  902. // A payment had to be timed out on chain before it got past
  903. // the first hop. In this case, we'll report a permanent
  904. // channel failure as this means us, or the remote party had to
  905. // go on chain.
  906. case isResolution && htlc.Reason == nil:
  907. linkError := NewDetailedLinkError(
  908. &lnwire.FailPermanentChannelFailure{},
  909. OutgoingFailureOnChainTimeout,
  910. )
  911. log.Infof("%v: hash=%v, pid=%d",
  912. linkError.FailureDetail.FailureString(),
  913. paymentHash, attemptID)
  914. return linkError
  915. // A regular multi-hop payment error that we'll need to
  916. // decrypt.
  917. default:
  918. // We'll attempt to fully decrypt the onion encrypted
  919. // error. If we're unable to then we'll bail early.
  920. failure, err := deobfuscator.DecryptError(htlc.Reason)
  921. if err != nil {
  922. log.Errorf("unable to de-obfuscate onion failure "+
  923. "(hash=%v, pid=%d): %v",
  924. paymentHash, attemptID, err)
  925. return ErrUnreadableFailureMessage
  926. }
  927. return failure
  928. }
  929. }
  930. // handlePacketForward is used in cases when we need forward the htlc update
  931. // from one channel link to another and be able to propagate the settle/fail
  932. // updates back. This behaviour is achieved by creation of payment circuits.
  933. func (s *Switch) handlePacketForward(packet *htlcPacket) error {
  934. switch htlc := packet.htlc.(type) {
  935. // Channel link forwarded us a new htlc, therefore we initiate the
  936. // payment circuit within our internal state so we can properly forward
  937. // the ultimate settle message back latter.
  938. case *lnwire.UpdateAddHTLC:
  939. // Check if the node is set to reject all onward HTLCs and also make
  940. // sure that HTLC is not from the source node.
  941. if s.cfg.RejectHTLC {
  942. failure := NewDetailedLinkError(
  943. &lnwire.FailChannelDisabled{},
  944. OutgoingFailureForwardsDisabled,
  945. )
  946. return s.failAddPacket(packet, failure)
  947. }
  948. // Before we attempt to find a non-strict forwarding path for
  949. // this htlc, check whether the htlc is being routed over the
  950. // same incoming and outgoing channel. If our node does not
  951. // allow forwards of this nature, we fail the htlc early. This
  952. // check is in place to disallow inefficiently routed htlcs from
  953. // locking up our balance. With channels where the
  954. // option-scid-alias feature was negotiated, we also have to be
  955. // sure that the IDs aren't the same since one or both could be
  956. // an alias.
  957. linkErr := s.checkCircularForward(
  958. packet.incomingChanID, packet.outgoingChanID,
  959. s.cfg.AllowCircularRoute, htlc.PaymentHash,
  960. )
  961. if linkErr != nil {
  962. return s.failAddPacket(packet, linkErr)
  963. }
  964. s.indexMtx.RLock()
  965. targetLink, err := s.getLinkByMapping(packet)
  966. if err != nil {
  967. s.indexMtx.RUnlock()
  968. log.Debugf("unable to find link with "+
  969. "destination %v", packet.outgoingChanID)
  970. // If packet was forwarded from another channel link
  971. // than we should notify this link that some error
  972. // occurred.
  973. linkError := NewLinkError(
  974. &lnwire.FailUnknownNextPeer{},
  975. )
  976. return s.failAddPacket(packet, linkError)
  977. }
  978. targetPeerKey := targetLink.PeerPubKey()
  979. interfaceLinks, _ := s.getLinks(targetPeerKey)
  980. s.indexMtx.RUnlock()
  981. // We'll keep track of any HTLC failures during the link
  982. // selection process. This way we can return the error for
  983. // precise link that the sender selected, while optimistically
  984. // trying all links to utilize our available bandwidth.
  985. linkErrs := make(map[lnwire.ShortChannelID]*LinkError)
  986. // Find all destination channel links with appropriate
  987. // bandwidth.
  988. var destinations []ChannelLink
  989. for _, link := range interfaceLinks {
  990. var failure *LinkError
  991. // We'll skip any links that aren't yet eligible for
  992. // forwarding.
  993. if !link.EligibleToForward() {
  994. failure = NewDetailedLinkError(
  995. &lnwire.FailUnknownNextPeer{},
  996. OutgoingFailureLinkNotEligible,
  997. )
  998. } else {
  999. // We'll ensure that the HTLC satisfies the
  1000. // current forwarding conditions of this target
  1001. // link.
  1002. currentHeight := atomic.LoadUint32(&s.bestHeight)
  1003. failure = link.CheckHtlcForward(
  1004. htlc.PaymentHash, packet.incomingAmount,
  1005. packet.amount, packet.incomingTimeout,
  1006. packet.outgoingTimeout,
  1007. packet.inboundFee,
  1008. currentHeight,
  1009. packet.originalOutgoingChanID,
  1010. )
  1011. }
  1012. // If this link can forward the htlc, add it to the set
  1013. // of destinations.
  1014. if failure == nil {
  1015. destinations = append(destinations, link)
  1016. continue
  1017. }
  1018. linkErrs[link.ShortChanID()] = failure
  1019. }
  1020. // If we had a forwarding failure due to the HTLC not
  1021. // satisfying the current policy, then we'll send back an
  1022. // error, but ensure we send back the error sourced at the
  1023. // *target* link.
  1024. if len(destinations) == 0 {
  1025. // At this point, some or all of the links rejected the
  1026. // HTLC so we couldn't forward it. So we'll try to look
  1027. // up the error that came from the source.
  1028. linkErr, ok := linkErrs[packet.outgoingChanID]
  1029. if !ok {
  1030. // If we can't find the error of the source,
  1031. // then we'll return an unknown next peer,
  1032. // though this should never happen.
  1033. linkErr = NewLinkError(
  1034. &lnwire.FailUnknownNextPeer{},
  1035. )
  1036. log.Warnf("unable to find err source for "+
  1037. "outgoing_link=%v, errors=%v",
  1038. packet.outgoingChanID, newLogClosure(func() string {
  1039. return spew.Sdump(linkErrs)
  1040. }))
  1041. }
  1042. log.Tracef("incoming HTLC(%x) violated "+
  1043. "target outgoing link (id=%v) policy: %v",
  1044. htlc.PaymentHash[:], packet.outgoingChanID,
  1045. linkErr)
  1046. return s.failAddPacket(packet, linkErr)
  1047. }
  1048. // Choose a random link out of the set of links that can forward
  1049. // this htlc. The reason for randomization is to evenly
  1050. // distribute the htlc load without making assumptions about
  1051. // what the best channel is.
  1052. destination := destinations[rand.Intn(len(destinations))] // nolint:gosec
  1053. // Retrieve the incoming link by its ShortChannelID. Note that
  1054. // the incomingChanID is never set to hop.Source here.
  1055. s.indexMtx.RLock()
  1056. incomingLink, err := s.getLinkByShortID(packet.incomingChanID)
  1057. s.indexMtx.RUnlock()
  1058. if err != nil {
  1059. // If we couldn't find the incoming link, we can't
  1060. // evaluate the incoming's exposure to dust, so we just
  1061. // fail the HTLC back.
  1062. linkErr := NewLinkError(
  1063. &lnwire.FailTemporaryChannelFailure{},
  1064. )
  1065. return s.failAddPacket(packet, linkErr)
  1066. }
  1067. // Evaluate whether this HTLC would increase our exposure to
  1068. // dust on the incoming link. If it does, fail it backwards.
  1069. if s.evaluateDustThreshold(
  1070. incomingLink, packet.incomingAmount, true,
  1071. ) {
  1072. // The incoming dust exceeds the threshold, so we fail
  1073. // the add back.
  1074. linkErr := NewLinkError(
  1075. &lnwire.FailTemporaryChannelFailure{},
  1076. )
  1077. return s.failAddPacket(packet, linkErr)
  1078. }
  1079. // Also evaluate whether this HTLC would increase our exposure
  1080. // to dust on the destination link. If it does, fail it back.
  1081. if s.evaluateDustThreshold(
  1082. destination, packet.amount, false,
  1083. ) {
  1084. // The outgoing dust exceeds the threshold, so we fail
  1085. // the add back.
  1086. linkErr := NewLinkError(
  1087. &lnwire.FailTemporaryChannelFailure{},
  1088. )
  1089. return s.failAddPacket(packet, linkErr)
  1090. }
  1091. // Send the packet to the destination channel link which
  1092. // manages the channel.
  1093. packet.outgoingChanID = destination.ShortChanID()
  1094. return destination.handleSwitchPacket(packet)
  1095. case *lnwire.UpdateFailHTLC, *lnwire.UpdateFulfillHTLC:
  1096. // If the source of this packet has not been set, use the
  1097. // circuit map to lookup the origin.
  1098. circuit, err := s.closeCircuit(packet)
  1099. if err != nil {
  1100. return err
  1101. }
  1102. // closeCircuit returns a nil circuit when a settle packet returns an
  1103. // ErrUnknownCircuit error upon the inner call to CloseCircuit.
  1104. if circuit == nil {
  1105. return nil
  1106. }
  1107. fail, isFail := htlc.(*lnwire.UpdateFailHTLC)
  1108. if isFail && !packet.hasSource {
  1109. // HTLC resolutions and messages restored from disk
  1110. // don't have the obfuscator set from the original htlc
  1111. // add packet - set it here for use in blinded errors.
  1112. packet.obfuscator = circuit.ErrorEncrypter
  1113. switch {
  1114. // No message to encrypt, locally sourced payment.
  1115. case circuit.ErrorEncrypter == nil:
  1116. // If this is a resolution message, then we'll need to
  1117. // encrypt it as it's actually internally sourced.
  1118. case packet.isResolution:
  1119. var err error
  1120. // TODO(roasbeef): don't need to pass actually?
  1121. failure := &lnwire.FailPermanentChannelFailure{}
  1122. fail.Reason, err = circuit.ErrorEncrypter.EncryptFirstHop(
  1123. failure,
  1124. )
  1125. if err != nil {
  1126. err = fmt.Errorf("unable to obfuscate "+
  1127. "error: %v", err)
  1128. log.Error(err)
  1129. }
  1130. // Alternatively, if the remote party send us an
  1131. // UpdateFailMalformedHTLC, then we'll need to convert
  1132. // this into a proper well formatted onion error as
  1133. // there's no HMAC currently.
  1134. case packet.convertedError:
  1135. log.Infof("Converting malformed HTLC error "+
  1136. "for circuit for Circuit(%x: "+
  1137. "(%s, %d) <-> (%s, %d))", packet.circuit.PaymentHash,
  1138. packet.incomingChanID, packet.incomingHTLCID,
  1139. packet.outgoingChanID, packet.outgoingHTLCID)
  1140. fail.Reason = circuit.ErrorEncrypter.EncryptMalformedError(
  1141. fail.Reason,
  1142. )
  1143. default:
  1144. // Otherwise, it's a forwarded error, so we'll perform a
  1145. // wrapper encryption as normal.
  1146. fail.Reason = circuit.ErrorEncrypter.IntermediateEncrypt(
  1147. fail.Reason,
  1148. )
  1149. }
  1150. } else if !isFail && circuit.Outgoing != nil {
  1151. // If this is an HTLC settle, and it wasn't from a
  1152. // locally initiated HTLC, then we'll log a forwarding
  1153. // event so we can flush it to disk later.
  1154. //
  1155. // TODO(roasbeef): only do this once link actually
  1156. // fully settles?
  1157. localHTLC := packet.incomingChanID == hop.Source
  1158. if !localHTLC {
  1159. log.Infof("Forwarded HTLC(%x) of %v (fee: %v) "+
  1160. "from IncomingChanID(%v) to OutgoingChanID(%v)",
  1161. circuit.PaymentHash[:], circuit.OutgoingAmount,
  1162. circuit.IncomingAmount-circuit.OutgoingAmount,
  1163. circuit.Incoming.ChanID, circuit.Outgoing.ChanID)
  1164. s.fwdEventMtx.Lock()
  1165. s.pendingFwdingEvents = append(
  1166. s.pendingFwdingEvents,
  1167. channeldb.ForwardingEvent{
  1168. Timestamp: time.Now(),
  1169. IncomingChanID: circuit.Incoming.ChanID,
  1170. OutgoingChanID: circuit.Outgoing.ChanID,
  1171. AmtIn: circuit.IncomingAmount,
  1172. AmtOut: circuit.OutgoingAmount,
  1173. },
  1174. )
  1175. s.fwdEventMtx.Unlock()
  1176. }
  1177. }
  1178. // A blank IncomingChanID in a circuit indicates that it is a pending
  1179. // user-initiated payment.
  1180. if packet.incomingChanID == hop.Source {
  1181. s.wg.Add(1)
  1182. go s.handleLocalResponse(packet)
  1183. return nil
  1184. }
  1185. // Check to see that the source link is online before removing
  1186. // the circuit.
  1187. return s.mailOrchestrator.Deliver(packet.incomingChanID, packet)
  1188. default:
  1189. return errors.New("wrong update type")
  1190. }
  1191. }
  1192. // checkCircularForward checks whether a forward is circular (arrives and
  1193. // departs on the same link) and returns a link error if the switch is
  1194. // configured to disallow this behaviour.
  1195. func (s *Switch) checkCircularForward(incoming, outgoing lnwire.ShortChannelID,
  1196. allowCircular bool, paymentHash lntypes.Hash) *LinkError {
  1197. // If they are equal, we can skip the alias mapping checks.
  1198. if incoming == outgoing {
  1199. // The switch may be configured to allow circular routes, so
  1200. // just log and return nil.
  1201. if allowCircular {
  1202. log.Debugf("allowing circular route over link: %v "+
  1203. "(payment hash: %x)", incoming, paymentHash)
  1204. return nil
  1205. }
  1206. // Otherwise, we'll return a temporary channel failure.
  1207. return NewDetailedLinkError(
  1208. lnwire.NewTemporaryChannelFailure(nil),
  1209. OutgoingFailureCircularRoute,
  1210. )
  1211. }
  1212. // We'll fetch the "base" SCID from the baseIndex for the incoming and
  1213. // outgoing SCIDs. If either one does not have a base SCID, then the
  1214. // two channels are not equal since one will be a channel that does not
  1215. // need a mapping and SCID equality was checked above. If the "base"
  1216. // SCIDs are equal, then this is a circular route. Otherwise, it isn't.
  1217. s.indexMtx.RLock()
  1218. incomingBaseScid, ok := s.baseIndex[incoming]
  1219. if !ok {
  1220. // This channel does not use baseIndex, bail out.
  1221. s.indexMtx.RUnlock()
  1222. return nil
  1223. }
  1224. outgoingBaseScid, ok := s.baseIndex[outgoing]
  1225. if !ok {
  1226. // This channel does not use baseIndex, bail out.
  1227. s.indexMtx.RUnlock()
  1228. return nil
  1229. }
  1230. s.indexMtx.RUnlock()
  1231. // Check base SCID equality.
  1232. if incomingBaseScid != outgoingBaseScid {
  1233. // The base SCIDs are not equal so these are not the same
  1234. // channel.
  1235. return nil
  1236. }
  1237. // If the incoming and outgoing link are equal, the htlc is part of a
  1238. // circular route which may be used to lock up our liquidity. If the
  1239. // switch is configured to allow circular routes, log that we are
  1240. // allowing the route then return nil.
  1241. if allowCircular {
  1242. log.Debugf("allowing circular route over link: %v "+
  1243. "(payment hash: %x)", incoming, paymentHash)
  1244. return nil
  1245. }
  1246. // If our node disallows circular routes, return a temporary channel
  1247. // failure. There is nothing wrong with the policy used by the remote
  1248. // node, so we do not include a channel update.
  1249. return NewDetailedLinkError(
  1250. lnwire.NewTemporaryChannelFailure(nil),
  1251. OutgoingFailureCircularRoute,
  1252. )
  1253. }
  1254. // failAddPacket encrypts a fail packet back to an add packet's source.
  1255. // The ciphertext will be derived from the failure message proivded by context.
  1256. // This method returns the failErr if all other steps complete successfully.
  1257. func (s *Switch) failAddPacket(packet *htlcPacket, failure *LinkError) error {
  1258. // Encrypt the failure so that the sender will be able to read the error
  1259. // message. Since we failed this packet, we use EncryptFirstHop to
  1260. // obfuscate the failure for their eyes only.
  1261. reason, err := packet.obfuscator.EncryptFirstHop(failure.WireMessage())
  1262. if err != nil {
  1263. err := fmt.Errorf("unable to obfuscate "+
  1264. "error: %v", err)
  1265. log.Error(err)
  1266. return err
  1267. }
  1268. log.Error(failure.Error())
  1269. // Create a failure packet for this htlc. The full set of
  1270. // information about the htlc failure is included so that they can
  1271. // be included in link failure notifications.
  1272. failPkt := &htlcPacket{
  1273. sourceRef: packet.sourceRef,
  1274. incomingChanID: packet.incomingChanID,
  1275. incomingHTLCID: packet.incomingHTLCID,
  1276. outgoingChanID: packet.outgoingChanID,
  1277. outgoingHTLCID: packet.outgoingHTLCID,
  1278. incomingAmount: packet.incomingAmount,
  1279. amount: packet.amount,
  1280. incomingTimeout: packet.incomingTimeout,
  1281. outgoingTimeout: packet.outgoingTimeout,
  1282. circuit: packet.circuit,
  1283. obfuscator: packet.obfuscator,
  1284. linkFailure: failure,
  1285. htlc: &lnwire.UpdateFailHTLC{
  1286. Reason: reason,
  1287. },
  1288. }
  1289. // Route a fail packet back to the source link.
  1290. err = s.mailOrchestrator.Deliver(failPkt.incomingChanID, failPkt)
  1291. if err != nil {
  1292. err = fmt.Errorf("source chanid=%v unable to "+
  1293. "handle switch packet: %v",
  1294. packet.incomingChanID, err)
  1295. log.Error(err)
  1296. return err
  1297. }
  1298. return failure
  1299. }
  1300. // closeCircuit accepts a settle or fail htlc and the associated htlc packet and
  1301. // attempts to determine the source that forwarded this htlc. This method will
  1302. // set the incoming chan and htlc ID of the given packet if the source was
  1303. // found, and will properly [re]encrypt any failure messages.
  1304. func (s *Switch) closeCircuit(pkt *htlcPacket) (*PaymentCircuit, error) {
  1305. // If the packet has its source, that means it was failed locally by
  1306. // the outgoing link. We fail it here to make sure only one response
  1307. // makes it through the switch.
  1308. if pkt.hasSource {
  1309. circuit, err := s.circuits.FailCircuit(pkt.inKey())
  1310. switch err {
  1311. // Circuit successfully closed.
  1312. case nil:
  1313. return circuit, nil
  1314. // Circuit was previously closed, but has not been deleted.
  1315. // We'll just drop this response until the circuit has been
  1316. // fully removed.
  1317. case ErrCircuitClosing:
  1318. return nil, err
  1319. // Failed to close circuit because it does not exist. This is
  1320. // likely because the circuit was already successfully closed.
  1321. // Since this packet failed locally, there is no forwarding
  1322. // package entry to acknowledge.
  1323. case ErrUnknownCircuit:
  1324. return nil, err
  1325. // Unexpected error.
  1326. default:
  1327. return nil, err
  1328. }
  1329. }
  1330. // Otherwise, this is packet was received from the remote party. Use
  1331. // circuit map to find the incoming link to receive the settle/fail.
  1332. circuit, err := s.circuits.CloseCircuit(pkt.outKey())
  1333. switch err {
  1334. // Open circuit successfully closed.
  1335. case nil:
  1336. pkt.incomingChanID = circuit.Incoming.ChanID
  1337. pkt.incomingHTLCID = circuit.Incoming.HtlcID
  1338. pkt.circuit = circuit
  1339. pkt.sourceRef = &circuit.AddRef
  1340. pktType := "SETTLE"
  1341. if _, ok := pkt.htlc.(*lnwire.UpdateFailHTLC); ok {
  1342. pktType = "FAIL"
  1343. }
  1344. log.Debugf("Closed completed %s circuit for %x: "+
  1345. "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
  1346. pkt.incomingChanID, pkt.incomingHTLCID,
  1347. pkt.outgoingChanID, pkt.outgoingHTLCID)
  1348. return circuit, nil
  1349. // Circuit was previously closed, but has not been deleted. We'll just
  1350. // drop this response until the circuit has been removed.
  1351. case ErrCircuitClosing:
  1352. return nil, err
  1353. // Failed to close circuit because it does not exist. This is likely
  1354. // because the circuit was already successfully closed.
  1355. case ErrUnknownCircuit:
  1356. if pkt.destRef != nil {
  1357. // Add this SettleFailRef to the set of pending settle/fail entries
  1358. // awaiting acknowledgement.
  1359. s.pendingSettleFails = append(s.pendingSettleFails, *pkt.destRef)
  1360. }
  1361. // If this is a settle, we will not log an error message as settles
  1362. // are expected to hit the ErrUnknownCircuit case. The only way fails
  1363. // can hit this case if the link restarts after having just sent a fail
  1364. // to the switch.
  1365. _, isSettle := pkt.htlc.(*lnwire.UpdateFulfillHTLC)
  1366. if !isSettle {
  1367. err := fmt.Errorf("unable to find target channel "+
  1368. "for HTLC fail: channel ID = %s, "+
  1369. "HTLC ID = %d", pkt.outgoingChanID,
  1370. pkt.outgoingHTLCID)
  1371. log.Error(err)
  1372. return nil, err
  1373. }
  1374. return nil, nil
  1375. // Unexpected error.
  1376. default:
  1377. return nil, err
  1378. }
  1379. }
  1380. // ackSettleFail is used by the switch to ACK any settle/fail entries in the
  1381. // forwarding package of the outgoing link for a payment circuit. We do this if
  1382. // we're the originator of the payment, so the link stops attempting to
  1383. // re-broadcast.
  1384. func (s *Switch) ackSettleFail(settleFailRefs ...channeldb.SettleFailRef) error {
  1385. return kvdb.Batch(s.cfg.DB, func(tx kvdb.RwTx) error {
  1386. return s.cfg.SwitchPackager.AckSettleFails(tx, settleFailRefs...)
  1387. })
  1388. }
  1389. // teardownCircuit removes a pending or open circuit from the switch's circuit
  1390. // map and prints useful logging statements regarding the outcome.
  1391. func (s *Switch) teardownCircuit(pkt *htlcPacket) error {
  1392. var pktType string
  1393. switch htlc := pkt.htlc.(type) {
  1394. case *lnwire.UpdateFulfillHTLC:
  1395. pktType = "SETTLE"
  1396. case *lnwire.UpdateFailHTLC:
  1397. pktType = "FAIL"
  1398. default:
  1399. err := fmt.Errorf("cannot tear down packet of type: %T", htlc)
  1400. log.Errorf(err.Error())
  1401. return err
  1402. }
  1403. switch {
  1404. case pkt.circuit.HasKeystone():
  1405. log.Debugf("Tearing down open circuit with %s pkt, removing circuit=%v "+
  1406. "with keystone=%v", pktType, pkt.inKey(), pkt.outKey())
  1407. err := s.circuits.DeleteCircuits(pkt.inKey())
  1408. if err != nil {
  1409. log.Warnf("Failed to tear down open circuit (%s, %d) <-> (%s, %d) "+
  1410. "with payment_hash-%v using %s pkt",
  1411. pkt.incomingChanID, pkt.incomingHTLCID,
  1412. pkt.outgoingChanID, pkt.outgoingHTLCID,
  1413. pkt.circuit.PaymentHash, pktType)
  1414. return err
  1415. }
  1416. log.Debugf("Closed completed %s circuit for %x: "+
  1417. "(%s, %d) <-> (%s, %d)", pktType, pkt.circuit.PaymentHash,
  1418. pkt.incomingChanID, pkt.incomingHTLCID,
  1419. pkt.outgoingChanID, pkt.outgoingHTLCID)
  1420. default:
  1421. log.Debugf("Tearing down incomplete circuit with %s for inkey=%v",
  1422. pktType, pkt.inKey())
  1423. err := s.circuits.DeleteCircuits(pkt.inKey())
  1424. if err != nil {
  1425. log.Warnf("Failed to tear down pending %s circuit for %x: "+
  1426. "(%s, %d)", pktType, pkt.circuit.PaymentHash,
  1427. pkt.incomingChanID, pkt.incomingHTLCID)
  1428. return err
  1429. }
  1430. log.Debugf("Removed pending onion circuit for %x: "+
  1431. "(%s, %d)", pkt.circuit.PaymentHash,
  1432. pkt.incomingChanID, pkt.incomingHTLCID)
  1433. }
  1434. return nil
  1435. }
  1436. // CloseLink creates and sends the close channel command to the target link
  1437. // directing the specified closure type. If the closure type is CloseRegular,
  1438. // targetFeePerKw parameter should be the ideal fee-per-kw that will be used as
  1439. // a starting point for close negotiation. The deliveryScript parameter is an
  1440. // optional parameter which sets a user specified script to close out to.
  1441. func (s *Switch) CloseLink(chanPoint *wire.OutPoint,
  1442. closeType contractcourt.ChannelCloseType,
  1443. targetFeePerKw, maxFee chainfee.SatPerKWeight,
  1444. deliveryScript lnwire.DeliveryAddress) (chan interface{}, chan error) {
  1445. // TODO(roasbeef) abstract out the close updates.
  1446. updateChan := make(chan interface{}, 2)
  1447. errChan := make(chan error, 1)
  1448. command := &ChanClose{
  1449. CloseType: closeType,
  1450. ChanPoint: chanPoint,
  1451. Updates: updateChan,
  1452. TargetFeePerKw: targetFeePerKw,
  1453. MaxFee: maxFee,
  1454. DeliveryScript: deliveryScript,
  1455. Err: errChan,
  1456. }
  1457. select {
  1458. case s.chanCloseRequests <- command:
  1459. return updateChan, errChan
  1460. case <-s.quit:
  1461. errChan <- ErrSwitchExiting
  1462. close(updateChan)
  1463. return updateChan, errChan
  1464. }
  1465. }
  1466. // htlcForwarder is responsible for optimally forwarding (and possibly
  1467. // fragmenting) incoming/outgoing HTLCs amongst all active interfaces and their
  1468. // links. The duties of the forwarder are similar to that of a network switch,
  1469. // in that it facilitates multi-hop payments by acting as a central messaging
  1470. // bus. The switch communicates will active links to create, manage, and tear
  1471. // down active onion routed payments. Each active channel is modeled as
  1472. // networked device with metadata such as the available payment bandwidth, and
  1473. // total link capacity.
  1474. //
  1475. // NOTE: This MUST be run as a goroutine.
  1476. func (s *Switch) htlcForwarder() {
  1477. defer s.wg.Done()
  1478. defer func() {
  1479. s.blockEpochStream.Cancel()
  1480. // Remove all links once we've been signalled for shutdown.
  1481. var linksToStop []ChannelLink
  1482. s.indexMtx.Lock()
  1483. for _, link := range s.linkIndex {
  1484. activeLink := s.removeLink(link.ChanID())
  1485. if activeLink == nil {
  1486. log.Errorf("unable to remove ChannelLink(%v) "+
  1487. "on stop", link.ChanID())
  1488. continue
  1489. }
  1490. linksToStop = append(linksToStop, activeLink)
  1491. }
  1492. for _, link := range s.pendingLinkIndex {
  1493. pendingLink := s.removeLink(link.ChanID())
  1494. if pendingLink == nil {
  1495. log.Errorf("unable to remove ChannelLink(%v) "+
  1496. "on stop", link.ChanID())
  1497. continue
  1498. }
  1499. linksToStop = append(linksToStop, pendingLink)
  1500. }
  1501. s.indexMtx.Unlock()
  1502. // Now that all pending and live links have been removed from
  1503. // the forwarding indexes, stop each one before shutting down.
  1504. // We'll shut them down in parallel to make exiting as fast as
  1505. // possible.
  1506. var wg sync.WaitGroup
  1507. for _, link := range linksToStop {
  1508. wg.Add(1)
  1509. go func(l ChannelLink) {
  1510. defer wg.Done()
  1511. l.Stop()
  1512. }(link)
  1513. }
  1514. wg.Wait()
  1515. // Before we exit fully, we'll attempt to flush out any
  1516. // forwarding events that may still be lingering since the last
  1517. // batch flush.
  1518. if err := s.FlushForwardingEvents(); err != nil {
  1519. log.Errorf("unable to flush forwarding events: %v", err)
  1520. }
  1521. }()
  1522. // TODO(roasbeef): cleared vs settled distinction
  1523. var (
  1524. totalNumUpdates uint64
  1525. totalSatSent btcutil.Amount
  1526. totalSatRecv btcutil.Amount
  1527. )
  1528. s.cfg.LogEventTicker.Resume()
  1529. defer s.cfg.LogEventTicker.Stop()
  1530. // Every 15 seconds, we'll flush out the forwarding events that
  1531. // occurred during that period.
  1532. s.cfg.FwdEventTicker.Resume()
  1533. defer s.cfg.FwdEventTicker.Stop()
  1534. defer s.cfg.AckEventTicker.Stop()
  1535. out:
  1536. for {
  1537. // If the set of pending settle/fail entries is non-zero,
  1538. // reinstate the ack ticker so we can batch ack them.
  1539. if len(s.pendingSettleFails) > 0 {
  1540. s.cfg.AckEventTicker.Resume()
  1541. }
  1542. select {
  1543. case blockEpoch, ok := <-s.blockEpochStream.Epochs:
  1544. if !ok {
  1545. break out
  1546. }
  1547. atomic.StoreUint32(&s.bestHeight, uint32(blockEpoch.Height))
  1548. // A local close request has arrived, we'll forward this to the
  1549. // relevant link (if it exists) so the channel can be
  1550. // cooperatively closed (if possible).
  1551. case req := <-s.chanCloseRequests:
  1552. chanID := lnwire.NewChanIDFromOutPoint(*req.ChanPoint)
  1553. s.indexMtx.RLock()
  1554. link, ok := s.linkIndex[chanID]
  1555. if !ok {
  1556. s.indexMtx.RUnlock()
  1557. req.Err <- fmt.Errorf("no peer for channel with "+
  1558. "chan_id=%x", chanID[:])
  1559. continue
  1560. }
  1561. s.indexMtx.RUnlock()
  1562. peerPub := link.PeerPubKey()
  1563. log.Debugf("Requesting local channel close: peer=%v, "+
  1564. "chan_id=%x", link.PeerPubKey(), chanID[:])
  1565. go s.cfg.LocalChannelClose(peerPub[:], req)
  1566. case resolutionMsg := <-s.resolutionMsgs:
  1567. // We'll persist the resolution message to the Switch's
  1568. // resolution store.
  1569. resMsg := resolutionMsg.ResolutionMsg
  1570. err := s.resMsgStore.addResolutionMsg(&resMsg)
  1571. if err != nil {
  1572. // This will only fail if there is a database
  1573. // error or a serialization error. Sending the
  1574. // error prevents the contractcourt from being
  1575. // in a state where it believes the send was
  1576. // successful, when it wasn't.
  1577. log.Errorf("unable to add resolution msg: %v",
  1578. err)
  1579. resolutionMsg.errChan <- err
  1580. continue
  1581. }
  1582. // At this point, the resolution message has been
  1583. // persisted. It is safe to signal success by sending
  1584. // a nil error since the Switch will re-deliver the
  1585. // resolution message on restart.
  1586. resolutionMsg.errChan <- nil
  1587. // Create a htlc packet for this resolution. We do
  1588. // not have some of the information that we'll need
  1589. // for blinded error handling here , so we'll rely on
  1590. // our forwarding logic to fill it in later.
  1591. pkt := &htlcPacket{
  1592. outgoingChanID: resolutionMsg.SourceChan,
  1593. outgoingHTLCID: resolutionMsg.HtlcIndex,
  1594. isResolution: true,
  1595. }
  1596. // Resolution messages will either be cancelling
  1597. // backwards an existing HTLC, or settling a previously
  1598. // outgoing HTLC. Based on this, we'll map the message
  1599. // to the proper htlcPacket.
  1600. if resolutionMsg.Failure != nil {
  1601. pkt.htlc = &lnwire.UpdateFailHTLC{}
  1602. } else {
  1603. pkt.htlc = &lnwire.UpdateFulfillHTLC{
  1604. PaymentPreimage: *resolutionMsg.PreImage,
  1605. }
  1606. }
  1607. log.Infof("Received outside contract resolution, "+
  1608. "mapping to: %v", spew.Sdump(pkt))
  1609. // We don't check the error, as the only failure we can
  1610. // encounter is due to the circuit already being
  1611. // closed. This is fine, as processing this message is
  1612. // meant to be idempotent.
  1613. err = s.handlePacketForward(pkt)
  1614. if err != nil {
  1615. log.Errorf("Unable to forward resolution msg: %v", err)
  1616. }
  1617. // A new packet has arrived for forwarding, we'll interpret the
  1618. // packet concretely, then either forward it along, or
  1619. // interpret a return packet to a locally initialized one.
  1620. case cmd := <-s.htlcPlex:
  1621. cmd.err <- s.handlePacketForward(cmd.pkt)
  1622. // When this time ticks, then it indicates that we should
  1623. // collect all the forwarding events since the last internal,
  1624. // and write them out to our log.
  1625. case <-s.cfg.FwdEventTicker.Ticks():
  1626. s.wg.Add(1)
  1627. go func() {
  1628. defer s.wg.Done()
  1629. if err := s.FlushForwardingEvents(); err != nil {
  1630. log.Errorf("unable to flush "+
  1631. "forwarding events: %v", err)
  1632. }
  1633. }()
  1634. // The log ticker has fired, so we'll calculate some forwarding
  1635. // stats for the last 10 seconds to display within the logs to
  1636. // users.
  1637. case <-s.cfg.LogEventTicker.Ticks():
  1638. // First, we'll collate the current running tally of
  1639. // our forwarding stats.
  1640. prevSatSent := totalSatSent
  1641. prevSatRecv := totalSatRecv
  1642. prevNumUpdates := totalNumUpdates
  1643. var (
  1644. newNumUpdates uint64
  1645. newSatSent btcutil.Amount
  1646. newSatRecv btcutil.Amount
  1647. )
  1648. // Next, we'll run through all the registered links and
  1649. // compute their up-to-date forwarding stats.
  1650. s.indexMtx.RLock()
  1651. for _, link := range s.linkIndex {
  1652. // TODO(roasbeef): when links first registered
  1653. // stats printed.
  1654. updates, sent, recv := link.Stats()
  1655. newNumUpdates += updates
  1656. newSatSent += sent.ToSatoshis()
  1657. newSatRecv += recv.ToSatoshis()
  1658. }
  1659. s.indexMtx.RUnlock()
  1660. var (
  1661. diffNumUpdates uint64
  1662. diffSatSent btcutil.Amount
  1663. diffSatRecv btcutil.Amount
  1664. )
  1665. // If this is the first time we're computing these
  1666. // stats, then the diff is just the new value. We do
  1667. // this in order to avoid integer underflow issues.
  1668. if prevNumUpdates == 0 {
  1669. diffNumUpdates = newNumUpdates
  1670. diffSatSent = newSatSent
  1671. diffSatRecv = newSatRecv
  1672. } else {
  1673. diffNumUpdates = newNumUpdates - prevNumUpdates
  1674. diffSatSent = newSatSent - prevSatSent
  1675. diffSatRecv = newSatRecv - prevSatRecv
  1676. }
  1677. // If the diff of num updates is zero, then we haven't
  1678. // forwarded anything in the last 10 seconds, so we can
  1679. // skip this update.
  1680. if diffNumUpdates == 0 {
  1681. continue
  1682. }
  1683. // If the diff of num updates is negative, then some
  1684. // links may have been unregistered from the switch, so
  1685. // we'll update our stats to only include our registered
  1686. // links.
  1687. if int64(diffNumUpdates) < 0 {
  1688. totalNumUpdates = newNumUpdates
  1689. totalSatSent = newSatSent
  1690. totalSatRecv = newSatRecv
  1691. continue
  1692. }
  1693. // Otherwise, we'll log this diff, then accumulate the
  1694. // new stats into the running total.
  1695. log.Debugf("Sent %d satoshis and received %d satoshis "+
  1696. "in the last 10 seconds (%f tx/sec)",
  1697. diffSatSent, diffSatRecv,
  1698. float64(diffNumUpdates)/10)
  1699. totalNumUpdates += diffNumUpdates
  1700. totalSatSent += diffSatSent
  1701. totalSatRecv += diffSatRecv
  1702. // The ack ticker has fired so if we have any settle/fail entries
  1703. // for a forwarding package to ack, we will do so here in a batch
  1704. // db call.
  1705. case <-s.cfg.AckEventTicker.Ticks():
  1706. // If the current set is empty, pause the ticker.
  1707. if len(s.pendingSettleFails) == 0 {
  1708. s.cfg.AckEventTicker.Pause()
  1709. continue
  1710. }
  1711. // Batch ack the settle/fail entries.
  1712. if err := s.ackSettleFail(s.pendingSettleFails...); err != nil {
  1713. log.Errorf("Unable to ack batch of settle/fails: %v", err)
  1714. continue
  1715. }
  1716. log.Tracef("Acked %d settle fails: %v", len(s.pendingSettleFails),
  1717. newLogClosure(func() string {
  1718. return spew.Sdump(s.pendingSettleFails)
  1719. }))
  1720. // Reset the pendingSettleFails buffer while keeping acquired
  1721. // memory.
  1722. s.pendingSettleFails = s.pendingSettleFails[:0]
  1723. case <-s.quit:
  1724. return
  1725. }
  1726. }
  1727. }
  1728. // Start starts all helper goroutines required for the operation of the switch.
  1729. func (s *Switch) Start() error {
  1730. if !atomic.CompareAndSwapInt32(&s.started, 0, 1) {
  1731. log.Warn("Htlc Switch already started")
  1732. return errors.New("htlc switch already started")
  1733. }
  1734. log.Infof("HTLC Switch starting")
  1735. blockEpochStream, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
  1736. if err != nil {
  1737. return err
  1738. }
  1739. s.blockEpochStream = blockEpochStream
  1740. s.wg.Add(1)
  1741. go s.htlcForwarder()
  1742. if err := s.reforwardResponses(); err != nil {
  1743. s.Stop()
  1744. log.Errorf("unable to reforward responses: %v", err)
  1745. return err
  1746. }
  1747. if err := s.reforwardResolutions(); err != nil {
  1748. // We are already stopping so we can ignore the error.
  1749. _ = s.Stop()
  1750. log.Errorf("unable to reforward resolutions: %v", err)
  1751. return err
  1752. }
  1753. return nil
  1754. }
  1755. // reforwardResolutions fetches the set of resolution messages stored on-disk
  1756. // and reforwards them if their circuits are still open. If the circuits have
  1757. // been deleted, then we will delete the resolution message from the database.
  1758. func (s *Switch) reforwardResolutions() error {
  1759. // Fetch all stored resolution messages, deleting the ones that are
  1760. // resolved.
  1761. resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
  1762. if err != nil {
  1763. return err
  1764. }
  1765. switchPackets := make([]*htlcPacket, 0, len(resMsgs))
  1766. for _, resMsg := range resMsgs {
  1767. // If the open circuit no longer exists, then we can remove the
  1768. // message from the store.
  1769. outKey := CircuitKey{
  1770. ChanID: resMsg.SourceChan,
  1771. HtlcID: resMsg.HtlcIndex,
  1772. }
  1773. if s.circuits.LookupOpenCircuit(outKey) == nil {
  1774. // The open circuit doesn't exist.
  1775. err := s.resMsgStore.deleteResolutionMsg(&outKey)
  1776. if err != nil {
  1777. return err
  1778. }
  1779. continue
  1780. }
  1781. // The circuit is still open, so we can assume that the link or
  1782. // switch (if we are the source) hasn't cleaned it up yet.
  1783. // We rely on our forwarding logic to fill in details that
  1784. // are not currently available to us.
  1785. resPkt := &htlcPacket{
  1786. outgoingChanID: resMsg.SourceChan,
  1787. outgoingHTLCID: resMsg.HtlcIndex,
  1788. isResolution: true,
  1789. }
  1790. if resMsg.Failure != nil {
  1791. resPkt.htlc = &lnwire.UpdateFailHTLC{}
  1792. } else {
  1793. resPkt.htlc = &lnwire.UpdateFulfillHTLC{
  1794. PaymentPreimage: *resMsg.PreImage,
  1795. }
  1796. }
  1797. switchPackets = append(switchPackets, resPkt)
  1798. }
  1799. // We'll now dispatch the set of resolution messages to the proper
  1800. // destination. An error is only encountered here if the switch is
  1801. // shutting down.
  1802. if err := s.ForwardPackets(nil, switchPackets...); err != nil {
  1803. return err
  1804. }
  1805. return nil
  1806. }
  1807. // reforwardResponses for every known, non-pending channel, loads all associated
  1808. // forwarding packages and reforwards any Settle or Fail HTLCs found. This is
  1809. // used to resurrect the switch's mailboxes after a restart. This also runs for
  1810. // waiting close channels since there may be settles or fails that need to be
  1811. // reforwarded before they completely close.
  1812. func (s *Switch) reforwardResponses() error {
  1813. openChannels, err := s.cfg.FetchAllChannels()
  1814. if err != nil {
  1815. return err
  1816. }
  1817. for _, openChannel := range openChannels {
  1818. shortChanID := openChannel.ShortChanID()
  1819. // Locally-initiated payments never need reforwarding.
  1820. if shortChanID == hop.Source {
  1821. continue
  1822. }
  1823. // If the channel is pending, it should have no forwarding
  1824. // packages, and nothing to reforward.
  1825. if openChannel.IsPending {
  1826. continue
  1827. }
  1828. // Channels in open or waiting-close may still have responses in
  1829. // their forwarding packages. We will continue to reattempt
  1830. // forwarding on startup until the channel is fully-closed.
  1831. //
  1832. // Load this channel's forwarding packages, and deliver them to
  1833. // the switch.
  1834. fwdPkgs, err := s.loadChannelFwdPkgs(shortChanID)
  1835. if err != nil {
  1836. log.Errorf("unable to load forwarding "+
  1837. "packages for %v: %v", shortChanID, err)
  1838. return err
  1839. }
  1840. s.reforwardSettleFails(fwdPkgs)
  1841. }
  1842. return nil
  1843. }
  1844. // loadChannelFwdPkgs loads all forwarding packages owned by the `source` short
  1845. // channel identifier.
  1846. func (s *Switch) loadChannelFwdPkgs(source lnwire.ShortChannelID) ([]*channeldb.FwdPkg, error) {
  1847. var fwdPkgs []*channeldb.FwdPkg
  1848. if err := kvdb.View(s.cfg.DB, func(tx kvdb.RTx) error {
  1849. var err error
  1850. fwdPkgs, err = s.cfg.SwitchPackager.LoadChannelFwdPkgs(
  1851. tx, source,
  1852. )
  1853. return err
  1854. }, func() {
  1855. fwdPkgs = nil
  1856. }); err != nil {
  1857. return nil, err
  1858. }
  1859. return fwdPkgs, nil
  1860. }
  1861. // reforwardSettleFails parses the Settle and Fail HTLCs from the list of
  1862. // forwarding packages, and reforwards those that have not been acknowledged.
  1863. // This is intended to occur on startup, in order to recover the switch's
  1864. // mailboxes, and to ensure that responses can be propagated in case the
  1865. // outgoing link never comes back online.
  1866. //
  1867. // NOTE: This should mimic the behavior processRemoteSettleFails.
  1868. func (s *Switch) reforwardSettleFails(fwdPkgs []*channeldb.FwdPkg) {
  1869. for _, fwdPkg := range fwdPkgs {
  1870. settleFails, err := lnwallet.PayDescsFromRemoteLogUpdates(
  1871. fwdPkg.Source, fwdPkg.Height, fwdPkg.SettleFails,
  1872. )
  1873. if err != nil {
  1874. log.Errorf("Unable to process remote log updates: %v",
  1875. err)
  1876. continue
  1877. }
  1878. switchPackets := make([]*htlcPacket, 0, len(settleFails))
  1879. for i, pd := range settleFails {
  1880. // Skip any settles or fails that have already been
  1881. // acknowledged by the incoming link that originated the
  1882. // forwarded Add.
  1883. if fwdPkg.SettleFailFilter.Contains(uint16(i)) {
  1884. continue
  1885. }
  1886. switch pd.EntryType {
  1887. // A settle for an HTLC we previously forwarded HTLC has
  1888. // been received. So we'll forward the HTLC to the
  1889. // switch which will handle propagating the settle to
  1890. // the prior hop.
  1891. case lnwallet.Settle:
  1892. settlePacket := &htlcPacket{
  1893. outgoingChanID: fwdPkg.Source,
  1894. outgoingHTLCID: pd.ParentIndex,
  1895. destRef: pd.DestRef,
  1896. htlc: &lnwire.UpdateFulfillHTLC{
  1897. PaymentPreimage: pd.RPreimage,
  1898. },
  1899. }
  1900. // Add the packet to the batch to be forwarded, and
  1901. // notify the overflow queue that a spare spot has been
  1902. // freed up within the commitment state.
  1903. switchPackets = append(switchPackets, settlePacket)
  1904. // A failureCode message for a previously forwarded HTLC has been
  1905. // received. As a result a new slot will be freed up in our
  1906. // commitment state, so we'll forward this to the switch so the
  1907. // backwards undo can continue.
  1908. case lnwallet.Fail:
  1909. // Fetch the reason the HTLC was canceled so
  1910. // we can continue to propagate it. This
  1911. // failure originated from another node, so
  1912. // the linkFailure field is not set on this
  1913. // packet. We rely on the link to fill in
  1914. // additional circuit information for us.
  1915. failPacket := &htlcPacket{
  1916. outgoingChanID: fwdPkg.Source,
  1917. outgoingHTLCID: pd.ParentIndex,
  1918. destRef: pd.DestRef,
  1919. htlc: &lnwire.UpdateFailHTLC{
  1920. Reason: lnwire.OpaqueReason(pd.FailReason),
  1921. },
  1922. }
  1923. // Add the packet to the batch to be forwarded, and
  1924. // notify the overflow queue that a spare spot has been
  1925. // freed up within the commitment state.
  1926. switchPackets = append(switchPackets, failPacket)
  1927. }
  1928. }
  1929. // Since this send isn't tied to a specific link, we pass a nil
  1930. // link quit channel, meaning the send will fail only if the
  1931. // switch receives a shutdown request.
  1932. if err := s.ForwardPackets(nil, switchPackets...); err != nil {
  1933. log.Errorf("Unhandled error while reforwarding packets "+
  1934. "settle/fail over htlcswitch: %v", err)
  1935. }
  1936. }
  1937. }
  1938. // Stop gracefully stops all active helper goroutines, then waits until they've
  1939. // exited.
  1940. func (s *Switch) Stop() error {
  1941. if !atomic.CompareAndSwapInt32(&s.shutdown, 0, 1) {
  1942. log.Warn("Htlc Switch already stopped")
  1943. return errors.New("htlc switch already shutdown")
  1944. }
  1945. log.Info("HTLC Switch shutting down...")
  1946. defer log.Debug("HTLC Switch shutdown complete")
  1947. close(s.quit)
  1948. s.wg.Wait()
  1949. // Wait until all active goroutines have finished exiting before
  1950. // stopping the mailboxes, otherwise the mailbox map could still be
  1951. // accessed and modified.
  1952. s.mailOrchestrator.Stop()
  1953. return nil
  1954. }
  1955. // CreateAndAddLink will create a link and then add it to the internal maps
  1956. // when given a ChannelLinkConfig and LightningChannel.
  1957. func (s *Switch) CreateAndAddLink(linkCfg ChannelLinkConfig,
  1958. lnChan *lnwallet.LightningChannel) error {
  1959. link := NewChannelLink(linkCfg, lnChan)
  1960. return s.AddLink(link)
  1961. }
  1962. // AddLink is used to initiate the handling of the add link command. The
  1963. // request will be propagated and handled in the main goroutine.
  1964. func (s *Switch) AddLink(link ChannelLink) error {
  1965. s.indexMtx.Lock()
  1966. defer s.indexMtx.Unlock()
  1967. chanID := link.ChanID()
  1968. // First, ensure that this link is not already active in the switch.
  1969. _, err := s.getLink(chanID)
  1970. if err == nil {
  1971. return fmt.Errorf("unable to add ChannelLink(%v), already "+
  1972. "active", chanID)
  1973. }
  1974. // Get and attach the mailbox for this link, which buffers packets in
  1975. // case there packets that we tried to deliver while this link was
  1976. // offline.
  1977. shortChanID := link.ShortChanID()
  1978. mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID, shortChanID)
  1979. link.AttachMailBox(mailbox)
  1980. // Attach the Switch's failAliasUpdate function to the link.
  1981. link.attachFailAliasUpdate(s.failAliasUpdate)
  1982. if err := link.Start(); err != nil {
  1983. log.Errorf("AddLink failed to start link with chanID=%v: %v",
  1984. chanID, err)
  1985. s.removeLink(chanID)
  1986. return err
  1987. }
  1988. if shortChanID == hop.Source {
  1989. log.Infof("Adding pending link chan_id=%v, short_chan_id=%v",
  1990. chanID, shortChanID)
  1991. s.pendingLinkIndex[chanID] = link
  1992. } else {
  1993. log.Infof("Adding live link chan_id=%v, short_chan_id=%v",
  1994. chanID, shortChanID)
  1995. s.addLiveLink(link)
  1996. s.mailOrchestrator.BindLiveShortChanID(
  1997. mailbox, chanID, shortChanID,
  1998. )
  1999. }
  2000. return nil
  2001. }
  2002. // addLiveLink adds a link to all associated forwarding index, this makes it a
  2003. // candidate for forwarding HTLCs.
  2004. func (s *Switch) addLiveLink(link ChannelLink) {
  2005. linkScid := link.ShortChanID()
  2006. // We'll add the link to the linkIndex which lets us quickly
  2007. // look up a channel when we need to close or register it, and
  2008. // the forwarding index which'll be used when forwarding HTLC's
  2009. // in the multi-hop setting.
  2010. s.linkIndex[link.ChanID()] = link
  2011. s.forwardingIndex[linkScid] = link
  2012. // Next we'll add the link to the interface index so we can
  2013. // quickly look up all the channels for a particular node.
  2014. peerPub := link.PeerPubKey()
  2015. if _, ok := s.interfaceIndex[peerPub]; !ok {
  2016. s.interfaceIndex[peerPub] = make(map[lnwire.ChannelID]ChannelLink)
  2017. }
  2018. s.interfaceIndex[peerPub][link.ChanID()] = link
  2019. aliases := link.getAliases()
  2020. if link.isZeroConf() {
  2021. if link.zeroConfConfirmed() {
  2022. // Since the zero-conf channel has confirmed, we can
  2023. // populate the aliasToReal mapping.
  2024. confirmedScid := link.confirmedScid()
  2025. for _, alias := range aliases {
  2026. s.aliasToReal[alias] = confirmedScid
  2027. }
  2028. // Add the confirmed SCID as a key in the baseIndex.
  2029. s.baseIndex[confirmedScid] = linkScid
  2030. }
  2031. // Now we populate the baseIndex which will be used to fetch
  2032. // the link given any of the channel's alias SCIDs or the real
  2033. // SCID. The link's SCID is an alias, so we don't need to
  2034. // special-case it like the option-scid-alias feature-bit case
  2035. // further down.
  2036. for _, alias := range aliases {
  2037. s.baseIndex[alias] = linkScid
  2038. }
  2039. } else if link.negotiatedAliasFeature() {
  2040. // The link's SCID is the confirmed SCID for non-zero-conf
  2041. // option-scid-alias feature bit channels.
  2042. for _, alias := range aliases {
  2043. s.aliasToReal[alias] = linkScid
  2044. s.baseIndex[alias] = linkScid
  2045. }
  2046. // Since the link's SCID is confirmed, it was not included in
  2047. // the baseIndex above as a key. Add it now.
  2048. s.baseIndex[linkScid] = linkScid
  2049. }
  2050. }
  2051. // GetLink is used to initiate the handling of the get link command. The
  2052. // request will be propagated/handled to/in the main goroutine.
  2053. func (s *Switch) GetLink(chanID lnwire.ChannelID) (ChannelUpdateHandler,
  2054. error) {
  2055. s.indexMtx.RLock()
  2056. defer s.indexMtx.RUnlock()
  2057. return s.getLink(chanID)
  2058. }
  2059. // getLink returns the link stored in either the pending index or the live
  2060. // lindex.
  2061. func (s *Switch) getLink(chanID lnwire.ChannelID) (ChannelLink, error) {
  2062. link, ok := s.linkIndex[chanID]
  2063. if !ok {
  2064. link, ok = s.pendingLinkIndex[chanID]
  2065. if !ok {
  2066. return nil, ErrChannelLinkNotFound
  2067. }
  2068. }
  2069. return link, nil
  2070. }
  2071. // GetLinkByShortID attempts to return the link which possesses the target short
  2072. // channel ID.
  2073. func (s *Switch) GetLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink,
  2074. error) {
  2075. s.indexMtx.RLock()
  2076. defer s.indexMtx.RUnlock()
  2077. link, err := s.getLinkByShortID(chanID)
  2078. if err != nil {
  2079. // If we failed to find the link under the passed-in SCID, we
  2080. // consult the Switch's baseIndex map to see if the confirmed
  2081. // SCID was used for a zero-conf channel.
  2082. aliasID, ok := s.baseIndex[chanID]
  2083. if !ok {
  2084. return nil, err
  2085. }
  2086. // An alias was found, use it to lookup if a link exists.
  2087. return s.getLinkByShortID(aliasID)
  2088. }
  2089. return link, nil
  2090. }
  2091. // getLinkByShortID attempts to return the link which possesses the target
  2092. // short channel ID.
  2093. //
  2094. // NOTE: This MUST be called with the indexMtx held.
  2095. func (s *Switch) getLinkByShortID(chanID lnwire.ShortChannelID) (ChannelLink, error) {
  2096. link, ok := s.forwardingIndex[chanID]
  2097. if !ok {
  2098. return nil, ErrChannelLinkNotFound
  2099. }
  2100. return link, nil
  2101. }
  2102. // getLinkByMapping attempts to fetch the link via the htlcPacket's
  2103. // outgoingChanID, possibly using a mapping. If it finds the link via mapping,
  2104. // the outgoingChanID will be changed so that an error can be properly
  2105. // attributed when looping over linkErrs in handlePacketForward.
  2106. //
  2107. // * If the outgoingChanID is an alias, we'll fetch the link regardless if it's
  2108. // public or not.
  2109. //
  2110. // * If the outgoingChanID is a confirmed SCID, we'll need to do more checks.
  2111. // - If there is no entry found in baseIndex, fetch the link. This channel
  2112. // did not have the option-scid-alias feature negotiated (which includes
  2113. // zero-conf and option-scid-alias channel-types).
  2114. // - If there is an entry found, fetch the link from forwardingIndex and
  2115. // fail if this is a private link.
  2116. //
  2117. // NOTE: This MUST be called with the indexMtx read lock held.
  2118. func (s *Switch) getLinkByMapping(pkt *htlcPacket) (ChannelLink, error) {
  2119. // Determine if this ShortChannelID is an alias or a confirmed SCID.
  2120. chanID := pkt.outgoingChanID
  2121. aliasID := s.cfg.IsAlias(chanID)
  2122. // Set the originalOutgoingChanID so the proper channel_update can be
  2123. // sent back if the option-scid-alias feature bit was negotiated.
  2124. pkt.originalOutgoingChanID = chanID
  2125. if aliasID {
  2126. // Since outgoingChanID is an alias, we'll fetch the link via
  2127. // baseIndex.
  2128. baseScid, ok := s.baseIndex[chanID]
  2129. if !ok {
  2130. // No mapping exists, bail.
  2131. return nil, ErrChannelLinkNotFound
  2132. }
  2133. // A mapping exists, so use baseScid to find the link in the
  2134. // forwardingIndex.
  2135. link, ok := s.forwardingIndex[baseScid]
  2136. if !ok {
  2137. // Link not found, bail.
  2138. return nil, ErrChannelLinkNotFound
  2139. }
  2140. // Change the packet's outgoingChanID field so that errors are
  2141. // properly attributed.
  2142. pkt.outgoingChanID = baseScid
  2143. // Return the link without checking if it's private or not.
  2144. return link, nil
  2145. }
  2146. // The outgoingChanID is a confirmed SCID. Attempt to fetch the base
  2147. // SCID from baseIndex.
  2148. baseScid, ok := s.baseIndex[chanID]
  2149. if !ok {
  2150. // outgoingChanID is not a key in base index meaning this
  2151. // channel did not have the option-scid-alias feature bit
  2152. // negotiated. We'll fetch the link and return it.
  2153. link, ok := s.forwardingIndex[chanID]
  2154. if !ok {
  2155. // The link wasn't found, bail out.
  2156. return nil, ErrChannelLinkNotFound
  2157. }
  2158. return link, nil
  2159. }
  2160. // Fetch the link whose internal SCID is baseScid.
  2161. link, ok := s.forwardingIndex[baseScid]
  2162. if !ok {
  2163. // Link wasn't found, bail out.
  2164. return nil, ErrChannelLinkNotFound
  2165. }
  2166. // If the link is unadvertised, we fail since the real SCID was used to
  2167. // forward over it and this is a channel where the option-scid-alias
  2168. // feature bit was negotiated.
  2169. if link.IsUnadvertised() {
  2170. return nil, ErrChannelLinkNotFound
  2171. }
  2172. // The link is public so the confirmed SCID can be used to forward over
  2173. // it. We'll also replace pkt's outgoingChanID field so errors can
  2174. // properly be attributed in the calling function.
  2175. pkt.outgoingChanID = baseScid
  2176. return link, nil
  2177. }
  2178. // HasActiveLink returns true if the given channel ID has a link in the link
  2179. // index AND the link is eligible to forward.
  2180. func (s *Switch) HasActiveLink(chanID lnwire.ChannelID) bool {
  2181. s.indexMtx.RLock()
  2182. defer s.indexMtx.RUnlock()
  2183. if link, ok := s.linkIndex[chanID]; ok {
  2184. return link.EligibleToForward()
  2185. }
  2186. return false
  2187. }
  2188. // RemoveLink purges the switch of any link associated with chanID. If a pending
  2189. // or active link is not found, this method does nothing. Otherwise, the method
  2190. // returns after the link has been completely shutdown.
  2191. func (s *Switch) RemoveLink(chanID lnwire.ChannelID) {
  2192. s.indexMtx.Lock()
  2193. link, err := s.getLink(chanID)
  2194. if err != nil {
  2195. // If err is non-nil, this means that link is also nil. The
  2196. // link variable cannot be nil without err being non-nil.
  2197. s.indexMtx.Unlock()
  2198. log.Tracef("Unable to remove link for ChannelID(%v): %v",
  2199. chanID, err)
  2200. return
  2201. }
  2202. // Check if the link is already stopping and grab the stop chan if it
  2203. // is.
  2204. stopChan, ok := s.linkStopIndex[chanID]
  2205. if !ok {
  2206. // If the link is non-nil, it is not currently stopping, so
  2207. // we'll add a stop chan to the linkStopIndex.
  2208. stopChan = make(chan struct{})
  2209. s.linkStopIndex[chanID] = stopChan
  2210. }
  2211. s.indexMtx.Unlock()
  2212. if ok {
  2213. // If the stop chan exists, we will wait for it to be closed.
  2214. // Once it is closed, we will exit.
  2215. select {
  2216. case <-stopChan:
  2217. return
  2218. case <-s.quit:
  2219. return
  2220. }
  2221. }
  2222. // Stop the link before removing it from the maps.
  2223. link.Stop()
  2224. s.indexMtx.Lock()
  2225. _ = s.removeLink(chanID)
  2226. // Close stopChan and remove this link from the linkStopIndex.
  2227. // Deleting from the index and removing from the link must be done
  2228. // in the same block while the mutex is held.
  2229. close(stopChan)
  2230. delete(s.linkStopIndex, chanID)
  2231. s.indexMtx.Unlock()
  2232. }
  2233. // removeLink is used to remove and stop the channel link.
  2234. //
  2235. // NOTE: This MUST be called with the indexMtx held.
  2236. func (s *Switch) removeLink(chanID lnwire.ChannelID) ChannelLink {
  2237. log.Infof("Removing channel link with ChannelID(%v)", chanID)
  2238. link, err := s.getLink(chanID)
  2239. if err != nil {
  2240. return nil
  2241. }
  2242. // Remove the channel from live link indexes.
  2243. delete(s.pendingLinkIndex, link.ChanID())
  2244. delete(s.linkIndex, link.ChanID())
  2245. delete(s.forwardingIndex, link.ShortChanID())
  2246. // If the link has been added to the peer index, then we'll move to
  2247. // delete the entry within the index.
  2248. peerPub := link.PeerPubKey()
  2249. if peerIndex, ok := s.interfaceIndex[peerPub]; ok {
  2250. delete(peerIndex, link.ChanID())
  2251. // If after deletion, there are no longer any links, then we'll
  2252. // remove the interface map all together.
  2253. if len(peerIndex) == 0 {
  2254. delete(s.interfaceIndex, peerPub)
  2255. }
  2256. }
  2257. return link
  2258. }
  2259. // UpdateShortChanID locates the link with the passed-in chanID and updates the
  2260. // underlying channel state. This is only used in zero-conf channels to allow
  2261. // the confirmed SCID to be updated.
  2262. func (s *Switch) UpdateShortChanID(chanID lnwire.ChannelID) error {
  2263. s.indexMtx.Lock()
  2264. defer s.indexMtx.Unlock()
  2265. // Locate the target link in the link index. If no such link exists,
  2266. // then we will ignore the request.
  2267. link, ok := s.linkIndex[chanID]
  2268. if !ok {
  2269. return fmt.Errorf("link %v not found", chanID)
  2270. }
  2271. // Try to update the link's underlying channel state, returning early
  2272. // if this update failed.
  2273. _, err := link.UpdateShortChanID()
  2274. if err != nil {
  2275. return err
  2276. }
  2277. // Since the zero-conf channel is confirmed, we should populate the
  2278. // aliasToReal map and update the baseIndex.
  2279. aliases := link.getAliases()
  2280. confirmedScid := link.confirmedScid()
  2281. for _, alias := range aliases {
  2282. s.aliasToReal[alias] = confirmedScid
  2283. }
  2284. s.baseIndex[confirmedScid] = link.ShortChanID()
  2285. return nil
  2286. }
  2287. // GetLinksByInterface fetches all the links connected to a particular node
  2288. // identified by the serialized compressed form of its public key.
  2289. func (s *Switch) GetLinksByInterface(hop [33]byte) ([]ChannelUpdateHandler,
  2290. error) {
  2291. s.indexMtx.RLock()
  2292. defer s.indexMtx.RUnlock()
  2293. var handlers []ChannelUpdateHandler
  2294. links, err := s.getLinks(hop)
  2295. if err != nil {
  2296. return nil, err
  2297. }
  2298. // Range over the returned []ChannelLink to convert them into
  2299. // []ChannelUpdateHandler.
  2300. for _, link := range links {
  2301. handlers = append(handlers, link)
  2302. }
  2303. return handlers, nil
  2304. }
  2305. // getLinks is function which returns the channel links of the peer by hop
  2306. // destination id.
  2307. //
  2308. // NOTE: This MUST be called with the indexMtx held.
  2309. func (s *Switch) getLinks(destination [33]byte) ([]ChannelLink, error) {
  2310. links, ok := s.interfaceIndex[destination]
  2311. if !ok {
  2312. return nil, ErrNoLinksFound
  2313. }
  2314. channelLinks := make([]ChannelLink, 0, len(links))
  2315. for _, link := range links {
  2316. channelLinks = append(channelLinks, link)
  2317. }
  2318. return channelLinks, nil
  2319. }
  2320. // CircuitModifier returns a reference to subset of the interfaces provided by
  2321. // the circuit map, to allow links to open and close circuits.
  2322. func (s *Switch) CircuitModifier() CircuitModifier {
  2323. return s.circuits
  2324. }
  2325. // CircuitLookup returns a reference to subset of the interfaces provided by the
  2326. // circuit map, to allow looking up circuits.
  2327. func (s *Switch) CircuitLookup() CircuitLookup {
  2328. return s.circuits
  2329. }
  2330. // commitCircuits persistently adds a circuit to the switch's circuit map.
  2331. func (s *Switch) commitCircuits(circuits ...*PaymentCircuit) (
  2332. *CircuitFwdActions, error) {
  2333. return s.circuits.CommitCircuits(circuits...)
  2334. }
  2335. // FlushForwardingEvents flushes out the set of pending forwarding events to
  2336. // the persistent log. This will be used by the switch to periodically flush
  2337. // out the set of forwarding events to disk. External callers can also use this
  2338. // method to ensure all data is flushed to dis before querying the log.
  2339. func (s *Switch) FlushForwardingEvents() error {
  2340. // First, we'll obtain a copy of the current set of pending forwarding
  2341. // events.
  2342. s.fwdEventMtx.Lock()
  2343. // If we won't have any forwarding events, then we can exit early.
  2344. if len(s.pendingFwdingEvents) == 0 {
  2345. s.fwdEventMtx.Unlock()
  2346. return nil
  2347. }
  2348. events := make([]channeldb.ForwardingEvent, len(s.pendingFwdingEvents))
  2349. copy(events[:], s.pendingFwdingEvents[:])
  2350. // With the copy obtained, we can now clear out the header pointer of
  2351. // the current slice. This way, we can re-use the underlying storage
  2352. // allocated for the slice.
  2353. s.pendingFwdingEvents = s.pendingFwdingEvents[:0]
  2354. s.fwdEventMtx.Unlock()
  2355. // Finally, we'll write out the copied events to the persistent
  2356. // forwarding log.
  2357. return s.cfg.FwdingLog.AddForwardingEvents(events)
  2358. }
  2359. // BestHeight returns the best height known to the switch.
  2360. func (s *Switch) BestHeight() uint32 {
  2361. return atomic.LoadUint32(&s.bestHeight)
  2362. }
  2363. // evaluateDustThreshold takes in a ChannelLink, HTLC amount, and a boolean to
  2364. // determine whether the default dust threshold has been exceeded. This
  2365. // heuristic takes into account the trimmed-to-dust mechanism. The sum of the
  2366. // commitment's dust with the mailbox's dust with the amount is checked against
  2367. // the default threshold. If incoming is true, then the amount is not included
  2368. // in the sum as it was already included in the commitment's dust. A boolean is
  2369. // returned telling the caller whether the HTLC should be failed back.
  2370. func (s *Switch) evaluateDustThreshold(link ChannelLink,
  2371. amount lnwire.MilliSatoshi, incoming bool) bool {
  2372. // Retrieve the link's current commitment feerate and dustClosure.
  2373. feeRate := link.getFeeRate()
  2374. isDust := link.getDustClosure()
  2375. // Evaluate if the HTLC is dust on either sides' commitment.
  2376. isLocalDust := isDust(feeRate, incoming, true, amount.ToSatoshis())
  2377. isRemoteDust := isDust(feeRate, incoming, false, amount.ToSatoshis())
  2378. if !(isLocalDust || isRemoteDust) {
  2379. // If the HTLC is not dust on either commitment, it's fine to
  2380. // forward.
  2381. return false
  2382. }
  2383. // Fetch the dust sums currently in the mailbox for this link.
  2384. cid := link.ChanID()
  2385. sid := link.ShortChanID()
  2386. mailbox := s.mailOrchestrator.GetOrCreateMailBox(cid, sid)
  2387. localMailDust, remoteMailDust := mailbox.DustPackets()
  2388. // If the htlc is dust on the local commitment, we'll obtain the dust
  2389. // sum for it.
  2390. if isLocalDust {
  2391. localSum := link.getDustSum(false)
  2392. localSum += localMailDust
  2393. // Optionally include the HTLC amount only for outgoing
  2394. // HTLCs.
  2395. if !incoming {
  2396. localSum += amount
  2397. }
  2398. // Finally check against the defined dust threshold.
  2399. if localSum > s.cfg.DustThreshold {
  2400. return true
  2401. }
  2402. }
  2403. // Also check if the htlc is dust on the remote commitment, if we've
  2404. // reached this point.
  2405. if isRemoteDust {
  2406. remoteSum := link.getDustSum(true)
  2407. remoteSum += remoteMailDust
  2408. // Optionally include the HTLC amount only for outgoing
  2409. // HTLCs.
  2410. if !incoming {
  2411. remoteSum += amount
  2412. }
  2413. // Finally check against the defined dust threshold.
  2414. if remoteSum > s.cfg.DustThreshold {
  2415. return true
  2416. }
  2417. }
  2418. // If we reached this point, this HTLC is fine to forward.
  2419. return false
  2420. }
  2421. // failMailboxUpdate is passed to the mailbox orchestrator which in turn passes
  2422. // it to individual mailboxes. It allows the mailboxes to construct a
  2423. // FailureMessage when failing back HTLC's due to expiry and may include an
  2424. // alias in the ShortChannelID field. The outgoingScid is the SCID originally
  2425. // used in the onion. The mailboxScid is the SCID that the mailbox and link
  2426. // use. The mailboxScid is only used in the non-alias case, so it is always
  2427. // the confirmed SCID.
  2428. func (s *Switch) failMailboxUpdate(outgoingScid,
  2429. mailboxScid lnwire.ShortChannelID) lnwire.FailureMessage {
  2430. // Try to use the failAliasUpdate function in case this is a channel
  2431. // that uses aliases. If it returns nil, we'll fallback to the original
  2432. // pre-alias behavior.
  2433. update := s.failAliasUpdate(outgoingScid, false)
  2434. if update == nil {
  2435. // Execute the fallback behavior.
  2436. var err error
  2437. update, err = s.cfg.FetchLastChannelUpdate(mailboxScid)
  2438. if err != nil {
  2439. return &lnwire.FailTemporaryNodeFailure{}
  2440. }
  2441. }
  2442. return lnwire.NewTemporaryChannelFailure(update)
  2443. }
  2444. // failAliasUpdate prepares a ChannelUpdate for a failed incoming or outgoing
  2445. // HTLC on a channel where the option-scid-alias feature bit was negotiated. If
  2446. // the associated channel is not one of these, this function will return nil
  2447. // and the caller is expected to handle this properly. In this case, a return
  2448. // to the original non-alias behavior is expected.
  2449. func (s *Switch) failAliasUpdate(scid lnwire.ShortChannelID,
  2450. incoming bool) *lnwire.ChannelUpdate {
  2451. // This function does not defer the unlocking because of the database
  2452. // lookups for ChannelUpdate.
  2453. s.indexMtx.RLock()
  2454. if s.cfg.IsAlias(scid) {
  2455. // The alias SCID was used. In the incoming case this means
  2456. // the channel is zero-conf as the link sets the scid. In the
  2457. // outgoing case, the sender set the scid to use and may be
  2458. // either the alias or the confirmed one, if it exists.
  2459. realScid, ok := s.aliasToReal[scid]
  2460. if !ok {
  2461. // The real, confirmed SCID does not exist yet. Find
  2462. // the "base" SCID that the link uses via the
  2463. // baseIndex. If we can't find it, return nil. This
  2464. // means the channel is zero-conf.
  2465. baseScid, ok := s.baseIndex[scid]
  2466. s.indexMtx.RUnlock()
  2467. if !ok {
  2468. return nil
  2469. }
  2470. update, err := s.cfg.FetchLastChannelUpdate(baseScid)
  2471. if err != nil {
  2472. return nil
  2473. }
  2474. // Replace the baseScid with the passed-in alias.
  2475. update.ShortChannelID = scid
  2476. sig, err := s.cfg.SignAliasUpdate(update)
  2477. if err != nil {
  2478. return nil
  2479. }
  2480. update.Signature, err = lnwire.NewSigFromSignature(sig)
  2481. if err != nil {
  2482. return nil
  2483. }
  2484. return update
  2485. }
  2486. s.indexMtx.RUnlock()
  2487. // Fetch the SCID via the confirmed SCID and replace it with
  2488. // the alias.
  2489. update, err := s.cfg.FetchLastChannelUpdate(realScid)
  2490. if err != nil {
  2491. return nil
  2492. }
  2493. // In the incoming case, we want to ensure that we don't leak
  2494. // the UTXO in case the channel is private. In the outgoing
  2495. // case, since the alias was used, we do the same thing.
  2496. update.ShortChannelID = scid
  2497. sig, err := s.cfg.SignAliasUpdate(update)
  2498. if err != nil {
  2499. return nil
  2500. }
  2501. update.Signature, err = lnwire.NewSigFromSignature(sig)
  2502. if err != nil {
  2503. return nil
  2504. }
  2505. return update
  2506. }
  2507. // If the confirmed SCID is not in baseIndex, this is not an
  2508. // option-scid-alias or zero-conf channel.
  2509. baseScid, ok := s.baseIndex[scid]
  2510. if !ok {
  2511. s.indexMtx.RUnlock()
  2512. return nil
  2513. }
  2514. // Fetch the link so we can get an alias to use in the ShortChannelID
  2515. // of the ChannelUpdate.
  2516. link, ok := s.forwardingIndex[baseScid]
  2517. s.indexMtx.RUnlock()
  2518. if !ok {
  2519. // This should never happen, but if it does for some reason,
  2520. // fallback to the old behavior.
  2521. return nil
  2522. }
  2523. aliases := link.getAliases()
  2524. if len(aliases) == 0 {
  2525. // This should never happen, but if it does, fallback.
  2526. return nil
  2527. }
  2528. // Fetch the ChannelUpdate via the real, confirmed SCID.
  2529. update, err := s.cfg.FetchLastChannelUpdate(scid)
  2530. if err != nil {
  2531. return nil
  2532. }
  2533. // The incoming case will replace the ShortChannelID in the retrieved
  2534. // ChannelUpdate with the alias to ensure no privacy leak occurs. This
  2535. // would happen if a private non-zero-conf option-scid-alias
  2536. // feature-bit channel leaked its UTXO here rather than supplying an
  2537. // alias. In the outgoing case, the confirmed SCID was actually used
  2538. // for forwarding in the onion, so no replacement is necessary as the
  2539. // sender knows the scid.
  2540. if incoming {
  2541. // We will replace and sign the update with the first alias.
  2542. // Since this happens on the incoming side, it's not actually
  2543. // possible to know what the sender used in the onion.
  2544. update.ShortChannelID = aliases[0]
  2545. sig, err := s.cfg.SignAliasUpdate(update)
  2546. if err != nil {
  2547. return nil
  2548. }
  2549. update.Signature, err = lnwire.NewSigFromSignature(sig)
  2550. if err != nil {
  2551. return nil
  2552. }
  2553. }
  2554. return update
  2555. }
  2556. // AddAliasForLink instructs the Switch to update its in-memory maps to reflect
  2557. // that a link has a new alias.
  2558. func (s *Switch) AddAliasForLink(chanID lnwire.ChannelID,
  2559. alias lnwire.ShortChannelID) error {
  2560. // Fetch the link so that we can update the underlying channel's set of
  2561. // aliases.
  2562. s.indexMtx.RLock()
  2563. link, err := s.getLink(chanID)
  2564. s.indexMtx.RUnlock()
  2565. if err != nil {
  2566. return err
  2567. }
  2568. // If the link is a channel where the option-scid-alias feature bit was
  2569. // not negotiated, we'll return an error.
  2570. if !link.negotiatedAliasFeature() {
  2571. return fmt.Errorf("attempted to update non-alias channel")
  2572. }
  2573. linkScid := link.ShortChanID()
  2574. // We'll update the maps so the Switch includes this alias in its
  2575. // forwarding decisions.
  2576. if link.isZeroConf() {
  2577. if link.zeroConfConfirmed() {
  2578. // If the channel has confirmed on-chain, we'll
  2579. // add this alias to the aliasToReal map.
  2580. confirmedScid := link.confirmedScid()
  2581. s.aliasToReal[alias] = confirmedScid
  2582. }
  2583. // Add this alias to the baseIndex mapping.
  2584. s.baseIndex[alias] = linkScid
  2585. } else if link.negotiatedAliasFeature() {
  2586. // The channel is confirmed, so we'll populate the aliasToReal
  2587. // and baseIndex maps.
  2588. s.aliasToReal[alias] = linkScid
  2589. s.baseIndex[alias] = linkScid
  2590. }
  2591. return nil
  2592. }