-
Notifications
You must be signed in to change notification settings - Fork 6
/
signer.go
119 lines (100 loc) · 2.5 KB
/
signer.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
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
110
111
112
113
114
115
116
117
118
119
package goether
import (
"crypto/ecdsa"
"io/ioutil"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto/ecies"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/signer/core/apitypes"
)
type Signer struct {
Address common.Address
key *ecdsa.PrivateKey
}
func NewSigner(prvHex string) (*Signer, error) {
k, err := crypto.HexToECDSA(prvHex)
if err != nil {
return nil, err
}
return &Signer{
key: k,
Address: crypto.PubkeyToAddress(k.PublicKey),
}, nil
}
func NewSignerFromPath(prvPath string) (*Signer, error) {
b, err := ioutil.ReadFile(prvPath)
if err != nil {
return nil, err
}
return NewSigner(strings.TrimSpace(string(b)))
}
func (s Signer) GetPrivateKey() *ecdsa.PrivateKey {
return s.key
}
func (s Signer) GetPublicKey() []byte {
return crypto.FromECDSAPub(&s.key.PublicKey)
}
func (s Signer) GetPublicKeyHex() string {
return hexutil.Encode(s.GetPublicKey())
}
// SignTx DynamicFeeTx
func (s *Signer) SignTx(
nonce int, to common.Address, amount *big.Int,
gasLimit int, gasTipCap *big.Int, gasFeeCap *big.Int,
data []byte, chainID *big.Int,
) (tx *types.Transaction, err error) {
baseTx := &types.DynamicFeeTx{
Nonce: uint64(nonce),
GasTipCap: gasTipCap,
GasFeeCap: gasFeeCap,
Gas: uint64(gasLimit),
To: &to,
Value: amount,
Data: data,
}
return types.SignNewTx(s.key, types.LatestSignerForChainID(chainID), baseTx)
}
func (s *Signer) SignLegacyTx(
nonce int, to common.Address, amount *big.Int,
gasLimit int, gasPrice *big.Int,
data []byte, chainID *big.Int,
) (tx *types.Transaction, err error) {
return types.SignTx(
types.NewTransaction(
uint64(nonce), to, amount,
uint64(gasLimit), gasPrice, data),
types.NewEIP155Signer(chainID),
s.key,
)
}
func (s Signer) SignMsg(msg []byte) (sig []byte, err error) {
hash := accounts.TextHash(msg)
sig, err = crypto.Sign(hash, s.key)
if err != nil {
return
}
sig[64] += 27
return
}
func (s Signer) SignTypedData(typedData apitypes.TypedData) (sig []byte, err error) {
hash, err := EIP712Hash(typedData)
if err != nil {
return
}
sig, err = crypto.Sign(hash, s.key)
if err != nil {
return
}
sig[64] += 27
return
}
// Decrypt decrypt
func (s Signer) Decrypt(ct []byte) ([]byte, error) {
eciesPriv := ecies.ImportECDSA(s.key)
return eciesPriv.Decrypt(ct, nil, nil)
}