func TestService_Verification(t *testing.T) { local := onet.NewLocalTest() defer local.CloseAll() sbLength := 4 _, el, genService := local.MakeHELS(sbLength, skipchainSID) service := genService.(*Service) elRoot := onet.NewRoster(el.List[0:3]) sbRoot, err := makeGenesisRoster(service, elRoot) log.ErrFatal(err) log.Lvl1("Creating non-conforming skipBlock") sb := NewSkipBlock() sb.Roster = el sb.MaximumHeight = 1 sb.BaseHeight = 1 sb.ParentBlockID = sbRoot.Hash sb.VerifierID = VerifyShard _, err = service.ProposeSkipBlock(&ProposeSkipBlock{nil, sb}) require.NotNil(t, err, "Shouldn't accept a non-confoirming skipblock") log.Lvl1("Creating skipblock with same Roster as root") sbInter, err := makeGenesisRosterArgs(service, elRoot, sbRoot.Hash, VerifyShard, 1, 1) log.ErrFatal(err) log.Lvl1("Creating skipblock with sub-Roster from root") elSub := onet.NewRoster(el.List[0:2]) sbInter, err = makeGenesisRosterArgs(service, elSub, sbRoot.Hash, VerifyShard, 1, 1) log.ErrFatal(err) scsb := &SetChildrenSkipBlock{sbRoot.Hash, sbInter.Hash} service.SetChildrenSkipBlock(scsb) }
func runProtocolOnceGo(nbrHosts int, name string, refuseCount int, succeed bool) error { log.Lvl2("Running BFTCoSi with", nbrHosts, "hosts") local := onet.NewLocalTest() defer local.CloseAll() _, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 2, true) log.Lvl3("Tree is:", tree.Dump()) done := make(chan bool) // create the message we want to sign for this round msg := []byte("Hello BFTCoSi") // Start the protocol node, err := local.CreateProtocol(name, tree) if err != nil { return errors.New("Couldn't create new node: " + err.Error()) } // Register the function generating the protocol instance var root *ProtocolBFTCoSi root = node.(*ProtocolBFTCoSi) root.Msg = msg cMux.Lock() counter := &Counter{refuseCount: refuseCount} counters.add(counter) root.Data = []byte(strconv.Itoa(counters.size() - 1)) log.Lvl3("Added counter", counters.size()-1, refuseCount) cMux.Unlock() log.ErrFatal(err) // function that will be called when protocol is finished by the root root.RegisterOnDone(func() { done <- true }) go node.Start() log.Lvl1("Launched protocol") // are we done yet? wait := time.Second * 60 select { case <-done: counter.Lock() if counter.veriCount != nbrHosts { return errors.New("Each host should have called verification.") } // if assert refuses we don't care for unlocking (t.Refuse) counter.Unlock() sig := root.Signature() err := sig.Verify(root.Suite(), root.Roster().Publics()) if succeed && err != nil { return fmt.Errorf("%s Verification of the signature refused: %s - %+v", root.Name(), err.Error(), sig.Sig) } if !succeed && err == nil { return fmt.Errorf("%s: Shouldn't have succeeded for %d hosts, but signed for count: %d", root.Name(), nbrHosts, refuseCount) } case <-time.After(wait): log.Lvl1("Going to break because of timeout") return errors.New("Waited " + wait.String() + " for BFTCoSi to finish ...") } return nil }
func TestClient_ProposeData(t *testing.T) { l := onet.NewTCPTest() _, el, _ := l.GenTree(5, true) defer l.CloseAll() c := NewTestClient(l) log.Lvl1("Creating root and control chain") _, inter, cerr := c.CreateRootControl(el, el, 1, 1, 1, VerifyNone) log.ErrFatal(cerr) td := &testData{1, "data-sc"} log.Lvl1("Creating data chain") var data1 *SkipBlock inter, data1, cerr = c.CreateData(inter, 1, 1, VerifyNone, td) log.ErrFatal(cerr) td.A++ log.Lvl1("Proposing data on intermediate chain") data2, cerr := c.ProposeData(inter, data1, td) log.ErrFatal(cerr) dataLast, cerr := c.GetUpdateChain(inter, data1.Hash) log.ErrFatal(cerr) if len(dataLast.Update) != 2 { t.Fatal("Should have two SkipBlocks for update-chain", len(dataLast.Update)) } if !dataLast.Update[1].Equal(data2.Latest) { t.Fatal("Newest SkipBlock should be stored") } c.Close() }
func TestServiceStatus(t *testing.T) { local := onet.NewTCPTest() // generate 5 hosts, they don't connect, they process messages, and they // don't register the tree or entitylist _, el, tr := local.GenTree(5, false) defer local.CloseAll() // Send a request to the service client := NewTestClient(local) log.Lvl1("Sending request to service...") stat, cerr := client.Request(el.List[0]) log.Lvl1(el.List[0]) log.ErrFatal(cerr) log.Lvl1(stat) assert.NotEmpty(t, stat.Msg["Status"].Field["Available_Services"]) pi, err := local.CreateProtocol("ExampleChannels", tr) if err != nil { t.Fatal("Couldn't start protocol:", err) } go pi.Start() <-pi.(*channels.ProtocolExampleChannels).ChildCount stat, cerr = client.Request(el.List[0]) log.ErrFatal(cerr) log.Lvl1(stat) assert.NotEmpty(t, stat.Msg["Status"].Field["Available_Services"]) }
// Run starts the simulation on the simulation-side func (e *Simulation) Run(config *onet.SimulationConfig) error { msg := []byte(e.Message) size := config.Tree.Size() log.Lvl2("Size is:", size, "rounds:", e.Rounds) for round := 0; round < e.Rounds; round++ { log.Lvl1("Starting round", round, "with message", string(msg)) round := monitor.NewTimeMeasure("round") p, err := config.Overlay.CreateProtocolOnet("NaiveTree", config.Tree) if err != nil { log.Error("Quitting the simulation....", err) return err } pi := p.(*Protocol) pi.Message = msg pi.verifySignature = e.Checking done := make(chan bool) pi.TreeNodeInstance.OnDoneCallback(func() bool { done <- true return true }) err = pi.Start() if err != nil { log.Error("Quitting the simulation....", err) return err } <-done round.Record() } return nil }
func TestService_MultiLevel(t *testing.T) { local := onet.NewLocalTest() defer local.CloseAll() _, el, genService := local.MakeHELS(3, skipchainSID) service := genService.(*Service) for base := 1; base <= 3; base++ { for height := 1; height <= 3; height++ { if base == 1 && height > 1 { break } sbRoot, err := makeGenesisRosterArgs(service, el, nil, VerifyNone, base, height) log.ErrFatal(err) latest := sbRoot log.Lvl1("Adding blocks for", base, height) for sbi := 1; sbi < 10; sbi++ { sb := NewSkipBlock() sb.Roster = el psbr, err := service.ProposeSkipBlock(&ProposeSkipBlock{latest.Hash, sb}) log.ErrFatal(err) latest = psbr.(*ProposedSkipBlockReply).Latest } log.ErrFatal(checkMLForwardBackward(service, sbRoot, base, height)) log.ErrFatal(checkMLUpdate(service, sbRoot, latest, base, height)) } } // Setting up two chains and linking one to the other }
func TestService_GetUpdateChain(t *testing.T) { // Create a small chain and test whether we can get from one element // of the chain to the last element with a valid slice of SkipBlocks local := onet.NewLocalTest() defer local.CloseAll() sbLength := 3 _, el, gs := local.MakeHELS(sbLength, skipchainSID) s := gs.(*Service) sbs := make([]*SkipBlock, sbLength) var err error sbs[0], err = makeGenesisRoster(s, el) log.ErrFatal(err) log.Lvl1("Initialize skipchain.") // init skipchain for i := 1; i < sbLength; i++ { log.Lvl2("Doing skipblock", i) newSB := NewSkipBlock() newSB.Roster = el psbrMsg, err := s.ProposeSkipBlock(&ProposeSkipBlock{sbs[i-1].Hash, newSB}) assert.Nil(t, err) reply := psbrMsg.(*ProposedSkipBlockReply) sbs[i] = reply.Latest } for i := 0; i < sbLength; i++ { m, err := s.GetUpdateChain(&GetUpdateChain{sbs[i].Hash}) sbc := m.(*GetUpdateChainReply) log.ErrFatal(err) if !sbc.Update[0].Equal(sbs[i]) { t.Fatal("First hash is not from our SkipBlock") } if !sbc.Update[len(sbc.Update)-1].Equal(sbs[sbLength-1]) { log.Lvl2(sbc.Update[len(sbc.Update)-1].Hash) log.Lvl2(sbs[sbLength-1].Hash) t.Fatal("Last Hash is not equal to last SkipBlock for", i) } for up, sb1 := range sbc.Update { log.ErrFatal(sb1.VerifySignatures()) if up < len(sbc.Update)-1 { sb2 := sbc.Update[up+1] h1 := sb1.Height h2 := sb2.Height log.Lvl2("sbc1.Height=", sb1.Height) log.Lvl2("sbc2.Height=", sb2.Height) // height := min(len(sb1.ForwardLink), h2) height := h1 if h2 < height { height = h2 } if !bytes.Equal(sb1.ForwardLink[height-1].Hash, sb2.Hash) { t.Fatal("Forward-pointer of", up, "is different of hash in", up+1) } } } } }
func TestCosi(t *testing.T) { //defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) for _, nbrHosts := range []int{1, 3, 13} { log.Lvl2("Running cosi with", nbrHosts, "hosts") local := onet.NewLocalTest() hosts, el, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true) aggPublic := network.Suite.Point().Null() for _, e := range el.List { aggPublic = aggPublic.Add(aggPublic, e.Public) } done := make(chan bool) // create the message we want to sign for this round msg := []byte("Hello World Cosi") // Register the function generating the protocol instance var root *CoSi // function that will be called when protocol is finished by the root doneFunc := func(sig []byte) { suite := hosts[0].Suite() publics := el.Publics() if err := root.VerifyResponses(aggPublic); err != nil { t.Fatal("Error verifying responses", err) } if err := VerifySignature(suite, publics, msg, sig); err != nil { t.Fatal("Error verifying signature:", err) } done <- true } // Start the protocol p, err := local.CreateProtocol("CoSi", tree) if err != nil { t.Fatal("Couldn't create new node:", err) } root = p.(*CoSi) root.Message = msg responseFunc := func(in []abstract.Scalar) { log.Lvl1("Got response") if len(root.Children()) != len(in) { t.Fatal("Didn't get same number of responses") } } root.RegisterResponseHook(responseFunc) root.RegisterSignatureHook(doneFunc) go root.StartProtocol() select { case <-done: case <-time.After(time.Second * 2): t.Fatal("Could not get signature verification done in time") } local.CloseAll() } }
func TestClient_ProposeRoster(t *testing.T) { t.Skip("See https://github.com/dedis/cothority/issues/733") nbrHosts := 5 l := onet.NewTCPTest() _, el, _ := l.GenTree(nbrHosts, true) defer l.CloseAll() c := NewTestClient(l) log.Lvl1("Creating root and control chain") _, inter, cerr := c.CreateRootControl(el, el, 1, 1, 1, VerifyNone) log.ErrFatal(cerr) el2 := onet.NewRoster(el.List[:nbrHosts-1]) log.Lvl1("Proposing roster", el2) var sb1 *ProposedSkipBlockReply sb1, cerr = c.ProposeRoster(inter, el2) log.ErrFatal(cerr) log.Lvl1("Proposing same roster again") _, cerr = c.ProposeRoster(inter, el2) if cerr == nil { t.Fatal("Appending two Blocks to the same last block should fail") } log.Lvl1("Proposing following roster") sb2, cerr := c.ProposeRoster(sb1.Latest, el2) log.ErrFatal(cerr) if !sb2.Previous.Equal(sb1.Latest) { t.Fatal("New previous should be previous latest") } if !bytes.Equal(sb2.Previous.ForwardLink[0].Hash, sb2.Latest.Hash) { t.Fatal("second should point to third SkipBlock") } updates, cerr := c.GetUpdateChain(inter, inter.Hash) if len(updates.Update) != 3 { t.Fatal("Should now have three Blocks to go from Genesis to current, but have", len(updates.Update), inter, sb2) } if !updates.Update[2].Equal(sb2.Latest) { t.Fatal("Last block in update-chain should be last block added") } c.Close() }
// Run initiates a JVSS simulation func (jvs *Simulation) Run(config *onet.SimulationConfig) error { size := config.Tree.Size() msg := []byte("Test message for JVSS simulation") log.Lvl1("Size:", size, "rounds:", jvs.Rounds) p, err := config.Overlay.CreateProtocolOnet("JVSS", config.Tree) if err != nil { return err } proto := p.(*JVSS) log.Lvl1("Starting setup") proto.Start() log.Lvl1("Setup done") for round := 0; round < jvs.Rounds; round++ { log.Lvl1("Starting signing round", round) r := monitor.NewTimeMeasure("round") log.Lvl2("Requesting signature") sig, err := proto.Sign(msg) if err != nil { log.Error("Could not create signature") return err } if jvs.Verify { log.Lvl2("Signature received") if err := proto.Verify(msg, sig); err != nil { log.Error("Signature invalid") return err } log.Lvl2("Signature valid") } r.Record() } return nil }
// Run implements onet.Simulation. func (cs *Simulation) Run(config *onet.SimulationConfig) error { size := len(config.Roster.List) msg := []byte("Hello World Cosi Simulation") log.Lvl2("Simulation starting with: Size=", size, ", Rounds=", cs.Rounds) for round := 0; round < cs.Rounds; round++ { log.Lvl1("Starting round", round) roundM := monitor.NewTimeMeasure("round") // create the node with the protocol, but do NOT start it yet. node, err := config.Overlay.CreateProtocolOnet(Name, config.Tree) if err != nil { return err } // the protocol itself proto := node.(*CoSimul) // give the message to sign proto.SigningMessage(msg) // tell us when it is done done := make(chan bool) fn := func(sig []byte) { roundM.Record() publics := proto.Publics() if err := cosi.VerifySignature(network.Suite, publics, msg, sig); err != nil { log.Lvl1("Round", round, " => fail verification") } else { log.Lvl2("Round", round, " => success") } done <- true } proto.RegisterSignatureHook(fn) if err := proto.Start(); err != nil { log.Error("Couldn't start protocol in round", round) } <-done } log.Lvl1("Simulation finished") return nil }
// DownloadBlock takes 'dir' as the directory where to download the block. // It returns the downloaded file func DownloadBlock(dir string) (string, error) { blockDir := SimulDirToBlockDir(dir) cmd := exec.Command("wget", "--no-check-certificate", "-O", blockDir+"/blk00000.dat", "-c", "https://icsil1-box.epfl.ch:5001/fbsharing/IzTFdOxf") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr log.Lvl1("Cmd is", cmd) if err := cmd.Start(); err != nil { return "", err } if err := cmd.Wait(); err != nil { return "", err } return GetBlockName(dir), nil }
func TestCoSimul(t *testing.T) { for VerifyResponse = 0; VerifyResponse < 3; VerifyResponse++ { for _, nbrHosts := range []int{1, 3, 13} { log.Lvl2("Running cosi with", nbrHosts, "hosts") local := onet.NewLocalTest() hosts, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true) log.Lvl2(tree.Dump()) done := make(chan bool) // create the message we want to sign for this round msg := []byte("Hello World Cosi") // Register the function generating the protocol instance var root *CoSimul // function that will be called when protocol is finished by the root doneFunc := func(sig []byte) { suite := hosts[0].Suite() if err := cosi.VerifySignature(suite, root.Publics(), msg, sig); err != nil { t.Fatal("error verifying signature:", err) } else { log.Lvl1("Verification OK") } done <- true } // Start the protocol p, err := local.CreateProtocol(Name, tree) if err != nil { t.Fatal("Couldn't create new node:", err) } root = p.(*CoSimul) root.Message = msg root.RegisterSignatureHook(doneFunc) go root.StartProtocol() select { case <-done: case <-time.After(time.Second * 2): t.Fatal("Could not get signature verification done in time") } local.CloseAll() } } }
func TestServiceGuard(t *testing.T) { local := onet.NewTCPTest() _, el, _ := local.GenTree(5, true) defer local.CloseAll() // Send a request to the service client := NewLocalTestClient(local) log.Lvl1("Sending request to service...") UID := []byte("USER") Epoch := []byte("EPOCH") msg := network.Suite.Point() Hzi, _ := client.SendToGuard(el.List[0], UID, Epoch, msg) // We send the message twice to see that the key did not change for the //same epoch. Hz2, _ := client.SendToGuard(el.List[0], UID, Epoch, msg) assert.Equal(t, Hzi, Hz2) }
// Run implements onet.Simulation interface func (e *Simulation) Run(onetConf *onet.SimulationConfig) error { log.Lvl2("Naive Tree Simulation starting with: Rounds=", e.Rounds) server := NewNtreeServer(e.Blocksize) for round := 0; round < e.Rounds; round++ { client := byzcoin.NewClient(server) err := client.StartClientSimulation(blockchain.GetBlockDir(), e.Blocksize) if err != nil { log.Error("ClientSimulation:", err) } log.Lvl1("Starting round", round) // create an empty node node := onetConf.Overlay.NewTreeNodeInstanceFromProtoName(onetConf.Tree, "ByzCoinNtree") // instantiate a byzcoin protocol rComplete := monitor.NewTimeMeasure("round") pi, err := server.Instantiate(node) if err != nil { return err } onetConf.Overlay.RegisterProtocolInstance(pi) nt := pi.(*Ntree) // Register when the protocol is finished (all the nodes have finished) done := make(chan bool) nt.RegisterOnDone(func(sig *NtreeSignature) { rComplete.Record() log.Lvl3("Done") done <- true }) go func() { if err := nt.Start(); err != nil { log.Error("Couldn't start ntree protocol:", err) } }() // wait for the end <-done log.Lvl3("Round", round, "finished") } return nil }
// Run is used on the destination machines and runs a number of // rounds func (e *simulation) Run(config *onet.SimulationConfig) error { size := config.Tree.Size() log.Lvl2("Size is:", size, "rounds:", e.Rounds) for round := 0; round < e.Rounds; round++ { log.Lvl1("Starting round", round) round := monitor.NewTimeMeasure("round") p, err := config.Overlay.CreateProtocolOnet("Count", config.Tree) if err != nil { return err } go p.Start() children := <-p.(*ProtocolCount).Count round.Record() if children != size { return errors.New("Didn't get " + strconv.Itoa(size) + " children") } } return nil }
func TestServiceCosi(t *testing.T) { defer log.AfterTest(t) log.TestOutput(testing.Verbose(), 4) local := onet.NewTCPTest() // generate 5 hosts, they don't connect, they process messages, and they // don't register the tree or entitylist hosts, el, _ := local.GenTree(5, false) defer local.CloseAll() // Send a request to the service client := NewTestClient(local) msg := []byte("hello cosi service") log.Lvl1("Sending request to service...") res, err := client.SignatureRequest(el, msg) log.ErrFatal(err, "Couldn't send") // verify the response still assert.Nil(t, cosi.VerifySignature(hosts[0].Suite(), el.Publics(), msg, res.Signature)) }
func TestCrashAfterRevocation(t *testing.T) { l := onet.NewTCPTest() hosts, el, _ := l.GenTree(5, true) services := l.GetServices(hosts, identityService) defer l.CloseAll() for _, s := range services { log.Lvl3(s.(*Service).Identities) } c1 := NewIdentity(el, 2, "one") c2 := NewIdentity(el, 2, "two") c3 := NewIdentity(el, 2, "three") defer c1.Close() defer c2.Close() defer c3.Close() log.ErrFatal(c1.CreateIdentity()) log.ErrFatal(c2.AttachToIdentity(c1.ID)) proposeUpVote(c1) log.ErrFatal(c3.AttachToIdentity(c1.ID)) proposeUpVote(c1) proposeUpVote(c2) log.ErrFatal(c1.ConfigUpdate()) log.Lvl2(c1.Config) conf := c1.GetProposed() delete(conf.Device, "three") log.Lvl2(conf) log.ErrFatal(c1.ProposeSend(conf)) proposeUpVote(c1) proposeUpVote(c2) log.ErrFatal(c1.ConfigUpdate()) log.Lvl2(c1.Config) log.Lvl1("C3 trying to send anyway") conf = c3.GetProposed() c3.ProposeSend(conf) if c3.ProposeVote(true) == nil { t.Fatal("Should not be able to vote") } log.ErrFatal(c1.ProposeUpdate()) }
func TestService_SignBlock(t *testing.T) { // Testing whether we sign correctly the SkipBlocks local := onet.NewLocalTest() defer local.CloseAll() _, el, genService := local.MakeHELS(3, skipchainSID) service := genService.(*Service) sbRoot, err := makeGenesisRosterArgs(service, el, nil, VerifyNone, 1, 1) log.ErrFatal(err) el2 := onet.NewRoster(el.List[0:2]) sb := NewSkipBlock() sb.Roster = el2 psbr, err := service.ProposeSkipBlock(&ProposeSkipBlock{sbRoot.Hash, sb}) log.ErrFatal(err) reply := psbr.(*ProposedSkipBlockReply) sbRoot = reply.Previous sbSecond := reply.Latest log.Lvl1("Verifying signatures") log.ErrFatal(sbRoot.VerifySignatures()) log.ErrFatal(sbSecond.VerifySignatures()) }
func (sr *BlockReply) MarshalJSON() ([]byte, error) { type Alias BlockReply var b bytes.Buffer suite, err := suites.StringToSuite(sr.SuiteStr) if err != nil { return nil, err } //log.Print("Preparing abstracts") if err := suite.Write(&b, sr.Response, sr.Challenge, sr.AggCommit, sr.AggPublic); err != nil { log.Lvl1("encoding stampreply response/challenge/AggCommit:", err) return nil, err } //log.Print("Returning helper-struct") return json.Marshal(&struct { SignatureInfo []byte *Alias }{ SignatureInfo: b.Bytes(), Alias: (*Alias)(sr), }) }
func TestCheckRefuseBit(t *testing.T) { const TestProtocolName = "DummyBFTCoSiRefuseBit" // Register test protocol using BFTCoSi onet.GlobalProtocolRegister(TestProtocolName, func(n *onet.TreeNodeInstance) (onet.ProtocolInstance, error) { return NewBFTCoSiProtocol(n, verifyRefuseBit) }) wg := sync.WaitGroup{} for _, n := range []int{3} { for refuseCount := 0; refuseCount < 1<<uint(n); refuseCount++ { wg.Add(1) go func(n, fc int) { log.Lvl1("RefuseBit at", n, fc) log.ErrFatal(runProtocolOnceGo(n, TestProtocolName, fc, bitCount(fc) < (n+1)*2/3)) log.Lvl3("Done with", n, fc) wg.Done() }(n, refuseCount) } } wg.Wait() }
func TestJVSS(t *testing.T) { // Setup parameters var name string = "JVSS" // Protocol name var nodes uint32 = 16 // Number of nodes var rounds int = 1 // Number of rounds msg := []byte("Hello World!") // Message to-be-signed local := onet.NewLocalTest() _, _, tree := local.GenTree(int(nodes), true) defer local.CloseAll() log.Lvl1("JVSS - starting") leader, err := local.CreateProtocol(name, tree) if err != nil { t.Fatal("Couldn't initialise protocol tree:", err) } jv := leader.(*JVSS) leader.Start() log.Lvl1("JVSS - setup done") for i := 0; i < rounds; i++ { log.Lvl1("JVSS - starting round", i) log.Lvl1("JVSS - requesting signature") sig, err := jv.Sign(msg) if err != nil { t.Fatal("Error signature failed", err) } log.Lvl1("JVSS - signature received") err = jv.Verify(msg, sig) if err != nil { t.Fatal("Error signature verification failed", err) } log.Lvl1("JVSS - signature verification succeded") } }
// Run implements onet.Simulation interface func (e *Simulation) Run(onetConf *onet.SimulationConfig) error { log.Lvl2("Simulation starting with: Rounds=", e.Rounds) server := NewByzCoinServer(e.Blocksize, e.TimeoutMs, e.Fail) pi, err := onetConf.Overlay.CreateProtocolOnet("Broadcast", onetConf.Tree) if err != nil { return err } proto, _ := pi.(*manage.Broadcast) // channel to notify we are done broadDone := make(chan bool) proto.RegisterOnDone(func() { broadDone <- true }) // ignore error on purpose: Broadcast.Start() always returns nil _ = proto.Start() // wait <-broadDone for round := 0; round < e.Rounds; round++ { client := NewClient(server) err := client.StartClientSimulation(blockchain.GetBlockDir(), e.Blocksize) if err != nil { log.Error("Error in ClientSimulation:", err) return err } log.Lvl1("Starting round", round) // create an empty node tni := onetConf.Overlay.NewTreeNodeInstanceFromProtoName(onetConf.Tree, "ByzCoin") if err != nil { return err } // instantiate a byzcoin protocol rComplete := monitor.NewTimeMeasure("round") pi, err := server.Instantiate(tni) if err != nil { return err } onetConf.Overlay.RegisterProtocolInstance(pi) bz := pi.(*ByzCoin) // Register callback for the generation of the signature ! bz.RegisterOnSignatureDone(func(sig *BlockSignature) { rComplete.Record() if err := verifyBlockSignature(tni.Suite(), tni.Roster().Aggregate, sig); err != nil { log.Error("Round", round, "failed:", err) } else { log.Lvl2("Round", round, "success") } }) // Register when the protocol is finished (all the nodes have finished) done := make(chan bool) bz.RegisterOnDone(func() { done <- true }) if e.Fail > 0 { go func() { err := bz.startAnnouncementPrepare() if err != nil { log.Error("Error while starting "+ "announcment prepare:", err) } }() // do not run bz.startAnnouncementCommit() } else { go func() { if err := bz.Start(); err != nil { log.Error("Couldn't start protocol", err) } }() } // wait for the end <-done log.Lvl3("Round", round, "finished") } return nil }
// Run runs the simulation func (e *Simulation) Run(onetConf *onet.SimulationConfig) error { doneChan := make(chan bool) doneCB := func() { doneChan <- true } // FIXME use client instead dir := blockchain.GetBlockDir() parser, err := blockchain.NewParser(dir, magicNum) if err != nil { log.Error("Error: Couldn't parse blocks in", dir) return err } transactions, err := parser.Parse(0, e.Blocksize) if err != nil { log.Error("Error while parsing transactions", err) return err } // FIXME c&p from byzcoin.go trlist := blockchain.NewTransactionList(transactions, len(transactions)) header := blockchain.NewHeader(trlist, "", "") trblock := blockchain.NewTrBlock(trlist, header) // Here we first setup the N^2 connections with a broadcast protocol pi, err := onetConf.Overlay.CreateProtocolOnet("Broadcast", onetConf.Tree) if err != nil { log.Error(err) } proto := pi.(*manage.Broadcast) // channel to notify we are done broadDone := make(chan bool) proto.RegisterOnDone(func() { broadDone <- true }) // ignore error on purpose: Start always returns nil _ = proto.Start() // wait <-broadDone log.Lvl3("Simulation can start!") for round := 0; round < e.Rounds; round++ { log.Lvl1("Starting round", round) p, err := onetConf.Overlay.CreateProtocolOnet("ByzCoinPBFT", onetConf.Tree) if err != nil { return err } proto := p.(*Protocol) proto.trBlock = trblock proto.onDoneCB = doneCB r := monitor.NewTimeMeasure("round_pbft") err = proto.Start() if err != nil { log.Error("Couldn't start PrePrepare") return err } // wait for finishing pbft: <-doneChan r.Record() log.Lvl2("Finished round", round) } return nil }