Skip to content

Instantly share code, notes, and snippets.

@jadeallenx
Last active December 21, 2015 08:19
Show Gist options
  • Save jadeallenx/6277777 to your computer and use it in GitHub Desktop.
Save jadeallenx/6277777 to your computer and use it in GitHub Desktop.
22> A1 = hashtree:compute(hashtree:generate(hashtree:test()), []). 
[<<229,160,31,238,20,224,237,92,72,113,79,34,24,15,37,173,
   131,101,181,63,151,121,247,157,196,163,215,233,...>>,
 <<191,254,11,52,219,161,107,198,250,193,124,8,186,197,93,
   103,108,222,213,164,173,228,31,226,201,146,74,...>>,
 <<63,121,187,123,67,91,5,50,22,81,218,239,211,116,205,
   198,129,220,6,250,166,94,55,78,56,51,...>>]
25> A2 = hashtree:compute(A1, []).
[<<20,237,229,232,233,122,217,55,35,39,114,143,80,153,185,
   86,4,163,149,147,202,195,189,56,163,67,173,118,...>>,
 <<63,121,187,123,67,91,5,50,22,81,218,239,211,116,205,
   198,129,220,6,250,166,94,55,78,56,51,123,...>>]
26> A3 = hashtree:compute(A2, []).
[<<215,31,137,131,173,78,225,112,248,18,159,30,188,221,
   116,64,190,119,152,216,225,200,4,32,191,17,241,236,...>>]
40> hd(A3) == hashtree:make_tree(hashtree:generate(hashtree:test())).
3: [<<229,160,31,238,20,224,237,92,72,113,79,34,24,15,37,173,131,101,181,63,
      151,121,247,157,196,163,215,233,57,99,249,74>>,
    <<191,254,11,52,219,161,107,198,250,193,124,8,186,197,93,103,108,222,213,
      164,173,228,31,226,201,146,74,93,222,143,62,91>>,
    <<63,121,187,123,67,91,5,50,22,81,218,239,211,116,205,198,129,220,6,250,
      166,94,55,78,56,51,123,136,202,4,109,234>>]
2: [<<20,237,229,232,233,122,217,55,35,39,114,143,80,153,185,86,4,163,149,147,
      202,195,189,56,163,67,173,118,32,82,19,231>>,
    <<63,121,187,123,67,91,5,50,22,81,218,239,211,116,205,198,129,220,6,250,
      166,94,55,78,56,51,123,136,202,4,109,234>>]
1: [<<215,31,137,131,173,78,225,112,248,18,159,30,188,221,116,64,190,119,152,
      216,225,200,4,32,191,17,241,236,237,97,13,186>>]
true
%% naive hashtree toy
-module(hashtree).
-export([test/0, start/0, generate/1, make_tree/1]).
start() ->
crypto:start().
test() ->
["a", "b", "c", "d", "e"].
generate(L) when is_list(L) ->
[crypto:hash(sha256, Y) || Y <- L].
make_tree([L]) -> L;
make_tree(L) when length(L) > 1 ->
Acc = compute(L, []),
make_tree(Acc).
compute([], Acc) -> lists:reverse(Acc);
compute([ H1, H2 | T], Acc) ->
compute(T, [ hash(H1, H2) | Acc ]);
compute([ H1 | T ], Acc) ->
compute(T, [ H1 | Acc]).
hash(C1, C2) when is_binary(C1) andalso is_binary(C2) ->
crypto:hash(sha256, <<C1/binary, C2/binary>>).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment