@@ -23,9 +23,17 @@ function rootHashFromPath(controlBlock, tapLeafMsg) {
2323 return k [ m ] ;
2424}
2525exports . rootHashFromPath = rootHashFromPath ;
26- function toHashTree ( scripts ) {
27- if ( scripts . length === 1 ) {
28- const script = scripts [ 0 ] ;
26+ /**
27+ * Build the hash tree from the scripts binary tree.
28+ * The binary tree can be balanced or not.
29+ * @param scriptsTree - is a list representing a binary tree where an element can be:
30+ * - a taproot leaf [(output, version)], or
31+ * - a pair of two taproot leafs [(output, version), (output, version)], or
32+ * - one taproot leaf and a list of elements
33+ */
34+ function toHashTree ( scriptsTree ) {
35+ if ( scriptsTree . length === 1 ) {
36+ const script = scriptsTree [ 0 ] ;
2937 if ( Array . isArray ( script ) ) {
3038 return toHashTree ( script ) ;
3139 }
@@ -36,10 +44,8 @@ function toHashTree(scripts) {
3644 hash : tapLeafHash ( script . output , script . version ) ,
3745 } ;
3846 }
39- // todo: this is a binary tree, use zero an one index
40- const half = Math . trunc ( scripts . length / 2 ) ;
41- const left = toHashTree ( scripts . slice ( 0 , half ) ) ;
42- const right = toHashTree ( scripts . slice ( half ) ) ;
47+ const left = toHashTree ( [ scriptsTree [ 0 ] ] ) ;
48+ const right = toHashTree ( [ scriptsTree [ 1 ] ] ) ;
4349 let leftHash = left . hash ;
4450 let rightHash = right . hash ;
4551 if ( leftHash . compare ( rightHash ) === 1 )
@@ -51,6 +57,12 @@ function toHashTree(scripts) {
5157 } ;
5258}
5359exports . toHashTree = toHashTree ;
60+ /**
61+ * Given a MAST tree, it finds the path of a particular hash.
62+ * @param node - the root of the tree
63+ * @param hash - the hash to search for
64+ * @returns - and array of hashes representing the path, or an empty array if no pat is found
65+ */
5466function findScriptPath ( node , hash ) {
5567 if ( node . left ) {
5668 if ( node . left . hash . equals ( hash ) ) return node . right ? [ node . right . hash ] : [ ] ;
0 commit comments