Skip to content

Commit

Permalink
ECDSA & EDDSA working w/ threshold-chain/tss-lib (#23)
Browse files Browse the repository at this point in the history
* ECDSA & EDDSA working w/ bnb-chain/tss-lib v1.3.5

https://gitlab.com/thorchain/tss/go-tss/-/merge_requests/264

* use github.com/btcsuite/btcd/btcec/v2

* Use threshold-network tss-lib fork (#28)

* Use threshold-network tss-lib fork

* Add lock in notifier to avoid data race

Write at 0x00c000288110 by goroutine 380:
  gitlab.com/thorchain/tss/go-tss/keysign.(*notifier).updateUnset()
      /home/runner/work/go-tss/go-tss/keysign/notifier.go:62 +0xe4
  gitlab.com/thorchain/tss/go-tss/keysign.(*SignatureNotifier).createOrUpdateNotifier()
      /home/runner/work/go-tss/go-tss/keysign/signature_notifier.go:252 +0x2fd
  gitlab.com/thorchain/tss/go-tss/keysign.(*SignatureNotifier).handleStream()
      /home/runner/work/go-tss/go-tss/keysign/signature_notifier.go:136 +0xa71
  gitlab.com/thorchain/tss/go-tss/keysign.(*SignatureNotifier).handleStream-fm()
      <autogenerated>:1 +0x4d
  github.com/libp2p/go-libp2p/p2p/host/basic.(*BasicHost).SetStreamHandler.func1()
      /home/runner/go/pkg/mod/github.com/zeta-chain/[email protected]/p2p/host/basic/basic_host.go:580 +0x86
  github.com/libp2p/go-libp2p/p2p/host/basic.(*BasicHost).newStreamHandler.func1()
      /home/runner/go/pkg/mod/github.com/zeta-chain/[email protected]/p2p/host/basic/basic_host.go:421 +0x74

Previous read at 0x00c000288110 by goroutine 208:
  gitlab.com/thorchain/tss/go-tss/keysign.(*notifier).readyToProcess()
      /home/runner/work/go-tss/go-tss/keysign/notifier.go:51 +0xd46
  gitlab.com/thorchain/tss/go-tss/keysign.TestSignatureNotifierBroadcastFirst()
      /home/runner/work/go-tss/go-tss/keysign/signature_notifier_test.go:162 +0xdb8
  testing.tRunner()
      /opt/hostedtoolcache/go/1.20.14/x64/src/testing/testing.go:1576 +0x216
  testing.(*T).Run.func1()
      /opt/hostedtoolcache/go/1.20.14/x64/src/testing/testing.go:1629 +0x47

---------

Co-authored-by: sumamu <[email protected]>
  • Loading branch information
gartnera and sumamu authored Sep 16, 2024
1 parent 05876ac commit 89fee4b
Show file tree
Hide file tree
Showing 71 changed files with 2,539 additions and 559 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ go.sum: go.mod
go mod verify

test:
@go test --race ./...
@go test --race -timeout 30m ./...

test-watch: clear
@gow -c test -tags testnet -mod=readonly ./...

unittest:
@go test --race -v -coverprofile=coverage.out -timeout 15m ./...
@go test --race -v -coverprofile=coverage.out -timeout 30m ./...
@go tool cover -func=coverage.out

lint-pre:
Expand Down
2 changes: 1 addition & 1 deletion blame/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package blame
import (
"sync"

btss "github.com/bnb-chain/tss-lib/tss"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
btss "gitlab.com/thorchain/tss/tss-lib/tss"
)

type Manager struct {
Expand Down
24 changes: 19 additions & 5 deletions blame/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"errors"
"fmt"

btss "github.com/bnb-chain/tss-lib/tss"
mapset "github.com/deckarep/golang-set"
"github.com/libp2p/go-libp2p/core/peer"
btss "gitlab.com/thorchain/tss/tss-lib/tss"

"gitlab.com/thorchain/tss/go-tss/conversion"
"gitlab.com/thorchain/tss/go-tss/messages"
Expand Down Expand Up @@ -132,7 +132,7 @@ func (m *Manager) TssWrongShareBlame(wiredMsg *messages.WireMessage) (string, er
// this blame blames the node fail to send the shares to the node
// with batch signing, we need to put the accepted shares into different message group
// then search the missing share for each keysign message
func (m *Manager) TssMissingShareBlame(rounds int) ([]Node, bool, error) {
func (m *Manager) TssMissingShareBlame(rounds int, algo messages.Algo) ([]Node, bool, error) {
acceptedShareForMsg := make(map[string][][]string)
var blameNodes []Node
var peers []string
Expand All @@ -156,22 +156,36 @@ func (m *Manager) TssMissingShareBlame(rounds int) ([]Node, bool, error) {
if len(el)+1 == len(m.PartyIDtoP2PID) {
continue
}

switch algo {
// we find whether the missing share is in unicast
if rounds == messages.TSSKEYGENROUNDS {
case messages.ECDSAKEYGEN:
// we are processing the keygen and if the missing shares is in second round(index=1)
// we mark it as the unicast.
if index == 1 {
isUnicast = true
}
}
if rounds == messages.TSSKEYSIGNROUNDS {
case messages.ECDSAKEYSIGN:
// we are processing the keysign and if the missing shares is in the 5 round(index<1)
// we all mark it as the unicast, because in some cases, the error will be detected
// in the following round, so we cannot "trust" the node stops at the current round.
if index < 5 {
isUnicast = true
}

case messages.EDDSAKEYGEN:
if index == 2 {
isUnicast = true
}
case messages.EDDSAKEYSIGN:
// currently, EDDSA do not have proof, so all the communication is broadcast.
isUnicast = false

default:
m.logger.Error().Msgf("fail to find the algorithm for this keygen/keysign, set unicast as false by default")
isUnicast = false
}

// we add our own id to avoid blame ourselves
// since all the local parties have the same id, so we just need to take one of them to get the peer

Expand Down
11 changes: 6 additions & 5 deletions blame/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import (
"sync"
"testing"

bkg "github.com/bnb-chain/tss-lib/ecdsa/keygen"
btss "github.com/bnb-chain/tss-lib/tss"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/libp2p/go-libp2p/core/peer"
bkg "gitlab.com/thorchain/tss/tss-lib/ecdsa/keygen"
btss "gitlab.com/thorchain/tss/tss-lib/tss"
. "gopkg.in/check.v1"

"gitlab.com/thorchain/tss/go-tss/conversion"
Expand Down Expand Up @@ -55,7 +56,7 @@ func (p *policyTestSuite) SetUpTest(c *C) {
outCh := make(chan btss.Message, len(partiesID))
endCh := make(chan bkg.LocalPartySaveData, len(partiesID))
ctx := btss.NewPeerContext(partiesID)
params := btss.NewParameters(ctx, localPartyID, len(partiesID), 3)
params := btss.NewParameters(btcec.S256(), ctx, localPartyID, len(partiesID), 3)
keyGenParty := bkg.NewLocalParty(params, outCh, endCh)

testPartyMap := new(sync.Map)
Expand Down Expand Up @@ -129,14 +130,14 @@ func (p *policyTestSuite) TestTssMissingShareBlame(c *C) {
acceptedShares[RoundInfo{0, "testRound", "123:0"}] = []string{"1", "2"}
acceptedShares[RoundInfo{1, "testRound", "123:0"}] = []string{"1"}
blameMgr.acceptShareLocker.Unlock()
nodes, _, err := blameMgr.TssMissingShareBlame(2)
nodes, _, err := blameMgr.TssMissingShareBlame(2, messages.ECDSAKEYGEN)
c.Assert(err, IsNil)
c.Assert(nodes[0].Pubkey, Equals, localTestPubKeys[3])
// we test if the missing share happens in round2
blameMgr.acceptShareLocker.Lock()
acceptedShares[RoundInfo{0, "testRound", "123:0"}] = []string{"1", "2", "3"}
blameMgr.acceptShareLocker.Unlock()
nodes, _, err = blameMgr.TssMissingShareBlame(2)
nodes, _, err = blameMgr.TssMissingShareBlame(2, messages.ECDSAKEYGEN)
c.Assert(err, IsNil)
results := []string{nodes[0].Pubkey, nodes[1].Pubkey}
sort.Strings(results)
Expand Down
2 changes: 1 addition & 1 deletion blame/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"errors"
"sync"

btss "gitlab.com/thorchain/tss/tss-lib/tss"
btss "github.com/bnb-chain/tss-lib/tss"
)

const (
Expand Down
12 changes: 6 additions & 6 deletions cmd/tss-benchgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ import (
"sync/atomic"
"time"

"gitlab.com/thorchain/tss/tss-lib/common"
"gitlab.com/thorchain/tss/tss-lib/ecdsa/keygen"
"gitlab.com/thorchain/tss/tss-lib/test"
"gitlab.com/thorchain/tss/tss-lib/tss"
"github.com/bnb-chain/tss-lib/common"
"github.com/bnb-chain/tss-lib/ecdsa/keygen"
"github.com/bnb-chain/tss-lib/test"
"github.com/bnb-chain/tss-lib/tss"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/ipfs/go-log"
"github.com/pkg/errors"
"golang.org/x/text/language"
Expand Down Expand Up @@ -134,8 +135,7 @@ func runKeyGen(dir string, t, n int) {

// init the parties
for i := 0; i < len(pIDs); i++ {
params := tss.NewParameters(p2pCtx, pIDs[i], len(pIDs), t)
params.UNSAFE_setKGIgnoreH1H2Dupes(true)
params := tss.NewParameters(btcec.S256(), p2pCtx, pIDs[i], len(pIDs), t)
P := keygen.NewLocalParty(params, outCh, endCh, preParamTestData).(*keygen.LocalParty)
parties = append(parties, P)
go func(P *keygen.LocalParty) {
Expand Down
26 changes: 12 additions & 14 deletions cmd/tss-benchsign/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import (
"sync/atomic"
"time"

"gitlab.com/thorchain/tss/tss-lib/common"
"gitlab.com/thorchain/tss/tss-lib/ecdsa/keygen"
"gitlab.com/thorchain/tss/tss-lib/ecdsa/signing"
"gitlab.com/thorchain/tss/tss-lib/test"
"gitlab.com/thorchain/tss/tss-lib/tss"
"github.com/btcsuite/btcd/btcec"
"github.com/bnb-chain/tss-lib/common"
"github.com/bnb-chain/tss-lib/ecdsa/keygen"
"github.com/bnb-chain/tss-lib/ecdsa/signing"
"github.com/bnb-chain/tss-lib/test"
"github.com/bnb-chain/tss-lib/tss"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/ipfs/go-log"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
Expand Down Expand Up @@ -125,13 +125,13 @@ func runSign(dir string, t int) {

errCh := make(chan *tss.Error, len(signPIDs))
outCh := make(chan tss.Message, len(signPIDs))
endCh := make(chan *signing.SignatureData, len(signPIDs))
endCh := make(chan common.SignatureData, len(signPIDs))

updater := test.SharedPartyUpdater

// init the parties
for i := 0; i < len(signPIDs); i++ {
params := tss.NewParameters(p2pCtx, signPIDs[i], len(signPIDs), t)
params := tss.NewParameters(btcec.S256(), p2pCtx, signPIDs[i], len(signPIDs), t)
P := signing.NewLocalParty(msg, params, keys[i], outCh, endCh).(*signing.LocalParty)
parties = append(parties, P)
go func(P *signing.LocalParty) {
Expand Down Expand Up @@ -165,6 +165,7 @@ outer:
go updater(parties[dest[0].Index], msg, errCh)
}

//nolint
case data := <-endCh:
atomic.AddInt32(&ended, 1)
if atomic.LoadInt32(&ended) == int32(len(signPIDs)) {
Expand All @@ -175,8 +176,9 @@ outer:
X: pkX,
Y: pkY,
}
r := new(big.Int).SetBytes(data.Signature.GetR())
s := new(big.Int).SetBytes(data.Signature.GetS())

r := new(big.Int).SetBytes(data.GetR())
s := new(big.Int).SetBytes(data.GetS())
var ok bool
if ok = ecdsa.Verify(
&pk,
Expand All @@ -185,10 +187,6 @@ outer:
); !ok {
panic("ECDSA signature verification did not pass")
}
btcecSig := &btcec.Signature{R: r, S: s}
if ok = btcecSig.Verify(msg.Bytes(), (*btcec.PublicKey)(&pk)); !ok {
panic("ECDSA signature verification 2 did not pass")
}
break outer
}
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/tss-recovery/tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
"math/big"
"os"

"gitlab.com/thorchain/tss/tss-lib/ecdsa/keygen"
"github.com/btcsuite/btcd/btcec"
"github.com/bnb-chain/tss-lib/ecdsa/keygen"
"github.com/btcsuite/btcd/btcec/v2"
coskey "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
bech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
Expand Down Expand Up @@ -55,11 +55,11 @@ func getTssPubKey(x, y *big.Int) (string, sdk.AccAddress, error) {
if x == nil || y == nil {
return "", sdk.AccAddress{}, errors.New("invalid points")
}
tssPubKey := btcec.PublicKey{
Curve: btcec.S256(),
X: x,
Y: y,
}
X := &btcec.FieldVal{}
X.SetByteSlice(x.Bytes())
Y := &btcec.FieldVal{}
Y.SetByteSlice(y.Bytes())
tssPubKey := btcec.NewPublicKey(X, Y)
pubKeyCompressed := coskey.PubKey{
Key: tssPubKey.SerializeCompressed(),
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/tss-recovery/tss-recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import (
"io/ioutil"
"os"

"gitlab.com/thorchain/tss/tss-lib/crypto/vss"
"github.com/bnb-chain/tss-lib/crypto/vss"
"github.com/btcsuite/btcd/btcec/v2"
. "github.com/decred/dcrd/dcrec/secp256k1"
)

Expand Down Expand Up @@ -40,7 +41,7 @@ func main() {
vssShares[i] = &share
}

tssPrivateKey, err := vssShares[:n].ReConstruct()
tssPrivateKey, err := vssShares[:n].ReConstruct(btcec.S256())
if err != nil {
fmt.Printf("error in tss verify")
}
Expand Down
12 changes: 11 additions & 1 deletion cmd/tss/mock_tss_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,17 @@ func (mts *MockTssServer) Keygen(req keygen.Request) (keygen.Response, error) {
if mts.failToKeyGen {
return keygen.Response{}, errors.New("you ask for it")
}
return keygen.NewResponse(conversion.GetRandomPubKey(), "whatever", common.Success, blame.Blame{}), nil
return keygen.NewResponse(common.ECDSA, conversion.GetRandomPubKey(), "whatever", common.Success, blame.Blame{}), nil
}

func (mts *MockTssServer) KeygenAllAlgo(req keygen.Request) ([]keygen.Response, error) {
if mts.failToKeyGen {
return []keygen.Response{{}}, errors.New("you ask for it")
}
return []keygen.Response{
keygen.NewResponse(common.ECDSA, conversion.GetRandomPubKey(), "whatever", common.Success, blame.Blame{}),
keygen.NewResponse(common.EdDSA, conversion.GetRandomPubKey(), "whatever", common.Success, blame.Blame{}),
}, nil
}

func (mts *MockTssServer) KeySign(req keysign.Request) (keysign.Response, error) {
Expand Down
37 changes: 37 additions & 0 deletions cmd/tss/tss_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func NewTssHttpServer(tssAddr string, t tss.Server) *TssHttpServer {
func (t *TssHttpServer) tssNewHandler() http.Handler {
router := mux.NewRouter()
router.Handle("/keygen", http.HandlerFunc(t.keygenHandler)).Methods(http.MethodPost)
router.Handle("/keygenall", http.HandlerFunc(t.keygenAllHandler)).Methods(http.MethodPost)
router.Handle("/keysign", http.HandlerFunc(t.keySignHandler)).Methods(http.MethodPost)
router.Handle("/ping", http.HandlerFunc(t.pingHandler)).Methods(http.MethodGet)
router.Handle("/p2pid", http.HandlerFunc(t.getP2pIDHandler)).Methods(http.MethodGet)
Expand Down Expand Up @@ -87,6 +88,42 @@ func (t *TssHttpServer) keygenHandler(w http.ResponseWriter, r *http.Request) {
}
}

func (t *TssHttpServer) keygenAllHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
defer func() {
if err := r.Body.Close(); nil != err {
t.logger.Error().Err(err).Msg("fail to close request body")
}
}()
t.logger.Info().Msg("receive key gen request")
decoder := json.NewDecoder(r.Body)
var keygenReq keygen.Request
if err := decoder.Decode(&keygenReq); nil != err {
t.logger.Error().Err(err).Msg("fail to decode keygen request")
w.WriteHeader(http.StatusBadRequest)
return
}

resp, err := t.tssServer.KeygenAllAlgo(keygenReq)
if err != nil {
t.logger.Error().Err(err).Msg("fail to key gen")
}
t.logger.Debug().Msgf("resp:%+v", resp)
buf, err := json.Marshal(resp)
if err != nil {
t.logger.Error().Err(err).Msg("fail to marshal response to json")
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = w.Write(buf)
if err != nil {
t.logger.Error().Err(err).Msg("fail to write to response")
}
}

func (t *TssHttpServer) keySignHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
Expand Down
2 changes: 1 addition & 1 deletion common/tss.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import (
"strings"
"sync"

btss "github.com/bnb-chain/tss-lib/tss"
tcrypto "github.com/cometbft/cometbft/crypto"
"github.com/cometbft/cometbft/crypto/secp256k1"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
btss "gitlab.com/thorchain/tss/tss-lib/tss"

"gitlab.com/thorchain/tss/go-tss/blame"
"gitlab.com/thorchain/tss/go-tss/conversion"
Expand Down
Loading

0 comments on commit 89fee4b

Please sign in to comment.