@@ -38,15 +38,17 @@ interface HashBranch {
3838const isHashBranch = ( ht : HashTree ) : ht is HashBranch =>
3939 'left' in ht && 'right' in ht ;
4040
41+ /**
42+ * Binary tree representing leaf, branch, and root node hashes of a Taptree.
43+ * Each node contains a hash, and potentially left and right branch hashes.
44+ * This tree is used for 2 purposes: Providing the root hash for tweaking,
45+ * and calculating merkle inclusion proofs when constructing a control block.
46+ */
4147export type HashTree = HashLeaf | HashBranch ;
4248
4349/**
44- * Build the hash tree from the scripts binary tree.
45- * The binary tree can be balanced or not.
46- * @param scriptTree - is a list representing a binary tree where an element can be:
47- * - a taproot leaf [(output, version)], or
48- * - a pair of two taproot leafs [(output, version), (output, version)], or
49- * - one taproot leaf and a list of elements
50+ * Build a hash tree of merkle nodes from the scripts binary tree.
51+ * @param scriptTree - the tree of scripts to pairwise hash.
5052 */
5153export function toHashTree ( scriptTree : Taptree ) : HashTree {
5254 if ( isTapleaf ( scriptTree ) ) return { hash : tapleafHash ( scriptTree ) } ;
@@ -63,29 +65,27 @@ export function toHashTree(scriptTree: Taptree): HashTree {
6365}
6466
6567/**
66- * Given a MAST tree, it finds the path of a particular hash.
68+ * Given a HashTree, finds the path from a particular hash to the root .
6769 * @param node - the root of the tree
6870 * @param hash - the hash to search for
69- * @returns - and array of hashes representing the path, undefined if no path is found
71+ * @returns - array of sibling hashes, from leaf (inclusive) to root
72+ * (exclusive) needed to prove inclusion of the specified hash. undefined if no
73+ * path is found
7074 */
7175export function findScriptPath (
7276 node : HashTree ,
7377 hash : Buffer ,
7478) : Buffer [ ] | undefined {
75- if ( ! isHashBranch ( node ) ) {
76- if ( node . hash . equals ( hash ) ) {
77- return [ ] ;
78- } else {
79- return undefined ;
80- }
79+ if ( isHashBranch ( node ) ) {
80+ const leftPath = findScriptPath ( node . left , hash ) ;
81+ if ( leftPath !== undefined ) return [ ...leftPath , node . right . hash ] ;
82+
83+ const rightPath = findScriptPath ( node . right , hash ) ;
84+ if ( rightPath !== undefined ) return [ ...rightPath , node . left . hash ] ;
85+ } else if ( node . hash . equals ( hash ) ) {
86+ return [ ] ;
8187 }
8288
83- const leftPath = findScriptPath ( node . left , hash ) ;
84- if ( leftPath !== undefined ) return [ node . right . hash , ...leftPath ] ;
85-
86- const rightPath = findScriptPath ( node . right , hash ) ;
87- if ( rightPath !== undefined ) return [ node . left . hash , ...rightPath ] ;
88-
8989 return undefined ;
9090}
9191
0 commit comments