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

chainfee: allow specifying min relay feerate from the API source #8891

Merged
merged 6 commits into from
Jul 25, 2024

Conversation

yyforyongyu
Copy link
Member

In an attempt to test the sweeper's Aggregator's filtering logic, where it would filter out the input whose budget cannot cover the min relay fee, I realized there's no way to set the min relay feerate in our test, which led to this PR.

This PR adds a new field to the expected resp returned from the API, allowing the service to specify a min relay feerate to be used. A bug is also found, which could result in a floor feerate being used when calling EstimateFeePerKW as there's no cached created during the startup, yet the ticker hasn't fired.

Partially address #8688.

@yyforyongyu yyforyongyu added utxo sweeping itests Issues related to integration tests. web fee estimator Issues related to external fee estimator labels Jul 4, 2024
@yyforyongyu yyforyongyu added this to the v0.18.2 milestone Jul 4, 2024
@yyforyongyu yyforyongyu self-assigned this Jul 4, 2024
Copy link
Contributor

coderabbitai bot commented Jul 4, 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 Configuration 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.

Copy link
Collaborator

@ProofOfKeags ProofOfKeags left a comment

Choose a reason for hiding this comment

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

I don't think any of these things are blocking but I did leave some comments.

lnwallet/chainfee/estimator.go Show resolved Hide resolved
lnwallet/chainfee/estimator.go Outdated Show resolved Hide resolved
lnwallet/chainfee/estimator.go Show resolved Hide resolved
lnwallet/chainfee/estimator.go Outdated Show resolved Hide resolved
lnwallet/chainfee/log.go Outdated Show resolved Hide resolved
lntest/fee_service.go Show resolved Hide resolved
Copy link
Collaborator

@ellemouton ellemouton left a comment

Choose a reason for hiding this comment

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

Very nice!
One blocking question about the first commit bug fix

