Skip to content

Instantly share code, notes, and snippets.

@IvRRimum
Created March 6, 2022 17:25
Show Gist options
  • Save IvRRimum/2457e18092292e89eb7ee218c7dc70da to your computer and use it in GitHub Desktop.
Save IvRRimum/2457e18092292e89eb7ee218c7dc70da to your computer and use it in GitHub Desktop.
How to get address from scriptSig: Golang
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/btcsuite/btcutil/base58"
"golang.org/x/crypto/ripemd160"
)
func SHA256D(d []byte) []byte {
hash := sha256.Sum256(d)
hash2 := sha256.Sum256(hash[:])
return hash2[:]
}
func ConvertPKHToAddress(prefix string, address []byte) string {
address = append([]byte(prefix), address...)
fmt.Println(fmt.Sprintf("%x", address))
fmt.Println(fmt.Sprintf("%x", SHA256D(address)[:4]))
endHash := append(address, SHA256D(address)[:4]...)
fmt.Println(fmt.Sprintf("%x", base58.Encode(endHash)))
return base58.Encode(endHash)
}
func PubkeyToAddress(pubKey string) string {
// Convert pubkey to bytes
data, err := hex.DecodeString(pubKey)
if err != nil {
panic(err)
}
// Apply sha256
hash := sha256.Sum256(data)
fmt.Println(fmt.Sprintf("%x", hash[:]))
// Apply ripemd160
ripemd160 := ripemd160.New()
ripemd160.Write(hash[:])
ripedHash := ripemd160.Sum(nil)
fmt.Println(fmt.Sprintf("%v", hex.EncodeToString(ripedHash)))
return ConvertPKHToAddress("\x6f", ripedHash)
}
func main() {
pubkey := "02438799fefc3518466312279642efbde44aae9367accd5b344d943da093a64970"
fmt.Println(fmt.Sprintf("Address: %s", string(PubkeyToAddress(pubkey))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment