Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BTC address converted into scripthash library? #280

Open
i6868686 opened this issue Oct 21, 2024 · 1 comment
Open

BTC address converted into scripthash library? #280

i6868686 opened this issue Oct 21, 2024 · 1 comment

Comments

@i6868686
Copy link

I need to convert the address to scripthash to use electrumx. Is there a library or method for this? Or do I have examples for reference? thank you very much

I tried to use the following method to convert the address into scripthash, but the balance of my address could not be checked in electrumx.

import hashlib
import base58

def p2pkh_to_scripthash(address):
decoded = base58.b58decode_check(address)
pubkey_hash = decoded[1:]
sha256_hash = hashlib.sha256(pubkey_hash).digest()
return sha256_hash[::-1].hex()

P2PKH

p2pkh_address = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'
scripthash = p2pkh_to_scripthash(p2pkh_address)
print(f"Scripthash for P2PKH address {p2pkh_address}: {scripthash}")

bc1pvks94hj8p6z9mjvxwua8xhsvfkvjfj8vlll3nkv5aq3mmeglgcasm4eyav

1NXJGRGj7FSwHEK4oMy2vkiFV8sVTLgy5F

bc1q8f8nj8yeatul9ryxmn3dw03f5ual74d4rrklul

@cculianu
Copy link
Collaborator

cculianu commented Oct 21, 2024

No.. that's not how it works. The scripthash is actually the hash of the locking script that appears on-chain for a paricular address. A locking script for p2pkh has the form: OP_DUP OP_HASH160 <rmd160_pubkey_hash> OP_EQUALVERIFY OP_CHECKSIG. (For segwit addresses or the new bc1 style addresses it has a completely different form.)

You need to take the single sha256 hash of the bytes of that locking script, not of the pubkey hash.

In your case, for p2pkh only, you would need to prepend the bytes: [0x76, 0xa9, 0x14]. Then also append at the end the bytes: [0x88, 0xac] ... prepend/append these to the pubkey hash bytes you obtained. Then take the sha256 of that whole thing.

It's confusing, I know.. hopefully this helps.

If you wanted to have this done for you, look in electrumx/lib/coins.py and other places for code you can import/steal to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants