-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwallet.go
More file actions
109 lines (91 loc) · 2.17 KB
/
Copy pathwallet.go
File metadata and controls
109 lines (91 loc) · 2.17 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Package jingtumlib 钱包类,用于创建和导入钱包等功能。
// @FileName: wallet.go
// @Auther : 杨雪波
// @Email : yangxuebo@yeah.net
// @CreateTime: 2018-07-26 10:44:32
// @UpdateTime: 2018-07-26 10:44:54
package jingtumlib
import (
"crypto/ecdsa"
"fmt"
"jingtumlib/constant"
"jingtumlib/crypto/secp256k1"
"jingtumlib/utils"
"github.com/btcsuite/btcd/btcec"
)
//Wallet 钱包结构体
type Wallet struct {
priv *secp256k1.PrivateKey
secret string
}
//IsValidAddress 钱包地址合法性验证
func IsValidAddress(address string) bool {
if address == "" {
return false
}
return utils.IsValidAddress(address)
}
//IsValidSecret 钱包私钥合法性验证
func IsValidSecret(secret string) bool {
if secret == "" {
return false
}
keyPair := &secp256k1.Secp256KeyPair{}
_, err := keyPair.DeriveKeyPair(secret)
if nil != err {
return false
}
return true
}
//Generate 生成钱包
func Generate() (*Wallet, error) {
keyPair := &secp256k1.Secp256KeyPair{}
secret, err := keyPair.GenerateSeed()
if err != nil {
return nil, err
}
return FromSecret(secret)
}
//FromSecret 根据井通私钥创建钱包
func FromSecret(secret string) (*Wallet, error) {
if secret == "" {
return nil, constant.ERR_EMPTY_PARAM
}
keyPair := &secp256k1.Secp256KeyPair{}
priv, err := keyPair.DeriveKeyPair(secret)
if nil != err {
return nil, err
}
wallet := new(Wallet)
wallet.priv = priv
wallet.secret = secret
return wallet, nil
}
//GetPublicKey 获取16进制公钥
func (wallet *Wallet) GetPublicKey() string {
return wallet.priv.PublicKey.BytesToHex()
}
//GetSecret 获取私钥
func (wallet *Wallet) GetSecret() string {
return wallet.secret
}
//GetAddress 获取钱包地址
func (wallet *Wallet) GetAddress() string {
return wallet.priv.PublicKey.ToAddress()
}
//signTx 对交易数据签名
func (wallet *Wallet) signTx(hash []byte) (string, error) {
priv := &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: btcec.S256(),
X: wallet.priv.X,
Y: wallet.priv.Y,
},
D: wallet.priv.D,
}
signature, err := (*btcec.PrivateKey)(priv).Sign(hash)
if err != nil {
return "", err
}
return fmt.Sprintf("%X", signature.Serialize()), nil
}