github.com/annchain/OG@v0.0.9/consensus/annsensus_test/archive/dkg_demo_test.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_test
    15  //
    16  //import (
    17  //	"bytes"
    18  //	"fmt"
    19  //	"github.com/annchain/OG/account"
    20  //	"github.com/annchain/OG/common"
    21  //	"github.com/annchain/OG/common/ogcrypto"
    22  //	"github.com/annchain/OG/consensus/annsensus/test"
    23  //	"github.com/annchain/OG/og/message"
    24  //	"github.com/annchain/OG/types"
    25  //	"github.com/annchain/OG/types/p2p_message"
    26  //	"github.com/annchain/OG/types/tx_types"
    27  //	"github.com/annchain/gcache"
    28  //	"github.com/annchain/kyber/v3/pairing/bn256"
    29  //	"github.com/sirupsen/logrus"
    30  //	"math/rand"
    31  //	"testing"
    32  //	"time"
    33  //)
    34  //
    35  //type TestAnnSensus struct {
    36  //	*AnnSensus
    37  //}
    38  //
    39  //type AId struct {
    40  //	Address common.Address
    41  //	dkgId   int
    42  //}
    43  //
    44  //func (a AId) String() string {
    45  //	return fmt.Sprintf("add %s  dkgId %d", a.Address.TerminalString(), a.dkgId)
    46  //}
    47  //
    48  //func (a *TestAnnSensus) Aid() AId {
    49  //	return AId{
    50  //		Address: a.MyAccount.Address,
    51  //		dkgId:   int(a.dkg.GetId()),
    52  //	}
    53  //}
    54  //
    55  //func GetAnn(anns []TestAnnSensus, Addr common.Address) *TestAnnSensus {
    56  //	for i, ann := range anns {
    57  //		if bytes.Equal(ann.MyAccount.Address.ToBytes(), Addr.ToBytes()) {
    58  //			return &anns[i]
    59  //		}
    60  //	}
    61  //	panic("not found")
    62  //}
    63  //
    64  //type p2pMsg struct {
    65  //	data    []byte
    66  //	msgType message.typesType
    67  //}
    68  //
    69  //type TestHub struct {
    70  //	Id              common.Address
    71  //	PeerPipeIns           []common.Address
    72  //	sendMsgToChan   sendMsgToChanFunc
    73  //	sendMsgByPubKey sendMsgByPubKeyFunc
    74  //	OutMsg          chan p2pMsg
    75  //	quit            chan struct{}
    76  //	As              *TestAnnSensus
    77  //	msgCache        gcache.Cache
    78  //}
    79  //
    80  //type sendMsgToChanFunc func(addr common.Address, mdg test.TestMsg)
    81  //type sendMsgByPubKeyFunc func(pub *ogcrypto.PublicKey, msg test.TestMsg)
    82  //
    83  //func newtestHub(id common.Address, peers []common.Address, sendMsgToChan sendMsgToChanFunc, sendMsgByPubKey sendMsgByPubKeyFunc, as *TestAnnSensus) *TestHub {
    84  //	return &TestHub{
    85  //		Id:              id,
    86  //		PeerPipeIns:           peers,
    87  //		OutMsg:          make(chan p2pMsg, 100),
    88  //		sendMsgToChan:   sendMsgToChan,
    89  //		sendMsgByPubKey: sendMsgByPubKey,
    90  //		quit:            make(chan struct{}),
    91  //		As:              as,
    92  //		msgCache:        gcache.New(1000).Expiration(time.Minute).Simple().Build(),
    93  //	}
    94  //}
    95  //
    96  //func (t *TestHub) BroadcastMessage(messageType message.typesType, message p2p_message.Message) {
    97  //	var sent bool
    98  //	for _, peer := range t.PeerPipeIns {
    99  //		tMsg := test.TestMsg{
   100  //			MessageType: messageType,
   101  //			Message:     message,
   102  //			From:        t.Id,
   103  //		}
   104  //		t.sendMsgToChan(peer, tMsg)
   105  //		if !sent {
   106  //			hash := tMsg.GetHash()
   107  //			t.msgCache.Set(hash, struct{}{})
   108  //			sent = true
   109  //		}
   110  //		//logrus.WithField("me ", t.MyIndex).WithField("to peer ", peer).WithField("type ", messageType).Trace("send msg")
   111  //	}
   112  //}
   113  //
   114  //func (t *TestHub) SendToPeer(peerId string, messageType message.typesType, msg p2p_message.Message) error {
   115  //	return nil
   116  //}
   117  //
   118  //func (t *TestHub) AnonymousSendMessage(messageType message.typesType, message p2p_message.Message, anyNomousPubKey *ogcrypto.PublicKey) {
   119  //	tMsg := test.TestMsg{
   120  //		MessageType: messageType,
   121  //		Message:     message,
   122  //		From:        t.Id,
   123  //	}
   124  //	t.sendMsgByPubKey(anyNomousPubKey, tMsg)
   125  //	hash := tMsg.GetHash()
   126  //	t.msgCache.Set(hash, struct{}{})
   127  //}
   128  //
   129  //func (as *TestAnnSensus) Start() {
   130  //	as.campaignFlag = false
   131  //	as.dkg.Start()
   132  //	go as.loop()
   133  //	go as.Hub.(*TestHub).loop()
   134  //	logrus.Info("started ann  ", as.dkg.GetId())
   135  //}
   136  //
   137  //func (a *TestAnnSensus) Stop() {
   138  //	a.dkg.Stop()
   139  //	close(a.close)
   140  //	a.Hub.(*TestHub).quit <- struct{}{}
   141  //	logrus.Info("stopped ann ", a.dkg.GetId())
   142  //}
   143  //
   144  //func (as *TestAnnSensus) GenCampaign() *tx_types.Campaign {
   145  //	// generate campaign.
   146  //	//generate new dkg public key for every campaign
   147  //	candidatePublicKey := as.dkg.GenerateDkg()
   148  //	// generate campaign.
   149  //	camp := as.genCamp(candidatePublicKey)
   150  //
   151  //	as.newCampaign(camp)
   152  //	err := camp.UnmarshalDkgKey(bn256.UnmarshalBinaryPointG2)
   153  //	if err != nil {
   154  //		panic(err)
   155  //	}
   156  //	//ok := as.VerifyCampaign(camp)
   157  //	//if !ok {
   158  //	//	panic(ok)
   159  //	//}
   160  //	return camp
   161  //}
   162  //
   163  //func (as *TestAnnSensus) newCampaign(cp *tx_types.Campaign) {
   164  //	cp.GetBase().PublicKey = as.MyAccount.PublicKey.KeyBytes
   165  //	cp.GetBase().AccountNonce = uint64(as.dkg.GetId() * 10)
   166  //	cp.Issuer = &as.MyAccount.Address
   167  //	s := ogcrypto.NewSigner(as.cryptoType)
   168  //	cp.GetBase().Signature = s.Sign(as.MyAccount.PrivateKey, cp.SignatureTargets()).KeyBytes
   169  //	cp.GetBase().Weight = uint64(rand.Int31n(100)%10 + 3)
   170  //	cp.Height = uint64(as.dkg.TermId + 3)
   171  //	cp.GetBase().Hash = cp.CalcTxHash()
   172  //	return
   173  //}
   174  //
   175  //func (t *TestHub) loop() {
   176  //	elog := logrus.WithField("me", t.Id).WithField("aid ", t.As.Aid().String())
   177  //	for {
   178  //		select {
   179  //		case pMsg := <-t.OutMsg:
   180  //			var msg test.TestMsg
   181  //			switch pMsg.msgType {
   182  //			case message.MessageTypeConsensusDkgDeal:
   183  //				msg.MessageType = pMsg.msgType
   184  //				msg.Message = &p2p_message.MessageConsensusDkgDeal{}
   185  //			case message.MessageTypeConsensusDkgDealResponse:
   186  //				msg.MessageType = pMsg.msgType
   187  //				msg.Message = &p2p_message.MessageConsensusDkgDealResponse{}
   188  //			case message.MessageTypeConsensusDkgSigSets:
   189  //				msg.MessageType = pMsg.msgType
   190  //				msg.Message = &p2p_message.MessageConsensusDkgSigSets{}
   191  //			default:
   192  //				elog.Warn(pMsg, "unkown meg type will panic")
   193  //				panic(pMsg)
   194  //			}
   195  //			_, err := msg.UnmarshalMsg(pMsg.data)
   196  //			if err != nil {
   197  //				panic(err)
   198  //			}
   199  //			time.Sleep(10 * time.Millisecond)
   200  //			hash := msg.GetHash()
   201  //			switch msg.MessageType {
   202  //			case message.MessageTypeConsensusDkgDeal:
   203  //				request := msg.Message.(*p2p_message.MessageConsensusDkgDeal)
   204  //				if _, err := t.msgCache.GetIFPresent(hash); err == nil {
   205  //					//elog.WithField("from ", msg.From).WithField("msg type",
   206  //					//	msg.typesType).WithField("msg ", len(request.Data)).WithField("hash ",
   207  //					//	msg.GetHash()).Warn("duplicate dkg msg")
   208  //					continue
   209  //				}
   210  //				go t.As.HandleConsensusDkgDeal(request, fmt.Sprintf("%s", msg.From.TerminalString()))
   211  //			case message.MessageTypeConsensusDkgDealResponse:
   212  //				request := msg.Message.(*p2p_message.MessageConsensusDkgDealResponse)
   213  //				if _, err := t.msgCache.GetIFPresent(hash); err == nil {
   214  //					//elog.WithField("from ", msg.From).WithField("msg type",
   215  //					//	msg.typesType).WithField("msg ", len(request.Data)).WithField("hash ",
   216  //					//	msg.GetHash()).Warn("duplicate response  msg")
   217  //					continue
   218  //				}
   219  //				go t.As.HandleConsensusDkgDealResponse(request, fmt.Sprintf("%s", msg.From.TerminalString()))
   220  //			case message.MessageTypeConsensusDkgSigSets:
   221  //				request := msg.Message.(*p2p_message.MessageConsensusDkgSigSets)
   222  //				if _, err := t.msgCache.GetIFPresent(hash); err == nil {
   223  //					//elog.WithField("from ", msg.From).WithField("msg type",
   224  //					//	msg.typesType).WithField("msg ", len(request.PkBls)).WithField("hash ",
   225  //					//	msg.GetHash()).Warn("duplicate response  msg")
   226  //					continue
   227  //				}
   228  //				go t.As.HandleConsensusDkgSigSets(request, fmt.Sprintf("%s", msg.From.TerminalString()))
   229  //			default:
   230  //				elog.Info("never come here, msg loop")
   231  //				return
   232  //			}
   233  //			elog.WithField("msg", msg).Debug("i got a msg")
   234  //			t.msgCache.Set(hash, struct{}{})
   235  //		case <-t.quit:
   236  //			elog.Debug("stopped")
   237  //			return
   238  //		}
   239  //	}
   240  //}
   241  //
   242  //func run(n int) {
   243  //	logInit()
   244  //	var Anns []TestAnnSensus
   245  //	sendMsgToChan := func(addr common.Address, msg test.TestMsg) {
   246  //		data, err := msg.MarshalMsg(nil)
   247  //		if err != nil {
   248  //			panic(err)
   249  //		}
   250  //		pMsg := p2pMsg{data: data, msgType: msg.MessageType}
   251  //		ann := GetAnn(Anns, addr)
   252  //		ann.Hub.(*TestHub).OutMsg <- pMsg
   253  //		var resp *p2p_message.MessageConsensusDkgDealResponse
   254  //		if msg.MessageType == message.MessageTypeConsensusDkgDealResponse {
   255  //			resp = msg.Message.(*p2p_message.MessageConsensusDkgDealResponse)
   256  //		}
   257  //		logrus.WithField("me ", msg.From).WithField("to peer ", ann.Aid().String()).WithField("type ",
   258  //			msg.MessageType).WithField("msg ", resp).WithField("len ", len(data)).Trace("send msg")
   259  //		return
   260  //	}
   261  //	sendMsgByPubKey := func(pub *ogcrypto.PublicKey, msg test.TestMsg) {
   262  //		data, err := msg.MarshalMsg(nil)
   263  //		if err != nil {
   264  //			panic(err)
   265  //		}
   266  //		pMsg := p2pMsg{data: data, msgType: msg.MessageType}
   267  //		for j := 0; j < n; j++ {
   268  //			if bytes.Equal(Anns[j].MyAccount.PublicKey.KeyBytes, pub.KeyBytes) {
   269  //				Anns[j].Hub.(*TestHub).OutMsg <- pMsg
   270  //				logrus.WithField("from peer", msg.From.TerminalString()).WithField("to peer id ", Anns[j].Aid().String()).WithField("type ",
   271  //					msg.MessageType).Trace("send msg enc")
   272  //				return
   273  //			}
   274  //		}
   275  //		logrus.Warn("not found for pubkey ", pub)
   276  //		return
   277  //	}
   278  //
   279  //	var accounts []account.Account
   280  //	var pks []ogcrypto.PublicKey
   281  //	signer := ogcrypto.NewSigner(ogcrypto.CryptoTypeSecp256k1)
   282  //	for j := 0; j < n; j++ {
   283  //		pub, priv := signer.RandomKeyPair()
   284  //		account := account.Account{
   285  //			PrivateKey: priv,
   286  //			PublicKey:  pub,
   287  //			Address:    pub.Address(),
   288  //			Id:         j,
   289  //		}
   290  //		accounts = append(accounts, account)
   291  //		pks = append(pks, account.PublicKey)
   292  //	}
   293  //
   294  //	for j := 0; j < n; j++ {
   295  //		as := NewAnnSensus(4, false, ogcrypto.CryptoTypeSecp256k1, true, n,
   296  //			pks, "test.json", false)
   297  //		a := TestAnnSensus{
   298  //			AnnSensus: as,
   299  //		}
   300  //		var peers []common.Address
   301  //		for k := 0; k < n; k++ {
   302  //			if k == j {
   303  //				continue
   304  //			}
   305  //			peers = append(peers, accounts[k].Address)
   306  //		}
   307  //		hub := newtestHub(accounts[j].Address, peers, sendMsgToChan, sendMsgByPubKey, &a)
   308  //		as.InitAccount(&accounts[j], time.Second, nil, nil, &DummyDag{}, nil, nil, hub)
   309  //		a.AnnSensus = as
   310  //		logrus.WithField("addr ", a.MyAccount.Address.TerminalString()).Debug("gen hub done")
   311  //		Anns = append(Anns, a)
   312  //	}
   313  //
   314  //	//start here
   315  //	//collect campaigns
   316  //	message.MsgCountInit()
   317  //	for i := range Anns {
   318  //		Anns[i].Start()
   319  //	}
   320  //	time.Sleep(20 * time.Millisecond)
   321  //	var num int
   322  //	for {
   323  //		select {
   324  //		case <-time.After(time.Second * 5):
   325  //			num++
   326  //			if num > 10 {
   327  //				return
   328  //			}
   329  //			var cps types.Txis
   330  //			for _, ann := range Anns {
   331  //				cps = append(cps, ann.GenCampaign())
   332  //			}
   333  //			logrus.Debug("gen camp ", cps)
   334  //			for i := range Anns {
   335  //				go func(i int) {
   336  //					log.WithField("i ", i).WithField("ann ", Anns[i].dkg.GetId()).Debug("new term start")
   337  //					Anns[i].ConsensusTXConfirmed <- cps
   338  //				}(i)
   339  //			}
   340  //		case <-time.After(time.Second * 21):
   341  //			break
   342  //		}
   343  //
   344  //	}
   345  //
   346  //	for i := range Anns {
   347  //		Anns[i].Stop()
   348  //	}
   349  //
   350  //}
   351  //
   352  //func (as *TestAnnSensus) loop() {
   353  //	for {
   354  //		select {
   355  //		case tc := <-as.termChangeChan:
   356  //			log.WithField("me ", as.dkg.GetId()).WithField("pk ", tc).Info("got term change and pk")
   357  //			as.term.ChangeTerm(tc, as.Idag.GetHeight())
   358  //			//
   359  //		case <-as.newTermChan:
   360  //			// sequencer generate entry.
   361  //
   362  //			// TODO:
   363  //			// 1. check if yourself is the miner.
   364  //			// 2. produce raw_seq and broadcast it to network.
   365  //			// 3. start bft until someone produce a seq with BLS sig.
   366  //			log.Info("got newTermChange signal")
   367  //		case <-as.startTermChange:
   368  //			log := as.dkg.Log()
   369  //			cp := as.term.GetCampaign(as.MyAccount.Address)
   370  //			log.WithField("cp ", cp).Debug("will reset with cp")
   371  //			as.dkg.Reset(cp)
   372  //			as.dkg.SelectCandidates(as.Idag.LatestSequencer())
   373  //			if !as.dkg.IsValidPartner() {
   374  //				log.Debug("i am not a lucky dkg partner quit")
   375  //
   376  //				continue
   377  //			}
   378  //			log.Debug("start dkg gossip")
   379  //			go as.dkg.StartGossip()
   380  //
   381  //		case pk := <-as.dkgPulicKeyChan:
   382  //			log := as.dkg.Log()
   383  //			log.WithField("pk ", pk).Info("got a bls public key from dkg")
   384  //			//after dkg  gossip finished, set term change flag
   385  //			//term change is finished
   386  //			as.term.SwitchFlag(false)
   387  //			sigset := as.dkg.GetBlsSigsets()
   388  //			log.WithField("sig sets", sigset).Info("got sigsets")
   389  //			//continue //for test case commit this
   390  //			tc := as.genTermChg(pk, sigset)
   391  //			if tc == nil {
   392  //				log.Warn("tc is nil")
   393  //				continue
   394  //			}
   395  //			go func() {
   396  //				as.termChangeChan <- tc
   397  //			}()
   398  //
   399  //		case txs := <-as.ConsensusTXConfirmed:
   400  //			var cps tx_types.Campaigns
   401  //			for _, tx := range txs {
   402  //				if tx.GetType() == types.TxBaseTypeCampaign {
   403  //					cp := tx.(*tx_types.Campaign)
   404  //					cps = append(cps, cp)
   405  //					if bytes.Equal(cp.Issuer.KeyBytes[:], as.MyAccount.Address.KeyBytes[:]) {
   406  //
   407  //					}
   408  //				}
   409  //			}
   410  //			as.newTerm(cps)
   411  //
   412  //		case <-as.close:
   413  //			log.Info("got quit signal , annsensus loop stopped")
   414  //			return
   415  //		}
   416  //	}
   417  //
   418  //}
   419  //
   420  //func (as *TestAnnSensus) newTerm(cps tx_types.Campaigns) {
   421  //	log.Trace("new term change")
   422  //	if len(cps) > 0 {
   423  //		for _, c := range cps {
   424  //			err := as.AddCampaign(c)
   425  //			if err != nil {
   426  //				log.WithError(err).Debug("add campaign err")
   427  //				//continue
   428  //			}
   429  //		}
   430  //	}
   431  //	// start term changing.
   432  //	as.term.SwitchFlag(true)
   433  //	log.Debug("will term Change")
   434  //	go func() {
   435  //		as.startTermChange <- true
   436  //	}()
   437  //
   438  //	log.Infof("already candidates: %d, alsorans: %d", len(as.Candidates()), len(as.Alsorans()))
   439  //}
   440  //
   441  //func TestDKGMain(t *testing.T) {
   442  //	run(2)
   443  //}