├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── eqc └── merkerl_eqc.erl ├── rebar.config ├── rebar.config.script ├── rebar.lock ├── rebar3 ├── src ├── merkerl.app.src ├── merkerl.erl └── skewed.erl └── test └── merkerl_test.erl /.gitignore: -------------------------------------------------------------------------------- 1 | *.beam 2 | .rebar3 3 | *~ 4 | *.orig 5 | .*.swp 6 | _build 7 | ebin/ 8 | .local_dialyzer_plt 9 | erln8.config 10 | .eqc/ 11 | /.eqc-info 12 | /coverage/ 13 | /current_counterexample.eqc 14 | log/ 15 | doc/ 16 | *.dump 17 | *.crashdump 18 | GPATH 19 | GRTAGS 20 | GTAGS 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | 4 | language: erlang 5 | 6 | otp_release: 7 | - 20.1 8 | 9 | cache: 10 | directories: 11 | - $HOME/.cache/rebar3 12 | 13 | script: ./rebar3 as test do eunit, coveralls send, dialyzer 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: compile cover test typecheck xref check doc 2 | REBAR=./rebar3 3 | 4 | compile: 5 | $(REBAR) compile 6 | 7 | clean: 8 | $(REBAR) clean 9 | 10 | cover: test 11 | $(REBAR) cover 12 | 13 | test: compile 14 | $(REBAR) as test do eunit 15 | 16 | typecheck: 17 | $(REBAR) dialyzer 18 | 19 | xref: 20 | $(REBAR) xref 21 | 22 | doc: 23 | $(REBAR) edoc 24 | 25 | check: test typecheck xref 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/helium/merkerl.svg?branch=master)](https://travis-ci.org/helium/merkerl) 2 | [![Coverage Status](https://coveralls.io/repos/github/helium/merkerl/badge.svg?branch=master)](https://coveralls.io/github/helium/merkerl?branch=master) 3 | 4 | 5 | merkerl 6 | -------- 7 | 8 | A library for building and using [Merkle Trees](https://en.wikipedia.org/wiki/Merkle_tree). 9 | 10 | Why yet another Merkle Tree implementation? Mostly because other implementations didn't allow for pluggable hash functions, did not support proof generation or verification, tried to support mutable trees, or some combination of the above. 11 | 12 | 13 | Build 14 | ----- 15 | 16 | ``` 17 | $ make 18 | ``` 19 | 20 | To build documentation: 21 | 22 | ``` 23 | $ make docs 24 | ``` 25 | 26 | 27 | Usage 28 | ----- 29 | 30 | Construct a merkle tree: 31 | 32 | ``` 33 | Values = ["foo", "bar", "baz", "dog", "cat", "bear", "plant"], 34 | Merkle = merkerl:new(Values, fun merkerl:hash_value/1), 35 | ``` 36 | 37 | Generate a proof for a value in a merkle tree: 38 | 39 | ``` 40 | ValueHash = merkerl:hash_value("bar"), 41 | Proof = merkerl:gen_proof(ValueHash, Merkle), 42 | ``` 43 | 44 | Verify a proof for a value in a merkle tree: 45 | 46 | ``` 47 | ok = merkerl:verify_proof(ValueHash, Merkle, Proof), 48 | ``` 49 | 50 | There are other functions for accessing the leaves and values from a 51 | merkle tree. For complete documentation, see the generated docs. 52 | -------------------------------------------------------------------------------- /eqc/merkerl_eqc.erl: -------------------------------------------------------------------------------- 1 | -module(merkerl_eqc). 2 | 3 | %% include some quickcheck headers 4 | -include_lib("eqc/include/eqc.hrl"). 5 | 6 | -export([prop_merkerl/0]). 7 | 8 | prop_merkerl() -> 9 | %% generate 2 disjoint lists of binaries 10 | ?FORALL({Values, NonValues}, ?SUCHTHAT({X1, X2}, {list(binary()), list(binary())}, sets:is_disjoint(sets:from_list(X1), sets:from_list(X2))), 11 | begin 12 | try 13 | UniqueValues = Values -- (Values -- lists:usort(Values)), 14 | Tree = merkerl:new(Values, fun merkerl:hash_value/1), 15 | RootHash = merkerl:root_hash(Tree), 16 | NonTree = merkerl:new(NonValues, fun merkerl:hash_value/1), 17 | ValuesAndProofs = [ {V, merkerl:gen_proof(merkerl:hash_value(V), Tree)} || V <- Values ], 18 | NoEdgeHashes = lists:all(fun({V, P}) -> 19 | ProofHashes = merkerl:proof_hashes(P), 20 | not lists:member(merkerl:hash_value(V), ProofHashes) andalso 21 | not lists:member(RootHash, ProofHashes) 22 | end, ValuesAndProofs), 23 | InvalidProofs = [ {V, P} || {V, P} <- ValuesAndProofs, element(1, P) == error ], 24 | Verified = lists:all(fun({V, P}) -> merkerl:verify_proof(merkerl:hash_value(V), Tree, P) == ok end, ValuesAndProofs), 25 | NoneVerified = lists:all(fun({V, P}) -> merkerl:verify_proof(merkerl:hash_value(V), NonTree, P) /= ok end, ValuesAndProofs), 26 | NonValuesAndProofs = [ {V, merkerl:gen_proof(merkerl:hash_value(V), Tree)} || V <- NonValues ], 27 | InvalidVerified = lists:all(fun({V, P}) -> merkerl:verify_proof(merkerl:hash_value(V), Tree, P) /= ok end, NonValuesAndProofs), 28 | InvalidNonProofs = [ {V, P} || {V, P} <- NonValuesAndProofs, element(1, P) == error ], 29 | UniqueLength = length(lists:usort(Values)), 30 | ExpectedHeight = case UniqueLength of 31 | 0 -> 0; 32 | N -> 33 | ceil(math:log2(N) + 1) 34 | end, 35 | ?WHENFAIL(begin 36 | io:format(user, "Values: ~p\n", [Values]), 37 | io:format(user, "NonValues: ~p\n", [NonValues]), 38 | io:format(user, "Tree: ~p\n", [Tree]) 39 | end, 40 | conjunction([{count, eqc:equals(merkerl:count(Tree), length(lists:usort(Values)))}, 41 | {height, eqc:equals(merkerl:height(Tree), ExpectedHeight)}, 42 | {ordering, eqc:equals(merkerl:values(Tree), UniqueValues)}, 43 | {no_proofs_invalid, eqc:equals(InvalidProofs, [])}, 44 | {no_edge_hashes, NoEdgeHashes}, 45 | {all_proofs_verified, Verified}, 46 | {no_non_proofs_verified, NoneVerified}, 47 | {no_invalid_proofs_verified, InvalidVerified}, 48 | {invalid_keys_have_no_proofs, eqc:equals(length(NonValues), length(InvalidNonProofs))} 49 | ])) 50 | catch 51 | _:Err -> 52 | io:format(user, "\nException: ~p\n", [Err]), 53 | io:format(user, "Stacktrace: ~p\n", [erlang:get_stacktrace()]), 54 | io:format(user, "Values: ~p\n", [Values]), 55 | io:format(user, "NonValues: ~p\n", [NonValues]), 56 | false 57 | end 58 | end). 59 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info, warnings_as_errors]}. 2 | {cover_enabled, true}. 3 | {cover_export_enabled, true}. 4 | 5 | {xref_checks,[undefined_function_calls,undefined_functions,locals_not_used, 6 | deprecated_function_calls, deprecated_functions]}. 7 | -------------------------------------------------------------------------------- /rebar.config.script: -------------------------------------------------------------------------------- 1 | case os:getenv("TRAVIS") of 2 | "true" -> 3 | JobId = os:getenv("TRAVIS_JOB_ID"), 4 | Plugins = proplists:get_value(plugins, CONFIG, []), 5 | [{coveralls_coverdata, "_build/test/cover/eunit.coverdata"}, 6 | {coveralls_service_name, "travis-ci"}, 7 | {coveralls_service_job_id, JobId} | 8 | lists:keystore(plugins, 1, CONFIG, {plugins, [coveralls|Plugins]})]; 9 | _ -> 10 | CONFIG 11 | end. 12 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | []. 2 | -------------------------------------------------------------------------------- /rebar3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helium/merkerl/26ddcaf7f3c2c76eebf6f9258822f923ce69cb75/rebar3 -------------------------------------------------------------------------------- /src/merkerl.app.src: -------------------------------------------------------------------------------- 1 | %% Copyright 2017 Marc Nijdam 2 | 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | 15 | {application, merkerl, 16 | [{description, "An Erlang implementation of a merkle tree"}, 17 | {vsn, "git"}, 18 | {registered, []}, 19 | {applications, [kernel, stdlib]}, 20 | {env,[]}, 21 | 22 | %% hex.pm packaging: 23 | {licenses, ["Apache 2.0"]}, 24 | {links, [{"Github", "https://github.com/helium/merkerl"}]} 25 | ]}. 26 | -------------------------------------------------------------------------------- /src/merkerl.erl: -------------------------------------------------------------------------------- 1 | %% @doc A module with a simple merkle tree implementation as described 2 | %% in https://en.wikipedia.org/wiki/Merkle_tree implementation. This 3 | %% module implements a immutable merkle tree. Once all the values are 4 | %% available, it can construct a balanced tree for those values which 5 | %% can then be used to access the leaf values, generate merkle proofs, 6 | %% and verify generated proofs. 7 | 8 | -module(merkerl). 9 | 10 | -record(merkle, { 11 | root :: tree(), 12 | count = 0 :: non_neg_integer() 13 | }). 14 | 15 | -record(leaf, { 16 | hash :: hash(), 17 | value :: any() 18 | }). 19 | 20 | -record(empty, { 21 | hash = <<0:256>> :: hash() 22 | }). 23 | 24 | -record(node, { 25 | hash :: hash(), 26 | height = 0 :: non_neg_integer(), 27 | left :: tree(), 28 | right :: tree() 29 | }). 30 | 31 | -type hash() :: binary(). 32 | -opaque merkle() :: #merkle{}. 33 | -opaque proof() :: [{left|right, hash()}]. 34 | -type tree() :: #leaf{} | #empty{} | #node{}. 35 | 36 | -export_type([merkle/0, proof/0, hash/0]). 37 | -export([new/2, root_hash/1, height/1, count/1, values/1, leaves/1, fold/3, 38 | gen_proof/2, verify_proof/3, proof_hashes/1, hash_value/1]). 39 | 40 | 41 | %% @doc Construct a merkle tree given a list of values and a hash 42 | %% function. The hash function is used to calculate the hash of the 43 | %% leaf value. A simple one hash_value/1 is provided in this 44 | %% module. The resulting merkle tree retains the order of the values 45 | %% but duplicate values (as determined by the result of the hash 46 | %% function) are skipped, so only the first found element counts. 47 | -spec new([term()], fun((term()) -> hash())) -> merkle(). 48 | new(Values, HashFun) -> 49 | {_, UniqueLeaves} = lists:foldl(fun(Value, {SeenValues, Acc}) -> 50 | case sets:is_element(Value, SeenValues) of 51 | true -> 52 | {SeenValues, Acc}; 53 | false -> 54 | L = to_leaf(Value, HashFun), 55 | {sets:add_element(Value, SeenValues), [L | Acc]} 56 | end 57 | end, {sets:new(), []}, lists:reverse(Values)), 58 | #merkle{root=build_tree(UniqueLeaves), count=length(UniqueLeaves)}. 59 | 60 | -spec build_tree([tree()]) -> tree(). 61 | build_tree([]) -> 62 | #empty{}; 63 | build_tree([Root]) -> 64 | Root; 65 | build_tree(List) -> 66 | Level = lists:reverse(combine(List, [])), 67 | build_tree(Level). 68 | 69 | combine([], Acc) -> 70 | Acc; 71 | combine([X], Acc) -> 72 | [X | Acc]; 73 | combine([X, Y |T], Acc) -> 74 | combine(T, [to_tree(X, Y) | Acc]). 75 | 76 | -spec mk_node(tree(), tree(), hash(), hash(), non_neg_integer()) -> tree(). 77 | mk_node(L, R, LHash, RHash, Height) -> 78 | Hash = crypto:hash(sha256, <>), 79 | #node{left=L, right=R, height=Height+1, hash=Hash}. 80 | 81 | -spec to_leaf(term(), fun((term()) -> hash())) -> tree(). 82 | to_leaf(Value, HashFun) -> 83 | #leaf{value=Value, hash=HashFun(Value)}. 84 | 85 | -spec to_tree(tree(), tree()) -> tree(). 86 | to_tree(L=#leaf{hash=LHash}, R=#leaf{hash=RHash}) -> 87 | mk_node(L, R, LHash, RHash, 1); 88 | to_tree(L=#node{hash=LHash, height=LHeight}, R=#leaf{hash=RHash}) -> 89 | mk_node(L, R, LHash, RHash, LHeight); 90 | to_tree(L=#node{hash=LHash, height=LHeight}, R=#node{hash=RHash, height=RHeight}) -> 91 | mk_node(L, R, LHash, RHash, max(LHeight, RHeight)). 92 | 93 | %% @doc Gets the root hash of the given merkle tree. This is a fast 94 | %% operation since the hash was calculated on construction of the 95 | %% tree. 96 | -spec root_hash(merkle()) -> hash(). 97 | root_hash(#merkle{root=Tree}) -> 98 | tree_hash(Tree). 99 | 100 | %% @doc Get the height of the given merkle tree. This is a fast 101 | %% operation since the hash was calculated on construction of the 102 | %% tree. 103 | -spec height(merkle()) -> non_neg_integer(). 104 | height(#merkle{root=Tree}) -> 105 | tree_height(Tree). 106 | 107 | %% @doc get the number of leaves int he merkle tree. 108 | -spec count(merkle()) -> non_neg_integer(). 109 | count(#merkle{count=Count}) -> 110 | Count. 111 | 112 | %% @doc Get the values of the merkle tree. This returns the values in 113 | %% the same order as the list that was passed in on merkle 114 | %% construction. 115 | -spec values(merkle()) -> [term()]. 116 | values(M=#merkle{}) -> 117 | fold(fun({_Hash, Value}, Acc) -> [Value | Acc] end, [], M). 118 | 119 | %% @doc Get a list of values and their hashes from the tree. The 120 | %% resulting list retains the same order as the list that was passed 121 | %% in on merkle construction. 122 | -spec leaves(merkle()) -> [{hash(), term()}]. 123 | leaves(M=#merkle{}) -> 124 | fold(fun(Leaf, Acc) -> [Leaf | Acc] end, [], M). 125 | 126 | %% @doc Fold over the leaves of the merkle tree. The given function 127 | %% will take the a `{hash, value}' tuple, and a given accumulator to 128 | %% fold over the merkle tree with and returns the resulting 129 | %% accumulator. 130 | -spec fold(FoldFun, Acc, tree() | merkle()) -> Acc when 131 | FoldFun :: fun(({hash(), term()}, Acc) -> Acc), 132 | Acc :: any(). 133 | fold(Fun, Acc, #merkle{root=Tree}) -> 134 | fold(Fun, Acc, Tree); 135 | fold(Fun, Acc, #node{left=L, right=R}) -> 136 | RAcc = fold(Fun, Acc, R), 137 | fold(Fun, RAcc, L); 138 | fold(Fun, Acc, #leaf{hash=Hash, value=Value}) -> 139 | Fun({Hash, Value}, Acc); 140 | fold(_Fun, Acc, #empty{}) -> 141 | Acc. 142 | 143 | -spec tree_hash(tree()) -> hash(). 144 | tree_hash(#node{hash=Hash}) -> 145 | Hash; 146 | tree_hash(#leaf{hash=Hash}) -> 147 | Hash; 148 | tree_hash(#empty{hash=Hash}) -> 149 | Hash. 150 | 151 | -spec tree_height(tree()) -> non_neg_integer(). 152 | tree_height(#node{height=Height}) -> 153 | Height; 154 | tree_height(#leaf{}) -> 155 | 1; 156 | tree_height(#empty{}) -> 157 | 0. 158 | 159 | %% @doc Generate a merkle proof for a given hash in the tree. Note 160 | %% that the resulting proof does not include the value hash itself, 161 | %% which saves space in the proof. 162 | -spec gen_proof(any(), merkle()) -> proof() | not_found. 163 | gen_proof(ValueHash, #merkle{root=Tree}) -> 164 | gen_proof(ValueHash, Tree, []). 165 | 166 | -spec gen_proof(hash(), tree() | merkle(), list()) -> proof() | {error, Reason} when 167 | Reason :: not_found 168 | | no_possible_proof. 169 | gen_proof(_ValueHash, #empty{}, _Acc) -> 170 | {error, no_possible_proof}; 171 | gen_proof(ValueHash, #leaf{hash=ValueHash}, Acc) -> 172 | Acc; 173 | gen_proof(_ValueHash, #leaf{}, _Acc) -> 174 | {error, not_found}; 175 | gen_proof(ValueHash, #node{left=#leaf{hash=ValueHash}, right=R}, Acc) -> 176 | [{left, tree_hash(R)} | Acc]; 177 | gen_proof(ValueHash, #node{left=L, right=#leaf{hash=ValueHash}}, Acc) -> 178 | [{right, tree_hash(L)} | Acc]; 179 | gen_proof(ValueHash, #node{left=L, right=R}, Acc) -> 180 | case gen_proof(ValueHash, L, Acc) of 181 | {error, Reason} -> case gen_proof(ValueHash, R, Acc) of 182 | {error, Reason} -> {error, Reason}; 183 | Proof -> [{right, tree_hash(L)} | Proof] 184 | end; 185 | Proof -> [{left, tree_hash(R)} | Proof] 186 | end. 187 | 188 | %% @doc Verifies that a given hash of a value is in a given merkle 189 | %% tree using the provided proof. 190 | -spec verify_proof(hash(), merkle() | hash(), proof() | {error, any()}) -> ok | {error, Reason} when 191 | Reason :: root_hash_mismatch 192 | | invalid_proof. 193 | verify_proof(_, _, {error, _}) -> 194 | {error, invalid_proof}; 195 | verify_proof(ValueHash, #merkle{root=Tree}, Proof) -> 196 | verify_proof(ValueHash, tree_hash(Tree), Proof); 197 | verify_proof(ValueHash, RootHash, Proof) when is_binary(RootHash) -> 198 | ProofHash = verify_proof(ValueHash, Proof), 199 | case ProofHash == RootHash of 200 | true -> ok; 201 | false -> {error, root_hash_mismatch} 202 | end. 203 | 204 | verify_proof(ValueHash, []) -> 205 | ValueHash; 206 | verify_proof(ValueHash, [{left, RHash} | Tail]) -> 207 | LHash = verify_proof(ValueHash, Tail), 208 | hash_value(<>); 209 | verify_proof(ValueHash, [{right, LHash} | Tail]) -> 210 | RHash = verify_proof(ValueHash, Tail), 211 | hash_value(<>). 212 | 213 | %% @doc Get just the hashes from a given proof. 214 | -spec proof_hashes(proof()) -> [hash()]. 215 | proof_hashes(Proof) -> 216 | [element(2, T) || T <- Proof]. 217 | 218 | %% @doc A commonly used hash value for merkle trees. This function 219 | %% will SHA256 hash the given value when it is binary. A convenience 220 | %% form detects non-binary forms and uses term_to_binary/1 to convert 221 | %% other erlang terms to a binary form. It is not recommended to use 222 | %% the non-binary form if the resulting trees or proofs are to be sent 223 | %% over a network. 224 | hash_value(Value) when is_binary(Value) -> 225 | crypto:hash(sha256, Value); 226 | hash_value(Value) -> 227 | hash_value(term_to_binary(Value)). 228 | -------------------------------------------------------------------------------- /src/skewed.erl: -------------------------------------------------------------------------------- 1 | %% @doc A module with a skewed merkle tree implementation as described 2 | %% in https://medium.com/codechain/skewed-merkle-tree-259b984acc0c. 3 | %% This module implements a skewed merkle tree where value can be added/stacked via add/2, 4 | %% the time and memory it takes to create is linearly proportional to the number of values. 5 | 6 | -module(skewed). 7 | 8 | -ifdef(TEST). 9 | -include_lib("eunit/include/eunit.hrl"). 10 | -endif. 11 | 12 | -export([ 13 | new/0, new/1, new/2, 14 | add/2, gen_proof/2, verify_proof/3, 15 | root_hash/1, height/1, count/1, 16 | hash_value/2, 17 | contains/2 18 | ]). 19 | 20 | -record(leaf, { 21 | hash :: hash() 22 | }). 23 | 24 | -record(empty, { 25 | hash = <<0:256>> :: hash() 26 | }). 27 | 28 | -record(node, { 29 | hash :: hash(), 30 | height = 0 :: non_neg_integer(), 31 | left :: #node{} | #empty{}, 32 | right :: leaf() 33 | }). 34 | 35 | -record(skewed, { 36 | root = #empty{} :: tree(), 37 | count = 0 :: non_neg_integer(), 38 | hash_function = fun hash_value/2 :: hash_function() 39 | }). 40 | 41 | -type hash() :: binary(). 42 | -type skewed() :: #skewed{}. 43 | -type leaf() :: #leaf{}. 44 | -type tree() :: #empty{} | #node{}. 45 | 46 | -define(LEAF_PREFIX, 0). 47 | -define(NODE_PREFIX, 1). 48 | 49 | -type hash_function() :: fun((term(), 0 | 1) -> hash()). 50 | 51 | -export_type([skewed/0, hash/0, hash_function/0]). 52 | 53 | %% @doc 54 | %% Create new empty skewed merkle tree. 55 | %% @end 56 | -spec new() -> skewed(). 57 | new() -> 58 | #skewed{}. 59 | 60 | -spec new(hash() | hash_function()) -> skewed(). 61 | new(Hash) when is_binary(Hash) -> 62 | #skewed{root=#empty{hash=Hash}}; 63 | new(HashFunction) when is_function(HashFunction) -> 64 | #skewed{hash_function=HashFunction}. 65 | 66 | -spec new(hash(), hash_function()) -> skewed(). 67 | new(Hash, HashFunction) -> 68 | #skewed{root=#empty{hash=Hash}, hash_function=HashFunction}. 69 | 70 | %% @doc 71 | %% Add/stack new value (leaf) on top and recalculate root hash. 72 | %% @end 73 | -spec add(any(), skewed()) -> skewed(). 74 | add(Value, #skewed{root=Tree, count=Count, hash_function=HashFun}=Skewed) -> 75 | Leaf = to_leaf(Value, HashFun), 76 | Node = to_node(Tree, Leaf, tree_hash(Tree), leaf_hash(Leaf), HashFun, Count), 77 | Skewed#skewed{root=Node, count=Count+1}. 78 | 79 | %% @doc 80 | %% Generate a proof that `Value' appears in `Tree' by returning the list of 81 | %% required sibling hashes and the root hash of the tree. 82 | %% @end 83 | -spec gen_proof(any(), skewed()) -> not_found | [hash(),...]. 84 | gen_proof(_Value, #skewed{count=0}) -> 85 | not_found; 86 | gen_proof(Value, #skewed{root=Tree, hash_function=HashFun}) -> 87 | Hash = HashFun(Value, ?LEAF_PREFIX), 88 | case contains(Tree, Hash, [tree_hash(Tree)]) of 89 | false -> not_found; 90 | Proof -> Proof 91 | end. 92 | 93 | 94 | %% @doc 95 | %% Verify will check that the HashToVerify is correctly in the tree with the provided, 96 | %% in order, lists of hashes (proof) and compare it to the RootHash. 97 | %% @end 98 | -spec verify_proof(hash(), hash_function(), [hash(),...]) -> boolean(). 99 | verify_proof(HashToVerify, _HashFun, [RootHash]) -> 100 | HashToVerify == RootHash; 101 | verify_proof(HashToVerify, HashFun, [FirstHash|Hashes]) -> 102 | RH = lists:last(Hashes), 103 | FirstEmpty = #empty{hash=FirstHash}, 104 | Result = lists:foldl( 105 | fun(RootHash, Acc) when RootHash == RH -> 106 | ?MODULE:root_hash(Acc) == RootHash; 107 | (Hash, #skewed{root=Tree, count=Count}=Acc) -> 108 | Leaf = to_leaf(Hash), 109 | Node = to_node(Tree, Leaf, tree_hash(Tree), leaf_hash(Leaf), HashFun, Count), 110 | Acc#skewed{root=Node, count=Count+1} 111 | end, 112 | #skewed{root=FirstEmpty, count=0}, 113 | [HashToVerify|Hashes] 114 | ), 115 | Result == true. 116 | 117 | %% @doc 118 | %% Gets the root hash of the given skewed tree. This is a fast 119 | %% operation since the hash was calculated on construction of the tree. 120 | %% @end 121 | -spec root_hash(skewed()) -> hash(). 122 | root_hash(#skewed{root=Tree}) -> 123 | tree_hash(Tree). 124 | 125 | %% @doc 126 | %% Get the height of the given skewed tree. This is a fast operation 127 | %% since the height was calculated on construction of the tree. 128 | %% @end 129 | -spec height(skewed()) -> non_neg_integer(). 130 | height(#skewed{root=Tree}) -> 131 | tree_height(Tree). 132 | 133 | %% @doc 134 | %% get the number of leaves int he skewed tree. 135 | %% @end 136 | -spec count(skewed()) -> non_neg_integer(). 137 | count(#skewed{count=Count}) -> 138 | Count. 139 | 140 | %% @doc 141 | %% A commonly used hash value for skewed trees. This function 142 | %% will SHA256 hash the given value when it is binary. A convenience 143 | %% form detects non-binary forms and uses term_to_binary/1 to convert 144 | %% other erlang terms to a binary form. It is not recommended to use 145 | %% the non-binary form if the resulting trees or proofs are to be sent 146 | %% over a network. 147 | %% @end 148 | -spec hash_value(any(), 0 | 1) -> hash(). 149 | hash_value(Value, Prefix) when is_binary(Value) -> 150 | crypto:hash(sha256, <>); 151 | hash_value(Value, Prefix) -> 152 | hash_value(term_to_binary(Value), Prefix). 153 | 154 | %% @doc 155 | %% Check if the skewed tree contains a value. 156 | %% @end 157 | -spec contains(skewed() | tree(), any()) -> boolean(). 158 | contains(#skewed{count=0}, _Value) -> 159 | false; 160 | contains(#skewed{root=Tree}, Value) -> 161 | Hash = hash_value(Value, ?LEAF_PREFIX), 162 | case contains(Tree, Hash, []) of 163 | false -> false; 164 | _ -> true 165 | end. 166 | 167 | %%==================================================================== 168 | %% Internal functions 169 | %%==================================================================== 170 | 171 | -spec contains(tree(), hash(), [hash()]) -> false | [hash(),...]. 172 | contains(#empty{}, _, _Acc) -> 173 | false; 174 | contains(#node{right=#leaf{hash=Hash}, left=Left}, Hash, Acc) -> 175 | [tree_hash(Left)|Acc]; 176 | contains(#node{left=Left, right=#leaf{hash=RightHash}}, Hash, Acc) -> 177 | contains(Left, Hash, [RightHash|Acc]). 178 | 179 | -spec to_leaf(hash()) -> leaf(). 180 | to_leaf(Hash) -> 181 | #leaf{hash=Hash}. 182 | 183 | -spec to_leaf(term(), hash_function()) -> leaf(). 184 | to_leaf(Value, HashFun) -> 185 | #leaf{hash=HashFun(Value, ?LEAF_PREFIX)}. 186 | 187 | -spec to_node(tree(), leaf(), hash(), hash(), hash_function(), non_neg_integer()) -> tree(). 188 | to_node(L, R, LHash, RHash, HashFun, Height) -> 189 | Hash = HashFun(<>, ?NODE_PREFIX), 190 | #node{left=L, right=R, height=Height+1, hash=Hash}. 191 | 192 | -spec leaf_hash(leaf()) -> hash(). 193 | leaf_hash(#leaf{hash=Hash}) -> 194 | Hash. 195 | 196 | -spec tree_hash(tree()) -> hash(). 197 | tree_hash(#node{hash=Hash}) -> 198 | Hash; 199 | tree_hash(#empty{hash=Hash}) -> 200 | Hash. 201 | 202 | -spec tree_height(tree()) -> non_neg_integer(). 203 | tree_height(#node{height=Height}) -> 204 | Height; 205 | tree_height(#empty{}) -> 206 | 0. 207 | 208 | %% ------------------------------------------------------------------ 209 | %% EUNIT Tests 210 | %% ------------------------------------------------------------------ 211 | -ifdef(TEST). 212 | 213 | new_test() -> 214 | Tree = new(<<1,2,3>>), 215 | ?assertEqual(<<1,2,3>>, ?MODULE:root_hash(Tree)), 216 | ?assertEqual(0, ?MODULE:count(Tree)). 217 | 218 | verify_test() -> 219 | HashFun = fun hash_value/2, 220 | Size = 5, 221 | Tree = lists:foldl( 222 | fun(Value, Acc) -> 223 | add(Value, Acc) 224 | end, 225 | new(), 226 | lists:seq(1, Size) 227 | ), 228 | RootHash = ?MODULE:root_hash(Tree), 229 | Value = 3, 230 | %% this is the hash of the node adjacent to the leaf with value 3 (`Value') 231 | Hash2 = <<253,49,101,79,133,255,101,251,21,117,172,62,98,57,87,84,34,25,155,89,71,139,184,212,1,255,127,234,83,163,195,155>>, 232 | ValueHashes = lists:foldr(fun(V, A) -> [HashFun(V, ?LEAF_PREFIX)|A] end, [], lists:seq(Value+1, Size)), 233 | ExpectedProof = [Hash2] ++ ValueHashes ++ [RootHash], 234 | ?assertEqual(ExpectedProof, gen_proof(Value, Tree)), 235 | ?assert(verify_proof(HashFun(Value, ?LEAF_PREFIX), HashFun, ExpectedProof)), 236 | ?assertNot(verify_proof(HashFun(Value, ?LEAF_PREFIX), HashFun, [RootHash])), 237 | ?assert(verify_proof(RootHash, HashFun, [RootHash])), 238 | ok. 239 | 240 | proof_test() -> 241 | HashFun = fun hash_value/2, 242 | ?assertEqual(not_found, gen_proof(lol, new())), 243 | Size = 5, 244 | Tree = lists:foldl( 245 | fun(Value, Acc) -> 246 | add(Value, Acc) 247 | end, 248 | new(HashFun(7, ?LEAF_PREFIX)), 249 | lists:seq(1, Size) 250 | ), 251 | ?assertEqual(not_found, gen_proof(10, Tree)), 252 | ?assertNotEqual(not_found, gen_proof(2, Tree)), 253 | ?assertEqual(not_found, gen_proof(7, Tree)), 254 | ok. 255 | 256 | contains_test() -> 257 | Size = 5, 258 | Tree = lists:foldl( 259 | fun(Value, Acc) -> 260 | add(Value, Acc) 261 | end, 262 | new(), 263 | lists:seq(1, Size) 264 | ), 265 | 266 | ?assertEqual(true, lists:all(fun(I) -> 267 | true == contains(Tree, I) 268 | end, 269 | lists:seq(1, Size))), 270 | 271 | ?assertEqual(true, lists:all(fun(I) -> 272 | false == contains(Tree, I) 273 | end, 274 | lists:seq(-10, 0))), 275 | 276 | %% Check that empty tree contains no value 277 | Tree2 = new(), 278 | ?assertEqual(true, lists:all(fun(I) -> 279 | false == contains(Tree2, I) 280 | end, 281 | lists:seq(-1, 10))), 282 | 283 | ok. 284 | 285 | height_test() -> 286 | Tree0 = new(), 287 | ?assertEqual(0, height(Tree0)), 288 | Tree1 = lists:foldl( 289 | fun(Value, Acc) -> 290 | add(Value, Acc) 291 | end, 292 | new(), 293 | lists:seq(1, 10) 294 | ), 295 | io:format("Tree1: ~p~n", [Tree1]), 296 | ?assertEqual(10, height(Tree1)), 297 | ?assertEqual(0, tree_height(#empty{hash= <<>>})), 298 | ok. 299 | 300 | construct_test() -> 301 | Tree0 = new(crypto:hash(sha256, "yolo")), 302 | ?assertEqual(0, height(Tree0)), 303 | Tree1 = add("hello", Tree0), 304 | ?assertEqual(1, height(Tree1)), 305 | Tree2 = add("namaste", Tree1), 306 | ?assertEqual(2, height(Tree2)), 307 | ok. 308 | 309 | count_test() -> 310 | Tree0 = new(), 311 | ?assertEqual(0, count(Tree0)), 312 | Tree1 = lists:foldl( 313 | fun(Value, Acc) -> 314 | add(Value, Acc) 315 | end, 316 | new(), 317 | lists:seq(1, 10) 318 | ), 319 | ?assertEqual(10, count(Tree1)), 320 | ok. 321 | 322 | -endif. 323 | -------------------------------------------------------------------------------- /test/merkerl_test.erl: -------------------------------------------------------------------------------- 1 | -module(merkerl_test). 2 | 3 | -include_lib("eunit/include/eunit.hrl"). 4 | 5 | basic_test() -> 6 | %% Construct a tree 7 | Values = ["foo", "bar", "baz", "dog", "cat", "bear", "plant"], 8 | M = merkerl:new(Values, fun merkerl:hash_value/1), 9 | %% Verify leaf count and tree height 10 | ?assertEqual(7, merkerl:count(M)), 11 | ?assertEqual(4, merkerl:height(M)), 12 | 13 | %% Verify values 14 | ?assertEqual(Values, merkerl:values(M)), 15 | %% Verify leaves 16 | ?assertEqual(lists:zip(lists:map(fun merkerl:hash_value/1, Values), Values), 17 | merkerl:leaves(M)), 18 | 19 | %% Generate a proof 20 | ValueHash = merkerl:hash_value("bar"), 21 | MP = merkerl:gen_proof(ValueHash, M), 22 | 23 | ?assertEqual(3, length(merkerl:proof_hashes(MP))), 24 | 25 | %% And verify it 26 | ?assertEqual(ok, merkerl:verify_proof(ValueHash, M, MP)), 27 | %% Will error on bad value 28 | BadValueHash = merkerl:hash_value("bah"), 29 | ?assertEqual({error, root_hash_mismatch}, 30 | merkerl:verify_proof(BadValueHash, M, MP)), 31 | 32 | %% Will not generate proof for non-existing value 33 | ?assertEqual({error, not_found}, 34 | merkerl:gen_proof(BadValueHash, M)), 35 | %% or generate a proof based on a previous error condition, 36 | ?assertEqual({error, invalid_proof}, 37 | merkerl:verify_proof(BadValueHash, M, merkerl:gen_proof(BadValueHash, M))), 38 | 39 | ok. 40 | 41 | empty_test() -> 42 | M = merkerl:new([], fun merkerl:hash_value/1), 43 | %% Verify leaf count and tree height 44 | ?assertEqual(0, merkerl:count(M)), 45 | ?assertEqual(0, merkerl:height(M)), 46 | ?assertEqual(<<0:256>>, merkerl:root_hash(M)), 47 | ?assertEqual([], merkerl:values(M)), 48 | ?assertEqual([], merkerl:leaves(M)), 49 | 50 | % Can not generate proofs 51 | ?assertEqual({error, no_possible_proof}, 52 | merkerl:gen_proof(merkerl:hash_value("bar"), M)), 53 | 54 | ok. 55 | 56 | near_empty_test() -> 57 | M = merkerl:new(["foo"], fun merkerl:hash_value/1), 58 | %% Verify leaf count and tree height 59 | ?assertEqual(1, merkerl:count(M)), 60 | ?assertEqual(1, merkerl:height(M)), 61 | 62 | % Can generate proof 63 | ValueHash = merkerl:hash_value("foo"), 64 | MP = merkerl:gen_proof(ValueHash, M), 65 | 66 | % Check proof hashes 67 | ?assertEqual(0, length(merkerl:proof_hashes(MP))), 68 | %% And verify it 69 | ?assertEqual(ok, merkerl:verify_proof(ValueHash, M, MP)), 70 | 71 | ok. 72 | 73 | 74 | dedupe_test() -> 75 | %% Removes duplicates 76 | ?assertEqual(1, merkerl:count(merkerl:new(["bar", "bar"], fun merkerl:hash_value/1))), 77 | 78 | ok. 79 | --------------------------------------------------------------------------------