SHA-256 Merkle tree: Difference between revisions

m
(add task to aarch64 assembly raspberry pi)
m (→‎{{header|Wren}}: Minor tidy)
 
(2 intermediate revisions by 2 users not shown)
Line 7:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program merkleRoot64.s */
Line 695:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
<pre>
Start hash number : 22
Line 702:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program merkleRoot.s */
Line 1,313:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
Start hash number : 22
Line 1,320:
=={{header|C}}==
{{libheader|GLib}}
<langsyntaxhighlight lang="c">#include <glib.h>
#include <stdlib.h>
#include <stdio.h>
Line 1,391:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 1,400:
=={{header|C++}}==
{{libheader|OpenSSL}}
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <fstream>
#include <iomanip>
Line 1,499:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 1,510:
{{libheader| DCPsha256}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program SHA256_Merkle_tree;
 
Line 1,606:
writeln(Merkle_tree('title.png'));
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>A4F902CF9D51FE51EDA156A6792E1445DFF65EDF3A217A1F3334CC9CF1495C2C</pre>
Line 1,612:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-08-14}}
<langsyntaxhighlight lang="factor">USING: checksums checksums.sha fry grouping io
io.encodings.binary io.files kernel make math math.parser
namespaces sequences ;
Line 1,638:
bytes>hex-string ;
 
"title.png" 1024 merkle-hash print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,645:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,696:
fmt.Printf("%x", hashes[0])
fmt.Println()
}</langsyntaxhighlight>
 
{{out}}
<pre>
a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c
</langpre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">{-# LANGUAGE BangPatterns, LambdaCase #-}
 
import Control.Monad (mfilter)
import Crypto.Hash.SHA256 (hash)
import qualified Data.ByteString as B
import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder)
import Data.Functor ((<&>))
import Data.Maybe (listToMaybe)
import Data.Strict.Tuple (Pair(..))
import qualified Data.Strict.Tuple as T
import System.Environment (getArgs)
import System.IO (Handle, stdin, stdout)
import System.IO.Streams (InputStream)
import qualified System.IO.Streams as S
import Text.Read (readMaybe)
 
type Node a = Pair Int a
type LevelPred = Int -> Int -> Bool
type Combine a = a -> a -> a
 
-- From a stream of nodes construct the root of a tree from the bottom up. For
-- each level of the tree pairs of nodes are combined to form a parent node one
-- level higher. Use a stack to store nodes waiting to be combined with another
-- node on their level. (An exception to this is at the end of processing,
-- where all the nodes on the stack can be combined.)
build :: Combine a -> [Node a] -> InputStream (Node a) -> IO (Maybe (Node a))
build combine !stack is = S.read is >>= \case
Nothing -> return $ listToMaybe $ reduce always combine stack
Just h -> build combine (reduce (==) combine (h:stack)) is
 
-- Given a predicate, combining function and a stack, then as long as the
-- predicate is true, repeatedly replace the two top values on the stack with
-- their combined values.
reduce :: LevelPred -> Combine a -> [Node a] -> [Node a]
reduce prd combine (x@(i :!: _):y@(j :!: _):zs)
| prd i j = reduce prd combine (nodeLift combine y x : zs)
reduce _ _ zs = zs
 
-- Apply a combining function to the values in two nodes while calculating the
-- appropriate level for the new node.
nodeLift :: Combine a -> Node a -> Node a -> Node a
nodeLift f (i :!: x) (j :!: y) = max i j + 1 :!: f x y
 
always :: a -> b -> Bool
always _ _ = True
 
-- Build a SHA256-based Merkle tree using bytes read from a handle, and hashing
-- the data using the given chunk size.
merkleTreeSha256 :: Int -> Handle -> IO (Maybe B.ByteString)
merkleTreeSha256 sz h = mkHash <&> fmap T.snd
where mkHash = S.makeInputStream getBuf >>=
S.map (\bs -> 0 :!: hash bs) >>=
build (\x y -> hash (x `B.append` y)) []
getBuf = B.hGet h sz <&> (mfilter (/= B.empty) . Just)
 
-- Print a ByteString in hex.
printByteStringHex :: B.ByteString -> IO ()
printByteStringHex = hPutBuilder stdout . (<> char7 '\n') . byteStringHex
 
