How to resolve the algorithm SHA-256 Merkle tree step by step in the Raku programming language
How to resolve the algorithm SHA-256 Merkle tree step by step in the Raku programming language
Table of Contents
Problem Statement
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm SHA-256 Merkle tree step by step in the Raku programming language
Source code in the raku programming language
use Digest::SHA256::Native;
unit sub MAIN(Int :b(:$block-size) = 1024 × 1024, *@args);
my $in = @args ?? IO::CatHandle.new(@args) !! $*IN;
my @blocks = do while my $block = $in.read: $block-size { sha256 $block };
while @blocks > 1 {
@blocks = @blocks.batch(2).map: { $_ > 1 ?? sha256([~] $_) !! .[0] }
}
say @blocks[0]».fmt('%02x').join;
You may also check:How to resolve the algorithm Circles of given radius through two points step by step in the F# programming language
You may also check:How to resolve the algorithm Write entire file step by step in the Go programming language
You may also check:How to resolve the algorithm ABC problem step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Currying step by step in the Prolog programming language
You may also check:How to resolve the algorithm Cantor set step by step in the Arturo programming language