Electrum

來自比特幣地址的腳本雜湊與 Golang

  • June 1, 2022

我打破了我的頭尋找解決方案。

我想將比特幣地址用於electrumx

從文件範例中獲取比特幣地址:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa

我需要轉換為8b01df4e368ea28f8dc0423bcf7a4923e3a12d307c875e47a0cfbf90b5c39161

來自文件的範例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.

我的程式碼:

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
}

為什麼實際!=範例


我發現了其他問題,但他們使用 來自比特幣地址的其他語言 ScriptHash 和 BitcoinJS

請幫幫我

改變

sha256.Write([]byte(scriptHex))

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

您必須散列二進制數據,而不是它的十六進製字元串表示

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

引用自:https://bitcoin.stackexchange.com/questions/113934