@@ -27,12 +27,21 @@ export function rootHashFromPath(
2727 return k [ m ] ;
2828}
2929
30- export interface HashTree {
30+ interface HashLeaf {
3131 hash : Buffer ;
32- left ?: HashTree ;
33- right ?: HashTree ;
3432}
3533
34+ interface HashBranch {
35+ hash : Buffer ;
36+ left : HashTree ;
37+ right : HashTree ;
38+ }
39+
40+ const isHashBranch = ( ht : HashTree ) : ht is HashBranch =>
41+ 'left' in ht && 'right' in ht ;
42+
43+ export type HashTree = HashLeaf | HashBranch ;
44+
3645/**
3746 * Build the hash tree from the scripts binary tree.
3847 * The binary tree can be balanced or not.
@@ -59,24 +68,27 @@ export function toHashTree(scriptTree: Taptree): HashTree {
5968 * Given a MAST tree, it finds the path of a particular hash.
6069 * @param node - the root of the tree
6170 * @param hash - the hash to search for
62- * @returns - and array of hashes representing the path, or an empty array if no pat is found
71+ * @returns - and array of hashes representing the path, undefined if no path is found
6372 */
64- export function findScriptPath ( node : HashTree , hash : Buffer ) : Buffer [ ] {
65- if ( node . left ) {
66- if ( node . left . hash . equals ( hash ) ) return node . right ? [ node . right . hash ] : [ ] ;
67- const leftPath = findScriptPath ( node . left , hash ) ;
68- if ( leftPath . length )
69- return node . right ? [ node . right . hash ] . concat ( leftPath ) : leftPath ;
73+ export function findScriptPath (
74+ node : HashTree ,
75+ hash : Buffer ,
76+ ) : Buffer [ ] | undefined {
77+ if ( ! isHashBranch ( node ) ) {
78+ if ( node . hash . equals ( hash ) ) {
79+ return [ ] ;
80+ } else {
81+ return undefined ;
82+ }
7083 }
7184
72- if ( node . right ) {
73- if ( node . right . hash . equals ( hash ) ) return node . left ? [ node . left . hash ] : [ ] ;
74- const rightPath = findScriptPath ( node . right , hash ) ;
75- if ( rightPath . length )
76- return node . left ? [ node . left . hash ] . concat ( rightPath ) : rightPath ;
77- }
85+ const leftPath = findScriptPath ( node . left , hash ) ;
86+ if ( leftPath !== undefined ) return [ node . right . hash , ...leftPath ] ;
87+
88+ const rightPath = findScriptPath ( node . right , hash ) ;
89+ if ( rightPath !== undefined ) return [ node . left . hash , ...rightPath ] ;
7890
79- return [ ] ;
91+ return undefined ;
8092}
8193
8294export function tapleafHash ( leaf : Tapleaf ) : Buffer {
0 commit comments