main :: IO ()
main = getArgs <&> map readMaybe >>= \case
[Just sz] -> merkleTreeSha256 sz stdin >>= \case
Nothing -> putStrLn "No input to hash"
Just h -> printByteStringHex h
_ -> putStrLn "Argument usage: chunk-size"</syntaxhighlight>
 
{{out}}
Line 1,704 ⟶ 1,776:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.*;
import java.security.*;
import java.util.*;
Line 1,761 ⟶ 1,833:
return digests.get(0);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,769 ⟶ 1,841:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using SHA
 
function merkletree(filename="title.png", blocksize=1024)
Line 1,784 ⟶ 1,856:
 
println(merkletree())
</langsyntaxhighlight>{{out}}
<pre>a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">data=Import["https://rosettacode.org/mw/title.png","Byte"];
parts=Hash[ByteArray[#],"SHA256","ByteArray"]&/@Partition[data,UpTo[1024]];
parts=NestWhile[If[Length[#]==2,Hash[Join@@#,"SHA256","ByteArray"],First[#]]&/@Partition[#,UpTo[2]]&,parts,Length[#]>1&];
StringJoin[IntegerString[Normal[First[parts]],16]]</langsyntaxhighlight>
{{out}}
<pre>a4f92cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</pre>
Line 1,798 ⟶ 1,870:
{{libheader|nimcrypto}}
To compute the digests of file blocks, we use the procedure “digest” which accepts the address of a byte array and a byte count. To compute the digests of pairs of digests, we use instead a SHA256 context and the procedures “update” and “finish”, which avoids a copy in an intermediate buffer.
<syntaxhighlight lang="nim">
<lang Nim>
import nimcrypto
 
Line 1,827 ⟶ 1,899:
hashes= newHashes
 
echo hashes[0]</langsyntaxhighlight>
 
{{out}}
Line 1,835 ⟶ 1,907:
==={{header|Free Pascal}}===
minimal modified [http://rosettacode.org/wiki/SHA-256_Merkle_tree#Delphi Delphi] version
<langsyntaxhighlight lang="pascal">
program SHA256_Merkle_tree;
{$IFDEF WINDOWS}
Line 1,949 ⟶ 2,021:
readln;
{$ENDIF}
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,956 ⟶ 2,028:
=={{header|Perl}}==
{{Trans|Raku}}
<langsyntaxhighlight lang="perl"># 20210222 Perl programming solution
 
use strict;
Line 1,976 ⟶ 2,048:
}
 
print unpack ( 'H*', $blocks[0] ) , "\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 1,984 ⟶ 2,056:
=={{header|Phix}}==
{{libheader|Phix/libcurl}}
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,029 ⟶ 2,101:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">asHex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">merkle</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"title.png"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"https://rosettacode.org/mw/title.png"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1024</span><span style="color: #0000FF;">)))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,038 ⟶ 2,110:
This version attempts to combine blocks as soon as possible to minimize the memory footprint.
 
<langsyntaxhighlight Pythonlang="python">#!/usr/bin/env python
# compute the root label for a SHA256 Merkle tree built on blocks of a given
# size (default 1MB) taken from the given file(s)
Line 2,080 ⟶ 2,152:
 
argh.dispatch_command(main)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,088 ⟶ 2,160:
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>use Digest::SHA256::Native;
 
unit sub MAIN(Int :b(:$block-size) = 1024 × 1024, *@args);
Line 2,100 ⟶ 2,172:
}
 
say @blocks[0]».fmt('%02x').join;</langsyntaxhighlight>
 
{{Out}}
Line 2,107 ⟶ 2,179:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate crypto;
 
use crypto::digest::Digest;
Line 2,169 ⟶ 2,241:
Err(error) => eprintln!("I/O error: {}", error),
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,181 ⟶ 2,253:
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./crypto" for Sha256, Bytes
import "./seq" for Lst
import "./str" for Str
import "./fmt" for Conv
var bytes = File.read("title.png").bytes.toList
Line 2,215 ⟶ 2,287:
hashes = hashes2
}
System.print(Bytes.toHexString(hashes[0]))</langsyntaxhighlight>
 
{{out}}
9,482

edits