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

backport: finish merging 25001 #6531

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

PastaPastaPasta
Copy link
Member

Issue being fixed or feature implemented

This was partially done earlier; do the remaining commits

What was done?

see commits

How Has This Been Tested?

built locally

Breaking Changes

none

Checklist:

Go over all the following points, and put an x in all the boxes that apply.

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation
  • I have assigned this pull request to a milestone (for repository code-owners and collaborators only)

@PastaPastaPasta PastaPastaPasta added this to the 22.1 milestone Jan 12, 2025
Copy link

coderabbitai bot commented Jan 12, 2025

Walkthrough

The provided pull request introduces a comprehensive set of changes across multiple source files in the Bitcoin codebase, focusing on improving string handling, error management, and performance. The modifications primarily revolve around three key aspects:

  1. String View Adoption: Many functions have been updated to use std::string_view, which allows for more efficient string processing by avoiding unnecessary copies. This change spans across encoding, decoding, and utility functions in files like strencodings.cpp, strencodings.h, and string.h.

  2. Error Handling Refinement: The codebase transitions from using boolean flags for error indication to leveraging std::optional for decoding and parsing functions. This approach provides a more robust and type-safe method of handling potential failures in operations like base64 and base32 decoding.

  3. Input Validation: Several functions have replaced the ValidAsCString validation method with ContainsNoNUL, which specifically checks for the presence of null characters in strings. This change is applied consistently across various files, indicating a deliberate approach to input validation.

These modifications aim to enhance code clarity, improve performance, and strengthen error handling throughout the Bitcoin implementation, demonstrating a systematic approach to code modernization.

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

@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.

Actionable comments posted: 0

🧹 Nitpick comments (6)
src/util/string.h (1)

79-87: Consider adding noexcept specifier

The Join template functions could benefit from noexcept specification where applicable.

-template <typename T, typename T2>
-T Join(const std::vector<T>& list, const T2& separator)
+template <typename T, typename T2>
+T Join(const std::vector<T>& list, const T2& separator) noexcept(noexcept(T{}))
src/util/strencodings.h (1)

67-67: Improved error handling with std::optional return type

The change from output parameters to std::optional return type for DecodeBase64 and DecodeBase32 functions improves error handling and makes the API more modern and safer.

Consider adding documentation to clarify what conditions would cause the functions to return an empty optional.

Also applies to: 70-71

src/util/strencodings.cpp (1)

205-210: Comprehensive Base32 padding handling

The Base32 padding logic handles all valid cases (1, 3, 4, or 6 padding characters) explicitly and safely.

Consider adding a comment explaining why these specific padding lengths are valid for Base32.

src/rpc/evo.cpp (2)

818-820: Improve error handling for base64 signature decoding

The code now properly handles base64 decoding errors using std::optional, providing better error handling and safety.

Consider extracting the error message to a constant to maintain consistency across the codebase:

static const char* BASE64_DECODE_ERROR = "failed to decode base64 ready signature for protx";

if (!opt_vchSig.has_value()) throw JSONRPCError(RPC_INTERNAL_ERROR, BASE64_DECODE_ERROR);

880-884: Improve error handling for base64 signature parsing

The code now properly handles base64 decoding errors using std::optional and provides a more specific error message.

Consider making the error message more descriptive to help users understand what went wrong:

if (!opt_vchSig.has_value()) {
    throw JSONRPCError(RPC_INVALID_PARAMETER, "The provided signature is not a valid base64 string");
}
src/test/util_tests.cpp (1)

2697-2703: Add test cases for RemovePrefixView function

New test cases added to verify the RemovePrefixView functionality with various input combinations.

Consider adding more edge cases to improve test coverage:

BOOST_CHECK_EQUAL(RemovePrefixView("foo/bar", "foo/"), "bar");
BOOST_CHECK_EQUAL(RemovePrefixView("foo/bar/", "foo/bar/"), "");
BOOST_CHECK_EQUAL(RemovePrefixView("foo/bar/baz", "foo/bar/baz/"), "foo/bar/baz");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8dac4b1 and fae670a.

