diff --git a/sei-cosmos/crypto/codec/tm.go b/sei-cosmos/crypto/codec/tm.go index 3adc02dc8b..f71231be39 100644 --- a/sei-cosmos/crypto/codec/tm.go +++ b/sei-cosmos/crypto/codec/tm.go @@ -1,9 +1,8 @@ package codec import ( - tmcrypto "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" - tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" + "github.com/tendermint/tendermint/crypto" + pb "github.com/tendermint/tendermint/proto/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" @@ -11,10 +10,10 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -// FromTmProtoPublicKey converts a TM's tmprotocrypto.PublicKey into our own PubKey. -func FromTmProtoPublicKey(protoPk tmprotocrypto.PublicKey) (cryptotypes.PubKey, error) { +// FromTmProtoPublicKey converts a TM's pb.PublicKey into our own PubKey. +func FromTmProtoPublicKey(protoPk pb.PublicKey) (cryptotypes.PubKey, error) { switch protoPk := protoPk.Sum.(type) { - case *tmprotocrypto.PublicKey_Ed25519: + case *pb.PublicKey_Ed25519: return &ed25519.PubKey{ Key: protoPk.Ed25519, }, nil @@ -23,33 +22,33 @@ func FromTmProtoPublicKey(protoPk tmprotocrypto.PublicKey) (cryptotypes.PubKey, } } -// ToTmProtoPublicKey converts our own PubKey to TM's tmprotocrypto.PublicKey. -func ToTmProtoPublicKey(pk cryptotypes.PubKey) (tmprotocrypto.PublicKey, error) { +// ToTmProtoPublicKey converts our own PubKey to TM's pb.PublicKey. +func ToTmProtoPublicKey(pk cryptotypes.PubKey) (pb.PublicKey, error) { switch pk := pk.(type) { case *ed25519.PubKey: - return tmprotocrypto.PublicKey{ - Sum: &tmprotocrypto.PublicKey_Ed25519{ + return pb.PublicKey{ + Sum: &pb.PublicKey_Ed25519{ Ed25519: pk.Key, }, }, nil case *secp256k1.PubKey: - return tmprotocrypto.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "secp256k1 consensus keys are not supported") + return pb.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "secp256k1 consensus keys are not supported") default: - return tmprotocrypto.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to Tendermint public key", pk) + return pb.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to Tendermint public key", pk) } } -// FromTmPubKeyInterface converts TM's tmcrypto.PubKey to our own PubKey. -func FromTmPubKeyInterface(tmPk tmcrypto.PubKey) (cryptotypes.PubKey, error) { - return FromTmProtoPublicKey(encoding.PubKeyToProto(tmPk)) +// FromTmPubKeyInterface converts TM's crypto.PubKey to our own PubKey. +func FromTmPubKeyInterface(tmPk crypto.PubKey) (cryptotypes.PubKey, error) { + return FromTmProtoPublicKey(crypto.PubKeyToProto(tmPk)) } -// ToTmPubKeyInterface converts our own PubKey to TM's tmcrypto.PubKey. -func ToTmPubKeyInterface(pk cryptotypes.PubKey) (tmcrypto.PubKey, error) { +// ToTmPubKeyInterface converts our own PubKey to TM's crypto.PubKey. +func ToTmPubKeyInterface(pk cryptotypes.PubKey) (crypto.PubKey, error) { tmProtoPk, err := ToTmProtoPublicKey(pk) if err != nil { - return tmcrypto.PubKey{}, err + return crypto.PubKey{}, err } - return encoding.PubKeyFromProto(tmProtoPk) + return crypto.PubKeyFromProto(tmProtoPk) } diff --git a/sei-cosmos/x/simulation/mock_tendermint.go b/sei-cosmos/x/simulation/mock_tendermint.go index bac06c106c..23e3552951 100644 --- a/sei-cosmos/x/simulation/mock_tendermint.go +++ b/sei-cosmos/x/simulation/mock_tendermint.go @@ -8,7 +8,7 @@ import ( "time" abci "github.com/tendermint/tendermint/abci/types" - cryptoenc "github.com/tendermint/tendermint/crypto/encoding" + "github.com/tendermint/tendermint/crypto" tmbytes "github.com/tendermint/tendermint/libs/bytes" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -69,7 +69,7 @@ func (vals mockValidators) randomProposer(r *rand.Rand) tmbytes.HexBytes { key := keys[r.Intn(len(keys))] proposer := vals[key].val - pk, err := cryptoenc.PubKeyFromProto(proposer.PubKey) + pk, err := crypto.PubKeyFromProto(proposer.PubKey) if err != nil { //nolint:wsl panic(err) } @@ -149,7 +149,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, event("begin_block", "signing", "missed") } - pubkey, err := cryptoenc.PubKeyFromProto(mVal.val.PubKey) + pubkey, err := crypto.PubKeyFromProto(mVal.val.PubKey) if err != nil { panic(err) } diff --git a/sei-tendermint/abci/example/kvstore/helpers.go b/sei-tendermint/abci/example/kvstore/helpers.go index a287a2f8ed..8fcab0c282 100644 --- a/sei-tendermint/abci/example/kvstore/helpers.go +++ b/sei-tendermint/abci/example/kvstore/helpers.go @@ -24,7 +24,10 @@ func RandVals(cnt int) []types.ValidatorUpdate { if err != nil { panic(err) } - res[i] = types.UpdateValidator(pubKey, int64(power), "") + res[i] = types.ValidatorUpdate{ + PubKey: crypto.PubKeyToProto(pubKey), + Power: int64(power), + } } return res } diff --git a/sei-tendermint/abci/example/kvstore/kvstore.go b/sei-tendermint/abci/example/kvstore/kvstore.go index 4c219f8db1..e36d9e1e0c 100644 --- a/sei-tendermint/abci/example/kvstore/kvstore.go +++ b/sei-tendermint/abci/example/kvstore/kvstore.go @@ -15,8 +15,8 @@ import ( "github.com/tendermint/tendermint/abci/example/code" "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/libs/log" cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto" "github.com/tendermint/tendermint/version" @@ -329,7 +329,7 @@ func (app *Application) Validators() (validators []types.ValidatorUpdate) { } func MakeValSetChangeTx(pubkey cryptoproto.PublicKey, power int64) []byte { - pk, err := encoding.PubKeyFromProto(pubkey) + pk, err := crypto.PubKeyFromProto(pubkey) if err != nil { panic(err) } @@ -379,12 +379,12 @@ func (app *Application) execValidatorTx(tx []byte) *types.ExecTxResult { Log: fmt.Sprintf("can't decode ed25519 key: %v", err), } } - return app.updateValidator(types.UpdateValidator(key, power, "")) + return app.updateValidator(types.ValidatorUpdate{PubKey: crypto.PubKeyToProto(key), Power: power}) } // add, update, or remove a validator func (app *Application) updateValidator(v types.ValidatorUpdate) *types.ExecTxResult { - pubkey, err := encoding.PubKeyFromProto(v.PubKey) + pubkey, err := crypto.PubKeyFromProto(v.PubKey) if err != nil { panic(fmt.Errorf("can't decode public key: %w", err)) } diff --git a/sei-tendermint/abci/tests/server/client.go b/sei-tendermint/abci/tests/server/client.go index 2b7f4bcb73..8c3f431576 100644 --- a/sei-tendermint/abci/tests/server/client.go +++ b/sei-tendermint/abci/tests/server/client.go @@ -24,7 +24,10 @@ func InitChain(ctx context.Context, client abciclient.Client) error { } // nolint:gosec // G404: Use of weak random number generator power := mrand.Int() - vals[i] = types.UpdateValidator(pubkey, int64(power), "") + vals[i] = types.ValidatorUpdate{ + PubKey: crypto.PubKeyToProto(pubkey), + Power: int64(power), + } } _, err := client.InitChain(ctx, &types.RequestInitChain{ Validators: vals, diff --git a/sei-tendermint/abci/types/pubkey.go b/sei-tendermint/abci/types/pubkey.go deleted file mode 100644 index c556e11f3b..0000000000 --- a/sei-tendermint/abci/types/pubkey.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -import ( - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" -) - -func UpdateValidator(pk crypto.PubKey, power int64, keyType string) ValidatorUpdate { - return ValidatorUpdate{ - PubKey: encoding.PubKeyToProto(pk), - Power: power, - } -} diff --git a/sei-tendermint/abci/types/types.go b/sei-tendermint/abci/types/types.go index c9bc0f8153..665a1a1008 100644 --- a/sei-tendermint/abci/types/types.go +++ b/sei-tendermint/abci/types/types.go @@ -6,7 +6,6 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/internal/jsontypes" ) @@ -133,7 +132,7 @@ type validatorUpdateJSON struct { } func (v *ValidatorUpdate) MarshalJSON() ([]byte, error) { - key, err := encoding.PubKeyFromProto(v.PubKey) + key, err := crypto.PubKeyFromProto(v.PubKey) if err != nil { return nil, err } @@ -156,7 +155,7 @@ func (v *ValidatorUpdate) UnmarshalJSON(data []byte) error { if err := jsontypes.Unmarshal(vu.PubKey, &key); err != nil { return err } - v.PubKey = encoding.PubKeyToProto(key) + v.PubKey = crypto.PubKeyToProto(key) v.Power = vu.Power return nil } diff --git a/sei-tendermint/crypto/conv.go b/sei-tendermint/crypto/conv.go new file mode 100644 index 0000000000..3ac8629d1a --- /dev/null +++ b/sei-tendermint/crypto/conv.go @@ -0,0 +1,35 @@ +package crypto + +import ( + "fmt" + + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/internal/jsontypes" + "github.com/tendermint/tendermint/libs/utils" + pb "github.com/tendermint/tendermint/proto/tendermint/crypto" +) + +func init() { + jsontypes.MustRegister((*pb.PublicKey)(nil)) + jsontypes.MustRegister((*pb.PublicKey_Ed25519)(nil)) +} + +var PubKeyConv = utils.ProtoConv[PubKey, *pb.PublicKey]{ + Encode: func(k PubKey) *pb.PublicKey { return utils.Alloc(PubKeyToProto(k)) }, + Decode: func(x *pb.PublicKey) (PubKey, error) { return PubKeyFromProto(*x) }, +} + +// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey +func PubKeyToProto(k PubKey) pb.PublicKey { + return pb.PublicKey{Sum: &pb.PublicKey_Ed25519{Ed25519: k.Bytes()}} +} + +// PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey +func PubKeyFromProto(k pb.PublicKey) (PubKey, error) { + switch k := k.Sum.(type) { + case *pb.PublicKey_Ed25519: + return ed25519.PublicKeyFromBytes(k.Ed25519) + default: + return PubKey{}, fmt.Errorf("fromproto: key type %v is not supported", k) + } +} diff --git a/sei-tendermint/crypto/ed25519/ed25519.go b/sei-tendermint/crypto/ed25519/ed25519.go index b17f3dda4f..9b0d7d073f 100644 --- a/sei-tendermint/crypto/ed25519/ed25519.go +++ b/sei-tendermint/crypto/ed25519/ed25519.go @@ -32,7 +32,7 @@ const cacheSize = 4096 // curve25519-voi's Ed25519 implementation supports configurable // verification behavior, and tendermint uses the ZIP-215 verification // semantics. -var verifyOptions = &ed25519.Options{Verify: ed25519.VerifyOptionsZIP_215} +var verifyOptions = ed25519.VerifyOptionsZIP_215 var cachingVerifier = cache.NewVerifier(cache.NewLRUCache(cacheSize)) // SecretKey represents a secret key in the Ed25519 signature scheme. @@ -129,26 +129,65 @@ func (k SecretKey) Sign(message []byte) Signature { } } +// Domain separation tag. +type Tag struct{ tag string } + +func NewTag(tag string) (Tag, error) { + if len(tag) > ed25519.ContextMaxSize { + return Tag{}, fmt.Errorf("len(%q) = %v, want <= %v", tag, len(tag), ed25519.ContextMaxSize) + } + return Tag{tag}, nil +} + +// SignWithTag signs a message with a domain separation tag. +// It is safe to assume that signatures for messages with different tags do not collide. +// It is also safe to assume that Sign() signatures do not collide with SignWithTag() signatures. +// It is secure to use the same secret key for signing with both Sign() and SignWithTag() [https://datatracker.ietf.org/doc/html/rfc8032#section-8.6]. +func (k SecretKey) SignWithTag(tag Tag, msg []byte) Signature { + opts := &ed25519.Options{Context: tag.tag} + // Returns no error if opts.Context is of correct size. + sig := utils.OrPanic1(ed25519.PrivateKey((*k.key)[:]).Sign(nil, msg, opts)) + return Signature{sig: [ed25519.SignatureSize]byte(sig)} +} + // Compare defines a total order on public keys. func (k PublicKey) Compare(other PublicKey) int { return bytes.Compare(k.key[:], other.key[:]) } -// Verify verifies a signature using the public key. +// Verify verifies a signature. func (k PublicKey) Verify(msg []byte, sig Signature) error { - if !cachingVerifier.VerifyWithOptions(k.key[:], msg, sig.sig[:], verifyOptions) { + opts := &ed25519.Options{Verify: verifyOptions} + if !cachingVerifier.VerifyWithOptions(k.key[:], msg, sig.sig[:], opts) { + return ErrBadSig{} + } + return nil +} + +// Verify verifies a signature, given domain separation tag. +func (k PublicKey) VerifyWithTag(tag Tag, msg []byte, sig Signature) error { + opts := &ed25519.Options{Context: tag.tag, Verify: verifyOptions} + if !cachingVerifier.VerifyWithOptions(k.key[:], msg, sig.sig[:], opts) { return ErrBadSig{} } return nil } // BatchVerifier implements batch verification for ed25519. -type BatchVerifier struct{ inner *ed25519.BatchVerifier } +type BatchVerifier struct { + inner *ed25519.BatchVerifier +} func NewBatchVerifier() *BatchVerifier { return &BatchVerifier{ed25519.NewBatchVerifier()} } func (b *BatchVerifier) Add(key PublicKey, msg []byte, sig Signature) { - cachingVerifier.AddWithOptions(b.inner, key.key[:], msg, sig.sig[:], verifyOptions) + opts := &ed25519.Options{Verify: verifyOptions} + cachingVerifier.AddWithOptions(b.inner, key.key[:], msg, sig.sig[:], opts) +} + +func (b *BatchVerifier) AddWithTag(key PublicKey, tag Tag, msg []byte, sig Signature) { + opts := &ed25519.Options{Context: tag.tag, Verify: verifyOptions} + cachingVerifier.AddWithOptions(b.inner, key.key[:], msg, sig.sig[:], opts) } // Verify verifies the batched signatures using OS entropy. diff --git a/sei-tendermint/crypto/ed25519/ed25519_test.go b/sei-tendermint/crypto/ed25519/ed25519_test.go index 3357e1e652..2ad4769e02 100644 --- a/sei-tendermint/crypto/ed25519/ed25519_test.go +++ b/sei-tendermint/crypto/ed25519/ed25519_test.go @@ -2,6 +2,7 @@ package ed25519 import ( "fmt" + "github.com/tendermint/tendermint/libs/utils" "github.com/tendermint/tendermint/libs/utils/require" "testing" ) @@ -22,22 +23,63 @@ func TestSign(t *testing.T) { } } -func TestBatchSafe(t *testing.T) { +func TestSignWithTag(t *testing.T) { + var keys []SecretKey + for i := range byte(3) { + keys = append(keys, TestSecretKey([]byte{i})) + } + t.Logf("keys = %+v", keys) + msg := []byte("test message") + tag := utils.OrPanic1(NewTag("testTag")) + for i := range keys { + for j := range keys { + if wantErr, err := i != j, keys[j].Public().VerifyWithTag(tag, msg, keys[i].SignWithTag(tag, msg)); wantErr != (err != nil) { + t.Errorf("keys[%d].Verify(keys[%d].Sign()) = %v, wantErr = %v", j, i, err, wantErr) + } + } + } +} + +func TestDomainSeparation(t *testing.T) { + msg := []byte("test message") + tag1 := utils.OrPanic1(NewTag("testTag")) + tag2 := utils.OrPanic1(NewTag("testTag2")) + k := TestSecretKey([]byte{34, 33}) + sigs := map[utils.Option[Tag]]Signature{} + sigs[utils.Some(tag1)] = k.SignWithTag(tag1, msg) + sigs[utils.Some(tag2)] = k.SignWithTag(tag2, msg) + sigs[utils.None[Tag]()] = k.Sign(msg) + for _, tag := range utils.Slice(utils.Some(tag1), utils.Some(tag2), utils.None[Tag]()) { + for wantTag, sig := range sigs { + var err error + if tag, ok := tag.Get(); ok { + err = k.Public().VerifyWithTag(tag, msg, sig) + } else { + err = k.Public().Verify(msg, sig) + } + require.Equal(t, err == nil, tag == wantTag, "err = %v", err) + } + } +} + +func TestBatchVerifier(t *testing.T) { v := NewBatchVerifier() + tag := utils.OrPanic1(NewTag("testTag")) - for i := 0; i <= 38; i++ { + for i := range 100 { priv := TestSecretKey(fmt.Appendf(nil, "test-%v", i)) pub := priv.Public() - var msg []byte if i%2 == 0 { msg = []byte("easter") } else { msg = []byte("egg") } - - v.Add(pub, msg, priv.Sign(msg)) + if i%3 == 0 { + v.AddWithTag(pub, tag, msg, priv.SignWithTag(tag, msg)) + } else { + v.Add(pub, msg, priv.Sign(msg)) + } } - require.NoError(t, v.Verify()) } diff --git a/sei-tendermint/crypto/encoding/codec.go b/sei-tendermint/crypto/encoding/codec.go deleted file mode 100644 index 210979e4d6..0000000000 --- a/sei-tendermint/crypto/encoding/codec.go +++ /dev/null @@ -1,30 +0,0 @@ -package encoding - -import ( - "fmt" - - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/internal/jsontypes" - cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto" -) - -func init() { - jsontypes.MustRegister((*cryptoproto.PublicKey)(nil)) - jsontypes.MustRegister((*cryptoproto.PublicKey_Ed25519)(nil)) -} - -// PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey -func PubKeyToProto(k crypto.PubKey) cryptoproto.PublicKey { - return cryptoproto.PublicKey{Sum: &cryptoproto.PublicKey_Ed25519{Ed25519: k.Bytes()}} -} - -// PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey -func PubKeyFromProto(k cryptoproto.PublicKey) (crypto.PubKey, error) { - switch k := k.Sum.(type) { - case *cryptoproto.PublicKey_Ed25519: - return ed25519.PublicKeyFromBytes(k.Ed25519) - default: - return crypto.PubKey{}, fmt.Errorf("fromproto: key type %v is not supported", k) - } -} diff --git a/sei-tendermint/internal/consensus/reactor_test.go b/sei-tendermint/internal/consensus/reactor_test.go index 0e75cfc5cd..1eb0e59fbb 100644 --- a/sei-tendermint/internal/consensus/reactor_test.go +++ b/sei-tendermint/internal/consensus/reactor_test.go @@ -19,7 +19,7 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto/encoding" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/internal/eventbus" "github.com/tendermint/tendermint/internal/mempool" "github.com/tendermint/tendermint/internal/p2p" @@ -501,7 +501,7 @@ func TestReactorValidatorSetChanges(t *testing.T) { pv, _ := states[nodeIdx].privValidator.Get() key, err := pv.GetPubKey(ctx) require.NoError(t, err) - keyProto := encoding.PubKeyToProto(key) + keyProto := crypto.PubKeyToProto(key) newPower := int64(rng.Intn(100000)) tx := kvstore.MakeValSetChangeTx(keyProto, newPower) require.NoError(t, finalizeTx(ctx, valSet, blocksSubs, states, tx)) diff --git a/sei-tendermint/internal/consensus/replay_test.go b/sei-tendermint/internal/consensus/replay_test.go index a63ea8a2f3..75b7d8d949 100644 --- a/sei-tendermint/internal/consensus/replay_test.go +++ b/sei-tendermint/internal/consensus/replay_test.go @@ -21,7 +21,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/internal/eventbus" "github.com/tendermint/tendermint/internal/mempool" "github.com/tendermint/tendermint/internal/proxy" @@ -343,7 +342,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { pv, _ := css[nVals].privValidator.Get() newValidatorPubKey1, err := pv.GetPubKey(ctx) require.NoError(t, err) - valPubKey1ABCI := encoding.PubKeyToProto(newValidatorPubKey1) + valPubKey1ABCI := crypto.PubKeyToProto(newValidatorPubKey1) newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) err = assertMempool(t, css[0].txNotifier).CheckTx(ctx, newValidatorTx1, nil, mempool.TxInfo{}) assert.NoError(t, err) @@ -379,7 +378,7 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { pv, _ = css[nVals].privValidator.Get() updateValidatorPubKey1, err := pv.GetPubKey(ctx) require.NoError(t, err) - updatePubKey1ABCI := encoding.PubKeyToProto(updateValidatorPubKey1) + updatePubKey1ABCI := crypto.PubKeyToProto(updateValidatorPubKey1) updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) err = assertMempool(t, css[0].txNotifier).CheckTx(ctx, updateValidatorTx1, nil, mempool.TxInfo{}) assert.NoError(t, err) @@ -414,14 +413,14 @@ func setupSimulator(ctx context.Context, t *testing.T) *simulatorTestSuite { pv, _ = css[nVals+1].privValidator.Get() newValidatorPubKey2, err := pv.GetPubKey(ctx) require.NoError(t, err) - newVal2ABCI := encoding.PubKeyToProto(newValidatorPubKey2) + newVal2ABCI := crypto.PubKeyToProto(newValidatorPubKey2) newValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower) err = assertMempool(t, css[0].txNotifier).CheckTx(ctx, newValidatorTx2, nil, mempool.TxInfo{}) assert.NoError(t, err) pv, _ = css[nVals+2].privValidator.Get() newValidatorPubKey3, err := pv.GetPubKey(ctx) require.NoError(t, err) - newVal3ABCI := encoding.PubKeyToProto(newValidatorPubKey3) + newVal3ABCI := crypto.PubKeyToProto(newValidatorPubKey3) newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) err = assertMempool(t, css[0].txNotifier).CheckTx(ctx, newValidatorTx3, nil, mempool.TxInfo{}) assert.NoError(t, err) diff --git a/sei-tendermint/internal/p2p/conn/connection.go b/sei-tendermint/internal/p2p/conn/connection.go index 571a9ced2e..381d6c8827 100644 --- a/sei-tendermint/internal/p2p/conn/connection.go +++ b/sei-tendermint/internal/p2p/conn/connection.go @@ -421,10 +421,10 @@ func (c *MConnection) recvRoutine(ctx context.Context) (err error) { recvPong.Store(true) } case *p2p.Packet_PacketMsg: - channelID, castOk := utils.SafeCast[ChannelID](p.PacketMsg.ChannelID) + channelID, castOk := utils.SafeCast[ChannelID](p.PacketMsg.ChannelId) ch, ok := channels[channelID] if !castOk || !ok { - return errBadChannel{fmt.Errorf("unknown channel %X", p.PacketMsg.ChannelID)} + return errBadChannel{fmt.Errorf("unknown channel %X", p.PacketMsg.ChannelId)} } c.logger.Debug("Read PacketMsg", "conn", c, "packet", packet) msgBytes, err := ch.pushMsg(p.PacketMsg) @@ -451,8 +451,8 @@ func (c *MConnection) maxPacketMsgSize() int { bz, err := proto.Marshal(&p2p.Packet{ Sum: &p2p.Packet_PacketMsg{ PacketMsg: &p2p.PacketMsg{ - ChannelID: 0x01, - EOF: true, + ChannelId: 0x01, + Eof: true, Data: make([]byte, c.config.MaxPacketMsgPayloadSize), }, }, @@ -477,12 +477,12 @@ func (ch *sendChannel) ratio() float32 { // Not goroutine-safe func (ch *sendChannel) popMsg(maxPayload int) *p2p.PacketMsg { payload := ch.queue.Get(0) - packet := &p2p.PacketMsg{ChannelID: int32(ch.desc.ID)} + packet := &p2p.PacketMsg{ChannelId: int32(ch.desc.ID)} if len(*payload) <= maxPayload { - packet.EOF = true + packet.Eof = true packet.Data = *ch.queue.PopFront() } else { - packet.EOF = false + packet.Eof = false packet.Data = (*payload)[:maxPayload] *payload = (*payload)[maxPayload:] } @@ -509,7 +509,7 @@ func (ch *recvChannel) pushMsg(packet *p2p.PacketMsg) ([]byte, error) { return nil, fmt.Errorf("received message exceeds available capacity: %v < %v", wantMax, got) } ch.buf = append(ch.buf, packet.Data...) - if packet.EOF { + if packet.Eof { msgBytes := ch.buf ch.buf = make([]byte, 0, ch.desc.RecvBufferCapacity) return msgBytes, nil diff --git a/sei-tendermint/internal/p2p/conn/connection_test.go b/sei-tendermint/internal/p2p/conn/connection_test.go index f493ed3463..85d9f6e1ea 100644 --- a/sei-tendermint/internal/p2p/conn/connection_test.go +++ b/sei-tendermint/internal/p2p/conn/connection_test.go @@ -36,8 +36,7 @@ func newMConnectionWithCh( cfg := DefaultMConnConfig() cfg.PingInterval = 250 * time.Millisecond cfg.PongTimeout = 500 * time.Millisecond - c := NewMConnection(log.NewNopLogger(), conn, chDescs, cfg) - return c + return NewMConnection(log.NewNopLogger(), conn, chDescs, cfg) } func mayDisconnectAfterDone(ctx context.Context, err error) error { @@ -202,8 +201,8 @@ func TestMConnectionReadErrorLongMessage(t *testing.T) { // send msg thats just right msg := &p2p.PacketMsg{ - ChannelID: 0x01, - EOF: true, + ChannelId: 0x01, + Eof: true, Data: make([]byte, mconn1.config.MaxPacketMsgPayloadSize), } packet := &p2p.Packet{ @@ -246,7 +245,7 @@ func TestConnVectors(t *testing.T) { {"PacketPong", pongMsg(), "1200"}, {"PacketMsg", &p2p.Packet{Sum: &p2p.Packet_PacketMsg{ PacketMsg: &p2p.PacketMsg{ - ChannelID: 1, EOF: false, Data: []byte("data transmitted over the wire"), + ChannelId: 1, Eof: false, Data: []byte("data transmitted over the wire"), }, }}, "1a2208011a1e64617461207472616e736d6974746564206f766572207468652077697265"}, } @@ -272,8 +271,8 @@ func TestMConnectionChannelOverflow(t *testing.T) { protoWriter := protoio.NewDelimitedWriter(c2) msg := &p2p.PacketMsg{ - ChannelID: int32(1025), - EOF: true, + ChannelId: int32(1025), + Eof: true, Data: []byte(`42`), } packet := &p2p.Packet{ diff --git a/sei-tendermint/internal/p2p/conn/evil_secret_connection_test.go b/sei-tendermint/internal/p2p/conn/evil_secret_connection_test.go index 0c5b68daf9..6d0610e992 100644 --- a/sei-tendermint/internal/p2p/conn/evil_secret_connection_test.go +++ b/sei-tendermint/internal/p2p/conn/evil_secret_connection_test.go @@ -4,21 +4,21 @@ import ( "bytes" "errors" "io" + "net" "testing" gogotypes "github.com/gogo/protobuf/types" - "github.com/oasisprotocol/curve25519-voi/primitives/merlin" - "github.com/stretchr/testify/assert" - "golang.org/x/crypto/chacha20poly1305" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/internal/libs/protoio" + "github.com/tendermint/tendermint/libs/utils" + "github.com/tendermint/tendermint/libs/utils/require" tmp2p "github.com/tendermint/tendermint/proto/tendermint/p2p" ) type buffer struct { + net.Conn next bytes.Buffer } @@ -39,13 +39,12 @@ func (b *buffer) Close() error { } type evilConn struct { - secretConn *SecretConnection - buffer *buffer + *SecretConnection + buffer *buffer - locEphPub *[32]byte - locEphPriv *[32]byte - remEphPub *[32]byte - privKey crypto.PrivKey + loc ephSecret + rem ephPublic + privKey crypto.PrivKey readStep int writeStep int @@ -58,22 +57,14 @@ type evilConn struct { } func newEvilConn(shareEphKey, badEphKey, shareAuthSignature, badAuthSignature bool) *evilConn { - privKey := ed25519.GenerateSecretKey() - locEphPub, locEphPriv := genEphKeys() - var rep [32]byte - c := &evilConn{ - locEphPub: locEphPub, - locEphPriv: locEphPriv, - remEphPub: &rep, - privKey: privKey, - + return &evilConn{ + loc: genEphKey(), + privKey: ed25519.GenerateSecretKey(), shareEphKey: shareEphKey, badEphKey: badEphKey, shareAuthSignature: shareAuthSignature, badAuthSignature: badAuthSignature, } - - return c } func (c *evilConn) Read(data []byte) (n int, err error) { @@ -84,8 +75,7 @@ func (c *evilConn) Read(data []byte) (n int, err error) { switch c.readStep { case 0: if !c.badEphKey { - lc := *c.locEphPub - bz, err := protoio.MarshalDelimited(&gogotypes.BytesValue{Value: lc[:]}) + bz, err := protoio.MarshalDelimited(&gogotypes.BytesValue{Value: c.loc.public[:]}) if err != nil { panic(err) } @@ -113,12 +103,12 @@ func (c *evilConn) Read(data []byte) (n int, err error) { case 1: signature := c.signChallenge() if !c.badAuthSignature { - pkpb := encoding.PubKeyToProto(c.privKey.Public()) + pkpb := crypto.PubKeyConv.Encode(c.privKey.Public()) bz, err := protoio.MarshalDelimited(&tmp2p.AuthSigMessage{PubKey: pkpb, Sig: signature.Bytes()}) if err != nil { panic(err) } - n, err = c.secretConn.Write(bz) + n, err = c.SecretConnection.Write(bz) if err != nil { panic(err) } @@ -131,7 +121,7 @@ func (c *evilConn) Read(data []byte) (n int, err error) { if err != nil { panic(err) } - n, err = c.secretConn.Write(bz) + n, err = c.SecretConnection.Write(bz) if err != nil { panic(err) } @@ -150,16 +140,9 @@ func (c *evilConn) Read(data []byte) (n int, err error) { func (c *evilConn) Write(data []byte) (n int, err error) { switch c.writeStep { case 0: - var ( - bytes gogotypes.BytesValue - remEphPub [32]byte - ) - err := protoio.UnmarshalDelimited(data, &bytes) - if err != nil { - panic(err) - } - copy(remEphPub[:], bytes.Value) - c.remEphPub = &remEphPub + var bytes gogotypes.BytesValue + utils.OrPanic(protoio.UnmarshalDelimited(data, &bytes)) + c.rem = ephPublic(bytes.Value) c.writeStep = 1 if !c.shareAuthSignature { c.writeStep = 2 @@ -178,84 +161,36 @@ func (c *evilConn) Close() error { } func (c *evilConn) signChallenge() ed25519.Signature { - // Sort by lexical order. - loEphPub, hiEphPub := sort32(c.locEphPub, c.remEphPub) - - transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH") - - transcript.AppendMessage(labelEphemeralLowerPublicKey, loEphPub[:]) - transcript.AppendMessage(labelEphemeralUpperPublicKey, hiEphPub[:]) - - // Check if the local ephemeral public key was the least, lexicographically - // sorted. - locIsLeast := bytes.Equal(c.locEphPub[:], loEphPub[:]) - - // Compute common diffie hellman secret using X25519. - dhSecret, err := computeDHSecret(c.remEphPub, c.locEphPriv) - if err != nil { - panic(err) - } - - transcript.AppendMessage(labelDHSecret, dhSecret[:]) - - // Generate the secret used for receiving, sending, challenge via HKDF-SHA2 - // on the transcript state (which itself also uses HKDF-SHA2 to derive a key - // from the dhSecret). - recvSecret, sendSecret := deriveSecrets(dhSecret, locIsLeast) - - const challengeSize = 32 - var challenge [challengeSize]byte - transcript.ExtractBytes(challenge[:], labelSecretConnectionMac) - - sendAead, err := chacha20poly1305.New(sendSecret[:]) - if err != nil { - panic(errors.New("invalid send SecretConnection Key")) - } - recvAead, err := chacha20poly1305.New(recvSecret[:]) - if err != nil { - panic(errors.New("invalid receive SecretConnection Key")) - } - b := &buffer{} - c.secretConn = &SecretConnection{ - conn: b, - recvBuffer: nil, - recvNonce: new([aeadNonceSize]byte), - sendNonce: new([aeadNonceSize]byte), - recvAead: recvAead, - sendAead: sendAead, - } + c.SecretConnection = newSecretConnection(b, c.loc, c.rem) c.buffer = b - - // Sign the challenge bytes for authentication. - return signChallenge(&challenge, c.privKey) + return c.privKey.Sign(c.challenge[:]) } // TestMakeSecretConnection creates an evil connection and tests that // MakeSecretConnection errors at different stages. func TestMakeSecretConnection(t *testing.T) { testCases := []struct { - name string - conn *evilConn - errMsg string + name string + conn *evilConn + err utils.Option[error] }{ - {"refuse to share ethimeral key", newEvilConn(false, false, false, false), "EOF"}, - {"share bad ethimeral key", newEvilConn(true, true, false, false), "wrong wireType"}, - {"refuse to share auth signature", newEvilConn(true, false, false, false), "EOF"}, - {"share bad auth signature", newEvilConn(true, false, true, true), "failed to decrypt SecretConnection"}, - {"all good", newEvilConn(true, false, true, false), ""}, + {"refuse to share ephemeral key", newEvilConn(false, false, false, false), utils.Some(errDH)}, + {"share bad ephemeral key", newEvilConn(true, true, false, false), utils.Some(errDH)}, + {"refuse to share auth signature", newEvilConn(true, false, false, false), utils.Some(io.EOF)}, + {"share bad auth signature", newEvilConn(true, false, true, true), utils.Some(errAEAD)}, + {"all good", newEvilConn(true, false, true, false), utils.None[error]()}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() privKey := ed25519.GenerateSecretKey() - _, err := MakeSecretConnection(tc.conn, privKey) - if tc.errMsg != "" { - if assert.Error(t, err) { - assert.Contains(t, err.Error(), tc.errMsg) - } + _, err := MakeSecretConnection(ctx, tc.conn, privKey) + if wantErr, ok := tc.err.Get(); ok { + require.True(t, errors.Is(err, wantErr), "got %v, want %v", err, wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/sei-tendermint/internal/p2p/conn/secret_connection.go b/sei-tendermint/internal/p2p/conn/secret_connection.go index 5988976ed9..079880a497 100644 --- a/sei-tendermint/internal/p2p/conn/secret_connection.go +++ b/sei-tendermint/internal/p2p/conn/secret_connection.go @@ -2,6 +2,7 @@ package conn import ( "bytes" + "context" "crypto/cipher" crand "crypto/rand" "crypto/sha256" @@ -11,7 +12,6 @@ import ( "io" "math" "net" - "sync" "time" gogotypes "github.com/gogo/protobuf/types" @@ -22,11 +22,11 @@ import ( "golang.org/x/crypto/hkdf" "golang.org/x/crypto/nacl/box" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/internal/libs/async" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/internal/libs/protoio" - tmproto "github.com/tendermint/tendermint/proto/tendermint/crypto" - tmp2p "github.com/tendermint/tendermint/proto/tendermint/p2p" + "github.com/tendermint/tendermint/libs/utils" + "github.com/tendermint/tendermint/libs/utils/scope" + pb "github.com/tendermint/tendermint/proto/tendermint/p2p" ) // 4 + 1024 == 1028 total frame size @@ -35,7 +35,6 @@ const ( dataMaxSize = 1024 totalFrameSize = dataMaxSize + dataLenSize aeadSizeOverhead = 16 // overhead of poly 1305 authentication tag - aeadKeySize = chacha20poly1305.KeySize aeadNonceSize = chacha20poly1305.NonceSize labelEphemeralLowerPublicKey = "EPHEMERAL_LOWER_PUBLIC_KEY" @@ -44,11 +43,36 @@ const ( labelSecretConnectionMac = "SECRET_CONNECTION_MAC" ) -var ( - ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer") +var ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer") +var secretConnKeyAndChallengeGen = []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN") - secretConnKeyAndChallengeGen = []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN") -) +type nonce [aeadNonceSize]byte + +// Increment nonce little-endian by 1 with wraparound. +// Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four +// bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes +// (little-endian in nonce[4:]). +func (n *nonce) inc() { + counter := binary.LittleEndian.Uint64(n[4:]) + if counter == math.MaxUint64 { + // Terminates the session and makes sure the nonce would not re-used. + // See https://github.com/tendermint/tendermint/issues/3531 + panic("can't increase nonce without overflow") + } + counter++ + binary.LittleEndian.PutUint64(n[4:], counter) +} + +type sendState struct { + cipher cipher.AEAD + nonce nonce +} + +type recvState struct { + cipher cipher.AEAD + buffer []byte + nonce nonce +} // SecretConnection implements net.Conn. // It is an implementation of the STS protocol. @@ -60,27 +84,36 @@ var ( // Otherwise they are vulnerable to MITM. // (TODO(ismail): see also https://github.com/tendermint/tendermint/issues/3010) type SecretConnection struct { + conn net.Conn + challenge [32]byte + recvState utils.Mutex[*recvState] + sendState utils.Mutex[*sendState] + remPubKey crypto.PubKey +} + +func newSecretConnection(conn net.Conn, loc ephSecret, rem ephPublic) *SecretConnection { + pubs := utils.Slice(loc.public, rem) + if bytes.Compare(pubs[0][:], pubs[1][:]) > 0 { + pubs[0], pubs[1] = pubs[1], pubs[0] + } + transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH") + transcript.AppendMessage(labelEphemeralLowerPublicKey, pubs[0][:]) + transcript.AppendMessage(labelEphemeralUpperPublicKey, pubs[1][:]) + dh := loc.DhSecret(rem) + transcript.AppendMessage(labelDHSecret, dh[:]) + var challenge [32]byte + transcript.ExtractBytes(challenge[:], labelSecretConnectionMac) - // immutable - recvAead cipher.AEAD - sendAead cipher.AEAD - - remPubKey ed25519.PublicKey - conn io.ReadWriteCloser - - // net.Conn must be thread safe: - // https://golang.org/pkg/net/#Conn. - // Since we have internal mutable state, - // we need mtxs. But recv and send states - // are independent, so we can use two mtxs. - // All .Read are covered by recvMtx, - // all .Write are covered by sendMtx. - recvMtx sync.Mutex - recvBuffer []byte - recvNonce *[aeadNonceSize]byte - - sendMtx sync.Mutex - sendNonce *[aeadNonceSize]byte + // Generate the secret used for receiving, sending, challenge via HKDF-SHA2 + // on the transcript state (which itself also uses HKDF-SHA2 to derive a key + // from the dhSecret). + aead := dh.AeadSecrets(loc.public == pubs[0]) + return &SecretConnection{ + conn: conn, + challenge: challenge, + recvState: utils.NewMutex(&recvState{cipher: aead.recv.Cipher()}), + sendState: utils.NewMutex(&sendState{cipher: aead.send.Cipher()}), + } } // MakeSecretConnection performs handshake and returns a new authenticated @@ -88,354 +121,237 @@ type SecretConnection struct { // Returns nil if there is an error in handshake. // Caller should call conn.Close() // See docs/sts-final.pdf for more information. -func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey ed25519.SecretKey) (*SecretConnection, error) { - locPubKey := locPrivKey.Public() - - // Generate ephemeral keys for perfect forward secrecy. - locEphPub, locEphPriv := genEphKeys() +func MakeSecretConnection(ctx context.Context, conn net.Conn, locPrivKey crypto.PrivKey) (*SecretConnection, error) { + // Generate ephemeral key for perfect forward secrecy. + loc := genEphKey() // Write local ephemeral pubkey and receive one too. // NOTE: every 32-byte string is accepted as a Curve25519 public key (see // DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf) - remEphPub, err := shareEphPubKey(conn, locEphPub) + rem, err := shareEphPubKey(ctx, conn, loc.public) if err != nil { return nil, err } - - // Sort by lexical order. - loEphPub, hiEphPub := sort32(locEphPub, remEphPub) - - transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH") - - transcript.AppendMessage(labelEphemeralLowerPublicKey, loEphPub[:]) - transcript.AppendMessage(labelEphemeralUpperPublicKey, hiEphPub[:]) - - // Check if the local ephemeral public key was the least, lexicographically - // sorted. - locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:]) - - // Compute common diffie hellman secret using X25519. - dhSecret, err := computeDHSecret(remEphPub, locEphPriv) - if err != nil { - return nil, err - } - - transcript.AppendMessage(labelDHSecret, dhSecret[:]) - - // Generate the secret used for receiving, sending, challenge via HKDF-SHA2 - // on the transcript state (which itself also uses HKDF-SHA2 to derive a key - // from the dhSecret). - recvSecret, sendSecret := deriveSecrets(dhSecret, locIsLeast) - - const challengeSize = 32 - var challenge [challengeSize]byte - transcript.ExtractBytes(challenge[:], labelSecretConnectionMac) - - sendAead, err := chacha20poly1305.New(sendSecret[:]) - if err != nil { - return nil, errors.New("invalid send SecretConnection Key") - } - recvAead, err := chacha20poly1305.New(recvSecret[:]) - if err != nil { - return nil, errors.New("invalid receive SecretConnection Key") - } - - sc := &SecretConnection{ - conn: conn, - recvBuffer: nil, - recvNonce: new([aeadNonceSize]byte), - sendNonce: new([aeadNonceSize]byte), - recvAead: recvAead, - sendAead: sendAead, - } - - // Sign the challenge bytes for authentication. - locSignature := signChallenge(&challenge, locPrivKey) - - // Share (in secret) each other's pubkey & challenge signature - authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature) - if err != nil { - return nil, err - } - - remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig - - if err := remPubKey.Verify(challenge[:], remSignature); err != nil { - return nil, fmt.Errorf("challenge verification failed: %w", err) - } - - // We've authorized. - sc.remPubKey = remPubKey - return sc, nil + sc := newSecretConnection(conn, loc, rem) + + return scope.Run1(ctx, func(ctx context.Context, s scope.Scope) (*SecretConnection, error) { + // Share (in secret) each other's pubkey & challenge signature + s.Spawn(func() error { + loc := &authSigMessage{locPrivKey.Public(), locPrivKey.Sign(sc.challenge[:])} + _, err := protoio.NewDelimitedWriter(sc).WriteMsg(authSigMessageConv.Encode(loc)) + return err + }) + var pba pb.AuthSigMessage + if _, err := protoio.NewDelimitedReader(sc, 1024*1024).ReadMsg(&pba); err != nil { + return nil, err + } + rem, err := authSigMessageConv.Decode(&pba) + if err != nil { + return nil, fmt.Errorf("authSigMessageFromProto(): %w", err) + } + if err := rem.Key.Verify(sc.challenge[:], rem.Sig); err != nil { + return nil, fmt.Errorf("challenge verification failed: %w", err) + } + sc.remPubKey = rem.Key + return sc, nil + }) } // RemotePubKey returns authenticated remote pubkey -func (sc *SecretConnection) RemotePubKey() ed25519.PublicKey { - return sc.remPubKey -} +func (sc *SecretConnection) RemotePubKey() crypto.PubKey { return sc.remPubKey } // Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`. // CONTRACT: data smaller than dataMaxSize is written atomically. func (sc *SecretConnection) Write(data []byte) (n int, err error) { - sc.sendMtx.Lock() - defer sc.sendMtx.Unlock() - - for 0 < len(data) { - if err := func() error { - var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) - var frame = pool.Get(totalFrameSize) - defer func() { - pool.Put(sealedFrame) - pool.Put(frame) - }() - var chunk []byte - if dataMaxSize < len(data) { - chunk = data[:dataMaxSize] - data = data[dataMaxSize:] - } else { - chunk = data - data = nil + for sendState := range sc.sendState.Lock() { + for 0 < len(data) { + if err := func() error { + var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) + var frame = pool.Get(totalFrameSize) + defer func() { + pool.Put(sealedFrame) + pool.Put(frame) + }() + var chunk []byte + if dataMaxSize < len(data) { + chunk = data[:dataMaxSize] + data = data[dataMaxSize:] + } else { + chunk = data + data = nil + } + chunkLength := len(chunk) + binary.LittleEndian.PutUint32(frame, uint32(chunkLength)) + copy(frame[dataLenSize:], chunk) + + // encrypt the frame + sendState.cipher.Seal(sealedFrame[:0], sendState.nonce[:], frame, nil) + sendState.nonce.inc() + // end encryption + + _, err = sc.conn.Write(sealedFrame) + if err != nil { + return err + } + n += len(chunk) + return nil + }(); err != nil { + return n, err } - chunkLength := len(chunk) - binary.LittleEndian.PutUint32(frame, uint32(chunkLength)) - copy(frame[dataLenSize:], chunk) - - // encrypt the frame - sc.sendAead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil) - incrNonce(sc.sendNonce) - // end encryption - - _, err = sc.conn.Write(sealedFrame) - if err != nil { - return err - } - n += len(chunk) - return nil - }(); err != nil { - return n, err } + return n, err } - return n, err + panic("unreachable") } +var errAEAD = errors.New("decoding failed") + // CONTRACT: data smaller than dataMaxSize is read atomically. func (sc *SecretConnection) Read(data []byte) (n int, err error) { - sc.recvMtx.Lock() - defer sc.recvMtx.Unlock() - - // read off and update the recvBuffer, if non-empty - if 0 < len(sc.recvBuffer) { - n = copy(data, sc.recvBuffer) - sc.recvBuffer = sc.recvBuffer[n:] - return - } + for recvState := range sc.recvState.Lock() { + // read off and update the recvBuffer, if non-empty + if 0 < len(recvState.buffer) { + n = copy(data, recvState.buffer) + recvState.buffer = recvState.buffer[n:] + return + } - // read off the conn - var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) - defer pool.Put(sealedFrame) - _, err = io.ReadFull(sc.conn, sealedFrame) - if err != nil { - return - } + // read off the conn + var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize) + defer pool.Put(sealedFrame) + _, err = io.ReadFull(sc.conn, sealedFrame) + if err != nil { + return + } - // decrypt the frame. - // reads and updates the sc.recvNonce - var frame = pool.Get(totalFrameSize) - defer pool.Put(frame) - _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil) - if err != nil { - return n, fmt.Errorf("failed to decrypt SecretConnection: %w", err) - } - incrNonce(sc.recvNonce) - // end decryption - - // copy checkLength worth into data, - // set recvBuffer to the rest. - var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes - if chunkLength > dataMaxSize { - return 0, errors.New("chunkLength is greater than dataMaxSize") - } - var chunk = frame[dataLenSize : dataLenSize+chunkLength] - n = copy(data, chunk) - if n < len(chunk) { - sc.recvBuffer = make([]byte, len(chunk)-n) - copy(sc.recvBuffer, chunk[n:]) + // decrypt the frame. + // reads and updates the sc.recvNonce + var frame = pool.Get(totalFrameSize) + defer pool.Put(frame) + _, err = recvState.cipher.Open(frame[:0], recvState.nonce[:], sealedFrame, nil) + if err != nil { + return n, fmt.Errorf("%w: %v", errAEAD, err) + } + recvState.nonce.inc() + // end decryption + + // copy checkLength worth into data, + // set recvBuffer to the rest. + var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes + if chunkLength > dataMaxSize { + return 0, errors.New("chunkLength is greater than dataMaxSize") + } + var chunk = frame[dataLenSize : dataLenSize+chunkLength] + n = copy(data, chunk) + if n < len(chunk) { + recvState.buffer = make([]byte, len(chunk)-n) + copy(recvState.buffer, chunk[n:]) + } + return n, err } - return n, err + panic("unreachable") } // Implements net.Conn -func (sc *SecretConnection) Close() error { return sc.conn.Close() } -func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() } -func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } -func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) } -func (sc *SecretConnection) SetReadDeadline(t time.Time) error { - return sc.conn.(net.Conn).SetReadDeadline(t) -} -func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { - return sc.conn.(net.Conn).SetWriteDeadline(t) +func (sc *SecretConnection) Close() error { return sc.conn.Close() } +func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.LocalAddr() } +func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.RemoteAddr() } +func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.SetDeadline(t) } +func (sc *SecretConnection) SetReadDeadline(t time.Time) error { return sc.conn.SetReadDeadline(t) } +func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { return sc.conn.SetWriteDeadline(t) } + +type ephPublic [32]byte + +type ephSecret struct { + secret [32]byte + public ephPublic } -func genEphKeys() (ephPub, ephPriv *[32]byte) { - var err error +func genEphKey() ephSecret { // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek), // we do not "clamp" the private key scalar: // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74 - ephPub, ephPriv, err = box.GenerateKey(crand.Reader) + public, secret, err := box.GenerateKey(crand.Reader) if err != nil { - panic("Could not generate ephemeral key-pair") + panic(fmt.Errorf("Could not generate ephemeral key-pair: %w", err)) + } + return ephSecret{ + secret: *secret, + public: *public, } - return } -func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { - - // Send our pubkey and receive theirs in tandem. - var trs, _ = async.Parallel( - func(_ int) (val any, abort bool, err error) { - lc := *locEphPub - _, err = protoio.NewDelimitedWriter(conn).WriteMsg(&gogotypes.BytesValue{Value: lc[:]}) - if err != nil { - return nil, true, err // abort - } - return nil, false, nil - }, - func(_ int) (val any, abort bool, err error) { - var bytes gogotypes.BytesValue - _, err = protoio.NewDelimitedReader(conn, 1024*1024).ReadMsg(&bytes) - if err != nil { - return nil, true, err // abort - } +var errDH = errors.New("DH handshake failed") + +func shareEphPubKey(ctx context.Context, conn io.ReadWriter, locEphPub ephPublic) (ephPublic, error) { + return scope.Run1(ctx, func(ctx context.Context, s scope.Scope) (ephPublic, error) { + s.Spawn(func() error { + _, err := protoio.NewDelimitedWriter(conn).WriteMsg(&gogotypes.BytesValue{Value: locEphPub[:]}) + return err + }) + var bytes gogotypes.BytesValue + if _, err := protoio.NewDelimitedReader(conn, 1024*1024).ReadMsg(&bytes); err != nil { + return ephPublic{}, fmt.Errorf("%w: %v", errDH, err) + } + if len(bytes.Value) != len(ephPublic{}) { + return ephPublic{}, fmt.Errorf("%w: bad ephemeral key size", errDH) + } + return ephPublic(bytes.Value), nil + }) +} - var _remEphPub [32]byte - copy(_remEphPub[:], bytes.Value) - return _remEphPub, false, nil - }, - ) +type dhSecret [32]byte +type aeadSecret [chacha20poly1305.KeySize]byte - // If error: - if trs.FirstError() != nil { - err = trs.FirstError() - return - } - - // Otherwise: - var _remEphPub = trs.FirstValue().([32]byte) - return &_remEphPub, nil +type aeadSecrets struct { + send aeadSecret + recv aeadSecret } -func deriveSecrets( - dhSecret *[32]byte, - locIsLeast bool, -) (recvSecret, sendSecret *[aeadKeySize]byte) { - hash := sha256.New - hkdf := hkdf.New(hash, dhSecret[:], nil, secretConnKeyAndChallengeGen) - // get enough data for 2 aead keys, and a 32 byte challenge - res := new([2*aeadKeySize + 32]byte) - _, err := io.ReadFull(hkdf, res[:]) - if err != nil { - panic(err) - } - - recvSecret = new([aeadKeySize]byte) - sendSecret = new([aeadKeySize]byte) +func (s aeadSecret) Cipher() cipher.AEAD { + // Never returns an error on input of correct size. + return utils.OrPanic1(chacha20poly1305.New(s[:])) +} - // bytes 0 through aeadKeySize - 1 are one aead key. - // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key. - // which key corresponds to sending and receiving key depends on whether - // the local key is less than the remote key. +func (s dhSecret) AeadSecrets(locIsLeast bool) aeadSecrets { + hkdf := hkdf.New(sha256.New, s[:], nil, secretConnKeyAndChallengeGen) + aead := aeadSecrets{} + // hkdf reader never returns an error. + utils.OrPanic1(io.ReadFull(hkdf, aead.send[:])) + utils.OrPanic1(io.ReadFull(hkdf, aead.recv[:])) if locIsLeast { - copy(recvSecret[:], res[0:aeadKeySize]) - copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2]) - } else { - copy(sendSecret[:], res[0:aeadKeySize]) - copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2]) + aead.send, aead.recv = aead.recv, aead.send } - - return + return aead } // computeDHSecret computes a Diffie-Hellman shared secret key // from our own local private key and the other's public key. -func computeDHSecret(remPubKey, locPrivKey *[32]byte) (*[32]byte, error) { - shrKey, err := curve25519.X25519(locPrivKey[:], remPubKey[:]) - if err != nil { - return nil, err - } - var shrKeyArray [32]byte - copy(shrKeyArray[:], shrKey) - return &shrKeyArray, nil -} - -func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) { - if bytes.Compare(foo[:], bar[:]) < 0 { - lo = foo - hi = bar - } else { - lo = bar - hi = foo - } - return -} - -func signChallenge(challenge *[32]byte, locPrivKey ed25519.SecretKey) ed25519.Signature { - return locPrivKey.Sign(challenge[:]) +func (s ephSecret) DhSecret(remPubKey ephPublic) dhSecret { + return dhSecret(utils.OrPanic1(curve25519.X25519(s.secret[:], remPubKey[:]))) } type authSigMessage struct { - Key ed25519.PublicKey - Sig ed25519.Signature -} - -func shareAuthSignature(sc io.ReadWriter, pubKey ed25519.PublicKey, sig ed25519.Signature) (authSigMessage, error) { - // Send our info and receive theirs in tandem. - var trs, _ = async.Parallel( - func(_ int) (val any, abort bool, err error) { - pk := tmproto.PublicKey{Sum: &tmproto.PublicKey_Ed25519{Ed25519: pubKey.Bytes()}} - if _, err := protoio.NewDelimitedWriter(sc).WriteMsg(&tmp2p.AuthSigMessage{PubKey: pk, Sig: sig.Bytes()}); err != nil { - return nil, true, err - } - return nil, false, nil - }, - func(_ int) (val any, abort bool, err error) { - var pba tmp2p.AuthSigMessage - if _, err := protoio.NewDelimitedReader(sc, 1024*1024).ReadMsg(&pba); err != nil { - return nil, true, err - } - key, err := ed25519.PublicKeyFromBytes(pba.PubKey.GetEd25519()) - if err != nil { - return nil, true, fmt.Errorf("ed25519.PublicKeyFromBytes(): %w", err) - } - sig, err := ed25519.SignatureFromBytes(pba.Sig) - if err != nil { - return nil, true, fmt.Errorf("ed25519.SignatureFromBytes(): %w", err) - } - return authSigMessage{Key: key, Sig: sig}, false, nil - }, - ) - - // If error: - if trs.FirstError() != nil { - return authSigMessage{}, trs.FirstError() - } - - var _recvMsg = trs.FirstValue().(authSigMessage) - return _recvMsg, nil + Key crypto.PubKey + Sig crypto.Sig } -//-------------------------------------------------------------------------------- - -// Increment nonce little-endian by 1 with wraparound. -// Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four -// bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes -// (little-endian in nonce[4:]). -func incrNonce(nonce *[aeadNonceSize]byte) { - counter := binary.LittleEndian.Uint64(nonce[4:]) - if counter == math.MaxUint64 { - // Terminates the session and makes sure the nonce would not re-used. - // See https://github.com/tendermint/tendermint/issues/3531 - panic("can't increase nonce without overflow") - } - counter++ - binary.LittleEndian.PutUint64(nonce[4:], counter) +var authSigMessageConv = utils.ProtoConv[*authSigMessage, *pb.AuthSigMessage]{ + Encode: func(m *authSigMessage) *pb.AuthSigMessage { + return &pb.AuthSigMessage{ + PubKey: crypto.PubKeyConv.Encode(m.Key), + Sig: m.Sig.Bytes(), + } + }, + Decode: func(p *pb.AuthSigMessage) (*authSigMessage, error) { + key, err := crypto.PubKeyConv.DecodeReq(p.PubKey) + if err != nil { + return nil, fmt.Errorf("PubKey: %w", err) + } + sig, err := crypto.SigFromBytes(p.Sig) + if err != nil { + return nil, fmt.Errorf("Sig: %w", err) + } + return &authSigMessage{key, sig}, nil + }, } diff --git a/sei-tendermint/internal/p2p/conn/secret_connection_test.go b/sei-tendermint/internal/p2p/conn/secret_connection_test.go index 032b75bcfe..91a1978aa6 100644 --- a/sei-tendermint/internal/p2p/conn/secret_connection_test.go +++ b/sei-tendermint/internal/p2p/conn/secret_connection_test.go @@ -2,25 +2,25 @@ package conn import ( "bufio" + "context" "encoding/hex" + "errors" "flag" "fmt" "io" - "log" mrand "math/rand" + "net" "os" "path/filepath" "strconv" "strings" - "sync" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/internal/libs/async" tmrand "github.com/tendermint/tendermint/libs/rand" + "github.com/tendermint/tendermint/libs/utils" + "github.com/tendermint/tendermint/libs/utils/require" + "github.com/tendermint/tendermint/libs/utils/scope" ) // Run go test -update from within this module @@ -28,13 +28,17 @@ import ( var update = flag.Bool("update", false, "update .golden files") type kvstoreConn struct { - *io.PipeReader - *io.PipeWriter + net.Conn + reader *io.PipeReader + writer *io.PipeWriter } +func (drw kvstoreConn) Read(data []byte) (n int, err error) { return drw.reader.Read(data) } +func (drw kvstoreConn) Write(data []byte) (n int, err error) { return drw.writer.Write(data) } + func (drw kvstoreConn) Close() (err error) { - err2 := drw.PipeWriter.CloseWithError(io.EOF) - err1 := drw.PipeReader.Close() + err2 := drw.writer.CloseWithError(io.EOF) + err1 := drw.reader.Close() if err2 != nil { return err } @@ -43,172 +47,98 @@ func (drw kvstoreConn) Close() (err error) { func TestSecretConnectionHandshake(t *testing.T) { fooSecConn, barSecConn := makeSecretConnPair(t) - if err := fooSecConn.Close(); err != nil { - t.Error(err) - } - if err := barSecConn.Close(); err != nil { - t.Error(err) - } + require.NoError(t, fooSecConn.Close()) + require.NoError(t, barSecConn.Close()) } -func TestConcurrentWrite(t *testing.T) { - fooSecConn, barSecConn := makeSecretConnPair(t) - fooWriteText := tmrand.Str(dataMaxSize) - - // write from two routines. - // should be safe from race according to net.Conn: - // https://golang.org/pkg/net/#Conn - n := 100 - wg := new(sync.WaitGroup) - wg.Add(3) - go writeLots(t, wg, fooSecConn, fooWriteText, n) - go writeLots(t, wg, fooSecConn, fooWriteText, n) - - // Consume reads from bar's reader - readLots(t, wg, barSecConn, n*2) - wg.Wait() - - if err := fooSecConn.Close(); err != nil { - t.Error(err) - } -} - -func TestConcurrentRead(t *testing.T) { - fooSecConn, barSecConn := makeSecretConnPair(t) - fooWriteText := tmrand.Str(dataMaxSize) - n := 100 +func TestConcurrentReadWrite(t *testing.T) { + ctx := t.Context() + sc1, sc2 := makeSecretConnPair(t) + rng := utils.TestRng() + fooWriteText := utils.GenBytes(rng, dataMaxSize) + n := 100 * dataMaxSize // read from two routines. // should be safe from race according to net.Conn: // https://golang.org/pkg/net/#Conn - wg := new(sync.WaitGroup) - wg.Add(3) - go readLots(t, wg, fooSecConn, n/2) - go readLots(t, wg, fooSecConn, n/2) - - // write to bar - writeLots(t, wg, barSecConn, fooWriteText, n) - wg.Wait() - - if err := fooSecConn.Close(); err != nil { - t.Error(err) - } + err := scope.Run(ctx, func(ctx context.Context, s scope.Scope) error { + s.Spawn(func() error { return readLots(sc1, n) }) + s.Spawn(func() error { return readLots(sc1, n) }) + s.Spawn(func() error { return writeLots(sc2, fooWriteText, n) }) + s.Spawn(func() error { return writeLots(sc2, fooWriteText, n) }) + return nil + }) + require.NoError(t, err) + require.NoError(t, sc1.Close()) + require.NoError(t, sc2.Close()) } func TestSecretConnectionReadWrite(t *testing.T) { - fooConn, barConn := makeKVStoreConnPair() - fooWrites, barWrites := []string{}, []string{} - fooReads, barReads := []string{}, []string{} - - // Pre-generate the things to write (for foo & bar) - for i := 0; i < 100; i++ { - fooWrites = append(fooWrites, tmrand.Str((mrand.Int()%(dataMaxSize*5))+1)) - barWrites = append(barWrites, tmrand.Str((mrand.Int()%(dataMaxSize*5))+1)) - } - - // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa - genNodeRunner := func(id string, nodeConn kvstoreConn, nodeWrites []string, nodeReads *[]string) async.Task { - return func(_ int) (interface{}, bool, error) { - // Initiate cryptographic private key and secret connection trhough nodeConn. - nodePrvKey := ed25519.GenerateSecretKey() - nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey) - if err != nil { - t.Errorf("failed to establish SecretConnection for node: %v", err) - return nil, true, err - } - // In parallel, handle some reads and writes. - var trs, ok = async.Parallel( - func(_ int) (interface{}, bool, error) { - // Node writes: - for _, nodeWrite := range nodeWrites { - n, err := nodeSecretConn.Write([]byte(nodeWrite)) + ctx := t.Context() + c1, c2 := makeKVStoreConnPair() + writes := utils.NewMutex(map[ed25519.PublicKey][]byte{}) + reads := utils.NewMutex(map[ed25519.PublicKey][]byte{}) + rng := utils.TestRng() + err := scope.Run(ctx, func(ctx context.Context, s scope.Scope) error { + for _, c := range utils.Slice(c1, c2) { + s.Spawn(func() error { + k := ed25519.GenerateSecretKey() + sc, err := MakeSecretConnection(ctx, c, k) + if err != nil { + return fmt.Errorf("MakeSecretConnection(): %w", err) + } + // In parallel, handle some reads and writes. + s.Spawn(func() error { + var ws []byte + for range 100 { + w := utils.GenBytes(rng, rng.Intn(dataMaxSize*5)+1) + ws = append(ws, w...) + n, err := sc.Write(w) if err != nil { - t.Errorf("failed to write to nodeSecretConn: %v", err) - return nil, true, err + return fmt.Errorf("failed to write to nodeSecretConn: %w", err) } - if n != len(nodeWrite) { - err = fmt.Errorf("failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n) - t.Error(err) - return nil, true, err + if n != len(w) { + return fmt.Errorf("failed to write all bytes. Expected %v, wrote %v", len(w), n) } } - if err := nodeConn.PipeWriter.Close(); err != nil { - t.Error(err) - return nil, true, err + for writes := range writes.Lock() { + writes[k.Public()] = ws } - return nil, false, nil - }, - func(_ int) (interface{}, bool, error) { - // Node reads: + return c.writer.Close() + }) + s.Spawn(func() error { + var rs []byte readBuffer := make([]byte, dataMaxSize) for { - n, err := nodeSecretConn.Read(readBuffer) - if err == io.EOF { - if err := nodeConn.PipeReader.Close(); err != nil { - t.Error(err) - return nil, true, err + n, err := sc.Read(readBuffer) + if err != nil { + if errors.Is(err, io.EOF) { + for reads := range reads.Lock() { + reads[sc.RemotePubKey()] = rs + } + return c.reader.Close() } - return nil, false, nil - } else if err != nil { - t.Errorf("failed to read from nodeSecretConn: %v", err) - return nil, true, err + return fmt.Errorf("failed to read from nodeSecretConn: %w", err) + } + if n == 0 { + return fmt.Errorf("Read() is nonblocking") } - *nodeReads = append(*nodeReads, string(readBuffer[:n])) + rs = append(rs, readBuffer[:n]...) } - }, - ) - assert.True(t, ok, "Unexpected task abortion") - - // If error: - if trs.FirstError() != nil { - return nil, true, trs.FirstError() - } - - // Otherwise: - return nil, false, nil + }) + return nil + }) } - } - - // Run foo & bar in parallel - var trs, ok = async.Parallel( - genNodeRunner("foo", fooConn, fooWrites, &fooReads), - genNodeRunner("bar", barConn, barWrites, &barReads), - ) - require.Nil(t, trs.FirstError()) - require.True(t, ok, "unexpected task abortion") - - // A helper to ensure that the writes and reads match. - // Additionally, small writes (<= dataMaxSize) must be atomically read. - compareWritesReads := func(writes []string, reads []string) { - for { - // Pop next write & corresponding reads - var read, write = "", writes[0] - var readCount = 0 - for _, readChunk := range reads { - read += readChunk - readCount++ - if len(write) <= len(read) { - break - } - if len(write) <= dataMaxSize { - break // atomicity of small writes - } - } - // Compare - if write != read { - t.Errorf("expected to read %X, got %X", write, read) - } - // Iterate - writes = writes[1:] - reads = reads[readCount:] - if len(writes) == 0 { - break + return nil + }) + require.NoError(t, err) + for reads := range reads.Lock() { + for writes := range writes.Lock() { + for k, want := range writes { + require.Equal(t, want, reads[k]) } } } - - compareWritesReads(fooWrites, barReads) - compareWritesReads(barWrites, fooReads) } func TestDeriveSecretsAndChallengeGolden(t *testing.T) { @@ -219,18 +149,14 @@ func TestDeriveSecretsAndChallengeGolden(t *testing.T) { require.NoError(t, os.WriteFile(goldenFilepath, []byte(data), 0644)) } f, err := os.Open(goldenFilepath) - if err != nil { - log.Fatal(err) - } - t.Cleanup(closeAll(t, f)) + require.NoError(t, err) + defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() params := strings.Split(line, ",") - randSecretVector, err := hex.DecodeString(params[0]) + dh, err := hex.DecodeString(params[0]) require.NoError(t, err) - randSecret := new([32]byte) - copy((*randSecret)[:], randSecretVector) locIsLeast, err := strconv.ParseBool(params[1]) require.NoError(t, err) expectedRecvSecret, err := hex.DecodeString(params[2]) @@ -238,30 +164,33 @@ func TestDeriveSecretsAndChallengeGolden(t *testing.T) { expectedSendSecret, err := hex.DecodeString(params[3]) require.NoError(t, err) - recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) - require.Equal(t, expectedRecvSecret, (*recvSecret)[:], "Recv Secrets aren't equal") - require.Equal(t, expectedSendSecret, (*sendSecret)[:], "Send Secrets aren't equal") + aead := dhSecret(dh).AeadSecrets(locIsLeast) + require.Equal(t, aeadSecret(expectedRecvSecret), aead.recv, "Recv Secrets aren't equal") + require.Equal(t, aeadSecret(expectedSendSecret), aead.send, "Send Secrets aren't equal") } } -func writeLots(t *testing.T, wg *sync.WaitGroup, conn io.Writer, txt string, n int) { - defer wg.Done() - for i := 0; i < n; i++ { - _, err := conn.Write([]byte(txt)) - if err != nil { - t.Errorf("failed to write to fooSecConn: %v", err) - return +func writeLots(sc *SecretConnection, data []byte, total int) error { + for total > 0 { + n := min(len(data), total) + total -= n + if _, err := sc.Write(data[:n]); err != nil { + return err } } + return nil } -func readLots(t *testing.T, wg *sync.WaitGroup, conn io.Reader, n int) { - readBuffer := make([]byte, dataMaxSize) - for i := 0; i < n; i++ { - _, err := conn.Read(readBuffer) - assert.NoError(t, err) +func readLots(sc *SecretConnection, total int) error { + for total > 0 { + readBuffer := make([]byte, min(dataMaxSize, total)) + n, err := sc.Read(readBuffer) + if err != nil { + return err + } + total -= n } - wg.Done() + return nil } // Creates the data for a test vector file. @@ -269,16 +198,14 @@ func readLots(t *testing.T, wg *sync.WaitGroup, conn io.Reader, n int) { // Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge) func createGoldenTestVectors() string { data := "" - for i := 0; i < 32; i++ { - randSecretVector := tmrand.Bytes(32) - randSecret := new([32]byte) - copy((*randSecret)[:], randSecretVector) - data += hex.EncodeToString((*randSecret)[:]) + "," + for range 32 { + dh := dhSecret(tmrand.Bytes(len(dhSecret{}))) + data += hex.EncodeToString(dh[:]) + "," locIsLeast := mrand.Int63()%2 == 0 data += strconv.FormatBool(locIsLeast) + "," - recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) - data += hex.EncodeToString((*recvSecret)[:]) + "," - data += hex.EncodeToString((*sendSecret)[:]) + "," + aead := dh.AeadSecrets(locIsLeast) + data += hex.EncodeToString(aead.recv[:]) + "," + data += hex.EncodeToString(aead.send[:]) + "," } return data } @@ -287,56 +214,35 @@ func createGoldenTestVectors() string { func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) { barReader, fooWriter := io.Pipe() fooReader, barWriter := io.Pipe() - return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter} + return kvstoreConn{reader: fooReader, writer: fooWriter}, kvstoreConn{reader: barReader, writer: barWriter} } -func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) { - var ( - fooConn, barConn = makeKVStoreConnPair() - fooPrvKey = ed25519.GenerateSecretKey() - fooPubKey = fooPrvKey.Public() - barPrvKey = ed25519.GenerateSecretKey() - barPubKey = barPrvKey.Public() - ) +func makeSecretConnPair(tb testing.TB) (sc1 *SecretConnection, sc2 *SecretConnection) { + ctx := tb.Context() + c1, c2 := makeKVStoreConnPair() + k1 := ed25519.GenerateSecretKey() + k2 := ed25519.GenerateSecretKey() // Make connections from both sides in parallel. - var trs, ok = async.Parallel( - func(_ int) (val interface{}, abort bool, err error) { - fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) - if err != nil { - tb.Errorf("failed to establish SecretConnection for foo: %v", err) - return nil, true, err - } - remotePubKey := fooSecConn.RemotePubKey() - if remotePubKey != barPubKey { - err = fmt.Errorf("unexpected fooSecConn.RemotePubKey. Expected %v, got %v", - barPubKey, remotePubKey) - tb.Error(err) - return nil, true, err - } - return nil, false, nil - }, - func(_ int) (val interface{}, abort bool, err error) { - barSecConn, err = MakeSecretConnection(barConn, barPrvKey) - if barSecConn == nil { - tb.Errorf("failed to establish SecretConnection for bar: %v", err) - return nil, true, err - } - remotePubKey := barSecConn.RemotePubKey() - if remotePubKey != fooPubKey { - err = fmt.Errorf("unexpected barSecConn.RemotePubKey. Expected %v, got %v", - fooPubKey, remotePubKey) - tb.Error(err) - return nil, true, err - } - return nil, false, nil - }, - ) - - require.Nil(tb, trs.FirstError()) - require.True(tb, ok, "Unexpected task abortion") - - return fooSecConn, barSecConn + err := scope.Run(ctx, func(ctx context.Context, s scope.Scope) error { + s.Spawn(func() error { + var err error + sc1, err = MakeSecretConnection(ctx, c1, k1) + return err + }) + s.Spawn(func() error { + var err error + sc2, err = MakeSecretConnection(ctx, c2, k2) + return err + }) + return nil + }) + if err != nil { + tb.Fatal(err) + } + require.Equal(tb, k1.Public(), sc2.RemotePubKey()) + require.Equal(tb, k2.Public(), sc1.RemotePubKey()) + return sc1, sc2 } // Benchmarks @@ -372,8 +278,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) { } }() - b.StartTimer() - for i := 0; i < b.N; i++ { + for b.Loop() { idx := mrand.Intn(len(fooWriteBytes)) _, err := fooSecConn.Write(fooWriteBytes[idx]) if err != nil { @@ -381,7 +286,6 @@ func BenchmarkWriteSecretConnection(b *testing.B) { return } } - b.StopTimer() if err := fooSecConn.Close(); err != nil { b.Error(err) @@ -407,7 +311,7 @@ func BenchmarkReadSecretConnection(b *testing.B) { fooWriteBytes = append(fooWriteBytes, tmrand.Bytes(size)) } go func() { - for i := 0; i < b.N; i++ { + for i := range b.N { idx := mrand.Intn(len(fooWriteBytes)) _, err := fooSecConn.Write(fooWriteBytes[idx]) if err != nil { @@ -417,8 +321,7 @@ func BenchmarkReadSecretConnection(b *testing.B) { } }() - b.StartTimer() - for i := 0; i < b.N; i++ { + for b.Loop() { readBuffer := make([]byte, dataMaxSize) _, err := barSecConn.Read(readBuffer) @@ -428,19 +331,4 @@ func BenchmarkReadSecretConnection(b *testing.B) { b.Fatalf("Failed to read from barSecConn: %v", err) } } - b.StopTimer() -} - -type closer interface { - Close() error -} - -func closeAll(t *testing.T, closers ...closer) func() { - return func() { - for _, s := range closers { - if err := s.Close(); err != nil { - t.Log(err) - } - } - } } diff --git a/sei-tendermint/internal/p2p/pex/reactor.go b/sei-tendermint/internal/p2p/pex/reactor.go index 8b24237c85..cf2a82dd9c 100644 --- a/sei-tendermint/internal/p2p/pex/reactor.go +++ b/sei-tendermint/internal/p2p/pex/reactor.go @@ -194,9 +194,9 @@ func (r *Reactor) handlePexMessage(m p2p.RecvMsg[*pb.PexMessage]) error { // Fetch peers from the peer manager, convert NodeAddresses into URL // strings, and send them back to the caller. nodeAddresses := r.router.Advertise(maxAddresses) - pexAddresses := make([]pb.PexAddress, len(nodeAddresses)) + pexAddresses := make([]*pb.PexAddress, len(nodeAddresses)) for idx, addr := range nodeAddresses { - pexAddresses[idx] = pb.PexAddress{URL: addr.String()} + pexAddresses[idx] = &pb.PexAddress{Url: addr.String()} } r.channel.Send(wrap(&pb.PexResponse{Addresses: pexAddresses}), m.From) return nil @@ -211,7 +211,7 @@ func (r *Reactor) handlePexMessage(m p2p.RecvMsg[*pb.PexMessage]) error { var addrs []p2p.NodeAddress for _, pexAddress := range resp.Addresses { - addr, err := p2p.ParseNodeAddress(pexAddress.URL) + addr, err := p2p.ParseNodeAddress(pexAddress.Url) if err != nil { return fmt.Errorf("PEX parse node address error: %w", err) } diff --git a/sei-tendermint/internal/p2p/pex/reactor_test.go b/sei-tendermint/internal/p2p/pex/reactor_test.go index eebd954b2e..fe5ead3dbb 100644 --- a/sei-tendermint/internal/p2p/pex/reactor_test.go +++ b/sei-tendermint/internal/p2p/pex/reactor_test.go @@ -144,11 +144,11 @@ func TestReactorErrorsOnReceivingTooManyPeers(t *testing.T) { } t.Log("send a response with too many addresses") - addresses := make([]pb.PexAddress, 101) + addresses := make([]*pb.PexAddress, 101) for i := range addresses { nodeAddress := p2p.NodeAddress{NodeID: randomNodeID()} - addresses[i] = pb.PexAddress{ - URL: nodeAddress.String(), + addresses[i] = &pb.PexAddress{ + Url: nodeAddress.String(), } } ch.Send(wrap(&pb.PexResponse{Addresses: addresses}), n1) @@ -459,12 +459,12 @@ func (r *reactorTestSuite) listenForPeerDown( r.network.Node(on).WaitForConn(t.Context(), with, false) } -func (r *reactorTestSuite) getAddressesFor(nodes []int) []pb.PexAddress { - addresses := make([]pb.PexAddress, len(nodes)) +func (r *reactorTestSuite) getAddressesFor(nodes []int) []*pb.PexAddress { + addresses := make([]*pb.PexAddress, len(nodes)) for idx, node := range nodes { nodeID := r.nodes[node] - addresses[idx] = pb.PexAddress{ - URL: r.network.Node(nodeID).NodeAddress.String(), + addresses[idx] = &pb.PexAddress{ + Url: r.network.Node(nodeID).NodeAddress.String(), } } return addresses diff --git a/sei-tendermint/internal/p2p/transport.go b/sei-tendermint/internal/p2p/transport.go index b055c62f7e..bc48f1753b 100644 --- a/sei-tendermint/internal/p2p/transport.go +++ b/sei-tendermint/internal/p2p/transport.go @@ -84,7 +84,7 @@ func (r *Router) handshake(ctx context.Context, tcpConn *net.TCPConn, dialAddr u return nil }) var err error - secretConn, err := conn.MakeSecretConnection(tcpConn, r.privKey) + secretConn, err := conn.MakeSecretConnection(ctx, tcpConn, r.privKey) if err != nil { return nil, err } diff --git a/sei-tendermint/internal/state/execution.go b/sei-tendermint/internal/state/execution.go index 2efd7acdd1..a030a94977 100644 --- a/sei-tendermint/internal/state/execution.go +++ b/sei-tendermint/internal/state/execution.go @@ -10,7 +10,7 @@ import ( abciclient "github.com/tendermint/tendermint/abci/client" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/encoding" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/internal/eventbus" "github.com/tendermint/tendermint/internal/mempool" @@ -629,7 +629,7 @@ func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate, } // Check if validator's pubkey matches an ABCI type in the consensus params - pk, err := encoding.PubKeyFromProto(valUpdate.PubKey) + pk, err := crypto.PubKeyFromProto(valUpdate.PubKey) if err != nil { return err } diff --git a/sei-tendermint/internal/state/execution_test.go b/sei-tendermint/internal/state/execution_test.go index dbd6d9eff6..cfaabdffa2 100644 --- a/sei-tendermint/internal/state/execution_test.go +++ b/sei-tendermint/internal/state/execution_test.go @@ -17,7 +17,6 @@ import ( abcimocks "github.com/tendermint/tendermint/abci/types/mocks" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/internal/eventbus" mpmocks "github.com/tendermint/tendermint/internal/mempool/mocks" "github.com/tendermint/tendermint/internal/proxy" @@ -375,8 +374,8 @@ func TestProcessProposal(t *testing.T) { func TestValidateValidatorUpdates(t *testing.T) { pubkey1 := ed25519.GenerateSecretKey().Public() pubkey2 := ed25519.GenerateSecretKey().Public() - pk1 := encoding.PubKeyToProto(pubkey1) - pk2 := encoding.PubKeyToProto(pubkey2) + pk1 := crypto.PubKeyToProto(pubkey1) + pk2 := crypto.PubKeyToProto(pubkey2) defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}} @@ -432,8 +431,8 @@ func TestUpdateValidators(t *testing.T) { pubkey2 := ed25519.GenerateSecretKey().Public() val2 := types.NewValidator(pubkey2, 20) - pk := encoding.PubKeyToProto(pubkey1) - pk2 := encoding.PubKeyToProto(pubkey2) + pk := crypto.PubKeyToProto(pubkey1) + pk2 := crypto.PubKeyToProto(pubkey2) testCases := []struct { name string @@ -551,7 +550,7 @@ func TestFinalizeBlockValidatorUpdates(t *testing.T) { blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} pubkey := ed25519.GenerateSecretKey().Public() - pk := encoding.PubKeyToProto(pubkey) + pk := crypto.PubKeyToProto(pubkey) app.ValidatorUpdates = []abci.ValidatorUpdate{ {PubKey: pk, Power: 10}, } @@ -615,7 +614,7 @@ func TestFinalizeBlockValidatorUpdatesResultingInEmptySet(t *testing.T) { require.NoError(t, err) blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()} - vp := encoding.PubKeyToProto(state.Validators.Validators[0].PubKey) + vp := crypto.PubKeyToProto(state.Validators.Validators[0].PubKey) // Remove the only validator app.ValidatorUpdates = []abci.ValidatorUpdate{ {PubKey: vp, Power: 0}, diff --git a/sei-tendermint/internal/state/helpers_test.go b/sei-tendermint/internal/state/helpers_test.go index 91d351ff43..a9cd8dfa64 100644 --- a/sei-tendermint/internal/state/helpers_test.go +++ b/sei-tendermint/internal/state/helpers_test.go @@ -13,7 +13,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" sm "github.com/tendermint/tendermint/internal/state" sf "github.com/tendermint/tendermint/internal/state/test/factory" "github.com/tendermint/tendermint/internal/test/factory" @@ -156,8 +155,8 @@ func makeHeaderPartsResponsesValPubKeyChange( // If the pubkey is new, remove the old and add the new. _, val := state.NextValidators.GetByIndex(0) if pubkey != val.PubKey { - vPbPk := encoding.PubKeyToProto(val.PubKey) - pbPk := encoding.PubKeyToProto(pubkey) + vPbPk := crypto.PubKeyToProto(val.PubKey) + pbPk := crypto.PubKeyToProto(pubkey) finalizeBlockResponses.ValidatorUpdates = []abci.ValidatorUpdate{ {PubKey: vPbPk, Power: 0}, @@ -181,7 +180,7 @@ func makeHeaderPartsResponsesValPowerChange( // If the pubkey is new, remove the old and add the new. _, val := state.NextValidators.GetByIndex(0) if val.VotingPower != power { - vPbPk := encoding.PubKeyToProto(val.PubKey) + vPbPk := crypto.PubKeyToProto(val.PubKey) finalizeBlockResponses.ValidatorUpdates = []abci.ValidatorUpdate{ {PubKey: vPbPk, Power: power}, diff --git a/sei-tendermint/internal/state/state_test.go b/sei-tendermint/internal/state/state_test.go index 34a1d7c456..86d5046590 100644 --- a/sei-tendermint/internal/state/state_test.go +++ b/sei-tendermint/internal/state/state_test.go @@ -15,8 +15,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/crypto/merkle" sm "github.com/tendermint/tendermint/internal/state" statefactory "github.com/tendermint/tendermint/internal/state/test/factory" @@ -117,7 +117,7 @@ func TestFinalizeBlockResponsesSaveLoad1(t *testing.T) { finalizeBlockResponses.TxResults[0] = &abci.ExecTxResult{Data: []byte("foo"), Events: nil} finalizeBlockResponses.TxResults[1] = &abci.ExecTxResult{Data: []byte("bar"), Log: "ok", Events: nil} - pbpk := encoding.PubKeyToProto(ed25519.GenerateSecretKey().Public()) + pbpk := crypto.PubKeyToProto(ed25519.GenerateSecretKey().Public()) finalizeBlockResponses.ValidatorUpdates = []abci.ValidatorUpdate{{PubKey: pbpk, Power: 10}} require.NoError(t, stateStore.SaveFinalizeBlockResponses(block.Height, finalizeBlockResponses)) @@ -355,7 +355,7 @@ func TestProposerFrequency(t *testing.T) { for caseNum, testCase := range testCases { // run each case 5 times to sample different // initial priorities - for i := 0; i < 5; i++ { + for range 5 { valSet := genValSetWithPowers(testCase.powers) testProposerFreq(t, caseNum, valSet) } @@ -365,11 +365,11 @@ func TestProposerFrequency(t *testing.T) { maxVals := 100 maxPower := 1000 nTestCases := 5 - for i := 0; i < nTestCases; i++ { + for i := range nTestCases { N := mrand.Int()%maxVals + 1 vals := make([]*types.Validator, N) totalVotePower := int64(0) - for j := 0; j < N; j++ { + for j := range N { // make sure votePower > 0 votePower := int64(mrand.Int()%maxPower) + 1 totalVotePower += votePower @@ -391,7 +391,7 @@ func genValSetWithPowers(powers []int64) *types.ValidatorSet { size := len(powers) vals := make([]*types.Validator, size) totalVotePower := int64(0) - for i := 0; i < size; i++ { + for i := range size { totalVotePower += powers[i] val := types.NewValidator(ed25519.GenerateSecretKey().Public(), powers[i]) val.ProposerPriority = mrand.Int63() @@ -411,7 +411,7 @@ func testProposerFreq(t *testing.T, caseNum int, valSet *types.ValidatorSet) { runMult := 1 runs := int(totalPower) * runMult freqs := make([]int, N) - for i := 0; i < runs; i++ { + for range runs { prop := valSet.GetProposer() idx, _ := valSet.GetByAddress(prop.Address) freqs[idx]++ @@ -474,7 +474,7 @@ func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) { // add a validator val2PubKey := ed25519.GenerateSecretKey().Public() val2VotingPower := int64(100) - fvp := encoding.PubKeyToProto(val2PubKey) + fvp := crypto.PubKeyToProto(val2PubKey) updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val2VotingPower} validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal}) @@ -601,7 +601,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) { // add a validator with the same voting power as the first val2PubKey := ed25519.GenerateSecretKey().Public() - fvp := encoding.PubKeyToProto(val2PubKey) + fvp := crypto.PubKeyToProto(val2PubKey) updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val1VotingPower} validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal}) assert.NoError(t, err) @@ -707,7 +707,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) { expectedVal1Prio = -9 expectedVal2Prio = 9 - for i := 0; i < 1000; i++ { + for i := range 1000 { // no validator updates: fb := &abci.ResponseFinalizeBlock{ ValidatorUpdates: nil, @@ -767,7 +767,7 @@ func TestLargeGenesisValidator(t *testing.T) { // update state a few times with no validator updates // asserts that the single validator's ProposerPrio stays the same oldState := state - for i := 0; i < 10; i++ { + for range 10 { // no updates: fb := &abci.ResponseFinalizeBlock{ ValidatorUpdates: nil, @@ -800,7 +800,7 @@ func TestLargeGenesisValidator(t *testing.T) { // see: https://github.com/tendermint/tendermint/issues/2960 firstAddedValPubKey := ed25519.GenerateSecretKey().Public() firstAddedValVotingPower := int64(10) - fvp := encoding.PubKeyToProto(firstAddedValPubKey) + fvp := crypto.PubKeyToProto(firstAddedValPubKey) firstAddedVal := abci.ValidatorUpdate{PubKey: fvp, Power: firstAddedValVotingPower} validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{firstAddedVal}) assert.NoError(t, err) @@ -858,7 +858,7 @@ func TestLargeGenesisValidator(t *testing.T) { // add 10 validators with the same voting power as the one added directly after genesis: for i := 0; i < 10; i++ { addedPubKey := ed25519.GenerateSecretKey().Public() - ap := encoding.PubKeyToProto(addedPubKey) + ap := crypto.PubKeyToProto(addedPubKey) addedVal := abci.ValidatorUpdate{PubKey: ap, Power: firstAddedValVotingPower} validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{addedVal}) assert.NoError(t, err) @@ -880,7 +880,7 @@ func TestLargeGenesisValidator(t *testing.T) { require.Equal(t, 10+2, len(state.NextValidators.Validators)) // remove genesis validator: - gp := encoding.PubKeyToProto(genesisPubKey) + gp := crypto.PubKeyToProto(genesisPubKey) removeGenesisVal := abci.ValidatorUpdate{PubKey: gp, Power: 0} fb = &abci.ResponseFinalizeBlock{ ValidatorUpdates: []abci.ValidatorUpdate{removeGenesisVal}, @@ -1143,7 +1143,6 @@ func TestStateProto(t *testing.T) { } for _, tt := range tc { - tt := tt pbs, err := tt.state.ToProto() if !tt.expPass1 { assert.Error(t, err) diff --git a/sei-tendermint/privval/grpc/client.go b/sei-tendermint/privval/grpc/client.go index 78e9aa22d2..56d70e1478 100644 --- a/sei-tendermint/privval/grpc/client.go +++ b/sei-tendermint/privval/grpc/client.go @@ -7,7 +7,6 @@ import ( "google.golang.org/grpc/status" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/libs/log" privvalproto "github.com/tendermint/tendermint/proto/tendermint/privval" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -62,7 +61,7 @@ func (sc *SignerClient) GetPubKey(ctx context.Context) (crypto.PubKey, error) { return crypto.PubKey{}, errStatus.Err() } - pk, err := encoding.PubKeyFromProto(resp.PubKey) + pk, err := crypto.PubKeyFromProto(resp.PubKey) if err != nil { return crypto.PubKey{}, err } diff --git a/sei-tendermint/privval/grpc/server.go b/sei-tendermint/privval/grpc/server.go index 8a3de0faa9..4c542d3a1e 100644 --- a/sei-tendermint/privval/grpc/server.go +++ b/sei-tendermint/privval/grpc/server.go @@ -7,7 +7,6 @@ import ( "google.golang.org/grpc/status" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/libs/log" privvalproto "github.com/tendermint/tendermint/proto/tendermint/privval" "github.com/tendermint/tendermint/types" @@ -42,7 +41,7 @@ func (ss *SignerServer) GetPubKey(ctx context.Context, req *privvalproto.PubKeyR return nil, status.Errorf(codes.NotFound, "error getting pubkey: %v", err) } ss.logger.Info("SignerServer: GetPubKey Success") - return &privvalproto.PubKeyResponse{PubKey: encoding.PubKeyToProto(pubKey)}, nil + return &privvalproto.PubKeyResponse{PubKey: crypto.PubKeyToProto(pubKey)}, nil } // SignVote receives a vote sign requests, attempts to sign it diff --git a/sei-tendermint/privval/grpc/server_test.go b/sei-tendermint/privval/grpc/server_test.go index ed79468c6c..3843f84793 100644 --- a/sei-tendermint/privval/grpc/server_test.go +++ b/sei-tendermint/privval/grpc/server_test.go @@ -8,7 +8,6 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/libs/log" tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/libs/utils" @@ -48,7 +47,7 @@ func TestGetPubKey(t *testing.T) { } else { pk, err := tc.pv.GetPubKey(ctx) require.NoError(t, err) - require.Equal(t, resp.PubKey, encoding.PubKeyToProto(pk)) + require.Equal(t, resp.PubKey, crypto.PubKeyToProto(pk)) } }) } diff --git a/sei-tendermint/privval/msgs_test.go b/sei-tendermint/privval/msgs_test.go index 77a01a8329..7449cfda78 100644 --- a/sei-tendermint/privval/msgs_test.go +++ b/sei-tendermint/privval/msgs_test.go @@ -10,7 +10,6 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto" privproto "github.com/tendermint/tendermint/proto/tendermint/privval" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -52,7 +51,7 @@ func exampleProposal() *types.Proposal { func TestPrivvalVectors(t *testing.T) { // WARNING: this key has to be stable for hashes to match. pk := ed25519.TestSecretKey([]byte("it's a secret")).Public() - ppk := encoding.PubKeyToProto(pk) + ppk := crypto.PubKeyToProto(pk) // Generate a simple vote vote := exampleVote() diff --git a/sei-tendermint/privval/signer_client.go b/sei-tendermint/privval/signer_client.go index 3a6f194d29..a2b15a34ff 100644 --- a/sei-tendermint/privval/signer_client.go +++ b/sei-tendermint/privval/signer_client.go @@ -6,7 +6,6 @@ import ( "time" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/libs/log" privvalproto "github.com/tendermint/tendermint/proto/tendermint/privval" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -94,12 +93,7 @@ func (sc *SignerClient) GetPubKey(ctx context.Context) (crypto.PubKey, error) { return crypto.PubKey{}, &RemoteSignerError{Code: int(resp.Error.Code), Description: resp.Error.Description} } - pk, err := encoding.PubKeyFromProto(resp.PubKey) - if err != nil { - return crypto.PubKey{}, err - } - - return pk, nil + return crypto.PubKeyFromProto(resp.PubKey) } // SignVote requests a remote signer to sign a vote diff --git a/sei-tendermint/privval/signer_requestHandler.go b/sei-tendermint/privval/signer_requestHandler.go index b0908c50c6..8d57d98106 100644 --- a/sei-tendermint/privval/signer_requestHandler.go +++ b/sei-tendermint/privval/signer_requestHandler.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto" privvalproto "github.com/tendermint/tendermint/proto/tendermint/privval" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -37,7 +36,7 @@ func DefaultValidationRequestHandler( if err != nil { return res, err } - pk := encoding.PubKeyToProto(pubKey) + pk := crypto.PubKeyToProto(pubKey) if err != nil { res = mustWrapMsg(&privvalproto.PubKeyResponse{ PubKey: cryptoproto.PublicKey{}, Error: &privvalproto.RemoteSignerError{Code: 0, Description: err.Error()}}) diff --git a/sei-tendermint/proto/tendermint/p2p/conn.pb.go b/sei-tendermint/proto/tendermint/p2p/conn.pb.go index 16ee463a6a..ee094b9aeb 100644 --- a/sei-tendermint/proto/tendermint/p2p/conn.pb.go +++ b/sei-tendermint/proto/tendermint/p2p/conn.pb.go @@ -5,7 +5,6 @@ package p2p import ( fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" crypto "github.com/tendermint/tendermint/proto/tendermint/crypto" io "io" @@ -97,8 +96,8 @@ func (m *PacketPong) XXX_DiscardUnknown() { var xxx_messageInfo_PacketPong proto.InternalMessageInfo type PacketMsg struct { - ChannelID int32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` - EOF bool `protobuf:"varint,2,opt,name=eof,proto3" json:"eof,omitempty"` + ChannelId int32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Eof bool `protobuf:"varint,2,opt,name=eof,proto3" json:"eof,omitempty"` Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` } @@ -135,16 +134,16 @@ func (m *PacketMsg) XXX_DiscardUnknown() { var xxx_messageInfo_PacketMsg proto.InternalMessageInfo -func (m *PacketMsg) GetChannelID() int32 { +func (m *PacketMsg) GetChannelId() int32 { if m != nil { - return m.ChannelID + return m.ChannelId } return 0 } -func (m *PacketMsg) GetEOF() bool { +func (m *PacketMsg) GetEof() bool { if m != nil { - return m.EOF + return m.Eof } return false } @@ -256,8 +255,9 @@ func (*Packet) XXX_OneofWrappers() []interface{} { } type AuthSigMessage struct { - PubKey crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key"` - Sig []byte `protobuf:"bytes,2,opt,name=sig,proto3" json:"sig,omitempty"` + PubKey *crypto.PublicKey `protobuf:"bytes,1,opt,name=pub_key,json=pubKey,proto3" json:"pub_key,omitempty"` + Sig []byte `protobuf:"bytes,2,opt,name=sig,proto3" json:"sig,omitempty"` + SeiGigaConnection bool `protobuf:"varint,3,opt,name=sei_giga_connection,json=seiGigaConnection,proto3" json:"sei_giga_connection,omitempty"` } func (m *AuthSigMessage) Reset() { *m = AuthSigMessage{} } @@ -293,11 +293,11 @@ func (m *AuthSigMessage) XXX_DiscardUnknown() { var xxx_messageInfo_AuthSigMessage proto.InternalMessageInfo -func (m *AuthSigMessage) GetPubKey() crypto.PublicKey { +func (m *AuthSigMessage) GetPubKey() *crypto.PublicKey { if m != nil { return m.PubKey } - return crypto.PublicKey{} + return nil } func (m *AuthSigMessage) GetSig() []byte { @@ -307,6 +307,13 @@ func (m *AuthSigMessage) GetSig() []byte { return nil } +func (m *AuthSigMessage) GetSeiGigaConnection() bool { + if m != nil { + return m.SeiGigaConnection + } + return false +} + func init() { proto.RegisterType((*PacketPing)(nil), "tendermint.p2p.PacketPing") proto.RegisterType((*PacketPong)(nil), "tendermint.p2p.PacketPong") @@ -318,32 +325,32 @@ func init() { func init() { proto.RegisterFile("tendermint/p2p/conn.proto", fileDescriptor_22474b5527c8fa9f) } var fileDescriptor_22474b5527c8fa9f = []byte{ - // 395 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0x3d, 0x8f, 0xd3, 0x40, - 0x10, 0xf5, 0xe2, 0xbb, 0x1c, 0x99, 0x84, 0x13, 0x5a, 0x51, 0x24, 0xd1, 0xc9, 0x89, 0x5c, 0xa5, - 0x40, 0xb6, 0x64, 0x44, 0x03, 0xa2, 0xc0, 0x7c, 0x88, 0xd3, 0x29, 0xba, 0xc8, 0x74, 0x34, 0x96, - 0x3f, 0x96, 0xf5, 0x2a, 0xe7, 0xdd, 0x55, 0x76, 0x5d, 0xf8, 0x5f, 0xf0, 0xb3, 0x8e, 0xee, 0x4a, - 0xaa, 0x08, 0x39, 0x7f, 0x04, 0x79, 0x1d, 0x88, 0x23, 0x71, 0xdd, 0x7b, 0x33, 0xf3, 0xe6, 0x43, - 0xf3, 0x60, 0xaa, 0x09, 0xcf, 0xc9, 0xb6, 0x64, 0x5c, 0xfb, 0x32, 0x90, 0x7e, 0x26, 0x38, 0xf7, - 0xe4, 0x56, 0x68, 0x81, 0x2f, 0x8f, 0x29, 0x4f, 0x06, 0x72, 0xf6, 0x82, 0x0a, 0x2a, 0x4c, 0xca, - 0x6f, 0x51, 0x57, 0x35, 0xbb, 0xea, 0x35, 0xc8, 0xb6, 0xb5, 0xd4, 0xc2, 0xdf, 0x90, 0x5a, 0x75, - 0x59, 0x77, 0x0c, 0xb0, 0x4e, 0xb2, 0x0d, 0xd1, 0x6b, 0xc6, 0x69, 0x8f, 0x09, 0x4e, 0xdd, 0x02, - 0x86, 0x1d, 0x5b, 0x29, 0x8a, 0x5f, 0x02, 0x64, 0x45, 0xc2, 0x39, 0xb9, 0x8b, 0x59, 0x3e, 0x41, - 0x0b, 0xb4, 0x3c, 0x0f, 0x9f, 0x35, 0xbb, 0xf9, 0xf0, 0x43, 0x17, 0xbd, 0xfe, 0x18, 0x0d, 0x0f, - 0x05, 0xd7, 0x39, 0x9e, 0x82, 0x4d, 0xc4, 0xf7, 0xc9, 0x93, 0x05, 0x5a, 0x3e, 0x0d, 0x2f, 0x9a, - 0xdd, 0xdc, 0xfe, 0x74, 0xfb, 0x39, 0x6a, 0x63, 0x18, 0xc3, 0x59, 0x9e, 0xe8, 0x64, 0x62, 0x2f, - 0xd0, 0x72, 0x1c, 0x19, 0xec, 0xfe, 0x44, 0x30, 0xe8, 0x46, 0xe1, 0x77, 0x30, 0x92, 0x06, 0xc5, - 0x92, 0x71, 0x6a, 0x06, 0x8d, 0x82, 0x99, 0x77, 0x7a, 0xaa, 0x77, 0xdc, 0xf9, 0x8b, 0x15, 0x81, - 0xfc, 0xc7, 0xfa, 0x72, 0xc1, 0xa9, 0x59, 0xe0, 0x71, 0xb9, 0x38, 0x91, 0x0b, 0x4e, 0xf1, 0x1b, - 0x38, 0xb0, 0xb8, 0x54, 0xd4, 0xac, 0x38, 0x0a, 0xa6, 0xff, 0x57, 0xaf, 0x54, 0x2b, 0x1e, 0xca, - 0xbf, 0x24, 0x3c, 0x07, 0x5b, 0x55, 0xa5, 0x1b, 0xc3, 0xe5, 0xfb, 0x4a, 0x17, 0x5f, 0x19, 0x5d, - 0x11, 0xa5, 0x12, 0x4a, 0xf0, 0x5b, 0xb8, 0x90, 0x55, 0x1a, 0x6f, 0x48, 0x7d, 0x38, 0xe7, 0xaa, - 0xdf, 0xb1, 0xfb, 0x89, 0xb7, 0xae, 0xd2, 0x3b, 0x96, 0xdd, 0x90, 0x3a, 0x3c, 0xbb, 0xdf, 0xcd, - 0xad, 0x68, 0x20, 0xab, 0xf4, 0x86, 0xd4, 0xf8, 0x39, 0xd8, 0x8a, 0x75, 0x87, 0x8c, 0xa3, 0x16, - 0x86, 0xb7, 0xf7, 0x8d, 0x83, 0x1e, 0x1a, 0x07, 0xfd, 0x6e, 0x1c, 0xf4, 0x63, 0xef, 0x58, 0x0f, - 0x7b, 0xc7, 0xfa, 0xb5, 0x77, 0xac, 0x6f, 0xaf, 0x29, 0xd3, 0x45, 0x95, 0x7a, 0x99, 0x28, 0xfd, - 0xde, 0xd7, 0xfb, 0x0e, 0x32, 0xee, 0x38, 0xb5, 0x54, 0x3a, 0x30, 0xd1, 0x57, 0x7f, 0x02, 0x00, - 0x00, 0xff, 0xff, 0x30, 0xfd, 0xb2, 0x8d, 0x6b, 0x02, 0x00, 0x00, + // 387 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x52, 0x3d, 0x6f, 0xe2, 0x40, + 0x10, 0xf5, 0x1e, 0x07, 0x07, 0x03, 0x42, 0x77, 0x7b, 0x0d, 0x20, 0xce, 0x42, 0xae, 0xa8, 0x6c, + 0xc9, 0x27, 0x9a, 0x93, 0xae, 0x38, 0xae, 0xb8, 0x8b, 0x10, 0x8a, 0xe5, 0x74, 0x69, 0x2c, 0x7f, + 0x6c, 0x96, 0x15, 0x78, 0x77, 0xc5, 0xae, 0x0b, 0xff, 0x84, 0x74, 0xf9, 0x59, 0x49, 0x47, 0x99, + 0x32, 0x82, 0x3f, 0x12, 0xd9, 0x26, 0x60, 0xa4, 0xa4, 0x7b, 0x6f, 0x67, 0xde, 0xf8, 0xcd, 0xf8, + 0xc1, 0x50, 0x13, 0x9e, 0x90, 0x6d, 0xca, 0xb8, 0x76, 0xa4, 0x2b, 0x9d, 0x58, 0x70, 0x6e, 0xcb, + 0xad, 0xd0, 0x02, 0xf7, 0xcf, 0x25, 0x5b, 0xba, 0x72, 0x34, 0xae, 0xb5, 0xc6, 0xdb, 0x5c, 0x6a, + 0xe1, 0xac, 0x49, 0xae, 0xaa, 0x6e, 0xab, 0x07, 0xe0, 0x85, 0xf1, 0x9a, 0x68, 0x8f, 0x71, 0x5a, + 0x63, 0x82, 0x53, 0xcb, 0x83, 0x4e, 0xc5, 0x96, 0x8a, 0xe2, 0x1f, 0x00, 0xf1, 0x2a, 0xe4, 0x9c, + 0x6c, 0x02, 0x96, 0x0c, 0xd0, 0x04, 0x4d, 0x9b, 0x7e, 0xe7, 0xf8, 0x72, 0x95, 0xe0, 0xaf, 0xd0, + 0x20, 0xe2, 0x6e, 0xf0, 0x69, 0x82, 0xa6, 0x6d, 0xbf, 0x80, 0x18, 0xc3, 0xe7, 0x24, 0xd4, 0xe1, + 0xa0, 0x31, 0x41, 0xd3, 0x9e, 0x5f, 0x62, 0xeb, 0x09, 0x41, 0xab, 0x1a, 0x89, 0x7f, 0x43, 0x57, + 0x96, 0x28, 0x90, 0x8c, 0xd3, 0x72, 0x60, 0xd7, 0x1d, 0xd9, 0x97, 0xe6, 0xed, 0xb3, 0xb7, 0xff, + 0x86, 0x0f, 0xf2, 0xc4, 0xea, 0x72, 0xc1, 0x69, 0xf9, 0xdd, 0x8f, 0xe5, 0xe2, 0x42, 0x2e, 0x38, + 0xc5, 0xbf, 0xe0, 0xc8, 0x82, 0x54, 0xd1, 0xd2, 0x62, 0xd7, 0x1d, 0xbe, 0xaf, 0x5e, 0xaa, 0x42, + 0xdc, 0x91, 0x6f, 0x64, 0xde, 0x84, 0x86, 0xca, 0x52, 0xeb, 0x1e, 0x41, 0xff, 0x4f, 0xa6, 0x57, + 0x37, 0x8c, 0x2e, 0x89, 0x52, 0x21, 0x25, 0x78, 0x06, 0x5f, 0x64, 0x16, 0x05, 0x6b, 0x92, 0x1f, + 0xf7, 0x19, 0xd7, 0x47, 0x56, 0xc7, 0xb7, 0xbd, 0x2c, 0xda, 0xb0, 0x78, 0x41, 0x72, 0xbf, 0x25, + 0xb3, 0x68, 0x41, 0xf2, 0xe2, 0x76, 0x8a, 0x55, 0x3b, 0xf4, 0xfc, 0x02, 0x62, 0x1b, 0xbe, 0x2b, + 0xc2, 0x02, 0xca, 0x68, 0x18, 0x14, 0xbf, 0x96, 0xc4, 0x9a, 0x09, 0x5e, 0xfa, 0x6c, 0xfb, 0xdf, + 0x14, 0x61, 0xff, 0x18, 0x0d, 0xff, 0x9e, 0x0a, 0xf3, 0xeb, 0xc7, 0xbd, 0x89, 0x76, 0x7b, 0x13, + 0xbd, 0xec, 0x4d, 0xf4, 0x70, 0x30, 0x8d, 0xdd, 0xc1, 0x34, 0x9e, 0x0f, 0xa6, 0x71, 0x3b, 0xa3, + 0x4c, 0xaf, 0xb2, 0xc8, 0x8e, 0x45, 0xea, 0xd4, 0x82, 0x50, 0x8f, 0x4f, 0x91, 0x03, 0xe7, 0x32, + 0x4f, 0x51, 0xab, 0x7c, 0xfd, 0xf9, 0x1a, 0x00, 0x00, 0xff, 0xff, 0x3a, 0x00, 0x4f, 0xc6, 0x68, + 0x02, 0x00, 0x00, } func (m *PacketPing) Marshal() (dAtA []byte, err error) { @@ -419,9 +426,9 @@ func (m *PacketMsg) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x1a } - if m.EOF { + if m.Eof { i-- - if m.EOF { + if m.Eof { dAtA[i] = 1 } else { dAtA[i] = 0 @@ -429,8 +436,8 @@ func (m *PacketMsg) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x10 } - if m.ChannelID != 0 { - i = encodeVarintConn(dAtA, i, uint64(m.ChannelID)) + if m.ChannelId != 0 { + i = encodeVarintConn(dAtA, i, uint64(m.ChannelId)) i-- dAtA[i] = 0x8 } @@ -552,6 +559,16 @@ func (m *AuthSigMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.SeiGigaConnection { + i-- + if m.SeiGigaConnection { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x18 + } if len(m.Sig) > 0 { i -= len(m.Sig) copy(dAtA[i:], m.Sig) @@ -559,16 +576,18 @@ func (m *AuthSigMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x12 } - { - size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err + if m.PubKey != nil { + { + size, err := m.PubKey.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintConn(dAtA, i, uint64(size)) } - i -= size - i = encodeVarintConn(dAtA, i, uint64(size)) + i-- + dAtA[i] = 0xa } - i-- - dAtA[i] = 0xa return len(dAtA) - i, nil } @@ -607,10 +626,10 @@ func (m *PacketMsg) Size() (n int) { } var l int _ = l - if m.ChannelID != 0 { - n += 1 + sovConn(uint64(m.ChannelID)) + if m.ChannelId != 0 { + n += 1 + sovConn(uint64(m.ChannelId)) } - if m.EOF { + if m.Eof { n += 2 } l = len(m.Data) @@ -674,12 +693,17 @@ func (m *AuthSigMessage) Size() (n int) { } var l int _ = l - l = m.PubKey.Size() - n += 1 + l + sovConn(uint64(l)) + if m.PubKey != nil { + l = m.PubKey.Size() + n += 1 + l + sovConn(uint64(l)) + } l = len(m.Sig) if l > 0 { n += 1 + l + sovConn(uint64(l)) } + if m.SeiGigaConnection { + n += 2 + } return n } @@ -820,9 +844,9 @@ func (m *PacketMsg) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ChannelID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) } - m.ChannelID = 0 + m.ChannelId = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowConn @@ -832,14 +856,14 @@ func (m *PacketMsg) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ChannelID |= int32(b&0x7F) << shift + m.ChannelId |= int32(b&0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field EOF", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Eof", wireType) } var v int for shift := uint(0); ; shift += 7 { @@ -856,7 +880,7 @@ func (m *PacketMsg) Unmarshal(dAtA []byte) error { break } } - m.EOF = bool(v != 0) + m.Eof = bool(v != 0) case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) @@ -1125,6 +1149,9 @@ func (m *AuthSigMessage) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } + if m.PubKey == nil { + m.PubKey = &crypto.PublicKey{} + } if err := m.PubKey.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } @@ -1163,6 +1190,26 @@ func (m *AuthSigMessage) Unmarshal(dAtA []byte) error { m.Sig = []byte{} } iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SeiGigaConnection", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowConn + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.SeiGigaConnection = bool(v != 0) default: iNdEx = preIndex skippy, err := skipConn(dAtA[iNdEx:]) diff --git a/sei-tendermint/proto/tendermint/p2p/conn.proto b/sei-tendermint/proto/tendermint/p2p/conn.proto index 807c2a50ee..984883371c 100644 --- a/sei-tendermint/proto/tendermint/p2p/conn.proto +++ b/sei-tendermint/proto/tendermint/p2p/conn.proto @@ -2,7 +2,6 @@ syntax = "proto3"; package tendermint.p2p; -import "gogoproto/gogo.proto"; import "tendermint/crypto/keys.proto"; option go_package = "github.com/tendermint/tendermint/proto/tendermint/p2p"; @@ -12,8 +11,8 @@ message PacketPing {} message PacketPong {} message PacketMsg { - int32 channel_id = 1 [(gogoproto.customname) = "ChannelID"]; - bool eof = 2 [(gogoproto.customname) = "EOF"]; + int32 channel_id = 1; + bool eof = 2; bytes data = 3; } @@ -26,6 +25,7 @@ message Packet { } message AuthSigMessage { - tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; + tendermint.crypto.PublicKey pub_key = 1; bytes sig = 2; + bool sei_giga_connection = 3; } diff --git a/sei-tendermint/proto/tendermint/p2p/pex.pb.go b/sei-tendermint/proto/tendermint/p2p/pex.pb.go index 15ccce15e5..30b5565773 100644 --- a/sei-tendermint/proto/tendermint/p2p/pex.pb.go +++ b/sei-tendermint/proto/tendermint/p2p/pex.pb.go @@ -5,7 +5,6 @@ package p2p import ( fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" @@ -24,7 +23,7 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type PexAddress struct { - URL string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"` + Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"` } func (m *PexAddress) Reset() { *m = PexAddress{} } @@ -60,9 +59,9 @@ func (m *PexAddress) XXX_DiscardUnknown() { var xxx_messageInfo_PexAddress proto.InternalMessageInfo -func (m *PexAddress) GetURL() string { +func (m *PexAddress) GetUrl() string { if m != nil { - return m.URL + return m.Url } return "" } @@ -104,7 +103,7 @@ func (m *PexRequest) XXX_DiscardUnknown() { var xxx_messageInfo_PexRequest proto.InternalMessageInfo type PexResponse struct { - Addresses []PexAddress `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses"` + Addresses []*PexAddress `protobuf:"bytes,1,rep,name=addresses,proto3" json:"addresses,omitempty"` } func (m *PexResponse) Reset() { *m = PexResponse{} } @@ -140,7 +139,7 @@ func (m *PexResponse) XXX_DiscardUnknown() { var xxx_messageInfo_PexResponse proto.InternalMessageInfo -func (m *PexResponse) GetAddresses() []PexAddress { +func (m *PexResponse) GetAddresses() []*PexAddress { if m != nil { return m.Addresses } @@ -242,27 +241,25 @@ func init() { func init() { proto.RegisterFile("tendermint/p2p/pex.proto", fileDescriptor_81c2f011fd13be57) } var fileDescriptor_81c2f011fd13be57 = []byte{ - // 311 bytes of a gzipped FileDescriptorProto + // 283 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x28, 0x49, 0xcd, 0x4b, 0x49, 0x2d, 0xca, 0xcd, 0xcc, 0x2b, 0xd1, 0x2f, 0x30, 0x2a, 0xd0, 0x2f, 0x48, 0xad, 0xd0, 0x2b, - 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x43, 0xc8, 0xe8, 0x15, 0x18, 0x15, 0x48, 0x89, 0xa4, 0xe7, - 0xa7, 0xe7, 0x83, 0xa5, 0xf4, 0x41, 0x2c, 0x88, 0x2a, 0x25, 0x63, 0x2e, 0xae, 0x80, 0xd4, 0x0a, - 0xc7, 0x94, 0x94, 0xa2, 0xd4, 0xe2, 0x62, 0x21, 0x49, 0x2e, 0xe6, 0xd2, 0xa2, 0x1c, 0x09, 0x46, - 0x05, 0x46, 0x0d, 0x4e, 0x27, 0xf6, 0x47, 0xf7, 0xe4, 0x99, 0x43, 0x83, 0x7c, 0x82, 0x40, 0x62, - 0x5e, 0x2c, 0x1c, 0x4c, 0x02, 0xcc, 0x5e, 0x2c, 0x1c, 0xcc, 0x02, 0x2c, 0x4a, 0x3c, 0x60, 0x4d, - 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x4a, 0xbe, 0x5c, 0xdc, 0x60, 0x5e, 0x71, 0x41, 0x7e, - 0x5e, 0x71, 0xaa, 0x90, 0x1d, 0x17, 0x67, 0x22, 0xc4, 0xb8, 0xd4, 0x62, 0x09, 0x46, 0x05, 0x66, - 0x0d, 0x6e, 0x23, 0x29, 0x3d, 0x54, 0xb7, 0xe8, 0x21, 0xac, 0x74, 0x62, 0x39, 0x71, 0x4f, 0x9e, - 0x21, 0x08, 0xa1, 0x45, 0x69, 0x01, 0x23, 0xd8, 0x74, 0xdf, 0xd4, 0xe2, 0xe2, 0xc4, 0xf4, 0x54, - 0x21, 0x5b, 0x2e, 0xee, 0x82, 0xd4, 0x8a, 0xf8, 0x22, 0x88, 0x65, 0x12, 0xcc, 0x0a, 0x8c, 0x38, - 0x0c, 0x84, 0x3a, 0xc7, 0x83, 0x21, 0x88, 0xab, 0x00, 0xce, 0x13, 0x72, 0xe0, 0xe2, 0x81, 0x68, - 0x87, 0xb8, 0x4e, 0x82, 0x05, 0xac, 0x5f, 0x1a, 0xab, 0x7e, 0x88, 0x12, 0x0f, 0x86, 0x20, 0xee, - 0x02, 0x04, 0xd7, 0x89, 0x95, 0x8b, 0xb9, 0xb8, 0x34, 0xd7, 0x8b, 0x85, 0x83, 0x51, 0x80, 0x09, - 0x12, 0x0a, 0x4e, 0xfe, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, - 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x65, 0x9a, - 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x8f, 0x14, 0x33, 0xc8, 0x91, 0x04, - 0x8e, 0x01, 0xd4, 0x58, 0x4b, 0x62, 0x03, 0x8b, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xa7, - 0x1d, 0xdd, 0x6f, 0xce, 0x01, 0x00, 0x00, + 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x43, 0xc8, 0xe8, 0x15, 0x18, 0x15, 0x28, 0x69, 0x71, 0x71, + 0x05, 0xa4, 0x56, 0x38, 0xa6, 0xa4, 0x14, 0xa5, 0x16, 0x17, 0x0b, 0x09, 0x70, 0x31, 0x97, 0x16, + 0xe5, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0x98, 0x5e, 0x2c, 0x1c, 0x4c, 0x02, 0xcc, + 0x5e, 0x2c, 0x1c, 0xcc, 0x02, 0x2c, 0x4a, 0x3c, 0x60, 0xb5, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, + 0x25, 0x4a, 0xee, 0x5c, 0xdc, 0x60, 0x5e, 0x71, 0x41, 0x7e, 0x5e, 0x71, 0xaa, 0x90, 0x05, 0x17, + 0x67, 0x22, 0xc4, 0x94, 0xd4, 0x62, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x29, 0x3d, 0x54, + 0xcb, 0xf4, 0x10, 0x36, 0x05, 0x21, 0x14, 0x2b, 0x2d, 0x60, 0x04, 0x9b, 0xeb, 0x9b, 0x5a, 0x5c, + 0x9c, 0x98, 0x9e, 0x2a, 0x64, 0xcb, 0xc5, 0x5d, 0x90, 0x5a, 0x11, 0x5f, 0x04, 0xb1, 0x46, 0x82, + 0x59, 0x81, 0x11, 0x87, 0x51, 0x50, 0x87, 0x78, 0x30, 0x04, 0x71, 0x15, 0xc0, 0x79, 0x42, 0x0e, + 0x5c, 0x3c, 0x10, 0xed, 0x10, 0x77, 0x49, 0xb0, 0x80, 0xf5, 0x4b, 0x63, 0xd5, 0x0f, 0x51, 0xe2, + 0xc1, 0x10, 0xc4, 0x5d, 0x80, 0xe0, 0x3a, 0xb1, 0x72, 0x31, 0x17, 0x97, 0xe6, 0x7a, 0xb1, 0x70, + 0x30, 0x0a, 0x30, 0x41, 0xfc, 0xef, 0xe4, 0x7f, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, + 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, + 0x0c, 0x51, 0xa6, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x48, 0x81, + 0x8e, 0x1c, 0xfe, 0xa0, 0x70, 0xd7, 0x47, 0x8d, 0x90, 0x24, 0x36, 0xb0, 0xa8, 0x31, 0x20, 0x00, + 0x00, 0xff, 0xff, 0x58, 0x86, 0x8b, 0x44, 0xa9, 0x01, 0x00, 0x00, } func (m *PexAddress) Marshal() (dAtA []byte, err error) { @@ -285,10 +282,10 @@ func (m *PexAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.URL) > 0 { - i -= len(m.URL) - copy(dAtA[i:], m.URL) - i = encodeVarintPex(dAtA, i, uint64(len(m.URL))) + if len(m.Url) > 0 { + i -= len(m.Url) + copy(dAtA[i:], m.Url) + i = encodeVarintPex(dAtA, i, uint64(len(m.Url))) i-- dAtA[i] = 0xa } @@ -446,7 +443,7 @@ func (m *PexAddress) Size() (n int) { } var l int _ = l - l = len(m.URL) + l = len(m.Url) if l > 0 { n += 1 + l + sovPex(uint64(l)) } @@ -551,7 +548,7 @@ func (m *PexAddress) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field URL", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Url", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -579,7 +576,7 @@ func (m *PexAddress) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.URL = string(dAtA[iNdEx:postIndex]) + m.Url = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex @@ -710,7 +707,7 @@ func (m *PexResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Addresses = append(m.Addresses, PexAddress{}) + m.Addresses = append(m.Addresses, &PexAddress{}) if err := m.Addresses[len(m.Addresses)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } diff --git a/sei-tendermint/proto/tendermint/p2p/pex.proto b/sei-tendermint/proto/tendermint/p2p/pex.proto index ecdca50dc9..95d34e6e0d 100644 --- a/sei-tendermint/proto/tendermint/p2p/pex.proto +++ b/sei-tendermint/proto/tendermint/p2p/pex.proto @@ -2,20 +2,17 @@ syntax = "proto3"; package tendermint.p2p; -import "gogoproto/gogo.proto"; - option go_package = "github.com/tendermint/tendermint/proto/tendermint/p2p"; message PexAddress { - string url = 1 [(gogoproto.customname) = "URL"]; - reserved 2, 3; // See https://github.com/tendermint/spec/pull/352 + string url = 1; } message PexRequest {} message PexResponse { - repeated PexAddress addresses = 1 [(gogoproto.nullable) = false]; + repeated PexAddress addresses = 1; } message PexMessage { diff --git a/sei-tendermint/rpc/client/rpc_test.go b/sei-tendermint/rpc/client/rpc_test.go index b8c3c5cac5..aa4bc370a8 100644 --- a/sei-tendermint/rpc/client/rpc_test.go +++ b/sei-tendermint/rpc/client/rpc_test.go @@ -16,7 +16,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto/encoding" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/internal/mempool" rpccore "github.com/tendermint/tendermint/internal/rpc/core" tmjson "github.com/tendermint/tendermint/libs/json" @@ -557,7 +557,7 @@ func TestClientMethodCalls(t *testing.T) { err = abci.ReadMessage(bytes.NewReader(qres.Value), &v) require.NoError(t, err, "Error reading query result, value %v", qres.Value) - pk, err := encoding.PubKeyFromProto(v.PubKey) + pk, err := crypto.PubKeyFromProto(v.PubKey) require.NoError(t, err) require.Equal(t, pv.Key.PubKey, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value)) diff --git a/sei-tendermint/test/e2e/app/app.go b/sei-tendermint/test/e2e/app/app.go index b65de0a1b9..bdf4c33706 100644 --- a/sei-tendermint/test/e2e/app/app.go +++ b/sei-tendermint/test/e2e/app/app.go @@ -14,6 +14,7 @@ import ( "github.com/tendermint/tendermint/abci/example/code" abci "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/proto/tendermint/types" @@ -393,7 +394,10 @@ func (app *Application) validatorUpdates(height uint64) (abci.ValidatorUpdates, if err != nil { return nil, fmt.Errorf("invalid ed25519 pubkey value %q: %w", keyString, err) } - valUpdates = append(valUpdates, abci.UpdateValidator(pubKey, int64(power), app.cfg.KeyType)) + valUpdates = append(valUpdates, abci.ValidatorUpdate{ + PubKey: crypto.PubKeyToProto(pubKey), + Power: int64(power), + }) } // the validator updates could be returned in arbitrary order, diff --git a/sei-tendermint/test/fuzz/tests/p2p_secretconnection_test.go b/sei-tendermint/test/fuzz/tests/p2p_secretconnection_test.go index 7c7cb38ed8..271828dc06 100644 --- a/sei-tendermint/test/fuzz/tests/p2p_secretconnection_test.go +++ b/sei-tendermint/test/fuzz/tests/p2p_secretconnection_test.go @@ -4,28 +4,28 @@ package tests import ( "bytes" + "context" "fmt" "io" - "log" + "net" "testing" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/internal/libs/async" - sc "github.com/tendermint/tendermint/internal/p2p/conn" + "github.com/tendermint/tendermint/internal/p2p/conn" + "github.com/tendermint/tendermint/libs/utils/require" + "github.com/tendermint/tendermint/libs/utils/scope" ) func FuzzP2PSecretConnection(f *testing.F) { - f.Fuzz(func(t *testing.T, data []byte) { - fuzz(data) - }) + f.Fuzz(fuzz) } -func fuzz(data []byte) { +func fuzz(t *testing.T, data []byte) { if len(data) == 0 { return } - fooConn, barConn := makeSecretConnPair() + fooConn, barConn := makeSecretConnPair(t) // Run Write in a separate goroutine because if data is greater than 1024 // bytes, each Write must be followed by Read (see io.Pipe documentation). @@ -61,13 +61,17 @@ func fuzz(data []byte) { } type kvstoreConn struct { - *io.PipeReader - *io.PipeWriter + net.Conn + reader *io.PipeReader + writer *io.PipeWriter } +func (drw kvstoreConn) Read(data []byte) (n int, err error) { return drw.reader.Read(data) } +func (drw kvstoreConn) Write(data []byte) (n int, err error) { return drw.writer.Write(data) } + func (drw kvstoreConn) Close() (err error) { - err2 := drw.PipeWriter.CloseWithError(io.EOF) - err1 := drw.PipeReader.Close() + err2 := drw.writer.CloseWithError(io.EOF) + err1 := drw.reader.Close() if err2 != nil { return err } @@ -78,58 +82,33 @@ func (drw kvstoreConn) Close() (err error) { func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) { barReader, fooWriter := io.Pipe() fooReader, barWriter := io.Pipe() - return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter} + return kvstoreConn{reader: fooReader, writer: fooWriter}, kvstoreConn{reader: barReader, writer: barWriter} } -func makeSecretConnPair() (fooSecConn, barSecConn *sc.SecretConnection) { - var ( - fooConn, barConn = makeKVStoreConnPair() - fooPrvKey = ed25519.GenerateSecretKey() - fooPubKey = fooPrvKey.Public() - barPrvKey = ed25519.GenerateSecretKey() - barPubKey = barPrvKey.Public() - ) +func makeSecretConnPair(tb testing.TB) (sc1 *conn.SecretConnection, sc2 *conn.SecretConnection) { + ctx := tb.Context() + c1, c2 := makeKVStoreConnPair() + k1 := ed25519.GenerateSecretKey() + k2 := ed25519.GenerateSecretKey() // Make connections from both sides in parallel. - var trs, ok = async.Parallel( - func(_ int) (val any, abort bool, err error) { - fooSecConn, err = sc.MakeSecretConnection(fooConn, fooPrvKey) - if err != nil { - log.Printf("failed to establish SecretConnection for foo: %v", err) - return nil, true, err - } - remotePubBytes := fooSecConn.RemotePubKey() - if remotePubBytes != barPubKey { - err = fmt.Errorf("unexpected fooSecConn.RemotePubKey. Expected %v, got %v", - barPubKey, fooSecConn.RemotePubKey()) - log.Print(err) - return nil, true, err - } - return nil, false, nil - }, - func(_ int) (val any, abort bool, err error) { - barSecConn, err = sc.MakeSecretConnection(barConn, barPrvKey) - if barSecConn == nil { - log.Printf("failed to establish SecretConnection for bar: %v", err) - return nil, true, err - } - remotePubBytes := barSecConn.RemotePubKey() - if remotePubBytes != fooPubKey { - err = fmt.Errorf("unexpected barSecConn.RemotePubKey. Expected %v, got %v", - fooPubKey, barSecConn.RemotePubKey()) - log.Print(err) - return nil, true, err - } - return nil, false, nil - }, - ) - - if trs.FirstError() != nil { - log.Fatalf("unexpected error: %v", trs.FirstError()) - } - if !ok { - log.Fatal("Unexpected task abortion") + err := scope.Run(ctx, func(ctx context.Context, s scope.Scope) error { + s.Spawn(func() error { + var err error + sc1, err = conn.MakeSecretConnection(ctx, c1, k1) + return err + }) + s.Spawn(func() error { + var err error + sc2, err = conn.MakeSecretConnection(ctx, c2, k2) + return err + }) + return nil + }) + if err != nil { + tb.Fatal(err) } - - return fooSecConn, barSecConn + require.Equal(tb, k1.Public(), sc2.RemotePubKey()) + require.Equal(tb, k2.Public(), sc1.RemotePubKey()) + return sc1, sc2 } diff --git a/sei-tendermint/types/protobuf.go b/sei-tendermint/types/protobuf.go index c59ccdee02..d48dc78af5 100644 --- a/sei-tendermint/types/protobuf.go +++ b/sei-tendermint/types/protobuf.go @@ -2,7 +2,7 @@ package types import ( abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/encoding" + "github.com/tendermint/tendermint/crypto" ) //------------------------------------------------------- @@ -22,7 +22,7 @@ func (tm2pb) Validator(val *Validator) abci.Validator { func (tm2pb) ValidatorUpdate(val *Validator) abci.ValidatorUpdate { return abci.ValidatorUpdate{ - PubKey: encoding.PubKeyToProto(val.PubKey), + PubKey: crypto.PubKeyToProto(val.PubKey), Power: val.VotingPower, } } @@ -46,7 +46,7 @@ type pb2tm struct{} func (pb2tm) ValidatorUpdates(vals []abci.ValidatorUpdate) ([]*Validator, error) { tmVals := make([]*Validator, len(vals)) for i, v := range vals { - pub, err := encoding.PubKeyFromProto(v.PubKey) + pub, err := crypto.PubKeyFromProto(v.PubKey) if err != nil { return nil, err } diff --git a/sei-tendermint/types/protobuf_test.go b/sei-tendermint/types/protobuf_test.go index f931da0f69..0cc2a68e7d 100644 --- a/sei-tendermint/types/protobuf_test.go +++ b/sei-tendermint/types/protobuf_test.go @@ -9,7 +9,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/encoding" ) func TestABCIPubKey(t *testing.T) { @@ -19,8 +18,8 @@ func TestABCIPubKey(t *testing.T) { } func testABCIPubKey(t *testing.T, pk crypto.PubKey) error { - abciPubKey := encoding.PubKeyToProto(pk) - pk2, err := encoding.PubKeyFromProto(abciPubKey) + abciPubKey := crypto.PubKeyToProto(pk) + pk2, err := crypto.PubKeyFromProto(abciPubKey) require.NoError(t, err) require.Equal(t, pk, pk2) return nil diff --git a/sei-tendermint/types/validator.go b/sei-tendermint/types/validator.go index 6d16d74a56..de2bff3079 100644 --- a/sei-tendermint/types/validator.go +++ b/sei-tendermint/types/validator.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" "github.com/tendermint/tendermint/internal/jsontypes" tmrand "github.com/tendermint/tendermint/libs/rand" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -152,7 +151,7 @@ func ValidatorListString(vals []*Validator) string { // as its redundant with the pubkey. This also excludes ProposerPriority // which changes every round. func (v *Validator) Bytes() []byte { - pk := encoding.PubKeyToProto(v.PubKey) + pk := crypto.PubKeyToProto(v.PubKey) pbv := tmproto.SimpleValidator{ PubKey: &pk, VotingPower: v.VotingPower, @@ -172,7 +171,7 @@ func (v *Validator) ToProto() (*tmproto.Validator, error) { } return &tmproto.Validator{ Address: v.Address, - PubKey: encoding.PubKeyToProto(v.PubKey), + PubKey: crypto.PubKeyToProto(v.PubKey), VotingPower: v.VotingPower, ProposerPriority: v.ProposerPriority, }, nil @@ -185,7 +184,7 @@ func ValidatorFromProto(vp *tmproto.Validator) (*Validator, error) { return nil, errors.New("nil validator") } - pk, err := encoding.PubKeyFromProto(vp.PubKey) + pk, err := crypto.PubKeyFromProto(vp.PubKey) if err != nil { return nil, err }