Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contractcourt: consider delivery addresses when evaluating toSelfAmount #8800

Merged
merged 3 commits into from
Jun 11, 2024

Conversation

ProofOfKeags
Copy link
Collaborator

Change Description

This commit fixes #8535 by changing how we assess toSelfAmount inside
the chainWatcher.

In certain cases users may wish to close out channel funds to external
delivery addresses set either during open or close.

Prior to this change we only consider addresses that our wallet is
aware of and permitted the possibility of multiple to_self outputs,
which is impossible according to the protocol.

This change now identifies to_self outputs based off of matching
delivery scripts, and if no delivery script is set, fall back to
the first output that our wallet can recognize.

NOTE FOR REVIEWERS: The itest commit is ordered first to confirm that the test fails prior to the change. After the fix commit, the test passes. If you want to confirm that the test is correctly designed you can run the test prior to the fix commit.

Steps to Test

make itest icase=coop_close_with_external_delivery

Pull Request Checklist

Testing

  • Your PR passes all CI checks.
  • Tests covering the positive and negative (error paths) are included.
  • Bug fixes contain tests triggering the bug to prevent regressions.

Code Style and Documentation

📝 Please see our Contribution Guidelines for further guidance.

Copy link
Contributor

coderabbitai bot commented May 31, 2024

Important

Review skipped

Auto reviews are limited to specific labels.

Labels to auto review (1)
  • llm-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ProofOfKeags ProofOfKeags requested review from ViktorTigerstrom, a team, morehouse and ziggie1984 and removed request for a team May 31, 2024 22:14
@ProofOfKeags ProofOfKeags self-assigned this May 31, 2024
@ProofOfKeags ProofOfKeags changed the title Bugfix/8535 contractcourt: consider delivery addresses when evaluating toSelfAmount May 31, 2024
@ProofOfKeags ProofOfKeags added this to the v0.18.1 milestone May 31, 2024
@ProofOfKeags ProofOfKeags requested review from Crypt-iQ and removed request for morehouse and ziggie1984 May 31, 2024 22:49
@ProofOfKeags ProofOfKeags force-pushed the bugfix/8535 branch 3 times, most recently from 361829c to 9fcac8a Compare June 3, 2024 19:24
Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had some minor comments, nicely used the function in the fn package 👏.

I think it might make sense to add the func commenting style into our guidelines so that we don't diverge too much in the codebase in general. (referring to this: // isWalletOutput :: *TxOut -> bool)

Apart from that this change looks good, Release notes for 18.1 are missing.

})
}

// testCoopCloseWithExternalDeliveryImpl ensurees that we have a valid settled
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: :s/ensurees/ensures/g

// belongs to the LND wallet. We use this as a heuristic in the case
// where we might be looking for spendable force closure outputs.
//
// isWalletOutput :: *TxOut -> bool
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to either introduce this new way of commenting function into the coding docs so that we don't diverge in our coding style ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what the specific ask is here.

The annotation I have here is for informational purposes only to alleviate the need to squint at the function itself to figure out its "shape". The format I use is stolen from Haskell and subtle variations can be found in Standard ML, OCaml, Haskell, Idris, Agda, F#, etc.

In recent years it has been adapted into other more mainstream languages in documentation notes like you can see here, here and here. The reason for this is that it's a fairly space efficient way to communicate the shape of the function without diving into the implementation details.

Are you saying that we need a note in the style guidelines to bless this? Or is it to describe in detail how to interpret a standalone type signature? What would you like to see?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you saying that we need a note in the style guidelines to bless this?

Yes this is what I meant, because I find it useful.

_, addrs, _, err := txscript.ExtractPkScriptAddrs(
// Doesn't matter what net we actually pass in.
txOut.PkScript, &chaincfg.TestNet3Params,
// It doesn't matter what chain params we use here.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: explanation why it does not matter would be helpful.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish I knew 😅. I've restored the comment to its original text now. Also worth noting that this is inside the txscript package in btcd.

}

// Here we define a function capable of identifying whether an output
// belongs to the LND wallet. We use this as a heuristic in the case
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure I understand this comment, seems to me we currently only use this function in the cooperate close case, why do we mention the force closure output here ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I hadn't looked at this prior to you pointing this out, it does appear that this function's only use site is in a context where we already assume/know it to be a coop close. That said, given that the function is named toSelfAmount, I think it's fair to keep it general enough to handle either case.

Generally, since the logical dependency relationship is that the caller depends on the callee, I don't think it's reasonable to assume how a function might be called. Perhaps if we want to limit it I can rename it to coopToSelfAmount and then trim out any commentary about how it might be used in a FC case. Perhaps this is the right compromise.

@ziggie1984
Copy link
Collaborator

#8808 was merged so this can be updated now.

@Crypt-iQ
Copy link
Collaborator

Crypt-iQ commented Jun 5, 2024

think gomod needs to be updated to compile. linter failing as well. code looks good can check again when these are fixed

