github.com/decred/dcrlnd@v0.7.6/lnwallet/channel_test.go (about) 1 package lnwallet 2 3 import ( 4 "bytes" 5 "container/list" 6 "crypto/sha256" 7 "fmt" 8 "math/rand" 9 "reflect" 10 "runtime" 11 "testing" 12 "testing/quick" 13 14 "github.com/davecgh/go-spew/spew" 15 "github.com/decred/dcrd/chaincfg/v3" 16 "github.com/decred/dcrd/dcrec/secp256k1/v4" 17 "github.com/decred/dcrd/dcrutil/v4" 18 "github.com/decred/dcrd/txscript/v4" 19 "github.com/decred/dcrd/wire" 20 "github.com/stretchr/testify/require" 21 22 "github.com/decred/dcrlnd/chainntnfs" 23 "github.com/decred/dcrlnd/channeldb" 24 "github.com/decred/dcrlnd/input" 25 "github.com/decred/dcrlnd/lntypes" 26 "github.com/decred/dcrlnd/lnwallet/chainfee" 27 "github.com/decred/dcrlnd/lnwire" 28 ) 29 30 var ( 31 testChainParams = chaincfg.RegNetParams() 32 ) 33 34 // createHTLC is a utility function for generating an HTLC with a given 35 // preimage and a given amount. 36 func createHTLC(id int, amount lnwire.MilliAtom) (*lnwire.UpdateAddHTLC, [32]byte) { 37 preimage := bytes.Repeat([]byte{byte(id)}, 32) 38 paymentHash := sha256.Sum256(preimage) 39 40 var returnPreimage [32]byte 41 copy(returnPreimage[:], preimage) 42 43 return &lnwire.UpdateAddHTLC{ 44 ID: uint64(id), 45 PaymentHash: paymentHash, 46 Amount: amount, 47 Expiry: uint32(5), 48 }, returnPreimage 49 } 50 51 func assertOutputExistsByValue(t *testing.T, commitTx *wire.MsgTx, 52 value dcrutil.Amount) { 53 54 for _, txOut := range commitTx.TxOut { 55 if txOut.Value == int64(value) { 56 return 57 } 58 } 59 60 t.Fatalf("unable to find output of value %v within tx %v", value, 61 spew.Sdump(commitTx)) 62 } 63 64 // testAddSettleWorkflow tests a simple channel scenario where Alice and Bob 65 // add, the settle an HTLC between themselves. 66 func testAddSettleWorkflow(t *testing.T, tweakless bool) { 67 // Create a test channel which will be used for the duration of this 68 // unittest. The channel will be funded evenly with Alice having 5 DCR, 69 // and Bob having 5 DCR. 70 chanType := channeldb.SingleFunderTweaklessBit 71 if !tweakless { 72 chanType = channeldb.SingleFunderBit 73 } 74 75 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels(chanType) 76 if err != nil { 77 t.Fatalf("unable to create test channels: %v", err) 78 } 79 defer cleanUp() 80 81 paymentPreimage := bytes.Repeat([]byte{1}, 32) 82 paymentHash := sha256.Sum256(paymentPreimage) 83 htlcAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 84 htlc := &lnwire.UpdateAddHTLC{ 85 PaymentHash: paymentHash, 86 Amount: htlcAmt, 87 Expiry: uint32(5), 88 } 89 90 // First Alice adds the outgoing HTLC to her local channel's state 91 // update log. Then Alice sends this wire message over to Bob who adds 92 // this htlc to his remote state update log. 93 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 94 if err != nil { 95 t.Fatalf("unable to add htlc: %v", err) 96 } 97 98 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 99 if err != nil { 100 t.Fatalf("unable to recv htlc: %v", err) 101 } 102 103 // Next alice commits this change by sending a signature message. Since 104 // we expect the messages to be ordered, Bob will receive the HTLC we 105 // just sent before he receives this signature, so the signature will 106 // cover the HTLC. 107 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 108 if err != nil { 109 t.Fatalf("alice unable to sign commitment: %v", err) 110 } 111 112 // Bob receives this signature message, and checks that this covers the 113 // state he has in his remote log. This includes the HTLC just sent 114 // from Alice. 115 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 116 if err != nil { 117 t.Fatalf("bob unable to process alice's new commitment: %v", err) 118 } 119 120 // Bob revokes his prior commitment given to him by Alice, since he now 121 // has a valid signature for a newer commitment. 122 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 123 if err != nil { 124 t.Fatalf("unable to generate bob revocation: %v", err) 125 } 126 127 // Bob finally send a signature for Alice's commitment transaction. 128 // This signature will cover the HTLC, since Bob will first send the 129 // revocation just created. The revocation also acks every received 130 // HTLC up to the point where Alice sent here signature. 131 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 132 if err != nil { 133 t.Fatalf("bob unable to sign alice's commitment: %v", err) 134 } 135 136 // Alice then processes this revocation, sending her own revocation for 137 // her prior commitment transaction. Alice shouldn't have any HTLCs to 138 // forward since she's sending an outgoing HTLC. 139 fwdPkg, _, _, _, err := aliceChannel.ReceiveRevocation(bobRevocation) 140 if err != nil { 141 t.Fatalf("alice unable to process bob's revocation: %v", err) 142 } 143 if len(fwdPkg.Adds) != 0 { 144 t.Fatalf("alice forwards %v add htlcs, should forward none", 145 len(fwdPkg.Adds)) 146 } 147 if len(fwdPkg.SettleFails) != 0 { 148 t.Fatalf("alice forwards %v settle/fail htlcs, "+ 149 "should forward none", len(fwdPkg.SettleFails)) 150 } 151 152 // Alice then processes bob's signature, and since she just received 153 // the revocation, she expect this signature to cover everything up to 154 // the point where she sent her signature, including the HTLC. 155 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 156 if err != nil { 157 t.Fatalf("alice unable to process bob's new commitment: %v", err) 158 } 159 160 // Alice then generates a revocation for bob. 161 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 162 if err != nil { 163 t.Fatalf("unable to revoke alice channel: %v", err) 164 } 165 166 // Finally Bob processes Alice's revocation, at this point the new HTLC 167 // is fully locked in within both commitment transactions. Bob should 168 // also be able to forward an HTLC now that the HTLC has been locked 169 // into both commitment transactions. 170 fwdPkg, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 171 if err != nil { 172 t.Fatalf("bob unable to process alice's revocation: %v", err) 173 } 174 if len(fwdPkg.Adds) != 1 { 175 t.Fatalf("bob forwards %v add htlcs, should only forward one", 176 len(fwdPkg.Adds)) 177 } 178 if len(fwdPkg.SettleFails) != 0 { 179 t.Fatalf("bob forwards %v settle/fail htlcs, "+ 180 "should forward none", len(fwdPkg.SettleFails)) 181 } 182 183 // At this point, both sides should have the proper number of atoms 184 // sent, and commitment height updated within their local channel 185 // state. 186 aliceSent := lnwire.MilliAtom(0) 187 bobSent := lnwire.MilliAtom(0) 188 189 if aliceChannel.channelState.TotalMAtomsSent != aliceSent { 190 t.Fatalf("alice has incorrect milli-atoms sent: %v vs %v", 191 aliceChannel.channelState.TotalMAtomsSent, aliceSent) 192 } 193 if aliceChannel.channelState.TotalMAtomsReceived != bobSent { 194 t.Fatalf("alice has incorrect milli-atoms received %v vs %v", 195 aliceChannel.channelState.TotalMAtomsReceived, bobSent) 196 } 197 if bobChannel.channelState.TotalMAtomsSent != bobSent { 198 t.Fatalf("bob has incorrect milli-atoms sent %v vs %v", 199 bobChannel.channelState.TotalMAtomsSent, bobSent) 200 } 201 if bobChannel.channelState.TotalMAtomsReceived != aliceSent { 202 t.Fatalf("bob has incorrect milli-atoms received %v vs %v", 203 bobChannel.channelState.TotalMAtomsReceived, aliceSent) 204 } 205 if bobChannel.currentHeight != 1 { 206 t.Fatalf("bob has incorrect commitment height, %v vs %v", 207 bobChannel.currentHeight, 1) 208 } 209 if aliceChannel.currentHeight != 1 { 210 t.Fatalf("alice has incorrect commitment height, %v vs %v", 211 aliceChannel.currentHeight, 1) 212 } 213 214 // Both commitment transactions should have three outputs, and one of 215 // them should be exactly the amount of the HTLC. 216 if len(aliceChannel.channelState.LocalCommitment.CommitTx.TxOut) != 3 { 217 t.Fatalf("alice should have three commitment outputs, instead "+ 218 "have %v", 219 len(aliceChannel.channelState.LocalCommitment.CommitTx.TxOut)) 220 } 221 if len(bobChannel.channelState.LocalCommitment.CommitTx.TxOut) != 3 { 222 t.Fatalf("bob should have three commitment outputs, instead "+ 223 "have %v", 224 len(bobChannel.channelState.LocalCommitment.CommitTx.TxOut)) 225 } 226 assertOutputExistsByValue(t, 227 aliceChannel.channelState.LocalCommitment.CommitTx, 228 htlcAmt.ToAtoms()) 229 assertOutputExistsByValue(t, 230 bobChannel.channelState.LocalCommitment.CommitTx, 231 htlcAmt.ToAtoms()) 232 233 // Now we'll repeat a similar exchange, this time with Bob settling the 234 // HTLC once he learns of the preimage. 235 var preimage [32]byte 236 copy(preimage[:], paymentPreimage) 237 err = bobChannel.SettleHTLC(preimage, bobHtlcIndex, nil, nil, nil) 238 if err != nil { 239 t.Fatalf("bob unable to settle inbound htlc: %v", err) 240 } 241 242 err = aliceChannel.ReceiveHTLCSettle(preimage, aliceHtlcIndex) 243 if err != nil { 244 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 245 } 246 247 bobSig2, bobHtlcSigs2, _, err := bobChannel.SignNextCommitment() 248 if err != nil { 249 t.Fatalf("bob unable to sign settle commitment: %v", err) 250 } 251 err = aliceChannel.ReceiveNewCommitment(bobSig2, bobHtlcSigs2) 252 if err != nil { 253 t.Fatalf("alice unable to process bob's new commitment: %v", err) 254 } 255 256 aliceRevocation2, _, err := aliceChannel.RevokeCurrentCommitment() 257 if err != nil { 258 t.Fatalf("alice unable to generate revocation: %v", err) 259 } 260 aliceSig2, aliceHtlcSigs2, _, err := aliceChannel.SignNextCommitment() 261 if err != nil { 262 t.Fatalf("alice unable to sign new commitment: %v", err) 263 } 264 265 fwdPkg, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation2) 266 if err != nil { 267 t.Fatalf("bob unable to process alice's revocation: %v", err) 268 } 269 if len(fwdPkg.Adds) != 0 { 270 t.Fatalf("bob forwards %v add htlcs, should forward none", 271 len(fwdPkg.Adds)) 272 } 273 if len(fwdPkg.SettleFails) != 0 { 274 t.Fatalf("bob forwards %v settle/fail htlcs, "+ 275 "should forward none", len(fwdPkg.SettleFails)) 276 } 277 278 err = bobChannel.ReceiveNewCommitment(aliceSig2, aliceHtlcSigs2) 279 if err != nil { 280 t.Fatalf("bob unable to process alice's new commitment: %v", err) 281 } 282 283 bobRevocation2, _, err := bobChannel.RevokeCurrentCommitment() 284 if err != nil { 285 t.Fatalf("bob unable to revoke commitment: %v", err) 286 } 287 fwdPkg, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation2) 288 if err != nil { 289 t.Fatalf("alice unable to process bob's revocation: %v", err) 290 } 291 if len(fwdPkg.Adds) != 0 { 292 // Alice should now be able to forward the settlement HTLC to 293 // any down stream peers. 294 t.Fatalf("alice should be forwarding an add HTLC, "+ 295 "instead forwarding %v: %v", len(fwdPkg.Adds), 296 spew.Sdump(fwdPkg.Adds)) 297 } 298 if len(fwdPkg.SettleFails) != 1 { 299 t.Fatalf("alice should be forwarding one settle/fails HTLC, "+ 300 "instead forwarding: %v", len(fwdPkg.SettleFails)) 301 } 302 303 // At this point, Bob should have 6 DCR settled, with Alice still 304 // having 4 DCR. Alice's channel should show 1 DCR sent and Bob's 305 // channel should show 1 DCR received. They should also be at 306 // commitment height two, with the revocation window extended by 1 (5). 307 mAtTransferred := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 308 if aliceChannel.channelState.TotalMAtomsSent != mAtTransferred { 309 t.Fatalf("alice atoms sent incorrect %v vs %v expected", 310 aliceChannel.channelState.TotalMAtomsSent, 311 mAtTransferred) 312 } 313 if aliceChannel.channelState.TotalMAtomsReceived != 0 { 314 t.Fatalf("alice atoms received incorrect %v vs %v expected", 315 aliceChannel.channelState.TotalMAtomsReceived, 0) 316 } 317 if bobChannel.channelState.TotalMAtomsReceived != mAtTransferred { 318 t.Fatalf("bob atoms received incorrect %v vs %v expected", 319 bobChannel.channelState.TotalMAtomsReceived, 320 mAtTransferred) 321 } 322 if bobChannel.channelState.TotalMAtomsSent != 0 { 323 t.Fatalf("bob atoms sent incorrect %v vs %v expected", 324 bobChannel.channelState.TotalMAtomsSent, 0) 325 } 326 if bobChannel.currentHeight != 2 { 327 t.Fatalf("bob has incorrect commitment height, %v vs %v", 328 bobChannel.currentHeight, 2) 329 } 330 if aliceChannel.currentHeight != 2 { 331 t.Fatalf("alice has incorrect commitment height, %v vs %v", 332 aliceChannel.currentHeight, 2) 333 } 334 335 // The logs of both sides should now be cleared since the entry adding 336 // the HTLC should have been removed once both sides receive the 337 // revocation. 338 if aliceChannel.localUpdateLog.Len() != 0 { 339 t.Fatalf("alice's local not updated, should be empty, has %v "+ 340 "entries instead", aliceChannel.localUpdateLog.Len()) 341 } 342 if aliceChannel.remoteUpdateLog.Len() != 0 { 343 t.Fatalf("alice's remote not updated, should be empty, has %v "+ 344 "entries instead", aliceChannel.remoteUpdateLog.Len()) 345 } 346 if len(aliceChannel.localUpdateLog.updateIndex) != 0 { 347 t.Fatalf("alice's local log index not cleared, should be empty but "+ 348 "has %v entries", len(aliceChannel.localUpdateLog.updateIndex)) 349 } 350 if len(aliceChannel.remoteUpdateLog.updateIndex) != 0 { 351 t.Fatalf("alice's remote log index not cleared, should be empty but "+ 352 "has %v entries", len(aliceChannel.remoteUpdateLog.updateIndex)) 353 } 354 } 355 356 // TestSimpleAddSettleWorkflow tests a simple channel scenario wherein the 357 // local node (Alice in this case) creates a new outgoing HTLC to bob, commits 358 // this change, then bob immediately commits a settlement of the HTLC after the 359 // initial add is fully committed in both commit chains. 360 // 361 // TODO(roasbeef): write higher level framework to exercise various states of 362 // the state machine 363 // - DSL language perhaps? 364 // - constructed via input/output files 365 func TestSimpleAddSettleWorkflow(t *testing.T) { 366 t.Parallel() 367 368 for _, tweakless := range []bool{true, false} { 369 tweakless := tweakless 370 t.Run(fmt.Sprintf("tweakless=%v", tweakless), func(t *testing.T) { 371 testAddSettleWorkflow(t, tweakless) 372 }) 373 } 374 } 375 376 // TestChannelZeroAddLocalHeight tests that we properly set the addCommitHeightLocal 377 // field during state log restoration. 378 // 379 // The full state transition of this test is: 380 // 381 // Alice Bob 382 // 383 // -----add------> 384 // -----sig------> 385 // <----rev------- 386 // <----sig------- 387 // -----rev------> 388 // <---settle----- 389 // <----sig------- 390 // -----rev------> 391 // *alice dies* 392 // <----add------- 393 // x----sig------- 394 // 395 // The last sig will be rejected if addCommitHeightLocal is not set for the 396 // initial add that Alice sent. This test checks that this behavior does 397 // not occur and that we properly set the addCommitHeightLocal field. 398 func TestChannelZeroAddLocalHeight(t *testing.T) { 399 t.Parallel() 400 401 // Create a test channel so that we can test the buggy behavior. 402 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 403 channeldb.SingleFunderTweaklessBit, 404 ) 405 require.NoError(t, err) 406 defer cleanUp() 407 408 // First we create an HTLC that Alice sends to Bob. 409 htlc, _ := createHTLC(0, lnwire.MilliAtom(500000)) 410 411 // -----add-----> 412 _, err = aliceChannel.AddHTLC(htlc, nil) 413 require.NoError(t, err) 414 _, err = bobChannel.ReceiveHTLC(htlc) 415 require.NoError(t, err) 416 417 // Force a state transition to lock in this add on both commitments. 418 // -----sig-----> 419 // <----rev------ 420 // <----sig------ 421 // -----rev-----> 422 err = ForceStateTransition(aliceChannel, bobChannel) 423 require.NoError(t, err) 424 425 // Now Bob should fail the htlc back to Alice. 426 // <----fail----- 427 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 428 require.NoError(t, err) 429 err = aliceChannel.ReceiveFailHTLC(0, []byte("bad")) 430 require.NoError(t, err) 431 432 // Bob should send a commitment signature to Alice. 433 // <----sig------ 434 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 435 require.NoError(t, err) 436 437 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 438 require.NoError(t, err) 439 440 // Alice should reply with a revocation. 441 // -----rev-----> 442 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 443 require.NoError(t, err) 444 445 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 446 require.NoError(t, err) 447 448 // We now restore Alice's channel as this was the point at which 449 // the addCommitHeightLocal field wouldn't be set, causing a force 450 // close. 451 newAliceChannel, err := NewLightningChannel( 452 aliceChannel.Signer, aliceChannel.channelState, 453 aliceChannel.sigPool, testChainParams, 454 ) 455 require.NoError(t, err) 456 457 // Bob now sends an htlc to Alice 458 htlc2, _ := createHTLC(0, lnwire.MilliAtom(500000)) 459 460 // <----add----- 461 _, err = bobChannel.AddHTLC(htlc2, nil) 462 require.NoError(t, err) 463 _, err = newAliceChannel.ReceiveHTLC(htlc2) 464 require.NoError(t, err) 465 466 // Bob should now send a commitment signature to Alice. 467 // <----sig----- 468 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 469 require.NoError(t, err) 470 471 // Alice should accept the commitment. Previously she would 472 // force close here. 473 err = newAliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 474 require.NoError(t, err) 475 } 476 477 // TestCheckCommitTxSize checks that estimation size of commitment 478 // transaction with some degree of error corresponds to the actual size. 479 func TestCheckCommitTxSize(t *testing.T) { 480 t.Parallel() 481 482 checkSize := func(channel *LightningChannel, count int) { 483 // Due to the possible number of HTLC outputs being over 0xff, the 484 // varint that stores the number of outputs might be one byte off 485 // (estimation for worst case commitment tx uses 2 bytes). 486 commitTxSizeEstimationError := int64(1) 487 488 // Due to variable size of the signatures (70-73) in witness 489 // script actual size of commitment transaction might be lower 490 // by 6 bytes (recall that 2 signatures are required when 491 // redeeming the funding transaction). 492 commitTxSizeEstimationError += int64(6) 493 494 commitTx, err := channel.getSignedCommitTx() 495 if err != nil { 496 t.Fatalf("unable to initiate alice force close: %v", err) 497 } 498 actualCost := int64(commitTx.SerializeSize()) 499 estimatedCost := input.EstimateCommitmentTxSize(count) 500 501 diff := estimatedCost - actualCost 502 if 0 > diff || commitTxSizeEstimationError < diff { 503 bts, _ := commitTx.Bytes() 504 t.Logf("%x", bts) 505 t.Fatalf("estimation is wrong with %d HTLCs, diff: %v", 506 count, diff) 507 } 508 509 } 510 511 // Create a test channel which will be used for the duration of this 512 // unittest. The channel will be funded evenly with Alice having 5 BTC, 513 // and Bob having 5 BTC. 514 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 515 channeldb.SingleFunderTweaklessBit, 516 ) 517 if err != nil { 518 t.Fatalf("unable to create test channels: %v", err) 519 } 520 defer cleanUp() 521 522 // Check that size estimation of the commitment transaction without 523 // HTLCs is right. 524 checkSize(aliceChannel, 0) 525 checkSize(bobChannel, 0) 526 527 t.Logf("Checking adds") 528 529 // Adding HTLCs and check that size stays in allowable estimation 530 // error window. 531 for i := 0; i <= 10; i++ { 532 htlc, _ := createHTLC(i, lnwire.MilliAtom(1e9)) 533 534 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 535 t.Fatalf("alice unable to add htlc: %v", err) 536 } 537 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 538 t.Fatalf("bob unable to receive htlc: %v", err) 539 } 540 541 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 542 t.Fatalf("unable to complete state update: %v", err) 543 } 544 checkSize(aliceChannel, i+1) 545 checkSize(bobChannel, i+1) 546 } 547 548 t.Logf("Checking settles") 549 550 // Settle HTLCs and check that estimation is counting cost of settle 551 // HTLCs properly. 552 for i := 10; i >= 0; i-- { 553 _, preimage := createHTLC(i, lnwire.MilliAtom(1e9)) 554 555 err := bobChannel.SettleHTLC(preimage, uint64(i), nil, nil, nil) 556 if err != nil { 557 t.Fatalf("bob unable to settle inbound htlc: %v", err) 558 } 559 560 err = aliceChannel.ReceiveHTLCSettle(preimage, uint64(i)) 561 if err != nil { 562 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 563 } 564 565 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 566 t.Fatalf("unable to complete state update: %v", err) 567 } 568 checkSize(aliceChannel, i) 569 checkSize(bobChannel, i) 570 } 571 } 572 573 // TestCommitHTLCSigTieBreak asserts that HTLC signatures are sent the proper 574 // BIP69+CLTV sorting expected by BOLT 3 when multiple HTLCs have identical 575 // payment hashes and amounts, but differing CLTVs. This is exercised by adding 576 // the HTLCs in the descending order of their CLTVs, and asserting that their 577 // order is reversed when signing. 578 func TestCommitHTLCSigTieBreak(t *testing.T) { 579 t.Run("no restart", func(t *testing.T) { 580 testCommitHTLCSigTieBreak(t, false) 581 }) 582 t.Run("restart", func(t *testing.T) { 583 testCommitHTLCSigTieBreak(t, true) 584 }) 585 } 586 587 func testCommitHTLCSigTieBreak(t *testing.T, restart bool) { 588 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 589 channeldb.SingleFunderTweaklessBit, 590 ) 591 if err != nil { 592 t.Fatalf("unable to create test channels; %v", err) 593 } 594 defer cleanUp() 595 596 const ( 597 htlcAmt = lnwire.MilliAtom(200000 * 1000) 598 numHtlcs = 2 599 ) 600 601 // Add HTLCs with identical payment hashes and amounts, but descending 602 // CLTV values. We will expect the signatures to appear in the reverse 603 // order that the HTLCs are added due to the commitment sorting. 604 for i := 0; i < numHtlcs; i++ { 605 var ( 606 preimage lntypes.Preimage 607 hash = preimage.Hash() 608 ) 609 610 htlc := &lnwire.UpdateAddHTLC{ 611 ID: uint64(i), 612 PaymentHash: hash, 613 Amount: htlcAmt, 614 Expiry: uint32(numHtlcs - i), 615 } 616 617 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 618 t.Fatalf("alice unable to add htlc: %v", err) 619 } 620 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 621 t.Fatalf("bob unable to receive htlc: %v", err) 622 } 623 } 624 625 // Have Alice initiate the first half of the commitment dance. The 626 // tie-breaking for commitment sorting won't affect the commitment 627 // signed by Alice because received HTLC scripts commit to the CLTV 628 // directly, so the outputs will have different scriptPubkeys. 629 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 630 if err != nil { 631 t.Fatalf("unable to sign alice's commitment: %v", err) 632 } 633 634 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 635 if err != nil { 636 t.Fatalf("unable to receive alice's commitment: %v", err) 637 } 638 639 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 640 if err != nil { 641 t.Fatalf("unable to revoke bob's commitment: %v", err) 642 } 643 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 644 if err != nil { 645 t.Fatalf("unable to receive bob's revocation: %v", err) 646 } 647 648 // Now have Bob initiate the second half of the commitment dance. Here 649 // the offered HTLC scripts he adds for Alice will need to have the 650 // tie-breaking applied because the CLTV is not committed, but instead 651 // implicit via the construction of the second-level transactions. 652 bobSig, bobHtlcSigs, bobHtlcs, err := bobChannel.SignNextCommitment() 653 if err != nil { 654 t.Fatalf("unable to sign bob's commitment: %v", err) 655 } 656 657 if len(bobHtlcs) != numHtlcs { 658 t.Fatalf("expected %d htlcs, got: %v", numHtlcs, len(bobHtlcs)) 659 } 660 661 // Ensure that our HTLCs appear in the reverse order from which they 662 // were added by inspecting each's outpoint index. We expect the output 663 // indexes to be in descending order, i.e. the first HTLC added had the 664 // highest CLTV and should end up last. 665 lastIndex := bobHtlcs[0].OutputIndex 666 for i, htlc := range bobHtlcs[1:] { 667 if htlc.OutputIndex >= lastIndex { 668 t.Fatalf("htlc %d output index %d is not descending", 669 i, htlc.OutputIndex) 670 } 671 672 lastIndex = htlc.OutputIndex 673 } 674 675 // If requsted, restart Alice so that we can test that the necessary 676 // indexes can be reconstructed before needing to validate the 677 // signatures from Bob. 678 if restart { 679 aliceState := aliceChannel.channelState 680 aliceChannels, err := aliceState.Db.FetchOpenChannels( 681 aliceState.IdentityPub, 682 ) 683 if err != nil { 684 t.Fatalf("unable to fetch channel: %v", err) 685 } 686 687 aliceChannelNew, err := NewLightningChannel( 688 aliceChannel.Signer, aliceChannels[0], 689 aliceChannel.sigPool, testChainParams, 690 ) 691 if err != nil { 692 t.Fatalf("unable to create new channel: %v", err) 693 } 694 695 aliceChannel = aliceChannelNew 696 } 697 698 // Finally, have Alice validate the signatures to ensure that she is 699 // expecting the signatures in the proper order. 700 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 701 if err != nil { 702 t.Fatalf("unable to receive bob's commitment: %v", err) 703 } 704 } 705 706 // TestCooperativeChannelClosure checks that the coop close process finishes 707 // with an agreement from both parties, and that the final balances of the 708 // close tx check out. 709 func TestCooperativeChannelClosure(t *testing.T) { 710 t.Run("tweakless", func(t *testing.T) { 711 testCoopClose(t, &coopCloseTestCase{ 712 chanType: channeldb.SingleFunderTweaklessBit, 713 }) 714 }) 715 t.Run("anchors", func(t *testing.T) { 716 testCoopClose(t, &coopCloseTestCase{ 717 chanType: channeldb.SingleFunderTweaklessBit | 718 channeldb.AnchorOutputsBit, 719 anchorAmt: anchorSize * 2, 720 }) 721 }) 722 } 723 724 type coopCloseTestCase struct { 725 chanType channeldb.ChannelType 726 anchorAmt dcrutil.Amount 727 } 728 729 func testCoopClose(t *testing.T, testCase *coopCloseTestCase) { 730 t.Parallel() 731 732 // Create a test channel which will be used for the duration of this 733 // unittest. The channel will be funded evenly with Alice having 5 DCR, 734 // and Bob having 5 DCR. 735 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 736 testCase.chanType, 737 ) 738 if err != nil { 739 t.Fatalf("unable to create test channels: %v", err) 740 } 741 defer cleanUp() 742 743 // We can use any dummy script, given that thist test doesn't actually 744 // verify whether the signature corresponds to the correct script. 745 aliceDeliveryScript := alicePkScript 746 bobDeliveryScript := bobPkScript 747 748 aliceFeeRate := chainfee.AtomPerKByte( 749 aliceChannel.channelState.LocalCommitment.FeePerKB, 750 ) 751 bobFeeRate := chainfee.AtomPerKByte( 752 bobChannel.channelState.LocalCommitment.FeePerKB, 753 ) 754 755 // We'll start with both Alice and Bob creating a new close proposal 756 // with the same fee. 757 aliceFee := aliceChannel.CalcFee(aliceFeeRate) 758 aliceSig, _, _, err := aliceChannel.CreateCloseProposal( 759 aliceFee, aliceDeliveryScript, bobDeliveryScript, 760 ) 761 if err != nil { 762 t.Fatalf("unable to create alice coop close proposal: %v", err) 763 } 764 765 bobFee := bobChannel.CalcFee(bobFeeRate) 766 bobSig, _, _, err := bobChannel.CreateCloseProposal( 767 bobFee, bobDeliveryScript, aliceDeliveryScript, 768 ) 769 if err != nil { 770 t.Fatalf("unable to create bob coop close proposal: %v", err) 771 } 772 773 // With the proposals created, both sides should be able to properly 774 // process the other party's signature. This indicates that the 775 // transaction is well formed, and the signatures verify. 776 aliceCloseTx, bobTxBalance, err := bobChannel.CompleteCooperativeClose( 777 bobSig, aliceSig, bobDeliveryScript, aliceDeliveryScript, 778 bobFee, 779 ) 780 if err != nil { 781 t.Fatalf("unable to complete alice cooperative close: %v", err) 782 } 783 bobCloseSha := aliceCloseTx.TxHash() 784 785 bobCloseTx, aliceTxBalance, err := aliceChannel.CompleteCooperativeClose( 786 aliceSig, bobSig, aliceDeliveryScript, bobDeliveryScript, 787 aliceFee, 788 ) 789 if err != nil { 790 t.Fatalf("unable to complete bob cooperative close: %v", err) 791 } 792 aliceCloseSha := bobCloseTx.TxHash() 793 794 if bobCloseSha != aliceCloseSha { 795 t.Fatalf("alice and bob close transactions don't match: %v", err) 796 } 797 798 // Finally, make sure the final balances are correct from both's 799 // perspective. 800 aliceBalance := aliceChannel.channelState.LocalCommitment. 801 LocalBalance.ToAtoms() 802 803 // The commit balance have had the initiator's (Alice) commitfee and 804 // any anchors subtracted, so add that back to the final expected 805 // balance. Alice also pays the coop close fee, so that must be 806 // subtracted. 807 commitFee := aliceChannel.channelState.LocalCommitment.CommitFee 808 expBalanceAlice := aliceBalance + commitFee + 809 testCase.anchorAmt - bobFee 810 if aliceTxBalance != expBalanceAlice { 811 t.Fatalf("expected balance %v got %v", expBalanceAlice, 812 aliceTxBalance) 813 } 814 815 // Bob is not the initiator, so his final balance should simply be 816 // equal to the latest commitment balance. 817 expBalanceBob := bobChannel.channelState.LocalCommitment. 818 LocalBalance.ToAtoms() 819 if bobTxBalance != expBalanceBob { 820 t.Fatalf("expected bob's balance to be %v got %v", 821 expBalanceBob, bobTxBalance) 822 } 823 } 824 825 // TestForceClose checks that the resulting ForceCloseSummary is correct when a 826 // peer is ForceClosing the channel. Will check outputs both above and below 827 // the dust limit. Additionally, we'll ensure that the node which executed the 828 // force close generates HTLC resolutions that are capable of sweeping both 829 // incoming and outgoing HTLC's. 830 func TestForceClose(t *testing.T) { 831 t.Run("tweakless", func(t *testing.T) { 832 testForceClose(t, &forceCloseTestCase{ 833 chanType: channeldb.SingleFunderTweaklessBit, 834 expectedCommitSize: input.CommitmentTxSize, 835 }) 836 }) 837 t.Run("anchors", func(t *testing.T) { 838 testForceClose(t, &forceCloseTestCase{ 839 chanType: channeldb.SingleFunderTweaklessBit | 840 channeldb.AnchorOutputsBit, 841 expectedCommitSize: input.CommitmentWithAnchorsTxSize, 842 anchorAmt: anchorSize * 2, 843 }) 844 }) 845 } 846 847 type forceCloseTestCase struct { 848 chanType channeldb.ChannelType 849 expectedCommitSize int64 850 anchorAmt dcrutil.Amount 851 } 852 853 func testForceClose(t *testing.T, testCase *forceCloseTestCase) { 854 t.Parallel() 855 856 // Create a test channel which will be used for the duration of this 857 // unittest. The channel will be funded evenly with Alice having 5 DCR, 858 // and Bob having 5 DCR. 859 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 860 testCase.chanType, 861 ) 862 if err != nil { 863 t.Fatalf("unable to create test channels: %v", err) 864 } 865 defer cleanUp() 866 867 bobAmount := bobChannel.channelState.LocalCommitment.LocalBalance 868 869 // First, we'll add an outgoing HTLC from Alice to Bob, such that it 870 // will still be present within the broadcast commitment transaction. 871 // We'll ensure that the HTLC amount is above Alice's dust limit. 872 htlcAmount := lnwire.NewMAtomsFromAtoms(200000) 873 htlcAlice, _ := createHTLC(0, htlcAmount) 874 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 875 t.Fatalf("alice unable to add htlc: %v", err) 876 } 877 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 878 t.Fatalf("bob unable to recv add htlc: %v", err) 879 } 880 881 // We'll also a distinct HTLC from Bob -> Alice. This way, Alice will 882 // have both an incoming and outgoing HTLC on her commitment 883 // transaction. 884 htlcBob, preimageBob := createHTLC(0, htlcAmount) 885 if _, err := bobChannel.AddHTLC(htlcBob, nil); err != nil { 886 t.Fatalf("alice unable to add htlc: %v", err) 887 } 888 if _, err := aliceChannel.ReceiveHTLC(htlcBob); err != nil { 889 t.Fatalf("bob unable to recv add htlc: %v", err) 890 } 891 892 // Next, we'll perform two state transitions to ensure that both HTLC's 893 // get fully locked-in. 894 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 895 t.Fatalf("Can't update the channel state: %v", err) 896 } 897 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 898 t.Fatalf("Can't update the channel state: %v", err) 899 } 900 901 // With the cache populated, we'll now attempt the force close 902 // initiated by Alice. 903 closeSummary, err := aliceChannel.ForceClose() 904 if err != nil { 905 t.Fatalf("unable to force close channel: %v", err) 906 } 907 908 // Alice should detect that she can sweep the outgoing HTLC after a 909 // timeout, but also that she's able to sweep in incoming HTLC Bob sent 910 // her. 911 if len(closeSummary.HtlcResolutions.OutgoingHTLCs) != 1 { 912 t.Fatalf("alice out htlc resolutions not populated: expected %v "+ 913 "htlcs, got %v htlcs", 914 1, len(closeSummary.HtlcResolutions.OutgoingHTLCs)) 915 } 916 if len(closeSummary.HtlcResolutions.IncomingHTLCs) != 1 { 917 t.Fatalf("alice in htlc resolutions not populated: expected %v "+ 918 "htlcs, got %v htlcs", 919 1, len(closeSummary.HtlcResolutions.IncomingHTLCs)) 920 } 921 922 // Verify the anchor resolutions for the anchor commitment format. 923 if testCase.chanType.HasAnchors() { 924 // Check the close summary resolution. 925 anchorRes := closeSummary.AnchorResolution 926 if anchorRes == nil { 927 t.Fatal("expected anchor resolution") 928 } 929 if anchorRes.CommitAnchor.Hash != closeSummary.CloseTx.TxHash() { 930 t.Fatal("commit tx not referenced by anchor res") 931 } 932 if anchorRes.AnchorSignDescriptor.Output.Value != 933 int64(anchorSize) { 934 935 t.Fatal("unexpected anchor size") 936 } 937 if anchorRes.AnchorSignDescriptor.WitnessScript == nil { 938 t.Fatal("expected anchor witness script") 939 } 940 941 // Check the pre-confirmation resolutions. 942 res, err := aliceChannel.NewAnchorResolutions() 943 if err != nil { 944 t.Fatalf("pre-confirmation resolution error: %v", err) 945 } 946 947 // Check we have the expected anchor resolutions. 948 require.NotNil(t, res.Local, "expected local anchor resolution") 949 require.NotNil(t, 950 res.Remote, "expected remote anchor resolution", 951 ) 952 require.Nil(t, 953 res.RemotePending, "expected no anchor resolution", 954 ) 955 } 956 957 // The SelfOutputSignDesc should be non-nil since the output to-self is 958 // non-dust. 959 aliceCommitResolution := closeSummary.CommitResolution 960 if aliceCommitResolution == nil { 961 t.Fatalf("alice fails to include to-self output in " + 962 "ForceCloseSummary") 963 } 964 965 // The rest of the close summary should have been populated properly. 966 aliceDelayPoint := aliceChannel.channelState.LocalChanCfg.DelayBasePoint 967 if !aliceCommitResolution.SelfOutputSignDesc.KeyDesc.PubKey.IsEqual( 968 aliceDelayPoint.PubKey, 969 ) { 970 t.Fatalf("alice incorrect pubkey in SelfOutputSignDesc") 971 } 972 973 // Factoring in the fee rate, Alice's amount should properly reflect 974 // that we've added two additional HTLC to the commitment transaction. 975 totalCommitSize := testCase.expectedCommitSize + 976 (input.HTLCOutputSize * 2) 977 feePerKB := chainfee.AtomPerKByte( 978 aliceChannel.channelState.LocalCommitment.FeePerKB, 979 ) 980 commitFee := feePerKB.FeeForSize(totalCommitSize) 981 982 expectedAmount := (aliceChannel.Capacity / 2) - 983 htlcAmount.ToAtoms() - commitFee - testCase.anchorAmt 984 985 if aliceCommitResolution.SelfOutputSignDesc.Output.Value != int64(expectedAmount) { 986 t.Fatalf("alice incorrect output value in SelfOutputSignDesc, "+ 987 "expected %v, got %v", int64(expectedAmount), 988 aliceCommitResolution.SelfOutputSignDesc.Output.Value) 989 } 990 991 // Alice's listed CSV delay should also match the delay that was 992 // pre-committed to at channel opening. 993 if aliceCommitResolution.MaturityDelay != 994 uint32(aliceChannel.channelState.LocalChanCfg.CsvDelay) { 995 996 t.Fatalf("alice: incorrect local CSV delay in ForceCloseSummary, "+ 997 "expected %v, got %v", 998 aliceChannel.channelState.LocalChanCfg.CsvDelay, 999 aliceCommitResolution.MaturityDelay) 1000 } 1001 1002 // Next, we'll ensure that the second level HTLC transaction it itself 1003 // spendable, and also that the delivery output (with delay) itself has 1004 // a valid sign descriptor. 1005 htlcResolution := closeSummary.HtlcResolutions.OutgoingHTLCs[0] 1006 outHtlcIndex := htlcResolution.SignedTimeoutTx.TxIn[0].PreviousOutPoint.Index 1007 senderHtlcPkScript := closeSummary.CloseTx.TxOut[outHtlcIndex].PkScript 1008 senderHtlcScriptVersion := closeSummary.CloseTx.TxOut[outHtlcIndex].Version 1009 1010 // First, verify that the second level transaction can properly spend 1011 // the multi-sig clause within the output on the commitment transaction 1012 // that produces this HTLC. 1013 timeoutTx := htlcResolution.SignedTimeoutTx 1014 vm, err := txscript.NewEngine(senderHtlcPkScript, timeoutTx, 0, 1015 input.ScriptVerifyFlags, senderHtlcScriptVersion, nil) 1016 if err != nil { 1017 t.Fatalf("unable to create engine: %v", err) 1018 } 1019 if err := vm.Execute(); err != nil { 1020 t.Fatalf("htlc timeout spend is invalid: %v", err) 1021 } 1022 1023 // Next, we'll ensure that we can spend the output of the second level 1024 // transaction given a properly crafted sweep transaction. 1025 sweepTx := wire.NewMsgTx() 1026 sweepTx.Version = input.LNTxVersion 1027 sweepTx.AddTxIn(&wire.TxIn{ 1028 PreviousOutPoint: wire.OutPoint{ 1029 Hash: htlcResolution.SignedTimeoutTx.TxHash(), 1030 Index: 0, 1031 }, 1032 ValueIn: timeoutTx.TxOut[0].Value, 1033 }) 1034 sweepTx.AddTxOut(&wire.TxOut{ 1035 PkScript: senderHtlcPkScript, 1036 Value: htlcResolution.SweepSignDesc.Output.Value, 1037 }) 1038 htlcResolution.SweepSignDesc.InputIndex = 0 1039 witness, err := input.HtlcSpendSuccess(aliceChannel.Signer, 1040 &htlcResolution.SweepSignDesc, sweepTx, 1041 uint32(aliceChannel.channelState.LocalChanCfg.CsvDelay)) 1042 if err != nil { 1043 t.Fatalf("unable to gen witness for timeout output: %v", err) 1044 } 1045 sweepTx.TxIn[0].SignatureScript, err = input.WitnessStackToSigScript(witness) 1046 if err != nil { 1047 t.Fatalf("unable to convert witness stack to sigScript: %v", err) 1048 } 1049 1050 // With the witness fully populated for the success spend from the 1051 // second-level transaction, we ensure that the scripts properly 1052 // validate given the information within the htlc resolution struct. 1053 vm, err = txscript.NewEngine( 1054 htlcResolution.SweepSignDesc.Output.PkScript, 1055 sweepTx, 0, input.ScriptVerifyFlags, 1056 htlcResolution.SweepSignDesc.Output.Version, nil, 1057 ) 1058 if err != nil { 1059 t.Fatalf("unable to create engine: %v", err) 1060 } 1061 if err := vm.Execute(); err != nil { 1062 t.Fatalf("htlc timeout spend is invalid: %v", err) 1063 } 1064 1065 // Finally, the txid of the commitment transaction and the one returned 1066 // as the closing transaction should also match. 1067 closeTxHash := closeSummary.CloseTx.TxHash() 1068 commitTxHash := aliceChannel.channelState.LocalCommitment.CommitTx.TxHash() 1069 if !bytes.Equal(closeTxHash[:], commitTxHash[:]) { 1070 t.Fatalf("alice: incorrect close transaction txid") 1071 } 1072 1073 // We'll now perform similar set of checks to ensure that Alice is able 1074 // to sweep the output that Bob sent to her on-chain with knowledge of 1075 // the preimage. 1076 inHtlcResolution := closeSummary.HtlcResolutions.IncomingHTLCs[0] 1077 inHtlcIndex := inHtlcResolution.SignedSuccessTx.TxIn[0].PreviousOutPoint.Index 1078 receiverHtlcScript := closeSummary.CloseTx.TxOut[inHtlcIndex].PkScript 1079 receiverHtlcScriptVersion := closeSummary.CloseTx.TxOut[inHtlcIndex].Version 1080 1081 // With the original pkscript located, we'll now verify that the second 1082 // level transaction can spend from the multi-sig out. Supply the 1083 // preimage manually. This is usually done by the contract resolver 1084 // before publication. 1085 successTx := inHtlcResolution.SignedSuccessTx 1086 successTx.TxIn[0].SignatureScript, err = input.ReplaceReceiverHtlcSpendRedeemPreimage( 1087 successTx.TxIn[0].SignatureScript, preimageBob[:], 1088 ) 1089 if err != nil { 1090 t.Fatalf("unable to replace preimage in sigScript: %v", err) 1091 } 1092 vm, err = txscript.NewEngine(receiverHtlcScript, 1093 successTx, 0, input.ScriptVerifyFlags, receiverHtlcScriptVersion, nil) 1094 if err != nil { 1095 t.Fatalf("unable to create engine: %v", err) 1096 } 1097 if err := vm.Execute(); err != nil { 1098 t.Fatalf("htlc success spend is invalid: %v", err) 1099 } 1100 1101 // Finally, we'll construct a transaction to spend the produced 1102 // second-level output with the attached input.SignDescriptor. 1103 sweepTx = wire.NewMsgTx() 1104 sweepTx.AddTxIn(&wire.TxIn{ 1105 PreviousOutPoint: inHtlcResolution.ClaimOutpoint, 1106 }) 1107 sweepTx.AddTxOut(&wire.TxOut{ 1108 PkScript: receiverHtlcScript, 1109 Value: inHtlcResolution.SweepSignDesc.Output.Value, 1110 }) 1111 inHtlcResolution.SweepSignDesc.InputIndex = 0 1112 witness, err = input.HtlcSpendSuccess(aliceChannel.Signer, 1113 &inHtlcResolution.SweepSignDesc, sweepTx, 1114 uint32(aliceChannel.channelState.LocalChanCfg.CsvDelay)) 1115 if err != nil { 1116 t.Fatalf("unable to gen witness for timeout output: %v", err) 1117 } 1118 sweepTx.TxIn[0].SignatureScript, err = input.WitnessStackToSigScript(witness) 1119 if err != nil { 1120 t.Fatalf("unable to convert witness stack to sigScript: %v", err) 1121 } 1122 1123 // The spend we create above spending the second level HTLC output 1124 // should validate without any issues. 1125 vm, err = txscript.NewEngine( 1126 inHtlcResolution.SweepSignDesc.Output.PkScript, 1127 sweepTx, 0, input.ScriptVerifyFlags, 1128 inHtlcResolution.SweepSignDesc.Output.Version, nil, 1129 ) 1130 if err != nil { 1131 t.Fatalf("unable to create engine: %v", err) 1132 } 1133 if err := vm.Execute(); err != nil { 1134 t.Fatalf("htlc timeout spend is invalid: %v", err) 1135 } 1136 1137 // Check the same for Bob's ForceCloseSummary. 1138 closeSummary, err = bobChannel.ForceClose() 1139 if err != nil { 1140 t.Fatalf("unable to force close channel: %v", err) 1141 } 1142 bobCommitResolution := closeSummary.CommitResolution 1143 if bobCommitResolution == nil { 1144 t.Fatalf("bob fails to include to-self output in ForceCloseSummary") 1145 } 1146 bobDelayPoint := bobChannel.channelState.LocalChanCfg.DelayBasePoint 1147 if !bobCommitResolution.SelfOutputSignDesc.KeyDesc.PubKey.IsEqual(bobDelayPoint.PubKey) { 1148 t.Fatalf("bob incorrect pubkey in SelfOutputSignDesc") 1149 } 1150 if bobCommitResolution.SelfOutputSignDesc.Output.Value != 1151 int64(bobAmount.ToAtoms()-htlcAmount.ToAtoms()) { 1152 1153 t.Fatalf("bob incorrect output value in SelfOutputSignDesc, "+ 1154 "expected %v, got %v", 1155 bobAmount.ToAtoms(), 1156 bobCommitResolution.SelfOutputSignDesc.Output.Value) 1157 } 1158 if bobCommitResolution.MaturityDelay != 1159 uint32(bobChannel.channelState.LocalChanCfg.CsvDelay) { 1160 1161 t.Fatalf("bob: incorrect local CSV delay in ForceCloseSummary, "+ 1162 "expected %v, got %v", 1163 bobChannel.channelState.LocalChanCfg.CsvDelay, 1164 bobCommitResolution.MaturityDelay) 1165 } 1166 1167 closeTxHash = closeSummary.CloseTx.TxHash() 1168 commitTxHash = bobChannel.channelState.LocalCommitment.CommitTx.TxHash() 1169 if !bytes.Equal(closeTxHash[:], commitTxHash[:]) { 1170 t.Fatalf("bob: incorrect close transaction txid") 1171 } 1172 1173 // As we didn't add the preimage of Alice's HTLC to bob's preimage 1174 // cache, he should only detect that he can sweep only his outgoing 1175 // HTLC upon force close. 1176 if len(closeSummary.HtlcResolutions.OutgoingHTLCs) != 1 { 1177 t.Fatalf("alice out htlc resolutions not populated: expected %v "+ 1178 "htlcs, got %v htlcs", 1179 1, len(closeSummary.HtlcResolutions.OutgoingHTLCs)) 1180 } 1181 1182 // Bob should recognize that the incoming HTLC is there, but the 1183 // preimage should be empty as he doesn't have the knowledge required 1184 // to sweep it. 1185 if len(closeSummary.HtlcResolutions.IncomingHTLCs) != 1 { 1186 t.Fatalf("bob in htlc resolutions not populated: expected %v "+ 1187 "htlcs, got %v htlcs", 1188 1, len(closeSummary.HtlcResolutions.IncomingHTLCs)) 1189 } 1190 } 1191 1192 // TestForceCloseDustOutput tests that if either side force closes with an 1193 // active dust output (for only a single party due to asymmetric dust values), 1194 // then the force close summary is well crafted. 1195 func TestForceCloseDustOutput(t *testing.T) { 1196 t.Parallel() 1197 1198 // Create a test channel which will be used for the duration of this 1199 // unittest. The channel will be funded evenly with Alice having 5 DCR, 1200 // and Bob having 5 DCR. 1201 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1202 channeldb.SingleFunderTweaklessBit, 1203 ) 1204 if err != nil { 1205 t.Fatalf("unable to create test channels: %v", err) 1206 } 1207 defer cleanUp() 1208 1209 // We set both node's channel reserves to 0, to make sure 1210 // they can create small dust ouputs without going under 1211 // their channel reserves. 1212 aliceChannel.channelState.LocalChanCfg.ChanReserve = 0 1213 bobChannel.channelState.LocalChanCfg.ChanReserve = 0 1214 aliceChannel.channelState.RemoteChanCfg.ChanReserve = 0 1215 bobChannel.channelState.RemoteChanCfg.ChanReserve = 0 1216 1217 htlcAmount := lnwire.NewMAtomsFromAtoms(500) 1218 1219 bobAmount := bobChannel.channelState.LocalCommitment.LocalBalance 1220 1221 // Have Bobs' to-self output be below her dust limit and check 1222 // ForceCloseSummary again on both peers. 1223 htlc, preimage := createHTLC(0, bobAmount-htlcAmount) 1224 bobHtlcIndex, err := bobChannel.AddHTLC(htlc, nil) 1225 if err != nil { 1226 t.Fatalf("alice unable to add htlc: %v", err) 1227 } 1228 aliceHtlcIndex, err := aliceChannel.ReceiveHTLC(htlc) 1229 if err != nil { 1230 t.Fatalf("bob unable to receive htlc: %v", err) 1231 } 1232 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 1233 t.Fatalf("Can't update the channel state: %v", err) 1234 } 1235 1236 // Settle HTLC and sign new commitment. 1237 err = aliceChannel.SettleHTLC(preimage, aliceHtlcIndex, nil, nil, nil) 1238 if err != nil { 1239 t.Fatalf("bob unable to settle inbound htlc: %v", err) 1240 } 1241 err = bobChannel.ReceiveHTLCSettle(preimage, bobHtlcIndex) 1242 if err != nil { 1243 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 1244 } 1245 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 1246 t.Fatalf("Can't update the channel state: %v", err) 1247 } 1248 1249 aliceAmount := aliceChannel.channelState.LocalCommitment.LocalBalance 1250 1251 closeSummary, err := aliceChannel.ForceClose() 1252 if err != nil { 1253 t.Fatalf("unable to force close channel: %v", err) 1254 } 1255 1256 // Alice's to-self output should still be in the commitment 1257 // transaction. 1258 commitResolution := closeSummary.CommitResolution 1259 if commitResolution == nil { 1260 t.Fatalf("alice fails to include to-self output in " + 1261 "ForceCloseSummary") 1262 } 1263 if !commitResolution.SelfOutputSignDesc.KeyDesc.PubKey.IsEqual( 1264 aliceChannel.channelState.LocalChanCfg.DelayBasePoint.PubKey, 1265 ) { 1266 t.Fatalf("alice incorrect pubkey in SelfOutputSignDesc") 1267 } 1268 if commitResolution.SelfOutputSignDesc.Output.Value != 1269 int64(aliceAmount.ToAtoms()) { 1270 t.Fatalf("alice incorrect output value in SelfOutputSignDesc, "+ 1271 "expected %v, got %v", 1272 aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms(), 1273 commitResolution.SelfOutputSignDesc.Output.Value) 1274 } 1275 1276 if commitResolution.MaturityDelay != 1277 uint32(aliceChannel.channelState.LocalChanCfg.CsvDelay) { 1278 t.Fatalf("alice: incorrect local CSV delay in ForceCloseSummary, "+ 1279 "expected %v, got %v", 1280 aliceChannel.channelState.LocalChanCfg.CsvDelay, 1281 commitResolution.MaturityDelay) 1282 } 1283 1284 closeTxHash := closeSummary.CloseTx.TxHash() 1285 commitTxHash := aliceChannel.channelState.LocalCommitment.CommitTx.TxHash() 1286 if !bytes.Equal(closeTxHash[:], commitTxHash[:]) { 1287 t.Fatalf("alice: incorrect close transaction txid") 1288 } 1289 1290 closeSummary, err = bobChannel.ForceClose() 1291 if err != nil { 1292 t.Fatalf("unable to force close channel: %v", err) 1293 } 1294 1295 // Bob's to-self output is below Bob's dust value and should be 1296 // reflected in the ForceCloseSummary. 1297 commitResolution = closeSummary.CommitResolution 1298 if commitResolution != nil { 1299 t.Fatalf("bob incorrectly includes to-self output in " + 1300 "ForceCloseSummary") 1301 } 1302 1303 closeTxHash = closeSummary.CloseTx.TxHash() 1304 commitTxHash = bobChannel.channelState.LocalCommitment.CommitTx.TxHash() 1305 if !bytes.Equal(closeTxHash[:], commitTxHash[:]) { 1306 t.Fatalf("bob: incorrect close transaction txid") 1307 } 1308 } 1309 1310 // TestDustHTLCFees checks that fees are calculated correctly when HTLCs fall 1311 // below the nodes' dust limit. In these cases, the amount of the dust HTLCs 1312 // should be applied to the commitment transaction fee. 1313 func TestDustHTLCFees(t *testing.T) { 1314 t.Parallel() 1315 1316 // Create a test channel which will be used for the duration of this 1317 // unittest. The channel will be funded evenly with Alice having 5 DCR, 1318 // and Bob having 5 DCR. 1319 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1320 channeldb.SingleFunderTweaklessBit, 1321 ) 1322 if err != nil { 1323 t.Fatalf("unable to create test channels: %v", err) 1324 } 1325 defer cleanUp() 1326 1327 aliceStartingBalance := aliceChannel.channelState.LocalCommitment.LocalBalance 1328 1329 // This HTLC amount should be lower than the dust limits of both nodes. 1330 htlcAmount := lnwire.NewMAtomsFromAtoms(100) 1331 htlc, _ := createHTLC(0, htlcAmount) 1332 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 1333 t.Fatalf("alice unable to add htlc: %v", err) 1334 } 1335 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 1336 t.Fatalf("bob unable to receive htlc: %v", err) 1337 } 1338 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 1339 t.Fatalf("Can't update the channel state: %v", err) 1340 } 1341 1342 // After the transition, we'll ensure that we performed fee accounting 1343 // properly. Namely, the local+remote+commitfee values should add up to 1344 // the total capacity of the channel. This same should hold for both 1345 // sides. 1346 totalAtomsAlice := (aliceChannel.channelState.LocalCommitment.LocalBalance + 1347 aliceChannel.channelState.LocalCommitment.RemoteBalance + 1348 lnwire.NewMAtomsFromAtoms(aliceChannel.channelState.LocalCommitment.CommitFee)) 1349 if totalAtomsAlice+htlcAmount != lnwire.NewMAtomsFromAtoms(aliceChannel.Capacity) { 1350 t.Fatalf("alice's funds leaked: total atoms are %v, but channel "+ 1351 "capacity is %v", int64(totalAtomsAlice), 1352 int64(aliceChannel.Capacity)) 1353 } 1354 totalAtomsBob := (bobChannel.channelState.LocalCommitment.LocalBalance + 1355 bobChannel.channelState.LocalCommitment.RemoteBalance + 1356 lnwire.NewMAtomsFromAtoms(bobChannel.channelState.LocalCommitment.CommitFee)) 1357 if totalAtomsBob+htlcAmount != lnwire.NewMAtomsFromAtoms(bobChannel.Capacity) { 1358 t.Fatalf("bob's funds leaked: total atoms are %v, but channel "+ 1359 "capacity is %v", int64(totalAtomsBob), 1360 int64(bobChannel.Capacity)) 1361 } 1362 1363 // The commitment fee paid should be the same, as there have been no 1364 // new material outputs added. 1365 defaultFee := calcStaticFee(channeldb.SingleFunderTweaklessBit, 0) 1366 if aliceChannel.channelState.LocalCommitment.CommitFee != defaultFee { 1367 t.Fatalf("dust htlc amounts not subtracted from commitment fee "+ 1368 "expected %v, got %v", defaultFee, 1369 aliceChannel.channelState.LocalCommitment.CommitFee) 1370 } 1371 if bobChannel.channelState.LocalCommitment.CommitFee != defaultFee { 1372 t.Fatalf("dust htlc amounts not subtracted from commitment fee "+ 1373 "expected %v, got %v", defaultFee, 1374 bobChannel.channelState.LocalCommitment.CommitFee) 1375 } 1376 1377 // Alice's final balance should reflect the HTLC deficit even though 1378 // the HTLC was paid to fees as it was trimmed. 1379 aliceEndBalance := aliceChannel.channelState.LocalCommitment.LocalBalance 1380 aliceExpectedBalance := aliceStartingBalance - htlcAmount 1381 if aliceEndBalance != aliceExpectedBalance { 1382 t.Fatalf("alice not credited for dust: expected %v, got %v", 1383 aliceExpectedBalance, aliceEndBalance) 1384 } 1385 } 1386 1387 // TestHTLCDustLimit checks the situation in which an HTLC is larger than one 1388 // channel participant's dust limit, but smaller than the other participant's 1389 // dust limit. In this case, the participants' commitment chains will diverge. 1390 // In one commitment chain, the HTLC will be added as normal, in the other 1391 // chain, the amount of the HTLC will contribute to the fees to be paid. 1392 func TestHTLCDustLimit(t *testing.T) { 1393 t.Parallel() 1394 1395 // Create a test channel which will be used for the duration of this 1396 // unittest. The channel will be funded evenly with Alice having 5 DCR, 1397 // and Bob having 5 DCR. 1398 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1399 channeldb.SingleFunderTweaklessBit, 1400 ) 1401 if err != nil { 1402 t.Fatalf("unable to create test channels: %v", err) 1403 } 1404 defer cleanUp() 1405 1406 // The amount of the HTLC should be above Alice's dust limit and below 1407 // Bob's dust limit. 1408 htlcAtoms := dcrutil.Amount(8000) + HtlcTimeoutFee( 1409 aliceChannel.channelState.ChanType, 1410 chainfee.AtomPerKByte( 1411 aliceChannel.channelState.LocalCommitment.FeePerKB, 1412 ), 1413 ) 1414 htlcAmount := lnwire.NewMAtomsFromAtoms(htlcAtoms) 1415 1416 htlc, preimage := createHTLC(0, htlcAmount) 1417 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 1418 if err != nil { 1419 t.Fatalf("alice unable to add htlc: %v", err) 1420 } 1421 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 1422 if err != nil { 1423 t.Fatalf("bob unable to receive htlc: %v", err) 1424 } 1425 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 1426 t.Fatalf("Can't update the channel state: %v", err) 1427 } 1428 1429 // At this point, Alice's commitment transaction should have an HTLC, 1430 // while Bob's should not, because the value falls beneath his dust 1431 // limit. The amount of the HTLC should be applied to fees in Bob's 1432 // commitment transaction. 1433 aliceCommitment := aliceChannel.localCommitChain.tip() 1434 if len(aliceCommitment.txn.TxOut) != 3 { 1435 t.Fatalf("incorrect # of outputs: expected %v, got %v", 1436 3, len(aliceCommitment.txn.TxOut)) 1437 } 1438 bobCommitment := bobChannel.localCommitChain.tip() 1439 if len(bobCommitment.txn.TxOut) != 2 { 1440 t.Fatalf("incorrect # of outputs: expected %v, got %v", 1441 2, len(bobCommitment.txn.TxOut)) 1442 } 1443 defaultFee := calcStaticFee(channeldb.SingleFunderTweaklessBit, 0) 1444 if bobChannel.channelState.LocalCommitment.CommitFee != defaultFee { 1445 t.Fatalf("dust htlc amount was subtracted from commitment fee "+ 1446 "expected %v, got %v", defaultFee, 1447 bobChannel.channelState.LocalCommitment.CommitFee) 1448 } 1449 1450 // Settle HTLC and create a new commitment state. 1451 err = bobChannel.SettleHTLC(preimage, bobHtlcIndex, nil, nil, nil) 1452 if err != nil { 1453 t.Fatalf("bob unable to settle inbound htlc: %v", err) 1454 } 1455 err = aliceChannel.ReceiveHTLCSettle(preimage, aliceHtlcIndex) 1456 if err != nil { 1457 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 1458 } 1459 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 1460 t.Fatalf("state transition error: %v", err) 1461 } 1462 1463 // At this point, for Alice's commitment chains, the value of the HTLC 1464 // should have been added to Alice's balance and TotalMatomsSent. 1465 commitment := aliceChannel.localCommitChain.tip() 1466 if len(commitment.txn.TxOut) != 2 { 1467 t.Fatalf("incorrect # of outputs: expected %v, got %v", 1468 2, len(commitment.txn.TxOut)) 1469 } 1470 if aliceChannel.channelState.TotalMAtomsSent != htlcAmount { 1471 t.Fatalf("alice atoms sent incorrect: expected %v, got %v", 1472 htlcAmount, aliceChannel.channelState.TotalMAtomsSent) 1473 } 1474 } 1475 1476 // TestHTLCSigNumber tests that a received commitment is only accepted if it 1477 // comes with the exact number of valid HTLC signatures. 1478 func TestHTLCSigNumber(t *testing.T) { 1479 t.Parallel() 1480 1481 // createChanWithHTLC is a helper method that sets ut two channels, and 1482 // adds HTLCs with the passed values to the channels. 1483 createChanWithHTLC := func(htlcValues ...dcrutil.Amount) ( 1484 *LightningChannel, *LightningChannel, func()) { 1485 1486 // Create a test channel funded evenly with Alice having 5 DCR, 1487 // and Bob having 5 DCR. Alice's dustlimit is 200 Atoms, while 1488 // Bob has 1300 Atoms. 1489 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1490 channeldb.SingleFunderTweaklessBit, 1491 ) 1492 if err != nil { 1493 t.Fatalf("unable to create test channels: %v", err) 1494 } 1495 1496 for i, htlcAtoms := range htlcValues { 1497 htlcMAtoms := lnwire.NewMAtomsFromAtoms(htlcAtoms) 1498 htlc, _ := createHTLC(i, htlcMAtoms) 1499 _, err := aliceChannel.AddHTLC(htlc, nil) 1500 if err != nil { 1501 t.Fatalf("alice unable to add htlc: %v", err) 1502 } 1503 _, err = bobChannel.ReceiveHTLC(htlc) 1504 if err != nil { 1505 t.Fatalf("bob unable to receive htlc: %v", err) 1506 } 1507 } 1508 1509 return aliceChannel, bobChannel, cleanUp 1510 } 1511 1512 // Calculate two values that will be below and above Bob's dust limit. 1513 estimator := chainfee.NewStaticEstimator(1e5, 0) 1514 feePerKB, err := estimator.EstimateFeePerKB(1) 1515 if err != nil { 1516 t.Fatalf("unable to get fee: %v", err) 1517 } 1518 1519 belowDust := dcrutil.Amount(5000) + HtlcTimeoutFee( 1520 channeldb.SingleFunderTweaklessBit, feePerKB, 1521 ) 1522 aboveDust := dcrutil.Amount(14000) + HtlcSuccessFee( 1523 channeldb.SingleFunderTweaklessBit, feePerKB, 1524 ) 1525 1526 // =================================================================== 1527 // Test that Bob will reject a commitment if Alice doesn't send enough 1528 // HTLC signatures. 1529 // =================================================================== 1530 aliceChannel, bobChannel, cleanUp := createChanWithHTLC(aboveDust, 1531 aboveDust) 1532 defer cleanUp() 1533 1534 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 1535 if err != nil { 1536 t.Fatalf("Error signing next commitment: %v", err) 1537 } 1538 1539 if len(aliceHtlcSigs) != 2 { 1540 t.Fatalf("expected 2 htlc sig, instead got %v", 1541 len(aliceHtlcSigs)) 1542 } 1543 1544 // Now discard one signature from the htlcSig slice. Bob should reject 1545 // the commitment because of this. 1546 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs[1:]) 1547 if err == nil { 1548 t.Fatalf("Expected Bob to reject signatures") 1549 } 1550 1551 // =================================================================== 1552 // Test that Bob will reject a commitment if Alice doesn't send any 1553 // HTLC signatures. 1554 // =================================================================== 1555 aliceChannel, bobChannel, cleanUp = createChanWithHTLC(aboveDust) 1556 defer cleanUp() 1557 1558 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 1559 if err != nil { 1560 t.Fatalf("Error signing next commitment: %v", err) 1561 } 1562 1563 if len(aliceHtlcSigs) != 1 { 1564 t.Fatalf("expected 1 htlc sig, instead got %v", 1565 len(aliceHtlcSigs)) 1566 } 1567 1568 // Now just give Bob an empty htlcSig slice. He should reject the 1569 // commitment because of this. 1570 err = bobChannel.ReceiveNewCommitment(aliceSig, []lnwire.Sig{}) 1571 if err == nil { 1572 t.Fatalf("Expected Bob to reject signatures") 1573 } 1574 1575 // ============================================================== 1576 // Test that sigs are not returned for HTLCs below dust limit. 1577 // ============================================================== 1578 aliceChannel, bobChannel, cleanUp = createChanWithHTLC(belowDust) 1579 defer cleanUp() 1580 1581 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 1582 if err != nil { 1583 t.Fatalf("Error signing next commitment: %v", err) 1584 } 1585 1586 // Since the HTLC is below Bob's dust limit, Alice won't need to send 1587 // any signatures for this HTLC. 1588 if len(aliceHtlcSigs) != 0 { 1589 t.Fatalf("expected no htlc sigs, instead got %v", 1590 len(aliceHtlcSigs)) 1591 } 1592 1593 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 1594 if err != nil { 1595 t.Fatalf("Bob failed receiving commitment: %v", err) 1596 } 1597 1598 // ================================================================ 1599 // Test that sigs are correctly returned for HTLCs above dust limit. 1600 // ================================================================ 1601 aliceChannel, bobChannel, cleanUp = createChanWithHTLC(aboveDust) 1602 defer cleanUp() 1603 1604 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 1605 if err != nil { 1606 t.Fatalf("Error signing next commitment: %v", err) 1607 } 1608 1609 // Since the HTLC is above Bob's dust limit, Alice should send a 1610 // signature for this HTLC. 1611 if len(aliceHtlcSigs) != 1 { 1612 t.Fatalf("expected 1 htlc sig, instead got %v", 1613 len(aliceHtlcSigs)) 1614 } 1615 1616 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 1617 if err != nil { 1618 t.Fatalf("Bob failed receiving commitment: %v", err) 1619 } 1620 1621 // ==================================================================== 1622 // Test that Bob will not validate a received commitment if Alice sends 1623 // signatures for HTLCs below the dust limit. 1624 // ==================================================================== 1625 aliceChannel, bobChannel, cleanUp = createChanWithHTLC(belowDust, 1626 aboveDust) 1627 defer cleanUp() 1628 1629 // Alice should produce only one signature, since one HTLC is below 1630 // dust. 1631 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 1632 if err != nil { 1633 t.Fatalf("Error signing next commitment: %v", err) 1634 } 1635 1636 if len(aliceHtlcSigs) != 1 { 1637 t.Fatalf("expected 1 htlc sig, instead got %v", 1638 len(aliceHtlcSigs)) 1639 } 1640 1641 // Add an extra signature. 1642 aliceHtlcSigs = append(aliceHtlcSigs, aliceHtlcSigs[0]) 1643 1644 // Bob should reject these signatures since they don't match the number 1645 // of HTLCs above dust. 1646 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 1647 if err == nil { 1648 t.Fatalf("Expected Bob to reject signatures") 1649 } 1650 } 1651 1652 // TestChannelBalanceDustLimit tests the condition when the remaining balance 1653 // for one of the channel participants is so small as to be considered dust. In 1654 // this case, the output for that participant is removed and all funds (minus 1655 // fees) in the commitment transaction are allocated to the remaining channel 1656 // participant. 1657 // 1658 // TODO(roasbeef): test needs to be fixed after reserve limits are done 1659 func TestChannelBalanceDustLimit(t *testing.T) { 1660 t.Parallel() 1661 1662 // Create a test channel which will be used for the duration of this 1663 // unittest. The channel will be funded evenly with Alice having 5 DCR, 1664 // and Bob having 5 DCR. 1665 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1666 channeldb.SingleFunderTweaklessBit, 1667 ) 1668 if err != nil { 1669 t.Fatalf("unable to create test channels: %v", err) 1670 } 1671 defer cleanUp() 1672 1673 aliceDustLimit := aliceChannel.channelState.LocalChanCfg.DustLimit 1674 bobDustLimit := bobChannel.channelState.LocalChanCfg.DustLimit 1675 if aliceDustLimit >= bobDustLimit { 1676 t.Fatalf("failed test precondition: aliceDustLimit must be < bobDustLimit") 1677 } 1678 1679 // To allow Alice's balance to get beneath her dust limit, set the 1680 // channel reserve to be 0. 1681 aliceChannel.channelState.LocalChanCfg.ChanReserve = 0 1682 bobChannel.channelState.RemoteChanCfg.ChanReserve = 0 1683 1684 // Figure out how much it will cost to add an HTLC to the channel. 1685 chanType := channeldb.SingleFunderTweaklessBit 1686 htlcFee := calcStaticFee(chanType, 1) - calcStaticFee(chanType, 0) 1687 1688 // Select how much to send from alice to bob. This must be enough so that 1689 // the remaining balance in alice's commitment output is higher than her 1690 // dust limit but lower than bob's dust limit, causing bob to remove that 1691 // output from his commitment transaction. 1692 aliceBalance := aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms() 1693 htlcAtoms := aliceBalance - htlcFee - aliceDustLimit - 1 1694 1695 htlcAmount := lnwire.NewMAtomsFromAtoms(htlcAtoms) 1696 htlc, preimage := createHTLC(0, htlcAmount) 1697 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 1698 if err != nil { 1699 t.Fatalf("alice unable to add htlc: %v", err) 1700 } 1701 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 1702 if err != nil { 1703 t.Fatalf("bob unable to receive htlc: %v", err) 1704 } 1705 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 1706 t.Fatalf("state transition error: %v", err) 1707 } 1708 err = bobChannel.SettleHTLC(preimage, bobHtlcIndex, nil, nil, nil) 1709 if err != nil { 1710 t.Fatalf("bob unable to settle inbound htlc: %v", err) 1711 } 1712 err = aliceChannel.ReceiveHTLCSettle(preimage, aliceHtlcIndex) 1713 if err != nil { 1714 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 1715 } 1716 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 1717 t.Fatalf("state transition error: %v", err) 1718 } 1719 1720 // At the conclusion of this test, in Bob's commitment chains, the 1721 // output for Alice's balance should have been removed as dust, leaving 1722 // only a single output that will send the remaining funds in the 1723 // channel to Bob. Alice should still have 2 outputs, given that we 1724 // built the htlc to specifically leave some amount to her. 1725 bobCommitment := bobChannel.localCommitChain.tip() 1726 if len(bobCommitment.txn.TxOut) != 1 { 1727 t.Fatalf("incorrect # of outputs for bob: expected %v, got %v", 1728 1, len(bobCommitment.txn.TxOut)) 1729 } 1730 if aliceChannel.channelState.TotalMAtomsSent != htlcAmount { 1731 t.Fatalf("alice atoms sent incorrect: expected %v, got %v", 1732 htlcAmount, aliceChannel.channelState.TotalMAtomsSent) 1733 } 1734 aliceCommitment := aliceChannel.localCommitChain.tip() 1735 if len(aliceCommitment.txn.TxOut) != 2 { 1736 t.Fatalf("incorrect # of outputs for alice: expected %v, got %v", 1737 2, len(aliceCommitment.txn.TxOut)) 1738 } 1739 } 1740 1741 func TestStateUpdatePersistence(t *testing.T) { 1742 t.Parallel() 1743 1744 // Create a test channel which will be used for the duration of this 1745 // unittest. The channel will be funded evenly with Alice having 5 DCR, 1746 // and Bob having 5 DCR. 1747 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 1748 channeldb.SingleFunderTweaklessBit, 1749 ) 1750 if err != nil { 1751 t.Fatalf("unable to create test channels: %v", err) 1752 } 1753 defer cleanUp() 1754 1755 htlcAmt := lnwire.NewMAtomsFromAtoms(5000) 1756 1757 var fakeOnionBlob [lnwire.OnionPacketSize]byte 1758 copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) 1759 1760 // Alice adds 3 HTLCs to the update log, while Bob adds a single HTLC. 1761 var alicePreimage [32]byte 1762 copy(alicePreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 1763 var bobPreimage [32]byte 1764 copy(bobPreimage[:], bytes.Repeat([]byte{0xbb}, 32)) 1765 for i := 0; i < 3; i++ { 1766 rHash := sha256.Sum256(alicePreimage[:]) 1767 h := &lnwire.UpdateAddHTLC{ 1768 ID: uint64(i), 1769 PaymentHash: rHash, 1770 Amount: htlcAmt, 1771 Expiry: uint32(10), 1772 OnionBlob: fakeOnionBlob, 1773 } 1774 1775 if _, err := aliceChannel.AddHTLC(h, nil); err != nil { 1776 t.Fatalf("unable to add alice's htlc: %v", err) 1777 } 1778 if _, err := bobChannel.ReceiveHTLC(h); err != nil { 1779 t.Fatalf("unable to recv alice's htlc: %v", err) 1780 } 1781 } 1782 rHash := sha256.Sum256(bobPreimage[:]) 1783 bobh := &lnwire.UpdateAddHTLC{ 1784 PaymentHash: rHash, 1785 Amount: htlcAmt, 1786 Expiry: uint32(10), 1787 OnionBlob: fakeOnionBlob, 1788 } 1789 if _, err := bobChannel.AddHTLC(bobh, nil); err != nil { 1790 t.Fatalf("unable to add bob's htlc: %v", err) 1791 } 1792 if _, err := aliceChannel.ReceiveHTLC(bobh); err != nil { 1793 t.Fatalf("unable to recv bob's htlc: %v", err) 1794 } 1795 1796 // Also add a fee update to the update logs. 1797 fee := chainfee.AtomPerKByte(2e4) 1798 if err := aliceChannel.UpdateFee(fee); err != nil { 1799 t.Fatalf("unable to send fee update") 1800 } 1801 if err := bobChannel.ReceiveUpdateFee(fee); err != nil { 1802 t.Fatalf("unable to receive fee update") 1803 } 1804 1805 // Helper method that asserts the expected number of updates are found 1806 // in the update logs. 1807 assertNumLogUpdates := func(numAliceUpdates, numBobUpdates int) { 1808 if aliceChannel.localUpdateLog.Len() != numAliceUpdates { 1809 t.Fatalf("expected %d local updates, found %d", 1810 numAliceUpdates, 1811 aliceChannel.localUpdateLog.Len()) 1812 } 1813 if aliceChannel.remoteUpdateLog.Len() != numBobUpdates { 1814 t.Fatalf("expected %d remote updates, found %d", 1815 numBobUpdates, 1816 aliceChannel.remoteUpdateLog.Len()) 1817 } 1818 1819 if bobChannel.localUpdateLog.Len() != numBobUpdates { 1820 t.Fatalf("expected %d local updates, found %d", 1821 numBobUpdates, 1822 bobChannel.localUpdateLog.Len()) 1823 } 1824 if bobChannel.remoteUpdateLog.Len() != numAliceUpdates { 1825 t.Fatalf("expected %d remote updates, found %d", 1826 numAliceUpdates, 1827 bobChannel.remoteUpdateLog.Len()) 1828 } 1829 } 1830 1831 // Both nodes should now have Alice's 3 Adds and 1 FeeUpdate in the 1832 // log, and Bob's 1 Add. 1833 assertNumLogUpdates(4, 1) 1834 1835 // Next, Alice initiates a state transition to include the HTLC's she 1836 // added above in a new commitment state. 1837 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 1838 t.Fatalf("unable to complete alice's state transition: %v", err) 1839 } 1840 1841 // Since the HTLC Bob sent wasn't included in Bob's version of the 1842 // commitment transaction (but it was in Alice's, as he ACK'd her 1843 // changes before creating a new state), Bob needs to trigger another 1844 // state update in order to re-sync their states. 1845 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 1846 t.Fatalf("unable to complete bob's state transition: %v", err) 1847 } 1848 1849 // After the state transition the fee update is fully locked in, and 1850 // should've been removed from both channels' update logs. 1851 if aliceChannel.localCommitChain.tail().feePerKB != fee { 1852 t.Fatalf("fee not locked in") 1853 } 1854 if bobChannel.localCommitChain.tail().feePerKB != fee { 1855 t.Fatalf("fee not locked in") 1856 } 1857 assertNumLogUpdates(3, 1) 1858 1859 // The latest commitment from both sides should have all the HTLCs. 1860 numAliceOutgoing := aliceChannel.localCommitChain.tail().outgoingHTLCs 1861 numAliceIncoming := aliceChannel.localCommitChain.tail().incomingHTLCs 1862 if len(numAliceOutgoing) != 3 { 1863 t.Fatalf("expected %v htlcs, instead got %v", 3, numAliceOutgoing) 1864 } 1865 if len(numAliceIncoming) != 1 { 1866 t.Fatalf("expected %v htlcs, instead got %v", 1, numAliceIncoming) 1867 } 1868 numBobOutgoing := bobChannel.localCommitChain.tail().outgoingHTLCs 1869 numBobIncoming := bobChannel.localCommitChain.tail().incomingHTLCs 1870 if len(numBobOutgoing) != 1 { 1871 t.Fatalf("expected %v htlcs, instead got %v", 1, numBobOutgoing) 1872 } 1873 if len(numBobIncoming) != 3 { 1874 t.Fatalf("expected %v htlcs, instead got %v", 3, numBobIncoming) 1875 } 1876 1877 // TODO(roasbeef): also ensure signatures were stored 1878 // * ensure expiry matches 1879 1880 // Now fetch both of the channels created above from disk to simulate a 1881 // node restart with persistence. 1882 alicePub := aliceChannel.channelState.IdentityPub 1883 aliceChannels, err := aliceChannel.channelState.Db.FetchOpenChannels( 1884 alicePub, 1885 ) 1886 if err != nil { 1887 t.Fatalf("unable to fetch channel: %v", err) 1888 } 1889 bobPub := bobChannel.channelState.IdentityPub 1890 bobChannels, err := bobChannel.channelState.Db.FetchOpenChannels(bobPub) 1891 if err != nil { 1892 t.Fatalf("unable to fetch channel: %v", err) 1893 } 1894 1895 aliceChannelNew, err := NewLightningChannel( 1896 aliceChannel.Signer, aliceChannels[0], aliceChannel.sigPool, 1897 testChainParams, 1898 ) 1899 if err != nil { 1900 t.Fatalf("unable to create new channel: %v", err) 1901 } 1902 1903 bobChannelNew, err := NewLightningChannel( 1904 bobChannel.Signer, bobChannels[0], bobChannel.sigPool, 1905 testChainParams, 1906 ) 1907 if err != nil { 1908 t.Fatalf("unable to create new channel: %v", err) 1909 } 1910 1911 // The state update logs of the new channels and the old channels 1912 // should now be identical other than the height the HTLCs were added. 1913 if aliceChannel.localUpdateLog.logIndex != 1914 aliceChannelNew.localUpdateLog.logIndex { 1915 t.Fatalf("alice log counter: expected %v, got %v", 1916 aliceChannel.localUpdateLog.logIndex, 1917 aliceChannelNew.localUpdateLog.logIndex) 1918 } 1919 if aliceChannel.remoteUpdateLog.logIndex != 1920 aliceChannelNew.remoteUpdateLog.logIndex { 1921 t.Fatalf("alice log counter: expected %v, got %v", 1922 aliceChannel.remoteUpdateLog.logIndex, 1923 aliceChannelNew.remoteUpdateLog.logIndex) 1924 } 1925 if aliceChannel.localUpdateLog.Len() != 1926 aliceChannelNew.localUpdateLog.Len() { 1927 t.Fatalf("alice log len: expected %v, got %v", 1928 aliceChannel.localUpdateLog.Len(), 1929 aliceChannelNew.localUpdateLog.Len()) 1930 } 1931 if aliceChannel.remoteUpdateLog.Len() != 1932 aliceChannelNew.remoteUpdateLog.Len() { 1933 t.Fatalf("alice log len: expected %v, got %v", 1934 aliceChannel.remoteUpdateLog.Len(), 1935 aliceChannelNew.remoteUpdateLog.Len()) 1936 } 1937 if bobChannel.localUpdateLog.logIndex != 1938 bobChannelNew.localUpdateLog.logIndex { 1939 t.Fatalf("bob log counter: expected %v, got %v", 1940 bobChannel.localUpdateLog.logIndex, 1941 bobChannelNew.localUpdateLog.logIndex) 1942 } 1943 if bobChannel.remoteUpdateLog.logIndex != 1944 bobChannelNew.remoteUpdateLog.logIndex { 1945 t.Fatalf("bob log counter: expected %v, got %v", 1946 bobChannel.remoteUpdateLog.logIndex, 1947 bobChannelNew.remoteUpdateLog.logIndex) 1948 } 1949 if bobChannel.localUpdateLog.Len() != 1950 bobChannelNew.localUpdateLog.Len() { 1951 t.Fatalf("bob log len: expected %v, got %v", 1952 bobChannel.localUpdateLog.Len(), 1953 bobChannelNew.localUpdateLog.Len()) 1954 } 1955 if bobChannel.remoteUpdateLog.Len() != 1956 bobChannelNew.remoteUpdateLog.Len() { 1957 t.Fatalf("bob log len: expected %v, got %v", 1958 bobChannel.remoteUpdateLog.Len(), 1959 bobChannelNew.remoteUpdateLog.Len()) 1960 } 1961 1962 // TODO(roasbeef): expand test to also ensure state revocation log has 1963 // proper pk scripts 1964 1965 // Newly generated pkScripts for HTLCs should be the same as in the old channel. 1966 for _, entry := range aliceChannel.localUpdateLog.htlcIndex { 1967 htlc := entry.Value.(*PaymentDescriptor) 1968 restoredHtlc := aliceChannelNew.localUpdateLog.lookupHtlc(htlc.HtlcIndex) 1969 if !bytes.Equal(htlc.ourPkScript, restoredHtlc.ourPkScript) { 1970 t.Fatalf("alice ourPkScript in ourLog: expected %X, got %X", 1971 htlc.ourPkScript[:5], restoredHtlc.ourPkScript[:5]) 1972 } 1973 if !bytes.Equal(htlc.theirPkScript, restoredHtlc.theirPkScript) { 1974 t.Fatalf("alice theirPkScript in ourLog: expected %X, got %X", 1975 htlc.theirPkScript[:5], restoredHtlc.theirPkScript[:5]) 1976 } 1977 } 1978 for _, entry := range aliceChannel.remoteUpdateLog.htlcIndex { 1979 htlc := entry.Value.(*PaymentDescriptor) 1980 restoredHtlc := aliceChannelNew.remoteUpdateLog.lookupHtlc(htlc.HtlcIndex) 1981 if !bytes.Equal(htlc.ourPkScript, restoredHtlc.ourPkScript) { 1982 t.Fatalf("alice ourPkScript in theirLog: expected %X, got %X", 1983 htlc.ourPkScript[:5], restoredHtlc.ourPkScript[:5]) 1984 } 1985 if !bytes.Equal(htlc.theirPkScript, restoredHtlc.theirPkScript) { 1986 t.Fatalf("alice theirPkScript in theirLog: expected %X, got %X", 1987 htlc.theirPkScript[:5], restoredHtlc.theirPkScript[:5]) 1988 } 1989 } 1990 for _, entry := range bobChannel.localUpdateLog.htlcIndex { 1991 htlc := entry.Value.(*PaymentDescriptor) 1992 restoredHtlc := bobChannelNew.localUpdateLog.lookupHtlc(htlc.HtlcIndex) 1993 if !bytes.Equal(htlc.ourPkScript, restoredHtlc.ourPkScript) { 1994 t.Fatalf("bob ourPkScript in ourLog: expected %X, got %X", 1995 htlc.ourPkScript[:5], restoredHtlc.ourPkScript[:5]) 1996 } 1997 if !bytes.Equal(htlc.theirPkScript, restoredHtlc.theirPkScript) { 1998 t.Fatalf("bob theirPkScript in ourLog: expected %X, got %X", 1999 htlc.theirPkScript[:5], restoredHtlc.theirPkScript[:5]) 2000 } 2001 } 2002 for _, entry := range bobChannel.remoteUpdateLog.htlcIndex { 2003 htlc := entry.Value.(*PaymentDescriptor) 2004 restoredHtlc := bobChannelNew.remoteUpdateLog.lookupHtlc(htlc.HtlcIndex) 2005 if !bytes.Equal(htlc.ourPkScript, restoredHtlc.ourPkScript) { 2006 t.Fatalf("bob ourPkScript in theirLog: expected %X, got %X", 2007 htlc.ourPkScript[:5], restoredHtlc.ourPkScript[:5]) 2008 } 2009 if !bytes.Equal(htlc.theirPkScript, restoredHtlc.theirPkScript) { 2010 t.Fatalf("bob theirPkScript in theirLog: expected %X, got %X", 2011 htlc.theirPkScript[:5], restoredHtlc.theirPkScript[:5]) 2012 } 2013 } 2014 2015 // Now settle all the HTLCs, then force a state update. The state 2016 // update should succeed as both sides have identical. 2017 for i := 0; i < 3; i++ { 2018 err := bobChannelNew.SettleHTLC(alicePreimage, uint64(i), nil, nil, nil) 2019 if err != nil { 2020 t.Fatalf("unable to settle htlc #%v: %v", i, err) 2021 } 2022 err = aliceChannelNew.ReceiveHTLCSettle(alicePreimage, uint64(i)) 2023 if err != nil { 2024 t.Fatalf("unable to settle htlc#%v: %v", i, err) 2025 } 2026 } 2027 err = aliceChannelNew.SettleHTLC(bobPreimage, 0, nil, nil, nil) 2028 if err != nil { 2029 t.Fatalf("unable to settle htlc: %v", err) 2030 } 2031 err = bobChannelNew.ReceiveHTLCSettle(bobPreimage, 0) 2032 if err != nil { 2033 t.Fatalf("unable to settle htlc: %v", err) 2034 } 2035 2036 // Similar to the two transitions above, as both Bob and Alice added 2037 // entries to the update log before a state transition was initiated by 2038 // either side, both sides are required to trigger an update in order 2039 // to lock in their changes. 2040 if err := ForceStateTransition(aliceChannelNew, bobChannelNew); err != nil { 2041 t.Fatalf("unable to update commitments: %v", err) 2042 } 2043 if err := ForceStateTransition(bobChannelNew, aliceChannelNew); err != nil { 2044 t.Fatalf("unable to update commitments: %v", err) 2045 } 2046 2047 // The amounts transferred should been updated as per the amounts in 2048 // the HTLCs 2049 if aliceChannelNew.channelState.TotalMAtomsSent != htlcAmt*3 { 2050 t.Fatalf("expected %v alice atoms sent, got %v", 2051 htlcAmt*3, aliceChannelNew.channelState.TotalMAtomsSent) 2052 } 2053 if aliceChannelNew.channelState.TotalMAtomsReceived != htlcAmt { 2054 t.Fatalf("expected %v alice atoms received, got %v", 2055 htlcAmt, aliceChannelNew.channelState.TotalMAtomsReceived) 2056 } 2057 if bobChannelNew.channelState.TotalMAtomsSent != htlcAmt { 2058 t.Fatalf("expected %v bob atoms sent, got %v", 2059 htlcAmt, bobChannel.channelState.TotalMAtomsSent) 2060 } 2061 if bobChannelNew.channelState.TotalMAtomsReceived != htlcAmt*3 { 2062 t.Fatalf("expected %v bob atoms sent, got %v", 2063 htlcAmt*3, bobChannel.channelState.TotalMAtomsReceived) 2064 } 2065 2066 // As a final test, we'll ensure that the HTLC counters for both sides 2067 // has been persisted properly. If we instruct Alice to add a new HTLC, 2068 // it should have an index of 3. If we instruct Bob to do the 2069 // same, it should have an index of 1. 2070 aliceHtlcIndex, err := aliceChannel.AddHTLC(bobh, nil) 2071 if err != nil { 2072 t.Fatalf("unable to add htlc: %v", err) 2073 } 2074 if aliceHtlcIndex != 3 { 2075 t.Fatalf("wrong htlc index: expected %v, got %v", 3, aliceHtlcIndex) 2076 } 2077 bobHtlcIndex, err := bobChannel.AddHTLC(bobh, nil) 2078 if err != nil { 2079 t.Fatalf("unable to add htlc: %v", err) 2080 } 2081 if bobHtlcIndex != 1 { 2082 t.Fatalf("wrong htlc index: expected %v, got %v", 1, aliceHtlcIndex) 2083 } 2084 } 2085 2086 func TestCancelHTLC(t *testing.T) { 2087 t.Parallel() 2088 2089 // Create a test channel which will be used for the duration of this 2090 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2091 // and Bob having 5 DCR. 2092 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2093 channeldb.SingleFunderTweaklessBit, 2094 ) 2095 if err != nil { 2096 t.Fatalf("unable to create test channels: %v", err) 2097 } 2098 defer cleanUp() 2099 2100 // Add a new HTLC from Alice to Bob, then trigger a new state 2101 // transition in order to include it in the latest state. 2102 htlcAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 2103 2104 var preImage [32]byte 2105 copy(preImage[:], bytes.Repeat([]byte{0xaa}, 32)) 2106 htlc := &lnwire.UpdateAddHTLC{ 2107 PaymentHash: sha256.Sum256(preImage[:]), 2108 Amount: htlcAmt, 2109 Expiry: 10, 2110 } 2111 2112 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 2113 if err != nil { 2114 t.Fatalf("unable to add alice htlc: %v", err) 2115 } 2116 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 2117 if err != nil { 2118 t.Fatalf("unable to add bob htlc: %v", err) 2119 } 2120 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 2121 t.Fatalf("unable to create new commitment state: %v", err) 2122 } 2123 2124 // With the HTLC committed, Alice's balance should reflect the clearing 2125 // of the new HTLC. 2126 aliceExpectedBalance := dcrutil.Amount(dcrutil.AtomsPerCoin*4) - 2127 calcStaticFee(channeldb.SingleFunderTweaklessBit, 1) 2128 if aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms() != 2129 aliceExpectedBalance { 2130 t.Fatalf("Alice's balance is wrong: expected %v, got %v", 2131 aliceExpectedBalance, 2132 aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms()) 2133 } 2134 2135 // Now, with the HTLC committed on both sides, trigger a cancellation 2136 // from Bob to Alice, removing the HTLC. 2137 err = bobChannel.FailHTLC(bobHtlcIndex, []byte("failreason"), nil, nil, nil) 2138 if err != nil { 2139 t.Fatalf("unable to cancel HTLC: %v", err) 2140 } 2141 err = aliceChannel.ReceiveFailHTLC(aliceHtlcIndex, []byte("bad")) 2142 if err != nil { 2143 t.Fatalf("unable to recv htlc cancel: %v", err) 2144 } 2145 2146 // Now trigger another state transition, the HTLC should now be removed 2147 // from both sides, with balances reflected. 2148 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 2149 t.Fatalf("unable to create new commitment: %v", err) 2150 } 2151 2152 // Now HTLCs should be present on the commitment transaction for either 2153 // side. 2154 if len(aliceChannel.localCommitChain.tip().outgoingHTLCs) != 0 || 2155 len(aliceChannel.remoteCommitChain.tip().outgoingHTLCs) != 0 { 2156 t.Fatalf("htlc's still active from alice's POV") 2157 } 2158 if len(aliceChannel.localCommitChain.tip().incomingHTLCs) != 0 || 2159 len(aliceChannel.remoteCommitChain.tip().incomingHTLCs) != 0 { 2160 t.Fatalf("htlc's still active from alice's POV") 2161 } 2162 if len(bobChannel.localCommitChain.tip().outgoingHTLCs) != 0 || 2163 len(bobChannel.remoteCommitChain.tip().outgoingHTLCs) != 0 { 2164 t.Fatalf("htlc's still active from bob's POV") 2165 } 2166 if len(bobChannel.localCommitChain.tip().incomingHTLCs) != 0 || 2167 len(bobChannel.remoteCommitChain.tip().incomingHTLCs) != 0 { 2168 t.Fatalf("htlc's still active from bob's POV") 2169 } 2170 2171 expectedBalance := dcrutil.Amount(dcrutil.AtomsPerCoin * 5) 2172 staticFee := calcStaticFee(channeldb.SingleFunderTweaklessBit, 0) 2173 if aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms() != 2174 expectedBalance-staticFee { 2175 2176 t.Fatalf("balance is wrong: expected %v, got %v", 2177 aliceChannel.channelState.LocalCommitment.LocalBalance.ToAtoms(), 2178 expectedBalance-staticFee) 2179 } 2180 if aliceChannel.channelState.LocalCommitment.RemoteBalance.ToAtoms() != 2181 expectedBalance { 2182 2183 t.Fatalf("balance is wrong: expected %v, got %v", 2184 aliceChannel.channelState.LocalCommitment.RemoteBalance.ToAtoms(), 2185 expectedBalance) 2186 } 2187 if bobChannel.channelState.LocalCommitment.LocalBalance.ToAtoms() != 2188 expectedBalance { 2189 2190 t.Fatalf("balance is wrong: expected %v, got %v", 2191 bobChannel.channelState.LocalCommitment.LocalBalance.ToAtoms(), 2192 expectedBalance) 2193 } 2194 if bobChannel.channelState.LocalCommitment.RemoteBalance.ToAtoms() != 2195 expectedBalance-staticFee { 2196 2197 t.Fatalf("balance is wrong: expected %v, got %v", 2198 bobChannel.channelState.LocalCommitment.RemoteBalance.ToAtoms(), 2199 expectedBalance-staticFee) 2200 } 2201 } 2202 2203 func TestCooperativeCloseDustAdherence(t *testing.T) { 2204 t.Parallel() 2205 2206 // Create a test channel which will be used for the duration of this 2207 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2208 // and Bob having 5 DCR. 2209 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2210 channeldb.SingleFunderTweaklessBit, 2211 ) 2212 if err != nil { 2213 t.Fatalf("unable to create test channels: %v", err) 2214 } 2215 defer cleanUp() 2216 2217 aliceFeeRate := chainfee.AtomPerKByte( 2218 aliceChannel.channelState.LocalCommitment.FeePerKB, 2219 ) 2220 bobFeeRate := chainfee.AtomPerKByte( 2221 bobChannel.channelState.LocalCommitment.FeePerKB, 2222 ) 2223 2224 setDustLimit := func(dustVal dcrutil.Amount) { 2225 aliceChannel.channelState.LocalChanCfg.DustLimit = dustVal 2226 aliceChannel.channelState.RemoteChanCfg.DustLimit = dustVal 2227 bobChannel.channelState.LocalChanCfg.DustLimit = dustVal 2228 bobChannel.channelState.RemoteChanCfg.DustLimit = dustVal 2229 } 2230 2231 resetChannelState := func() { 2232 aliceChannel.status = channelOpen 2233 bobChannel.status = channelOpen 2234 } 2235 2236 setBalances := func(aliceBalance, bobBalance lnwire.MilliAtom) { 2237 aliceChannel.channelState.LocalCommitment.LocalBalance = aliceBalance 2238 aliceChannel.channelState.LocalCommitment.RemoteBalance = bobBalance 2239 bobChannel.channelState.LocalCommitment.LocalBalance = bobBalance 2240 bobChannel.channelState.LocalCommitment.RemoteBalance = aliceBalance 2241 } 2242 2243 aliceDeliveryScript := alicePkScript 2244 bobDeliveryScript := bobPkScript 2245 2246 // We'll start be initializing the limit of both Alice and Bob to 10k 2247 // atoms. 2248 dustLimit := dcrutil.Amount(10000) 2249 setDustLimit(dustLimit) 2250 2251 // Both sides currently have over 1 DCR settled as part of their 2252 // balances. As a result, performing a cooperative closure now result 2253 // in both sides having an output within the closure transaction. 2254 aliceFee := aliceChannel.CalcFee(aliceFeeRate) + 1000 2255 aliceSig, _, _, err := aliceChannel.CreateCloseProposal( 2256 aliceFee, aliceDeliveryScript, bobDeliveryScript, 2257 ) 2258 if err != nil { 2259 t.Fatalf("unable to close channel: %v", err) 2260 } 2261 2262 bobFee := bobChannel.CalcFee(bobFeeRate) + 1000 2263 bobSig, _, _, err := bobChannel.CreateCloseProposal( 2264 bobFee, bobDeliveryScript, aliceDeliveryScript, 2265 ) 2266 if err != nil { 2267 t.Fatalf("unable to close channel: %v", err) 2268 } 2269 2270 closeTx, _, err := bobChannel.CompleteCooperativeClose( 2271 bobSig, aliceSig, bobDeliveryScript, aliceDeliveryScript, 2272 bobFee, 2273 ) 2274 if err != nil { 2275 t.Fatalf("unable to accept channel close: %v", err) 2276 } 2277 2278 // The closure transaction should have exactly two outputs. 2279 if len(closeTx.TxOut) != 2 { 2280 t.Fatalf("close tx has wrong number of outputs: expected %v "+ 2281 "got %v", 2, len(closeTx.TxOut)) 2282 } 2283 2284 // We'll reset the channel states before proceeding to our next test. 2285 resetChannelState() 2286 2287 // Next we'll modify the current balances and dust limits such that 2288 // Bob's current balance is _below_ his dust limit. 2289 aliceBal := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 2290 bobBal := lnwire.NewMAtomsFromAtoms(250) 2291 setBalances(aliceBal, bobBal) 2292 2293 // Attempt another cooperative channel closure. It should succeed 2294 // without any issues. 2295 aliceSig, _, _, err = aliceChannel.CreateCloseProposal( 2296 aliceFee, aliceDeliveryScript, bobDeliveryScript, 2297 ) 2298 if err != nil { 2299 t.Fatalf("unable to close channel: %v", err) 2300 } 2301 2302 bobSig, _, _, err = bobChannel.CreateCloseProposal( 2303 bobFee, bobDeliveryScript, aliceDeliveryScript, 2304 ) 2305 if err != nil { 2306 t.Fatalf("unable to close channel: %v", err) 2307 } 2308 2309 closeTx, _, err = bobChannel.CompleteCooperativeClose( 2310 bobSig, aliceSig, bobDeliveryScript, aliceDeliveryScript, 2311 bobFee, 2312 ) 2313 if err != nil { 2314 t.Fatalf("unable to accept channel close: %v", err) 2315 } 2316 2317 // The closure transaction should only have a single output, and that 2318 // output should be Alice's balance. 2319 if len(closeTx.TxOut) != 1 { 2320 t.Fatalf("close tx has wrong number of outputs: expected %v "+ 2321 "got %v", 1, len(closeTx.TxOut)) 2322 } 2323 commitFee := aliceChannel.channelState.LocalCommitment.CommitFee 2324 aliceExpectedBalance := aliceBal.ToAtoms() - aliceFee + commitFee 2325 if closeTx.TxOut[0].Value != int64(aliceExpectedBalance) { 2326 t.Fatalf("alice's balance is incorrect: expected %v, got %v", 2327 aliceExpectedBalance, 2328 closeTx.TxOut[0].Value) 2329 } 2330 2331 // We'll modify the current balances and dust limits such that 2332 // Alice's current balance is too low to pay the proposed fee. 2333 setBalances(bobBal, aliceBal) 2334 resetChannelState() 2335 2336 // Attempting to close with this fee now should fail, since Alice 2337 // cannot afford it. 2338 _, _, _, err = aliceChannel.CreateCloseProposal( 2339 aliceFee, aliceDeliveryScript, bobDeliveryScript, 2340 ) 2341 if err == nil { 2342 t.Fatalf("expected error") 2343 } 2344 2345 // Finally, we'll modify the current balances and dust limits such that 2346 // Alice's balance after paying the coop fee is _below_ her dust limit. 2347 lowBalance := lnwire.MilliAtom(6031 * 1000) // 6030 = dust limit 2348 setBalances(lowBalance, aliceBal) 2349 resetChannelState() 2350 2351 // Our final attempt at another cooperative channel closure. It should 2352 // succeed without any issues. 2353 aliceSig, _, _, err = aliceChannel.CreateCloseProposal( 2354 aliceFee, aliceDeliveryScript, bobDeliveryScript, 2355 ) 2356 if err != nil { 2357 t.Fatalf("unable to close channel: %v", err) 2358 } 2359 2360 bobSig, _, _, err = bobChannel.CreateCloseProposal( 2361 bobFee, bobDeliveryScript, aliceDeliveryScript, 2362 ) 2363 if err != nil { 2364 t.Fatalf("unable to close channel: %v", err) 2365 } 2366 2367 closeTx, _, err = bobChannel.CompleteCooperativeClose( 2368 bobSig, aliceSig, bobDeliveryScript, aliceDeliveryScript, 2369 bobFee, 2370 ) 2371 if err != nil { 2372 t.Fatalf("unable to accept channel close: %v", err) 2373 } 2374 2375 // The closure transaction should only have a single output, and that 2376 // output should be Bob's balance. 2377 if len(closeTx.TxOut) != 1 { 2378 t.Log(spew.Sdump(closeTx)) 2379 t.Fatalf("close tx has wrong number of outputs: expected %v "+ 2380 "got %v", 1, len(closeTx.TxOut)) 2381 } 2382 if closeTx.TxOut[0].Value != int64(aliceBal.ToAtoms()) { 2383 t.Fatalf("bob's balance is incorrect: expected %v, got %v", 2384 aliceBal.ToAtoms(), closeTx.TxOut[0].Value) 2385 } 2386 } 2387 2388 // TestUpdateFeeAdjustments tests that the state machine is able to properly 2389 // accept valid fee changes, as well as reject any invalid fee updates. 2390 func TestUpdateFeeAdjustments(t *testing.T) { 2391 t.Parallel() 2392 2393 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2394 channeldb.SingleFunderTweaklessBit, 2395 ) 2396 if err != nil { 2397 t.Fatalf("unable to create test channels: %v", err) 2398 } 2399 defer cleanUp() 2400 2401 // First, we'll grab the current base fee rate as we'll be using this 2402 // to make relative adjustments int he fee rate. 2403 baseFeeRate := aliceChannel.channelState.LocalCommitment.FeePerKB 2404 2405 // We'll first try to increase the fee rate 5x, this should be able to 2406 // be committed without any issue. 2407 newFee := chainfee.AtomPerKByte(baseFeeRate * 5) 2408 2409 if err := aliceChannel.UpdateFee(newFee); err != nil { 2410 t.Fatalf("unable to alice update fee: %v", err) 2411 } 2412 if err := bobChannel.ReceiveUpdateFee(newFee); err != nil { 2413 t.Fatalf("unable to bob update fee: %v", err) 2414 } 2415 2416 // With the fee updates applied, we'll now initiate a state transition 2417 // to ensure the fee update is locked in. 2418 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 2419 t.Fatalf("unable to create new commitment: %v", err) 2420 } 2421 2422 // We'll now attempt to increase the fee rate 1,000,000x of the base 2423 // fee. This should result in an error as Alice won't be able to pay 2424 // this new fee rate. 2425 newFee = chainfee.AtomPerKByte(baseFeeRate * 1000000) 2426 if err := aliceChannel.UpdateFee(newFee); err == nil { 2427 t.Fatalf("alice should reject the fee rate") 2428 } 2429 2430 // Finally, we'll attempt to adjust the fee down and use a fee which is 2431 // smaller than the initial base fee rate. The fee application and 2432 // state transition should proceed without issue. 2433 newFee = chainfee.AtomPerKByte(baseFeeRate / 10) 2434 if err := aliceChannel.UpdateFee(newFee); err != nil { 2435 t.Fatalf("unable to alice update fee: %v", err) 2436 } 2437 if err := bobChannel.ReceiveUpdateFee(newFee); err != nil { 2438 t.Fatalf("unable to bob update fee: %v", err) 2439 } 2440 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 2441 t.Fatalf("unable to create new commitment: %v", err) 2442 } 2443 } 2444 2445 // TestUpdateFeeFail tests that the signature verification will fail if they 2446 // fee updates are out of sync. 2447 func TestUpdateFeeFail(t *testing.T) { 2448 t.Parallel() 2449 2450 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2451 channeldb.SingleFunderTweaklessBit, 2452 ) 2453 if err != nil { 2454 t.Fatalf("unable to create test channels: %v", err) 2455 } 2456 defer cleanUp() 2457 2458 // Bob receives the update, that will apply to his commitment 2459 // transaction. 2460 if err := bobChannel.ReceiveUpdateFee(2e4); err != nil { 2461 t.Fatalf("unable to apply fee update: %v", err) 2462 } 2463 2464 // Alice sends signature for commitment that does not cover any fee 2465 // update. 2466 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 2467 if err != nil { 2468 t.Fatalf("alice unable to sign commitment: %v", err) 2469 } 2470 2471 // Bob verifies this commit, meaning that he checks that it is 2472 // consistent everything he has received. This should fail, since he got 2473 // the fee update, but Alice never sent it. 2474 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 2475 if err == nil { 2476 t.Fatalf("expected bob to fail receiving alice's signature") 2477 } 2478 2479 } 2480 2481 // TestUpdateFeeConcurrentSig tests that the channel can properly handle a fee 2482 // update that it receives concurrently with signing its next commitment. 2483 func TestUpdateFeeConcurrentSig(t *testing.T) { 2484 t.Parallel() 2485 2486 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2487 channeldb.SingleFunderTweaklessBit, 2488 ) 2489 if err != nil { 2490 t.Fatalf("unable to create test channels: %v", err) 2491 } 2492 defer cleanUp() 2493 2494 paymentPreimage := bytes.Repeat([]byte{1}, 32) 2495 paymentHash := sha256.Sum256(paymentPreimage) 2496 htlc := &lnwire.UpdateAddHTLC{ 2497 PaymentHash: paymentHash, 2498 Amount: dcrutil.AtomsPerCoin, 2499 Expiry: uint32(5), 2500 } 2501 2502 // First Alice adds the outgoing HTLC to her local channel's state 2503 // update log. Then Alice sends this wire message over to Bob who 2504 // adds this htlc to his remote state update log. 2505 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 2506 t.Fatalf("unable to add htlc: %v", err) 2507 } 2508 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 2509 t.Fatalf("unable to recv htlc: %v", err) 2510 } 2511 2512 // Simulate Alice sending update fee message to bob. 2513 fee := chainfee.AtomPerKByte(2e4) 2514 if err := aliceChannel.UpdateFee(fee); err != nil { 2515 t.Fatalf("unable to send fee update") 2516 } 2517 2518 // Alice signs a commitment, and sends this to bob. 2519 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 2520 if err != nil { 2521 t.Fatalf("alice unable to sign commitment: %v", err) 2522 } 2523 2524 // At the same time, Bob signs a commitment. 2525 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 2526 if err != nil { 2527 t.Fatalf("bob unable to sign alice's commitment: %v", err) 2528 } 2529 2530 // ...that Alice receives. 2531 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 2532 if err != nil { 2533 t.Fatalf("alice unable to process bob's new commitment: %v", err) 2534 } 2535 2536 // Now let Bob receive the fee update + commitment that Alice sent. 2537 if err := bobChannel.ReceiveUpdateFee(fee); err != nil { 2538 t.Fatalf("unable to receive fee update") 2539 } 2540 2541 // Bob receives this signature message, and verifies that it is 2542 // consistent with the state he had for Alice, including the received 2543 // HTLC and fee update. 2544 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 2545 if err != nil { 2546 t.Fatalf("bob unable to process alice's new commitment: %v", err) 2547 } 2548 2549 if chainfee.AtomPerKByte(bobChannel.channelState.LocalCommitment.FeePerKB) == fee { 2550 t.Fatalf("bob's feePerKB was unexpectedly locked in") 2551 } 2552 2553 // Bob can revoke the prior commitment he had. This should lock in the 2554 // fee update for him. 2555 _, _, err = bobChannel.RevokeCurrentCommitment() 2556 if err != nil { 2557 t.Fatalf("unable to generate bob revocation: %v", err) 2558 } 2559 2560 if chainfee.AtomPerKByte(bobChannel.channelState.LocalCommitment.FeePerKB) != fee { 2561 t.Fatalf("bob's feePerKB was not locked in") 2562 } 2563 } 2564 2565 // TestUpdateFeeSenderCommits verifies that the state machine progresses as 2566 // expected if we send a fee update, and then the sender of the fee update 2567 // sends a commitment signature. 2568 func TestUpdateFeeSenderCommits(t *testing.T) { 2569 t.Parallel() 2570 2571 // Create a test channel which will be used for the duration of this 2572 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2573 // and Bob having 5 DCR. 2574 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2575 channeldb.SingleFunderTweaklessBit, 2576 ) 2577 if err != nil { 2578 t.Fatalf("unable to create test channels: %v", err) 2579 } 2580 defer cleanUp() 2581 2582 paymentPreimage := bytes.Repeat([]byte{1}, 32) 2583 paymentHash := sha256.Sum256(paymentPreimage) 2584 htlc := &lnwire.UpdateAddHTLC{ 2585 PaymentHash: paymentHash, 2586 Amount: dcrutil.AtomsPerCoin, 2587 Expiry: uint32(5), 2588 } 2589 2590 // First Alice adds the outgoing HTLC to her local channel's state 2591 // update log. Then Alice sends this wire message over to Bob who 2592 // adds this htlc to his remote state update log. 2593 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 2594 t.Fatalf("unable to add htlc: %v", err) 2595 } 2596 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 2597 t.Fatalf("unable to recv htlc: %v", err) 2598 } 2599 2600 // Simulate Alice sending update fee message to bob. 2601 fee := chainfee.AtomPerKByte(2e4) 2602 if err = aliceChannel.UpdateFee(fee); err != nil { 2603 t.Fatalf("alice unable to update fee: %v", err) 2604 } 2605 if err = bobChannel.ReceiveUpdateFee(fee); err != nil { 2606 t.Fatalf("bob unable to receive update fee: %v", err) 2607 } 2608 2609 // Alice signs a commitment, which will cover everything sent to Bob 2610 // (the HTLC and the fee update), and everything acked by Bob (nothing 2611 // so far). 2612 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 2613 if err != nil { 2614 t.Fatalf("alice unable to sign commitment: %v", err) 2615 } 2616 2617 // Bob receives this signature message, and verifies that it is 2618 // consistent with the state he had for Alice, including the received 2619 // HTLC and fee update. 2620 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 2621 if err != nil { 2622 t.Fatalf("bob unable to process alice's new commitment: %v", err) 2623 } 2624 2625 if chainfee.AtomPerKByte( 2626 bobChannel.channelState.LocalCommitment.FeePerKB, 2627 ) == fee { 2628 t.Fatalf("bob's FeePerKB was unexpectedly locked in") 2629 } 2630 2631 // Bob can revoke the prior commitment he had. This should lock in the 2632 // fee update for him. 2633 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 2634 if err != nil { 2635 t.Fatalf("unable to generate bob revocation: %v", err) 2636 } 2637 2638 if chainfee.AtomPerKByte( 2639 bobChannel.channelState.LocalCommitment.FeePerKB, 2640 ) != fee { 2641 t.Fatalf("bob's FeePerKB was not locked in") 2642 } 2643 2644 // Bob commits to all updates he has received from Alice. This includes 2645 // the HTLC he received, and the fee update. 2646 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 2647 if err != nil { 2648 t.Fatalf("bob unable to sign alice's commitment: %v", err) 2649 } 2650 2651 // Alice receives the revocation of the old one, and can now assume 2652 // that Bob's received everything up to the signature she sent, 2653 // including the HTLC and fee update. 2654 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 2655 if err != nil { 2656 t.Fatalf("alice unable to process bob's revocation: %v", err) 2657 } 2658 2659 // Alice receives new signature from Bob, and assumes this covers the 2660 // changes. 2661 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 2662 if err != nil { 2663 t.Fatalf("alice unable to process bob's new commitment: %v", err) 2664 } 2665 2666 if chainfee.AtomPerKByte( 2667 aliceChannel.channelState.LocalCommitment.FeePerKB, 2668 ) == fee { 2669 t.Fatalf("alice's FeePerKB was unexpectedly locked in") 2670 } 2671 2672 // Alice can revoke the old commitment, which will lock in the fee 2673 // update. 2674 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 2675 if err != nil { 2676 t.Fatalf("unable to revoke alice channel: %v", err) 2677 } 2678 2679 if chainfee.AtomPerKByte( 2680 aliceChannel.channelState.LocalCommitment.FeePerKB, 2681 ) != fee { 2682 t.Fatalf("alice's FeePerKB was not locked in") 2683 } 2684 2685 // Bob receives revocation from Alice. 2686 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 2687 if err != nil { 2688 t.Fatalf("bob unable to process alice's revocation: %v", err) 2689 } 2690 2691 } 2692 2693 // TestUpdateFeeReceiverCommits tests that the state machine progresses as 2694 // expected if we send a fee update, and then the receiver of the fee update 2695 // sends a commitment signature. 2696 func TestUpdateFeeReceiverCommits(t *testing.T) { 2697 t.Parallel() 2698 2699 // Create a test channel which will be used for the duration of this 2700 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2701 // and Bob having 5 DCR. 2702 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2703 channeldb.SingleFunderTweaklessBit, 2704 ) 2705 if err != nil { 2706 t.Fatalf("unable to create test channels: %v", err) 2707 } 2708 defer cleanUp() 2709 2710 paymentPreimage := bytes.Repeat([]byte{1}, 32) 2711 paymentHash := sha256.Sum256(paymentPreimage) 2712 htlc := &lnwire.UpdateAddHTLC{ 2713 PaymentHash: paymentHash, 2714 Amount: dcrutil.AtomsPerCoin, 2715 Expiry: uint32(5), 2716 } 2717 2718 // First Alice adds the outgoing HTLC to her local channel's state 2719 // update log. Then Alice sends this wire message over to Bob who 2720 // adds this htlc to his remote state update log. 2721 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 2722 t.Fatalf("unable to add htlc: %v", err) 2723 } 2724 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 2725 t.Fatalf("unable to recv htlc: %v", err) 2726 } 2727 2728 // Simulate Alice sending update fee message to bob 2729 fee := chainfee.AtomPerKByte(2e4) 2730 if err = aliceChannel.UpdateFee(fee); err != nil { 2731 t.Fatalf("unable to update fee: %v", err) 2732 } 2733 if err = bobChannel.ReceiveUpdateFee(fee); err != nil { 2734 t.Fatalf("unable to receive update fee: %v", err) 2735 } 2736 2737 // Bob commits to every change he has sent since last time (none). He 2738 // does not commit to the received HTLC and fee update, since Alice 2739 // cannot know if he has received them. 2740 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 2741 if err != nil { 2742 t.Fatalf("alice unable to sign commitment: %v", err) 2743 } 2744 2745 // Alice receives this signature message, and verifies that it is 2746 // consistent with the remote state, not including any of the updates. 2747 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 2748 if err != nil { 2749 t.Fatalf("bob unable to process alice's new commitment: %v", err) 2750 } 2751 2752 // Alice can revoke the prior commitment she had, this will ack 2753 // everything received before last commitment signature, but in this 2754 // case that is nothing. 2755 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 2756 if err != nil { 2757 t.Fatalf("unable to generate bob revocation: %v", err) 2758 } 2759 2760 // Bob receives the revocation of the old commitment 2761 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 2762 if err != nil { 2763 t.Fatalf("alice unable to process bob's revocation: %v", err) 2764 } 2765 2766 // Alice will sign next commitment. Since she sent the revocation, she 2767 // also ack'ed everything received, but in this case this is nothing. 2768 // Since she sent the two updates, this signature will cover those two. 2769 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 2770 if err != nil { 2771 t.Fatalf("bob unable to sign alice's commitment: %v", err) 2772 } 2773 2774 // Bob gets the signature for the new commitment from Alice. He assumes 2775 // this covers everything received from alice, including the two updates. 2776 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 2777 if err != nil { 2778 t.Fatalf("alice unable to process bob's new commitment: %v", err) 2779 } 2780 2781 if chainfee.AtomPerKByte( 2782 bobChannel.channelState.LocalCommitment.FeePerKB, 2783 ) == fee { 2784 t.Fatalf("bob's FeePerKB was unexpectedly locked in") 2785 } 2786 2787 // Bob can revoke the old commitment. This will ack what he has 2788 // received, including the HTLC and fee update. This will lock in the 2789 // fee update for bob. 2790 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 2791 if err != nil { 2792 t.Fatalf("unable to revoke alice channel: %v", err) 2793 } 2794 2795 if chainfee.AtomPerKByte( 2796 bobChannel.channelState.LocalCommitment.FeePerKB, 2797 ) != fee { 2798 t.Fatalf("bob's FeePerKB was not locked in") 2799 } 2800 2801 // Bob will send a new signature, which will cover what he just acked: 2802 // the HTLC and fee update. 2803 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 2804 if err != nil { 2805 t.Fatalf("alice unable to sign commitment: %v", err) 2806 } 2807 2808 // Alice receives revocation from Bob, and can now be sure that Bob 2809 // received the two updates, and they are considered locked in. 2810 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 2811 if err != nil { 2812 t.Fatalf("bob unable to process alice's revocation: %v", err) 2813 } 2814 2815 // Alice will receive the signature from Bob, which will cover what was 2816 // just acked by his revocation. 2817 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 2818 if err != nil { 2819 t.Fatalf("alice unable to process bob's new commitment: %v", err) 2820 } 2821 2822 if chainfee.AtomPerKByte( 2823 aliceChannel.channelState.LocalCommitment.FeePerKB, 2824 ) == fee { 2825 t.Fatalf("alice's FeePerKB was unexpectedly locked in") 2826 } 2827 2828 // After Alice now revokes her old commitment, the fee update should 2829 // lock in. 2830 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 2831 if err != nil { 2832 t.Fatalf("unable to generate bob revocation: %v", err) 2833 } 2834 2835 if chainfee.AtomPerKByte( 2836 aliceChannel.channelState.LocalCommitment.FeePerKB, 2837 ) != fee { 2838 t.Fatalf("Alice's FeePerKB was not locked in") 2839 } 2840 2841 // Bob receives revocation from Alice. 2842 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 2843 if err != nil { 2844 t.Fatalf("bob unable to process alice's revocation: %v", err) 2845 } 2846 } 2847 2848 // TestUpdateFeeReceiverSendsUpdate tests that receiving a fee update as channel 2849 // initiator fails, and that trying to initiate fee update as non-initiation 2850 // fails. 2851 func TestUpdateFeeReceiverSendsUpdate(t *testing.T) { 2852 t.Parallel() 2853 2854 // Create a test channel which will be used for the duration of this 2855 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2856 // and Bob having 5 DCR. 2857 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2858 channeldb.SingleFunderTweaklessBit, 2859 ) 2860 if err != nil { 2861 t.Fatalf("unable to create test channels: %v", err) 2862 } 2863 defer cleanUp() 2864 2865 // Since Alice is the channel initiator, she should fail when receiving 2866 // fee update 2867 fee := chainfee.AtomPerKByte(2e4) 2868 err = aliceChannel.ReceiveUpdateFee(fee) 2869 if err == nil { 2870 t.Fatalf("expected alice to fail receiving fee update") 2871 } 2872 2873 // Similarly, initiating fee update should fail for Bob. 2874 err = bobChannel.UpdateFee(fee) 2875 if err == nil { 2876 t.Fatalf("expected bob to fail initiating fee update") 2877 } 2878 } 2879 2880 // Test that if multiple update fee messages are sent consecutively, then the 2881 // last one is the one that is being committed to. 2882 func TestUpdateFeeMultipleUpdates(t *testing.T) { 2883 t.Parallel() 2884 2885 // Create a test channel which will be used for the duration of this 2886 // unittest. The channel will be funded evenly with Alice having 5 DCR, 2887 // and Bob having 5 DCR. 2888 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 2889 channeldb.SingleFunderTweaklessBit, 2890 ) 2891 if err != nil { 2892 t.Fatalf("unable to create test channels: %v", err) 2893 } 2894 defer cleanUp() 2895 2896 // Simulate Alice sending update fee message to bob. 2897 fee1 := chainfee.AtomPerKByte(2e4) 2898 fee2 := chainfee.AtomPerKByte(2e4) 2899 fee := chainfee.AtomPerKByte(2e4) 2900 if err = aliceChannel.UpdateFee(fee1); err != nil { 2901 t.Fatalf("alice unable to update fee1: %v", err) 2902 } 2903 if err = aliceChannel.UpdateFee(fee2); err != nil { 2904 t.Fatalf("alice unable to update fee2: %v", err) 2905 } 2906 if err = aliceChannel.UpdateFee(fee); err != nil { 2907 t.Fatalf("alice unable to update fee: %v", err) 2908 } 2909 2910 // Alice signs a commitment, which will cover everything sent to Bob 2911 // (the HTLC and the fee update), and everything acked by Bob (nothing 2912 // so far). 2913 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 2914 if err != nil { 2915 t.Fatalf("alice unable to sign commitment: %v", err) 2916 } 2917 2918 if err = bobChannel.ReceiveUpdateFee(fee1); err != nil { 2919 t.Fatalf("bob unable to receive update fee1: %v", err) 2920 } 2921 if err = bobChannel.ReceiveUpdateFee(fee2); err != nil { 2922 t.Fatalf("bob unable to receive update fee2: %v", err) 2923 } 2924 if err = bobChannel.ReceiveUpdateFee(fee); err != nil { 2925 t.Fatalf("bob unable to receive update fee: %v", err) 2926 } 2927 2928 // Bob receives this signature message, and verifies that it is 2929 // consistent with the state he had for Alice, including the received 2930 // HTLC and fee update. 2931 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 2932 if err != nil { 2933 t.Fatalf("bob unable to process alice's new commitment: %v", err) 2934 } 2935 2936 if chainfee.AtomPerKByte( 2937 bobChannel.channelState.LocalCommitment.FeePerKB, 2938 ) == fee { 2939 t.Fatalf("bob's FeePerKB was unexpectedly locked in") 2940 } 2941 2942 // Alice sending more fee updates now should not mess up the old fee 2943 // they both committed to. 2944 fee3 := chainfee.AtomPerKByte(444) 2945 fee4 := chainfee.AtomPerKByte(555) 2946 fee5 := chainfee.AtomPerKByte(666) 2947 if err = aliceChannel.UpdateFee(fee3); err != nil { 2948 t.Fatalf("alice unable to update fee3: %v", err) 2949 } 2950 if err = aliceChannel.UpdateFee(fee4); err != nil { 2951 t.Fatalf("alice unable to update fee4: %v", err) 2952 } 2953 if err = aliceChannel.UpdateFee(fee5); err != nil { 2954 t.Fatalf("alice unable to update fee5: %v", err) 2955 } 2956 if err = bobChannel.ReceiveUpdateFee(fee3); err != nil { 2957 t.Fatalf("bob unable to receive update fee3: %v", err) 2958 } 2959 if err = bobChannel.ReceiveUpdateFee(fee4); err != nil { 2960 t.Fatalf("bob unable to receive update fee4: %v", err) 2961 } 2962 if err = bobChannel.ReceiveUpdateFee(fee5); err != nil { 2963 t.Fatalf("bob unable to receive update fee5; %v", err) 2964 } 2965 2966 // Bob can revoke the prior commitment he had. This should lock in the 2967 // fee update for him. 2968 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 2969 if err != nil { 2970 t.Fatalf("unable to generate bob revocation: %v", err) 2971 } 2972 2973 if chainfee.AtomPerKByte( 2974 bobChannel.channelState.LocalCommitment.FeePerKB, 2975 ) != fee { 2976 t.Fatalf("bob's FeePerKB was not locked in") 2977 } 2978 2979 // Bob commits to all updates he has received from Alice. This includes 2980 // the HTLC he received, and the fee update. 2981 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 2982 if err != nil { 2983 t.Fatalf("bob unable to sign alice's commitment: %v", err) 2984 } 2985 2986 // Alice receives the revocation of the old one, and can now assume that 2987 // Bob's received everything up to the signature she sent, including the 2988 // HTLC and fee update. 2989 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 2990 if err != nil { 2991 t.Fatalf("alice unable to process bob's revocation: %v", err) 2992 } 2993 2994 // Alice receives new signature from Bob, and assumes this covers the 2995 // changes. 2996 if err := aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs); err != nil { 2997 t.Fatalf("alice unable to process bob's new commitment: %v", err) 2998 } 2999 3000 if chainfee.AtomPerKByte( 3001 aliceChannel.channelState.LocalCommitment.FeePerKB, 3002 ) == fee { 3003 t.Fatalf("alice's FeePerKB was unexpectedly locked in") 3004 } 3005 3006 // Alice can revoke the old commitment, which will lock in the fee 3007 // update. 3008 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 3009 if err != nil { 3010 t.Fatalf("unable to revoke alice channel: %v", err) 3011 } 3012 3013 if chainfee.AtomPerKByte( 3014 aliceChannel.channelState.LocalCommitment.FeePerKB, 3015 ) != fee { 3016 t.Fatalf("alice's FeePerKB was not locked in") 3017 } 3018 3019 // Bob receives revocation from Alice. 3020 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 3021 if err != nil { 3022 t.Fatalf("bob unable to process alice's revocation: %v", err) 3023 } 3024 } 3025 3026 // TestAddHTLCNegativeBalance tests that if enough HTLC's are added to the 3027 // state machine to drive the balance to zero, then the next HTLC attempted to 3028 // be added will result in an error being returned. 3029 func TestAddHTLCNegativeBalance(t *testing.T) { 3030 t.Parallel() 3031 3032 // We'll kick off the test by creating our channels which both are 3033 // loaded with 5 DCR each. 3034 aliceChannel, _, cleanUp, err := CreateTestChannels( 3035 channeldb.SingleFunderTweaklessBit, 3036 ) 3037 if err != nil { 3038 t.Fatalf("unable to create test channels: %v", err) 3039 } 3040 defer cleanUp() 3041 3042 // We set the channel reserve to 0, such that we can add HTLCs all the 3043 // way to a negative balance. 3044 aliceChannel.channelState.LocalChanCfg.ChanReserve = 0 3045 3046 // First, we'll add 3 HTLCs of 1 DCR each to Alice's commitment. 3047 const numHTLCs = 3 3048 htlcAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 3049 for i := 0; i < numHTLCs; i++ { 3050 htlc, _ := createHTLC(i, htlcAmt) 3051 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 3052 t.Fatalf("unable to add htlc: %v", err) 3053 } 3054 } 3055 3056 // Alice now has an available balance of 2 DCR. We'll add a new HTLC of 3057 // value 2 DCR, which should make Alice's balance negative (since she 3058 // has to pay a commitment fee). 3059 htlcAmt = lnwire.NewMAtomsFromAtoms(2 * dcrutil.AtomsPerCoin) 3060 htlc, _ := createHTLC(numHTLCs+1, htlcAmt) 3061 _, err = aliceChannel.AddHTLC(htlc, nil) 3062 if err != ErrBelowChanReserve { 3063 t.Fatalf("expected balance below channel reserve, instead "+ 3064 "got: %v", err) 3065 } 3066 } 3067 3068 // assertNoChanSyncNeeded is a helper function that asserts that upon restart, 3069 // two channels conclude that they're fully synchronized and don't need to 3070 // retransmit any new messages. 3071 func assertNoChanSyncNeeded(t *testing.T, aliceChannel *LightningChannel, 3072 bobChannel *LightningChannel) { 3073 3074 _, _, line, _ := runtime.Caller(1) 3075 3076 aliceChanSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 3077 if err != nil { 3078 t.Fatalf("line #%v: unable to produce chan sync msg: %v", 3079 line, err) 3080 } 3081 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceChanSyncMsg) 3082 if err != nil { 3083 t.Fatalf("line #%v: unable to process ChannelReestablish "+ 3084 "msg: %v", line, err) 3085 } 3086 if len(bobMsgsToSend) != 0 { 3087 t.Fatalf("line #%v: bob shouldn't have to send any messages, "+ 3088 "instead wants to send: %v", line, spew.Sdump(bobMsgsToSend)) 3089 } 3090 3091 bobChanSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 3092 if err != nil { 3093 t.Fatalf("line #%v: unable to produce chan sync msg: %v", 3094 line, err) 3095 } 3096 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg(bobChanSyncMsg) 3097 if err != nil { 3098 t.Fatalf("line #%v: unable to process ChannelReestablish "+ 3099 "msg: %v", line, err) 3100 } 3101 if len(bobMsgsToSend) != 0 { 3102 t.Fatalf("line #%v: alice shouldn't have to send any "+ 3103 "messages, instead wants to send: %v", line, 3104 spew.Sdump(aliceMsgsToSend)) 3105 } 3106 } 3107 3108 // TestChanSyncFullySynced tests that after a successful commitment exchange, 3109 // and a forced restart, both nodes conclude that they're fully synchronized 3110 // and don't need to retransmit any messages. 3111 func TestChanSyncFullySynced(t *testing.T) { 3112 t.Parallel() 3113 3114 // Create a test channel which will be used for the duration of this 3115 // unittest. The channel will be funded evenly with Alice having 5 DCR, 3116 // and Bob having 5 DCR. 3117 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 3118 channeldb.SingleFunderTweaklessBit, 3119 ) 3120 if err != nil { 3121 t.Fatalf("unable to create test channels: %v", err) 3122 } 3123 defer cleanUp() 3124 3125 // If we exchange channel sync messages from the get-go , then both 3126 // sides should conclude that no further synchronization is needed. 3127 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 3128 3129 // Next, we'll create an HTLC for Alice to extend to Bob. 3130 var paymentPreimage [32]byte 3131 copy(paymentPreimage[:], bytes.Repeat([]byte{1}, 32)) 3132 paymentHash := sha256.Sum256(paymentPreimage[:]) 3133 htlcAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 3134 htlc := &lnwire.UpdateAddHTLC{ 3135 PaymentHash: paymentHash, 3136 Amount: htlcAmt, 3137 Expiry: uint32(5), 3138 } 3139 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 3140 if err != nil { 3141 t.Fatalf("unable to add htlc: %v", err) 3142 } 3143 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 3144 if err != nil { 3145 t.Fatalf("unable to recv htlc: %v", err) 3146 } 3147 3148 // Then we'll initiate a state transition to lock in this new HTLC. 3149 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 3150 t.Fatalf("unable to complete alice's state transition: %v", err) 3151 } 3152 3153 // At this point, if both sides generate a ChannelReestablish message, 3154 // they should both conclude that they're fully in sync. 3155 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 3156 3157 // If bob settles the HTLC, and then initiates a state transition, they 3158 // should both still think that they're in sync. 3159 err = bobChannel.SettleHTLC(paymentPreimage, bobHtlcIndex, nil, nil, nil) 3160 if err != nil { 3161 t.Fatalf("unable to settle htlc: %v", err) 3162 } 3163 err = aliceChannel.ReceiveHTLCSettle(paymentPreimage, aliceHtlcIndex) 3164 if err != nil { 3165 t.Fatalf("unable to settle htlc: %v", err) 3166 } 3167 3168 // Next, we'll complete Bob's state transition, and assert again that 3169 // they think they're fully synced. 3170 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3171 t.Fatalf("unable to complete bob's state transition: %v", err) 3172 } 3173 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 3174 3175 // Finally, if we simulate a restart on both sides, then both should 3176 // still conclude that they don't need to synchronize their state. 3177 alicePub := aliceChannel.channelState.IdentityPub 3178 aliceChannels, err := aliceChannel.channelState.Db.FetchOpenChannels( 3179 alicePub, 3180 ) 3181 if err != nil { 3182 t.Fatalf("unable to fetch channel: %v", err) 3183 } 3184 bobPub := bobChannel.channelState.IdentityPub 3185 bobChannels, err := bobChannel.channelState.Db.FetchOpenChannels(bobPub) 3186 if err != nil { 3187 t.Fatalf("unable to fetch channel: %v", err) 3188 } 3189 3190 aliceChannelNew, err := NewLightningChannel( 3191 aliceChannel.Signer, aliceChannels[0], aliceChannel.sigPool, 3192 testChainParams, 3193 ) 3194 if err != nil { 3195 t.Fatalf("unable to create new channel: %v", err) 3196 } 3197 bobChannelNew, err := NewLightningChannel( 3198 bobChannel.Signer, bobChannels[0], bobChannel.sigPool, 3199 testChainParams, 3200 ) 3201 if err != nil { 3202 t.Fatalf("unable to create new channel: %v", err) 3203 } 3204 3205 assertNoChanSyncNeeded(t, aliceChannelNew, bobChannelNew) 3206 } 3207 3208 // restartChannel reads the passed channel from disk, and returns a newly 3209 // initialized instance. This simulates one party restarting and losing their 3210 // in memory state. 3211 func restartChannel(channelOld *LightningChannel) (*LightningChannel, error) { 3212 nodePub := channelOld.channelState.IdentityPub 3213 nodeChannels, err := channelOld.channelState.Db.FetchOpenChannels( 3214 nodePub, 3215 ) 3216 if err != nil { 3217 return nil, err 3218 } 3219 3220 channelNew, err := NewLightningChannel( 3221 channelOld.Signer, nodeChannels[0], 3222 channelOld.sigPool, testChainParams, 3223 ) 3224 if err != nil { 3225 return nil, err 3226 } 3227 3228 return channelNew, nil 3229 } 3230 3231 // TestChanSyncOweCommitment tests that if Bob restarts (and then Alice) before 3232 // he receives Alice's CommitSig message, then Alice concludes that she needs 3233 // to re-send the CommitDiff. After the diff has been sent, both nodes should 3234 // resynchronize and be able to complete the dangling commit. 3235 func TestChanSyncOweCommitment(t *testing.T) { 3236 t.Parallel() 3237 3238 // Create a test channel which will be used for the duration of this 3239 // unittest. The channel will be funded evenly with Alice having 5 DCR, 3240 // and Bob having 5 DCR. 3241 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 3242 channeldb.SingleFunderTweaklessBit, 3243 ) 3244 if err != nil { 3245 t.Fatalf("unable to create test channels: %v", err) 3246 } 3247 defer cleanUp() 3248 3249 var fakeOnionBlob [lnwire.OnionPacketSize]byte 3250 copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) 3251 3252 // We'll start off the scenario with Bob sending 3 HTLC's to Alice in a 3253 // single state update. 3254 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 3255 const numBobHtlcs = 3 3256 var bobPreimage [32]byte 3257 copy(bobPreimage[:], bytes.Repeat([]byte{0xbb}, 32)) 3258 for i := 0; i < 3; i++ { 3259 rHash := sha256.Sum256(bobPreimage[:]) 3260 h := &lnwire.UpdateAddHTLC{ 3261 PaymentHash: rHash, 3262 Amount: htlcAmt, 3263 Expiry: uint32(10), 3264 OnionBlob: fakeOnionBlob, 3265 ExtraData: make([]byte, 0), 3266 } 3267 3268 htlcIndex, err := bobChannel.AddHTLC(h, nil) 3269 if err != nil { 3270 t.Fatalf("unable to add bob's htlc: %v", err) 3271 } 3272 3273 h.ID = htlcIndex 3274 if _, err := aliceChannel.ReceiveHTLC(h); err != nil { 3275 t.Fatalf("unable to recv bob's htlc: %v", err) 3276 } 3277 } 3278 3279 chanID := lnwire.NewChanIDFromOutPoint( 3280 &aliceChannel.channelState.FundingOutpoint, 3281 ) 3282 3283 // With the HTLC's applied to both update logs, we'll initiate a state 3284 // transition from Bob. 3285 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3286 t.Fatalf("unable to complete bob's state transition: %v", err) 3287 } 3288 3289 // Next, Alice's settles all 3 HTLC's from Bob, and also adds a new 3290 // HTLC of her own. 3291 for i := 0; i < 3; i++ { 3292 err := aliceChannel.SettleHTLC(bobPreimage, uint64(i), nil, nil, nil) 3293 if err != nil { 3294 t.Fatalf("unable to settle htlc: %v", err) 3295 } 3296 err = bobChannel.ReceiveHTLCSettle(bobPreimage, uint64(i)) 3297 if err != nil { 3298 t.Fatalf("unable to settle htlc: %v", err) 3299 } 3300 } 3301 var alicePreimage [32]byte 3302 copy(alicePreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 3303 rHash := sha256.Sum256(alicePreimage[:]) 3304 aliceHtlc := &lnwire.UpdateAddHTLC{ 3305 ChanID: chanID, 3306 PaymentHash: rHash, 3307 Amount: htlcAmt, 3308 Expiry: uint32(10), 3309 OnionBlob: fakeOnionBlob, 3310 ExtraData: make([]byte, 0), 3311 } 3312 aliceHtlcIndex, err := aliceChannel.AddHTLC(aliceHtlc, nil) 3313 if err != nil { 3314 t.Fatalf("unable to add alice's htlc: %v", err) 3315 } 3316 bobHtlcIndex, err := bobChannel.ReceiveHTLC(aliceHtlc) 3317 if err != nil { 3318 t.Fatalf("unable to recv alice's htlc: %v", err) 3319 } 3320 3321 // Now we'll begin the core of the test itself. Alice will extend a new 3322 // commitment to Bob, but the connection drops before Bob can process 3323 // it. 3324 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 3325 if err != nil { 3326 t.Fatalf("unable to sign commitment: %v", err) 3327 } 3328 3329 // Bob doesn't get this message so upon reconnection, they need to 3330 // synchronize. Alice should conclude that she owes Bob a commitment, 3331 // while Bob should think he's properly synchronized. 3332 aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 3333 if err != nil { 3334 t.Fatalf("unable to produce chan sync msg: %v", err) 3335 } 3336 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 3337 if err != nil { 3338 t.Fatalf("unable to produce chan sync msg: %v", err) 3339 } 3340 3341 // This is a helper function that asserts Alice concludes that she 3342 // needs to retransmit the exact commitment that we failed to send 3343 // above. 3344 assertAliceCommitRetransmit := func() { 3345 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg( 3346 bobSyncMsg, 3347 ) 3348 if err != nil { 3349 t.Fatalf("unable to process chan sync msg: %v", err) 3350 } 3351 if len(aliceMsgsToSend) != 5 { 3352 t.Fatalf("expected alice to send %v messages instead "+ 3353 "will send %v: %v", 5, len(aliceMsgsToSend), 3354 spew.Sdump(aliceMsgsToSend)) 3355 } 3356 3357 // Each of the settle messages that Alice sent should match her 3358 // original intent. 3359 for i := 0; i < 3; i++ { 3360 settleMsg, ok := aliceMsgsToSend[i].(*lnwire.UpdateFulfillHTLC) 3361 if !ok { 3362 t.Fatalf("expected an HTLC settle message, "+ 3363 "instead have %v", spew.Sdump(settleMsg)) 3364 } 3365 if settleMsg.ID != uint64(i) { 3366 t.Fatalf("wrong ID in settle msg: expected %v, "+ 3367 "got %v", i, settleMsg.ID) 3368 } 3369 if settleMsg.ChanID != chanID { 3370 t.Fatalf("incorrect chan id: expected %v, got %v", 3371 chanID, settleMsg.ChanID) 3372 } 3373 if settleMsg.PaymentPreimage != bobPreimage { 3374 t.Fatalf("wrong pre-image: expected %v, got %v", 3375 alicePreimage, settleMsg.PaymentPreimage) 3376 } 3377 } 3378 3379 // The HTLC add message should be identical. 3380 if _, ok := aliceMsgsToSend[3].(*lnwire.UpdateAddHTLC); !ok { 3381 t.Fatalf("expected an HTLC add message, instead have %v", 3382 spew.Sdump(aliceMsgsToSend[3])) 3383 } 3384 if !reflect.DeepEqual(aliceHtlc, aliceMsgsToSend[3]) { 3385 t.Fatalf("htlc msg doesn't match exactly: "+ 3386 "expected %v got %v", spew.Sdump(aliceHtlc), 3387 spew.Sdump(aliceMsgsToSend[3])) 3388 } 3389 3390 // Next, we'll ensure that the CommitSig message exactly 3391 // matches what Alice originally intended to send. 3392 commitSigMsg, ok := aliceMsgsToSend[4].(*lnwire.CommitSig) 3393 if !ok { 3394 t.Fatalf("expected a CommitSig message, instead have %v", 3395 spew.Sdump(aliceMsgsToSend[4])) 3396 } 3397 if commitSigMsg.CommitSig != aliceSig { 3398 t.Fatalf("commit sig msgs don't match: expected %x got %x", 3399 aliceSig, commitSigMsg.CommitSig) 3400 } 3401 if len(commitSigMsg.HtlcSigs) != len(aliceHtlcSigs) { 3402 t.Fatalf("wrong number of htlc sigs: expected %v, got %v", 3403 len(aliceHtlcSigs), len(commitSigMsg.HtlcSigs)) 3404 } 3405 for i, htlcSig := range commitSigMsg.HtlcSigs { 3406 if htlcSig != aliceHtlcSigs[i] { 3407 t.Fatalf("htlc sig msgs don't match: "+ 3408 "expected %x got %x", 3409 aliceHtlcSigs[i], 3410 htlcSig) 3411 } 3412 } 3413 } 3414 3415 // Alice should detect that she needs to re-send 5 messages: the 3 3416 // settles, her HTLC add, and finally her commit sig message. 3417 assertAliceCommitRetransmit() 3418 3419 // From Bob's Pov he has nothing else to send, so he should conclude he 3420 // has no further action remaining. 3421 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 3422 if err != nil { 3423 t.Fatalf("unable to process chan sync msg: %v", err) 3424 } 3425 if len(bobMsgsToSend) != 0 { 3426 t.Fatalf("expected bob to send %v messages instead will "+ 3427 "send %v: %v", 5, len(bobMsgsToSend), 3428 spew.Sdump(bobMsgsToSend)) 3429 } 3430 3431 // If we restart Alice, she should still conclude that she needs to 3432 // send the exact same set of messages. 3433 aliceChannel, err = restartChannel(aliceChannel) 3434 if err != nil { 3435 t.Fatalf("unable to restart alice: %v", err) 3436 } 3437 assertAliceCommitRetransmit() 3438 3439 // TODO(roasbeef): restart bob as well??? 3440 3441 // At this point, we should be able to resume the prior state update 3442 // without any issues, resulting in Alice settling the 3 htlc's, and 3443 // adding one of her own. 3444 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 3445 if err != nil { 3446 t.Fatalf("bob unable to process alice's commitment: %v", err) 3447 } 3448 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 3449 if err != nil { 3450 t.Fatalf("unable to revoke bob commitment: %v", err) 3451 } 3452 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 3453 if err != nil { 3454 t.Fatalf("bob unable to sign commitment: %v", err) 3455 } 3456 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 3457 if err != nil { 3458 t.Fatalf("alice unable to recv revocation: %v", err) 3459 } 3460 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 3461 if err != nil { 3462 t.Fatalf("alice unable to rev bob's commitment: %v", err) 3463 } 3464 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 3465 if err != nil { 3466 t.Fatalf("alice unable to revoke commitment: %v", err) 3467 } 3468 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 3469 if err != nil { 3470 t.Fatalf("bob unable to recv revocation: %v", err) 3471 } 3472 3473 // At this point, we'll now assert that their log states are what we 3474 // expect. 3475 // 3476 // Alice's local log counter should be 4 and her HTLC index 3. She 3477 // should detect Bob's remote log counter as being 3 and his HTLC index 3478 // 3 as well. 3479 if aliceChannel.localUpdateLog.logIndex != 4 { 3480 t.Fatalf("incorrect log index: expected %v, got %v", 4, 3481 aliceChannel.localUpdateLog.logIndex) 3482 } 3483 if aliceChannel.localUpdateLog.htlcCounter != 1 { 3484 t.Fatalf("incorrect htlc index: expected %v, got %v", 1, 3485 aliceChannel.localUpdateLog.htlcCounter) 3486 } 3487 if aliceChannel.remoteUpdateLog.logIndex != 3 { 3488 t.Fatalf("incorrect log index: expected %v, got %v", 3, 3489 aliceChannel.localUpdateLog.logIndex) 3490 } 3491 if aliceChannel.remoteUpdateLog.htlcCounter != 3 { 3492 t.Fatalf("incorrect htlc index: expected %v, got %v", 3, 3493 aliceChannel.localUpdateLog.htlcCounter) 3494 } 3495 3496 // Bob should also have the same state, but mirrored. 3497 if bobChannel.localUpdateLog.logIndex != 3 { 3498 t.Fatalf("incorrect log index: expected %v, got %v", 3, 3499 bobChannel.localUpdateLog.logIndex) 3500 } 3501 if bobChannel.localUpdateLog.htlcCounter != 3 { 3502 t.Fatalf("incorrect htlc index: expected %v, got %v", 3, 3503 bobChannel.localUpdateLog.htlcCounter) 3504 } 3505 if bobChannel.remoteUpdateLog.logIndex != 4 { 3506 t.Fatalf("incorrect log index: expected %v, got %v", 4, 3507 bobChannel.localUpdateLog.logIndex) 3508 } 3509 if bobChannel.remoteUpdateLog.htlcCounter != 1 { 3510 t.Fatalf("incorrect htlc index: expected %v, got %v", 1, 3511 bobChannel.localUpdateLog.htlcCounter) 3512 } 3513 3514 // We'll conclude the test by having Bob settle Alice's HTLC, then 3515 // initiate a state transition. 3516 err = bobChannel.SettleHTLC(alicePreimage, bobHtlcIndex, nil, nil, nil) 3517 if err != nil { 3518 t.Fatalf("unable to settle htlc: %v", err) 3519 } 3520 err = aliceChannel.ReceiveHTLCSettle(alicePreimage, aliceHtlcIndex) 3521 if err != nil { 3522 t.Fatalf("unable to settle htlc: %v", err) 3523 } 3524 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3525 t.Fatalf("unable to complete bob's state transition: %v", err) 3526 } 3527 3528 // At this point, the final balances of both parties should properly 3529 // reflect the amount of HTLC's sent. 3530 bobMAtomsSent := numBobHtlcs * htlcAmt 3531 if aliceChannel.channelState.TotalMAtomsSent != htlcAmt { 3532 t.Fatalf("wrong value for mAt sent: expected %v, got %v", 3533 htlcAmt, aliceChannel.channelState.TotalMAtomsSent) 3534 } 3535 if aliceChannel.channelState.TotalMAtomsReceived != bobMAtomsSent { 3536 t.Fatalf("wrong value for mAt recv: expected %v, got %v", 3537 bobMAtomsSent, aliceChannel.channelState.TotalMAtomsReceived) 3538 } 3539 if bobChannel.channelState.TotalMAtomsSent != bobMAtomsSent { 3540 t.Fatalf("wrong value for mAt sent: expected %v, got %v", 3541 bobMAtomsSent, bobChannel.channelState.TotalMAtomsSent) 3542 } 3543 if bobChannel.channelState.TotalMAtomsReceived != htlcAmt { 3544 t.Fatalf("wrong value for mAt recv: expected %v, got %v", 3545 htlcAmt, bobChannel.channelState.TotalMAtomsReceived) 3546 } 3547 } 3548 3549 // TestChanSyncOweCommitmentPendingRemote asserts that local updates are applied 3550 // to the remote commit across restarts. 3551 func TestChanSyncOweCommitmentPendingRemote(t *testing.T) { 3552 t.Parallel() 3553 3554 // Create a test channel which will be used for the duration of this 3555 // unittest. 3556 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 3557 channeldb.SingleFunderTweaklessBit, 3558 ) 3559 if err != nil { 3560 t.Fatalf("unable to create test channels: %v", err) 3561 } 3562 defer cleanUp() 3563 3564 var fakeOnionBlob [lnwire.OnionPacketSize]byte 3565 copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) 3566 3567 // We'll start off the scenario where Bob send two htlcs to Alice in a 3568 // single state update. 3569 var preimages []lntypes.Preimage 3570 const numHtlcs = 2 3571 for id := byte(0); id < numHtlcs; id++ { 3572 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 3573 var bobPreimage [32]byte 3574 copy(bobPreimage[:], bytes.Repeat([]byte{id}, 32)) 3575 rHash := sha256.Sum256(bobPreimage[:]) 3576 h := &lnwire.UpdateAddHTLC{ 3577 PaymentHash: rHash, 3578 Amount: htlcAmt, 3579 Expiry: uint32(10), 3580 OnionBlob: fakeOnionBlob, 3581 } 3582 3583 htlcIndex, err := bobChannel.AddHTLC(h, nil) 3584 if err != nil { 3585 t.Fatalf("unable to add bob's htlc: %v", err) 3586 } 3587 3588 h.ID = htlcIndex 3589 if _, err := aliceChannel.ReceiveHTLC(h); err != nil { 3590 t.Fatalf("unable to recv bob's htlc: %v", err) 3591 } 3592 3593 preimages = append(preimages, bobPreimage) 3594 } 3595 3596 // With the HTLCs applied to both update logs, we'll initiate a state 3597 // transition from Bob. 3598 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3599 t.Fatalf("unable to complete bob's state transition: %v", err) 3600 } 3601 3602 // Next, Alice settles the HTLCs from Bob in distinct state updates. 3603 for i := 0; i < numHtlcs; i++ { 3604 err = aliceChannel.SettleHTLC(preimages[i], uint64(i), nil, nil, nil) 3605 if err != nil { 3606 t.Fatalf("unable to settle htlc: %v", err) 3607 } 3608 err = bobChannel.ReceiveHTLCSettle(preimages[i], uint64(i)) 3609 if err != nil { 3610 t.Fatalf("unable to settle htlc: %v", err) 3611 } 3612 3613 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 3614 if err != nil { 3615 t.Fatalf("unable to sign commitment: %v", err) 3616 } 3617 3618 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 3619 if err != nil { 3620 t.Fatalf("unable to receive commitment: %v", err) 3621 } 3622 3623 // Bob revokes his current commitment. After this call 3624 // completes, the htlc is settled on the local commitment 3625 // transaction. Bob still owes Alice a signature to also settle 3626 // the htlc on her local commitment transaction. 3627 bobRevoke, _, err := bobChannel.RevokeCurrentCommitment() 3628 if err != nil { 3629 t.Fatalf("unable to revoke commitment: %v", err) 3630 } 3631 3632 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevoke) 3633 if err != nil { 3634 t.Fatalf("unable to revoke commitment: %v", err) 3635 } 3636 } 3637 3638 // We restart Bob. This should have no impact on further message that 3639 // are generated. 3640 bobChannel, err = restartChannel(bobChannel) 3641 if err != nil { 3642 t.Fatalf("unable to restart bob: %v", err) 3643 } 3644 3645 // Bob signs the commitment he owes. 3646 bobCommit, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 3647 if err != nil { 3648 t.Fatalf("unable to sign commitment: %v", err) 3649 } 3650 3651 // This commitment is expected to contain no htlcs anymore. 3652 if len(bobHtlcSigs) != 0 { 3653 t.Fatalf("no htlcs expected, but got %v", len(bobHtlcSigs)) 3654 } 3655 3656 // Get Alice to revoke and trigger Bob to compact his logs. 3657 err = aliceChannel.ReceiveNewCommitment(bobCommit, bobHtlcSigs) 3658 if err != nil { 3659 t.Fatal(err) 3660 } 3661 aliceRevoke, _, err := aliceChannel.RevokeCurrentCommitment() 3662 if err != nil { 3663 t.Fatal(err) 3664 } 3665 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevoke) 3666 if err != nil { 3667 t.Fatal(err) 3668 } 3669 } 3670 3671 // TestChanSyncOweRevocation tests that if Bob restarts (and then Alice) before 3672 // he receiver's Alice's RevokeAndAck message, then Alice concludes that she 3673 // needs to re-send the RevokeAndAck. After the revocation has been sent, both 3674 // nodes should be able to successfully complete another state transition. 3675 func TestChanSyncOweRevocation(t *testing.T) { 3676 t.Parallel() 3677 3678 // Create a test channel which will be used for the duration of this 3679 // unittest. The channel will be funded evenly with Alice having 5 DCR, 3680 // and Bob having 5 DCR. 3681 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 3682 channeldb.SingleFunderTweaklessBit, 3683 ) 3684 if err != nil { 3685 t.Fatalf("unable to create test channels: %v", err) 3686 } 3687 defer cleanUp() 3688 3689 chanID := lnwire.NewChanIDFromOutPoint( 3690 &aliceChannel.channelState.FundingOutpoint, 3691 ) 3692 3693 // We'll start the test with Bob extending a single HTLC to Alice, and 3694 // then initiating a state transition. 3695 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 3696 var bobPreimage [32]byte 3697 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 3698 rHash := sha256.Sum256(bobPreimage[:]) 3699 bobHtlc := &lnwire.UpdateAddHTLC{ 3700 ChanID: chanID, 3701 PaymentHash: rHash, 3702 Amount: htlcAmt, 3703 Expiry: uint32(10), 3704 } 3705 bobHtlcIndex, err := bobChannel.AddHTLC(bobHtlc, nil) 3706 if err != nil { 3707 t.Fatalf("unable to add bob's htlc: %v", err) 3708 } 3709 aliceHtlcIndex, err := aliceChannel.ReceiveHTLC(bobHtlc) 3710 if err != nil { 3711 t.Fatalf("unable to recv bob's htlc: %v", err) 3712 } 3713 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3714 t.Fatalf("unable to complete bob's state transition: %v", err) 3715 } 3716 3717 // Next, Alice will settle that single HTLC, the _begin_ the start of a 3718 // state transition. 3719 err = aliceChannel.SettleHTLC(bobPreimage, aliceHtlcIndex, nil, nil, nil) 3720 if err != nil { 3721 t.Fatalf("unable to settle htlc: %v", err) 3722 } 3723 err = bobChannel.ReceiveHTLCSettle(bobPreimage, bobHtlcIndex) 3724 if err != nil { 3725 t.Fatalf("unable to settle htlc: %v", err) 3726 } 3727 3728 // We'll model the state transition right up until Alice needs to send 3729 // her revocation message to complete the state transition. 3730 // 3731 // Alice signs the next state, then Bob receives and sends his 3732 // revocation message. 3733 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 3734 if err != nil { 3735 t.Fatalf("unable to sign commitment: %v", err) 3736 } 3737 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 3738 if err != nil { 3739 t.Fatalf("bob unable to process alice's commitment: %v", err) 3740 } 3741 3742 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 3743 if err != nil { 3744 t.Fatalf("unable to revoke bob commitment: %v", err) 3745 } 3746 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 3747 if err != nil { 3748 t.Fatalf("bob unable to sign commitment: %v", err) 3749 } 3750 3751 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 3752 if err != nil { 3753 t.Fatalf("alice unable to recv revocation: %v", err) 3754 } 3755 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 3756 if err != nil { 3757 t.Fatalf("alice unable to rev bob's commitment: %v", err) 3758 } 3759 3760 // At this point, we'll simulate the connection breaking down by Bob's 3761 // lack of knowledge of the revocation message that Alice just sent. 3762 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 3763 if err != nil { 3764 t.Fatalf("alice unable to revoke commitment: %v", err) 3765 } 3766 3767 // If we fetch the channel sync messages at this state, then Alice 3768 // should report that she owes Bob a revocation message, while Bob 3769 // thinks they're fully in sync. 3770 aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 3771 if err != nil { 3772 t.Fatalf("unable to produce chan sync msg: %v", err) 3773 } 3774 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 3775 if err != nil { 3776 t.Fatalf("unable to produce chan sync msg: %v", err) 3777 } 3778 3779 assertAliceOwesRevoke := func() { 3780 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 3781 if err != nil { 3782 t.Fatalf("unable to process chan sync msg: %v", err) 3783 } 3784 if len(aliceMsgsToSend) != 1 { 3785 t.Fatalf("expected single message retransmission from Alice, "+ 3786 "instead got %v", spew.Sdump(aliceMsgsToSend)) 3787 } 3788 aliceReRevoke, ok := aliceMsgsToSend[0].(*lnwire.RevokeAndAck) 3789 if !ok { 3790 t.Fatalf("expected to retransmit revocation msg, instead "+ 3791 "have: %v", spew.Sdump(aliceMsgsToSend[0])) 3792 } 3793 3794 // Alice should re-send the revocation message for her prior 3795 // state. 3796 expectedRevocation, err := aliceChannel.generateRevocation( 3797 aliceChannel.currentHeight - 1, 3798 ) 3799 if err != nil { 3800 t.Fatalf("unable to regenerate revocation: %v", err) 3801 } 3802 if !reflect.DeepEqual(expectedRevocation, aliceReRevoke) { 3803 t.Fatalf("wrong re-revocation: expected %v, got %v", 3804 expectedRevocation, aliceReRevoke) 3805 } 3806 } 3807 3808 // From Bob's PoV he shouldn't think that he owes Alice any messages. 3809 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 3810 if err != nil { 3811 t.Fatalf("unable to process chan sync msg: %v", err) 3812 } 3813 if len(bobMsgsToSend) != 0 { 3814 t.Fatalf("expected bob to not retransmit, instead has: %v", 3815 spew.Sdump(bobMsgsToSend)) 3816 } 3817 3818 // Alice should detect that she owes Bob a revocation message, and only 3819 // that single message. 3820 assertAliceOwesRevoke() 3821 3822 // If we restart Alice, then she should still decide that she owes a 3823 // revocation message to Bob. 3824 aliceChannel, err = restartChannel(aliceChannel) 3825 if err != nil { 3826 t.Fatalf("unable to restart alice: %v", err) 3827 } 3828 assertAliceOwesRevoke() 3829 3830 // TODO(roasbeef): restart bob too??? 3831 3832 // We'll continue by then allowing bob to process Alice's revocation message. 3833 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 3834 if err != nil { 3835 t.Fatalf("bob unable to recv revocation: %v", err) 3836 } 3837 3838 // Finally, Alice will add an HTLC over her own such that we assert the 3839 // channel can continue to receive updates. 3840 var alicePreimage [32]byte 3841 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 3842 rHash = sha256.Sum256(alicePreimage[:]) 3843 aliceHtlc := &lnwire.UpdateAddHTLC{ 3844 ChanID: chanID, 3845 PaymentHash: rHash, 3846 Amount: htlcAmt, 3847 Expiry: uint32(10), 3848 } 3849 if _, err := aliceChannel.AddHTLC(aliceHtlc, nil); err != nil { 3850 t.Fatalf("unable to add alice's htlc: %v", err) 3851 } 3852 if _, err := bobChannel.ReceiveHTLC(aliceHtlc); err != nil { 3853 t.Fatalf("unable to recv alice's htlc: %v", err) 3854 } 3855 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 3856 t.Fatalf("unable to complete alice's state transition: %v", err) 3857 } 3858 3859 // At this point, both sides should detect that they're fully synced. 3860 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 3861 } 3862 3863 // TestChanSyncOweRevocationAndCommit tests that if Alice initiates a state 3864 // transition with Bob and Bob sends both a RevokeAndAck and CommitSig message 3865 // but Alice doesn't receive them before the connection dies, then he'll 3866 // retransmit them both. 3867 func TestChanSyncOweRevocationAndCommit(t *testing.T) { 3868 t.Parallel() 3869 3870 // Create a test channel which will be used for the duration of this 3871 // unittest. The channel will be funded evenly with Alice having 5 DCR, 3872 // and Bob having 5 DCR. 3873 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 3874 channeldb.SingleFunderTweaklessBit, 3875 ) 3876 if err != nil { 3877 t.Fatalf("unable to create test channels: %v", err) 3878 } 3879 defer cleanUp() 3880 3881 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 3882 3883 // We'll kick off the test by having Bob send Alice an HTLC, then lock 3884 // it in with a state transition. 3885 var bobPreimage [32]byte 3886 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 3887 rHash := sha256.Sum256(bobPreimage[:]) 3888 bobHtlc := &lnwire.UpdateAddHTLC{ 3889 PaymentHash: rHash, 3890 Amount: htlcAmt, 3891 Expiry: uint32(10), 3892 } 3893 bobHtlcIndex, err := bobChannel.AddHTLC(bobHtlc, nil) 3894 if err != nil { 3895 t.Fatalf("unable to add bob's htlc: %v", err) 3896 } 3897 aliceHtlcIndex, err := aliceChannel.ReceiveHTLC(bobHtlc) 3898 if err != nil { 3899 t.Fatalf("unable to recv bob's htlc: %v", err) 3900 } 3901 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 3902 t.Fatalf("unable to complete bob's state transition: %v", err) 3903 } 3904 3905 // Next, Alice will settle that incoming HTLC, then we'll start the 3906 // core of the test itself. 3907 err = aliceChannel.SettleHTLC(bobPreimage, aliceHtlcIndex, nil, nil, nil) 3908 if err != nil { 3909 t.Fatalf("unable to settle htlc: %v", err) 3910 } 3911 err = bobChannel.ReceiveHTLCSettle(bobPreimage, bobHtlcIndex) 3912 if err != nil { 3913 t.Fatalf("unable to settle htlc: %v", err) 3914 } 3915 3916 // Progressing the exchange: Alice will send her signature, Bob will 3917 // receive, send a revocation and also a signature for Alice's state. 3918 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 3919 if err != nil { 3920 t.Fatalf("unable to sign commitment: %v", err) 3921 } 3922 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 3923 if err != nil { 3924 t.Fatalf("bob unable to process alice's commitment: %v", err) 3925 } 3926 3927 // Bob generates the revoke and sig message, but the messages don't 3928 // reach Alice before the connection dies. 3929 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 3930 if err != nil { 3931 t.Fatalf("unable to revoke bob commitment: %v", err) 3932 } 3933 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 3934 if err != nil { 3935 t.Fatalf("bob unable to sign commitment: %v", err) 3936 } 3937 3938 // If we now attempt to resync, then Alice should conclude that she 3939 // doesn't need any further updates, while Bob concludes that he needs 3940 // to re-send both his revocation and commit sig message. 3941 aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 3942 if err != nil { 3943 t.Fatalf("unable to produce chan sync msg: %v", err) 3944 } 3945 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 3946 if err != nil { 3947 t.Fatalf("unable to produce chan sync msg: %v", err) 3948 } 3949 3950 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 3951 if err != nil { 3952 t.Fatalf("unable to process chan sync msg: %v", err) 3953 } 3954 if len(aliceMsgsToSend) != 0 { 3955 t.Fatalf("expected alice to not retransmit, instead she's "+ 3956 "sending: %v", spew.Sdump(aliceMsgsToSend)) 3957 } 3958 3959 assertBobSendsRevokeAndCommit := func() { 3960 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 3961 if err != nil { 3962 t.Fatalf("unable to process chan sync msg: %v", err) 3963 } 3964 if len(bobMsgsToSend) != 2 { 3965 t.Fatalf("expected bob to send %v messages, instead "+ 3966 "sends: %v", 2, spew.Sdump(bobMsgsToSend)) 3967 } 3968 bobReRevoke, ok := bobMsgsToSend[0].(*lnwire.RevokeAndAck) 3969 if !ok { 3970 t.Fatalf("expected bob to re-send revoke, instead sending: %v", 3971 spew.Sdump(bobMsgsToSend[0])) 3972 } 3973 if !reflect.DeepEqual(bobReRevoke, bobRevocation) { 3974 t.Fatalf("revocation msgs don't match: expected %v, got %v", 3975 bobRevocation, bobReRevoke) 3976 } 3977 3978 bobReCommitSigMsg, ok := bobMsgsToSend[1].(*lnwire.CommitSig) 3979 if !ok { 3980 t.Fatalf("expected bob to re-send commit sig, instead sending: %v", 3981 spew.Sdump(bobMsgsToSend[1])) 3982 } 3983 if bobReCommitSigMsg.CommitSig != bobSig { 3984 t.Fatalf("commit sig msgs don't match: expected %x got %x", 3985 bobSig, bobReCommitSigMsg.CommitSig) 3986 } 3987 if len(bobReCommitSigMsg.HtlcSigs) != len(bobHtlcSigs) { 3988 t.Fatalf("wrong number of htlc sigs: expected %v, got %v", 3989 len(bobHtlcSigs), len(bobReCommitSigMsg.HtlcSigs)) 3990 } 3991 for i, htlcSig := range bobReCommitSigMsg.HtlcSigs { 3992 if htlcSig != aliceHtlcSigs[i] { 3993 t.Fatalf("htlc sig msgs don't match: "+ 3994 "expected %x got %x", 3995 bobHtlcSigs[i], htlcSig) 3996 } 3997 } 3998 } 3999 4000 // We expect Bob to send exactly two messages: first his revocation 4001 // message to Alice, and second his original commit sig message. 4002 assertBobSendsRevokeAndCommit() 4003 4004 // At this point we simulate the connection failing with a restart from 4005 // Bob. He should still re-send the exact same set of messages. 4006 bobChannel, err = restartChannel(bobChannel) 4007 if err != nil { 4008 t.Fatalf("unable to restart channel: %v", err) 4009 } 4010 assertBobSendsRevokeAndCommit() 4011 4012 // We'll now finish the state transition by having Alice process both 4013 // messages, and send her final revocation. 4014 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 4015 if err != nil { 4016 t.Fatalf("alice unable to recv revocation: %v", err) 4017 } 4018 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 4019 if err != nil { 4020 t.Fatalf("alice unable to rev bob's commitment: %v", err) 4021 } 4022 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 4023 if err != nil { 4024 t.Fatalf("alice unable to revoke commitment: %v", err) 4025 } 4026 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 4027 if err != nil { 4028 t.Fatalf("bob unable to recv revocation: %v", err) 4029 } 4030 } 4031 4032 // TestChanSyncOweRevocationAndCommitForceTransition tests that if Alice 4033 // initiates a state transition with Bob, but Alice fails to receive his 4034 // RevokeAndAck and the connection dies before Bob sends his CommitSig message, 4035 // then Bob will re-send her RevokeAndAck message. Bob will also send and 4036 // _identical_ CommitSig as he detects his commitment chain is ahead of 4037 // Alice's. 4038 func TestChanSyncOweRevocationAndCommitForceTransition(t *testing.T) { 4039 t.Parallel() 4040 4041 // Create a test channel which will be used for the duration of this 4042 // unittest. The channel will be funded evenly with Alice having 5 DCR, 4043 // and Bob having 5 DCR. 4044 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 4045 channeldb.SingleFunderTweaklessBit, 4046 ) 4047 if err != nil { 4048 t.Fatalf("unable to create test channels: %v", err) 4049 } 4050 defer cleanUp() 4051 4052 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 4053 4054 // We'll kick off the test by having Bob send Alice an HTLC, then lock 4055 // it in with a state transition. 4056 var bobPreimage [32]byte 4057 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 4058 rHash := sha256.Sum256(bobPreimage[:]) 4059 var bobHtlc [2]*lnwire.UpdateAddHTLC 4060 bobHtlc[0] = &lnwire.UpdateAddHTLC{ 4061 PaymentHash: rHash, 4062 Amount: htlcAmt, 4063 Expiry: uint32(10), 4064 } 4065 bobHtlcIndex, err := bobChannel.AddHTLC(bobHtlc[0], nil) 4066 if err != nil { 4067 t.Fatalf("unable to add bob's htlc: %v", err) 4068 } 4069 aliceHtlcIndex, err := aliceChannel.ReceiveHTLC(bobHtlc[0]) 4070 if err != nil { 4071 t.Fatalf("unable to recv bob's htlc: %v", err) 4072 } 4073 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 4074 t.Fatalf("unable to complete bob's state transition: %v", err) 4075 } 4076 4077 // To ensure the channel sync logic handles the case where the two 4078 // commit chains are at different heights, we'll add another HTLC from 4079 // Bob to Alice, but let Alice skip the commitment for this state 4080 // update. 4081 rHash = sha256.Sum256(bytes.Repeat([]byte{0xbb}, 32)) 4082 bobHtlc[1] = &lnwire.UpdateAddHTLC{ 4083 PaymentHash: rHash, 4084 Amount: htlcAmt, 4085 Expiry: uint32(10), 4086 ID: 1, 4087 } 4088 _, err = bobChannel.AddHTLC(bobHtlc[1], nil) 4089 if err != nil { 4090 t.Fatalf("unable to add bob's htlc: %v", err) 4091 } 4092 _, err = aliceChannel.ReceiveHTLC(bobHtlc[1]) 4093 if err != nil { 4094 t.Fatalf("unable to recv bob's htlc: %v", err) 4095 } 4096 4097 // Bob signs the new state update, and sends the signature to Alice. 4098 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 4099 if err != nil { 4100 t.Fatalf("bob unable to sign commitment: %v", err) 4101 } 4102 4103 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 4104 if err != nil { 4105 t.Fatalf("alice unable to rev bob's commitment: %v", err) 4106 } 4107 4108 // Alice revokes her current state, but doesn't immediately send a 4109 // signature for Bob's updated state. Instead she will issue a new 4110 // update before sending a new CommitSig. This will lead to Alice's 4111 // local commit chain getting height > remote commit chain. 4112 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 4113 if err != nil { 4114 t.Fatalf("alice unable to revoke commitment: %v", err) 4115 } 4116 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 4117 if err != nil { 4118 t.Fatalf("bob unable to recv revocation: %v", err) 4119 } 4120 4121 // Next, Alice will settle that incoming HTLC, then we'll start the 4122 // core of the test itself. 4123 err = aliceChannel.SettleHTLC(bobPreimage, aliceHtlcIndex, nil, nil, nil) 4124 if err != nil { 4125 t.Fatalf("unable to settle htlc: %v", err) 4126 } 4127 err = bobChannel.ReceiveHTLCSettle(bobPreimage, bobHtlcIndex) 4128 if err != nil { 4129 t.Fatalf("unable to settle htlc: %v", err) 4130 } 4131 4132 // Progressing the exchange: Alice will send her signature, with Bob 4133 // processing the new state locally. 4134 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 4135 if err != nil { 4136 t.Fatalf("unable to sign commitment: %v", err) 4137 } 4138 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 4139 if err != nil { 4140 t.Fatalf("bob unable to process alice's commitment: %v", err) 4141 } 4142 4143 // Bob then sends his revocation message, but before Alice can process 4144 // it (and before he scan send his CommitSig message), then connection 4145 // dies. 4146 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 4147 if err != nil { 4148 t.Fatalf("unable to revoke bob commitment: %v", err) 4149 } 4150 4151 // Now if we attempt to synchronize states at this point, Alice should 4152 // detect that she owes nothing, while Bob should re-send both his 4153 // RevokeAndAck as well as his commitment message. 4154 aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 4155 if err != nil { 4156 t.Fatalf("unable to produce chan sync msg: %v", err) 4157 } 4158 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 4159 if err != nil { 4160 t.Fatalf("unable to produce chan sync msg: %v", err) 4161 } 4162 4163 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 4164 if err != nil { 4165 t.Fatalf("unable to process chan sync msg: %v", err) 4166 } 4167 if len(aliceMsgsToSend) != 0 { 4168 t.Fatalf("expected alice to not retransmit, instead she's "+ 4169 "sending: %v", spew.Sdump(aliceMsgsToSend)) 4170 } 4171 4172 // If we process Alice's sync message from Bob's PoV, then he should 4173 // send his RevokeAndAck message again. Additionally, the CommitSig 4174 // message that he sends should be sufficient to finalize the state 4175 // transition. 4176 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 4177 if err != nil { 4178 t.Fatalf("unable to process chan sync msg: %v", err) 4179 } 4180 if len(bobMsgsToSend) != 2 { 4181 t.Fatalf("expected bob to send %v messages, instead "+ 4182 "sends: %v", 2, spew.Sdump(bobMsgsToSend)) 4183 } 4184 bobReRevoke, ok := bobMsgsToSend[0].(*lnwire.RevokeAndAck) 4185 if !ok { 4186 t.Fatalf("expected bob to re-send revoke, instead sending: %v", 4187 spew.Sdump(bobMsgsToSend[0])) 4188 } 4189 if !reflect.DeepEqual(bobReRevoke, bobRevocation) { 4190 t.Fatalf("revocation msgs don't match: expected %v, got %v", 4191 bobRevocation, bobReRevoke) 4192 } 4193 4194 // The second message should be his CommitSig message that he never 4195 // sent, but will send in order to force both states to synchronize. 4196 bobReCommitSigMsg, ok := bobMsgsToSend[1].(*lnwire.CommitSig) 4197 if !ok { 4198 t.Fatalf("expected bob to re-send commit sig, instead sending: %v", 4199 spew.Sdump(bobMsgsToSend[1])) 4200 } 4201 4202 // At this point we simulate the connection failing with a restart from 4203 // Bob. He should still re-send the exact same set of messages. 4204 bobChannel, err = restartChannel(bobChannel) 4205 if err != nil { 4206 t.Fatalf("unable to restart channel: %v", err) 4207 } 4208 if len(bobMsgsToSend) != 2 { 4209 t.Fatalf("expected bob to send %v messages, instead "+ 4210 "sends: %v", 2, spew.Sdump(bobMsgsToSend)) 4211 } 4212 bobReRevoke, ok = bobMsgsToSend[0].(*lnwire.RevokeAndAck) 4213 if !ok { 4214 t.Fatalf("expected bob to re-send revoke, instead sending: %v", 4215 spew.Sdump(bobMsgsToSend[0])) 4216 } 4217 bobSigMsg, ok := bobMsgsToSend[1].(*lnwire.CommitSig) 4218 if !ok { 4219 t.Fatalf("expected bob to re-send commit sig, instead sending: %v", 4220 spew.Sdump(bobMsgsToSend[1])) 4221 } 4222 if !reflect.DeepEqual(bobReRevoke, bobRevocation) { 4223 t.Fatalf("revocation msgs don't match: expected %v, got %v", 4224 bobRevocation, bobReRevoke) 4225 } 4226 if bobReCommitSigMsg.CommitSig != bobSigMsg.CommitSig { 4227 t.Fatalf("commit sig msgs don't match: expected %x got %x", 4228 bobSigMsg.CommitSig, 4229 bobReCommitSigMsg.CommitSig) 4230 } 4231 if len(bobReCommitSigMsg.HtlcSigs) != len(bobSigMsg.HtlcSigs) { 4232 t.Fatalf("wrong number of htlc sigs: expected %v, got %v", 4233 len(bobSigMsg.HtlcSigs), len(bobReCommitSigMsg.HtlcSigs)) 4234 } 4235 for i, htlcSig := range bobReCommitSigMsg.HtlcSigs { 4236 if htlcSig != bobSigMsg.HtlcSigs[i] { 4237 t.Fatalf("htlc sig msgs don't match: "+ 4238 "expected %x got %x", 4239 bobSigMsg.HtlcSigs[i], htlcSig) 4240 } 4241 } 4242 4243 // Now, we'll continue the exchange, sending Bob's revocation and 4244 // signature message to Alice, ending with Alice sending her revocation 4245 // message to Bob. 4246 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 4247 if err != nil { 4248 t.Fatalf("alice unable to recv revocation: %v", err) 4249 } 4250 err = aliceChannel.ReceiveNewCommitment( 4251 bobSigMsg.CommitSig, bobSigMsg.HtlcSigs, 4252 ) 4253 if err != nil { 4254 t.Fatalf("alice unable to rev bob's commitment: %v", err) 4255 } 4256 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 4257 if err != nil { 4258 t.Fatalf("alice unable to revoke commitment: %v", err) 4259 } 4260 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 4261 if err != nil { 4262 t.Fatalf("bob unable to recv revocation: %v", err) 4263 } 4264 } 4265 4266 // TestChanSyncFailure tests the various scenarios during channel sync where we 4267 // should be able to detect that the channels cannot be synced because of 4268 // invalid state. 4269 func TestChanSyncFailure(t *testing.T) { 4270 t.Parallel() 4271 4272 // Create a test channel which will be used for the duration of this 4273 // unittest. The channel will be funded evenly with Alice having 5 DCR, 4274 // and Bob having 5 DCR. 4275 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 4276 channeldb.SingleFunderBit, 4277 ) 4278 if err != nil { 4279 t.Fatalf("unable to create test channels: %v", err) 4280 } 4281 defer cleanUp() 4282 4283 htlcAmt := lnwire.NewMAtomsFromAtoms(20000) 4284 index := byte(0) 4285 4286 // advanceState is a helper method to fully advance the channel state 4287 // by one. 4288 advanceState := func() { 4289 t.Helper() 4290 4291 // We'll kick off the test by having Bob send Alice an HTLC, 4292 // then lock it in with a state transition. 4293 var bobPreimage [32]byte 4294 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa - index}, 32)) 4295 rHash := sha256.Sum256(bobPreimage[:]) 4296 bobHtlc := &lnwire.UpdateAddHTLC{ 4297 PaymentHash: rHash, 4298 Amount: htlcAmt, 4299 Expiry: uint32(10), 4300 ID: uint64(index), 4301 } 4302 index++ 4303 4304 _, err := bobChannel.AddHTLC(bobHtlc, nil) 4305 if err != nil { 4306 t.Fatalf("unable to add bob's htlc: %v", err) 4307 } 4308 _, err = aliceChannel.ReceiveHTLC(bobHtlc) 4309 if err != nil { 4310 t.Fatalf("unable to recv bob's htlc: %v", err) 4311 } 4312 err = ForceStateTransition(bobChannel, aliceChannel) 4313 if err != nil { 4314 t.Fatalf("unable to complete bob's state "+ 4315 "transition: %v", err) 4316 } 4317 } 4318 4319 // halfAdvance is a helper method that sends a new commitment signature 4320 // from Alice to Bob, but doesn't make Bob revoke his current state. 4321 halfAdvance := func() { 4322 t.Helper() 4323 4324 // We'll kick off the test by having Bob send Alice an HTLC, 4325 // then lock it in with a state transition. 4326 var bobPreimage [32]byte 4327 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa - index}, 32)) 4328 rHash := sha256.Sum256(bobPreimage[:]) 4329 bobHtlc := &lnwire.UpdateAddHTLC{ 4330 PaymentHash: rHash, 4331 Amount: htlcAmt, 4332 Expiry: uint32(10), 4333 ID: uint64(index), 4334 } 4335 index++ 4336 4337 _, err := bobChannel.AddHTLC(bobHtlc, nil) 4338 if err != nil { 4339 t.Fatalf("unable to add bob's htlc: %v", err) 4340 } 4341 _, err = aliceChannel.ReceiveHTLC(bobHtlc) 4342 if err != nil { 4343 t.Fatalf("unable to recv bob's htlc: %v", err) 4344 } 4345 4346 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 4347 if err != nil { 4348 t.Fatalf("unable to sign next commit: %v", err) 4349 } 4350 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 4351 if err != nil { 4352 t.Fatalf("unable to receive commit sig: %v", err) 4353 } 4354 } 4355 4356 // assertLocalDataLoss checks that aliceOld and bobChannel detects that 4357 // Alice has lost state during sync. 4358 assertLocalDataLoss := func(aliceOld *LightningChannel) { 4359 t.Helper() 4360 4361 aliceSyncMsg, err := aliceOld.channelState.ChanSyncMsg() 4362 if err != nil { 4363 t.Fatalf("unable to produce chan sync msg: %v", err) 4364 } 4365 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 4366 if err != nil { 4367 t.Fatalf("unable to produce chan sync msg: %v", err) 4368 } 4369 4370 // Alice should detect from Bob's message that she lost state. 4371 _, _, _, err = aliceOld.ProcessChanSyncMsg(bobSyncMsg) 4372 if _, ok := err.(*ErrCommitSyncLocalDataLoss); !ok { 4373 t.Fatalf("wrong error, expected "+ 4374 "ErrCommitSyncLocalDataLoss instead got: %v", 4375 err) 4376 } 4377 4378 // Bob should detect that Alice probably lost state. 4379 _, _, _, err = bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 4380 if err != ErrCommitSyncRemoteDataLoss { 4381 t.Fatalf("wrong error, expected "+ 4382 "ErrCommitSyncRemoteDataLoss instead got: %v", 4383 err) 4384 } 4385 } 4386 4387 // clearBorkedState is a method that allows us to clear the borked 4388 // state that will arise after the first chan message sync. We need to 4389 // do this in order to be able to continue to update the commitment 4390 // state for our test scenarios. 4391 clearBorkedState := func() { 4392 err = aliceChannel.channelState.ClearChanStatus( 4393 channeldb.ChanStatusLocalDataLoss | channeldb.ChanStatusBorked, 4394 ) 4395 if err != nil { 4396 t.Fatalf("unable to update channel state: %v", err) 4397 } 4398 err = bobChannel.channelState.ClearChanStatus( 4399 channeldb.ChanStatusLocalDataLoss | channeldb.ChanStatusBorked, 4400 ) 4401 if err != nil { 4402 t.Fatalf("unable to update channel state: %v", err) 4403 } 4404 } 4405 4406 // Start by advancing the state. 4407 advanceState() 4408 4409 // They should be in sync. 4410 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 4411 4412 // Make a copy of Alice's state from the database at this point. 4413 aliceOld, err := restartChannel(aliceChannel) 4414 if err != nil { 4415 t.Fatalf("unable to restart channel: %v", err) 4416 } 4417 4418 // Advance the states. 4419 advanceState() 4420 4421 // Trying to sync up the old version of Alice's channel should detect 4422 // that we are out of sync. 4423 assertLocalDataLoss(aliceOld) 4424 4425 // Make sure the up-to-date channels still are in sync. 4426 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 4427 4428 // Clear the borked state before we attempt to advance. 4429 clearBorkedState() 4430 4431 // Advance the state again, and do the same check. 4432 advanceState() 4433 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 4434 assertLocalDataLoss(aliceOld) 4435 4436 // If we remove the recovery options from Bob's message, Alice cannot 4437 // tell if she lost state, since Bob might be lying. She still should 4438 // be able to detect that chains cannot be synced. 4439 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 4440 if err != nil { 4441 t.Fatalf("unable to produce chan sync msg: %v", err) 4442 } 4443 bobSyncMsg.LocalUnrevokedCommitPoint = nil 4444 _, _, _, err = aliceOld.ProcessChanSyncMsg(bobSyncMsg) 4445 if err != ErrCannotSyncCommitChains { 4446 t.Fatalf("wrong error, expected ErrCannotSyncCommitChains "+ 4447 "instead got: %v", err) 4448 } 4449 4450 // If Bob lies about the NextLocalCommitHeight, making it greater than 4451 // what Alice expect, she cannot tell for sure whether she lost state, 4452 // but should detect the desync. 4453 bobSyncMsg, err = bobChannel.channelState.ChanSyncMsg() 4454 if err != nil { 4455 t.Fatalf("unable to produce chan sync msg: %v", err) 4456 } 4457 bobSyncMsg.NextLocalCommitHeight++ 4458 _, _, _, err = aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 4459 if err != ErrCannotSyncCommitChains { 4460 t.Fatalf("wrong error, expected ErrCannotSyncCommitChains "+ 4461 "instead got: %v", err) 4462 } 4463 4464 // If Bob's NextLocalCommitHeight is lower than what Alice expects, Bob 4465 // probably lost state. 4466 bobSyncMsg, err = bobChannel.channelState.ChanSyncMsg() 4467 if err != nil { 4468 t.Fatalf("unable to produce chan sync msg: %v", err) 4469 } 4470 bobSyncMsg.NextLocalCommitHeight-- 4471 _, _, _, err = aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 4472 if err != ErrCommitSyncRemoteDataLoss { 4473 t.Fatalf("wrong error, expected ErrCommitSyncRemoteDataLoss "+ 4474 "instead got: %v", err) 4475 } 4476 4477 // If Alice and Bob's states are in sync, but Bob is sending the wrong 4478 // LocalUnrevokedCommitPoint, Alice should detect this. 4479 bobSyncMsg, err = bobChannel.channelState.ChanSyncMsg() 4480 if err != nil { 4481 t.Fatalf("unable to produce chan sync msg: %v", err) 4482 } 4483 p := bobSyncMsg.LocalUnrevokedCommitPoint.SerializeCompressed() 4484 p[4] ^= 0x01 4485 modCommitPoint, err := secp256k1.ParsePubKey(p) 4486 if err != nil { 4487 t.Fatalf("unable to parse pubkey: %v", err) 4488 } 4489 4490 bobSyncMsg.LocalUnrevokedCommitPoint = modCommitPoint 4491 _, _, _, err = aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 4492 if err != ErrInvalidLocalUnrevokedCommitPoint { 4493 t.Fatalf("wrong error, expected "+ 4494 "ErrInvalidLocalUnrevokedCommitPoint instead got: %v", 4495 err) 4496 } 4497 4498 // Make sure the up-to-date channels still are good. 4499 assertNoChanSyncNeeded(t, aliceChannel, bobChannel) 4500 4501 // Clear the borked state before we attempt to advance. 4502 clearBorkedState() 4503 4504 // Finally check that Alice is also able to detect a wrong commit point 4505 // when there's a pending remote commit. 4506 halfAdvance() 4507 4508 bobSyncMsg, err = bobChannel.channelState.ChanSyncMsg() 4509 if err != nil { 4510 t.Fatalf("unable to produce chan sync msg: %v", err) 4511 } 4512 bobSyncMsg.LocalUnrevokedCommitPoint = modCommitPoint 4513 _, _, _, err = aliceChannel.ProcessChanSyncMsg(bobSyncMsg) 4514 if err != ErrInvalidLocalUnrevokedCommitPoint { 4515 t.Fatalf("wrong error, expected "+ 4516 "ErrInvalidLocalUnrevokedCommitPoint instead got: %v", 4517 err) 4518 } 4519 } 4520 4521 // TestFeeUpdateRejectInsaneFee tests that if the initiator tries to attach a 4522 // fee that would put them below their current reserve, then it's rejected by 4523 // the state machine. 4524 func TestFeeUpdateRejectInsaneFee(t *testing.T) { 4525 t.Parallel() 4526 4527 // Create a test channel which will be used for the duration of this 4528 // unittest. The channel will be funded evenly with Alice having 5 DCR, 4529 // and Bob having 5 DCR. 4530 aliceChannel, _, cleanUp, err := CreateTestChannels( 4531 channeldb.SingleFunderTweaklessBit, 4532 ) 4533 if err != nil { 4534 t.Fatalf("unable to create test channels: %v", err) 4535 } 4536 defer cleanUp() 4537 4538 // Next, we'll try to add a fee rate to Alice which is 1,000,000x her 4539 // starting fee rate. 4540 startingFeeRate := chainfee.AtomPerKByte( 4541 aliceChannel.channelState.LocalCommitment.FeePerKB, 4542 ) 4543 newFeeRate := startingFeeRate * 1000000 4544 4545 // Both Alice and Bob should reject this new fee rate as it is far too 4546 // large. 4547 if err := aliceChannel.UpdateFee(newFeeRate); err == nil { 4548 t.Fatalf("alice should have rejected fee update") 4549 } 4550 } 4551 4552 // TestChannelRetransmissionFeeUpdate tests that the initiator will include any 4553 // pending fee updates if it needs to retransmit signatures. 4554 func TestChannelRetransmissionFeeUpdate(t *testing.T) { 4555 t.Parallel() 4556 4557 // Create a test channel which will be used for the duration of this 4558 // unittest. The channel will be funded evenly with Alice having 5 DCR, 4559 // and Bob having 5 DCR. 4560 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 4561 channeldb.SingleFunderTweaklessBit, 4562 ) 4563 if err != nil { 4564 t.Fatalf("unable to create test channels: %v", err) 4565 } 4566 defer cleanUp() 4567 4568 // First, we'll fetch the current fee rate present within the 4569 // commitment transactions. 4570 startingFeeRate := chainfee.AtomPerKByte( 4571 aliceChannel.channelState.LocalCommitment.FeePerKB, 4572 ) 4573 4574 // Next, we'll start a commitment update, with Alice sending a new 4575 // update to double the fee rate of the commitment. 4576 newFeeRate := startingFeeRate * 2 4577 if err := aliceChannel.UpdateFee(newFeeRate); err != nil { 4578 t.Fatalf("unable to update fee for Alice's channel: %v", err) 4579 } 4580 if err := bobChannel.ReceiveUpdateFee(newFeeRate); err != nil { 4581 t.Fatalf("unable to update fee for Bob's channel: %v", err) 4582 } 4583 4584 // Now, Alice will send a new commitment to Bob, but we'll simulate a 4585 // connection failure, so Bob doesn't get her signature. 4586 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 4587 if err != nil { 4588 t.Fatalf("unable to sign commitment: %v", err) 4589 } 4590 4591 // Restart both channels to simulate a connection restart. 4592 aliceChannel, err = restartChannel(aliceChannel) 4593 if err != nil { 4594 t.Fatalf("unable to restart alice: %v", err) 4595 } 4596 bobChannel, err = restartChannel(bobChannel) 4597 if err != nil { 4598 t.Fatalf("unable to restart channel: %v", err) 4599 } 4600 4601 // Bob doesn't get this message so upon reconnection, they need to 4602 // synchronize. Alice should conclude that she owes Bob a commitment, 4603 // while Bob should think he's properly synchronized. 4604 aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() 4605 if err != nil { 4606 t.Fatalf("unable to produce chan sync msg: %v", err) 4607 } 4608 bobSyncMsg, err := bobChannel.channelState.ChanSyncMsg() 4609 if err != nil { 4610 t.Fatalf("unable to produce chan sync msg: %v", err) 4611 } 4612 4613 // Bob should detect that he doesn't need to send anything to Alice. 4614 bobMsgsToSend, _, _, err := bobChannel.ProcessChanSyncMsg(aliceSyncMsg) 4615 if err != nil { 4616 t.Fatalf("unable to process chan sync msg: %v", err) 4617 } 4618 if len(bobMsgsToSend) != 0 { 4619 t.Fatalf("expected bob to send %v messages instead "+ 4620 "will send %v: %v", 0, len(bobMsgsToSend), 4621 spew.Sdump(bobMsgsToSend)) 4622 } 4623 4624 // When Alice processes Bob's chan sync message, she should realize 4625 // that she needs to first send a new UpdateFee message, and also a 4626 // CommitSig. 4627 aliceMsgsToSend, _, _, err := aliceChannel.ProcessChanSyncMsg( 4628 bobSyncMsg, 4629 ) 4630 if err != nil { 4631 t.Fatalf("unable to process chan sync msg: %v", err) 4632 } 4633 if len(aliceMsgsToSend) != 2 { 4634 t.Fatalf("expected alice to send %v messages instead "+ 4635 "will send %v: %v", 2, len(aliceMsgsToSend), 4636 spew.Sdump(aliceMsgsToSend)) 4637 } 4638 4639 // The first message should be an UpdateFee message. 4640 retransFeeMsg, ok := aliceMsgsToSend[0].(*lnwire.UpdateFee) 4641 if !ok { 4642 t.Fatalf("expected UpdateFee message, instead have: %v", 4643 spew.Sdump(aliceMsgsToSend[0])) 4644 } 4645 4646 // The fee should match exactly the new fee update we applied above. 4647 if retransFeeMsg.FeePerKB != uint32(newFeeRate) { 4648 t.Fatalf("fee update doesn't match: expected %v, got %v", 4649 uint32(newFeeRate), retransFeeMsg) 4650 } 4651 4652 // The second, should be a CommitSig message, and be identical to the 4653 // sig message she sent prior. 4654 commitSigMsg, ok := aliceMsgsToSend[1].(*lnwire.CommitSig) 4655 if !ok { 4656 t.Fatalf("expected a CommitSig message, instead have %v", 4657 spew.Sdump(aliceMsgsToSend[1])) 4658 } 4659 if commitSigMsg.CommitSig != aliceSig { 4660 t.Fatalf("commit sig msgs don't match: expected %x got %x", 4661 aliceSig, commitSigMsg.CommitSig) 4662 } 4663 if len(commitSigMsg.HtlcSigs) != len(aliceHtlcSigs) { 4664 t.Fatalf("wrong number of htlc sigs: expected %v, got %v", 4665 len(aliceHtlcSigs), len(commitSigMsg.HtlcSigs)) 4666 } 4667 for i, htlcSig := range commitSigMsg.HtlcSigs { 4668 if htlcSig != aliceHtlcSigs[i] { 4669 t.Fatalf("htlc sig msgs don't match: "+ 4670 "expected %x got %x", 4671 aliceHtlcSigs[i], htlcSig) 4672 } 4673 } 4674 4675 // Now, we if re-apply the updates to Bob, we should be able to resume 4676 // the commitment update as normal. 4677 if err := bobChannel.ReceiveUpdateFee(newFeeRate); err != nil { 4678 t.Fatalf("unable to update fee for Bob's channel: %v", err) 4679 } 4680 4681 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 4682 if err != nil { 4683 t.Fatalf("bob unable to process alice's commitment: %v", err) 4684 } 4685 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 4686 if err != nil { 4687 t.Fatalf("unable to revoke bob commitment: %v", err) 4688 } 4689 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 4690 if err != nil { 4691 t.Fatalf("bob unable to sign commitment: %v", err) 4692 } 4693 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 4694 if err != nil { 4695 t.Fatalf("alice unable to recv revocation: %v", err) 4696 } 4697 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 4698 if err != nil { 4699 t.Fatalf("alice unable to rev bob's commitment: %v", err) 4700 } 4701 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 4702 if err != nil { 4703 t.Fatalf("alice unable to revoke commitment: %v", err) 4704 } 4705 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 4706 if err != nil { 4707 t.Fatalf("bob unable to recv revocation: %v", err) 4708 } 4709 4710 // Both parties should now have the latest fee rate locked-in. 4711 if chainfee.AtomPerKByte( 4712 aliceChannel.channelState.LocalCommitment.FeePerKB, 4713 ) != newFeeRate { 4714 t.Fatalf("alice's FeePerKB was not locked in") 4715 } 4716 if chainfee.AtomPerKByte( 4717 bobChannel.channelState.LocalCommitment.FeePerKB, 4718 ) != newFeeRate { 4719 t.Fatalf("bob's FeePerKB was not locked in") 4720 } 4721 4722 // Finally, we'll add with adding a new HTLC, then forcing a state 4723 // transition. This should also proceed as normal. 4724 var bobPreimage [32]byte 4725 copy(bobPreimage[:], bytes.Repeat([]byte{0xaa}, 32)) 4726 rHash := sha256.Sum256(bobPreimage[:]) 4727 bobHtlc := &lnwire.UpdateAddHTLC{ 4728 PaymentHash: rHash, 4729 Amount: lnwire.NewMAtomsFromAtoms(20000), 4730 Expiry: uint32(10), 4731 } 4732 if _, err := bobChannel.AddHTLC(bobHtlc, nil); err != nil { 4733 t.Fatalf("unable to add bob's htlc: %v", err) 4734 } 4735 if _, err := aliceChannel.ReceiveHTLC(bobHtlc); err != nil { 4736 t.Fatalf("unable to recv bob's htlc: %v", err) 4737 } 4738 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 4739 t.Fatalf("unable to complete bob's state transition: %v", err) 4740 } 4741 } 4742 4743 // TestFeeUpdateOldDiskFormat tests that we properly recover FeeUpdates written 4744 // to disk using the old format, where the logIndex was not written. 4745 func TestFeeUpdateOldDiskFormat(t *testing.T) { 4746 t.Parallel() 4747 4748 // Create a test channel which will be used for the duration of this 4749 // unittest. The channel will be funded evenly with Alice having 5 BTC, 4750 // and Bob having 5 BTC. 4751 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 4752 channeldb.SingleFunderTweaklessBit, 4753 ) 4754 if err != nil { 4755 t.Fatalf("unable to create test channels: %v", err) 4756 } 4757 defer cleanUp() 4758 4759 // helper that counts the number of updates, and number of fee updates 4760 // in the given log. 4761 countLog := func(log *updateLog) (int, int) { 4762 var numUpdates, numFee int 4763 for e := log.Front(); e != nil; e = e.Next() { 4764 htlc := e.Value.(*PaymentDescriptor) 4765 if htlc.EntryType == FeeUpdate { 4766 numFee++ 4767 } 4768 numUpdates++ 4769 } 4770 return numUpdates, numFee 4771 } 4772 4773 // helper that asserts that Alice's local log and Bob's remote log 4774 // contains the expected number of fee updates and adds. 4775 assertLogItems := func(expFee, expAdd int) { 4776 t.Helper() 4777 4778 expUpd := expFee + expAdd 4779 upd, fees := countLog(aliceChannel.localUpdateLog) 4780 if upd != expUpd { 4781 t.Fatalf("expected %d updates, found %d in Alice's "+ 4782 "log", expUpd, upd) 4783 } 4784 if fees != expFee { 4785 t.Fatalf("expected %d fee updates, found %d in "+ 4786 "Alice's log", expFee, fees) 4787 } 4788 upd, fees = countLog(bobChannel.remoteUpdateLog) 4789 if upd != expUpd { 4790 t.Fatalf("expected %d updates, found %d in Bob's log", 4791 expUpd, upd) 4792 } 4793 if fees != expFee { 4794 t.Fatalf("expected %d fee updates, found %d in Bob's "+ 4795 "log", expFee, fees) 4796 } 4797 } 4798 4799 // First, we'll fetch the current fee rate present within the 4800 // commitment transactions. 4801 startingFeeRate := chainfee.AtomPerKByte( 4802 aliceChannel.channelState.LocalCommitment.FeePerKB, 4803 ) 4804 newFeeRate := startingFeeRate 4805 4806 // We will send a few HTLCs and a fee update. 4807 htlcAmt := lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 4808 const numHTLCs = 30 4809 var htlcs []*lnwire.UpdateAddHTLC 4810 for i := 0; i < numHTLCs; i++ { 4811 htlc, _ := createHTLC(i, htlcAmt) 4812 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 4813 t.Fatalf("unable to add htlc: %v", err) 4814 } 4815 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 4816 t.Fatalf("unable to recv htlc: %v", err) 4817 } 4818 htlcs = append(htlcs, htlc) 4819 4820 if i%5 != 0 { 4821 continue 4822 } 4823 4824 // After every 5th HTLC, we'll also include a fee update. 4825 newFeeRate += startingFeeRate 4826 if err := aliceChannel.UpdateFee(newFeeRate); err != nil { 4827 t.Fatalf("unable to update fee for Alice's channel: %v", 4828 err) 4829 } 4830 if err := bobChannel.ReceiveUpdateFee(newFeeRate); err != nil { 4831 t.Fatalf("unable to update fee for Bob's channel: %v", 4832 err) 4833 } 4834 } 4835 // Check that the expected number of items is found in the logs. 4836 expFee := numHTLCs / 5 4837 assertLogItems(expFee, numHTLCs) 4838 4839 // Now, Alice will send a new commitment to Bob, but we'll simulate a 4840 // connection failure, so Bob doesn't get the signature. 4841 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 4842 if err != nil { 4843 t.Fatalf("unable to sign commitment: %v", err) 4844 } 4845 4846 // Before restarting Alice, to mimic the old format, we fetch the 4847 // pending remote commit from disk, set the UpdateFee message's 4848 // logIndex to 0, and re-write it. 4849 pendingRemoteCommitDiff, err := aliceChannel.channelState.RemoteCommitChainTip() 4850 if err != nil { 4851 t.Fatal(err) 4852 } 4853 for i, u := range pendingRemoteCommitDiff.LogUpdates { 4854 switch u.UpdateMsg.(type) { 4855 case *lnwire.UpdateFee: 4856 pendingRemoteCommitDiff.LogUpdates[i].LogIndex = 0 4857 } 4858 } 4859 err = aliceChannel.channelState.AppendRemoteCommitChain( 4860 pendingRemoteCommitDiff, 4861 ) 4862 if err != nil { 4863 t.Fatal(err) 4864 } 4865 4866 // Restart both channels to simulate a connection restart. This will 4867 // trigger a update logs restoration. 4868 aliceChannel, err = restartChannel(aliceChannel) 4869 if err != nil { 4870 t.Fatalf("unable to restart alice: %v", err) 4871 } 4872 bobChannel, err = restartChannel(bobChannel) 4873 if err != nil { 4874 t.Fatalf("unable to restart channel: %v", err) 4875 } 4876 4877 // After a reconnection, Alice will resend the pending updates, that 4878 // was not ACKed by Bob, so we re-send the HTLCs and fee updates. 4879 newFeeRate = startingFeeRate 4880 for i := 0; i < numHTLCs; i++ { 4881 htlc := htlcs[i] 4882 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 4883 t.Fatalf("unable to recv htlc: %v", err) 4884 } 4885 4886 if i%5 != 0 { 4887 continue 4888 } 4889 4890 newFeeRate += startingFeeRate 4891 if err := bobChannel.ReceiveUpdateFee(newFeeRate); err != nil { 4892 t.Fatalf("unable to update fee for Bob's channel: %v", 4893 err) 4894 } 4895 } 4896 assertLogItems(expFee, numHTLCs) 4897 4898 // We send Alice's commitment signatures, and finish the state 4899 // transition. 4900 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 4901 if err != nil { 4902 t.Fatalf("bob unable to process alice's commitment: %v", err) 4903 } 4904 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 4905 if err != nil { 4906 t.Fatalf("unable to revoke bob commitment: %v", err) 4907 } 4908 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 4909 if err != nil { 4910 t.Fatalf("bob unable to sign commitment: %v", err) 4911 } 4912 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 4913 if err != nil { 4914 t.Fatalf("alice unable to recv revocation: %v", err) 4915 } 4916 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 4917 if err != nil { 4918 t.Fatalf("alice unable to rev bob's commitment: %v", err) 4919 } 4920 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 4921 if err != nil { 4922 t.Fatalf("alice unable to revoke commitment: %v", err) 4923 } 4924 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 4925 if err != nil { 4926 t.Fatalf("bob unable to recv revocation: %v", err) 4927 } 4928 4929 // Both parties should now have the latest fee rate locked-in. 4930 if chainfee.AtomPerKByte( 4931 aliceChannel.channelState.LocalCommitment.FeePerKB, 4932 ) != newFeeRate { 4933 t.Fatalf("alice's feePerKB was not locked in") 4934 } 4935 if chainfee.AtomPerKByte( 4936 bobChannel.channelState.LocalCommitment.FeePerKB, 4937 ) != newFeeRate { 4938 t.Fatalf("bob's feePerKB was not locked in") 4939 } 4940 4941 // Finally, to trigger a compactLogs execution, we'll add a new HTLC, 4942 // then force a state transition. 4943 htlc, _ := createHTLC(numHTLCs, htlcAmt) 4944 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 4945 t.Fatalf("unable to add htlc: %v", err) 4946 } 4947 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 4948 t.Fatalf("unable to recv htlc: %v", err) 4949 } 4950 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 4951 t.Fatalf("unable to complete bob's state transition: %v", err) 4952 } 4953 4954 // Finally, check the logs to make sure all fee updates have been 4955 // removed... 4956 assertLogItems(0, numHTLCs+1) 4957 4958 // ...and the final fee rate locked in. 4959 if chainfee.AtomPerKByte( 4960 aliceChannel.channelState.LocalCommitment.FeePerKB, 4961 ) != newFeeRate { 4962 t.Fatalf("alice's feePerKB was not locked in") 4963 } 4964 if chainfee.AtomPerKByte( 4965 bobChannel.channelState.LocalCommitment.FeePerKB, 4966 ) != newFeeRate { 4967 t.Fatalf("bob's feePerKB was not locked in") 4968 } 4969 } 4970 4971 // TestChanSyncUnableToSync tests that if Alice or Bob receive an invalid 4972 // ChannelReestablish messages,then they reject the message and declare the 4973 // channel un-continuable by returning ErrCannotSyncCommitChains. 4974 func TestChanSyncUnableToSync(t *testing.T) { 4975 t.Parallel() 4976 4977 // Create a test channel which will be used for the duration of this 4978 // unittest. The channel will be funded evenly with Alice having 5 DCR, 4979 // and Bob having 5 DCR. 4980 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 4981 channeldb.SingleFunderBit, 4982 ) 4983 if err != nil { 4984 t.Fatalf("unable to create test channels: %v", err) 4985 } 4986 defer cleanUp() 4987 4988 // If we immediately send both sides a "bogus" ChanSync message, then 4989 // they both should conclude that they're unable to synchronize the 4990 // state. 4991 badChanSync := &lnwire.ChannelReestablish{ 4992 ChanID: lnwire.NewChanIDFromOutPoint( 4993 &aliceChannel.channelState.FundingOutpoint, 4994 ), 4995 NextLocalCommitHeight: 1000, 4996 RemoteCommitTailHeight: 9000, 4997 } 4998 _, _, _, err = bobChannel.ProcessChanSyncMsg(badChanSync) 4999 if err != ErrCannotSyncCommitChains { 5000 t.Fatalf("expected error instead have: %v", err) 5001 } 5002 _, _, _, err = aliceChannel.ProcessChanSyncMsg(badChanSync) 5003 if err != ErrCannotSyncCommitChains { 5004 t.Fatalf("expected error instead have: %v", err) 5005 } 5006 } 5007 5008 // TestChanSyncInvalidLastSecret ensures that if Alice and Bob have completed 5009 // state transitions in an existing channel, and then send a ChannelReestablish 5010 // message after a restart, the following holds: if Alice has lost data, so she 5011 // sends an invalid commit secret then both parties recognize this as possible 5012 // data loss. 5013 func TestChanSyncInvalidLastSecret(t *testing.T) { 5014 t.Parallel() 5015 5016 // Create a test channel which will be used for the duration of this 5017 // unittest. The channel will be funded evenly with Alice having 5 DCR, 5018 // and Bob having 5 DCR. 5019 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5020 channeldb.SingleFunderBit, 5021 ) 5022 if err != nil { 5023 t.Fatalf("unable to create test channels: %v", err) 5024 } 5025 defer cleanUp() 5026 5027 // We'll create a new instances of Alice before doing any state updates 5028 // such that we have the initial in memory state at the start of the 5029 // channel. 5030 aliceOld, err := restartChannel(aliceChannel) 5031 if err != nil { 5032 t.Fatalf("unable to restart alice") 5033 } 5034 5035 // First, we'll add an HTLC, and then initiate a state transition 5036 // between the two parties such that we actually have a prior 5037 // revocation to send. 5038 var paymentPreimage [32]byte 5039 copy(paymentPreimage[:], bytes.Repeat([]byte{1}, 32)) 5040 paymentHash := sha256.Sum256(paymentPreimage[:]) 5041 htlcAmt := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin) 5042 htlc := &lnwire.UpdateAddHTLC{ 5043 PaymentHash: paymentHash, 5044 Amount: htlcAmt, 5045 Expiry: uint32(5), 5046 } 5047 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5048 t.Fatalf("unable to add htlc: %v", err) 5049 } 5050 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5051 t.Fatalf("unable to recv htlc: %v", err) 5052 } 5053 5054 // Then we'll initiate a state transition to lock in this new HTLC. 5055 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5056 t.Fatalf("unable to complete alice's state transition: %v", err) 5057 } 5058 5059 // Next, we'll restart both parties in order to simulate a connection 5060 // re-establishment. 5061 aliceChannel, err = restartChannel(aliceChannel) 5062 if err != nil { 5063 t.Fatalf("unable to restart alice: %v", err) 5064 } 5065 bobChannel, err = restartChannel(bobChannel) 5066 if err != nil { 5067 t.Fatalf("unable to restart bob: %v", err) 5068 } 5069 5070 // Next, we'll produce the ChanSync messages for both parties. 5071 aliceChanSync, err := aliceChannel.channelState.ChanSyncMsg() 5072 if err != nil { 5073 t.Fatalf("unable to generate chan sync msg: %v", err) 5074 } 5075 bobChanSync, err := bobChannel.channelState.ChanSyncMsg() 5076 if err != nil { 5077 t.Fatalf("unable to generate chan sync msg: %v", err) 5078 } 5079 5080 // We'll modify Alice's sync message to have an invalid commitment 5081 // secret. 5082 aliceChanSync.LastRemoteCommitSecret[4] ^= 0x01 5083 5084 // Alice's former self should conclude that she possibly lost data as 5085 // Bob is sending a valid commit secret for the latest state. 5086 _, _, _, err = aliceOld.ProcessChanSyncMsg(bobChanSync) 5087 if _, ok := err.(*ErrCommitSyncLocalDataLoss); !ok { 5088 t.Fatalf("wrong error, expected ErrCommitSyncLocalDataLoss "+ 5089 "instead got: %v", err) 5090 } 5091 5092 // Bob should conclude that he should force close the channel, as Alice 5093 // cannot continue operation. 5094 _, _, _, err = bobChannel.ProcessChanSyncMsg(aliceChanSync) 5095 if err != ErrInvalidLastCommitSecret { 5096 t.Fatalf("wrong error, expected ErrInvalidLastCommitSecret, "+ 5097 "instead got: %v", err) 5098 } 5099 } 5100 5101 // TestChanAvailableBandwidth tests the accuracy of the AvailableBalance() 5102 // method. The value returned from this message should reflect the value 5103 // returned within the commitment state of a channel after the transition is 5104 // initiated. 5105 func TestChanAvailableBandwidth(t *testing.T) { 5106 t.Parallel() 5107 5108 // Create a test channel which will be used for the duration of this 5109 // unittest. The channel will be funded evenly with Alice having 5 DCR, 5110 // and Bob having 5 DCR. 5111 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5112 channeldb.SingleFunderTweaklessBit, 5113 ) 5114 if err != nil { 5115 t.Fatalf("unable to create test channels: %v", err) 5116 } 5117 defer cleanUp() 5118 5119 aliceReserve := lnwire.NewMAtomsFromAtoms( 5120 aliceChannel.channelState.LocalChanCfg.ChanReserve, 5121 ) 5122 feeRate := chainfee.AtomPerKByte( 5123 aliceChannel.channelState.LocalCommitment.FeePerKB, 5124 ) 5125 htlcFee := lnwire.NewMAtomsFromAtoms( 5126 feeRate.FeeForSize(input.HTLCOutputSize), 5127 ) 5128 5129 assertBandwidthEstimateCorrect := func(aliceInitiate bool) { 5130 // With the HTLC's added, we'll now query the AvailableBalance 5131 // method for the current available channel bandwidth from 5132 // Alice's PoV. 5133 aliceAvailableBalance := aliceChannel.AvailableBalance() 5134 5135 // With this balance obtained, we'll now trigger a state update 5136 // to actually determine what the current up to date balance 5137 // is. 5138 if aliceInitiate { 5139 err := ForceStateTransition(aliceChannel, bobChannel) 5140 if err != nil { 5141 t.Fatalf("unable to complete alice's state "+ 5142 "transition: %v", err) 5143 } 5144 } else { 5145 err := ForceStateTransition(bobChannel, aliceChannel) 5146 if err != nil { 5147 t.Fatalf("unable to complete alice's state "+ 5148 "transition: %v", err) 5149 } 5150 } 5151 5152 // Now, we'll obtain the current available bandwidth in Alice's 5153 // latest commitment and compare that to the prior estimate. 5154 aliceBalance := aliceChannel.channelState.LocalCommitment.LocalBalance 5155 5156 // The balance we have available for new HTLCs should be the 5157 // current local commitment balance, minus the channel reserve 5158 // and the fee for adding an HTLC. 5159 expBalance := aliceBalance - aliceReserve - htlcFee 5160 if expBalance != aliceAvailableBalance { 5161 _, _, line, _ := runtime.Caller(1) 5162 t.Fatalf("line: %v, incorrect balance: expected %v, "+ 5163 "got %v", line, expBalance, aliceAvailableBalance) 5164 } 5165 } 5166 5167 // First, we'll add 3 outgoing HTLC's from Alice to Bob. 5168 const numHtlcs = 3 5169 var htlcAmt lnwire.MilliAtom = 100000 5170 alicePreimages := make([][32]byte, numHtlcs) 5171 for i := 0; i < numHtlcs; i++ { 5172 htlc, preImage := createHTLC(i, htlcAmt) 5173 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5174 t.Fatalf("unable to add htlc: %v", err) 5175 } 5176 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5177 t.Fatalf("unable to recv htlc: %v", err) 5178 } 5179 5180 alicePreimages[i] = preImage 5181 } 5182 5183 assertBandwidthEstimateCorrect(true) 5184 5185 // We'll repeat the same exercise, but with non-dust HTLCs. So we'll 5186 // crank up the value of the HTLC's we're adding to the commitment 5187 // transaction. 5188 htlcAmt = lnwire.NewMAtomsFromAtoms(30000) 5189 for i := 0; i < numHtlcs; i++ { 5190 htlc, preImage := createHTLC(numHtlcs+i, htlcAmt) 5191 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5192 t.Fatalf("unable to add htlc: %v", err) 5193 } 5194 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5195 t.Fatalf("unable to recv htlc: %v", err) 5196 } 5197 5198 alicePreimages = append(alicePreimages, preImage) 5199 } 5200 5201 assertBandwidthEstimateCorrect(true) 5202 5203 // Next, we'll have Bob 5 of Alice's HTLC's, and cancel one of them (in 5204 // the update log). 5205 for i := 0; i < (numHtlcs*2)-1; i++ { 5206 preImage := alicePreimages[i] 5207 err := bobChannel.SettleHTLC(preImage, uint64(i), nil, nil, nil) 5208 if err != nil { 5209 t.Fatalf("unable to settle htlc: %v", err) 5210 } 5211 err = aliceChannel.ReceiveHTLCSettle(preImage, uint64(i)) 5212 if err != nil { 5213 t.Fatalf("unable to settle htlc: %v", err) 5214 } 5215 } 5216 5217 htlcIndex := uint64((numHtlcs * 2) - 1) 5218 err = bobChannel.FailHTLC(htlcIndex, []byte("f"), nil, nil, nil) 5219 if err != nil { 5220 t.Fatalf("unable to cancel HTLC: %v", err) 5221 } 5222 err = aliceChannel.ReceiveFailHTLC(htlcIndex, []byte("bad")) 5223 if err != nil { 5224 t.Fatalf("unable to recv htlc cancel: %v", err) 5225 } 5226 5227 // We must do a state transition before the balance is available 5228 // for Alice. 5229 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5230 t.Fatalf("unable to complete alice's state "+ 5231 "transition: %v", err) 5232 } 5233 5234 // With the HTLC's settled in the log, we'll now assert that if we 5235 // initiate a state transition, then our guess was correct. 5236 assertBandwidthEstimateCorrect(false) 5237 5238 // TODO(roasbeef): additional tests from diff starting conditions 5239 } 5240 5241 // TestChanAvailableBalanceNearHtlcFee checks that we get the expected reported 5242 // balance when it is close to the htlc fee. 5243 func TestChanAvailableBalanceNearHtlcFee(t *testing.T) { 5244 t.Parallel() 5245 5246 // Create a test channel which will be used for the duration of this 5247 // unittest. The channel will be funded evenly with Alice having 5 BTC, 5248 // and Bob having 5 BTC. 5249 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5250 channeldb.SingleFunderTweaklessBit, 5251 ) 5252 if err != nil { 5253 t.Fatalf("unable to create test channels: %v", err) 5254 } 5255 defer cleanUp() 5256 5257 // Alice and Bob start with half the channel capacity. 5258 aliceBalance := lnwire.NewMAtomsFromAtoms(5 * dcrutil.AtomsPerCoin) 5259 bobBalance := lnwire.NewMAtomsFromAtoms(5 * dcrutil.AtomsPerCoin) 5260 5261 aliceReserve := lnwire.NewMAtomsFromAtoms( 5262 aliceChannel.channelState.LocalChanCfg.ChanReserve, 5263 ) 5264 bobReserve := lnwire.NewMAtomsFromAtoms( 5265 bobChannel.channelState.LocalChanCfg.ChanReserve, 5266 ) 5267 5268 aliceDustlimit := lnwire.NewMAtomsFromAtoms( 5269 aliceChannel.channelState.LocalChanCfg.DustLimit, 5270 ) 5271 feeRate := chainfee.AtomPerKByte( 5272 aliceChannel.channelState.LocalCommitment.FeePerKB, 5273 ) 5274 htlcFee := lnwire.NewMAtomsFromAtoms( 5275 feeRate.FeeForSize(input.HTLCOutputSize), 5276 ) 5277 commitFee := lnwire.NewMAtomsFromAtoms( 5278 aliceChannel.channelState.LocalCommitment.CommitFee, 5279 ) 5280 htlcTimeoutFee := lnwire.NewMAtomsFromAtoms( 5281 HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), 5282 ) 5283 htlcSuccessFee := lnwire.NewMAtomsFromAtoms( 5284 HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), 5285 ) 5286 5287 // Helper method to check the current reported balance. 5288 checkBalance := func(t *testing.T, expBalanceAlice, 5289 expBalanceBob lnwire.MilliAtom) { 5290 5291 t.Helper() 5292 aliceBalance := aliceChannel.AvailableBalance() 5293 if aliceBalance != expBalanceAlice { 5294 t.Fatalf("Expected alice balance %v, got %v", 5295 expBalanceAlice, aliceBalance) 5296 } 5297 5298 bobBalance := bobChannel.AvailableBalance() 5299 if bobBalance != expBalanceBob { 5300 t.Fatalf("Expected bob balance %v, got %v", 5301 expBalanceBob, bobBalance) 5302 } 5303 } 5304 5305 // Helper method to send an HTLC from Alice to Bob, decreasing Alice's 5306 // balance. 5307 htlcIndex := uint64(0) 5308 sendHtlc := func(htlcAmt lnwire.MilliAtom) { 5309 t.Helper() 5310 5311 htlc, preImage := createHTLC(int(htlcIndex), htlcAmt) 5312 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5313 t.Fatalf("unable to add htlc: %v", err) 5314 } 5315 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5316 t.Fatalf("unable to recv htlc: %v", err) 5317 } 5318 5319 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5320 t.Fatalf("unable to complete alice's state "+ 5321 "transition: %v", err) 5322 } 5323 5324 err = bobChannel.SettleHTLC(preImage, htlcIndex, nil, nil, nil) 5325 if err != nil { 5326 t.Fatalf("unable to settle htlc: %v", err) 5327 } 5328 err = aliceChannel.ReceiveHTLCSettle(preImage, htlcIndex) 5329 if err != nil { 5330 t.Fatalf("unable to settle htlc: %v", err) 5331 } 5332 5333 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5334 t.Fatalf("unable to complete alice's state "+ 5335 "transition: %v", err) 5336 } 5337 5338 htlcIndex++ 5339 aliceBalance -= htlcAmt 5340 bobBalance += htlcAmt 5341 } 5342 5343 // Balance should start out equal to half the channel capacity minus 5344 // the commitment fee Alice must pay and the channel reserve. In 5345 // addition the HTLC fee will be subtracted fromt the balance to 5346 // reflect that this value must be reserved for any payment above the 5347 // dust limit. 5348 expAliceBalance := aliceBalance - commitFee - aliceReserve - htlcFee 5349 5350 // Bob is not the initiator, so he will have all his balance available, 5351 // since Alice pays for fees. Bob only need to keep his balance above 5352 // the reserve. 5353 expBobBalance := bobBalance - bobReserve 5354 checkBalance(t, expAliceBalance, expBobBalance) 5355 5356 // Find the minumim size of a non-dust HTLC. 5357 aliceNonDustHtlc := aliceDustlimit + htlcTimeoutFee 5358 5359 // Send a HTLC leaving Alice's remaining balance just enough to have 5360 // nonDustHtlc left after paying the commit fee and htlc fee. 5361 htlcAmt := aliceBalance - (commitFee + aliceReserve + htlcFee + aliceNonDustHtlc) 5362 sendHtlc(htlcAmt) 5363 5364 // Now the real balance left will be 5365 // nonDustHtlc+commitfee+aliceReserve+htlcfee. The available balance 5366 // reported will just be nonDustHtlc, since the rest of the balance is 5367 // reserved. 5368 expAliceBalance = aliceNonDustHtlc 5369 expBobBalance = bobBalance - bobReserve 5370 checkBalance(t, expAliceBalance, expBobBalance) 5371 5372 // Send an HTLC using all but one msat of the reported balance. 5373 htlcAmt = aliceNonDustHtlc - 1 5374 sendHtlc(htlcAmt) 5375 5376 // 1 msat should be left. 5377 expAliceBalance = 1 5378 5379 // Bob should still have all his balance available, since even though 5380 // Alice cannot afford to add a non-dust HTLC, she can afford to add a 5381 // non-dust HTLC from Bob. 5382 expBobBalance = bobBalance - bobReserve 5383 checkBalance(t, expAliceBalance, expBobBalance) 5384 5385 // Sendng the last msat. 5386 htlcAmt = 1 5387 sendHtlc(htlcAmt) 5388 5389 // No balance left. 5390 expAliceBalance = 0 5391 5392 // We try to always reserve enough for the non-iniitator to be able to 5393 // add an HTLC, hence Bob should still have all his non-reserved 5394 // balance available. 5395 expBobBalance = bobBalance - bobReserve 5396 checkBalance(t, expAliceBalance, expBobBalance) 5397 5398 // Even though Alice has a reported balance of 0, this is because we 5399 // try to avoid getting into the position where she cannot pay the fee 5400 // for Bob adding another HTLC. This means she actually _has_ some 5401 // balance left, and we now force the channel into this situation by 5402 // sending yet another HTLC. In practice this can also happen if a fee 5403 // update eats into Alice's balance. 5404 htlcAmt = 1 5405 sendHtlc(htlcAmt) 5406 5407 // Now Alice balance is so low that she cannot even afford to add a new 5408 // HTLC from Bob to the commitment transaction. Bob's balance should 5409 // reflect this, by only reporting dust amount being available. Alice 5410 // should still report a zero balance. 5411 5412 // Since the dustlimit is different for the two commitments, the 5413 // largest HTLC Bob can send that Alice can afford on both commitments 5414 // (remember she cannot afford to pay the HTLC fee) is the largest dust 5415 // HTLC on Alice's commitemnt, since her dust limit is lower. 5416 bobNonDustHtlc := aliceDustlimit + htlcSuccessFee 5417 expBobBalance = bobNonDustHtlc - 1 5418 expAliceBalance = 0 5419 checkBalance(t, expAliceBalance, expBobBalance) 5420 } 5421 5422 // TestChanCommitWeightDustHtlcs checks that we correctly calculate the 5423 // commitment weight when some HTLCs are dust. 5424 func TestChanCommitWeightDustHtlcs(t *testing.T) { 5425 t.Parallel() 5426 5427 // Create a test channel which will be used for the duration of this 5428 // unittest. The channel will be funded evenly with Alice having 5 BTC, 5429 // and Bob having 5 BTC. 5430 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5431 channeldb.SingleFunderTweaklessBit, 5432 ) 5433 if err != nil { 5434 t.Fatalf("unable to create test channels: %v", err) 5435 } 5436 defer cleanUp() 5437 5438 aliceDustlimit := lnwire.NewMAtomsFromAtoms( 5439 aliceChannel.channelState.LocalChanCfg.DustLimit, 5440 ) 5441 bobDustlimit := lnwire.NewMAtomsFromAtoms( 5442 bobChannel.channelState.LocalChanCfg.DustLimit, 5443 ) 5444 5445 feeRate := chainfee.AtomPerKByte( 5446 aliceChannel.channelState.LocalCommitment.FeePerKB, 5447 ) 5448 htlcTimeoutFee := lnwire.NewMAtomsFromAtoms( 5449 HtlcTimeoutFee(aliceChannel.channelState.ChanType, feeRate), 5450 ) 5451 htlcSuccessFee := lnwire.NewMAtomsFromAtoms( 5452 HtlcSuccessFee(aliceChannel.channelState.ChanType, feeRate), 5453 ) 5454 5455 // Helper method to add an HTLC from Alice to Bob. 5456 htlcIndex := uint64(0) 5457 addHtlc := func(htlcAmt lnwire.MilliAtom) lntypes.Preimage { 5458 t.Helper() 5459 5460 htlc, preImage := createHTLC(int(htlcIndex), htlcAmt) 5461 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5462 t.Fatalf("unable to add htlc: %v", err) 5463 } 5464 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5465 t.Fatalf("unable to recv htlc: %v", err) 5466 } 5467 5468 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5469 t.Fatalf("unable to complete alice's state "+ 5470 "transition: %v", err) 5471 } 5472 5473 return preImage 5474 } 5475 5476 settleHtlc := func(preImage lntypes.Preimage) { 5477 t.Helper() 5478 5479 err = bobChannel.SettleHTLC(preImage, htlcIndex, nil, nil, nil) 5480 if err != nil { 5481 t.Fatalf("unable to settle htlc: %v", err) 5482 } 5483 err = aliceChannel.ReceiveHTLCSettle(preImage, htlcIndex) 5484 if err != nil { 5485 t.Fatalf("unable to settle htlc: %v", err) 5486 } 5487 5488 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5489 t.Fatalf("unable to complete alice's state "+ 5490 "transition: %v", err) 5491 } 5492 htlcIndex++ 5493 } 5494 5495 // Helper method that fetches the current remote commitment weight 5496 // fromt the given channel's POV. 5497 remoteCommitWeight := func(lc *LightningChannel) int64 { 5498 remoteACKedIndex := lc.localCommitChain.tip().theirMessageIndex 5499 htlcView := lc.fetchHTLCView(remoteACKedIndex, 5500 lc.localUpdateLog.logIndex) 5501 5502 _, w := lc.availableCommitmentBalance( 5503 htlcView, true, 5504 ) 5505 5506 return w 5507 } 5508 5509 // Start by getting the initial remote commitment wight seen from 5510 // Alice's perspective. At this point there are no HTLCs on the 5511 // commitment. 5512 weight1 := remoteCommitWeight(aliceChannel) 5513 5514 // Now add an HTLC that will be just below Bob's dustlimit. 5515 // Since this is an HTLC added from Alice on Bob's commitment, we will 5516 // use the HTLC success fee. 5517 bobDustHtlc := bobDustlimit + htlcSuccessFee - 1 5518 preimg := addHtlc(bobDustHtlc) 5519 5520 // Now get the current wight of the remote commitment. We expect it to 5521 // not have changed, since the HTLC we added is considered dust. 5522 weight2 := remoteCommitWeight(aliceChannel) 5523 require.Equal(t, weight1, weight2) 5524 5525 // In addition, we expect this weight to result in the fee we currently 5526 // see being paid on the remote commitent. 5527 calcFee := feeRate.FeeForSize(weight2) 5528 remoteCommitFee := aliceChannel.channelState.RemoteCommitment.CommitFee 5529 require.Equal(t, calcFee, remoteCommitFee) 5530 5531 // Settle the HTLC, bringing commitment weight back to base. 5532 settleHtlc(preimg) 5533 5534 // Now we do a similar check from Bob's POV. Start with getting his 5535 // current view of Alice's commitment weight. 5536 weight1 = remoteCommitWeight(bobChannel) 5537 5538 // We'll add an HTLC from Alice to Bob, that is just above dust on 5539 // Alice's commitment. Now we'll use the timeout fee. 5540 aliceDustHtlc := aliceDustlimit + htlcTimeoutFee 5541 preimg = addHtlc(aliceDustHtlc) 5542 5543 // Get the current remote commitment weight from Bob's POV, and ensure 5544 // it is now heavier, since Alice added a non-dust HTLC. 5545 weight2 = remoteCommitWeight(bobChannel) 5546 require.Greater(t, weight2, weight1) 5547 5548 // Ensure the current remote commit has the expected commitfee. 5549 calcFee = feeRate.FeeForSize(weight2) 5550 remoteCommitFee = bobChannel.channelState.RemoteCommitment.CommitFee 5551 require.Equal(t, calcFee, remoteCommitFee) 5552 5553 settleHtlc(preimg) 5554 } 5555 5556 // TestSignCommitmentFailNotLockedIn tests that a channel will not attempt to 5557 // create a new state if it doesn't yet know of the next revocation point for 5558 // the remote party. 5559 func TestSignCommitmentFailNotLockedIn(t *testing.T) { 5560 t.Parallel() 5561 5562 // Create a test channel which will be used for the duration of this 5563 // unittest. The channel will be funded evenly with Alice having 5 DCR, 5564 // and Bob having 5 DCR. 5565 aliceChannel, _, cleanUp, err := CreateTestChannels( 5566 channeldb.SingleFunderTweaklessBit, 5567 ) 5568 if err != nil { 5569 t.Fatalf("unable to create test channels: %v", err) 5570 } 5571 defer cleanUp() 5572 5573 // Next, we'll modify Alice's internal state to omit knowledge of Bob's 5574 // next revocation point. 5575 aliceChannel.channelState.RemoteNextRevocation = nil 5576 5577 // If we now try to initiate a state update, then it should fail as 5578 // Alice is unable to actually create a new state. 5579 _, _, _, err = aliceChannel.SignNextCommitment() 5580 if err != ErrNoWindow { 5581 t.Fatalf("expected ErrNoWindow, instead have: %v", err) 5582 } 5583 } 5584 5585 // TestLockedInHtlcForwardingSkipAfterRestart ensures that after a restart, a 5586 // state machine doesn't attempt to re-forward any HTLC's that were already 5587 // locked in, but in a prior state. 5588 func TestLockedInHtlcForwardingSkipAfterRestart(t *testing.T) { 5589 t.Parallel() 5590 5591 // First, we'll make a channel between Alice and Bob. 5592 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5593 channeldb.SingleFunderTweaklessBit, 5594 ) 5595 if err != nil { 5596 t.Fatalf("unable to create test channels: %v", err) 5597 } 5598 defer cleanUp() 5599 5600 // We'll now add two HTLC's from Alice to Bob, then Alice will initiate 5601 // a state transition. 5602 var htlcAmt lnwire.MilliAtom = 100000 5603 htlc, _ := createHTLC(0, htlcAmt) 5604 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5605 t.Fatalf("unable to add htlc: %v", err) 5606 } 5607 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5608 t.Fatalf("unable to recv htlc: %v", err) 5609 } 5610 htlc2, _ := createHTLC(1, htlcAmt) 5611 if _, err := aliceChannel.AddHTLC(htlc2, nil); err != nil { 5612 t.Fatalf("unable to add htlc2: %v", err) 5613 } 5614 if _, err := bobChannel.ReceiveHTLC(htlc2); err != nil { 5615 t.Fatalf("unable to recv htlc2: %v", err) 5616 } 5617 5618 // We'll now manually initiate a state transition between Alice and 5619 // bob. 5620 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 5621 if err != nil { 5622 t.Fatal(err) 5623 } 5624 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 5625 if err != nil { 5626 t.Fatal(err) 5627 } 5628 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 5629 if err != nil { 5630 t.Fatal(err) 5631 } 5632 5633 // Alice should detect that she doesn't need to forward any HTLC's. 5634 fwdPkg, _, _, _, err := aliceChannel.ReceiveRevocation(bobRevocation) 5635 if err != nil { 5636 t.Fatal(err) 5637 } 5638 if len(fwdPkg.Adds) != 0 { 5639 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5640 "forward %v htlcs", len(fwdPkg.Adds)) 5641 } 5642 if len(fwdPkg.SettleFails) != 0 { 5643 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5644 "forward %v htlcs", len(fwdPkg.SettleFails)) 5645 } 5646 5647 // Now, have Bob initiate a transition to lock in the Adds sent by 5648 // Alice. 5649 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 5650 if err != nil { 5651 t.Fatal(err) 5652 } 5653 5654 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 5655 if err != nil { 5656 t.Fatal(err) 5657 } 5658 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 5659 if err != nil { 5660 t.Fatal(err) 5661 } 5662 5663 // Bob should now detect that he now has 2 incoming HTLC's that he can 5664 // forward along. 5665 fwdPkg, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 5666 if err != nil { 5667 t.Fatal(err) 5668 } 5669 if len(fwdPkg.Adds) != 2 { 5670 t.Fatalf("bob should forward 2 hltcs, instead has %v", 5671 len(fwdPkg.Adds)) 5672 } 5673 if len(fwdPkg.SettleFails) != 0 { 5674 t.Fatalf("bob should forward 0 hltcs, instead has %v", 5675 len(fwdPkg.SettleFails)) 5676 } 5677 5678 // We'll now restart both Alice and Bob. This emulates a reconnection 5679 // between the two peers. 5680 aliceChannel, err = restartChannel(aliceChannel) 5681 if err != nil { 5682 t.Fatalf("unable to restart alice: %v", err) 5683 } 5684 bobChannel, err = restartChannel(bobChannel) 5685 if err != nil { 5686 t.Fatalf("unable to restart bob: %v", err) 5687 } 5688 5689 // With both nodes restarted, Bob will now attempt to cancel one of 5690 // Alice's HTLC's. 5691 err = bobChannel.FailHTLC(htlc.ID, []byte("failreason"), nil, nil, nil) 5692 if err != nil { 5693 t.Fatalf("unable to cancel HTLC: %v", err) 5694 } 5695 err = aliceChannel.ReceiveFailHTLC(htlc.ID, []byte("bad")) 5696 if err != nil { 5697 t.Fatalf("unable to recv htlc cancel: %v", err) 5698 } 5699 5700 // We'll now initiate another state transition, but this time Bob will 5701 // lead. 5702 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 5703 if err != nil { 5704 t.Fatal(err) 5705 } 5706 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 5707 if err != nil { 5708 t.Fatal(err) 5709 } 5710 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 5711 if err != nil { 5712 t.Fatal(err) 5713 } 5714 5715 // At this point, Bob receives the revocation from Alice, which is now 5716 // his signal to examine all the HTLC's that have been locked in to 5717 // process. 5718 fwdPkg, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 5719 if err != nil { 5720 t.Fatal(err) 5721 } 5722 5723 // Bob should detect that he doesn't need to forward *any* HTLC's, as 5724 // he was the one that initiated extending the commitment chain of 5725 // Alice. 5726 if len(fwdPkg.Adds) != 0 { 5727 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5728 "forward %v htlcs", len(fwdPkg.Adds)) 5729 } 5730 if len(fwdPkg.SettleFails) != 0 { 5731 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5732 "forward %v htlcs", len(fwdPkg.SettleFails)) 5733 } 5734 5735 // Now, begin another state transition led by Alice, and fail the second 5736 // HTLC part-way through the dance. 5737 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 5738 if err != nil { 5739 t.Fatal(err) 5740 } 5741 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 5742 if err != nil { 5743 t.Fatal(err) 5744 } 5745 5746 // Failing the HTLC here will cause the update to be included in Alice's 5747 // remote log, but it should not be committed by this transition. 5748 err = bobChannel.FailHTLC(htlc2.ID, []byte("failreason"), nil, nil, nil) 5749 if err != nil { 5750 t.Fatalf("unable to cancel HTLC: %v", err) 5751 } 5752 err = aliceChannel.ReceiveFailHTLC(htlc2.ID, []byte("bad")) 5753 if err != nil { 5754 t.Fatalf("unable to recv htlc cancel: %v", err) 5755 } 5756 5757 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 5758 if err != nil { 5759 t.Fatal(err) 5760 } 5761 5762 // Alice should detect that she doesn't need to forward any Adds's, but 5763 // that the Fail has been locked in an can be forwarded. 5764 _, adds, settleFails, _, err := aliceChannel.ReceiveRevocation(bobRevocation) 5765 if err != nil { 5766 t.Fatal(err) 5767 } 5768 if len(adds) != 0 { 5769 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5770 "forward %v htlcs", len(adds)) 5771 } 5772 if len(settleFails) != 1 { 5773 t.Fatalf("alice should only forward %d HTLC's, instead wants to "+ 5774 "forward %v htlcs", 1, len(settleFails)) 5775 } 5776 if settleFails[0].ParentIndex != htlc.ID { 5777 t.Fatalf("alice should forward fail for htlcid=%d, instead "+ 5778 "forwarding id=%d", htlc.ID, 5779 settleFails[0].ParentIndex) 5780 } 5781 5782 // We'll now restart both Alice and Bob. This emulates a reconnection 5783 // between the two peers. 5784 aliceChannel, err = restartChannel(aliceChannel) 5785 if err != nil { 5786 t.Fatalf("unable to restart alice: %v", err) 5787 } 5788 bobChannel, err = restartChannel(bobChannel) 5789 if err != nil { 5790 t.Fatalf("unable to restart bob: %v", err) 5791 } 5792 5793 // Readd the Fail to both Alice and Bob's channels, as the non-committed 5794 // update will not have survived the restart. 5795 err = bobChannel.FailHTLC(htlc2.ID, []byte("failreason"), nil, nil, nil) 5796 if err != nil { 5797 t.Fatalf("unable to cancel HTLC: %v", err) 5798 } 5799 err = aliceChannel.ReceiveFailHTLC(htlc2.ID, []byte("bad")) 5800 if err != nil { 5801 t.Fatalf("unable to recv htlc cancel: %v", err) 5802 } 5803 5804 // Have Alice initiate a state transition, which does not include the 5805 // HTLCs just readded to the channel state. 5806 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 5807 if err != nil { 5808 t.Fatal(err) 5809 } 5810 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 5811 if err != nil { 5812 t.Fatal(err) 5813 } 5814 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 5815 if err != nil { 5816 t.Fatal(err) 5817 } 5818 5819 // Alice should detect that she doesn't need to forward any HTLC's, as 5820 // the updates haven't been committed by Bob yet. 5821 fwdPkg, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 5822 if err != nil { 5823 t.Fatal(err) 5824 } 5825 if len(fwdPkg.Adds) != 0 { 5826 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5827 "forward %v htlcs", len(fwdPkg.Adds)) 5828 } 5829 if len(fwdPkg.SettleFails) != 0 { 5830 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5831 "forward %v htlcs", len(fwdPkg.SettleFails)) 5832 } 5833 5834 // Now initiate a final update from Bob to lock in the final Fail. 5835 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 5836 if err != nil { 5837 t.Fatal(err) 5838 } 5839 5840 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 5841 if err != nil { 5842 t.Fatal(err) 5843 } 5844 5845 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 5846 if err != nil { 5847 t.Fatal(err) 5848 } 5849 5850 // Bob should detect that he has nothing to forward, as he hasn't 5851 // received any HTLCs. 5852 fwdPkg, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 5853 if err != nil { 5854 t.Fatal(err) 5855 } 5856 if len(fwdPkg.Adds) != 0 { 5857 t.Fatalf("bob should forward 4 hltcs, instead has %v", 5858 len(fwdPkg.Adds)) 5859 } 5860 if len(fwdPkg.SettleFails) != 0 { 5861 t.Fatalf("bob should forward 0 hltcs, instead has %v", 5862 len(fwdPkg.SettleFails)) 5863 } 5864 5865 // Finally, have Bob initiate a state transition that locks in the Fail 5866 // added after the restart. 5867 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 5868 if err != nil { 5869 t.Fatal(err) 5870 } 5871 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 5872 if err != nil { 5873 t.Fatal(err) 5874 } 5875 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 5876 if err != nil { 5877 t.Fatal(err) 5878 } 5879 5880 // When Alice receives the revocation, she should detect that she 5881 // can now forward the freshly locked-in Fail. 5882 _, adds, settleFails, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 5883 if err != nil { 5884 t.Fatal(err) 5885 } 5886 if len(adds) != 0 { 5887 t.Fatalf("alice shouldn't forward any HTLC's, instead wants to "+ 5888 "forward %v htlcs", len(adds)) 5889 } 5890 if len(settleFails) != 1 { 5891 t.Fatalf("alice should only forward one HTLC, instead wants to "+ 5892 "forward %v htlcs", len(settleFails)) 5893 } 5894 if settleFails[0].ParentIndex != htlc2.ID { 5895 t.Fatalf("alice should forward fail for htlcid=%d, instead "+ 5896 "forwarding id=%d", htlc2.ID, 5897 settleFails[0].ParentIndex) 5898 } 5899 } 5900 5901 // TestInvalidCommitSigError tests that if the remote party sends us an invalid 5902 // commitment signature, then we'll reject it and return a special error that 5903 // contains information to allow the remote party to debug their issues. 5904 func TestInvalidCommitSigError(t *testing.T) { 5905 t.Parallel() 5906 5907 // First, we'll make a channel between Alice and Bob. 5908 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5909 channeldb.SingleFunderTweaklessBit, 5910 ) 5911 if err != nil { 5912 t.Fatalf("unable to create test channels: %v", err) 5913 } 5914 defer cleanUp() 5915 5916 // With the channel established, we'll now send a single HTLC from 5917 // Alice to Bob. 5918 var htlcAmt lnwire.MilliAtom = 100000 5919 htlc, _ := createHTLC(0, htlcAmt) 5920 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 5921 t.Fatalf("unable to add htlc: %v", err) 5922 } 5923 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 5924 t.Fatalf("unable to recv htlc: %v", err) 5925 } 5926 5927 // Alice will now attempt to initiate a state transition. 5928 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 5929 if err != nil { 5930 t.Fatalf("unable to sign new commit: %v", err) 5931 } 5932 5933 // Before the signature gets to Bob, we'll mutate it, such that the 5934 // signature is now actually invalid. 5935 aliceSig[0] ^= 88 5936 5937 // Bob should reject this new state, and return the proper error. 5938 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 5939 if err == nil { 5940 t.Fatalf("bob accepted invalid state but shouldn't have") 5941 } 5942 if _, ok := err.(*InvalidCommitSigError); !ok { 5943 t.Fatalf("bob sent incorrect error, expected %T, got %T", 5944 &InvalidCommitSigError{}, err) 5945 } 5946 } 5947 5948 // TestChannelUnilateralCloseHtlcResolution tests that in the case of a 5949 // unilateral channel closure, then the party that didn't broadcast the 5950 // commitment is able to properly sweep all relevant outputs. 5951 func TestChannelUnilateralCloseHtlcResolution(t *testing.T) { 5952 t.Parallel() 5953 5954 // Create a test channel which will be used for the duration of this 5955 // unittest. The channel will be funded evenly with Alice having 5 DCR, 5956 // and Bob having 5 DCR. 5957 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 5958 channeldb.SingleFunderTweaklessBit, 5959 ) 5960 if err != nil { 5961 t.Fatalf("unable to create test channels: %v", err) 5962 } 5963 defer cleanUp() 5964 5965 // We'll start off the test by adding an HTLC in both directions, then 5966 // initiating enough state transitions to lock both of them in. 5967 htlcAmount := lnwire.NewMAtomsFromAtoms(200000) 5968 htlcAlice, _ := createHTLC(0, htlcAmount) 5969 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 5970 t.Fatalf("alice unable to add htlc: %v", err) 5971 } 5972 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 5973 t.Fatalf("bob unable to recv add htlc: %v", err) 5974 } 5975 htlcBob, preimageBob := createHTLC(0, htlcAmount) 5976 if _, err := bobChannel.AddHTLC(htlcBob, nil); err != nil { 5977 t.Fatalf("bob unable to add htlc: %v", err) 5978 } 5979 if _, err := aliceChannel.ReceiveHTLC(htlcBob); err != nil { 5980 t.Fatalf("alice unable to recv add htlc: %v", err) 5981 } 5982 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 5983 t.Fatalf("Can't update the channel state: %v", err) 5984 } 5985 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 5986 t.Fatalf("Can't update the channel state: %v", err) 5987 } 5988 5989 // With both HTLC's locked in, we'll now simulate Bob force closing the 5990 // transaction on Alice. 5991 bobForceClose, err := bobChannel.ForceClose() 5992 if err != nil { 5993 t.Fatalf("unable to close: %v", err) 5994 } 5995 5996 // We'll then use Bob's transaction to trigger a spend notification for 5997 // Alice. 5998 closeTx := bobForceClose.CloseTx 5999 commitTxHash := closeTx.TxHash() 6000 spendDetail := &chainntnfs.SpendDetail{ 6001 SpendingTx: closeTx, 6002 SpenderTxHash: &commitTxHash, 6003 } 6004 aliceCloseSummary, err := NewUnilateralCloseSummary( 6005 aliceChannel.channelState, aliceChannel.Signer, 6006 spendDetail, 6007 aliceChannel.channelState.RemoteCommitment, 6008 aliceChannel.channelState.RemoteCurrentRevocation, 6009 ) 6010 if err != nil { 6011 t.Fatalf("unable to create alice close summary: %v", err) 6012 } 6013 6014 // She should detect that she can sweep both the outgoing HTLC as well 6015 // as the incoming one from Bob. 6016 if len(aliceCloseSummary.HtlcResolutions.OutgoingHTLCs) != 1 { 6017 t.Fatalf("alice out htlc resolutions not populated: expected %v "+ 6018 "htlcs, got %v htlcs", 6019 1, len(aliceCloseSummary.HtlcResolutions.OutgoingHTLCs)) 6020 } 6021 if len(aliceCloseSummary.HtlcResolutions.IncomingHTLCs) != 1 { 6022 t.Fatalf("alice in htlc resolutions not populated: expected %v "+ 6023 "htlcs, got %v htlcs", 6024 1, len(aliceCloseSummary.HtlcResolutions.IncomingHTLCs)) 6025 } 6026 6027 outHtlcResolution := aliceCloseSummary.HtlcResolutions.OutgoingHTLCs[0] 6028 inHtlcResolution := aliceCloseSummary.HtlcResolutions.IncomingHTLCs[0] 6029 6030 // First, we'll ensure that Alice can directly spend the outgoing HTLC 6031 // given a transaction with the proper lock time set. 6032 receiverHtlcScript := closeTx.TxOut[outHtlcResolution.ClaimOutpoint.Index].PkScript 6033 sweepTx := wire.NewMsgTx() 6034 sweepTx.AddTxIn(&wire.TxIn{ 6035 PreviousOutPoint: outHtlcResolution.ClaimOutpoint, 6036 }) 6037 sweepTx.AddTxOut(&wire.TxOut{ 6038 PkScript: receiverHtlcScript, 6039 Value: outHtlcResolution.SweepSignDesc.Output.Value, 6040 }) 6041 outHtlcResolution.SweepSignDesc.InputIndex = 0 6042 sweepTx.LockTime = outHtlcResolution.Expiry 6043 6044 // With the transaction constructed, we'll generate a witness that 6045 // should be valid for it, and verify using an instance of Script. 6046 witness, err := input.ReceiverHtlcSpendTimeout( 6047 aliceChannel.Signer, &outHtlcResolution.SweepSignDesc, 6048 sweepTx, int32(outHtlcResolution.Expiry), 6049 ) 6050 if err != nil { 6051 t.Fatalf("unable to witness: %v", err) 6052 } 6053 sweepTx.TxIn[0].SignatureScript, err = input.WitnessStackToSigScript(witness) 6054 if err != nil { 6055 t.Fatalf("unable to convert witness stack to sigScript: %v", err) 6056 } 6057 6058 vm, err := txscript.NewEngine( 6059 outHtlcResolution.SweepSignDesc.Output.PkScript, 6060 sweepTx, 0, input.ScriptVerifyFlags, 6061 outHtlcResolution.SweepSignDesc.Output.Version, nil, 6062 ) 6063 if err != nil { 6064 t.Fatalf("unable to create engine: %v", err) 6065 } 6066 if err := vm.Execute(); err != nil { 6067 t.Fatalf("htlc timeout spend is invalid: %v", err) 6068 } 6069 6070 // Next, we'll ensure that we're able to sweep the incoming HTLC with a 6071 // similar sweep transaction, this time using the payment pre-image. 6072 senderHtlcScript := closeTx.TxOut[inHtlcResolution.ClaimOutpoint.Index].PkScript 6073 sweepTx = wire.NewMsgTx() 6074 sweepTx.AddTxIn(&wire.TxIn{ 6075 PreviousOutPoint: inHtlcResolution.ClaimOutpoint, 6076 }) 6077 sweepTx.AddTxOut(&wire.TxOut{ 6078 PkScript: senderHtlcScript, 6079 Value: inHtlcResolution.SweepSignDesc.Output.Value, 6080 }) 6081 inHtlcResolution.SweepSignDesc.InputIndex = 0 6082 witness, err = input.SenderHtlcSpendRedeem( 6083 aliceChannel.Signer, &inHtlcResolution.SweepSignDesc, 6084 sweepTx, preimageBob[:], 6085 ) 6086 if err != nil { 6087 t.Fatalf("unable to construct witnesss: %v", err) 6088 } 6089 sweepTx.TxIn[0].SignatureScript, err = input.WitnessStackToSigScript(witness) 6090 if err != nil { 6091 t.Fatalf("unable to generate witness for success "+ 6092 "output: %v", err) 6093 } 6094 6095 // Finally, we'll verify the constructed witness to ensure that Alice 6096 // can properly sweep the output. 6097 vm, err = txscript.NewEngine( 6098 inHtlcResolution.SweepSignDesc.Output.PkScript, 6099 sweepTx, 0, input.ScriptVerifyFlags, 6100 inHtlcResolution.SweepSignDesc.Output.Version, nil, 6101 ) 6102 if err != nil { 6103 t.Fatalf("unable to create engine: %v", err) 6104 } 6105 if err := vm.Execute(); err != nil { 6106 t.Fatalf("htlc timeout spend is invalid: %v", err) 6107 } 6108 } 6109 6110 // TestChannelUnilateralClosePendingCommit tests that if the remote party 6111 // broadcasts their pending commit (hasn't yet revoked the lower one), then 6112 // we'll create a proper unilateral channel clsoure that can sweep the created 6113 // outputs. 6114 func TestChannelUnilateralClosePendingCommit(t *testing.T) { 6115 t.Parallel() 6116 6117 // Create a test channel which will be used for the duration of this 6118 // unittest. The channel will be funded evenly with Alice having 5 DCR, 6119 // and Bob having 5 DCR. 6120 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6121 channeldb.SingleFunderBit, 6122 ) 6123 if err != nil { 6124 t.Fatalf("unable to create test channels: %v", err) 6125 } 6126 defer cleanUp() 6127 6128 // First, we'll add an HTLC from Alice to Bob, just to be be able to 6129 // create a new state transition. 6130 htlcAmount := lnwire.NewMAtomsFromAtoms(20000) 6131 htlcAlice, _ := createHTLC(0, htlcAmount) 6132 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 6133 t.Fatalf("alice unable to add htlc: %v", err) 6134 } 6135 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 6136 t.Fatalf("bob unable to recv add htlc: %v", err) 6137 } 6138 6139 // With the HTLC added, we'll now manually initiate a state transition 6140 // from Alice to Bob. 6141 _, _, _, err = aliceChannel.SignNextCommitment() 6142 if err != nil { 6143 t.Fatal(err) 6144 } 6145 6146 // At this point, Alice's commitment chain should have a new pending 6147 // commit for Bob. We'll extract it so we can simulate Bob broadcasting 6148 // the commitment due to an issue. 6149 bobCommit := aliceChannel.remoteCommitChain.tip().txn 6150 bobTxHash := bobCommit.TxHash() 6151 spendDetail := &chainntnfs.SpendDetail{ 6152 SpenderTxHash: &bobTxHash, 6153 SpendingTx: bobCommit, 6154 } 6155 6156 // At this point, if we attempt to create a unilateral close summary 6157 // using this commitment, but with the wrong state, we should find that 6158 // our output wasn't picked up. 6159 aliceWrongCloseSummary, err := NewUnilateralCloseSummary( 6160 aliceChannel.channelState, aliceChannel.Signer, 6161 spendDetail, 6162 aliceChannel.channelState.RemoteCommitment, 6163 aliceChannel.channelState.RemoteCurrentRevocation, 6164 ) 6165 if err != nil { 6166 t.Fatalf("unable to create alice close summary: %v", err) 6167 } 6168 6169 if aliceWrongCloseSummary.CommitResolution != nil { 6170 t.Fatalf("alice shouldn't have found self output") 6171 } 6172 6173 // If we create the close summary again, but this time use Alice's 6174 // pending commit to Bob, then the unilateral close summary should be 6175 // properly populated. 6176 aliceRemoteChainTip, err := aliceChannel.channelState.RemoteCommitChainTip() 6177 if err != nil { 6178 t.Fatalf("unable to fetch remote chain tip: %v", err) 6179 } 6180 aliceCloseSummary, err := NewUnilateralCloseSummary( 6181 aliceChannel.channelState, aliceChannel.Signer, 6182 spendDetail, 6183 aliceRemoteChainTip.Commitment, 6184 aliceChannel.channelState.RemoteNextRevocation, 6185 ) 6186 if err != nil { 6187 t.Fatalf("unable to create alice close summary: %v", err) 6188 } 6189 6190 // With this proper version, Alice's commit resolution should have been 6191 // properly located. 6192 if aliceCloseSummary.CommitResolution == nil { 6193 t.Fatalf("unable to find alice's commit resolution") 6194 } 6195 6196 // The proper short channel ID should also be set in Alice's close 6197 // channel summary. 6198 if aliceCloseSummary.ChannelCloseSummary.ShortChanID != 6199 aliceChannel.ShortChanID() { 6200 6201 t.Fatalf("wrong short chan ID, expected %v got %v", 6202 aliceChannel.ShortChanID(), 6203 aliceCloseSummary.ChannelCloseSummary.ShortChanID) 6204 } 6205 6206 aliceSignDesc := aliceCloseSummary.CommitResolution.SelfOutputSignDesc 6207 6208 // Finally, we'll ensure that we're able to properly sweep our output 6209 // from using the materials within the unilateral close summary. 6210 sweepTx := wire.NewMsgTx() 6211 sweepTx.AddTxIn(&wire.TxIn{ 6212 PreviousOutPoint: aliceCloseSummary.CommitResolution.SelfOutPoint, 6213 }) 6214 sweepTx.AddTxOut(&wire.TxOut{ 6215 PkScript: testHdSeed[:], 6216 Value: aliceSignDesc.Output.Value, 6217 }) 6218 witness, err := input.CommitSpendNoDelay( 6219 aliceChannel.Signer, &aliceSignDesc, sweepTx, false, 6220 ) 6221 if err != nil { 6222 t.Fatalf("unable to generate sweep witness: %v", err) 6223 } 6224 sweepTx.TxIn[0].SignatureScript, err = input.WitnessStackToSigScript(witness) 6225 if err != nil { 6226 t.Fatalf("unable to convert witness stack to sigScript: %v", err) 6227 } 6228 6229 // If we validate the signature on the new sweep transaction, it should 6230 // be fully valid. 6231 vm, err := txscript.NewEngine( 6232 aliceSignDesc.Output.PkScript, 6233 sweepTx, 0, input.ScriptVerifyFlags, aliceSignDesc.Output.Version, nil, 6234 ) 6235 if err != nil { 6236 t.Fatalf("unable to create engine: %v", err) 6237 } 6238 if err := vm.Execute(); err != nil { 6239 t.Fatalf("htlc timeout spend is invalid: %v", err) 6240 } 6241 } 6242 6243 // TestDesyncHTLCs checks that we cannot add HTLCs that would make the 6244 // balance negative, when the remote and local update logs are desynced. 6245 func TestDesyncHTLCs(t *testing.T) { 6246 t.Parallel() 6247 6248 // We'll kick off the test by creating our channels which both are 6249 // loaded with 5 DCR each. 6250 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6251 channeldb.SingleFunderTweaklessBit, 6252 ) 6253 if err != nil { 6254 t.Fatalf("unable to create test channels: %v", err) 6255 } 6256 defer cleanUp() 6257 6258 // First add one HTLC of value 4.1 DCR. 6259 htlcAmt := lnwire.NewMAtomsFromAtoms(4.1 * dcrutil.AtomsPerCoin) 6260 htlc, _ := createHTLC(0, htlcAmt) 6261 aliceIndex, err := aliceChannel.AddHTLC(htlc, nil) 6262 if err != nil { 6263 t.Fatalf("unable to add htlc: %v", err) 6264 } 6265 bobIndex, err := bobChannel.ReceiveHTLC(htlc) 6266 if err != nil { 6267 t.Fatalf("unable to recv htlc: %v", err) 6268 } 6269 6270 // Lock this HTLC in. 6271 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6272 t.Fatalf("unable to complete state update: %v", err) 6273 } 6274 6275 // Now let Bob fail this HTLC. 6276 err = bobChannel.FailHTLC(bobIndex, []byte("failreason"), nil, nil, nil) 6277 if err != nil { 6278 t.Fatalf("unable to cancel HTLC: %v", err) 6279 } 6280 if err := aliceChannel.ReceiveFailHTLC(aliceIndex, []byte("bad")); err != nil { 6281 t.Fatalf("unable to recv htlc cancel: %v", err) 6282 } 6283 6284 // Alice now has gotten all her original balance (5 DCR) back, however, 6285 // adding a new HTLC at this point SHOULD fail, since if she adds the 6286 // HTLC and signs the next state, Bob cannot assume she received the 6287 // FailHTLC, and must assume she doesn't have the necessary balance 6288 // available. 6289 // 6290 // We try adding an HTLC of value 1 DCR, which should fail because the 6291 // balance is unavailable. 6292 htlcAmt = lnwire.NewMAtomsFromAtoms(1 * dcrutil.AtomsPerCoin) 6293 htlc, _ = createHTLC(1, htlcAmt) 6294 if _, err = aliceChannel.AddHTLC(htlc, nil); err != ErrBelowChanReserve { 6295 t.Fatalf("expected ErrInsufficientBalance, instead received: %v", 6296 err) 6297 } 6298 6299 // Now do a state transition, which will ACK the FailHTLC, making Alice 6300 // able to add the new HTLC. 6301 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6302 t.Fatalf("unable to complete state update: %v", err) 6303 } 6304 if _, err = aliceChannel.AddHTLC(htlc, nil); err != nil { 6305 t.Fatalf("unable to add htlc: %v", err) 6306 } 6307 } 6308 6309 // TODO(roasbeef): testing.Quick test case for retrans!!! 6310 6311 // TestMaxAcceptedHTLCs tests that the correct error message (ErrMaxHTLCNumber) 6312 // is thrown when a node tries to accept more than MaxAcceptedHTLCs in a 6313 // channel. 6314 func TestMaxAcceptedHTLCs(t *testing.T) { 6315 t.Parallel() 6316 6317 // We'll kick off the test by creating our channels which both are 6318 // loaded with 5 DCR each. 6319 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6320 channeldb.SingleFunderTweaklessBit, 6321 ) 6322 if err != nil { 6323 t.Fatalf("unable to create test channels: %v", err) 6324 } 6325 defer cleanUp() 6326 6327 // One over the maximum number of HTLCs that either can accept. 6328 const numHTLCs = 12 6329 6330 // Set the remote's required MaxAcceptedHtlcs. This means that Alice 6331 // can only offer the remote up to numHTLCs HTLCs. 6332 aliceChannel.channelState.LocalChanCfg.MaxAcceptedHtlcs = numHTLCs 6333 bobChannel.channelState.RemoteChanCfg.MaxAcceptedHtlcs = numHTLCs 6334 6335 // Similarly, set the remote config's MaxAcceptedHtlcs. This means 6336 // that the remote will be aware that Bob will only accept up to 6337 // numHTLCs at a time. 6338 aliceChannel.channelState.RemoteChanCfg.MaxAcceptedHtlcs = numHTLCs 6339 bobChannel.channelState.LocalChanCfg.MaxAcceptedHtlcs = numHTLCs 6340 6341 // Each HTLC amount is 0.1 DCR. 6342 htlcAmt := lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 6343 6344 // htlcID is used to keep track of the HTLC that Bob will fail back to 6345 // Alice. 6346 var htlcID uint64 6347 6348 // Send the maximum allowed number of HTLCs. 6349 for i := 0; i < numHTLCs; i++ { 6350 htlc, _ := createHTLC(i, htlcAmt) 6351 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6352 t.Fatalf("unable to add htlc: %v", err) 6353 } 6354 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6355 t.Fatalf("unable to recv htlc: %v", err) 6356 } 6357 6358 // Just assign htlcID to the last received HTLC. 6359 htlcID = htlc.ID 6360 } 6361 6362 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6363 t.Fatalf("unable to transition state: %v", err) 6364 } 6365 6366 // The next HTLC should fail with ErrMaxHTLCNumber. 6367 htlc, _ := createHTLC(numHTLCs, htlcAmt) 6368 _, err = aliceChannel.AddHTLC(htlc, nil) 6369 if err != ErrMaxHTLCNumber { 6370 t.Fatalf("expected ErrMaxHTLCNumber, instead received: %v", err) 6371 } 6372 6373 // Receiving the next HTLC should fail. 6374 if _, err := bobChannel.ReceiveHTLC(htlc); err != ErrMaxHTLCNumber { 6375 t.Fatalf("expected ErrMaxHTLCNumber, instead received: %v", err) 6376 } 6377 6378 // Bob will fail the htlc specified by htlcID and then force a state 6379 // transition. 6380 err = bobChannel.FailHTLC(htlcID, []byte{}, nil, nil, nil) 6381 if err != nil { 6382 t.Fatalf("unable to fail htlc: %v", err) 6383 } 6384 6385 if err := aliceChannel.ReceiveFailHTLC(htlcID, []byte{}); err != nil { 6386 t.Fatalf("unable to receive fail htlc: %v", err) 6387 } 6388 6389 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 6390 t.Fatalf("unable to transition state: %v", err) 6391 } 6392 6393 // Bob should succeed in adding a new HTLC since a previous HTLC was just 6394 // failed. We use numHTLCs here since the previous AddHTLC with this index 6395 // failed. 6396 htlc, _ = createHTLC(numHTLCs, htlcAmt) 6397 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6398 t.Fatalf("unable to add htlc: %v", err) 6399 } 6400 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6401 t.Fatalf("unable to recv htlc: %v", err) 6402 } 6403 6404 // Add a commitment to Bob's commitment chain. 6405 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 6406 if err != nil { 6407 t.Fatalf("unable to sign next commitment: %v", err) 6408 } 6409 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 6410 if err != nil { 6411 t.Fatalf("unable to recv new commitment: %v", err) 6412 } 6413 6414 // The next HTLC should fail with ErrMaxHTLCNumber. The index is incremented 6415 // by one. 6416 htlc, _ = createHTLC(numHTLCs+1, htlcAmt) 6417 if _, err = aliceChannel.AddHTLC(htlc, nil); err != ErrMaxHTLCNumber { 6418 t.Fatalf("expected ErrMaxHTLCNumber, instead received: %v", err) 6419 } 6420 6421 // Likewise, Bob should not be able to receive this HTLC if Alice can't 6422 // add it. 6423 if _, err := bobChannel.ReceiveHTLC(htlc); err != ErrMaxHTLCNumber { 6424 t.Fatalf("expected ErrMaxHTLCNumber, instead received: %v", err) 6425 } 6426 } 6427 6428 // TestMaxAsynchronousHtlcs tests that Bob correctly receives (and does not 6429 // fail) an HTLC from Alice when exchanging asynchronous payments. We want to 6430 // mimic the following case where Bob's commitment transaction is full before 6431 // starting: 6432 // 6433 // Alice Bob 6434 // 6435 // 1. <---settle/fail--- 6436 // 2. <-------sig------- 6437 // 3. --------sig------> (covers an add sent before step 1) 6438 // 4. <-------rev------- 6439 // 5. --------rev------> 6440 // 6. --------add------> 6441 // 7. - - - - sig - - -> 6442 // This represents an asynchronous commitment dance in which both sides are 6443 // sending signatures at the same time. In step 3, the signature does not 6444 // cover the recent settle/fail that Bob sent in step 1. However, the add that 6445 // Alice sends to Bob in step 6 does not overflow Bob's commitment transaction. 6446 // This is because validateCommitmentSanity counts the HTLC's by ignoring 6447 // HTLC's which will be removed in the next signature that Alice sends. Thus, 6448 // the add won't overflow. This is because the signature received in step 7 6449 // covers the settle/fail in step 1 and makes space for the add in step 6. 6450 func TestMaxAsynchronousHtlcs(t *testing.T) { 6451 t.Parallel() 6452 6453 // We'll kick off the test by creating our channels which both are 6454 // loaded with 5 BTC each. 6455 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6456 channeldb.SingleFunderTweaklessBit, 6457 ) 6458 if err != nil { 6459 t.Fatalf("unable to create test channels: %v", err) 6460 } 6461 defer cleanUp() 6462 6463 // One over the maximum number of HTLCs that either can accept. 6464 const numHTLCs = 12 6465 6466 // Set the remote's required MaxAcceptedHtlcs. This means that Alice 6467 // can only offer the remote up to numHTLCs HTLCs. 6468 aliceChannel.channelState.LocalChanCfg.MaxAcceptedHtlcs = numHTLCs 6469 bobChannel.channelState.RemoteChanCfg.MaxAcceptedHtlcs = numHTLCs 6470 6471 // Similarly, set the remote config's MaxAcceptedHtlcs. This means 6472 // that the remote will be aware that Bob will only accept up to 6473 // numHTLCs at a time. 6474 aliceChannel.channelState.RemoteChanCfg.MaxAcceptedHtlcs = numHTLCs 6475 bobChannel.channelState.LocalChanCfg.MaxAcceptedHtlcs = numHTLCs 6476 6477 // Each HTLC amount is 0.1 BTC. 6478 htlcAmt := lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 6479 6480 var htlcID uint64 6481 6482 // Send the maximum allowed number of HTLCs minus one. 6483 for i := 0; i < numHTLCs-1; i++ { 6484 htlc, _ := createHTLC(i, htlcAmt) 6485 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6486 t.Fatalf("unable to add htlc: %v", err) 6487 } 6488 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6489 t.Fatalf("unable to recv htlc: %v", err) 6490 } 6491 6492 // Just assign htlcID to the last received HTLC. 6493 htlcID = htlc.ID 6494 } 6495 6496 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6497 t.Fatalf("unable to transition state: %v", err) 6498 } 6499 6500 // Send an HTLC to Bob so that Bob's commitment transaction is full. 6501 htlc, _ := createHTLC(numHTLCs-1, htlcAmt) 6502 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6503 t.Fatalf("unable to add htlc: %v", err) 6504 } 6505 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6506 t.Fatalf("unable to recv htlc: %v", err) 6507 } 6508 6509 // Fail back an HTLC and sign a commitment as in steps 1 & 2. 6510 err = bobChannel.FailHTLC(htlcID, []byte{}, nil, nil, nil) 6511 if err != nil { 6512 t.Fatalf("unable to fail htlc: %v", err) 6513 } 6514 6515 if err := aliceChannel.ReceiveFailHTLC(htlcID, []byte{}); err != nil { 6516 t.Fatalf("unable to receive fail htlc: %v", err) 6517 } 6518 6519 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 6520 if err != nil { 6521 t.Fatalf("unable to sign next commitment: %v", err) 6522 } 6523 6524 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 6525 if err != nil { 6526 t.Fatalf("unable to receive new commitment: %v", err) 6527 } 6528 6529 // Cover the HTLC referenced with id equal to numHTLCs-1 with a new 6530 // signature (step 3). 6531 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 6532 if err != nil { 6533 t.Fatalf("unable to sign next commitment: %v", err) 6534 } 6535 6536 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 6537 if err != nil { 6538 t.Fatalf("unable to receive new commitment: %v", err) 6539 } 6540 6541 // Both sides exchange revocations as in step 4 & 5. 6542 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 6543 if err != nil { 6544 t.Fatalf("unable to revoke revocation: %v", err) 6545 } 6546 6547 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 6548 if err != nil { 6549 t.Fatalf("unable to receive revocation: %v", err) 6550 } 6551 6552 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 6553 if err != nil { 6554 t.Fatalf("unable to revoke revocation: %v", err) 6555 } 6556 6557 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 6558 if err != nil { 6559 t.Fatalf("unable to receive revocation: %v", err) 6560 } 6561 6562 // Send the final Add which should succeed as in step 6. 6563 htlc, _ = createHTLC(numHTLCs, htlcAmt) 6564 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6565 t.Fatalf("unable to add htlc: %v", err) 6566 } 6567 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6568 t.Fatalf("unable to recv htlc: %v", err) 6569 } 6570 6571 // Receiving the commitment should succeed as in step 7 since space was 6572 // made. 6573 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 6574 if err != nil { 6575 t.Fatalf("unable to sign next commitment: %v", err) 6576 } 6577 6578 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 6579 if err != nil { 6580 t.Fatalf("unable to receive new commitment: %v", err) 6581 } 6582 } 6583 6584 // TestMaxPendingAmount tests that the maximum overall pending HTLC value is met 6585 // given several HTLCs that, combined, exceed this value. An ErrMaxPendingAmount 6586 // error should be returned. 6587 func TestMaxPendingAmount(t *testing.T) { 6588 t.Parallel() 6589 6590 // We'll kick off the test by creating our channels which both are 6591 // loaded with 5 DCR each. 6592 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6593 channeldb.SingleFunderTweaklessBit, 6594 ) 6595 if err != nil { 6596 t.Fatalf("unable to create test channels: %v", err) 6597 } 6598 defer cleanUp() 6599 6600 // We set the remote required MaxPendingAmount to 3 DCR. We will 6601 // attempt to overflow this value and see if it gives us the 6602 // ErrMaxPendingAmount error. 6603 maxPending := lnwire.NewMAtomsFromAtoms(dcrutil.AtomsPerCoin * 3) 6604 6605 // We set the max pending amount of Alice's config. This mean that she 6606 // cannot offer Bob HTLCs with a total value above this limit at a given 6607 // time. 6608 aliceChannel.channelState.LocalChanCfg.MaxPendingAmount = maxPending 6609 bobChannel.channelState.RemoteChanCfg.MaxPendingAmount = maxPending 6610 6611 // First, we'll add 2 HTLCs of 1.5 DCR each to Alice's commitment. 6612 // This won't trigger Alice's ErrMaxPendingAmount error. 6613 const numHTLCs = 2 6614 htlcAmt := lnwire.NewMAtomsFromAtoms(1.5 * dcrutil.AtomsPerCoin) 6615 for i := 0; i < numHTLCs; i++ { 6616 htlc, _ := createHTLC(i, htlcAmt) 6617 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6618 t.Fatalf("unable to add htlc: %v", err) 6619 } 6620 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6621 t.Fatalf("unable to recv htlc: %v", err) 6622 } 6623 } 6624 6625 // We finally add one more HTLC of 0.1 DCR to Alice's commitment. This 6626 // SHOULD trigger Alice's ErrMaxPendingAmount error. 6627 htlcAmt = lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 6628 htlc, _ := createHTLC(numHTLCs, htlcAmt) 6629 _, err = aliceChannel.AddHTLC(htlc, nil) 6630 if err != ErrMaxPendingAmount { 6631 t.Fatalf("expected ErrMaxPendingAmount, instead received: %v", err) 6632 } 6633 6634 // And also Bob shouldn't be accepting this HTLC upon calling ReceiveHTLC. 6635 if _, err := bobChannel.ReceiveHTLC(htlc); err != ErrMaxPendingAmount { 6636 t.Fatalf("expected ErrMaxPendingAmount, instead received: %v", err) 6637 } 6638 } 6639 6640 func assertChannelBalances(t *testing.T, alice, bob *LightningChannel, 6641 aliceBalance, bobBalance dcrutil.Amount) { 6642 6643 _, _, line, _ := runtime.Caller(1) 6644 6645 aliceSelfBalance := alice.channelState.LocalCommitment.LocalBalance.ToAtoms() 6646 aliceBobBalance := alice.channelState.LocalCommitment.RemoteBalance.ToAtoms() 6647 if aliceSelfBalance != aliceBalance { 6648 t.Fatalf("line #%v: wrong alice self balance: expected %v, got %v", 6649 line, aliceBalance, aliceSelfBalance) 6650 } 6651 if aliceBobBalance != bobBalance { 6652 t.Fatalf("line #%v: wrong alice bob's balance: expected %v, got %v", 6653 line, bobBalance, aliceBobBalance) 6654 } 6655 6656 bobSelfBalance := bob.channelState.LocalCommitment.LocalBalance.ToAtoms() 6657 bobAliceBalance := bob.channelState.LocalCommitment.RemoteBalance.ToAtoms() 6658 if bobSelfBalance != bobBalance { 6659 t.Fatalf("line #%v: wrong bob self balance: expected %v, got %v", 6660 line, bobBalance, bobSelfBalance) 6661 } 6662 if bobAliceBalance != aliceBalance { 6663 t.Fatalf("line #%v: wrong alice bob's balance: expected %v, got %v", 6664 line, aliceBalance, bobAliceBalance) 6665 } 6666 } 6667 6668 // TestChanReserve tests that the ErrBelowChanReserve error is thrown when an 6669 // HTLC is added that causes a node's balance to dip below its channel reserve 6670 // limit. 6671 func TestChanReserve(t *testing.T) { 6672 t.Parallel() 6673 6674 setupChannels := func() (*LightningChannel, *LightningChannel, func()) { 6675 // We'll kick off the test by creating our channels which both 6676 // are loaded with 5 DCR each. 6677 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6678 channeldb.SingleFunderTweaklessBit, 6679 ) 6680 if err != nil { 6681 t.Fatalf("unable to create test channels: %v", err) 6682 } 6683 6684 // We set the remote required ChanReserve to 0.5 DCR. We will 6685 // attempt to cause Alice's balance to dip below this amount 6686 // and test whether it triggers the ErrBelowChanReserve error. 6687 aliceMinReserve := dcrutil.Amount(0.5 * 6688 dcrutil.AtomsPerCoin) 6689 6690 // Alice will need to keep her reserve above aliceMinReserve, 6691 // so set this limit to here local config. 6692 aliceChannel.channelState.LocalChanCfg.ChanReserve = aliceMinReserve 6693 6694 // During channel opening Bob will also get to know Alice's 6695 // minimum reserve, and this will be found in his remote 6696 // config. 6697 bobChannel.channelState.RemoteChanCfg.ChanReserve = aliceMinReserve 6698 6699 // We set Bob's channel reserve to a value that is larger than 6700 // his current balance in the channel. This will ensure that 6701 // after a channel is first opened, Bob can still receive HTLCs 6702 // even though his balance is less than his channel reserve. 6703 bobMinReserve := dcrutil.Amount(6 * dcrutil.AtomsPerCoin) 6704 bobChannel.channelState.LocalChanCfg.ChanReserve = bobMinReserve 6705 aliceChannel.channelState.RemoteChanCfg.ChanReserve = bobMinReserve 6706 6707 return aliceChannel, bobChannel, cleanUp 6708 } 6709 aliceChannel, bobChannel, cleanUp := setupChannels() 6710 defer cleanUp() 6711 6712 aliceIndex := 0 6713 bobIndex := 0 6714 6715 // Add an HTLC that will increase Bob's balance. This should succeed, 6716 // since Alice stays above her channel reserve, and Bob increases his 6717 // balance (while still being below his channel reserve). 6718 // 6719 // Resulting balances: 6720 // Alice: 4.5 6721 // Bob: 5.0 6722 htlcAmt := lnwire.NewMAtomsFromAtoms(0.5 * dcrutil.AtomsPerCoin) 6723 htlc, _ := createHTLC(aliceIndex, htlcAmt) 6724 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6725 t.Fatalf("unable to add htlc: %v", err) 6726 } 6727 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6728 t.Fatalf("unable to recv htlc: %v", err) 6729 } 6730 6731 // Force a state transition, making sure this HTLC is considered valid 6732 // even though the channel reserves are not met. 6733 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6734 t.Fatalf("unable to complete state update: %v", err) 6735 } 6736 6737 commitFee := aliceChannel.channelState.LocalCommitment.CommitFee 6738 assertChannelBalances( 6739 t, aliceChannel, bobChannel, 6740 dcrutil.AtomsPerCoin*4.5-commitFee, dcrutil.AtomsPerCoin*5, 6741 ) 6742 6743 // Now let Bob try to add an HTLC. This should fail, since it will 6744 // decrease his balance, which is already below the channel reserve. 6745 // 6746 // Resulting balances: 6747 // Alice: 4.5 6748 // Bob: 5.0 6749 htlc, _ = createHTLC(bobIndex, htlcAmt) 6750 _, err := bobChannel.AddHTLC(htlc, nil) 6751 if err != ErrBelowChanReserve { 6752 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6753 } 6754 6755 // Alice will reject this htlc upon receiving the htlc. 6756 if _, err := aliceChannel.ReceiveHTLC(htlc); err != ErrBelowChanReserve { 6757 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6758 } 6759 6760 // We must setup the channels again, since a violation of the channel 6761 // constraints leads to channel shutdown. 6762 aliceChannel, bobChannel, cleanUp = setupChannels() 6763 defer cleanUp() 6764 6765 aliceIndex = 0 6766 6767 // Now we'll add HTLC of 3.5 DCR to Alice's commitment, this should put 6768 // Alice's balance at 1.5 DCR. 6769 // 6770 // Resulting balances: 6771 // Alice: 1.5 6772 // Bob: 9.5 6773 htlcAmt = lnwire.NewMAtomsFromAtoms(3.5 * dcrutil.AtomsPerCoin) 6774 6775 // The first HTLC should successfully be sent. 6776 htlc, _ = createHTLC(aliceIndex, htlcAmt) 6777 aliceIndex++ 6778 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 6779 t.Fatalf("unable to add htlc: %v", err) 6780 } 6781 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 6782 t.Fatalf("unable to recv htlc: %v", err) 6783 } 6784 6785 // Add a second HTLC of 1 DCR. This should fail because it will take 6786 // Alice's balance all the way down to her channel reserve, but since 6787 // she is the initiator the additional transaction fee makes her 6788 // balance dip below. 6789 htlcAmt = lnwire.NewMAtomsFromAtoms(1 * dcrutil.AtomsPerCoin) 6790 htlc, _ = createHTLC(aliceIndex, htlcAmt) 6791 _, err = aliceChannel.AddHTLC(htlc, nil) 6792 if err != ErrBelowChanReserve { 6793 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6794 } 6795 6796 // Likewise, Bob will reject receiving the htlc because of the same reason. 6797 if _, err := bobChannel.ReceiveHTLC(htlc); err != ErrBelowChanReserve { 6798 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6799 } 6800 6801 // We must setup the channels again, since a violation of the channel 6802 // constraints leads to channel shutdown. 6803 aliceChannel, bobChannel, cleanUp = setupChannels() 6804 defer cleanUp() 6805 6806 aliceIndex = 0 6807 bobIndex = 0 6808 6809 // Add a HTLC of 2 DCR to Alice, and the settle it. 6810 // Resulting balances: 6811 // Alice: 3.0 6812 // Bob: 7.0 6813 htlcAmt = lnwire.NewMAtomsFromAtoms(2 * dcrutil.AtomsPerCoin) 6814 htlc, preimage := createHTLC(aliceIndex, htlcAmt) 6815 aliceHtlcIndex, err := aliceChannel.AddHTLC(htlc, nil) 6816 if err != nil { 6817 t.Fatalf("unable to add htlc: %v", err) 6818 } 6819 bobHtlcIndex, err := bobChannel.ReceiveHTLC(htlc) 6820 if err != nil { 6821 t.Fatalf("unable to recv htlc: %v", err) 6822 } 6823 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 6824 t.Fatalf("unable to complete state update: %v", err) 6825 } 6826 6827 commitFee = aliceChannel.channelState.LocalCommitment.CommitFee 6828 assertChannelBalances( 6829 t, aliceChannel, bobChannel, 6830 dcrutil.AtomsPerCoin*3-commitFee, dcrutil.AtomsPerCoin*5, 6831 ) 6832 6833 if err := bobChannel.SettleHTLC(preimage, bobHtlcIndex, nil, nil, nil); err != nil { 6834 t.Fatalf("bob unable to settle inbound htlc: %v", err) 6835 } 6836 if err := aliceChannel.ReceiveHTLCSettle(preimage, aliceHtlcIndex); err != nil { 6837 t.Fatalf("alice unable to accept settle of outbound htlc: %v", err) 6838 } 6839 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 6840 t.Fatalf("unable to complete state update: %v", err) 6841 } 6842 6843 commitFee = aliceChannel.channelState.LocalCommitment.CommitFee 6844 assertChannelBalances( 6845 t, aliceChannel, bobChannel, 6846 dcrutil.AtomsPerCoin*3-commitFee, dcrutil.AtomsPerCoin*7, 6847 ) 6848 6849 // And now let Bob add an HTLC of 1 DCR. This will take Bob's balance 6850 // all the way down to his channel reserve, but since he is not paying 6851 // the fee this is okay. 6852 htlcAmt = lnwire.NewMAtomsFromAtoms(1 * dcrutil.AtomsPerCoin) 6853 htlc, _ = createHTLC(bobIndex, htlcAmt) 6854 if _, err := bobChannel.AddHTLC(htlc, nil); err != nil { 6855 t.Fatalf("unable to add htlc: %v", err) 6856 } 6857 if _, err := aliceChannel.ReceiveHTLC(htlc); err != nil { 6858 t.Fatalf("unable to recv htlc: %v", err) 6859 } 6860 6861 // Do a last state transition, which should succeed. 6862 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 6863 t.Fatalf("unable to complete state update: %v", err) 6864 } 6865 6866 commitFee = aliceChannel.channelState.LocalCommitment.CommitFee 6867 assertChannelBalances( 6868 t, aliceChannel, bobChannel, 6869 dcrutil.AtomsPerCoin*3-commitFee, dcrutil.AtomsPerCoin*6, 6870 ) 6871 } 6872 6873 // TestChanReserveRemoteInitiator tests that the channel reserve of the 6874 // initiator is accounted for when adding HTLCs, whether the initiator is the 6875 // local or remote node. 6876 func TestChanReserveRemoteInitiator(t *testing.T) { 6877 t.Parallel() 6878 6879 // We start out with a channel where both parties have 5 BTC. 6880 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6881 channeldb.SingleFunderTweaklessBit, 6882 ) 6883 if err != nil { 6884 t.Fatal(err) 6885 } 6886 defer cleanUp() 6887 6888 // Set Alice's channel reserve to be 5 BTC-commitfee. This means she 6889 // has just enough balance to cover the comitment fee, but not enough 6890 // to add any more HTLCs to the commitment. Although a reserve this 6891 // high is unrealistic, a channel can easiliy get into a situation 6892 // where the initiator cannot pay for the fee of any more HTLCs. 6893 commitFee := aliceChannel.channelState.LocalCommitment.CommitFee 6894 aliceMinReserve := 5*dcrutil.AtomsPerCoin - commitFee 6895 6896 aliceChannel.channelState.LocalChanCfg.ChanReserve = aliceMinReserve 6897 bobChannel.channelState.RemoteChanCfg.ChanReserve = aliceMinReserve 6898 6899 // Now let Bob attempt to add an HTLC of 0.1 BTC. He has plenty of 6900 // money available to spend, but Alice, which is the initiator, cannot 6901 // afford any more HTLCs on the commitment transaction because that 6902 // would take here below her channel reserve.. 6903 htlcAmt := lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 6904 htlc, _ := createHTLC(0, htlcAmt) 6905 6906 // Bob should refuse to add this HTLC, since he realizes it will create 6907 // an invalid commitment. 6908 _, err = bobChannel.AddHTLC(htlc, nil) 6909 if err != ErrBelowChanReserve { 6910 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", 6911 err) 6912 } 6913 6914 // Of course Alice will also not have enough balance to add it herself. 6915 _, err = aliceChannel.AddHTLC(htlc, nil) 6916 if err != ErrBelowChanReserve { 6917 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", 6918 err) 6919 } 6920 6921 // Same for Alice, she should refuse to accept this second HTLC. 6922 if _, err := aliceChannel.ReceiveHTLC(htlc); err != ErrBelowChanReserve { 6923 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6924 } 6925 } 6926 6927 // TestChanReserveLocalInitiatorDustHtlc tests that fee the initiator must pay 6928 // when adding HTLCs is accounted for, even though the HTLC is considered dust 6929 // by the remote bode. 6930 func TestChanReserveLocalInitiatorDustHtlc(t *testing.T) { 6931 t.Parallel() 6932 6933 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6934 channeldb.SingleFunderTweaklessBit, 6935 ) 6936 if err != nil { 6937 t.Fatal(err) 6938 } 6939 defer cleanUp() 6940 6941 // The amount of the HTLC should not be considered dust according to 6942 // Alice's dust limit (6030 atoms), but be dust according to Bob's dust 6943 // limit (12060 atoms). It is considered dust if the amount remaining 6944 // after paying the HTLC fee is below the dustlimit, so we choose a 6945 // size of 7000+htlcFee. 6946 htlcSat := dcrutil.Amount(7000) + HtlcTimeoutFee( 6947 aliceChannel.channelState.ChanType, 6948 chainfee.AtomPerKByte( 6949 aliceChannel.channelState.LocalCommitment.FeePerKB, 6950 ), 6951 ) 6952 6953 // Set Alice's channel reserve to be low enough to carry the value of 6954 // the HTLC, but not low enough to allow the extra fee from adding the 6955 // HTLC to the commitment. 6956 commitFee := aliceChannel.channelState.LocalCommitment.CommitFee 6957 aliceMinReserve := 5*dcrutil.AtomsPerCoin - commitFee - htlcSat 6958 6959 aliceChannel.channelState.LocalChanCfg.ChanReserve = aliceMinReserve 6960 bobChannel.channelState.RemoteChanCfg.ChanReserve = aliceMinReserve 6961 6962 htlcDustAmt := lnwire.NewMAtomsFromAtoms(htlcSat) 6963 htlc, _ := createHTLC(0, htlcDustAmt) 6964 6965 // Alice should realize that the fee she must pay to add this HTLC to 6966 // the local commitment would take her below the channel reserve. 6967 _, err = aliceChannel.AddHTLC(htlc, nil) 6968 if err != ErrBelowChanReserve { 6969 t.Fatalf("expected ErrBelowChanReserve, instead received: %v", err) 6970 } 6971 } 6972 6973 // TestMinHTLC tests that the ErrBelowMinHTLC error is thrown if an HTLC is added 6974 // that is below the minimm allowed value for HTLCs. 6975 func TestMinHTLC(t *testing.T) { 6976 t.Parallel() 6977 6978 // We'll kick off the test by creating our channels which both are 6979 // loaded with 5 DCR each. 6980 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 6981 channeldb.SingleFunderTweaklessBit, 6982 ) 6983 if err != nil { 6984 t.Fatalf("unable to create test channels: %v", err) 6985 } 6986 defer cleanUp() 6987 6988 // We set Alice's MinHTLC to 0.1 DCR. We will attempt to send an 6989 // HTLC BELOW this value to trigger the ErrBelowMinHTLC error. 6990 minValue := lnwire.NewMAtomsFromAtoms(0.1 * dcrutil.AtomsPerCoin) 6991 6992 // Setting the min value in Alice's local config means that the 6993 // remote will not accept any HTLCs of value less than specified. 6994 aliceChannel.channelState.LocalChanCfg.MinHTLC = minValue 6995 bobChannel.channelState.RemoteChanCfg.MinHTLC = minValue 6996 6997 // First, we will add an HTLC of 0.5 DCR. This will not trigger 6998 // ErrBelowMinHTLC. 6999 htlcAmt := lnwire.NewMAtomsFromAtoms(0.5 * dcrutil.AtomsPerCoin) 7000 htlc, _ := createHTLC(0, htlcAmt) 7001 if _, err := aliceChannel.AddHTLC(htlc, nil); err != nil { 7002 t.Fatalf("unable to add htlc: %v", err) 7003 } 7004 if _, err := bobChannel.ReceiveHTLC(htlc); err != nil { 7005 t.Fatalf("unable to recv htlc: %v", err) 7006 } 7007 7008 // We add an HTLC below the min value, this should result in 7009 // an ErrBelowMinHTLC error. 7010 amt := minValue - 100 7011 htlc, _ = createHTLC(1, amt) 7012 _, err = aliceChannel.AddHTLC(htlc, nil) 7013 if err != ErrBelowMinHTLC { 7014 t.Fatalf("expected ErrBelowMinHTLC, instead received: %v", err) 7015 } 7016 7017 // Bob will receive this HTLC, but reject the next received htlc, since 7018 // the htlc is too small. 7019 _, err = bobChannel.ReceiveHTLC(htlc) 7020 if err != ErrBelowMinHTLC { 7021 t.Fatalf("expected ErrBelowMinHTLC, instead received: %v", err) 7022 } 7023 } 7024 7025 // TestInvalidHTLCAmt tests that ErrInvalidHTLCAmt is returned when trying to 7026 // add HTLCs that don't carry a positive value. 7027 func TestInvalidHTLCAmt(t *testing.T) { 7028 t.Parallel() 7029 7030 // We'll kick off the test by creating our channels which both are 7031 // loaded with 5 BTC each. 7032 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7033 channeldb.SingleFunderTweaklessBit, 7034 ) 7035 if err != nil { 7036 t.Fatalf("unable to create test channels: %v", err) 7037 } 7038 defer cleanUp() 7039 7040 // We'll set the min HTLC values for each party to zero, which 7041 // technically would permit zero-value HTLCs. 7042 aliceChannel.channelState.LocalChanCfg.MinHTLC = 0 7043 bobChannel.channelState.RemoteChanCfg.MinHTLC = 0 7044 7045 // Create a zero-value HTLC. 7046 htlcAmt := lnwire.MilliAtom(0) 7047 htlc, _ := createHTLC(0, htlcAmt) 7048 7049 // Sending or receiving the HTLC should fail with ErrInvalidHTLCAmt. 7050 _, err = aliceChannel.AddHTLC(htlc, nil) 7051 if err != ErrInvalidHTLCAmt { 7052 t.Fatalf("expected ErrInvalidHTLCAmt, got: %v", err) 7053 } 7054 _, err = bobChannel.ReceiveHTLC(htlc) 7055 if err != ErrInvalidHTLCAmt { 7056 t.Fatalf("expected ErrInvalidHTLCAmt, got: %v", err) 7057 } 7058 } 7059 7060 // TestNewBreachRetributionSkipsDustHtlcs ensures that in the case of a 7061 // contract breach, all dust HTLCs are ignored and not reflected in the 7062 // produced BreachRetribution struct. We ignore these HTLCs as they aren't 7063 // actually manifested on the commitment transaction, as a result we can't 7064 // actually revoked them. 7065 func TestNewBreachRetributionSkipsDustHtlcs(t *testing.T) { 7066 t.Parallel() 7067 7068 // We'll kick off the test by creating our channels which both are 7069 // loaded with 5 DCR each. 7070 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7071 channeldb.SingleFunderTweaklessBit, 7072 ) 7073 if err != nil { 7074 t.Fatalf("unable to create test channels: %v", err) 7075 } 7076 defer cleanUp() 7077 7078 var fakeOnionBlob [lnwire.OnionPacketSize]byte 7079 copy(fakeOnionBlob[:], bytes.Repeat([]byte{0x05}, lnwire.OnionPacketSize)) 7080 7081 // We'll modify the dust settings on both channels to be a predictable 7082 // value for the prurpose of the test. 7083 dustValue := dcrutil.Amount(200) 7084 aliceChannel.channelState.LocalChanCfg.DustLimit = dustValue 7085 aliceChannel.channelState.RemoteChanCfg.DustLimit = dustValue 7086 bobChannel.channelState.LocalChanCfg.DustLimit = dustValue 7087 bobChannel.channelState.RemoteChanCfg.DustLimit = dustValue 7088 7089 // We'll now create a series of dust HTLC's, and send then from Alice 7090 // to Bob, finally locking both of them in. 7091 var bobPreimage [32]byte 7092 copy(bobPreimage[:], bytes.Repeat([]byte{0xbb}, 32)) 7093 for i := 0; i < 3; i++ { 7094 rHash := sha256.Sum256(bobPreimage[:]) 7095 h := &lnwire.UpdateAddHTLC{ 7096 PaymentHash: rHash, 7097 Amount: lnwire.NewMAtomsFromAtoms(dustValue), 7098 Expiry: uint32(10), 7099 OnionBlob: fakeOnionBlob, 7100 } 7101 7102 htlcIndex, err := aliceChannel.AddHTLC(h, nil) 7103 if err != nil { 7104 t.Fatalf("unable to add bob's htlc: %v", err) 7105 } 7106 7107 h.ID = htlcIndex 7108 if _, err := bobChannel.ReceiveHTLC(h); err != nil { 7109 t.Fatalf("unable to recv bob's htlc: %v", err) 7110 } 7111 } 7112 7113 // With the HTLC's applied to both update logs, we'll initiate a state 7114 // transition from Alice. 7115 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 7116 t.Fatalf("unable to complete alice's state transition: %v", err) 7117 } 7118 7119 // At this point, we'll capture the current state number, as well as 7120 // the current commitment. 7121 revokedStateNum := aliceChannel.channelState.LocalCommitment.CommitHeight 7122 7123 // We'll now have Bob settle those HTLC's to Alice and then advance 7124 // forward to a new state. 7125 for i := 0; i < 3; i++ { 7126 err := bobChannel.SettleHTLC(bobPreimage, uint64(i), nil, nil, nil) 7127 if err != nil { 7128 t.Fatalf("unable to settle htlc: %v", err) 7129 } 7130 err = aliceChannel.ReceiveHTLCSettle(bobPreimage, uint64(i)) 7131 if err != nil { 7132 t.Fatalf("unable to settle htlc: %v", err) 7133 } 7134 } 7135 if err := ForceStateTransition(bobChannel, aliceChannel); err != nil { 7136 t.Fatalf("unable to complete bob's state transition: %v", err) 7137 } 7138 7139 // At this point, we'll now simulate a contract breach by Bob using the 7140 // NewBreachRetribution method. 7141 breachRet, err := NewBreachRetribution( 7142 aliceChannel.channelState, revokedStateNum, 100, 7143 ) 7144 if err != nil { 7145 t.Fatalf("unable to create breach retribution: %v", err) 7146 } 7147 7148 // The retribution shouldn't have any HTLCs set as they were all below 7149 // dust for both parties. 7150 if len(breachRet.HtlcRetributions) != 0 { 7151 t.Fatalf("zero HTLC retributions should have been created, "+ 7152 "instead %v were", len(breachRet.HtlcRetributions)) 7153 } 7154 } 7155 7156 // compareHtlcs compares two PaymentDescriptors. 7157 func compareHtlcs(htlc1, htlc2 *PaymentDescriptor) error { 7158 if htlc1.LogIndex != htlc2.LogIndex { 7159 return fmt.Errorf("htlc log index did not match") 7160 } 7161 if htlc1.HtlcIndex != htlc2.HtlcIndex { 7162 return fmt.Errorf("htlc index did not match") 7163 } 7164 if htlc1.ParentIndex != htlc2.ParentIndex { 7165 return fmt.Errorf("htlc parent index did not match") 7166 } 7167 7168 if htlc1.RHash != htlc2.RHash { 7169 return fmt.Errorf("htlc rhash did not match") 7170 } 7171 return nil 7172 } 7173 7174 // compareIndexes is a helper method to compare two index maps. 7175 func compareIndexes(a, b map[uint64]*list.Element) error { 7176 for k1, e1 := range a { 7177 e2, ok := b[k1] 7178 if !ok { 7179 return fmt.Errorf("element with key %d "+ 7180 "not found in b", k1) 7181 } 7182 htlc1, htlc2 := e1.Value.(*PaymentDescriptor), e2.Value.(*PaymentDescriptor) 7183 if err := compareHtlcs(htlc1, htlc2); err != nil { 7184 return err 7185 } 7186 } 7187 7188 for k1, e1 := range b { 7189 e2, ok := a[k1] 7190 if !ok { 7191 return fmt.Errorf("element with key %d not "+ 7192 "found in a", k1) 7193 } 7194 htlc1, htlc2 := e1.Value.(*PaymentDescriptor), e2.Value.(*PaymentDescriptor) 7195 if err := compareHtlcs(htlc1, htlc2); err != nil { 7196 return err 7197 } 7198 } 7199 7200 return nil 7201 } 7202 7203 // compareLogs is a helper method to compare two updateLogs. 7204 func compareLogs(a, b *updateLog) error { 7205 if a.logIndex != b.logIndex { 7206 return fmt.Errorf("log indexes don't match: %d vs %d", 7207 a.logIndex, b.logIndex) 7208 } 7209 7210 if a.htlcCounter != b.htlcCounter { 7211 return fmt.Errorf("htlc counters don't match: %d vs %d", 7212 a.htlcCounter, b.htlcCounter) 7213 } 7214 7215 if err := compareIndexes(a.updateIndex, b.updateIndex); err != nil { 7216 return fmt.Errorf("update indexes don't match: %v", err) 7217 } 7218 if err := compareIndexes(a.htlcIndex, b.htlcIndex); err != nil { 7219 return fmt.Errorf("htlc indexes don't match: %v", err) 7220 } 7221 7222 if a.Len() != b.Len() { 7223 return fmt.Errorf("list lengths not equal: %d vs %d", 7224 a.Len(), b.Len()) 7225 } 7226 7227 e1, e2 := a.Front(), b.Front() 7228 for ; e1 != nil; e1, e2 = e1.Next(), e2.Next() { 7229 htlc1, htlc2 := e1.Value.(*PaymentDescriptor), e2.Value.(*PaymentDescriptor) 7230 if err := compareHtlcs(htlc1, htlc2); err != nil { 7231 return err 7232 } 7233 } 7234 7235 return nil 7236 } 7237 7238 // TestChannelRestoreUpdateLogs makes sure we are able to properly restore the 7239 // update logs in the case where a different number of HTLCs are locked in on 7240 // the local, remote and pending remote commitment. 7241 func TestChannelRestoreUpdateLogs(t *testing.T) { 7242 t.Parallel() 7243 7244 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7245 channeldb.SingleFunderTweaklessBit, 7246 ) 7247 if err != nil { 7248 t.Fatalf("unable to create test channels: %v", err) 7249 } 7250 defer cleanUp() 7251 7252 // First, we'll add an HTLC from Alice to Bob, which we will lock in on 7253 // Bob's commit, but not on Alice's. 7254 htlcAmount := lnwire.NewMAtomsFromAtoms(20000) 7255 htlcAlice, _ := createHTLC(0, htlcAmount) 7256 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7257 t.Fatalf("alice unable to add htlc: %v", err) 7258 } 7259 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 7260 t.Fatalf("bob unable to recv add htlc: %v", err) 7261 } 7262 7263 // Let Alice sign a new state, which will include the HTLC just sent. 7264 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 7265 if err != nil { 7266 t.Fatalf("unable to sign commitment: %v", err) 7267 } 7268 7269 // Bob receives this commitment signature, and revokes his old state. 7270 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 7271 if err != nil { 7272 t.Fatalf("unable to receive commitment: %v", err) 7273 } 7274 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 7275 if err != nil { 7276 t.Fatalf("unable to revoke commitment: %v", err) 7277 } 7278 7279 // When Alice now receives this revocation, she will advance her remote 7280 // commitment chain to the commitment which includes the HTLC just 7281 // sent. However her local commitment chain still won't include the 7282 // state with the HTLC, since she hasn't received a new commitment 7283 // signature from Bob yet. 7284 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 7285 if err != nil { 7286 t.Fatalf("unable to recive revocation: %v", err) 7287 } 7288 7289 // Now make Alice send and sign an additional HTLC. We don't let Bob 7290 // receive it. We do this since we want to check that update logs are 7291 // restored properly below, and we'll only restore updates that have 7292 // been ACKed. 7293 htlcAlice, _ = createHTLC(1, htlcAmount) 7294 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7295 t.Fatalf("alice unable to add htlc: %v", err) 7296 } 7297 7298 // Send the signature covering the HTLC. This is okay, since the local 7299 // and remote commit chains are updated in an async fashion. Since the 7300 // remote chain was updated with the latest state (since Bob sent the 7301 // revocation earlier) we can keep advancing the remote commit chain. 7302 _, _, _, err = aliceChannel.SignNextCommitment() 7303 if err != nil { 7304 t.Fatalf("unable to sign commitment: %v", err) 7305 } 7306 7307 // After Alice has signed this commitment, her local commitment will 7308 // contain no HTLCs, her remote commitment will contain an HTLC with 7309 // index 0, and the pending remote commitment (a signed remote 7310 // commitment which is not AKCed yet) will contain an additional HTLC 7311 // with index 1. 7312 7313 // We now re-create the channels, mimicking a restart. This should sync 7314 // the update logs up to the correct state set up above. 7315 newAliceChannel, err := NewLightningChannel( 7316 aliceChannel.Signer, aliceChannel.channelState, 7317 aliceChannel.sigPool, testChainParams, 7318 ) 7319 if err != nil { 7320 t.Fatalf("unable to create new channel: %v", err) 7321 } 7322 7323 newBobChannel, err := NewLightningChannel( 7324 bobChannel.Signer, bobChannel.channelState, 7325 bobChannel.sigPool, testChainParams, 7326 ) 7327 if err != nil { 7328 t.Fatalf("unable to create new channel: %v", err) 7329 } 7330 7331 // compare all the logs between the old and new channels, to make sure 7332 // they all got restored properly. 7333 err = compareLogs(aliceChannel.localUpdateLog, 7334 newAliceChannel.localUpdateLog) 7335 if err != nil { 7336 t.Fatalf("alice local log not restored: %v", err) 7337 } 7338 7339 err = compareLogs(aliceChannel.remoteUpdateLog, 7340 newAliceChannel.remoteUpdateLog) 7341 if err != nil { 7342 t.Fatalf("alice remote log not restored: %v", err) 7343 } 7344 7345 err = compareLogs(bobChannel.localUpdateLog, 7346 newBobChannel.localUpdateLog) 7347 if err != nil { 7348 t.Fatalf("bob local log not restored: %v", err) 7349 } 7350 7351 err = compareLogs(bobChannel.remoteUpdateLog, 7352 newBobChannel.remoteUpdateLog) 7353 if err != nil { 7354 t.Fatalf("bob remote log not restored: %v", err) 7355 } 7356 } 7357 7358 // fetchNumUpdates counts the number of updateType in the log. 7359 func fetchNumUpdates(t updateType, log *updateLog) int { 7360 num := 0 7361 for e := log.Front(); e != nil; e = e.Next() { 7362 htlc := e.Value.(*PaymentDescriptor) 7363 if htlc.EntryType == t { 7364 num++ 7365 } 7366 } 7367 return num 7368 } 7369 7370 // assertInLog checks that the given log contains the expected number of Adds 7371 // and Fails. 7372 func assertInLog(t *testing.T, log *updateLog, numAdds, numFails int) { 7373 adds := fetchNumUpdates(Add, log) 7374 if adds != numAdds { 7375 t.Fatalf("expected %d adds, found %d", numAdds, adds) 7376 } 7377 fails := fetchNumUpdates(Fail, log) 7378 if fails != numFails { 7379 t.Fatalf("expected %d fails, found %d", numFails, fails) 7380 } 7381 } 7382 7383 // assertInLogs asserts that the expected number of Adds and Fails occurs in 7384 // the local and remote update log of the given channel. 7385 func assertInLogs(t *testing.T, channel *LightningChannel, numAddsLocal, 7386 numFailsLocal, numAddsRemote, numFailsRemote int) { 7387 assertInLog(t, channel.localUpdateLog, numAddsLocal, numFailsLocal) 7388 assertInLog(t, channel.remoteUpdateLog, numAddsRemote, numFailsRemote) 7389 } 7390 7391 // restoreAndAssert creates a new LightningChannel from the given channel's 7392 // state, and asserts that the new channel has had its logs restored to the 7393 // expected state. 7394 func restoreAndAssert(t *testing.T, channel *LightningChannel, numAddsLocal, 7395 numFailsLocal, numAddsRemote, numFailsRemote int) { 7396 7397 newChannel, err := NewLightningChannel( 7398 channel.Signer, channel.channelState, 7399 channel.sigPool, testChainParams, 7400 ) 7401 if err != nil { 7402 t.Fatalf("unable to create new channel: %v", err) 7403 } 7404 7405 assertInLog(t, newChannel.localUpdateLog, numAddsLocal, numFailsLocal) 7406 assertInLog(t, newChannel.remoteUpdateLog, numAddsRemote, numFailsRemote) 7407 } 7408 7409 // TestChannelRestoreUpdateLogsFailedHTLC runs through a scenario where an 7410 // HTLC is added and failed, and asserts along the way that we would restore 7411 // the update logs of the channel to the expected state at any point. 7412 func TestChannelRestoreUpdateLogsFailedHTLC(t *testing.T) { 7413 t.Parallel() 7414 7415 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7416 channeldb.SingleFunderTweaklessBit, 7417 ) 7418 if err != nil { 7419 t.Fatalf("unable to create test channels: %v", err) 7420 } 7421 defer cleanUp() 7422 7423 // First, we'll add an HTLC from Alice to Bob, and lock it in for both. 7424 htlcAmount := lnwire.NewMAtomsFromAtoms(20000) 7425 htlcAlice, _ := createHTLC(0, htlcAmount) 7426 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7427 t.Fatalf("alice unable to add htlc: %v", err) 7428 } 7429 // The htlc Alice sent should be in her local update log. 7430 assertInLogs(t, aliceChannel, 1, 0, 0, 0) 7431 7432 // A restore at this point should NOT restore this update, as it is not 7433 // locked in anywhere yet. 7434 restoreAndAssert(t, aliceChannel, 0, 0, 0, 0) 7435 7436 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 7437 t.Fatalf("bob unable to recv add htlc: %v", err) 7438 } 7439 7440 // Lock in the Add on both sides. 7441 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 7442 t.Fatalf("unable to complete state update: %v", err) 7443 } 7444 7445 // Since it is locked in, Alice should have the Add in the local log, 7446 // and it should be restored during restoration. 7447 assertInLogs(t, aliceChannel, 1, 0, 0, 0) 7448 restoreAndAssert(t, aliceChannel, 1, 0, 0, 0) 7449 7450 // Now we make Bob fail this HTLC. 7451 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 7452 if err != nil { 7453 t.Fatalf("unable to cancel HTLC: %v", err) 7454 } 7455 7456 err = aliceChannel.ReceiveFailHTLC(0, []byte("failreason")) 7457 if err != nil { 7458 t.Fatalf("unable to recv htlc cancel: %v", err) 7459 } 7460 7461 // This Fail update should have been added to Alice's remote update log. 7462 assertInLogs(t, aliceChannel, 1, 0, 0, 1) 7463 7464 // Restoring should restore the HTLC added to Alice's local log, but 7465 // NOT the Fail sent by Bob, since it is not locked in. 7466 restoreAndAssert(t, aliceChannel, 1, 0, 0, 0) 7467 7468 // Bob sends a signature. 7469 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 7470 if err != nil { 7471 t.Fatalf("unable to sign commitment: %v", err) 7472 } 7473 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 7474 if err != nil { 7475 t.Fatalf("unable to receive commitment: %v", err) 7476 } 7477 7478 // When Alice receives Bob's new commitment, the logs will stay the 7479 // same until she revokes her old state. The Fail will still not be 7480 // restored during a restoration. 7481 assertInLogs(t, aliceChannel, 1, 0, 0, 1) 7482 restoreAndAssert(t, aliceChannel, 1, 0, 0, 0) 7483 7484 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 7485 if err != nil { 7486 t.Fatalf("unable to revoke commitment: %v", err) 7487 } 7488 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 7489 if err != nil { 7490 t.Fatalf("bob unable to process alice's revocation: %v", err) 7491 } 7492 7493 // At this point Alice has advanced her local commitment chain to a 7494 // commitment with no HTLCs left. The current state on her remote 7495 // commitment chain, however, still has the HTLC active, as she hasn't 7496 // sent a new signature yet. If we'd now restart and restore, the htlc 7497 // failure update should still be waiting for inclusion in Alice's next 7498 // signature. Otherwise the produced signature would be invalid. 7499 assertInLogs(t, aliceChannel, 1, 0, 0, 1) 7500 restoreAndAssert(t, aliceChannel, 1, 0, 0, 1) 7501 7502 // Now send a signature from Alice. This will give Bob a new commitment 7503 // where the HTLC is removed. 7504 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 7505 if err != nil { 7506 t.Fatalf("unable to sign commitment: %v", err) 7507 } 7508 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 7509 if err != nil { 7510 t.Fatalf("unable to receive commitment: %v", err) 7511 } 7512 7513 // When sending a new commitment, Alice will add a pending commit to 7514 // her remote chain. Since the unsigned acked updates aren't deleted 7515 // until we receive a revocation, the fail should still be present. 7516 assertInLogs(t, aliceChannel, 1, 0, 0, 1) 7517 restoreAndAssert(t, aliceChannel, 1, 0, 0, 1) 7518 7519 // When Alice receives Bob's revocation, the Fail is irrevocably locked 7520 // in on both sides. She should compact the logs, removing the HTLC and 7521 // the corresponding Fail from the local update log. 7522 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 7523 if err != nil { 7524 t.Fatalf("unable to revoke commitment: %v", err) 7525 } 7526 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 7527 if err != nil { 7528 t.Fatalf("unable to receive revocation: %v", err) 7529 } 7530 7531 assertInLogs(t, aliceChannel, 0, 0, 0, 0) 7532 restoreAndAssert(t, aliceChannel, 0, 0, 0, 0) 7533 } 7534 7535 // TestDuplicateFailRejection tests that if either party attempts to fail an 7536 // HTLC twice, then we'll reject the second fail attempt. 7537 func TestDuplicateFailRejection(t *testing.T) { 7538 t.Parallel() 7539 7540 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7541 channeldb.SingleFunderTweaklessBit, 7542 ) 7543 if err != nil { 7544 t.Fatalf("unable to create test channels: %v", err) 7545 } 7546 defer cleanUp() 7547 7548 // First, we'll add an HTLC from Alice to Bob, and lock it in for both 7549 // parties. 7550 htlcAmount := lnwire.NewMAtomsFromAtoms(20000) 7551 htlcAlice, _ := createHTLC(0, htlcAmount) 7552 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7553 t.Fatalf("alice unable to add htlc: %v", err) 7554 } 7555 _, err = bobChannel.ReceiveHTLC(htlcAlice) 7556 if err != nil { 7557 t.Fatalf("unable to recv htlc: %v", err) 7558 } 7559 7560 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 7561 t.Fatalf("unable to complete state update: %v", err) 7562 } 7563 7564 // With the HTLC locked in, we'll now have Bob fail the HTLC back to 7565 // Alice. 7566 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 7567 if err != nil { 7568 t.Fatalf("unable to cancel HTLC: %v", err) 7569 } 7570 if err := aliceChannel.ReceiveFailHTLC(0, []byte("bad")); err != nil { 7571 t.Fatalf("unable to recv htlc cancel: %v", err) 7572 } 7573 7574 // If we attempt to fail it AGAIN, then both sides should reject this 7575 // second failure attempt. 7576 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 7577 if err == nil { 7578 t.Fatalf("duplicate HTLC failure attempt should have failed") 7579 } 7580 if err := aliceChannel.ReceiveFailHTLC(0, []byte("bad")); err == nil { 7581 t.Fatalf("duplicate HTLC failure attempt should have failed") 7582 } 7583 7584 // We'll now have Bob sign a new commitment to lock in the HTLC fail 7585 // for Alice. 7586 _, _, _, err = bobChannel.SignNextCommitment() 7587 if err != nil { 7588 t.Fatalf("unable to sign commit: %v", err) 7589 } 7590 7591 // We'll now force a restart for Bob and Alice, so we can test the 7592 // persistence related portion of this assertion. 7593 bobChannel, err = restartChannel(bobChannel) 7594 if err != nil { 7595 t.Fatalf("unable to restart channel: %v", err) 7596 } 7597 aliceChannel, err = restartChannel(aliceChannel) 7598 if err != nil { 7599 t.Fatalf("unable to restart channel: %v", err) 7600 } 7601 7602 // If we try to fail the same HTLC again, then we should get an error. 7603 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 7604 if err == nil { 7605 t.Fatalf("duplicate HTLC failure attempt should have failed") 7606 } 7607 7608 // Alice on the other hand should accept the failure again, as she 7609 // dropped all items in the logs which weren't committed. 7610 if err := aliceChannel.ReceiveFailHTLC(0, []byte("bad")); err != nil { 7611 t.Fatalf("unable to recv htlc cancel: %v", err) 7612 } 7613 } 7614 7615 // TestDuplicateSettleRejection tests that if either party attempts to settle 7616 // an HTLC twice, then we'll reject the second settle attempt. 7617 func TestDuplicateSettleRejection(t *testing.T) { 7618 t.Parallel() 7619 7620 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7621 channeldb.SingleFunderTweaklessBit, 7622 ) 7623 if err != nil { 7624 t.Fatalf("unable to create test channels: %v", err) 7625 } 7626 defer cleanUp() 7627 7628 // First, we'll add an HTLC from Alice to Bob, and lock it in for both 7629 // parties. 7630 htlcAmount := lnwire.NewMAtomsFromAtoms(20000) 7631 htlcAlice, alicePreimage := createHTLC(0, htlcAmount) 7632 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7633 t.Fatalf("alice unable to add htlc: %v", err) 7634 } 7635 _, err = bobChannel.ReceiveHTLC(htlcAlice) 7636 if err != nil { 7637 t.Fatalf("unable to recv htlc: %v", err) 7638 } 7639 7640 if err := ForceStateTransition(aliceChannel, bobChannel); err != nil { 7641 t.Fatalf("unable to complete state update: %v", err) 7642 } 7643 7644 // With the HTLC locked in, we'll now have Bob settle the HTLC back to 7645 // Alice. 7646 err = bobChannel.SettleHTLC(alicePreimage, uint64(0), nil, nil, nil) 7647 if err != nil { 7648 t.Fatalf("unable to cancel HTLC: %v", err) 7649 } 7650 err = aliceChannel.ReceiveHTLCSettle(alicePreimage, uint64(0)) 7651 if err != nil { 7652 t.Fatalf("unable to recv htlc cancel: %v", err) 7653 } 7654 7655 // If we attempt to fail it AGAIN, then both sides should reject this 7656 // second failure attempt. 7657 err = bobChannel.SettleHTLC(alicePreimage, uint64(0), nil, nil, nil) 7658 if err == nil { 7659 t.Fatalf("duplicate HTLC failure attempt should have failed") 7660 } 7661 err = aliceChannel.ReceiveHTLCSettle(alicePreimage, uint64(0)) 7662 if err == nil { 7663 t.Fatalf("duplicate HTLC failure attempt should have failed") 7664 } 7665 7666 // We'll now have Bob sign a new commitment to lock in the HTLC fail 7667 // for Alice. 7668 _, _, _, err = bobChannel.SignNextCommitment() 7669 if err != nil { 7670 t.Fatalf("unable to sign commit: %v", err) 7671 } 7672 7673 // We'll now force a restart for Bob and Alice, so we can test the 7674 // persistence related portion of this assertion. 7675 bobChannel, err = restartChannel(bobChannel) 7676 if err != nil { 7677 t.Fatalf("unable to restart channel: %v", err) 7678 } 7679 aliceChannel, err = restartChannel(aliceChannel) 7680 if err != nil { 7681 t.Fatalf("unable to restart channel: %v", err) 7682 } 7683 7684 // If we try to fail the same HTLC again, then we should get an error. 7685 err = bobChannel.SettleHTLC(alicePreimage, uint64(0), nil, nil, nil) 7686 if err == nil { 7687 t.Fatalf("duplicate HTLC failure attempt should have failed") 7688 } 7689 7690 // Alice on the other hand should accept the failure again, as she 7691 // dropped all items in the logs which weren't committed. 7692 err = aliceChannel.ReceiveHTLCSettle(alicePreimage, uint64(0)) 7693 if err != nil { 7694 t.Fatalf("unable to recv htlc cancel: %v", err) 7695 } 7696 } 7697 7698 // TestChannelRestoreCommitHeight tests that the local and remote commit 7699 // heights of HTLCs are set correctly across restores. 7700 func TestChannelRestoreCommitHeight(t *testing.T) { 7701 t.Parallel() 7702 7703 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 7704 channeldb.SingleFunderTweaklessBit, 7705 ) 7706 if err != nil { 7707 t.Fatalf("unable to create test channels: %v", err) 7708 } 7709 defer cleanUp() 7710 7711 // helper method to check add heights of the htlcs found in the given 7712 // log after a restore. 7713 restoreAndAssertCommitHeights := func(t *testing.T, 7714 channel *LightningChannel, remoteLog bool, htlcIndex uint64, 7715 expLocal, expRemote uint64) *LightningChannel { 7716 7717 newChannel, err := NewLightningChannel( 7718 channel.Signer, channel.channelState, channel.sigPool, 7719 testChainParams, 7720 ) 7721 if err != nil { 7722 t.Fatalf("unable to create new channel: %v", err) 7723 } 7724 7725 var pd *PaymentDescriptor 7726 if remoteLog { 7727 if newChannel.localUpdateLog.lookupHtlc(htlcIndex) != nil { 7728 t.Fatalf("htlc found in wrong log") 7729 } 7730 pd = newChannel.remoteUpdateLog.lookupHtlc(htlcIndex) 7731 7732 } else { 7733 if newChannel.remoteUpdateLog.lookupHtlc(htlcIndex) != nil { 7734 t.Fatalf("htlc found in wrong log") 7735 } 7736 pd = newChannel.localUpdateLog.lookupHtlc(htlcIndex) 7737 } 7738 if pd == nil { 7739 t.Fatalf("htlc not found in log") 7740 } 7741 7742 if pd.addCommitHeightLocal != expLocal { 7743 t.Fatalf("expected local add height to be %d, was %d", 7744 expLocal, pd.addCommitHeightLocal) 7745 } 7746 if pd.addCommitHeightRemote != expRemote { 7747 t.Fatalf("expected remote add height to be %d, was %d", 7748 expRemote, pd.addCommitHeightRemote) 7749 } 7750 return newChannel 7751 } 7752 7753 // We'll send an HtLC from Alice to Bob. 7754 htlcAmount := lnwire.NewMAtomsFromAtoms(100000000) 7755 htlcAlice, _ := createHTLC(0, htlcAmount) 7756 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7757 t.Fatalf("alice unable to add htlc: %v", err) 7758 } 7759 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 7760 t.Fatalf("bob unable to recv add htlc: %v", err) 7761 } 7762 7763 // Let Alice sign a new state, which will include the HTLC just sent. 7764 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 7765 if err != nil { 7766 t.Fatalf("unable to sign commitment: %v", err) 7767 } 7768 7769 // The HTLC should only be on the pending remote commitment, so the 7770 // only the remote add height should be set during a restore. 7771 aliceChannel = restoreAndAssertCommitHeights( 7772 t, aliceChannel, false, 0, 0, 1, 7773 ) 7774 7775 // Bob receives this commitment signature, and revokes his old state. 7776 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 7777 if err != nil { 7778 t.Fatalf("unable to receive commitment: %v", err) 7779 } 7780 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 7781 if err != nil { 7782 t.Fatalf("unable to revoke commitment: %v", err) 7783 } 7784 7785 // Now the HTLC is locked into Bob's commitment, a restoration should 7786 // set only the local commit height, as it is not locked into Alice's 7787 // yet. 7788 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 1, 0) 7789 7790 // Alice receives the revocation, ACKing her pending commitment. 7791 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 7792 if err != nil { 7793 t.Fatalf("unable to recive revocation: %v", err) 7794 } 7795 7796 // However, the HTLC is still not locked into her local commitment, so 7797 // the local add height should still be 0 after a restoration. 7798 aliceChannel = restoreAndAssertCommitHeights( 7799 t, aliceChannel, false, 0, 0, 1, 7800 ) 7801 7802 // Now let Bob send the commitment signature making the HTLC lock in on 7803 // Alice's commitment. 7804 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 7805 if err != nil { 7806 t.Fatalf("unable to sign commitment: %v", err) 7807 } 7808 7809 // At this stage Bob has a pending remote commitment. Make sure 7810 // restoring at this stage correcly restores the HTLC add commit 7811 // heights. 7812 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 1, 1) 7813 7814 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 7815 if err != nil { 7816 t.Fatalf("unable to receive commitment: %v", err) 7817 } 7818 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 7819 if err != nil { 7820 t.Fatalf("unable to revoke commitment: %v", err) 7821 } 7822 7823 // Now both the local and remote add heights should be properly set. 7824 aliceChannel = restoreAndAssertCommitHeights( 7825 t, aliceChannel, false, 0, 1, 1, 7826 ) 7827 7828 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 7829 if err != nil { 7830 t.Fatalf("unable to recive revocation: %v", err) 7831 } 7832 7833 // Alice ACKing Bob's pending commitment shouldn't change the heights 7834 // restored. 7835 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 1, 1) 7836 7837 // Send andother HTLC from Alice to Bob, to test whether already 7838 // existing HTLCs (the HTLC with index 0) keep getting the add heights 7839 // restored properly. 7840 htlcAlice, _ = createHTLC(1, htlcAmount) 7841 if _, err := aliceChannel.AddHTLC(htlcAlice, nil); err != nil { 7842 t.Fatalf("alice unable to add htlc: %v", err) 7843 } 7844 if _, err := bobChannel.ReceiveHTLC(htlcAlice); err != nil { 7845 t.Fatalf("bob unable to recv add htlc: %v", err) 7846 } 7847 7848 // Send a new signature from Alice to Bob, making Alice have a pending 7849 // remote commitment. 7850 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 7851 if err != nil { 7852 t.Fatalf("unable to sign commitment: %v", err) 7853 } 7854 7855 // A restoration should keep the add heights iof the first HTLC, and 7856 // the new HTLC should have a remote add height 2. 7857 aliceChannel = restoreAndAssertCommitHeights( 7858 t, aliceChannel, false, 0, 1, 1, 7859 ) 7860 aliceChannel = restoreAndAssertCommitHeights( 7861 t, aliceChannel, false, 1, 0, 2, 7862 ) 7863 7864 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 7865 if err != nil { 7866 t.Fatalf("unable to receive commitment: %v", err) 7867 } 7868 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 7869 if err != nil { 7870 t.Fatalf("unable to revoke commitment: %v", err) 7871 } 7872 7873 // Since Bob just revoked another commitment, a restoration should 7874 // increase the add height of the firt HTLC to 2, as we only keep the 7875 // last unrevoked commitment. The new HTLC will also have a local add 7876 // height of 2. 7877 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 2, 1) 7878 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 1, 2, 0) 7879 7880 // Alice receives the revocation, ACKing her pending commitment for Bob. 7881 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 7882 if err != nil { 7883 t.Fatalf("unable to receive revocation: %v", err) 7884 } 7885 7886 // Alice receiving Bob's revocation should bump both addCommitHeightRemote 7887 // heights to 2. 7888 aliceChannel = restoreAndAssertCommitHeights( 7889 t, aliceChannel, false, 0, 1, 2, 7890 ) 7891 aliceChannel = restoreAndAssertCommitHeights( 7892 t, aliceChannel, false, 1, 0, 2, 7893 ) 7894 7895 // Sign a new state for Alice, making Bob have a pending remote 7896 // commitment. 7897 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 7898 if err != nil { 7899 t.Fatalf("unable to sign commitment: %v", err) 7900 } 7901 7902 // The signing of a new commitment for Alice should have given the new 7903 // HTLC an add height. 7904 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 2, 1) 7905 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 1, 2, 2) 7906 7907 // Alice should receive the commitment and send over a revocation. 7908 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 7909 if err != nil { 7910 t.Fatalf("unable to receive commitment: %v", err) 7911 } 7912 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 7913 if err != nil { 7914 t.Fatalf("unable to revoke commitment: %v", err) 7915 } 7916 7917 // Both heights should be 2 and they are on both commitments. 7918 aliceChannel = restoreAndAssertCommitHeights( 7919 t, aliceChannel, false, 0, 2, 2, 7920 ) 7921 aliceChannel = restoreAndAssertCommitHeights( 7922 t, aliceChannel, false, 1, 2, 2, 7923 ) 7924 7925 // Bob receives the revocation, which should set both addCommitHeightRemote 7926 // fields to 2. 7927 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 7928 if err != nil { 7929 t.Fatalf("unable to receive revocation: %v", err) 7930 } 7931 7932 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 2, 2) 7933 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 1, 2, 2) 7934 7935 // Bob now fails back the htlc that was just locked in. 7936 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 7937 if err != nil { 7938 t.Fatalf("unable to cancel HTLC: %v", err) 7939 } 7940 err = aliceChannel.ReceiveFailHTLC(0, []byte("bad")) 7941 if err != nil { 7942 t.Fatalf("unable to recv htlc cancel: %v", err) 7943 } 7944 7945 // Now Bob signs for the fail update. 7946 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 7947 if err != nil { 7948 t.Fatalf("unable to sign commitment: %v", err) 7949 } 7950 7951 // Bob has a pending commitment for Alice, it shouldn't affect the add 7952 // commit heights though. 7953 bobChannel = restoreAndAssertCommitHeights(t, bobChannel, true, 0, 2, 2) 7954 _ = restoreAndAssertCommitHeights(t, bobChannel, true, 1, 2, 2) 7955 7956 // Alice receives commitment, sends revocation. 7957 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 7958 if err != nil { 7959 t.Fatalf("unable to receive commitment: %v", err) 7960 } 7961 _, _, err = aliceChannel.RevokeCurrentCommitment() 7962 if err != nil { 7963 t.Fatalf("unable to revoke commitment: %v", err) 7964 } 7965 7966 aliceChannel = restoreAndAssertCommitHeights( 7967 t, aliceChannel, false, 0, 3, 2, 7968 ) 7969 _ = restoreAndAssertCommitHeights(t, aliceChannel, false, 1, 3, 2) 7970 } 7971 7972 // TestForceCloseFailLocalDataLoss tests that we don't allow a force close of a 7973 // channel that's in a non-default state. 7974 func TestForceCloseFailLocalDataLoss(t *testing.T) { 7975 t.Parallel() 7976 7977 aliceChannel, _, cleanUp, err := CreateTestChannels( 7978 channeldb.SingleFunderBit, 7979 ) 7980 if err != nil { 7981 t.Fatalf("unable to create test channels: %v", err) 7982 } 7983 defer cleanUp() 7984 7985 // Now that we have our set of channels, we'll modify the channel state 7986 // to have a non-default channel flag. 7987 err = aliceChannel.channelState.ApplyChanStatus( 7988 channeldb.ChanStatusLocalDataLoss, 7989 ) 7990 if err != nil { 7991 t.Fatalf("unable to apply channel state: %v", err) 7992 } 7993 7994 // Due to the change above, if we attempt to force close this 7995 // channel, we should fail as it isn't safe to force close a 7996 // channel that isn't in the pure default state. 7997 _, err = aliceChannel.ForceClose() 7998 if err == nil { 7999 t.Fatalf("expected force close to fail due to non-default " + 8000 "chan state") 8001 } 8002 } 8003 8004 // TestForceCloseBorkedState tests that once we force close a channel, it's 8005 // marked as borked in the database. Additionally, all calls to mutate channel 8006 // state should also fail. 8007 func TestForceCloseBorkedState(t *testing.T) { 8008 t.Parallel() 8009 8010 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 8011 channeldb.SingleFunderBit, 8012 ) 8013 if err != nil { 8014 t.Fatalf("unable to create test channels: %v", err) 8015 } 8016 defer cleanUp() 8017 8018 // Do the commitment dance until Bob sends a revocation so Alice is 8019 // able to receive the revocation, and then also make a new state 8020 // herself. 8021 aliceSigs, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 8022 if err != nil { 8023 t.Fatalf("unable to sign commit: %v", err) 8024 } 8025 err = bobChannel.ReceiveNewCommitment(aliceSigs, aliceHtlcSigs) 8026 if err != nil { 8027 t.Fatalf("unable to receive commitment: %v", err) 8028 } 8029 revokeMsg, _, err := bobChannel.RevokeCurrentCommitment() 8030 if err != nil { 8031 t.Fatalf("unable to revoke bob commitment: %v", err) 8032 } 8033 bobSigs, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 8034 if err != nil { 8035 t.Fatalf("unable to sign commit: %v", err) 8036 } 8037 err = aliceChannel.ReceiveNewCommitment(bobSigs, bobHtlcSigs) 8038 if err != nil { 8039 t.Fatalf("unable to receive commitment: %v", err) 8040 } 8041 8042 // Now that we have a new Alice channel, we'll force close once to 8043 // trigger the update on disk to mark the channel as borked. 8044 if _, err := aliceChannel.ForceClose(); err != nil { 8045 t.Fatalf("unable to force close channel: %v", err) 8046 } 8047 8048 // Next we'll mark the channel as borked before we proceed. 8049 err = aliceChannel.channelState.ApplyChanStatus( 8050 channeldb.ChanStatusBorked, 8051 ) 8052 if err != nil { 8053 t.Fatalf("unable to apply chan status: %v", err) 8054 } 8055 8056 // The on-disk state should indicate that the channel is now borked. 8057 if !aliceChannel.channelState.HasChanStatus( 8058 channeldb.ChanStatusBorked, 8059 ) { 8060 t.Fatalf("chan status not updated as borked") 8061 } 8062 8063 // At this point, all channel mutating methods should now fail as they 8064 // shouldn't be able to proceed if the channel is borked. 8065 _, _, _, _, err = aliceChannel.ReceiveRevocation(revokeMsg) 8066 if err != channeldb.ErrChanBorked { 8067 t.Fatalf("advance commitment tail should have failed") 8068 } 8069 8070 // We manually advance the commitment tail here since the above 8071 // ReceiveRevocation call will fail before it's actually advanced. 8072 aliceChannel.remoteCommitChain.advanceTail() 8073 _, _, _, err = aliceChannel.SignNextCommitment() 8074 if err != channeldb.ErrChanBorked { 8075 t.Fatalf("sign commitment should have failed: %v", err) 8076 } 8077 _, _, err = aliceChannel.RevokeCurrentCommitment() 8078 if err != channeldb.ErrChanBorked { 8079 t.Fatalf("append remove chain tail should have failed") 8080 } 8081 } 8082 8083 // TestChannelMaxFeeRate ensures we correctly compute a channel initiator's max 8084 // fee rate based on an allocation and its available balance. It should never 8085 // dip below the established fee floor. 8086 func TestChannelMaxFeeRate(t *testing.T) { 8087 t.Parallel() 8088 8089 assertMaxFeeRate := func(c *LightningChannel, maxAlloc float64, 8090 expFeeRate chainfee.AtomPerKByte) { 8091 t.Helper() 8092 8093 maxFeeRate := c.MaxFeeRate(maxAlloc) 8094 if maxFeeRate != expFeeRate { 8095 t.Fatalf("expected max fee rate of %v with max "+ 8096 "allocation of %v, got %v", expFeeRate, 8097 maxAlloc, maxFeeRate) 8098 } 8099 8100 if err := c.validateFeeRate(maxFeeRate); err != nil { 8101 t.Fatalf("fee rate validation failed: %v", err) 8102 } 8103 } 8104 8105 // propertyTest tests that the validateFeeRate function always passes 8106 // for the output returned by MaxFeeRate for any valid random inputs 8107 // fed to MaxFeeRate. 8108 propertyTest := func(c *LightningChannel) func(alloc maxAlloc) bool { 8109 return func(ma maxAlloc) bool { 8110 maxFeeRate := c.MaxFeeRate(float64(ma)) 8111 return c.validateFeeRate(maxFeeRate) == nil 8112 } 8113 } 8114 8115 aliceChannel, _, cleanUp, err := CreateTestChannels( 8116 channeldb.SingleFunderTweaklessBit, 8117 ) 8118 if err != nil { 8119 t.Fatalf("unable to create test channels: %v", err) 8120 } 8121 defer cleanUp() 8122 8123 if err := quick.Check(propertyTest(aliceChannel), nil); err != nil { 8124 t.Fatal(err) 8125 } 8126 8127 assertMaxFeeRate(aliceChannel, 1.0, 1346144505) 8128 assertMaxFeeRate(aliceChannel, 0.001, 1346144) 8129 assertMaxFeeRate(aliceChannel, 0.000001, 10000) 8130 assertMaxFeeRate(aliceChannel, 0.0000001, chainfee.FeePerKBFloor) 8131 8132 // Check that anchor channels are capped at their max fee rate. 8133 anchorChannel, _, cleanUp, err := CreateTestChannels( 8134 channeldb.SingleFunderTweaklessBit | 8135 channeldb.AnchorOutputsBit | channeldb.ZeroHtlcTxFeeBit, 8136 ) 8137 if err != nil { 8138 t.Fatalf("unable to create test channels: %v", err) 8139 } 8140 defer cleanUp() 8141 8142 if err = quick.Check(propertyTest(anchorChannel), nil); err != nil { 8143 t.Fatal(err) 8144 } 8145 8146 // Anchor commitments are heavier, hence will the same allocation lead 8147 // to slightly lower fee rates. 8148 assertMaxFeeRate(anchorChannel, 1.0, 1134195555) 8149 assertMaxFeeRate(anchorChannel, 0.001, 1134195) 8150 assertMaxFeeRate(anchorChannel, 0.000001, chainfee.FeePerKBFloor) 8151 assertMaxFeeRate(anchorChannel, 0.0000001, chainfee.FeePerKBFloor) 8152 } 8153 8154 // TestIdealCommitFeeRate tests that we correctly compute the ideal commitment 8155 // fee of a channel given the current network fee, minimum relay fee, maximum 8156 // fee allocation and whether the channel has anchor outputs. 8157 func TestIdealCommitFeeRate(t *testing.T) { 8158 t.Parallel() 8159 8160 assertIdealFeeRate := func(c *LightningChannel, netFee, minRelay, 8161 maxAnchorCommit chainfee.AtomPerKByte, 8162 maxFeeAlloc float64, expectedFeeRate chainfee.AtomPerKByte) { 8163 8164 feeRate := c.IdealCommitFeeRate( 8165 netFee, minRelay, maxAnchorCommit, maxFeeAlloc, 8166 ) 8167 if feeRate != expectedFeeRate { 8168 t.Fatalf("expected fee rate of %v got %v", 8169 expectedFeeRate, feeRate) 8170 } 8171 8172 if err := c.validateFeeRate(feeRate); err != nil { 8173 t.Fatalf("fee rate validation failed: %v", err) 8174 } 8175 } 8176 8177 // propertyTest tests that the validateFeeRate function always passes 8178 // for the output returned by IdealCommitFeeRate for any valid random 8179 // inputs fed to IdealCommitFeeRate. 8180 propertyTest := func(c *LightningChannel) func(ma maxAlloc, 8181 netFee, minRelayFee, maxAnchorFee fee) bool { 8182 8183 return func(ma maxAlloc, netFee, minRelayFee, 8184 maxAnchorFee fee) bool { 8185 8186 idealFeeRate := c.IdealCommitFeeRate( 8187 chainfee.AtomPerKByte(netFee), 8188 chainfee.AtomPerKByte(minRelayFee), 8189 chainfee.AtomPerKByte(maxAnchorFee), 8190 float64(ma), 8191 ) 8192 8193 return c.validateFeeRate(idealFeeRate) == nil 8194 } 8195 } 8196 8197 // Test ideal fee rates for a non-anchor channel 8198 t.Run("non-anchor-channel", func(t *testing.T) { 8199 aliceChannel, _, cleanUp, err := CreateTestChannels( 8200 channeldb.SingleFunderTweaklessBit, 8201 ) 8202 if err != nil { 8203 t.Fatalf("unable to create test channels: %v", err) 8204 } 8205 defer cleanUp() 8206 8207 err = quick.Check(propertyTest(aliceChannel), nil) 8208 if err != nil { 8209 t.Fatal(err) 8210 } 8211 8212 // If the maximum fee is lower than the network fee and above 8213 // the min relay fee, use the maximum fee. 8214 assertIdealFeeRate( 8215 aliceChannel, 700000000, 0, 0, 1.0, 700000000, 8216 ) 8217 8218 // If the network fee is lower than the max fee and above the 8219 // min relay fee, use the network fee. 8220 assertIdealFeeRate( 8221 aliceChannel, 500000000, 0, 0, 1.0, 500000000, 8222 ) 8223 8224 // If the fee is below the minimum relay fee, and the min relay 8225 // fee is less than our max fee, use the minimum relay fee. 8226 assertIdealFeeRate( 8227 aliceChannel, 500000000, 600000000, 0, 1.0, 600000000, 8228 ) 8229 8230 // The absolute maximum fee rate we can pay (ie, using a max 8231 // allocation of 1) is still below the minimum relay fee. In 8232 // this case, use the absolute max fee. 8233 assertIdealFeeRate( 8234 aliceChannel, 800000000, 700000000, 0, 0.001, 8235 700000000, 8236 ) 8237 }) 8238 8239 // Test ideal fee rates for an anchor channel 8240 t.Run("anchor-channel", func(t *testing.T) { 8241 anchorChannel, _, cleanUp, err := CreateTestChannels( 8242 channeldb.SingleFunderTweaklessBit | 8243 channeldb.AnchorOutputsBit | 8244 channeldb.ZeroHtlcTxFeeBit, 8245 ) 8246 if err != nil { 8247 t.Fatalf("unable to create test channels: %v", err) 8248 } 8249 defer cleanUp() 8250 8251 err = quick.Check(propertyTest(anchorChannel), nil) 8252 if err != nil { 8253 t.Fatal(err) 8254 } 8255 8256 // Anchor commitments are heavier, hence the same allocation 8257 // leads to slightly lower fee rates. 8258 assertIdealFeeRate( 8259 anchorChannel, 700000000, 0, chainfee.FeePerKBFloor, 8260 0.1, chainfee.FeePerKBFloor, 8261 ) 8262 8263 // If the maximum fee is lower than the network fee, use the 8264 // maximum fee. 8265 assertIdealFeeRate( 8266 anchorChannel, 700000000, 0, 1000000, 0.001, 1000000, 8267 ) 8268 8269 assertIdealFeeRate( 8270 anchorChannel, 700000000, 0, 700, 0.000001, 8271 chainfee.FeePerKBFloor, 8272 ) 8273 8274 assertIdealFeeRate( 8275 anchorChannel, 700000000, 0, 1000000, 0.0000001, 8276 chainfee.FeePerKBFloor, 8277 ) 8278 8279 // If the maximum anchor commit fee rate is less than the 8280 // maximum fee, use the max anchor commit fee since this is an 8281 // anchor channel. 8282 assertIdealFeeRate( 8283 anchorChannel, 700000000, 0, 400000, 0.001, 400000, 8284 ) 8285 8286 // If the minimum relay fee is above the max anchor commitment 8287 // fee rate but still below our max fee rate then use the min 8288 // relay fee. 8289 assertIdealFeeRate( 8290 anchorChannel, 700000000, 400000, 300000, 0.001, 8291 400000, 8292 ) 8293 8294 // If the min relay fee is above the ideal max fee rate but is 8295 // below the max fee rate when the max fee allocation is set to 8296 // 1, the minimum relay fee is used. 8297 assertIdealFeeRate( 8298 anchorChannel, 700000000, 500000, 300000, 0.001, 8299 500000, 8300 ) 8301 8302 // The absolute maximum fee rate we can pay (ie, using a max 8303 // allocation of 1) is still below the minimum relay fee. In 8304 // this case, use the absolute max fee. 8305 assertIdealFeeRate( 8306 anchorChannel, 700000000, 450000000, 300000, 0.001, 8307 450000000, 8308 ) 8309 }) 8310 } 8311 8312 type maxAlloc float64 8313 8314 // Generate ensures that the random value generated by the testing quick 8315 // package for maxAlloc is always a positive float64 between 0 and 1. 8316 func (maxAlloc) Generate(r *rand.Rand, _ int) reflect.Value { 8317 ma := maxAlloc(r.Float64()) 8318 return reflect.ValueOf(ma) 8319 } 8320 8321 type fee chainfee.AtomPerKByte 8322 8323 // Generate ensures that the random value generated by the testing quick 8324 // package for a fee is always a positive int64. 8325 func (fee) Generate(r *rand.Rand, _ int) reflect.Value { 8326 am := fee(r.Int63()) 8327 return reflect.ValueOf(am) 8328 } 8329 8330 // TestChannelFeeRateFloor asserts that valid commitments can be proposed and 8331 // received using chainfee.FeePerKBFloor as the initiator's fee rate. 8332 func TestChannelFeeRateFloor(t *testing.T) { 8333 t.Parallel() 8334 8335 alice, bob, cleanUp, err := CreateTestChannels( 8336 channeldb.SingleFunderTweaklessBit, 8337 ) 8338 if err != nil { 8339 t.Fatalf("unable to create test channels: %v", err) 8340 } 8341 defer cleanUp() 8342 8343 // Set the fee rate to the proposing fee rate floor. 8344 minFee := chainfee.FeePerKBFloor 8345 8346 // Alice is the initiator, so only she can propose fee updates. 8347 if err := alice.UpdateFee(minFee); err != nil { 8348 t.Fatalf("unable to send fee update") 8349 } 8350 if err := bob.ReceiveUpdateFee(minFee); err != nil { 8351 t.Fatalf("unable to receive fee update") 8352 } 8353 8354 // Check that alice can still sign commitments. 8355 sig, htlcSigs, _, err := alice.SignNextCommitment() 8356 if err != nil { 8357 t.Fatalf("alice unable to sign commitment: %v", err) 8358 } 8359 8360 // Check that bob can still receive commitments. 8361 err = bob.ReceiveNewCommitment(sig, htlcSigs) 8362 if err != nil { 8363 t.Fatalf("bob unable to process alice's new commitment: %v", 8364 err) 8365 } 8366 } 8367 8368 // TestFetchParent tests lookup of an entry's parent in the appropriate log. 8369 func TestFetchParent(t *testing.T) { 8370 tests := []struct { 8371 name string 8372 remoteChain bool 8373 remoteLog bool 8374 localEntries []*PaymentDescriptor 8375 remoteEntries []*PaymentDescriptor 8376 8377 // parentIndex is the parent index of the entry that we will 8378 // lookup with fetch parent. 8379 parentIndex uint64 8380 8381 // expectErr indicates that we expect fetch parent to fail. 8382 expectErr bool 8383 8384 // expectedIndex is the htlc index that we expect the parent 8385 // to have. 8386 expectedIndex uint64 8387 }{ 8388 { 8389 name: "not found in remote log", 8390 localEntries: nil, 8391 remoteEntries: nil, 8392 remoteChain: true, 8393 remoteLog: true, 8394 parentIndex: 0, 8395 expectErr: true, 8396 }, 8397 { 8398 name: "not found in local log", 8399 localEntries: nil, 8400 remoteEntries: nil, 8401 remoteChain: false, 8402 remoteLog: false, 8403 parentIndex: 0, 8404 expectErr: true, 8405 }, 8406 { 8407 name: "remote log + chain, remote add height 0", 8408 localEntries: nil, 8409 remoteEntries: []*PaymentDescriptor{ 8410 // This entry will be added at log index =0. 8411 { 8412 HtlcIndex: 1, 8413 addCommitHeightLocal: 100, 8414 addCommitHeightRemote: 100, 8415 }, 8416 // This entry will be added at log index =1, it 8417 // is the parent entry we are looking for. 8418 { 8419 HtlcIndex: 2, 8420 addCommitHeightLocal: 100, 8421 addCommitHeightRemote: 0, 8422 }, 8423 }, 8424 remoteChain: true, 8425 remoteLog: true, 8426 parentIndex: 1, 8427 expectErr: true, 8428 }, 8429 { 8430 name: "remote log, local chain, local add height 0", 8431 remoteEntries: []*PaymentDescriptor{ 8432 // This entry will be added at log index =0. 8433 { 8434 HtlcIndex: 1, 8435 addCommitHeightLocal: 100, 8436 addCommitHeightRemote: 100, 8437 }, 8438 // This entry will be added at log index =1, it 8439 // is the parent entry we are looking for. 8440 { 8441 HtlcIndex: 2, 8442 addCommitHeightLocal: 0, 8443 addCommitHeightRemote: 100, 8444 }, 8445 }, 8446 localEntries: nil, 8447 remoteChain: false, 8448 remoteLog: true, 8449 parentIndex: 1, 8450 expectErr: true, 8451 }, 8452 { 8453 name: "local log + chain, local add height 0", 8454 localEntries: []*PaymentDescriptor{ 8455 // This entry will be added at log index =0. 8456 { 8457 HtlcIndex: 1, 8458 addCommitHeightLocal: 100, 8459 addCommitHeightRemote: 100, 8460 }, 8461 // This entry will be added at log index =1, it 8462 // is the parent entry we are looking for. 8463 { 8464 HtlcIndex: 2, 8465 addCommitHeightLocal: 0, 8466 addCommitHeightRemote: 100, 8467 }, 8468 }, 8469 remoteEntries: nil, 8470 remoteChain: false, 8471 remoteLog: false, 8472 parentIndex: 1, 8473 expectErr: true, 8474 }, 8475 8476 { 8477 name: "local log + remote chain, remote add height 0", 8478 localEntries: []*PaymentDescriptor{ 8479 // This entry will be added at log index =0. 8480 { 8481 HtlcIndex: 1, 8482 addCommitHeightLocal: 100, 8483 addCommitHeightRemote: 100, 8484 }, 8485 // This entry will be added at log index =1, it 8486 // is the parent entry we are looking for. 8487 { 8488 HtlcIndex: 2, 8489 addCommitHeightLocal: 100, 8490 addCommitHeightRemote: 0, 8491 }, 8492 }, 8493 remoteEntries: nil, 8494 remoteChain: true, 8495 remoteLog: false, 8496 parentIndex: 1, 8497 expectErr: true, 8498 }, 8499 { 8500 name: "remote log found", 8501 localEntries: nil, 8502 remoteEntries: []*PaymentDescriptor{ 8503 // This entry will be added at log index =0. 8504 { 8505 HtlcIndex: 1, 8506 addCommitHeightLocal: 100, 8507 addCommitHeightRemote: 0, 8508 }, 8509 // This entry will be added at log index =1, it 8510 // is the parent entry we are looking for. 8511 { 8512 HtlcIndex: 2, 8513 addCommitHeightLocal: 100, 8514 addCommitHeightRemote: 100, 8515 }, 8516 }, 8517 remoteChain: true, 8518 remoteLog: true, 8519 parentIndex: 1, 8520 expectErr: false, 8521 expectedIndex: 2, 8522 }, 8523 { 8524 name: "local log found", 8525 localEntries: []*PaymentDescriptor{ 8526 // This entry will be added at log index =0. 8527 { 8528 HtlcIndex: 1, 8529 addCommitHeightLocal: 0, 8530 addCommitHeightRemote: 100, 8531 }, 8532 // This entry will be added at log index =1, it 8533 // is the parent entry we are looking for. 8534 { 8535 HtlcIndex: 2, 8536 addCommitHeightLocal: 100, 8537 addCommitHeightRemote: 100, 8538 }, 8539 }, 8540 remoteEntries: nil, 8541 remoteChain: false, 8542 remoteLog: false, 8543 parentIndex: 1, 8544 expectErr: false, 8545 expectedIndex: 2, 8546 }, 8547 } 8548 8549 for _, test := range tests { 8550 test := test 8551 8552 t.Run(test.name, func(t *testing.T) { 8553 // Create a lightning channel with newly initialized 8554 // local and remote logs. 8555 lc := LightningChannel{ 8556 localUpdateLog: newUpdateLog(0, 0), 8557 remoteUpdateLog: newUpdateLog(0, 0), 8558 } 8559 8560 // Add the local and remote entries to update logs. 8561 for _, entry := range test.localEntries { 8562 lc.localUpdateLog.appendHtlc(entry) 8563 } 8564 for _, entry := range test.remoteEntries { 8565 lc.remoteUpdateLog.appendHtlc(entry) 8566 } 8567 8568 parent, err := lc.fetchParent( 8569 &PaymentDescriptor{ 8570 ParentIndex: test.parentIndex, 8571 }, 8572 test.remoteChain, 8573 test.remoteLog, 8574 ) 8575 gotErr := err != nil 8576 if test.expectErr != gotErr { 8577 t.Fatalf("expected error: %v, got: %v, "+ 8578 "error:%v", test.expectErr, gotErr, err) 8579 } 8580 8581 // If our lookup failed, we do not need to check parent 8582 // index. 8583 if err != nil { 8584 return 8585 } 8586 8587 if parent.HtlcIndex != test.expectedIndex { 8588 t.Fatalf("expected parent index: %v, got: %v", 8589 test.parentIndex, parent.HtlcIndex) 8590 } 8591 }) 8592 8593 } 8594 } 8595 8596 // TestEvaluateView tests the creation of a htlc view and the opt in mutation of 8597 // send and receive balances. This test does not check htlc mutation on a htlc 8598 // level. 8599 func TestEvaluateView(t *testing.T) { 8600 const ( 8601 // addHeight is a non-zero height that is used for htlc adds. 8602 addHeight = 200 8603 8604 // nextHeight is a constant that we use for the next height in 8605 // all unit tests. 8606 nextHeight = 400 8607 8608 // feePerKB is the fee we start all of our unit tests with. 8609 feePerKB = 1 8610 8611 // htlcAddAmount is the amount for htlc adds in tests. 8612 htlcAddAmount = 15 8613 8614 // ourFeeUpdateAmt is an amount that we update fees to 8615 // expressed in msat. 8616 ourFeeUpdateAmt = 20000 8617 8618 // ourFeeUpdatePerSat is the fee rate *in satoshis* that we 8619 // expect if we update to ourFeeUpdateAmt. 8620 ourFeeUpdatePerSat = chainfee.AtomPerKByte(20) 8621 8622 // theirFeeUpdateAmt iis an amount that they update fees to 8623 // expressed in msat. 8624 theirFeeUpdateAmt = 10000 8625 8626 // theirFeeUpdatePerSat is the fee rate *in satoshis* that we 8627 // expect if we update to ourFeeUpdateAmt. 8628 theirFeeUpdatePerSat = chainfee.AtomPerKByte(10) 8629 ) 8630 8631 tests := []struct { 8632 name string 8633 ourHtlcs []*PaymentDescriptor 8634 theirHtlcs []*PaymentDescriptor 8635 remoteChain bool 8636 mutateState bool 8637 8638 // ourExpectedHtlcs is the set of our htlcs that we expect in 8639 // the htlc view once it has been evaluated. We just store 8640 // htlc index -> bool for brevity, because we only check the 8641 // presence of the htlc in the returned set. 8642 ourExpectedHtlcs map[uint64]bool 8643 8644 // theirExpectedHtlcs is the set of their htlcs that we expect 8645 // in the htlc view once it has been evaluated. We just store 8646 // htlc index -> bool for brevity, because we only check the 8647 // presence of the htlc in the returned set. 8648 theirExpectedHtlcs map[uint64]bool 8649 8650 // expectedFee is the fee we expect to be set after evaluating 8651 // the htlc view. 8652 expectedFee chainfee.AtomPerKByte 8653 8654 // expectReceived is the amount we expect the channel to have 8655 // tracked as our receive total. 8656 expectReceived lnwire.MilliAtom 8657 8658 // expectSent is the amount we expect the channel to have 8659 // tracked as our send total. 8660 expectSent lnwire.MilliAtom 8661 }{ 8662 { 8663 name: "our fee update is applied", 8664 remoteChain: false, 8665 mutateState: false, 8666 ourHtlcs: []*PaymentDescriptor{ 8667 { 8668 Amount: ourFeeUpdateAmt, 8669 EntryType: FeeUpdate, 8670 }, 8671 }, 8672 theirHtlcs: nil, 8673 expectedFee: ourFeeUpdatePerSat, 8674 ourExpectedHtlcs: nil, 8675 theirExpectedHtlcs: nil, 8676 expectReceived: 0, 8677 expectSent: 0, 8678 }, 8679 { 8680 name: "their fee update is applied", 8681 remoteChain: false, 8682 mutateState: false, 8683 ourHtlcs: []*PaymentDescriptor{}, 8684 theirHtlcs: []*PaymentDescriptor{ 8685 { 8686 Amount: theirFeeUpdateAmt, 8687 EntryType: FeeUpdate, 8688 }, 8689 }, 8690 expectedFee: theirFeeUpdatePerSat, 8691 ourExpectedHtlcs: nil, 8692 theirExpectedHtlcs: nil, 8693 expectReceived: 0, 8694 expectSent: 0, 8695 }, 8696 { 8697 // We expect unresolved htlcs to to remain in the view. 8698 name: "htlcs adds without settles", 8699 remoteChain: false, 8700 mutateState: false, 8701 ourHtlcs: []*PaymentDescriptor{ 8702 { 8703 HtlcIndex: 0, 8704 Amount: htlcAddAmount, 8705 EntryType: Add, 8706 }, 8707 }, 8708 theirHtlcs: []*PaymentDescriptor{ 8709 { 8710 HtlcIndex: 0, 8711 Amount: htlcAddAmount, 8712 EntryType: Add, 8713 }, 8714 { 8715 HtlcIndex: 1, 8716 Amount: htlcAddAmount, 8717 EntryType: Add, 8718 }, 8719 }, 8720 expectedFee: feePerKB, 8721 ourExpectedHtlcs: map[uint64]bool{ 8722 0: true, 8723 }, 8724 theirExpectedHtlcs: map[uint64]bool{ 8725 0: true, 8726 1: true, 8727 }, 8728 expectReceived: 0, 8729 expectSent: 0, 8730 }, 8731 { 8732 name: "our htlc settled, state mutated", 8733 remoteChain: false, 8734 mutateState: true, 8735 ourHtlcs: []*PaymentDescriptor{ 8736 { 8737 HtlcIndex: 0, 8738 Amount: htlcAddAmount, 8739 EntryType: Add, 8740 addCommitHeightLocal: addHeight, 8741 }, 8742 }, 8743 theirHtlcs: []*PaymentDescriptor{ 8744 { 8745 HtlcIndex: 0, 8746 Amount: htlcAddAmount, 8747 EntryType: Add, 8748 }, 8749 { 8750 HtlcIndex: 1, 8751 Amount: htlcAddAmount, 8752 EntryType: Settle, 8753 // Map their htlc settle update to our 8754 // htlc add (0). 8755 ParentIndex: 0, 8756 }, 8757 }, 8758 expectedFee: feePerKB, 8759 ourExpectedHtlcs: nil, 8760 theirExpectedHtlcs: map[uint64]bool{ 8761 0: true, 8762 }, 8763 expectReceived: 0, 8764 expectSent: htlcAddAmount, 8765 }, 8766 { 8767 name: "our htlc settled, state not mutated", 8768 remoteChain: false, 8769 mutateState: false, 8770 ourHtlcs: []*PaymentDescriptor{ 8771 { 8772 HtlcIndex: 0, 8773 Amount: htlcAddAmount, 8774 EntryType: Add, 8775 addCommitHeightLocal: addHeight, 8776 }, 8777 }, 8778 theirHtlcs: []*PaymentDescriptor{ 8779 { 8780 HtlcIndex: 0, 8781 Amount: htlcAddAmount, 8782 EntryType: Add, 8783 }, 8784 { 8785 HtlcIndex: 1, 8786 Amount: htlcAddAmount, 8787 EntryType: Settle, 8788 // Map their htlc settle update to our 8789 // htlc add (0). 8790 ParentIndex: 0, 8791 }, 8792 }, 8793 expectedFee: feePerKB, 8794 ourExpectedHtlcs: nil, 8795 theirExpectedHtlcs: map[uint64]bool{ 8796 0: true, 8797 }, 8798 expectReceived: 0, 8799 expectSent: 0, 8800 }, 8801 { 8802 name: "their htlc settled, state mutated", 8803 remoteChain: false, 8804 mutateState: true, 8805 ourHtlcs: []*PaymentDescriptor{ 8806 { 8807 HtlcIndex: 0, 8808 Amount: htlcAddAmount, 8809 EntryType: Add, 8810 }, 8811 { 8812 HtlcIndex: 1, 8813 Amount: htlcAddAmount, 8814 EntryType: Settle, 8815 // Map our htlc settle update to their 8816 // htlc add (1). 8817 ParentIndex: 1, 8818 }, 8819 }, 8820 theirHtlcs: []*PaymentDescriptor{ 8821 { 8822 HtlcIndex: 0, 8823 Amount: htlcAddAmount, 8824 EntryType: Add, 8825 addCommitHeightLocal: addHeight, 8826 }, 8827 { 8828 HtlcIndex: 1, 8829 Amount: htlcAddAmount, 8830 EntryType: Add, 8831 addCommitHeightLocal: addHeight, 8832 }, 8833 }, 8834 expectedFee: feePerKB, 8835 ourExpectedHtlcs: map[uint64]bool{ 8836 0: true, 8837 }, 8838 theirExpectedHtlcs: map[uint64]bool{ 8839 0: true, 8840 }, 8841 expectReceived: htlcAddAmount, 8842 expectSent: 0, 8843 }, 8844 { 8845 name: "their htlc settled, state not mutated", 8846 remoteChain: false, 8847 mutateState: false, 8848 ourHtlcs: []*PaymentDescriptor{ 8849 { 8850 HtlcIndex: 0, 8851 Amount: htlcAddAmount, 8852 EntryType: Add, 8853 }, 8854 { 8855 HtlcIndex: 1, 8856 Amount: htlcAddAmount, 8857 EntryType: Settle, 8858 // Map our htlc settle update to their 8859 // htlc add (0). 8860 ParentIndex: 0, 8861 }, 8862 }, 8863 theirHtlcs: []*PaymentDescriptor{ 8864 { 8865 HtlcIndex: 0, 8866 Amount: htlcAddAmount, 8867 EntryType: Add, 8868 addCommitHeightLocal: addHeight, 8869 }, 8870 }, 8871 expectedFee: feePerKB, 8872 ourExpectedHtlcs: map[uint64]bool{ 8873 0: true, 8874 }, 8875 theirExpectedHtlcs: nil, 8876 expectReceived: 0, 8877 expectSent: 0, 8878 }, 8879 } 8880 8881 for _, test := range tests { 8882 test := test 8883 8884 t.Run(test.name, func(t *testing.T) { 8885 lc := LightningChannel{ 8886 channelState: &channeldb.OpenChannel{ 8887 TotalMAtomsSent: 0, 8888 TotalMAtomsReceived: 0, 8889 }, 8890 8891 // Create update logs for local and remote. 8892 localUpdateLog: newUpdateLog(0, 0), 8893 remoteUpdateLog: newUpdateLog(0, 0), 8894 } 8895 8896 for _, htlc := range test.ourHtlcs { 8897 if htlc.EntryType == Add { 8898 lc.localUpdateLog.appendHtlc(htlc) 8899 } else { 8900 lc.localUpdateLog.appendUpdate(htlc) 8901 } 8902 } 8903 8904 for _, htlc := range test.theirHtlcs { 8905 if htlc.EntryType == Add { 8906 lc.remoteUpdateLog.appendHtlc(htlc) 8907 } else { 8908 lc.remoteUpdateLog.appendUpdate(htlc) 8909 } 8910 } 8911 8912 view := &htlcView{ 8913 ourUpdates: test.ourHtlcs, 8914 theirUpdates: test.theirHtlcs, 8915 feePerKB: feePerKB, 8916 } 8917 8918 var ( 8919 // Create vars to store balance changes. We do 8920 // not check these values in this test because 8921 // balance modification happens on the htlc 8922 // processing level. 8923 ourBalance lnwire.MilliAtom 8924 theirBalance lnwire.MilliAtom 8925 ) 8926 8927 // Evaluate the htlc view, mutate as test expects. 8928 result, err := lc.evaluateHTLCView( 8929 view, &ourBalance, &theirBalance, nextHeight, 8930 test.remoteChain, test.mutateState, 8931 ) 8932 if err != nil { 8933 t.Fatalf("unexpected error: %v", err) 8934 } 8935 8936 if result.feePerKB != test.expectedFee { 8937 t.Fatalf("expected fee: %v, got: %v", 8938 test.expectedFee, result.feePerKB) 8939 } 8940 8941 checkExpectedHtlcs( 8942 t, result.ourUpdates, test.ourExpectedHtlcs, 8943 ) 8944 8945 checkExpectedHtlcs( 8946 t, result.theirUpdates, test.theirExpectedHtlcs, 8947 ) 8948 8949 if lc.channelState.TotalMAtomsSent != test.expectSent { 8950 t.Fatalf("expected sent: %v, got: %v", 8951 test.expectSent, 8952 lc.channelState.TotalMAtomsSent) 8953 } 8954 8955 if lc.channelState.TotalMAtomsReceived != 8956 test.expectReceived { 8957 8958 t.Fatalf("expected received: %v, got: %v", 8959 test.expectReceived, 8960 lc.channelState.TotalMAtomsReceived) 8961 } 8962 }) 8963 } 8964 } 8965 8966 // checkExpectedHtlcs checks that a set of htlcs that we have contains all the 8967 // htlcs we expect. 8968 func checkExpectedHtlcs(t *testing.T, actual []*PaymentDescriptor, 8969 expected map[uint64]bool) { 8970 8971 if len(expected) != len(actual) { 8972 t.Fatalf("expected: %v htlcs, got: %v", 8973 len(expected), len(actual)) 8974 } 8975 8976 for _, htlc := range actual { 8977 _, ok := expected[htlc.HtlcIndex] 8978 if !ok { 8979 t.Fatalf("htlc with index: %v not "+ 8980 "expected in set", htlc.HtlcIndex) 8981 } 8982 } 8983 } 8984 8985 // heights represents the heights on a payment descriptor. 8986 type heights struct { 8987 localAdd uint64 8988 localRemove uint64 8989 remoteAdd uint64 8990 remoteRemove uint64 8991 } 8992 8993 // TestProcessFeeUpdate tests the applying of fee updates and mutation of 8994 // local and remote add and remove heights on update messages. 8995 func TestProcessFeeUpdate(t *testing.T) { 8996 const ( 8997 // height is a non-zero height that can be used for htlcs 8998 // heights. 8999 height = 200 9000 9001 // nextHeight is a constant that we use for the next height in 9002 // all unit tests. 9003 nextHeight = 400 9004 9005 // feePerKB is the fee we start all of our unit tests with. 9006 feePerKB = 1 9007 9008 // ourFeeUpdateAmt is an amount that we update fees to expressed 9009 // in msat. 9010 ourFeeUpdateAmt = 20000 9011 9012 // ourFeeUpdatePerSat is the fee rate *in satoshis* that we 9013 // expect if we update to ourFeeUpdateAmt. 9014 ourFeeUpdatePerSat = chainfee.AtomPerKByte(20) 9015 ) 9016 9017 tests := []struct { 9018 name string 9019 startHeights heights 9020 expectedHeights heights 9021 remoteChain bool 9022 mutate bool 9023 expectedFee chainfee.AtomPerKByte 9024 }{ 9025 { 9026 // Looking at local chain, local add is non-zero so 9027 // the update has been applied already; no fee change. 9028 name: "non-zero local height, fee unchanged", 9029 startHeights: heights{ 9030 localAdd: height, 9031 localRemove: 0, 9032 remoteAdd: 0, 9033 remoteRemove: height, 9034 }, 9035 expectedHeights: heights{ 9036 localAdd: height, 9037 localRemove: 0, 9038 remoteAdd: 0, 9039 remoteRemove: height, 9040 }, 9041 remoteChain: false, 9042 mutate: false, 9043 expectedFee: feePerKB, 9044 }, 9045 { 9046 // Looking at local chain, local add is zero so the 9047 // update has not been applied yet; we expect a fee 9048 // update. 9049 name: "zero local height, fee changed", 9050 startHeights: heights{ 9051 localAdd: 0, 9052 localRemove: 0, 9053 remoteAdd: height, 9054 remoteRemove: 0, 9055 }, 9056 expectedHeights: heights{ 9057 localAdd: 0, 9058 localRemove: 0, 9059 remoteAdd: height, 9060 remoteRemove: 0, 9061 }, 9062 remoteChain: false, 9063 mutate: false, 9064 expectedFee: ourFeeUpdatePerSat, 9065 }, 9066 { 9067 // Looking at remote chain, the remote add height is 9068 // zero, so the update has not been applied so we expect 9069 // a fee change. 9070 name: "zero remote height, fee changed", 9071 startHeights: heights{ 9072 localAdd: height, 9073 localRemove: 0, 9074 remoteAdd: 0, 9075 remoteRemove: 0, 9076 }, 9077 expectedHeights: heights{ 9078 localAdd: height, 9079 localRemove: 0, 9080 remoteAdd: 0, 9081 remoteRemove: 0, 9082 }, 9083 remoteChain: true, 9084 mutate: false, 9085 expectedFee: ourFeeUpdatePerSat, 9086 }, 9087 { 9088 // Looking at remote chain, the remote add height is 9089 // non-zero, so the update has been applied so we expect 9090 // no fee change. 9091 name: "non-zero remote height, no fee change", 9092 startHeights: heights{ 9093 localAdd: height, 9094 localRemove: 0, 9095 remoteAdd: height, 9096 remoteRemove: 0, 9097 }, 9098 expectedHeights: heights{ 9099 localAdd: height, 9100 localRemove: 0, 9101 remoteAdd: height, 9102 remoteRemove: 0, 9103 }, 9104 remoteChain: true, 9105 mutate: false, 9106 expectedFee: feePerKB, 9107 }, 9108 { 9109 // Local add height is non-zero, so the update has 9110 // already been applied; we do not expect fee to 9111 // change or any mutations to be applied. 9112 name: "non-zero local height, mutation not applied", 9113 startHeights: heights{ 9114 localAdd: height, 9115 localRemove: 0, 9116 remoteAdd: 0, 9117 remoteRemove: height, 9118 }, 9119 expectedHeights: heights{ 9120 localAdd: height, 9121 localRemove: 0, 9122 remoteAdd: 0, 9123 remoteRemove: height, 9124 }, 9125 remoteChain: false, 9126 mutate: true, 9127 expectedFee: feePerKB, 9128 }, 9129 { 9130 // Local add is zero and we are looking at our local 9131 // chain, so the update has not been applied yet. We 9132 // expect the local add and remote heights to be 9133 // mutated. 9134 name: "zero height, fee changed, mutation applied", 9135 startHeights: heights{ 9136 localAdd: 0, 9137 localRemove: 0, 9138 remoteAdd: 0, 9139 remoteRemove: 0, 9140 }, 9141 expectedHeights: heights{ 9142 localAdd: nextHeight, 9143 localRemove: nextHeight, 9144 remoteAdd: 0, 9145 remoteRemove: 0, 9146 }, 9147 remoteChain: false, 9148 mutate: true, 9149 expectedFee: ourFeeUpdatePerSat, 9150 }, 9151 } 9152 9153 for _, test := range tests { 9154 test := test 9155 9156 t.Run(test.name, func(t *testing.T) { 9157 // Create a fee update with add and remove heights as 9158 // set in the test. 9159 heights := test.startHeights 9160 update := &PaymentDescriptor{ 9161 Amount: ourFeeUpdateAmt, 9162 addCommitHeightRemote: heights.remoteAdd, 9163 addCommitHeightLocal: heights.localAdd, 9164 removeCommitHeightRemote: heights.remoteRemove, 9165 removeCommitHeightLocal: heights.localRemove, 9166 EntryType: FeeUpdate, 9167 } 9168 9169 view := &htlcView{ 9170 feePerKB: chainfee.AtomPerKByte(feePerKB), 9171 } 9172 processFeeUpdate( 9173 update, nextHeight, test.remoteChain, 9174 test.mutate, view, 9175 ) 9176 9177 if view.feePerKB != test.expectedFee { 9178 t.Fatalf("expected fee: %v, got: %v", 9179 test.expectedFee, feePerKB) 9180 } 9181 9182 checkHeights(t, update, test.expectedHeights) 9183 }) 9184 } 9185 } 9186 9187 func checkHeights(t *testing.T, update *PaymentDescriptor, expected heights) { 9188 updateHeights := heights{ 9189 localAdd: update.addCommitHeightLocal, 9190 localRemove: update.removeCommitHeightLocal, 9191 remoteAdd: update.addCommitHeightRemote, 9192 remoteRemove: update.removeCommitHeightRemote, 9193 } 9194 9195 if !reflect.DeepEqual(updateHeights, expected) { 9196 t.Fatalf("expected: %v, got: %v", expected, updateHeights) 9197 } 9198 } 9199 9200 // TestProcessAddRemoveEntry tests the updating of our and their balances when 9201 // we process adds, settles and fails. It also tests the mutating of add and 9202 // remove heights. 9203 func TestProcessAddRemoveEntry(t *testing.T) { 9204 const ( 9205 // addHeight is a non-zero addHeight that is used for htlc 9206 // add heights. 9207 addHeight = 100 9208 9209 // removeHeight is a non-zero removeHeight that is used for 9210 // htlc remove heights. 9211 removeHeight = 200 9212 9213 // nextHeight is a constant that we use for the nextHeight in 9214 // all unit tests. 9215 nextHeight = 400 9216 9217 // updateAmount is the amount that the update is set to. 9218 updateAmount = lnwire.MilliAtom(10) 9219 9220 // startBalance is a balance we start both sides out with 9221 // so that balances can be incremented. 9222 startBalance = lnwire.MilliAtom(100) 9223 ) 9224 9225 tests := []struct { 9226 name string 9227 startHeights heights 9228 remoteChain bool 9229 isIncoming bool 9230 mutateState bool 9231 ourExpectedBalance lnwire.MilliAtom 9232 theirExpectedBalance lnwire.MilliAtom 9233 expectedHeights heights 9234 updateType updateType 9235 }{ 9236 { 9237 name: "add, remote chain, already processed", 9238 startHeights: heights{ 9239 localAdd: 0, 9240 remoteAdd: addHeight, 9241 localRemove: 0, 9242 remoteRemove: 0, 9243 }, 9244 remoteChain: true, 9245 isIncoming: false, 9246 mutateState: false, 9247 ourExpectedBalance: startBalance, 9248 theirExpectedBalance: startBalance, 9249 expectedHeights: heights{ 9250 localAdd: 0, 9251 remoteAdd: addHeight, 9252 localRemove: 0, 9253 remoteRemove: 0, 9254 }, 9255 updateType: Add, 9256 }, 9257 { 9258 name: "add, local chain, already processed", 9259 startHeights: heights{ 9260 localAdd: addHeight, 9261 remoteAdd: 0, 9262 localRemove: 0, 9263 remoteRemove: 0, 9264 }, 9265 remoteChain: false, 9266 isIncoming: false, 9267 mutateState: false, 9268 ourExpectedBalance: startBalance, 9269 theirExpectedBalance: startBalance, 9270 expectedHeights: heights{ 9271 localAdd: addHeight, 9272 remoteAdd: 0, 9273 localRemove: 0, 9274 remoteRemove: 0, 9275 }, 9276 updateType: Add, 9277 }, 9278 { 9279 name: "incoming add, local chain, not mutated", 9280 startHeights: heights{ 9281 localAdd: 0, 9282 remoteAdd: 0, 9283 localRemove: 0, 9284 remoteRemove: 0, 9285 }, 9286 remoteChain: false, 9287 isIncoming: true, 9288 mutateState: false, 9289 ourExpectedBalance: startBalance, 9290 theirExpectedBalance: startBalance - updateAmount, 9291 expectedHeights: heights{ 9292 localAdd: 0, 9293 remoteAdd: 0, 9294 localRemove: 0, 9295 remoteRemove: 0, 9296 }, 9297 updateType: Add, 9298 }, 9299 { 9300 name: "incoming add, local chain, mutated", 9301 startHeights: heights{ 9302 localAdd: 0, 9303 remoteAdd: 0, 9304 localRemove: 0, 9305 remoteRemove: 0, 9306 }, 9307 remoteChain: false, 9308 isIncoming: true, 9309 mutateState: true, 9310 ourExpectedBalance: startBalance, 9311 theirExpectedBalance: startBalance - updateAmount, 9312 expectedHeights: heights{ 9313 localAdd: nextHeight, 9314 remoteAdd: 0, 9315 localRemove: 0, 9316 remoteRemove: 0, 9317 }, 9318 updateType: Add, 9319 }, 9320 9321 { 9322 name: "outgoing add, remote chain, not mutated", 9323 startHeights: heights{ 9324 localAdd: 0, 9325 remoteAdd: 0, 9326 localRemove: 0, 9327 remoteRemove: 0, 9328 }, 9329 remoteChain: true, 9330 isIncoming: false, 9331 mutateState: false, 9332 ourExpectedBalance: startBalance - updateAmount, 9333 theirExpectedBalance: startBalance, 9334 expectedHeights: heights{ 9335 localAdd: 0, 9336 remoteAdd: 0, 9337 localRemove: 0, 9338 remoteRemove: 0, 9339 }, 9340 updateType: Add, 9341 }, 9342 { 9343 name: "outgoing add, remote chain, mutated", 9344 startHeights: heights{ 9345 localAdd: 0, 9346 remoteAdd: 0, 9347 localRemove: 0, 9348 remoteRemove: 0, 9349 }, 9350 remoteChain: true, 9351 isIncoming: false, 9352 mutateState: true, 9353 ourExpectedBalance: startBalance - updateAmount, 9354 theirExpectedBalance: startBalance, 9355 expectedHeights: heights{ 9356 localAdd: 0, 9357 remoteAdd: nextHeight, 9358 localRemove: 0, 9359 remoteRemove: 0, 9360 }, 9361 updateType: Add, 9362 }, 9363 { 9364 name: "settle, remote chain, already processed", 9365 startHeights: heights{ 9366 localAdd: addHeight, 9367 remoteAdd: addHeight, 9368 localRemove: 0, 9369 remoteRemove: removeHeight, 9370 }, 9371 remoteChain: true, 9372 isIncoming: false, 9373 mutateState: false, 9374 ourExpectedBalance: startBalance, 9375 theirExpectedBalance: startBalance, 9376 expectedHeights: heights{ 9377 localAdd: addHeight, 9378 remoteAdd: addHeight, 9379 localRemove: 0, 9380 remoteRemove: removeHeight, 9381 }, 9382 updateType: Settle, 9383 }, 9384 { 9385 name: "settle, local chain, already processed", 9386 startHeights: heights{ 9387 localAdd: addHeight, 9388 remoteAdd: addHeight, 9389 localRemove: removeHeight, 9390 remoteRemove: 0, 9391 }, 9392 remoteChain: false, 9393 isIncoming: false, 9394 mutateState: false, 9395 ourExpectedBalance: startBalance, 9396 theirExpectedBalance: startBalance, 9397 expectedHeights: heights{ 9398 localAdd: addHeight, 9399 remoteAdd: addHeight, 9400 localRemove: removeHeight, 9401 remoteRemove: 0, 9402 }, 9403 updateType: Settle, 9404 }, 9405 { 9406 // Remote chain, and not processed yet. Incoming settle, 9407 // so we expect our balance to increase. 9408 name: "incoming settle", 9409 startHeights: heights{ 9410 localAdd: addHeight, 9411 remoteAdd: addHeight, 9412 localRemove: 0, 9413 remoteRemove: 0, 9414 }, 9415 remoteChain: true, 9416 isIncoming: true, 9417 mutateState: false, 9418 ourExpectedBalance: startBalance + updateAmount, 9419 theirExpectedBalance: startBalance, 9420 expectedHeights: heights{ 9421 localAdd: addHeight, 9422 remoteAdd: addHeight, 9423 localRemove: 0, 9424 remoteRemove: 0, 9425 }, 9426 updateType: Settle, 9427 }, 9428 { 9429 // Remote chain, and not processed yet. Incoming settle, 9430 // so we expect our balance to increase. 9431 name: "outgoing settle", 9432 startHeights: heights{ 9433 localAdd: addHeight, 9434 remoteAdd: addHeight, 9435 localRemove: 0, 9436 remoteRemove: 0, 9437 }, 9438 remoteChain: true, 9439 isIncoming: false, 9440 mutateState: false, 9441 ourExpectedBalance: startBalance, 9442 theirExpectedBalance: startBalance + updateAmount, 9443 expectedHeights: heights{ 9444 localAdd: addHeight, 9445 remoteAdd: addHeight, 9446 localRemove: 0, 9447 remoteRemove: 0, 9448 }, 9449 updateType: Settle, 9450 }, 9451 { 9452 // Remote chain, and not processed yet. Incoming fail, 9453 // so we expect their balance to increase. 9454 name: "incoming fail", 9455 startHeights: heights{ 9456 localAdd: addHeight, 9457 remoteAdd: addHeight, 9458 localRemove: 0, 9459 remoteRemove: 0, 9460 }, 9461 remoteChain: true, 9462 isIncoming: true, 9463 mutateState: false, 9464 ourExpectedBalance: startBalance, 9465 theirExpectedBalance: startBalance + updateAmount, 9466 expectedHeights: heights{ 9467 localAdd: addHeight, 9468 remoteAdd: addHeight, 9469 localRemove: 0, 9470 remoteRemove: 0, 9471 }, 9472 updateType: Fail, 9473 }, 9474 { 9475 // Remote chain, and not processed yet. Outgoing fail, 9476 // so we expect our balance to increase. 9477 name: "outgoing fail", 9478 startHeights: heights{ 9479 localAdd: addHeight, 9480 remoteAdd: addHeight, 9481 localRemove: 0, 9482 remoteRemove: 0, 9483 }, 9484 remoteChain: true, 9485 isIncoming: false, 9486 mutateState: false, 9487 ourExpectedBalance: startBalance + updateAmount, 9488 theirExpectedBalance: startBalance, 9489 expectedHeights: heights{ 9490 localAdd: addHeight, 9491 remoteAdd: addHeight, 9492 localRemove: 0, 9493 remoteRemove: 0, 9494 }, 9495 updateType: Fail, 9496 }, 9497 { 9498 // Local chain, and not processed yet. Incoming settle, 9499 // so we expect our balance to increase. Mutate is 9500 // true, so we expect our remove removeHeight to have 9501 // changed. 9502 name: "fail, our remove height mutated", 9503 startHeights: heights{ 9504 localAdd: addHeight, 9505 remoteAdd: addHeight, 9506 localRemove: 0, 9507 remoteRemove: 0, 9508 }, 9509 remoteChain: false, 9510 isIncoming: true, 9511 mutateState: true, 9512 ourExpectedBalance: startBalance + updateAmount, 9513 theirExpectedBalance: startBalance, 9514 expectedHeights: heights{ 9515 localAdd: addHeight, 9516 remoteAdd: addHeight, 9517 localRemove: nextHeight, 9518 remoteRemove: 0, 9519 }, 9520 updateType: Settle, 9521 }, 9522 { 9523 // Remote chain, and not processed yet. Incoming settle, 9524 // so we expect our balance to increase. Mutate is 9525 // true, so we expect their remove removeHeight to have 9526 // changed. 9527 name: "fail, their remove height mutated", 9528 startHeights: heights{ 9529 localAdd: addHeight, 9530 remoteAdd: addHeight, 9531 localRemove: 0, 9532 remoteRemove: 0, 9533 }, 9534 remoteChain: true, 9535 isIncoming: true, 9536 mutateState: true, 9537 ourExpectedBalance: startBalance + updateAmount, 9538 theirExpectedBalance: startBalance, 9539 expectedHeights: heights{ 9540 localAdd: addHeight, 9541 remoteAdd: addHeight, 9542 localRemove: 0, 9543 remoteRemove: nextHeight, 9544 }, 9545 updateType: Settle, 9546 }, 9547 } 9548 9549 for _, test := range tests { 9550 test := test 9551 9552 t.Run(test.name, func(t *testing.T) { 9553 t.Parallel() 9554 9555 heights := test.startHeights 9556 update := &PaymentDescriptor{ 9557 Amount: updateAmount, 9558 addCommitHeightLocal: heights.localAdd, 9559 addCommitHeightRemote: heights.remoteAdd, 9560 removeCommitHeightLocal: heights.localRemove, 9561 removeCommitHeightRemote: heights.remoteRemove, 9562 EntryType: test.updateType, 9563 } 9564 9565 var ( 9566 // Start both parties off with an initial 9567 // balance. Copy by value here so that we do 9568 // not mutate the startBalance constant. 9569 ourBalance, theirBalance = startBalance, 9570 startBalance 9571 ) 9572 9573 // Choose the processing function we need based on the 9574 // update type. Process remove is used for settles, 9575 // fails and malformed htlcs. 9576 process := processRemoveEntry 9577 if test.updateType == Add { 9578 process = processAddEntry 9579 } 9580 9581 process( 9582 update, &ourBalance, &theirBalance, nextHeight, 9583 test.remoteChain, test.isIncoming, 9584 test.mutateState, 9585 ) 9586 9587 // Check that balances were updated as expected. 9588 if ourBalance != test.ourExpectedBalance { 9589 t.Fatalf("expected our balance: %v, got: %v", 9590 test.ourExpectedBalance, ourBalance) 9591 } 9592 9593 if theirBalance != test.theirExpectedBalance { 9594 t.Fatalf("expected their balance: %v, got: %v", 9595 test.theirExpectedBalance, theirBalance) 9596 } 9597 9598 // Check that heights on the update are as expected. 9599 checkHeights(t, update, test.expectedHeights) 9600 }) 9601 } 9602 } 9603 9604 // TestChannelUnsignedAckedFailure tests that unsigned acked updates are 9605 // properly restored after signing for them and disconnecting. 9606 // 9607 // The full state transition of this test is: 9608 // 9609 // Alice Bob 9610 // 9611 // -----add-----> 9612 // -----sig-----> 9613 // <----rev------ 9614 // <----sig------ 9615 // -----rev-----> 9616 // <----fail----- 9617 // <----sig------ 9618 // -----rev-----> 9619 // -----sig-----X (does not reach Bob! Alice dies!) 9620 // 9621 // -----sig-----> 9622 // <----rev------ 9623 // <----add------ 9624 // <----sig------ 9625 // 9626 // The last sig was rejected with the old behavior of deleting unsigned 9627 // acked updates from the database after signing for them. The current 9628 // behavior of filtering them for deletion upon receiving a revocation 9629 // causes Alice to accept the signature as valid. 9630 func TestChannelUnsignedAckedFailure(t *testing.T) { 9631 t.Parallel() 9632 9633 // Create a test channel so that we can test the buggy behavior. 9634 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 9635 channeldb.SingleFunderTweaklessBit, 9636 ) 9637 require.NoError(t, err) 9638 defer cleanUp() 9639 9640 // First we create an HTLC that Alice sends to Bob. 9641 htlc, _ := createHTLC(0, lnwire.MilliAtom(500000)) 9642 9643 // -----add-----> 9644 _, err = aliceChannel.AddHTLC(htlc, nil) 9645 require.NoError(t, err) 9646 _, err = bobChannel.ReceiveHTLC(htlc) 9647 require.NoError(t, err) 9648 9649 // Force a state transition to lock in this add on both commitments. 9650 // -----sig-----> 9651 // <----rev------ 9652 // <----sig------ 9653 // -----rev-----> 9654 err = ForceStateTransition(aliceChannel, bobChannel) 9655 require.NoError(t, err) 9656 9657 // Now Bob should fail the htlc back to Alice. 9658 // <----fail----- 9659 err = bobChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 9660 require.NoError(t, err) 9661 err = aliceChannel.ReceiveFailHTLC(0, []byte("bad")) 9662 require.NoError(t, err) 9663 9664 // Bob should send a commitment signature to Alice. 9665 // <----sig------ 9666 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 9667 require.NoError(t, err) 9668 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 9669 require.NoError(t, err) 9670 9671 // Alice should reply with a revocation. 9672 // -----rev-----> 9673 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 9674 require.NoError(t, err) 9675 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 9676 require.NoError(t, err) 9677 9678 // Alice should sign the next commitment and go down before 9679 // sending it. 9680 // -----sig-----X 9681 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 9682 require.NoError(t, err) 9683 9684 newAliceChannel, err := NewLightningChannel( 9685 aliceChannel.Signer, aliceChannel.channelState, 9686 aliceChannel.sigPool, testChainParams, 9687 ) 9688 require.NoError(t, err) 9689 9690 // Bob receives Alice's signature. 9691 // -----sig-----> 9692 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 9693 require.NoError(t, err) 9694 9695 // Bob revokes his current commitment and sends a revocation 9696 // to Alice. 9697 // <----rev------ 9698 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 9699 require.NoError(t, err) 9700 _, _, _, _, err = newAliceChannel.ReceiveRevocation(bobRevocation) 9701 require.NoError(t, err) 9702 9703 // Now Bob sends an HTLC to Alice. 9704 htlc2, _ := createHTLC(0, lnwire.MilliAtom(500000)) 9705 9706 // <----add------ 9707 _, err = bobChannel.AddHTLC(htlc2, nil) 9708 require.NoError(t, err) 9709 _, err = newAliceChannel.ReceiveHTLC(htlc2) 9710 require.NoError(t, err) 9711 9712 // Bob sends the final signature to Alice and Alice should not 9713 // reject it, given that we properly restore the unsigned acked 9714 // updates and therefore our update log is structured correctly. 9715 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 9716 require.NoError(t, err) 9717 err = newAliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 9718 require.NoError(t, err) 9719 } 9720 9721 // TestChannelLocalUnsignedUpdatesFailure checks that updates from the local 9722 // log are restored if the remote hasn't sent us a signature covering them. 9723 // 9724 // The full state transition is: 9725 // 9726 // Alice Bob 9727 // 9728 // <----add----- 9729 // <----sig----- 9730 // -----rev----> 9731 // -----sig----> 9732 // <----rev----- 9733 // ----fail----> 9734 // -----sig----> 9735 // <----rev----- 9736 // *reconnect* 9737 // <----sig----- 9738 // 9739 // Alice should reject the last signature since the settle is not restored 9740 // into the local update log and thus calculates Bob's signature as invalid. 9741 func TestChannelLocalUnsignedUpdatesFailure(t *testing.T) { 9742 t.Parallel() 9743 9744 // Create a test channel so that we can test the buggy behavior. 9745 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 9746 channeldb.SingleFunderTweaklessBit, 9747 ) 9748 require.NoError(t, err) 9749 defer cleanUp() 9750 9751 // First we create an htlc that Bob sends to Alice. 9752 htlc, _ := createHTLC(0, lnwire.MilliAtom(500000)) 9753 9754 // <----add----- 9755 _, err = bobChannel.AddHTLC(htlc, nil) 9756 require.NoError(t, err) 9757 _, err = aliceChannel.ReceiveHTLC(htlc) 9758 require.NoError(t, err) 9759 9760 // Force a state transition to lock in this add on both commitments. 9761 // <----sig----- 9762 // -----rev----> 9763 // -----sig----> 9764 // <----rev----- 9765 err = ForceStateTransition(bobChannel, aliceChannel) 9766 require.NoError(t, err) 9767 9768 // Now Alice should fail the htlc back to Bob. 9769 // -----fail---> 9770 err = aliceChannel.FailHTLC(0, []byte("failreason"), nil, nil, nil) 9771 require.NoError(t, err) 9772 err = bobChannel.ReceiveFailHTLC(0, []byte("bad")) 9773 require.NoError(t, err) 9774 9775 // Alice should send a commitment signature to Bob. 9776 // -----sig----> 9777 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 9778 require.NoError(t, err) 9779 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 9780 require.NoError(t, err) 9781 9782 // Bob should reply with a revocation and Alice should save the fail as 9783 // an unsigned local update. 9784 // <----rev----- 9785 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 9786 require.NoError(t, err) 9787 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 9788 require.NoError(t, err) 9789 9790 // Restart Alice and assert that she can receive Bob's next commitment 9791 // signature. 9792 // *reconnect* 9793 newAliceChannel, err := NewLightningChannel( 9794 aliceChannel.Signer, aliceChannel.channelState, 9795 aliceChannel.sigPool, testChainParams, 9796 ) 9797 require.NoError(t, err) 9798 9799 // Bob sends the final signature and Alice should not reject it. 9800 // <----sig----- 9801 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 9802 require.NoError(t, err) 9803 err = newAliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 9804 require.NoError(t, err) 9805 } 9806 9807 // TestChannelSignedAckRegression tests a previously-regressing state 9808 // transition no longer causes channel desynchronization. 9809 // 9810 // The full state transition of this test is: 9811 // 9812 // Alice Bob 9813 // 9814 // <----add------- 9815 // <----sig------- 9816 // -----rev------> 9817 // -----sig------> 9818 // <----rev------- 9819 // ----settle----> 9820 // -----sig------> 9821 // <----rev------- 9822 // <----sig------- 9823 // -----add------> 9824 // -----sig------> 9825 // <----rev------- 9826 // *restarts* 9827 // -----rev------> 9828 // <----sig------- 9829 func TestChannelSignedAckRegression(t *testing.T) { 9830 t.Parallel() 9831 9832 // Create test channels to test out this state transition. 9833 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 9834 channeldb.SingleFunderTweaklessBit, 9835 ) 9836 require.NoError(t, err) 9837 defer cleanUp() 9838 9839 // Create an HTLC that Bob will send to Alice. 9840 htlc, preimage := createHTLC(0, lnwire.MilliAtom(5000000)) 9841 9842 // <----add------ 9843 _, err = bobChannel.AddHTLC(htlc, nil) 9844 require.NoError(t, err) 9845 _, err = aliceChannel.ReceiveHTLC(htlc) 9846 require.NoError(t, err) 9847 9848 // Force a state transition to lock in the HTLC. 9849 // <----sig------ 9850 // -----rev-----> 9851 // -----sig-----> 9852 // <----rev------ 9853 err = ForceStateTransition(bobChannel, aliceChannel) 9854 require.NoError(t, err) 9855 9856 // Alice settles the HTLC back to Bob. 9857 // ----settle---> 9858 err = aliceChannel.SettleHTLC(preimage, uint64(0), nil, nil, nil) 9859 require.NoError(t, err) 9860 err = bobChannel.ReceiveHTLCSettle(preimage, uint64(0)) 9861 require.NoError(t, err) 9862 9863 // -----sig----> 9864 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 9865 require.NoError(t, err) 9866 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 9867 require.NoError(t, err) 9868 9869 // <----rev----- 9870 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 9871 require.NoError(t, err) 9872 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 9873 require.NoError(t, err) 9874 9875 // <----sig----- 9876 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 9877 require.NoError(t, err) 9878 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 9879 require.NoError(t, err) 9880 9881 // Create an HTLC that Alice will send to Bob. 9882 htlc2, _ := createHTLC(0, lnwire.MilliAtom(5000000)) 9883 9884 // -----add----> 9885 _, err = aliceChannel.AddHTLC(htlc2, nil) 9886 require.NoError(t, err) 9887 _, err = bobChannel.ReceiveHTLC(htlc2) 9888 require.NoError(t, err) 9889 9890 // -----sig----> 9891 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 9892 require.NoError(t, err) 9893 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 9894 require.NoError(t, err) 9895 9896 // <----rev----- 9897 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 9898 require.NoError(t, err) 9899 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 9900 require.NoError(t, err) 9901 9902 // Restart Bob's channel state here. 9903 newBobChannel, err := NewLightningChannel( 9904 bobChannel.Signer, bobChannel.channelState, 9905 bobChannel.sigPool, testChainParams, 9906 ) 9907 require.NoError(t, err) 9908 9909 // -----rev----> 9910 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 9911 require.NoError(t, err) 9912 fwdPkg, _, _, _, err := newBobChannel.ReceiveRevocation(aliceRevocation) 9913 require.NoError(t, err) 9914 9915 // Assert that the fwdpkg is not empty. 9916 require.Equal(t, len(fwdPkg.SettleFails), 1) 9917 9918 // Bob should no longer fail to sign this commitment due to faulty 9919 // update logs. 9920 // <----sig----- 9921 bobSig, bobHtlcSigs, _, err = newBobChannel.SignNextCommitment() 9922 require.NoError(t, err) 9923 9924 // Alice should receive the new commitment without hiccups. 9925 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 9926 require.NoError(t, err) 9927 } 9928 9929 // TestMayAddOutgoingHtlc tests MayAddOutgoingHtlc against zero and non-zero 9930 // htlc amounts. 9931 func TestMayAddOutgoingHtlc(t *testing.T) { 9932 t.Parallel() 9933 9934 // The default channel created as a part of the test fixture already 9935 // has a MinHTLC value of zero, so we don't need to do anything here 9936 // other than create it. 9937 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 9938 channeldb.SingleFunderTweaklessBit, 9939 ) 9940 require.NoError(t, err) 9941 defer cleanUp() 9942 9943 // The channels start out with a 50/50 balance, so both sides should be 9944 // able to add an outgoing HTLC with no specific amount added. 9945 require.NoError(t, aliceChannel.MayAddOutgoingHtlc(0)) 9946 require.NoError(t, bobChannel.MayAddOutgoingHtlc(0)) 9947 9948 chanBal, err := dcrutil.NewAmount(testChannelCapacity) 9949 require.NoError(t, err) 9950 9951 // Each side should be able to add 1/4 of total channel balance since 9952 // we're 50/50 split. 9953 mayAdd := lnwire.MilliAtom(chanBal / 4 * 1000) 9954 require.NoError(t, aliceChannel.MayAddOutgoingHtlc(mayAdd)) 9955 require.NoError(t, bobChannel.MayAddOutgoingHtlc(mayAdd)) 9956 9957 // Both channels should fail if we try to add an amount more than 9958 // their current balance. 9959 mayNotAdd := lnwire.MilliAtom(chanBal * 1000) 9960 require.Error(t, aliceChannel.MayAddOutgoingHtlc(mayNotAdd)) 9961 require.Error(t, bobChannel.MayAddOutgoingHtlc(mayNotAdd)) 9962 9963 // Hard set alice's min htlc to zero and test the case where we just 9964 // fall back to a non-zero value. 9965 aliceChannel.channelState.LocalChanCfg.MinHTLC = 0 9966 require.NoError(t, aliceChannel.MayAddOutgoingHtlc(0)) 9967 } 9968 9969 // TestIsChannelClean tests that IsChannelClean returns the expected values 9970 // in different channel states. 9971 func TestIsChannelClean(t *testing.T) { 9972 t.Parallel() 9973 9974 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels( 9975 channeldb.ZeroHtlcTxFeeBit, 9976 ) 9977 require.NoError(t, err) 9978 defer cleanUp() 9979 9980 // Channel state should be clean at the start of the test. 9981 assertCleanOrDirty(true, aliceChannel, bobChannel, t) 9982 9983 // Assert that neither side considers the channel clean when alice 9984 // sends an htlc. 9985 // ---add---> 9986 htlc, preimage := createHTLC(0, lnwire.MilliAtom(5000000)) 9987 _, err = aliceChannel.AddHTLC(htlc, nil) 9988 require.NoError(t, err) 9989 _, err = bobChannel.ReceiveHTLC(htlc) 9990 require.NoError(t, err) 9991 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 9992 9993 // Assert that the channel remains dirty until the HTLC is completely 9994 // removed from both commitments. 9995 9996 // ---sig---> 9997 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 9998 require.NoError(t, err) 9999 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 10000 require.NoError(t, err) 10001 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10002 10003 // <---rev--- 10004 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 10005 require.NoError(t, err) 10006 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 10007 require.NoError(t, err) 10008 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10009 10010 // <---sig--- 10011 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 10012 require.NoError(t, err) 10013 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 10014 require.NoError(t, err) 10015 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10016 10017 // ---rev---> 10018 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 10019 require.NoError(t, err) 10020 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 10021 require.NoError(t, err) 10022 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10023 10024 // <--settle-- 10025 err = bobChannel.SettleHTLC(preimage, 0, nil, nil, nil) 10026 require.NoError(t, err) 10027 err = aliceChannel.ReceiveHTLCSettle(preimage, 0) 10028 require.NoError(t, err) 10029 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10030 10031 // <---sig--- 10032 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 10033 require.NoError(t, err) 10034 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 10035 require.NoError(t, err) 10036 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10037 10038 // ---rev---> 10039 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 10040 require.NoError(t, err) 10041 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 10042 require.NoError(t, err) 10043 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10044 10045 // ---sig---> 10046 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 10047 require.NoError(t, err) 10048 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 10049 require.NoError(t, err) 10050 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10051 10052 // <---rev--- 10053 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 10054 require.NoError(t, err) 10055 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 10056 require.NoError(t, err) 10057 assertCleanOrDirty(true, aliceChannel, bobChannel, t) 10058 10059 // Now we check that update_fee is handled and state is dirty until it 10060 // is completely locked in. 10061 // ---fee---> 10062 fee := chainfee.AtomPerKByte(50_000) 10063 err = aliceChannel.UpdateFee(fee) 10064 require.NoError(t, err) 10065 err = bobChannel.ReceiveUpdateFee(fee) 10066 require.NoError(t, err) 10067 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10068 10069 // ---sig---> 10070 aliceSig, aliceHtlcSigs, _, err = aliceChannel.SignNextCommitment() 10071 require.NoError(t, err) 10072 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 10073 require.NoError(t, err) 10074 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10075 10076 // <---rev--- 10077 bobRevocation, _, err = bobChannel.RevokeCurrentCommitment() 10078 require.NoError(t, err) 10079 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 10080 require.NoError(t, err) 10081 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10082 10083 // <---sig--- 10084 bobSig, bobHtlcSigs, _, err = bobChannel.SignNextCommitment() 10085 require.NoError(t, err) 10086 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 10087 require.NoError(t, err) 10088 assertCleanOrDirty(false, aliceChannel, bobChannel, t) 10089 10090 // The state should finally be clean after alice sends her revocation. 10091 // ---rev---> 10092 aliceRevocation, _, err = aliceChannel.RevokeCurrentCommitment() 10093 require.NoError(t, err) 10094 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 10095 require.NoError(t, err) 10096 assertCleanOrDirty(true, aliceChannel, bobChannel, t) 10097 } 10098 10099 // assertCleanOrDirty is a helper function that asserts that both channels are 10100 // clean if clean is true, and dirty if clean is false. 10101 func assertCleanOrDirty(clean bool, alice, bob *LightningChannel, 10102 t *testing.T) { 10103 10104 t.Helper() 10105 10106 if clean { 10107 require.True(t, alice.IsChannelClean()) 10108 require.True(t, bob.IsChannelClean()) 10109 return 10110 } 10111 10112 require.False(t, alice.IsChannelClean()) 10113 require.False(t, bob.IsChannelClean()) 10114 } 10115 10116 // TestChannelGetDustSum tests that we correctly calculate the channel's dust 10117 // sum for the local and remote commitments. 10118 func TestChannelGetDustSum(t *testing.T) { 10119 t.Run("dust sum tweakless", func(t *testing.T) { 10120 testGetDustSum(t, channeldb.SingleFunderTweaklessBit) 10121 }) 10122 t.Run("dust sum anchors zero htlc fee", func(t *testing.T) { 10123 testGetDustSum(t, channeldb.SingleFunderTweaklessBit| 10124 channeldb.AnchorOutputsBit| 10125 channeldb.ZeroHtlcTxFeeBit, 10126 ) 10127 }) 10128 } 10129 10130 func testGetDustSum(t *testing.T, chantype channeldb.ChannelType) { 10131 t.Parallel() 10132 10133 testAmt := lnwire.MilliAtom(30_000 * 1000) 10134 if chantype.ZeroHtlcTxFee() { 10135 testAmt = 10_000 * 1000 10136 } 10137 10138 // This makes a channel with Alice's dust limit set to 6030 atoms and 10139 // Bob's dust limit set to 12060 atoms. 10140 aliceChannel, bobChannel, cleanUp, err := CreateTestChannels(chantype) 10141 require.NoError(t, err) 10142 defer cleanUp() 10143 10144 // Use a function closure to assert the dust sum for a passed channel's 10145 // local and remote commitments match the expected values. 10146 checkDust := func(c *LightningChannel, expLocal, 10147 expRemote lnwire.MilliAtom) { 10148 10149 localDustSum := c.GetDustSum(false) 10150 require.Equal(t, expLocal, localDustSum) 10151 remoteDustSum := c.GetDustSum(true) 10152 require.Equal(t, expRemote, remoteDustSum) 10153 } 10154 10155 // We'll lower the fee from 100000 atoms/kB to 50000 atoms/kBfor our test. 10156 fee := chainfee.AtomPerKByte(50000) 10157 err = aliceChannel.UpdateFee(fee) 10158 require.NoError(t, err) 10159 err = bobChannel.ReceiveUpdateFee(fee) 10160 require.NoError(t, err) 10161 err = ForceStateTransition(aliceChannel, bobChannel) 10162 require.NoError(t, err) 10163 10164 // Create an HTLC that Bob will send to Alice which is above Alice's 10165 // dust limit and below Bob's dust limit. This takes into account dust 10166 // trimming for non-zero-fee channels. 10167 htlc1Amt := testAmt 10168 htlc1, preimage1 := createHTLC(0, htlc1Amt) 10169 10170 _, err = bobChannel.AddHTLC(htlc1, nil) 10171 require.NoError(t, err) 10172 _, err = aliceChannel.ReceiveHTLC(htlc1) 10173 require.NoError(t, err) 10174 10175 // Assert that GetDustSum from Alice's perspective does not consider 10176 // the HTLC dust on her commitment, but does on Bob's commitment. 10177 checkDust(aliceChannel, lnwire.MilliAtom(0), htlc1Amt) 10178 10179 // Assert that GetDustSum from Bob's perspective results in the same 10180 // conditions above holding. 10181 checkDust(bobChannel, htlc1Amt, lnwire.MilliAtom(0)) 10182 10183 // Forcing a state transition to occur should not change the dust sum. 10184 err = ForceStateTransition(bobChannel, aliceChannel) 10185 require.NoError(t, err) 10186 checkDust(aliceChannel, lnwire.MilliAtom(0), htlc1Amt) 10187 checkDust(bobChannel, htlc1Amt, lnwire.MilliAtom(0)) 10188 10189 // Settling the HTLC back from Alice to Bob should not change the dust 10190 // sum because the HTLC is counted until it's removed from the update 10191 // logs via compactLogs. 10192 err = aliceChannel.SettleHTLC(preimage1, uint64(0), nil, nil, nil) 10193 require.NoError(t, err) 10194 err = bobChannel.ReceiveHTLCSettle(preimage1, uint64(0)) 10195 require.NoError(t, err) 10196 checkDust(aliceChannel, lnwire.MilliAtom(0), htlc1Amt) 10197 checkDust(bobChannel, htlc1Amt, lnwire.MilliAtom(0)) 10198 10199 // Forcing a state transition will remove the HTLC in-memory for Bob 10200 // since ReceiveRevocation is called which calls compactLogs. Bob 10201 // should have a zero dust sum at this point. Alice will see Bob as 10202 // having the original dust sum since compactLogs hasn't been called. 10203 err = ForceStateTransition(aliceChannel, bobChannel) 10204 require.NoError(t, err) 10205 checkDust(aliceChannel, lnwire.MilliAtom(0), htlc1Amt) 10206 checkDust(bobChannel, lnwire.MilliAtom(0), lnwire.MilliAtom(0)) 10207 10208 // Alice now sends an HTLC of 100 atoms, which is below both sides' dust 10209 // limits. 10210 htlc2Amt := lnwire.MilliAtom(100 * 100) 10211 htlc2, _ := createHTLC(0, htlc2Amt) 10212 10213 _, err = aliceChannel.AddHTLC(htlc2, nil) 10214 require.NoError(t, err) 10215 _, err = bobChannel.ReceiveHTLC(htlc2) 10216 require.NoError(t, err) 10217 10218 // Assert that GetDustSum from Alice's perspective includes the new 10219 // HTLC as dust on both commitments. 10220 checkDust(aliceChannel, htlc2Amt, htlc1Amt+htlc2Amt) 10221 10222 // Assert that GetDustSum from Bob's perspective also includes the HTLC 10223 // on both commitments. 10224 checkDust(bobChannel, htlc2Amt, htlc2Amt) 10225 10226 // Alice signs for this HTLC and neither perspective should change. 10227 aliceSig, aliceHtlcSigs, _, err := aliceChannel.SignNextCommitment() 10228 require.NoError(t, err) 10229 err = bobChannel.ReceiveNewCommitment(aliceSig, aliceHtlcSigs) 10230 require.NoError(t, err) 10231 checkDust(aliceChannel, htlc2Amt, htlc1Amt+htlc2Amt) 10232 checkDust(bobChannel, htlc2Amt, htlc2Amt) 10233 10234 // Bob now sends a revocation for his prior commitment, and this should 10235 // change Alice's perspective to no longer include the first HTLC as 10236 // dust. 10237 bobRevocation, _, err := bobChannel.RevokeCurrentCommitment() 10238 require.NoError(t, err) 10239 _, _, _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) 10240 require.NoError(t, err) 10241 checkDust(aliceChannel, htlc2Amt, htlc2Amt) 10242 checkDust(bobChannel, htlc2Amt, htlc2Amt) 10243 10244 // The rest of the dance is completed and neither perspective should 10245 // change. 10246 bobSig, bobHtlcSigs, _, err := bobChannel.SignNextCommitment() 10247 require.NoError(t, err) 10248 err = aliceChannel.ReceiveNewCommitment(bobSig, bobHtlcSigs) 10249 require.NoError(t, err) 10250 aliceRevocation, _, err := aliceChannel.RevokeCurrentCommitment() 10251 require.NoError(t, err) 10252 _, _, _, _, err = bobChannel.ReceiveRevocation(aliceRevocation) 10253 require.NoError(t, err) 10254 checkDust(aliceChannel, htlc2Amt, htlc2Amt) 10255 checkDust(bobChannel, htlc2Amt, htlc2Amt) 10256 10257 // We'll now assert that if Alice sends an HTLC above her dust limit 10258 // and then updates the fee of the channel to trigger the trimmed to 10259 // dust mechanism, Alice will count this HTLC in the dust sum for her 10260 // commitment in the non-zero-fee case. 10261 htlc3Amt := testAmt 10262 htlc3, _ := createHTLC(1, htlc3Amt) 10263 10264 _, err = aliceChannel.AddHTLC(htlc3, nil) 10265 require.NoError(t, err) 10266 _, err = bobChannel.ReceiveHTLC(htlc3) 10267 require.NoError(t, err) 10268 10269 // Assert that this new HTLC is not counted on Alice's local commitment 10270 // in the dust sum. Bob's commitment should count it. 10271 checkDust(aliceChannel, htlc2Amt, htlc2Amt+htlc3Amt) 10272 checkDust(bobChannel, htlc2Amt+htlc3Amt, htlc2Amt) 10273 10274 // Alice will now send UpdateFee with a large feerate and neither 10275 // perspective should change. 10276 fee = chainfee.AtomPerKByte(100_000) 10277 err = aliceChannel.UpdateFee(fee) 10278 require.NoError(t, err) 10279 err = bobChannel.ReceiveUpdateFee(fee) 10280 require.NoError(t, err) 10281 checkDust(aliceChannel, htlc2Amt, htlc2Amt+htlc3Amt) 10282 checkDust(bobChannel, htlc2Amt+htlc3Amt, htlc2Amt) 10283 10284 // Forcing a state transition should change in the non-zero-fee case. 10285 err = ForceStateTransition(aliceChannel, bobChannel) 10286 require.NoError(t, err) 10287 if chantype.ZeroHtlcTxFee() { 10288 checkDust(aliceChannel, htlc2Amt, htlc2Amt+htlc3Amt) 10289 checkDust(bobChannel, htlc2Amt+htlc3Amt, htlc2Amt) 10290 } else { 10291 checkDust(aliceChannel, htlc2Amt+htlc3Amt, htlc2Amt+htlc3Amt) 10292 checkDust(bobChannel, htlc2Amt+htlc3Amt, htlc2Amt+htlc3Amt) 10293 } 10294 }