manager.go 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210
  1. package funding
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/btcsuite/btcd/blockchain"
  11. "github.com/btcsuite/btcd/btcec/v2"
  12. "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  13. "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
  14. "github.com/btcsuite/btcd/btcutil"
  15. "github.com/btcsuite/btcd/chaincfg/chainhash"
  16. "github.com/btcsuite/btcd/txscript"
  17. "github.com/btcsuite/btcd/wire"
  18. "github.com/davecgh/go-spew/spew"
  19. "github.com/go-errors/errors"
  20. "github.com/lightningnetwork/lnd/chainntnfs"
  21. "github.com/lightningnetwork/lnd/chanacceptor"
  22. "github.com/lightningnetwork/lnd/channeldb"
  23. "github.com/lightningnetwork/lnd/channeldb/models"
  24. "github.com/lightningnetwork/lnd/discovery"
  25. "github.com/lightningnetwork/lnd/fn"
  26. "github.com/lightningnetwork/lnd/graph"
  27. "github.com/lightningnetwork/lnd/input"
  28. "github.com/lightningnetwork/lnd/keychain"
  29. "github.com/lightningnetwork/lnd/labels"
  30. "github.com/lightningnetwork/lnd/lnpeer"
  31. "github.com/lightningnetwork/lnd/lnrpc"
  32. "github.com/lightningnetwork/lnd/lnutils"
  33. "github.com/lightningnetwork/lnd/lnwallet"
  34. "github.com/lightningnetwork/lnd/lnwallet/chainfee"
  35. "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
  36. "github.com/lightningnetwork/lnd/lnwire"
  37. "golang.org/x/crypto/salsa20"
  38. )
  39. var (
  40. // byteOrder defines the endian-ness we use for encoding to and from
  41. // buffers.
  42. byteOrder = binary.BigEndian
  43. // checkPeerChannelReadyInterval is used when we are waiting for the
  44. // peer to send us ChannelReady. We will check every 1 second to see
  45. // if the message is received.
  46. //
  47. // NOTE: for itest, this value is changed to 10ms.
  48. checkPeerChannelReadyInterval = 1 * time.Second
  49. // errNoLocalNonce is returned when a local nonce is not found in the
  50. // expected TLV.
  51. errNoLocalNonce = fmt.Errorf("local nonce not found")
  52. // errNoPartialSig is returned when a partial sig is not found in the
  53. // expected TLV.
  54. errNoPartialSig = fmt.Errorf("partial sig not found")
  55. )
  56. // WriteOutpoint writes an outpoint to an io.Writer. This is not the same as
  57. // the channeldb variant as this uses WriteVarBytes for the Hash.
  58. func WriteOutpoint(w io.Writer, o *wire.OutPoint) error {
  59. scratch := make([]byte, 4)
  60. if err := wire.WriteVarBytes(w, 0, o.Hash[:]); err != nil {
  61. return err
  62. }
  63. byteOrder.PutUint32(scratch, o.Index)
  64. _, err := w.Write(scratch)
  65. return err
  66. }
  67. const (
  68. // MinBtcRemoteDelay is the minimum CSV delay we will require the remote
  69. // to use for its commitment transaction.
  70. MinBtcRemoteDelay uint16 = 144
  71. // MaxBtcRemoteDelay is the maximum CSV delay we will require the remote
  72. // to use for its commitment transaction.
  73. MaxBtcRemoteDelay uint16 = 2016
  74. // MinChanFundingSize is the smallest channel that we'll allow to be
  75. // created over the RPC interface.
  76. MinChanFundingSize = btcutil.Amount(20000)
  77. // MaxBtcFundingAmount is a soft-limit of the maximum channel size
  78. // currently accepted on the Bitcoin chain within the Lightning
  79. // Protocol. This limit is defined in BOLT-0002, and serves as an
  80. // initial precautionary limit while implementations are battle tested
  81. // in the real world.
  82. MaxBtcFundingAmount = btcutil.Amount(1<<24) - 1
  83. // MaxBtcFundingAmountWumbo is a soft-limit on the maximum size of wumbo
  84. // channels. This limit is 10 BTC and is the only thing standing between
  85. // you and limitless channel size (apart from 21 million cap).
  86. MaxBtcFundingAmountWumbo = btcutil.Amount(1000000000)
  87. // TODO(roasbeef): tune.
  88. msgBufferSize = 50
  89. // MaxWaitNumBlocksFundingConf is the maximum number of blocks to wait
  90. // for the funding transaction to be confirmed before forgetting
  91. // channels that aren't initiated by us. 2016 blocks is ~2 weeks.
  92. MaxWaitNumBlocksFundingConf = 2016
  93. // pendingChansLimit is the maximum number of pending channels that we
  94. // can have. After this point, pending channel opens will start to be
  95. // rejected.
  96. pendingChansLimit = 1_000
  97. )
  98. var (
  99. // ErrFundingManagerShuttingDown is an error returned when attempting to
  100. // process a funding request/message but the funding manager has already
  101. // been signaled to shut down.
  102. ErrFundingManagerShuttingDown = errors.New("funding manager shutting " +
  103. "down")
  104. // ErrConfirmationTimeout is an error returned when we as a responder
  105. // are waiting for a funding transaction to confirm, but too many
  106. // blocks pass without confirmation.
  107. ErrConfirmationTimeout = errors.New("timeout waiting for funding " +
  108. "confirmation")
  109. // errUpfrontShutdownScriptNotSupported is returned if an upfront
  110. // shutdown script is set for a peer that does not support the feature
  111. // bit.
  112. errUpfrontShutdownScriptNotSupported = errors.New("peer does not " +
  113. "support option upfront shutdown script")
  114. zeroID [32]byte
  115. )
  116. // reservationWithCtx encapsulates a pending channel reservation. This wrapper
  117. // struct is used internally within the funding manager to track and progress
  118. // the funding workflow initiated by incoming/outgoing methods from the target
  119. // peer. Additionally, this struct houses a response and error channel which is
  120. // used to respond to the caller in the case a channel workflow is initiated
  121. // via a local signal such as RPC.
  122. //
  123. // TODO(roasbeef): actually use the context package
  124. // - deadlines, etc.
  125. type reservationWithCtx struct {
  126. reservation *lnwallet.ChannelReservation
  127. peer lnpeer.Peer
  128. chanAmt btcutil.Amount
  129. // forwardingPolicy is the policy provided by the initFundingMsg.
  130. forwardingPolicy models.ForwardingPolicy
  131. // Constraints we require for the remote.
  132. remoteCsvDelay uint16
  133. remoteMinHtlc lnwire.MilliSatoshi
  134. remoteMaxValue lnwire.MilliSatoshi
  135. remoteMaxHtlcs uint16
  136. remoteChanReserve btcutil.Amount
  137. // maxLocalCsv is the maximum csv we will accept from the remote.
  138. maxLocalCsv uint16
  139. // channelType is the explicit channel type proposed by the initiator of
  140. // the channel.
  141. channelType *lnwire.ChannelType
  142. updateMtx sync.RWMutex
  143. lastUpdated time.Time
  144. updates chan *lnrpc.OpenStatusUpdate
  145. err chan error
  146. }
  147. // isLocked checks the reservation's timestamp to determine whether it is
  148. // locked.
  149. func (r *reservationWithCtx) isLocked() bool {
  150. r.updateMtx.RLock()
  151. defer r.updateMtx.RUnlock()
  152. // The time zero value represents a locked reservation.
  153. return r.lastUpdated.IsZero()
  154. }
  155. // updateTimestamp updates the reservation's timestamp with the current time.
  156. func (r *reservationWithCtx) updateTimestamp() {
  157. r.updateMtx.Lock()
  158. defer r.updateMtx.Unlock()
  159. r.lastUpdated = time.Now()
  160. }
  161. // InitFundingMsg is sent by an outside subsystem to the funding manager in
  162. // order to kick off a funding workflow with a specified target peer. The
  163. // original request which defines the parameters of the funding workflow are
  164. // embedded within this message giving the funding manager full context w.r.t
  165. // the workflow.
  166. type InitFundingMsg struct {
  167. // Peer is the peer that we want to open a channel to.
  168. Peer lnpeer.Peer
  169. // TargetPubkey is the public key of the peer.
  170. TargetPubkey *btcec.PublicKey
  171. // ChainHash is the target genesis hash for this channel.
  172. ChainHash chainhash.Hash
  173. // SubtractFees set to true means that fees will be subtracted
  174. // from the LocalFundingAmt.
  175. SubtractFees bool
  176. // LocalFundingAmt is the size of the channel.
  177. LocalFundingAmt btcutil.Amount
  178. // BaseFee is the base fee charged for routing payments regardless of
  179. // the number of milli-satoshis sent.
  180. BaseFee *uint64
  181. // FeeRate is the fee rate in ppm (parts per million) that will be
  182. // charged proportionally based on the value of each forwarded HTLC, the
  183. // lowest possible rate is 0 with a granularity of 0.000001
  184. // (millionths).
  185. FeeRate *uint64
  186. // PushAmt is the amount pushed to the counterparty.
  187. PushAmt lnwire.MilliSatoshi
  188. // FundingFeePerKw is the fee for the funding transaction.
  189. FundingFeePerKw chainfee.SatPerKWeight
  190. // Private determines whether or not this channel will be private.
  191. Private bool
  192. // MinHtlcIn is the minimum incoming HTLC that we accept.
  193. MinHtlcIn lnwire.MilliSatoshi
  194. // RemoteCsvDelay is the CSV delay we require for the remote peer.
  195. RemoteCsvDelay uint16
  196. // RemoteChanReserve is the channel reserve we required for the remote
  197. // peer.
  198. RemoteChanReserve btcutil.Amount
  199. // MinConfs indicates the minimum number of confirmations that each
  200. // output selected to fund the channel should satisfy.
  201. MinConfs int32
  202. // ShutdownScript is an optional upfront shutdown script for the
  203. // channel. This value is optional, so may be nil.
  204. ShutdownScript lnwire.DeliveryAddress
  205. // MaxValueInFlight is the maximum amount of coins in MilliSatoshi
  206. // that can be pending within the channel. It only applies to the
  207. // remote party.
  208. MaxValueInFlight lnwire.MilliSatoshi
  209. // MaxHtlcs is the maximum number of HTLCs that the remote peer
  210. // can offer us.
  211. MaxHtlcs uint16
  212. // MaxLocalCsv is the maximum local csv delay we will accept from our
  213. // peer.
  214. MaxLocalCsv uint16
  215. // FundUpToMaxAmt is the maximum amount to try to commit to. If set, the
  216. // MinFundAmt field denotes the acceptable minimum amount to commit to,
  217. // while trying to commit as many coins as possible up to this value.
  218. FundUpToMaxAmt btcutil.Amount
  219. // MinFundAmt must be set iff FundUpToMaxAmt is set. It denotes the
  220. // minimum amount to commit to.
  221. MinFundAmt btcutil.Amount
  222. // Outpoints is a list of client-selected outpoints that should be used
  223. // for funding a channel. If LocalFundingAmt is specified then this
  224. // amount is allocated from the sum of outpoints towards funding. If
  225. // the FundUpToMaxAmt is specified the entirety of selected funds is
  226. // allocated towards channel funding.
  227. Outpoints []wire.OutPoint
  228. // ChanFunder is an optional channel funder that allows the caller to
  229. // control exactly how the channel funding is carried out. If not
  230. // specified, then the default chanfunding.WalletAssembler will be
  231. // used.
  232. ChanFunder chanfunding.Assembler
  233. // PendingChanID is not all zeroes (the default value), then this will
  234. // be the pending channel ID used for the funding flow within the wire
  235. // protocol.
  236. PendingChanID PendingChanID
  237. // ChannelType allows the caller to use an explicit channel type for the
  238. // funding negotiation. This type will only be observed if BOTH sides
  239. // support explicit channel type negotiation.
  240. ChannelType *lnwire.ChannelType
  241. // Memo is any arbitrary information we wish to store locally about the
  242. // channel that will be useful to our future selves.
  243. Memo []byte
  244. // Updates is a channel which updates to the opening status of the
  245. // channel are sent on.
  246. Updates chan *lnrpc.OpenStatusUpdate
  247. // Err is a channel which errors encountered during the funding flow are
  248. // sent on.
  249. Err chan error
  250. }
  251. // fundingMsg is sent by the ProcessFundingMsg function and packages a
  252. // funding-specific lnwire.Message along with the lnpeer.Peer that sent it.
  253. type fundingMsg struct {
  254. msg lnwire.Message
  255. peer lnpeer.Peer
  256. }
  257. // pendingChannels is a map instantiated per-peer which tracks all active
  258. // pending single funded channels indexed by their pending channel identifier,
  259. // which is a set of 32-bytes generated via a CSPRNG.
  260. type pendingChannels map[PendingChanID]*reservationWithCtx
  261. // serializedPubKey is used within the FundingManager's activeReservations list
  262. // to identify the nodes with which the FundingManager is actively working to
  263. // initiate new channels.
  264. type serializedPubKey [33]byte
  265. // newSerializedKey creates a new serialized public key from an instance of a
  266. // live pubkey object.
  267. func newSerializedKey(pubKey *btcec.PublicKey) serializedPubKey {
  268. var s serializedPubKey
  269. copy(s[:], pubKey.SerializeCompressed())
  270. return s
  271. }
  272. // DevConfig specifies configs used for integration test only.
  273. type DevConfig struct {
  274. // ProcessChannelReadyWait is the duration to sleep before processing
  275. // remote node's channel ready message once the channel as been marked
  276. // as `channelReadySent`.
  277. ProcessChannelReadyWait time.Duration
  278. }
  279. // Config defines the configuration for the FundingManager. All elements
  280. // within the configuration MUST be non-nil for the FundingManager to carry out
  281. // its duties.
  282. type Config struct {
  283. // Dev specifies config values used in integration test. For
  284. // production, this config will always be an empty struct.
  285. Dev *DevConfig
  286. // NoWumboChans indicates if we're to reject all incoming wumbo channel
  287. // requests, and also reject all outgoing wumbo channel requests.
  288. NoWumboChans bool
  289. // IDKey is the PublicKey that is used to identify this node within the
  290. // Lightning Network.
  291. IDKey *btcec.PublicKey
  292. // IDKeyLoc is the locator for the key that is used to identify this
  293. // node within the LightningNetwork.
  294. IDKeyLoc keychain.KeyLocator
  295. // Wallet handles the parts of the funding process that involves moving
  296. // funds from on-chain transaction outputs into Lightning channels.
  297. Wallet *lnwallet.LightningWallet
  298. // PublishTransaction facilitates the process of broadcasting a
  299. // transaction to the network.
  300. PublishTransaction func(*wire.MsgTx, string) error
  301. // UpdateLabel updates the label that a transaction has in our wallet,
  302. // overwriting any existing labels.
  303. UpdateLabel func(chainhash.Hash, string) error
  304. // FeeEstimator calculates appropriate fee rates based on historical
  305. // transaction information.
  306. FeeEstimator chainfee.Estimator
  307. // Notifier is used by the FundingManager to determine when the
  308. // channel's funding transaction has been confirmed on the blockchain
  309. // so that the channel creation process can be completed.
  310. Notifier chainntnfs.ChainNotifier
  311. // ChannelDB is the database that keeps track of all channel state.
  312. ChannelDB *channeldb.ChannelStateDB
  313. // SignMessage signs an arbitrary message with a given public key. The
  314. // actual digest signed is the double sha-256 of the message. In the
  315. // case that the private key corresponding to the passed public key
  316. // cannot be located, then an error is returned.
  317. //
  318. // TODO(roasbeef): should instead pass on this responsibility to a
  319. // distinct sub-system?
  320. SignMessage func(keyLoc keychain.KeyLocator,
  321. msg []byte, doubleHash bool) (*ecdsa.Signature, error)
  322. // CurrentNodeAnnouncement should return the latest, fully signed node
  323. // announcement from the backing Lightning Network node with a fresh
  324. // timestamp.
  325. CurrentNodeAnnouncement func() (lnwire.NodeAnnouncement, error)
  326. // SendAnnouncement is used by the FundingManager to send announcement
  327. // messages to the Gossiper to possibly broadcast to the greater
  328. // network. A set of optional message fields can be provided to populate
  329. // any information within the graph that is not included in the gossip
  330. // message.
  331. SendAnnouncement func(msg lnwire.Message,
  332. optionalFields ...discovery.OptionalMsgField) chan error
  333. // NotifyWhenOnline allows the FundingManager to register with a
  334. // subsystem that will notify it when the peer comes online. This is
  335. // used when sending the channelReady message, since it MUST be
  336. // delivered after the funding transaction is confirmed.
  337. //
  338. // NOTE: The peerChan channel must be buffered.
  339. NotifyWhenOnline func(peer [33]byte, peerChan chan<- lnpeer.Peer)
  340. // FindChannel queries the database for the channel with the given
  341. // channel ID. Providing the node's public key is an optimization that
  342. // prevents deserializing and scanning through all possible channels.
  343. FindChannel func(node *btcec.PublicKey,
  344. chanID lnwire.ChannelID) (*channeldb.OpenChannel, error)
  345. // TempChanIDSeed is a cryptographically random string of bytes that's
  346. // used as a seed to generate pending channel ID's.
  347. TempChanIDSeed [32]byte
  348. // DefaultRoutingPolicy is the default routing policy used when
  349. // initially announcing channels.
  350. DefaultRoutingPolicy models.ForwardingPolicy
  351. // DefaultMinHtlcIn is the default minimum incoming htlc value that is
  352. // set as a channel parameter.
  353. DefaultMinHtlcIn lnwire.MilliSatoshi
  354. // NumRequiredConfs is a function closure that helps the funding
  355. // manager decide how many confirmations it should require for a
  356. // channel extended to it. The function is able to take into account
  357. // the amount of the channel, and any funds we'll be pushed in the
  358. // process to determine how many confirmations we'll require.
  359. NumRequiredConfs func(btcutil.Amount, lnwire.MilliSatoshi) uint16
  360. // RequiredRemoteDelay is a function that maps the total amount in a
  361. // proposed channel to the CSV delay that we'll require for the remote
  362. // party. Naturally a larger channel should require a higher CSV delay
  363. // in order to give us more time to claim funds in the case of a
  364. // contract breach.
  365. RequiredRemoteDelay func(btcutil.Amount) uint16
  366. // RequiredRemoteChanReserve is a function closure that, given the
  367. // channel capacity and dust limit, will return an appropriate amount
  368. // for the remote peer's required channel reserve that is to be adhered
  369. // to at all times.
  370. RequiredRemoteChanReserve func(capacity,
  371. dustLimit btcutil.Amount) btcutil.Amount
  372. // RequiredRemoteMaxValue is a function closure that, given the channel
  373. // capacity, returns the amount of MilliSatoshis that our remote peer
  374. // can have in total outstanding HTLCs with us.
  375. RequiredRemoteMaxValue func(btcutil.Amount) lnwire.MilliSatoshi
  376. // RequiredRemoteMaxHTLCs is a function closure that, given the channel
  377. // capacity, returns the number of maximum HTLCs the remote peer can
  378. // offer us.
  379. RequiredRemoteMaxHTLCs func(btcutil.Amount) uint16
  380. // WatchNewChannel is to be called once a new channel enters the final
  381. // funding stage: waiting for on-chain confirmation. This method sends
  382. // the channel to the ChainArbitrator so it can watch for any on-chain
  383. // events related to the channel. We also provide the public key of the
  384. // node we're establishing a channel with for reconnection purposes.
  385. WatchNewChannel func(*channeldb.OpenChannel, *btcec.PublicKey) error
  386. // ReportShortChanID allows the funding manager to report the confirmed
  387. // short channel ID of a formerly pending zero-conf channel to outside
  388. // sub-systems.
  389. ReportShortChanID func(wire.OutPoint) error
  390. // ZombieSweeperInterval is the periodic time interval in which the
  391. // zombie sweeper is run.
  392. ZombieSweeperInterval time.Duration
  393. // ReservationTimeout is the length of idle time that must pass before
  394. // a reservation is considered a zombie.
  395. ReservationTimeout time.Duration
  396. // MinChanSize is the smallest channel size that we'll accept as an
  397. // inbound channel. We have such a parameter, as otherwise, nodes could
  398. // flood us with very small channels that would never really be usable
  399. // due to fees.
  400. MinChanSize btcutil.Amount
  401. // MaxChanSize is the largest channel size that we'll accept as an
  402. // inbound channel. We have such a parameter, so that you may decide how
  403. // WUMBO you would like your channel.
  404. MaxChanSize btcutil.Amount
  405. // MaxPendingChannels is the maximum number of pending channels we
  406. // allow for each peer.
  407. MaxPendingChannels int
  408. // RejectPush is set true if the fundingmanager should reject any
  409. // incoming channels having a non-zero push amount.
  410. RejectPush bool
  411. // MaxLocalCSVDelay is the maximum csv delay we will allow for our
  412. // commit output. Channels that exceed this value will be failed.
  413. MaxLocalCSVDelay uint16
  414. // NotifyOpenChannelEvent informs the ChannelNotifier when channels
  415. // transition from pending open to open.
  416. NotifyOpenChannelEvent func(wire.OutPoint)
  417. // OpenChannelPredicate is a predicate on the lnwire.OpenChannel message
  418. // and on the requesting node's public key that returns a bool which
  419. // tells the funding manager whether or not to accept the channel.
  420. OpenChannelPredicate chanacceptor.ChannelAcceptor
  421. // NotifyPendingOpenChannelEvent informs the ChannelNotifier when
  422. // channels enter a pending state.
  423. NotifyPendingOpenChannelEvent func(wire.OutPoint,
  424. *channeldb.OpenChannel)
  425. // EnableUpfrontShutdown specifies whether the upfront shutdown script
  426. // is enabled.
  427. EnableUpfrontShutdown bool
  428. // MaxAnchorsCommitFeeRate is the max commitment fee rate we'll use as
  429. // the initiator for channels of the anchor type.
  430. MaxAnchorsCommitFeeRate chainfee.SatPerKWeight
  431. // DeleteAliasEdge allows the Manager to delete an alias channel edge
  432. // from the graph. It also returns our local to-be-deleted policy.
  433. DeleteAliasEdge func(scid lnwire.ShortChannelID) (
  434. *models.ChannelEdgePolicy, error)
  435. // AliasManager is an implementation of the aliasHandler interface that
  436. // abstracts away the handling of many alias functions.
  437. AliasManager aliasHandler
  438. // IsSweeperOutpoint queries the sweeper store for successfully
  439. // published sweeps. This is useful to decide for the internal wallet
  440. // backed funding flow to not use utxos still being swept by the sweeper
  441. // subsystem.
  442. IsSweeperOutpoint func(wire.OutPoint) bool
  443. // AuxLeafStore is an optional store that can be used to store auxiliary
  444. // leaves for certain custom channel types.
  445. AuxLeafStore fn.Option[lnwallet.AuxLeafStore]
  446. }
  447. // Manager acts as an orchestrator/bridge between the wallet's
  448. // 'ChannelReservation' workflow, and the wire protocol's funding initiation
  449. // messages. Any requests to initiate the funding workflow for a channel,
  450. // either kicked-off locally or remotely are handled by the funding manager.
  451. // Once a channel's funding workflow has been completed, any local callers, the
  452. // local peer, and possibly the remote peer are notified of the completion of
  453. // the channel workflow. Additionally, any temporary or permanent access
  454. // controls between the wallet and remote peers are enforced via the funding
  455. // manager.
  456. type Manager struct {
  457. started sync.Once
  458. stopped sync.Once
  459. // cfg is a copy of the configuration struct that the FundingManager
  460. // was initialized with.
  461. cfg *Config
  462. // chanIDKey is a cryptographically random key that's used to generate
  463. // temporary channel ID's.
  464. chanIDKey [32]byte
  465. // chanIDNonce is a nonce that's incremented for each new funding
  466. // reservation created.
  467. chanIDNonce atomic.Uint64
  468. // nonceMtx is a mutex that guards the pendingMusigNonces.
  469. nonceMtx sync.RWMutex
  470. // pendingMusigNonces is used to store the musig2 nonce we generate to
  471. // send funding locked until we receive a funding locked message from
  472. // the remote party. We'll use this to keep track of the nonce we
  473. // generated, so we send the local+remote nonces to the peer state
  474. // machine.
  475. //
  476. // NOTE: This map is protected by the nonceMtx above.
  477. //
  478. // TODO(roasbeef): replace w/ generic concurrent map
  479. pendingMusigNonces map[lnwire.ChannelID]*musig2.Nonces
  480. // activeReservations is a map which houses the state of all pending
  481. // funding workflows.
  482. activeReservations map[serializedPubKey]pendingChannels
  483. // signedReservations is a utility map that maps the permanent channel
  484. // ID of a funding reservation to its temporary channel ID. This is
  485. // required as mid funding flow, we switch to referencing the channel
  486. // by its full channel ID once the commitment transactions have been
  487. // signed by both parties.
  488. signedReservations map[lnwire.ChannelID]PendingChanID
  489. // resMtx guards both of the maps above to ensure that all access is
  490. // goroutine safe.
  491. resMtx sync.RWMutex
  492. // fundingMsgs is a channel that relays fundingMsg structs from
  493. // external sub-systems using the ProcessFundingMsg call.
  494. fundingMsgs chan *fundingMsg
  495. // fundingRequests is a channel used to receive channel initiation
  496. // requests from a local subsystem within the daemon.
  497. fundingRequests chan *InitFundingMsg
  498. localDiscoverySignals *lnutils.SyncMap[lnwire.ChannelID, chan struct{}]
  499. handleChannelReadyBarriers *lnutils.SyncMap[lnwire.ChannelID, struct{}]
  500. quit chan struct{}
  501. wg sync.WaitGroup
  502. }
  503. // channelOpeningState represents the different states a channel can be in
  504. // between the funding transaction has been confirmed and the channel is
  505. // announced to the network and ready to be used.
  506. type channelOpeningState uint8
  507. const (
  508. // markedOpen is the opening state of a channel if the funding
  509. // transaction is confirmed on-chain, but channelReady is not yet
  510. // successfully sent to the other peer.
  511. markedOpen channelOpeningState = iota
  512. // channelReadySent is the opening state of a channel if the
  513. // channelReady message has successfully been sent to the other peer,
  514. // but we still haven't announced the channel to the network.
  515. channelReadySent
  516. // addedToGraph is the opening state of a channel if the channel has
  517. // been successfully added to the graph immediately after the
  518. // channelReady message has been sent, but we still haven't announced
  519. // the channel to the network.
  520. addedToGraph
  521. )
  522. func (c channelOpeningState) String() string {
  523. switch c {
  524. case markedOpen:
  525. return "markedOpen"
  526. case channelReadySent:
  527. return "channelReadySent"
  528. case addedToGraph:
  529. return "addedToGraph"
  530. default:
  531. return "unknown"
  532. }
  533. }
  534. // NewFundingManager creates and initializes a new instance of the
  535. // fundingManager.
  536. func NewFundingManager(cfg Config) (*Manager, error) {
  537. return &Manager{
  538. cfg: &cfg,
  539. chanIDKey: cfg.TempChanIDSeed,
  540. activeReservations: make(
  541. map[serializedPubKey]pendingChannels,
  542. ),
  543. signedReservations: make(
  544. map[lnwire.ChannelID][32]byte,
  545. ),
  546. fundingMsgs: make(
  547. chan *fundingMsg, msgBufferSize,
  548. ),
  549. fundingRequests: make(
  550. chan *InitFundingMsg, msgBufferSize,
  551. ),
  552. localDiscoverySignals: &lnutils.SyncMap[
  553. lnwire.ChannelID, chan struct{},
  554. ]{},
  555. handleChannelReadyBarriers: &lnutils.SyncMap[
  556. lnwire.ChannelID, struct{},
  557. ]{},
  558. pendingMusigNonces: make(
  559. map[lnwire.ChannelID]*musig2.Nonces,
  560. ),
  561. quit: make(chan struct{}),
  562. }, nil
  563. }
  564. // Start launches all helper goroutines required for handling requests sent
  565. // to the funding manager.
  566. func (f *Manager) Start() error {
  567. var err error
  568. f.started.Do(func() {
  569. log.Info("Funding manager starting")
  570. err = f.start()
  571. })
  572. return err
  573. }
  574. func (f *Manager) start() error {
  575. // Upon restart, the Funding Manager will check the database to load any
  576. // channels that were waiting for their funding transactions to be
  577. // confirmed on the blockchain at the time when the daemon last went
  578. // down.
  579. // TODO(roasbeef): store height that funding finished?
  580. // * would then replace call below
  581. allChannels, err := f.cfg.ChannelDB.FetchAllChannels()
  582. if err != nil {
  583. return err
  584. }
  585. for _, channel := range allChannels {
  586. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  587. // For any channels that were in a pending state when the
  588. // daemon was last connected, the Funding Manager will
  589. // re-initialize the channel barriers, and republish the
  590. // funding transaction if we're the initiator.
  591. if channel.IsPending {
  592. log.Tracef("Loading pending ChannelPoint(%v), "+
  593. "creating chan barrier",
  594. channel.FundingOutpoint)
  595. f.localDiscoverySignals.Store(
  596. chanID, make(chan struct{}),
  597. )
  598. // Rebroadcast the funding transaction for any pending
  599. // channel that we initiated. No error will be returned
  600. // if the transaction already has been broadcast.
  601. chanType := channel.ChanType
  602. if chanType.IsSingleFunder() &&
  603. chanType.HasFundingTx() &&
  604. channel.IsInitiator {
  605. f.rebroadcastFundingTx(channel)
  606. }
  607. } else if channel.ChanType.IsSingleFunder() &&
  608. channel.ChanType.HasFundingTx() &&
  609. channel.IsZeroConf() && channel.IsInitiator &&
  610. !channel.ZeroConfConfirmed() {
  611. // Rebroadcast the funding transaction for unconfirmed
  612. // zero-conf channels if we have the funding tx and are
  613. // also the initiator.
  614. f.rebroadcastFundingTx(channel)
  615. }
  616. // We will restart the funding state machine for all channels,
  617. // which will wait for the channel's funding transaction to be
  618. // confirmed on the blockchain, and transmit the messages
  619. // necessary for the channel to be operational.
  620. f.wg.Add(1)
  621. go f.advanceFundingState(channel, chanID, nil)
  622. }
  623. f.wg.Add(1) // TODO(roasbeef): tune
  624. go f.reservationCoordinator()
  625. return nil
  626. }
  627. // Stop signals all helper goroutines to execute a graceful shutdown. This
  628. // method will block until all goroutines have exited.
  629. func (f *Manager) Stop() error {
  630. f.stopped.Do(func() {
  631. log.Info("Funding manager shutting down...")
  632. defer log.Debug("Funding manager shutdown complete")
  633. close(f.quit)
  634. f.wg.Wait()
  635. })
  636. return nil
  637. }
  638. // rebroadcastFundingTx publishes the funding tx on startup for each
  639. // unconfirmed channel.
  640. func (f *Manager) rebroadcastFundingTx(c *channeldb.OpenChannel) {
  641. var fundingTxBuf bytes.Buffer
  642. err := c.FundingTxn.Serialize(&fundingTxBuf)
  643. if err != nil {
  644. log.Errorf("Unable to serialize funding transaction %v: %v",
  645. c.FundingTxn.TxHash(), err)
  646. // Clear the buffer of any bytes that were written before the
  647. // serialization error to prevent logging an incomplete
  648. // transaction.
  649. fundingTxBuf.Reset()
  650. } else {
  651. log.Debugf("Rebroadcasting funding tx for ChannelPoint(%v): "+
  652. "%x", c.FundingOutpoint, fundingTxBuf.Bytes())
  653. }
  654. // Set a nil short channel ID at this stage because we do not know it
  655. // until our funding tx confirms.
  656. label := labels.MakeLabel(labels.LabelTypeChannelOpen, nil)
  657. err = f.cfg.PublishTransaction(c.FundingTxn, label)
  658. if err != nil {
  659. log.Errorf("Unable to rebroadcast funding tx %x for "+
  660. "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
  661. c.FundingOutpoint, err)
  662. }
  663. }
  664. // PendingChanID is a type that represents a pending channel ID. This might be
  665. // selected by the caller, but if not, will be automatically selected.
  666. type PendingChanID = [32]byte
  667. // nextPendingChanID returns the next free pending channel ID to be used to
  668. // identify a particular future channel funding workflow.
  669. func (f *Manager) nextPendingChanID() PendingChanID {
  670. // Obtain a fresh nonce. We do this by encoding the incremented nonce.
  671. nextNonce := f.chanIDNonce.Add(1)
  672. var nonceBytes [8]byte
  673. binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
  674. // We'll generate the next pending channelID by "encrypting" 32-bytes
  675. // of zeroes which'll extract 32 random bytes from our stream cipher.
  676. var (
  677. nextChanID PendingChanID
  678. zeroes [32]byte
  679. )
  680. salsa20.XORKeyStream(
  681. nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
  682. )
  683. return nextChanID
  684. }
  685. // CancelPeerReservations cancels all active reservations associated with the
  686. // passed node. This will ensure any outputs which have been pre committed,
  687. // (and thus locked from coin selection), are properly freed.
  688. func (f *Manager) CancelPeerReservations(nodePub [33]byte) {
  689. log.Debugf("Cancelling all reservations for peer %x", nodePub[:])
  690. f.resMtx.Lock()
  691. defer f.resMtx.Unlock()
  692. // We'll attempt to look up this node in the set of active
  693. // reservations. If they don't have any, then there's no further work
  694. // to be done.
  695. nodeReservations, ok := f.activeReservations[nodePub]
  696. if !ok {
  697. log.Debugf("No active reservations for node: %x", nodePub[:])
  698. return
  699. }
  700. // If they do have any active reservations, then we'll cancel all of
  701. // them (which releases any locked UTXO's), and also delete it from the
  702. // reservation map.
  703. for pendingID, resCtx := range nodeReservations {
  704. if err := resCtx.reservation.Cancel(); err != nil {
  705. log.Errorf("unable to cancel reservation for "+
  706. "node=%x: %v", nodePub[:], err)
  707. }
  708. resCtx.err <- fmt.Errorf("peer disconnected")
  709. delete(nodeReservations, pendingID)
  710. }
  711. // Finally, we'll delete the node itself from the set of reservations.
  712. delete(f.activeReservations, nodePub)
  713. }
  714. // chanIdentifier wraps pending channel ID and channel ID into one struct so
  715. // it's easier to identify a specific channel.
  716. //
  717. // TODO(yy): move to a different package to hide the private fields so direct
  718. // access is disabled.
  719. type chanIdentifier struct {
  720. // tempChanID is the pending channel ID created by the funder when
  721. // initializing the funding flow. For fundee, it's received from the
  722. // `open_channel` message.
  723. tempChanID lnwire.ChannelID
  724. // chanID is the channel ID created by the funder once the
  725. // `accept_channel` message is received. For fundee, it's received from
  726. // the `funding_created` message.
  727. chanID lnwire.ChannelID
  728. // chanIDSet is a boolean indicates whether the active channel ID is
  729. // set for this identifier. For zero conf channels, the `chanID` can be
  730. // all-zero, which is the same as the empty value of `ChannelID`. To
  731. // avoid the confusion, we use this boolean to explicitly signal
  732. // whether the `chanID` is set or not.
  733. chanIDSet bool
  734. }
  735. // newChanIdentifier creates a new chanIdentifier.
  736. func newChanIdentifier(tempChanID lnwire.ChannelID) *chanIdentifier {
  737. return &chanIdentifier{
  738. tempChanID: tempChanID,
  739. }
  740. }
  741. // setChanID updates the `chanIdentifier` with the active channel ID.
  742. func (c *chanIdentifier) setChanID(chanID lnwire.ChannelID) {
  743. c.chanID = chanID
  744. c.chanIDSet = true
  745. }
  746. // hasChanID returns true if the active channel ID has been set.
  747. func (c *chanIdentifier) hasChanID() bool {
  748. return c.chanIDSet
  749. }
  750. // failFundingFlow will fail the active funding flow with the target peer,
  751. // identified by its unique temporary channel ID. This method will send an
  752. // error to the remote peer, and also remove the reservation from our set of
  753. // pending reservations.
  754. //
  755. // TODO(roasbeef): if peer disconnects, and haven't yet broadcast funding
  756. // transaction, then all reservations should be cleared.
  757. func (f *Manager) failFundingFlow(peer lnpeer.Peer, cid *chanIdentifier,
  758. fundingErr error) {
  759. log.Debugf("Failing funding flow for pending_id=%v: %v",
  760. cid.tempChanID, fundingErr)
  761. // First, notify Brontide to remove the pending channel.
  762. //
  763. // NOTE: depending on where we fail the flow, we may not have the
  764. // active channel ID yet.
  765. if cid.hasChanID() {
  766. err := peer.RemovePendingChannel(cid.chanID)
  767. if err != nil {
  768. log.Errorf("Unable to remove channel %v with peer %x: "+
  769. "%v", cid,
  770. peer.IdentityKey().SerializeCompressed(), err)
  771. }
  772. }
  773. ctx, err := f.cancelReservationCtx(
  774. peer.IdentityKey(), cid.tempChanID, false,
  775. )
  776. if err != nil {
  777. log.Errorf("unable to cancel reservation: %v", err)
  778. }
  779. // In case the case where the reservation existed, send the funding
  780. // error on the error channel.
  781. if ctx != nil {
  782. ctx.err <- fundingErr
  783. }
  784. // We only send the exact error if it is part of out whitelisted set of
  785. // errors (lnwire.FundingError or lnwallet.ReservationError).
  786. var msg lnwire.ErrorData
  787. switch e := fundingErr.(type) {
  788. // Let the actual error message be sent to the remote for the
  789. // whitelisted types.
  790. case lnwallet.ReservationError:
  791. msg = lnwire.ErrorData(e.Error())
  792. case lnwire.FundingError:
  793. msg = lnwire.ErrorData(e.Error())
  794. case chanacceptor.ChanAcceptError:
  795. msg = lnwire.ErrorData(e.Error())
  796. // For all other error types we just send a generic error.
  797. default:
  798. msg = lnwire.ErrorData("funding failed due to internal error")
  799. }
  800. errMsg := &lnwire.Error{
  801. ChanID: cid.tempChanID,
  802. Data: msg,
  803. }
  804. log.Debugf("Sending funding error to peer (%x): %v",
  805. peer.IdentityKey().SerializeCompressed(), spew.Sdump(errMsg))
  806. if err := peer.SendMessage(false, errMsg); err != nil {
  807. log.Errorf("unable to send error message to peer %v", err)
  808. }
  809. }
  810. // sendWarning sends a new warning message to the target peer, targeting the
  811. // specified cid with the passed funding error.
  812. func (f *Manager) sendWarning(peer lnpeer.Peer, cid *chanIdentifier,
  813. fundingErr error) {
  814. msg := fundingErr.Error()
  815. errMsg := &lnwire.Warning{
  816. ChanID: cid.tempChanID,
  817. Data: lnwire.WarningData(msg),
  818. }
  819. log.Debugf("Sending funding warning to peer (%x): %v",
  820. peer.IdentityKey().SerializeCompressed(),
  821. spew.Sdump(errMsg),
  822. )
  823. if err := peer.SendMessage(false, errMsg); err != nil {
  824. log.Errorf("unable to send error message to peer %v", err)
  825. }
  826. }
  827. // reservationCoordinator is the primary goroutine tasked with progressing the
  828. // funding workflow between the wallet, and any outside peers or local callers.
  829. //
  830. // NOTE: This MUST be run as a goroutine.
  831. func (f *Manager) reservationCoordinator() {
  832. defer f.wg.Done()
  833. zombieSweepTicker := time.NewTicker(f.cfg.ZombieSweeperInterval)
  834. defer zombieSweepTicker.Stop()
  835. for {
  836. select {
  837. case fmsg := <-f.fundingMsgs:
  838. switch msg := fmsg.msg.(type) {
  839. case *lnwire.OpenChannel:
  840. f.fundeeProcessOpenChannel(fmsg.peer, msg)
  841. case *lnwire.AcceptChannel:
  842. f.funderProcessAcceptChannel(fmsg.peer, msg)
  843. case *lnwire.FundingCreated:
  844. f.fundeeProcessFundingCreated(fmsg.peer, msg)
  845. case *lnwire.FundingSigned:
  846. f.funderProcessFundingSigned(fmsg.peer, msg)
  847. case *lnwire.ChannelReady:
  848. f.wg.Add(1)
  849. go f.handleChannelReady(fmsg.peer, msg)
  850. case *lnwire.Warning:
  851. f.handleWarningMsg(fmsg.peer, msg)
  852. case *lnwire.Error:
  853. f.handleErrorMsg(fmsg.peer, msg)
  854. }
  855. case req := <-f.fundingRequests:
  856. f.handleInitFundingMsg(req)
  857. case <-zombieSweepTicker.C:
  858. f.pruneZombieReservations()
  859. case <-f.quit:
  860. return
  861. }
  862. }
  863. }
  864. // advanceFundingState will advance the channel through the steps after the
  865. // funding transaction is broadcasted, up until the point where the channel is
  866. // ready for operation. This includes waiting for the funding transaction to
  867. // confirm, sending channel_ready to the peer, adding the channel to the graph,
  868. // and announcing the channel. The updateChan can be set non-nil to get
  869. // OpenStatusUpdates.
  870. //
  871. // NOTE: This MUST be run as a goroutine.
  872. func (f *Manager) advanceFundingState(channel *channeldb.OpenChannel,
  873. pendingChanID PendingChanID,
  874. updateChan chan<- *lnrpc.OpenStatusUpdate) {
  875. defer f.wg.Done()
  876. // If the channel is still pending we must wait for the funding
  877. // transaction to confirm.
  878. if channel.IsPending {
  879. err := f.advancePendingChannelState(channel, pendingChanID)
  880. if err != nil {
  881. log.Errorf("Unable to advance pending state of "+
  882. "ChannelPoint(%v): %v",
  883. channel.FundingOutpoint, err)
  884. return
  885. }
  886. }
  887. var chanOpts []lnwallet.ChannelOpt
  888. f.cfg.AuxLeafStore.WhenSome(func(s lnwallet.AuxLeafStore) {
  889. chanOpts = append(chanOpts, lnwallet.WithLeafStore(s))
  890. })
  891. // We create the state-machine object which wraps the database state.
  892. lnChannel, err := lnwallet.NewLightningChannel(
  893. nil, channel, nil, chanOpts...,
  894. )
  895. if err != nil {
  896. log.Errorf("Unable to create LightningChannel(%v): %v",
  897. channel.FundingOutpoint, err)
  898. return
  899. }
  900. for {
  901. channelState, shortChanID, err := f.getChannelOpeningState(
  902. &channel.FundingOutpoint,
  903. )
  904. if err == channeldb.ErrChannelNotFound {
  905. // Channel not in fundingManager's opening database,
  906. // meaning it was successfully announced to the
  907. // network.
  908. // TODO(halseth): could do graph consistency check
  909. // here, and re-add the edge if missing.
  910. log.Debugf("ChannelPoint(%v) with chan_id=%x not "+
  911. "found in opening database, assuming already "+
  912. "announced to the network",
  913. channel.FundingOutpoint, pendingChanID)
  914. return
  915. } else if err != nil {
  916. log.Errorf("Unable to query database for "+
  917. "channel opening state(%v): %v",
  918. channel.FundingOutpoint, err)
  919. return
  920. }
  921. // If we did find the channel in the opening state database, we
  922. // have seen the funding transaction being confirmed, but there
  923. // are still steps left of the setup procedure. We continue the
  924. // procedure where we left off.
  925. err = f.stateStep(
  926. channel, lnChannel, shortChanID, pendingChanID,
  927. channelState, updateChan,
  928. )
  929. if err != nil {
  930. log.Errorf("Unable to advance state(%v): %v",
  931. channel.FundingOutpoint, err)
  932. return
  933. }
  934. }
  935. }
  936. // stateStep advances the confirmed channel one step in the funding state
  937. // machine. This method is synchronous and the new channel opening state will
  938. // have been written to the database when it successfully returns. The
  939. // updateChan can be set non-nil to get OpenStatusUpdates.
  940. func (f *Manager) stateStep(channel *channeldb.OpenChannel,
  941. lnChannel *lnwallet.LightningChannel,
  942. shortChanID *lnwire.ShortChannelID, pendingChanID PendingChanID,
  943. channelState channelOpeningState,
  944. updateChan chan<- *lnrpc.OpenStatusUpdate) error {
  945. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  946. log.Debugf("Channel(%v) with ShortChanID %v has opening state %v",
  947. chanID, shortChanID, channelState)
  948. switch channelState {
  949. // The funding transaction was confirmed, but we did not successfully
  950. // send the channelReady message to the peer, so let's do that now.
  951. case markedOpen:
  952. err := f.sendChannelReady(channel, lnChannel)
  953. if err != nil {
  954. return fmt.Errorf("failed sending channelReady: %w",
  955. err)
  956. }
  957. // As the channelReady message is now sent to the peer, the
  958. // channel is moved to the next state of the state machine. It
  959. // will be moved to the last state (actually deleted from the
  960. // database) after the channel is finally announced.
  961. err = f.saveChannelOpeningState(
  962. &channel.FundingOutpoint, channelReadySent,
  963. shortChanID,
  964. )
  965. if err != nil {
  966. return fmt.Errorf("error setting channel state to"+
  967. " channelReadySent: %w", err)
  968. }
  969. log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
  970. "sent ChannelReady", chanID, shortChanID)
  971. return nil
  972. // channelReady was sent to peer, but the channel was not added to the
  973. // graph and the channel announcement was not sent.
  974. case channelReadySent:
  975. // We must wait until we've received the peer's channel_ready
  976. // before sending a channel_update according to BOLT#07.
  977. received, err := f.receivedChannelReady(
  978. channel.IdentityPub, chanID,
  979. )
  980. if err != nil {
  981. return fmt.Errorf("failed to check if channel_ready "+
  982. "was received: %v", err)
  983. }
  984. if !received {
  985. // We haven't received ChannelReady, so we'll continue
  986. // to the next iteration of the loop after sleeping for
  987. // checkPeerChannelReadyInterval.
  988. select {
  989. case <-time.After(checkPeerChannelReadyInterval):
  990. case <-f.quit:
  991. return ErrFundingManagerShuttingDown
  992. }
  993. return nil
  994. }
  995. return f.handleChannelReadyReceived(
  996. channel, shortChanID, pendingChanID, updateChan,
  997. )
  998. // The channel was added to the Router's topology, but the channel
  999. // announcement was not sent.
  1000. case addedToGraph:
  1001. if channel.IsZeroConf() {
  1002. // If this is a zero-conf channel, then we will wait
  1003. // for it to be confirmed before announcing it to the
  1004. // greater network.
  1005. err := f.waitForZeroConfChannel(channel)
  1006. if err != nil {
  1007. return fmt.Errorf("failed waiting for zero "+
  1008. "channel: %v", err)
  1009. }
  1010. // Update the local shortChanID variable such that
  1011. // annAfterSixConfs uses the confirmed SCID.
  1012. confirmedScid := channel.ZeroConfRealScid()
  1013. shortChanID = &confirmedScid
  1014. }
  1015. err := f.annAfterSixConfs(channel, shortChanID)
  1016. if err != nil {
  1017. return fmt.Errorf("error sending channel "+
  1018. "announcement: %v", err)
  1019. }
  1020. // We delete the channel opening state from our internal
  1021. // database as the opening process has succeeded. We can do
  1022. // this because we assume the AuthenticatedGossiper queues the
  1023. // announcement messages, and persists them in case of a daemon
  1024. // shutdown.
  1025. err = f.deleteChannelOpeningState(&channel.FundingOutpoint)
  1026. if err != nil {
  1027. return fmt.Errorf("error deleting channel state: %w",
  1028. err)
  1029. }
  1030. // After the fee parameters have been stored in the
  1031. // announcement we can delete them from the database. For
  1032. // private channels we do not announce the channel policy to
  1033. // the network but still need to delete them from the database.
  1034. err = f.deleteInitialForwardingPolicy(chanID)
  1035. if err != nil {
  1036. log.Infof("Could not delete initial policy for chanId "+
  1037. "%x", chanID)
  1038. }
  1039. log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
  1040. "announced", chanID, shortChanID)
  1041. return nil
  1042. }
  1043. return fmt.Errorf("undefined channelState: %v", channelState)
  1044. }
  1045. // advancePendingChannelState waits for a pending channel's funding tx to
  1046. // confirm, and marks it open in the database when that happens.
  1047. func (f *Manager) advancePendingChannelState(
  1048. channel *channeldb.OpenChannel, pendingChanID PendingChanID) error {
  1049. if channel.IsZeroConf() {
  1050. // Persist the alias to the alias database.
  1051. baseScid := channel.ShortChannelID
  1052. err := f.cfg.AliasManager.AddLocalAlias(
  1053. baseScid, baseScid, true, false,
  1054. )
  1055. if err != nil {
  1056. return fmt.Errorf("error adding local alias to "+
  1057. "store: %v", err)
  1058. }
  1059. // We don't wait for zero-conf channels to be confirmed and
  1060. // instead immediately proceed with the rest of the funding
  1061. // flow. The channel opening state is stored under the alias
  1062. // SCID.
  1063. err = f.saveChannelOpeningState(
  1064. &channel.FundingOutpoint, markedOpen,
  1065. &channel.ShortChannelID,
  1066. )
  1067. if err != nil {
  1068. return fmt.Errorf("error setting zero-conf channel "+
  1069. "state to markedOpen: %v", err)
  1070. }
  1071. // The ShortChannelID is already set since it's an alias, but
  1072. // we still need to mark the channel as no longer pending.
  1073. err = channel.MarkAsOpen(channel.ShortChannelID)
  1074. if err != nil {
  1075. return fmt.Errorf("error setting zero-conf channel's "+
  1076. "pending flag to false: %v", err)
  1077. }
  1078. // Inform the ChannelNotifier that the channel has transitioned
  1079. // from pending open to open.
  1080. f.cfg.NotifyOpenChannelEvent(channel.FundingOutpoint)
  1081. // Find and close the discoverySignal for this channel such
  1082. // that ChannelReady messages will be processed.
  1083. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  1084. discoverySignal, ok := f.localDiscoverySignals.Load(chanID)
  1085. if ok {
  1086. close(discoverySignal)
  1087. }
  1088. return nil
  1089. }
  1090. confChannel, err := f.waitForFundingWithTimeout(channel)
  1091. if err == ErrConfirmationTimeout {
  1092. return f.fundingTimeout(channel, pendingChanID)
  1093. } else if err != nil {
  1094. return fmt.Errorf("error waiting for funding "+
  1095. "confirmation for ChannelPoint(%v): %v",
  1096. channel.FundingOutpoint, err)
  1097. }
  1098. if blockchain.IsCoinBaseTx(confChannel.fundingTx) {
  1099. // If it's a coinbase transaction, we need to wait for it to
  1100. // mature. We wait out an additional MinAcceptDepth on top of
  1101. // the coinbase maturity as an extra margin of safety.
  1102. maturity := f.cfg.Wallet.Cfg.NetParams.CoinbaseMaturity
  1103. numCoinbaseConfs := uint32(maturity)
  1104. if channel.NumConfsRequired > maturity {
  1105. numCoinbaseConfs = uint32(channel.NumConfsRequired)
  1106. }
  1107. txid := &channel.FundingOutpoint.Hash
  1108. fundingScript, err := makeFundingScript(channel)
  1109. if err != nil {
  1110. log.Errorf("unable to create funding script for "+
  1111. "ChannelPoint(%v): %v",
  1112. channel.FundingOutpoint, err)
  1113. return err
  1114. }
  1115. confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
  1116. txid, fundingScript, numCoinbaseConfs,
  1117. channel.BroadcastHeight(),
  1118. )
  1119. if err != nil {
  1120. log.Errorf("Unable to register for confirmation of "+
  1121. "ChannelPoint(%v): %v",
  1122. channel.FundingOutpoint, err)
  1123. return err
  1124. }
  1125. select {
  1126. case _, ok := <-confNtfn.Confirmed:
  1127. if !ok {
  1128. return fmt.Errorf("ChainNotifier shutting "+
  1129. "down, can't complete funding flow "+
  1130. "for ChannelPoint(%v)",
  1131. channel.FundingOutpoint)
  1132. }
  1133. case <-f.quit:
  1134. return ErrFundingManagerShuttingDown
  1135. }
  1136. }
  1137. // Success, funding transaction was confirmed.
  1138. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  1139. log.Debugf("ChannelID(%v) is now fully confirmed! "+
  1140. "(shortChanID=%v)", chanID, confChannel.shortChanID)
  1141. err = f.handleFundingConfirmation(channel, confChannel)
  1142. if err != nil {
  1143. return fmt.Errorf("unable to handle funding "+
  1144. "confirmation for ChannelPoint(%v): %v",
  1145. channel.FundingOutpoint, err)
  1146. }
  1147. return nil
  1148. }
  1149. // ProcessFundingMsg sends a message to the internal fundingManager goroutine,
  1150. // allowing it to handle the lnwire.Message.
  1151. func (f *Manager) ProcessFundingMsg(msg lnwire.Message, peer lnpeer.Peer) {
  1152. select {
  1153. case f.fundingMsgs <- &fundingMsg{msg, peer}:
  1154. case <-f.quit:
  1155. return
  1156. }
  1157. }
  1158. // fundeeProcessOpenChannel creates an initial 'ChannelReservation' within the
  1159. // wallet, then responds to the source peer with an accept channel message
  1160. // progressing the funding workflow.
  1161. //
  1162. // TODO(roasbeef): add error chan to all, let channelManager handle
  1163. // error+propagate.
  1164. //
  1165. //nolint:funlen
  1166. func (f *Manager) fundeeProcessOpenChannel(peer lnpeer.Peer,
  1167. msg *lnwire.OpenChannel) {
  1168. // Check number of pending channels to be smaller than maximum allowed
  1169. // number and send ErrorGeneric to remote peer if condition is
  1170. // violated.
  1171. peerPubKey := peer.IdentityKey()
  1172. peerIDKey := newSerializedKey(peerPubKey)
  1173. amt := msg.FundingAmount
  1174. // We get all pending channels for this peer. This is the list of the
  1175. // active reservations and the channels pending open in the database.
  1176. f.resMtx.RLock()
  1177. reservations := f.activeReservations[peerIDKey]
  1178. // We don't count reservations that were created from a canned funding
  1179. // shim. The user has registered the shim and therefore expects this
  1180. // channel to arrive.
  1181. numPending := 0
  1182. for _, res := range reservations {
  1183. if !res.reservation.IsCannedShim() {
  1184. numPending++
  1185. }
  1186. }
  1187. f.resMtx.RUnlock()
  1188. // Create the channel identifier.
  1189. cid := newChanIdentifier(msg.PendingChannelID)
  1190. // Also count the channels that are already pending. There we don't know
  1191. // the underlying intent anymore, unfortunately.
  1192. channels, err := f.cfg.ChannelDB.FetchOpenChannels(peerPubKey)
  1193. if err != nil {
  1194. f.failFundingFlow(peer, cid, err)
  1195. return
  1196. }
  1197. for _, c := range channels {
  1198. // Pending channels that have a non-zero thaw height were also
  1199. // created through a canned funding shim. Those also don't
  1200. // count towards the DoS protection limit.
  1201. //
  1202. // TODO(guggero): Properly store the funding type (wallet, shim,
  1203. // PSBT) on the channel so we don't need to use the thaw height.
  1204. if c.IsPending && c.ThawHeight == 0 {
  1205. numPending++
  1206. }
  1207. }
  1208. // TODO(roasbeef): modify to only accept a _single_ pending channel per
  1209. // block unless white listed
  1210. if numPending >= f.cfg.MaxPendingChannels {
  1211. f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
  1212. return
  1213. }
  1214. // Ensure that the pendingChansLimit is respected.
  1215. pendingChans, err := f.cfg.ChannelDB.FetchPendingChannels()
  1216. if err != nil {
  1217. f.failFundingFlow(peer, cid, err)
  1218. return
  1219. }
  1220. if len(pendingChans) > pendingChansLimit {
  1221. f.failFundingFlow(peer, cid, lnwire.ErrMaxPendingChannels)
  1222. return
  1223. }
  1224. // We'll also reject any requests to create channels until we're fully
  1225. // synced to the network as we won't be able to properly validate the
  1226. // confirmation of the funding transaction.
  1227. isSynced, _, err := f.cfg.Wallet.IsSynced()
  1228. if err != nil || !isSynced {
  1229. if err != nil {
  1230. log.Errorf("unable to query wallet: %v", err)
  1231. }
  1232. err := errors.New("Synchronizing blockchain")
  1233. f.failFundingFlow(peer, cid, err)
  1234. return
  1235. }
  1236. // Ensure that the remote party respects our maximum channel size.
  1237. if amt > f.cfg.MaxChanSize {
  1238. f.failFundingFlow(
  1239. peer, cid,
  1240. lnwallet.ErrChanTooLarge(amt, f.cfg.MaxChanSize),
  1241. )
  1242. return
  1243. }
  1244. // We'll, also ensure that the remote party isn't attempting to propose
  1245. // a channel that's below our current min channel size.
  1246. if amt < f.cfg.MinChanSize {
  1247. f.failFundingFlow(
  1248. peer, cid,
  1249. lnwallet.ErrChanTooSmall(amt, f.cfg.MinChanSize),
  1250. )
  1251. return
  1252. }
  1253. // If request specifies non-zero push amount and 'rejectpush' is set,
  1254. // signal an error.
  1255. if f.cfg.RejectPush && msg.PushAmount > 0 {
  1256. f.failFundingFlow(peer, cid, lnwallet.ErrNonZeroPushAmount())
  1257. return
  1258. }
  1259. // Send the OpenChannel request to the ChannelAcceptor to determine
  1260. // whether this node will accept the channel.
  1261. chanReq := &chanacceptor.ChannelAcceptRequest{
  1262. Node: peer.IdentityKey(),
  1263. OpenChanMsg: msg,
  1264. }
  1265. // Query our channel acceptor to determine whether we should reject
  1266. // the channel.
  1267. acceptorResp := f.cfg.OpenChannelPredicate.Accept(chanReq)
  1268. if acceptorResp.RejectChannel() {
  1269. f.failFundingFlow(peer, cid, acceptorResp.ChanAcceptError)
  1270. return
  1271. }
  1272. log.Infof("Recv'd fundingRequest(amt=%v, push=%v, delay=%v, "+
  1273. "pendingId=%x) from peer(%x)", amt, msg.PushAmount,
  1274. msg.CsvDelay, msg.PendingChannelID,
  1275. peer.IdentityKey().SerializeCompressed())
  1276. // Attempt to initialize a reservation within the wallet. If the wallet
  1277. // has insufficient resources to create the channel, then the
  1278. // reservation attempt may be rejected. Note that since we're on the
  1279. // responding side of a single funder workflow, we don't commit any
  1280. // funds to the channel ourselves.
  1281. //
  1282. // Before we init the channel, we'll also check to see what commitment
  1283. // format we can use with this peer. This is dependent on *both* us and
  1284. // the remote peer are signaling the proper feature bit if we're using
  1285. // implicit negotiation, and simply the channel type sent over if we're
  1286. // using explicit negotiation.
  1287. chanType, commitType, err := negotiateCommitmentType(
  1288. msg.ChannelType, peer.LocalFeatures(), peer.RemoteFeatures(),
  1289. )
  1290. if err != nil {
  1291. // TODO(roasbeef): should be using soft errors
  1292. log.Errorf("channel type negotiation failed: %v", err)
  1293. f.failFundingFlow(peer, cid, err)
  1294. return
  1295. }
  1296. var scidFeatureVal bool
  1297. if hasFeatures(
  1298. peer.LocalFeatures(), peer.RemoteFeatures(),
  1299. lnwire.ScidAliasOptional,
  1300. ) {
  1301. scidFeatureVal = true
  1302. }
  1303. var (
  1304. zeroConf bool
  1305. scid bool
  1306. )
  1307. // Only echo back a channel type in AcceptChannel if we actually used
  1308. // explicit negotiation above.
  1309. if chanType != nil {
  1310. // Check if the channel type includes the zero-conf or
  1311. // scid-alias bits.
  1312. featureVec := lnwire.RawFeatureVector(*chanType)
  1313. zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
  1314. scid = featureVec.IsSet(lnwire.ScidAliasRequired)
  1315. // If the zero-conf channel type was negotiated, ensure that
  1316. // the acceptor allows it.
  1317. if zeroConf && !acceptorResp.ZeroConf {
  1318. // Fail the funding flow.
  1319. flowErr := fmt.Errorf("channel acceptor blocked " +
  1320. "zero-conf channel negotiation")
  1321. log.Errorf("Cancelling funding flow for %v based on "+
  1322. "channel acceptor response: %v", cid, flowErr)
  1323. f.failFundingFlow(peer, cid, flowErr)
  1324. return
  1325. }
  1326. // If the zero-conf channel type wasn't negotiated and the
  1327. // fundee still wants a zero-conf channel, perform more checks.
  1328. // Require that both sides have the scid-alias feature bit set.
  1329. // We don't require anchors here - this is for compatibility
  1330. // with LDK.
  1331. if !zeroConf && acceptorResp.ZeroConf {
  1332. if !scidFeatureVal {
  1333. // Fail the funding flow.
  1334. flowErr := fmt.Errorf("scid-alias feature " +
  1335. "must be negotiated for zero-conf")
  1336. log.Errorf("Cancelling funding flow for "+
  1337. "zero-conf channel %v: %v", cid,
  1338. flowErr)
  1339. f.failFundingFlow(peer, cid, flowErr)
  1340. return
  1341. }
  1342. // Set zeroConf to true to enable the zero-conf flow.
  1343. zeroConf = true
  1344. }
  1345. }
  1346. public := msg.ChannelFlags&lnwire.FFAnnounceChannel != 0
  1347. switch {
  1348. // Sending the option-scid-alias channel type for a public channel is
  1349. // disallowed.
  1350. case public && scid:
  1351. err = fmt.Errorf("option-scid-alias chantype for public " +
  1352. "channel")
  1353. log.Errorf("Cancelling funding flow for public channel %v "+
  1354. "with scid-alias: %v", cid, err)
  1355. f.failFundingFlow(peer, cid, err)
  1356. return
  1357. // The current variant of taproot channels can only be used with
  1358. // unadvertised channels for now.
  1359. case commitType.IsTaproot() && public:
  1360. err = fmt.Errorf("taproot channel type for public channel")
  1361. log.Errorf("Cancelling funding flow for public taproot "+
  1362. "channel %v: %v", cid, err)
  1363. f.failFundingFlow(peer, cid, err)
  1364. return
  1365. }
  1366. req := &lnwallet.InitFundingReserveMsg{
  1367. ChainHash: &msg.ChainHash,
  1368. PendingChanID: msg.PendingChannelID,
  1369. NodeID: peer.IdentityKey(),
  1370. NodeAddr: peer.Address(),
  1371. LocalFundingAmt: 0,
  1372. RemoteFundingAmt: amt,
  1373. CommitFeePerKw: chainfee.SatPerKWeight(msg.FeePerKiloWeight),
  1374. FundingFeePerKw: 0,
  1375. PushMSat: msg.PushAmount,
  1376. Flags: msg.ChannelFlags,
  1377. MinConfs: 1,
  1378. CommitType: commitType,
  1379. ZeroConf: zeroConf,
  1380. OptionScidAlias: scid,
  1381. ScidAliasFeature: scidFeatureVal,
  1382. }
  1383. reservation, err := f.cfg.Wallet.InitChannelReservation(req)
  1384. if err != nil {
  1385. log.Errorf("Unable to initialize reservation: %v", err)
  1386. f.failFundingFlow(peer, cid, err)
  1387. return
  1388. }
  1389. log.Debugf("Initialized channel reservation: zeroConf=%v, psbt=%v, "+
  1390. "cannedShim=%v", reservation.IsZeroConf(),
  1391. reservation.IsPsbt(), reservation.IsCannedShim())
  1392. if zeroConf {
  1393. // Store an alias for zero-conf channels. Other option-scid
  1394. // channels will do this at a later point.
  1395. aliasScid, err := f.cfg.AliasManager.RequestAlias()
  1396. if err != nil {
  1397. log.Errorf("Unable to request alias: %v", err)
  1398. f.failFundingFlow(peer, cid, err)
  1399. return
  1400. }
  1401. reservation.AddAlias(aliasScid)
  1402. }
  1403. // As we're the responder, we get to specify the number of confirmations
  1404. // that we require before both of us consider the channel open. We'll
  1405. // use our mapping to derive the proper number of confirmations based on
  1406. // the amount of the channel, and also if any funds are being pushed to
  1407. // us. If a depth value was set by our channel acceptor, we will use
  1408. // that value instead.
  1409. numConfsReq := f.cfg.NumRequiredConfs(msg.FundingAmount, msg.PushAmount)
  1410. if acceptorResp.MinAcceptDepth != 0 {
  1411. numConfsReq = acceptorResp.MinAcceptDepth
  1412. }
  1413. // We'll ignore the min_depth calculated above if this is a zero-conf
  1414. // channel.
  1415. if zeroConf {
  1416. numConfsReq = 0
  1417. }
  1418. reservation.SetNumConfsRequired(numConfsReq)
  1419. // We'll also validate and apply all the constraints the initiating
  1420. // party is attempting to dictate for our commitment transaction.
  1421. stateBounds := &channeldb.ChannelStateBounds{
  1422. ChanReserve: msg.ChannelReserve,
  1423. MaxPendingAmount: msg.MaxValueInFlight,
  1424. MinHTLC: msg.HtlcMinimum,
  1425. MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
  1426. }
  1427. commitParams := &channeldb.CommitmentParams{
  1428. DustLimit: msg.DustLimit,
  1429. CsvDelay: msg.CsvDelay,
  1430. }
  1431. err = reservation.CommitConstraints(
  1432. stateBounds, commitParams, f.cfg.MaxLocalCSVDelay, true,
  1433. )
  1434. if err != nil {
  1435. log.Errorf("Unacceptable channel constraints: %v", err)
  1436. f.failFundingFlow(peer, cid, err)
  1437. return
  1438. }
  1439. // Check whether the peer supports upfront shutdown, and get a new
  1440. // wallet address if our node is configured to set shutdown addresses by
  1441. // default. We use the upfront shutdown script provided by our channel
  1442. // acceptor (if any) in lieu of user input.
  1443. shutdown, err := getUpfrontShutdownScript(
  1444. f.cfg.EnableUpfrontShutdown, peer, acceptorResp.UpfrontShutdown,
  1445. f.selectShutdownScript,
  1446. )
  1447. if err != nil {
  1448. f.failFundingFlow(
  1449. peer, cid,
  1450. fmt.Errorf("getUpfrontShutdownScript error: %w", err),
  1451. )
  1452. return
  1453. }
  1454. reservation.SetOurUpfrontShutdown(shutdown)
  1455. // If a script enforced channel lease is being proposed, we'll need to
  1456. // validate its custom TLV records.
  1457. if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
  1458. if msg.LeaseExpiry == nil {
  1459. err := errors.New("missing lease expiry")
  1460. f.failFundingFlow(peer, cid, err)
  1461. return
  1462. }
  1463. // If we had a shim registered for this channel prior to
  1464. // receiving its corresponding OpenChannel message, then we'll
  1465. // validate the proposed LeaseExpiry against what was registered
  1466. // in our shim.
  1467. if reservation.LeaseExpiry() != 0 {
  1468. if uint32(*msg.LeaseExpiry) !=
  1469. reservation.LeaseExpiry() {
  1470. err := errors.New("lease expiry mismatch")
  1471. f.failFundingFlow(peer, cid, err)
  1472. return
  1473. }
  1474. }
  1475. }
  1476. log.Infof("Requiring %v confirmations for pendingChan(%x): "+
  1477. "amt=%v, push_amt=%v, committype=%v, upfrontShutdown=%x",
  1478. numConfsReq, msg.PendingChannelID, amt, msg.PushAmount,
  1479. commitType, msg.UpfrontShutdownScript)
  1480. // Generate our required constraints for the remote party, using the
  1481. // values provided by the channel acceptor if they are non-zero.
  1482. remoteCsvDelay := f.cfg.RequiredRemoteDelay(amt)
  1483. if acceptorResp.CSVDelay != 0 {
  1484. remoteCsvDelay = acceptorResp.CSVDelay
  1485. }
  1486. // If our default dust limit was above their ChannelReserve, we change
  1487. // it to the ChannelReserve. We must make sure the ChannelReserve we
  1488. // send in the AcceptChannel message is above both dust limits.
  1489. // Therefore, take the maximum of msg.DustLimit and our dust limit.
  1490. //
  1491. // NOTE: Even with this bounding, the ChannelAcceptor may return an
  1492. // BOLT#02-invalid ChannelReserve.
  1493. maxDustLimit := reservation.OurContribution().DustLimit
  1494. if msg.DustLimit > maxDustLimit {
  1495. maxDustLimit = msg.DustLimit
  1496. }
  1497. chanReserve := f.cfg.RequiredRemoteChanReserve(amt, maxDustLimit)
  1498. if acceptorResp.Reserve != 0 {
  1499. chanReserve = acceptorResp.Reserve
  1500. }
  1501. remoteMaxValue := f.cfg.RequiredRemoteMaxValue(amt)
  1502. if acceptorResp.InFlightTotal != 0 {
  1503. remoteMaxValue = acceptorResp.InFlightTotal
  1504. }
  1505. maxHtlcs := f.cfg.RequiredRemoteMaxHTLCs(amt)
  1506. if acceptorResp.HtlcLimit != 0 {
  1507. maxHtlcs = acceptorResp.HtlcLimit
  1508. }
  1509. // Default to our default minimum hltc value, replacing it with the
  1510. // channel acceptor's value if it is set.
  1511. minHtlc := f.cfg.DefaultMinHtlcIn
  1512. if acceptorResp.MinHtlcIn != 0 {
  1513. minHtlc = acceptorResp.MinHtlcIn
  1514. }
  1515. // If we are handling a FundingOpen request then we need to specify the
  1516. // default channel fees since they are not provided by the responder
  1517. // interactively.
  1518. ourContribution := reservation.OurContribution()
  1519. forwardingPolicy := f.defaultForwardingPolicy(
  1520. ourContribution.ChannelStateBounds,
  1521. )
  1522. // Once the reservation has been created successfully, we add it to
  1523. // this peer's map of pending reservations to track this particular
  1524. // reservation until either abort or completion.
  1525. f.resMtx.Lock()
  1526. if _, ok := f.activeReservations[peerIDKey]; !ok {
  1527. f.activeReservations[peerIDKey] = make(pendingChannels)
  1528. }
  1529. resCtx := &reservationWithCtx{
  1530. reservation: reservation,
  1531. chanAmt: amt,
  1532. forwardingPolicy: *forwardingPolicy,
  1533. remoteCsvDelay: remoteCsvDelay,
  1534. remoteMinHtlc: minHtlc,
  1535. remoteMaxValue: remoteMaxValue,
  1536. remoteMaxHtlcs: maxHtlcs,
  1537. remoteChanReserve: chanReserve,
  1538. maxLocalCsv: f.cfg.MaxLocalCSVDelay,
  1539. channelType: chanType,
  1540. err: make(chan error, 1),
  1541. peer: peer,
  1542. }
  1543. f.activeReservations[peerIDKey][msg.PendingChannelID] = resCtx
  1544. f.resMtx.Unlock()
  1545. // Update the timestamp once the fundingOpenMsg has been handled.
  1546. defer resCtx.updateTimestamp()
  1547. cfg := channeldb.ChannelConfig{
  1548. ChannelStateBounds: channeldb.ChannelStateBounds{
  1549. MaxPendingAmount: remoteMaxValue,
  1550. ChanReserve: chanReserve,
  1551. MinHTLC: minHtlc,
  1552. MaxAcceptedHtlcs: maxHtlcs,
  1553. },
  1554. CommitmentParams: channeldb.CommitmentParams{
  1555. DustLimit: msg.DustLimit,
  1556. CsvDelay: remoteCsvDelay,
  1557. },
  1558. MultiSigKey: keychain.KeyDescriptor{
  1559. PubKey: copyPubKey(msg.FundingKey),
  1560. },
  1561. RevocationBasePoint: keychain.KeyDescriptor{
  1562. PubKey: copyPubKey(msg.RevocationPoint),
  1563. },
  1564. PaymentBasePoint: keychain.KeyDescriptor{
  1565. PubKey: copyPubKey(msg.PaymentPoint),
  1566. },
  1567. DelayBasePoint: keychain.KeyDescriptor{
  1568. PubKey: copyPubKey(msg.DelayedPaymentPoint),
  1569. },
  1570. HtlcBasePoint: keychain.KeyDescriptor{
  1571. PubKey: copyPubKey(msg.HtlcPoint),
  1572. },
  1573. }
  1574. // With our parameters set, we'll now process their contribution so we
  1575. // can move the funding workflow ahead.
  1576. remoteContribution := &lnwallet.ChannelContribution{
  1577. FundingAmount: amt,
  1578. FirstCommitmentPoint: msg.FirstCommitmentPoint,
  1579. ChannelConfig: &cfg,
  1580. UpfrontShutdown: msg.UpfrontShutdownScript,
  1581. }
  1582. if resCtx.reservation.IsTaproot() {
  1583. localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
  1584. if err != nil {
  1585. log.Error(errNoLocalNonce)
  1586. f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
  1587. return
  1588. }
  1589. remoteContribution.LocalNonce = &musig2.Nonces{
  1590. PubNonce: localNonce,
  1591. }
  1592. }
  1593. err = reservation.ProcessSingleContribution(remoteContribution)
  1594. if err != nil {
  1595. log.Errorf("unable to add contribution reservation: %v", err)
  1596. f.failFundingFlow(peer, cid, err)
  1597. return
  1598. }
  1599. log.Infof("Sending fundingResp for pending_id(%x)",
  1600. msg.PendingChannelID)
  1601. bounds := remoteContribution.ChannelConfig.ChannelStateBounds
  1602. log.Debugf("Remote party accepted channel state space bounds: %v",
  1603. lnutils.SpewLogClosure(bounds))
  1604. params := remoteContribution.ChannelConfig.CommitmentParams
  1605. log.Debugf("Remote party accepted commitment rendering params: %v",
  1606. lnutils.SpewLogClosure(params))
  1607. // With the initiator's contribution recorded, respond with our
  1608. // contribution in the next message of the workflow.
  1609. fundingAccept := lnwire.AcceptChannel{
  1610. PendingChannelID: msg.PendingChannelID,
  1611. DustLimit: ourContribution.DustLimit,
  1612. MaxValueInFlight: remoteMaxValue,
  1613. ChannelReserve: chanReserve,
  1614. MinAcceptDepth: uint32(numConfsReq),
  1615. HtlcMinimum: minHtlc,
  1616. CsvDelay: remoteCsvDelay,
  1617. MaxAcceptedHTLCs: maxHtlcs,
  1618. FundingKey: ourContribution.MultiSigKey.PubKey,
  1619. RevocationPoint: ourContribution.RevocationBasePoint.PubKey,
  1620. PaymentPoint: ourContribution.PaymentBasePoint.PubKey,
  1621. DelayedPaymentPoint: ourContribution.DelayBasePoint.PubKey,
  1622. HtlcPoint: ourContribution.HtlcBasePoint.PubKey,
  1623. FirstCommitmentPoint: ourContribution.FirstCommitmentPoint,
  1624. UpfrontShutdownScript: ourContribution.UpfrontShutdown,
  1625. ChannelType: chanType,
  1626. LeaseExpiry: msg.LeaseExpiry,
  1627. }
  1628. if commitType.IsTaproot() {
  1629. fundingAccept.LocalNonce = lnwire.SomeMusig2Nonce(
  1630. ourContribution.LocalNonce.PubNonce,
  1631. )
  1632. }
  1633. if err := peer.SendMessage(true, &fundingAccept); err != nil {
  1634. log.Errorf("unable to send funding response to peer: %v", err)
  1635. f.failFundingFlow(peer, cid, err)
  1636. return
  1637. }
  1638. }
  1639. // funderProcessAcceptChannel processes a response to the workflow initiation
  1640. // sent by the remote peer. This message then queues a message with the funding
  1641. // outpoint, and a commitment signature to the remote peer.
  1642. //
  1643. //nolint:funlen
  1644. func (f *Manager) funderProcessAcceptChannel(peer lnpeer.Peer,
  1645. msg *lnwire.AcceptChannel) {
  1646. pendingChanID := msg.PendingChannelID
  1647. peerKey := peer.IdentityKey()
  1648. var peerKeyBytes []byte
  1649. if peerKey != nil {
  1650. peerKeyBytes = peerKey.SerializeCompressed()
  1651. }
  1652. resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
  1653. if err != nil {
  1654. log.Warnf("Can't find reservation (peerKey:%x, chan_id:%v)",
  1655. peerKeyBytes, pendingChanID)
  1656. return
  1657. }
  1658. // Update the timestamp once the fundingAcceptMsg has been handled.
  1659. defer resCtx.updateTimestamp()
  1660. log.Infof("Recv'd fundingResponse for pending_id(%x)",
  1661. pendingChanID[:])
  1662. // Create the channel identifier.
  1663. cid := newChanIdentifier(msg.PendingChannelID)
  1664. // Perform some basic validation of any custom TLV records included.
  1665. //
  1666. // TODO: Return errors as funding.Error to give context to remote peer?
  1667. if resCtx.channelType != nil {
  1668. // We'll want to quickly check that the ChannelType echoed by
  1669. // the channel request recipient matches what we proposed.
  1670. if msg.ChannelType == nil {
  1671. err := errors.New("explicit channel type not echoed " +
  1672. "back")
  1673. f.failFundingFlow(peer, cid, err)
  1674. return
  1675. }
  1676. proposedFeatures := lnwire.RawFeatureVector(*resCtx.channelType)
  1677. ackedFeatures := lnwire.RawFeatureVector(*msg.ChannelType)
  1678. if !proposedFeatures.Equals(&ackedFeatures) {
  1679. err := errors.New("channel type mismatch")
  1680. f.failFundingFlow(peer, cid, err)
  1681. return
  1682. }
  1683. // We'll want to do the same with the LeaseExpiry if one should
  1684. // be set.
  1685. if resCtx.reservation.LeaseExpiry() != 0 {
  1686. if msg.LeaseExpiry == nil {
  1687. err := errors.New("lease expiry not echoed " +
  1688. "back")
  1689. f.failFundingFlow(peer, cid, err)
  1690. return
  1691. }
  1692. if uint32(*msg.LeaseExpiry) !=
  1693. resCtx.reservation.LeaseExpiry() {
  1694. err := errors.New("lease expiry mismatch")
  1695. f.failFundingFlow(peer, cid, err)
  1696. return
  1697. }
  1698. }
  1699. } else if msg.ChannelType != nil {
  1700. // The spec isn't too clear about whether it's okay to set the
  1701. // channel type in the accept_channel response if we didn't
  1702. // explicitly set it in the open_channel message. For now, we
  1703. // check that it's the same type we'd have arrived through
  1704. // implicit negotiation. If it's another type, we fail the flow.
  1705. _, implicitCommitType := implicitNegotiateCommitmentType(
  1706. peer.LocalFeatures(), peer.RemoteFeatures(),
  1707. )
  1708. _, negotiatedCommitType, err := negotiateCommitmentType(
  1709. msg.ChannelType, peer.LocalFeatures(),
  1710. peer.RemoteFeatures(),
  1711. )
  1712. if err != nil {
  1713. err := errors.New("received unexpected channel type")
  1714. f.failFundingFlow(peer, cid, err)
  1715. return
  1716. }
  1717. if implicitCommitType != negotiatedCommitType {
  1718. err := errors.New("negotiated unexpected channel type")
  1719. f.failFundingFlow(peer, cid, err)
  1720. return
  1721. }
  1722. }
  1723. // The required number of confirmations should not be greater than the
  1724. // maximum number of confirmations required by the ChainNotifier to
  1725. // properly dispatch confirmations.
  1726. if msg.MinAcceptDepth > chainntnfs.MaxNumConfs {
  1727. err := lnwallet.ErrNumConfsTooLarge(
  1728. msg.MinAcceptDepth, chainntnfs.MaxNumConfs,
  1729. )
  1730. log.Warnf("Unacceptable channel constraints: %v", err)
  1731. f.failFundingFlow(peer, cid, err)
  1732. return
  1733. }
  1734. // Check that zero-conf channels have minimum depth set to 0.
  1735. if resCtx.reservation.IsZeroConf() && msg.MinAcceptDepth != 0 {
  1736. err = fmt.Errorf("zero-conf channel has min_depth non-zero")
  1737. log.Warn(err)
  1738. f.failFundingFlow(peer, cid, err)
  1739. return
  1740. }
  1741. // If this is not a zero-conf channel but the peer responded with a
  1742. // min-depth of zero, we will use our minimum of 1 instead.
  1743. minDepth := msg.MinAcceptDepth
  1744. if !resCtx.reservation.IsZeroConf() && minDepth == 0 {
  1745. log.Infof("Responder to pending_id=%v sent a minimum "+
  1746. "confirmation depth of 0 for non-zero-conf channel. "+
  1747. "We will use a minimum depth of 1 instead.",
  1748. cid.tempChanID)
  1749. minDepth = 1
  1750. }
  1751. // We'll also specify the responder's preference for the number of
  1752. // required confirmations, and also the set of channel constraints
  1753. // they've specified for commitment states we can create.
  1754. resCtx.reservation.SetNumConfsRequired(uint16(minDepth))
  1755. bounds := channeldb.ChannelStateBounds{
  1756. ChanReserve: msg.ChannelReserve,
  1757. MaxPendingAmount: msg.MaxValueInFlight,
  1758. MinHTLC: msg.HtlcMinimum,
  1759. MaxAcceptedHtlcs: msg.MaxAcceptedHTLCs,
  1760. }
  1761. commitParams := channeldb.CommitmentParams{
  1762. DustLimit: msg.DustLimit,
  1763. CsvDelay: msg.CsvDelay,
  1764. }
  1765. err = resCtx.reservation.CommitConstraints(
  1766. &bounds, &commitParams, resCtx.maxLocalCsv, false,
  1767. )
  1768. if err != nil {
  1769. log.Warnf("Unacceptable channel constraints: %v", err)
  1770. f.failFundingFlow(peer, cid, err)
  1771. return
  1772. }
  1773. cfg := channeldb.ChannelConfig{
  1774. ChannelStateBounds: channeldb.ChannelStateBounds{
  1775. MaxPendingAmount: resCtx.remoteMaxValue,
  1776. ChanReserve: resCtx.remoteChanReserve,
  1777. MinHTLC: resCtx.remoteMinHtlc,
  1778. MaxAcceptedHtlcs: resCtx.remoteMaxHtlcs,
  1779. },
  1780. CommitmentParams: channeldb.CommitmentParams{
  1781. DustLimit: msg.DustLimit,
  1782. CsvDelay: resCtx.remoteCsvDelay,
  1783. },
  1784. MultiSigKey: keychain.KeyDescriptor{
  1785. PubKey: copyPubKey(msg.FundingKey),
  1786. },
  1787. RevocationBasePoint: keychain.KeyDescriptor{
  1788. PubKey: copyPubKey(msg.RevocationPoint),
  1789. },
  1790. PaymentBasePoint: keychain.KeyDescriptor{
  1791. PubKey: copyPubKey(msg.PaymentPoint),
  1792. },
  1793. DelayBasePoint: keychain.KeyDescriptor{
  1794. PubKey: copyPubKey(msg.DelayedPaymentPoint),
  1795. },
  1796. HtlcBasePoint: keychain.KeyDescriptor{
  1797. PubKey: copyPubKey(msg.HtlcPoint),
  1798. },
  1799. }
  1800. // The remote node has responded with their portion of the channel
  1801. // contribution. At this point, we can process their contribution which
  1802. // allows us to construct and sign both the commitment transaction, and
  1803. // the funding transaction.
  1804. remoteContribution := &lnwallet.ChannelContribution{
  1805. FirstCommitmentPoint: msg.FirstCommitmentPoint,
  1806. ChannelConfig: &cfg,
  1807. UpfrontShutdown: msg.UpfrontShutdownScript,
  1808. }
  1809. if resCtx.reservation.IsTaproot() {
  1810. localNonce, err := msg.LocalNonce.UnwrapOrErrV(errNoLocalNonce)
  1811. if err != nil {
  1812. log.Error(errNoLocalNonce)
  1813. f.failFundingFlow(resCtx.peer, cid, errNoLocalNonce)
  1814. return
  1815. }
  1816. remoteContribution.LocalNonce = &musig2.Nonces{
  1817. PubNonce: localNonce,
  1818. }
  1819. }
  1820. err = resCtx.reservation.ProcessContribution(remoteContribution)
  1821. // The wallet has detected that a PSBT funding process was requested by
  1822. // the user and has halted the funding process after negotiating the
  1823. // multisig keys. We now have everything that is needed for the user to
  1824. // start constructing a PSBT that sends to the multisig funding address.
  1825. var psbtIntent *chanfunding.PsbtIntent
  1826. if psbtErr, ok := err.(*lnwallet.PsbtFundingRequired); ok {
  1827. // Return the information that is needed by the user to
  1828. // construct the PSBT back to the caller.
  1829. addr, amt, packet, err := psbtErr.Intent.FundingParams()
  1830. if err != nil {
  1831. log.Errorf("Unable to process PSBT funding params "+
  1832. "for contribution from %x: %v", peerKeyBytes,
  1833. err)
  1834. f.failFundingFlow(peer, cid, err)
  1835. return
  1836. }
  1837. var buf bytes.Buffer
  1838. err = packet.Serialize(&buf)
  1839. if err != nil {
  1840. log.Errorf("Unable to serialize PSBT for "+
  1841. "contribution from %x: %v", peerKeyBytes, err)
  1842. f.failFundingFlow(peer, cid, err)
  1843. return
  1844. }
  1845. resCtx.updates <- &lnrpc.OpenStatusUpdate{
  1846. PendingChanId: pendingChanID[:],
  1847. Update: &lnrpc.OpenStatusUpdate_PsbtFund{
  1848. PsbtFund: &lnrpc.ReadyForPsbtFunding{
  1849. FundingAddress: addr.EncodeAddress(),
  1850. FundingAmount: amt,
  1851. Psbt: buf.Bytes(),
  1852. },
  1853. },
  1854. }
  1855. psbtIntent = psbtErr.Intent
  1856. } else if err != nil {
  1857. log.Errorf("Unable to process contribution from %x: %v",
  1858. peerKeyBytes, err)
  1859. f.failFundingFlow(peer, cid, err)
  1860. return
  1861. }
  1862. log.Infof("pendingChan(%x): remote party proposes num_confs=%v, "+
  1863. "csv_delay=%v", pendingChanID[:], msg.MinAcceptDepth,
  1864. msg.CsvDelay)
  1865. bounds = remoteContribution.ChannelConfig.ChannelStateBounds
  1866. log.Debugf("Remote party accepted channel state space bounds: %v",
  1867. lnutils.SpewLogClosure(bounds))
  1868. commitParams = remoteContribution.ChannelConfig.CommitmentParams
  1869. log.Debugf("Remote party accepted commitment rendering params: %v",
  1870. lnutils.SpewLogClosure(commitParams))
  1871. // If the user requested funding through a PSBT, we cannot directly
  1872. // continue now and need to wait for the fully funded and signed PSBT
  1873. // to arrive. To not block any other channels from opening, we wait in
  1874. // a separate goroutine.
  1875. if psbtIntent != nil {
  1876. f.wg.Add(1)
  1877. go func() {
  1878. defer f.wg.Done()
  1879. f.waitForPsbt(psbtIntent, resCtx, cid)
  1880. }()
  1881. // With the new goroutine spawned, we can now exit to unblock
  1882. // the main event loop.
  1883. return
  1884. }
  1885. // In a normal, non-PSBT funding flow, we can jump directly to the next
  1886. // step where we expect our contribution to be finalized.
  1887. f.continueFundingAccept(resCtx, cid)
  1888. }
  1889. // waitForPsbt blocks until either a signed PSBT arrives, an error occurs or
  1890. // the funding manager shuts down. In the case of a valid PSBT, the funding flow
  1891. // is continued.
  1892. //
  1893. // NOTE: This method must be called as a goroutine.
  1894. func (f *Manager) waitForPsbt(intent *chanfunding.PsbtIntent,
  1895. resCtx *reservationWithCtx, cid *chanIdentifier) {
  1896. // failFlow is a helper that logs an error message with the current
  1897. // context and then fails the funding flow.
  1898. peerKey := resCtx.peer.IdentityKey()
  1899. failFlow := func(errMsg string, cause error) {
  1900. log.Errorf("Unable to handle funding accept message "+
  1901. "for peer_key=%x, pending_chan_id=%x: %s: %v",
  1902. peerKey.SerializeCompressed(), cid.tempChanID, errMsg,
  1903. cause)
  1904. f.failFundingFlow(resCtx.peer, cid, cause)
  1905. }
  1906. // We'll now wait until the intent has received the final and complete
  1907. // funding transaction. If the channel is closed without any error being
  1908. // sent, we know everything's going as expected.
  1909. select {
  1910. case err := <-intent.PsbtReady:
  1911. switch err {
  1912. // If the user canceled the funding reservation, we need to
  1913. // inform the other peer about us canceling the reservation.
  1914. case chanfunding.ErrUserCanceled:
  1915. failFlow("aborting PSBT flow", err)
  1916. return
  1917. // If the remote canceled the funding reservation, we don't need
  1918. // to send another fail message. But we want to inform the user
  1919. // about what happened.
  1920. case chanfunding.ErrRemoteCanceled:
  1921. log.Infof("Remote canceled, aborting PSBT flow "+
  1922. "for peer_key=%x, pending_chan_id=%x",
  1923. peerKey.SerializeCompressed(), cid.tempChanID)
  1924. return
  1925. // Nil error means the flow continues normally now.
  1926. case nil:
  1927. // For any other error, we'll fail the funding flow.
  1928. default:
  1929. failFlow("error waiting for PSBT flow", err)
  1930. return
  1931. }
  1932. // A non-nil error means we can continue the funding flow.
  1933. // Notify the wallet so it can prepare everything we need to
  1934. // continue.
  1935. err = resCtx.reservation.ProcessPsbt()
  1936. if err != nil {
  1937. failFlow("error continuing PSBT flow", err)
  1938. return
  1939. }
  1940. // We are now ready to continue the funding flow.
  1941. f.continueFundingAccept(resCtx, cid)
  1942. // Handle a server shutdown as well because the reservation won't
  1943. // survive a restart as it's in memory only.
  1944. case <-f.quit:
  1945. log.Errorf("Unable to handle funding accept message "+
  1946. "for peer_key=%x, pending_chan_id=%x: funding manager "+
  1947. "shutting down", peerKey.SerializeCompressed(),
  1948. cid.tempChanID)
  1949. return
  1950. }
  1951. }
  1952. // continueFundingAccept continues the channel funding flow once our
  1953. // contribution is finalized, the channel output is known and the funding
  1954. // transaction is signed.
  1955. func (f *Manager) continueFundingAccept(resCtx *reservationWithCtx,
  1956. cid *chanIdentifier) {
  1957. // Now that we have their contribution, we can extract, then send over
  1958. // both the funding out point and our signature for their version of
  1959. // the commitment transaction to the remote peer.
  1960. outPoint := resCtx.reservation.FundingOutpoint()
  1961. _, sig := resCtx.reservation.OurSignatures()
  1962. // A new channel has almost finished the funding process. In order to
  1963. // properly synchronize with the writeHandler goroutine, we add a new
  1964. // channel to the barriers map which will be closed once the channel is
  1965. // fully open.
  1966. channelID := lnwire.NewChanIDFromOutPoint(*outPoint)
  1967. log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
  1968. // The next message that advances the funding flow will reference the
  1969. // channel via its permanent channel ID, so we'll set up this mapping
  1970. // so we can retrieve the reservation context once we get the
  1971. // FundingSigned message.
  1972. f.resMtx.Lock()
  1973. f.signedReservations[channelID] = cid.tempChanID
  1974. f.resMtx.Unlock()
  1975. log.Infof("Generated ChannelPoint(%v) for pending_id(%x)", outPoint,
  1976. cid.tempChanID[:])
  1977. // Before sending FundingCreated sent, we notify Brontide to keep track
  1978. // of this pending open channel.
  1979. err := resCtx.peer.AddPendingChannel(channelID, f.quit)
  1980. if err != nil {
  1981. pubKey := resCtx.peer.IdentityKey().SerializeCompressed()
  1982. log.Errorf("Unable to add pending channel %v with peer %x: %v",
  1983. channelID, pubKey, err)
  1984. }
  1985. // Once Brontide is aware of this channel, we need to set it in
  1986. // chanIdentifier so this channel will be removed from Brontide if the
  1987. // funding flow fails.
  1988. cid.setChanID(channelID)
  1989. // Send the FundingCreated msg.
  1990. fundingCreated := &lnwire.FundingCreated{
  1991. PendingChannelID: cid.tempChanID,
  1992. FundingPoint: *outPoint,
  1993. }
  1994. // If this is a taproot channel, then we'll need to populate the musig2
  1995. // partial sig field instead of the regular commit sig field.
  1996. if resCtx.reservation.IsTaproot() {
  1997. partialSig, ok := sig.(*lnwallet.MusigPartialSig)
  1998. if !ok {
  1999. err := fmt.Errorf("expected musig partial sig, got %T",
  2000. sig)
  2001. log.Error(err)
  2002. f.failFundingFlow(resCtx.peer, cid, err)
  2003. return
  2004. }
  2005. fundingCreated.PartialSig = lnwire.MaybePartialSigWithNonce(
  2006. partialSig.ToWireSig(),
  2007. )
  2008. } else {
  2009. fundingCreated.CommitSig, err = lnwire.NewSigFromSignature(sig)
  2010. if err != nil {
  2011. log.Errorf("Unable to parse signature: %v", err)
  2012. f.failFundingFlow(resCtx.peer, cid, err)
  2013. return
  2014. }
  2015. }
  2016. if err := resCtx.peer.SendMessage(true, fundingCreated); err != nil {
  2017. log.Errorf("Unable to send funding complete message: %v", err)
  2018. f.failFundingFlow(resCtx.peer, cid, err)
  2019. return
  2020. }
  2021. }
  2022. // fundeeProcessFundingCreated progresses the funding workflow when the daemon
  2023. // is on the responding side of a single funder workflow. Once this message has
  2024. // been processed, a signature is sent to the remote peer allowing it to
  2025. // broadcast the funding transaction, progressing the workflow into the final
  2026. // stage.
  2027. //
  2028. //nolint:funlen
  2029. func (f *Manager) fundeeProcessFundingCreated(peer lnpeer.Peer,
  2030. msg *lnwire.FundingCreated) {
  2031. peerKey := peer.IdentityKey()
  2032. pendingChanID := msg.PendingChannelID
  2033. resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
  2034. if err != nil {
  2035. log.Warnf("can't find reservation (peer_id:%v, chan_id:%x)",
  2036. peerKey, pendingChanID[:])
  2037. return
  2038. }
  2039. // The channel initiator has responded with the funding outpoint of the
  2040. // final funding transaction, as well as a signature for our version of
  2041. // the commitment transaction. So at this point, we can validate the
  2042. // initiator's commitment transaction, then send our own if it's valid.
  2043. // TODO(roasbeef): make case (p vs P) consistent throughout
  2044. fundingOut := msg.FundingPoint
  2045. log.Infof("completing pending_id(%x) with ChannelPoint(%v)",
  2046. pendingChanID[:], fundingOut)
  2047. // Create the channel identifier without setting the active channel ID.
  2048. cid := newChanIdentifier(pendingChanID)
  2049. // For taproot channels, the commit signature is actually the partial
  2050. // signature. Otherwise, we can convert the ECDSA commit signature into
  2051. // our internal input.Signature type.
  2052. var commitSig input.Signature
  2053. if resCtx.reservation.IsTaproot() {
  2054. partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
  2055. if err != nil {
  2056. f.failFundingFlow(peer, cid, err)
  2057. return
  2058. }
  2059. commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
  2060. &partialSig,
  2061. )
  2062. } else {
  2063. commitSig, err = msg.CommitSig.ToSignature()
  2064. if err != nil {
  2065. log.Errorf("unable to parse signature: %v", err)
  2066. f.failFundingFlow(peer, cid, err)
  2067. return
  2068. }
  2069. }
  2070. // With all the necessary data available, attempt to advance the
  2071. // funding workflow to the next stage. If this succeeds then the
  2072. // funding transaction will broadcast after our next message.
  2073. // CompleteReservationSingle will also mark the channel as 'IsPending'
  2074. // in the database.
  2075. completeChan, err := resCtx.reservation.CompleteReservationSingle(
  2076. &fundingOut, commitSig,
  2077. )
  2078. if err != nil {
  2079. // TODO(roasbeef): better error logging: peerID, channelID, etc.
  2080. log.Errorf("unable to complete single reservation: %v", err)
  2081. f.failFundingFlow(peer, cid, err)
  2082. return
  2083. }
  2084. // Get forwarding policy before deleting the reservation context.
  2085. forwardingPolicy := resCtx.forwardingPolicy
  2086. // The channel is marked IsPending in the database, and can be removed
  2087. // from the set of active reservations.
  2088. f.deleteReservationCtx(peerKey, cid.tempChanID)
  2089. // If something goes wrong before the funding transaction is confirmed,
  2090. // we use this convenience method to delete the pending OpenChannel
  2091. // from the database.
  2092. deleteFromDatabase := func() {
  2093. localBalance := completeChan.LocalCommitment.LocalBalance.ToSatoshis()
  2094. closeInfo := &channeldb.ChannelCloseSummary{
  2095. ChanPoint: completeChan.FundingOutpoint,
  2096. ChainHash: completeChan.ChainHash,
  2097. RemotePub: completeChan.IdentityPub,
  2098. CloseType: channeldb.FundingCanceled,
  2099. Capacity: completeChan.Capacity,
  2100. SettledBalance: localBalance,
  2101. RemoteCurrentRevocation: completeChan.RemoteCurrentRevocation,
  2102. RemoteNextRevocation: completeChan.RemoteNextRevocation,
  2103. LocalChanConfig: completeChan.LocalChanCfg,
  2104. }
  2105. // Close the channel with us as the initiator because we are
  2106. // deciding to exit the funding flow due to an internal error.
  2107. if err := completeChan.CloseChannel(
  2108. closeInfo, channeldb.ChanStatusLocalCloseInitiator,
  2109. ); err != nil {
  2110. log.Errorf("Failed closing channel %v: %v",
  2111. completeChan.FundingOutpoint, err)
  2112. }
  2113. }
  2114. // A new channel has almost finished the funding process. In order to
  2115. // properly synchronize with the writeHandler goroutine, we add a new
  2116. // channel to the barriers map which will be closed once the channel is
  2117. // fully open.
  2118. channelID := lnwire.NewChanIDFromOutPoint(fundingOut)
  2119. log.Debugf("Creating chan barrier for ChanID(%v)", channelID)
  2120. fundingSigned := &lnwire.FundingSigned{}
  2121. // For taproot channels, we'll need to send over a partial signature
  2122. // that includes the nonce along side the signature.
  2123. _, sig := resCtx.reservation.OurSignatures()
  2124. if resCtx.reservation.IsTaproot() {
  2125. partialSig, ok := sig.(*lnwallet.MusigPartialSig)
  2126. if !ok {
  2127. err := fmt.Errorf("expected musig partial sig, got %T",
  2128. sig)
  2129. log.Error(err)
  2130. f.failFundingFlow(resCtx.peer, cid, err)
  2131. deleteFromDatabase()
  2132. return
  2133. }
  2134. fundingSigned.PartialSig = lnwire.MaybePartialSigWithNonce(
  2135. partialSig.ToWireSig(),
  2136. )
  2137. } else {
  2138. fundingSigned.CommitSig, err = lnwire.NewSigFromSignature(sig)
  2139. if err != nil {
  2140. log.Errorf("unable to parse signature: %v", err)
  2141. f.failFundingFlow(peer, cid, err)
  2142. deleteFromDatabase()
  2143. return
  2144. }
  2145. }
  2146. // Before sending FundingSigned, we notify Brontide first to keep track
  2147. // of this pending open channel.
  2148. if err := peer.AddPendingChannel(channelID, f.quit); err != nil {
  2149. pubKey := peer.IdentityKey().SerializeCompressed()
  2150. log.Errorf("Unable to add pending channel %v with peer %x: %v",
  2151. cid.chanID, pubKey, err)
  2152. }
  2153. // Once Brontide is aware of this channel, we need to set it in
  2154. // chanIdentifier so this channel will be removed from Brontide if the
  2155. // funding flow fails.
  2156. cid.setChanID(channelID)
  2157. fundingSigned.ChanID = cid.chanID
  2158. log.Infof("sending FundingSigned for pending_id(%x) over "+
  2159. "ChannelPoint(%v)", pendingChanID[:], fundingOut)
  2160. // With their signature for our version of the commitment transaction
  2161. // verified, we can now send over our signature to the remote peer.
  2162. if err := peer.SendMessage(true, fundingSigned); err != nil {
  2163. log.Errorf("unable to send FundingSigned message: %v", err)
  2164. f.failFundingFlow(peer, cid, err)
  2165. deleteFromDatabase()
  2166. return
  2167. }
  2168. // With a permanent channel id established we can save the respective
  2169. // forwarding policy in the database. In the channel announcement phase
  2170. // this forwarding policy is retrieved and applied.
  2171. err = f.saveInitialForwardingPolicy(cid.chanID, &forwardingPolicy)
  2172. if err != nil {
  2173. log.Errorf("Unable to store the forwarding policy: %v", err)
  2174. }
  2175. // Now that we've sent over our final signature for this channel, we'll
  2176. // send it to the ChainArbitrator so it can watch for any on-chain
  2177. // actions during this final confirmation stage.
  2178. if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
  2179. log.Errorf("Unable to send new ChannelPoint(%v) for "+
  2180. "arbitration: %v", fundingOut, err)
  2181. }
  2182. // Create an entry in the local discovery map so we can ensure that we
  2183. // process the channel confirmation fully before we receive a
  2184. // channel_ready message.
  2185. f.localDiscoverySignals.Store(cid.chanID, make(chan struct{}))
  2186. // Inform the ChannelNotifier that the channel has entered
  2187. // pending open state.
  2188. f.cfg.NotifyPendingOpenChannelEvent(fundingOut, completeChan)
  2189. // At this point we have sent our last funding message to the
  2190. // initiating peer before the funding transaction will be broadcast.
  2191. // With this last message, our job as the responder is now complete.
  2192. // We'll wait for the funding transaction to reach the specified number
  2193. // of confirmations, then start normal operations.
  2194. //
  2195. // When we get to this point we have sent the signComplete message to
  2196. // the channel funder, and BOLT#2 specifies that we MUST remember the
  2197. // channel for reconnection. The channel is already marked
  2198. // as pending in the database, so in case of a disconnect or restart,
  2199. // we will continue waiting for the confirmation the next time we start
  2200. // the funding manager. In case the funding transaction never appears
  2201. // on the blockchain, we must forget this channel. We therefore
  2202. // completely forget about this channel if we haven't seen the funding
  2203. // transaction in 288 blocks (~ 48 hrs), by canceling the reservation
  2204. // and canceling the wait for the funding confirmation.
  2205. f.wg.Add(1)
  2206. go f.advanceFundingState(completeChan, pendingChanID, nil)
  2207. }
  2208. // funderProcessFundingSigned processes the final message received in a single
  2209. // funder workflow. Once this message is processed, the funding transaction is
  2210. // broadcast. Once the funding transaction reaches a sufficient number of
  2211. // confirmations, a message is sent to the responding peer along with a compact
  2212. // encoding of the location of the channel within the blockchain.
  2213. func (f *Manager) funderProcessFundingSigned(peer lnpeer.Peer,
  2214. msg *lnwire.FundingSigned) {
  2215. // As the funding signed message will reference the reservation by its
  2216. // permanent channel ID, we'll need to perform an intermediate look up
  2217. // before we can obtain the reservation.
  2218. f.resMtx.Lock()
  2219. pendingChanID, ok := f.signedReservations[msg.ChanID]
  2220. delete(f.signedReservations, msg.ChanID)
  2221. f.resMtx.Unlock()
  2222. // Create the channel identifier and set the channel ID.
  2223. //
  2224. // NOTE: we may get an empty pending channel ID here if the key cannot
  2225. // be found, which means when we cancel the reservation context in
  2226. // `failFundingFlow`, we will get an error. In this case, we will send
  2227. // an error msg to our peer using the active channel ID.
  2228. //
  2229. // TODO(yy): refactor the funding flow to fix this case.
  2230. cid := newChanIdentifier(pendingChanID)
  2231. cid.setChanID(msg.ChanID)
  2232. // If the pending channel ID is not found, fail the funding flow.
  2233. if !ok {
  2234. // NOTE: we directly overwrite the pending channel ID here for
  2235. // this rare case since we don't have a valid pending channel
  2236. // ID.
  2237. cid.tempChanID = msg.ChanID
  2238. err := fmt.Errorf("unable to find signed reservation for "+
  2239. "chan_id=%x", msg.ChanID)
  2240. log.Warnf(err.Error())
  2241. f.failFundingFlow(peer, cid, err)
  2242. return
  2243. }
  2244. peerKey := peer.IdentityKey()
  2245. resCtx, err := f.getReservationCtx(peerKey, pendingChanID)
  2246. if err != nil {
  2247. log.Warnf("Unable to find reservation (peer_id:%v, "+
  2248. "chan_id:%x)", peerKey, pendingChanID[:])
  2249. // TODO: add ErrChanNotFound?
  2250. f.failFundingFlow(peer, cid, err)
  2251. return
  2252. }
  2253. // Create an entry in the local discovery map so we can ensure that we
  2254. // process the channel confirmation fully before we receive a
  2255. // channel_ready message.
  2256. fundingPoint := resCtx.reservation.FundingOutpoint()
  2257. permChanID := lnwire.NewChanIDFromOutPoint(*fundingPoint)
  2258. f.localDiscoverySignals.Store(permChanID, make(chan struct{}))
  2259. // We have to store the forwardingPolicy before the reservation context
  2260. // is deleted. The policy will then be read and applied in
  2261. // newChanAnnouncement.
  2262. err = f.saveInitialForwardingPolicy(
  2263. permChanID, &resCtx.forwardingPolicy,
  2264. )
  2265. if err != nil {
  2266. log.Errorf("Unable to store the forwarding policy: %v", err)
  2267. }
  2268. // For taproot channels, the commit signature is actually the partial
  2269. // signature. Otherwise, we can convert the ECDSA commit signature into
  2270. // our internal input.Signature type.
  2271. var commitSig input.Signature
  2272. if resCtx.reservation.IsTaproot() {
  2273. partialSig, err := msg.PartialSig.UnwrapOrErrV(errNoPartialSig)
  2274. if err != nil {
  2275. f.failFundingFlow(peer, cid, err)
  2276. return
  2277. }
  2278. commitSig = new(lnwallet.MusigPartialSig).FromWireSig(
  2279. &partialSig,
  2280. )
  2281. } else {
  2282. commitSig, err = msg.CommitSig.ToSignature()
  2283. if err != nil {
  2284. log.Errorf("unable to parse signature: %v", err)
  2285. f.failFundingFlow(peer, cid, err)
  2286. return
  2287. }
  2288. }
  2289. completeChan, err := resCtx.reservation.CompleteReservation(
  2290. nil, commitSig,
  2291. )
  2292. if err != nil {
  2293. log.Errorf("Unable to complete reservation sign "+
  2294. "complete: %v", err)
  2295. f.failFundingFlow(peer, cid, err)
  2296. return
  2297. }
  2298. // The channel is now marked IsPending in the database, and we can
  2299. // delete it from our set of active reservations.
  2300. f.deleteReservationCtx(peerKey, pendingChanID)
  2301. // Broadcast the finalized funding transaction to the network, but only
  2302. // if we actually have the funding transaction.
  2303. if completeChan.ChanType.HasFundingTx() {
  2304. fundingTx := completeChan.FundingTxn
  2305. var fundingTxBuf bytes.Buffer
  2306. if err := fundingTx.Serialize(&fundingTxBuf); err != nil {
  2307. log.Errorf("Unable to serialize funding "+
  2308. "transaction %v: %v", fundingTx.TxHash(), err)
  2309. // Clear the buffer of any bytes that were written
  2310. // before the serialization error to prevent logging an
  2311. // incomplete transaction.
  2312. fundingTxBuf.Reset()
  2313. }
  2314. log.Infof("Broadcasting funding tx for ChannelPoint(%v): %x",
  2315. completeChan.FundingOutpoint, fundingTxBuf.Bytes())
  2316. // Set a nil short channel ID at this stage because we do not
  2317. // know it until our funding tx confirms.
  2318. label := labels.MakeLabel(
  2319. labels.LabelTypeChannelOpen, nil,
  2320. )
  2321. err = f.cfg.PublishTransaction(fundingTx, label)
  2322. if err != nil {
  2323. log.Errorf("Unable to broadcast funding tx %x for "+
  2324. "ChannelPoint(%v): %v", fundingTxBuf.Bytes(),
  2325. completeChan.FundingOutpoint, err)
  2326. // We failed to broadcast the funding transaction, but
  2327. // watch the channel regardless, in case the
  2328. // transaction made it to the network. We will retry
  2329. // broadcast at startup.
  2330. //
  2331. // TODO(halseth): retry more often? Handle with CPFP?
  2332. // Just delete from the DB?
  2333. }
  2334. }
  2335. // Now that we have a finalized reservation for this funding flow,
  2336. // we'll send the to be active channel to the ChainArbitrator so it can
  2337. // watch for any on-chain actions before the channel has fully
  2338. // confirmed.
  2339. if err := f.cfg.WatchNewChannel(completeChan, peerKey); err != nil {
  2340. log.Errorf("Unable to send new ChannelPoint(%v) for "+
  2341. "arbitration: %v", fundingPoint, err)
  2342. }
  2343. log.Infof("Finalizing pending_id(%x) over ChannelPoint(%v), "+
  2344. "waiting for channel open on-chain", pendingChanID[:],
  2345. fundingPoint)
  2346. // Send an update to the upstream client that the negotiation process
  2347. // is over.
  2348. //
  2349. // TODO(roasbeef): add abstraction over updates to accommodate
  2350. // long-polling, or SSE, etc.
  2351. upd := &lnrpc.OpenStatusUpdate{
  2352. Update: &lnrpc.OpenStatusUpdate_ChanPending{
  2353. ChanPending: &lnrpc.PendingUpdate{
  2354. Txid: fundingPoint.Hash[:],
  2355. OutputIndex: fundingPoint.Index,
  2356. },
  2357. },
  2358. PendingChanId: pendingChanID[:],
  2359. }
  2360. select {
  2361. case resCtx.updates <- upd:
  2362. // Inform the ChannelNotifier that the channel has entered
  2363. // pending open state.
  2364. f.cfg.NotifyPendingOpenChannelEvent(*fundingPoint, completeChan)
  2365. case <-f.quit:
  2366. return
  2367. }
  2368. // At this point we have broadcast the funding transaction and done all
  2369. // necessary processing.
  2370. f.wg.Add(1)
  2371. go f.advanceFundingState(completeChan, pendingChanID, resCtx.updates)
  2372. }
  2373. // confirmedChannel wraps a confirmed funding transaction, as well as the short
  2374. // channel ID which identifies that channel into a single struct. We'll use
  2375. // this to pass around the final state of a channel after it has been
  2376. // confirmed.
  2377. type confirmedChannel struct {
  2378. // shortChanID expresses where in the block the funding transaction was
  2379. // located.
  2380. shortChanID lnwire.ShortChannelID
  2381. // fundingTx is the funding transaction that created the channel.
  2382. fundingTx *wire.MsgTx
  2383. }
  2384. // fundingTimeout is called when callers of waitForFundingWithTimeout receive
  2385. // an ErrConfirmationTimeout. It is used to clean-up channel state and mark the
  2386. // channel as closed. The error is only returned for the responder of the
  2387. // channel flow.
  2388. func (f *Manager) fundingTimeout(c *channeldb.OpenChannel,
  2389. pendingID PendingChanID) error {
  2390. // We'll get a timeout if the number of blocks mined since the channel
  2391. // was initiated reaches MaxWaitNumBlocksFundingConf and we are not the
  2392. // channel initiator.
  2393. localBalance := c.LocalCommitment.LocalBalance.ToSatoshis()
  2394. closeInfo := &channeldb.ChannelCloseSummary{
  2395. ChainHash: c.ChainHash,
  2396. ChanPoint: c.FundingOutpoint,
  2397. RemotePub: c.IdentityPub,
  2398. Capacity: c.Capacity,
  2399. SettledBalance: localBalance,
  2400. CloseType: channeldb.FundingCanceled,
  2401. RemoteCurrentRevocation: c.RemoteCurrentRevocation,
  2402. RemoteNextRevocation: c.RemoteNextRevocation,
  2403. LocalChanConfig: c.LocalChanCfg,
  2404. }
  2405. // Close the channel with us as the initiator because we are timing the
  2406. // channel out.
  2407. if err := c.CloseChannel(
  2408. closeInfo, channeldb.ChanStatusLocalCloseInitiator,
  2409. ); err != nil {
  2410. return fmt.Errorf("failed closing channel %v: %w",
  2411. c.FundingOutpoint, err)
  2412. }
  2413. timeoutErr := fmt.Errorf("timeout waiting for funding tx (%v) to "+
  2414. "confirm", c.FundingOutpoint)
  2415. // When the peer comes online, we'll notify it that we are now
  2416. // considering the channel flow canceled.
  2417. f.wg.Add(1)
  2418. go func() {
  2419. defer f.wg.Done()
  2420. peer, err := f.waitForPeerOnline(c.IdentityPub)
  2421. switch err {
  2422. // We're already shutting down, so we can just return.
  2423. case ErrFundingManagerShuttingDown:
  2424. return
  2425. // nil error means we continue on.
  2426. case nil:
  2427. // For unexpected errors, we print the error and still try to
  2428. // fail the funding flow.
  2429. default:
  2430. log.Errorf("Unexpected error while waiting for peer "+
  2431. "to come online: %v", err)
  2432. }
  2433. // Create channel identifier and set the channel ID.
  2434. cid := newChanIdentifier(pendingID)
  2435. cid.setChanID(lnwire.NewChanIDFromOutPoint(c.FundingOutpoint))
  2436. // TODO(halseth): should this send be made
  2437. // reliable?
  2438. // The reservation won't exist at this point, but we'll send an
  2439. // Error message over anyways with ChanID set to pendingID.
  2440. f.failFundingFlow(peer, cid, timeoutErr)
  2441. }()
  2442. return timeoutErr
  2443. }
  2444. // waitForFundingWithTimeout is a wrapper around waitForFundingConfirmation and
  2445. // waitForTimeout that will return ErrConfirmationTimeout if we are not the
  2446. // channel initiator and the MaxWaitNumBlocksFundingConf has passed from the
  2447. // funding broadcast height. In case of confirmation, the short channel ID of
  2448. // the channel and the funding transaction will be returned.
  2449. func (f *Manager) waitForFundingWithTimeout(
  2450. ch *channeldb.OpenChannel) (*confirmedChannel, error) {
  2451. confChan := make(chan *confirmedChannel)
  2452. timeoutChan := make(chan error, 1)
  2453. cancelChan := make(chan struct{})
  2454. f.wg.Add(1)
  2455. go f.waitForFundingConfirmation(ch, cancelChan, confChan)
  2456. // If we are not the initiator, we have no money at stake and will
  2457. // timeout waiting for the funding transaction to confirm after a
  2458. // while.
  2459. if !ch.IsInitiator && !ch.IsZeroConf() {
  2460. f.wg.Add(1)
  2461. go f.waitForTimeout(ch, cancelChan, timeoutChan)
  2462. }
  2463. defer close(cancelChan)
  2464. select {
  2465. case err := <-timeoutChan:
  2466. if err != nil {
  2467. return nil, err
  2468. }
  2469. return nil, ErrConfirmationTimeout
  2470. case <-f.quit:
  2471. // The fundingManager is shutting down, and will resume wait on
  2472. // startup.
  2473. return nil, ErrFundingManagerShuttingDown
  2474. case confirmedChannel, ok := <-confChan:
  2475. if !ok {
  2476. return nil, fmt.Errorf("waiting for funding" +
  2477. "confirmation failed")
  2478. }
  2479. return confirmedChannel, nil
  2480. }
  2481. }
  2482. // makeFundingScript re-creates the funding script for the funding transaction
  2483. // of the target channel.
  2484. func makeFundingScript(channel *channeldb.OpenChannel) ([]byte, error) {
  2485. localKey := channel.LocalChanCfg.MultiSigKey.PubKey
  2486. remoteKey := channel.RemoteChanCfg.MultiSigKey.PubKey
  2487. if channel.ChanType.IsTaproot() {
  2488. pkScript, _, err := input.GenTaprootFundingScript(
  2489. localKey, remoteKey, int64(channel.Capacity),
  2490. channel.TapscriptRoot,
  2491. )
  2492. if err != nil {
  2493. return nil, err
  2494. }
  2495. return pkScript, nil
  2496. }
  2497. multiSigScript, err := input.GenMultiSigScript(
  2498. localKey.SerializeCompressed(),
  2499. remoteKey.SerializeCompressed(),
  2500. )
  2501. if err != nil {
  2502. return nil, err
  2503. }
  2504. return input.WitnessScriptHash(multiSigScript)
  2505. }
  2506. // waitForFundingConfirmation handles the final stages of the channel funding
  2507. // process once the funding transaction has been broadcast. The primary
  2508. // function of waitForFundingConfirmation is to wait for blockchain
  2509. // confirmation, and then to notify the other systems that must be notified
  2510. // when a channel has become active for lightning transactions.
  2511. // The wait can be canceled by closing the cancelChan. In case of success,
  2512. // a *lnwire.ShortChannelID will be passed to confChan.
  2513. //
  2514. // NOTE: This MUST be run as a goroutine.
  2515. func (f *Manager) waitForFundingConfirmation(
  2516. completeChan *channeldb.OpenChannel, cancelChan <-chan struct{},
  2517. confChan chan<- *confirmedChannel) {
  2518. defer f.wg.Done()
  2519. defer close(confChan)
  2520. // Register with the ChainNotifier for a notification once the funding
  2521. // transaction reaches `numConfs` confirmations.
  2522. txid := completeChan.FundingOutpoint.Hash
  2523. fundingScript, err := makeFundingScript(completeChan)
  2524. if err != nil {
  2525. log.Errorf("unable to create funding script for "+
  2526. "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
  2527. err)
  2528. return
  2529. }
  2530. numConfs := uint32(completeChan.NumConfsRequired)
  2531. // If the underlying channel is a zero-conf channel, we'll set numConfs
  2532. // to 6, since it will be zero here.
  2533. if completeChan.IsZeroConf() {
  2534. numConfs = 6
  2535. }
  2536. confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
  2537. &txid, fundingScript, numConfs,
  2538. completeChan.BroadcastHeight(),
  2539. )
  2540. if err != nil {
  2541. log.Errorf("Unable to register for confirmation of "+
  2542. "ChannelPoint(%v): %v", completeChan.FundingOutpoint,
  2543. err)
  2544. return
  2545. }
  2546. log.Infof("Waiting for funding tx (%v) to reach %v confirmations",
  2547. txid, numConfs)
  2548. var confDetails *chainntnfs.TxConfirmation
  2549. var ok bool
  2550. // Wait until the specified number of confirmations has been reached,
  2551. // we get a cancel signal, or the wallet signals a shutdown.
  2552. select {
  2553. case confDetails, ok = <-confNtfn.Confirmed:
  2554. // fallthrough
  2555. case <-cancelChan:
  2556. log.Warnf("canceled waiting for funding confirmation, "+
  2557. "stopping funding flow for ChannelPoint(%v)",
  2558. completeChan.FundingOutpoint)
  2559. return
  2560. case <-f.quit:
  2561. log.Warnf("fundingManager shutting down, stopping funding "+
  2562. "flow for ChannelPoint(%v)",
  2563. completeChan.FundingOutpoint)
  2564. return
  2565. }
  2566. if !ok {
  2567. log.Warnf("ChainNotifier shutting down, cannot complete "+
  2568. "funding flow for ChannelPoint(%v)",
  2569. completeChan.FundingOutpoint)
  2570. return
  2571. }
  2572. fundingPoint := completeChan.FundingOutpoint
  2573. log.Infof("ChannelPoint(%v) is now active: ChannelID(%v)",
  2574. fundingPoint, lnwire.NewChanIDFromOutPoint(fundingPoint))
  2575. // With the block height and the transaction index known, we can
  2576. // construct the compact chanID which is used on the network to unique
  2577. // identify channels.
  2578. shortChanID := lnwire.ShortChannelID{
  2579. BlockHeight: confDetails.BlockHeight,
  2580. TxIndex: confDetails.TxIndex,
  2581. TxPosition: uint16(fundingPoint.Index),
  2582. }
  2583. select {
  2584. case confChan <- &confirmedChannel{
  2585. shortChanID: shortChanID,
  2586. fundingTx: confDetails.Tx,
  2587. }:
  2588. case <-f.quit:
  2589. return
  2590. }
  2591. }
  2592. // waitForTimeout will close the timeout channel if MaxWaitNumBlocksFundingConf
  2593. // has passed from the broadcast height of the given channel. In case of error,
  2594. // the error is sent on timeoutChan. The wait can be canceled by closing the
  2595. // cancelChan.
  2596. //
  2597. // NOTE: timeoutChan MUST be buffered.
  2598. // NOTE: This MUST be run as a goroutine.
  2599. func (f *Manager) waitForTimeout(completeChan *channeldb.OpenChannel,
  2600. cancelChan <-chan struct{}, timeoutChan chan<- error) {
  2601. defer f.wg.Done()
  2602. epochClient, err := f.cfg.Notifier.RegisterBlockEpochNtfn(nil)
  2603. if err != nil {
  2604. timeoutChan <- fmt.Errorf("unable to register for epoch "+
  2605. "notification: %v", err)
  2606. return
  2607. }
  2608. defer epochClient.Cancel()
  2609. // On block maxHeight we will cancel the funding confirmation wait.
  2610. broadcastHeight := completeChan.BroadcastHeight()
  2611. maxHeight := broadcastHeight + MaxWaitNumBlocksFundingConf
  2612. for {
  2613. select {
  2614. case epoch, ok := <-epochClient.Epochs:
  2615. if !ok {
  2616. timeoutChan <- fmt.Errorf("epoch client " +
  2617. "shutting down")
  2618. return
  2619. }
  2620. // Close the timeout channel and exit if the block is
  2621. // above the max height.
  2622. if uint32(epoch.Height) >= maxHeight {
  2623. log.Warnf("Waited for %v blocks without "+
  2624. "seeing funding transaction confirmed,"+
  2625. " cancelling.",
  2626. MaxWaitNumBlocksFundingConf)
  2627. // Notify the caller of the timeout.
  2628. close(timeoutChan)
  2629. return
  2630. }
  2631. // TODO: If we are the channel initiator implement
  2632. // a method for recovering the funds from the funding
  2633. // transaction
  2634. case <-cancelChan:
  2635. return
  2636. case <-f.quit:
  2637. // The fundingManager is shutting down, will resume
  2638. // waiting for the funding transaction on startup.
  2639. return
  2640. }
  2641. }
  2642. }
  2643. // makeLabelForTx updates the label for the confirmed funding transaction. If
  2644. // we opened the channel, and lnd's wallet published our funding tx (which is
  2645. // not the case for some channels) then we update our transaction label with
  2646. // our short channel ID, which is known now that our funding transaction has
  2647. // confirmed. We do not label transactions we did not publish, because our
  2648. // wallet has no knowledge of them.
  2649. func (f *Manager) makeLabelForTx(c *channeldb.OpenChannel) {
  2650. if c.IsInitiator && c.ChanType.HasFundingTx() {
  2651. shortChanID := c.ShortChanID()
  2652. // For zero-conf channels, we'll use the actually-confirmed
  2653. // short channel id.
  2654. if c.IsZeroConf() {
  2655. shortChanID = c.ZeroConfRealScid()
  2656. }
  2657. label := labels.MakeLabel(
  2658. labels.LabelTypeChannelOpen, &shortChanID,
  2659. )
  2660. err := f.cfg.UpdateLabel(c.FundingOutpoint.Hash, label)
  2661. if err != nil {
  2662. log.Errorf("unable to update label: %v", err)
  2663. }
  2664. }
  2665. }
  2666. // handleFundingConfirmation marks a channel as open in the database, and set
  2667. // the channelOpeningState markedOpen. In addition it will report the now
  2668. // decided short channel ID to the switch, and close the local discovery signal
  2669. // for this channel.
  2670. func (f *Manager) handleFundingConfirmation(
  2671. completeChan *channeldb.OpenChannel,
  2672. confChannel *confirmedChannel) error {
  2673. fundingPoint := completeChan.FundingOutpoint
  2674. chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
  2675. // TODO(roasbeef): ideally persistent state update for chan above
  2676. // should be abstracted
  2677. // Now that that the channel has been fully confirmed, we'll request
  2678. // that the wallet fully verify this channel to ensure that it can be
  2679. // used.
  2680. err := f.cfg.Wallet.ValidateChannel(completeChan, confChannel.fundingTx)
  2681. if err != nil {
  2682. // TODO(roasbeef): delete chan state?
  2683. return fmt.Errorf("unable to validate channel: %w", err)
  2684. }
  2685. // Now that the channel has been validated, we'll persist an alias for
  2686. // this channel if the option-scid-alias feature-bit was negotiated.
  2687. if completeChan.NegotiatedAliasFeature() {
  2688. aliasScid, err := f.cfg.AliasManager.RequestAlias()
  2689. if err != nil {
  2690. return fmt.Errorf("unable to request alias: %w", err)
  2691. }
  2692. err = f.cfg.AliasManager.AddLocalAlias(
  2693. aliasScid, confChannel.shortChanID, true, false,
  2694. )
  2695. if err != nil {
  2696. return fmt.Errorf("unable to request alias: %w", err)
  2697. }
  2698. }
  2699. // The funding transaction now being confirmed, we add this channel to
  2700. // the fundingManager's internal persistent state machine that we use
  2701. // to track the remaining process of the channel opening. This is
  2702. // useful to resume the opening process in case of restarts. We set the
  2703. // opening state before we mark the channel opened in the database,
  2704. // such that we can receover from one of the db writes failing.
  2705. err = f.saveChannelOpeningState(
  2706. &fundingPoint, markedOpen, &confChannel.shortChanID,
  2707. )
  2708. if err != nil {
  2709. return fmt.Errorf("error setting channel state to "+
  2710. "markedOpen: %v", err)
  2711. }
  2712. // Now that the channel has been fully confirmed and we successfully
  2713. // saved the opening state, we'll mark it as open within the database.
  2714. err = completeChan.MarkAsOpen(confChannel.shortChanID)
  2715. if err != nil {
  2716. return fmt.Errorf("error setting channel pending flag to "+
  2717. "false: %v", err)
  2718. }
  2719. // Update the confirmed funding transaction label.
  2720. f.makeLabelForTx(completeChan)
  2721. // Inform the ChannelNotifier that the channel has transitioned from
  2722. // pending open to open.
  2723. f.cfg.NotifyOpenChannelEvent(completeChan.FundingOutpoint)
  2724. // Close the discoverySignal channel, indicating to a separate
  2725. // goroutine that the channel now is marked as open in the database
  2726. // and that it is acceptable to process channel_ready messages
  2727. // from the peer.
  2728. if discoverySignal, ok := f.localDiscoverySignals.Load(chanID); ok {
  2729. close(discoverySignal)
  2730. }
  2731. return nil
  2732. }
  2733. // sendChannelReady creates and sends the channelReady message.
  2734. // This should be called after the funding transaction has been confirmed,
  2735. // and the channelState is 'markedOpen'.
  2736. func (f *Manager) sendChannelReady(completeChan *channeldb.OpenChannel,
  2737. channel *lnwallet.LightningChannel) error {
  2738. chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
  2739. var peerKey [33]byte
  2740. copy(peerKey[:], completeChan.IdentityPub.SerializeCompressed())
  2741. // Next, we'll send over the channel_ready message which marks that we
  2742. // consider the channel open by presenting the remote party with our
  2743. // next revocation key. Without the revocation key, the remote party
  2744. // will be unable to propose state transitions.
  2745. nextRevocation, err := channel.NextRevocationKey()
  2746. if err != nil {
  2747. return fmt.Errorf("unable to create next revocation: %w", err)
  2748. }
  2749. channelReadyMsg := lnwire.NewChannelReady(chanID, nextRevocation)
  2750. // If this is a taproot channel, then we also need to send along our
  2751. // set of musig2 nonces as well.
  2752. if completeChan.ChanType.IsTaproot() {
  2753. log.Infof("ChanID(%v): generating musig2 nonces...",
  2754. chanID)
  2755. f.nonceMtx.Lock()
  2756. localNonce, ok := f.pendingMusigNonces[chanID]
  2757. if !ok {
  2758. // If we don't have any nonces generated yet for this
  2759. // first state, then we'll generate them now and stow
  2760. // them away. When we receive the funding locked
  2761. // message, we'll then pass along this same set of
  2762. // nonces.
  2763. newNonce, err := channel.GenMusigNonces()
  2764. if err != nil {
  2765. f.nonceMtx.Unlock()
  2766. return err
  2767. }
  2768. // Now that we've generated the nonce for this channel,
  2769. // we'll store it in the set of pending nonces.
  2770. localNonce = newNonce
  2771. f.pendingMusigNonces[chanID] = localNonce
  2772. }
  2773. f.nonceMtx.Unlock()
  2774. channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce(
  2775. localNonce.PubNonce,
  2776. )
  2777. }
  2778. // If the channel negotiated the option-scid-alias feature bit, we'll
  2779. // send a TLV segment that includes an alias the peer can use in their
  2780. // invoice hop hints. We'll send the first alias we find for the
  2781. // channel since it does not matter which alias we send. We'll error
  2782. // out in the odd case that no aliases are found.
  2783. if completeChan.NegotiatedAliasFeature() {
  2784. aliases := f.cfg.AliasManager.GetAliases(
  2785. completeChan.ShortChanID(),
  2786. )
  2787. if len(aliases) == 0 {
  2788. return fmt.Errorf("no aliases found")
  2789. }
  2790. // We can use a pointer to aliases since GetAliases returns a
  2791. // copy of the alias slice.
  2792. channelReadyMsg.AliasScid = &aliases[0]
  2793. }
  2794. // If the peer has disconnected before we reach this point, we will need
  2795. // to wait for him to come back online before sending the channelReady
  2796. // message. This is special for channelReady, since failing to send any
  2797. // of the previous messages in the funding flow just cancels the flow.
  2798. // But now the funding transaction is confirmed, the channel is open
  2799. // and we have to make sure the peer gets the channelReady message when
  2800. // it comes back online. This is also crucial during restart of lnd,
  2801. // where we might try to resend the channelReady message before the
  2802. // server has had the time to connect to the peer. We keep trying to
  2803. // send channelReady until we succeed, or the fundingManager is shut
  2804. // down.
  2805. for {
  2806. peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
  2807. if err != nil {
  2808. return err
  2809. }
  2810. localAlias := peer.LocalFeatures().HasFeature(
  2811. lnwire.ScidAliasOptional,
  2812. )
  2813. remoteAlias := peer.RemoteFeatures().HasFeature(
  2814. lnwire.ScidAliasOptional,
  2815. )
  2816. // We could also refresh the channel state instead of checking
  2817. // whether the feature was negotiated, but this saves us a
  2818. // database read.
  2819. if channelReadyMsg.AliasScid == nil && localAlias &&
  2820. remoteAlias {
  2821. // If an alias was not assigned above and the scid
  2822. // alias feature was negotiated, check if we already
  2823. // have an alias stored in case handleChannelReady was
  2824. // called before this. If an alias exists, use that in
  2825. // channel_ready. Otherwise, request and store an
  2826. // alias and use that.
  2827. aliases := f.cfg.AliasManager.GetAliases(
  2828. completeChan.ShortChannelID,
  2829. )
  2830. if len(aliases) == 0 {
  2831. // No aliases were found.
  2832. alias, err := f.cfg.AliasManager.RequestAlias()
  2833. if err != nil {
  2834. return err
  2835. }
  2836. err = f.cfg.AliasManager.AddLocalAlias(
  2837. alias, completeChan.ShortChannelID,
  2838. false, false,
  2839. )
  2840. if err != nil {
  2841. return err
  2842. }
  2843. channelReadyMsg.AliasScid = &alias
  2844. } else {
  2845. channelReadyMsg.AliasScid = &aliases[0]
  2846. }
  2847. }
  2848. log.Infof("Peer(%x) is online, sending ChannelReady "+
  2849. "for ChannelID(%v)", peerKey, chanID)
  2850. if err := peer.SendMessage(true, channelReadyMsg); err == nil {
  2851. // Sending succeeded, we can break out and continue the
  2852. // funding flow.
  2853. break
  2854. }
  2855. log.Warnf("Unable to send channelReady to peer %x: %v. "+
  2856. "Will retry when online", peerKey, err)
  2857. }
  2858. return nil
  2859. }
  2860. // receivedChannelReady checks whether or not we've received a ChannelReady
  2861. // from the remote peer. If we have, RemoteNextRevocation will be set.
  2862. func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
  2863. chanID lnwire.ChannelID) (bool, error) {
  2864. // If the funding manager has exited, return an error to stop looping.
  2865. // Note that the peer may appear as online while the funding manager
  2866. // has stopped due to the shutdown order in the server.
  2867. select {
  2868. case <-f.quit:
  2869. return false, ErrFundingManagerShuttingDown
  2870. default:
  2871. }
  2872. // Avoid a tight loop if peer is offline.
  2873. if _, err := f.waitForPeerOnline(node); err != nil {
  2874. log.Errorf("Wait for peer online failed: %v", err)
  2875. return false, err
  2876. }
  2877. // If we cannot find the channel, then we haven't processed the
  2878. // remote's channelReady message.
  2879. channel, err := f.cfg.FindChannel(node, chanID)
  2880. if err != nil {
  2881. log.Errorf("Unable to locate ChannelID(%v) to determine if "+
  2882. "ChannelReady was received", chanID)
  2883. return false, err
  2884. }
  2885. // If we haven't insert the next revocation point, we haven't finished
  2886. // processing the channel ready message.
  2887. if channel.RemoteNextRevocation == nil {
  2888. return false, nil
  2889. }
  2890. // Finally, the barrier signal is removed once we finish
  2891. // `handleChannelReady`. If we can still find the signal, we haven't
  2892. // finished processing it yet.
  2893. _, loaded := f.handleChannelReadyBarriers.Load(chanID)
  2894. return !loaded, nil
  2895. }
  2896. // extractAnnounceParams extracts the various channel announcement and update
  2897. // parameters that will be needed to construct a ChannelAnnouncement and a
  2898. // ChannelUpdate.
  2899. func (f *Manager) extractAnnounceParams(c *channeldb.OpenChannel) (
  2900. lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
  2901. // We'll obtain the min HTLC value we can forward in our direction, as
  2902. // we'll use this value within our ChannelUpdate. This constraint is
  2903. // originally set by the remote node, as it will be the one that will
  2904. // need to determine the smallest HTLC it deems economically relevant.
  2905. fwdMinHTLC := c.LocalChanCfg.MinHTLC
  2906. // We don't necessarily want to go as low as the remote party allows.
  2907. // Check it against our default forwarding policy.
  2908. if fwdMinHTLC < f.cfg.DefaultRoutingPolicy.MinHTLCOut {
  2909. fwdMinHTLC = f.cfg.DefaultRoutingPolicy.MinHTLCOut
  2910. }
  2911. // We'll obtain the max HTLC value we can forward in our direction, as
  2912. // we'll use this value within our ChannelUpdate. This value must be <=
  2913. // channel capacity and <= the maximum in-flight msats set by the peer.
  2914. fwdMaxHTLC := c.LocalChanCfg.MaxPendingAmount
  2915. capacityMSat := lnwire.NewMSatFromSatoshis(c.Capacity)
  2916. if fwdMaxHTLC > capacityMSat {
  2917. fwdMaxHTLC = capacityMSat
  2918. }
  2919. return fwdMinHTLC, fwdMaxHTLC
  2920. }
  2921. // addToGraph sends a ChannelAnnouncement and a ChannelUpdate to the
  2922. // gossiper so that the channel is added to the graph builder's internal graph.
  2923. // These announcement messages are NOT broadcasted to the greater network,
  2924. // only to the channel counter party. The proofs required to announce the
  2925. // channel to the greater network will be created and sent in annAfterSixConfs.
  2926. // The peerAlias is used for zero-conf channels to give the counter-party a
  2927. // ChannelUpdate they understand. ourPolicy may be set for various
  2928. // option-scid-alias channels to re-use the same policy.
  2929. func (f *Manager) addToGraph(completeChan *channeldb.OpenChannel,
  2930. shortChanID *lnwire.ShortChannelID,
  2931. peerAlias *lnwire.ShortChannelID,
  2932. ourPolicy *models.ChannelEdgePolicy) error {
  2933. chanID := lnwire.NewChanIDFromOutPoint(completeChan.FundingOutpoint)
  2934. fwdMinHTLC, fwdMaxHTLC := f.extractAnnounceParams(completeChan)
  2935. ann, err := f.newChanAnnouncement(
  2936. f.cfg.IDKey, completeChan.IdentityPub,
  2937. &completeChan.LocalChanCfg.MultiSigKey,
  2938. completeChan.RemoteChanCfg.MultiSigKey.PubKey, *shortChanID,
  2939. chanID, fwdMinHTLC, fwdMaxHTLC, ourPolicy,
  2940. completeChan.ChanType,
  2941. )
  2942. if err != nil {
  2943. return fmt.Errorf("error generating channel "+
  2944. "announcement: %v", err)
  2945. }
  2946. // Send ChannelAnnouncement and ChannelUpdate to the gossiper to add
  2947. // to the Router's topology.
  2948. errChan := f.cfg.SendAnnouncement(
  2949. ann.chanAnn, discovery.ChannelCapacity(completeChan.Capacity),
  2950. discovery.ChannelPoint(completeChan.FundingOutpoint),
  2951. )
  2952. select {
  2953. case err := <-errChan:
  2954. if err != nil {
  2955. if graph.IsError(err, graph.ErrOutdated,
  2956. graph.ErrIgnored) {
  2957. log.Debugf("Graph rejected "+
  2958. "ChannelAnnouncement: %v", err)
  2959. } else {
  2960. return fmt.Errorf("error sending channel "+
  2961. "announcement: %v", err)
  2962. }
  2963. }
  2964. case <-f.quit:
  2965. return ErrFundingManagerShuttingDown
  2966. }
  2967. errChan = f.cfg.SendAnnouncement(
  2968. ann.chanUpdateAnn, discovery.RemoteAlias(peerAlias),
  2969. )
  2970. select {
  2971. case err := <-errChan:
  2972. if err != nil {
  2973. if graph.IsError(err, graph.ErrOutdated,
  2974. graph.ErrIgnored) {
  2975. log.Debugf("Graph rejected "+
  2976. "ChannelUpdate: %v", err)
  2977. } else {
  2978. return fmt.Errorf("error sending channel "+
  2979. "update: %v", err)
  2980. }
  2981. }
  2982. case <-f.quit:
  2983. return ErrFundingManagerShuttingDown
  2984. }
  2985. return nil
  2986. }
  2987. // annAfterSixConfs broadcasts the necessary channel announcement messages to
  2988. // the network after 6 confs. Should be called after the channelReady message
  2989. // is sent and the channel is added to the graph (channelState is
  2990. // 'addedToGraph') and the channel is ready to be used. This is the last
  2991. // step in the channel opening process, and the opening state will be deleted
  2992. // from the database if successful.
  2993. func (f *Manager) annAfterSixConfs(completeChan *channeldb.OpenChannel,
  2994. shortChanID *lnwire.ShortChannelID) error {
  2995. // If this channel is not meant to be announced to the greater network,
  2996. // we'll only send our NodeAnnouncement to our counterparty to ensure we
  2997. // don't leak any of our information.
  2998. announceChan := completeChan.ChannelFlags&lnwire.FFAnnounceChannel != 0
  2999. if !announceChan {
  3000. log.Debugf("Will not announce private channel %v.",
  3001. shortChanID.ToUint64())
  3002. peer, err := f.waitForPeerOnline(completeChan.IdentityPub)
  3003. if err != nil {
  3004. return err
  3005. }
  3006. nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
  3007. if err != nil {
  3008. return fmt.Errorf("unable to retrieve current node "+
  3009. "announcement: %v", err)
  3010. }
  3011. chanID := lnwire.NewChanIDFromOutPoint(
  3012. completeChan.FundingOutpoint,
  3013. )
  3014. pubKey := peer.PubKey()
  3015. log.Debugf("Sending our NodeAnnouncement for "+
  3016. "ChannelID(%v) to %x", chanID, pubKey)
  3017. // TODO(halseth): make reliable. If the peer is not online this
  3018. // will fail, and the opening process will stop. Should instead
  3019. // block here, waiting for the peer to come online.
  3020. if err := peer.SendMessage(true, &nodeAnn); err != nil {
  3021. return fmt.Errorf("unable to send node announcement "+
  3022. "to peer %x: %v", pubKey, err)
  3023. }
  3024. } else {
  3025. // Otherwise, we'll wait until the funding transaction has
  3026. // reached 6 confirmations before announcing it.
  3027. numConfs := uint32(completeChan.NumConfsRequired)
  3028. if numConfs < 6 {
  3029. numConfs = 6
  3030. }
  3031. txid := completeChan.FundingOutpoint.Hash
  3032. log.Debugf("Will announce channel %v after ChannelPoint"+
  3033. "(%v) has gotten %d confirmations",
  3034. shortChanID.ToUint64(), completeChan.FundingOutpoint,
  3035. numConfs)
  3036. fundingScript, err := makeFundingScript(completeChan)
  3037. if err != nil {
  3038. return fmt.Errorf("unable to create funding script "+
  3039. "for ChannelPoint(%v): %v",
  3040. completeChan.FundingOutpoint, err)
  3041. }
  3042. // Register with the ChainNotifier for a notification once the
  3043. // funding transaction reaches at least 6 confirmations.
  3044. confNtfn, err := f.cfg.Notifier.RegisterConfirmationsNtfn(
  3045. &txid, fundingScript, numConfs,
  3046. completeChan.BroadcastHeight(),
  3047. )
  3048. if err != nil {
  3049. return fmt.Errorf("unable to register for "+
  3050. "confirmation of ChannelPoint(%v): %v",
  3051. completeChan.FundingOutpoint, err)
  3052. }
  3053. // Wait until 6 confirmations has been reached or the wallet
  3054. // signals a shutdown.
  3055. select {
  3056. case _, ok := <-confNtfn.Confirmed:
  3057. if !ok {
  3058. return fmt.Errorf("ChainNotifier shutting "+
  3059. "down, cannot complete funding flow "+
  3060. "for ChannelPoint(%v)",
  3061. completeChan.FundingOutpoint)
  3062. }
  3063. // Fallthrough.
  3064. case <-f.quit:
  3065. return fmt.Errorf("%v, stopping funding flow for "+
  3066. "ChannelPoint(%v)",
  3067. ErrFundingManagerShuttingDown,
  3068. completeChan.FundingOutpoint)
  3069. }
  3070. fundingPoint := completeChan.FundingOutpoint
  3071. chanID := lnwire.NewChanIDFromOutPoint(fundingPoint)
  3072. log.Infof("Announcing ChannelPoint(%v), short_chan_id=%v",
  3073. &fundingPoint, shortChanID)
  3074. // If this is a non-zero-conf option-scid-alias channel, we'll
  3075. // delete the mappings the gossiper uses so that ChannelUpdates
  3076. // with aliases won't be accepted. This is done elsewhere for
  3077. // zero-conf channels.
  3078. isScidFeature := completeChan.NegotiatedAliasFeature()
  3079. isZeroConf := completeChan.IsZeroConf()
  3080. if isScidFeature && !isZeroConf {
  3081. baseScid := completeChan.ShortChanID()
  3082. err := f.cfg.AliasManager.DeleteSixConfs(baseScid)
  3083. if err != nil {
  3084. return fmt.Errorf("failed deleting six confs "+
  3085. "maps: %v", err)
  3086. }
  3087. // We'll delete the edge and add it again via
  3088. // addToGraph. This is because the peer may have
  3089. // sent us a ChannelUpdate with an alias and we don't
  3090. // want to relay this.
  3091. ourPolicy, err := f.cfg.DeleteAliasEdge(baseScid)
  3092. if err != nil {
  3093. return fmt.Errorf("failed deleting real edge "+
  3094. "for alias channel from graph: %v",
  3095. err)
  3096. }
  3097. err = f.addToGraph(
  3098. completeChan, &baseScid, nil, ourPolicy,
  3099. )
  3100. if err != nil {
  3101. return fmt.Errorf("failed to re-add to "+
  3102. "graph: %v", err)
  3103. }
  3104. }
  3105. // Create and broadcast the proofs required to make this channel
  3106. // public and usable for other nodes for routing.
  3107. err = f.announceChannel(
  3108. f.cfg.IDKey, completeChan.IdentityPub,
  3109. &completeChan.LocalChanCfg.MultiSigKey,
  3110. completeChan.RemoteChanCfg.MultiSigKey.PubKey,
  3111. *shortChanID, chanID, completeChan.ChanType,
  3112. )
  3113. if err != nil {
  3114. return fmt.Errorf("channel announcement failed: %w",
  3115. err)
  3116. }
  3117. log.Debugf("Channel with ChannelPoint(%v), short_chan_id=%v "+
  3118. "sent to gossiper", &fundingPoint, shortChanID)
  3119. }
  3120. return nil
  3121. }
  3122. // waitForZeroConfChannel is called when the state is addedToGraph with
  3123. // a zero-conf channel. This will wait for the real confirmation, add the
  3124. // confirmed SCID to the graph, and then announce after six confs.
  3125. func (f *Manager) waitForZeroConfChannel(c *channeldb.OpenChannel) error {
  3126. // First we'll check whether the channel is confirmed on-chain. If it
  3127. // is already confirmed, the chainntnfs subsystem will return with the
  3128. // confirmed tx. Otherwise, we'll wait here until confirmation occurs.
  3129. confChan, err := f.waitForFundingWithTimeout(c)
  3130. if err != nil {
  3131. return fmt.Errorf("error waiting for zero-conf funding "+
  3132. "confirmation for ChannelPoint(%v): %v",
  3133. c.FundingOutpoint, err)
  3134. }
  3135. // We'll need to refresh the channel state so that things are properly
  3136. // populated when validating the channel state. Otherwise, a panic may
  3137. // occur due to inconsistency in the OpenChannel struct.
  3138. err = c.Refresh()
  3139. if err != nil {
  3140. return fmt.Errorf("unable to refresh channel state: %w", err)
  3141. }
  3142. // Now that we have the confirmed transaction and the proper SCID,
  3143. // we'll call ValidateChannel to ensure the confirmed tx is properly
  3144. // formatted.
  3145. err = f.cfg.Wallet.ValidateChannel(c, confChan.fundingTx)
  3146. if err != nil {
  3147. return fmt.Errorf("unable to validate zero-conf channel: "+
  3148. "%v", err)
  3149. }
  3150. // Once we know the confirmed ShortChannelID, we'll need to save it to
  3151. // the database and refresh the OpenChannel struct with it.
  3152. err = c.MarkRealScid(confChan.shortChanID)
  3153. if err != nil {
  3154. return fmt.Errorf("unable to set confirmed SCID for zero "+
  3155. "channel: %v", err)
  3156. }
  3157. // Six confirmations have been reached. If this channel is public,
  3158. // we'll delete some of the alias mappings the gossiper uses.
  3159. isPublic := c.ChannelFlags&lnwire.FFAnnounceChannel != 0
  3160. if isPublic {
  3161. err = f.cfg.AliasManager.DeleteSixConfs(c.ShortChannelID)
  3162. if err != nil {
  3163. return fmt.Errorf("unable to delete base alias after "+
  3164. "six confirmations: %v", err)
  3165. }
  3166. // TODO: Make this atomic!
  3167. ourPolicy, err := f.cfg.DeleteAliasEdge(c.ShortChanID())
  3168. if err != nil {
  3169. return fmt.Errorf("unable to delete alias edge from "+
  3170. "graph: %v", err)
  3171. }
  3172. // We'll need to update the graph with the new ShortChannelID
  3173. // via an addToGraph call. We don't pass in the peer's
  3174. // alias since we'll be using the confirmed SCID from now on
  3175. // regardless if it's public or not.
  3176. err = f.addToGraph(
  3177. c, &confChan.shortChanID, nil, ourPolicy,
  3178. )
  3179. if err != nil {
  3180. return fmt.Errorf("failed adding confirmed zero-conf "+
  3181. "SCID to graph: %v", err)
  3182. }
  3183. }
  3184. // Since we have now marked down the confirmed SCID, we'll also need to
  3185. // tell the Switch to refresh the relevant ChannelLink so that forwards
  3186. // under the confirmed SCID are possible if this is a public channel.
  3187. err = f.cfg.ReportShortChanID(c.FundingOutpoint)
  3188. if err != nil {
  3189. // This should only fail if the link is not found in the
  3190. // Switch's linkIndex map. If this is the case, then the peer
  3191. // has gone offline and the next time the link is loaded, it
  3192. // will have a refreshed state. Just log an error here.
  3193. log.Errorf("unable to report scid for zero-conf channel "+
  3194. "channel: %v", err)
  3195. }
  3196. // Update the confirmed transaction's label.
  3197. f.makeLabelForTx(c)
  3198. return nil
  3199. }
  3200. // genFirstStateMusigNonce generates a nonces for the "first" local state. This
  3201. // is the verification nonce for the state created for us after the initial
  3202. // commitment transaction signed as part of the funding flow.
  3203. func genFirstStateMusigNonce(channel *channeldb.OpenChannel,
  3204. ) (*musig2.Nonces, error) {
  3205. musig2ShaChain, err := channeldb.DeriveMusig2Shachain(
  3206. channel.RevocationProducer,
  3207. )
  3208. if err != nil {
  3209. return nil, fmt.Errorf("unable to generate musig channel "+
  3210. "nonces: %v", err)
  3211. }
  3212. // We use the _next_ commitment height here as we need to generate the
  3213. // nonce for the next state the remote party will sign for us.
  3214. verNonce, err := channeldb.NewMusigVerificationNonce(
  3215. channel.LocalChanCfg.MultiSigKey.PubKey,
  3216. channel.LocalCommitment.CommitHeight+1,
  3217. musig2ShaChain,
  3218. )
  3219. if err != nil {
  3220. return nil, fmt.Errorf("unable to generate musig channel "+
  3221. "nonces: %v", err)
  3222. }
  3223. return verNonce, nil
  3224. }
  3225. // handleChannelReady finalizes the channel funding process and enables the
  3226. // channel to enter normal operating mode.
  3227. func (f *Manager) handleChannelReady(peer lnpeer.Peer, //nolint:funlen
  3228. msg *lnwire.ChannelReady) {
  3229. defer f.wg.Done()
  3230. // If we are in development mode, we'll wait for specified duration
  3231. // before processing the channel ready message.
  3232. if f.cfg.Dev != nil {
  3233. duration := f.cfg.Dev.ProcessChannelReadyWait
  3234. log.Warnf("Channel(%v): sleeping %v before processing "+
  3235. "channel_ready", msg.ChanID, duration)
  3236. select {
  3237. case <-time.After(duration):
  3238. log.Warnf("Channel(%v): slept %v before processing "+
  3239. "channel_ready", msg.ChanID, duration)
  3240. case <-f.quit:
  3241. log.Warnf("Channel(%v): quit sleeping", msg.ChanID)
  3242. return
  3243. }
  3244. }
  3245. log.Debugf("Received ChannelReady for ChannelID(%v) from "+
  3246. "peer %x", msg.ChanID,
  3247. peer.IdentityKey().SerializeCompressed())
  3248. // We now load or create a new channel barrier for this channel.
  3249. _, loaded := f.handleChannelReadyBarriers.LoadOrStore(
  3250. msg.ChanID, struct{}{},
  3251. )
  3252. // If we are currently in the process of handling a channel_ready
  3253. // message for this channel, ignore.
  3254. if loaded {
  3255. log.Infof("Already handling channelReady for "+
  3256. "ChannelID(%v), ignoring.", msg.ChanID)
  3257. return
  3258. }
  3259. // If not already handling channelReady for this channel, then the
  3260. // `LoadOrStore` has set up a barrier, and it will be removed once this
  3261. // function exits.
  3262. defer f.handleChannelReadyBarriers.Delete(msg.ChanID)
  3263. localDiscoverySignal, ok := f.localDiscoverySignals.Load(msg.ChanID)
  3264. if ok {
  3265. // Before we proceed with processing the channel_ready
  3266. // message, we'll wait for the local waitForFundingConfirmation
  3267. // goroutine to signal that it has the necessary state in
  3268. // place. Otherwise, we may be missing critical information
  3269. // required to handle forwarded HTLC's.
  3270. select {
  3271. case <-localDiscoverySignal:
  3272. // Fallthrough
  3273. case <-f.quit:
  3274. return
  3275. }
  3276. // With the signal received, we can now safely delete the entry
  3277. // from the map.
  3278. f.localDiscoverySignals.Delete(msg.ChanID)
  3279. }
  3280. // First, we'll attempt to locate the channel whose funding workflow is
  3281. // being finalized by this message. We go to the database rather than
  3282. // our reservation map as we may have restarted, mid funding flow. Also
  3283. // provide the node's public key to make the search faster.
  3284. chanID := msg.ChanID
  3285. channel, err := f.cfg.FindChannel(peer.IdentityKey(), chanID)
  3286. if err != nil {
  3287. log.Errorf("Unable to locate ChannelID(%v), cannot complete "+
  3288. "funding", chanID)
  3289. return
  3290. }
  3291. // If this is a taproot channel, then we can generate the set of nonces
  3292. // the remote party needs to send the next remote commitment here.
  3293. var firstVerNonce *musig2.Nonces
  3294. if channel.ChanType.IsTaproot() {
  3295. firstVerNonce, err = genFirstStateMusigNonce(channel)
  3296. if err != nil {
  3297. log.Error(err)
  3298. return
  3299. }
  3300. }
  3301. // We'll need to store the received TLV alias if the option_scid_alias
  3302. // feature was negotiated. This will be used to provide route hints
  3303. // during invoice creation. In the zero-conf case, it is also used to
  3304. // provide a ChannelUpdate to the remote peer. This is done before the
  3305. // call to InsertNextRevocation in case the call to PutPeerAlias fails.
  3306. // If it were to fail on the first call to handleChannelReady, we
  3307. // wouldn't want the channel to be usable yet.
  3308. if channel.NegotiatedAliasFeature() {
  3309. // If the AliasScid field is nil, we must fail out. We will
  3310. // most likely not be able to route through the peer.
  3311. if msg.AliasScid == nil {
  3312. log.Debugf("Consider closing ChannelID(%v), peer "+
  3313. "does not implement the option-scid-alias "+
  3314. "feature properly", chanID)
  3315. return
  3316. }
  3317. // We'll store the AliasScid so that invoice creation can use
  3318. // it.
  3319. err = f.cfg.AliasManager.PutPeerAlias(chanID, *msg.AliasScid)
  3320. if err != nil {
  3321. log.Errorf("unable to store peer's alias: %v", err)
  3322. return
  3323. }
  3324. // If we do not have an alias stored, we'll create one now.
  3325. // This is only used in the upgrade case where a user toggles
  3326. // the option-scid-alias feature-bit to on. We'll also send the
  3327. // channel_ready message here in case the link is created
  3328. // before sendChannelReady is called.
  3329. aliases := f.cfg.AliasManager.GetAliases(
  3330. channel.ShortChannelID,
  3331. )
  3332. if len(aliases) == 0 {
  3333. // No aliases were found so we'll request and store an
  3334. // alias and use it in the channel_ready message.
  3335. alias, err := f.cfg.AliasManager.RequestAlias()
  3336. if err != nil {
  3337. log.Errorf("unable to request alias: %v", err)
  3338. return
  3339. }
  3340. err = f.cfg.AliasManager.AddLocalAlias(
  3341. alias, channel.ShortChannelID, false, false,
  3342. )
  3343. if err != nil {
  3344. log.Errorf("unable to add local alias: %v",
  3345. err)
  3346. return
  3347. }
  3348. secondPoint, err := channel.SecondCommitmentPoint()
  3349. if err != nil {
  3350. log.Errorf("unable to fetch second "+
  3351. "commitment point: %v", err)
  3352. return
  3353. }
  3354. channelReadyMsg := lnwire.NewChannelReady(
  3355. chanID, secondPoint,
  3356. )
  3357. channelReadyMsg.AliasScid = &alias
  3358. if firstVerNonce != nil {
  3359. channelReadyMsg.NextLocalNonce = lnwire.SomeMusig2Nonce( //nolint:lll
  3360. firstVerNonce.PubNonce,
  3361. )
  3362. }
  3363. err = peer.SendMessage(true, channelReadyMsg)
  3364. if err != nil {
  3365. log.Errorf("unable to send channel_ready: %v",
  3366. err)
  3367. return
  3368. }
  3369. }
  3370. }
  3371. // If the RemoteNextRevocation is non-nil, it means that we have
  3372. // already processed channelReady for this channel, so ignore. This
  3373. // check is after the alias logic so we store the peer's most recent
  3374. // alias. The spec requires us to validate that subsequent
  3375. // channel_ready messages use the same per commitment point (the
  3376. // second), but it is not actually necessary since we'll just end up
  3377. // ignoring it. We are, however, required to *send* the same per
  3378. // commitment point, since another pedantic implementation might
  3379. // verify it.
  3380. if channel.RemoteNextRevocation != nil {
  3381. log.Infof("Received duplicate channelReady for "+
  3382. "ChannelID(%v), ignoring.", chanID)
  3383. return
  3384. }
  3385. // If this is a taproot channel, then we'll need to map the received
  3386. // nonces to a nonce pair, and also fetch our pending nonces, which are
  3387. // required in order to make the channel whole.
  3388. var chanOpts []lnwallet.ChannelOpt
  3389. if channel.ChanType.IsTaproot() {
  3390. f.nonceMtx.Lock()
  3391. localNonce, ok := f.pendingMusigNonces[chanID]
  3392. if !ok {
  3393. // If there's no pending nonce for this channel ID,
  3394. // we'll use the one generated above.
  3395. localNonce = firstVerNonce
  3396. f.pendingMusigNonces[chanID] = firstVerNonce
  3397. }
  3398. f.nonceMtx.Unlock()
  3399. log.Infof("ChanID(%v): applying local+remote musig2 nonces",
  3400. chanID)
  3401. remoteNonce, err := msg.NextLocalNonce.UnwrapOrErrV(
  3402. errNoLocalNonce,
  3403. )
  3404. if err != nil {
  3405. cid := newChanIdentifier(msg.ChanID)
  3406. f.sendWarning(peer, cid, err)
  3407. return
  3408. }
  3409. chanOpts = append(
  3410. chanOpts,
  3411. lnwallet.WithLocalMusigNonces(localNonce),
  3412. lnwallet.WithRemoteMusigNonces(&musig2.Nonces{
  3413. PubNonce: remoteNonce,
  3414. }),
  3415. )
  3416. }
  3417. // The channel_ready message contains the next commitment point we'll
  3418. // need to create the next commitment state for the remote party. So
  3419. // we'll insert that into the channel now before passing it along to
  3420. // other sub-systems.
  3421. err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
  3422. if err != nil {
  3423. log.Errorf("unable to insert next commitment point: %v", err)
  3424. return
  3425. }
  3426. // Before we can add the channel to the peer, we'll need to ensure that
  3427. // we have an initial forwarding policy set.
  3428. if err := f.ensureInitialForwardingPolicy(chanID, channel); err != nil {
  3429. log.Errorf("Unable to ensure initial forwarding policy: %v",
  3430. err)
  3431. }
  3432. err = peer.AddNewChannel(&lnpeer.NewChannel{
  3433. OpenChannel: channel,
  3434. ChanOpts: chanOpts,
  3435. }, f.quit)
  3436. if err != nil {
  3437. log.Errorf("Unable to add new channel %v with peer %x: %v",
  3438. channel.FundingOutpoint,
  3439. peer.IdentityKey().SerializeCompressed(), err,
  3440. )
  3441. }
  3442. }
  3443. // handleChannelReadyReceived is called once the remote's channelReady message
  3444. // is received and processed. At this stage, we must have sent out our
  3445. // channelReady message, once the remote's channelReady is processed, the
  3446. // channel is now active, thus we change its state to `addedToGraph` to
  3447. // let the channel start handling routing.
  3448. func (f *Manager) handleChannelReadyReceived(channel *channeldb.OpenChannel,
  3449. scid *lnwire.ShortChannelID, pendingChanID PendingChanID,
  3450. updateChan chan<- *lnrpc.OpenStatusUpdate) error {
  3451. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  3452. // Since we've sent+received funding locked at this point, we
  3453. // can clean up the pending musig2 nonce state.
  3454. f.nonceMtx.Lock()
  3455. delete(f.pendingMusigNonces, chanID)
  3456. f.nonceMtx.Unlock()
  3457. var peerAlias *lnwire.ShortChannelID
  3458. if channel.IsZeroConf() {
  3459. // We'll need to wait until channel_ready has been received and
  3460. // the peer lets us know the alias they want to use for the
  3461. // channel. With this information, we can then construct a
  3462. // ChannelUpdate for them. If an alias does not yet exist,
  3463. // we'll just return, letting the next iteration of the loop
  3464. // check again.
  3465. var defaultAlias lnwire.ShortChannelID
  3466. chanID := lnwire.NewChanIDFromOutPoint(channel.FundingOutpoint)
  3467. foundAlias, _ := f.cfg.AliasManager.GetPeerAlias(chanID)
  3468. if foundAlias == defaultAlias {
  3469. return nil
  3470. }
  3471. peerAlias = &foundAlias
  3472. }
  3473. err := f.addToGraph(channel, scid, peerAlias, nil)
  3474. if err != nil {
  3475. return fmt.Errorf("failed adding to graph: %w", err)
  3476. }
  3477. // As the channel is now added to the ChannelRouter's topology, the
  3478. // channel is moved to the next state of the state machine. It will be
  3479. // moved to the last state (actually deleted from the database) after
  3480. // the channel is finally announced.
  3481. err = f.saveChannelOpeningState(
  3482. &channel.FundingOutpoint, addedToGraph, scid,
  3483. )
  3484. if err != nil {
  3485. return fmt.Errorf("error setting channel state to"+
  3486. " addedToGraph: %w", err)
  3487. }
  3488. log.Debugf("Channel(%v) with ShortChanID %v: successfully "+
  3489. "added to graph", chanID, scid)
  3490. // Give the caller a final update notifying them that the channel is
  3491. fundingPoint := channel.FundingOutpoint
  3492. cp := &lnrpc.ChannelPoint{
  3493. FundingTxid: &lnrpc.ChannelPoint_FundingTxidBytes{
  3494. FundingTxidBytes: fundingPoint.Hash[:],
  3495. },
  3496. OutputIndex: fundingPoint.Index,
  3497. }
  3498. if updateChan != nil {
  3499. upd := &lnrpc.OpenStatusUpdate{
  3500. Update: &lnrpc.OpenStatusUpdate_ChanOpen{
  3501. ChanOpen: &lnrpc.ChannelOpenUpdate{
  3502. ChannelPoint: cp,
  3503. },
  3504. },
  3505. PendingChanId: pendingChanID[:],
  3506. }
  3507. select {
  3508. case updateChan <- upd:
  3509. case <-f.quit:
  3510. return ErrFundingManagerShuttingDown
  3511. }
  3512. }
  3513. return nil
  3514. }
  3515. // ensureInitialForwardingPolicy ensures that we have an initial forwarding
  3516. // policy set for the given channel. If we don't, we'll fall back to the default
  3517. // values.
  3518. func (f *Manager) ensureInitialForwardingPolicy(chanID lnwire.ChannelID,
  3519. channel *channeldb.OpenChannel) error {
  3520. // Before we can add the channel to the peer, we'll need to ensure that
  3521. // we have an initial forwarding policy set. This should always be the
  3522. // case except for a channel that was created with lnd <= 0.15.5 and
  3523. // is still pending while updating to this version.
  3524. var needDBUpdate bool
  3525. forwardingPolicy, err := f.getInitialForwardingPolicy(chanID)
  3526. if err != nil {
  3527. log.Errorf("Unable to fetch initial forwarding policy, "+
  3528. "falling back to default values: %v", err)
  3529. forwardingPolicy = f.defaultForwardingPolicy(
  3530. channel.LocalChanCfg.ChannelStateBounds,
  3531. )
  3532. needDBUpdate = true
  3533. }
  3534. // We only started storing the actual values for MinHTLCOut and MaxHTLC
  3535. // after 0.16.x, so if a channel was opened with such a version and is
  3536. // still pending while updating to this version, we'll need to set the
  3537. // values to the default values.
  3538. if forwardingPolicy.MinHTLCOut == 0 {
  3539. forwardingPolicy.MinHTLCOut = channel.LocalChanCfg.MinHTLC
  3540. needDBUpdate = true
  3541. }
  3542. if forwardingPolicy.MaxHTLC == 0 {
  3543. forwardingPolicy.MaxHTLC = channel.LocalChanCfg.MaxPendingAmount
  3544. needDBUpdate = true
  3545. }
  3546. // And finally, if we found that the values currently stored aren't
  3547. // sufficient for the link, we'll update the database.
  3548. if needDBUpdate {
  3549. err := f.saveInitialForwardingPolicy(chanID, forwardingPolicy)
  3550. if err != nil {
  3551. return fmt.Errorf("unable to update initial "+
  3552. "forwarding policy: %v", err)
  3553. }
  3554. }
  3555. return nil
  3556. }
  3557. // chanAnnouncement encapsulates the two authenticated announcements that we
  3558. // send out to the network after a new channel has been created locally.
  3559. type chanAnnouncement struct {
  3560. chanAnn *lnwire.ChannelAnnouncement
  3561. chanUpdateAnn *lnwire.ChannelUpdate
  3562. chanProof *lnwire.AnnounceSignatures
  3563. }
  3564. // newChanAnnouncement creates the authenticated channel announcement messages
  3565. // required to broadcast a newly created channel to the network. The
  3566. // announcement is two part: the first part authenticates the existence of the
  3567. // channel and contains four signatures binding the funding pub keys and
  3568. // identity pub keys of both parties to the channel, and the second segment is
  3569. // authenticated only by us and contains our directional routing policy for the
  3570. // channel. ourPolicy may be set in order to re-use an existing, non-default
  3571. // policy.
  3572. func (f *Manager) newChanAnnouncement(localPubKey,
  3573. remotePubKey *btcec.PublicKey, localFundingKey *keychain.KeyDescriptor,
  3574. remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
  3575. chanID lnwire.ChannelID, fwdMinHTLC, fwdMaxHTLC lnwire.MilliSatoshi,
  3576. ourPolicy *models.ChannelEdgePolicy,
  3577. chanType channeldb.ChannelType) (*chanAnnouncement, error) {
  3578. chainHash := *f.cfg.Wallet.Cfg.NetParams.GenesisHash
  3579. // The unconditional section of the announcement is the ShortChannelID
  3580. // itself which compactly encodes the location of the funding output
  3581. // within the blockchain.
  3582. chanAnn := &lnwire.ChannelAnnouncement{
  3583. ShortChannelID: shortChanID,
  3584. Features: lnwire.NewRawFeatureVector(),
  3585. ChainHash: chainHash,
  3586. }
  3587. // If this is a taproot channel, then we'll set a special bit in the
  3588. // feature vector to indicate to the routing layer that this needs a
  3589. // slightly different type of validation.
  3590. //
  3591. // TODO(roasbeef): temp, remove after gossip 1.5
  3592. if chanType.IsTaproot() {
  3593. log.Debugf("Applying taproot feature bit to "+
  3594. "ChannelAnnouncement for %v", chanID)
  3595. chanAnn.Features.Set(
  3596. lnwire.SimpleTaprootChannelsRequiredStaging,
  3597. )
  3598. }
  3599. // The chanFlags field indicates which directed edge of the channel is
  3600. // being updated within the ChannelUpdateAnnouncement announcement
  3601. // below. A value of zero means it's the edge of the "first" node and 1
  3602. // being the other node.
  3603. var chanFlags lnwire.ChanUpdateChanFlags
  3604. // The lexicographical ordering of the two identity public keys of the
  3605. // nodes indicates which of the nodes is "first". If our serialized
  3606. // identity key is lower than theirs then we're the "first" node and
  3607. // second otherwise.
  3608. selfBytes := localPubKey.SerializeCompressed()
  3609. remoteBytes := remotePubKey.SerializeCompressed()
  3610. if bytes.Compare(selfBytes, remoteBytes) == -1 {
  3611. copy(chanAnn.NodeID1[:], localPubKey.SerializeCompressed())
  3612. copy(chanAnn.NodeID2[:], remotePubKey.SerializeCompressed())
  3613. copy(
  3614. chanAnn.BitcoinKey1[:],
  3615. localFundingKey.PubKey.SerializeCompressed(),
  3616. )
  3617. copy(
  3618. chanAnn.BitcoinKey2[:],
  3619. remoteFundingKey.SerializeCompressed(),
  3620. )
  3621. // If we're the first node then update the chanFlags to
  3622. // indicate the "direction" of the update.
  3623. chanFlags = 0
  3624. } else {
  3625. copy(chanAnn.NodeID1[:], remotePubKey.SerializeCompressed())
  3626. copy(chanAnn.NodeID2[:], localPubKey.SerializeCompressed())
  3627. copy(
  3628. chanAnn.BitcoinKey1[:],
  3629. remoteFundingKey.SerializeCompressed(),
  3630. )
  3631. copy(
  3632. chanAnn.BitcoinKey2[:],
  3633. localFundingKey.PubKey.SerializeCompressed(),
  3634. )
  3635. // If we're the second node then update the chanFlags to
  3636. // indicate the "direction" of the update.
  3637. chanFlags = 1
  3638. }
  3639. // Our channel update message flags will signal that we support the
  3640. // max_htlc field.
  3641. msgFlags := lnwire.ChanUpdateRequiredMaxHtlc
  3642. // We announce the channel with the default values. Some of
  3643. // these values can later be changed by crafting a new ChannelUpdate.
  3644. chanUpdateAnn := &lnwire.ChannelUpdate{
  3645. ShortChannelID: shortChanID,
  3646. ChainHash: chainHash,
  3647. Timestamp: uint32(time.Now().Unix()),
  3648. MessageFlags: msgFlags,
  3649. ChannelFlags: chanFlags,
  3650. TimeLockDelta: uint16(
  3651. f.cfg.DefaultRoutingPolicy.TimeLockDelta,
  3652. ),
  3653. HtlcMinimumMsat: fwdMinHTLC,
  3654. HtlcMaximumMsat: fwdMaxHTLC,
  3655. }
  3656. // The caller of newChanAnnouncement is expected to provide the initial
  3657. // forwarding policy to be announced. If no persisted initial policy
  3658. // values are found, then we will use the default policy values in the
  3659. // channel announcement.
  3660. storedFwdingPolicy, err := f.getInitialForwardingPolicy(chanID)
  3661. if err != nil && !errors.Is(err, channeldb.ErrChannelNotFound) {
  3662. return nil, errors.Errorf("unable to generate channel "+
  3663. "update announcement: %v", err)
  3664. }
  3665. switch {
  3666. case ourPolicy != nil:
  3667. // If ourPolicy is non-nil, modify the default parameters of the
  3668. // ChannelUpdate.
  3669. chanUpdateAnn.MessageFlags = ourPolicy.MessageFlags
  3670. chanUpdateAnn.ChannelFlags = ourPolicy.ChannelFlags
  3671. chanUpdateAnn.TimeLockDelta = ourPolicy.TimeLockDelta
  3672. chanUpdateAnn.HtlcMinimumMsat = ourPolicy.MinHTLC
  3673. chanUpdateAnn.HtlcMaximumMsat = ourPolicy.MaxHTLC
  3674. chanUpdateAnn.BaseFee = uint32(ourPolicy.FeeBaseMSat)
  3675. chanUpdateAnn.FeeRate = uint32(
  3676. ourPolicy.FeeProportionalMillionths,
  3677. )
  3678. case storedFwdingPolicy != nil:
  3679. chanUpdateAnn.BaseFee = uint32(storedFwdingPolicy.BaseFee)
  3680. chanUpdateAnn.FeeRate = uint32(storedFwdingPolicy.FeeRate)
  3681. default:
  3682. log.Infof("No channel forwarding policy specified for channel "+
  3683. "announcement of ChannelID(%v). "+
  3684. "Assuming default fee parameters.", chanID)
  3685. chanUpdateAnn.BaseFee = uint32(
  3686. f.cfg.DefaultRoutingPolicy.BaseFee,
  3687. )
  3688. chanUpdateAnn.FeeRate = uint32(
  3689. f.cfg.DefaultRoutingPolicy.FeeRate,
  3690. )
  3691. }
  3692. // With the channel update announcement constructed, we'll generate a
  3693. // signature that signs a double-sha digest of the announcement.
  3694. // This'll serve to authenticate this announcement and any other future
  3695. // updates we may send.
  3696. chanUpdateMsg, err := chanUpdateAnn.DataToSign()
  3697. if err != nil {
  3698. return nil, err
  3699. }
  3700. sig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanUpdateMsg, true)
  3701. if err != nil {
  3702. return nil, errors.Errorf("unable to generate channel "+
  3703. "update announcement signature: %v", err)
  3704. }
  3705. chanUpdateAnn.Signature, err = lnwire.NewSigFromSignature(sig)
  3706. if err != nil {
  3707. return nil, errors.Errorf("unable to generate channel "+
  3708. "update announcement signature: %v", err)
  3709. }
  3710. // The channel existence proofs itself is currently announced in
  3711. // distinct message. In order to properly authenticate this message, we
  3712. // need two signatures: one under the identity public key used which
  3713. // signs the message itself and another signature of the identity
  3714. // public key under the funding key itself.
  3715. //
  3716. // TODO(roasbeef): use SignAnnouncement here instead?
  3717. chanAnnMsg, err := chanAnn.DataToSign()
  3718. if err != nil {
  3719. return nil, err
  3720. }
  3721. nodeSig, err := f.cfg.SignMessage(f.cfg.IDKeyLoc, chanAnnMsg, true)
  3722. if err != nil {
  3723. return nil, errors.Errorf("unable to generate node "+
  3724. "signature for channel announcement: %v", err)
  3725. }
  3726. bitcoinSig, err := f.cfg.SignMessage(
  3727. localFundingKey.KeyLocator, chanAnnMsg, true,
  3728. )
  3729. if err != nil {
  3730. return nil, errors.Errorf("unable to generate bitcoin "+
  3731. "signature for node public key: %v", err)
  3732. }
  3733. // Finally, we'll generate the announcement proof which we'll use to
  3734. // provide the other side with the necessary signatures required to
  3735. // allow them to reconstruct the full channel announcement.
  3736. proof := &lnwire.AnnounceSignatures{
  3737. ChannelID: chanID,
  3738. ShortChannelID: shortChanID,
  3739. }
  3740. proof.NodeSignature, err = lnwire.NewSigFromSignature(nodeSig)
  3741. if err != nil {
  3742. return nil, err
  3743. }
  3744. proof.BitcoinSignature, err = lnwire.NewSigFromSignature(bitcoinSig)
  3745. if err != nil {
  3746. return nil, err
  3747. }
  3748. return &chanAnnouncement{
  3749. chanAnn: chanAnn,
  3750. chanUpdateAnn: chanUpdateAnn,
  3751. chanProof: proof,
  3752. }, nil
  3753. }
  3754. // announceChannel announces a newly created channel to the rest of the network
  3755. // by crafting the two authenticated announcements required for the peers on
  3756. // the network to recognize the legitimacy of the channel. The crafted
  3757. // announcements are then sent to the channel router to handle broadcasting to
  3758. // the network during its next trickle.
  3759. // This method is synchronous and will return when all the network requests
  3760. // finish, either successfully or with an error.
  3761. func (f *Manager) announceChannel(localIDKey, remoteIDKey *btcec.PublicKey,
  3762. localFundingKey *keychain.KeyDescriptor,
  3763. remoteFundingKey *btcec.PublicKey, shortChanID lnwire.ShortChannelID,
  3764. chanID lnwire.ChannelID, chanType channeldb.ChannelType) error {
  3765. // First, we'll create the batch of announcements to be sent upon
  3766. // initial channel creation. This includes the channel announcement
  3767. // itself, the channel update announcement, and our half of the channel
  3768. // proof needed to fully authenticate the channel.
  3769. //
  3770. // We can pass in zeroes for the min and max htlc policy, because we
  3771. // only use the channel announcement message from the returned struct.
  3772. ann, err := f.newChanAnnouncement(localIDKey, remoteIDKey,
  3773. localFundingKey, remoteFundingKey, shortChanID, chanID,
  3774. 0, 0, nil, chanType,
  3775. )
  3776. if err != nil {
  3777. log.Errorf("can't generate channel announcement: %v", err)
  3778. return err
  3779. }
  3780. // We only send the channel proof announcement and the node announcement
  3781. // because addToGraph previously sent the ChannelAnnouncement and
  3782. // the ChannelUpdate announcement messages. The channel proof and node
  3783. // announcements are broadcast to the greater network.
  3784. errChan := f.cfg.SendAnnouncement(ann.chanProof)
  3785. select {
  3786. case err := <-errChan:
  3787. if err != nil {
  3788. if graph.IsError(err, graph.ErrOutdated,
  3789. graph.ErrIgnored) {
  3790. log.Debugf("Graph rejected "+
  3791. "AnnounceSignatures: %v", err)
  3792. } else {
  3793. log.Errorf("Unable to send channel "+
  3794. "proof: %v", err)
  3795. return err
  3796. }
  3797. }
  3798. case <-f.quit:
  3799. return ErrFundingManagerShuttingDown
  3800. }
  3801. // Now that the channel is announced to the network, we will also
  3802. // obtain and send a node announcement. This is done since a node
  3803. // announcement is only accepted after a channel is known for that
  3804. // particular node, and this might be our first channel.
  3805. nodeAnn, err := f.cfg.CurrentNodeAnnouncement()
  3806. if err != nil {
  3807. log.Errorf("can't generate node announcement: %v", err)
  3808. return err
  3809. }
  3810. errChan = f.cfg.SendAnnouncement(&nodeAnn)
  3811. select {
  3812. case err := <-errChan:
  3813. if err != nil {
  3814. if graph.IsError(err, graph.ErrOutdated,
  3815. graph.ErrIgnored) {
  3816. log.Debugf("Graph rejected "+
  3817. "NodeAnnouncement: %v", err)
  3818. } else {
  3819. log.Errorf("Unable to send node "+
  3820. "announcement: %v", err)
  3821. return err
  3822. }
  3823. }
  3824. case <-f.quit:
  3825. return ErrFundingManagerShuttingDown
  3826. }
  3827. return nil
  3828. }
  3829. // InitFundingWorkflow sends a message to the funding manager instructing it
  3830. // to initiate a single funder workflow with the source peer.
  3831. // TODO(roasbeef): re-visit blocking nature..
  3832. func (f *Manager) InitFundingWorkflow(msg *InitFundingMsg) {
  3833. f.fundingRequests <- msg
  3834. }
  3835. // getUpfrontShutdownScript takes a user provided script and a getScript
  3836. // function which can be used to generate an upfront shutdown script. If our
  3837. // peer does not support the feature, this function will error if a non-zero
  3838. // script was provided by the user, and return an empty script otherwise. If
  3839. // our peer does support the feature, we will return the user provided script
  3840. // if non-zero, or a freshly generated script if our node is configured to set
  3841. // upfront shutdown scripts automatically.
  3842. func getUpfrontShutdownScript(enableUpfrontShutdown bool, peer lnpeer.Peer,
  3843. script lnwire.DeliveryAddress,
  3844. getScript func(bool) (lnwire.DeliveryAddress, error)) (lnwire.DeliveryAddress,
  3845. error) {
  3846. // Check whether the remote peer supports upfront shutdown scripts.
  3847. remoteUpfrontShutdown := peer.RemoteFeatures().HasFeature(
  3848. lnwire.UpfrontShutdownScriptOptional,
  3849. )
  3850. // If the peer does not support upfront shutdown scripts, and one has been
  3851. // provided, return an error because the feature is not supported.
  3852. if !remoteUpfrontShutdown && len(script) != 0 {
  3853. return nil, errUpfrontShutdownScriptNotSupported
  3854. }
  3855. // If the peer does not support upfront shutdown, return an empty address.
  3856. if !remoteUpfrontShutdown {
  3857. return nil, nil
  3858. }
  3859. // If the user has provided an script and the peer supports the feature,
  3860. // return it. Note that user set scripts override the enable upfront
  3861. // shutdown flag.
  3862. if len(script) > 0 {
  3863. return script, nil
  3864. }
  3865. // If we do not have setting of upfront shutdown script enabled, return
  3866. // an empty script.
  3867. if !enableUpfrontShutdown {
  3868. return nil, nil
  3869. }
  3870. // We can safely send a taproot address iff, both sides have negotiated
  3871. // the shutdown-any-segwit feature.
  3872. taprootOK := peer.RemoteFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional) &&
  3873. peer.LocalFeatures().HasFeature(lnwire.ShutdownAnySegwitOptional)
  3874. return getScript(taprootOK)
  3875. }
  3876. // handleInitFundingMsg creates a channel reservation within the daemon's
  3877. // wallet, then sends a funding request to the remote peer kicking off the
  3878. // funding workflow.
  3879. func (f *Manager) handleInitFundingMsg(msg *InitFundingMsg) {
  3880. var (
  3881. peerKey = msg.Peer.IdentityKey()
  3882. localAmt = msg.LocalFundingAmt
  3883. baseFee = msg.BaseFee
  3884. feeRate = msg.FeeRate
  3885. minHtlcIn = msg.MinHtlcIn
  3886. remoteCsvDelay = msg.RemoteCsvDelay
  3887. maxValue = msg.MaxValueInFlight
  3888. maxHtlcs = msg.MaxHtlcs
  3889. maxCSV = msg.MaxLocalCsv
  3890. chanReserve = msg.RemoteChanReserve
  3891. outpoints = msg.Outpoints
  3892. )
  3893. // If no maximum CSV delay was set for this channel, we use our default
  3894. // value.
  3895. if maxCSV == 0 {
  3896. maxCSV = f.cfg.MaxLocalCSVDelay
  3897. }
  3898. log.Infof("Initiating fundingRequest(local_amt=%v "+
  3899. "(subtract_fees=%v), push_amt=%v, chain_hash=%v, peer=%x, "+
  3900. "min_confs=%v)", localAmt, msg.SubtractFees, msg.PushAmt,
  3901. msg.ChainHash, peerKey.SerializeCompressed(), msg.MinConfs)
  3902. // We set the channel flags to indicate whether we want this channel to
  3903. // be announced to the network.
  3904. var channelFlags lnwire.FundingFlag
  3905. if !msg.Private {
  3906. // This channel will be announced.
  3907. channelFlags = lnwire.FFAnnounceChannel
  3908. }
  3909. // If the caller specified their own channel ID, then we'll use that.
  3910. // Otherwise we'll generate a fresh one as normal. This will be used
  3911. // to track this reservation throughout its lifetime.
  3912. var chanID PendingChanID
  3913. if msg.PendingChanID == zeroID {
  3914. chanID = f.nextPendingChanID()
  3915. } else {
  3916. // If the user specified their own pending channel ID, then
  3917. // we'll ensure it doesn't collide with any existing pending
  3918. // channel ID.
  3919. chanID = msg.PendingChanID
  3920. if _, err := f.getReservationCtx(peerKey, chanID); err == nil {
  3921. msg.Err <- fmt.Errorf("pendingChannelID(%x) "+
  3922. "already present", chanID[:])
  3923. return
  3924. }
  3925. }
  3926. // Check whether the peer supports upfront shutdown, and get an address
  3927. // which should be used (either a user specified address or a new
  3928. // address from the wallet if our node is configured to set shutdown
  3929. // address by default).
  3930. shutdown, err := getUpfrontShutdownScript(
  3931. f.cfg.EnableUpfrontShutdown, msg.Peer, msg.ShutdownScript,
  3932. f.selectShutdownScript,
  3933. )
  3934. if err != nil {
  3935. msg.Err <- err
  3936. return
  3937. }
  3938. // Initialize a funding reservation with the local wallet. If the
  3939. // wallet doesn't have enough funds to commit to this channel, then the
  3940. // request will fail, and be aborted.
  3941. //
  3942. // Before we init the channel, we'll also check to see what commitment
  3943. // format we can use with this peer. This is dependent on *both* us and
  3944. // the remote peer are signaling the proper feature bit.
  3945. chanType, commitType, err := negotiateCommitmentType(
  3946. msg.ChannelType, msg.Peer.LocalFeatures(),
  3947. msg.Peer.RemoteFeatures(),
  3948. )
  3949. if err != nil {
  3950. log.Errorf("channel type negotiation failed: %v", err)
  3951. msg.Err <- err
  3952. return
  3953. }
  3954. var (
  3955. zeroConf bool
  3956. scid bool
  3957. )
  3958. if chanType != nil {
  3959. // Check if the returned chanType includes either the zero-conf
  3960. // or scid-alias bits.
  3961. featureVec := lnwire.RawFeatureVector(*chanType)
  3962. zeroConf = featureVec.IsSet(lnwire.ZeroConfRequired)
  3963. scid = featureVec.IsSet(lnwire.ScidAliasRequired)
  3964. // The option-scid-alias channel type for a public channel is
  3965. // disallowed.
  3966. if scid && !msg.Private {
  3967. err = fmt.Errorf("option-scid-alias chantype for " +
  3968. "public channel")
  3969. log.Error(err)
  3970. msg.Err <- err
  3971. return
  3972. }
  3973. }
  3974. // First, we'll query the fee estimator for a fee that should get the
  3975. // commitment transaction confirmed by the next few blocks (conf target
  3976. // of 3). We target the near blocks here to ensure that we'll be able
  3977. // to execute a timely unilateral channel closure if needed.
  3978. commitFeePerKw, err := f.cfg.FeeEstimator.EstimateFeePerKW(3)
  3979. if err != nil {
  3980. msg.Err <- err
  3981. return
  3982. }
  3983. // For anchor channels cap the initial commit fee rate at our defined
  3984. // maximum.
  3985. if commitType.HasAnchors() &&
  3986. commitFeePerKw > f.cfg.MaxAnchorsCommitFeeRate {
  3987. commitFeePerKw = f.cfg.MaxAnchorsCommitFeeRate
  3988. }
  3989. var scidFeatureVal bool
  3990. if hasFeatures(
  3991. msg.Peer.LocalFeatures(), msg.Peer.RemoteFeatures(),
  3992. lnwire.ScidAliasOptional,
  3993. ) {
  3994. scidFeatureVal = true
  3995. }
  3996. req := &lnwallet.InitFundingReserveMsg{
  3997. ChainHash: &msg.ChainHash,
  3998. PendingChanID: chanID,
  3999. NodeID: peerKey,
  4000. NodeAddr: msg.Peer.Address(),
  4001. SubtractFees: msg.SubtractFees,
  4002. LocalFundingAmt: localAmt,
  4003. RemoteFundingAmt: 0,
  4004. FundUpToMaxAmt: msg.FundUpToMaxAmt,
  4005. MinFundAmt: msg.MinFundAmt,
  4006. RemoteChanReserve: chanReserve,
  4007. Outpoints: outpoints,
  4008. CommitFeePerKw: commitFeePerKw,
  4009. FundingFeePerKw: msg.FundingFeePerKw,
  4010. PushMSat: msg.PushAmt,
  4011. Flags: channelFlags,
  4012. MinConfs: msg.MinConfs,
  4013. CommitType: commitType,
  4014. ChanFunder: msg.ChanFunder,
  4015. // Unconfirmed Utxos which are marked by the sweeper subsystem
  4016. // are excluded from the coin selection because they are not
  4017. // final and can be RBFed by the sweeper subsystem.
  4018. AllowUtxoForFunding: func(u lnwallet.Utxo) bool {
  4019. // Utxos with at least 1 confirmation are safe to use
  4020. // for channel openings because they don't bare the risk
  4021. // of being replaced (BIP 125 RBF).
  4022. if u.Confirmations > 0 {
  4023. return true
  4024. }
  4025. // Query the sweeper storage to make sure we don't use
  4026. // an unconfirmed utxo still in use by the sweeper
  4027. // subsystem.
  4028. return !f.cfg.IsSweeperOutpoint(u.OutPoint)
  4029. },
  4030. ZeroConf: zeroConf,
  4031. OptionScidAlias: scid,
  4032. ScidAliasFeature: scidFeatureVal,
  4033. Memo: msg.Memo,
  4034. }
  4035. reservation, err := f.cfg.Wallet.InitChannelReservation(req)
  4036. if err != nil {
  4037. msg.Err <- err
  4038. return
  4039. }
  4040. if zeroConf {
  4041. // Store the alias for zero-conf channels in the underlying
  4042. // partial channel state.
  4043. aliasScid, err := f.cfg.AliasManager.RequestAlias()
  4044. if err != nil {
  4045. msg.Err <- err
  4046. return
  4047. }
  4048. reservation.AddAlias(aliasScid)
  4049. }
  4050. // Set our upfront shutdown address in the existing reservation.
  4051. reservation.SetOurUpfrontShutdown(shutdown)
  4052. // Now that we have successfully reserved funds for this channel in the
  4053. // wallet, we can fetch the final channel capacity. This is done at
  4054. // this point since the final capacity might change in case of
  4055. // SubtractFees=true.
  4056. capacity := reservation.Capacity()
  4057. log.Infof("Target commit tx sat/kw for pendingID(%x): %v", chanID,
  4058. int64(commitFeePerKw))
  4059. // If the remote CSV delay was not set in the open channel request,
  4060. // we'll use the RequiredRemoteDelay closure to compute the delay we
  4061. // require given the total amount of funds within the channel.
  4062. if remoteCsvDelay == 0 {
  4063. remoteCsvDelay = f.cfg.RequiredRemoteDelay(capacity)
  4064. }
  4065. // If no minimum HTLC value was specified, use the default one.
  4066. if minHtlcIn == 0 {
  4067. minHtlcIn = f.cfg.DefaultMinHtlcIn
  4068. }
  4069. // If no max value was specified, use the default one.
  4070. if maxValue == 0 {
  4071. maxValue = f.cfg.RequiredRemoteMaxValue(capacity)
  4072. }
  4073. if maxHtlcs == 0 {
  4074. maxHtlcs = f.cfg.RequiredRemoteMaxHTLCs(capacity)
  4075. }
  4076. // Once the reservation has been created, and indexed, queue a funding
  4077. // request to the remote peer, kicking off the funding workflow.
  4078. ourContribution := reservation.OurContribution()
  4079. // Prepare the optional channel fee values from the initFundingMsg. If
  4080. // useBaseFee or useFeeRate are false the client did not provide fee
  4081. // values hence we assume default fee settings from the config.
  4082. forwardingPolicy := f.defaultForwardingPolicy(
  4083. ourContribution.ChannelStateBounds,
  4084. )
  4085. if baseFee != nil {
  4086. forwardingPolicy.BaseFee = lnwire.MilliSatoshi(*baseFee)
  4087. }
  4088. if feeRate != nil {
  4089. forwardingPolicy.FeeRate = lnwire.MilliSatoshi(*feeRate)
  4090. }
  4091. // Fetch our dust limit which is part of the default channel
  4092. // constraints, and log it.
  4093. ourDustLimit := ourContribution.DustLimit
  4094. log.Infof("Dust limit for pendingID(%x): %v", chanID, ourDustLimit)
  4095. // If the channel reserve is not specified, then we calculate an
  4096. // appropriate amount here.
  4097. if chanReserve == 0 {
  4098. chanReserve = f.cfg.RequiredRemoteChanReserve(
  4099. capacity, ourDustLimit,
  4100. )
  4101. }
  4102. // If a pending channel map for this peer isn't already created, then
  4103. // we create one, ultimately allowing us to track this pending
  4104. // reservation within the target peer.
  4105. peerIDKey := newSerializedKey(peerKey)
  4106. f.resMtx.Lock()
  4107. if _, ok := f.activeReservations[peerIDKey]; !ok {
  4108. f.activeReservations[peerIDKey] = make(pendingChannels)
  4109. }
  4110. resCtx := &reservationWithCtx{
  4111. chanAmt: capacity,
  4112. forwardingPolicy: *forwardingPolicy,
  4113. remoteCsvDelay: remoteCsvDelay,
  4114. remoteMinHtlc: minHtlcIn,
  4115. remoteMaxValue: maxValue,
  4116. remoteMaxHtlcs: maxHtlcs,
  4117. remoteChanReserve: chanReserve,
  4118. maxLocalCsv: maxCSV,
  4119. channelType: chanType,
  4120. reservation: reservation,
  4121. peer: msg.Peer,
  4122. updates: msg.Updates,
  4123. err: msg.Err,
  4124. }
  4125. f.activeReservations[peerIDKey][chanID] = resCtx
  4126. f.resMtx.Unlock()
  4127. // Update the timestamp once the InitFundingMsg has been handled.
  4128. defer resCtx.updateTimestamp()
  4129. // Check the sanity of the selected channel constraints.
  4130. bounds := &channeldb.ChannelStateBounds{
  4131. ChanReserve: chanReserve,
  4132. MaxPendingAmount: maxValue,
  4133. MinHTLC: minHtlcIn,
  4134. MaxAcceptedHtlcs: maxHtlcs,
  4135. }
  4136. commitParams := &channeldb.CommitmentParams{
  4137. DustLimit: ourDustLimit,
  4138. CsvDelay: remoteCsvDelay,
  4139. }
  4140. err = lnwallet.VerifyConstraints(
  4141. bounds, commitParams, resCtx.maxLocalCsv, capacity,
  4142. )
  4143. if err != nil {
  4144. _, reserveErr := f.cancelReservationCtx(peerKey, chanID, false)
  4145. if reserveErr != nil {
  4146. log.Errorf("unable to cancel reservation: %v",
  4147. reserveErr)
  4148. }
  4149. msg.Err <- err
  4150. return
  4151. }
  4152. // When opening a script enforced channel lease, include the required
  4153. // expiry TLV record in our proposal.
  4154. var leaseExpiry *lnwire.LeaseExpiry
  4155. if commitType == lnwallet.CommitmentTypeScriptEnforcedLease {
  4156. leaseExpiry = new(lnwire.LeaseExpiry)
  4157. *leaseExpiry = lnwire.LeaseExpiry(reservation.LeaseExpiry())
  4158. }
  4159. log.Infof("Starting funding workflow with %v for pending_id(%x), "+
  4160. "committype=%v", msg.Peer.Address(), chanID, commitType)
  4161. fundingOpen := lnwire.OpenChannel{
  4162. ChainHash: *f.cfg.Wallet.Cfg.NetParams.GenesisHash,
  4163. PendingChannelID: chanID,
  4164. FundingAmount: capacity,
  4165. PushAmount: msg.PushAmt,
  4166. DustLimit: ourDustLimit,
  4167. MaxValueInFlight: maxValue,
  4168. ChannelReserve: chanReserve,
  4169. HtlcMinimum: minHtlcIn,
  4170. FeePerKiloWeight: uint32(commitFeePerKw),
  4171. CsvDelay: remoteCsvDelay,
  4172. MaxAcceptedHTLCs: maxHtlcs,
  4173. FundingKey: ourContribution.MultiSigKey.PubKey,
  4174. RevocationPoint: ourContribution.RevocationBasePoint.PubKey,
  4175. PaymentPoint: ourContribution.PaymentBasePoint.PubKey,
  4176. HtlcPoint: ourContribution.HtlcBasePoint.PubKey,
  4177. DelayedPaymentPoint: ourContribution.DelayBasePoint.PubKey,
  4178. FirstCommitmentPoint: ourContribution.FirstCommitmentPoint,
  4179. ChannelFlags: channelFlags,
  4180. UpfrontShutdownScript: shutdown,
  4181. ChannelType: chanType,
  4182. LeaseExpiry: leaseExpiry,
  4183. }
  4184. if commitType.IsTaproot() {
  4185. fundingOpen.LocalNonce = lnwire.SomeMusig2Nonce(
  4186. ourContribution.LocalNonce.PubNonce,
  4187. )
  4188. }
  4189. if err := msg.Peer.SendMessage(true, &fundingOpen); err != nil {
  4190. e := fmt.Errorf("unable to send funding request message: %w",
  4191. err)
  4192. log.Errorf(e.Error())
  4193. // Since we were unable to send the initial message to the peer
  4194. // and start the funding flow, we'll cancel this reservation.
  4195. _, err := f.cancelReservationCtx(peerKey, chanID, false)
  4196. if err != nil {
  4197. log.Errorf("unable to cancel reservation: %v", err)
  4198. }
  4199. msg.Err <- e
  4200. return
  4201. }
  4202. }
  4203. // handleWarningMsg processes the warning which was received from remote peer.
  4204. func (f *Manager) handleWarningMsg(peer lnpeer.Peer, msg *lnwire.Warning) {
  4205. log.Warnf("received warning message from peer %x: %v",
  4206. peer.IdentityKey().SerializeCompressed(), msg.Warning())
  4207. }
  4208. // handleErrorMsg processes the error which was received from remote peer,
  4209. // depending on the type of error we should do different clean up steps and
  4210. // inform the user about it.
  4211. func (f *Manager) handleErrorMsg(peer lnpeer.Peer, msg *lnwire.Error) {
  4212. chanID := msg.ChanID
  4213. peerKey := peer.IdentityKey()
  4214. // First, we'll attempt to retrieve and cancel the funding workflow
  4215. // that this error was tied to. If we're unable to do so, then we'll
  4216. // exit early as this was an unwarranted error.
  4217. resCtx, err := f.cancelReservationCtx(peerKey, chanID, true)
  4218. if err != nil {
  4219. log.Warnf("Received error for non-existent funding "+
  4220. "flow: %v (%v)", err, msg.Error())
  4221. return
  4222. }
  4223. // If we did indeed find the funding workflow, then we'll return the
  4224. // error back to the caller (if any), and cancel the workflow itself.
  4225. fundingErr := fmt.Errorf("received funding error from %x: %v",
  4226. peerKey.SerializeCompressed(), msg.Error(),
  4227. )
  4228. log.Errorf(fundingErr.Error())
  4229. // If this was a PSBT funding flow, the remote likely timed out because
  4230. // we waited too long. Return a nice error message to the user in that
  4231. // case so the user knows what's the problem.
  4232. if resCtx.reservation.IsPsbt() {
  4233. fundingErr = fmt.Errorf("%w: %v", chanfunding.ErrRemoteCanceled,
  4234. fundingErr)
  4235. }
  4236. resCtx.err <- fundingErr
  4237. }
  4238. // pruneZombieReservations loops through all pending reservations and fails the
  4239. // funding flow for any reservations that have not been updated since the
  4240. // ReservationTimeout and are not locked waiting for the funding transaction.
  4241. func (f *Manager) pruneZombieReservations() {
  4242. zombieReservations := make(pendingChannels)
  4243. f.resMtx.RLock()
  4244. for _, pendingReservations := range f.activeReservations {
  4245. for pendingChanID, resCtx := range pendingReservations {
  4246. if resCtx.isLocked() {
  4247. continue
  4248. }
  4249. // We don't want to expire PSBT funding reservations.
  4250. // These reservations are always initiated by us and the
  4251. // remote peer is likely going to cancel them after some
  4252. // idle time anyway. So no need for us to also prune
  4253. // them.
  4254. sinceLastUpdate := time.Since(resCtx.lastUpdated)
  4255. isExpired := sinceLastUpdate > f.cfg.ReservationTimeout
  4256. if !resCtx.reservation.IsPsbt() && isExpired {
  4257. zombieReservations[pendingChanID] = resCtx
  4258. }
  4259. }
  4260. }
  4261. f.resMtx.RUnlock()
  4262. for pendingChanID, resCtx := range zombieReservations {
  4263. err := fmt.Errorf("reservation timed out waiting for peer "+
  4264. "(peer_id:%x, chan_id:%x)",
  4265. resCtx.peer.IdentityKey().SerializeCompressed(),
  4266. pendingChanID[:])
  4267. log.Warnf(err.Error())
  4268. chanID := lnwire.NewChanIDFromOutPoint(
  4269. *resCtx.reservation.FundingOutpoint(),
  4270. )
  4271. // Create channel identifier and set the channel ID.
  4272. cid := newChanIdentifier(pendingChanID)
  4273. cid.setChanID(chanID)
  4274. f.failFundingFlow(resCtx.peer, cid, err)
  4275. }
  4276. }
  4277. // cancelReservationCtx does all needed work in order to securely cancel the
  4278. // reservation.
  4279. func (f *Manager) cancelReservationCtx(peerKey *btcec.PublicKey,
  4280. pendingChanID PendingChanID,
  4281. byRemote bool) (*reservationWithCtx, error) {
  4282. log.Infof("Cancelling funding reservation for node_key=%x, "+
  4283. "chan_id=%x", peerKey.SerializeCompressed(), pendingChanID[:])
  4284. peerIDKey := newSerializedKey(peerKey)
  4285. f.resMtx.Lock()
  4286. defer f.resMtx.Unlock()
  4287. nodeReservations, ok := f.activeReservations[peerIDKey]
  4288. if !ok {
  4289. // No reservations for this node.
  4290. return nil, errors.Errorf("no active reservations for peer(%x)",
  4291. peerIDKey[:])
  4292. }
  4293. ctx, ok := nodeReservations[pendingChanID]
  4294. if !ok {
  4295. return nil, errors.Errorf("unknown channel (id: %x) for "+
  4296. "peer(%x)", pendingChanID[:], peerIDKey[:])
  4297. }
  4298. // If the reservation was a PSBT funding flow and it was canceled by the
  4299. // remote peer, then we need to thread through a different error message
  4300. // to the subroutine that's waiting for the user input so it can return
  4301. // a nice error message to the user.
  4302. if ctx.reservation.IsPsbt() && byRemote {
  4303. ctx.reservation.RemoteCanceled()
  4304. }
  4305. if err := ctx.reservation.Cancel(); err != nil {
  4306. return nil, errors.Errorf("unable to cancel reservation: %v",
  4307. err)
  4308. }
  4309. delete(nodeReservations, pendingChanID)
  4310. // If this was the last active reservation for this peer, delete the
  4311. // peer's entry altogether.
  4312. if len(nodeReservations) == 0 {
  4313. delete(f.activeReservations, peerIDKey)
  4314. }
  4315. return ctx, nil
  4316. }
  4317. // deleteReservationCtx deletes the reservation uniquely identified by the
  4318. // target public key of the peer, and the specified pending channel ID.
  4319. func (f *Manager) deleteReservationCtx(peerKey *btcec.PublicKey,
  4320. pendingChanID PendingChanID) {
  4321. peerIDKey := newSerializedKey(peerKey)
  4322. f.resMtx.Lock()
  4323. defer f.resMtx.Unlock()
  4324. nodeReservations, ok := f.activeReservations[peerIDKey]
  4325. if !ok {
  4326. // No reservations for this node.
  4327. return
  4328. }
  4329. delete(nodeReservations, pendingChanID)
  4330. // If this was the last active reservation for this peer, delete the
  4331. // peer's entry altogether.
  4332. if len(nodeReservations) == 0 {
  4333. delete(f.activeReservations, peerIDKey)
  4334. }
  4335. }
  4336. // getReservationCtx returns the reservation context for a particular pending
  4337. // channel ID for a target peer.
  4338. func (f *Manager) getReservationCtx(peerKey *btcec.PublicKey,
  4339. pendingChanID PendingChanID) (*reservationWithCtx, error) {
  4340. peerIDKey := newSerializedKey(peerKey)
  4341. f.resMtx.RLock()
  4342. resCtx, ok := f.activeReservations[peerIDKey][pendingChanID]
  4343. f.resMtx.RUnlock()
  4344. if !ok {
  4345. return nil, errors.Errorf("unknown channel (id: %x) for "+
  4346. "peer(%x)", pendingChanID[:], peerIDKey[:])
  4347. }
  4348. return resCtx, nil
  4349. }
  4350. // IsPendingChannel returns a boolean indicating whether the channel identified
  4351. // by the pendingChanID and given peer is pending, meaning it is in the process
  4352. // of being funded. After the funding transaction has been confirmed, the
  4353. // channel will receive a new, permanent channel ID, and will no longer be
  4354. // considered pending.
  4355. func (f *Manager) IsPendingChannel(pendingChanID PendingChanID,
  4356. peer lnpeer.Peer) bool {
  4357. peerIDKey := newSerializedKey(peer.IdentityKey())
  4358. f.resMtx.RLock()
  4359. _, ok := f.activeReservations[peerIDKey][pendingChanID]
  4360. f.resMtx.RUnlock()
  4361. return ok
  4362. }
  4363. func copyPubKey(pub *btcec.PublicKey) *btcec.PublicKey {
  4364. var tmp btcec.JacobianPoint
  4365. pub.AsJacobian(&tmp)
  4366. tmp.ToAffine()
  4367. return btcec.NewPublicKey(&tmp.X, &tmp.Y)
  4368. }
  4369. // defaultForwardingPolicy returns the default forwarding policy based on the
  4370. // default routing policy and our local channel constraints.
  4371. func (f *Manager) defaultForwardingPolicy(
  4372. bounds channeldb.ChannelStateBounds) *models.ForwardingPolicy {
  4373. return &models.ForwardingPolicy{
  4374. MinHTLCOut: bounds.MinHTLC,
  4375. MaxHTLC: bounds.MaxPendingAmount,
  4376. BaseFee: f.cfg.DefaultRoutingPolicy.BaseFee,
  4377. FeeRate: f.cfg.DefaultRoutingPolicy.FeeRate,
  4378. TimeLockDelta: f.cfg.DefaultRoutingPolicy.TimeLockDelta,
  4379. }
  4380. }
  4381. // saveInitialForwardingPolicy saves the forwarding policy for the provided
  4382. // chanPoint in the channelOpeningStateBucket.
  4383. func (f *Manager) saveInitialForwardingPolicy(chanID lnwire.ChannelID,
  4384. forwardingPolicy *models.ForwardingPolicy) error {
  4385. return f.cfg.ChannelDB.SaveInitialForwardingPolicy(
  4386. chanID, forwardingPolicy,
  4387. )
  4388. }
  4389. // getInitialForwardingPolicy fetches the initial forwarding policy for a given
  4390. // channel id from the database which will be applied during the channel
  4391. // announcement phase.
  4392. func (f *Manager) getInitialForwardingPolicy(
  4393. chanID lnwire.ChannelID) (*models.ForwardingPolicy, error) {
  4394. return f.cfg.ChannelDB.GetInitialForwardingPolicy(chanID)
  4395. }
  4396. // deleteInitialForwardingPolicy removes channel fees for this chanID from
  4397. // the database.
  4398. func (f *Manager) deleteInitialForwardingPolicy(chanID lnwire.ChannelID) error {
  4399. return f.cfg.ChannelDB.DeleteInitialForwardingPolicy(chanID)
  4400. }
  4401. // saveChannelOpeningState saves the channelOpeningState for the provided
  4402. // chanPoint to the channelOpeningStateBucket.
  4403. func (f *Manager) saveChannelOpeningState(chanPoint *wire.OutPoint,
  4404. state channelOpeningState, shortChanID *lnwire.ShortChannelID) error {
  4405. var outpointBytes bytes.Buffer
  4406. if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
  4407. return err
  4408. }
  4409. // Save state and the uint64 representation of the shortChanID
  4410. // for later use.
  4411. scratch := make([]byte, 10)
  4412. byteOrder.PutUint16(scratch[:2], uint16(state))
  4413. byteOrder.PutUint64(scratch[2:], shortChanID.ToUint64())
  4414. return f.cfg.ChannelDB.SaveChannelOpeningState(
  4415. outpointBytes.Bytes(), scratch,
  4416. )
  4417. }
  4418. // getChannelOpeningState fetches the channelOpeningState for the provided
  4419. // chanPoint from the database, or returns ErrChannelNotFound if the channel
  4420. // is not found.
  4421. func (f *Manager) getChannelOpeningState(chanPoint *wire.OutPoint) (
  4422. channelOpeningState, *lnwire.ShortChannelID, error) {
  4423. var outpointBytes bytes.Buffer
  4424. if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
  4425. return 0, nil, err
  4426. }
  4427. value, err := f.cfg.ChannelDB.GetChannelOpeningState(
  4428. outpointBytes.Bytes(),
  4429. )
  4430. if err != nil {
  4431. return 0, nil, err
  4432. }
  4433. state := channelOpeningState(byteOrder.Uint16(value[:2]))
  4434. shortChanID := lnwire.NewShortChanIDFromInt(byteOrder.Uint64(value[2:]))
  4435. return state, &shortChanID, nil
  4436. }
  4437. // deleteChannelOpeningState removes any state for chanPoint from the database.
  4438. func (f *Manager) deleteChannelOpeningState(chanPoint *wire.OutPoint) error {
  4439. var outpointBytes bytes.Buffer
  4440. if err := WriteOutpoint(&outpointBytes, chanPoint); err != nil {
  4441. return err
  4442. }
  4443. return f.cfg.ChannelDB.DeleteChannelOpeningState(
  4444. outpointBytes.Bytes(),
  4445. )
  4446. }
  4447. // selectShutdownScript selects the shutdown script we should send to the peer.
  4448. // If we can use taproot, then we prefer that, otherwise we'll use a p2wkh
  4449. // script.
  4450. func (f *Manager) selectShutdownScript(taprootOK bool,
  4451. ) (lnwire.DeliveryAddress, error) {
  4452. addrType := lnwallet.WitnessPubKey
  4453. if taprootOK {
  4454. addrType = lnwallet.TaprootPubkey
  4455. }
  4456. addr, err := f.cfg.Wallet.NewAddress(
  4457. addrType, false, lnwallet.DefaultAccountName,
  4458. )
  4459. if err != nil {
  4460. return nil, err
  4461. }
  4462. return txscript.PayToAddrScript(addr)
  4463. }
  4464. // waitForPeerOnline blocks until the peer specified by peerPubkey comes online
  4465. // and then returns the online peer.
  4466. func (f *Manager) waitForPeerOnline(peerPubkey *btcec.PublicKey) (lnpeer.Peer,
  4467. error) {
  4468. peerChan := make(chan lnpeer.Peer, 1)
  4469. var peerKey [33]byte
  4470. copy(peerKey[:], peerPubkey.SerializeCompressed())
  4471. f.cfg.NotifyWhenOnline(peerKey, peerChan)
  4472. var peer lnpeer.Peer
  4473. select {
  4474. case peer = <-peerChan:
  4475. case <-f.quit:
  4476. return peer, ErrFundingManagerShuttingDown
  4477. }
  4478. return peer, nil
  4479. }