@@ -73,6 +73,11 @@ function p2tr(a, opts) {
7373 }
7474 return a . witness . slice ( ) ;
7575 } ) ;
76+ const _hashTree = lazy . value ( ( ) => {
77+ if ( a . scriptTree ) return ( 0 , taprootutils_1 . toHashTree ) ( a . scriptTree ) ;
78+ if ( a . hash ) return { hash : a . hash } ;
79+ return ;
80+ } ) ;
7681 const network = a . network || networks_1 . bitcoin ;
7782 const o = { name : 'p2tr' , network } ;
7883 lazy . prop ( o , 'address' , ( ) => {
@@ -82,8 +87,8 @@ function p2tr(a, opts) {
8287 return bech32_1 . bech32m . encode ( network . bech32 , words ) ;
8388 } ) ;
8489 lazy . prop ( o , 'hash' , ( ) => {
85- if ( a . hash ) return a . hash ;
86- if ( a . scriptTree ) return ( 0 , taprootutils_1 . toHashTree ) ( a . scriptTree ) . hash ;
90+ const hashTree = _hashTree ( ) ;
91+ if ( hashTree ) return hashTree . hash ;
8792 const w = _witness ( ) ;
8893 if ( w && w . length > 1 ) {
8994 const controlBlock = w [ w . length - 1 ] ;
@@ -144,9 +149,8 @@ function p2tr(a, opts) {
144149 } ) ;
145150 lazy . prop ( o , 'witness' , ( ) => {
146151 if ( a . witness ) return a . witness ;
147- if ( a . scriptTree && a . redeem && a . redeem . output && a . internalPubkey ) {
148- // todo: optimize/cache
149- const hashTree = ( 0 , taprootutils_1 . toHashTree ) ( a . scriptTree ) ;
152+ const hashTree = _hashTree ( ) ;
153+ if ( hashTree && a . redeem && a . redeem . output && a . internalPubkey ) {
150154 const leafHash = ( 0 , taprootutils_1 . tapleafHash ) ( {
151155 output : a . redeem . output ,
152156 version : o . redeemVersion ,
@@ -204,7 +208,7 @@ function p2tr(a, opts) {
204208 throw new TypeError ( 'Invalid pubkey for p2tr' ) ;
205209 }
206210 if ( a . hash && a . scriptTree ) {
207- const hash = ( 0 , taprootutils_1 . toHashTree ) ( a . scriptTree ) . hash ;
211+ const hash = _hashTree ( ) . hash ;
208212 if ( ! a . hash . equals ( hash ) ) throw new TypeError ( 'Hash mismatch' ) ;
209213 }
210214 const witness = _witness ( ) ;
0 commit comments