📒 Files selected for processing (26)
  • src/base58.cpp (2 hunks)
  • src/bitcoin-tx.cpp (1 hunks)
  • src/httprpc.cpp (1 hunks)
  • src/httpserver.cpp (1 hunks)
  • src/i2p.cpp (1 hunks)
  • src/netaddress.cpp (3 hunks)
  • src/netbase.cpp (5 hunks)
  • src/psbt.cpp (1 hunks)
  • src/psbt.h (1 hunks)
  • src/qt/walletframe.cpp (2 hunks)
  • src/rpc/evo.cpp (2 hunks)
  • src/rpc/governance.cpp (3 hunks)
  • src/stacktraces.cpp (1 hunks)
  • src/test/base32_tests.cpp (1 hunks)
  • src/test/base64_tests.cpp (2 hunks)
  • src/test/fuzz/base_encode_decode.cpp (2 hunks)
  • src/test/fuzz/http_request.cpp (1 hunks)
  • src/test/fuzz/psbt.cpp (2 hunks)
  • src/test/fuzz/string.cpp (2 hunks)
  • src/test/util_tests.cpp (2 hunks)
  • src/util/message.cpp (1 hunks)
  • src/util/moneystr.cpp (1 hunks)
  • src/util/strencodings.cpp (9 hunks)
  • src/util/strencodings.h (10 hunks)
  • src/util/string.h (3 hunks)
  • src/util/system.cpp (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Clang Diff Format Check
src/rpc/evo.cpp

[warning] 816-816: Code formatting issue: Conditional statement needs to be split into multiple lines


[warning] 877-877: Code formatting issue: Missing space after variable declaration

🔇 Additional comments (47)
src/test/base32_tests.cpp (2)

25-27: LGTM! Improved error handling approach

The transition from bool* to std::optional for DecodeBase32 results in cleaner and more idiomatic C++ code. The use of BOOST_REQUIRE ensures immediate test failure on decode errors.


31-34: LGTM! Comprehensive null character handling tests

Good coverage of edge cases for null character handling, including:

  • Middle of string
  • Valid input
  • After valid base32 string
  • Invalid size scenarios
src/test/base64_tests.cpp (2)

22-24: LGTM! Consistent error handling improvement

The changes align with the base32 updates, using std::optional for cleaner error handling.


38-41: LGTM! Comprehensive null character validation

Good set of test cases covering various null character scenarios in base64 strings.

src/test/fuzz/base_encode_decode.cpp (3)

25-25: Performance improvement using TrimStringView

Good optimization by using TrimStringView instead of TrimString to avoid unnecessary string copies.


35-39: LGTM! Consistent Base32 decoding pattern

The changes align with the new error handling approach using std::optional.


42-44: LGTM! Consistent Base64 decoding pattern

The changes maintain consistency with the Base32 implementation.

src/util/moneystr.cpp (1)

43-43: LGTM! Consistent string validation

The change from ValidAsCString to ContainsNoNUL provides more precise validation and maintains consistency with similar changes across the codebase.

src/util/message.cpp (2)

38-39: LGTM! Improved error handling with std::optional

The change from boolean flag to std::optional for DecodeBase64 result improves code clarity and error handling.


44-44: Verify proper error handling for RecoverCompact

While the dereferencing of signature_bytes is safe due to the prior check, consider adding error handling for RecoverCompact failure.

src/test/fuzz/psbt.cpp (1)

26-27: LGTM! Improved type safety in fuzzing tests

The changes enhance type safety by:

  1. Using an intermediate variable for the random string
  2. Explicitly converting to byte span using MakeByteSpan

Also applies to: 74-75

src/test/fuzz/http_request.cpp (1)

57-57: LGTM! More explicit string construction

The change improves code clarity by using explicit std::string construction instead of relying on implicit conversion.

src/util/string.h (4)

32-39: LGTM! Optimized string trimming with string_view

The new TrimStringView implementation properly handles empty results and avoids unnecessary string allocations.


42-45: LGTM! Clean separation of view and string operations

Good practice to provide both string_view and string versions of the trim operation.


47-58: LGTM! Consistent pattern for prefix removal

Following the same pattern as trim operations with separate view and string versions.


102-107: LGTM! Improved null character detection

The new ContainsNoNUL function is more explicit about its purpose and uses modern C++ features.

src/base58.cpp (2)

129-132: LGTM! The validation change improves clarity.

The change from ValidAsCString to ContainsNoNUL makes the validation more focused and explicit about what it's checking.


163-166: LGTM! Consistent validation approach.

The validation change is consistent with the DecodeBase58 function above.

src/qt/walletframe.cpp (4)

252-252: LGTM! Better type for binary data.

Changed from std::string to std::vector<unsigned char>, which is more appropriate for handling binary PSBT data.


256-261: LGTM! Improved error handling with std::optional.

The change to use std::optional for base64 decoding provides clearer error handling and better type safety.


272-272: LGTM! Direct binary reading.

Using std::istream_iterator<unsigned char> provides direct binary reading without string conversion.


277-277: LGTM! Consistent byte span usage.

Using MakeByteSpan adapts the data correctly for the updated DecodeRawPSBT interface.

src/test/fuzz/string.cpp (1)

43-43: LGTM! Consistent validation approach.

The change from ValidAsCString to ContainsNoNUL aligns with similar changes in other files, making the validation intent more explicit.

src/psbt.cpp (2)

346-351: LGTM! Improved error handling with std::optional.

The change to use std::optional for base64 decoding provides better type safety and clearer error handling.


354-356: LGTM! Better type safety with Span.

Changed function signature to use Span<const std::byte>, providing better type safety for binary data handling.

src/util/strencodings.h (3)

238-244: Good addition of IntIdentity helper

The IntIdentity helper class provides a clean default implementation for the infn parameter in ConvertBits. This improves code clarity and maintainability.


248-249: Verify ConvertBits template usage with new IntIdentity

The ConvertBits template function now uses the new IntIdentity helper. We should verify all existing uses remain compatible.

✅ Verification successful

ConvertBits template modification is backward compatible

All existing uses of ConvertBits are compatible with the new IntIdentity parameter as they rely on the default value, requiring no changes to the calling code.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all uses of ConvertBits to verify compatibility
rg "ConvertBits<" --type cpp

Length of output: 648


97-102: Verify the behavior change in LocaleIndependentAtoi

The function now uses TrimStringView and std::from_chars instead of the C locale-dependent functions. While this is a good modernization, we should verify the behavior is identical.

✅ Verification successful

✓ Behavior change in LocaleIndependentAtoi is correct

The function's behavior is identical to the C locale-dependent functions, as verified by:

  • Comprehensive test suite covering all edge cases
  • Explicit fuzz test verification against legacy behavior
  • Consistent usage patterns across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to LocaleIndependentAtoi to verify usage patterns
rg -A 2 "LocaleIndependentAtoi" 

Length of output: 10089

src/httprpc.cpp (1)

174-178: Improved error handling in RPCAuthorized

The changes improve both efficiency and safety:

  1. Using std::string_view reduces unnecessary copying
  2. Using std::optional for Base64 decoding makes error handling more explicit
  3. Early return on decoding failure simplifies the control flow
src/i2p.cpp (1)

72-76: Streamlined Base64 decoding with std::optional

The changes improve the code by:

  1. Using std::optional for clearer error handling
  2. Using std::move to avoid unnecessary copying of the decoded data
  3. Providing a more descriptive error message on failure
src/util/strencodings.cpp (4)

150-153: Robust padding handling in Base64 decoding

The padding removal logic is now more explicit and safer, properly handling one or two padding characters.


156-162: Efficient Base64 decoding implementation

The implementation is improved with:

  1. Proper memory pre-allocation
  2. Use of ConvertBits for the actual conversion
  3. Clear error handling through the return value

213-222: Efficient Base32 decoding implementation

Similar improvements to Base64 decoding:

  1. Proper memory pre-allocation
  2. Use of ConvertBits for conversion
  3. Clear error handling

494-494: Verify ParseByteUnits with new string_view parameter

The function now takes std::string_view, which is more efficient but we should verify all callers handle the lifetime correctly.

✅ Verification successful

String view lifetime usage is safe

All current usages of ParseByteUnits maintain proper string_view lifetime:

  • Test cases use string literals
  • Production code in init.cpp safely uses temporary strings
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to ParseByteUnits
rg "ParseByteUnits\(" --type cpp

Length of output: 2251

src/httpserver.cpp (1)

275-279: LGTM! Improved error handling for Base64 decoding.

The changes enhance robustness and readability by:

  • Using std::optional for clearer error handling
  • Employing string iterator for more idiomatic delimiter search
  • Properly handling all error cases with early returns
src/stacktraces.cpp (1)

430-435: LGTM! Enhanced error handling for crash info deserialization.

The changes improve robustness by:

  • Using std::optional for explicit error handling
  • Adding proper validation of the decoded buffer
  • Using clear variable naming with opt_buf
src/netbase.cpp (1)

147-147: LGTM! Consistent input validation across network functions.

The changes standardize string validation by using ContainsNoNUL consistently across:

  • LookupIntern
  • LookupHost
  • Lookup
  • LookupNumeric
  • LookupSubNet

This provides a more focused check for null characters in input strings.

Also applies to: 176-176, 194-194, 219-219, 671-671

src/bitcoin-tx.cpp (1)

226-226: LGTM! Performance optimization in string handling.

The change from TrimString to TrimStringView potentially improves performance by avoiding unnecessary string copies during parsing.

src/netaddress.cpp (4)

214-214: LGTM! Improved string validation.

The change from ValidAsCString to ContainsNoNUL is a good improvement as it makes the validation intent clearer.


244-247: LGTM! Improved readability with descriptive variable names.

The use of descriptive variable names (input_pubkey, input_checksum, input_version) improves code readability.


283-290: LGTM! Consistent error handling pattern.

The changes in SetI2P follow the same pattern as SetTor, maintaining consistency in error handling.


238-244: Verify error handling in base32 decoding.

The change to use std::optional for base32 decoding improves error handling, but we should verify that all error cases are properly handled.

✅ Verification successful

Base32 decoding error handling is properly implemented

The implementation in DecodeBase32 returns std::optional for all error cases (invalid length, invalid characters, conversion failures) and all callers properly check for nullopt before using the result. The test suite includes comprehensive validation of error cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other base32 decoding error handling patterns
rg -A 3 "DecodeBase32\(" | grep -v "if.*has_value"

Length of output: 2565


Script:

#!/bin/bash
# Check the implementation of DecodeBase32 for error cases
ast-grep --pattern 'DecodeBase32(std::string_view str) {
  $$$
}'

