@@ -14,6 +14,30 @@ import * as lodash from 'lodash';
1414
1515const Chain = require ( '../chain' ) ;
1616
17+ const addressCacheStore = {
18+ list : [ ] as Array < any > ,
19+ map : new Map ( ) as Map < any , string >
20+ } ;
21+
22+ function getCachedAddress ( chain : string , network : string , script : string ) {
23+ const result = addressCacheStore . map . get ( `${ chain } :${ network } :${ script } ` ) ;
24+ if ( result ) {
25+ addressCacheStore . list . push ( `${ chain } :${ network } :${ script } ` ) ;
26+ if ( addressCacheStore . list . length > 10000 ) {
27+ addressCacheStore . map . delete ( addressCacheStore . list . shift ( ) ) ;
28+ }
29+ }
30+ return result ;
31+ }
32+
33+ function setCachedAddress ( chain : string , network : string , script : any , address : any ) {
34+ addressCacheStore . map . set ( `${ chain } :${ network } :${ script } ` , address ) ;
35+ addressCacheStore . list . push ( `${ chain } :${ network } :${ script } ` ) ;
36+ if ( addressCacheStore . list . length > 10000 ) {
37+ addressCacheStore . map . delete ( addressCacheStore . list . shift ( ) ) ;
38+ }
39+ }
40+
1741export type ITransaction = {
1842 txid : string ;
1943 chain : string ;
@@ -216,12 +240,18 @@ export class Transaction extends BaseModel<ITransaction> {
216240 continue ;
217241 }
218242 let address = '' ;
219- let scriptBuffer = output . script && output . script . toBuffer ( ) ;
220- if ( scriptBuffer ) {
221- address = output . script . toAddress ( network ) . toString ( true ) ;
222- if ( address === 'false' && output . script . classify ( ) === 'Pay to public key' ) {
223- let hash = Chain [ chain ] . lib . crypto . Hash . sha256ripemd160 ( output . script . chunks [ 0 ] . buf ) ;
224- address = Chain [ chain ] . lib . Address ( hash , network ) . toString ( true ) ;
243+ if ( output . script ) {
244+ const hexScript = output . script . toHex ( ) ;
245+ const cachedAddress = getCachedAddress ( chain , network , hexScript ) ;
246+ if ( cachedAddress ) {
247+ address = cachedAddress ;
248+ } else {
249+ address = output . script . toAddress ( network ) . toString ( true ) ;
250+ if ( address === 'false' && output . script . classify ( ) === 'Pay to public key' ) {
251+ let hash = Chain [ chain ] . lib . crypto . Hash . sha256ripemd160 ( output . script . chunks [ 0 ] . buf ) ;
252+ address = Chain [ chain ] . lib . Address ( hash , network ) . toString ( true ) ;
253+ }
254+ setCachedAddress ( chain , network , output . script . toHex ( ) , address ) ;
225255 }
226256 }
227257
@@ -242,7 +272,7 @@ export class Transaction extends BaseModel<ITransaction> {
242272 mintHeight : height ,
243273 coinbase : isCoinbase ,
244274 value : output . satoshis ,
245- script : scriptBuffer ,
275+ script : output . script . toBuffer ( ) ,
246276 spentHeight : SpentHeightIndicators . unspent ,
247277 wallets : [ ]
248278 }
0 commit comments