@@ -38,15 +38,17 @@ interface HashBranch {
38
38
const isHashBranch = ( ht : HashTree ) : ht is HashBranch =>
39
39
'left' in ht && 'right' in ht ;
40
40
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
+ */
41
47
export type HashTree = HashLeaf | HashBranch ;
42
48
43
49
/**
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.
50
52
*/
51
53
export function toHashTree ( scriptTree : Taptree ) : HashTree {
52
54
if ( isTapleaf ( scriptTree ) ) return { hash : tapleafHash ( scriptTree ) } ;
@@ -63,29 +65,27 @@ export function toHashTree(scriptTree: Taptree): HashTree {
63
65
}
64
66
65
67
/**
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 .
67
69
* @param node - the root of the tree
68
70
* @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
70
74
*/
71
75
export function findScriptPath (
72
76
node : HashTree ,
73
77
hash : Buffer ,
74
78
) : 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 [ ] ;
81
87
}
82
88
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
-
89
89
return undefined ;
90
90
}
91
91
0 commit comments