tendermint/pub_key.go

93 lines
2.1 KiB
Go
Raw Normal View History

2015-10-25 13:45:13 -07:00
package crypto
2015-10-25 13:42:49 -07:00
import (
"bytes"
"github.com/tendermint/ed25519"
"github.com/tendermint/ed25519/extra25519"
. "github.com/tendermint/go-common"
2015-10-25 13:45:13 -07:00
"github.com/tendermint/go-wire"
"golang.org/x/crypto/ripemd160"
2015-10-25 13:42:49 -07:00
)
// PubKey is part of Account and Validator.
type PubKey interface {
Address() []byte
2016-03-15 11:11:54 -07:00
Bytes() []byte
2016-02-08 00:50:52 -08:00
KeyString() string
2015-10-25 13:42:49 -07:00
VerifyBytes(msg []byte, sig Signature) bool
2016-03-13 09:40:15 -07:00
Equals(PubKey) bool
2015-10-25 13:42:49 -07:00
}
// Types of PubKey implementations
const (
PubKeyTypeEd25519 = byte(0x01)
)
// for wire.readReflect
var _ = wire.RegisterInterface(
struct{ PubKey }{},
wire.ConcreteType{PubKeyEd25519{}, PubKeyTypeEd25519},
)
2016-03-15 11:11:54 -07:00
func PubKeyFromBytes(pubKeyBytes []byte) (pubKey PubKey, err error) {
err = wire.ReadBinaryBytes(pubKeyBytes, &pubKey)
return
}
2015-10-25 13:42:49 -07:00
//-------------------------------------
// Implements PubKey
type PubKeyEd25519 [32]byte
func (pubKey PubKeyEd25519) Address() []byte {
2016-03-15 11:11:54 -07:00
pubKeyBytes := pubKey.Bytes()
2015-10-25 13:42:49 -07:00
hasher := ripemd160.New()
2016-03-15 11:11:54 -07:00
hasher.Write(pubKeyBytes) // does not error
2015-10-25 13:42:49 -07:00
return hasher.Sum(nil)
}
2016-03-15 11:11:54 -07:00
func (pubKey PubKeyEd25519) Bytes() []byte {
return wire.BinaryBytes(struct{ PubKey }{pubKey})
}
2015-10-25 13:42:49 -07:00
// TODO: Consider returning a reason for failure, or logging a runtime type mismatch.
func (pubKey PubKeyEd25519) VerifyBytes(msg []byte, sig_ Signature) bool {
sig, ok := sig_.(SignatureEd25519)
if !ok {
return false
}
pubKeyBytes := [32]byte(pubKey)
sigBytes := [64]byte(sig)
return ed25519.Verify(&pubKeyBytes, msg, &sigBytes)
}
// For use with golang/crypto/nacl/box
// If error, returns nil.
func (pubKey PubKeyEd25519) ToCurve25519() *[32]byte {
keyCurve25519, pubKeyBytes := new([32]byte), [32]byte(pubKey)
ok := extra25519.PublicKeyToCurve25519(keyCurve25519, &pubKeyBytes)
if !ok {
return nil
}
return keyCurve25519
}
func (pubKey PubKeyEd25519) String() string {
return Fmt("PubKeyEd25519{%X}", pubKey[:])
}
// Must return the full bytes in hex.
// Used for map keying, etc.
func (pubKey PubKeyEd25519) KeyString() string {
return Fmt("%X", pubKey[:])
}
func (pubKey PubKeyEd25519) Equals(other PubKey) bool {
if otherEd, ok := other.(PubKeyEd25519); ok {
return bytes.Equal(pubKey[:], otherEd[:])
} else {
return false
}
}