-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcredential.go
82 lines (68 loc) · 2.01 KB
/
credential.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
76
77
78
79
80
81
82
package ethtool
import (
"fmt"
"crypto/ecdsa"
"math/big"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
)
type Credential struct{
PrivateKey *ecdsa.PrivateKey
PublicKey *ecdsa.PublicKey
Address common.Address
}
func KeyToCredential(privateKey *ecdsa.PrivateKey) (*Credential,error){
publicKey,ok := privateKey.Public().(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("Public key cast error.")
}
address := crypto.PubkeyToAddress(*publicKey)
credential := &Credential{
PrivateKey: privateKey,
PublicKey: publicKey,
Address: address,
}
return credential,nil
}
func HexToCredential(hexkey string) (*Credential,error) {
privateKey,err := crypto.HexToECDSA(hexkey[2:])
if err != nil {
return nil, err
}
return KeyToCredential(privateKey)
}
func NewCredential() (*Credential,error) {
privateKey,err := crypto.GenerateKey()
if err != nil {
return nil,err
}
return KeyToCredential(privateKey)
}
func (c *Credential) PrivateKeyHex() string {
return hexutil.Encode(crypto.FromECDSA(c.PrivateKey))
}
func (c *Credential) PublicKeyHex() string {
return hexutil.Encode(crypto.FromECDSAPub(c.PublicKey))
}
func (c *Credential) AddressHex() string {
return c.Address.Hex()
}
func (c *Credential) Sign(data []byte) ([]byte,error) {
hash := crypto.Keccak256(data)
return crypto.Sign(hash,c.PrivateKey)
}
func (c* Credential) SignTx(tx *types.Transaction, chainid *big.Int) (*types.Transaction,error) {
signer := types.NewEIP155Signer(chainid)
return types.SignTx(tx,signer,c.PrivateKey)
}
func (c *Credential) Verify(data,signature []byte) bool {
hash := crypto.Keccak256(data)
pubkey := crypto.CompressPubkey(c.PublicKey)
return crypto.VerifySignature(pubkey,hash,signature)
}
func (c *Credential) GetTransactOpts() *bind.TransactOpts {
return bind.NewKeyedTransactor(c.PrivateKey)
}