Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev/signer #2

Merged
merged 22 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/service/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ var Cmd = &cobra.Command{

func registerCommands(cmd *cobra.Command) {
cmd.AddCommand(keygenCmd)
cmd.AddCommand(signCmd)
slbmax marked this conversation as resolved.
Show resolved Hide resolved
}
103 changes: 103 additions & 0 deletions cmd/service/run/sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package run

import (
"context"
"github.com/bnb-chain/tss-lib/v2/ecdsa/keygen"
tsslib "github.com/bnb-chain/tss-lib/v2/tss"
"github.com/hyle-team/tss-svc/cmd/utils"
"github.com/hyle-team/tss-svc/internal/p2p"
"github.com/hyle-team/tss-svc/internal/secrets/vault"
"github.com/hyle-team/tss-svc/internal/tss"
"github.com/hyle-team/tss-svc/internal/tss/session"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"os/signal"
"strconv"
"syscall"
)

var signCmd = &cobra.Command{
Use: "sign [data-string] [threshold]",
slbmax marked this conversation as resolved.
Show resolved Hide resolved
Args: cobra.ExactArgs(2),
PreRunE: func(cmd *cobra.Command, args []string) error {
if !utils.OutputValid() {
return errors.New("invalid output type")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := utils.ConfigFromFlags(cmd)
if err != nil {
return errors.Wrap(err, "failed to read config from flags")
}

dataToSign := args[0]
if len(dataToSign) == 0 {
return errors.Wrap(errors.New("empty data to-sign"), "invalid data")
}
arg2 := args[1]
threshold, err := strconv.Atoi(arg2)
if err != nil {
return errors.Wrap(err, "invalid threshold")
}

storage := vault.NewStorage(cfg.VaultClient())

// Configuring local data for LocalSignParty
localData := keygen.NewLocalPartySaveData(len(cfg.Parties()))
var partyIds []*tsslib.PartyID
for _, party := range cfg.Parties() {
partyIds = append(partyIds, party.Identifier())
}
localSaveData := keygen.BuildLocalSaveDataSubset(localData, tsslib.SortPartyIDs(partyIds))
slbmax marked this conversation as resolved.
Show resolved Hide resolved
account, err := storage.GetCoreAccount()
if err != nil {
return errors.Wrap(err, "failed to get core account")
}

errGroup := new(errgroup.Group)
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()

connectionManager := p2p.NewConnectionManager(cfg.Parties(), p2p.PartyStatus_SIGNING, cfg.Log().WithField("component", "connection_manager"))

session := session.NewSigningSession(
tss.LocalSignParty{
Address: account.CosmosAddress(),
Data: &localSaveData,
Threshold: threshold,
},
cfg.TSSParams().SigningSessionParams(),
cfg.Log().WithField("component", "signing_session"),
cfg.Parties(),
dataToSign,
connectionManager.GetReadyCount,
)

sessionManager := p2p.NewSessionManager(session)
errGroup.Go(func() error {
server := p2p.NewServer(cfg.GRPCListener(), sessionManager)
server.SetStatus(p2p.PartyStatus_SIGNING)
return server.Run(ctx)
})

errGroup.Go(func() error {
defer cancel()

if err := session.Run(ctx); err != nil {
return errors.Wrap(err, "failed to run signing session")
}
result, err := session.WaitFor()
if err != nil {
return errors.Wrap(err, "failed to obtain signing session result")
}

cfg.Log().Info("signing session successfully completed. Signature: ", result.String())
slbmax marked this conversation as resolved.
Show resolved Hide resolved

return nil
})

return errGroup.Wait()
},
}
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ replace (
require (
github.com/bnb-chain/tss-lib/v2 v2.0.2
github.com/cosmos/cosmos-sdk v0.46.13
github.com/ethereum/go-ethereum v1.10.26
github.com/hashicorp/vault/api v1.15.0
github.com/hyle-team/bridgeless-core v0.0.0-20241003084139-414cc4a6f73c
github.com/pkg/errors v0.9.1
Expand All @@ -42,7 +43,10 @@ require (
github.com/armon/go-metrics v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect
github.com/btcsuite/btcd v0.23.4 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
Expand All @@ -64,7 +68,6 @@ require (
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
github.com/ethereum/go-ethereum v1.10.26 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/getsentry/sentry-go v0.27.0 // indirect
github.com/go-gorp/gorp/v3 v3.1.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,8 @@ github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtyd
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts=
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce h1:YtWJF7RHm2pYCvA5t0RPmAaLUhREsKuKd+SLhxFbFeQ=
github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce/go.mod h1:0DVlHczLPewLcPGEIeUEzfOJhqGPQ0mJJRDBtD307+o=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I=
Expand Down
15 changes: 14 additions & 1 deletion internal/tss/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ type ParamsConfigurator interface {
}

type Params struct {
Keygen KeygenParams `fig:"keygen"`
Keygen KeygenParams `fig:"keygen"`
Signing SigningParams `fig:"signing"`
}

func (p Params) KeygenSessionParams() session.KeygenSessionParams {
Expand All @@ -28,11 +29,23 @@ func (p Params) KeygenSessionParams() session.KeygenSessionParams {
}
}

func (p Params) SigningSessionParams() session.SigningSessionParams {
return session.SigningSessionParams{
Id: p.Signing.Id,
StartTime: p.Signing.StartTime,
}
}

type KeygenParams struct {
Id string `fig:"session_id,required"`
StartTime time.Time `fig:"start_time,required"`
}

type SigningParams struct {
Id string `fig:"session_id,required"`
StartTime time.Time `fig:"start_time,required"`
}

type tssParamsConfigurator struct {
getter kv.Getter
once comfig.Once
Expand Down
3 changes: 2 additions & 1 deletion internal/tss/session/boundaries.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ package session
import "time"

const (
BoundaryKeygenSession = time.Minute
BoundaryKeygenSession = time.Minute
BoundarySigningSession = 10 * time.Second
)
122 changes: 122 additions & 0 deletions internal/tss/session/sign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package session

import (
"context"
"fmt"
"github.com/bnb-chain/tss-lib/v2/common"
"github.com/hyle-team/tss-svc/internal/core"
"github.com/hyle-team/tss-svc/internal/p2p"
"github.com/hyle-team/tss-svc/internal/tss"
"github.com/pkg/errors"
"gitlab.com/distributed_lab/logan/v3"
"sync"
"time"
)

type SigningSessionParams struct {
Id string
StartTime time.Time
}

type SigningSession struct {
slbmax marked this conversation as resolved.
Show resolved Hide resolved
params SigningSessionParams
logger *logan.Entry
wg *sync.WaitGroup

connectedPartiesCount func() int
partiesCount int

signingParty interface {
Run(ctx context.Context)
WaitFor() *common.SignatureData
Receive(sender core.Address, data *p2p.TssData)
}

data string
result *common.SignatureData
err error
}

func NewSigningSession(self tss.LocalSignParty, params SigningSessionParams, logger *logan.Entry, parties []p2p.Party, data string, connectedPartiesCountFunc func() int) *SigningSession {
return &SigningSession{
params: params,
wg: &sync.WaitGroup{},
logger: logger,
connectedPartiesCount: connectedPartiesCountFunc,
partiesCount: len(parties),
data: data,
signingParty: tss.NewSignParty(self, parties, data, params.Id, logger),
}
}

func (s *SigningSession) Run(ctx context.Context) error {
runDelay := time.Until(s.params.StartTime)
if runDelay <= 0 {
return errors.New("target time is in the past")
}

s.logger.Info(fmt.Sprintf("signing session will start in %s", runDelay))

select {
case <-ctx.Done():
s.logger.Info("signing session cancelled")
return nil
case <-time.After(runDelay):
}

if s.connectedPartiesCount() != s.partiesCount {
return errors.New("cannot start signing session: not all parties connected")
}

s.wg.Add(1)
go s.run(ctx)
return nil
}

func (s *SigningSession) run(ctx context.Context) {
defer s.wg.Done()

boundedCtx, cancel := context.WithTimeout(ctx, BoundarySigningSession)
defer cancel()

s.signingParty.Run(boundedCtx)
s.result = s.signingParty.WaitFor()
s.logger.Info("signing session finished")
if s.result != nil {
return
}

if err := boundedCtx.Err(); err != nil {
s.err = err
} else {
s.err = errors.New("signing session error occurred")
}
}

func (s *SigningSession) WaitFor() (*common.SignatureData, error) {
s.wg.Wait()
return s.result, s.err
}

func (s *SigningSession) Id() string {
return s.params.Id
}

func (s *SigningSession) Receive(request *p2p.SubmitRequest) error {
if request.Type != p2p.RequestType_SIGN {
return errors.New("invalid request type")
}

var data *p2p.TssData

if err := request.Data.UnmarshalTo(data); err != nil {
return errors.Wrap(err, "failed to unmarshal TSS request data")
}

sender, _ := core.AddressFromString(request.Sender)
s.signingParty.Receive(sender, data)
return nil
}

// RegisterIdChangeListener is a no-op for SigningSession
func (s *SigningSession) RegisterIdChangeListener(func(oldId, newId string)) {}
Loading