-
Notifications
You must be signed in to change notification settings - Fork 12
/
eth_validation.go
52 lines (44 loc) · 1.46 KB
/
eth_validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package types
import (
"bytes"
"errors"
"fmt"
"regexp"
"github.com/ethereum/go-ethereum/common"
)
const (
// EthereumContractAddressLen is the length of contract address strings
EthereumContractAddressLen = 42
// EthereumAddressPrefix is the address prefix address
EthereumAddressPrefix = "0x"
)
var ethereumAddressRegular = regexp.MustCompile("^0x[0-9a-fA-F]{40}$")
// IsEmptyHash returns true if the hash corresponds to an empty ethereum hex hash.
func IsEmptyHash(hash string) bool {
return bytes.Equal(common.HexToHash(hash).Bytes(), common.Hash{}.Bytes())
}
// IsZeroEthereumAddress returns true if the address corresponds to an empty ethereum hex address.
func IsZeroEthereumAddress(address string) bool {
return bytes.Equal(common.HexToAddress(address).Bytes(), common.Address{}.Bytes())
}
// ValidateEthereumAddress validates the ethereum address strings
func ValidateEthereumAddress(address string) error {
if address == "" {
return errors.New("empty")
}
if len(address) != EthereumContractAddressLen {
return errors.New("wrong length")
}
if !ethereumAddressRegular.MatchString(address) {
return errors.New("invalid format")
}
// add ethereum address checksum check 2021-09-02.
if !common.IsHexAddress(address) {
return errors.New("doesn't pass format validation")
}
expectAddress := common.HexToAddress(address).Hex()
if expectAddress != address {
return fmt.Errorf("mismatch expected: %s, got: %s", expectAddress, address)
}
return nil
}