7

Why would I use OP_HASH160 over OP_SHA256 and vice versa? Why are there two options? In what situations should I use one over the other?

Example unlocking scripts:

From BIP199: ( where HASHOP could be either )

    OP_IF
        [HASHOP] <digest> OP_EQUALVERIFY OP_DUP OP_HASH160 <seller pubkey hash>            
    OP_ELSE
        <num> [TIMEOUTOP] OP_DROP OP_DUP OP_HASH160 <buyer pubkey hash>
    OP_ENDIF
    OP_EQUALVERIFY
    OP_CHECKSIG

From miniscript's received HTLC demo:

<key_remote> OP_CHECKSIG OP_NOTIF
  <key_revocation> OP_CHECKSIG
OP_ELSE
  OP_IF
    OP_DUP OP_HASH160 <HASH160(key_local)> OP_EQUALVERIFY OP_CHECKSIGVERIFY
    OP_SIZE <20> OP_EQUALVERIFY OP_HASH160 <h> OP_EQUAL
  OP_ELSE
    <f003> OP_CHECKSEQUENCEVERIFY
  OP_ENDIF
OP_ENDIF
2

I think HASH160 is the standard/preferable to SHA-256 in locking/unlocking scripts just because its digest is smaller (20-byte digest instead of 32-byte of SHA-256) and, therefore, it takes less space in the blockchain. As it takes less space, you pay less in mining fees with no security cost (160 bits is well above the 128-bit threshold)

Remember that with HASH160 you are already hashing twice (HASH160 = RIPEMD160(SHA-256)) so the little security benefit compared to two rounds of SHA-256 doesn't compensate for the extra fee/blockchain space.

2
  • Is the result from HASH160 vs SHA256 the same? – arshbot Dec 16 '19 at 23:17
  • No, the final result is different. Only the intermediary result of HASH160 is the same as the final result of SHA256. With an example: let's hash "test string" with SHA256, you can do this on the command line with echo "test string" | sha256sum, the result is 37d2046a395cbfcb2712ff5c96a727b1966876080047c56717009dbbc235f566. To do the HASH160, you need to further hash this with RIPEMD-160, obtained with echo 37d2046a395cbfcb2712ff5c96a727b1966876080047c56717009dbbc235f566 | openssl rmd160, the result is 79c15f63a1044e02075b42e6df876890392197f0, which is the HASH160 of "test string" – Pedro Dec 16 '19 at 23:42
1

HASH160 is mostly used due to convention and convenience - it has historically been used in p2pkh, p2sh, and p2wpkh addresses, and is usually well supported and understood by any tooling around the bitcoin ecosystem.

For on-chain reasons, HASH160 produces a shorter digest of 20 bytes, vs. 32 bytes for SHA256.

Beyond that, it is simply a choice - you are welcome to use any reasonably secure hashing algorithm. Bitcoin Script supports RIPEMD160, HASH160, SHA1, SHA256, and SHA256d. All of them would work for an HTLC use case (although SHA1 should probably be avoided as it has been proven weaker than the others to an extent, although not currently a catastrophic one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.