2

I'm looping through various addresses and I need to know which ones are BTC addresses and which are ETH addresses. So far I just check if the address is hex encoded. Is this function safe to use?

package main

import (
    "encoding/hex"
    "strings"
    "fmt"
)

func main() {
    key := "1DfjCuWDKRWpv1vGP9UNsb4ooArWnXfqnr"
    fmt.Println(isEther(key)) 
}

func isEther(s string) bool {
    s = strings.TrimPrefix(s, "0x")
    _, err := hex.DecodeString(s)
    if err == nil {
        return true
    }
    return false
}
1

From types.go:

// IsHexAddress verifies whether a string can represent a valid hex-encoded
// Ethereum address or not.
func IsHexAddress(s string) bool {
    if hasHexPrefix(s) {
        s = s[2:]
    }
    return len(s) == 2*AddressLength && isHex(s)
}

You'll need to pull in the other called functions and variables, or redefine them in your own file.

There are other address-related utility functions in that file that might also be of use.

0

You can also use a regular expression to check if an Ethereum address is valid:

package main

import (
    "fmt"
    "regexp"
)

func IsValidAddress(v string) bool {
    re := regexp.MustCompile("^0x[0-9a-fA-F]{40}$")
    return re.MatchString(v)
}

func main() {
    fmt.Println(IsValidAddress("0x323b5d4c32345ced77393b3530b1eed0f346429d")) // true
    fmt.Println(IsValidAddress("0xXYZb5d4c32345ced77393b3530b1eed0f346429d")) // false
}

https://play.golang.org/p/k3JqUnZBiKK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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