bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.6k stars 2.08k forks source link

Calculate Electrum scripthash from address #990

Closed youssefgh closed 6 years ago

youssefgh commented 6 years ago

How can i get the scripthash from the address ? as in the following example :

{'priv': 'L8g5V8kFFeg2WbecahRSdobARbHz2w2STH9S8ePHVSY4fmia7Rsj',
        'pub': '03e9f948421aaa89415dc5f281a61b60dde12aae3181b3a76cd2d849b164fc6d0b',
        'address': 'bc1qqmpt7u5e9hfznljta5gnvhyvfd2kdd0r90hwue',
        'minikey': False,
        'txin_type': 'p2wpkh',
        'compressed': True,
        'addr_encoding': 'bech32',
        'scripthash': '1929acaaef3a208c715228e9f1ca0318e3a6b9394ab53c8d026137f847ecf97b'}

Sorry to bother you with opening an issue here as a question The original question in stackexchange : ScriptHash from bitcoin address with BitcoinJS

dcousens commented 6 years ago

Sorry to bother you with opening an issue here as a question

Not a problem! I don't have time to peruse the stackexchange for related Q&A; your issue here is useful to others, so don't hesitate to open questions.

How can i get the scripthash from the address ?

I think electrum uses a similar indexing scheme to https://github.com/bitcoinjs/indexd, that is, SHA256(script). If so, then the following should be what you need:

let script = bitcoin.address.toOutputScript(address)
let hash = bitcoin.crypto.sha256(script)

console.log(address, ' maps to ', hash.toString('hex'))
youssefgh commented 6 years ago

Thanks a lot Your example worked with just a small modification:

let script = bitcoin.address.toOutputScript(address)
let hash = bitcoin.crypto.sha256(script)
let reversedHash = new Buffer(hash.reverse())

console.log(address, ' maps to ', reversedHash.toString('hex'))

No idea why Electrum uses the reverse of the hash and not the hash itself Cheers

junderw commented 6 years ago

endianness and Bitcoin ftw

YanDevDe commented 4 years ago

And how can you do that in reverse order? I mean by converting from scripthash to public address?

Assuming we got scripthash from this

let script = bitcoin.address.toOutputScript(address)
let hash = bitcoin.crypto.sha256(script)
let reversedHash = new Buffer(hash.reverse())

console.log(address, ' maps to ', reversedHash.toString('hex'))

I tried following script but somehow it doesnt work:

const reversedHash = Buffer.from(scripthash, "hex"); //scripthash come from Electrum
const hash = reversedHash.reverse();
const address = bitcoin.address.fromOutputScript(hash);

console.log(address)

Did I something wrong?

lukechilds commented 4 years ago

@YanDevDe bitcoin.address.fromOutputScript requires an output script (actually scriptPubKey), you are passing it the hash of the output script.