I am running this code and nothing happens.

I am trying to hash160 a script with OP_HASH160 {scriptHash} OP_EQUAL and get a P2SH address as output but not sure this is the right script to achieve this.

// OP_HASH160 {scriptHash} OP_EQUAL
var bitcoin = require('bitcoinjs-lib')
var bscript = require('./src/script')
var types = require('./src/types')
var typeforce = require('typeforce')
var OPS = require('bitcoin-ops')

function check (script) {
  var buffer = bscript.compile(script)

  return buffer.length === 23 &&
    buffer[0] === OPS.OP_HASH160 &&
    buffer[1] === 0x14 &&
    buffer[22] === OPS.OP_EQUAL
check.toJSON = function () { return 'scriptHash output' }

function encode (scriptHash) {
  typeforce(types.Hash160bit, scriptHash)

  return bscript.compile([OPS.OP_HASH160, f1b914051eaabf34c22d354053698e512b36, OPS.OP_EQUAL])

function decode (buffer) {
  typeforce(check, buffer)

  return buffer.slice(2, 22)

module.exports = {
  check: check,
  decode: decode,
  encode: encode

What am I doing wrong? Thanks


You don't hash the OP_HASH160 {scriptHash} OP_EQUAL, that's just a template associated with P2SH addresses. You need to hash the redeem script, add version byte and checksum and then encode into base58.

Sample Python code:

def p2sh(script):
    scripthash = hash160(script)
    data = b'\x05' + scripthash
    checksum = sha256(sha256(data))[:4]
    address = data + checksum
    return base58.encode(address)
  • Thanks! I tried to run your code but nothing happens. How can I get the address and the private key from that string? I'm new to python. i.imgur.com/uPKt09A.png – Robert Jun 19 '18 at 23:40
  • try cloning this repository, it's where I got it from. From the cloned project folder open python and run the following snippet: bpaste.net/show/82cda4df9253 You can't get the private key from anything, it is something you must have. To get an address from a privatekey try this bpaste.net/show/7c224235cebe – Mike D Jun 20 '18 at 8:28

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.