-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcrypto_evm.go
78 lines (61 loc) · 1.68 KB
/
crypto_evm.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
// +build evm
package crypto
import (
"crypto/ecdsa"
"fmt"
"github.com/ethereum/go-ethereum/crypto"
ssha "github.com/miguelmota/go-solidity-sha3"
)
type Secp256k1PrivateKey ecdsa.PrivateKey
func (s *Secp256k1PrivateKey) ToECDSAPrivKey() *ecdsa.PrivateKey {
ecdsaPrivKey := ecdsa.PrivateKey(*s)
return &ecdsaPrivKey
}
func LoadSecp256k1PrivKey(filePath string) (*Secp256k1PrivateKey, error) {
privKey, err := crypto.LoadECDSA(filePath)
if err != nil {
return nil, err
}
secpPrivKey := Secp256k1PrivateKey(*privKey)
return &secpPrivKey, nil
}
func SoliditySign(hash []byte, prv PrivateKey) (sig []byte, err error) {
switch prv.(type) {
case *Secp256k1PrivateKey:
sig, err = crypto.Sign(hash, prv.(*Secp256k1PrivateKey).ToECDSAPrivKey())
case *YubiHsmPrivateKey:
//TODO this feels out of place
sig, err = YubiHsmSign(hash, prv.(*YubiHsmPrivateKey))
default:
return nil, fmt.Errorf("unknown private key type")
}
if err != nil {
return nil, err
}
v := sig[len(sig)-1]
sig[len(sig)-1] = v + 27
return sig, nil
}
func SoliditySignPrefixed(hash []byte, prv PrivateKey) (sig []byte, err error) {
// Need to prefix the hash with the Ethereum Signed Message
hash = ssha.SoliditySHA3(
[]string{"string", "bytes32"},
"\x19Ethereum Signed Message:\n32",
hash,
)
switch prv.(type) {
case *Secp256k1PrivateKey:
sig, err = crypto.Sign(hash, prv.(*Secp256k1PrivateKey).ToECDSAPrivKey())
case *YubiHsmPrivateKey:
//TODO this feels out of place
sig, err = YubiHsmSign(hash, prv.(*YubiHsmPrivateKey))
default:
return nil, fmt.Errorf("unknown private key type")
}
if err != nil {
return nil, err
}
v := sig[len(sig)-1]
sig[len(sig)-1] = v + 27
return sig, nil
}