When creating a raw transaction, why after the OP_HASH160 the number of bytes of the hashed public key should be included if it's always 20 bytes (that's what RIPEMD160 throws)?

Does this happen with every OP_CODE value in scripts?

Please explain. Thanks.


Are you refering to the pay-to-pubkey-hash script (https://en.bitcoin.it/wiki/Script#Standard_Transaction_to_Bitcoin_address_.28pay-to-pubkey-hash.29)?

In that case it is the hash of the public key, which is 20 bytes. It is NOT the public key itself.

Every op-code correponds to a byte-value in the raw transaction script. All operations are preformed on a stack onto which values can be pushed. The public-key-hash must therefore first be pushed onto the stack, before it can be compared to another value on the stack.

To first push the public-key-hash to the stack we prepend "the number of bytes" which is 20, because this value is itself just an op-code that pushes the next 20 bytes of data to the stack. (See https://en.bitcoin.it/wiki/Script#Constants)

This makes the scripting language more flexible.

  • I see. Prepending the number of bytes allows the OP_CODE to not be "married" with an specific value size. – John Smith Jul 25 '17 at 20:28
  • Otherwise the protocol client would have to do something like if(OP_HASH160) then push the next 20 bytes to te stack. Right? – John Smith Jul 25 '17 at 20:33

why after the OP_HASH160 the number of bytes of the public key should be included if it's always 20 bytes?

not always :)



The OP_HASH160 opcode does not actually do any checking or have any size bytes that follows it. All it does is it takes the top stack item and hashes it with RIPEMD160(SHA256()). Then it pushes that item back to the stack. It does not compare anything nor does it require that any data follows the opcode.

The number of bytes that follows the opcode is actually for an OP_PUSHDATA opcode to push the next 20 bytes onto the stack. That pushes the 20 byte hash that we want to compare to to the stack. Then the OP_EQUAL compares the top two stack items: the hash produced by OP_HASH160 and the 20 bytes that we just pushed to the stack.

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.