Beispiel #1
0
// Instantiate returns a new NTree protocol instance
func (nt *NtreeServer) Instantiate(node *onet.TreeNodeInstance) (onet.ProtocolInstance, error) {
	log.Lvl2("Waiting for enough transactions...")
	currTransactions := nt.WaitEnoughBlocks()
	pi, err := NewNTreeRootProtocol(node, currTransactions)
	log.Lvl2("Instantiated Ntree Root Protocol with", len(currTransactions), "transactions")
	return pi, err
}
Beispiel #2
0
// ProposeVote calls the 'accept'-vote on the current propose-configuration
func (i *Identity) ProposeVote(accept bool) onet.ClientError {
	log.Lvl3("Voting proposal")
	if i.Proposed == nil {
		return onet.NewClientErrorCode(ErrorConfigMissing, "No proposed config")
	}
	log.Lvlf3("Voting %t on %s", accept, i.Proposed.Device)
	if !accept {
		return nil
	}
	hash, err := i.Proposed.Hash()
	if err != nil {
		return onet.NewClientErrorCode(ErrorOnet, err.Error())
	}
	sig, err := crypto.SignSchnorr(network.Suite, i.Private, hash)
	if err != nil {
		return onet.NewClientErrorCode(ErrorOnet, err.Error())
	}
	pvr := &ProposeVoteReply{}
	cerr := i.Client.SendProtobuf(i.Cothority.RandomServerIdentity(), &ProposeVote{
		ID:        i.ID,
		Signer:    i.DeviceName,
		Signature: &sig,
	}, pvr)
	if cerr != nil {
		return cerr
	}
	if pvr.Data != nil {
		log.Lvl2("Threshold reached and signed")
		i.Config = i.Proposed
		i.Proposed = nil
	} else {
		log.Lvl2("Threshold not reached")
	}
	return nil
}
Beispiel #3
0
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)
				}
			}
		}
	}
}
Beispiel #4
0
// CreateRootControl creates two Skipchains: a root SkipChain with
// maximumHeight of maxHRoot and an control SkipChain with
// maximumHeight of maxHControl. It connects both chains for later
// reference.
func (c *Client) CreateRootControl(elRoot, elControl *onet.Roster, baseHeight, maxHRoot, maxHControl int, ver VerifierID) (root, control *SkipBlock, cerr onet.ClientError) {
	log.Lvl2("Creating root roster", elRoot)
	root, cerr = c.CreateRoster(elRoot, baseHeight, maxHRoot, ver, nil)
	if cerr != nil {
		return
	}
	log.Lvl2("Creating control roster", elControl)
	control, cerr = c.CreateRoster(elControl, baseHeight, maxHControl, ver, root.Hash)
	if cerr != nil {
		return
	}
	return c.LinkParentChildBlock(root, control)
}
Beispiel #5
0
// Start initiates the JVSS protocol by setting up a long-term shared secret
// which can be used later on by the JVSS group to sign and verify messages.
func (jv *JVSS) Start() error {
	log.Lvl2(jv.Name(), "index", jv.Index(), " Starts()")
	sid := newSID(LTSS)
	jv.sidStore.insert(sid)
	err := jv.initSecret(sid)
	if err != nil {
		log.Error(err)
		return err
	}
	log.Lvl2("Waiting on long-term secrets:", jv.Name())
	<-jv.longTermSecDone
	log.Lvl2("Done waiting on long-term secrets:", jv.Name())
	return err
}
Beispiel #6
0
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
}
Beispiel #7
0
// signFile will search for the file and sign it
// it always returns nil as an error
func signFile(c *cli.Context) error {
	if c.Args().First() == "" {
		log.Fatal("Please give the file to sign", 1)
	}
	fileName := c.Args().First()
	groupToml := c.String(optionGroup)
	file, err := os.Open(fileName)
	log.ErrFatal(err, "Couldn't read file to be signed:")

	sig, err := sign(file, groupToml)
	log.ErrFatal(err, "Couldn't create signature:")

	log.Lvl3(sig)
	var outFile *os.File
	outFileName := c.String("out")
	if outFileName != "" {
		outFile, err = os.Create(outFileName)
		log.ErrFatal(err, "Couldn't create signature file:")
	} else {
		outFile = os.Stdout
	}
	writeSigAsJSON(sig, outFile)
	if outFileName != "" {
		log.Lvl2("Signature written to: %s", outFile.Name())
	} // else keep the Stdout empty
	return nil
}
Beispiel #8
0
// Tests a 2-node system
func TestBroadcast(t *testing.T) {
	for _, nbrNodes := range []int{3, 10, 14} {
		local := onet.NewLocalTest()
		_, _, tree := local.GenTree(nbrNodes, false)

		pi, err := local.CreateProtocol("Broadcast", tree)
		if err != nil {
			t.Fatal("Couldn't start protocol:", err)
		}
		protocol := pi.(*manage.Broadcast)
		done := make(chan bool)
		protocol.RegisterOnDone(func() {
			done <- true
		})
		protocol.Start()
		timeout := network.WaitRetry * time.Duration(network.MaxRetryConnect*nbrNodes*2) * time.Millisecond
		select {
		case <-done:
			log.Lvl2("Done with connecting everybody")
		case <-time.After(timeout):
			t.Fatal("Didn't finish in time")
		}
		local.CloseAll()
		log.AfterTest(t)
	}
}
Beispiel #9
0
func (c *Client) triggerTransactions(blocksPath string, nTxs int) error {
	log.Lvl2("ByzCoin Client will trigger up to", nTxs, "transactions")
	parser, err := blockchain.NewParser(blocksPath, magicNum)
	if err != nil {
		log.Error("Error: Couldn't parse blocks in", blocksPath,
			".\nPlease download bitcoin blocks as .dat files first and place them in",
			blocksPath, "Either run a bitcoin node (recommended) or using a torrent.")
		return err
	}

	transactions, err := parser.Parse(0, ReadFirstNBlocks)
	if err != nil {
		return fmt.Errorf("Error while parsing transactions %v", err)
	}
	if len(transactions) == 0 {
		return errors.New("Couldn't read any transactions.")
	}
	if len(transactions) < nTxs {
		return fmt.Errorf("Read only %v but caller wanted %v", len(transactions), nTxs)
	}
	consumed := nTxs
	for consumed > 0 {
		for _, tr := range transactions {
			// "send" transaction to server (we skip tcp connection on purpose here)
			c.srv.AddTransaction(tr)
		}
		consumed--
	}
	return nil
}
Beispiel #10
0
func checkMLUpdate(service *Service, root, latest *SkipBlock, base, height int) error {
	chain, err := service.GetUpdateChain(&GetUpdateChain{root.Hash})
	if err != nil {
		return err
	}
	updates := chain.(*GetUpdateChainReply).Update
	genesis := updates[0]
	if len(genesis.ForwardLink) != height {
		return errors.New("Genesis-block doesn't have height " + strconv.Itoa(height))
	}
	if len(updates[1].BackLinkIds) != height {
		return errors.New("Second block doesn't have correct number of backlinks")
	}
	l := updates[len(updates)-1]
	if len(l.ForwardLink) != 0 {
		return errors.New("Last block still has forward-links")
	}
	if !l.Equal(latest) {
		return errors.New("Last block from update is not the same as last block")
	}
	log.Lvl2(base, height, len(updates))
	if base > 1 && height > 1 && len(updates) == 10 {
		return fmt.Errorf("Shouldn't need 10 blocks with base %d and height %d",
			base, height)
	}
	return nil
}
Beispiel #11
0
// loadConfig will try to load the configuration and `fatal` if it is there but
// not valid. If the config-file is missing altogether, loaded will be false and
// an empty config-file will be returned.
func loadConfig(c *cli.Context) (cfg *ciscConfig, loaded bool) {
	cfg = &ciscConfig{Identity: &identity.Identity{}}
	loaded = true

	configFile := getConfig(c)
	log.Lvl2("Loading from", configFile)
	buf, err := ioutil.ReadFile(configFile)
	if err != nil {
		if os.IsNotExist(err) {
			return
		}
		log.ErrFatal(err)
	}
	_, msg, err := network.UnmarshalRegistered(buf)
	log.ErrFatal(err)
	cfg, loaded = msg.(*ciscConfig)
	cfg.Identity.Client = onet.NewClient(identity.ServiceName)
	for _, f := range cfg.Follow {
		f.Client = onet.NewClient(identity.ServiceName)
	}
	if !loaded {
		log.Fatal("Wrong message-type in config-file")
	}
	return
}
Beispiel #12
0
// 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
}
Beispiel #13
0
// Dispatch listens for all channels and waits for a timeout in case nothing
// happens for a certain duration
func (p *ProtocolCount) Dispatch() error {
	running := true
	for running {
		log.Lvl3(p.Info(), "waiting for message during", p.Timeout())
		select {
		case pc := <-p.PrepareCountChan:
			log.Lvl3(p.Info(), "received from", pc.TreeNode.ServerIdentity.Address,
				pc.Timeout)
			p.SetTimeout(pc.Timeout)
			p.FuncPC()
		case c := <-p.CountChan:
			p.FuncC(c)
			running = false
		case _ = <-p.NodeIsUpChan:
			if p.Parent() != nil {
				err := p.SendTo(p.Parent(), &NodeIsUp{})
				if err != nil {
					log.Error(p.Info(), "couldn't send to parent",
						p.Parent().Name(), err)
				}
			} else {
				p.Replies++
			}
		case <-time.After(time.Duration(p.Timeout()) * time.Millisecond):
			log.Lvl3(p.Info(), "timed out while waiting for", p.Timeout())
			if p.IsRoot() {
				log.Lvl2("Didn't get all children in time:", p.Replies)
				p.Count <- p.Replies
				running = false
			}
		}
	}
	p.Done()
	return nil
}
Beispiel #14
0
func (c *CoSimul) getResponse(in []abstract.Scalar) {
	if c.IsLeaf() {
		// This is the leaf-node and we can't verify it
		return
	}

	verify := false
	switch VerifyResponse {
	case NoCheck:
		log.Lvl3("Not checking at all")
	case RootCheck:
		verify = c.IsRoot()
	case AllCheck:
		verify = !c.IsLeaf()
	}

	if verify {
		err := c.VerifyResponses(c.TreeNode().AggregatePublic())
		if err != nil {
			log.Error("Couldn't verify responses at our level", c.Name(), err.Error())
		} else {
			log.Lvl2("Successfully verified responses at", c.Name())
		}
	}
}
Beispiel #15
0
func TestService_SetChildrenSkipBlock(t *testing.T) {
	// How many nodes in Root
	nodesRoot := 3

	local := onet.NewLocalTest()
	defer local.CloseAll()
	hosts, el, genService := local.MakeHELS(nodesRoot, skipchainSID)
	service := genService.(*Service)

	// Setting up two chains and linking one to the other
	sbRoot, err := makeGenesisRoster(service, el)
	log.ErrFatal(err)
	sbInter, err := makeGenesisRosterArgs(service, el, sbRoot.Hash, VerifyNone, 1, 1)
	log.ErrFatal(err)
	scsb := &SetChildrenSkipBlock{sbRoot.Hash, sbInter.Hash}
	service.SetChildrenSkipBlock(scsb)
	// Verifying other nodes also got the updated chains
	// Check for the root-chain
	for i, h := range hosts {
		log.Lvlf2("%x", skipchainSID)
		s := local.Services[h.ServerIdentity.ID][skipchainSID].(*Service)
		m, err := s.GetUpdateChain(&GetUpdateChain{sbRoot.Hash})
		log.ErrFatal(err, "Failed in iteration="+strconv.Itoa(i)+":")
		sb := m.(*GetUpdateChainReply)
		log.Lvl2(s.Context)
		if len(sb.Update) != 1 {
			// we expect only the first block
			t.Fatal("There should be only 1 SkipBlock in the update")
		}
		link := sb.Update[0].ChildSL
		if !bytes.Equal(link.Hash, sbInter.Hash) {
			t.Fatal("The child-link doesn't point to our intermediate SkipBlock", i)
		}
		// We need to verify the signature on the child-link, too. This
		// has to be signed by the collective signature of sbRoot.
		if cerr := sbRoot.VerifySignatures(); cerr != nil {
			t.Fatal("Signature on child-link is not valid")
		}
	}

	// And check for the intermediate-chain to be updated
	for _, h := range hosts {
		s := local.Services[h.ServerIdentity.ID][skipchainSID].(*Service)

		m, cerr := s.GetUpdateChain(&GetUpdateChain{sbInter.Hash})
		sb := m.(*GetUpdateChainReply)

		log.ErrFatal(cerr)
		if len(sb.Update) != 1 {
			t.Fatal("There should be only 1 SkipBlock in the update")
		}
		if !bytes.Equal(sb.Update[0].ParentBlockID, sbRoot.Hash) {
			t.Fatal("The intermediate SkipBlock doesn't point to the root")
		}
		if err := sb.Update[0].VerifySignatures(); err != nil {
			t.Fatal("Signature of that SkipBlock doesn't fit")
		}
	}
}
Beispiel #16
0
// If 'r' is nil, it will starts the response process.
func (bft *ProtocolBFTCoSi) handleResponsePrepare(r *Response) error {
	if r != nil {
		// check if we have enough responses
		bft.tmpMutex.Lock()
		bft.tempPrepareResponse = append(bft.tempPrepareResponse, r.Response)
		bft.tempExceptions = append(bft.tempExceptions, r.Exceptions...)
		if len(bft.tempPrepareResponse) < len(bft.Children()) {
			bft.tmpMutex.Unlock()
			return nil
		}
		bft.tmpMutex.Unlock()
	}

	// wait for verification
	bzrReturn, ok := bft.waitResponseVerification()
	// append response
	if !ok {
		log.Lvl2(bft.Roster(), "Refused to sign")
	}

	// Return if we're not root
	if !bft.IsRoot() {
		return bft.SendTo(bft.Parent(), bzrReturn)
	}
	// Since cosi does not support exceptions yet, we have to remove
	// the responses that are not supposed to be there,i.e. exceptions.
	cosiSig := bft.prepare.Signature()
	correctResponseBuff, err := bzrReturn.Response.MarshalBinary()
	if err != nil {
		return err
	}
	// replace the old one with the corrected one
	copy(cosiSig[32:64], correctResponseBuff)
	bft.prepareSignature = cosiSig

	// Verify the signature is correct
	data := sha512.Sum512(bft.Msg)
	sig := &BFTSignature{
		Msg:        data[:],
		Sig:        cosiSig,
		Exceptions: bft.tempExceptions,
	}

	aggCommit := bft.Suite().Point().Null()
	for _, c := range bft.tempPrepareCommit {
		aggCommit.Add(aggCommit, c)
	}
	if err := sig.Verify(bft.Suite(), bft.Roster().Publics()); err != nil {
		log.Error(bft.Name(), "Verification of the signature failed:", err)
		bft.signRefusal = true
	}
	log.Lvl3(bft.Name(), "Verification of signature successful")
	// Start the challenge of the 'commit'-round
	if err := bft.startChallenge(RoundCommit); err != nil {
		log.Error(bft.Name(), err)
		return err
	}
	return nil
}
Beispiel #17
0
// Instantiate takes blockSize transactions and create the byzcoin instances.
func (s *Server) Instantiate(node *onet.TreeNodeInstance) (onet.ProtocolInstance, error) {
	// wait until we have enough blocks
	currTransactions := s.WaitEnoughBlocks()
	log.Lvl2("Instantiate ByzCoin Round with", len(currTransactions), "transactions")
	pi, err := NewByzCoinRootProtocol(node, currTransactions, s.timeOutMs, s.fail)

	return pi, err
}
Beispiel #18
0
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()
		}
	}
}
Beispiel #19
0
func TestService_ProposeSkipBlock(t *testing.T) {
	// First create a roster to attach the data to it
	local := onet.NewLocalTest()
	defer local.CloseAll()
	_, el, genService := local.MakeHELS(5, skipchainSID)
	service := genService.(*Service)
	service.SkipBlocks = make(map[string]*SkipBlock)

	// Setting up root roster
	sbRoot, err := makeGenesisRoster(service, el)
	log.ErrFatal(err)

	// send a ProposeBlock
	genesis := NewSkipBlock()
	genesis.Data = []byte("In the beginning God created the heaven and the earth.")
	genesis.MaximumHeight = 2
	genesis.BaseHeight = 2
	genesis.ParentBlockID = sbRoot.Hash
	genesis.Roster = sbRoot.Roster
	blockCount := 0
	psbrMsg, err := service.ProposeSkipBlock(&ProposeSkipBlock{nil, genesis})
	assert.Nil(t, err)
	psbr := psbrMsg.(*ProposedSkipBlockReply)
	latest := psbr.Latest
	// verify creation of GenesisBlock:
	assert.Equal(t, blockCount, latest.Index)
	// the genesis block has a random back-link:
	assert.Equal(t, 1, len(latest.BackLinkIds))
	assert.NotEqual(t, 0, latest.BackLinkIds)

	next := NewSkipBlock()
	next.Data = []byte("And the earth was without form, and void; " +
		"and darkness was upon the face of the deep. " +
		"And the Spirit of God moved upon the face of the waters.")
	next.MaximumHeight = 2
	next.ParentBlockID = sbRoot.Hash
	next.Roster = sbRoot.Roster
	id := psbr.Latest.Hash
	psbrMsg, err = service.ProposeSkipBlock(&ProposeSkipBlock{id, next})
	assert.Nil(t, err)
	psbr2 := psbrMsg.(*ProposedSkipBlockReply)
	log.Lvl2(psbr2)
	if psbr2 == nil {
		t.Fatal("Didn't get anything in return")
	}
	assert.NotNil(t, psbr2)
	assert.NotNil(t, psbr2.Latest)
	latest2 := psbr2.Latest
	// verify creation of GenesisBlock:
	blockCount++
	assert.Equal(t, blockCount, latest2.Index)
	assert.Equal(t, 1, len(latest2.BackLinkIds))
	assert.NotEqual(t, 0, latest2.BackLinkIds)

	// We've added 2 blocks, + root block = 3
	assert.Equal(t, 3, service.lenSkipBlocks())
}
Beispiel #20
0
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()
	}
}
Beispiel #21
0
func (bz *ByzCoin) listen() {
	// FIXME handle different failure modes
	fail := (bz.rootFailMode != 0) && bz.IsRoot()
	var timeoutStarted bool
	for {
		var err error
		select {
		case msg := <-bz.announceChan:
			// Announcement
			err = bz.handleAnnouncement(msg.Announce)
		case msg := <-bz.commitChan:
			// Commitment
			if !fail {
				err = bz.handleCommit(msg.Commitment)
			}
		case msg := <-bz.challengePrepareChan:
			// Challenge
			if !fail {
				err = bz.handleChallengePrepare(&msg.ChallengePrepare)
			}
		case msg := <-bz.challengeCommitChan:
			if !fail {
				err = bz.handleChallengeCommit(&msg.ChallengeCommit)
			}
		case msg := <-bz.responseChan:
			// Response
			if !fail {
				switch msg.Response.TYPE {
				case RoundPrepare:
					err = bz.handleResponsePrepare(&msg.Response)
				case RoundCommit:
					err = bz.handleResponseCommit(&msg.Response)
				}
			}
		case timeout := <-bz.timeoutChan:
			// start the timer
			if timeoutStarted {
				continue
			}
			timeoutStarted = true
			go bz.startTimer(timeout)
		case msg := <-bz.viewchangeChan:
			// receive view change
			err = bz.handleViewChange(msg.TreeNode, &msg.viewChange)
		case <-bz.doneProcessing:
			// we are done
			log.Lvl2(bz.Name(), "ByzCoin Dispatches stop.")
			bz.tempBlock = nil
			return
		}
		if err != nil {
			log.Error("Error handling messages:", err)
		}
	}
}
Beispiel #22
0
func TestBftCoSi(t *testing.T) {
	const TestProtocolName = "DummyBFTCoSi"

	// Register test protocol using BFTCoSi
	onet.GlobalProtocolRegister(TestProtocolName, func(n *onet.TreeNodeInstance) (onet.ProtocolInstance, error) {
		return NewBFTCoSiProtocol(n, verify)
	})

	log.Lvl2("Simple count")
	runProtocol(t, TestProtocolName, 0)
}
Beispiel #23
0
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())
}
Beispiel #24
0
// sign takes a stream and a toml file defining the servers
func sign(r io.Reader, tomlFileName string) (*s.SignatureResponse, error) {
	log.Lvl2("Starting signature")
	f, err := os.Open(tomlFileName)
	if err != nil {
		return nil, err
	}
	el, err := config.ReadGroupToml(f)
	if err != nil {
		return nil, err
	}
	if len(el.List) <= 0 {
		return nil, errors.New("Empty or invalid cosi group file:" +
			tomlFileName)
	}
	log.Lvl2("Sending signature to", el)
	res, err := signStatement(r, el)
	if err != nil {
		return nil, err
	}
	return res, nil
}
Beispiel #25
0
// 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
}
Beispiel #26
0
// Saves the clientApp in the configfile - refuses to save an empty file.
func (cfg *ciscConfig) saveConfig(c *cli.Context) error {
	configFile := getConfig(c)
	if cfg == nil {
		return errors.New("Cannot save empty clientApp")
	}
	buf, err := network.MarshalRegisteredType(cfg)
	if err != nil {
		log.Error(err)
		return err
	}
	log.Lvl2("Saving to", configFile)
	return ioutil.WriteFile(configFile, buf, 0660)
}
Beispiel #27
0
func TestCheckRefuse(t *testing.T) {
	const TestProtocolName = "DummyBFTCoSiRefuse"

	// Register test protocol using BFTCoSi
	onet.GlobalProtocolRegister(TestProtocolName, func(n *onet.TreeNodeInstance) (onet.ProtocolInstance, error) {
		return NewBFTCoSiProtocol(n, verifyRefuse)
	})

	for refuseCount := 1; refuseCount <= 3; refuseCount++ {
		log.Lvl2("Refuse at", refuseCount)
		runProtocol(t, TestProtocolName, refuseCount)
	}
}
Beispiel #28
0
// 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
}
Beispiel #29
0
// PrePrepare intializes a full run of the protocol.
func (p *Protocol) PrePrepare() error {
	// pre-prepare: broadcast the block
	var err error
	log.Lvl2(p.Name(), "Broadcast PrePrepare")
	prep := &PrePrepare{p.trBlock}
	p.broadcast(func(tn *onet.TreeNode) {
		tempErr := p.SendTo(tn, prep)
		if tempErr != nil {
			err = tempErr
		}
		p.state = statePrepare
	})
	log.Lvl3(p.Name(), "Broadcast PrePrepare DONE")
	return err
}
Beispiel #30
0
// Verify-function that will refuse if the `called` bit is 0.
func verifyRefuseBit(m []byte, d []byte) bool {
	c, err := strconv.Atoi(string(d))
	log.ErrFatal(err)
	counter := counters.get(c)
	counter.Lock()
	defer counter.Unlock()
	log.Lvl4("Counter", c, counter.refuseCount, counter.veriCount)
	myBit := uint(counter.veriCount)
	counter.veriCount++
	if counter.refuseCount&(1<<myBit) != 0 {
		log.Lvl2("Refusing for myBit ==", myBit)
		return false
	}
	log.Lvl3("Verification called", counter.veriCount, "times")
	return true
}