forked from coming-chat/wallet-SDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account_util.go
75 lines (62 loc) · 1.77 KB
/
account_util.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package doge
import (
"errors"
"github.com/btcsuite/btcd/btcutil"
"github.com/centrifuge/go-substrate-rpc-client/v4/types"
)
type Util struct {
Chainnet string
}
func NewUtilWithChainnet(chainnet string) (*Util, error) {
if isValidChain(chainnet) {
return &Util{Chainnet: chainnet}, nil
} else {
return nil, ErrUnsupportedChain
}
}
// MARK - Implement the protocol Util
// @param publicKey can start with 0x or not.
func (u *Util) EncodePublicKeyToAddress(publicKey string) (string, error) {
return EncodePublicKeyToAddress(publicKey, u.Chainnet)
}
func (u *Util) EncodePublicDataToAddress(public []byte) (string, error) {
return EncodePublicDataToAddress(public, u.Chainnet)
}
// Warning: Dogecoin cannot support decode address to public key
func (u *Util) DecodeAddressToPublicKey(address string) (string, error) {
return "", errors.New("Dogecoin cannot support decode address to public key")
}
func (u *Util) IsValidAddress(address string) bool {
return IsValidAddress(address, u.Chainnet)
}
// MARK - like Util
// @param publicKey can start with 0x or not.
func EncodePublicKeyToAddress(publicKey string, chainnet string) (string, error) {
pubData, err := types.HexDecodeString(publicKey)
if err != nil {
return "", err
}
return EncodePublicDataToAddress(pubData, chainnet)
}
func EncodePublicDataToAddress(public []byte, chainnet string) (string, error) {
net, err := netParamsOf(chainnet)
if err != nil {
return "", err
}
address, err := btcutil.NewAddressPubKey(public, net)
if err != nil {
return "", err
}
return address.EncodeAddress(), nil
}
func IsValidAddress(address, chainnet string) bool {
net, err := netParamsOf(chainnet)
if err != nil {
return false
}
_, err = btcutil.DecodeAddress(address, net)
if err != nil {
return false
}
return true
}