staticaddr: channel funding with deposits#1040
staticaddr: channel funding with deposits#1040hieblmi wants to merge 17 commits intolightninglabs:masterfrom
Conversation
Summary of ChangesHello @hieblmi, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly extends the functionality of static addresses by enabling them to be used as a source for funding Lightning channels. It introduces a new Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a new openchannel subcommand for static addresses, allowing users to fund channels from their deposits. The implementation is comprehensive, covering the command-line interface, RPC definitions, daemon logic, and documentation.
My review focuses on the new cmd/loop/openchannel.go file, where I've identified a few issues related to context handling, input validation, and error wrapping. These are important for ensuring the robustness and maintainability of the new command.
The refactoring to move utility functions into a staticutil package is a great improvement for code organization and reuse. The protocol changes to use PSBT for withdrawals are also a solid enhancement.
Overall, this is a well-structured PR that adds significant functionality. Addressing the feedback will further improve its quality.
f9b49dc to
9d37fca
Compare
94f45cc to
375cf47
Compare
2b9378a to
5b6631d
Compare
|
@gemini-code-assist review |
d2d2a88 to
ffa9e9e
Compare
Make our own type StaticAddressLoopInRequest which has a single field of type lnrpc.OpenChannelRequest. Removed copy-pasted lnrpc types which are needed for OpenChannelRequest.
Block-based deposit fetching from the internal lnd wallet was susceptible to wallet syncing issues. Replace it with interval-based polling. Reconciliation errors are now logged instead of being fatal, improving resilience during transient failures.
ffa9e9e to
75a263b
Compare
|
Hi @sputn1ck, I addressed some more findings, namely:
|
| err.Error(), cancelErr, | ||
| ) { | ||
|
|
||
| shimPending = false |
There was a problem hiding this comment.
Data race in shimPending variable. It is accessed from multiple goroutines without synchronization.
There was a problem hiding this comment.
Added a mutex to gate access.
| hash, err := chainhash.NewHash( | ||
| update.ChanPending.Txid, | ||
| ) | ||
| if err != nil { | ||
| log.Infof("Error creating hash for channel "+ | ||
| "open tx: %v", err) | ||
| } |
There was a problem hiding this comment.
I think we should return error in this if. We use the hash variable below as if it is valid, but it could be nil and we just log the error and crash later.
There was a problem hiding this comment.
Good catch, fixed.
| err = m.cfg.DepositManager.TransitionDeposits( | ||
| ctx, deposits, deposit.OnChannelPublished, | ||
| deposit.ChannelPublished, | ||
| ) | ||
| if err != nil { | ||
| log.Errorf("error transitioning deposits to "+ | ||
| "ChannelPublished: %v", err) | ||
| } |
There was a problem hiding this comment.
TransitionDeposits errors are logged but the function still returns success, leaving deposits stuck in OpeningChannel while the channel is actually pending. This should be returned to the caller or retried.
There was a problem hiding this comment.
The current approach is to just log the transition error and return the chanOutpoint since the transition error might be a recurring error that isn't solved without intervention.
So the approach is to reconcile these OpeningChannel states after a restart in recoverOpeningChannelDeposits.
| OpeningChannel: fsm.State{ | ||
| Transitions: fsm.Transitions{ | ||
| fsm.OnError: Deposited, | ||
| OnChannelPublished: ChannelPublished, | ||
| OnRecover: OpeningChannel, | ||
| }, | ||
| Action: fsm.NoOpAction, | ||
| }, | ||
| ChannelPublished: fsm.State{ | ||
| Action: f.FinalizeDepositAction, | ||
| }, |
There was a problem hiding this comment.
These two states lack OnExpiry transitions from them. OnExpiry may be delivered to each of them.
- OpeningChannel has Action: fsm.NoOpAction. This means it stops current FSM execution and unlocks the FSM mutex, letting potential SendEvent calls sneak in.
- FinalizeDepositAction also returns fsm.NoOp and triggers further things via a channel (f.finalizedDepositChan) so there is still a window when SendEvent can sneak in.
handleBlockNotification fires OnExpiry on every new block once the deposit is expired (staticaddr/deposit/fsm.go), regardless of state.
So there is a possibility that OnExpiry is delivered to each of these new states. We have to add state self-transitions to each of them.
There was a problem hiding this comment.
That is a great catch, thank you!
Fixed it.
| log.Infof("Recovering %d deposits in OpeningChannel state", | ||
| len(openingDeposits)) | ||
|
|
||
| utxos, err := m.cfg.WalletKit.ListUnspent( |
There was a problem hiding this comment.
What if the deposit is spent, but not confirmed? Shouldn't we still track it? Maybe it is evicted from mempool. Or even confirmed first and then reorged.
| require.ErrorContains(t, err, tc.expectedErrSubstr) | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
I propose to add test coverage for edge cases:
- reorg
- daemon restart during channel opening
- eviction from mempool
- rejection from mempool
- stream errors
- PSBT finalize then stream abort
- duplicate outpoints in request
|
|
||
| // Run runs the open channel manager. | ||
| func (m *Manager) Run(ctx context.Context) error { | ||
| err := m.recoverOpeningChannelDeposits(ctx) |
There was a problem hiding this comment.
Should we recover deposits during daemon running as well, not only during startup time?
If the PSBT finalize succeeds but the stream fails before ChanPending, deposits remain in OpeningChannel until restart.
There was a problem hiding this comment.
Fixed. We are checking if there's an error but the PSBT was finalized and sent, then we recover remaining deposits.
| // selects a local channel amount in which case we coin-select deposits | ||
| // to cover for it. 3.) The user selects the fundmax flag, in which case | ||
| // we select all deposits to fund the channel. | ||
| if len(req.Outpoints) > 0 { |
There was a problem hiding this comment.
What if req.Outpoints has duplicates? This leads to fee miscalculation and invalid PSBT building (having the same input twice). I propose to return an error early if we detect duplicates in req.Outpoints and add test coverage.
There was a problem hiding this comment.
added logic to detect dupes and return in that case.
staticaddr/deposit/manager.go
Outdated
looprpc/client.proto
Outdated
| /* | ||
| The transaction hash of the channel opening transaction. | ||
| */ | ||
| string channel_open_tx_hash = 1; |
There was a problem hiding this comment.
Should we also add the output index (always 0 in the current implementation)? Just in case we implement batch open or something in the future. The code which uses this thing shouldn't guess what is the index, it should take it from the API.
There was a problem hiding this comment.
Alternatively change channel_open_tx_hash to channel_open_outpoint and put "txid:index" there.
There was a problem hiding this comment.
I like the second suggestion, added.
Protect the shimPending variable with a sync.Mutex since it is accessed from multiple goroutines: the main loop goroutine and the server error handling goroutine. Without synchronization this is a data race.
Return an error instead of just logging when chainhash.NewHash fails in the ChanPending handler. The hash variable would be nil and crash on the subsequent String() call.
…ublished Both OpeningChannel and ChannelPublished lacked OnExpiry transitions. handleBlockNotification fires OnExpiry on every new block once the deposit is expired, regardless of the current state. Since both states use NoOpAction or FinalizeDepositAction which release the FSM mutex briefly, an OnExpiry SendEvent can sneak in. Add self-transitions so the event is safely absorbed.
Duplicate outpoints in the request lead to fee miscalculation and an invalid PSBT with the same input listed twice. Validate early and return a clear error message.
Remove unreachable error check after filterNewDeposits which does not return an error. The err variable was already handled from the ListUnspent call above and could never be non-nil at this point.
If the PSBT finalize step succeeds but the stream fails before ChanPending, deposits would remain stuck in OpeningChannel until the next daemon restart. Run the recovery logic immediately so deposits are resolved without requiring a restart.
Add tests for the following edge cases requested in review: - Reorg: channel tx reorged, UTXOs reappear as unspent, deposits return to Deposited state. - Daemon restart during channel opening: deposits in OpeningChannel recovered based on UTXO status (spent → ChannelPublished, unspent → Deposited). - Mempool eviction: tx evicted, UTXOs unspent, deposits return to Deposited. - Mempool rejection: tx never accepted, same recovery as eviction. - Stream errors: lnd stream fails before PSBT finalize, error returned without errPsbtFinalized so deposits can be safely rolled back. - PSBT finalize then stream abort: finalize succeeds but stream dies before ChanPending, error wrapped with errPsbtFinalized so caller triggers recovery instead of blind rollback. - Duplicate outpoints: already covered by TestOpenChannelDuplicateOutpoints.
Change StaticOpenChannelResponse to return channel_open_outpoint in "txid:index" format instead of just the tx hash. This includes the output index so callers don't have to guess it, which is important for potential future batch opens.
75a263b to
f345933
Compare
This PR introduces a
openchannelsubcommand to static addresses.It provides the same experience as
lncli openchannel.Exmples:
Open a channel with all available deposits:
Open a channel with specified local funding amount, coin-selected from available deposits under fee and dust considerations.
Open a channel from two deposits AAA and BBB while taking their combined value(fundmax) as funding amount and considering fees and dust limit.
Open a channel from two deposits AAA and BBB while taking a specified amount(local_amt) as funding amount and considering fees and dust limit.
TODOs: