-
Notifications
You must be signed in to change notification settings - Fork 422
Implement PSBT fields that were missing for a Signer #2761
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
Conversation
Codecov ReportAttention: Patch coverage is
❗ Your organization needs to install the Codecov GitHub app to enable full functionality. Additional details and impacted files@@ Coverage Diff @@
## main #2761 +/- ##
==========================================
+ Coverage 89.15% 89.43% +0.28%
==========================================
Files 118 118
Lines 97246 99545 +2299
Branches 97246 99545 +2299
==========================================
+ Hits 86696 89027 +2331
+ Misses 8303 8262 -41
- Partials 2247 2256 +9 ☔ View full report in Codecov by Sentry. |
19fd700 to
f8328b5
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yea, I think storing derivation info in proprietary fields makes sense.
f8328b5 to
075ee16
Compare
ed57652 to
3b73b43
Compare
3b73b43 to
65050aa
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks much better now, thanks!
65050aa to
5956be4
Compare
|
@wpaulino I think the Windows platform test needs to be restarted. |
5956be4 to
b8cc17a
Compare
b8cc17a to
6970176
Compare
WalkthroughThe recent updates enhance the handling of channel transactions and key derivation in a Lightning Network implementation. A new field, Changes
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Additionally, you can add CodeRabbit Configration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 2
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (10 hunks)
Additional comments: 10
lightning/src/ln/channel_keys.rs (2)
- 41-52: The new method
derive_add_tweakcorrectly implements the logic to derive a tweak from a basepoint and a per_commitment_point. The use ofSha256::engine()and the subsequent calls tosha.input()followed bySha256::from_engine(sha).to_byte_array()align with the expected cryptographic operations for this purpose.- 41-52: The existing comment from TheBlueMatt is still applicable. It would be beneficial to add more descriptive comments to the
derive_add_tweakmethod to clarify the purpose and the process of the tweak derivation.lightning/src/sign/mod.rs (8)
- 21-21: The import of the
rawmodule frombitcoin::psbtis added. This is likely used for the new PSBT-related functionality.- 46-46: The addition of
get_revokeable_redeemscripttochan_utilsimport is noted. This function is essential for generating scripts for outputs that can be revoked.- 106-110: The addition of
channel_transaction_parameterstoDelayedPaymentOutputDescriptorandStaticPaymentOutputDescriptoris consistent with the PR's objective to make PSBTs self-sufficient for signers.- 130-130: The serialization of
channel_transaction_parametersusing TLV is added. This ensures backward compatibility and extensibility.- 167-176: Modifications to the
witness_scriptmethod inStaticPaymentOutputDescriptorto include the newchannel_transaction_parametersare observed. This change is necessary to generate the correct script for spending.- 324-372: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [317-358]
The addition of the
secp_ctxparameter to theto_psbt_inputmethod inSpendableOutputDescriptoris necessary for the new PSBT functionality. The method's logic has been updated to include the newchannel_transaction_parametersand the tweak derivation for theDelayedPaymentOutputDescriptor.
- 363-369: The
to_psbt_inputmethod forStaticPaymentOutputDescriptorhas been updated to include the newwitness_scriptlogic. This change is consistent with the PR's objectives.- 390-396: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [393-460]
The
create_spendable_outputs_psbtmethod now requires asecp_ctxparameter, and the logic has been updated to handle the newchannel_transaction_parameters. The method's complexity has increased, but it remains clear and maintainable.
6970176 to
cb10e40
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 1
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (9 hunks)
Files skipped from review as they are similar to previous changes (2)
- lightning/src/chain/channelmonitor.rs
- lightning/src/sign/mod.rs
Additional comments: 1
lightning/src/ln/channel_keys.rs (1)
- 41-52: The method
derive_add_tweakhas been added to derive a tweak from a basepoint and a per_commitment_point. The implementation uses SHA256 to hash the serialization of both points and returns the hash as a byte array. This method is critical for the functionality of deriving keys in the context of the Lightning Network's per-commitment secret scheme.Ensure that the serialization order (first the
per_commitment_point, then thebasepoint) is consistent with the protocol specifications and that the hash function is used correctly in this context.
9eeb0cd to
a0f0561
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (9 hunks)
Files skipped from review as they are similar to previous changes (2)
- lightning/src/chain/channelmonitor.rs
- lightning/src/sign/mod.rs
Additional comments: 1
lightning/src/ln/channel_keys.rs (1)
- 41-56: The new method
derive_add_tweakhas been added to derive a tweak from a public key. Ensure that the logic for tweak derivation is consistent with the intended cryptographic design and that the use ofSha256and serialization is correctly implemented.Verification successful
--- <!--Monologue: The broader ast-grep search still did not yield any results. This could indicate that the `derive_add_tweak` function's logic is indeed unique within the codebase, or that the pattern is still not capturing variations of the implementation. Given the specificity of cryptographic operations, it's plausible that this method is unique to the `channel_keys.rs` file and is not replicated elsewhere. Without further context or additional patterns to search for, it may be necessary to conclude the verification process based on the information available. --> Given the results of the ast-grep searches, which did not find any other instances of similar tweak derivation logic, it appears that the `derive_add_tweak` method in `channel_keys.rs` is unique within the codebase. The verification process did not uncover any inconsistencies or additional implementations of the tweak derivation logic. </details> <details> <summary>Scripts Executed</summary> The following scripts were executed for the analysis: --- Script: ```shell #!/bin/bash # Verify that the tweak derivation logic is consistent across the codebase. ast-grep --lang rust --pattern $'fn derive_add_tweak($_, $_) -> $_ { let mut sha = Sha256::engine(); sha.input(&$_); sha.input(&$_); Sha256::from_engine(sha).to_byte_array() }'Length of output: 185
Script:
#!/bin/bash # Broaden the search to find any similar tweak derivation logic across the codebase. ast-grep --lang rust --pattern $'fn $_($_, $_) -> $_ { let mut sha = Sha256::engine(); sha.input(&$_); sha.input(&$_); $_ }'Length of output: 133
a0f0561 to
d601e76
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (9 hunks)
Files skipped from review as they are similar to previous changes (2)
- lightning/src/chain/channelmonitor.rs
- lightning/src/sign/mod.rs
Additional comments: 2
lightning/src/ln/channel_keys.rs (2)
- 41-56: The
derive_add_tweakmethod has been added to derive a tweak from a basepoint and a per_commitment_point. Ensure that the logic for tweak derivation is consistent with the intended cryptographic design and that the use of SHA256 for hashing is appropriate for the security requirements.- 37-66: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [1-57]
Review the integration of the new
derive_add_tweakmethod with existing key derivation structures and usage patterns to ensure consistency and correctness within the module.
7c74131 to
cdecffe
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (56 hunks)
Files not summarized due to errors (1)
- lightning/src/sign/mod.rs: Error: Message exceeds token limit
Files skipped from review as they are similar to previous changes (2)
- lightning/src/chain/channelmonitor.rs
- lightning/src/ln/channel_keys.rs
Additional comments: 4
lightning/src/sign/mod.rs (4)
- 1841-1876: The method
KeysManager::newuses a deterministic approach to generate various keys from a given seed. This approach is generally secure as long as the seed is kept secret and is generated using a secure random number generator. However, it's crucial to ensure that the seed is indeed generated securely and is properly backed up by the user, as the loss of the seed could result in the loss of funds or inability to access the funds.One potential improvement could be to explicitly document the importance of the seed's security and backup in the method's documentation, emphasizing the consequences of seed loss.
- 2422-2446: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [2405-2437]
The
PhantomKeysManager::newmethod correctly initializes aPhantomKeysManagerinstance, including the generation of aphantom_secretandphantom_node_idbased on across_node_seed. This approach allows multiple nodes to participate in phantom node payments securely. It's important to ensure that thecross_node_seedis also generated securely and shared securely among participating nodes. Documenting the security considerations aroundcross_node_seedmanagement could help users understand its importance and ensure its proper handling.
- 1169-1198: > 📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1172-1223]
The method
InMemorySigner::sign_counterparty_payment_inputcorrectly signs a counterparty payment input. It properly checks for the input's existence, ensures thescript_sigis empty, and verifies that the input is spending the expected outpoint. These checks are crucial for the security of the signing operation. However, it's important to ensure that thesecp_ctxprovided to this method is securely managed and that theInMemorySignerinstance is properly isolated to prevent unauthorized access to the signing keys.
- 2472-2472: The
RandomBytes::newmethod initializes aRandomBytesinstance with a given seed. It's crucial that the seed used to initializeRandomBytesis generated from a secure source of randomness. Additionally, the use of an atomic counter to ensure uniqueness of the output is a good practice. However, it would be beneficial to document the importance of the seed's security and the atomicity of the counter operation to prevent potential misuse or misunderstanding by future developers or users.
cdecffe to
62ed503
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review Status
Actionable comments generated: 0
Configuration used: CodeRabbit UI
Files selected for processing (3)
- lightning/src/chain/channelmonitor.rs (1 hunks)
- lightning/src/ln/channel_keys.rs (1 hunks)
- lightning/src/sign/mod.rs (56 hunks)
Files not summarized due to errors (1)
- lightning/src/sign/mod.rs: Error: Message exceeds token limit
Files skipped from review as they are similar to previous changes (2)
- lightning/src/chain/channelmonitor.rs
- lightning/src/ln/channel_keys.rs
Additional comments: 7
lightning/src/sign/mod.rs (7)
- 15-30: The imports are well-organized and relevant to the functionality provided in this file. It's good practice to keep them grouped and sorted for better readability.
- 113-117: The optional nature of
channel_transaction_parametersinDelayedPaymentOutputDescriptoris correctly documented, indicating a change in behavior starting from versionv0.0.122. This is a good example of maintaining backward compatibility while introducing new features.- 174-181: The method
witness_scriptinStaticPaymentOutputDescriptorcorrectly handles the distinction between anchor and non-anchor channels. This is crucial for ensuring that the generated witness script is valid for the specific channel type. Good job on implementing this logic clearly.- 326-356: The documentation and implementation for adding a proprietary field to a PSBT input are clear and well-explained. This is a good example of extending PSBT functionality in a way that's compatible with existing standards.
- 113-117: Considering the previous comment regarding the optional nature of
channel_transaction_parameters, it might be beneficial to add a method or utility function that safely unwraps this option, given its guaranteed presence in newer versions. This could reduce repetitive checks and unwraps throughout the codebase.Consider adding a utility method for safely unwrapping
channel_transaction_parameterswith appropriate documentation on its guaranteed presence in newer versions.
- 174-181: While the current implementation correctly handles different channel types, it's important to ensure that any future changes to channel types or their properties are reflected here. Consider adding a unit test that verifies the correct
witness_scriptis generated for various channel configurations.- 326-356: The use of a proprietary field in PSBT inputs for storing additional data is a clever solution. However, ensure that this approach is documented and communicated with any external tools or wallets that may interact with these PSBTs, as they might not recognize or correctly handle these fields.
84af872 to
6ebf48a
Compare
6ebf48a to
f80e354
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Few quick notes, will take a further look in a bit.
lightning/src/sign/mod.rs
Outdated
| let payment_key = DelayedPaymentKey::from_basepoint( | ||
| secp_ctx, | ||
| basepoint, | ||
| &per_commitment_point, | ||
| ); | ||
| // Required to derive signing key: privkey = basepoint_secret + SHA256(per_commitment_point || basepoint) | ||
| let add_tweak = basepoint.derive_add_tweak(&per_commitment_point); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIUC you're deriving the same tweak twice across these two statements, would be nice to use the add_tweak and build the key or to have a method on DelayedPaymentKey to get both the tweak and key in one go.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Refactored pubkey derivation a bit to get add tweak and then use it to derive a pubkey.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Two more quick comments, otherwise LGTM. Feel free to squash when addressing these and the above.
6c1edd1 to
3b36897
Compare
Adding Witness Script and key tweaks makes a Partially Signed Bitcoin Transaction the single data source needed for a Signer to produce valid signatures. A Signer is not required to be able to generate L2 keys, e.g delayed payment basepoint.
3b36897 to
e08f7de
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we can go ahead and land this and address the followups before the next release.
| } | ||
|
|
||
| /// Derives a per-commitment-transaction (eg an htlc key or delayed_payment key) private key addition tweak | ||
| /// from a basepoint and a per_commitment_point: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We really need some paragraph breaks in here.
| /// `privkey = basepoint_secret + SHA256(per_commitment_point || basepoint)` | ||
| /// This calculates the hash part in the tweak derivation process, which is used to ensure | ||
| /// that each key is unique and cannot be guessed by an external party. It is equivalent | ||
| /// to the `from_basepoint` method, but without the addition operation, providing just the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should work?
| /// to the `from_basepoint` method, but without the addition operation, providing just the | |
| /// to the [`Self::from_basepoint`] method, but without the addition operation, providing just the |
| } | ||
|
|
||
| /// Adds a tweak to a public key to derive a new public key. | ||
| pub fn add_public_key_tweak<T: secp256k1::Signing>( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given this can panic if the tweak isn't a hash, I'd prefer if we either make this crate-private or at least document it.
| pub channel_keys_id: [u8; 32], | ||
| /// The value of the channel which this output originated from, possibly indirectly. | ||
| pub channel_value_satoshis: u64, | ||
| /// The channel public keys and other parameters needed to generate a spending transaction or to provide to a re-derived signer through |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be word-wrapped at 100 chars.
Implement Script for Witness and Add Tweak in Partially Signed Bitcoin Transaction to make it a single data source needed for a Signer to produce valid signatures.