0

I broke my head looking for a solution.
I want use bitcoin address for electrumx

Take bitcoin address from docs example: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
And i need convert to 8b01df4e368ea28f8dc0423bcf7a4923e3a12d307c875e47a0cfbf90b5c39161

Example from docs https://electrumx.readthedocs.io/en/latest/protocol-basics.html#script-hashes

For example, the legacy Bitcoin address from the genesis block:
1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa

has P2PKH script:
76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac

with SHA256 hash:
6191c3b590bfcfa0475e877c302da1e323497acf3b42c08d8fa28e364edf018b

which is sent to the server reversed as:
8b01df4e368ea28f8dc0423bcf7a4923e3a12d307c875e47a0cfbf90b5c39161

By subscribing to this hash you can find P2PKH payments to that address.

my code:

func AddressToScriptHex(addressStr string) string {
    address, err := btcutil.DecodeAddress(addressStr, &chaincfg.MainNetParams)
    if err != nil {
        return ""
    }
    script, err := txscript.PayToAddrScript(address)
    if err != nil {
        return ""
    }
    return fmt.Sprintf("%x", script)
}

func TestBtcUtil_AddressToScriptHex(t *testing.T) {
    addressStr := "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
    scriptHex := "76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac"

    assert.Equal(t, AddressToScriptHex(addressStr), scriptHex)
}

func TestBtcUtil_ScriptHexToSHA256(t *testing.T) {
    scriptHex := "76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac"
    exampleHash := "6191c3b590bfcfa0475e877c302da1e323497acf3b42c08d8fa28e364edf018b"
    sha256 := sha256.New()
    sha256.Write([]byte(scriptHex))

    actual := fmt.Sprintf("%x", sha256.Sum(nil))

    assert.Equal(t, exampleHash, actual) // ERROR
}

why actual != example


i was find other question, but they use other language ScriptHash from bitcoin address with BitcoinJS

Help me please

0

1 Answer 1

1

Change

sha256.Write([]byte(scriptHex))

to

s, err := hex.DecodeString(scriptHex)
if err != nil {
    log.Fatal(err) // or t.Fatalf(...) in unit test 
}
sha256.Write(s)

You must hash the binary data, not the hex string representation of it

See https://go.dev/play/p/iKHNKy118zd

1
  • You saved my head from an explosion. Thanks, this is exactly what I need! I gave you the status of the correct answer, but I can not give you a plus, due to the lack of 15 reputation units. Thank you. Jun 2, 2022 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.