@ProofOfKeags ProofOfKeags force-pushed the bugfix/8535 branch 4 times, most recently from 358e652 to 96fb23f Compare June 5, 2024 19:50
Copy link
Collaborator

@ziggie1984 ziggie1984 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM ⭐️

Copy link
Contributor

@Chinwendu20 Chinwendu20 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice use of the fn package in this PR 😎

// whether it was from the upfront shutdown, from the delivery address
// requested at close time, or even an automatically generated one. All
// coop-close cases can be identified in the following manner:
shutdown, _ := c.cfg.chanState.ShutdownInfo()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we do not handle DB error, here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this function doesn't return an error, if we can't reach the shutdown info for whatever reason we treat it as non-existent. Why it failed is inconsequential.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh okay, I was just thinking that maybe if there is something wrong with the DB we can catch it as soon as we encounter it here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this function already had an error in its signature then I'd probably do that. But this would cause a currently non-erroring function to return an error which I'd like to avoid. Swallowing errors can be dangerous but in this case all it does is affect the numbers we report and I don't think that's especially problematic. If it comes out to result in bad UX's we can come back and address it but for now I'd recommend leaving it as is.

Comment on lines +13 to +20
ht.Run("set delivery address at open", func(t *testing.T) {
tt := ht.Subtest(t)
testCoopCloseWithExternalDeliveryImpl(tt, true)
})
ht.Run("set delivery address at close", func(t *testing.T) {
tt := ht.Subtest(t)
testCoopCloseWithExternalDeliveryImpl(tt, false)
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting choice, why this and not TDD?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean by TDD? I'm only familiar with the acronym as Test Driven Development, and that is exactly what I've done here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I was referring to something like this:
image

source: https://golang.cafe/blog/golang-table-test-example

In the code being reviewed above, a number of things were rewritten twice.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I stole the test vector approach from @ellemouton 's refactoring of one of my earlier itests here:

https://github.com/lightningnetwork/lnd/blob/master/itest/lnd_coop_close_with_htlcs_test.go#L24-L34

I also recall @yyforyongyu saying that on a go-forward basis we should discourage table tests like in the image you linked. I tend to agree with this assessment but also would defer this type of decision to the elder wizards. I don't have a principled opinion on how to code test vectors.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just my two cents,

For this case, I would do testCoopCloseWithExternalDeliveryImpl and testCoopCloseWithExternalDeliveryImplWithUpfronShutdown instead.

I like using table-driven tests when the outputs of a function are only determined by one or two inputs in a test setup, like this one or this one. They share common heuristics like,

  • the method being tested is relatively simple - simple as in the number of inputs it takes and the number of outputs it returns, lines of code, logic, etc.
  • the test itself is straightforward, which is usually not the case in itest as we often need a somewhat complicated setup to reach one or multiple states before the actual test.
  • the assertions used in the test are NOT conditional based on the values of the table. An example I want to discourage is the multi-hop itest it took me quite some time to maintain while working on the sweeper series and I'm refactoring them now.

I'm also struggling to apply these rules of thumb from time to time because we need to improve the testability of the code. My general take is, as long as the tests are easy to maintain I'm happy. This means if table-driven tests are not used, I'm good, as the tests can always be refactored to use tables (low priority IMO); if table-driven tests are properly used, I'm good. I'm against improper usage of table-driven tests which lead to high maintenance costs.

So in most of cases, I'd avoid using table-driven tests in itest. I'd also recommend this Advanced Testing with Go talk, especially the "REPEAT YOURSELF" part.

Finally I would be very hesitant to make changes to any PR, unless critical, if it already got two approvals and no Request-for-change from others🤓

This commit fixes lightningnetwork#8535 by changing how we assess toSelfAmount inside
the chainWatcher.

In certain cases users may wish to close out channel funds to external
delivery addresses set either during open or close.

Prior to this change we only consider addresses that our wallet is
aware of.

This change now identifies outputs as to_self outputs if the delivery
script matches OR if our wallet is aware of the address. In certain
edge cases it can be possible for there to be more than one output
that matches these criteria and in that case we will return the sum
of those values.
Copy link
Collaborator

@ViktorTigerstrom ViktorTigerstrom left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Really elegant solution, great work 🚀!

Nit:
If anything, I think the test coverage could be extended a bit to improve the coverage further. I'm therefore leaving some suggestions below on how the coverage could be improved. None of this is blocking, and I'm fine with leaving it as is, so I leave it up to you to decide if you feel it's worth adding:

  1. Unless I'm missing something, we're currently missing any itest coverage for SettledBalance in general. I therefore think it would make sense to rename the integration test to testChannelSettledBalance (since we currently have a testChannelUnsettledBalance integration test) and also include coverage for cases where no DeliveryAddress has been specified.
  2. Instead of only asserting that the channel's SettledBalance is NotZero at the last line of testCoopCloseWithExternalDeliveryImpl, I think it would make sense to assert that the SettledBalance is the actual value we expect. It would then also make sense to add a PushAmt value to the OpenChannelParams.
  3. Furthermore, it would be great if you could add test coverage that proves that the toSelfAmount returns the sum of all outputs for which the address either matches the delivery script or is an address that our wallet is aware of. To provide that coverage, after adding a PushAmt value to the OpenChannelParams, you could potentially ensure that Alice sets the CloseAddress to Bob's address in the OpenChannelParams, but then let Bob initiate the CloseChannel RPC with one of Alice's addresses set as the DeliveryAddress in the CloseChannelRequest.

Like I said, these are non-blocking suggestions. Great work 🎉!

@ProofOfKeags
Copy link
Collaborator Author

If anything, I think the test coverage could be extended a bit to improve the coverage further. I'm therefore leaving some suggestions below on how the coverage could be improved. None of this is blocking, and I'm fine with leaving it as is, so I leave it up to you to decide if you feel it's worth adding:

I'm amenable to this.

Unless I'm missing something, we're currently missing any itest coverage for SettledBalance in general. I therefore think it would make sense to rename the integration test to testChannelSettledBalance (since we currently have a testChannelUnsettledBalance integration test) and also include coverage for cases where no DeliveryAddress has been specified.

Got it. I can add the case where it isn't specified.

Instead of only asserting that the channel's SettledBalance is NotZero at the last line of testCoopCloseWithExternalDeliveryImpl, I think it would make sense to assert that the SettledBalance is the actual value we expect. It would then also make sense to add a PushAmt value to the OpenChannelParams

This is a bit tricky as determining the balances of coop close transactions are subject to fee and output script factors and this can make solving for the "expected" amount equivalent to solving for the actual amount. We could use that PushAmt though to assert just that it's less/greater than some amount.

Furthermore, it would be great if you could add test coverage that proves that the toSelfAmount returns the sum of all outputs for which the address either matches the delivery script or is an address that our wallet is aware of. To provide that coverage, after adding a PushAmt value to the OpenChannelParams, you could potentially ensure that Alice sets the CloseAddress to Bob's address in the OpenChannelParams, but then let Bob initiate the CloseChannel RPC with one of Alice's addresses set as the DeliveryAddress in the CloseChannelRequest.

This is the suggestion I understand the least. I think the property that you are trying to ensure in this case is that if they each set their delivery address to one that the other controls, then their settled balances should always match each other, irrespective of what the push amount is. Am I interpreting this right?

@ViktorTigerstrom
Copy link
Collaborator

ViktorTigerstrom commented Jun 11, 2024

I'm amenable to this.

Awesome!

Got it. I can add the case where it isn't specified.

👍

This is a bit tricky as determining the balances of coop close transactions are subject to fee and output script factors and this can make solving for the "expected" amount equivalent to solving for the actual amount. We could use that PushAmt though to assert just that it's less/greater than some amount.

Wouldn't we be able to just assert that the SettledBalance matches the sum of the TxOuts of the closing tx (returned by ht.MineClosingTx(chanPoint)) that we're interested in for the respective the test? You could then use the PushAmt to easily find Bob's output (not the one with the DeliveryAddress Alice has set), or do address matching (but that'll likely be much more complicated). If you feel that this get's overcomplicated though, feel free to implement your PushAmt less/greater idea though!

Edit:
If you do implement my suggested amount assertion + my suggestion (1.) above, I do think it makes sense to also add assertion of the SettledBalance from Bob's side, to prove that if Alice doesn't set the DeliveryAddress to an address that Bob controls, Alice output amount isn't included in Bob's SettledBalance.

This is the suggestion I understand the least. I think the property that you are trying to ensure in this case is that if they each set their delivery address to one that the other controls, then their settled balances should always match each other, irrespective of what the push amount is. Am I interpreting this right?

Sorry, maybe I was a bit too unclear! I hope this is clearer, but let me know if I'm still too unclear:
What I was referring to was that the current test code provides coverage for a case where only the isDeliveryOutput function matches in the toSelfAmount function. If you implement suggestion (1.) of my previous comment, that should add coverage for a case where only the isWalletOutput function matches.
What my suggestion (3.) is trying to achieve, is to implement coverage for the edge case where there are outputs in the closing tx where both the isDeliveryOutput function and the isWalletOutput matches, just to prove that the function indeed sums the amount of those outputs if that's the case. My suggestion was attempting to achieve such a case in a simple way, as Alice set DeliveryAddress will then make the isDeliveryOutput function match, and Bob's set DeliveryAddress will then make the isWalletOutput function match when evaluating the SettledBalance from Alice perspective.
Though, if you have an easier way of achieving a scenario where there are outputs in the closing tx where both the isDeliveryOutput function and the isWalletOutput matches, feel more than free to implement that!

@yyforyongyu yyforyongyu merged commit 286ee95 into lightningnetwork:master Jun 11, 2024
30 of 34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
6 participants