Skip to content

op_hash160 misimplemented #14

Description

@Csi18nAlistairMann

Consider the script 74686973697361736563726574 op_hash160.
Answer expected: 0x835ca4a6a1c2baaaf63bf33c777aff2fc681b017
Answer returned: 0xa69008fd5d7297bed5b71fea578a770e150b2f92

Expected behaviour confirmed at https://www.indicrypto.com/bitcointools/tool/pubkey-to-hash, https://bitcoinprices.org/public-key-to-hash/ and by running through the current master at https://github.com/kallewoof/btcdeb.

The error derives from mishandling the preimages as ascii instead of binary.
In PHP the hash() function returns ascii formed as hexadecimal. Thus:

php > echo hash('ripemd160', hash('sha256', '74686973697361736563726574'));
a69008fd5d7297bed5b71fea578a770e150b2f92

A correct implementation converts the preimages to binary first:

function hexStringToByteString($hexString){
  $len=strlen($hexString);
  $byteString="";
  for ($i=0;$i<$len;$i=$i+2){
    $charnum=hexdec(substr($hexString,$i,2));
    $byteString.=chr($charnum);
  }
  return $byteString;
}

function op_hashop160($preimage) {
  $preimage1 = hexStringToByteString($preimage);    
  $hash1 = hash('sha256', $preimage1);    
  $preimage2 = hexStringToByteString($hash1);    
  $hash2 = hash('ripemd160', $preimage2);
  return $hash2;
}

php > echo op_hashop160('74686973697361736563726574');
835ca4a6a1c2baaaf63bf33c777aff2fc681b017

Thanks!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions