-
Notifications
You must be signed in to change notification settings - Fork 1
/
signer.go
54 lines (47 loc) · 1.08 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
package metax
import (
"crypto/ecdsa"
"io/ioutil"
"strings"
"github.com/ethereum/go-ethereum/common"
"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(privKey string) (*Signer, error) {
key, err := crypto.HexToECDSA(privKey)
if err != nil {
return nil, err
}
return &Signer{
key: key,
Address: crypto.PubkeyToAddress(key.PublicKey),
}, nil
}
func NewSignerFromPath(privPath string) (*Signer, error) {
f, err := ioutil.ReadFile(privPath)
if err != nil {
return nil, err
}
return NewSigner(strings.TrimSpace(string(f)))
}
func (s *Signer) GetPublicKey() []byte {
return crypto.FromECDSAPub(&s.key.PublicKey)
}
func (s *Signer) SignTypedData(typedData apitypes.TypedData) ([]byte, error) {
hashBytes, _, err := apitypes.TypedDataAndHash(typedData)
if err != nil {
return nil, err
}
sig, err := crypto.Sign(hashBytes, s.key)
if err != nil {
return nil, err
}
if sig[64] == 0 || sig[64] == 1 {
sig[64] += 27
}
return sig, nil
}