switch_test.go 149 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542
  1. package htlcswitch
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/sha256"
  6. "fmt"
  7. "io"
  8. mrand "math/rand"
  9. "reflect"
  10. "testing"
  11. "time"
  12. "github.com/btcsuite/btcd/btcutil"
  13. "github.com/davecgh/go-spew/spew"
  14. "github.com/go-errors/errors"
  15. "github.com/lightningnetwork/lnd/chainntnfs"
  16. "github.com/lightningnetwork/lnd/channeldb"
  17. "github.com/lightningnetwork/lnd/channeldb/models"
  18. "github.com/lightningnetwork/lnd/contractcourt"
  19. "github.com/lightningnetwork/lnd/htlcswitch/hodl"
  20. "github.com/lightningnetwork/lnd/htlcswitch/hop"
  21. "github.com/lightningnetwork/lnd/lntest/mock"
  22. "github.com/lightningnetwork/lnd/lntypes"
  23. "github.com/lightningnetwork/lnd/lnwire"
  24. "github.com/lightningnetwork/lnd/ticker"
  25. "github.com/stretchr/testify/require"
  26. )
  27. var zeroCircuit = models.CircuitKey{}
  28. var emptyScid = lnwire.ShortChannelID{}
  29. func genPreimage() ([32]byte, error) {
  30. var preimage [32]byte
  31. if _, err := io.ReadFull(rand.Reader, preimage[:]); err != nil {
  32. return preimage, err
  33. }
  34. return preimage, nil
  35. }
  36. // TestSwitchAddDuplicateLink tests that the switch will reject duplicate links
  37. // for live links. It also tests that we can successfully add a link after
  38. // having removed it.
  39. func TestSwitchAddDuplicateLink(t *testing.T) {
  40. t.Parallel()
  41. alicePeer, err := newMockServer(
  42. t, "alice", testStartingHeight, nil, testDefaultDelta,
  43. )
  44. require.NoError(t, err, "unable to create alice server")
  45. s, err := initSwitchWithTempDB(t, testStartingHeight)
  46. require.NoError(t, err, "unable to init switch")
  47. if err := s.Start(); err != nil {
  48. t.Fatalf("unable to start switch: %v", err)
  49. }
  50. defer s.Stop()
  51. chanID1, aliceScid := genID()
  52. aliceChannelLink := newMockChannelLink(
  53. s, chanID1, aliceScid, emptyScid, alicePeer, false, false,
  54. false, false,
  55. )
  56. if err := s.AddLink(aliceChannelLink); err != nil {
  57. t.Fatalf("unable to add alice link: %v", err)
  58. }
  59. // Alice should have a live link, adding again should fail.
  60. if err := s.AddLink(aliceChannelLink); err == nil {
  61. t.Fatalf("adding duplicate link should have failed")
  62. }
  63. // Remove the live link to ensure the indexes are cleared.
  64. s.RemoveLink(chanID1)
  65. // Alice has no links, adding should succeed.
  66. if err := s.AddLink(aliceChannelLink); err != nil {
  67. t.Fatalf("unable to add alice link: %v", err)
  68. }
  69. }
  70. // TestSwitchHasActiveLink tests the behavior of HasActiveLink, and asserts that
  71. // it only returns true if a link's short channel id has confirmed (meaning the
  72. // channel is no longer pending) and it's EligibleToForward method returns true,
  73. // i.e. it has received ChannelReady from the remote peer.
  74. func TestSwitchHasActiveLink(t *testing.T) {
  75. t.Parallel()
  76. alicePeer, err := newMockServer(
  77. t, "alice", testStartingHeight, nil, testDefaultDelta,
  78. )
  79. require.NoError(t, err, "unable to create alice server")
  80. s, err := initSwitchWithTempDB(t, testStartingHeight)
  81. require.NoError(t, err, "unable to init switch")
  82. if err := s.Start(); err != nil {
  83. t.Fatalf("unable to start switch: %v", err)
  84. }
  85. defer s.Stop()
  86. chanID1, aliceScid := genID()
  87. aliceChannelLink := newMockChannelLink(
  88. s, chanID1, aliceScid, emptyScid, alicePeer, false, false,
  89. false, false,
  90. )
  91. if err := s.AddLink(aliceChannelLink); err != nil {
  92. t.Fatalf("unable to add alice link: %v", err)
  93. }
  94. // The link has been added, but it's still pending. HasActiveLink should
  95. // return false since the link has not been added to the linkIndex
  96. // containing live links.
  97. if s.HasActiveLink(chanID1) {
  98. t.Fatalf("link should not be active yet, still pending")
  99. }
  100. // Finally, simulate the link receiving channel_ready by setting its
  101. // eligibility to true.
  102. aliceChannelLink.eligible = true
  103. // The link should now be reported as active, since EligibleToForward
  104. // returns true and the link is in the linkIndex.
  105. if !s.HasActiveLink(chanID1) {
  106. t.Fatalf("link should not be active now")
  107. }
  108. }
  109. // TestSwitchSendPending checks the inability of htlc switch to forward adds
  110. // over pending links.
  111. func TestSwitchSendPending(t *testing.T) {
  112. t.Parallel()
  113. alicePeer, err := newMockServer(
  114. t, "alice", testStartingHeight, nil, testDefaultDelta,
  115. )
  116. require.NoError(t, err, "unable to create alice server")
  117. bobPeer, err := newMockServer(
  118. t, "bob", testStartingHeight, nil, testDefaultDelta,
  119. )
  120. require.NoError(t, err, "unable to create bob server")
  121. s, err := initSwitchWithTempDB(t, testStartingHeight)
  122. require.NoError(t, err, "unable to init switch")
  123. if err := s.Start(); err != nil {
  124. t.Fatalf("unable to start switch: %v", err)
  125. }
  126. defer s.Stop()
  127. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  128. pendingChanID := lnwire.ShortChannelID{}
  129. aliceChannelLink := newMockChannelLink(
  130. s, chanID1, pendingChanID, emptyScid, alicePeer, false, false,
  131. false, false,
  132. )
  133. if err := s.AddLink(aliceChannelLink); err != nil {
  134. t.Fatalf("unable to add alice link: %v", err)
  135. }
  136. bobChannelLink := newMockChannelLink(
  137. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  138. false,
  139. )
  140. if err := s.AddLink(bobChannelLink); err != nil {
  141. t.Fatalf("unable to add bob link: %v", err)
  142. }
  143. // Create request which should is being forwarded from Bob channel
  144. // link to Alice channel link.
  145. preimage, err := genPreimage()
  146. require.NoError(t, err, "unable to generate preimage")
  147. rhash := sha256.Sum256(preimage[:])
  148. packet := &htlcPacket{
  149. incomingChanID: bobChanID,
  150. incomingHTLCID: 0,
  151. outgoingChanID: aliceChanID,
  152. obfuscator: NewMockObfuscator(),
  153. htlc: &lnwire.UpdateAddHTLC{
  154. PaymentHash: rhash,
  155. Amount: 1,
  156. },
  157. }
  158. // Send the ADD packet, this should not be forwarded out to the link
  159. // since there are no eligible links.
  160. if err = s.ForwardPackets(nil, packet); err != nil {
  161. t.Fatal(err)
  162. }
  163. select {
  164. case p := <-bobChannelLink.packets:
  165. if p.linkFailure != nil {
  166. err = p.linkFailure
  167. }
  168. case <-time.After(time.Second):
  169. t.Fatal("no timely reply from switch")
  170. }
  171. linkErr, ok := err.(*LinkError)
  172. if !ok {
  173. t.Fatalf("expected link error, got: %T", err)
  174. }
  175. if linkErr.WireMessage().Code() != lnwire.CodeUnknownNextPeer {
  176. t.Fatalf("expected fail unknown next peer, got: %T",
  177. linkErr.WireMessage().Code())
  178. }
  179. // No message should be sent, since the packet was failed.
  180. select {
  181. case <-aliceChannelLink.packets:
  182. t.Fatal("expected not to receive message")
  183. case <-time.After(time.Second):
  184. }
  185. // Since the packet should have been failed, there should be no active
  186. // circuits.
  187. if s.circuits.NumOpen() != 0 {
  188. t.Fatal("wrong amount of circuits")
  189. }
  190. }
  191. // TestSwitchForwardMapping checks that the Switch properly consults its maps
  192. // when forwarding packets.
  193. func TestSwitchForwardMapping(t *testing.T) {
  194. tests := []struct {
  195. name string
  196. // If this is true, then Alice's channel will be private.
  197. alicePrivate bool
  198. // If this is true, then Alice's channel will be a zero-conf
  199. // channel.
  200. zeroConf bool
  201. // If this is true, then Alice's channel will be an
  202. // option-scid-alias feature-bit, non-zero-conf channel.
  203. optionScid bool
  204. // If this is true, then an alias will be used for forwarding.
  205. useAlias bool
  206. // This is Alice's channel alias. This may not be set if this
  207. // is not an option_scid_alias channel (feature bit).
  208. aliceAlias lnwire.ShortChannelID
  209. // This is Alice's confirmed SCID. This may not be set if this
  210. // is a zero-conf channel before confirmation.
  211. aliceReal lnwire.ShortChannelID
  212. // If this is set, we expect Bob forwarding to Alice to fail.
  213. expectErr bool
  214. }{
  215. {
  216. name: "private unconfirmed zero-conf",
  217. alicePrivate: true,
  218. zeroConf: true,
  219. useAlias: true,
  220. aliceAlias: lnwire.ShortChannelID{
  221. BlockHeight: 16_000_002,
  222. TxIndex: 2,
  223. TxPosition: 2,
  224. },
  225. aliceReal: lnwire.ShortChannelID{},
  226. expectErr: false,
  227. },
  228. {
  229. name: "private confirmed zero-conf",
  230. alicePrivate: true,
  231. zeroConf: true,
  232. useAlias: true,
  233. aliceAlias: lnwire.ShortChannelID{
  234. BlockHeight: 16_000_003,
  235. TxIndex: 3,
  236. TxPosition: 3,
  237. },
  238. aliceReal: lnwire.ShortChannelID{
  239. BlockHeight: 300000,
  240. TxIndex: 3,
  241. TxPosition: 3,
  242. },
  243. expectErr: false,
  244. },
  245. {
  246. name: "private confirmed zero-conf failure",
  247. alicePrivate: true,
  248. zeroConf: true,
  249. useAlias: false,
  250. aliceAlias: lnwire.ShortChannelID{
  251. BlockHeight: 16_000_004,
  252. TxIndex: 4,
  253. TxPosition: 4,
  254. },
  255. aliceReal: lnwire.ShortChannelID{
  256. BlockHeight: 300002,
  257. TxIndex: 4,
  258. TxPosition: 4,
  259. },
  260. expectErr: true,
  261. },
  262. {
  263. name: "public unconfirmed zero-conf",
  264. alicePrivate: false,
  265. zeroConf: true,
  266. useAlias: true,
  267. aliceAlias: lnwire.ShortChannelID{
  268. BlockHeight: 16_000_005,
  269. TxIndex: 5,
  270. TxPosition: 5,
  271. },
  272. aliceReal: lnwire.ShortChannelID{},
  273. expectErr: false,
  274. },
  275. {
  276. name: "public confirmed zero-conf w/ alias",
  277. alicePrivate: false,
  278. zeroConf: true,
  279. useAlias: true,
  280. aliceAlias: lnwire.ShortChannelID{
  281. BlockHeight: 16_000_006,
  282. TxIndex: 6,
  283. TxPosition: 6,
  284. },
  285. aliceReal: lnwire.ShortChannelID{
  286. BlockHeight: 500000,
  287. TxIndex: 6,
  288. TxPosition: 6,
  289. },
  290. expectErr: false,
  291. },
  292. {
  293. name: "public confirmed zero-conf w/ real",
  294. alicePrivate: false,
  295. zeroConf: true,
  296. useAlias: false,
  297. aliceAlias: lnwire.ShortChannelID{
  298. BlockHeight: 16_000_007,
  299. TxIndex: 7,
  300. TxPosition: 7,
  301. },
  302. aliceReal: lnwire.ShortChannelID{
  303. BlockHeight: 502000,
  304. TxIndex: 7,
  305. TxPosition: 7,
  306. },
  307. expectErr: false,
  308. },
  309. {
  310. name: "private non-option channel",
  311. alicePrivate: true,
  312. aliceAlias: lnwire.ShortChannelID{},
  313. aliceReal: lnwire.ShortChannelID{
  314. BlockHeight: 505000,
  315. TxIndex: 8,
  316. TxPosition: 8,
  317. },
  318. },
  319. {
  320. name: "private option channel w/ alias",
  321. alicePrivate: true,
  322. optionScid: true,
  323. useAlias: true,
  324. aliceAlias: lnwire.ShortChannelID{
  325. BlockHeight: 16_000_015,
  326. TxIndex: 9,
  327. TxPosition: 9,
  328. },
  329. aliceReal: lnwire.ShortChannelID{
  330. BlockHeight: 506000,
  331. TxIndex: 10,
  332. TxPosition: 10,
  333. },
  334. expectErr: false,
  335. },
  336. {
  337. name: "private option channel failure",
  338. alicePrivate: true,
  339. optionScid: true,
  340. useAlias: false,
  341. aliceAlias: lnwire.ShortChannelID{
  342. BlockHeight: 16_000_016,
  343. TxIndex: 16,
  344. TxPosition: 16,
  345. },
  346. aliceReal: lnwire.ShortChannelID{
  347. BlockHeight: 507000,
  348. TxIndex: 17,
  349. TxPosition: 17,
  350. },
  351. expectErr: true,
  352. },
  353. {
  354. name: "public non-option channel",
  355. alicePrivate: false,
  356. useAlias: false,
  357. aliceAlias: lnwire.ShortChannelID{},
  358. aliceReal: lnwire.ShortChannelID{
  359. BlockHeight: 508000,
  360. TxIndex: 17,
  361. TxPosition: 17,
  362. },
  363. expectErr: false,
  364. },
  365. {
  366. name: "public option channel w/ alias",
  367. alicePrivate: false,
  368. optionScid: true,
  369. useAlias: true,
  370. aliceAlias: lnwire.ShortChannelID{
  371. BlockHeight: 16_000_018,
  372. TxIndex: 18,
  373. TxPosition: 18,
  374. },
  375. aliceReal: lnwire.ShortChannelID{
  376. BlockHeight: 509000,
  377. TxIndex: 19,
  378. TxPosition: 19,
  379. },
  380. expectErr: false,
  381. },
  382. {
  383. name: "public option channel w/ real",
  384. alicePrivate: false,
  385. optionScid: true,
  386. useAlias: false,
  387. aliceAlias: lnwire.ShortChannelID{
  388. BlockHeight: 16_000_019,
  389. TxIndex: 19,
  390. TxPosition: 19,
  391. },
  392. aliceReal: lnwire.ShortChannelID{
  393. BlockHeight: 510000,
  394. TxIndex: 20,
  395. TxPosition: 20,
  396. },
  397. expectErr: false,
  398. },
  399. }
  400. for _, test := range tests {
  401. test := test
  402. t.Run(test.name, func(t *testing.T) {
  403. t.Parallel()
  404. testSwitchForwardMapping(
  405. t, test.alicePrivate, test.zeroConf,
  406. test.useAlias, test.optionScid,
  407. test.aliceAlias, test.aliceReal,
  408. test.expectErr,
  409. )
  410. })
  411. }
  412. }
  413. func testSwitchForwardMapping(t *testing.T, alicePrivate, aliceZeroConf,
  414. useAlias, optionScid bool, aliceAlias, aliceReal lnwire.ShortChannelID,
  415. expectErr bool) {
  416. alicePeer, err := newMockServer(
  417. t, "alice", testStartingHeight, nil, testDefaultDelta,
  418. )
  419. require.NoError(t, err)
  420. bobPeer, err := newMockServer(
  421. t, "bob", testStartingHeight, nil, testDefaultDelta,
  422. )
  423. require.NoError(t, err)
  424. s, err := initSwitchWithTempDB(t, testStartingHeight)
  425. require.NoError(t, err)
  426. err = s.Start()
  427. require.NoError(t, err)
  428. defer func() { _ = s.Stop() }()
  429. // Create the lnwire.ChannelIDs that we'll use.
  430. chanID1, chanID2, _, _ := genIDs()
  431. var aliceChannelLink *mockChannelLink
  432. if aliceZeroConf {
  433. aliceChannelLink = newMockChannelLink(
  434. s, chanID1, aliceAlias, aliceReal, alicePeer, true,
  435. alicePrivate, true, false,
  436. )
  437. } else {
  438. aliceChannelLink = newMockChannelLink(
  439. s, chanID1, aliceReal, emptyScid, alicePeer, true,
  440. alicePrivate, false, optionScid,
  441. )
  442. if optionScid {
  443. aliceChannelLink.addAlias(aliceAlias)
  444. }
  445. }
  446. err = s.AddLink(aliceChannelLink)
  447. require.NoError(t, err)
  448. // Bob will just have a non-option_scid_alias channel so no mapping is
  449. // necessary.
  450. bobScid := lnwire.ShortChannelID{
  451. BlockHeight: 501000,
  452. TxIndex: 200,
  453. TxPosition: 2,
  454. }
  455. bobChannelLink := newMockChannelLink(
  456. s, chanID2, bobScid, emptyScid, bobPeer, true, false, false,
  457. false,
  458. )
  459. err = s.AddLink(bobChannelLink)
  460. require.NoError(t, err)
  461. // Generate preimage.
  462. preimage, err := genPreimage()
  463. require.NoError(t, err, "unable to generate preimage")
  464. rhash := sha256.Sum256(preimage[:])
  465. // Determine the outgoing SCID to use.
  466. outgoingSCID := aliceReal
  467. if useAlias {
  468. outgoingSCID = aliceAlias
  469. }
  470. packet := &htlcPacket{
  471. incomingChanID: bobScid,
  472. incomingHTLCID: 0,
  473. outgoingChanID: outgoingSCID,
  474. obfuscator: NewMockObfuscator(),
  475. htlc: &lnwire.UpdateAddHTLC{
  476. PaymentHash: rhash,
  477. Amount: 1,
  478. },
  479. }
  480. err = s.ForwardPackets(nil, packet)
  481. require.NoError(t, err)
  482. // If we expect a forwarding error, then assert that we receive one.
  483. // option_scid_alias forwards may fail if forwarding would be a privacy
  484. // leak.
  485. if expectErr {
  486. select {
  487. case <-bobChannelLink.packets:
  488. case <-time.After(time.Second * 5):
  489. t.Fatal("expected a forwarding error")
  490. }
  491. select {
  492. case <-aliceChannelLink.packets:
  493. t.Fatal("did not expect a packet")
  494. case <-time.After(time.Second * 5):
  495. }
  496. } else {
  497. select {
  498. case <-bobChannelLink.packets:
  499. t.Fatal("did not expect a forwarding error")
  500. case <-time.After(time.Second * 5):
  501. }
  502. select {
  503. case <-aliceChannelLink.packets:
  504. case <-time.After(time.Second * 5):
  505. t.Fatal("expected alice to receive packet")
  506. }
  507. }
  508. }
  509. // TestSwitchSendHTLCMapping tests that SendHTLC will properly route packets to
  510. // zero-conf or option-scid-alias (feature-bit) channels if the confirmed SCID
  511. // is used. It also tests that nothing breaks with the mapping change.
  512. func TestSwitchSendHTLCMapping(t *testing.T) {
  513. tests := []struct {
  514. name string
  515. // If this is true, the channel will be zero-conf.
  516. zeroConf bool
  517. // Denotes whether the channel is option-scid-alias, non
  518. // zero-conf feature bit.
  519. optionFeature bool
  520. // If this is true, then the alias will be used in the packet.
  521. useAlias bool
  522. // This will be the channel alias if there is a mapping.
  523. alias lnwire.ShortChannelID
  524. // This will be the confirmed SCID if the channel is confirmed.
  525. real lnwire.ShortChannelID
  526. }{
  527. {
  528. name: "non-zero-conf real scid w/ option",
  529. zeroConf: false,
  530. optionFeature: true,
  531. useAlias: false,
  532. alias: lnwire.ShortChannelID{
  533. BlockHeight: 10010,
  534. TxIndex: 10,
  535. TxPosition: 10,
  536. },
  537. real: lnwire.ShortChannelID{
  538. BlockHeight: 500000,
  539. TxIndex: 50,
  540. TxPosition: 50,
  541. },
  542. },
  543. {
  544. name: "non-zero-conf real scid no option",
  545. zeroConf: false,
  546. useAlias: false,
  547. alias: lnwire.ShortChannelID{},
  548. real: lnwire.ShortChannelID{
  549. BlockHeight: 400000,
  550. TxIndex: 50,
  551. TxPosition: 50,
  552. },
  553. },
  554. {
  555. name: "zero-conf alias scid w/ conf",
  556. zeroConf: true,
  557. useAlias: true,
  558. alias: lnwire.ShortChannelID{
  559. BlockHeight: 10020,
  560. TxIndex: 20,
  561. TxPosition: 20,
  562. },
  563. real: lnwire.ShortChannelID{
  564. BlockHeight: 450000,
  565. TxIndex: 50,
  566. TxPosition: 50,
  567. },
  568. },
  569. {
  570. name: "zero-conf alias scid no conf",
  571. zeroConf: true,
  572. useAlias: true,
  573. alias: lnwire.ShortChannelID{
  574. BlockHeight: 10015,
  575. TxIndex: 25,
  576. TxPosition: 35,
  577. },
  578. real: lnwire.ShortChannelID{},
  579. },
  580. {
  581. name: "zero-conf real scid",
  582. zeroConf: true,
  583. useAlias: false,
  584. alias: lnwire.ShortChannelID{
  585. BlockHeight: 10035,
  586. TxIndex: 35,
  587. TxPosition: 35,
  588. },
  589. real: lnwire.ShortChannelID{
  590. BlockHeight: 470000,
  591. TxIndex: 35,
  592. TxPosition: 45,
  593. },
  594. },
  595. }
  596. for _, test := range tests {
  597. test := test
  598. t.Run(test.name, func(t *testing.T) {
  599. t.Parallel()
  600. testSwitchSendHtlcMapping(
  601. t, test.zeroConf, test.useAlias, test.alias,
  602. test.real, test.optionFeature,
  603. )
  604. })
  605. }
  606. }
  607. func testSwitchSendHtlcMapping(t *testing.T, zeroConf, useAlias bool, alias,
  608. realScid lnwire.ShortChannelID, optionFeature bool) {
  609. peer, err := newMockServer(
  610. t, "alice", testStartingHeight, nil, testDefaultDelta,
  611. )
  612. require.NoError(t, err)
  613. s, err := initSwitchWithTempDB(t, testStartingHeight)
  614. require.NoError(t, err)
  615. err = s.Start()
  616. require.NoError(t, err)
  617. defer func() { _ = s.Stop() }()
  618. // Create the lnwire.ChannelID that we'll use.
  619. chanID, _ := genID()
  620. var link *mockChannelLink
  621. if zeroConf {
  622. link = newMockChannelLink(
  623. s, chanID, alias, realScid, peer, true, false, true,
  624. false,
  625. )
  626. } else {
  627. link = newMockChannelLink(
  628. s, chanID, realScid, emptyScid, peer, true, false,
  629. false, true,
  630. )
  631. if optionFeature {
  632. link.addAlias(alias)
  633. }
  634. }
  635. err = s.AddLink(link)
  636. require.NoError(t, err)
  637. // Generate preimage.
  638. preimage, err := genPreimage()
  639. require.NoError(t, err)
  640. rhash := sha256.Sum256(preimage[:])
  641. // Determine the outgoing SCID to use.
  642. outgoingSCID := realScid
  643. if useAlias {
  644. outgoingSCID = alias
  645. }
  646. // Send the HTLC and assert that we don't get an error.
  647. htlc := &lnwire.UpdateAddHTLC{
  648. PaymentHash: rhash,
  649. Amount: 1,
  650. }
  651. err = s.SendHTLC(outgoingSCID, 0, htlc)
  652. require.NoError(t, err)
  653. }
  654. // TestSwitchUpdateScid verifies that zero-conf and non-zero-conf
  655. // option-scid-alias (feature bit) channels will have the expected entries in
  656. // the aliasToReal and baseIndex maps.
  657. func TestSwitchUpdateScid(t *testing.T) {
  658. t.Parallel()
  659. peer, err := newMockServer(
  660. t, "alice", testStartingHeight, nil, testDefaultDelta,
  661. )
  662. require.NoError(t, err, "unable to create alice server")
  663. s, err := initSwitchWithTempDB(t, testStartingHeight)
  664. require.NoError(t, err)
  665. err = s.Start()
  666. require.NoError(t, err)
  667. defer func() { _ = s.Stop() }()
  668. // Create the IDs that we'll use.
  669. chanID, chanID2, _, _ := genIDs()
  670. alias := lnwire.ShortChannelID{
  671. BlockHeight: 16_000_000,
  672. TxIndex: 0,
  673. TxPosition: 0,
  674. }
  675. alias2 := alias
  676. alias2.TxPosition = 1
  677. realScid := lnwire.ShortChannelID{
  678. BlockHeight: 500000,
  679. TxIndex: 0,
  680. TxPosition: 0,
  681. }
  682. link := newMockChannelLink(
  683. s, chanID, alias, emptyScid, peer, true, false, true, false,
  684. )
  685. link.addAlias(alias2)
  686. err = s.AddLink(link)
  687. require.NoError(t, err)
  688. // Assert that the zero-conf link does not have entries in the
  689. // aliasToReal map.
  690. s.indexMtx.RLock()
  691. _, ok := s.aliasToReal[alias]
  692. require.False(t, ok)
  693. _, ok = s.aliasToReal[alias2]
  694. require.False(t, ok)
  695. // Assert that both aliases point to the "base" SCID, which is actually
  696. // just the first alias.
  697. baseScid, ok := s.baseIndex[alias]
  698. require.True(t, ok)
  699. require.Equal(t, alias, baseScid)
  700. baseScid, ok = s.baseIndex[alias2]
  701. require.True(t, ok)
  702. require.Equal(t, alias, baseScid)
  703. s.indexMtx.RUnlock()
  704. // We'll set the mock link's confirmed SCID so that UpdateShortChanID
  705. // populates aliasToReal and adds an entry to baseIndex.
  706. link.realScid = realScid
  707. link.confirmedZC = true
  708. err = s.UpdateShortChanID(chanID)
  709. require.NoError(t, err)
  710. // Assert that aliasToReal is populated and there is an entry in
  711. // baseIndex for realScid.
  712. s.indexMtx.RLock()
  713. realMapping, ok := s.aliasToReal[alias]
  714. require.True(t, ok)
  715. require.Equal(t, realScid, realMapping)
  716. realMapping, ok = s.aliasToReal[alias2]
  717. require.True(t, ok)
  718. require.Equal(t, realScid, realMapping)
  719. baseScid, ok = s.baseIndex[realScid]
  720. require.True(t, ok)
  721. require.Equal(t, alias, baseScid)
  722. s.indexMtx.RUnlock()
  723. // Now we'll perform the same checks with a non-zero-conf
  724. // option-scid-alias channel (feature-bit).
  725. optionReal := lnwire.ShortChannelID{
  726. BlockHeight: 600000,
  727. TxIndex: 0,
  728. TxPosition: 0,
  729. }
  730. optionAlias := lnwire.ShortChannelID{
  731. BlockHeight: 12000,
  732. TxIndex: 0,
  733. TxPosition: 0,
  734. }
  735. optionAlias2 := optionAlias
  736. optionAlias2.TxPosition = 1
  737. link2 := newMockChannelLink(
  738. s, chanID2, optionReal, emptyScid, peer, true, false, false,
  739. true,
  740. )
  741. link2.addAlias(optionAlias)
  742. link2.addAlias(optionAlias2)
  743. err = s.AddLink(link2)
  744. require.NoError(t, err)
  745. // Assert that the option-scid-alias link does have entries in the
  746. // aliasToReal and baseIndex maps.
  747. s.indexMtx.RLock()
  748. realMapping, ok = s.aliasToReal[optionAlias]
  749. require.True(t, ok)
  750. require.Equal(t, optionReal, realMapping)
  751. realMapping, ok = s.aliasToReal[optionAlias2]
  752. require.True(t, ok)
  753. require.Equal(t, optionReal, realMapping)
  754. baseScid, ok = s.baseIndex[optionReal]
  755. require.True(t, ok)
  756. require.Equal(t, optionReal, baseScid)
  757. baseScid, ok = s.baseIndex[optionAlias]
  758. require.True(t, ok)
  759. require.Equal(t, optionReal, baseScid)
  760. baseScid, ok = s.baseIndex[optionAlias2]
  761. require.True(t, ok)
  762. require.Equal(t, optionReal, baseScid)
  763. s.indexMtx.RUnlock()
  764. }
  765. // TestSwitchForward checks the ability of htlc switch to forward add/settle
  766. // requests.
  767. func TestSwitchForward(t *testing.T) {
  768. t.Parallel()
  769. alicePeer, err := newMockServer(
  770. t, "alice", testStartingHeight, nil, testDefaultDelta,
  771. )
  772. if err != nil {
  773. t.Fatalf("unable to create alice server: %v", err)
  774. }
  775. bobPeer, err := newMockServer(
  776. t, "bob", testStartingHeight, nil, testDefaultDelta,
  777. )
  778. if err != nil {
  779. t.Fatalf("unable to create bob server: %v", err)
  780. }
  781. s, err := initSwitchWithTempDB(t, testStartingHeight)
  782. if err != nil {
  783. t.Fatalf("unable to init switch: %v", err)
  784. }
  785. if err := s.Start(); err != nil {
  786. t.Fatalf("unable to start switch: %v", err)
  787. }
  788. defer s.Stop()
  789. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  790. aliceChannelLink := newMockChannelLink(
  791. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  792. false, false,
  793. )
  794. bobChannelLink := newMockChannelLink(
  795. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  796. false,
  797. )
  798. if err := s.AddLink(aliceChannelLink); err != nil {
  799. t.Fatalf("unable to add alice link: %v", err)
  800. }
  801. if err := s.AddLink(bobChannelLink); err != nil {
  802. t.Fatalf("unable to add bob link: %v", err)
  803. }
  804. // Create request which should be forwarded from Alice channel link to
  805. // bob channel link.
  806. preimage, err := genPreimage()
  807. if err != nil {
  808. t.Fatalf("unable to generate preimage: %v", err)
  809. }
  810. rhash := sha256.Sum256(preimage[:])
  811. packet := &htlcPacket{
  812. incomingChanID: aliceChannelLink.ShortChanID(),
  813. incomingHTLCID: 0,
  814. outgoingChanID: bobChannelLink.ShortChanID(),
  815. obfuscator: NewMockObfuscator(),
  816. htlc: &lnwire.UpdateAddHTLC{
  817. PaymentHash: rhash,
  818. Amount: 1,
  819. },
  820. }
  821. // Handle the request and checks that bob channel link received it.
  822. if err := s.ForwardPackets(nil, packet); err != nil {
  823. t.Fatal(err)
  824. }
  825. select {
  826. case <-bobChannelLink.packets:
  827. if err := bobChannelLink.completeCircuit(packet); err != nil {
  828. t.Fatalf("unable to complete payment circuit: %v", err)
  829. }
  830. case <-time.After(time.Second):
  831. t.Fatal("request was not propagated to destination")
  832. }
  833. if s.circuits.NumOpen() != 1 {
  834. t.Fatal("wrong amount of circuits")
  835. }
  836. if !s.IsForwardedHTLC(bobChannelLink.ShortChanID(), 0) {
  837. t.Fatal("htlc should be identified as forwarded")
  838. }
  839. // Create settle request pretending that bob link handled the add htlc
  840. // request and sent the htlc settle request back. This request should
  841. // be forwarder back to Alice link.
  842. packet = &htlcPacket{
  843. outgoingChanID: bobChannelLink.ShortChanID(),
  844. outgoingHTLCID: 0,
  845. amount: 1,
  846. htlc: &lnwire.UpdateFulfillHTLC{
  847. PaymentPreimage: preimage,
  848. },
  849. }
  850. // Handle the request and checks that payment circuit works properly.
  851. if err := s.ForwardPackets(nil, packet); err != nil {
  852. t.Fatal(err)
  853. }
  854. select {
  855. case pkt := <-aliceChannelLink.packets:
  856. if err := aliceChannelLink.deleteCircuit(pkt); err != nil {
  857. t.Fatalf("unable to remove circuit: %v", err)
  858. }
  859. case <-time.After(time.Second):
  860. t.Fatal("request was not propagated to channelPoint")
  861. }
  862. if s.circuits.NumOpen() != 0 {
  863. t.Fatal("wrong amount of circuits")
  864. }
  865. }
  866. func TestSwitchForwardFailAfterFullAdd(t *testing.T) {
  867. t.Parallel()
  868. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  869. alicePeer, err := newMockServer(
  870. t, "alice", testStartingHeight, nil, testDefaultDelta,
  871. )
  872. if err != nil {
  873. t.Fatalf("unable to create alice server: %v", err)
  874. }
  875. bobPeer, err := newMockServer(
  876. t, "bob", testStartingHeight, nil, testDefaultDelta,
  877. )
  878. require.NoError(t, err, "unable to create bob server")
  879. tempPath := t.TempDir()
  880. cdb, err := channeldb.Open(tempPath)
  881. require.NoError(t, err, "unable to open channeldb")
  882. t.Cleanup(func() { cdb.Close() })
  883. s, err := initSwitchWithDB(testStartingHeight, cdb)
  884. require.NoError(t, err, "unable to init switch")
  885. if err := s.Start(); err != nil {
  886. t.Fatalf("unable to start switch: %v", err)
  887. }
  888. // Even though we intend to Stop s later in the test, it is safe to
  889. // defer this Stop since its execution it is protected by an atomic
  890. // guard, guaranteeing it executes at most once.
  891. defer s.Stop()
  892. aliceChannelLink := newMockChannelLink(
  893. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  894. false, false,
  895. )
  896. bobChannelLink := newMockChannelLink(
  897. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  898. false,
  899. )
  900. if err := s.AddLink(aliceChannelLink); err != nil {
  901. t.Fatalf("unable to add alice link: %v", err)
  902. }
  903. if err := s.AddLink(bobChannelLink); err != nil {
  904. t.Fatalf("unable to add bob link: %v", err)
  905. }
  906. // Create request which should be forwarded from Alice channel link to
  907. // bob channel link.
  908. preimage := [sha256.Size]byte{1}
  909. rhash := sha256.Sum256(preimage[:])
  910. ogPacket := &htlcPacket{
  911. incomingChanID: aliceChannelLink.ShortChanID(),
  912. incomingHTLCID: 0,
  913. outgoingChanID: bobChannelLink.ShortChanID(),
  914. obfuscator: NewMockObfuscator(),
  915. htlc: &lnwire.UpdateAddHTLC{
  916. PaymentHash: rhash,
  917. Amount: 1,
  918. },
  919. }
  920. if s.circuits.NumPending() != 0 {
  921. t.Fatalf("wrong amount of half circuits")
  922. }
  923. if s.circuits.NumOpen() != 0 {
  924. t.Fatalf("wrong amount of circuits")
  925. }
  926. // Handle the request and checks that bob channel link received it.
  927. if err := s.ForwardPackets(nil, ogPacket); err != nil {
  928. t.Fatal(err)
  929. }
  930. if s.circuits.NumPending() != 1 {
  931. t.Fatalf("wrong amount of half circuits")
  932. }
  933. if s.circuits.NumOpen() != 0 {
  934. t.Fatalf("wrong amount of circuits")
  935. }
  936. // Pull packet from bob's link, but do not perform a full add.
  937. select {
  938. case packet := <-bobChannelLink.packets:
  939. // Complete the payment circuit and assign the outgoing htlc id
  940. // before restarting.
  941. if err := bobChannelLink.completeCircuit(packet); err != nil {
  942. t.Fatalf("unable to complete payment circuit: %v", err)
  943. }
  944. case <-time.After(time.Second):
  945. t.Fatal("request was not propagated to destination")
  946. }
  947. if s.circuits.NumPending() != 1 {
  948. t.Fatalf("wrong amount of half circuits")
  949. }
  950. if s.circuits.NumOpen() != 1 {
  951. t.Fatalf("wrong amount of circuits")
  952. }
  953. // Now we will restart bob, leaving the forwarding decision for this
  954. // htlc is in the half-added state.
  955. if err := s.Stop(); err != nil {
  956. t.Fatalf(err.Error())
  957. }
  958. if err := cdb.Close(); err != nil {
  959. t.Fatalf(err.Error())
  960. }
  961. cdb2, err := channeldb.Open(tempPath)
  962. require.NoError(t, err, "unable to reopen channeldb")
  963. t.Cleanup(func() { cdb2.Close() })
  964. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  965. require.NoError(t, err, "unable reinit switch")
  966. if err := s2.Start(); err != nil {
  967. t.Fatalf("unable to restart switch: %v", err)
  968. }
  969. // Even though we intend to Stop s2 later in the test, it is safe to
  970. // defer this Stop since its execution it is protected by an atomic
  971. // guard, guaranteeing it executes at most once.
  972. defer s2.Stop()
  973. aliceChannelLink = newMockChannelLink(
  974. s2, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  975. false, false,
  976. )
  977. bobChannelLink = newMockChannelLink(
  978. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  979. false,
  980. )
  981. if err := s2.AddLink(aliceChannelLink); err != nil {
  982. t.Fatalf("unable to add alice link: %v", err)
  983. }
  984. if err := s2.AddLink(bobChannelLink); err != nil {
  985. t.Fatalf("unable to add bob link: %v", err)
  986. }
  987. if s2.circuits.NumPending() != 1 {
  988. t.Fatalf("wrong amount of half circuits")
  989. }
  990. if s2.circuits.NumOpen() != 1 {
  991. t.Fatalf("wrong amount of circuits")
  992. }
  993. // Craft a failure message from the remote peer.
  994. fail := &htlcPacket{
  995. outgoingChanID: bobChannelLink.ShortChanID(),
  996. outgoingHTLCID: 0,
  997. amount: 1,
  998. htlc: &lnwire.UpdateFailHTLC{},
  999. }
  1000. // Send the fail packet from the remote peer through the switch.
  1001. if err := s2.ForwardPackets(nil, fail); err != nil {
  1002. t.Fatalf(err.Error())
  1003. }
  1004. // Pull packet from alice's link, as it should have gone through
  1005. // successfully.
  1006. select {
  1007. case pkt := <-aliceChannelLink.packets:
  1008. if err := aliceChannelLink.completeCircuit(pkt); err != nil {
  1009. t.Fatalf("unable to remove circuit: %v", err)
  1010. }
  1011. case <-time.After(time.Second):
  1012. t.Fatal("request was not propagated to destination")
  1013. }
  1014. // Circuit map should be empty now.
  1015. if s2.circuits.NumPending() != 0 {
  1016. t.Fatalf("wrong amount of half circuits")
  1017. }
  1018. if s2.circuits.NumOpen() != 0 {
  1019. t.Fatalf("wrong amount of circuits")
  1020. }
  1021. // Send the fail packet from the remote peer through the switch.
  1022. if err := s.ForwardPackets(nil, fail); err != nil {
  1023. t.Fatal(err)
  1024. }
  1025. select {
  1026. case <-aliceChannelLink.packets:
  1027. t.Fatalf("expected duplicate fail to not arrive at the destination")
  1028. case <-time.After(time.Second):
  1029. }
  1030. }
  1031. func TestSwitchForwardSettleAfterFullAdd(t *testing.T) {
  1032. t.Parallel()
  1033. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  1034. alicePeer, err := newMockServer(
  1035. t, "alice", testStartingHeight, nil, testDefaultDelta,
  1036. )
  1037. require.NoError(t, err, "unable to create alice server")
  1038. bobPeer, err := newMockServer(
  1039. t, "bob", testStartingHeight, nil, testDefaultDelta,
  1040. )
  1041. require.NoError(t, err, "unable to create bob server")
  1042. tempPath := t.TempDir()
  1043. cdb, err := channeldb.Open(tempPath)
  1044. require.NoError(t, err, "unable to open channeldb")
  1045. t.Cleanup(func() { cdb.Close() })
  1046. s, err := initSwitchWithDB(testStartingHeight, cdb)
  1047. require.NoError(t, err, "unable to init switch")
  1048. if err := s.Start(); err != nil {
  1049. t.Fatalf("unable to start switch: %v", err)
  1050. }
  1051. // Even though we intend to Stop s later in the test, it is safe to
  1052. // defer this Stop since its execution it is protected by an atomic
  1053. // guard, guaranteeing it executes at most once.
  1054. defer s.Stop()
  1055. aliceChannelLink := newMockChannelLink(
  1056. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1057. false, false,
  1058. )
  1059. bobChannelLink := newMockChannelLink(
  1060. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1061. false,
  1062. )
  1063. if err := s.AddLink(aliceChannelLink); err != nil {
  1064. t.Fatalf("unable to add alice link: %v", err)
  1065. }
  1066. if err := s.AddLink(bobChannelLink); err != nil {
  1067. t.Fatalf("unable to add bob link: %v", err)
  1068. }
  1069. // Create request which should be forwarded from Alice channel link to
  1070. // bob channel link.
  1071. preimage := [sha256.Size]byte{1}
  1072. rhash := sha256.Sum256(preimage[:])
  1073. ogPacket := &htlcPacket{
  1074. incomingChanID: aliceChannelLink.ShortChanID(),
  1075. incomingHTLCID: 0,
  1076. outgoingChanID: bobChannelLink.ShortChanID(),
  1077. obfuscator: NewMockObfuscator(),
  1078. htlc: &lnwire.UpdateAddHTLC{
  1079. PaymentHash: rhash,
  1080. Amount: 1,
  1081. },
  1082. }
  1083. if s.circuits.NumPending() != 0 {
  1084. t.Fatalf("wrong amount of half circuits")
  1085. }
  1086. if s.circuits.NumOpen() != 0 {
  1087. t.Fatalf("wrong amount of circuits")
  1088. }
  1089. // Handle the request and checks that bob channel link received it.
  1090. if err := s.ForwardPackets(nil, ogPacket); err != nil {
  1091. t.Fatal(err)
  1092. }
  1093. if s.circuits.NumPending() != 1 {
  1094. t.Fatalf("wrong amount of half circuits")
  1095. }
  1096. if s.circuits.NumOpen() != 0 {
  1097. t.Fatalf("wrong amount of circuits")
  1098. }
  1099. // Pull packet from bob's link, but do not perform a full add.
  1100. select {
  1101. case packet := <-bobChannelLink.packets:
  1102. // Complete the payment circuit and assign the outgoing htlc id
  1103. // before restarting.
  1104. if err := bobChannelLink.completeCircuit(packet); err != nil {
  1105. t.Fatalf("unable to complete payment circuit: %v", err)
  1106. }
  1107. case <-time.After(time.Second):
  1108. t.Fatal("request was not propagated to destination")
  1109. }
  1110. if s.circuits.NumPending() != 1 {
  1111. t.Fatalf("wrong amount of half circuits")
  1112. }
  1113. if s.circuits.NumOpen() != 1 {
  1114. t.Fatalf("wrong amount of circuits")
  1115. }
  1116. // Now we will restart bob, leaving the forwarding decision for this
  1117. // htlc is in the half-added state.
  1118. if err := s.Stop(); err != nil {
  1119. t.Fatalf(err.Error())
  1120. }
  1121. if err := cdb.Close(); err != nil {
  1122. t.Fatalf(err.Error())
  1123. }
  1124. cdb2, err := channeldb.Open(tempPath)
  1125. require.NoError(t, err, "unable to reopen channeldb")
  1126. t.Cleanup(func() { cdb2.Close() })
  1127. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  1128. require.NoError(t, err, "unable reinit switch")
  1129. if err := s2.Start(); err != nil {
  1130. t.Fatalf("unable to restart switch: %v", err)
  1131. }
  1132. // Even though we intend to Stop s2 later in the test, it is safe to
  1133. // defer this Stop since its execution it is protected by an atomic
  1134. // guard, guaranteeing it executes at most once.
  1135. defer s2.Stop()
  1136. aliceChannelLink = newMockChannelLink(
  1137. s2, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1138. false, false,
  1139. )
  1140. bobChannelLink = newMockChannelLink(
  1141. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1142. false,
  1143. )
  1144. if err := s2.AddLink(aliceChannelLink); err != nil {
  1145. t.Fatalf("unable to add alice link: %v", err)
  1146. }
  1147. if err := s2.AddLink(bobChannelLink); err != nil {
  1148. t.Fatalf("unable to add bob link: %v", err)
  1149. }
  1150. if s2.circuits.NumPending() != 1 {
  1151. t.Fatalf("wrong amount of half circuits")
  1152. }
  1153. if s2.circuits.NumOpen() != 1 {
  1154. t.Fatalf("wrong amount of circuits")
  1155. }
  1156. // Craft a settle message from the remote peer.
  1157. settle := &htlcPacket{
  1158. outgoingChanID: bobChannelLink.ShortChanID(),
  1159. outgoingHTLCID: 0,
  1160. amount: 1,
  1161. htlc: &lnwire.UpdateFulfillHTLC{
  1162. PaymentPreimage: preimage,
  1163. },
  1164. }
  1165. // Send the settle packet from the remote peer through the switch.
  1166. if err := s2.ForwardPackets(nil, settle); err != nil {
  1167. t.Fatalf(err.Error())
  1168. }
  1169. // Pull packet from alice's link, as it should have gone through
  1170. // successfully.
  1171. select {
  1172. case packet := <-aliceChannelLink.packets:
  1173. if err := aliceChannelLink.completeCircuit(packet); err != nil {
  1174. t.Fatalf("unable to complete circuit with in key=%s: %v",
  1175. packet.inKey(), err)
  1176. }
  1177. case <-time.After(time.Second):
  1178. t.Fatal("request was not propagated to destination")
  1179. }
  1180. // Circuit map should be empty now.
  1181. if s2.circuits.NumPending() != 0 {
  1182. t.Fatalf("wrong amount of half circuits")
  1183. }
  1184. if s2.circuits.NumOpen() != 0 {
  1185. t.Fatalf("wrong amount of circuits")
  1186. }
  1187. // Send the settle packet again, which not arrive at destination.
  1188. if err := s2.ForwardPackets(nil, settle); err != nil {
  1189. t.Fatal(err)
  1190. }
  1191. select {
  1192. case <-bobChannelLink.packets:
  1193. t.Fatalf("expected duplicate fail to not arrive at the destination")
  1194. case <-time.After(time.Second):
  1195. }
  1196. }
  1197. func TestSwitchForwardDropAfterFullAdd(t *testing.T) {
  1198. t.Parallel()
  1199. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  1200. alicePeer, err := newMockServer(
  1201. t, "alice", testStartingHeight, nil, testDefaultDelta,
  1202. )
  1203. require.NoError(t, err, "unable to create alice server")
  1204. bobPeer, err := newMockServer(
  1205. t, "bob", testStartingHeight, nil, testDefaultDelta,
  1206. )
  1207. require.NoError(t, err, "unable to create bob server")
  1208. tempPath := t.TempDir()
  1209. cdb, err := channeldb.Open(tempPath)
  1210. require.NoError(t, err, "unable to open channeldb")
  1211. t.Cleanup(func() { cdb.Close() })
  1212. s, err := initSwitchWithDB(testStartingHeight, cdb)
  1213. require.NoError(t, err, "unable to init switch")
  1214. if err := s.Start(); err != nil {
  1215. t.Fatalf("unable to start switch: %v", err)
  1216. }
  1217. // Even though we intend to Stop s later in the test, it is safe to
  1218. // defer this Stop since its execution it is protected by an atomic
  1219. // guard, guaranteeing it executes at most once.
  1220. defer s.Stop()
  1221. aliceChannelLink := newMockChannelLink(
  1222. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1223. false, false,
  1224. )
  1225. bobChannelLink := newMockChannelLink(
  1226. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1227. false,
  1228. )
  1229. if err := s.AddLink(aliceChannelLink); err != nil {
  1230. t.Fatalf("unable to add alice link: %v", err)
  1231. }
  1232. if err := s.AddLink(bobChannelLink); err != nil {
  1233. t.Fatalf("unable to add bob link: %v", err)
  1234. }
  1235. // Create request which should be forwarded from Alice channel link to
  1236. // bob channel link.
  1237. preimage := [sha256.Size]byte{1}
  1238. rhash := sha256.Sum256(preimage[:])
  1239. ogPacket := &htlcPacket{
  1240. incomingChanID: aliceChannelLink.ShortChanID(),
  1241. incomingHTLCID: 0,
  1242. outgoingChanID: bobChannelLink.ShortChanID(),
  1243. obfuscator: NewMockObfuscator(),
  1244. htlc: &lnwire.UpdateAddHTLC{
  1245. PaymentHash: rhash,
  1246. Amount: 1,
  1247. },
  1248. }
  1249. if s.circuits.NumPending() != 0 {
  1250. t.Fatalf("wrong amount of half circuits")
  1251. }
  1252. if s.circuits.NumOpen() != 0 {
  1253. t.Fatalf("wrong amount of circuits")
  1254. }
  1255. // Handle the request and checks that bob channel link received it.
  1256. if err := s.ForwardPackets(nil, ogPacket); err != nil {
  1257. t.Fatal(err)
  1258. }
  1259. if s.circuits.NumPending() != 1 {
  1260. t.Fatalf("wrong amount of half circuits")
  1261. }
  1262. if s.circuits.NumOpen() != 0 {
  1263. t.Fatalf("wrong amount of half circuits")
  1264. }
  1265. // Pull packet from bob's link, but do not perform a full add.
  1266. select {
  1267. case packet := <-bobChannelLink.packets:
  1268. // Complete the payment circuit and assign the outgoing htlc id
  1269. // before restarting.
  1270. if err := bobChannelLink.completeCircuit(packet); err != nil {
  1271. t.Fatalf("unable to complete payment circuit: %v", err)
  1272. }
  1273. case <-time.After(time.Second):
  1274. t.Fatal("request was not propagated to destination")
  1275. }
  1276. // Now we will restart bob, leaving the forwarding decision for this
  1277. // htlc is in the half-added state.
  1278. if err := s.Stop(); err != nil {
  1279. t.Fatalf(err.Error())
  1280. }
  1281. if err := cdb.Close(); err != nil {
  1282. t.Fatalf(err.Error())
  1283. }
  1284. cdb2, err := channeldb.Open(tempPath)
  1285. require.NoError(t, err, "unable to reopen channeldb")
  1286. t.Cleanup(func() { cdb2.Close() })
  1287. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  1288. require.NoError(t, err, "unable reinit switch")
  1289. if err := s2.Start(); err != nil {
  1290. t.Fatalf("unable to restart switch: %v", err)
  1291. }
  1292. // Even though we intend to Stop s2 later in the test, it is safe to
  1293. // defer this Stop since its execution it is protected by an atomic
  1294. // guard, guaranteeing it executes at most once.
  1295. defer s2.Stop()
  1296. aliceChannelLink = newMockChannelLink(
  1297. s2, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1298. false, false,
  1299. )
  1300. bobChannelLink = newMockChannelLink(
  1301. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1302. false,
  1303. )
  1304. if err := s2.AddLink(aliceChannelLink); err != nil {
  1305. t.Fatalf("unable to add alice link: %v", err)
  1306. }
  1307. if err := s2.AddLink(bobChannelLink); err != nil {
  1308. t.Fatalf("unable to add bob link: %v", err)
  1309. }
  1310. if s2.circuits.NumPending() != 1 {
  1311. t.Fatalf("wrong amount of half circuits")
  1312. }
  1313. if s2.circuits.NumOpen() != 1 {
  1314. t.Fatalf("wrong amount of half circuits")
  1315. }
  1316. // Resend the failed htlc. The packet will be dropped silently since the
  1317. // switch will detect that it has been half added previously.
  1318. if err := s2.ForwardPackets(nil, ogPacket); err != nil {
  1319. t.Fatal(err)
  1320. }
  1321. // After detecting an incomplete forward, the fail packet should have
  1322. // been returned to the sender.
  1323. select {
  1324. case <-aliceChannelLink.packets:
  1325. t.Fatal("request should not have returned to source")
  1326. case <-bobChannelLink.packets:
  1327. t.Fatal("request should not have forwarded to destination")
  1328. case <-time.After(time.Second):
  1329. }
  1330. }
  1331. func TestSwitchForwardFailAfterHalfAdd(t *testing.T) {
  1332. t.Parallel()
  1333. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  1334. alicePeer, err := newMockServer(
  1335. t, "alice", testStartingHeight, nil, testDefaultDelta,
  1336. )
  1337. require.NoError(t, err, "unable to create alice server")
  1338. bobPeer, err := newMockServer(
  1339. t, "bob", testStartingHeight, nil, testDefaultDelta,
  1340. )
  1341. require.NoError(t, err, "unable to create bob server")
  1342. tempPath := t.TempDir()
  1343. cdb, err := channeldb.Open(tempPath)
  1344. require.NoError(t, err, "unable to open channeldb")
  1345. t.Cleanup(func() { cdb.Close() })
  1346. s, err := initSwitchWithDB(testStartingHeight, cdb)
  1347. require.NoError(t, err, "unable to init switch")
  1348. if err := s.Start(); err != nil {
  1349. t.Fatalf("unable to start switch: %v", err)
  1350. }
  1351. // Even though we intend to Stop s later in the test, it is safe to
  1352. // defer this Stop since its execution it is protected by an atomic
  1353. // guard, guaranteeing it executes at most once.
  1354. defer s.Stop()
  1355. aliceChannelLink := newMockChannelLink(
  1356. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1357. false, false,
  1358. )
  1359. bobChannelLink := newMockChannelLink(
  1360. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1361. false,
  1362. )
  1363. if err := s.AddLink(aliceChannelLink); err != nil {
  1364. t.Fatalf("unable to add alice link: %v", err)
  1365. }
  1366. if err := s.AddLink(bobChannelLink); err != nil {
  1367. t.Fatalf("unable to add bob link: %v", err)
  1368. }
  1369. // Create request which should be forwarded from Alice channel link to
  1370. // bob channel link.
  1371. preimage := [sha256.Size]byte{1}
  1372. rhash := sha256.Sum256(preimage[:])
  1373. ogPacket := &htlcPacket{
  1374. incomingChanID: aliceChannelLink.ShortChanID(),
  1375. incomingHTLCID: 0,
  1376. outgoingChanID: bobChannelLink.ShortChanID(),
  1377. obfuscator: NewMockObfuscator(),
  1378. htlc: &lnwire.UpdateAddHTLC{
  1379. PaymentHash: rhash,
  1380. Amount: 1,
  1381. },
  1382. }
  1383. if s.circuits.NumPending() != 0 {
  1384. t.Fatalf("wrong amount of half circuits")
  1385. }
  1386. if s.circuits.NumOpen() != 0 {
  1387. t.Fatalf("wrong amount of circuits")
  1388. }
  1389. // Handle the request and checks that bob channel link received it.
  1390. if err := s.ForwardPackets(nil, ogPacket); err != nil {
  1391. t.Fatal(err)
  1392. }
  1393. if s.circuits.NumPending() != 1 {
  1394. t.Fatalf("wrong amount of half circuits")
  1395. }
  1396. if s.circuits.NumOpen() != 0 {
  1397. t.Fatalf("wrong amount of half circuits")
  1398. }
  1399. // Pull packet from bob's link, but do not perform a full add.
  1400. select {
  1401. case <-bobChannelLink.packets:
  1402. case <-time.After(time.Second):
  1403. t.Fatal("request was not propagated to destination")
  1404. }
  1405. // Now we will restart bob, leaving the forwarding decision for this
  1406. // htlc is in the half-added state.
  1407. if err := s.Stop(); err != nil {
  1408. t.Fatalf(err.Error())
  1409. }
  1410. if err := cdb.Close(); err != nil {
  1411. t.Fatalf(err.Error())
  1412. }
  1413. cdb2, err := channeldb.Open(tempPath)
  1414. require.NoError(t, err, "unable to reopen channeldb")
  1415. t.Cleanup(func() { cdb2.Close() })
  1416. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  1417. require.NoError(t, err, "unable reinit switch")
  1418. if err := s2.Start(); err != nil {
  1419. t.Fatalf("unable to restart switch: %v", err)
  1420. }
  1421. // Even though we intend to Stop s2 later in the test, it is safe to
  1422. // defer this Stop since its execution it is protected by an atomic
  1423. // guard, guaranteeing it executes at most once.
  1424. defer s2.Stop()
  1425. aliceChannelLink = newMockChannelLink(
  1426. s2, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1427. false, false,
  1428. )
  1429. bobChannelLink = newMockChannelLink(
  1430. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1431. false,
  1432. )
  1433. if err := s2.AddLink(aliceChannelLink); err != nil {
  1434. t.Fatalf("unable to add alice link: %v", err)
  1435. }
  1436. if err := s2.AddLink(bobChannelLink); err != nil {
  1437. t.Fatalf("unable to add bob link: %v", err)
  1438. }
  1439. if s2.circuits.NumPending() != 1 {
  1440. t.Fatalf("wrong amount of half circuits")
  1441. }
  1442. if s2.circuits.NumOpen() != 0 {
  1443. t.Fatalf("wrong amount of half circuits")
  1444. }
  1445. // Resend the failed htlc, it should be returned to alice since the
  1446. // switch will detect that it has been half added previously.
  1447. err = s2.ForwardPackets(nil, ogPacket)
  1448. if err != nil {
  1449. t.Fatal(err)
  1450. }
  1451. // After detecting an incomplete forward, the fail packet should have
  1452. // been returned to the sender.
  1453. select {
  1454. case pkt := <-aliceChannelLink.packets:
  1455. linkErr := pkt.linkFailure
  1456. if linkErr.FailureDetail != OutgoingFailureIncompleteForward {
  1457. t.Fatalf("expected incomplete forward, got: %v",
  1458. linkErr.FailureDetail)
  1459. }
  1460. case <-time.After(time.Second):
  1461. t.Fatal("request was not propagated to destination")
  1462. }
  1463. }
  1464. // TestSwitchForwardCircuitPersistence checks the ability of htlc switch to
  1465. // maintain the proper entries in the circuit map in the face of restarts.
  1466. func TestSwitchForwardCircuitPersistence(t *testing.T) {
  1467. t.Parallel()
  1468. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  1469. alicePeer, err := newMockServer(
  1470. t, "alice", testStartingHeight, nil, testDefaultDelta,
  1471. )
  1472. require.NoError(t, err, "unable to create alice server")
  1473. bobPeer, err := newMockServer(
  1474. t, "bob", testStartingHeight, nil, testDefaultDelta,
  1475. )
  1476. require.NoError(t, err, "unable to create bob server")
  1477. tempPath := t.TempDir()
  1478. cdb, err := channeldb.Open(tempPath)
  1479. require.NoError(t, err, "unable to open channeldb")
  1480. t.Cleanup(func() { cdb.Close() })
  1481. s, err := initSwitchWithDB(testStartingHeight, cdb)
  1482. require.NoError(t, err, "unable to init switch")
  1483. if err := s.Start(); err != nil {
  1484. t.Fatalf("unable to start switch: %v", err)
  1485. }
  1486. // Even though we intend to Stop s later in the test, it is safe to
  1487. // defer this Stop since its execution it is protected by an atomic
  1488. // guard, guaranteeing it executes at most once.
  1489. defer s.Stop()
  1490. aliceChannelLink := newMockChannelLink(
  1491. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1492. false, false,
  1493. )
  1494. bobChannelLink := newMockChannelLink(
  1495. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1496. false,
  1497. )
  1498. if err := s.AddLink(aliceChannelLink); err != nil {
  1499. t.Fatalf("unable to add alice link: %v", err)
  1500. }
  1501. if err := s.AddLink(bobChannelLink); err != nil {
  1502. t.Fatalf("unable to add bob link: %v", err)
  1503. }
  1504. // Create request which should be forwarded from Alice channel link to
  1505. // bob channel link.
  1506. preimage := [sha256.Size]byte{1}
  1507. rhash := sha256.Sum256(preimage[:])
  1508. ogPacket := &htlcPacket{
  1509. incomingChanID: aliceChannelLink.ShortChanID(),
  1510. incomingHTLCID: 0,
  1511. outgoingChanID: bobChannelLink.ShortChanID(),
  1512. obfuscator: NewMockObfuscator(),
  1513. htlc: &lnwire.UpdateAddHTLC{
  1514. PaymentHash: rhash,
  1515. Amount: 1,
  1516. },
  1517. }
  1518. if s.circuits.NumPending() != 0 {
  1519. t.Fatalf("wrong amount of half circuits")
  1520. }
  1521. if s.circuits.NumOpen() != 0 {
  1522. t.Fatalf("wrong amount of circuits")
  1523. }
  1524. // Handle the request and checks that bob channel link received it.
  1525. if err := s.ForwardPackets(nil, ogPacket); err != nil {
  1526. t.Fatal(err)
  1527. }
  1528. if s.circuits.NumPending() != 1 {
  1529. t.Fatalf("wrong amount of half circuits")
  1530. }
  1531. if s.circuits.NumOpen() != 0 {
  1532. t.Fatalf("wrong amount of circuits")
  1533. }
  1534. // Retrieve packet from outgoing link and cache until after restart.
  1535. var packet *htlcPacket
  1536. select {
  1537. case packet = <-bobChannelLink.packets:
  1538. case <-time.After(time.Second):
  1539. t.Fatal("request was not propagated to destination")
  1540. }
  1541. if err := s.Stop(); err != nil {
  1542. t.Fatalf(err.Error())
  1543. }
  1544. if err := cdb.Close(); err != nil {
  1545. t.Fatalf(err.Error())
  1546. }
  1547. cdb2, err := channeldb.Open(tempPath)
  1548. require.NoError(t, err, "unable to reopen channeldb")
  1549. t.Cleanup(func() { cdb2.Close() })
  1550. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  1551. require.NoError(t, err, "unable reinit switch")
  1552. if err := s2.Start(); err != nil {
  1553. t.Fatalf("unable to restart switch: %v", err)
  1554. }
  1555. // Even though we intend to Stop s2 later in the test, it is safe to
  1556. // defer this Stop since its execution it is protected by an atomic
  1557. // guard, guaranteeing it executes at most once.
  1558. defer s2.Stop()
  1559. aliceChannelLink = newMockChannelLink(
  1560. s2, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1561. false, false,
  1562. )
  1563. bobChannelLink = newMockChannelLink(
  1564. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1565. false,
  1566. )
  1567. if err := s2.AddLink(aliceChannelLink); err != nil {
  1568. t.Fatalf("unable to add alice link: %v", err)
  1569. }
  1570. if err := s2.AddLink(bobChannelLink); err != nil {
  1571. t.Fatalf("unable to add bob link: %v", err)
  1572. }
  1573. if s2.circuits.NumPending() != 1 {
  1574. t.Fatalf("wrong amount of half circuits")
  1575. }
  1576. if s2.circuits.NumOpen() != 0 {
  1577. t.Fatalf("wrong amount of half circuits")
  1578. }
  1579. // Now that the switch has restarted, complete the payment circuit.
  1580. if err := bobChannelLink.completeCircuit(packet); err != nil {
  1581. t.Fatalf("unable to complete payment circuit: %v", err)
  1582. }
  1583. if s2.circuits.NumPending() != 1 {
  1584. t.Fatalf("wrong amount of half circuits")
  1585. }
  1586. if s2.circuits.NumOpen() != 1 {
  1587. t.Fatal("wrong amount of circuits")
  1588. }
  1589. // Create settle request pretending that bob link handled the add htlc
  1590. // request and sent the htlc settle request back. This request should
  1591. // be forwarder back to Alice link.
  1592. ogPacket = &htlcPacket{
  1593. outgoingChanID: bobChannelLink.ShortChanID(),
  1594. outgoingHTLCID: 0,
  1595. amount: 1,
  1596. htlc: &lnwire.UpdateFulfillHTLC{
  1597. PaymentPreimage: preimage,
  1598. },
  1599. }
  1600. // Handle the request and checks that payment circuit works properly.
  1601. if err := s2.ForwardPackets(nil, ogPacket); err != nil {
  1602. t.Fatal(err)
  1603. }
  1604. select {
  1605. case packet = <-aliceChannelLink.packets:
  1606. if err := aliceChannelLink.completeCircuit(packet); err != nil {
  1607. t.Fatalf("unable to complete circuit with in key=%s: %v",
  1608. packet.inKey(), err)
  1609. }
  1610. case <-time.After(time.Second):
  1611. t.Fatal("request was not propagated to channelPoint")
  1612. }
  1613. if s2.circuits.NumPending() != 0 {
  1614. t.Fatalf("wrong amount of half circuits, want 1, got %d",
  1615. s2.circuits.NumPending())
  1616. }
  1617. if s2.circuits.NumOpen() != 0 {
  1618. t.Fatal("wrong amount of circuits")
  1619. }
  1620. if err := s2.Stop(); err != nil {
  1621. t.Fatal(err)
  1622. }
  1623. if err := cdb2.Close(); err != nil {
  1624. t.Fatalf(err.Error())
  1625. }
  1626. cdb3, err := channeldb.Open(tempPath)
  1627. require.NoError(t, err, "unable to reopen channeldb")
  1628. t.Cleanup(func() { cdb3.Close() })
  1629. s3, err := initSwitchWithDB(testStartingHeight, cdb3)
  1630. require.NoError(t, err, "unable reinit switch")
  1631. if err := s3.Start(); err != nil {
  1632. t.Fatalf("unable to restart switch: %v", err)
  1633. }
  1634. defer s3.Stop()
  1635. aliceChannelLink = newMockChannelLink(
  1636. s3, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1637. false, false,
  1638. )
  1639. bobChannelLink = newMockChannelLink(
  1640. s3, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  1641. false,
  1642. )
  1643. if err := s3.AddLink(aliceChannelLink); err != nil {
  1644. t.Fatalf("unable to add alice link: %v", err)
  1645. }
  1646. if err := s3.AddLink(bobChannelLink); err != nil {
  1647. t.Fatalf("unable to add bob link: %v", err)
  1648. }
  1649. if s3.circuits.NumPending() != 0 {
  1650. t.Fatalf("wrong amount of half circuits")
  1651. }
  1652. if s3.circuits.NumOpen() != 0 {
  1653. t.Fatalf("wrong amount of circuits")
  1654. }
  1655. }
  1656. type multiHopFwdTest struct {
  1657. name string
  1658. eligible1, eligible2 bool
  1659. failure1, failure2 *LinkError
  1660. expectedReply lnwire.FailCode
  1661. }
  1662. // TestCircularForwards tests the allowing/disallowing of circular payments
  1663. // through the same channel in the case where the switch is configured to allow
  1664. // and disallow same channel circular forwards.
  1665. func TestCircularForwards(t *testing.T) {
  1666. chanID1, aliceChanID := genID()
  1667. preimage := [sha256.Size]byte{1}
  1668. hash := sha256.Sum256(preimage[:])
  1669. tests := []struct {
  1670. name string
  1671. allowCircularPayment bool
  1672. expectedErr error
  1673. }{
  1674. {
  1675. name: "circular payment allowed",
  1676. allowCircularPayment: true,
  1677. expectedErr: nil,
  1678. },
  1679. {
  1680. name: "circular payment disallowed",
  1681. allowCircularPayment: false,
  1682. expectedErr: NewDetailedLinkError(
  1683. lnwire.NewTemporaryChannelFailure(nil),
  1684. OutgoingFailureCircularRoute,
  1685. ),
  1686. },
  1687. }
  1688. for _, test := range tests {
  1689. test := test
  1690. t.Run(test.name, func(t *testing.T) {
  1691. t.Parallel()
  1692. alicePeer, err := newMockServer(
  1693. t, "alice", testStartingHeight, nil,
  1694. testDefaultDelta,
  1695. )
  1696. if err != nil {
  1697. t.Fatalf("unable to create alice server: %v",
  1698. err)
  1699. }
  1700. s, err := initSwitchWithTempDB(t, testStartingHeight)
  1701. if err != nil {
  1702. t.Fatalf("unable to init switch: %v", err)
  1703. }
  1704. if err := s.Start(); err != nil {
  1705. t.Fatalf("unable to start switch: %v", err)
  1706. }
  1707. defer func() { _ = s.Stop() }()
  1708. // Set the switch to allow or disallow circular routes
  1709. // according to the test's requirements.
  1710. s.cfg.AllowCircularRoute = test.allowCircularPayment
  1711. aliceChannelLink := newMockChannelLink(
  1712. s, chanID1, aliceChanID, emptyScid, alicePeer,
  1713. true, false, false, false,
  1714. )
  1715. if err := s.AddLink(aliceChannelLink); err != nil {
  1716. t.Fatalf("unable to add alice link: %v", err)
  1717. }
  1718. // Create a new packet that loops through alice's link
  1719. // in a circle.
  1720. obfuscator := NewMockObfuscator()
  1721. packet := &htlcPacket{
  1722. incomingChanID: aliceChannelLink.ShortChanID(),
  1723. outgoingChanID: aliceChannelLink.ShortChanID(),
  1724. htlc: &lnwire.UpdateAddHTLC{
  1725. PaymentHash: hash,
  1726. Amount: 1,
  1727. },
  1728. obfuscator: obfuscator,
  1729. }
  1730. // Attempt to forward the packet and check for the expected
  1731. // error.
  1732. if err = s.ForwardPackets(nil, packet); err != nil {
  1733. t.Fatal(err)
  1734. }
  1735. select {
  1736. case p := <-aliceChannelLink.packets:
  1737. if p.linkFailure != nil {
  1738. err = p.linkFailure
  1739. }
  1740. case <-time.After(time.Second):
  1741. t.Fatal("no timely reply from switch")
  1742. }
  1743. if !reflect.DeepEqual(err, test.expectedErr) {
  1744. t.Fatalf("expected: %v, got: %v",
  1745. test.expectedErr, err)
  1746. }
  1747. // Ensure that no circuits were opened.
  1748. if s.circuits.NumOpen() > 0 {
  1749. t.Fatal("do not expect any open circuits")
  1750. }
  1751. })
  1752. }
  1753. }
  1754. // TestCheckCircularForward tests the error returned by checkCircularForward
  1755. // in cases where we allow and disallow same channel circular forwards.
  1756. func TestCheckCircularForward(t *testing.T) {
  1757. tests := []struct {
  1758. name string
  1759. // aliasMapping determines whether the test should add an alias
  1760. // mapping to Switch alias maps before checkCircularForward.
  1761. aliasMapping bool
  1762. // allowCircular determines whether we should allow circular
  1763. // forwards.
  1764. allowCircular bool
  1765. // incomingLink is the link that the htlc arrived on.
  1766. incomingLink lnwire.ShortChannelID
  1767. // outgoingLink is the link that the htlc forward
  1768. // is destined to leave on.
  1769. outgoingLink lnwire.ShortChannelID
  1770. // expectedErr is the error we expect to be returned.
  1771. expectedErr *LinkError
  1772. }{
  1773. {
  1774. name: "not circular, allowed in config",
  1775. aliasMapping: false,
  1776. allowCircular: true,
  1777. incomingLink: lnwire.NewShortChanIDFromInt(123),
  1778. outgoingLink: lnwire.NewShortChanIDFromInt(321),
  1779. expectedErr: nil,
  1780. },
  1781. {
  1782. name: "not circular, not allowed in config",
  1783. aliasMapping: false,
  1784. allowCircular: false,
  1785. incomingLink: lnwire.NewShortChanIDFromInt(123),
  1786. outgoingLink: lnwire.NewShortChanIDFromInt(321),
  1787. expectedErr: nil,
  1788. },
  1789. {
  1790. name: "circular, allowed in config",
  1791. aliasMapping: false,
  1792. allowCircular: true,
  1793. incomingLink: lnwire.NewShortChanIDFromInt(123),
  1794. outgoingLink: lnwire.NewShortChanIDFromInt(123),
  1795. expectedErr: nil,
  1796. },
  1797. {
  1798. name: "circular, not allowed in config",
  1799. aliasMapping: false,
  1800. allowCircular: false,
  1801. incomingLink: lnwire.NewShortChanIDFromInt(123),
  1802. outgoingLink: lnwire.NewShortChanIDFromInt(123),
  1803. expectedErr: NewDetailedLinkError(
  1804. lnwire.NewTemporaryChannelFailure(nil),
  1805. OutgoingFailureCircularRoute,
  1806. ),
  1807. },
  1808. {
  1809. name: "circular with map, not allowed",
  1810. aliasMapping: true,
  1811. allowCircular: false,
  1812. incomingLink: lnwire.NewShortChanIDFromInt(1 << 60),
  1813. outgoingLink: lnwire.NewShortChanIDFromInt(1 << 55),
  1814. expectedErr: NewDetailedLinkError(
  1815. lnwire.NewTemporaryChannelFailure(nil),
  1816. OutgoingFailureCircularRoute,
  1817. ),
  1818. },
  1819. {
  1820. name: "circular with map, not allowed 2",
  1821. aliasMapping: true,
  1822. allowCircular: false,
  1823. incomingLink: lnwire.NewShortChanIDFromInt(1 << 55),
  1824. outgoingLink: lnwire.NewShortChanIDFromInt(1 << 60),
  1825. expectedErr: NewDetailedLinkError(
  1826. lnwire.NewTemporaryChannelFailure(nil),
  1827. OutgoingFailureCircularRoute,
  1828. ),
  1829. },
  1830. {
  1831. name: "circular with map, allowed",
  1832. aliasMapping: true,
  1833. allowCircular: true,
  1834. incomingLink: lnwire.NewShortChanIDFromInt(1 << 60),
  1835. outgoingLink: lnwire.NewShortChanIDFromInt(1 << 55),
  1836. expectedErr: nil,
  1837. },
  1838. {
  1839. name: "circular with map, allowed 2",
  1840. aliasMapping: true,
  1841. allowCircular: true,
  1842. incomingLink: lnwire.NewShortChanIDFromInt(1 << 55),
  1843. outgoingLink: lnwire.NewShortChanIDFromInt(1 << 61),
  1844. expectedErr: nil,
  1845. },
  1846. {
  1847. name: "not circular, both confirmed SCID",
  1848. aliasMapping: false,
  1849. allowCircular: false,
  1850. incomingLink: lnwire.NewShortChanIDFromInt(1 << 60),
  1851. outgoingLink: lnwire.NewShortChanIDFromInt(1 << 61),
  1852. expectedErr: nil,
  1853. },
  1854. }
  1855. for _, test := range tests {
  1856. test := test
  1857. t.Run(test.name, func(t *testing.T) {
  1858. t.Parallel()
  1859. s, err := initSwitchWithTempDB(t, testStartingHeight)
  1860. require.NoError(t, err)
  1861. err = s.Start()
  1862. require.NoError(t, err)
  1863. defer func() { _ = s.Stop() }()
  1864. if test.aliasMapping {
  1865. // Make the incoming and outgoing point to the
  1866. // same base SCID.
  1867. inScid := test.incomingLink
  1868. outScid := test.outgoingLink
  1869. s.indexMtx.Lock()
  1870. s.baseIndex[inScid] = outScid
  1871. s.baseIndex[outScid] = outScid
  1872. s.indexMtx.Unlock()
  1873. }
  1874. // Check for a circular forward, the hash passed can
  1875. // be nil because it is only used for logging.
  1876. err = s.checkCircularForward(
  1877. test.incomingLink, test.outgoingLink,
  1878. test.allowCircular, lntypes.Hash{},
  1879. )
  1880. if !reflect.DeepEqual(err, test.expectedErr) {
  1881. t.Fatalf("expected: %v, got: %v",
  1882. test.expectedErr, err)
  1883. }
  1884. })
  1885. }
  1886. }
  1887. // TestSkipIneligibleLinksMultiHopForward tests that if a multi-hop HTLC comes
  1888. // along, then we won't attempt to forward it down al ink that isn't yet able
  1889. // to forward any HTLC's.
  1890. func TestSkipIneligibleLinksMultiHopForward(t *testing.T) {
  1891. tests := []multiHopFwdTest{
  1892. // None of the channels is eligible.
  1893. {
  1894. name: "not eligible",
  1895. expectedReply: lnwire.CodeUnknownNextPeer,
  1896. },
  1897. // Channel one has a policy failure and the other channel isn't
  1898. // available.
  1899. {
  1900. name: "policy fail",
  1901. eligible1: true,
  1902. failure1: NewLinkError(
  1903. lnwire.NewFinalIncorrectCltvExpiry(0),
  1904. ),
  1905. expectedReply: lnwire.CodeFinalIncorrectCltvExpiry,
  1906. },
  1907. // The requested channel is not eligible, but the packet is
  1908. // forwarded through the other channel.
  1909. {
  1910. name: "non-strict success",
  1911. eligible2: true,
  1912. expectedReply: lnwire.CodeNone,
  1913. },
  1914. // The requested channel has insufficient bandwidth and the
  1915. // other channel's policy isn't satisfied.
  1916. {
  1917. name: "non-strict policy fail",
  1918. eligible1: true,
  1919. failure1: NewDetailedLinkError(
  1920. lnwire.NewTemporaryChannelFailure(nil),
  1921. OutgoingFailureInsufficientBalance,
  1922. ),
  1923. eligible2: true,
  1924. failure2: NewLinkError(
  1925. lnwire.NewFinalIncorrectCltvExpiry(0),
  1926. ),
  1927. expectedReply: lnwire.CodeTemporaryChannelFailure,
  1928. },
  1929. }
  1930. for _, test := range tests {
  1931. test := test
  1932. t.Run(test.name, func(t *testing.T) {
  1933. testSkipIneligibleLinksMultiHopForward(t, &test)
  1934. })
  1935. }
  1936. }
  1937. // testSkipIneligibleLinksMultiHopForward tests that if a multi-hop HTLC comes
  1938. // along, then we won't attempt to forward it down al ink that isn't yet able
  1939. // to forward any HTLC's.
  1940. func testSkipIneligibleLinksMultiHopForward(t *testing.T,
  1941. testCase *multiHopFwdTest) {
  1942. t.Parallel()
  1943. var packet *htlcPacket
  1944. alicePeer, err := newMockServer(
  1945. t, "alice", testStartingHeight, nil, testDefaultDelta,
  1946. )
  1947. require.NoError(t, err, "unable to create alice server")
  1948. bobPeer, err := newMockServer(
  1949. t, "bob", testStartingHeight, nil, testDefaultDelta,
  1950. )
  1951. require.NoError(t, err, "unable to create bob server")
  1952. s, err := initSwitchWithTempDB(t, testStartingHeight)
  1953. require.NoError(t, err, "unable to init switch")
  1954. if err := s.Start(); err != nil {
  1955. t.Fatalf("unable to start switch: %v", err)
  1956. }
  1957. defer s.Stop()
  1958. chanID1, aliceChanID := genID()
  1959. aliceChannelLink := newMockChannelLink(
  1960. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  1961. false, false,
  1962. )
  1963. // We'll create a link for Bob, but mark the link as unable to forward
  1964. // any new outgoing HTLC's.
  1965. chanID2, bobChanID2 := genID()
  1966. bobChannelLink1 := newMockChannelLink(
  1967. s, chanID2, bobChanID2, emptyScid, bobPeer, testCase.eligible1,
  1968. false, false, false,
  1969. )
  1970. bobChannelLink1.checkHtlcForwardResult = testCase.failure1
  1971. chanID3, bobChanID3 := genID()
  1972. bobChannelLink2 := newMockChannelLink(
  1973. s, chanID3, bobChanID3, emptyScid, bobPeer, testCase.eligible2,
  1974. false, false, false,
  1975. )
  1976. bobChannelLink2.checkHtlcForwardResult = testCase.failure2
  1977. if err := s.AddLink(aliceChannelLink); err != nil {
  1978. t.Fatalf("unable to add alice link: %v", err)
  1979. }
  1980. if err := s.AddLink(bobChannelLink1); err != nil {
  1981. t.Fatalf("unable to add bob link: %v", err)
  1982. }
  1983. if err := s.AddLink(bobChannelLink2); err != nil {
  1984. t.Fatalf("unable to add bob link: %v", err)
  1985. }
  1986. // Create a new packet that's destined for Bob as an incoming HTLC from
  1987. // Alice.
  1988. preimage := [sha256.Size]byte{1}
  1989. rhash := sha256.Sum256(preimage[:])
  1990. obfuscator := NewMockObfuscator()
  1991. packet = &htlcPacket{
  1992. incomingChanID: aliceChannelLink.ShortChanID(),
  1993. incomingHTLCID: 0,
  1994. outgoingChanID: bobChannelLink1.ShortChanID(),
  1995. htlc: &lnwire.UpdateAddHTLC{
  1996. PaymentHash: rhash,
  1997. Amount: 1,
  1998. },
  1999. obfuscator: obfuscator,
  2000. }
  2001. // The request to forward should fail as
  2002. if err := s.ForwardPackets(nil, packet); err != nil {
  2003. t.Fatal(err)
  2004. }
  2005. // We select from all links and extract the error if exists.
  2006. // The packet must be selected but we don't always expect a link error.
  2007. var linkError *LinkError
  2008. select {
  2009. case p := <-aliceChannelLink.packets:
  2010. linkError = p.linkFailure
  2011. case p := <-bobChannelLink1.packets:
  2012. linkError = p.linkFailure
  2013. case p := <-bobChannelLink2.packets:
  2014. linkError = p.linkFailure
  2015. case <-time.After(time.Second):
  2016. t.Fatal("no timely reply from switch")
  2017. }
  2018. failure := obfuscator.(*mockObfuscator).failure
  2019. if testCase.expectedReply == lnwire.CodeNone {
  2020. if linkError != nil {
  2021. t.Fatalf("forwarding should have succeeded")
  2022. }
  2023. if failure != nil {
  2024. t.Fatalf("unexpected failure %T", failure)
  2025. }
  2026. } else {
  2027. if linkError == nil {
  2028. t.Fatalf("forwarding should have failed due to " +
  2029. "inactive link")
  2030. }
  2031. if failure.Code() != testCase.expectedReply {
  2032. t.Fatalf("unexpected failure %T", failure)
  2033. }
  2034. }
  2035. if s.circuits.NumOpen() != 0 {
  2036. t.Fatal("wrong amount of circuits")
  2037. }
  2038. }
  2039. // TestSkipIneligibleLinksLocalForward ensures that the switch will not attempt
  2040. // to forward any HTLC's down a link that isn't yet eligible for forwarding.
  2041. func TestSkipIneligibleLinksLocalForward(t *testing.T) {
  2042. t.Parallel()
  2043. testSkipLinkLocalForward(t, false, nil)
  2044. }
  2045. // TestSkipPolicyUnsatisfiedLinkLocalForward ensures that the switch will not
  2046. // attempt to send locally initiated HTLCs that would violate the channel policy
  2047. // down a link.
  2048. func TestSkipPolicyUnsatisfiedLinkLocalForward(t *testing.T) {
  2049. t.Parallel()
  2050. testSkipLinkLocalForward(t, true, lnwire.NewTemporaryChannelFailure(nil))
  2051. }
  2052. func testSkipLinkLocalForward(t *testing.T, eligible bool,
  2053. policyResult lnwire.FailureMessage) {
  2054. // We'll create a single link for this test, marking it as being unable
  2055. // to forward form the get go.
  2056. alicePeer, err := newMockServer(
  2057. t, "alice", testStartingHeight, nil, testDefaultDelta,
  2058. )
  2059. require.NoError(t, err, "unable to create alice server")
  2060. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2061. require.NoError(t, err, "unable to init switch")
  2062. if err := s.Start(); err != nil {
  2063. t.Fatalf("unable to start switch: %v", err)
  2064. }
  2065. defer s.Stop()
  2066. chanID1, _, aliceChanID, _ := genIDs()
  2067. aliceChannelLink := newMockChannelLink(
  2068. s, chanID1, aliceChanID, emptyScid, alicePeer, eligible, false,
  2069. false, false,
  2070. )
  2071. aliceChannelLink.checkHtlcTransitResult = NewLinkError(
  2072. policyResult,
  2073. )
  2074. if err := s.AddLink(aliceChannelLink); err != nil {
  2075. t.Fatalf("unable to add alice link: %v", err)
  2076. }
  2077. preimage, err := genPreimage()
  2078. require.NoError(t, err, "unable to generate preimage")
  2079. rhash := sha256.Sum256(preimage[:])
  2080. addMsg := &lnwire.UpdateAddHTLC{
  2081. PaymentHash: rhash,
  2082. Amount: 1,
  2083. }
  2084. // We'll attempt to send out a new HTLC that has Alice as the first
  2085. // outgoing link. This should fail as Alice isn't yet able to forward
  2086. // any active HTLC's.
  2087. err = s.SendHTLC(aliceChannelLink.ShortChanID(), 0, addMsg)
  2088. if err == nil {
  2089. t.Fatalf("local forward should fail due to inactive link")
  2090. }
  2091. if s.circuits.NumOpen() != 0 {
  2092. t.Fatal("wrong amount of circuits")
  2093. }
  2094. }
  2095. // TestSwitchCancel checks that if htlc was rejected we remove unused
  2096. // circuits.
  2097. func TestSwitchCancel(t *testing.T) {
  2098. t.Parallel()
  2099. alicePeer, err := newMockServer(
  2100. t, "alice", testStartingHeight, nil, testDefaultDelta,
  2101. )
  2102. require.NoError(t, err, "unable to create alice server")
  2103. bobPeer, err := newMockServer(
  2104. t, "bob", testStartingHeight, nil, testDefaultDelta,
  2105. )
  2106. require.NoError(t, err, "unable to create bob server")
  2107. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2108. require.NoError(t, err, "unable to init switch")
  2109. if err := s.Start(); err != nil {
  2110. t.Fatalf("unable to start switch: %v", err)
  2111. }
  2112. defer s.Stop()
  2113. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  2114. aliceChannelLink := newMockChannelLink(
  2115. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  2116. false, false,
  2117. )
  2118. bobChannelLink := newMockChannelLink(
  2119. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  2120. false,
  2121. )
  2122. if err := s.AddLink(aliceChannelLink); err != nil {
  2123. t.Fatalf("unable to add alice link: %v", err)
  2124. }
  2125. if err := s.AddLink(bobChannelLink); err != nil {
  2126. t.Fatalf("unable to add bob link: %v", err)
  2127. }
  2128. // Create request which should be forwarder from alice channel link
  2129. // to bob channel link.
  2130. preimage, err := genPreimage()
  2131. require.NoError(t, err, "unable to generate preimage")
  2132. rhash := sha256.Sum256(preimage[:])
  2133. request := &htlcPacket{
  2134. incomingChanID: aliceChannelLink.ShortChanID(),
  2135. incomingHTLCID: 0,
  2136. outgoingChanID: bobChannelLink.ShortChanID(),
  2137. obfuscator: NewMockObfuscator(),
  2138. htlc: &lnwire.UpdateAddHTLC{
  2139. PaymentHash: rhash,
  2140. Amount: 1,
  2141. },
  2142. }
  2143. // Handle the request and checks that bob channel link received it.
  2144. if err := s.ForwardPackets(nil, request); err != nil {
  2145. t.Fatal(err)
  2146. }
  2147. select {
  2148. case packet := <-bobChannelLink.packets:
  2149. if err := bobChannelLink.completeCircuit(packet); err != nil {
  2150. t.Fatalf("unable to complete payment circuit: %v", err)
  2151. }
  2152. case <-time.After(time.Second):
  2153. t.Fatal("request was not propagated to destination")
  2154. }
  2155. if s.circuits.NumPending() != 1 {
  2156. t.Fatalf("wrong amount of half circuits")
  2157. }
  2158. if s.circuits.NumOpen() != 1 {
  2159. t.Fatal("wrong amount of circuits")
  2160. }
  2161. // Create settle request pretending that bob channel link handled
  2162. // the add htlc request and sent the htlc settle request back. This
  2163. // request should be forwarder back to alice channel link.
  2164. request = &htlcPacket{
  2165. outgoingChanID: bobChannelLink.ShortChanID(),
  2166. outgoingHTLCID: 0,
  2167. amount: 1,
  2168. htlc: &lnwire.UpdateFailHTLC{},
  2169. }
  2170. // Handle the request and checks that payment circuit works properly.
  2171. if err := s.ForwardPackets(nil, request); err != nil {
  2172. t.Fatal(err)
  2173. }
  2174. select {
  2175. case pkt := <-aliceChannelLink.packets:
  2176. if err := aliceChannelLink.completeCircuit(pkt); err != nil {
  2177. t.Fatalf("unable to remove circuit: %v", err)
  2178. }
  2179. case <-time.After(time.Second):
  2180. t.Fatal("request was not propagated to channelPoint")
  2181. }
  2182. if s.circuits.NumPending() != 0 {
  2183. t.Fatal("wrong amount of circuits")
  2184. }
  2185. if s.circuits.NumOpen() != 0 {
  2186. t.Fatal("wrong amount of circuits")
  2187. }
  2188. }
  2189. // TestSwitchAddSamePayment tests that we send the payment with the same
  2190. // payment hash.
  2191. func TestSwitchAddSamePayment(t *testing.T) {
  2192. t.Parallel()
  2193. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  2194. alicePeer, err := newMockServer(
  2195. t, "alice", testStartingHeight, nil, testDefaultDelta,
  2196. )
  2197. require.NoError(t, err, "unable to create alice server")
  2198. bobPeer, err := newMockServer(
  2199. t, "bob", testStartingHeight, nil, testDefaultDelta,
  2200. )
  2201. require.NoError(t, err, "unable to create bob server")
  2202. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2203. require.NoError(t, err, "unable to init switch")
  2204. if err := s.Start(); err != nil {
  2205. t.Fatalf("unable to start switch: %v", err)
  2206. }
  2207. defer s.Stop()
  2208. aliceChannelLink := newMockChannelLink(
  2209. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  2210. false, false,
  2211. )
  2212. bobChannelLink := newMockChannelLink(
  2213. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  2214. false,
  2215. )
  2216. if err := s.AddLink(aliceChannelLink); err != nil {
  2217. t.Fatalf("unable to add alice link: %v", err)
  2218. }
  2219. if err := s.AddLink(bobChannelLink); err != nil {
  2220. t.Fatalf("unable to add bob link: %v", err)
  2221. }
  2222. // Create request which should be forwarder from alice channel link
  2223. // to bob channel link.
  2224. preimage, err := genPreimage()
  2225. require.NoError(t, err, "unable to generate preimage")
  2226. rhash := sha256.Sum256(preimage[:])
  2227. request := &htlcPacket{
  2228. incomingChanID: aliceChannelLink.ShortChanID(),
  2229. incomingHTLCID: 0,
  2230. outgoingChanID: bobChannelLink.ShortChanID(),
  2231. obfuscator: NewMockObfuscator(),
  2232. htlc: &lnwire.UpdateAddHTLC{
  2233. PaymentHash: rhash,
  2234. Amount: 1,
  2235. },
  2236. }
  2237. // Handle the request and checks that bob channel link received it.
  2238. if err := s.ForwardPackets(nil, request); err != nil {
  2239. t.Fatal(err)
  2240. }
  2241. select {
  2242. case packet := <-bobChannelLink.packets:
  2243. if err := bobChannelLink.completeCircuit(packet); err != nil {
  2244. t.Fatalf("unable to complete payment circuit: %v", err)
  2245. }
  2246. case <-time.After(time.Second):
  2247. t.Fatal("request was not propagated to destination")
  2248. }
  2249. if s.circuits.NumOpen() != 1 {
  2250. t.Fatal("wrong amount of circuits")
  2251. }
  2252. request = &htlcPacket{
  2253. incomingChanID: aliceChannelLink.ShortChanID(),
  2254. incomingHTLCID: 1,
  2255. outgoingChanID: bobChannelLink.ShortChanID(),
  2256. obfuscator: NewMockObfuscator(),
  2257. htlc: &lnwire.UpdateAddHTLC{
  2258. PaymentHash: rhash,
  2259. Amount: 1,
  2260. },
  2261. }
  2262. // Handle the request and checks that bob channel link received it.
  2263. if err := s.ForwardPackets(nil, request); err != nil {
  2264. t.Fatal(err)
  2265. }
  2266. select {
  2267. case packet := <-bobChannelLink.packets:
  2268. if err := bobChannelLink.completeCircuit(packet); err != nil {
  2269. t.Fatalf("unable to complete payment circuit: %v", err)
  2270. }
  2271. case <-time.After(time.Second):
  2272. t.Fatal("request was not propagated to destination")
  2273. }
  2274. if s.circuits.NumOpen() != 2 {
  2275. t.Fatal("wrong amount of circuits")
  2276. }
  2277. // Create settle request pretending that bob channel link handled
  2278. // the add htlc request and sent the htlc settle request back. This
  2279. // request should be forwarder back to alice channel link.
  2280. request = &htlcPacket{
  2281. outgoingChanID: bobChannelLink.ShortChanID(),
  2282. outgoingHTLCID: 0,
  2283. amount: 1,
  2284. htlc: &lnwire.UpdateFailHTLC{},
  2285. }
  2286. // Handle the request and checks that payment circuit works properly.
  2287. if err := s.ForwardPackets(nil, request); err != nil {
  2288. t.Fatal(err)
  2289. }
  2290. select {
  2291. case pkt := <-aliceChannelLink.packets:
  2292. if err := aliceChannelLink.completeCircuit(pkt); err != nil {
  2293. t.Fatalf("unable to remove circuit: %v", err)
  2294. }
  2295. case <-time.After(time.Second):
  2296. t.Fatal("request was not propagated to channelPoint")
  2297. }
  2298. if s.circuits.NumOpen() != 1 {
  2299. t.Fatal("wrong amount of circuits")
  2300. }
  2301. request = &htlcPacket{
  2302. outgoingChanID: bobChannelLink.ShortChanID(),
  2303. outgoingHTLCID: 1,
  2304. amount: 1,
  2305. htlc: &lnwire.UpdateFailHTLC{},
  2306. }
  2307. // Handle the request and checks that payment circuit works properly.
  2308. if err := s.ForwardPackets(nil, request); err != nil {
  2309. t.Fatal(err)
  2310. }
  2311. select {
  2312. case pkt := <-aliceChannelLink.packets:
  2313. if err := aliceChannelLink.completeCircuit(pkt); err != nil {
  2314. t.Fatalf("unable to remove circuit: %v", err)
  2315. }
  2316. case <-time.After(time.Second):
  2317. t.Fatal("request was not propagated to channelPoint")
  2318. }
  2319. if s.circuits.NumOpen() != 0 {
  2320. t.Fatal("wrong amount of circuits")
  2321. }
  2322. }
  2323. // TestSwitchSendPayment tests ability of htlc switch to respond to the
  2324. // users when response is came back from channel link.
  2325. func TestSwitchSendPayment(t *testing.T) {
  2326. t.Parallel()
  2327. alicePeer, err := newMockServer(
  2328. t, "alice", testStartingHeight, nil, testDefaultDelta,
  2329. )
  2330. require.NoError(t, err, "unable to create alice server")
  2331. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2332. require.NoError(t, err, "unable to init switch")
  2333. if err := s.Start(); err != nil {
  2334. t.Fatalf("unable to start switch: %v", err)
  2335. }
  2336. defer s.Stop()
  2337. chanID1, _, aliceChanID, _ := genIDs()
  2338. aliceChannelLink := newMockChannelLink(
  2339. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  2340. false, false,
  2341. )
  2342. if err := s.AddLink(aliceChannelLink); err != nil {
  2343. t.Fatalf("unable to add link: %v", err)
  2344. }
  2345. // Create request which should be forwarder from alice channel link
  2346. // to bob channel link.
  2347. preimage, err := genPreimage()
  2348. require.NoError(t, err, "unable to generate preimage")
  2349. rhash := sha256.Sum256(preimage[:])
  2350. update := &lnwire.UpdateAddHTLC{
  2351. PaymentHash: rhash,
  2352. Amount: 1,
  2353. }
  2354. paymentID := uint64(123)
  2355. // First check that the switch will correctly respond that this payment
  2356. // ID is unknown.
  2357. _, err = s.GetAttemptResult(
  2358. paymentID, rhash, newMockDeobfuscator(),
  2359. )
  2360. if err != ErrPaymentIDNotFound {
  2361. t.Fatalf("expected ErrPaymentIDNotFound, got %v", err)
  2362. }
  2363. // Handle the request and checks that bob channel link received it.
  2364. errChan := make(chan error)
  2365. go func() {
  2366. err := s.SendHTLC(
  2367. aliceChannelLink.ShortChanID(), paymentID, update,
  2368. )
  2369. if err != nil {
  2370. errChan <- err
  2371. return
  2372. }
  2373. resultChan, err := s.GetAttemptResult(
  2374. paymentID, rhash, newMockDeobfuscator(),
  2375. )
  2376. if err != nil {
  2377. errChan <- err
  2378. return
  2379. }
  2380. result, ok := <-resultChan
  2381. if !ok {
  2382. errChan <- fmt.Errorf("shutting down")
  2383. }
  2384. if result.Error != nil {
  2385. errChan <- result.Error
  2386. return
  2387. }
  2388. errChan <- nil
  2389. }()
  2390. select {
  2391. case packet := <-aliceChannelLink.packets:
  2392. if err := aliceChannelLink.completeCircuit(packet); err != nil {
  2393. t.Fatalf("unable to complete payment circuit: %v", err)
  2394. }
  2395. case err := <-errChan:
  2396. if err != nil {
  2397. t.Fatalf("unable to send payment: %v", err)
  2398. }
  2399. case <-time.After(time.Second):
  2400. t.Fatal("request was not propagated to destination")
  2401. }
  2402. if s.circuits.NumOpen() != 1 {
  2403. t.Fatal("wrong amount of circuits")
  2404. }
  2405. // Create fail request pretending that bob channel link handled
  2406. // the add htlc request with error and sent the htlc fail request
  2407. // back. This request should be forwarded back to alice channel link.
  2408. obfuscator := NewMockObfuscator()
  2409. failure := lnwire.NewFailIncorrectDetails(update.Amount, 100)
  2410. reason, err := obfuscator.EncryptFirstHop(failure)
  2411. require.NoError(t, err, "unable obfuscate failure")
  2412. if s.IsForwardedHTLC(aliceChannelLink.ShortChanID(), update.ID) {
  2413. t.Fatal("htlc should be identified as not forwarded")
  2414. }
  2415. packet := &htlcPacket{
  2416. outgoingChanID: aliceChannelLink.ShortChanID(),
  2417. outgoingHTLCID: 0,
  2418. amount: 1,
  2419. htlc: &lnwire.UpdateFailHTLC{
  2420. Reason: reason,
  2421. },
  2422. }
  2423. if err := s.ForwardPackets(nil, packet); err != nil {
  2424. t.Fatalf("can't forward htlc packet: %v", err)
  2425. }
  2426. select {
  2427. case err := <-errChan:
  2428. assertFailureCode(
  2429. t, err, lnwire.CodeIncorrectOrUnknownPaymentDetails,
  2430. )
  2431. case <-time.After(time.Second):
  2432. t.Fatal("err wasn't received")
  2433. }
  2434. }
  2435. // TestLocalPaymentNoForwardingEvents tests that if we send a series of locally
  2436. // initiated payments, then they aren't reflected in the forwarding log.
  2437. func TestLocalPaymentNoForwardingEvents(t *testing.T) {
  2438. t.Parallel()
  2439. // First, we'll create our traditional three hop network. We'll only be
  2440. // interacting with and asserting the state of the first end point for
  2441. // this test.
  2442. channels, _, err := createClusterChannels(
  2443. t, btcutil.SatoshiPerBitcoin*3, btcutil.SatoshiPerBitcoin*5,
  2444. )
  2445. require.NoError(t, err, "unable to create channel")
  2446. n := newThreeHopNetwork(t, channels.aliceToBob, channels.bobToAlice,
  2447. channels.bobToCarol, channels.carolToBob, testStartingHeight)
  2448. if err := n.start(); err != nil {
  2449. t.Fatalf("unable to start three hop network: %v", err)
  2450. }
  2451. // We'll now craft and send a payment from Alice to Bob.
  2452. amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
  2453. htlcAmt, totalTimelock, hops := generateHops(
  2454. amount, testStartingHeight, n.firstBobChannelLink,
  2455. )
  2456. // With the payment crafted, we'll send it from Alice to Bob. We'll
  2457. // wait for Alice to receive the preimage for the payment before
  2458. // proceeding.
  2459. receiver := n.bobServer
  2460. firstHop := n.firstBobChannelLink.ShortChanID()
  2461. _, err = makePayment(
  2462. n.aliceServer, receiver, firstHop, hops, amount, htlcAmt,
  2463. totalTimelock,
  2464. ).Wait(30 * time.Second)
  2465. require.NoError(t, err, "unable to make the payment")
  2466. // At this point, we'll forcibly stop the three hop network. Doing
  2467. // this will cause any pending forwarding events to be flushed by the
  2468. // various switches in the network.
  2469. n.stop()
  2470. // With all the switches stopped, we'll fetch Alice's mock forwarding
  2471. // event log.
  2472. log, ok := n.aliceServer.htlcSwitch.cfg.FwdingLog.(*mockForwardingLog)
  2473. if !ok {
  2474. t.Fatalf("mockForwardingLog assertion failed")
  2475. }
  2476. log.Lock()
  2477. defer log.Unlock()
  2478. // If we examine the memory of the forwarding log, then it should be
  2479. // blank.
  2480. if len(log.events) != 0 {
  2481. t.Fatalf("log should have no events, instead has: %v",
  2482. spew.Sdump(log.events))
  2483. }
  2484. }
  2485. // TestMultiHopPaymentForwardingEvents tests that if we send a series of
  2486. // multi-hop payments via Alice->Bob->Carol. Then Bob properly logs forwarding
  2487. // events, while Alice and Carol don't.
  2488. func TestMultiHopPaymentForwardingEvents(t *testing.T) {
  2489. t.Parallel()
  2490. // First, we'll create our traditional three hop network.
  2491. channels, _, err := createClusterChannels(
  2492. t, btcutil.SatoshiPerBitcoin*3, btcutil.SatoshiPerBitcoin*5,
  2493. )
  2494. require.NoError(t, err, "unable to create channel")
  2495. n := newThreeHopNetwork(t, channels.aliceToBob, channels.bobToAlice,
  2496. channels.bobToCarol, channels.carolToBob, testStartingHeight)
  2497. if err := n.start(); err != nil {
  2498. t.Fatalf("unable to start three hop network: %v", err)
  2499. }
  2500. // We'll make now 10 payments, of 100k satoshis each from Alice to
  2501. // Carol via Bob.
  2502. const numPayments = 10
  2503. finalAmt := lnwire.NewMSatFromSatoshis(100000)
  2504. htlcAmt, totalTimelock, hops := generateHops(
  2505. finalAmt, testStartingHeight, n.firstBobChannelLink,
  2506. n.carolChannelLink,
  2507. )
  2508. firstHop := n.firstBobChannelLink.ShortChanID()
  2509. for i := 0; i < numPayments/2; i++ {
  2510. _, err := makePayment(
  2511. n.aliceServer, n.carolServer, firstHop, hops, finalAmt,
  2512. htlcAmt, totalTimelock,
  2513. ).Wait(30 * time.Second)
  2514. if err != nil {
  2515. t.Fatalf("unable to send payment: %v", err)
  2516. }
  2517. }
  2518. bobLog, ok := n.bobServer.htlcSwitch.cfg.FwdingLog.(*mockForwardingLog)
  2519. if !ok {
  2520. t.Fatalf("mockForwardingLog assertion failed")
  2521. }
  2522. // After sending 5 of the payments, trigger the forwarding ticker, to
  2523. // make sure the events are properly flushed.
  2524. bobTicker, ok := n.bobServer.htlcSwitch.cfg.FwdEventTicker.(*ticker.Force)
  2525. if !ok {
  2526. t.Fatalf("mockTicker assertion failed")
  2527. }
  2528. // We'll trigger the ticker, and wait for the events to appear in Bob's
  2529. // forwarding log.
  2530. timeout := time.After(15 * time.Second)
  2531. for {
  2532. select {
  2533. case bobTicker.Force <- time.Now():
  2534. case <-time.After(1 * time.Second):
  2535. t.Fatalf("unable to force tick")
  2536. }
  2537. // If all 5 events is found in Bob's log, we can break out and
  2538. // continue the test.
  2539. bobLog.Lock()
  2540. if len(bobLog.events) == 5 {
  2541. bobLog.Unlock()
  2542. break
  2543. }
  2544. bobLog.Unlock()
  2545. // Otherwise wait a little bit before checking again.
  2546. select {
  2547. case <-time.After(50 * time.Millisecond):
  2548. case <-timeout:
  2549. bobLog.Lock()
  2550. defer bobLog.Unlock()
  2551. t.Fatalf("expected 5 events in event log, instead "+
  2552. "found: %v", spew.Sdump(bobLog.events))
  2553. }
  2554. }
  2555. // Send the remaining payments.
  2556. for i := numPayments / 2; i < numPayments; i++ {
  2557. _, err := makePayment(
  2558. n.aliceServer, n.carolServer, firstHop, hops, finalAmt,
  2559. htlcAmt, totalTimelock,
  2560. ).Wait(30 * time.Second)
  2561. if err != nil {
  2562. t.Fatalf("unable to send payment: %v", err)
  2563. }
  2564. }
  2565. // With all 10 payments sent. We'll now manually stop each of the
  2566. // switches so we can examine their end state.
  2567. n.stop()
  2568. // Alice and Carol shouldn't have any recorded forwarding events, as
  2569. // they were the source and the sink for these payment flows.
  2570. aliceLog, ok := n.aliceServer.htlcSwitch.cfg.FwdingLog.(*mockForwardingLog)
  2571. if !ok {
  2572. t.Fatalf("mockForwardingLog assertion failed")
  2573. }
  2574. aliceLog.Lock()
  2575. defer aliceLog.Unlock()
  2576. if len(aliceLog.events) != 0 {
  2577. t.Fatalf("log should have no events, instead has: %v",
  2578. spew.Sdump(aliceLog.events))
  2579. }
  2580. carolLog, ok := n.carolServer.htlcSwitch.cfg.FwdingLog.(*mockForwardingLog)
  2581. if !ok {
  2582. t.Fatalf("mockForwardingLog assertion failed")
  2583. }
  2584. carolLog.Lock()
  2585. defer carolLog.Unlock()
  2586. if len(carolLog.events) != 0 {
  2587. t.Fatalf("log should have no events, instead has: %v",
  2588. spew.Sdump(carolLog.events))
  2589. }
  2590. // Bob on the other hand, should have 10 events.
  2591. bobLog.Lock()
  2592. defer bobLog.Unlock()
  2593. if len(bobLog.events) != 10 {
  2594. t.Fatalf("log should have 10 events, instead has: %v",
  2595. spew.Sdump(bobLog.events))
  2596. }
  2597. // Each of the 10 events should have had all fields set properly.
  2598. for _, event := range bobLog.events {
  2599. // The incoming and outgoing channels should properly be set for
  2600. // the event.
  2601. if event.IncomingChanID != n.aliceChannelLink.ShortChanID() {
  2602. t.Fatalf("chan id mismatch: expected %v, got %v",
  2603. event.IncomingChanID,
  2604. n.aliceChannelLink.ShortChanID())
  2605. }
  2606. if event.OutgoingChanID != n.carolChannelLink.ShortChanID() {
  2607. t.Fatalf("chan id mismatch: expected %v, got %v",
  2608. event.OutgoingChanID,
  2609. n.carolChannelLink.ShortChanID())
  2610. }
  2611. // Additionally, the incoming and outgoing amounts should also
  2612. // be properly set.
  2613. if event.AmtIn != htlcAmt {
  2614. t.Fatalf("incoming amt mismatch: expected %v, got %v",
  2615. event.AmtIn, htlcAmt)
  2616. }
  2617. if event.AmtOut != finalAmt {
  2618. t.Fatalf("outgoing amt mismatch: expected %v, got %v",
  2619. event.AmtOut, finalAmt)
  2620. }
  2621. }
  2622. }
  2623. // TestUpdateFailMalformedHTLCErrorConversion tests that we're able to properly
  2624. // convert malformed HTLC errors that originate at the direct link, as well as
  2625. // during multi-hop HTLC forwarding.
  2626. func TestUpdateFailMalformedHTLCErrorConversion(t *testing.T) {
  2627. t.Parallel()
  2628. // First, we'll create our traditional three hop network.
  2629. channels, _, err := createClusterChannels(
  2630. t, btcutil.SatoshiPerBitcoin*3, btcutil.SatoshiPerBitcoin*5,
  2631. )
  2632. require.NoError(t, err, "unable to create channel")
  2633. n := newThreeHopNetwork(
  2634. t, channels.aliceToBob, channels.bobToAlice,
  2635. channels.bobToCarol, channels.carolToBob, testStartingHeight,
  2636. )
  2637. if err := n.start(); err != nil {
  2638. t.Fatalf("unable to start three hop network: %v", err)
  2639. }
  2640. assertPaymentFailure := func(t *testing.T) {
  2641. // With the decoder modified, we'll now attempt to send a
  2642. // payment from Alice to carol.
  2643. finalAmt := lnwire.NewMSatFromSatoshis(100000)
  2644. htlcAmt, totalTimelock, hops := generateHops(
  2645. finalAmt, testStartingHeight, n.firstBobChannelLink,
  2646. n.carolChannelLink,
  2647. )
  2648. firstHop := n.firstBobChannelLink.ShortChanID()
  2649. _, err = makePayment(
  2650. n.aliceServer, n.carolServer, firstHop, hops, finalAmt,
  2651. htlcAmt, totalTimelock,
  2652. ).Wait(30 * time.Second)
  2653. // The payment should fail as Carol is unable to decode the
  2654. // onion blob sent to her.
  2655. if err == nil {
  2656. t.Fatalf("unable to send payment: %v", err)
  2657. }
  2658. routingErr := err.(ClearTextError)
  2659. failureMsg := routingErr.WireMessage()
  2660. if _, ok := failureMsg.(*lnwire.FailInvalidOnionKey); !ok {
  2661. t.Fatalf("expected onion failure instead got: %v",
  2662. routingErr.WireMessage())
  2663. }
  2664. }
  2665. t.Run("multi-hop error conversion", func(t *testing.T) {
  2666. // Now that we have our network up, we'll modify the hop
  2667. // iterator for the Bob <-> Carol channel to fail to decode in
  2668. // order to simulate either a replay attack or an issue
  2669. // decoding the onion.
  2670. n.carolOnionDecoder.decodeFail = true
  2671. assertPaymentFailure(t)
  2672. })
  2673. t.Run("direct channel error conversion", func(t *testing.T) {
  2674. // Similar to the above test case, we'll now make the Alice <->
  2675. // Bob link always fail to decode an onion. This differs from
  2676. // the above test case in that there's no encryption on the
  2677. // error at all since Alice will directly receive a
  2678. // UpdateFailMalformedHTLC message.
  2679. n.bobOnionDecoder.decodeFail = true
  2680. assertPaymentFailure(t)
  2681. })
  2682. }
  2683. // TestSwitchGetAttemptResult tests that the switch interacts as expected with
  2684. // the circuit map and network result store when looking up the result of a
  2685. // payment ID. This is important for not to lose results under concurrent
  2686. // lookup and receiving results.
  2687. func TestSwitchGetAttemptResult(t *testing.T) {
  2688. t.Parallel()
  2689. const paymentID = 123
  2690. var preimg lntypes.Preimage
  2691. preimg[0] = 3
  2692. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2693. require.NoError(t, err, "unable to init switch")
  2694. if err := s.Start(); err != nil {
  2695. t.Fatalf("unable to start switch: %v", err)
  2696. }
  2697. defer s.Stop()
  2698. lookup := make(chan *PaymentCircuit, 1)
  2699. s.circuits = &mockCircuitMap{
  2700. lookup: lookup,
  2701. }
  2702. // If the payment circuit is not found in the circuit map, the payment
  2703. // result must be found in the store if available. Since we haven't
  2704. // added anything to the store yet, ErrPaymentIDNotFound should be
  2705. // returned.
  2706. lookup <- nil
  2707. _, err = s.GetAttemptResult(
  2708. paymentID, lntypes.Hash{}, newMockDeobfuscator(),
  2709. )
  2710. if err != ErrPaymentIDNotFound {
  2711. t.Fatalf("expected ErrPaymentIDNotFound, got %v", err)
  2712. }
  2713. // Next let the lookup find the circuit in the circuit map. It should
  2714. // subscribe to payment results, and return the result when available.
  2715. lookup <- &PaymentCircuit{}
  2716. resultChan, err := s.GetAttemptResult(
  2717. paymentID, lntypes.Hash{}, newMockDeobfuscator(),
  2718. )
  2719. require.NoError(t, err, "unable to get payment result")
  2720. // Add the result to the store.
  2721. n := &networkResult{
  2722. msg: &lnwire.UpdateFulfillHTLC{
  2723. PaymentPreimage: preimg,
  2724. },
  2725. unencrypted: true,
  2726. isResolution: true,
  2727. }
  2728. err = s.networkResults.storeResult(paymentID, n)
  2729. require.NoError(t, err, "unable to store result")
  2730. // The result should be available.
  2731. select {
  2732. case res, ok := <-resultChan:
  2733. if !ok {
  2734. t.Fatalf("channel was closed")
  2735. }
  2736. if res.Error != nil {
  2737. t.Fatalf("got unexpected error result")
  2738. }
  2739. if res.Preimage != preimg {
  2740. t.Fatalf("expected preimg %v, got %v",
  2741. preimg, res.Preimage)
  2742. }
  2743. case <-time.After(1 * time.Second):
  2744. t.Fatalf("result not received")
  2745. }
  2746. // As a final test, try to get the result again. Now that is no longer
  2747. // in the circuit map, it should be immediately available from the
  2748. // store.
  2749. lookup <- nil
  2750. resultChan, err = s.GetAttemptResult(
  2751. paymentID, lntypes.Hash{}, newMockDeobfuscator(),
  2752. )
  2753. require.NoError(t, err, "unable to get payment result")
  2754. select {
  2755. case res, ok := <-resultChan:
  2756. if !ok {
  2757. t.Fatalf("channel was closed")
  2758. }
  2759. if res.Error != nil {
  2760. t.Fatalf("got unexpected error result")
  2761. }
  2762. if res.Preimage != preimg {
  2763. t.Fatalf("expected preimg %v, got %v",
  2764. preimg, res.Preimage)
  2765. }
  2766. case <-time.After(1 * time.Second):
  2767. t.Fatalf("result not received")
  2768. }
  2769. }
  2770. // TestInvalidFailure tests that the switch returns an unreadable failure error
  2771. // if the failure cannot be decrypted.
  2772. func TestInvalidFailure(t *testing.T) {
  2773. t.Parallel()
  2774. alicePeer, err := newMockServer(
  2775. t, "alice", testStartingHeight, nil, testDefaultDelta,
  2776. )
  2777. require.NoError(t, err, "unable to create alice server")
  2778. s, err := initSwitchWithTempDB(t, testStartingHeight)
  2779. require.NoError(t, err, "unable to init switch")
  2780. if err := s.Start(); err != nil {
  2781. t.Fatalf("unable to start switch: %v", err)
  2782. }
  2783. defer s.Stop()
  2784. chanID1, _, aliceChanID, _ := genIDs()
  2785. // Set up a mock channel link.
  2786. aliceChannelLink := newMockChannelLink(
  2787. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  2788. false, false,
  2789. )
  2790. if err := s.AddLink(aliceChannelLink); err != nil {
  2791. t.Fatalf("unable to add link: %v", err)
  2792. }
  2793. // Create a request which should be forwarded to the mock channel link.
  2794. preimage, err := genPreimage()
  2795. require.NoError(t, err, "unable to generate preimage")
  2796. rhash := sha256.Sum256(preimage[:])
  2797. update := &lnwire.UpdateAddHTLC{
  2798. PaymentHash: rhash,
  2799. Amount: 1,
  2800. }
  2801. paymentID := uint64(123)
  2802. // Send the request.
  2803. err = s.SendHTLC(
  2804. aliceChannelLink.ShortChanID(), paymentID, update,
  2805. )
  2806. require.NoError(t, err, "unable to send payment")
  2807. // Catch the packet and complete the circuit so that the switch is ready
  2808. // for a response.
  2809. select {
  2810. case packet := <-aliceChannelLink.packets:
  2811. if err := aliceChannelLink.completeCircuit(packet); err != nil {
  2812. t.Fatalf("unable to complete payment circuit: %v", err)
  2813. }
  2814. case <-time.After(time.Second):
  2815. t.Fatal("request was not propagated to destination")
  2816. }
  2817. // Send response packet with an unreadable failure message to the
  2818. // switch. The reason failed is not relevant, because we mock the
  2819. // decryption.
  2820. packet := &htlcPacket{
  2821. outgoingChanID: aliceChannelLink.ShortChanID(),
  2822. outgoingHTLCID: 0,
  2823. amount: 1,
  2824. htlc: &lnwire.UpdateFailHTLC{
  2825. Reason: []byte{1, 2, 3},
  2826. },
  2827. }
  2828. if err := s.ForwardPackets(nil, packet); err != nil {
  2829. t.Fatalf("can't forward htlc packet: %v", err)
  2830. }
  2831. // Get payment result from switch. We expect an unreadable failure
  2832. // message error.
  2833. deobfuscator := SphinxErrorDecrypter{
  2834. OnionErrorDecrypter: &mockOnionErrorDecryptor{
  2835. err: ErrUnreadableFailureMessage,
  2836. },
  2837. }
  2838. resultChan, err := s.GetAttemptResult(
  2839. paymentID, rhash, &deobfuscator,
  2840. )
  2841. if err != nil {
  2842. t.Fatal(err)
  2843. }
  2844. select {
  2845. case result := <-resultChan:
  2846. if result.Error != ErrUnreadableFailureMessage {
  2847. t.Fatal("expected unreadable failure message")
  2848. }
  2849. case <-time.After(time.Second):
  2850. t.Fatal("err wasn't received")
  2851. }
  2852. // Modify the decryption to simulate that decryption went alright, but
  2853. // the failure cannot be decoded.
  2854. deobfuscator = SphinxErrorDecrypter{
  2855. OnionErrorDecrypter: &mockOnionErrorDecryptor{
  2856. sourceIdx: 2,
  2857. message: []byte{200},
  2858. },
  2859. }
  2860. resultChan, err = s.GetAttemptResult(
  2861. paymentID, rhash, &deobfuscator,
  2862. )
  2863. if err != nil {
  2864. t.Fatal(err)
  2865. }
  2866. select {
  2867. case result := <-resultChan:
  2868. rtErr, ok := result.Error.(ClearTextError)
  2869. if !ok {
  2870. t.Fatal("expected ClearTextError")
  2871. }
  2872. source, ok := rtErr.(*ForwardingError)
  2873. if !ok {
  2874. t.Fatalf("expected forwarding error, got: %T", rtErr)
  2875. }
  2876. if source.FailureSourceIdx != 2 {
  2877. t.Fatal("unexpected error source index")
  2878. }
  2879. if rtErr.WireMessage() != nil {
  2880. t.Fatal("expected empty failure message")
  2881. }
  2882. case <-time.After(time.Second):
  2883. t.Fatal("err wasn't received")
  2884. }
  2885. }
  2886. // htlcNotifierEvents is a function that generates a set of expected htlc
  2887. // notifier evetns for each node in a three hop network with the dynamic
  2888. // values provided. These functions take dynamic values so that changes to
  2889. // external systems (such as our default timelock delta) do not break
  2890. // these tests.
  2891. type htlcNotifierEvents func(channels *clusterChannels, htlcID uint64,
  2892. ts time.Time, htlc *lnwire.UpdateAddHTLC,
  2893. hops []*hop.Payload,
  2894. preimage *lntypes.Preimage) ([]interface{}, []interface{}, []interface{})
  2895. // TestHtlcNotifier tests the notifying of htlc events that are routed over a
  2896. // three hop network. It sets up an Alice -> Bob -> Carol network and routes
  2897. // payments from Alice -> Carol to test events from the perspective of a
  2898. // sending (Alice), forwarding (Bob) and receiving (Carol) node. Test cases
  2899. // are present for saduccessful and failed payments.
  2900. func TestHtlcNotifier(t *testing.T) {
  2901. tests := []struct {
  2902. name string
  2903. // Options is a set of options to apply to the three hop
  2904. // network's servers.
  2905. options []serverOption
  2906. // expectedEvents is a function which returns an expected set
  2907. // of events for the test.
  2908. expectedEvents htlcNotifierEvents
  2909. // iterations is the number of times we will send a payment,
  2910. // this is used to send more than one payment to force non-
  2911. // zero htlc indexes to make sure we aren't just checking
  2912. // default values.
  2913. iterations int
  2914. }{
  2915. {
  2916. name: "successful three hop payment",
  2917. options: nil,
  2918. expectedEvents: func(channels *clusterChannels,
  2919. htlcID uint64, ts time.Time,
  2920. htlc *lnwire.UpdateAddHTLC,
  2921. hops []*hop.Payload,
  2922. preimage *lntypes.Preimage) ([]interface{},
  2923. []interface{}, []interface{}) {
  2924. return getThreeHopEvents(
  2925. channels, htlcID, ts, htlc, hops, nil, preimage,
  2926. )
  2927. },
  2928. iterations: 2,
  2929. },
  2930. {
  2931. name: "failed at forwarding link",
  2932. // Set a functional option which disables bob as a
  2933. // forwarding node to force a payment error.
  2934. options: []serverOption{
  2935. serverOptionRejectHtlc(false, true, false),
  2936. },
  2937. expectedEvents: func(channels *clusterChannels,
  2938. htlcID uint64, ts time.Time,
  2939. htlc *lnwire.UpdateAddHTLC,
  2940. hops []*hop.Payload,
  2941. preimage *lntypes.Preimage) ([]interface{},
  2942. []interface{}, []interface{}) {
  2943. return getThreeHopEvents(
  2944. channels, htlcID, ts, htlc, hops,
  2945. &LinkError{
  2946. msg: &lnwire.FailChannelDisabled{},
  2947. FailureDetail: OutgoingFailureForwardsDisabled,
  2948. },
  2949. preimage,
  2950. )
  2951. },
  2952. iterations: 1,
  2953. },
  2954. }
  2955. for _, test := range tests {
  2956. test := test
  2957. t.Run(test.name, func(t *testing.T) {
  2958. testHtcNotifier(
  2959. t, test.options, test.iterations,
  2960. test.expectedEvents,
  2961. )
  2962. })
  2963. }
  2964. }
  2965. // testHtcNotifier runs a htlc notifier test.
  2966. func testHtcNotifier(t *testing.T, testOpts []serverOption, iterations int,
  2967. getEvents htlcNotifierEvents) {
  2968. t.Parallel()
  2969. // First, we'll create our traditional three hop
  2970. // network.
  2971. channels, _, err := createClusterChannels(
  2972. t, btcutil.SatoshiPerBitcoin*3, btcutil.SatoshiPerBitcoin*5,
  2973. )
  2974. require.NoError(t, err, "unable to create channel")
  2975. // Mock time so that all events are reported with a static timestamp.
  2976. now := time.Now()
  2977. mockTime := func() time.Time {
  2978. return now
  2979. }
  2980. // Create htlc notifiers for each server in the three hop network and
  2981. // start them.
  2982. aliceNotifier := NewHtlcNotifier(mockTime)
  2983. if err := aliceNotifier.Start(); err != nil {
  2984. t.Fatalf("could not start alice notifier")
  2985. }
  2986. t.Cleanup(func() {
  2987. if err := aliceNotifier.Stop(); err != nil {
  2988. t.Fatalf("failed to stop alice notifier: %v", err)
  2989. }
  2990. })
  2991. bobNotifier := NewHtlcNotifier(mockTime)
  2992. if err := bobNotifier.Start(); err != nil {
  2993. t.Fatalf("could not start bob notifier")
  2994. }
  2995. t.Cleanup(func() {
  2996. if err := bobNotifier.Stop(); err != nil {
  2997. t.Fatalf("failed to stop bob notifier: %v", err)
  2998. }
  2999. })
  3000. carolNotifier := NewHtlcNotifier(mockTime)
  3001. if err := carolNotifier.Start(); err != nil {
  3002. t.Fatalf("could not start carol notifier")
  3003. }
  3004. t.Cleanup(func() {
  3005. if err := carolNotifier.Stop(); err != nil {
  3006. t.Fatalf("failed to stop carol notifier: %v", err)
  3007. }
  3008. })
  3009. // Create a notifier server option which will set our htlc notifiers
  3010. // for the three hop network.
  3011. notifierOption := serverOptionWithHtlcNotifier(
  3012. aliceNotifier, bobNotifier, carolNotifier,
  3013. )
  3014. // Add the htlcNotifier option to any other options
  3015. // set in the test.
  3016. options := append(testOpts, notifierOption) // nolint:gocritic
  3017. n := newThreeHopNetwork(
  3018. t, channels.aliceToBob,
  3019. channels.bobToAlice, channels.bobToCarol,
  3020. channels.carolToBob, testStartingHeight,
  3021. options...,
  3022. )
  3023. if err := n.start(); err != nil {
  3024. t.Fatalf("unable to start three hop "+
  3025. "network: %v", err)
  3026. }
  3027. t.Cleanup(n.stop)
  3028. // Before we forward anything, subscribe to htlc events
  3029. // from each notifier.
  3030. aliceEvents, err := aliceNotifier.SubscribeHtlcEvents()
  3031. if err != nil {
  3032. t.Fatalf("could not subscribe to alice's"+
  3033. " events: %v", err)
  3034. }
  3035. t.Cleanup(aliceEvents.Cancel)
  3036. bobEvents, err := bobNotifier.SubscribeHtlcEvents()
  3037. if err != nil {
  3038. t.Fatalf("could not subscribe to bob's"+
  3039. " events: %v", err)
  3040. }
  3041. t.Cleanup(bobEvents.Cancel)
  3042. carolEvents, err := carolNotifier.SubscribeHtlcEvents()
  3043. if err != nil {
  3044. t.Fatalf("could not subscribe to carol's"+
  3045. " events: %v", err)
  3046. }
  3047. t.Cleanup(carolEvents.Cancel)
  3048. // Send multiple payments, as specified by the test to test incrementing
  3049. // of htlc ids.
  3050. for i := 0; i < iterations; i++ {
  3051. // We'll start off by making a payment from
  3052. // Alice -> Bob -> Carol. The preimage, generated
  3053. // by Carol's Invoice is expected in the Settle events
  3054. htlc, hops, preimage := n.sendThreeHopPayment(t)
  3055. alice, bob, carol := getEvents(
  3056. channels, uint64(i), now, htlc, hops, preimage,
  3057. )
  3058. checkHtlcEvents(t, aliceEvents.Updates(), alice)
  3059. checkHtlcEvents(t, bobEvents.Updates(), bob)
  3060. checkHtlcEvents(t, carolEvents.Updates(), carol)
  3061. }
  3062. }
  3063. // checkHtlcEvents checks that a subscription has the set of htlc events
  3064. // we expect it to have.
  3065. func checkHtlcEvents(t *testing.T, events <-chan interface{},
  3066. expectedEvents []interface{}) {
  3067. t.Helper()
  3068. for _, expected := range expectedEvents {
  3069. select {
  3070. case event := <-events:
  3071. if !reflect.DeepEqual(event, expected) {
  3072. t.Fatalf("expected %v, got: %v", expected,
  3073. event)
  3074. }
  3075. case <-time.After(5 * time.Second):
  3076. t.Fatalf("expected event: %v", expected)
  3077. }
  3078. }
  3079. // Check that there are no unexpected events following.
  3080. select {
  3081. case event := <-events:
  3082. t.Fatalf("unexpected event: %v", event)
  3083. default:
  3084. }
  3085. }
  3086. // sendThreeHopPayment is a helper function which sends a payment over
  3087. // Alice -> Bob -> Carol in a three hop network and returns Alice's first htlc
  3088. // and the remainder of the hops.
  3089. func (n *threeHopNetwork) sendThreeHopPayment(t *testing.T) (*lnwire.UpdateAddHTLC,
  3090. []*hop.Payload, *lntypes.Preimage) {
  3091. amount := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin)
  3092. htlcAmt, totalTimelock, hops := generateHops(amount, testStartingHeight,
  3093. n.firstBobChannelLink, n.carolChannelLink)
  3094. blob, err := generateRoute(hops...)
  3095. if err != nil {
  3096. t.Fatal(err)
  3097. }
  3098. invoice, htlc, pid, err := generatePayment(
  3099. amount, htlcAmt, totalTimelock, blob,
  3100. )
  3101. if err != nil {
  3102. t.Fatal(err)
  3103. }
  3104. err = n.carolServer.registry.AddInvoice(
  3105. context.Background(), *invoice, htlc.PaymentHash,
  3106. )
  3107. require.NoError(t, err, "unable to add invoice in carol registry")
  3108. if err := n.aliceServer.htlcSwitch.SendHTLC(
  3109. n.firstBobChannelLink.ShortChanID(), pid, htlc,
  3110. ); err != nil {
  3111. t.Fatalf("could not send htlc")
  3112. }
  3113. return htlc, hops, invoice.Terms.PaymentPreimage
  3114. }
  3115. // getThreeHopEvents gets the set of htlc events that we expect for a payment
  3116. // from Alice -> Bob -> Carol. If a non-nil link error is provided, the set
  3117. // of events will fail on Bob's outgoing link.
  3118. func getThreeHopEvents(channels *clusterChannels, htlcID uint64,
  3119. ts time.Time, htlc *lnwire.UpdateAddHTLC, hops []*hop.Payload,
  3120. linkError *LinkError,
  3121. preimage *lntypes.Preimage) ([]interface{}, []interface{}, []interface{}) {
  3122. aliceKey := HtlcKey{
  3123. IncomingCircuit: zeroCircuit,
  3124. OutgoingCircuit: models.CircuitKey{
  3125. ChanID: channels.aliceToBob.ShortChanID(),
  3126. HtlcID: htlcID,
  3127. },
  3128. }
  3129. // Alice always needs a forwarding event because she initiates the
  3130. // send.
  3131. aliceEvents := []interface{}{
  3132. &ForwardingEvent{
  3133. HtlcKey: aliceKey,
  3134. HtlcInfo: HtlcInfo{
  3135. OutgoingTimeLock: htlc.Expiry,
  3136. OutgoingAmt: htlc.Amount,
  3137. },
  3138. HtlcEventType: HtlcEventTypeSend,
  3139. Timestamp: ts,
  3140. },
  3141. }
  3142. bobKey := HtlcKey{
  3143. IncomingCircuit: models.CircuitKey{
  3144. ChanID: channels.bobToAlice.ShortChanID(),
  3145. HtlcID: htlcID,
  3146. },
  3147. OutgoingCircuit: models.CircuitKey{
  3148. ChanID: channels.bobToCarol.ShortChanID(),
  3149. HtlcID: htlcID,
  3150. },
  3151. }
  3152. bobInfo := HtlcInfo{
  3153. IncomingTimeLock: htlc.Expiry,
  3154. IncomingAmt: htlc.Amount,
  3155. OutgoingTimeLock: hops[1].FwdInfo.OutgoingCTLV,
  3156. OutgoingAmt: hops[1].FwdInfo.AmountToForward,
  3157. }
  3158. // If we expect the payment to fail, we add failures for alice and
  3159. // bob, and no events for carol because the payment never reaches her.
  3160. if linkError != nil {
  3161. aliceEvents = append(aliceEvents,
  3162. &ForwardingFailEvent{
  3163. HtlcKey: aliceKey,
  3164. HtlcEventType: HtlcEventTypeSend,
  3165. Timestamp: ts,
  3166. },
  3167. )
  3168. bobEvents := []interface{}{
  3169. &LinkFailEvent{
  3170. HtlcKey: bobKey,
  3171. HtlcInfo: bobInfo,
  3172. HtlcEventType: HtlcEventTypeForward,
  3173. LinkError: linkError,
  3174. Incoming: false,
  3175. Timestamp: ts,
  3176. },
  3177. &FinalHtlcEvent{
  3178. CircuitKey: bobKey.IncomingCircuit,
  3179. Settled: false,
  3180. Offchain: true,
  3181. Timestamp: ts,
  3182. },
  3183. }
  3184. return aliceEvents, bobEvents, nil
  3185. }
  3186. // If we want to get events for a successful payment, we add a settle
  3187. // for alice, a forward and settle for bob and a receive settle for
  3188. // carol.
  3189. aliceEvents = append(
  3190. aliceEvents,
  3191. &SettleEvent{
  3192. HtlcKey: aliceKey,
  3193. Preimage: *preimage,
  3194. HtlcEventType: HtlcEventTypeSend,
  3195. Timestamp: ts,
  3196. },
  3197. )
  3198. bobEvents := []interface{}{
  3199. &ForwardingEvent{
  3200. HtlcKey: bobKey,
  3201. HtlcInfo: bobInfo,
  3202. HtlcEventType: HtlcEventTypeForward,
  3203. Timestamp: ts,
  3204. },
  3205. &SettleEvent{
  3206. HtlcKey: bobKey,
  3207. Preimage: *preimage,
  3208. HtlcEventType: HtlcEventTypeForward,
  3209. Timestamp: ts,
  3210. },
  3211. &FinalHtlcEvent{
  3212. CircuitKey: bobKey.IncomingCircuit,
  3213. Settled: true,
  3214. Offchain: true,
  3215. Timestamp: ts,
  3216. },
  3217. }
  3218. carolEvents := []interface{}{
  3219. &SettleEvent{
  3220. HtlcKey: HtlcKey{
  3221. IncomingCircuit: models.CircuitKey{
  3222. ChanID: channels.carolToBob.ShortChanID(),
  3223. HtlcID: htlcID,
  3224. },
  3225. OutgoingCircuit: zeroCircuit,
  3226. },
  3227. Preimage: *preimage,
  3228. HtlcEventType: HtlcEventTypeReceive,
  3229. Timestamp: ts,
  3230. }, &FinalHtlcEvent{
  3231. CircuitKey: models.CircuitKey{
  3232. ChanID: channels.carolToBob.ShortChanID(),
  3233. HtlcID: htlcID,
  3234. },
  3235. Settled: true,
  3236. Offchain: true,
  3237. Timestamp: ts,
  3238. },
  3239. }
  3240. return aliceEvents, bobEvents, carolEvents
  3241. }
  3242. type mockForwardInterceptor struct {
  3243. t *testing.T
  3244. interceptedChan chan InterceptedPacket
  3245. }
  3246. func (m *mockForwardInterceptor) InterceptForwardHtlc(
  3247. intercepted InterceptedPacket) error {
  3248. m.interceptedChan <- intercepted
  3249. return nil
  3250. }
  3251. func (m *mockForwardInterceptor) getIntercepted() InterceptedPacket {
  3252. m.t.Helper()
  3253. select {
  3254. case p := <-m.interceptedChan:
  3255. return p
  3256. case <-time.After(time.Second):
  3257. require.Fail(m.t, "timeout")
  3258. return InterceptedPacket{}
  3259. }
  3260. }
  3261. func assertNumCircuits(t *testing.T, s *Switch, pending, opened int) {
  3262. if s.circuits.NumPending() != pending {
  3263. t.Fatalf("wrong amount of half circuits, expected %v but "+
  3264. "got %v", pending, s.circuits.NumPending())
  3265. }
  3266. if s.circuits.NumOpen() != opened {
  3267. t.Fatalf("wrong amount of circuits, expected %v but got %v",
  3268. opened, s.circuits.NumOpen())
  3269. }
  3270. }
  3271. func assertOutgoingLinkReceive(t *testing.T, targetLink *mockChannelLink,
  3272. expectReceive bool) *htlcPacket {
  3273. // Pull packet from targetLink link.
  3274. select {
  3275. case packet := <-targetLink.packets:
  3276. if !expectReceive {
  3277. t.Fatal("forward was intercepted, shouldn't land at bob link")
  3278. } else if err := targetLink.completeCircuit(packet); err != nil {
  3279. t.Fatalf("unable to complete payment circuit: %v", err)
  3280. }
  3281. return packet
  3282. case <-time.After(time.Second):
  3283. if expectReceive {
  3284. t.Fatal("request was not propagated to destination")
  3285. }
  3286. }
  3287. return nil
  3288. }
  3289. func assertOutgoingLinkReceiveIntercepted(t *testing.T,
  3290. targetLink *mockChannelLink) {
  3291. t.Helper()
  3292. select {
  3293. case <-targetLink.packets:
  3294. case <-time.After(time.Second):
  3295. t.Fatal("request was not propagated to destination")
  3296. }
  3297. }
  3298. type interceptableSwitchTestContext struct {
  3299. t *testing.T
  3300. preimage [sha256.Size]byte
  3301. rhash [32]byte
  3302. onionBlob [1366]byte
  3303. incomingHtlcID uint64
  3304. cltvRejectDelta uint32
  3305. cltvInterceptDelta uint32
  3306. forwardInterceptor *mockForwardInterceptor
  3307. aliceChannelLink *mockChannelLink
  3308. bobChannelLink *mockChannelLink
  3309. s *Switch
  3310. }
  3311. func newInterceptableSwitchTestContext(
  3312. t *testing.T) *interceptableSwitchTestContext {
  3313. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  3314. alicePeer, err := newMockServer(
  3315. t, "alice", testStartingHeight, nil, testDefaultDelta,
  3316. )
  3317. require.NoError(t, err, "unable to create alice server")
  3318. bobPeer, err := newMockServer(
  3319. t, "bob", testStartingHeight, nil, testDefaultDelta,
  3320. )
  3321. require.NoError(t, err, "unable to create bob server")
  3322. tempPath := t.TempDir()
  3323. cdb, err := channeldb.Open(tempPath)
  3324. require.NoError(t, err, "unable to open channeldb")
  3325. t.Cleanup(func() { cdb.Close() })
  3326. s, err := initSwitchWithDB(testStartingHeight, cdb)
  3327. require.NoError(t, err, "unable to init switch")
  3328. if err := s.Start(); err != nil {
  3329. t.Fatalf("unable to start switch: %v", err)
  3330. }
  3331. aliceChannelLink := newMockChannelLink(
  3332. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  3333. false, false,
  3334. )
  3335. bobChannelLink := newMockChannelLink(
  3336. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  3337. false,
  3338. )
  3339. if err := s.AddLink(aliceChannelLink); err != nil {
  3340. t.Fatalf("unable to add alice link: %v", err)
  3341. }
  3342. if err := s.AddLink(bobChannelLink); err != nil {
  3343. t.Fatalf("unable to add bob link: %v", err)
  3344. }
  3345. preimage := [sha256.Size]byte{1}
  3346. ctx := &interceptableSwitchTestContext{
  3347. t: t,
  3348. preimage: preimage,
  3349. rhash: sha256.Sum256(preimage[:]),
  3350. onionBlob: [1366]byte{4, 5, 6},
  3351. incomingHtlcID: uint64(0),
  3352. cltvRejectDelta: 10,
  3353. cltvInterceptDelta: 13,
  3354. forwardInterceptor: &mockForwardInterceptor{
  3355. t: t,
  3356. interceptedChan: make(chan InterceptedPacket),
  3357. },
  3358. aliceChannelLink: aliceChannelLink,
  3359. bobChannelLink: bobChannelLink,
  3360. s: s,
  3361. }
  3362. return ctx
  3363. }
  3364. func (c *interceptableSwitchTestContext) createTestPacket() *htlcPacket {
  3365. c.incomingHtlcID++
  3366. return &htlcPacket{
  3367. incomingChanID: c.aliceChannelLink.ShortChanID(),
  3368. incomingHTLCID: c.incomingHtlcID,
  3369. incomingTimeout: testStartingHeight + c.cltvInterceptDelta + 1,
  3370. outgoingChanID: c.bobChannelLink.ShortChanID(),
  3371. obfuscator: NewMockObfuscator(),
  3372. htlc: &lnwire.UpdateAddHTLC{
  3373. PaymentHash: c.rhash,
  3374. Amount: 1,
  3375. OnionBlob: c.onionBlob,
  3376. },
  3377. }
  3378. }
  3379. func (c *interceptableSwitchTestContext) finish() {
  3380. if err := c.s.Stop(); err != nil {
  3381. c.t.Fatalf(err.Error())
  3382. }
  3383. }
  3384. func (c *interceptableSwitchTestContext) createSettlePacket(
  3385. outgoingHTLCID uint64) *htlcPacket {
  3386. return &htlcPacket{
  3387. outgoingChanID: c.bobChannelLink.ShortChanID(),
  3388. outgoingHTLCID: outgoingHTLCID,
  3389. amount: 1,
  3390. htlc: &lnwire.UpdateFulfillHTLC{
  3391. PaymentPreimage: c.preimage,
  3392. },
  3393. }
  3394. }
  3395. func TestSwitchHoldForward(t *testing.T) {
  3396. t.Parallel()
  3397. c := newInterceptableSwitchTestContext(t)
  3398. defer c.finish()
  3399. notifier := &mock.ChainNotifier{
  3400. EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
  3401. }
  3402. notifier.EpochChan <- &chainntnfs.BlockEpoch{Height: testStartingHeight}
  3403. switchForwardInterceptor, err := NewInterceptableSwitch(
  3404. &InterceptableSwitchConfig{
  3405. Switch: c.s,
  3406. CltvRejectDelta: c.cltvRejectDelta,
  3407. CltvInterceptDelta: c.cltvInterceptDelta,
  3408. Notifier: notifier,
  3409. },
  3410. )
  3411. require.NoError(t, err)
  3412. require.NoError(t, switchForwardInterceptor.Start())
  3413. switchForwardInterceptor.SetInterceptor(c.forwardInterceptor.InterceptForwardHtlc)
  3414. linkQuit := make(chan struct{})
  3415. // Test a forward that expires too soon.
  3416. packet := c.createTestPacket()
  3417. packet.incomingTimeout = testStartingHeight + c.cltvRejectDelta - 1
  3418. err = switchForwardInterceptor.ForwardPackets(linkQuit, false, packet)
  3419. require.NoError(t, err, "can't forward htlc packet")
  3420. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3421. assertOutgoingLinkReceiveIntercepted(t, c.aliceChannelLink)
  3422. assertNumCircuits(t, c.s, 0, 0)
  3423. // Test a forward that expires too soon and can't be failed.
  3424. packet = c.createTestPacket()
  3425. packet.incomingTimeout = testStartingHeight + c.cltvRejectDelta - 1
  3426. // Simulate an error during the composition of the failure message.
  3427. currentCallback := c.s.cfg.FetchLastChannelUpdate
  3428. c.s.cfg.FetchLastChannelUpdate = func(
  3429. lnwire.ShortChannelID) (*lnwire.ChannelUpdate, error) {
  3430. return nil, errors.New("cannot fetch update")
  3431. }
  3432. err = switchForwardInterceptor.ForwardPackets(linkQuit, false, packet)
  3433. require.NoError(t, err, "can't forward htlc packet")
  3434. receivedPkt := assertOutgoingLinkReceive(t, c.bobChannelLink, true)
  3435. assertNumCircuits(t, c.s, 1, 1)
  3436. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3437. linkQuit, false,
  3438. c.createSettlePacket(receivedPkt.outgoingHTLCID),
  3439. ))
  3440. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3441. assertNumCircuits(t, c.s, 0, 0)
  3442. c.s.cfg.FetchLastChannelUpdate = currentCallback
  3443. // Test resume a hold forward.
  3444. assertNumCircuits(t, c.s, 0, 0)
  3445. err = switchForwardInterceptor.ForwardPackets(
  3446. linkQuit, false, c.createTestPacket(),
  3447. )
  3448. require.NoError(t, err)
  3449. assertNumCircuits(t, c.s, 0, 0)
  3450. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3451. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3452. Action: FwdActionResume,
  3453. Key: c.forwardInterceptor.getIntercepted().IncomingCircuit,
  3454. }))
  3455. receivedPkt = assertOutgoingLinkReceive(t, c.bobChannelLink, true)
  3456. assertNumCircuits(t, c.s, 1, 1)
  3457. // settling the htlc to close the circuit.
  3458. err = switchForwardInterceptor.ForwardPackets(
  3459. linkQuit, false,
  3460. c.createSettlePacket(receivedPkt.outgoingHTLCID),
  3461. )
  3462. require.NoError(t, err)
  3463. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3464. assertNumCircuits(t, c.s, 0, 0)
  3465. // Test resume a hold forward after disconnection.
  3466. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3467. linkQuit, false, c.createTestPacket(),
  3468. ))
  3469. // Wait until the packet is offered to the interceptor.
  3470. _ = c.forwardInterceptor.getIntercepted()
  3471. // No forward expected yet.
  3472. assertNumCircuits(t, c.s, 0, 0)
  3473. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3474. // Disconnect should resume the forwarding.
  3475. switchForwardInterceptor.SetInterceptor(nil)
  3476. receivedPkt = assertOutgoingLinkReceive(t, c.bobChannelLink, true)
  3477. assertNumCircuits(t, c.s, 1, 1)
  3478. // Settle the htlc to close the circuit.
  3479. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3480. linkQuit, false,
  3481. c.createSettlePacket(receivedPkt.outgoingHTLCID),
  3482. ))
  3483. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3484. assertNumCircuits(t, c.s, 0, 0)
  3485. // Test failing a hold forward
  3486. switchForwardInterceptor.SetInterceptor(
  3487. c.forwardInterceptor.InterceptForwardHtlc,
  3488. )
  3489. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3490. linkQuit, false, c.createTestPacket(),
  3491. ))
  3492. assertNumCircuits(t, c.s, 0, 0)
  3493. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3494. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3495. Action: FwdActionFail,
  3496. Key: c.forwardInterceptor.getIntercepted().IncomingCircuit,
  3497. FailureCode: lnwire.CodeTemporaryChannelFailure,
  3498. }))
  3499. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3500. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3501. assertNumCircuits(t, c.s, 0, 0)
  3502. // Test failing a hold forward with a failure message.
  3503. require.NoError(t,
  3504. switchForwardInterceptor.ForwardPackets(
  3505. linkQuit, false, c.createTestPacket(),
  3506. ),
  3507. )
  3508. assertNumCircuits(t, c.s, 0, 0)
  3509. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3510. reason := lnwire.OpaqueReason([]byte{1, 2, 3})
  3511. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3512. Action: FwdActionFail,
  3513. Key: c.forwardInterceptor.getIntercepted().IncomingCircuit,
  3514. FailureMessage: reason,
  3515. }))
  3516. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3517. packet = assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3518. require.Equal(t, reason, packet.htlc.(*lnwire.UpdateFailHTLC).Reason)
  3519. assertNumCircuits(t, c.s, 0, 0)
  3520. // Test failing a hold forward with a malformed htlc failure.
  3521. err = switchForwardInterceptor.ForwardPackets(
  3522. linkQuit, false, c.createTestPacket(),
  3523. )
  3524. require.NoError(t, err)
  3525. assertNumCircuits(t, c.s, 0, 0)
  3526. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3527. code := lnwire.CodeInvalidOnionKey
  3528. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3529. Action: FwdActionFail,
  3530. Key: c.forwardInterceptor.getIntercepted().IncomingCircuit,
  3531. FailureCode: code,
  3532. }))
  3533. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3534. packet = assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3535. failPacket := packet.htlc.(*lnwire.UpdateFailHTLC)
  3536. shaOnionBlob := sha256.Sum256(c.onionBlob[:])
  3537. expectedFailure := &lnwire.FailInvalidOnionKey{
  3538. OnionSHA256: shaOnionBlob,
  3539. }
  3540. fwdErr, err := newMockDeobfuscator().DecryptError(failPacket.Reason)
  3541. require.NoError(t, err)
  3542. require.Equal(t, expectedFailure, fwdErr.WireMessage())
  3543. assertNumCircuits(t, c.s, 0, 0)
  3544. // Test settling a hold forward
  3545. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3546. linkQuit, false, c.createTestPacket(),
  3547. ))
  3548. assertNumCircuits(t, c.s, 0, 0)
  3549. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3550. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3551. Key: c.forwardInterceptor.getIntercepted().IncomingCircuit,
  3552. Action: FwdActionSettle,
  3553. Preimage: c.preimage,
  3554. }))
  3555. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3556. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3557. assertNumCircuits(t, c.s, 0, 0)
  3558. require.NoError(t, switchForwardInterceptor.Stop())
  3559. // Test always-on interception.
  3560. notifier = &mock.ChainNotifier{
  3561. EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
  3562. }
  3563. notifier.EpochChan <- &chainntnfs.BlockEpoch{Height: testStartingHeight}
  3564. switchForwardInterceptor, err = NewInterceptableSwitch(
  3565. &InterceptableSwitchConfig{
  3566. Switch: c.s,
  3567. CltvRejectDelta: c.cltvRejectDelta,
  3568. CltvInterceptDelta: c.cltvInterceptDelta,
  3569. RequireInterceptor: true,
  3570. Notifier: notifier,
  3571. },
  3572. )
  3573. require.NoError(t, err)
  3574. require.NoError(t, switchForwardInterceptor.Start())
  3575. // Forward a fresh packet. It is expected to be failed immediately,
  3576. // because there is no interceptor registered.
  3577. require.NoError(t, switchForwardInterceptor.ForwardPackets(
  3578. linkQuit, false, c.createTestPacket(),
  3579. ))
  3580. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3581. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3582. assertNumCircuits(t, c.s, 0, 0)
  3583. // Forward a replayed packet. It is expected to be held until the
  3584. // interceptor connects. To continue the test, it needs to be ran in a
  3585. // goroutine.
  3586. errChan := make(chan error)
  3587. go func() {
  3588. errChan <- switchForwardInterceptor.ForwardPackets(
  3589. linkQuit, true, c.createTestPacket(),
  3590. )
  3591. }()
  3592. // Assert that nothing is forward to the switch.
  3593. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3594. assertNumCircuits(t, c.s, 0, 0)
  3595. // Register an interceptor.
  3596. switchForwardInterceptor.SetInterceptor(
  3597. c.forwardInterceptor.InterceptForwardHtlc,
  3598. )
  3599. // Expect the ForwardPackets call to unblock.
  3600. require.NoError(t, <-errChan)
  3601. // Now expect the queued packet to come through.
  3602. c.forwardInterceptor.getIntercepted()
  3603. // Disconnect and reconnect interceptor.
  3604. switchForwardInterceptor.SetInterceptor(nil)
  3605. switchForwardInterceptor.SetInterceptor(
  3606. c.forwardInterceptor.InterceptForwardHtlc,
  3607. )
  3608. // A replay of the held packet is expected.
  3609. intercepted := c.forwardInterceptor.getIntercepted()
  3610. // Settle the packet.
  3611. require.NoError(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3612. Key: intercepted.IncomingCircuit,
  3613. Action: FwdActionSettle,
  3614. Preimage: c.preimage,
  3615. }))
  3616. assertOutgoingLinkReceive(t, c.bobChannelLink, false)
  3617. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3618. assertNumCircuits(t, c.s, 0, 0)
  3619. require.NoError(t, switchForwardInterceptor.Stop())
  3620. select {
  3621. case <-c.forwardInterceptor.interceptedChan:
  3622. require.Fail(t, "unexpected interception")
  3623. default:
  3624. }
  3625. }
  3626. func TestInterceptableSwitchWatchDog(t *testing.T) {
  3627. t.Parallel()
  3628. c := newInterceptableSwitchTestContext(t)
  3629. defer c.finish()
  3630. // Start interceptable switch.
  3631. notifier := &mock.ChainNotifier{
  3632. EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
  3633. }
  3634. notifier.EpochChan <- &chainntnfs.BlockEpoch{Height: testStartingHeight}
  3635. switchForwardInterceptor, err := NewInterceptableSwitch(
  3636. &InterceptableSwitchConfig{
  3637. Switch: c.s,
  3638. CltvRejectDelta: c.cltvRejectDelta,
  3639. CltvInterceptDelta: c.cltvInterceptDelta,
  3640. Notifier: notifier,
  3641. },
  3642. )
  3643. require.NoError(t, err)
  3644. require.NoError(t, switchForwardInterceptor.Start())
  3645. // Set interceptor.
  3646. switchForwardInterceptor.SetInterceptor(
  3647. c.forwardInterceptor.InterceptForwardHtlc,
  3648. )
  3649. // Receive a packet.
  3650. linkQuit := make(chan struct{})
  3651. packet := c.createTestPacket()
  3652. err = switchForwardInterceptor.ForwardPackets(linkQuit, false, packet)
  3653. require.NoError(t, err, "can't forward htlc packet")
  3654. // Intercept the packet.
  3655. intercepted := c.forwardInterceptor.getIntercepted()
  3656. require.Equal(t,
  3657. int32(packet.incomingTimeout-c.cltvRejectDelta),
  3658. intercepted.AutoFailHeight,
  3659. )
  3660. // Htlc expires before a resolution from the interceptor.
  3661. notifier.EpochChan <- &chainntnfs.BlockEpoch{
  3662. Height: int32(packet.incomingTimeout) -
  3663. int32(c.cltvRejectDelta),
  3664. }
  3665. // Expect the htlc to be failed back.
  3666. assertOutgoingLinkReceive(t, c.aliceChannelLink, true)
  3667. // It is too late now to resolve. Expect an error.
  3668. require.Error(t, switchForwardInterceptor.Resolve(&FwdResolution{
  3669. Action: FwdActionSettle,
  3670. Key: intercepted.IncomingCircuit,
  3671. Preimage: c.preimage,
  3672. }))
  3673. }
  3674. // TestSwitchDustForwarding tests that the switch properly fails HTLC's which
  3675. // have incoming or outgoing links that breach their dust thresholds.
  3676. func TestSwitchDustForwarding(t *testing.T) {
  3677. t.Parallel()
  3678. // We'll create a three-hop network:
  3679. // - Alice has a dust limit of 200sats with Bob
  3680. // - Bob has a dust limit of 800sats with Alice
  3681. // - Bob has a dust limit of 200sats with Carol
  3682. // - Carol has a dust limit of 800sats with Bob
  3683. channels, _, err := createClusterChannels(
  3684. t, btcutil.SatoshiPerBitcoin, btcutil.SatoshiPerBitcoin,
  3685. )
  3686. require.NoError(t, err)
  3687. n := newThreeHopNetwork(
  3688. t, channels.aliceToBob, channels.bobToAlice,
  3689. channels.bobToCarol, channels.carolToBob, testStartingHeight,
  3690. )
  3691. err = n.start()
  3692. require.NoError(t, err)
  3693. // We'll also put Alice and Bob into hodl.ExitSettle mode, such that
  3694. // they won't settle incoming exit-hop HTLC's automatically.
  3695. n.aliceChannelLink.cfg.HodlMask = hodl.ExitSettle.Mask()
  3696. n.firstBobChannelLink.cfg.HodlMask = hodl.ExitSettle.Mask()
  3697. // We'll test that once the default threshold is exceeded on the
  3698. // Alice -> Bob channel, either side's calls to SendHTLC will fail.
  3699. //
  3700. // Alice will send 357 HTLC's of 700sats. Bob will also send 357 HTLC's
  3701. // of 700sats. If either side attempts to send a dust HTLC, it will
  3702. // fail so amounts below 800sats will breach the dust threshold.
  3703. amt := lnwire.NewMSatFromSatoshis(700)
  3704. aliceBobFirstHop := n.aliceChannelLink.ShortChanID()
  3705. sendDustHtlcs(t, n, true, amt, aliceBobFirstHop)
  3706. sendDustHtlcs(t, n, false, amt, aliceBobFirstHop)
  3707. // Generate the parameters needed for Bob to send another dust HTLC.
  3708. _, timelock, hops := generateHops(
  3709. amt, testStartingHeight, n.aliceChannelLink,
  3710. )
  3711. blob, err := generateRoute(hops...)
  3712. require.NoError(t, err)
  3713. // Assert that if Bob sends a dust HTLC it will fail.
  3714. failingPreimage := lntypes.Preimage{0, 0, 3}
  3715. failingHash := failingPreimage.Hash()
  3716. failingHtlc := &lnwire.UpdateAddHTLC{
  3717. PaymentHash: failingHash,
  3718. Amount: amt,
  3719. Expiry: timelock,
  3720. OnionBlob: blob,
  3721. }
  3722. checkAlmostDust := func(link *channelLink, mbox MailBox,
  3723. remote bool) bool {
  3724. timeout := time.After(15 * time.Second)
  3725. pollInterval := 300 * time.Millisecond
  3726. expectedDust := 357 * 2 * amt
  3727. for {
  3728. <-time.After(pollInterval)
  3729. select {
  3730. case <-timeout:
  3731. return false
  3732. default:
  3733. }
  3734. linkDust := link.getDustSum(remote)
  3735. localMailDust, remoteMailDust := mbox.DustPackets()
  3736. totalDust := linkDust
  3737. if remote {
  3738. totalDust += remoteMailDust
  3739. } else {
  3740. totalDust += localMailDust
  3741. }
  3742. if totalDust == expectedDust {
  3743. break
  3744. }
  3745. }
  3746. return true
  3747. }
  3748. // Wait until Bob is almost at the dust threshold.
  3749. bobMbox := n.bobServer.htlcSwitch.mailOrchestrator.GetOrCreateMailBox(
  3750. n.firstBobChannelLink.ChanID(),
  3751. n.firstBobChannelLink.ShortChanID(),
  3752. )
  3753. require.True(t, checkAlmostDust(n.firstBobChannelLink, bobMbox, false))
  3754. // Assert that the HTLC is failed due to the dust threshold.
  3755. err = n.bobServer.htlcSwitch.SendHTLC(
  3756. aliceBobFirstHop, uint64(357), failingHtlc,
  3757. )
  3758. require.ErrorIs(t, err, errDustThresholdExceeded)
  3759. // Generate the parameters needed for bob to send a non-dust HTLC.
  3760. nondustAmt := lnwire.NewMSatFromSatoshis(10_000)
  3761. _, _, hops = generateHops(
  3762. nondustAmt, testStartingHeight, n.aliceChannelLink,
  3763. )
  3764. blob, err = generateRoute(hops...)
  3765. require.NoError(t, err)
  3766. // Now attempt to send an HTLC above Bob's dust limit. It should
  3767. // succeed.
  3768. nondustPreimage := lntypes.Preimage{0, 0, 4}
  3769. nondustHash := nondustPreimage.Hash()
  3770. nondustHtlc := &lnwire.UpdateAddHTLC{
  3771. PaymentHash: nondustHash,
  3772. Amount: nondustAmt,
  3773. Expiry: timelock,
  3774. OnionBlob: blob,
  3775. }
  3776. // Assert that SendHTLC succeeds and evaluateDustThreshold returns
  3777. // false.
  3778. err = n.bobServer.htlcSwitch.SendHTLC(
  3779. aliceBobFirstHop, uint64(358), nondustHtlc,
  3780. )
  3781. require.NoError(t, err)
  3782. // Introduce Carol into the mix and assert that sending a multi-hop
  3783. // dust HTLC to Alice will fail. Bob should fail back the HTLC with a
  3784. // temporary channel failure.
  3785. carolAmt, carolTimelock, carolHops := generateHops(
  3786. amt, testStartingHeight, n.secondBobChannelLink,
  3787. n.aliceChannelLink,
  3788. )
  3789. carolBlob, err := generateRoute(carolHops...)
  3790. require.NoError(t, err)
  3791. carolPreimage := lntypes.Preimage{0, 0, 5}
  3792. carolHash := carolPreimage.Hash()
  3793. carolHtlc := &lnwire.UpdateAddHTLC{
  3794. PaymentHash: carolHash,
  3795. Amount: carolAmt,
  3796. Expiry: carolTimelock,
  3797. OnionBlob: carolBlob,
  3798. }
  3799. // Initialize Carol's attempt ID.
  3800. carolAttemptID := 0
  3801. err = n.carolServer.htlcSwitch.SendHTLC(
  3802. n.carolChannelLink.ShortChanID(), uint64(carolAttemptID),
  3803. carolHtlc,
  3804. )
  3805. require.NoError(t, err)
  3806. carolAttemptID++
  3807. carolResultChan, err := n.carolServer.htlcSwitch.GetAttemptResult(
  3808. uint64(carolAttemptID-1), carolHash, newMockDeobfuscator(),
  3809. )
  3810. require.NoError(t, err)
  3811. result, ok := <-carolResultChan
  3812. require.True(t, ok)
  3813. assertFailureCode(
  3814. t, result.Error, lnwire.CodeTemporaryChannelFailure,
  3815. )
  3816. // Send an HTLC from Alice to Carol and assert that it is failed at the
  3817. // call to SendHTLC.
  3818. htlcAmt, totalTimelock, aliceHops := generateHops(
  3819. amt, testStartingHeight, n.firstBobChannelLink,
  3820. n.carolChannelLink,
  3821. )
  3822. blob, err = generateRoute(aliceHops...)
  3823. require.NoError(t, err)
  3824. aliceMultihopPreimage := lntypes.Preimage{0, 0, 6}
  3825. aliceMultihopHash := aliceMultihopPreimage.Hash()
  3826. aliceMultihopHtlc := &lnwire.UpdateAddHTLC{
  3827. PaymentHash: aliceMultihopHash,
  3828. Amount: htlcAmt,
  3829. Expiry: totalTimelock,
  3830. OnionBlob: blob,
  3831. }
  3832. // Wait until Alice's expected dust for the remote commitment is just
  3833. // under the dust threshold.
  3834. aliceOrch := n.aliceServer.htlcSwitch.mailOrchestrator
  3835. aliceMbox := aliceOrch.GetOrCreateMailBox(
  3836. n.aliceChannelLink.ChanID(), n.aliceChannelLink.ShortChanID(),
  3837. )
  3838. require.True(t, checkAlmostDust(n.aliceChannelLink, aliceMbox, true))
  3839. err = n.aliceServer.htlcSwitch.SendHTLC(
  3840. n.aliceChannelLink.ShortChanID(), uint64(357),
  3841. aliceMultihopHtlc,
  3842. )
  3843. require.ErrorIs(t, err, errDustThresholdExceeded)
  3844. }
  3845. // sendDustHtlcs is a helper function used to send many dust HTLC's to test the
  3846. // Switch's dust-threshold logic. It takes a boolean denoting whether or not
  3847. // Alice is the sender.
  3848. func sendDustHtlcs(t *testing.T, n *threeHopNetwork, alice bool,
  3849. amt lnwire.MilliSatoshi, sid lnwire.ShortChannelID) {
  3850. t.Helper()
  3851. // The number of dust HTLC's we'll send for both Alice and Bob.
  3852. numHTLCs := 357
  3853. // Extract the destination into a variable. If alice is the sender, the
  3854. // destination is Bob.
  3855. destLink := n.aliceChannelLink
  3856. if alice {
  3857. destLink = n.firstBobChannelLink
  3858. }
  3859. // Create hops that will be used in the onion payload.
  3860. htlcAmt, totalTimelock, hops := generateHops(
  3861. amt, testStartingHeight, destLink,
  3862. )
  3863. // Convert the hops to a blob that will be put in the Add message.
  3864. blob, err := generateRoute(hops...)
  3865. require.NoError(t, err)
  3866. // Create a slice to store the preimages.
  3867. preimages := make([]lntypes.Preimage, numHTLCs)
  3868. // Initialize the attempt ID used in SendHTLC calls.
  3869. attemptID := uint64(0)
  3870. // Deterministically generate preimages. Avoid the all-zeroes preimage
  3871. // because that will be rejected by the database. We'll use a different
  3872. // third byte for Alice and Bob.
  3873. endByte := byte(2)
  3874. if alice {
  3875. endByte = byte(3)
  3876. }
  3877. for i := 0; i < numHTLCs; i++ {
  3878. preimages[i] = lntypes.Preimage{byte(i >> 8), byte(i), endByte}
  3879. }
  3880. sendingSwitch := n.bobServer.htlcSwitch
  3881. if alice {
  3882. sendingSwitch = n.aliceServer.htlcSwitch
  3883. }
  3884. // Call SendHTLC in a loop for numHTLCs.
  3885. for i := 0; i < numHTLCs; i++ {
  3886. // Construct the htlc packet.
  3887. hash := preimages[i].Hash()
  3888. htlc := &lnwire.UpdateAddHTLC{
  3889. PaymentHash: hash,
  3890. Amount: htlcAmt,
  3891. Expiry: totalTimelock,
  3892. OnionBlob: blob,
  3893. }
  3894. for {
  3895. // It may be the case that the dust threshold is hit
  3896. // before all 357*2 HTLC's are sent due to double
  3897. // counting. Get around this by continuing to send
  3898. // until successful.
  3899. err = sendingSwitch.SendHTLC(sid, attemptID, htlc)
  3900. if err == nil {
  3901. break
  3902. }
  3903. }
  3904. attemptID++
  3905. }
  3906. }
  3907. // TestSwitchMailboxDust tests that the switch takes into account the mailbox
  3908. // dust when evaluating the dust threshold. The mockChannelLink does not have
  3909. // channel state, so this only tests the switch-mailbox interaction.
  3910. func TestSwitchMailboxDust(t *testing.T) {
  3911. t.Parallel()
  3912. alicePeer, err := newMockServer(
  3913. t, "alice", testStartingHeight, nil, testDefaultDelta,
  3914. )
  3915. require.NoError(t, err)
  3916. bobPeer, err := newMockServer(
  3917. t, "bob", testStartingHeight, nil, testDefaultDelta,
  3918. )
  3919. require.NoError(t, err)
  3920. carolPeer, err := newMockServer(
  3921. t, "carol", testStartingHeight, nil, testDefaultDelta,
  3922. )
  3923. require.NoError(t, err)
  3924. s, err := initSwitchWithTempDB(t, testStartingHeight)
  3925. require.NoError(t, err)
  3926. err = s.Start()
  3927. require.NoError(t, err)
  3928. defer func() {
  3929. _ = s.Stop()
  3930. }()
  3931. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  3932. chanID3, carolChanID := genID()
  3933. aliceLink := newMockChannelLink(
  3934. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  3935. false, false,
  3936. )
  3937. err = s.AddLink(aliceLink)
  3938. require.NoError(t, err)
  3939. bobLink := newMockChannelLink(
  3940. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  3941. false,
  3942. )
  3943. err = s.AddLink(bobLink)
  3944. require.NoError(t, err)
  3945. carolLink := newMockChannelLink(
  3946. s, chanID3, carolChanID, emptyScid, carolPeer, true, false,
  3947. false, false,
  3948. )
  3949. err = s.AddLink(carolLink)
  3950. require.NoError(t, err)
  3951. // mockChannelLink sets the local and remote dust limits of the mailbox
  3952. // to 400 satoshis and the feerate to 0. We'll fill the mailbox up with
  3953. // dust packets and assert that calls to SendHTLC will fail.
  3954. preimage, err := genPreimage()
  3955. require.NoError(t, err)
  3956. rhash := sha256.Sum256(preimage[:])
  3957. amt := lnwire.NewMSatFromSatoshis(350)
  3958. addMsg := &lnwire.UpdateAddHTLC{
  3959. PaymentHash: rhash,
  3960. Amount: amt,
  3961. ChanID: chanID1,
  3962. }
  3963. // Initialize the carolHTLCID.
  3964. var carolHTLCID uint64
  3965. // It will take aliceCount HTLC's of 350sats to fill up Alice's mailbox
  3966. // to the point where another would put Alice over the dust threshold.
  3967. aliceCount := 1428
  3968. mailbox := s.mailOrchestrator.GetOrCreateMailBox(chanID1, aliceChanID)
  3969. for i := 0; i < aliceCount; i++ {
  3970. alicePkt := &htlcPacket{
  3971. incomingChanID: carolChanID,
  3972. incomingHTLCID: carolHTLCID,
  3973. outgoingChanID: aliceChanID,
  3974. obfuscator: NewMockObfuscator(),
  3975. incomingAmount: amt,
  3976. amount: amt,
  3977. htlc: addMsg,
  3978. }
  3979. err = mailbox.AddPacket(alicePkt)
  3980. require.NoError(t, err)
  3981. carolHTLCID++
  3982. }
  3983. // Sending one more HTLC to Alice should result in the dust threshold
  3984. // being breached.
  3985. err = s.SendHTLC(aliceChanID, 0, addMsg)
  3986. require.ErrorIs(t, err, errDustThresholdExceeded)
  3987. // We'll now call ForwardPackets from Bob to ensure that the mailbox
  3988. // sum is also accounted for in the forwarding case.
  3989. packet := &htlcPacket{
  3990. incomingChanID: bobChanID,
  3991. incomingHTLCID: 0,
  3992. outgoingChanID: aliceChanID,
  3993. obfuscator: NewMockObfuscator(),
  3994. incomingAmount: amt,
  3995. amount: amt,
  3996. htlc: &lnwire.UpdateAddHTLC{
  3997. PaymentHash: rhash,
  3998. Amount: amt,
  3999. ChanID: chanID1,
  4000. },
  4001. }
  4002. err = s.ForwardPackets(nil, packet)
  4003. require.NoError(t, err)
  4004. // Bob should receive a failure from the switch.
  4005. select {
  4006. case p := <-bobLink.packets:
  4007. require.NotEmpty(t, p.linkFailure)
  4008. assertFailureCode(
  4009. t, p.linkFailure, lnwire.CodeTemporaryChannelFailure,
  4010. )
  4011. case <-time.After(5 * time.Second):
  4012. t.Fatal("no timely reply from switch")
  4013. }
  4014. }
  4015. // TestSwitchResolution checks the ability of the switch to persist and handle
  4016. // resolution messages.
  4017. func TestSwitchResolution(t *testing.T) {
  4018. t.Parallel()
  4019. alicePeer, err := newMockServer(
  4020. t, "alice", testStartingHeight, nil, testDefaultDelta,
  4021. )
  4022. require.NoError(t, err)
  4023. bobPeer, err := newMockServer(
  4024. t, "bob", testStartingHeight, nil, testDefaultDelta,
  4025. )
  4026. require.NoError(t, err)
  4027. s, err := initSwitchWithTempDB(t, testStartingHeight)
  4028. require.NoError(t, err)
  4029. // Even though we intend to Stop s later in the test, it is safe to
  4030. // defer this Stop since its execution it is protected by an atomic
  4031. // guard, guaranteeing it executes at most once.
  4032. t.Cleanup(func() { var _ = s.Stop() })
  4033. err = s.Start()
  4034. require.NoError(t, err)
  4035. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  4036. aliceChannelLink := newMockChannelLink(
  4037. s, chanID1, aliceChanID, emptyScid, alicePeer, true, false,
  4038. false, false,
  4039. )
  4040. bobChannelLink := newMockChannelLink(
  4041. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  4042. false,
  4043. )
  4044. err = s.AddLink(aliceChannelLink)
  4045. require.NoError(t, err)
  4046. err = s.AddLink(bobChannelLink)
  4047. require.NoError(t, err)
  4048. // Create an add htlcPacket that Alice will send to Bob.
  4049. preimage, err := genPreimage()
  4050. require.NoError(t, err)
  4051. rhash := sha256.Sum256(preimage[:])
  4052. packet := &htlcPacket{
  4053. incomingChanID: aliceChannelLink.ShortChanID(),
  4054. incomingHTLCID: 0,
  4055. outgoingChanID: bobChannelLink.ShortChanID(),
  4056. obfuscator: NewMockObfuscator(),
  4057. htlc: &lnwire.UpdateAddHTLC{
  4058. PaymentHash: rhash,
  4059. Amount: 1,
  4060. },
  4061. }
  4062. err = s.ForwardPackets(nil, packet)
  4063. require.NoError(t, err)
  4064. // Bob will receive the packet and open the circuit.
  4065. select {
  4066. case <-bobChannelLink.packets:
  4067. err = bobChannelLink.completeCircuit(packet)
  4068. require.NoError(t, err)
  4069. case <-time.After(time.Second):
  4070. t.Fatal("request was not propagated to destination")
  4071. }
  4072. // Check that only one circuit is open.
  4073. require.Equal(t, 1, s.circuits.NumOpen())
  4074. // We'll send a settle resolution to Switch that should go to Alice.
  4075. settleResMsg := contractcourt.ResolutionMsg{
  4076. SourceChan: bobChanID,
  4077. HtlcIndex: 0,
  4078. PreImage: &preimage,
  4079. }
  4080. // Before the resolution is sent, remove alice's link so we can assert
  4081. // that the resolution is actually stored. Otherwise, it would be
  4082. // deleted shortly after being sent.
  4083. s.RemoveLink(chanID1)
  4084. // Send the resolution message.
  4085. err = s.ProcessContractResolution(settleResMsg)
  4086. require.NoError(t, err)
  4087. // Assert that the resolution store contains the settle reoslution.
  4088. resMsgs, err := s.resMsgStore.fetchAllResolutionMsg()
  4089. require.NoError(t, err)
  4090. require.Equal(t, 1, len(resMsgs))
  4091. require.Equal(t, settleResMsg.SourceChan, resMsgs[0].SourceChan)
  4092. require.Equal(t, settleResMsg.HtlcIndex, resMsgs[0].HtlcIndex)
  4093. require.Nil(t, resMsgs[0].Failure)
  4094. require.Equal(t, preimage, *resMsgs[0].PreImage)
  4095. // Now we'll restart Alice's link and delete the circuit.
  4096. err = s.AddLink(aliceChannelLink)
  4097. require.NoError(t, err)
  4098. // Alice will receive the packet and open the circuit.
  4099. select {
  4100. case alicePkt := <-aliceChannelLink.packets:
  4101. err = aliceChannelLink.completeCircuit(alicePkt)
  4102. require.NoError(t, err)
  4103. case <-time.After(time.Second):
  4104. t.Fatal("request was not propagated to destination")
  4105. }
  4106. // Assert that there are no more circuits.
  4107. require.Equal(t, 0, s.circuits.NumOpen())
  4108. // We'll restart the Switch and assert that Alice does not receive
  4109. // another packet.
  4110. switchDB := s.cfg.DB.(*channeldb.DB)
  4111. err = s.Stop()
  4112. require.NoError(t, err)
  4113. s, err = initSwitchWithDB(testStartingHeight, switchDB)
  4114. require.NoError(t, err)
  4115. err = s.Start()
  4116. require.NoError(t, err)
  4117. defer func() {
  4118. _ = s.Stop()
  4119. }()
  4120. err = s.AddLink(aliceChannelLink)
  4121. require.NoError(t, err)
  4122. err = s.AddLink(bobChannelLink)
  4123. require.NoError(t, err)
  4124. // Alice should not receive a packet since the Switch should have
  4125. // deleted the resolution message since the circuit was closed.
  4126. select {
  4127. case alicePkt := <-aliceChannelLink.packets:
  4128. t.Fatalf("received erroneous packet: %v", alicePkt)
  4129. case <-time.After(time.Second * 5):
  4130. }
  4131. // Check that the resolution message no longer exists in the store.
  4132. resMsgs, err = s.resMsgStore.fetchAllResolutionMsg()
  4133. require.NoError(t, err)
  4134. require.Equal(t, 0, len(resMsgs))
  4135. }
  4136. // TestSwitchForwardFailAlias tests that if ForwardPackets returns a failure
  4137. // before actually forwarding, the ChannelUpdate uses the SCID from the
  4138. // incoming channel and does not leak private information like the UTXO.
  4139. func TestSwitchForwardFailAlias(t *testing.T) {
  4140. tests := []struct {
  4141. name string
  4142. // Whether or not Alice will be a zero-conf channel or an
  4143. // option-scid-alias channel (feature-bit).
  4144. zeroConf bool
  4145. }{
  4146. {
  4147. name: "option-scid-alias forwarding failure",
  4148. zeroConf: false,
  4149. },
  4150. {
  4151. name: "zero-conf forwarding failure",
  4152. zeroConf: true,
  4153. },
  4154. }
  4155. for _, test := range tests {
  4156. test := test
  4157. t.Run(test.name, func(t *testing.T) {
  4158. testSwitchForwardFailAlias(t, test.zeroConf)
  4159. })
  4160. }
  4161. }
  4162. func testSwitchForwardFailAlias(t *testing.T, zeroConf bool) {
  4163. t.Parallel()
  4164. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  4165. alicePeer, err := newMockServer(
  4166. t, "alice", testStartingHeight, nil, testDefaultDelta,
  4167. )
  4168. require.NoError(t, err)
  4169. bobPeer, err := newMockServer(
  4170. t, "bob", testStartingHeight, nil, testDefaultDelta,
  4171. )
  4172. require.NoError(t, err)
  4173. tempPath := t.TempDir()
  4174. cdb, err := channeldb.Open(tempPath)
  4175. require.NoError(t, err)
  4176. t.Cleanup(func() { cdb.Close() })
  4177. s, err := initSwitchWithDB(testStartingHeight, cdb)
  4178. require.NoError(t, err)
  4179. err = s.Start()
  4180. require.NoError(t, err)
  4181. // Make Alice's channel zero-conf or option-scid-alias (feature bit).
  4182. aliceAlias := lnwire.ShortChannelID{
  4183. BlockHeight: 16_000_000,
  4184. TxIndex: 5,
  4185. TxPosition: 5,
  4186. }
  4187. var aliceLink *mockChannelLink
  4188. if zeroConf {
  4189. aliceLink = newMockChannelLink(
  4190. s, chanID1, aliceAlias, aliceChanID, alicePeer, true,
  4191. true, true, false,
  4192. )
  4193. } else {
  4194. aliceLink = newMockChannelLink(
  4195. s, chanID1, aliceChanID, emptyScid, alicePeer, true,
  4196. true, false, true,
  4197. )
  4198. aliceLink.addAlias(aliceAlias)
  4199. }
  4200. err = s.AddLink(aliceLink)
  4201. require.NoError(t, err)
  4202. bobLink := newMockChannelLink(
  4203. s, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  4204. false,
  4205. )
  4206. err = s.AddLink(bobLink)
  4207. require.NoError(t, err)
  4208. // Create a packet that will be sent from Alice to Bob via the switch.
  4209. preimage := [sha256.Size]byte{1}
  4210. rhash := sha256.Sum256(preimage[:])
  4211. ogPacket := &htlcPacket{
  4212. incomingChanID: aliceLink.ShortChanID(),
  4213. incomingHTLCID: 0,
  4214. outgoingChanID: bobLink.ShortChanID(),
  4215. obfuscator: NewMockObfuscator(),
  4216. htlc: &lnwire.UpdateAddHTLC{
  4217. PaymentHash: rhash,
  4218. Amount: 1,
  4219. },
  4220. }
  4221. // Forward the packet and check that Bob's channel link received it.
  4222. err = s.ForwardPackets(nil, ogPacket)
  4223. require.NoError(t, err)
  4224. // Assert that the circuits are in the expected state.
  4225. require.Equal(t, 1, s.circuits.NumPending())
  4226. require.Equal(t, 0, s.circuits.NumOpen())
  4227. // Pull packet from Bob's link, and do nothing with it.
  4228. select {
  4229. case <-bobLink.packets:
  4230. case <-s.quit:
  4231. t.Fatal("switch shutting down, failed to forward packet")
  4232. }
  4233. // Now we will restart the Switch to trigger the LoadedFromDisk logic.
  4234. err = s.Stop()
  4235. require.NoError(t, err)
  4236. err = cdb.Close()
  4237. require.NoError(t, err)
  4238. cdb2, err := channeldb.Open(tempPath)
  4239. require.NoError(t, err)
  4240. t.Cleanup(func() { cdb2.Close() })
  4241. s2, err := initSwitchWithDB(testStartingHeight, cdb2)
  4242. require.NoError(t, err)
  4243. err = s2.Start()
  4244. require.NoError(t, err)
  4245. defer func() {
  4246. _ = s2.Stop()
  4247. }()
  4248. var aliceLink2 *mockChannelLink
  4249. if zeroConf {
  4250. aliceLink2 = newMockChannelLink(
  4251. s2, chanID1, aliceAlias, aliceChanID, alicePeer, true,
  4252. true, true, false,
  4253. )
  4254. } else {
  4255. aliceLink2 = newMockChannelLink(
  4256. s2, chanID1, aliceChanID, emptyScid, alicePeer, true,
  4257. true, false, true,
  4258. )
  4259. aliceLink2.addAlias(aliceAlias)
  4260. }
  4261. err = s2.AddLink(aliceLink2)
  4262. require.NoError(t, err)
  4263. bobLink2 := newMockChannelLink(
  4264. s2, chanID2, bobChanID, emptyScid, bobPeer, true, false, false,
  4265. false,
  4266. )
  4267. err = s2.AddLink(bobLink2)
  4268. require.NoError(t, err)
  4269. // Reforward the ogPacket and wait for Alice to receive a failure
  4270. // packet.
  4271. err = s2.ForwardPackets(nil, ogPacket)
  4272. require.NoError(t, err)
  4273. select {
  4274. case failPacket := <-aliceLink2.packets:
  4275. // Assert that the failPacket does not leak UTXO information.
  4276. // This means checking that aliceChanID was not returned.
  4277. msg := failPacket.linkFailure.msg
  4278. failMsg, ok := msg.(*lnwire.FailTemporaryChannelFailure)
  4279. require.True(t, ok)
  4280. require.Equal(t, aliceAlias, failMsg.Update.ShortChannelID)
  4281. case <-s2.quit:
  4282. t.Fatal("switch shutting down, failed to forward packet")
  4283. }
  4284. }
  4285. // TestSwitchAliasFailAdd tests that the mailbox does not leak UTXO information
  4286. // when failing back an HTLC due to the 5-second timeout. This is tested in the
  4287. // switch rather than the mailbox because the mailbox tests do not have the
  4288. // proper context (e.g. the Switch's failAliasUpdate function). The caveat here
  4289. // is that if the private UTXO is already known, it is fine to send a failure
  4290. // back. This tests option-scid-alias (feature-bit) and zero-conf channels.
  4291. func TestSwitchAliasFailAdd(t *testing.T) {
  4292. tests := []struct {
  4293. name string
  4294. // Denotes whether the opened channel will be zero-conf.
  4295. zeroConf bool
  4296. // Denotes whether the opened channel will be private.
  4297. private bool
  4298. // Denotes whether an alias was used during forwarding.
  4299. useAlias bool
  4300. }{
  4301. {
  4302. name: "public zero-conf using alias",
  4303. zeroConf: true,
  4304. private: false,
  4305. useAlias: true,
  4306. },
  4307. {
  4308. name: "public zero-conf using real",
  4309. zeroConf: true,
  4310. private: false,
  4311. useAlias: true,
  4312. },
  4313. {
  4314. name: "private zero-conf using alias",
  4315. zeroConf: true,
  4316. private: true,
  4317. useAlias: true,
  4318. },
  4319. {
  4320. name: "public option-scid-alias using alias",
  4321. zeroConf: false,
  4322. private: false,
  4323. useAlias: true,
  4324. },
  4325. {
  4326. name: "public option-scid-alias using real",
  4327. zeroConf: false,
  4328. private: false,
  4329. useAlias: false,
  4330. },
  4331. {
  4332. name: "private option-scid-alias using alias",
  4333. zeroConf: false,
  4334. private: true,
  4335. useAlias: true,
  4336. },
  4337. }
  4338. for _, test := range tests {
  4339. test := test
  4340. t.Run(test.name, func(t *testing.T) {
  4341. testSwitchAliasFailAdd(
  4342. t, test.zeroConf, test.private, test.useAlias,
  4343. )
  4344. })
  4345. }
  4346. }
  4347. func testSwitchAliasFailAdd(t *testing.T, zeroConf, private, useAlias bool) {
  4348. t.Parallel()
  4349. chanID1, chanID2, aliceChanID, bobChanID := genIDs()
  4350. alicePeer, err := newMockServer(
  4351. t, "alice", testStartingHeight, nil, testDefaultDelta,
  4352. )
  4353. require.NoError(t, err)
  4354. bobPeer, err := newMockServer(
  4355. t, "bob", testStartingHeight, nil, testDefaultDelta,
  4356. )
  4357. require.NoError(t, err)
  4358. tempPath := t.TempDir()
  4359. cdb, err := channeldb.Open(tempPath)
  4360. require.NoError(t, err)
  4361. defer cdb.Close()
  4362. s, err := initSwitchWithDB(testStartingHeight, cdb)
  4363. require.NoError(t, err)
  4364. // Change the mailOrchestrator's expiry to a second.
  4365. s.mailOrchestrator.cfg.expiry = time.Second
  4366. err = s.Start()
  4367. require.NoError(t, err)
  4368. defer func() {
  4369. _ = s.Stop()
  4370. }()
  4371. // Make Alice's channel zero-conf or option-scid-alias (feature bit).
  4372. aliceAlias := lnwire.ShortChannelID{
  4373. BlockHeight: 16_000_000,
  4374. TxIndex: 5,
  4375. TxPosition: 5,
  4376. }
  4377. aliceAlias2 := aliceAlias
  4378. aliceAlias2.TxPosition = 6
  4379. var aliceLink *mockChannelLink
  4380. if zeroConf {
  4381. aliceLink = newMockChannelLink(
  4382. s, chanID1, aliceAlias, aliceChanID, alicePeer, true,
  4383. private, true, false,
  4384. )
  4385. aliceLink.addAlias(aliceAlias2)
  4386. } else {
  4387. aliceLink = newMockChannelLink(
  4388. s, chanID1, aliceChanID, emptyScid, alicePeer, true,
  4389. private, false, true,
  4390. )
  4391. aliceLink.addAlias(aliceAlias)
  4392. aliceLink.addAlias(aliceAlias2)
  4393. }
  4394. err = s.AddLink(aliceLink)
  4395. require.NoError(t, err)
  4396. bobLink := newMockChannelLink(
  4397. s, chanID2, bobChanID, emptyScid, bobPeer, true, true, false,
  4398. false,
  4399. )
  4400. err = s.AddLink(bobLink)
  4401. require.NoError(t, err)
  4402. // Create a packet that Bob will send to Alice via ForwardPackets.
  4403. preimage := [sha256.Size]byte{1}
  4404. rhash := sha256.Sum256(preimage[:])
  4405. ogPacket := &htlcPacket{
  4406. incomingChanID: bobLink.ShortChanID(),
  4407. incomingHTLCID: 0,
  4408. obfuscator: NewMockObfuscator(),
  4409. htlc: &lnwire.UpdateAddHTLC{
  4410. PaymentHash: rhash,
  4411. Amount: 1,
  4412. },
  4413. }
  4414. // Determine which outgoingChanID to set based on the useAlias boolean.
  4415. outgoingChanID := aliceChanID
  4416. if useAlias {
  4417. // Choose randomly from the 2 possible aliases.
  4418. aliases := aliceLink.getAliases()
  4419. idx := mrand.Intn(len(aliases))
  4420. outgoingChanID = aliases[idx]
  4421. }
  4422. ogPacket.outgoingChanID = outgoingChanID
  4423. // Forward the packet so Alice's mailbox fails it backwards.
  4424. err = s.ForwardPackets(nil, ogPacket)
  4425. require.NoError(t, err)
  4426. // Assert that the circuits are in the expected state.
  4427. require.Equal(t, 1, s.circuits.NumPending())
  4428. require.Equal(t, 0, s.circuits.NumOpen())
  4429. // Wait to receive the packet from Bob's mailbox.
  4430. select {
  4431. case failPacket := <-bobLink.packets:
  4432. // Assert that failPacket returns the expected SCID in the
  4433. // ChannelUpdate.
  4434. msg := failPacket.linkFailure.msg
  4435. failMsg, ok := msg.(*lnwire.FailTemporaryChannelFailure)
  4436. require.True(t, ok)
  4437. require.Equal(t, outgoingChanID, failMsg.Update.ShortChannelID)
  4438. case <-s.quit:
  4439. t.Fatal("switch shutting down, failed to receive fail packet")
  4440. }
  4441. }
  4442. // TestSwitchHandlePacketForwardAlias checks that handlePacketForward (which
  4443. // calls CheckHtlcForward) does not leak the UTXO in a failure message for
  4444. // alias channels. This test requires us to have a REAL link, which we also
  4445. // must modify in order to test it properly (e.g. making it a private channel).
  4446. // This doesn't lead to good code, but short of refactoring the link-generation
  4447. // code there is not a good alternative.
  4448. func TestSwitchHandlePacketForward(t *testing.T) {
  4449. tests := []struct {
  4450. name string
  4451. // Denotes whether or not the channel will be zero-conf.
  4452. zeroConf bool
  4453. // Denotes whether or not the channel will have negotiated the
  4454. // option-scid-alias feature-bit and is not zero-conf.
  4455. optionFeature bool
  4456. // Denotes whether or not the channel will be private.
  4457. private bool
  4458. // Denotes whether or not the alias will be used for
  4459. // forwarding.
  4460. useAlias bool
  4461. }{
  4462. {
  4463. name: "public zero-conf using alias",
  4464. zeroConf: true,
  4465. private: false,
  4466. useAlias: true,
  4467. },
  4468. {
  4469. name: "public zero-conf using real",
  4470. zeroConf: true,
  4471. private: false,
  4472. useAlias: false,
  4473. },
  4474. {
  4475. name: "private zero-conf using alias",
  4476. zeroConf: true,
  4477. private: true,
  4478. useAlias: true,
  4479. },
  4480. {
  4481. name: "public option-scid-alias using alias",
  4482. zeroConf: false,
  4483. optionFeature: true,
  4484. private: false,
  4485. useAlias: true,
  4486. },
  4487. {
  4488. name: "public option-scid-alias using real",
  4489. zeroConf: false,
  4490. optionFeature: true,
  4491. private: false,
  4492. useAlias: false,
  4493. },
  4494. {
  4495. name: "private option-scid-alias using alias",
  4496. zeroConf: false,
  4497. optionFeature: true,
  4498. private: true,
  4499. useAlias: true,
  4500. },
  4501. }
  4502. for _, test := range tests {
  4503. test := test
  4504. t.Run(test.name, func(t *testing.T) {
  4505. testSwitchHandlePacketForward(
  4506. t, test.zeroConf, test.private, test.useAlias,
  4507. test.optionFeature,
  4508. )
  4509. })
  4510. }
  4511. }
  4512. func testSwitchHandlePacketForward(t *testing.T, zeroConf, private,
  4513. useAlias, optionFeature bool) {
  4514. t.Parallel()
  4515. // Create a link for Alice that we'll add to the switch.
  4516. harness, err :=
  4517. newSingleLinkTestHarness(t, btcutil.SatoshiPerBitcoin, 0)
  4518. require.NoError(t, err)
  4519. aliceLink := harness.aliceLink
  4520. s, err := initSwitchWithTempDB(t, testStartingHeight)
  4521. if err != nil {
  4522. t.Fatalf("unable to init switch: %v", err)
  4523. }
  4524. if err := s.Start(); err != nil {
  4525. t.Fatalf("unable to start switch: %v", err)
  4526. }
  4527. defer func() {
  4528. _ = s.Stop()
  4529. }()
  4530. // Change Alice's ShortChanID and OtherShortChanID here.
  4531. aliceAlias := lnwire.ShortChannelID{
  4532. BlockHeight: 16_000_000,
  4533. TxIndex: 5,
  4534. TxPosition: 5,
  4535. }
  4536. aliceAlias2 := aliceAlias
  4537. aliceAlias2.TxPosition = 6
  4538. aliceChannelLink := aliceLink.(*channelLink)
  4539. aliceChannelState := aliceChannelLink.channel.State()
  4540. // Set the link's GetAliases function.
  4541. aliceChannelLink.cfg.GetAliases = func(
  4542. base lnwire.ShortChannelID) []lnwire.ShortChannelID {
  4543. return []lnwire.ShortChannelID{aliceAlias, aliceAlias2}
  4544. }
  4545. if !private {
  4546. // Change the channel to public depending on the test.
  4547. aliceChannelState.ChannelFlags = lnwire.FFAnnounceChannel
  4548. }
  4549. // If this is an option-scid-alias feature-bit non-zero-conf channel,
  4550. // we'll mark the channel as such.
  4551. if optionFeature {
  4552. aliceChannelState.ChanType |= channeldb.ScidAliasFeatureBit
  4553. }
  4554. // This is the ShortChannelID field in the OpenChannel struct.
  4555. aliceScid := aliceLink.ShortChanID()
  4556. if zeroConf {
  4557. // Store the alias in the shortChanID field and mark the real
  4558. // scid in the database.
  4559. err = aliceChannelState.MarkRealScid(aliceScid)
  4560. require.NoError(t, err)
  4561. aliceChannelState.ChanType |= channeldb.ZeroConfBit
  4562. }
  4563. err = s.AddLink(aliceLink)
  4564. require.NoError(t, err)
  4565. // Add a mockChannelLink for Bob.
  4566. bobChanID, bobScid := genID()
  4567. bobPeer, err := newMockServer(
  4568. t, "bob", testStartingHeight, nil, testDefaultDelta,
  4569. )
  4570. require.NoError(t, err)
  4571. bobLink := newMockChannelLink(
  4572. s, bobChanID, bobScid, emptyScid, bobPeer, true, false, false,
  4573. false,
  4574. )
  4575. err = s.AddLink(bobLink)
  4576. require.NoError(t, err)
  4577. preimage := [sha256.Size]byte{1}
  4578. rhash := sha256.Sum256(preimage[:])
  4579. ogPacket := &htlcPacket{
  4580. incomingChanID: bobLink.ShortChanID(),
  4581. incomingHTLCID: 0,
  4582. incomingAmount: 1000,
  4583. obfuscator: NewMockObfuscator(),
  4584. htlc: &lnwire.UpdateAddHTLC{
  4585. PaymentHash: rhash,
  4586. Amount: 1,
  4587. },
  4588. }
  4589. // Determine which outgoingChanID to set based on the useAlias bool.
  4590. outgoingChanID := aliceScid
  4591. if useAlias {
  4592. // Choose from the possible aliases.
  4593. aliases := aliceLink.getAliases()
  4594. idx := mrand.Intn(len(aliases))
  4595. outgoingChanID = aliases[idx]
  4596. }
  4597. ogPacket.outgoingChanID = outgoingChanID
  4598. // Forward the packet to Alice and she should fail it back with an
  4599. // AmountBelowMinimum FailureMessage.
  4600. err = s.ForwardPackets(nil, ogPacket)
  4601. require.NoError(t, err)
  4602. select {
  4603. case failPacket := <-bobLink.packets:
  4604. // Assert that failPacket returns the expected ChannelUpdate.
  4605. msg := failPacket.linkFailure.msg
  4606. failMsg, ok := msg.(*lnwire.FailAmountBelowMinimum)
  4607. require.True(t, ok)
  4608. require.Equal(t, outgoingChanID, failMsg.Update.ShortChannelID)
  4609. case <-s.quit:
  4610. t.Fatal("switch shutting down, failed to receive failure")
  4611. }
  4612. }
  4613. // TestSwitchAliasInterceptFail tests that when the InterceptableSwitch fails
  4614. // an incoming HTLC, it does not leak the on-chain UTXO for option-scid-alias
  4615. // (feature bit) or zero-conf channels.
  4616. func TestSwitchAliasInterceptFail(t *testing.T) {
  4617. tests := []struct {
  4618. name string
  4619. // Denotes whether or not the incoming channel is a zero-conf
  4620. // channel or an option-scid-alias channel instead (feature
  4621. // bit).
  4622. zeroConf bool
  4623. }{
  4624. {
  4625. name: "option-scid-alias",
  4626. zeroConf: false,
  4627. },
  4628. {
  4629. name: "zero-conf",
  4630. zeroConf: true,
  4631. },
  4632. }
  4633. for _, test := range tests {
  4634. test := test
  4635. t.Run(test.name, func(t *testing.T) {
  4636. testSwitchAliasInterceptFail(t, test.zeroConf)
  4637. })
  4638. }
  4639. }
  4640. func testSwitchAliasInterceptFail(t *testing.T, zeroConf bool) {
  4641. t.Parallel()
  4642. chanID, aliceScid := genID()
  4643. alicePeer, err := newMockServer(
  4644. t, "alice", testStartingHeight, nil, testDefaultDelta,
  4645. )
  4646. require.NoError(t, err)
  4647. tempPath := t.TempDir()
  4648. cdb, err := channeldb.Open(tempPath)
  4649. require.NoError(t, err)
  4650. t.Cleanup(func() { cdb.Close() })
  4651. s, err := initSwitchWithDB(testStartingHeight, cdb)
  4652. require.NoError(t, err)
  4653. err = s.Start()
  4654. require.NoError(t, err)
  4655. defer func() {
  4656. _ = s.Stop()
  4657. }()
  4658. // Make Alice's alias here.
  4659. aliceAlias := lnwire.ShortChannelID{
  4660. BlockHeight: 16_000_000,
  4661. TxIndex: 5,
  4662. TxPosition: 5,
  4663. }
  4664. aliceAlias2 := aliceAlias
  4665. aliceAlias2.TxPosition = 6
  4666. var aliceLink *mockChannelLink
  4667. if zeroConf {
  4668. aliceLink = newMockChannelLink(
  4669. s, chanID, aliceAlias, aliceScid, alicePeer, true,
  4670. true, true, false,
  4671. )
  4672. aliceLink.addAlias(aliceAlias2)
  4673. } else {
  4674. aliceLink = newMockChannelLink(
  4675. s, chanID, aliceScid, emptyScid, alicePeer, true,
  4676. true, false, true,
  4677. )
  4678. aliceLink.addAlias(aliceAlias)
  4679. aliceLink.addAlias(aliceAlias2)
  4680. }
  4681. err = s.AddLink(aliceLink)
  4682. require.NoError(t, err)
  4683. // Now we'll create the packet that will be sent from the Alice link.
  4684. preimage := [sha256.Size]byte{1}
  4685. rhash := sha256.Sum256(preimage[:])
  4686. ogPacket := &htlcPacket{
  4687. incomingChanID: aliceLink.ShortChanID(),
  4688. incomingTimeout: 1000,
  4689. incomingHTLCID: 0,
  4690. outgoingChanID: lnwire.ShortChannelID{},
  4691. obfuscator: NewMockObfuscator(),
  4692. htlc: &lnwire.UpdateAddHTLC{
  4693. PaymentHash: rhash,
  4694. Amount: 1,
  4695. },
  4696. }
  4697. // Now setup the interceptable switch so that we can reject this
  4698. // packet.
  4699. forwardInterceptor := &mockForwardInterceptor{
  4700. t: t,
  4701. interceptedChan: make(chan InterceptedPacket),
  4702. }
  4703. notifier := &mock.ChainNotifier{
  4704. EpochChan: make(chan *chainntnfs.BlockEpoch, 1),
  4705. }
  4706. notifier.EpochChan <- &chainntnfs.BlockEpoch{Height: testStartingHeight}
  4707. interceptSwitch, err := NewInterceptableSwitch(
  4708. &InterceptableSwitchConfig{
  4709. Switch: s,
  4710. Notifier: notifier,
  4711. CltvRejectDelta: 10,
  4712. CltvInterceptDelta: 13,
  4713. },
  4714. )
  4715. require.NoError(t, err)
  4716. require.NoError(t, interceptSwitch.Start())
  4717. interceptSwitch.SetInterceptor(forwardInterceptor.InterceptForwardHtlc)
  4718. err = interceptSwitch.ForwardPackets(nil, false, ogPacket)
  4719. require.NoError(t, err)
  4720. inCircuit := forwardInterceptor.getIntercepted().IncomingCircuit
  4721. require.NoError(t, interceptSwitch.resolve(&FwdResolution{
  4722. Action: FwdActionFail,
  4723. Key: inCircuit,
  4724. FailureCode: lnwire.CodeTemporaryChannelFailure,
  4725. }))
  4726. select {
  4727. case failPacket := <-aliceLink.packets:
  4728. // Assert that failPacket returns the expected ChannelUpdate.
  4729. failHtlc, ok := failPacket.htlc.(*lnwire.UpdateFailHTLC)
  4730. require.True(t, ok)
  4731. fwdErr, err := newMockDeobfuscator().DecryptError(
  4732. failHtlc.Reason,
  4733. )
  4734. require.NoError(t, err)
  4735. failure := fwdErr.WireMessage()
  4736. failureMsg, ok := failure.(*lnwire.FailTemporaryChannelFailure)
  4737. require.True(t, ok)
  4738. failScid := failureMsg.Update.ShortChannelID
  4739. isAlias := failScid == aliceAlias || failScid == aliceAlias2
  4740. require.True(t, isAlias)
  4741. case <-s.quit:
  4742. t.Fatalf("switch shutting down, failed to receive failure")
  4743. }
  4744. require.NoError(t, interceptSwitch.Stop())
  4745. }