Length of output: 67


Script:

#!/bin/bash
# Get the implementation of DecodeBase32
rg -A 30 "^std::optional<std::vector<unsigned char>> DecodeBase32\(std::string_view str\)" src/util/strencodings.cpp

Length of output: 2053


Script:

#!/bin/bash
# Get the complete implementation including the return statement
rg -A 40 "^std::optional<std::vector<unsigned char>> DecodeBase32\(std::string_view str\)" src/util/strencodings.cpp

Length of output: 2191

src/psbt.h (1)

917-917: LGTM! Improved type safety with Span.

The change from std::string to Span<const std::byte> for raw PSBT data improves type safety and makes the API more explicit about its binary data handling.

src/rpc/governance.cpp (2)

425-428: LGTM! Improved error handling with optional.

The change to use std::optional for base64 decoding improves error handling and makes the success/failure state more explicit.


Line range hint 962-977: LGTM! Consistent error handling pattern.

The changes in voteraw follow the same pattern as SignVote, maintaining consistency in error handling across the codebase.

src/util/system.cpp (1)

907-908: LGTM! Performance optimization with string_view.

The change to use std::string_view avoids unnecessary string copies during config parsing, which is a good performance optimization.

src/test/util_tests.cpp (1)

281-291: Update string trimming tests to use TrimStringView

Test cases have been updated to use TrimStringView, which is more efficient than TrimString as it avoids unnecessary string copies.

@@ -422,10 +422,10 @@ static bool SignVote(const CWallet& wallet, const CKeyID& keyID, CGovernanceVote
return false;
}
bool failed = true;
Copy link

Choose a reason for hiding this comment

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

14d91bf:

Suggested change
bool failed = true;

@@ -427,12 +427,12 @@ std::string GetCrashInfoStrFromSerializedStr(const std::string& ciStr)
static uint64_t basePtr = GetBaseAddress();

bool dataInvalid = false;
Copy link

Choose a reason for hiding this comment

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

14d91bf:

Suggested change
bool dataInvalid = false;

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.

3 participants