Skip to content

Commit

Permalink
tss and zetabridge
Browse files Browse the repository at this point in the history
  • Loading branch information
lumtis committed Apr 15, 2024
1 parent 9a63d23 commit d570f5e
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 125 deletions.
1 change: 0 additions & 1 deletion zetaclient/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ type ZetaCoreBridger interface {
txIndex int64,
) (string, error)
GetKeys() *keys.Keys
GetBlockHeight() (int64, error)
GetZetaBlockHeight() (int64, error)
GetLastBlockHeightByChain(chain chains.Chain) (*crosschaintypes.LastBlockHeight, error)
ListPendingCctx(chainID int64) ([]*crosschaintypes.CrossChainTx, uint64, error)
Expand Down
File renamed without changes.
File renamed without changes.
53 changes: 44 additions & 9 deletions zetaclient/tss/tss_signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ const (
)

type Key struct {
PubkeyInBytes []byte // FIXME: compressed pubkey?
PubkeyInBech32 string // FIXME: same above
PubkeyInBytes []byte
PubkeyInBech32 string
AddressInHex string
}

Expand All @@ -55,12 +55,15 @@ func NewTSSKey(pk string) (*Key, error) {
log.Error().Err(err).Msgf("GetPubKeyFromBech32 from %s", pk)
return nil, fmt.Errorf("GetPubKeyFromBech32: %w", err)
}

decompresspubkey, err := crypto.DecompressPubkey(pubkey.Bytes())
if err != nil {
return nil, fmt.Errorf("NewTSS: DecompressPubkey error: %w", err)
}

TSSKey.PubkeyInBytes = crypto.FromECDSAPub(decompresspubkey)
TSSKey.AddressInHex = crypto.PubkeyToAddress(*decompresspubkey).Hex()

return TSSKey, nil
}

