OSDN Git Service

Wallet store test (#312)
[bytom/vapor.git] / vendor / github.com / tendermint / go-crypto / priv_key.go
1 package crypto
2
3 import (
4         "encoding/hex"
5
6         "github.com/tendermint/ed25519"
7         "github.com/tendermint/go-wire"
8         "github.com/tendermint/go-wire/data"
9 )
10
11 func PrivKeyFromBytes(privKeyBytes []byte) (privKey PrivKey, err error) {
12         err = wire.ReadBinaryBytes(privKeyBytes, &privKey)
13         if err == nil {
14                 // add support for a ValidateKey method on PrivKeys
15                 // to make sure they load correctly
16                 val, ok := privKey.Unwrap().(validatable)
17                 if ok {
18                         err = val.ValidateKey()
19                 }
20         }
21         return
22 }
23
24 // validatable is an optional interface for keys that want to
25 // check integrity
26 type validatable interface {
27         ValidateKey() error
28 }
29
30 //----------------------------------------
31
32 // DO NOT USE THIS INTERFACE.
33 // You probably want to use PrivKey
34 // +gen wrapper:"PrivKey,Impl[PrivKeyEd25519,PrivKeySecp256k1],ed25519,secp256k1"
35 type PrivKeyInner interface {
36         Sign(msg []byte) Signature
37         PubKey() PubKey
38         Wrap() PrivKey
39 }
40
41 //-------------------------------------
42
43 var _ PrivKeyInner = PrivKeyEd25519{}
44
45 // Implements PrivKey
46 type PrivKeyEd25519 [64]byte
47
48 func (privKey PrivKeyEd25519) Sign(msg []byte) Signature {
49         privKeyBytes := [64]byte(privKey)
50         signatureBytes := ed25519.Sign(&privKeyBytes, msg)
51         return SignatureEd25519(*signatureBytes).Wrap()
52 }
53
54 func (privKey PrivKeyEd25519) PubKey() PubKey {
55         privKeyBytes := [64]byte(privKey)
56         pubBytes := *ed25519.MakePublicKey(&privKeyBytes)
57         return PubKeyEd25519(pubBytes).Wrap()
58 }
59
60 func (p PrivKeyEd25519) MarshalJSON() ([]byte, error) {
61         return data.Encoder.Marshal(p[:])
62 }
63
64 func (p *PrivKeyEd25519) UnmarshalJSON(enc []byte) error {
65         var ref []byte
66         err := data.Encoder.Unmarshal(&ref, enc)
67         copy(p[:], ref)
68         return err
69 }
70
71 func (privKey PrivKeyEd25519) String() string {
72         return hex.EncodeToString(privKey[:])
73 }
74
75 func GenPrivKeyEd25519() PrivKeyEd25519 {
76         privKeyBytes := new([64]byte)
77         copy(privKeyBytes[:32], CRandBytes(32))
78         ed25519.MakePublicKey(privKeyBytes)
79         return PrivKeyEd25519(*privKeyBytes)
80 }