# All files / src/encryption hashRipemd160.ts

90% Statements 27/30
50% Branches 3/6
100% Functions 6/6
90% Lines 27/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    641x
    1x

    1x

    7x
    7x
    7x
    7x

    7x

    1x

    159x

    164x
    164x

    1x
    1x

    1x
    1x
    1x
    1x

    1x
    159x
    159x
    159x

    159x
    159x

    1x
    158x
    158x

     import Ripemd160Polyfill from 'ripemd160-min'
    import { isNodeCryptoAvailable } from './cryptoUtils'

    type NodeCryptoCreateHash = typeof import('crypto').createHash

    export interface Ripemd160Digest {
      digest(data: Buffer): Buffer
    }

    export class Ripemd160PolyfillDigest implements Ripemd160Digest {
      digest(data: Buffer): Buffer {
        const instance = new Ripemd160Polyfill()
        instance.update(data)
        const hash = instance.digest()
        Iif (Array.isArray(hash)) {
          return Buffer.from(hash)
        } else {
          return Buffer.from(hash.buffer)
        }
      }
    }

    export class NodeCryptoRipemd160Digest implements Ripemd160Digest {
      nodeCryptoCreateHash: NodeCryptoCreateHash

      constructor(nodeCryptoCreateHash: NodeCryptoCreateHash) {
        this.nodeCryptoCreateHash = nodeCryptoCreateHash
      }

      digest(data: Buffer): Buffer {
        try {
          return this.nodeCryptoCreateHash('rmd160').update(data).digest()
        } catch (error) {
          try {
            return this.nodeCryptoCreateHash('ripemd160').update(data).digest()
          } catch (_err) {
            console.log(error)
            console.log('Node.js `crypto.createHash` exists but failing to digest for ripemd160, falling back to js implementation')
            const polyfill = new Ripemd160PolyfillDigest()
            return polyfill.digest(data)
          }
        }
      }
    }

    export function createHashRipemd160() {
      const nodeCryptoCreateHash = isNodeCryptoAvailable(nodeCrypto => {
        Eif (typeof nodeCrypto.createHash === 'function') {
          return nodeCrypto.createHash
        }
        return false
      })
      Eif (nodeCryptoCreateHash) {
        return new NodeCryptoRipemd160Digest(nodeCryptoCreateHash)
      } else {
        return new Ripemd160PolyfillDigest()
      }
    }

    export function hashRipemd160(data: Buffer) {
      const hash = createHashRipemd160()
      return hash.digest(data)
    }