Expand Down Expand Up @@ -98,6 +101,7 @@ func NewTSS(
if err != nil {
return nil, fmt.Errorf("SetupTSSServer error: %w", err)
}

newTss := TSS{
Server: server,
Keys: make(map[string]*Key),
Expand All @@ -112,14 +116,17 @@ func NewTSS(
if err != nil {
return nil, err
}

_, pubkeyInBech32, err := keys.GetKeyringKeybase(appContext.Config(), hotkeyPassword)
if err != nil {
return nil, err
}

err = newTss.VerifyKeysharesForPubkeys(tssHistoricalList, pubkeyInBech32)
if err != nil {
bridge.GetLogger().Error().Err(err).Msg("VerifyKeysharesForPubkeys fail")
}

keygenRes, err := newTss.CoreBridge.GetKeyGen()
if err != nil {
return nil, err
Expand All @@ -134,7 +141,13 @@ func NewTSS(
return &newTss, nil
}

func SetupTSSServer(peer p2p.AddrList, privkey tmcrypto.PrivKey, preParams *keygen.LocalPreParams, cfg config.Config, tssPassword string) (*tss.TssServer, error) {
func SetupTSSServer(
peer p2p.AddrList,
privkey tmcrypto.PrivKey,
preParams *keygen.LocalPreParams,
cfg config.Config,
tssPassword string,
) (*tss.TssServer, error) {

Check warning on line 150 in zetaclient/tss/tss_signer.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/tss/tss_signer.go#L150

Added line #L150 was not covered by tests
bootstrapPeers := peer
log.Info().Msgf("Peers AddrList %v", bootstrapPeers)

Expand All @@ -149,10 +162,12 @@ func SetupTSSServer(peer p2p.AddrList, privkey tmcrypto.PrivKey, preParams *keyg
tsspath = path.Join(homedir, ".Tss")
log.Info().Msgf("create temporary TSSPATH: %s", tsspath)
}

IP := cfg.PublicIP
if len(IP) == 0 {
log.Info().Msg("empty public IP in config")
}

tssServer, err := tss.NewTss(
bootstrapPeers,
6668,
Expand Down Expand Up @@ -192,7 +207,6 @@ func SetupTSSServer(peer p2p.AddrList, privkey tmcrypto.PrivKey, preParams *keyg
return tssServer, nil
}

// FIXME: does it return pubkey in compressed form or uncompressed?
func (tss *TSS) Pubkey() []byte {
return tss.Keys[tss.CurrentPubkey].PubkeyInBytes
}
Expand All @@ -208,6 +222,7 @@ func (tss *TSS) Sign(digest []byte, height uint64, nonce uint64, chain *chains.C
if optionalPubKey != "" {
tssPubkey = optionalPubKey
}

// #nosec G701 always in range
keysignReq := keysign.NewRequest(tssPubkey, []string{base64.StdEncoding.EncodeToString(H)}, int64(height), nil, "0.14.0")
tss.KeysignsTracker.StartMsgSign()
Expand All @@ -216,6 +231,7 @@ func (tss *TSS) Sign(digest []byte, height uint64, nonce uint64, chain *chains.C
if err != nil {
log.Warn().Msg("keysign fail")
}

if ksRes.Status == thorcommon.Fail {
log.Warn().Msgf("keysign status FAIL posting blame to core, blaming node(s): %#v", ksRes.Blame.BlameNodes)

Expand Down Expand Up @@ -246,21 +262,25 @@ func (tss *TSS) Sign(digest []byte, height uint64, nonce uint64, chain *chains.C
log.Warn().Err(err).Msgf("signature has length 0")
return [65]byte{}, fmt.Errorf("keysign fail: %s", err)
}

if !verifySignature(tssPubkey, signature, H) {
log.Error().Err(err).Msgf("signature verification failure")
return [65]byte{}, fmt.Errorf("signuature verification fail")
}

var sigbyte [65]byte
_, err = base64.StdEncoding.Decode(sigbyte[:32], []byte(signature[0].R))
if err != nil {
log.Error().Err(err).Msg("decoding signature R")
return [65]byte{}, fmt.Errorf("signuature verification fail")
}

_, err = base64.StdEncoding.Decode(sigbyte[32:64], []byte(signature[0].S))
if err != nil {
log.Error().Err(err).Msg("decoding signature S")
return [65]byte{}, fmt.Errorf("signuature verification fail")
}

_, err = base64.StdEncoding.Decode(sigbyte[64:65], []byte(signature[0].RecoveryID))
if err != nil {
log.Error().Err(err).Msg("decoding signature RecoveryID")
Expand Down Expand Up @@ -372,12 +392,15 @@ func (tss *TSS) SignBatch(digests [][]byte, height uint64, nonce uint64, chain *
func (tss *TSS) Validate() error {
evmAddress := tss.EVMAddress()
blankAddress := ethcommon.Address{}

if evmAddress == blankAddress {
return fmt.Errorf("invalid evm address : %s", evmAddress.String())
}

if tss.BTCAddressWitnessPubkeyHash() == nil {
return fmt.Errorf("invalid btc pub key hash : %s", tss.BTCAddress())
}

return nil
}

Expand Down Expand Up @@ -438,19 +461,22 @@ func (tss *TSS) VerifyKeysharesForPubkeys(tssList []observertypes.TSS, granteePu
}
return nil
}

func (tss *TSS) LoadTssFilesFromDirectory(tssPath string) error {
files, err := os.ReadDir(tssPath)
if err != nil {
fmt.Println("ReadDir error :", err.Error())
return err
}
found := false

var sharefiles []os.DirEntry
for _, file := range files {
if !file.IsDir() && strings.HasPrefix(filepath.Base(file.Name()), "localstate") {
sharefiles = append(sharefiles, file)
}
}

if len(sharefiles) > 0 {
sort.SliceStable(sharefiles, func(i, j int) bool {
fi, err := sharefiles[i].Info()
Expand Down Expand Up @@ -480,6 +506,7 @@ func (tss *TSS) LoadTssFilesFromDirectory(tssPath string) error {
}
}
}

if !found {
log.Info().Msg("TSS Keyshare file NOT found")
}
Expand Down Expand Up @@ -527,6 +554,7 @@ func TestKeysign(tssPubkey string, tssServer *tss.TssServer) error {
if err != nil {
log.Warn().Msg("keysign fail")
}

signature := ksRes.Signatures
// [{cyP8i/UuCVfQKDsLr1kpg09/CeIHje1FU6GhfmyMD5Q= D4jXTH3/CSgCg+9kLjhhfnNo3ggy9DTQSlloe3bbKAs= eY++Z2LwsuKG1JcghChrsEJ4u9grLloaaFZNtXI3Ujk= AA==}]
// 32B msg hash, 32B R, 32B S, 1B RC
Expand All @@ -536,13 +564,20 @@ func TestKeysign(tssPubkey string, tssServer *tss.TssServer) error {
log.Info().Msgf("signature has length 0, skipping verify")
return fmt.Errorf("signature has length 0")
}

verifySignature(tssPubkey, signature, H.Bytes())
if verifySignature(tssPubkey, signature, H.Bytes()) {
return nil
}

return fmt.Errorf("verify signature fail")
}

func IsEnvFlagEnabled(flag string) bool {
value := os.Getenv(flag)
return value == "true" || value == "1"

Check warning on line 578 in zetaclient/tss/tss_signer.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/tss/tss_signer.go#L576-L578

Added lines #L576 - L578 were not covered by tests
}

func verifySignature(tssPubkey string, signature []keysign.Signature, H []byte) bool {
if len(signature) == 0 {
log.Warn().Msg("verify_signature: empty signature array")
Expand All @@ -552,28 +587,33 @@ func verifySignature(tssPubkey string, signature []keysign.Signature, H []byte)
if err != nil {
log.Error().Msg("get pubkey from bech32 fail")
}

// verify the signature of msg.
var sigbyte [65]byte
_, err = base64.StdEncoding.Decode(sigbyte[:32], []byte(signature[0].R))
if err != nil {
log.Error().Err(err).Msg("decoding signature R")
return false
}

_, err = base64.StdEncoding.Decode(sigbyte[32:64], []byte(signature[0].S))
if err != nil {
log.Error().Err(err).Msg("decoding signature S")
return false
}

_, err = base64.StdEncoding.Decode(sigbyte[64:65], []byte(signature[0].RecoveryID))
if err != nil {
log.Error().Err(err).Msg("decoding signature RecoveryID")
return false
}

sigPublicKey, err := crypto.SigToPub(H, sigbyte[:])
if err != nil {
log.Error().Err(err).Msg("SigToPub error in verify_signature")
return false
}

compressedPubkey := crypto.CompressPubkey(sigPublicKey)
log.Info().Msgf("pubkey %s recovered pubkey %s", pubkey.String(), hex.EncodeToString(compressedPubkey))
return bytes.Equal(pubkey.Bytes(), compressedPubkey)
Expand Down Expand Up @@ -611,8 +651,3 @@ func getKeyAddrBTCWitnessPubkeyHash(tssPubkey string, chainID int64) (*btcutil.A
}
return addr, nil
}

func IsEnvFlagEnabled(flag string) bool {
value := os.Getenv(flag)
return value == "true" || value == "1"
}
12 changes: 0 additions & 12 deletions zetaclient/types/account_resp.go

This file was deleted.

1 change: 0 additions & 1 deletion zetaclient/types/ethish_test.go

This file was deleted.

24 changes: 0 additions & 24 deletions zetaclient/zetabridge/block_height.go

This file was deleted.

6 changes: 0 additions & 6 deletions zetaclient/zetabridge/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,12 +418,6 @@ func TestZetaCoreBridge_GetZetaBlockHeight(t *testing.T) {
require.NoError(t, err)
require.Equal(t, expectedOutput.Height, resp)
})

t.Run("get block height success", func(t *testing.T) {
resp, err := zetabridge.GetBlockHeight()
require.NoError(t, err)
require.Equal(t, expectedOutput.Height, resp)
})
}

func TestZetaCoreBridge_GetBaseGasPrice(t *testing.T) {
Expand Down
15 changes: 0 additions & 15 deletions zetaclient/zetabridge/zetacore_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@ import (
"sync"
"time"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/simapp/params"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
rpcclient "github.com/tendermint/tendermint/rpc/client"
"github.com/zeta-chain/zetacore/app"
"github.com/zeta-chain/zetacore/pkg/authz"
"github.com/zeta-chain/zetacore/pkg/chains"
crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types"
observertypes "github.com/zeta-chain/zetacore/x/observer/types"
"github.com/zeta-chain/zetacore/zetaclient/config"
corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context"
Expand Down Expand Up @@ -110,16 +105,6 @@ func NewZetaCoreBridge(
}, nil
}

// MakeLegacyCodec creates codec
func MakeLegacyCodec() *codec.LegacyAmino {
cdc := codec.NewLegacyAmino()
banktypes.RegisterLegacyAminoCodec(cdc)
authtypes.RegisterLegacyAminoCodec(cdc)
sdk.RegisterLegacyAminoCodec(cdc)
crosschaintypes.RegisterCodec(cdc)
return cdc
}

func (b *ZetaCoreBridge) GetLogger() *zerolog.Logger {
return &b.logger
}
Expand Down
Loading

0 comments on commit d570f5e

Please sign in to comment.