github.com/annchain/OG@v0.0.9/consensus/annsensus/archive/annsensus.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 // 17 //import ( 18 // "bytes" 19 // "errors" 20 // "fmt" 21 // "github.com/annchain/OG/account" 22 // "github.com/annchain/OG/common" 23 // "github.com/annchain/OG/common/goroutine" 24 // "github.com/annchain/OG/common/hexutil" 25 // "github.com/annchain/OG/consensus/annsensus/announcer" 26 // "github.com/annchain/OG/consensus/bft" 27 // "github.com/annchain/OG/consensus/bft_test" 28 // "github.com/annchain/OG/consensus/dkg/archive" 29 // "github.com/annchain/OG/consensus/term" 30 // "github.com/annchain/OG/og" 31 // "github.com/annchain/OG/og/message" 32 // "github.com/annchain/OG/og/txmaker" 33 // "github.com/annchain/OG/types/p2p_message" 34 // "github.com/annchain/OG/types/tx_types" 35 // "github.com/annchain/kyber/v3/pairing/bn256" 36 // "sort" 37 // "sync" 38 // "sync/atomic" 39 // "time" 40 // 41 // "github.com/annchain/OG/common/ogcrypto" 42 // "github.com/annchain/OG/types" 43 // "github.com/annchain/kyber/v3" 44 //) 45 // 46 //// Annsensus processes campaign election. 47 //type AnnSensus struct { 48 // //id int 49 // campaignFlag bool 50 // cryptoType ogcrypto.CryptoType 51 // 52 // //dkg *dkg.DkgPartner 53 // term *term.Term 54 // //bft *bft.BFT // tendermint protocal 55 // 56 // dkgPulicKeyChan chan kyber.Point // channel for receiving dkg response. 57 // newTxHandlers []chan types.Txi // channels to send txs. 58 // ConsensusTXConfirmed chan []types.Txi // receiving consensus txs from dag confirm. 59 // startTermChange chan bool 60 // 61 // Hub announcer.MessageSender 62 // Idag og.IDag 63 // 64 // MyAccount *account.Account 65 // Threshold int 66 // NbParticipants int 67 // 68 // mu sync.RWMutex 69 // 70 // close chan struct{} 71 // genesisAccounts ogcrypto.PublicKeys 72 // isGenesisPartner bool 73 // genesisBftIsRunning uint32 74 // UpdateEvent chan bool // syner update event 75 // newTermChan chan bool 76 // genesisPkChan chan *p2p_message.MessageConsensusDkgGenesisPublicKey 77 // NewPeerConnectedEventListener chan string 78 // ProposalSeqChan chan common.Hash 79 // HandleNewTxi func(tx types.Txi, peerId string) 80 // 81 // TxEnable bool 82 // NewLatestSequencer chan bool 83 // 84 // ConfigFilePath string 85 // termChangeChan chan *tx_types.TermChange 86 // currentTermChange *tx_types.TermChange 87 // 88 // addedGenesisCampaign bool 89 // initDone bool 90 //} 91 // 92 //func NewAnnSensus(termChangeInterval int, disableConsensus bool, cryptoType ogcrypto.CryptoType, campaign bool, partnerNum int, 93 // genesisAccounts ogcrypto.PublicKeys, configFile string, disableTermChange bool) *AnnSensus { 94 // ann := &AnnSensus{} 95 // //ann.disable = disableConsensus 96 // //if disableConsensus { 97 // // disableTermChange = true 98 // //} 99 // //ann.disableTermChange = disableTermChange 100 // //if termChangeInterval <= 0 && !ann.disableTermChange { 101 // // panic("require termChangeInterval ") 102 // //} 103 // //if len(genesisAccounts) < partnerNum && !ann.disableTermChange { 104 // // panic("need more account") 105 // //} 106 // ann.close = make(chan struct{}) 107 // ann.newTxHandlers = []chan types.Txi{} 108 // ann.campaignFlag = campaign 109 // ann.NbParticipants = partnerNum 110 // ann.ConsensusTXConfirmed = make(chan []types.Txi) 111 // ann.cryptoType = cryptoType 112 // ann.dkgPulicKeyChan = make(chan kyber.Point) 113 // ann.UpdateEvent = make(chan bool) 114 // 115 // ann.genesisAccounts = genesisAccounts 116 // sort.Sort(ann.genesisAccounts) 117 // ann.term = term.NewTerm(0, partnerNum, termChangeInterval) 118 // ann.newTermChan = make(chan bool) 119 // ann.genesisPkChan = make(chan *p2p_message.MessageConsensusDkgGenesisPublicKey) 120 // ann.NewPeerConnectedEventListener = make(chan string) 121 // 122 // ann.ProposalSeqChan = make(chan common.Hash) 123 // ann.NewLatestSequencer = make(chan bool) 124 // ann.startTermChange = make(chan bool) 125 // 126 // ann.termChangeChan = make(chan *tx_types.TermChange) 127 // //todo fix this later ,bft consensus 128 // //"The latest gossip on BFT consensus " 2f+1 129 // //if partnerNum < 2 { 130 // // panic(fmt.Sprintf("BFT needs at least 2 nodes, currently %d", partnerNum)) 131 // //} 132 // dkger := archive.NewDkgPartner(!disableConsensus, partnerNum, bft.MajorityTwoThird(partnerNum), ann.dkgPulicKeyChan, ann.genesisPkChan, ann.term) 133 // dkger.ConfigFilePath = configFile 134 // ann.dkg = dkger 135 // log.WithField("NbParticipants ", ann.NbParticipants).Info("new ann") 136 // 137 // return ann 138 //} 139 // 140 //func (as *AnnSensus) InitAccount(myAccount *account.Account, sequencerTime time.Duration, 141 // judgeNonce func(me *account.Account) uint64, txCreator *txmaker.OGTxCreator, Idag og.IDag, onSelfGenTxi chan types.Txi, 142 // handleNewTxi func(txi types.Txi, peerId string), sender announcer.MessageSender) { 143 // as.MyAccount = myAccount 144 // as.Hub = sender 145 // as.dkg.Hub = sender 146 // as.Idag = Idag 147 // var myId int 148 // if !as.disable { 149 // for id, pk := range as.genesisAccounts { 150 // if bytes.Equal(pk.KeyBytes, as.MyAccount.PublicKey.KeyBytes) { 151 // as.isGenesisPartner = true 152 // myId = id 153 // log.WithField("my id ", id).Info("i am a genesis partner") 154 // } 155 // } 156 // } 157 // as.dkg.SetId(myId) 158 // as.dkg.SetAccount(as.MyAccount) 159 // as.bft = bft.NewBFT(as.NbParticipants, myId, sequencerTime, judgeNonce, txCreator, Idag, myAccount, onSelfGenTxi, as.dkg) 160 // as.addBftPartner() 161 // as.bft.Hub = sender 162 // as.HandleNewTxi = handleNewTxi 163 //} 164 // 165 //func (as *AnnSensus) Start() { 166 // //log.Info("AnnSensus Start") 167 // //if as.disable { 168 // // log.Warn("annsensus disabled") 169 // // return 170 // //} 171 // as.dkg.Start() 172 // as.bft.Start() 173 // goroutine.New(as.loop) 174 // goroutine.New(as.termChangeLoop) 175 //} 176 // 177 //func (as *AnnSensus) Stop() { 178 // log.Info("AnnSensus will Stop") 179 // if as.disable { 180 // return 181 // } 182 // as.bft.Stop() 183 // as.dkg.Stop() 184 // close(as.close) 185 //} 186 // 187 //func (as *AnnSensus) Name() string { 188 // return "AnnSensus" 189 //} 190 // 191 //func (as *AnnSensus) GetBenchmarks() map[string]interface{} { 192 // return map[string]interface{}{ 193 // "newTxHandlers": len(as.newTxHandlers), 194 // "consensusTXConfirmed": len(as.ConsensusTXConfirmed), 195 // } 196 // // TODO 197 // return nil 198 //} 199 // 200 //func (as *AnnSensus) GetCandidate(addr common.Address) *tx_types.Campaign { 201 // return as.term.GetCandidate(addr) 202 //} 203 // 204 //func (as *AnnSensus) Candidates() map[common.Address]*tx_types.Campaign { 205 // return as.term.Candidates() 206 //} 207 // 208 //func (as *AnnSensus) GetAlsoran(addr common.Address) *tx_types.Campaign { 209 // return as.term.GetAlsoran(addr) 210 //} 211 // 212 //func (as *AnnSensus) Alsorans() map[common.Address]*tx_types.Campaign { 213 // return as.term.Alsorans() 214 //} 215 // 216 //// RegisterNewTxHandler add a channel into AnnSensus.newTxHandlers. These 217 //// channels are responsible to process new txs produced by annsensus. 218 //func (as *AnnSensus) RegisterNewTxHandler(c chan types.Txi) { 219 // as.newTxHandlers = append(as.newTxHandlers, c) 220 //} 221 // 222 //// ProdCampaignOn let annsensus start producing campaign. 223 //func (as *AnnSensus) ProduceCampaignOn() { 224 // as.produceCampaign() 225 //} 226 // 227 //// campaign continuously generate camp tx until AnnSensus.CampaingnOff is called. 228 //func (as *AnnSensus) produceCampaign() { 229 // //generate new dkg public key for every campaign 230 // if as.term.HasCampaign(as.MyAccount.Address) { 231 // log.WithField("als", as.term.Alsorans()).WithField("cps ", 232 // as.term.Campaigns()).WithField("candidates", as.term.Candidates()).Debug("has campaign") 233 // return 234 // } 235 // candidatePublicKey := as.dkg.GenerateDkg() 236 // // generate campaign. 237 // camp := as.genCamp(candidatePublicKey) 238 // if camp == nil { 239 // log.Warn("gen camp fail") 240 // return 241 // } 242 // log.WithField("pk ", hexutil.Encode(candidatePublicKey[:5])).WithField("cp ", camp).Debug("gen campaign") 243 // // send camp 244 // goroutine.New(func() { 245 // for _, c := range as.newTxHandlers { 246 // c <- camp 247 // } 248 // }) 249 // 250 //} 251 // 252 //// commit takes a list of campaigns as input and record these 253 //// camps' information. It checks if the number of camps reaches 254 //// the threshold. If so, start term changing flow. 255 //func (as *AnnSensus) commit(camps []*tx_types.Campaign) { 256 // 257 // for i, c := range camps { 258 // if as.isTermChanging() { 259 // // add those unsuccessful camps into alsoran list. 260 // log.Debug("is termchanging") 261 // as.AddAlsorans(camps[i:]) 262 // return 263 // } 264 // 265 // err := as.AddCampaign(c) 266 // if err != nil { 267 // log.WithError(err).Debug("add campaign err") 268 // //continue 269 // } 270 // if !as.canChangeTerm() { 271 // continue 272 // } 273 // // start term changing. 274 // as.term.SwitchFlag(true) 275 // log.Debug("will term Change") 276 // as.startTermChange <- true 277 // 278 // } 279 //} 280 // 281 //// AddCandidate adds campaign into annsensus if the campaign meets the 282 //// candidate requirements. 283 //func (as *AnnSensus) AddCampaign(cp *tx_types.Campaign) error { 284 // 285 // if as.term.HasCampaign(cp.Sender()) { 286 // log.WithField("id", as.dkg.GetId()).WithField("campaign", cp).Debug("duplicate campaign") 287 // return fmt.Errorf("duplicate") 288 // } 289 // 290 // pubkey := cp.GetDkgPublicKey() 291 // if pubkey == nil { 292 // log.WithField("nil PartPubf for campaign", cp).Warn("add campaign") 293 // return fmt.Errorf("pubkey is nil") 294 // } 295 // 296 // //as.dkg.AddPartner(cp, &as.MyAccount.PublicKey) 297 // as.term.AddCampaign(cp) 298 // log.WithField("me", as.dkg.GetId()).WithField("add cp", cp).Debug("added") 299 // return nil 300 //} 301 // 302 //// AddAlsorans adds a list of campaigns into annsensus as alsorans. 303 //// Campaigns will be regard as alsoran when current candidates cached 304 //// already reaches the term change requirements. 305 //func (as *AnnSensus) AddAlsorans(cps []*tx_types.Campaign) { 306 // as.term.AddAlsorans(cps) 307 //} 308 // 309 //// isTermChanging checks if the annsensus system is currently 310 //// changing its senators term. 311 //func (as *AnnSensus) isTermChanging() bool { 312 // return as.term.Changing() 313 //} 314 // 315 //// canChangeTerm returns true if the candidates cached reaches the 316 //// term change requirments. 317 //func (as *AnnSensus) canChangeTerm() bool { 318 // ok := as.term.CanChange(as.Idag.LatestSequencer().Height, atomic.LoadUint32(&as.genesisBftIsRunning) == 1) 319 // return ok 320 //} 321 // 322 //func (as *AnnSensus) termChangeLoop() { 323 // // start term change gossip 324 // 325 // for { 326 // select { 327 // case <-as.close: 328 // log.Info("got quit signal , annsensus termchange stopped") 329 // return 330 // 331 // case <-as.startTermChange: 332 // log := as.dkg.Log() 333 // cp := as.term.GetCampaign(as.MyAccount.Address) 334 // if cp == nil { 335 // log.Warn("cannot found campaign, i ma not a partner , no dkg gossip") 336 // } 337 // as.dkg.Reset(cp) 338 // as.dkg.SelectCandidates(as.Idag.LatestSequencer()) 339 // if !as.dkg.IsValidPartner() { 340 // log.Debug("i am not a lucky dkg partner quit") 341 // as.term.SwitchFlag(false) 342 // continue 343 // } 344 // log.Debug("start dkg gossip") 345 // goroutine.New(as.dkg.StartGossip) 346 // 347 // case pk := <-as.dkgPulicKeyChan: 348 // log := as.dkg.Log() 349 // log.WithField("pk ", pk).Info("got a bls public key from dkg") 350 // //after dkg gossip finished, set term change flag 351 // //term change is finished 352 // as.term.SwitchFlag(false) 353 // sigset := as.dkg.GetBlsSigsets() 354 // log.WithField("sig sets ", sigset).Info("got sigsets") 355 // //continue //for test case commit this 356 // tc := as.genTermChg(pk, sigset) 357 // if tc == nil { 358 // log.Error("tc is nil") 359 // continue 360 // } 361 // if atomic.CompareAndSwapUint32(&as.genesisBftIsRunning, 1, 0) { 362 // as.term.ChangeTerm(tc, as.Idag.GetHeight()) 363 // goroutine.New(func() { 364 // as.newTermChan <- true 365 // //as.newTermChan <- struct{}{} 366 // //as.ConsensusTXConfirmed <- types.Txis{tc} 367 // }) 368 // atomic.StoreUint32(&as.genesisBftIsRunning, 0) 369 // 370 // continue 371 // } 372 // //save the tc and sent it in next sequencer 373 // //may be it is a solution for the bug : 374 // //while syncing with bloom filter 375 // as.mu.RLock() 376 // as.currentTermChange = tc 377 // as.mu.RUnlock() 378 // } 379 // } 380 // 381 //} 382 // 383 //// pickTermChg picks a valid TermChange from a tc list. 384 //func (as *AnnSensus) pickTermChg(tcs []*tx_types.TermChange) (*tx_types.TermChange, error) { 385 // if len(tcs) == 0 { 386 // return nil, errors.New("nil tcs") 387 // } 388 // var niceTc *tx_types.TermChange 389 // for _, tc := range tcs { 390 // if niceTc != nil && niceTc.IsSameTermInfo(tc) { 391 // continue 392 // } 393 // if tc.TermID == as.term.ID()+1 { 394 // niceTc = tc 395 // } 396 // } 397 // if niceTc == nil { 398 // log.WithField("tc term id ", tcs[0].TermID).WithField("term id ", as.term.ID()).Warn("pic fail") 399 // return nil, errors.New("not found") 400 // } 401 // return niceTc, nil 402 //} 403 // 404 ////genTermChg 405 //func (as *AnnSensus) genTermChg(pk kyber.Point, sigset []*tx_types.SigSet) *tx_types.TermChange { 406 // base := types.TxBase{ 407 // Type: types.TxBaseTypeTermChange, 408 // } 409 // var pkbls []byte 410 // var err error 411 // if pk != nil { 412 // pkbls, err = pk.MarshalBinary() 413 // if err != nil { 414 // log.WithError(err).Warn("pk error") 415 // return nil 416 // } 417 // } 418 // 419 // tc := &tx_types.TermChange{ 420 // TxBase: base, 421 // TermID: as.term.ID() + 1, 422 // Issuer: &as.MyAccount.Address, 423 // PkBls: pkbls, 424 // SigSet: sigset, 425 // } 426 // return tc 427 //} 428 // 429 //func (as *AnnSensus) addGenesisCampaigns() { 430 // as.mu.RLock() 431 // if as.addedGenesisCampaign { 432 // as.mu.RUnlock() 433 // log.Info("already added genesis campaign") 434 // return 435 // } 436 // as.addedGenesisCampaign = true 437 // as.mu.RUnlock() 438 // for id, pk := range as.genesisAccounts { 439 // addr := pk.Address() 440 // cp := tx_types.Campaign{ 441 // //DkgPublicKey: pkMsg.DkgPublicKey, 442 // Issuer: &addr, 443 // TxBase: types.TxBase{ 444 // PublicKey: pk.KeyBytes, 445 // Weight: uint64(id*10 + 10), 446 // }, 447 // } 448 // as.term.AddCandidate(&cp, pk) 449 // } 450 //} 451 // 452 //func (as *AnnSensus) addBftPartner() { 453 // log.Debug("add bft partners") 454 // //should participate in genesis bft process 455 // as.dkg.On() 456 // 457 // var peers []bft.BFTPartner 458 // for i, pk := range as.genesisAccounts { 459 // //the third param is not used in peer 460 // peers = append(peers, bft.NewOgBftPeer(pk, as.NbParticipants, i, time.Second)) 461 // } 462 // as.bft.BFTPartner.SetPeers(peers) 463 //} 464 // 465 //func (as *AnnSensus) loop() { 466 // //var camp bool 467 // 468 // // sequencer entry 469 // var genesisCamps []*tx_types.Campaign 470 // var peerNum int 471 // 472 // var lastHeight uint64 473 // var termId uint64 474 // var genesisPublickeyProcessFinished bool 475 // var sentCampaign uint64 476 // 477 // var eventInit bool 478 // var loadDone bool 479 // var waitNewTerm bool 480 // //var lastheight uint64 481 // 482 // for { 483 // select { 484 // case <-as.close: 485 // log.Info("got quit signal, annsensus loop stopped") 486 // return 487 // 488 // //TODO sequencer generate a random seed ,use random seed to select candidate peers 489 // case txs := <-as.ConsensusTXConfirmed: 490 // log.WithField(" txs ", txs).Debug("got consensus txs") 491 // if as.disableTermChange { 492 // log.Debug("term change is disabled , quiting") 493 // continue 494 // } 495 // var cps []*tx_types.Campaign 496 // var tcs []*tx_types.TermChange 497 // for _, tx := range txs { 498 // if tx.GetType() == types.TxBaseTypeCampaign { 499 // cp := tx.(*tx_types.Campaign) 500 // cps = append(cps, cp) 501 // if bytes.Equal(cp.Issuer.KeyBytes[:], as.MyAccount.Address.KeyBytes[:]) { 502 // if sentCampaign > 0 { 503 // log.Debug("i sent a campaign") 504 // sentCampaign = 0 505 // } 506 // } 507 // } else if tx.GetType() == types.TxBaseTypeTermChange { 508 // tcs = append(tcs, tx.(*tx_types.TermChange)) 509 // } 510 // } 511 // // TODO: 512 // // here exists a bug: 513 // // the isTermChanging check should be here not in commit() 514 // 515 // if len(tcs) > 0 { 516 // tc, err := as.pickTermChg(tcs) 517 // if err != nil { 518 // log.Errorf("the received termChanges are not correct.") 519 // goto HandleCampaign 520 // } 521 // if as.isTermChanging() { 522 // log.Debug("is term changing") 523 // goto HandleCampaign 524 // } 525 // err = as.term.ChangeTerm(tc, as.Idag.LatestSequencer().Height) 526 // if err != nil { 527 // log.Errorf("change term error: %v", err) 528 // goto HandleCampaign 529 // } 530 // //if i am not a dkg partner , dkg publick key will got from termChange tx 531 // if !as.dkg.IsValidPartner() { 532 // pk, err := bn256.UnmarshalBinaryPointG2(tc.PkBls) 533 // if err != nil { 534 // log.WithError(err).Warn("unmarshal failed dkg joint public key") 535 // continue 536 // } 537 // as.dkg.SetJointPk(pk) 538 // } 539 // //send the signal if i am a partner of consensus nodes 540 // //if as.dkg.isValidPartner { 541 // goroutine.New(func() { 542 // as.newTermChan <- true 543 // }) 544 // //} else { 545 // // log.Debug("is not a valid partner") 546 // //} 547 // 548 // } 549 // HandleCampaign: 550 // //handle term change should be after handling campaign 551 // if len(cps) > 0 { 552 // as.commit(cps) 553 // log.Infof("already candidates: %d, alsorans: %d", len(as.Candidates()), len(as.Alsorans())) 554 // } 555 // 556 // case <-as.newTermChan: 557 // // sequencer generate entry. 558 // 559 // // TODO: 560 // // 1. check if yourself is the miner. 561 // // 2. produce raw_seq and broadcast it to network. 562 // // 3. start bft until someone produce a seq with BLS sig. 563 // log.Info("got newTermChange signal") 564 // as.bft.Reset(as.dkg.TermId, as.term.GetFormerPks(), int(as.dkg.GetId())) 565 // // 3. start pbft until someone produce a seq with BLS sig. 566 // //TODO how to save consensus data 567 // if as.dkg.TermId == 1 { 568 // } 569 // 570 // if as.dkg.IsValidPartner() { 571 // as.dkg.SaveConsensusData() 572 // as.bft.StartGossip() 573 // } else { 574 // log.Debug("is not a valid partner") 575 // } 576 // 577 // // 578 // //case <-time.After(time.Millisecond * 300): 579 // // height := as.Idag.LatestSequencer().Height 580 // // if height <= lastheight { 581 // // //should updated 582 // // continue 583 // // } 584 // // lastheight = height 585 // // if height > 2 && height%15 == 0 { 586 // // //may i send campaign ? 587 // // as.ProdCampaignOn() 588 // // } 589 // 590 // case <-as.NewLatestSequencer: 591 // var tc *tx_types.TermChange 592 // as.mu.RLock() 593 // tc = as.currentTermChange 594 // as.currentTermChange = nil 595 // as.mu.RUnlock() 596 // if tc != nil { 597 // for _, c := range as.newTxHandlers { 598 // c <- tc 599 // } 600 // } 601 // 602 // if !as.isTermChanging() { 603 // if as.canChangeTerm() { 604 // // start term changing. 605 // as.term.SwitchFlag(true) 606 // log.Debug("will termChange") 607 // as.startTermChange <- true 608 // } 609 // } 610 // 611 // if !as.campaignFlag || as.disableTermChange { 612 // continue 613 // } 614 // height := as.Idag.LatestSequencer().Height 615 // if height <= lastHeight { 616 // //should updated 617 // continue 618 // } 619 // if sentCampaign < height+2 && sentCampaign > 0 { 620 // //we sent campaign but did't receive them 621 // //sent again 622 // log.WithField("in term ", as.term.ID()).Debug("will generate campaign") 623 // as.ProduceCampaignOn() 624 // sentCampaign = height 625 // } 626 // //if term id is updated , we can produce campaign tx 627 // lastHeight = height 628 // if termId < as.term.ID() { 629 // termId = as.term.ID() 630 // //may i send campaign ? 631 // if sentCampaign == height { 632 // continue 633 // } 634 // log.WithField("in term ", as.term.ID()).Debug("will generate campaign in new term") 635 // as.ProduceCampaignOn() 636 // sentCampaign = height 637 // } 638 // 639 // case isUptoDate := <-as.UpdateEvent: 640 // as.TxEnable = isUptoDate 641 // height := as.Idag.LatestSequencer().Height 642 // log.WithField("height ", height).WithField("v ", isUptoDate).Info("get isUptoDate event") 643 // if eventInit { 644 // continue 645 // } 646 // 647 // if as.isGenesisPartner { 648 // //participate in bft process 649 // if height == 0 && isUptoDate { 650 // atomic.StoreUint32(&as.genesisBftIsRunning, 1) 651 // //wait until connect enought peers 652 // eventInit = true 653 // if !as.initDone && as.NbParticipants == 2 && peerNum == as.NbParticipants-1 { 654 // goroutine.New(func() { 655 // as.NewPeerConnectedEventListener <- "temp peer" 656 // }) 657 // } 658 // continue 659 // } 660 // //in this case , node is a genesis partner, load data 661 // 662 // if pk := as.dkg.GetJoinPublicKey(as.dkg.TermId); pk == nil && !loadDone { 663 // loadDone = true 664 // //load consensus data 665 // config, err := as.dkg.LoadConsensusData() 666 // if err != nil { 667 // log.WithError(err).Error("load error") 668 // panic(err) 669 // } 670 // as.dkg.SetConfig(config) 671 // log.Debug("will set config") 672 // as.addGenesisCampaigns() 673 // var sigSets []*tx_types.SigSet 674 // for k := range config.SigSets { 675 // sigSets = append(sigSets, config.SigSets[k]) 676 // } 677 // tc := as.genTermChg(pk, sigSets) 678 // as.term.ChangeTerm(tc, height) 679 // } 680 // if isUptoDate { 681 // //after updated , start bft process, skip bfd gossip 682 // log.Debug("start bft") 683 // eventInit = true 684 // waitNewTerm = true 685 // //TODO newTermChange if we got new Termchange 686 // if as.NbParticipants == 2 && peerNum == as.NbParticipants-1 { 687 // goroutine.New(func() { 688 // as.NewPeerConnectedEventListener <- "temp peer" 689 // }) 690 // } 691 // 692 // } 693 // } else { 694 // //not a consensus partner , obtain genesis dkg public key from network 695 // // 696 // if as.term.Started() { 697 // eventInit = true 698 // continue 699 // } 700 // msg := p2p_message.MessageTermChangeRequest{ 701 // Id: message.MsgCounter.Get(), 702 // } 703 // as.Hub.BroadcastMessage(message.MessageTypeTermChangeRequest, &msg) 704 // 705 // } 706 // 707 // case peerID := <-as.NewPeerConnectedEventListener: 708 // 709 // if !as.isGenesisPartner && !eventInit { 710 // msg := p2p_message.MessageTermChangeRequest{ 711 // Id: message.MsgCounter.Get(), 712 // } 713 // as.Hub.BroadcastMessage(message.MessageTypeTermChangeRequest, &msg) 714 // } 715 // if as.initDone { 716 // continue 717 // } 718 // if peerID != "temp peer" { 719 // peerNum++ 720 // } 721 // 722 // log.WithField("num", peerNum).Debug("peer num") 723 // if (peerNum == as.NbParticipants-1 || peerID == "temp peer") && atomic.LoadUint32(&as.genesisBftIsRunning) == 1 { 724 // log.Info("start dkg genesis consensus") 725 // goroutine.New(func() { 726 // as.dkg.SendGenesisPublicKey(as.genesisAccounts) 727 // }) 728 // as.initDone = true 729 // } 730 // if waitNewTerm && peerNum == as.NbParticipants-1 { 731 // waitNewTerm = false 732 // goroutine.New(func() { 733 // as.newTermChan <- true 734 // }) 735 // } 736 // 737 // //for genesis consensus , obtain tc from network 738 // case tc := <-as.termChangeChan: 739 // if eventInit { 740 // log.WithField("tc ", tc).Warn("already handle genesis tc") 741 // } 742 // pk, err := bn256.UnmarshalBinaryPointG2(tc.PkBls) 743 // if err != nil { 744 // log.WithError(err).Warn("unmarshal failed dkg joint public key") 745 // continue 746 // } 747 // if as.addedGenesisCampaign { 748 // log.Debug("one term change is enough") 749 // continue 750 // } 751 // as.dkg.SetJointPk(pk) 752 // eventInit = true 753 // as.addGenesisCampaigns() 754 // as.term.ChangeTerm(tc, as.Idag.GetHeight()) 755 // 756 // // 757 // case pkMsg := <-as.genesisPkChan: 758 // if genesisPublickeyProcessFinished { 759 // log.WithField("pkMsg ", pkMsg).Warn("already finished, don't send again") 760 // continue 761 // } 762 // id := -1 763 // for i, pk := range as.genesisAccounts { 764 // if bytes.Equal(pkMsg.PublicKey, pk.KeyBytes) { 765 // id = i 766 // break 767 // } 768 // } 769 // if id < 0 { 770 // log.Warn("not valid genesis pk") 771 // continue 772 // } 773 // addr := as.genesisAccounts[id].Address() 774 // cp := &tx_types.Campaign{ 775 // DkgPublicKey: pkMsg.DkgPublicKey, 776 // Issuer: &addr, 777 // TxBase: types.TxBase{ 778 // PublicKey: pkMsg.PublicKey, 779 // Weight: uint64(id*10 + 10), 780 // }, 781 // } 782 // err := cp.UnmarshalDkgKey(bn256.UnmarshalBinaryPointG2) 783 // if err != nil { 784 // log.WithField("pk data ", hexutil.Encode(cp.DkgPublicKey)).WithError(err).Warn("unmarshal error") 785 // continue 786 // } 787 // 788 // as.mu.RLock() 789 // genesisCamps = append(genesisCamps, cp) 790 // as.mu.RUnlock() 791 // log.WithField("id ", id).Debug("got geneis pk") 792 // if len(genesisCamps) == as.NbParticipants { 793 // goroutine.New(func() { 794 // as.commit(genesisCamps) 795 // }) 796 // genesisPublickeyProcessFinished = true 797 // } 798 // 799 // case hash := <-as.ProposalSeqChan: 800 // log.WithField("hash ", hash.TerminalString()).Debug("got proposal seq hash") 801 // as.bft.HandleProposal(hash) 802 // 803 // } 804 // } 805 // 806 //} 807 // 808 //type ConsensusInfo struct { 809 // Dkg *archive.DKGInfo `json:"dkg"` 810 // Bft *bft.BFTInfo `json:"bft"` 811 //} 812 // 813 //func (a *AnnSensus) GetInfo() *ConsensusInfo { 814 // var info ConsensusInfo 815 // info.Dkg, info.Bft = a.dkg.GetInfo(), a.bft.GetInfo() 816 // return &info 817 //} 818 // 819 //func (a *AnnSensus) GetBftStatus() interface{} { 820 // if a.bft == nil { 821 // return nil 822 // } 823 // return a.bft.GetStatus() 824 //}