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

rustfmt: Format sign module #2910

Merged
merged 16 commits into from
Apr 10, 2024

Conversation

tnull
Copy link
Contributor

@tnull tnull commented Feb 23, 2024

Chose this one next as it's straightforward and AFAICT there should be ~nothing currently in flight conflicting with this.

Also added a commit to format util/hash_tables.rs to fix the silent rebase conflict (i.e., it was introduced after the base of #2877) and a few trivial ones for helper crates.

Copy link

coderabbitai bot commented Feb 23, 2024

Note

Reviews Paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The updates primarily enhance the signing functionalities within the lightning module, focusing on code maintainability and readability. Changes include reorganizing imports, refining code structure, and updating function signatures across several files. These adjustments aim to streamline the code without impacting its core logic. Additionally, the exclusion of certain files from formatting hints at a broader reevaluation of the signing logic, suggesting a move towards more efficient or clear implementation strategies.

Changes

Files Summary
ecdsa.rs, taproot.rs Reordered imports, restructured code formatting, and adjusted function signatures for clarity and consistency.
type_resolver.rs Restructured ChannelSignerType enum and updated implementation methods to align with trait bounds.
hash_tables.rs Adjusted order of imports and updated function definitions for hash map and hash set operations in std_hashtables and hashbrown_tables. Updated RandomState struct and Default implementation. Re-exported hasher module and adjusted HashMap type. Functions updated for hasher configuration.
rustfmt_excluded_files Excluded specific files from rustfmt, indicating potential significant changes in signing logic.

🐰✨
Code hops and leaps, a tidy feat,
In the land of lightning, where bytes meet.
Imports align, and signatures shine,
A rabbit's touch, making code divine.
🌟📜🚀

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.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

@tnull
Copy link
Contributor Author

tnull commented Feb 23, 2024

@coderabbitai pause

Copy link

@coderabbitai coderabbitai bot left a 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

Commits Files that changed from the base of the PR and between 36e434d and 8051234.
Files selected for processing (5)
  • lightning/src/sign/ecdsa.rs (8 hunks)
  • lightning/src/sign/mod.rs (55 hunks)
  • lightning/src/sign/taproot.rs (8 hunks)
  • lightning/src/sign/type_resolver.rs (2 hunks)
  • rustfmt_excluded_files (1 hunks)
Files not summarized due to errors (1)
  • lightning/src/sign/mod.rs: Error: Message exceeds token limit
Files skipped from review due to trivial changes (2)
  • lightning/src/sign/ecdsa.rs
  • lightning/src/sign/taproot.rs
Additional comments: 13
lightning/src/sign/type_resolver.rs (6)
  • 4-7: The restructuring of the ChannelSignerType enum with clearer trait bounds is a positive change for readability and maintainability. It makes the relationship between ChannelSignerType and SignerProvider explicit, which is beneficial for developers working with this code.
  • 14-17: The implementation block for ChannelSignerType correctly specifies the trait bounds for SP, ensuring that SP::Target implements SignerProvider. This consistency with the enum declaration is crucial for maintaining the integrity of the type system.
  • 1-20: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [18-26]

The as_ref method provides a safe way to obtain a reference to the underlying ChannelSigner, leveraging Rust's powerful match syntax and type system. This method enhances the usability of ChannelSignerType by allowing easy access to the signer's functionality.

  • 35-51: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [27-35]

Similar to as_ref, the as_mut method improves the ChannelSignerType's flexibility by providing mutable access to the underlying ChannelSigner. This is essential for scenarios where the signer needs to be modified.

  • 36-38: The as_ecdsa method introduces an option type for safely handling the case where the ChannelSignerType is not an ECDSA signer. This approach prevents runtime errors and aligns with Rust's emphasis on safety and explicit error handling.
  • 43-48: The as_mut_ecdsa method complements as_ecdsa by providing mutable access to the ECDSA signer if present. This method is crucial for operations that require altering the state of the ECDSA signer.
rustfmt_excluded_files (1)
  • 234-239: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [1-1]

The removal of ecdsa.rs, mod.rs, taproot.rs, and type_resolver.rs from the rustfmt_excluded_files list is a significant step towards ensuring consistent code formatting across the project. This change aligns with the PR's objectives of improving code readability and maintainability by adhering to coding standards.

lightning/src/sign/mod.rs (6)
  • 15-74: The reordering of imports and the addition of conditional compilation flags (#[cfg(taproot)]) improve the code's readability and maintainability by clearly separating features and dependencies. This change aligns with best practices for managing feature-dependent code in Rust.
  • 116-123: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [75-122]

The DelayedPaymentOutputDescriptor struct and its implementation are well-structured, providing clear documentation and a straightforward implementation. The use of constants like MAX_WITNESS_LENGTH for defining the maximum length of a well-formed witness is a good practice, ensuring that magic numbers are avoided and making the code more maintainable.

  • 162-187: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [123-172]

The implementation of StaticPaymentOutputDescriptor and its method witness_script demonstrates good use of Rust's option handling and conditional logic to support different channel types. However, it's essential to ensure comprehensive testing around these conditional paths, especially since they impact the script generation for spending outputs.

  • 179-184: The method max_witness_length in StaticPaymentOutputDescriptor correctly calculates the maximum witness length based on whether the channel supports anchor outputs. This is a critical piece of logic for ensuring that transactions are constructed correctly. It's recommended to add explicit unit tests for this method to verify the calculations under different conditions.
Verification successful

The search for explicit unit tests targeting the StaticPaymentOutputDescriptor::max_witness_length method did not yield any results, indicating that such tests likely do not exist in the codebase. This supports the original suggestion to add explicit unit tests for this method to verify its calculations under different conditions.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Suggest adding explicit unit tests for StaticPaymentOutputDescriptor::max_witness_length.
echo "Suggest adding explicit unit tests for StaticPaymentOutputDescriptor::max_witness_length."

Length of output: 188



Script:

#!/bin/bash
# Search for unit tests targeting StaticPaymentOutputDescriptor::max_witness_length
rg "StaticPaymentOutputDescriptor::max_witness_length" --type rust

Length of output: 66

* 236-236: The use of `Recipient::PhantomNode` in the `NodeSigner` trait implementation for `PhantomKeysManager` introduces a new variant to handle phantom node payments. This is a significant addition that enhances the flexibility of the signing process to accommodate different types of nodes. Ensure that all potential security implications of introducing phantom node payments are thoroughly reviewed, especially regarding the reuse of the `cross_node_seed` across multiple nodes. * 2313-2337: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [2297-2328]

The method PhantomKeysManager::spend_spendable_outputs delegates to KeysManager::spend_spendable_outputs, maintaining a clear separation of concerns and reusing existing functionality effectively. This delegation is a good example of code reuse. However, ensure that the unique aspects of phantom node payments are adequately handled in the broader context of transaction signing and output spending.

Verification successful

Given the need to verify the handling of phantom node payments in transaction signing and output spending, and the lack of information from the previous script execution, we will proceed to gather the necessary information by searching the codebase for relevant implementations or references. This will help us understand how PhantomKeysManager interacts with transaction signing and output spending functionalities, and whether there are any unique aspects of phantom node payments that require special handling.


The search results provide extensive references to PhantomKeysManager and its usage across various parts of the codebase, including transaction signing, output spending, and handling phantom node payments. The references in lightning/src/sign/mod.rs and related files indicate that the PhantomKeysManager is designed to support phantom node payments by managing keys and signatures specific to phantom nodes. This includes generating phantom node IDs, handling secret keys for phantom nodes, and ensuring that phantom node payments are processed correctly.

The code snippets and references found in the search results show that the PhantomKeysManager plays a crucial role in handling phantom node payments, including aspects related to transaction signing and output spending. The implementation details, such as the generation of phantom node IDs and the handling of secret keys, suggest that the unique aspects of phantom node payments are indeed considered and adequately handled within the broader context of transaction signing and output spending.

Based on the information gathered from the search results, it can be concluded that the handling of phantom node payments, including their unique aspects in transaction signing and output spending, is implemented and integrated within the codebase through the PhantomKeysManager and related functionalities.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Ensure that the unique aspects of phantom node payments are adequately handled in transaction signing and output spending.
echo "Verify handling of phantom node payments in transaction signing."

Length of output: 138



Script:

#!/bin/bash
# Search for references to PhantomKeysManager and its interaction with transaction signing and output spending
echo "Searching for PhantomKeysManager usage..."
rg "PhantomKeysManager" --vimgrep

echo "Searching for special handling of phantom node payments in transaction signing and output spending..."
rg "phantom" --vimgrep

Length of output: 39541

Copy link

@coderabbitai coderabbitai bot left a 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

Commits Files that changed from the base of the PR and between 8051234 and 86413e7.
Files selected for processing (1)
  • lightning/src/util/hash_tables.rs (7 hunks)
Additional comments: 9
lightning/src/util/hash_tables.rs (9)
  • 19-19: The import of HashMap from std::collections remains unchanged and is correctly placed for the std_hashtables module.
  • 21-21: The use of std::collections::{hash_map, HashSet} is appropriate for the std_hashtables module, facilitating access to both HashMap and HashSet types and their related functionalities.
  • 29-31: The function new_hash_map correctly initializes a new HashMap with the default constructor. This is a straightforward and expected implementation for creating a new hash map.
  • 36-42: The function hash_map_from_iter is implemented correctly, utilizing HashMap::from_iter to create a new HashMap from an iterator. This is a clean and efficient way to initialize a hash map with pre-defined key-value pairs.
  • 46-54: The functions new_hash_set and hash_set_from_iter for creating new HashSet instances and initializing them from an iterator are correctly implemented. These methods follow the expected patterns for set creation and initialization in Rust.
  • 76-92: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [79-112]

The RandomState struct and its implementation in the hashbrown_tables module introduce a significant change. The logic for potentially randomizing the hasher state using getrandom (if available) is a crucial security enhancement. However, it's important to ensure that the possiblyrandom feature is correctly configured in the project settings to make use of this functionality effectively.

  • 124-124: The re-export of the hasher module's contents in the hashbrown_tables module is a good practice, ensuring that all necessary hasher-related types and functions are accessible where needed.
  • 143-149: The updated hash_map_from_iter function in the hashbrown_tables module now includes logic to pre-allocate the hash map with a capacity based on the iterator's size hint. This is a performance optimization that can reduce the number of re-allocations when filling the map from an iterator with a known or estimated size.
  • 163-165: Similarly, the hash_set_from_iter function's update to pre-allocate capacity based on the iterator's size hint is a performance optimization for HashSet creation. This approach is consistent with best practices for initializing collections from iterators with known sizes.

@codecov-commenter
Copy link

codecov-commenter commented Feb 23, 2024

Codecov Report

Attention: Patch coverage is 88.51675% with 72 lines in your changes are missing coverage. Please review.

Project coverage is 89.40%. Comparing base (eaf76f6) to head (3a199c6).

Files Patch % Lines
lightning/src/sign/mod.rs 88.88% 61 Missing and 8 partials ⚠️
lightning/src/sign/type_resolver.rs 0.00% 3 Missing ⚠️

❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2910      +/-   ##
==========================================
+ Coverage   89.36%   89.40%   +0.03%     
==========================================
  Files         117      117              
  Lines       95622    96016     +394     
  Branches    95622    96016     +394     
==========================================
+ Hits        85457    85840     +383     
- Misses       7930     7959      +29     
+ Partials     2235     2217      -18     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@tnull
Copy link
Contributor Author

tnull commented Feb 28, 2024

Kicked CI.

Copy link

@coderabbitai coderabbitai bot left a 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

Commits Files that changed from the base of the PR and between 86413e7 and a8717a2.
Files selected for processing (2)
  • msrv-no-dev-deps-check/src/lib.rs (1 hunks)
  • rustfmt_excluded_files (2 hunks)
Files skipped from review due to trivial changes (1)
  • msrv-no-dev-deps-check/src/lib.rs
Files skipped from review as they are similar to previous changes (1)
  • rustfmt_excluded_files

@tnull
Copy link
Contributor Author

tnull commented Feb 28, 2024

@coderabbitai pause, pretty please.

Copy link

coderabbitai bot commented Feb 28, 2024

@tnull: Sure, I'll pause the review process as requested. If you need anything else, feel free to let me know.

Actions performed

Reviews paused.

@TheBlueMatt
Copy link
Collaborator

Lets wait until #2761.

@tnull
Copy link
Contributor Author

tnull commented Mar 4, 2024

Lets wait until #2761.

Alright, then I'll move the hash tables fix to its own PR to unbreak CI. Also considering then prioritizing other modules to keep making progress.

@tnull
Copy link
Contributor Author

tnull commented Mar 4, 2024

Alright, then I'll move the hash tables fix to its own PR to unbreak CI. Also considering then prioritizing other modules to keep making progress.

Added here: #2919

@jkczyz
Copy link
Contributor

jkczyz commented Mar 25, 2024

Lets wait until #2761.

Alright, then I'll move the hash tables fix to its own PR to unbreak CI. Also considering then prioritizing other modules to keep making progress.

Should we land this PR first? Otherwise, the author of #2761 needs to undo all the formatting changes. 🙁

@TheBlueMatt
Copy link
Collaborator

Lets let the author of #2761 decide whether he wants to rebase with the fmt changes or without.

lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/type_resolver.rs Show resolved Hide resolved
@tnull
Copy link
Contributor Author

tnull commented Mar 27, 2024

Rebased, addressed comments, and cleaned up commit history.

lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
lightning/src/sign/mod.rs Outdated Show resolved Hide resolved
@tnull
Copy link
Contributor Author

tnull commented Mar 27, 2024

Force-pushed including the following fixups:

> git diff-tree -U3 230961f3e d0043d972
diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs
index 18c4d8340..b8fdbb9f5 100644
--- a/lightning/src/ln/chan_utils.rs
+++ b/lightning/src/ln/chan_utils.rs
@@ -850,6 +850,11 @@ impl ChannelTransactionParameters {
                self.counterparty_parameters.is_some() && self.funding_outpoint.is_some()
        }

+       /// Whether the channel supports zero-fee HTLC transaction anchors.
+       pub fn supports_anchors(&self) -> bool {
+               self.channel_type_features.supports_anchors_zero_fee_htlc_tx()
+       }
+
        /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters,
        /// given that the holder is the broadcaster.
        ///
diff --git a/lightning/src/sign/mod.rs b/lightning/src/sign/mod.rs
index dd9075db6..22a5fff83 100644
--- a/lightning/src/sign/mod.rs
+++ b/lightning/src/sign/mod.rs
@@ -163,7 +163,7 @@ impl StaticPaymentOutputDescriptor {
        /// originated from an anchor outputs channel, as they take the form of a P2WSH script.
        pub fn witness_script(&self) -> Option<ScriptBuf> {
                self.channel_transaction_parameters.as_ref().and_then(|channel_params| {
-                       if params_support_anchors(channel_params) {
+                       if channel_params.supports_anchors() {
                                let payment_point = channel_params.holder_pubkeys.payment_point;
                                Some(chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point))
                        } else {
@@ -176,8 +176,7 @@ impl StaticPaymentOutputDescriptor {
        /// Note: If you have the grind_signatures feature enabled, this will be at least 1 byte
        /// shorter.
        pub fn max_witness_length(&self) -> u64 {
-               if self.channel_transaction_parameters.as_ref().map(params_support_anchors).unwrap_or(false)
-               {
+               if self.channel_transaction_parameters.as_ref().map_or(false, |p| p.supports_anchors()) {
                        let witness_script_weight = 1 /* pubkey push */ + 33 /* pubkey */ +
                                1 /* OP_CHECKSIGVERIFY */ + 1 /* OP_1 */ + 1 /* OP_CHECKSEQUENCEVERIFY */;
                        1 /* num witness items */ + 1 /* sig push */ + 73 /* sig including sighash flag */ +
@@ -365,8 +364,7 @@ impl SpendableOutputDescriptor {
                                        let sequence = if descriptor
                                                .channel_transaction_parameters
                                                .as_ref()
-                                               .map(params_support_anchors)
-                                               .unwrap_or(false)
+                                               .map_or(false, |p| p.supports_anchors())
                                        {
                                                Sequence::from_consensus(1)
                                        } else {
@@ -381,8 +379,9 @@ impl SpendableOutputDescriptor {
                                        witness_weight += descriptor.max_witness_length();
                                        #[cfg(feature = "grind_signatures")]
                                        {
+                                               // Guarantees a low R signature
                                                witness_weight -= 1;
-                                       } // Guarantees a low R signature
+                                       }
                                        input_value += descriptor.output.value;
                                },
                                SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) => {
@@ -2348,10 +2347,6 @@ impl EntropySource for RandomBytes {
        }
 }

-fn params_support_anchors(channel_params: &ChannelTransactionParameters) -> bool {
-       channel_params.channel_type_features.supports_anchors_zero_fee_htlc_tx()
-}
-
 // Ensure that EcdsaChannelSigner can have a vtable
 #[test]
 pub fn dyn_sign() {

Copy link
Contributor

@jkczyz jkczyz left a comment

Choose a reason for hiding this comment

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

LGTM

lightning/src/ln/chan_utils.rs Outdated Show resolved Hide resolved
@tnull
Copy link
Contributor Author

tnull commented Mar 27, 2024

Force-pushed including the following changes:

> git diff-tree -U2 d0043d972 5b33d3264
diff --git a/lightning/src/ln/chan_utils.rs b/lightning/src/ln/chan_utils.rs
index b8fdbb9f5..f8d15d2a8 100644
--- a/lightning/src/ln/chan_utils.rs
+++ b/lightning/src/ln/chan_utils.rs
@@ -852,5 +852,5 @@ impl ChannelTransactionParameters {

        /// Whether the channel supports zero-fee HTLC transaction anchors.
-       pub fn supports_anchors(&self) -> bool {
+       pub(crate) fn supports_anchors(&self) -> bool {
                self.channel_type_features.supports_anchors_zero_fee_htlc_tx()
        }

jkczyz
jkczyz previously approved these changes Mar 27, 2024
@TheBlueMatt
Copy link
Collaborator

Lets maybe wait for #2845?

@tnull
Copy link
Contributor Author

tnull commented Apr 9, 2024

Rebased to resolve minor conflict.

@TheBlueMatt TheBlueMatt merged commit 1d2a27d into lightningdevkit:main Apr 10, 2024
16 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
Development

Successfully merging this pull request may close these issues.

4 participants