@@ -816,22 +816,24 @@ func (w *WebAPIEstimator) EstimateFeePerKW(numBlocks uint32) (
//
// NOTE: This method is part of the Estimator interface.
func (w *WebAPIEstimator) Start() error {
log.Infof("Starting Web API fee estimator...")
Copy link
Collaborator

Choose a reason for hiding this comment

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

probs just my friday morning brain not kicking in yet but is this behaviour actually different? cause Start wont return before w.started.Do is run right? so does it matter if updateFeeEstimates() is called here or in started.Do?

scenario 1: noCache = true:

  • we return early here but that's ok causeEstimateFeePerKW will then always call w.updateFeeEstimates() before looking at the cache.

scenario 2: noCache = false:

  • started.Do runs and calls w.updateFeeEstimate before returning from Start.
  • EstimateFeePerKW only ever called after Start is done so updateFeeEstimate would have been called

am I missing something here? (i probs just need more coffee)

Copy link
Member Author

Choose a reason for hiding this comment

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

yeah you are totally right! For some reason, I thought it was waiting for the ticker to fire before doing the first updateFeeEstimate. Will remove this commit. Meanwhile I realized that if Start is still finishing up, yet another call to EstimateFeePerKW is made, we could still get a floor feerate. This should never happen as we always wait for the Start to be finished first, but just in case.

Copy link
Collaborator

Choose a reason for hiding this comment

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

This can be avoided by inlining the Start method into the constructor.

lnwallet/chainfee/log.go Outdated Show resolved Hide resolved
lnwallet/chainfee/estimator.go Outdated Show resolved Hide resolved
lnwallet/chainfee/estimator_test.go Show resolved Hide resolved
lntest/fee_service.go Outdated Show resolved Hide resolved
docs/release-notes/release-notes-0.18.3.md Show resolved Hide resolved
Copy link
Collaborator

@ellemouton ellemouton left a comment

Choose a reason for hiding this comment

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

LGTM 🔥
One comment/opinion about the started check but non-blocking imo

Comment on lines +670 to +674
if resp.MinRelayFeerate == 0 {
log.Errorf("No min relay fee rate available, using default %v",
FeePerKwFloor)
Copy link
Collaborator

Choose a reason for hiding this comment

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

nice 💪

// GetFeeInfo will query the web API, parse the response and return a map of
// confirmation targets to sat/kw fees and min relay feerate in a parsed
// response.
func (s SparseConfFeeSource) GetFeeInfo() (WebAPIResponse, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

could return a pointer if you want. It was a pointer before & then dont need to return empty instances

Copy link
Collaborator

Choose a reason for hiding this comment

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

We should avoid pointer usage when constructing something from scratch.

Copy link
Collaborator

Choose a reason for hiding this comment

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

why? we use that pattern everywhere & is a pretty standard golang pattern afaiaa

Copy link
Collaborator

@ProofOfKeags ProofOfKeags Jul 24, 2024

Choose a reason for hiding this comment

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

  1. Why open yourself up to reference aliasing if the thing is being constructed for the first time right there. It obscures the ownership semantics of the data itself. This causes issues where the code becomes more brittle and subject to segmentation faults. If you are constructing something for the first time, you -- by definition -- own it. Owned data should not be behind pointers. We use pointers to lease data to other functions that either read from it or do scoped modification.
  2. Why do the heap allocation when you can do it on the stack? Heap allocation is significantly slower. Additionally pointer dereferences themselves are not free either.

Copy link
Member Author

Choose a reason for hiding this comment

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

FWIW go does recommend pass by values.

testFees := map[uint32]uint32{
1: 12345,
}
testResp := struct {
Copy link
Collaborator

Choose a reason for hiding this comment

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

shweet 🔥

@@ -792,6 +793,12 @@ func NewWebAPIEstimator(api WebAPIFeeSource, noCache bool,
func (w *WebAPIEstimator) EstimateFeePerKW(numBlocks uint32) (
SatPerKWeight, error) {

// If the estimator hasn't been started yet, we'll return an error as
// we can't provide a fee estimate.
if !w.started.Load() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

cool - I guuuuuueeeess there is no harm adding this but in general I like the assumption that Start is called & completed before anything else is called & so is by definition thread safe & deterministic. Cause the other side of the spectrum is doing this isStarted check on every API method which is not ideal I think

Copy link
Collaborator

@ProofOfKeags ProofOfKeags Jul 23, 2024

Choose a reason for hiding this comment

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

Or we could move away from start methods entirely and just start it in the constructor when it is called. IMO we should only have Start methods for things that primarily interact through channels.

This is known as RAII wherein the primary assumption is that a resource is ready to use when it is constructed.

Copy link
Member Author

Choose a reason for hiding this comment

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

RAII can be nice when using OOP. For instance in python you can define what happens when initializing the object in its __ini__. Here we may achieve something similar using the NewXXX method, which is better than embedding the Start method in the constructor (IIUR about this term) as, there might be multiple constructors, we need to carry this concern in every one of them, just like @ellemouton pointed out that the started now has to be checked on every API.

Also this pattern has already been used in some of the RPC calls, so we make sure the server is fully started before responding to requests. This led me to think about what NewXXX and Start should accomplish, maybe we should start inside the NewXXX so we can be somewhat certain that a given state is reached once the struct is returned. However that's a bigger refactor so I kinda let it go, maybe worth revisiting when it becomes an issue someday (for instance #8166)

Copy link
Collaborator

Choose a reason for hiding this comment

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

IMO the Start/Stop APIs only make sense if we can create a state machine that is capable of multi-start/multi-stop. However, we have (for some reason) intentionally avoided this. Absent multi-start/multi-stop, the lifetime of the object should dictate the lifetime of the goroutines it launches. Therefore one of the things we can do here is launch the goroutines in whatever the NewXXX method is, and then hook into the GC to call XXX.stop() when all of the XXX refs go out of scope using a gc finalizer

Definitely agree that this is not the place for that much larger discussion to unfold though. Just wanted to share my thoughts as I have found that the Start/Stop pattern in the codebase to be a wart that doesn't make sense, and people seem to just follow the pattern because "that's what we've always done".

This commit adds a new expected field, `min_relay_feerate`, in the
response body returned from the API source, allowing the API to specify
a min relay feerate to be used instead of the FeePerKwFloor.

This change is backwards compatible as for an old API source which
doesn't specify the `min_relay_feerate`, it will be interpreted as zero.
Previously we may get a floor feerate when calling `EstimateFeePerKW`
due to the fee estimator not finishing its startup process, which gives
us an empty fee map.

This is now fixed to return an error if the estimator is not started.
chanbackup/pubsub.go Outdated Show resolved Hide resolved
lnutils/log.go Outdated
Comment on lines 1 to 19
package lnutils

// LogClosure is used to provide a closure over expensive logging operations so
// don't have to be performed when the logging level doesn't warrant it.
type LogClosure func() string

// String invokes the underlying function and returns the result.
func (c LogClosure) String() string {
return c()
}

// NewLogClosure returns a new closure over a function that returns a string
// which itself provides a Stringer interface so that it can be used with the
// logging system.
func NewLogClosure(c func() string) LogClosure {
return LogClosure(c)
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

🫡

Comment on lines 31 to 45
// logClosure is used to provide a closure over expensive logging operations so
// don't have to be performed when the logging level doesn't warrant it.
type logClosure func() string

// String invokes the underlying function and returns the result.
func (c logClosure) String() string {
return c()
}

// newLogClosure returns a new closure over a function that returns a string
// which itself provides a Stringer interface so that it can be used with the
// logging system.
func newLogClosure(c func() string) logClosure {
return logClosure(c)
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

🔪😈

@@ -1869,7 +1870,7 @@ func (lc *LightningChannel) restoreCommitState(
lc.localCommitChain.addCommitment(localCommit)

lc.log.Tracef("starting local commitment: %v",
newLogClosure(func() string {
lnutils.NewLogClosure(func() string {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm thinking it could be good to add to the lnutils package a function specifically designed to handle the spew case

func SpewLogClosure(a interface{}) func() string {
        return func() string {
                return spew.Sdump(a)
        }
}

Copy link
Member Author

Choose a reason for hiding this comment

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

cool I like it

log.go Show resolved Hide resolved
Copy link
Collaborator

@ProofOfKeags ProofOfKeags left a comment

Choose a reason for hiding this comment

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

If you want to improve things further, I'd add the spew case to the API of lnutils/log, but I'm satisfied with the improvement as is.

Copy link
Collaborator

@ProofOfKeags ProofOfKeags left a comment

Choose a reason for hiding this comment

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

Net code reduction of 137LOC 🧡

@guggero guggero merged commit b40f165 into lightningnetwork:master Jul 25, 2024
31 of 34 checks passed
@yyforyongyu yyforyongyu deleted the fix-fee-estimator branch July 26, 2024 06:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
itests Issues related to integration tests. utxo sweeping web fee estimator Issues related to external fee estimator
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants