forked from leishman/yam
-
Notifications
You must be signed in to change notification settings - Fork 0
Refactor: Deduplicate readMessage implementations into shared utility #1
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
Open
Copilot
wants to merge
20
commits into
master
Choose a base branch
from
copilot/refactor-read-message-duplicate
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
0ce8d91
Add CI workflow for Linux, macOS, and Windows
kwsantiago ee9152d
Add security hardening: bounds checks, checksum validation, and hands…
kwsantiago 0fc6c4e
Merge pull request #4 from privkeyio/security-fixes
leishman f0c2c77
Merge pull request #5 from privkeyio/add-ci
leishman 65004de
Update README to clarify tool's dependencies
leishman 31801a1
Initial plan
Copilot 59d25e4
Refactor: extract readMessage to shared message_utils module
Copilot 2bbab67
Fix error handling flow to match original behavior
Copilot d08a727
Extract magic number 4_000_000 to named constant MAX_PAYLOAD_SIZE
Copilot f2099f9
Extract readMessageChecked helper to eliminate duplicated block pattern
Copilot 36f5b6c
Fix double-free bugs and add comprehensive tests to message_utils
Copilot 236db67
Revert double-free fix to match original behavior
Copilot eb6a9d5
Remove unused variable in readMessage test for cleaner code
pseudozach 9774e44
Remove redundant allocator.free calls in readMessage error handling
pseudozach 413ce16
Enforce strict message validation for scout as well
pseudozach 2893893
Remove tests
pseudozach 6a5c29f
Implement handshake timeout in performHandshake function
pseudozach 717bbb0
Remove waitForReject function to streamline message handling
pseudozach 8393dbd
Refactor: use single MAX_PAYLOAD_SIZE in message_utils
pseudozach b572051
Add basic tests to message_utils
pseudozach File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| name: CI | ||
|
|
||
| on: | ||
| push: | ||
| branches: [master] | ||
| pull_request: | ||
| branches: [master] | ||
|
|
||
| jobs: | ||
| build: | ||
| strategy: | ||
| matrix: | ||
| os: [ubuntu-latest, macos-latest, windows-latest] | ||
| runs-on: ${{ matrix.os }} | ||
| if: github.event.pull_request.draft != true | ||
|
|
||
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - name: Setup Zig | ||
| uses: mlugg/setup-zig@v2 | ||
| with: | ||
| version: 0.15.2 | ||
|
|
||
| - name: Build | ||
| run: zig build | ||
|
|
||
| - name: Run tests | ||
| run: zig build test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| // message_utils.zig - Shared utilities for Bitcoin P2P message handling | ||
| // This module contains shared logic extracted from scout.zig and courier.zig | ||
| // to reduce code duplication and improve maintainability. | ||
|
|
||
| const std = @import("std"); | ||
| const yam = @import("root.zig"); | ||
|
|
||
| /// Maximum payload size for peer messages (4 MB) | ||
| /// This limit prevents memory exhaustion from malicious or misbehaving peers | ||
| pub const MAX_PAYLOAD_SIZE: u32 = 4_000_000; | ||
|
|
||
| /// Options for configuring message reading behavior | ||
| pub const ReadMessageOptions = struct { | ||
| /// Maximum allowed payload size in bytes. If null, no limit is enforced. | ||
| /// courier.zig enforces a 4 MB limit for stricter peer connection management. | ||
| max_payload_size: ?u32 = null, | ||
|
|
||
| /// Whether to verify the message checksum. If true, returns error.InvalidChecksum | ||
| /// when the calculated checksum doesn't match the header checksum. | ||
| verify_checksum: bool = false, | ||
| }; | ||
|
|
||
| /// Result of reading a Bitcoin P2P protocol message | ||
| pub const Message = struct { | ||
| header: yam.MessageHeader, | ||
| payload: []u8, | ||
| }; | ||
|
|
||
| /// Read a Bitcoin P2P protocol message from a stream | ||
| /// | ||
| /// This function reads a 24-byte message header followed by the payload. | ||
| /// It handles partial reads and validates the magic number. | ||
| /// | ||
| /// Caller is responsible for freeing the returned payload using the same allocator. | ||
| /// | ||
| /// Parameters: | ||
| /// - stream: The network stream to read from | ||
| /// - allocator: Memory allocator for payload allocation | ||
| /// - options: Configuration options (payload size limit, checksum verification) | ||
| /// | ||
| /// Returns: Message struct containing header and payload | ||
| /// | ||
| /// Errors: | ||
| /// - ConnectionClosed: Stream closed before full message received | ||
| /// - InvalidMagic: Header magic number doesn't match Bitcoin mainnet (0xD9B4BEF9) | ||
| /// - PayloadTooLarge: Payload exceeds max_payload_size (if specified in options) | ||
| /// - InvalidChecksum: Checksum verification failed (if enabled in options) | ||
| pub fn readMessage( | ||
| stream: std.net.Stream, | ||
| allocator: std.mem.Allocator, | ||
| options: ReadMessageOptions, | ||
| ) !Message { | ||
| // Read the 24-byte message header | ||
| var header_buffer: [24]u8 align(4) = undefined; | ||
| var total_read: usize = 0; | ||
| while (total_read < header_buffer.len) { | ||
| const bytes_read = try stream.read(header_buffer[total_read..]); | ||
| if (bytes_read == 0) return error.ConnectionClosed; | ||
| total_read += bytes_read; | ||
| } | ||
|
|
||
| // Parse header from buffer | ||
| const header_ptr = std.mem.bytesAsValue(yam.MessageHeader, &header_buffer); | ||
| const header = header_ptr.*; | ||
|
|
||
| // Validate magic number (Bitcoin mainnet) | ||
| if (header.magic != 0xD9B4BEF9) return error.InvalidMagic; | ||
|
|
||
| // Read payload if present | ||
| var payload: []u8 = &.{}; | ||
| if (header.length > 0) { | ||
| // Enforce payload size limit if specified (e.g., 4 MB for courier.zig) | ||
| if (options.max_payload_size) |max_size| { | ||
| if (header.length > max_size) return error.PayloadTooLarge; | ||
| } | ||
|
|
||
| // Allocate buffer for payload | ||
| payload = try allocator.alloc(u8, header.length); | ||
| errdefer allocator.free(payload); | ||
|
|
||
| // Read payload data (may require multiple reads) | ||
| total_read = 0; | ||
| while (total_read < header.length) { | ||
| const bytes_read = try stream.read(payload[total_read..]); | ||
| if (bytes_read == 0) { | ||
| return error.ConnectionClosed; | ||
| } | ||
| total_read += bytes_read; | ||
| } | ||
|
|
||
| // Verify checksum if requested (used by courier.zig for individual peer connections) | ||
| if (options.verify_checksum) { | ||
| const calculated_checksum = yam.calculateChecksum(payload); | ||
| if (calculated_checksum != header.checksum) { | ||
| return error.InvalidChecksum; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return .{ .header = header, .payload = payload }; | ||
| } | ||
|
|
||
| // ============================================================================ | ||
| // Tests | ||
| // ============================================================================ | ||
|
|
||
| test "MAX_PAYLOAD_SIZE constant value" { | ||
| try std.testing.expectEqual(@as(u32, 4_000_000), MAX_PAYLOAD_SIZE); | ||
| } | ||
|
|
||
| test "ReadMessageOptions default values" { | ||
| const opts = ReadMessageOptions{}; | ||
| try std.testing.expectEqual(@as(?u32, null), opts.max_payload_size); | ||
| try std.testing.expectEqual(false, opts.verify_checksum); | ||
| } | ||
|
|
||
| test "ReadMessageOptions with custom values" { | ||
| const opts = ReadMessageOptions{ | ||
| .max_payload_size = MAX_PAYLOAD_SIZE, | ||
| .verify_checksum = true, | ||
| }; | ||
| try std.testing.expectEqual(@as(?u32, 4_000_000), opts.max_payload_size); | ||
| try std.testing.expectEqual(true, opts.verify_checksum); | ||
| } | ||
|
|
||
| test "Message struct basic usage" { | ||
| const allocator = std.testing.allocator; | ||
|
|
||
| const header = yam.MessageHeader.new("test", 0, 0); | ||
| const payload = try allocator.alloc(u8, 0); | ||
| defer allocator.free(payload); | ||
|
|
||
| const message = Message{ | ||
| .header = header, | ||
| .payload = payload, | ||
| }; | ||
|
|
||
| try std.testing.expectEqual(@as(u32, 0xD9B4BEF9), message.header.magic); | ||
| try std.testing.expectEqual(@as(usize, 0), message.payload.len); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
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.
@copilot we shouldn't be replacing 1 simple call with this duplicated new block in multiple places!
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.
Implemented
readMessageCheckedhelper method in theCourierstruct. All 3 call sites now use the simple one-liner pattern. (commit 8732e61)