github.com/annchain/OG@v0.0.9/consensus/dkg/archive/dkg_partner.go (about)

     1  //// Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     2  ////
     3  //// Licensed under the Apache License, Version 2.0 (the "License");
     4  //// you may not use this file except in compliance with the License.
     5  //// You may obtain a copy of the License at
     6  ////
     7  ////     http://www.apache.org/licenses/LICENSE-2.0
     8  ////
     9  //// Unless required by applicable law or agreed to in writing, software
    10  //// distributed under the License is distributed on an "AS IS" BASIS,
    11  //// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  //// See the License for the specific language governing permissions and
    13  //// limitations under the License.
    14  package archive
    15  //
    16  //import (
    17  //	"bytes"
    18  //	"encoding/hex"
    19  //	"fmt"
    20  //	"github.com/annchain/OG/account"
    21  //	"github.com/annchain/OG/common"
    22  //	"github.com/annchain/OG/common/goroutine"
    23  //	"github.com/annchain/OG/common/hexutil"
    24  //	dkg2 "github.com/annchain/OG/consensus/dkg"
    25  //	"github.com/annchain/OG/consensus/term"
    26  //	"github.com/annchain/OG/og/message"
    27  //	"github.com/annchain/OG/types/p2p_message"
    28  //	"github.com/annchain/OG/types/tx_types"
    29  //	"github.com/prometheus/common/log"
    30  //	"sort"
    31  //	"strings"
    32  //	"sync"
    33  //
    34  //	"github.com/annchain/OG/common/ogcrypto"
    35  //	"github.com/annchain/kyber/v3"
    36  //	"github.com/annchain/kyber/v3/pairing/bn256"
    37  //	"github.com/annchain/kyber/v3/share/dkg/pedersen"
    38  //	"github.com/annchain/kyber/v3/share/vss/pedersen"
    39  //	"github.com/annchain/kyber/v3/sign/bls"
    40  //)
    41  //
    42  //// DkgPartner is the parter in a DKG group built to discuss a pub/privkey
    43  //// It will receive DKG messages and update the status.
    44  //// It is the handler for maintaining the DkgContext.
    45  //// Campaign or term change is not part of DKGPartner. Do their job in their own module.
    46  //type DkgPartner struct {
    47  //	//SessionId            uint32
    48  //	//dkgOn             bool
    49  //	myPublircKey      []byte
    50  //	context           *dkg2.DkgContext
    51  //	formerContext     *dkg2.DkgContext //used for case : context reset , but bft is still generating sequencer
    52  //	gossipStartCh     chan struct{}
    53  //	gossipStopCh      chan struct{}
    54  //	gossipReqCh       chan *p2p_message.MessageConsensusDkgDeal
    55  //	gossipRespCh      chan *p2p_message.MessageConsensusDkgDealResponse
    56  //	gossipSigSetspCh  chan *p2p_message.MessageConsensusDkgSigSets
    57  //	dealCache         map[common.Address]*p2p_message.MessageConsensusDkgDeal
    58  //	dealResponseCache map[common.Address][]*p2p_message.MessageConsensusDkgDealResponse
    59  //	dealSigSetsCache  map[common.Address]*p2p_message.MessageConsensusDkgSigSets
    60  //	respWaitingCache  map[uint32][]*p2p_message.MessageConsensusDkgDealResponse
    61  //	blsSigSets        map[common.Address]*tx_types.SigSet
    62  //	ready             bool
    63  //	isValidPartner    bool
    64  //
    65  //	mu        sync.RWMutex
    66  //	myAccount *account.Account
    67  //	term      *term.Term
    68  //	Hub       dkg2.P2PSender
    69  //
    70  //	OnDkgPublicKeyJointChan chan kyber.Point // joint pubkey is got
    71  //	OnGenesisPkChan         chan *p2p_message.MessageConsensusDkgGenesisPublicKey
    72  //	ConfigFilePath          string
    73  //}
    74  //
    75  //func NewDkgPartner(dkgOn bool, numParts, threshold int, dkgPublicKeyJointChan chan kyber.Point,
    76  //	genesisPkChan chan *p2p_message.MessageConsensusDkgGenesisPublicKey, t *term.Term) *DkgPartner {
    77  //	// init dkg context to store keys
    78  //	c := dkg2.NewDkgContext(bn256.NewSuiteG2())
    79  //	c.NbParticipants = numParts
    80  //	c.Threshold = threshold
    81  //	c.PartPubs = []kyber.Point{}
    82  //
    83  //	d := &DkgPartner{}
    84  //	d.context = c
    85  //
    86  //	// message channels
    87  //	d.gossipStartCh = make(chan struct{})
    88  //	d.gossipReqCh = make(chan *p2p_message.MessageConsensusDkgDeal, 100)
    89  //	d.gossipRespCh = make(chan *p2p_message.MessageConsensusDkgDealResponse, 100)
    90  //	d.gossipSigSetspCh = make(chan *p2p_message.MessageConsensusDkgSigSets, 100)
    91  //	d.gossipStopCh = make(chan struct{})
    92  //
    93  //	d.dkgOn = dkgOn
    94  //	if d.dkgOn {
    95  //		d.GenerateDkg() //todo fix later
    96  //		d.myPublicKey = d.context.CandidatePublicKey[0]
    97  //		d.context.MyPartSec = d.context.CandidatePartSec[0]
    98  //	}
    99  //
   100  //
   101  //	d.dealCache = make(map[common.Address]*p2p_message.MessageConsensusDkgDeal)
   102  //	d.dealResponseCache = make(map[common.Address][]*p2p_message.MessageConsensusDkgDealResponse)
   103  //	d.respWaitingCache = make(map[uint32][]*p2p_message.MessageConsensusDkgDealResponse)
   104  //	d.dealSigSetsCache = make(map[common.Address]*p2p_message.MessageConsensusDkgSigSets)
   105  //	d.blsSigSets = make(map[common.Address]*tx_types.SigSet)
   106  //	d.ready = false
   107  //	d.isValidPartner = false
   108  //
   109  //	d.OnDkgPublicKeyJointChan = dkgPublicKeyJointChan
   110  //	d.OnGenesisPkChan = genesisPkChan
   111  //	d.term = t
   112  //
   113  //	return d
   114  //}
   115  //
   116  ////func (d *DkgPartner) SetId(id int) {
   117  ////	d.context.MyIndex = uint32(id)
   118  ////}
   119  ////
   120  ////func (d *DkgPartner) SetAccount(myAccount *account.Account) {
   121  ////	d.myAccount = myAccount
   122  ////}
   123  ////
   124  ////func (d *DkgPartner) GetParticipantNumber() int {
   125  ////	return d.context.NbParticipants
   126  ////}
   127  ////
   128  ////func (d *DkgPartner) Reset(myCampaign *tx_types.Campaign) {
   129  ////	if myCampaign == nil {
   130  ////		log.Warn("nil campagin, I am not a dkg context")
   131  ////	}
   132  ////
   133  ////	d.mu.RLock()
   134  ////	defer d.mu.RUnlock()
   135  ////	partSecs := d.context.CandidatePartSec
   136  ////	pubKeys := d.context.CandidatePublicKey
   137  ////	//TODO: keep multiple history generations
   138  ////	d.formerContext = d.context
   139  ////	d.formerContext.CandidatePartSec = nil
   140  ////	d.formerContext.CandidatePublicKey = nil
   141  ////	p := NewDkgContext(bn256.NewSuiteG2())
   142  ////	p.NbParticipants = d.context.NbParticipants
   143  ////	p.Threshold = d.context.Threshold
   144  ////	p.PartPubs = []kyber.Point{}
   145  ////	if myCampaign != nil {
   146  ////		index := -1
   147  ////		if len(myCampaign.DkgPublicKey) != 0 {
   148  ////			for i, pubKeys := range pubKeys {
   149  ////				if bytes.Equal(pubKeys, myCampaign.DkgPublicKey) {
   150  ////					index = i
   151  ////				}
   152  ////			}
   153  ////		}
   154  ////		if index < 0 {
   155  ////			log.WithField("cp", myCampaign).WithField("pks", d.context.CandidatePublicKey).Warn("pk not found")
   156  ////			index = 0
   157  ////			panic(fmt.Sprintf("fix this, pk not found  %s ", myCampaign))
   158  ////		}
   159  ////		if index >= len(partSecs) {
   160  ////			panic(fmt.Sprint(index, partSecs, hexutil.Encode(myCampaign.DkgPublicKey)))
   161  ////		}
   162  ////		log.WithField("cp ", myCampaign).WithField("index ", index).WithField("sk ", partSecs[index]).Debug("reset with sk")
   163  ////		p.MyPartSec = partSecs[index]
   164  ////		p.CandidatePartSec = append(p.CandidatePartSec, partSecs[index:]...)
   165  ////		d.myPublicKey = pubKeys[index]
   166  ////		p.CandidatePublicKey = append(p.CandidatePublicKey, pubKeys[index:]...)
   167  ////	} else {
   168  ////		//
   169  ////	}
   170  ////	d.dkgOn = false
   171  ////	d.context = p
   172  ////	d.SessionId++
   173  ////
   174  ////	//d.dealCache = make(map[common.Address]*p2p_message.MessageConsensusDkgDeal)
   175  ////	//d.dealResponseCache = make(map[common.Address][]*p2p_message.MessageConsensusDkgDealResponse)
   176  ////	//d.respWaitingCache = make(map[uint32][]*p2p_message.MessageConsensusDkgDealResponse)
   177  ////	d.dealSigSetsCache = make(map[common.Address]*p2p_message.MessageConsensusDkgSigSets)
   178  ////	d.blsSigSets = make(map[common.Address]*tx_types.SigSet)
   179  ////	d.ready = false
   180  ////	log.WithField("len candidate pk", len(d.context.CandidatePublicKey)).WithField("termId", d.SessionId).Debug("dkg will reset")
   181  ////}
   182  //
   183  //func (d *DkgPartner) Start() {
   184  //	//TODO
   185  //	dkg2.log.Info("dkg start")
   186  //	goroutine.New(d.gossiploop)
   187  //}
   188  //
   189  //func (d *DkgPartner) Stop() {
   190  //	d.gossipStopCh <- struct{}{}
   191  //	dkg2.log.Info("dkg stoped")
   192  //}
   193  //
   194  ////func (d *DkgPartner) Log() *logrus.Entry {
   195  ////	return d.log()
   196  ////}
   197  //
   198  ////func (d *DkgPartner) On() {
   199  ////	d.dkgOn = true
   200  ////}
   201  //
   202  ////func (d *DkgPartner) IsValidPartner() bool {
   203  ////	return d.isValidPartner
   204  ////}
   205  //
   206  ////func (d *DkgPartner) generateDkg() []byte {
   207  ////	sec, pub := GenPartnerPair(d.context)
   208  ////	d.context.CandidatePartSec = append(d.context.CandidatePartSec, sec)
   209  ////	//d.context.PartPubs = []kyber.Point{pub}??
   210  ////	pk, _ := pub.MarshalBinary()
   211  ////	d.context.CandidatePublicKey = append(d.context.CandidatePublicKey, pk)
   212  ////	log.WithField("pk", hexutil.Encode(pk[:5])).
   213  ////		WithField("len pk", len(d.context.CandidatePublicKey)).
   214  ////		WithField("sk", sec).
   215  ////		Debug("gen dkg")
   216  ////	return pk
   217  ////}
   218  //
   219  ////func (d *DkgPartner) log() *logrus.Entry {
   220  ////	return log.WithField("me", d.context.MyIndex).WithField("termId", d.SessionId)
   221  ////}
   222  //
   223  ////func (d *DkgPartner) GenerateDkg() []byte {
   224  ////	d.mu.RLock()
   225  ////	defer d.mu.RUnlock()
   226  ////	return d.generateDkg()
   227  ////}
   228  //
   229  ////PublicKey current pk
   230  ////func (d *DkgPartner) PublicKey() []byte {
   231  ////	return d.myPublicKey
   232  ////}
   233  //
   234  //func (d *DkgPartner) StartGossip() {
   235  //	d.gossipStartCh <- struct{}{}
   236  //}
   237  //
   238  ////calculate seed
   239  ////func CalculateRandomSeed(jointSig []byte) []byte {
   240  ////	//TODO
   241  ////	h := sha256.New()
   242  ////	h.Write(jointSig)
   243  ////	seed := h.Sum(nil)
   244  ////	return seed
   245  ////}
   246  //
   247  //func (d *DkgPartner) getDeals() (DealsMap, error) {
   248  //	return d.context.Dkger.Deals()
   249  //}
   250  //
   251  ////func (d *DkgPartner) AddPartner(c *tx_types.Campaign) {
   252  ////	d.mu.Lock()
   253  ////	defer d.mu.Unlock()
   254  ////	publicKey := ogcrypto.Signer.PublicKeyFromBytes(c.PublicKey)
   255  ////	d.addPartner(c,publicKey)
   256  ////	return
   257  ////
   258  ////}
   259  //
   260  //func (d *DkgPartner) addPartner(c *tx_types.Campaign) {
   261  //	d.context.PartPubs = append(d.context.PartPubs, c.GetDkgPublicKey())
   262  //	if bytes.Equal(c.PublicKey, d.myAccount.PublicKey.KeyBytes) {
   263  //		d.context.MyIndex = uint32(len(d.context.PartPubs) - 1)
   264  //		dkg2.log.WithField("id ", d.context.MyIndex).Trace("my id")
   265  //	}
   266  //	dkg2.log.WithField("cp ", c).Trace("added context")
   267  //	d.context.addressIndex[c.Sender()] = len(d.context.PartPubs) - 1
   268  //}
   269  //
   270  //func (d *DkgPartner) GetBlsSigsets() []*tx_types.SigSet {
   271  //	var sigset []*tx_types.SigSet
   272  //	d.mu.RLock()
   273  //	defer d.mu.RUnlock()
   274  //	for _, sig := range d.blsSigSets {
   275  //		sigset = append(sigset, sig)
   276  //	}
   277  //	return sigset
   278  //}
   279  //
   280  //func (d *DkgPartner) GenerateDKGer() error {
   281  //	d.mu.Lock()
   282  //	defer d.mu.Unlock()
   283  //
   284  //	return d.context.GenerateDKGer()
   285  //}
   286  //
   287  //func (d *DkgPartner) ProcesssDeal(dd *dkg.Deal) (resp *dkg.Response, err error) {
   288  //	d.mu.Lock()
   289  //	defer d.mu.Unlock()
   290  //
   291  //	return d.context.Dkger.ProcessDeal(dd)
   292  //}
   293  //
   294  //func (d *DkgPartner) CheckAddress(addr common.Address) bool {
   295  //	if d.term.GetCandidate(addr) == nil {
   296  //		return false
   297  //	}
   298  //	d.mu.RLock()
   299  //	defer d.mu.RUnlock()
   300  //	_, ok := d.context.addressIndex[addr]
   301  //	return ok
   302  //}
   303  //
   304  //func (d *DkgPartner) SendGenesisPublicKey(genesisAccounts []ogcrypto.PublicKey) {
   305  //	log := d.log()
   306  //	for i := 0; i < len(genesisAccounts); i++ {
   307  //		msg := &p2p_message.MessageConsensusDkgGenesisPublicKey{
   308  //			DkgPublicKey: d.myPublicKey,
   309  //			PublicKey:    d.myAccount.PublicKey.KeyBytes,
   310  //		}
   311  //		msg.Signature = ogcrypto.Signer.Sign(d.myAccount.PrivateKey, msg.SignatureTargets()).KeyBytes
   312  //		if uint32(i) == d.context.MyIndex {
   313  //			log.Tracef("escape me %d ", d.context.MyIndex)
   314  //			//myself
   315  //			d.OnGenesisPkChan <- msg
   316  //			continue
   317  //		}
   318  //		dkg2.AnonymousSendMessage(message.MessageTypeConsensusDkgGenesisPublicKey, msg, &genesisAccounts[i])
   319  //		log.WithField("msg", msg).WithField("peer", i).Debug("send genesis pk to")
   320  //	}
   321  //}
   322  //
   323  //func (d *DkgPartner) getUnhandled() ([]*p2p_message.MessageConsensusDkgDeal, []*p2p_message.MessageConsensusDkgDealResponse) {
   324  //	var unhandledDeal []*p2p_message.MessageConsensusDkgDeal
   325  //	var unhandledResponse []*p2p_message.MessageConsensusDkgDealResponse
   326  //	d.mu.RLock()
   327  //	defer d.mu.RUnlock()
   328  //	for i := range d.dealCache {
   329  //		unhandledDeal = append(unhandledDeal, d.dealCache[i])
   330  //	}
   331  //	for i := range d.dealResponseCache {
   332  //		unhandledResponse = append(unhandledResponse, d.dealResponseCache[i]...)
   333  //	}
   334  //	if len(d.dealCache) == 0 {
   335  //		d.dealCache = make(map[common.Address]*p2p_message.MessageConsensusDkgDeal)
   336  //	}
   337  //	if len(d.dealResponseCache) == 0 {
   338  //		d.dealResponseCache = make(map[common.Address][]*p2p_message.MessageConsensusDkgDealResponse)
   339  //	}
   340  //	return unhandledDeal, unhandledResponse
   341  //}
   342  //
   343  //func (d *DkgPartner) sendUnhandledTochan(unhandledDeal []*p2p_message.MessageConsensusDkgDeal, unhandledResponse []*p2p_message.MessageConsensusDkgDealResponse) {
   344  //	if len(unhandledDeal) != 0 || len(unhandledResponse) != 0 {
   345  //		dkg2.log.WithField("unhandledDeal deals ", len(unhandledDeal)).WithField(
   346  //			"unhandledResponse", unhandledResponse).Debug("will process")
   347  //
   348  //		for _, v := range unhandledDeal {
   349  //			d.gossipReqCh <- v
   350  //		}
   351  //		for _, v := range unhandledResponse {
   352  //			d.gossipRespCh <- v
   353  //		}
   354  //		dkg2.log.WithField("unhandledDeal deals", len(unhandledDeal)).WithField(
   355  //			"unhandledResponse", len(unhandledResponse)).Debug("processed")
   356  //	}
   357  //}
   358  //
   359  //func (d *DkgPartner) unhandledSigSets() []*p2p_message.MessageConsensusDkgSigSets {
   360  //	d.mu.RLock()
   361  //	defer d.mu.RUnlock()
   362  //	var sigs []*p2p_message.MessageConsensusDkgSigSets
   363  //	for _, v := range d.dealSigSetsCache {
   364  //		sigs = append(sigs, v)
   365  //	}
   366  //	d.dealSigSetsCache = make(map[common.Address]*p2p_message.MessageConsensusDkgSigSets)
   367  //	return sigs
   368  //}
   369  //
   370  //func (d *DkgPartner) ProcessDeal(deal *dkg.Deal) (*dkg.Response, error) {
   371  //	d.mu.RLock()
   372  //	defer d.mu.RUnlock()
   373  //	responseDeal, err := d.context.Dkger.ProcessDeal(deal)
   374  //	if err == nil {
   375  //		d.context.dealsIndex[deal.Index] = true
   376  //	}
   377  //	return responseDeal, err
   378  //
   379  //}
   380  //
   381  ////ProcessWaitingResponse
   382  //func (d *DkgPartner) ProcessWaitingResponse(deal *dkg.Deal) {
   383  //	log := d.log()
   384  //	var resps []*p2p_message.MessageConsensusDkgDealResponse
   385  //	d.mu.RLock()
   386  //	resps, _ = d.respWaitingCache[deal.Index]
   387  //	delete(d.respWaitingCache, deal.Index)
   388  //	d.mu.RUnlock()
   389  //	if len(resps) != 0 {
   390  //		log.WithField("for index ", deal.Index).WithField("resps ", resps).trace("will process cached response")
   391  //		for _, r := range resps {
   392  //			d.gossipRespCh <- r
   393  //		}
   394  //		log.WithField("resps ", resps).trace("processed cached response")
   395  //	}
   396  //}
   397  //
   398  ////func (d *DkgPartner) sendDealsToCorrespondingPartner(deals DealsMap, termId uint32) {
   399  ////	//for generating deals, we use n partPubs, including our partPub. it generates  n-1 deals, excluding our own deal
   400  ////	//skip myself
   401  ////	log := d.log()
   402  ////	for i, deal := range deals {
   403  ////		data, _ := deal.MarshalMsg(nil)
   404  ////		msg := &p2p_message.MessageConsensusDkgDeal{
   405  ////			Data: data,
   406  ////			MyIndex:   message.MsgCounter.Get(),
   407  ////		}
   408  ////		addr := d.GetPartnerAddressByIndex(i)
   409  ////		if addr == nil {
   410  ////			panic("address not found")
   411  ////		}
   412  ////		if *addr == d.myAccount.Address {
   413  ////			//this is for me , skip myself
   414  ////			log.WithField("i ", i).WithField("to ", addr.TerminalString()).WithField("deal",
   415  ////				deal.TerminateString()).Error("send dkg deal to myself")
   416  ////			panic("send dkg deal to myself")
   417  ////		}
   418  ////		//not a candidate
   419  ////		cp := d.term.GetCandidate(*addr)
   420  ////		if cp == nil {
   421  ////			panic("campaign not found")
   422  ////		}
   423  ////		msg.Signature = ogcrypto.Signer.Sign(d.myAccount.PrivateKey, msg.SignatureTargets()).KeyBytes
   424  ////		msg.PublicKey = d.myAccount.PublicKey.KeyBytes
   425  ////		pk := ogcrypto.Signer.PublicKeyFromBytes(cp.PublicKey)
   426  ////		log.WithField("to ", addr.TerminalString()).WithField("deal",
   427  ////			deal.TerminateString()).WithField("msg", msg).trace("send dkg deal to")
   428  ////		dkg2.AnonymousSendMessage(message.MessageTypeConsensusDkgDeal, msg, &pk)
   429  ////	}
   430  ////	return
   431  ////}
   432  //
   433  //func (d *DkgPartner) GetId() uint32 {
   434  //	if d.context == nil {
   435  //		return 0
   436  //	}
   437  //	return d.context.MyIndex
   438  //}
   439  //
   440  //func (d *DkgPartner) gossiploop() {
   441  //	for {
   442  //		select {
   443  //		case <-d.gossipStartCh:
   444  //		//	log := d.log()
   445  //		//	log.trace("gossip dkg started")
   446  //		//	if !d.dkgOn {
   447  //		//		//i am not a consensus context
   448  //		//		log.Warn("why send to me")
   449  //		//		continue
   450  //		//	}
   451  //		//	err := d.GenerateDKGer()
   452  //		//	if err != nil {
   453  //		//		log.WithField("sk", d.context.MyPartSec).WithField("part pubs", d.context.PartPubs).WithError(err).Error("gen dkger fail")
   454  //		//		continue
   455  //		//	}
   456  //		//	d.mu.RLock()
   457  //		//	deals, err := d.getDeals()
   458  //		//	termid := d.SessionId
   459  //		//	d.mu.RUnlock()
   460  //		//	if err != nil {
   461  //		//		log.WithError(err).Error("generate dkg deal error")
   462  //		//		continue
   463  //		//	}
   464  //			unhandledDeal, unhandledResponse := d.getUnhandled()
   465  //			d.mu.RLock()
   466  //			//dkg is ready now, can process dkg msg
   467  //			d.ready = true
   468  //			d.mu.RUnlock()
   469  //			log.trace("dkg is ready")
   470  //			d.sendDealsToCorrespondingPartner(deals, termid)
   471  //			//process unhandled(cached) dkg msg
   472  //			d.sendUnhandledTochan(unhandledDeal, unhandledResponse)
   473  //
   474  //		case request := <-d.gossipReqCh:
   475  //			log := d.log()
   476  //			if !d.dkgOn {
   477  //				//not a consensus context
   478  //				log.Warn("why send to me")
   479  //				continue
   480  //			}
   481  //
   482  //			addr := ogcrypto.Signer.AddressFromPubKeyBytes(request.PublicKey)
   483  //			if !d.CacheDealsIfNotReady(addr, request) {
   484  //				log.WithField("deal ", request).trace("process later ,not ready yet")
   485  //				continue
   486  //			}
   487  //			var deal dkg.Deal
   488  //			_, err := deal.UnmarshalMsg(request.Data)
   489  //			if err != nil {
   490  //				log.WithError(err).Warn("unmarshal failed")
   491  //				continue
   492  //			}
   493  //			if !d.CheckAddress(addr) {
   494  //				log.WithField("deal ", request).Warn("not found  dkg context address  or campaign  for deal")
   495  //				continue
   496  //			}
   497  //			responseDeal, err := d.ProcessDeal(&deal)
   498  //			if err != nil {
   499  //				log.WithField("from address ", addr.TerminalString()).WithField("deal ", request).WithError(err).Warn("deal process error")
   500  //				continue
   501  //			}
   502  //			if responseDeal.Response.Status != vss.StatusApproval {
   503  //				log.WithField("deal ", request).WithError(err).Warn("deal process not StatusApproval")
   504  //				continue
   505  //			}
   506  //			respData, err := responseDeal.MarshalMsg(nil)
   507  //			if err != nil {
   508  //				log.WithField("deal ", request).WithError(err).Warn("deal process marshal error")
   509  //				continue
   510  //			}
   511  //
   512  //			//response := p2p_message.MessageConsensusDkgDealResponse{
   513  //			//	Data: respData,
   514  //			//	//MyIndex:   request.MyIndex,
   515  //			//	MyIndex: message.MsgCounter.Get(),
   516  //			//}
   517  //			//response.Signature = ogcrypto.Signer.Sign(d.myAccount.PrivateKey, response.SignatureTargets()).KeyBytes
   518  //			//response.PublicKey = d.myAccount.PublicKey.KeyBytes
   519  //			//log.WithField("to request ", request).WithField("response ", &response).trace("will send response")
   520  //			//broadcast response to all context
   521  //
   522  //			//for k, v := range d.term.Candidates() {
   523  //			//	if k == d.myAccount.Address {
   524  //			//		continue
   525  //			//	}
   526  //			//	msgCopy := response
   527  //			//	pk := ogcrypto.Signer.PublicKeyFromBytes(v.PublicKey)
   528  //			//	goroutine.New(func() {
   529  //			//		dkg2.AnonymousSendMessage(message.MessageTypeConsensusDkgDealResponse, &msgCopy, &pk)
   530  //			//	})
   531  //			//}
   532  //			//and sent to myself ? already processed inside dkg,skip myself
   533  //			d.ProcessWaitingResponse(&deal)
   534  //
   535  //		case response := <-d.gossipRespCh:
   536  //			//log := d.log()
   537  //			//var resp dkg.Response
   538  //			//_, err := resp.UnmarshalMsg(response.Data)
   539  //			//if err != nil {
   540  //			//	log.WithError(err).Warn("verify signature failed")
   541  //			//	continue
   542  //			//}
   543  //			//if !d.dkgOn {
   544  //			//	//not a consensus context
   545  //			//	log.Warn("why send to me")
   546  //			//	continue
   547  //			//}
   548  //			addr := ogcrypto.Signer.AddressFromPubKeyBytes(response.PublicKey)
   549  //			if !d.CacheResponseIfNotReady(addr, response) {
   550  //				log.WithField("response ", resp).trace("process later ,not ready yet")
   551  //				continue
   552  //			}
   553  //
   554  //			if !d.CheckAddress(addr) {
   555  //				log.WithField("address ", addr.TerminalString()).WithField("resp ", response).WithField("deal ", response).Warn(
   556  //					"not found  dkg  context or campaign msg for address  of this  deal")
   557  //				continue
   558  //			}
   559  //			if !d.CacheResponseIfDealNotReceived(&resp, response) {
   560  //				log.WithField("addr ", addr.TerminalString()).WithField("for index ", resp.Index).trace("deal  not received yet")
   561  //				continue
   562  //			}
   563  //
   564  //			just, err := d.ProcessResponse(&resp)
   565  //			if err != nil {
   566  //				log.WithField("req ", response).WithField("rsp ", resp).WithField("just ", just).WithError(err).Warn("ProcessResponse failed")
   567  //				continue
   568  //			}
   569  //			log.WithField("response ", resp).Trace("process response ok")
   570  //			d.mu.RLock()
   571  //			d.context.responseNumber++
   572  //			d.mu.RUnlock()
   573  //			log.WithField("response number", d.context.responseNumber).Trace("dkg")
   574  //			//will got  (n-1)*(n-1) response
   575  //			if d.context.responseNumber < (d.context.NbParticipants-1)*(d.context.NbParticipants-1) {
   576  //				continue
   577  //			}
   578  //			log.trace("got response done")
   579  //			d.mu.RLock()
   580  //			jointPub, err := d.context.RecoverPub()
   581  //			d.mu.RUnlock()
   582  //			if err != nil {
   583  //				log.WithError(err).Warn("get recover pub key fail")
   584  //				continue
   585  //			}
   586  //			// send public key to changeTerm loop.
   587  //			// TODO
   588  //			// this channel may be changed later.
   589  //			log.WithField("bls key", jointPub).Trace("joint pubkey")
   590  //			//d.ann.dkgPkCh <- jointPub
   591  //			var msg p2p_message.MessageConsensusDkgSigSets
   592  //			msg.PkBls, _ = jointPub.MarshalBinary()
   593  //			msg.Signature = ogcrypto.Signer.Sign(d.myAccount.PrivateKey, msg.SignatureTargets()).KeyBytes
   594  //			msg.PublicKey = d.myAccount.PublicKey.KeyBytes
   595  //
   596  //			for k, v := range d.term.Candidates() {
   597  //				if k == d.myAccount.Address {
   598  //					continue
   599  //				}
   600  //				msgCopy := msg
   601  //				pk := ogcrypto.Signer.PublicKeyFromBytes(v.PublicKey)
   602  //				goroutine.New(func() {
   603  //					dkg2.AnonymousSendMessage(message.MessageTypeConsensusDkgSigSets, &msgCopy, &pk)
   604  //				})
   605  //			}
   606  //
   607  //			d.addSigsets(d.myAccount.Address, &tx_types.SigSet{PublicKey: msg.PublicKey, Signature: msg.Signature})
   608  //			sigCaches := d.unhandledSigSets()
   609  //			for _, sigSets := range sigCaches {
   610  //				d.gossipSigSetspCh <- sigSets
   611  //			}
   612  //
   613  //		case response := <-d.gossipSigSetspCh:
   614  //			log := d.log()
   615  //			pkBls, err := bn256.UnmarshalBinaryPointG2(response.PkBls)
   616  //			if err != nil {
   617  //				log.WithError(err).Warn("verify signature failed")
   618  //				continue
   619  //			}
   620  //			if !d.dkgOn {
   621  //				//not a consensus context
   622  //				log.Warn("why send to me")
   623  //				continue
   624  //			}
   625  //			addr := ogcrypto.Signer.AddressFromPubKeyBytes(response.PublicKey)
   626  //			if !d.CacheSigSetsIfNotReady(addr, response) {
   627  //				log.WithField("response ",
   628  //					response).trace("process later sigsets ,not ready yet")
   629  //				continue
   630  //			}
   631  //			if !d.CheckAddress(addr) {
   632  //				log.WithField("address ", addr.TerminalString()).WithField("resp ", response).WithField("deal ", response).Warn(
   633  //					"not found  dkg  context or campaign msg for address  of this  deal")
   634  //				continue
   635  //			}
   636  //			if !pkBls.Equal(d.context.JointPubKey) {
   637  //				log.WithField("got pkbls ", pkBls).WithField("joint pk ", d.context.JointPubKey).Warn("pk bls mismatch")
   638  //				continue
   639  //			}
   640  //			d.addSigsets(addr, &tx_types.SigSet{PublicKey: response.PublicKey, Signature: response.Signature})
   641  //
   642  //			if len(d.blsSigSets) >= d.context.NbParticipants {
   643  //				log.Info("got enough sig sets")
   644  //				d.context.KeyShare, err = d.context.Dkger.DistKeyShare()
   645  //				if err != nil {
   646  //					log.WithError(err).Error("key share err")
   647  //				}
   648  //				d.OnDkgPublicKeyJointChan <- d.context.JointPubKey
   649  //				d.ready = false
   650  //				d.clearCache()
   651  //
   652  //			}
   653  //
   654  //		case <-d.gossipStopCh:
   655  //			log := d.log()
   656  //			log.Info("got quit signal dkg gossip stopped")
   657  //			return
   658  //		}
   659  //	}
   660  //}
   661  //
   662  //func (d *DkgPartner) clearCache() {
   663  //	d.dealCache = make(map[common.Address]*p2p_message.MessageConsensusDkgDeal)
   664  //	d.dealResponseCache = make(map[common.Address][]*p2p_message.MessageConsensusDkgDealResponse)
   665  //	d.respWaitingCache = make(map[uint32][]*p2p_message.MessageConsensusDkgDealResponse)
   666  //}
   667  //
   668  ////CacheResponseIfDealNotReceived
   669  //func (d *DkgPartner) CacheResponseIfDealNotReceived(resp *dkg.Response, response *p2p_message.MessageConsensusDkgDealResponse) (ok bool) {
   670  //	log := d.log()
   671  //	d.mu.RLock()
   672  //	defer d.mu.RUnlock()
   673  //	if v := d.context.dealsIndex[resp.Index]; !v && resp.Index != d.context.MyIndex {
   674  //		//if addr is my address , it  is not in the index list ,process them
   675  //		resps, _ := d.respWaitingCache[resp.Index]
   676  //		resps = append(resps, response)
   677  //		d.respWaitingCache[resp.Index] = resps
   678  //		log.WithField("cached resps ", resps).trace("cached")
   679  //		return false
   680  //	}
   681  //	return true
   682  //}
   683  //
   684  ////CacheResponseIfNotReady check whether dkg is ready, not ready  cache the dkg deal response
   685  //func (d *DkgPartner) CacheResponseIfNotReady(addr common.Address, response *p2p_message.MessageConsensusDkgDealResponse) (ready bool) {
   686  //	d.mu.RLock()
   687  //	defer d.mu.RUnlock()
   688  //	if !d.ready {
   689  //		dkgResps, _ := d.dealResponseCache[addr]
   690  //		dkgResps = append(dkgResps, response)
   691  //		d.dealResponseCache[addr] = dkgResps
   692  //	}
   693  //	return d.ready
   694  //}
   695  //
   696  ////CacheDealsIfNotReady check whether dkg is ready, not ready  cache the dkg deal
   697  //func (d *DkgPartner) CacheDealsIfNotReady(addr common.Address, request *p2p_message.MessageConsensusDkgDeal) (ready bool) {
   698  //	log := d.log()
   699  //	d.mu.RLock()
   700  //	defer d.mu.RUnlock()
   701  //	if !d.ready {
   702  //		if oldDeal, ok := d.dealCache[addr]; ok {
   703  //			log.WithField("old ", oldDeal).WithField("new ", request).Warn("got duplicate deal")
   704  //		} else {
   705  //			d.dealCache[addr] = request
   706  //		}
   707  //	}
   708  //	return d.ready
   709  //}
   710  //
   711  ////CacheSigSetsIfNotReady
   712  //func (d *DkgPartner) CacheSigSetsIfNotReady(addr common.Address, response *p2p_message.MessageConsensusDkgSigSets) bool {
   713  //	d.mu.RLock()
   714  //	defer d.mu.RUnlock()
   715  //	if !d.ready || d.context.JointPubKey == nil {
   716  //		if _, ok := d.dealSigSetsCache[addr]; !ok {
   717  //			d.dealSigSetsCache[addr] = response
   718  //		}
   719  //		return false
   720  //
   721  //	}
   722  //	return true
   723  //}
   724  //
   725  //func (d *DkgPartner) addSigsets(addr common.Address, sig *tx_types.SigSet) {
   726  //	d.mu.RLock()
   727  //	defer d.mu.RUnlock()
   728  //	d.blsSigSets[addr] = sig
   729  //	return
   730  //
   731  //}
   732  //
   733  //func (d *DkgPartner) ProcessResponse(resp *dkg.Response) (just *dkg.Justification, err error) {
   734  //	d.mu.Lock()
   735  //	defer d.mu.Unlock()
   736  //
   737  //	return d.processResponse(resp)
   738  //}
   739  //
   740  //func (d *DkgPartner) processResponse(resp *dkg.Response) (just *dkg.Justification, err error) {
   741  //	return d.context.Dkger.ProcessResponse(resp)
   742  //}
   743  //
   744  //func (d *DkgPartner) GetPartnerAddressByIndex(i int) *common.Address {
   745  //	d.mu.RLock()
   746  //	defer d.mu.RUnlock()
   747  //
   748  //	for k, v := range d.context.addressIndex {
   749  //		if v == i {
   750  //			return &k
   751  //		}
   752  //	}
   753  //	return nil
   754  //}
   755  //
   756  //func (d *DkgPartner) GetAddresIndex() map[common.Address]int {
   757  //	d.mu.RLock()
   758  //	defer d.mu.RUnlock()
   759  //	return d.context.addressIndex
   760  //}
   761  //
   762  //type DealsMap map[int]*dkg.Deal
   763  //
   764  //func (t DealsMap) TerminateString() string {
   765  //	if t == nil || len(t) == 0 {
   766  //		return ""
   767  //	}
   768  //	var str []string
   769  //	var keys []int
   770  //	for k := range t {
   771  //		keys = append(keys, k)
   772  //	}
   773  //	sort.Ints(keys)
   774  //	for _, k := range keys {
   775  //		if v, ok := t[k]; ok {
   776  //			str = append(str, fmt.Sprintf("key-%d-val-%s", k, v.TerminateString()))
   777  //		}
   778  //	}
   779  //	return strings.Join(str, ",")
   780  //}
   781  //
   782  //func (d *DkgPartner) VerifyBlsSig(msg []byte, sig []byte, jointPub []byte, termId uint32) bool {
   783  //	log := d.log()
   784  //	pubKey, err := bn256.UnmarshalBinaryPointG2(jointPub)
   785  //	if err != nil {
   786  //		log.WithError(err).Warn("unmarshal join pubkey error")
   787  //		return false
   788  //	}
   789  //	if termId < d.TermId {
   790  //		if !pubKey.Equal(d.formerContext.JointPubKey) {
   791  //			log.WithField("termId ", termId).WithField("seq pk ", pubKey).WithField("our joint pk ", d.formerContext.JointPubKey).Warn("different")
   792  //			return false
   793  //		}
   794  //		err = bls.Verify(d.formerContext.Suite, pubKey, msg, sig)
   795  //		if err != nil {
   796  //			log.WithField("sig ", hex.EncodeToString(sig)).WithField("s ", d.context.Suite).WithField("pk", pubKey).WithError(err).Warn("bls verify error")
   797  //			return false
   798  //		}
   799  //		return true
   800  //	}
   801  //	if !pubKey.Equal(d.context.JointPubKey) {
   802  //		log.WithField("seq pk ", pubKey).WithField("our joint pk ", d.context.JointPubKey).Warn("different")
   803  //		return false
   804  //	}
   805  //	err = bls.Verify(d.context.Suite, pubKey, msg, sig)
   806  //	if err != nil {
   807  //		log.WithField("sig ", hex.EncodeToString(sig)).WithField("s ", d.context.Suite).WithField("pk", pubKey).WithError(err).Warn("bls verify error")
   808  //		return false
   809  //	}
   810  //	return true
   811  //	//Todo how to verify when term change
   812  //	// d.context.JointPubKey
   813  //}
   814  //
   815  //func (d *DkgPartner) Sign(msg []byte, termId uint32) (partSig []byte, err error) {
   816  //	partner := d.context
   817  //	if termId < d.TermId {
   818  //		partner = d.formerContext
   819  //		dkg2.log.Trace("use former context to sign")
   820  //	}
   821  //	return partner.PartSig(msg)
   822  //}
   823  //
   824  //func (d *DkgPartner) GetJoinPublicKey(termId uint32) kyber.Point {
   825  //	partner := d.context
   826  //	if termId < d.TermId {
   827  //		partner = d.formerContext
   828  //		dkg2.log.Trace("use former context to sign")
   829  //	}
   830  //	return partner.JointPubKey
   831  //}
   832  //
   833  //func (d *DkgPartner) RecoverAndVerifySignature(sigShares [][]byte, msg []byte, dkgTermId uint32) (jointSig []byte, err error) {
   834  //	log := d.log()
   835  //	d.mu.RLock()
   836  //	defer d.mu.RUnlock()
   837  //	partner := d.context
   838  //	//if the term id is small ,use former context to verify
   839  //	if dkgTermId < d.TermId {
   840  //		partner = d.formerContext
   841  //		log.Trace("use former id")
   842  //	}
   843  //	partner.SigShares = sigShares
   844  //	defer func() {
   845  //		partner.SigShares = nil
   846  //	}()
   847  //	jointSig, err = partner.RecoverSig(msg)
   848  //	if err != nil {
   849  //		var sigStr string
   850  //		for _, ss := range partner.SigShares {
   851  //			sigStr = sigStr + " " + hexutil.Encode(ss)
   852  //		}
   853  //		log.WithField("sigStr ", sigStr).WithField("msg ", hexutil.Encode(msg)).Warnf("context %d cannot recover jointSig with %d sigshares: %s\n",
   854  //			partner.MyIndex, len(partner.SigShares), err)
   855  //		return nil, err
   856  //	}
   857  //	log.Tracef("threshold signature from context %d: %s\n", partner.MyIndex, hexutil.Encode(jointSig))
   858  //	// verify if JointSig meets the JointPubkey
   859  //	err = partner.VerifyByDksPublic(msg, jointSig)
   860  //	if err != nil {
   861  //		log.WithError(err).Warnf("joinsig verify failed")
   862  //		return nil, err
   863  //	}
   864  //
   865  //	// verify if JointSig meets the JointPubkey
   866  //	err = partner.VerifyByPubPoly(msg, jointSig)
   867  //	if err != nil {
   868  //		log.WithError(err).Warnf("joinsig verify failed")
   869  //		return nil, err
   870  //	}
   871  //	return jointSig, nil
   872  //
   873  //}
   874  //
   875  //func (d *DkgPartner) SetJointPk(pk kyber.Point) {
   876  //	d.context.JointPubKey = pk
   877  //}
   878  //
   879  //type DKGInfo struct {
   880  //	TermId             uint32                 `json:"term_id"`
   881  //	Id                 uint32                 `json:"id"`
   882  //	PartPubs           []kyber.Point          `json:"part_pubs"`
   883  //	MyPartSec          kyber.Scalar           `json:"-"`
   884  //	CandidatePartSec   []kyber.Scalar         `json:"-"`
   885  //	CandidatePublicKey []hexutil.KeyBytes        `json:"candidate_public_key"`
   886  //	AddressIndex       map[common.Address]int `json:"address_index"`
   887  //}
   888  //
   889  //func (dkg *DkgPartner) GetInfo() *DKGInfo {
   890  //	dkgInfo := DKGInfo{
   891  //		TermId:           dkg.TermId,
   892  //		Id:               dkg.context.MyIndex,
   893  //		PartPubs:         dkg.context.PartPubs,
   894  //		MyPartSec:        dkg.context.MyPartSec,
   895  //		CandidatePartSec: dkg.context.CandidatePartSec,
   896  //		AddressIndex:     dkg.context.addressIndex,
   897  //	}
   898  //	for _, v := range dkg.context.CandidatePublicKey {
   899  //		dkgInfo.CandidatePublicKey = append(dkgInfo.CandidatePublicKey, v)
   900  //	}
   901  //	return &dkgInfo
   902  //}
   903  //
   904  //func (d *DkgPartner) HandleDkgDeal(request *p2p_message.MessageConsensusDkgDeal) {
   905  //	d.gossipReqCh <- request
   906  //}
   907  //
   908  //func (d *DkgPartner) HandleDkgDealRespone(response *p2p_message.MessageConsensusDkgDealResponse) {
   909  //	d.gossipRespCh <- response
   910  //}
   911  //
   912  //func (d *DkgPartner) HandleSigSet(requset *p2p_message.MessageConsensusDkgSigSets) {
   913  //	d.gossipSigSetspCh <- requset
   914  //}