Browse Source

keys: change to []bytes (#4950)

pull/4959/head
Marko 5 years ago
committed by GitHub
parent
commit
7c576f02ab
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 152 additions and 160 deletions
  1. +1
    -0
      CHANGELOG_PENDING.md
  2. +2
    -2
      abci/example/kvstore/persistent_kvstore.go
  3. +32
    -47
      crypto/ed25519/ed25519.go
  4. +18
    -0
      crypto/ed25519/encoding.go
  5. +7
    -20
      crypto/encoding/amino/encode_test.go
  6. +6
    -6
      crypto/encoding/codec.go
  7. +23
    -0
      crypto/secp256k1/encoding.go
  8. +19
    -41
      crypto/secp256k1/secp256k1.go
  9. +3
    -5
      crypto/secp256k1/secp256k1_test.go
  10. +1
    -2
      crypto/sr25519/encoding.go
  11. +15
    -9
      crypto/sr25519/privkey.go
  12. +7
    -9
      crypto/sr25519/pubkey.go
  13. +2
    -4
      privval/file_test.go
  14. +1
    -1
      rpc/client/evidence_test.go
  15. +2
    -1
      tools/tm-signer-harness/internal/test_harness.go
  16. +1
    -1
      tools/tm-signer-harness/main.go
  17. +1
    -1
      types/block.go
  18. +1
    -1
      types/proto3_test.go
  19. +6
    -6
      types/protobuf.go
  20. +1
    -1
      types/protobuf_test.go
  21. +3
    -3
      types/validator_set_test.go

+ 1
- 0
CHANGELOG_PENDING.md View File

@ -12,6 +12,7 @@ Friendly reminder, we have a [bug bounty program](https://hackerone.com/tendermi
- [evidence] \#4725 Remove `Pubkey` from DuplicateVoteEvidence - [evidence] \#4725 Remove `Pubkey` from DuplicateVoteEvidence
- [rpc] [\#4792](https://github.com/tendermint/tendermint/pull/4792) `/validators` are now sorted by voting power (@melekes) - [rpc] [\#4792](https://github.com/tendermint/tendermint/pull/4792) `/validators` are now sorted by voting power (@melekes)
- [crypto] \#4940 All keys have become `[]byte` instead of `[<size>]byte`. The byte method no longer returns the marshaled value but just the `[]byte` form of the data.
- [crypto] \#4941 Remove suffixes from all keys. - [crypto] \#4941 Remove suffixes from all keys.
- ed25519: type `PrivKeyEd25519` is now `PrivKey` - ed25519: type `PrivKeyEd25519` is now `PrivKey`
- ed25519: type `PubKeyEd25519` is now `PubKey` - ed25519: type `PubKeyEd25519` is now `PubKey`


+ 2
- 2
abci/example/kvstore/persistent_kvstore.go View File

@ -232,8 +232,8 @@ func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.Respon
func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx { func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
key := []byte("val:" + string(v.PubKey.Data)) key := []byte("val:" + string(v.PubKey.Data))
pubkey := ed25519.PubKey{}
copy(pubkey[:], v.PubKey.Data)
pubkey := make(ed25519.PubKey, ed25519.PubKeySize)
copy(pubkey, v.PubKey.Data)
if v.Power == 0 { if v.Power == 0 {
// remove validator // remove validator


+ 32
- 47
crypto/ed25519/ed25519.go View File

@ -6,7 +6,6 @@ import (
"fmt" "fmt"
"io" "io"
amino "github.com/tendermint/go-amino"
"golang.org/x/crypto/ed25519" "golang.org/x/crypto/ed25519"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
@ -20,29 +19,24 @@ var _ crypto.PrivKey = PrivKey{}
const ( const (
PrivKeyAminoName = "tendermint/PrivKeyEd25519" PrivKeyAminoName = "tendermint/PrivKeyEd25519"
PubKeyAminoName = "tendermint/PubKeyEd25519" PubKeyAminoName = "tendermint/PubKeyEd25519"
// PubKeySize is is the size, in bytes, of public keys as used in this package.
PubKeySize = 32
// PrivateKeySize is the size, in bytes, of private keys as used in this package.
PrivateKeySize = 64
// Size of an Edwards25519 signature. Namely the size of a compressed // Size of an Edwards25519 signature. Namely the size of a compressed
// Edwards25519 point, and a field element. Both of which are 32 bytes. // Edwards25519 point, and a field element. Both of which are 32 bytes.
SignatureSize = 64 SignatureSize = 64
// SeedSize is the size, in bytes, of private key seeds. These are the
// private key representations used by RFC 8032.
SeedSize = 32
) )
var cdc = amino.NewCodec()
func init() {
cdc.RegisterInterface((*crypto.PubKey)(nil), nil)
cdc.RegisterConcrete(PubKey{},
PubKeyAminoName, nil)
cdc.RegisterInterface((*crypto.PrivKey)(nil), nil)
cdc.RegisterConcrete(PrivKey{},
PrivKeyAminoName, nil)
}
// PrivKey implements crypto.PrivKey. // PrivKey implements crypto.PrivKey.
type PrivKey [64]byte
type PrivKey []byte
// Bytes marshals the privkey using amino encoding.
// Bytes returns the privkey byte format.
func (privKey PrivKey) Bytes() []byte { func (privKey PrivKey) Bytes() []byte {
return cdc.MustMarshalBinaryBare(privKey)
return []byte(privKey)
} }
// Sign produces a signature on the provided message. // Sign produces a signature on the provided message.
@ -53,18 +47,18 @@ func (privKey PrivKey) Bytes() []byte {
// If these conditions aren't met, Sign will panic or produce an // If these conditions aren't met, Sign will panic or produce an
// incorrect signature. // incorrect signature.
func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
signatureBytes := ed25519.Sign(privKey[:], msg)
signatureBytes := ed25519.Sign(ed25519.PrivateKey(privKey), msg)
return signatureBytes, nil return signatureBytes, nil
} }
// PubKey gets the corresponding public key from the private key. // PubKey gets the corresponding public key from the private key.
//
// Panics if the private key is not initialized.
func (privKey PrivKey) PubKey() crypto.PubKey { func (privKey PrivKey) PubKey() crypto.PubKey {
privKeyBytes := [64]byte(privKey)
// If the latter 32 bytes of the privkey are all zero, privkey is not
// initialized.
initialized := false initialized := false
// If the latter 32 bytes of the privkey are all zero, compute the pubkey
// otherwise privkey is initialized and we can use the cached value inside
// of the private key.
for _, v := range privKeyBytes[32:] {
for _, v := range privKey[32:] {
if v != 0 { if v != 0 {
initialized = true initialized = true
break break
@ -75,8 +69,8 @@ func (privKey PrivKey) PubKey() crypto.PubKey {
panic("Expected ed25519 PrivKey to include concatenated pubkey bytes") panic("Expected ed25519 PrivKey to include concatenated pubkey bytes")
} }
var pubkeyBytes [PubKeySize]byte
copy(pubkeyBytes[:], privKeyBytes[32:])
pubkeyBytes := make([]byte, PubKeySize)
copy(pubkeyBytes, privKey[32:])
return PubKey(pubkeyBytes) return PubKey(pubkeyBytes)
} }
@ -99,16 +93,14 @@ func GenPrivKey() PrivKey {
// genPrivKey generates a new ed25519 private key using the provided reader. // genPrivKey generates a new ed25519 private key using the provided reader.
func genPrivKey(rand io.Reader) PrivKey { func genPrivKey(rand io.Reader) PrivKey {
seed := make([]byte, 32)
seed := make([]byte, SeedSize)
_, err := io.ReadFull(rand, seed) _, err := io.ReadFull(rand, seed)
if err != nil { if err != nil {
panic(err) panic(err)
} }
privKey := ed25519.NewKeyFromSeed(seed)
var privKeyEd PrivKey
copy(privKeyEd[:], privKey)
return privKeyEd
return PrivKey(ed25519.NewKeyFromSeed(seed))
} }
// GenPrivKeyFromSecret hashes the secret with SHA2, and uses // GenPrivKeyFromSecret hashes the secret with SHA2, and uses
@ -118,34 +110,27 @@ func genPrivKey(rand io.Reader) PrivKey {
func GenPrivKeyFromSecret(secret []byte) PrivKey { func GenPrivKeyFromSecret(secret []byte) PrivKey {
seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes. seed := crypto.Sha256(secret) // Not Ripemd160 because we want 32 bytes.
privKey := ed25519.NewKeyFromSeed(seed)
var privKeyEd PrivKey
copy(privKeyEd[:], privKey)
return privKeyEd
return PrivKey(ed25519.NewKeyFromSeed(seed))
} }
//------------------------------------- //-------------------------------------
var _ crypto.PubKey = PubKey{} var _ crypto.PubKey = PubKey{}
// PubKeySize is the number of bytes in an Ed25519 signature.
const PubKeySize = 32
// PubKey implements crypto.PubKey for the Ed25519 signature scheme.
type PubKey [PubKeySize]byte
// PubKeyEd25519 implements crypto.PubKey for the Ed25519 signature scheme.
type PubKey []byte
// Address is the SHA256-20 of the raw pubkey bytes. // Address is the SHA256-20 of the raw pubkey bytes.
func (pubKey PubKey) Address() crypto.Address { func (pubKey PubKey) Address() crypto.Address {
return crypto.Address(tmhash.SumTruncated(pubKey[:]))
if len(pubKey) != PubKeySize {
panic("pubkey is incorrect size")
}
return crypto.Address(tmhash.SumTruncated(pubKey))
} }
// Bytes marshals the PubKey using amino encoding.
// Bytes returns the PubKey byte format.
func (pubKey PubKey) Bytes() []byte { func (pubKey PubKey) Bytes() []byte {
bz, err := cdc.MarshalBinaryBare(pubKey)
if err != nil {
panic(err)
}
return bz
return []byte(pubKey)
} }
func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool { func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
@ -153,11 +138,11 @@ func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
if len(sig) != SignatureSize { if len(sig) != SignatureSize {
return false return false
} }
return ed25519.Verify(pubKey[:], msg, sig)
return ed25519.Verify(ed25519.PublicKey(pubKey), msg, sig)
} }
func (pubKey PubKey) String() string { func (pubKey PubKey) String() string {
return fmt.Sprintf("PubKey{%X}", pubKey[:])
return fmt.Sprintf("PubKeyEd25519{%X}", []byte(pubKey))
} }
func (pubKey PubKey) Equals(other crypto.PubKey) bool { func (pubKey PubKey) Equals(other crypto.PubKey) bool {


+ 18
- 0
crypto/ed25519/encoding.go View File

@ -0,0 +1,18 @@
package ed25519
import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/crypto"
)
var cdc = amino.NewCodec()
func init() {
cdc.RegisterInterface((*crypto.PubKey)(nil), nil)
cdc.RegisterConcrete(PubKey{},
PubKeyAminoName, nil)
cdc.RegisterInterface((*crypto.PrivKey)(nil), nil)
cdc.RegisterConcrete(PrivKey{},
PrivKeyAminoName, nil)
}

+ 7
- 20
crypto/encoding/amino/encode_test.go View File

@ -1,7 +1,6 @@
package cryptoamino package cryptoamino
import ( import (
"os"
"reflect" "reflect"
"testing" "testing"
@ -17,17 +16,20 @@ import (
"github.com/tendermint/tendermint/crypto/sr25519" "github.com/tendermint/tendermint/crypto/sr25519"
) )
type byter interface {
Bytes() []byte
type AminoMarshal interface {
AminoMarshal() ([]byte, error)
AminoUnmarshal([]byte) error
} }
func checkAminoBinary(t *testing.T, src, dst interface{}, size int) { func checkAminoBinary(t *testing.T, src, dst interface{}, size int) {
// Marshal to binary bytes. // Marshal to binary bytes.
bz, err := cdc.MarshalBinaryBare(src) bz, err := cdc.MarshalBinaryBare(src)
require.Nil(t, err, "%+v", err) require.Nil(t, err, "%+v", err)
if byterSrc, ok := src.(byter); ok {
if byterSrc, ok := src.(AminoMarshal); ok {
// Make sure this is compatible with current (Bytes()) encoding. // Make sure this is compatible with current (Bytes()) encoding.
assert.Equal(t, byterSrc.Bytes(), bz, "Amino binary vs Bytes() mismatch")
bza, err := byterSrc.AminoMarshal()
assert.NoError(t, err)
assert.Equal(t, bza, bz, "Amino binary vs Bytes() mismatch")
} }
// Make sure we have the expected length. // Make sure we have the expected length.
assert.Equal(t, size, len(bz), "Amino binary size mismatch") assert.Equal(t, size, len(bz), "Amino binary size mismatch")
@ -52,21 +54,6 @@ func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool)
require.Nil(t, err, "%+v", err) require.Nil(t, err, "%+v", err)
} }
// ExamplePrintRegisteredTypes refers to unknown identifier: PrintRegisteredTypes
//nolint:govet
func ExamplePrintRegisteredTypes() {
cdc.PrintTypes(os.Stdout)
// Output: | Type | Name | Prefix | Length | Notes |
//| ---- | ---- | ------ | ----- | ------ |
//| PubKey | tendermint/PubKeyEd25519 | 0x1624DE64 | 0x20 | |
//| PubKey | tendermint/PubKeySr25519 | 0x0DFB1005 | 0x20 | |
//| PubKey | tendermint/PubKeySecp256k1 | 0xEB5AE987 | 0x21 | |
//| PubKey | tendermint/PubKeyMultisigThreshold | 0x22C1F7E2 | variable | |
//| PrivKey | tendermint/PrivKeyEd25519 | 0xA3288910 | 0x40 | |
//| PrivKey | tendermint/PrivKeySr25519 | 0x2F82D78B | 0x20 | |
//| PrivKey | tendermint/PrivKeySecp256k1 | 0xE1B0F79B | 0x20 | |
}
func TestKeyEncodings(t *testing.T) { func TestKeyEncodings(t *testing.T) {
cases := []struct { cases := []struct {
privKey crypto.PrivKey privKey crypto.PrivKey


+ 6
- 6
crypto/encoding/codec.go View File

@ -16,7 +16,7 @@ func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
case ed25519.PubKey: case ed25519.PubKey:
kp = pc.PublicKey{ kp = pc.PublicKey{
Sum: &pc.PublicKey_Ed25519{ Sum: &pc.PublicKey_Ed25519{
Ed25519: k[:],
Ed25519: k,
}, },
} }
default: default:
@ -33,8 +33,8 @@ func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) {
return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d", return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
len(k.Ed25519), ed25519.PubKeySize) len(k.Ed25519), ed25519.PubKeySize)
} }
var pk ed25519.PubKey
copy(pk[:], k.Ed25519)
pk := make(ed25519.PubKey, ed25519.PubKeySize)
copy(pk, k.Ed25519)
return pk, nil return pk, nil
default: default:
return nil, fmt.Errorf("fromproto: key type %v is not supported", k) return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
@ -48,7 +48,7 @@ func PrivKeyToProto(k crypto.PrivKey) (pc.PrivateKey, error) {
case ed25519.PrivKey: case ed25519.PrivKey:
kp = pc.PrivateKey{ kp = pc.PrivateKey{
Sum: &pc.PrivateKey_Ed25519{ Sum: &pc.PrivateKey_Ed25519{
Ed25519: k[:],
Ed25519: k,
}, },
} }
default: default:
@ -66,8 +66,8 @@ func PrivKeyFromProto(k pc.PrivateKey) (crypto.PrivKey, error) {
return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d", return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
len(k.Ed25519), ed25519.PubKeySize) len(k.Ed25519), ed25519.PubKeySize)
} }
var pk ed25519.PrivKey
copy(pk[:], k.Ed25519)
pk := make(ed25519.PrivKey, ed25519.PrivateKeySize)
copy(pk, k.Ed25519)
return pk, nil return pk, nil
default: default:
return nil, errors.New("fromproto: key type not supported") return nil, errors.New("fromproto: key type not supported")


+ 23
- 0
crypto/secp256k1/encoding.go View File

@ -0,0 +1,23 @@
package secp256k1
import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/crypto"
)
const (
PrivKeyAminoName = "tendermint/PrivKeySecp256k1"
PubKeyAminoName = "tendermint/PubKeySecp256k1"
)
var cdc = amino.NewCodec()
func init() {
cdc.RegisterInterface((*crypto.PubKey)(nil), nil)
cdc.RegisterConcrete(PubKey{},
PubKeyAminoName, nil)
cdc.RegisterInterface((*crypto.PrivKey)(nil), nil)
cdc.RegisterConcrete(PrivKey{},
PrivKeyAminoName, nil)
}

+ 19
- 41
crypto/secp256k1/secp256k1.go View File

@ -11,48 +11,26 @@ import (
secp256k1 "github.com/btcsuite/btcd/btcec" secp256k1 "github.com/btcsuite/btcd/btcec"
"golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto"
) )
//-------------------------------------
const (
PrivKeyAminoName = "tendermint/PrivKeySecp256k1"
PubKeyAminoName = "tendermint/PubKeySecp256k1"
)
var cdc = amino.NewCodec()
func init() {
cdc.RegisterInterface((*crypto.PubKey)(nil), nil)
cdc.RegisterConcrete(PubKey{},
PubKeyAminoName, nil)
cdc.RegisterInterface((*crypto.PrivKey)(nil), nil)
cdc.RegisterConcrete(PrivKey{},
PrivKeyAminoName, nil)
}
//-------------------------------------
var _ crypto.PrivKey = PrivKey{} var _ crypto.PrivKey = PrivKey{}
const PrivKeySize = 32
// PrivKey implements PrivKey. // PrivKey implements PrivKey.
type PrivKey [32]byte
type PrivKey []byte
// Bytes marshalls the private key using amino encoding. // Bytes marshalls the private key using amino encoding.
func (privKey PrivKey) Bytes() []byte { func (privKey PrivKey) Bytes() []byte {
return cdc.MustMarshalBinaryBare(privKey)
return []byte(privKey)
} }
// PubKey performs the point-scalar multiplication from the privKey on the // PubKey performs the point-scalar multiplication from the privKey on the
// generator point to get the pubkey. // generator point to get the pubkey.
func (privKey PrivKey) PubKey() crypto.PubKey { func (privKey PrivKey) PubKey() crypto.PubKey {
_, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
var pubkeyBytes PubKey
copy(pubkeyBytes[:], pubkeyObject.SerializeCompressed())
return pubkeyBytes
_, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
return PubKey(pubkeyObject.SerializeCompressed())
} }
// Equals - you probably don't need to use this. // Equals - you probably don't need to use this.
@ -72,10 +50,10 @@ func GenPrivKey() PrivKey {
// genPrivKey generates a new secp256k1 private key using the provided reader. // genPrivKey generates a new secp256k1 private key using the provided reader.
func genPrivKey(rand io.Reader) PrivKey { func genPrivKey(rand io.Reader) PrivKey {
var privKeyBytes [32]byte
var privKeyBytes [PrivKeySize]byte
d := new(big.Int) d := new(big.Int)
for { for {
privKeyBytes = [32]byte{}
privKeyBytes = [PrivKeySize]byte{}
_, err := io.ReadFull(rand, privKeyBytes[:]) _, err := io.ReadFull(rand, privKeyBytes[:])
if err != nil { if err != nil {
panic(err) panic(err)
@ -89,7 +67,7 @@ func genPrivKey(rand io.Reader) PrivKey {
} }
} }
return PrivKey(privKeyBytes)
return PrivKey(privKeyBytes[:])
} }
var one = new(big.Int).SetInt64(1) var one = new(big.Int).SetInt64(1)
@ -116,7 +94,7 @@ func GenPrivKeySecp256k1(secret []byte) PrivKey {
fe.Add(fe, one) fe.Add(fe, one)
feB := fe.Bytes() feB := fe.Bytes()
var privKey32 [32]byte
privKey32 := make([]byte, PrivKeySize)
// copy feB over to fixed 32 byte privKey32 and pad (if necessary) // copy feB over to fixed 32 byte privKey32 and pad (if necessary)
copy(privKey32[32-len(feB):32], feB) copy(privKey32[32-len(feB):32], feB)
@ -136,12 +114,16 @@ const PubKeySize = 33
// if the y-coordinate is the lexicographically largest of the two associated with // if the y-coordinate is the lexicographically largest of the two associated with
// the x-coordinate. Otherwise the first byte is a 0x03. // the x-coordinate. Otherwise the first byte is a 0x03.
// This prefix is followed with the x-coordinate. // This prefix is followed with the x-coordinate.
type PubKey [PubKeySize]byte
type PubKey []byte
// Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey)) // Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
func (pubKey PubKey) Address() crypto.Address { func (pubKey PubKey) Address() crypto.Address {
if len(pubKey) != PubKeySize {
panic("length of pubkey is incorrect")
}
hasherSHA256 := sha256.New() hasherSHA256 := sha256.New()
hasherSHA256.Write(pubKey[:]) // does not error
hasherSHA256.Write(pubKey) // does not error
sha := hasherSHA256.Sum(nil) sha := hasherSHA256.Sum(nil)
hasherRIPEMD160 := ripemd160.New() hasherRIPEMD160 := ripemd160.New()
@ -149,17 +131,13 @@ func (pubKey PubKey) Address() crypto.Address {
return crypto.Address(hasherRIPEMD160.Sum(nil)) return crypto.Address(hasherRIPEMD160.Sum(nil))
} }
// Bytes returns the pubkey marshalled with amino encoding.
// Bytes returns the pubkey byte format.
func (pubKey PubKey) Bytes() []byte { func (pubKey PubKey) Bytes() []byte {
bz, err := cdc.MarshalBinaryBare(pubKey)
if err != nil {
panic(err)
}
return bz
return []byte(pubKey)
} }
func (pubKey PubKey) String() string { func (pubKey PubKey) String() string {
return fmt.Sprintf("PubKey{%X}", pubKey[:])
return fmt.Sprintf("PubKeySecp256k1{%X}", []byte(pubKey))
} }
func (pubKey PubKey) Equals(other crypto.PubKey) bool { func (pubKey PubKey) Equals(other crypto.PubKey) bool {


+ 3
- 5
crypto/secp256k1/secp256k1_test.go View File

@ -36,15 +36,13 @@ func TestPubKeySecp256k1Address(t *testing.T) {
addrBbz, _, _ := base58.CheckDecode(d.addr) addrBbz, _, _ := base58.CheckDecode(d.addr)
addrB := crypto.Address(addrBbz) addrB := crypto.Address(addrBbz)
var priv secp256k1.PrivKey
copy(priv[:], privB)
var priv secp256k1.PrivKey = privB
pubKey := priv.PubKey() pubKey := priv.PubKey()
pubT, _ := pubKey.(secp256k1.PubKey) pubT, _ := pubKey.(secp256k1.PubKey)
pub := pubT[:]
addr := pubKey.Address()
assert.Equal(t, pub, pubB, "Expected pub keys to match")
addr := pubKey.Address()
assert.Equal(t, pubT, secp256k1.PubKey(pubB), "Expected pub keys to match")
assert.Equal(t, addr, addrB, "Expected addresses to match") assert.Equal(t, addr, addrB, "Expected addresses to match")
} }
} }


crypto/sr25519/codec.go → crypto/sr25519/encoding.go View File


+ 15
- 9
crypto/sr25519/privkey.go View File

@ -13,17 +13,19 @@ import (
// PrivKeySize is the number of bytes in an Sr25519 private key. // PrivKeySize is the number of bytes in an Sr25519 private key.
const PrivKeySize = 32 const PrivKeySize = 32
// PrivKey implements crypto.PrivKey.
type PrivKey [PrivKeySize]byte
// PrivKeySr25519 implements crypto.PrivKey.
type PrivKey []byte
// Bytes marshals the privkey using amino encoding. // Bytes marshals the privkey using amino encoding.
func (privKey PrivKey) Bytes() []byte { func (privKey PrivKey) Bytes() []byte {
return cdc.MustMarshalBinaryBare(privKey)
return []byte(privKey)
} }
// Sign produces a signature on the provided message. // Sign produces a signature on the provided message.
func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
miniSecretKey, err := schnorrkel.NewMiniSecretKeyFromRaw(privKey)
var p [PrivKeySize]byte
copy(p[:], privKey)
miniSecretKey, err := schnorrkel.NewMiniSecretKeyFromRaw(p)
if err != nil { if err != nil {
return []byte{}, err return []byte{}, err
} }
@ -42,7 +44,9 @@ func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
// PubKey gets the corresponding public key from the private key. // PubKey gets the corresponding public key from the private key.
func (privKey PrivKey) PubKey() crypto.PubKey { func (privKey PrivKey) PubKey() crypto.PubKey {
miniSecretKey, err := schnorrkel.NewMiniSecretKeyFromRaw(privKey)
var p [PrivKeySize]byte
copy(p[:], privKey)
miniSecretKey, err := schnorrkel.NewMiniSecretKeyFromRaw(p)
if err != nil { if err != nil {
panic(fmt.Sprintf("Invalid private key: %v", err)) panic(fmt.Sprintf("Invalid private key: %v", err))
} }
@ -52,8 +56,8 @@ func (privKey PrivKey) PubKey() crypto.PubKey {
if err != nil { if err != nil {
panic(fmt.Sprintf("Could not generate public key: %v", err)) panic(fmt.Sprintf("Could not generate public key: %v", err))
} }
return PubKey(pubkey.Encode())
key := pubkey.Encode()
return PubKey(key[:])
} }
// Equals - you probably don't need to use this. // Equals - you probably don't need to use this.
@ -84,7 +88,8 @@ func genPrivKey(rand io.Reader) PrivKey {
copy(seed[:], out) copy(seed[:], out)
return schnorrkel.NewMiniSecretKey(seed).ExpandEd25519().Encode()
key := schnorrkel.NewMiniSecretKey(seed).ExpandEd25519().Encode()
return key[:]
} }
// GenPrivKeyFromSecret hashes the secret with SHA2, and uses // GenPrivKeyFromSecret hashes the secret with SHA2, and uses
@ -96,5 +101,6 @@ func GenPrivKeyFromSecret(secret []byte) PrivKey {
var bz [PrivKeySize]byte var bz [PrivKeySize]byte
copy(bz[:], seed) copy(bz[:], seed)
privKey, _ := schnorrkel.NewMiniSecretKeyFromRaw(bz) privKey, _ := schnorrkel.NewMiniSecretKeyFromRaw(bz)
return privKey.ExpandEd25519().Encode()
key := privKey.ExpandEd25519().Encode()
return key[:]
} }

+ 7
- 9
crypto/sr25519/pubkey.go View File

@ -15,8 +15,8 @@ var _ crypto.PubKey = PubKey{}
// PubKeySize is the number of bytes in an Sr25519 public key. // PubKeySize is the number of bytes in an Sr25519 public key.
const PubKeySize = 32 const PubKeySize = 32
// PubKey implements crypto.PubKey for the Sr25519 signature scheme.
type PubKey [PubKeySize]byte
// PubKeySr25519 implements crypto.PubKey for the Sr25519 signature scheme.
type PubKey []byte
// Address is the SHA256-20 of the raw pubkey bytes. // Address is the SHA256-20 of the raw pubkey bytes.
func (pubKey PubKey) Address() crypto.Address { func (pubKey PubKey) Address() crypto.Address {
@ -25,11 +25,7 @@ func (pubKey PubKey) Address() crypto.Address {
// Bytes marshals the PubKey using amino encoding. // Bytes marshals the PubKey using amino encoding.
func (pubKey PubKey) Bytes() []byte { func (pubKey PubKey) Bytes() []byte {
bz, err := cdc.MarshalBinaryBare(pubKey)
if err != nil {
panic(err)
}
return bz
return []byte(pubKey)
} }
func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool { func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
@ -41,7 +37,9 @@ func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
copy(sig64[:], sig) copy(sig64[:], sig)
publicKey := &(schnorrkel.PublicKey{}) publicKey := &(schnorrkel.PublicKey{})
err := publicKey.Decode(pubKey)
var p [PubKeySize]byte
copy(p[:], pubKey)
err := publicKey.Decode(p)
if err != nil { if err != nil {
return false return false
} }
@ -58,7 +56,7 @@ func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
} }
func (pubKey PubKey) String() string { func (pubKey PubKey) String() string {
return fmt.Sprintf("PubKey{%X}", pubKey[:])
return fmt.Sprintf("PubKeySr25519{%X}", []byte(pubKey))
} }
// Equals - checks that two public keys are the same time // Equals - checks that two public keys are the same time


+ 2
- 4
privval/file_test.go View File

@ -119,10 +119,8 @@ func TestUnmarshalValidatorKey(t *testing.T) {
privKey := ed25519.GenPrivKey() privKey := ed25519.GenPrivKey()
pubKey := privKey.PubKey() pubKey := privKey.PubKey()
addr := pubKey.Address() addr := pubKey.Address()
pubArray := [32]byte(pubKey.(ed25519.PubKey))
pubBytes := pubArray[:]
privArray := [64]byte(privKey)
privBytes := privArray[:]
pubBytes := []byte(pubKey.(ed25519.PubKey))
privBytes := []byte(privKey)
pubB64 := base64.StdEncoding.EncodeToString(pubBytes) pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
privB64 := base64.StdEncoding.EncodeToString(privBytes) privB64 := base64.StdEncoding.EncodeToString(privBytes)


+ 1
- 1
rpc/client/evidence_test.go View File

@ -124,7 +124,7 @@ func TestBroadcastEvidence_DuplicateVoteEvidence(t *testing.T) {
client.WaitForHeight(c, status.SyncInfo.LatestBlockHeight+2, nil) client.WaitForHeight(c, status.SyncInfo.LatestBlockHeight+2, nil)
ed25519pub := pv.Key.PubKey.(ed25519.PubKey) ed25519pub := pv.Key.PubKey.(ed25519.PubKey)
rawpub := ed25519pub[:]
rawpub := ed25519pub.Bytes()
result2, err := c.ABCIQuery("/val", rawpub) result2, err := c.ABCIQuery("/val", rawpub)
require.NoError(t, err) require.NoError(t, err)
qres := result2.Response qres := result2.Response


+ 2
- 1
tools/tm-signer-harness/internal/test_harness.go View File

@ -1,6 +1,7 @@
package internal package internal
import ( import (
"bytes"
"fmt" "fmt"
"net" "net"
"os" "os"
@ -200,7 +201,7 @@ func (th *TestHarness) TestPublicKey() error {
return err return err
} }
th.logger.Info("Remote", "pubKey", sck) th.logger.Info("Remote", "pubKey", sck)
if fpvk != sck {
if !bytes.Equal(fpvk.Bytes(), sck.Bytes()) {
th.logger.Error("FAILED: Local and remote public keys do not match") th.logger.Error("FAILED: Local and remote public keys do not match")
return newTestHarnessError(ErrTestPublicKeyFailed, nil, "") return newTestHarnessError(ErrTestPublicKeyFailed, nil, "")
} }


+ 1
- 1
tools/tm-signer-harness/main.go View File

@ -135,7 +135,7 @@ func extractKey(tmhome, outputPath string) {
keyFile := filepath.Join(internal.ExpandPath(tmhome), "config", "priv_validator_key.json") keyFile := filepath.Join(internal.ExpandPath(tmhome), "config", "priv_validator_key.json")
stateFile := filepath.Join(internal.ExpandPath(tmhome), "data", "priv_validator_state.json") stateFile := filepath.Join(internal.ExpandPath(tmhome), "data", "priv_validator_state.json")
fpv := privval.LoadFilePV(keyFile, stateFile) fpv := privval.LoadFilePV(keyFile, stateFile)
pkb := [64]byte(fpv.Key.PrivKey.(ed25519.PrivKey))
pkb := []byte(fpv.Key.PrivKey.(ed25519.PrivKey))
if err := ioutil.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0600); err != nil { if err := ioutil.WriteFile(internal.ExpandPath(outputPath), pkb[:32], 0600); err != nil {
logger.Info("Failed to write private key", "output", outputPath, "err", err) logger.Info("Failed to write private key", "output", outputPath, "err", err)
os.Exit(1) os.Exit(1)


+ 1
- 1
types/block.go View File

@ -1090,7 +1090,7 @@ func (data *EvidenceData) StringIndented(indent string) string {
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
// BlockID defines the unique ID of a block as its Hash and its PartSetHeader
// BlockID
type BlockID struct { type BlockID struct {
Hash tmbytes.HexBytes `json:"hash"` Hash tmbytes.HexBytes `json:"hash"`
PartsHeader PartSetHeader `json:"parts"` PartsHeader PartSetHeader `json:"parts"`


+ 1
- 1
types/proto3_test.go View File

@ -4,7 +4,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/golang/protobuf/proto" // nolint: staticcheck // still used by gogoproto
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/types/proto3" "github.com/tendermint/tendermint/types/proto3"


+ 6
- 6
types/protobuf.go View File

@ -209,24 +209,24 @@ func (pb2tm) PubKey(pubKey abci.PubKey) (crypto.PubKey, error) {
return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d", return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
len(pubKey.Data), ed25519.PubKeySize) len(pubKey.Data), ed25519.PubKeySize)
} }
var pk ed25519.PubKey
copy(pk[:], pubKey.Data)
var pk = make(ed25519.PubKey, ed25519.PubKeySize)
copy(pk, pubKey.Data)
return pk, nil return pk, nil
case ABCIPubKeyTypeSr25519: case ABCIPubKeyTypeSr25519:
if len(pubKey.Data) != sr25519.PubKeySize { if len(pubKey.Data) != sr25519.PubKeySize {
return nil, fmt.Errorf("invalid size for PubKeySr25519. Got %d, expected %d", return nil, fmt.Errorf("invalid size for PubKeySr25519. Got %d, expected %d",
len(pubKey.Data), sr25519.PubKeySize) len(pubKey.Data), sr25519.PubKeySize)
} }
var pk sr25519.PubKey
copy(pk[:], pubKey.Data)
var pk = make(sr25519.PubKey, sr25519.PubKeySize)
copy(pk, pubKey.Data)
return pk, nil return pk, nil
case ABCIPubKeyTypeSecp256k1: case ABCIPubKeyTypeSecp256k1:
if len(pubKey.Data) != secp256k1.PubKeySize { if len(pubKey.Data) != secp256k1.PubKeySize {
return nil, fmt.Errorf("invalid size for PubKeySecp256k1. Got %d, expected %d", return nil, fmt.Errorf("invalid size for PubKeySecp256k1. Got %d, expected %d",
len(pubKey.Data), secp256k1.PubKeySize) len(pubKey.Data), secp256k1.PubKeySize)
} }
var pk secp256k1.PubKey
copy(pk[:], pubKey.Data)
var pk = make(secp256k1.PubKey, secp256k1.PubKeySize)
copy(pk, pubKey.Data)
return pk, nil return pk, nil
default: default:
return nil, fmt.Errorf("unknown pubkey type %v", pubKey.Type) return nil, fmt.Errorf("unknown pubkey type %v", pubKey.Type)


+ 1
- 1
types/protobuf_test.go View File

@ -4,7 +4,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/golang/protobuf/proto" // nolint: staticcheck // still used by gogoproto
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"


+ 3
- 3
types/validator_set_test.go View File

@ -360,9 +360,9 @@ func newValidator(address []byte, power int64) *Validator {
} }
func randPubKey() crypto.PubKey { func randPubKey() crypto.PubKey {
var pubKey [32]byte
copy(pubKey[:], tmrand.Bytes(32))
return ed25519.PubKey(pubKey)
pubKey := make(ed25519.PubKey, ed25519.PubKeySize)
copy(pubKey, tmrand.Bytes(32))
return ed25519.PubKey(tmrand.Bytes(32))
} }
func randValidator(totalVotingPower int64) *Validator { func randValidator(totalVotingPower int64) *Validator {


Loading…
Cancel
Save