Skip to content

feat: util for calculating multihash from byte stream#5824

Merged
LesnyRumcajs merged 5 commits intomainfrom
hm/digest_byte_stream
Jul 10, 2025
Merged

feat: util for calculating multihash from byte stream#5824
LesnyRumcajs merged 5 commits intomainfrom
hm/digest_byte_stream

Conversation

@hanabi1224
Copy link
Contributor

@hanabi1224 hanabi1224 commented Jul 9, 2025

Summary of changes

Part of #5810

Changes introduced in this pull request:

  • add digest_byte_stream for calculating multihash and CID of a large byte stream, e.g. F3 snapshot
  • unit test

Reference issue to close (if applicable)

Closes

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Summary by CodeRabbit

  • New Features

    • Added the ability to hash data directly from input streams, allowing users to compute multihashes from large or streamed data sources.
  • Tests

    • Introduced tests to ensure consistent hashing results between stream-based and buffer-based methods.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

A new method, digest_byte_stream, was added to the MultihashCode enum in src/utils/multihash.rs, enabling hashing of data from any std::io::Read stream. The method reads data in 1024-byte chunks and updates the hash incrementally. Corresponding tests verify that streaming and slice-based hashing produce identical results and handle unsupported variants properly.

Changes

File(s) Change Summary
src/utils/multihash.rs Added digest_byte_stream method to MultihashCode; imported Hasher trait; added tests comparing streaming and slice hashing, including error handling for unsupported variants

Poem

A stream of bytes, a hash anew,
With chunks of data passing through.
Now streams can join the hashing game,
And tests ensure results the same.
A rabbit hops with code delight—
New streams to hash, oh what a sight!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)
Updating crates.io index

warning: failed to write cache, path: /usr/local/registry/index/index.crates.io-1949cf8c6b5b557f/.cache/an/yh/anyhow, error: Permission denied (os error 13)
Downloading crates ...
Downloaded asn1-rs-impl v0.2.0
error: failed to create directory /usr/local/registry/cache/index.crates.io-1949cf8c6b5b557f

Caused by:
Permission denied (os error 13)


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between caeeb75 and 15bbe52.

📒 Files selected for processing (1)
  • src/utils/multihash.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/multihash.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Build MacOS
  • GitHub Check: cargo-publish-dry-run
  • GitHub Check: Build Ubuntu
  • GitHub Check: Build forest binaries on Linux AMD64
  • GitHub Check: All lint checks
  • GitHub Check: tests
  • GitHub Check: tests-release
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@hanabi1224 hanabi1224 marked this pull request as ready for review July 9, 2025 12:52
@hanabi1224 hanabi1224 requested a review from a team as a code owner July 9, 2025 12:52
@hanabi1224 hanabi1224 requested review from LesnyRumcajs and akaladarshi and removed request for a team July 9, 2025 12:52
@hanabi1224 hanabi1224 force-pushed the hm/digest_byte_stream branch from 53ca3b0 to d359939 Compare July 9, 2025 12:54
Ok(hasher.finalize())
}

Ok(match self {
Copy link
Member

Choose a reason for hiding this comment

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

nit: do you think it's a good opportunity for a macro to avoid code duplication?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think a macro would significantly reduce the LoC, but it would hurt readability. What do you think?

Copy link
Member

Choose a reason for hiding this comment

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

No strong position here, I don't expect this code to be updated with many new algorithms anytime soon in the future. We can leave it as is.

self.wrap(hash(&mut hasher, bytes)?)?
}
_ => {
unimplemented!("{self:?}")
Copy link
Member

Choose a reason for hiding this comment

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

That's a bit scary - we shouldn't crash the entire Forest on a bad reader.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

changed to anyhow::bail

Copy link
Member

Choose a reason for hiding this comment

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

let's add a test case for it for completeness?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done.

fn test_digest_byte_stream() {
use MultihashCode::*;

let mut bytes = vec![0; 10000];
Copy link
Member

Choose a reason for hiding this comment

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

if we're doing a bit of a fuzzy tests, perhaps it would make sense to randomize the input size as well.

Copy link
Member

Choose a reason for hiding this comment

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

Or just manually check some edge conditions; input size of zero, 1, 1024. Also, there's an uncovered path with an unknown hashing algorithm.

Copy link
Contributor Author

@hanabi1224 hanabi1224 Jul 10, 2025

Choose a reason for hiding this comment

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

IdentityHasher is for testing and does not work for input > 64 bytes

/// Identity hasher with a maximum size.
///
/// # Panics
///
/// Panics if the input is bigger than the maximum size.
/// Ported from <https://github.com/multiformats/rust-multihash/pull/289>

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added 0, 1, 1024

Comment on lines +86 to +96
let mut buf = [0; 1024];
loop {
let n = bytes.read(&mut buf)?;
if n == 0 {
break;
}
if let Some(b) = buf.get(0..n) {
hasher.update(b);
}
}
Ok(hasher.finalize())
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
let mut buf = [0; 1024];
loop {
let n = bytes.read(&mut buf)?;
if n == 0 {
break;
}
if let Some(b) = buf.get(0..n) {
hasher.update(b);
}
}
Ok(hasher.finalize())
while let Some(n) = bytes.read(&mut buf).ok() {
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hasher.finalize())

nit: some code golf if you want

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think the io::Error from .read should be escalated here.
Then I get

warning: irrefutable `while let` pattern
  --> src/utils/multihash.rs:96:19
   |
96 |             while let n = bytes.read(&mut buf)? {
   |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this pattern will always match, so the loop will never exit
   = help: consider instead using a `loop { ... }` with a `let` inside it
   = note: `#[warn(irrefutable_let_patterns)]` on by default
...
error: slicing may panic
   --> src/utils/multihash.rs:100:32
    |
100 |                 hasher.update(&buf[..n]);
    |                                ^^^^^^^^
    |
    = help: consider using `.get(..n)`or `.get_mut(..n)` instead
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#indexing_slicing

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It could be a while loop like below but I'm not sure if it's better than a loop loop, what do you think?

let mut n = 0;
            while {
                n = bytes.read(&mut buf)?;
                n > 0
            } {
                if let Some(b) = buf.get(0..n) {
                    hasher.update(b);
                }
            }

Copy link
Member

Choose a reason for hiding this comment

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

Let's leave the original version, then.

@LesnyRumcajs LesnyRumcajs added this pull request to the merge queue Jul 10, 2025
Merged via the queue into main with commit 60668d9 Jul 10, 2025
37 checks passed
@LesnyRumcajs LesnyRumcajs deleted the hm/digest_byte_stream branch July 10, 2025 15:07
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