This repository has been archived by the owner on Jul 30, 2019. It is now read-only.
/
keyutil.go
79 lines (67 loc) · 1.98 KB
/
keyutil.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
package keyutil
import (
"fmt"
"testing"
"github.com/medibloc/go-medibloc/common"
"github.com/medibloc/go-medibloc/crypto"
"github.com/medibloc/go-medibloc/crypto/signature"
"github.com/medibloc/go-medibloc/crypto/signature/algorithm"
"github.com/medibloc/go-medibloc/util/byteutils"
"github.com/stretchr/testify/require"
)
// AddrKeyPair contains address and private key.
type AddrKeyPair struct {
Addr common.Address
PrivKey signature.PrivateKey
}
// NewAddrKeyPairFromPrivKey creates a pair from private key.
func NewAddrKeyPairFromPrivKey(t *testing.T, privKey signature.PrivateKey) *AddrKeyPair {
addr, err := common.PublicKeyToAddress(privKey.PublicKey())
require.NoError(t, err)
return &AddrKeyPair{
Addr: addr,
PrivKey: privKey,
}
}
// NewAddrKeyPair creates a pair of address and private key.
func NewAddrKeyPair(t *testing.T) *AddrKeyPair {
privKey, err := crypto.GenerateKey(algorithm.SECP256K1)
require.NoError(t, err)
return NewAddrKeyPairFromPrivKey(t, privKey)
}
// Address returns address.
func (pair *AddrKeyPair) Address() string {
return pair.Addr.Hex()
}
// PrivateKey returns private key.
func (pair *AddrKeyPair) PrivateKey() string {
d, _ := pair.PrivKey.Encoded()
return byteutils.Bytes2Hex(d)
}
// String describes AddrKeyPair in string format.
func (pair *AddrKeyPair) String() string {
if pair == nil {
return ""
}
return fmt.Sprintf("Addr:%v, PrivKey:%v\n", pair.Address(), pair.PrivateKey())
}
// AddrKeyPairs is a slice of AddrKeyPair structure.
type AddrKeyPairs []*AddrKeyPair
// FindPrivKey finds private key of given address.
func (pairs AddrKeyPairs) FindPrivKey(addr common.Address) signature.PrivateKey {
for _, dynasty := range pairs {
if dynasty.Addr.Equals(addr) {
return dynasty.PrivKey
}
}
return nil
}
// FindPair finds AddrKeyPair of given address.
func (pairs AddrKeyPairs) FindPair(addr common.Address) *AddrKeyPair {
for _, dynasty := range pairs {
if dynasty.Addr.Equals(addr) {
return dynasty
}
}
return nil
}