Skip to content

Update AddHoldInvoice to add support for optional preimage/hash generation#10685

Open
saubyk wants to merge 4 commits intolightningnetwork:masterfrom
saubyk:update-holdinvoice
Open

Update AddHoldInvoice to add support for optional preimage/hash generation#10685
saubyk wants to merge 4 commits intolightningnetwork:masterfrom
saubyk:update-holdinvoice

Conversation

@saubyk
Copy link
Copy Markdown
Collaborator

@saubyk saubyk commented Mar 28, 2026

Fixes #7220

Change Description

Update AddHoldInvoice to add support for optional preimage/hash generation. Following scenarios are handled:

  • User provides only a hash. This is the original behavior
  • User provides neither a preimage or hash, both of which will then be automatically generated (the generated preimage will not be stored in the db and it's the user responsibility to retrieve and safe-keep from the api/cli response for the invoice settlement later)

Steps to Test

  • Run make unit pkg=./lnrpc/invoicesrpc/... to verify compilation and existing unit tests
  • Run make itest icase=hold_invoice_auto_generate to test the new integration test covering all modes:
    • Auto-generate (no hash, no preimage) — creates invoice, pays, settles with returned preimage
    • Hash only — backward compat, preimage not returned
  • Run make itest icase=hold_invoice_sender_persistence to verify existing hold invoice flow is unaffected
  • Manual lncli verification:
    • lncli addholdinvoice <hash> 10000 (legacy positional arg still works)
    • lncli addholdinvoice --hash=<hex> 10000 (new flag)
    • lncli addholdinvoice 10000 (auto-generate) [ Reminder: the generated preimage should be copied from the response or invoice cannot be settled if preimage is lost]

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.

@saubyk saubyk added this to the v0.22.0 milestone Mar 28, 2026
@saubyk saubyk self-assigned this Mar 28, 2026
@saubyk saubyk added this to lnd v0.22 Mar 28, 2026
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, 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 enhances the AddHoldInvoice functionality by introducing more flexible preimage and hash management. It allows users to either provide a preimage for the server to derive a hash from, or opt for the server to auto-generate both a preimage and hash. The changes include updates to the RPC interface, command-line tool, and server-side logic, ensuring backward compatibility while providing robust error handling for invalid configurations.

Highlights

  • AddHoldInvoice Enhancements: Updated AddHoldInvoice to support optional preimage/hash generation, allowing the server to auto-generate a preimage or derive a hash from a user-supplied preimage.
  • RPC Interface Updates: Modified the AddHoldInvoiceRequest and AddHoldInvoiceResp protobuf definitions to include new fields for preimage and hash handling.
  • New Integration Tests: Added a new integration test suite, testHoldInvoiceAutoGenerate, to verify the new functionality across various modes including auto-generation, user-supplied preimage, and legacy hash-only flows.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@saubyk saubyk moved this from Todo to In progress in lnd v0.22 Mar 28, 2026
@saubyk saubyk changed the title Update AddHoldInvoice to add support for optional presage/hash generation Update AddHoldInvoice to add support for optional preimage/hash generation Mar 28, 2026
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request enhances the AddHoldInvoice RPC and CLI command to support optional hash and preimage parameters. Users can now provide a preimage directly (from which the server derives the hash), provide a hash as before, or provide neither to have the server auto-generate both. The changes include updates to the protobuf definitions, CLI flag handling, server-side logic, and a comprehensive integration test suite. I have no feedback to provide.

@saubyk saubyk force-pushed the update-holdinvoice branch 2 times, most recently from bb700f6 to e2fac2a Compare April 2, 2026 20:09
@saubyk saubyk marked this pull request as ready for review April 6, 2026 02:41
@saubyk saubyk requested review from yyforyongyu and ziggie1984 April 6, 2026 02:41
@ziggie1984
Copy link
Copy Markdown
Collaborator

Design question: should --preimage exist as input, and should the preimage be stored in the DB?

Thanks for the PR — the auto-generate feature is a real quality-of-life improvement and the core implementation is solid. I want to raise two related design questions before this lands.


1. Should bytes preimage exist as an input field?

The stated purpose is to let callers avoid computing SHA256(preimage) themselves. But that's a trivial operation — every Lightning library exposes it, and lnd itself has preimage.Hash() in lntypes. The savings are minimal.

In exchange, the feature:

  • Sends the preimage over the RPC channel (potentially captured in logs, middleware, audit layers)
  • Stores the preimage in the DB at invoice creation time — before any payment has arrived, before the merchant has decided to settle

The original hold invoice design was deliberate: the merchant keeps the preimage locally, passes only the hash to AddHoldInvoice, and the preimage never touches lnd's DB until SettleInvoice is called. That's the whole point — the merchant controls exactly when the preimage is revealed.

The correct flow for a caller who already has a preimage is just:

hash = SHA256(preimage)
AddHoldInvoice(hash=hash)

My suggestion: remove bytes preimage from AddHoldInvoiceRequest and the corresponding CLI flag. The auto-generate path (neither hash nor preimage provided) is where the real value is.


2. Should the preimage be stored in the DB even for the auto-generate case?

Currently even the auto-generate path stores the preimage in ContractTerm.PaymentPreimage via AddInvoiceData.Preimage. But SettleInvoice always requires the caller to supply the preimage — lnd never reads it from the DB to perform settlement. So storing it serves no functional purpose.

The cleaner approach: generate the preimage locally in AddHoldInvoice, pass only the hash to AddInvoice (Preimage: nil), and return the preimage directly from the local variable in the response — never writing it to the DB:

default: // auto-generate
    var preimage lntypes.Preimage
    if _, err := rand.Read(preimage[:]); err != nil {
        return nil, fmt.Errorf("failed to generate preimage: %w", err)
    }
    h := preimage.Hash()
    hashPtr = &h
    autoPreimage = &preimage  // returned in response, not stored

This preserves the hold invoice invariant: the DB only ever holds the hash, never the preimage. The preimage is returned once in the response (the caller must store it, like a seed phrase), and provided back at settle time. It also eliminates a whole class of future bugs where a preimage stored in the DB could be used inadvertently if the HodlInvoice flag check ever has a regression.


To be clear — none of this blocks the auto-generate feature itself, which is good and should land. The question is just whether we want to keep --preimage as input and whether the preimage should live in the DB.

@lightninglabs-deploy
Copy link
Copy Markdown
Collaborator

@ziggie1984: review reminder
@yyforyongyu: review reminder
@saubyk, remember to re-request review from reviewers when ready

saubyk added 4 commits April 17, 2026 18:22
Make the hash field optional in AddHoldInvoiceRequest. When the hash
is omitted, the server generates a random preimage locally, derives
the payment hash, and returns the preimage in the response. The
generated preimage is not passed to AddInvoice, so it is never
persisted in the invoice DB — the caller must save the returned
value and supply it to SettleInvoice later. This preserves the
hold-invoice invariant that lnd only learns the preimage at settle
time.

The response adds payment_preimage (populated only for the
auto-generated case) and payment_hash (always populated), giving
callers the info needed to drive the hold-invoice lifecycle.
Add a --hash flag to the lncli addholdinvoice command, matching the
new optional-hash behavior on the RPC. The old positional hash
argument is kept for backward compatibility (detected by 64 hex
char length). When no hash is provided the server auto-generates
the preimage/hash pair and returns the preimage in the response
for the caller to save.
Add integration test covering the two AddHoldInvoice input modes:
auto-generate (no hash provided) and hash-only (backward compat).
For the auto-generate case, the test also verifies via
LookupInvoice that the generated preimage is not persisted in the
invoice DB. Each scenario exercises the full payment lifecycle
including settle.
Add release notes entry for the AddHoldInvoice optional-hash
feature under RPC Updates and lncli Updates.
@saubyk saubyk force-pushed the update-holdinvoice branch from e2fac2a to f72a89f Compare April 18, 2026 01:23
@github-actions github-actions Bot added the severity-high Requires knowledgeable engineer review label Apr 18, 2026
@github-actions
Copy link
Copy Markdown

🟠 PR Severity: HIGH | 5 files | 217 lines changed | HIGH: lnrpc/invoicesrpc/invoices_server.go (lnrpc/* RPC server) | MEDIUM: cmd/commands/invoicesrpc_active.go (cmd/* CLI), lnrpc/invoicesrpc/invoices.proto (.proto), lnrpc/invoicesrpc/invoices.swagger.json | LOW: docs/release-notes/release-notes-0.22.0.md | EXCLUDED (test/generated): itest/list_on_test.go, itest/lnd_hold_invoice_auto_generate_test.go, lnrpc/invoicesrpc/invoices.pb.go | No bump: 5 files under threshold 20, 217 lines under threshold 500. To override add severity-override-{critical,high,medium,low} label. <!-- pr-severity-bot -->

@saubyk
Copy link
Copy Markdown
Collaborator Author

saubyk commented Apr 18, 2026

Hi @ziggie1984 @yyforyongyu the feedback has been addressed. The pr is ready for your review. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

severity-high Requires knowledgeable engineer review

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

[feature]: New rpc for generating pre-image and corresponding hash

3 participants