コード例 #1
0
ファイル: close_all_test.go プロジェクト: nikirill/cothority
// Tests a 2-node system
func TestCloseall(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)
	local := sda.NewLocalTest()
	nbrNodes := 2
	_, _, tree := local.GenTree(nbrNodes, false, true, true)
	defer local.CloseAll()

	pi, err := local.CreateProtocol(tree, "ExampleChannels")
	if err != nil {
		t.Fatal("Couldn't start protocol:", err)
	}
	go pi.Start()
	protocol := pi.(*channels.ProtocolExampleChannels)
	timeout := network.WaitRetry * time.Duration(network.MaxRetry*nbrNodes*2) * time.Millisecond
	select {
	case children := <-protocol.ChildCount:
		log.Lvl2("Instance 1 is done")
		if children != nbrNodes {
			t.Fatal("Didn't get a child-cound of", nbrNodes)
		}
	case <-time.After(timeout):
		t.Fatal("Didn't finish in time")
	}
}
コード例 #2
0
ファイル: monitor_test.go プロジェクト: nikirill/cothority
func TestReadyNormal(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 3)
	m := make(map[string]string)
	m["servers"] = "1"
	stat := NewStats(m)
	fresh := stat.String()
	// First set up monitor listening
	mon := NewMonitor(stat)
	go mon.Listen()
	time.Sleep(100 * time.Millisecond)

	// Then measure
	err := ConnectSink("localhost:" + strconv.Itoa(DefaultSinkPort))
	if err != nil {
		t.Fatal(fmt.Sprintf("Error starting monitor: %s", err))
		return
	}

	meas := NewSingleMeasure("round", 10)
	meas.Record()
	time.Sleep(200 * time.Millisecond)
	NewSingleMeasure("round", 20)
	EndAndCleanup()
	time.Sleep(100 * time.Millisecond)
	updated := mon.Stats().String()
	if updated == fresh {
		t.Fatal("Stats not updated ?")
	}

}
コード例 #3
0
ファイル: broadcast_test.go プロジェクト: nikirill/cothority
// Tests a 2-node system
func TestBroadcast(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 3)
	for _, nbrNodes := range []int{3, 10, 14} {
		local := sda.NewLocalTest()
		_, _, tree := local.GenTree(nbrNodes, false, true, true)

		pi, err := local.CreateProtocol(tree, "Broadcast")
		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.MaxRetry*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()
	}
}
コード例 #4
0
ファイル: monitor_test.go プロジェクト: nikirill/cothority
func TestKeyOrder(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 3)
	m := make(map[string]string)
	m["servers"] = "1"
	m["hosts"] = "1"
	m["bf"] = "2"
	// create stats
	stat := NewStats(m)
	m1 := NewSingleMeasure("round", 10)
	m2 := NewSingleMeasure("setup", 5)
	stat.Update(m1)
	stat.Update(m2)
	str := new(bytes.Buffer)
	stat.WriteHeader(str)
	stat.WriteValues(str)

	stat2 := NewStats(m)
	stat2.Update(m1)
	stat2.Update(m2)

	str2 := new(bytes.Buffer)
	stat2.WriteHeader(str2)
	stat2.WriteValues(str2)
	if !bytes.Equal(str.Bytes(), str2.Bytes()) {
		t.Fatal("KeyOrder / output not the same for same stats")
	}
}
コード例 #5
0
ファイル: stats_test.go プロジェクト: nikirill/cothority
func TestStatsAverage(t *testing.T) {
	log.TestOutput(testing.Verbose(), 3)
	m := make(map[string]string)
	m["servers"] = "1"
	m["hosts"] = "1"
	m["bf"] = "2"
	// create stats
	stat1 := NewStats(m)
	stat2 := NewStats(m)
	m1 := NewSingleMeasure("round", 10)
	m2 := NewSingleMeasure("setup", 5)
	stat1.Update(m1)
	stat2.Update(m2)

	str := new(bytes.Buffer)
	avgStat := AverageStats([]*Stats{stat1, stat2})
	avgStat.WriteHeader(str)
	avgStat.WriteValues(str)

	stat3 := NewStats(m)
	stat4 := NewStats(m)
	stat3.Update(m1)
	stat4.Update(m2)

	str2 := new(bytes.Buffer)
	avgStat2 := AverageStats([]*Stats{stat3, stat4})
	avgStat2.WriteHeader(str2)
	avgStat2.WriteValues(str2)

	if !bytes.Equal(str.Bytes(), str2.Bytes()) {
		t.Fatal("Average are not the same !")
	}
}
コード例 #6
0
ファイル: simulation_test.go プロジェクト: nikirill/cothority
func TestSimulationBF(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)
	sc, _, err := createBFTree(7, 2)
	if err != nil {
		t.Fatal(err)
	}
	addresses := []string{
		"local1:2000", "local2:2000",
		"local1:2001", "local2:2001",
		"local1:2002", "local2:2002",
		"local1:2003",
	}
	for i, a := range sc.Roster.List {
		if a.Addresses[0] != addresses[i] {
			t.Fatal("Address", a.Addresses[0], "should be", addresses[i])
		}
	}
	if !sc.Tree.IsBinary(sc.Tree.Root) {
		t.Fatal("Created tree is not binary")
	}

	sc, _, err = createBFTree(13, 3)
	if err != nil {
		t.Fatal(err)
	}
	if len(sc.Tree.Root.Children) != 3 {
		t.Fatal("Branching-factor 3 tree has not 3 children")
	}
	if !sc.Tree.IsNary(sc.Tree.Root, 3) {
		t.Fatal("Created tree is not binary")
	}
}
コード例 #7
0
ファイル: crypto_test.go プロジェクト: nikirill/cothority
func TestMain(m *testing.M) {
	flag.Parse()
	log.TestOutput(testing.Verbose(), 4)
	code := m.Run()
	log.AfterTest(nil)
	os.Exit(code)
}
コード例 #8
0
ファイル: bftcosi_test.go プロジェクト: nikirill/cothority
func TestBftCoSi(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)

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

	for _, nbrHosts := range []int{3, 13} {
		countMut.Lock()
		veriCount = 0
		countMut.Unlock()
		log.Lvl2("Running BFTCoSi with", nbrHosts, "hosts")
		local := sda.NewLocalTest()
		_, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true, true)

		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(tree, TestProtocolName)
		if err != nil {
			t.Fatal("Couldn't create new node:", err)
		}

		// Register the function generating the protocol instance
		var root *ProtocolBFTCoSi
		root = node.(*ProtocolBFTCoSi)
		root.Msg = msg
		// function that will be called when protocol is finished by the root
		root.RegisterOnDone(func() {
			done <- true
		})
		go node.Start()
		// are we done yet?
		wait := time.Second * 3
		select {
		case <-done:
			countMut.Lock()
			assert.Equal(t, veriCount, nbrHosts,
				"Each host should have called verification.")
			// if assert fails we don't care for unlocking (t.Fail)
			countMut.Unlock()
			sig := root.Signature()
			if err := cosi.VerifyCosiSignatureWithException(root.Suite(),
				root.AggregatedPublic, msg, sig.Sig,
				sig.Exceptions); err != nil {

				t.Fatal(fmt.Sprintf("%s Verification of the signature failed: %s", root.Name(), err.Error()))
			}
		case <-time.After(wait):
			t.Fatal("Waited", wait, "sec for BFTCoSi to finish ...")
		}
		local.CloseAll()
	}
}
コード例 #9
0
ファイル: simulation_test.go プロジェクト: nikirill/cothority
func TestBigTree(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)
	for i := uint(12); i < 15; i++ {
		_, _, err := createBFTree(1<<i-1, 2)
		if err != nil {
			t.Fatal(err)
		}
	}
}
コード例 #10
0
ファイル: protocol_test.go プロジェクト: nikirill/cothority
// This makes h2 the leader, so it creates a tree and entity list
// and start a protocol. H1 should receive that message and request the entitity
// list and the treelist and then instantiate the protocol.
func TestProtocolAutomaticInstantiation(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	// setup
	chanH1 := make(chan bool)
	chanH2 := make(chan bool)
	chans := []chan bool{chanH1, chanH2}
	id := 0
	// custom creation function so we know the step due to the channels
	fn := func(n *sda.TreeNodeInstance) (sda.ProtocolInstance, error) {
		ps := SimpleProtocol{
			TreeNodeInstance: n,
			Chan:             chans[id],
		}
		ps.RegisterHandler(ps.ReceiveMessage)
		id++
		return &ps, nil
	}

	network.RegisterMessageType(SimpleMessage{})
	sda.ProtocolRegisterName(simpleProto, fn)
	h1, h2 := SetupTwoHosts(t, true)
	defer h1.Close()
	defer h2.Close()
	h1.StartProcessMessages()
	// create small Tree
	el := sda.NewRoster([]*network.ServerIdentity{h1.ServerIdentity, h2.ServerIdentity})
	h1.AddRoster(el)
	tree := el.GenerateBinaryTree()
	h1.AddTree(tree)
	// start the protocol
	go func() {
		_, err := h1.StartProtocol(simpleProto, tree)
		if err != nil {
			t.Fatal(fmt.Sprintf("Could not start protocol %v", err))
		}
	}()

	// we are supposed to receive something from host1 from Start()
	select {
	case _ = <-chanH1:
		break
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Could not receive from channel of host 1")
	}
	// Then we are supposed to receive from h2 after he got the tree and the
	// entity list from h1
	select {
	case _ = <-chanH2:
		break
	case <-time.After(2 * time.Second):
		t.Fatal("Could not receive from channel of host 1")
	}
}
コード例 #11
0
ファイル: stats_test.go プロジェクト: nikirill/cothority
func TestStatsAverageFiltered(t *testing.T) {
	log.TestOutput(testing.Verbose(), 3)
	m := make(map[string]string)
	m["servers"] = "1"
	m["hosts"] = "1"
	m["bf"] = "2"
	// create the filter entry
	m["filter_round"] = "50"
	// create stats
	stat1 := NewStats(m)
	stat2 := NewStats(m)
	m1 := NewSingleMeasure("round", 10)
	m2 := NewSingleMeasure("round", 20)
	m3 := NewSingleMeasure("round", 150)
	stat1.Update(m1)
	stat1.Update(m2)
	stat1.Update(m3)
	stat2.Update(m1)
	stat2.Update(m2)
	stat2.Update(m3)

	/* stat2.Collect()*/
	//val := stat2.Value("round")
	//if val.Avg() != (10+20)/2 {
	//t.Fatal("Average with filter does not work?")
	//}

	str := new(bytes.Buffer)
	avgStat := AverageStats([]*Stats{stat1, stat2})
	avgStat.WriteHeader(str)
	avgStat.WriteValues(str)

	stat3 := NewStats(m)
	stat4 := NewStats(m)
	stat3.Update(m1)
	stat3.Update(m2)
	stat3.Update(m3)
	stat4.Update(m1)
	stat4.Update(m2)
	stat4.Update(m3)

	str2 := new(bytes.Buffer)
	avgStat2 := AverageStats([]*Stats{stat3, stat4})
	avgStat2.WriteHeader(str2)
	avgStat2.WriteValues(str2)

	if !bytes.Equal(str.Bytes(), str2.Bytes()) {
		t.Fatal("Average are not the same !")
	}

}
コード例 #12
0
ファイル: randhound_test.go プロジェクト: nikirill/cothority
func TestRandHound(t *testing.T) {

	// Setup parameters
	var name string = "RandHound"             // Protocol name
	var nodes uint32 = 10                     // Number of nodes (peers + leader)
	var trustees uint32 = 5                   // Number of trustees
	var purpose string = "RandHound test run" // Purpose
	var shards uint32 = 2                     // Number of shards created from the randomness

	local := sda.NewLocalTest()
	_, _, tree := local.GenTree(int(nodes), false, true, true)
	defer local.CloseAll()

	log.TestOutput(testing.Verbose(), 1)

	// Setup and Start RandHound
	log.Printf("RandHound - starting")
	leader, err := local.CreateProtocol(tree, name)
	if err != nil {
		t.Fatal("Couldn't initialise RandHound protocol:", err)
	}
	rh := leader.(*randhound.RandHound)
	err = rh.Setup(nodes, trustees, purpose)
	if err != nil {
		t.Fatal("Couldn't initialise RandHound protocol:", err)
	}
	log.Printf("RandHound - group config: %d %d %d %d %d %d\n", rh.Group.N, rh.Group.F, rh.Group.L, rh.Group.K, rh.Group.R, rh.Group.T)
	log.Printf("RandHound - shards: %d\n", shards)
	leader.Start()

	select {
	case <-rh.Leader.Done:
		log.Printf("RandHound - done")
		rnd, err := rh.Random()
		if err != nil {
			t.Fatal(err)
		}
		sharding, err := rh.Shard(rnd, shards)
		if err != nil {
			t.Fatal(err)
		}
		log.Printf("RandHound - random bytes: %v\n", rnd)
		log.Printf("RandHound - sharding: %v\n", sharding)
	case <-time.After(time.Second * 60):
		t.Fatal("RandHound – time out")
	}
}
コード例 #13
0
ファイル: ntree_test.go プロジェクト: nikirill/cothority
func TestNtree(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)

	for _, nbrHosts := range []int{1, 3, 13} {
		log.Lvl2("Running ntree with", nbrHosts, "hosts")
		local := sda.NewLocalTest()

		_, _, tree := local.GenBigTree(nbrHosts, nbrHosts, 3, true, true)

		done := make(chan bool)
		// create the message we want to sign for this round
		msg := []byte("Ntree rocks slowly")

		// Register the function generating the protocol instance
		var root *ntree.Protocol
		// function that will be called when protocol is finished by the root
		doneFunc := func() bool {
			done <- true
			return true
		}

		// Start the protocol
		pi, err := local.CreateProtocol(tree, "NaiveTree")
		if err != nil {
			t.Fatal("Couldn't create new node:", err)
		}
		root = pi.(*ntree.Protocol)
		root.Message = msg
		root.OnDoneCallback(doneFunc)
		err = pi.Start()
		if nbrHosts == 1 {
			if err == nil {
				t.Fatal("Shouldn't be able to start NTree with 1 node")
			}
		} else if err != nil {
			t.Fatal("Couldn't start protocol:", err)
		} else {
			select {
			case <-done:
			case <-time.After(time.Second * 2):
				t.Fatal("Protocol didn't finish in time")
			}
		}
		local.CloseAll()
	}
}
コード例 #14
0
ファイル: net_test.go プロジェクト: nikirill/cothority
func TestTcpCounterIO(t *testing.T) {
	defer log.AfterTest(t)

	RegisterMessageType(&TestRegisterS{})
	log.TestOutput(testing.Verbose(), 4)
	receiverStarted := make(chan bool)
	fn := func(s Conn) {
		err := s.Send(context.TODO(), &TestRegisterS{10})
		if err != nil {
			t.Fatal("Error while sending message:", err)
		}
		close(receiverStarted)
	}

	h1 := NewTCPHost()
	h2 := NewTCPHost()
	done := make(chan bool)
	go func() {
		err := h1.Listen("localhost:3000", fn)
		if err != nil {
			t.Fatal("Listening failed for h1:", err)
		}
		done <- true
	}()

	c2, err := h2.Open("localhost:3000")
	if err != nil {
		t.Fatal("Couldn't open h2:", err)
	}
	<-receiverStarted
	c2.Receive(context.TODO())
	err = h1.Close()
	if err != nil {
		t.Fatal("Couldn't close:", err)
	}
	err = h2.Close()
	if err != nil {
		t.Fatal("Couldn't close:", err)
	}
	<-done
	// verify the amount of bytes read / written
	if h1.Tx() == 0 || h1.Tx() != h2.Rx() || h2.Rx() == 0 || h2.Rx() != c2.Rx() {
		t.Fatal("stg is wrong with CounterIO implementation of TcpConn / TcpHost")
	}

}
コード例 #15
0
ファイル: net_test.go プロジェクト: nikirill/cothority
// Testing exchange of entity
func TestSecureTcp(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	opened := make(chan bool)
	fn := func(s SecureConn) {
		log.Lvl3("Getting connection from", s)
		opened <- true
	}

	kp1 := config.NewKeyPair(Suite)
	entity1 := NewServerIdentity(kp1.Public, "localhost:2000")
	kp2 := config.NewKeyPair(Suite)
	entity2 := NewServerIdentity(kp2.Public, "localhost:2001")

	host1 := NewSecureTCPHost(kp1.Secret, entity1)
	host2 := NewSecureTCPHost(kp1.Secret, entity2)

	done := make(chan bool)
	go func() {
		err := host1.Listen(fn)
		if err != nil {
			t.Fatal("Couldn't listen:", err)
		}
		done <- true
	}()
	conn, err := host2.Open(entity1)
	if err != nil {
		t.Fatal("Couldn't connect to host1:", err)
	}
	if !conn.ServerIdentity().Public.Equal(kp1.Public) {
		t.Fatal("Connection-id is not from host1")
	}
	if !<-opened {
		t.Fatal("Lazy programmers - no select")
	}
	log.Lvl4("Closing connections")
	if err := host1.Close(); err != nil {
		t.Fatal("Couldn't close host", host1)
	}
	if err := host2.Close(); err != nil {
		t.Fatal("Couldn't close host", host2)
	}
	<-done
}
コード例 #16
0
ファイル: monitor_test.go プロジェクト: nikirill/cothority
// setupMonitor launches a basic monitor with a created Stats object
// When finished with the monitor, just call `End()`
func setupMonitor(t *testing.T) (*Monitor, *Stats) {
	log.TestOutput(testing.Verbose(), 2)
	m := make(map[string]string)
	m["servers"] = "1"
	stat := NewStats(m)
	// First set up monitor listening
	mon := NewMonitor(stat)
	go mon.Listen()
	time.Sleep(100 * time.Millisecond)

	// Then measure
	err := ConnectSink("localhost:" + strconv.Itoa(mon.SinkPort))
	EnableMeasure(true)
	if err != nil {
		t.Fatal(fmt.Sprintf("Error starting monitor: %s", err))
	}
	return mon, stat
}
コード例 #17
0
ファイル: simulation_test.go プロジェクト: nikirill/cothority
func TestLoadSave(t *testing.T) {
	defer log.AfterTest(t)
	log.TestOutput(testing.Verbose(), 4)
	sc, _, err := createBFTree(7, 2)
	if err != nil {
		t.Fatal(err)
	}
	dir, err := ioutil.TempDir("", "example")
	log.ErrFatal(err)
	defer os.RemoveAll(dir)
	sc.Save(dir)
	sc2, err := sda.LoadSimulationConfig(dir, "local1:2000")
	if err != nil {
		t.Fatal(err)
	}
	if sc2[0].Tree.ID != sc.Tree.ID {
		t.Fatal("Tree-id is not correct")
	}
}
コード例 #18
0
ファイル: overlay_test.go プロジェクト: nikirill/cothority
func TestOverlayDone(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	// setup
	h1 := sda.NewLocalHost(2000)
	defer h1.Close()
	fn := func(n *sda.TreeNodeInstance) (sda.ProtocolInstance, error) {
		ps := ProtocolOverlay{
			TreeNodeInstance: n,
		}
		return &ps, nil
	}
	el := sda.NewRoster([]*network.ServerIdentity{h1.ServerIdentity})
	h1.AddRoster(el)
	tree := el.GenerateBinaryTree()
	h1.AddTree(tree)
	sda.ProtocolRegisterName("ProtocolOverlay", fn)
	p, err := h1.CreateProtocol("ProtocolOverlay", tree)
	if err != nil {
		t.Fatal("error starting new node", err)
	}
	po := p.(*ProtocolOverlay)
	// release the resources
	var count int
	po.OnDoneCallback(func() bool {
		count++
		if count >= 2 {
			return true
		}
		return false
	})
	po.Release()
	overlay := h1.Overlay()
	if _, ok := overlay.TokenToNode(po.Token()); !ok {
		t.Fatal("Node should exists after first call Done()")
	}
	po.Release()
	if _, ok := overlay.TokenToNode(po.Token()); ok {
		t.Fatal("Node should NOT exists after call Done()")
	}
}
コード例 #19
0
ファイル: simulation_test.go プロジェクト: nikirill/cothority
func TestMultipleInstances(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	sc, _, err := createBFTree(7, 2)
	if err != nil {
		t.Fatal(err)
	}
	dir, err := ioutil.TempDir("", "example")
	log.ErrFatal(err)
	defer os.RemoveAll(dir)
	sc.Save(dir)
	sc2, err := sda.LoadSimulationConfig(dir, "local1")
	if err != nil {
		t.Fatal(err)
	}
	if len(sc2) != 4 {
		t.Fatal("We should have 4 local1-hosts but have", len(sc2))
	}
	if sc2[0].Host.ServerIdentity.ID == sc2[1].Host.ServerIdentity.ID {
		t.Fatal("Hosts are not copies")
	}
}
コード例 #20
0
ファイル: platform_test.go プロジェクト: nikirill/cothority
func TestReadRunfile(t *testing.T) {
	log.TestOutput(testing.Verbose(), 2)
	tplat := &TPlat{}

	tmpfile := "/tmp/testrun.toml"
	err := ioutil.WriteFile(tmpfile, []byte(testfile), 0666)
	if err != nil {
		log.Fatal("Couldn't create file:", err)
	}

	tests := platform.ReadRunFile(tplat, tmpfile)
	log.Lvl2(tplat)
	log.Lvlf2("%+v\n", tests[0])
	if tplat.App != "sign" {
		log.Fatal("App should be 'sign'")
	}
	if len(tests) != 2 {
		log.Fatal("There should be 2 tests")
	}
	if tests[0].Get("machines") != "8" {
		log.Fatal("Machines = 8 has not been copied into RunConfig")
	}
}
コード例 #21
0
ファイル: measure_test.go プロジェクト: nikirill/cothority
func TestCounterIOMeasureRecord(t *testing.T) {
	log.TestOutput(testing.Verbose(), 4)
	mon, _ := setupMonitor(t)
	dm := &DummyCounterIO{0, 0}
	// create the counter measure
	cm := NewCounterIOMeasure("dummy", dm)
	if cm.baseRx != dm.rvalue || cm.baseTx != dm.wvalue {
		t.Logf("baseRx = %d vs rvalue = %d || baseTx = %d vs wvalue = %d", cm.baseRx, dm.rvalue, cm.baseTx, dm.wvalue)
		t.Fatal("Tx() / Rx() not working ?")
	}
	//bread, bwritten := cm.baseRx, cm.baseTx
	cm.Record()
	// check the values again
	if cm.baseRx != dm.rvalue || cm.baseTx != dm.wvalue {
		t.Fatal("Record() not working for CounterIOMeasure")
	}

	// Important otherwise data don't get written down to the monitor yet.
	time.Sleep(100 * time.Millisecond)
	str := new(bytes.Buffer)
	stat := mon.Stats()
	stat.Collect()
	stat.WriteHeader(str)
	stat.WriteValues(str)
	wr, re := stat.Value("dummy_tx"), stat.Value("dummy_rx")
	if wr == nil || wr.Avg() != 10 {
		t.Logf("stats => %v", stat.values)
		t.Logf("wr.Avg() = %f", wr.Avg())
		t.Fatal("Stats don't have the right value (write)")
	}
	if re == nil || re.Avg() != 10 {
		t.Fatal("Stats don't have the right value (read)")
	}
	EndAndCleanup()
	time.Sleep(100 * time.Millisecond)
}
コード例 #22
0
ファイル: jvss_test.go プロジェクト: nikirill/cothority
func TestJVSS(t *testing.T) {

	// Setup parameters
	var name string = "JVSS"      // Protocol name
	var nodes uint32 = 5          // Number of nodes
	var rounds int = 3            // Number of rounds
	msg := []byte("Hello World!") // Message to-be-signed

	local := sda.NewLocalTest()
	_, _, tree := local.GenTree(int(nodes), false, true, true)
	defer local.CloseAll()

	log.TestOutput(testing.Verbose(), 1)

	log.Lvl1("JVSS - starting")
	leader, err := local.CreateProtocol(tree, name)
	if err != nil {
		t.Fatal("Couldn't initialise protocol tree:", err)
	}
	jv := leader.(*jvss.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, _ := jv.Sign(msg)
		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")
	}

}
コード例 #23
0
ファイル: big_test.go プロジェクト: nikirill/cothority
// There seems to be an error if a lot of hosts communicate with each other
// - this function tries to trigger that error so that it can be removed
// It generates one connection between each host and then starts sending
// messages all around.
func TestHugeConnections(t *testing.T) {
	defer log.AfterTest(t)
	// How many hosts are run
	nbrHosts := 10
	// 16MB of message size
	msgSize := 1024 * 1024 * 1
	big := bigMessage{
		Msize: msgSize,
		Msg:   make([]byte, msgSize),
		Pcrc:  25,
	}
	bigMessageType := RegisterMessageType(big)

	log.TestOutput(testing.Verbose(), 3)
	privkeys := make([]abstract.Scalar, nbrHosts)
	ids := make([]*ServerIdentity, nbrHosts)
	hosts := make([]SecureHost, nbrHosts)
	// 2-dimensional array of connections between all hosts, where only
	// the upper-right half is populated. The lower-left half is the
	// mirror of the upper-right half, and the diagonal is empty, as there
	// are no connections from one host to itself.
	conns := make([][]SecureConn, nbrHosts)
	wg := sync.WaitGroup{}
	// Create all hosts and open the connections
	for i := 0; i < nbrHosts; i++ {
		privkeys[i], ids[i] = genServerIdentity("localhost:" + strconv.Itoa(2000+i))
		hosts[i] = NewSecureTCPHost(privkeys[i], ids[i])
		log.Lvl5("Host is", hosts[i], "id is", ids[i])
		go func(h int) {
			err := hosts[h].Listen(func(c SecureConn) {
				log.Lvl5(2000+h, "got a connection")
				nm, err := c.Receive(context.TODO())
				if err != nil {
					t.Fatal("Couldn't receive msg:", err)
				}
				if nm.MsgType != bigMessageType {
					t.Fatal("Received message type is wrong")
				}
				big_copy := nm.Msg.(bigMessage)
				if big_copy.Msize != msgSize {
					t.Fatal(h, "Message-size is wrong:", big_copy.Msize, big_copy, big)
				}
				if big_copy.Pcrc != 25 {
					t.Fatal("CRC is wrong")
				}
				// And send it back
				log.Lvl3(h, "sends it back")

				go func(h int) {
					log.Lvl3(h, "Sending back")
					err := c.Send(context.TODO(), &big)
					if err != nil {
						t.Fatal(h, "couldn't send message:", err)
					}
				}(h)
				log.Lvl3(h, "done sending messages")
			})
			if err != nil {
				t.Fatal(err)
			}
		}(i)
		conns[i] = make([]SecureConn, nbrHosts)
		for j := 0; j < i; j++ {
			wg.Add(1)
			var err error
			log.Lvl5("Connecting", ids[i], "with", ids[j])
			conns[i][j], err = hosts[i].Open(ids[j])
			if err != nil {
				t.Fatal("Couldn't open:", err)
			}
			// Populate also the lower left for easy sending to
			// everybody
			conns[j][i] = conns[i][j]
		}
	}

	// Start sending messages back and forth
	for i := 0; i < nbrHosts; i++ {
		for j := 0; j < i; j++ {
			c := conns[i][j]
			go func(conn SecureConn, i, j int) {
				defer wg.Done()
				log.Lvl3("Sending from", i, "to", j, ":")
				ctx := context.TODO()
				if err := conn.Send(ctx, &big); err != nil {
					t.Fatal(i, j, "Couldn't send:", err)
				}
				nm, err := conn.Receive(context.TODO())
				if err != nil {
					t.Fatal(i, j, "Couldn't receive:", err)
				}
				bc := nm.Msg.(bigMessage)
				if bc.Msize != msgSize {
					t.Fatal(i, j, "Message-size is wrong")
				}
				if bc.Pcrc != 25 {
					t.Fatal(i, j, "CRC is wrong")
				}
				log.Lvl3(i, j, "Done")
			}(c, i, j)
		}
	}
	wg.Wait()

	// Close all
	for _, h := range hosts {
		if err := h.Close(); err != nil {
			t.Fatal("Couldn't close:", err)
		}
	}
}
コード例 #24
0
ファイル: secure_test.go プロジェクト: nikirill/cothority
func TestSecureSimple(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	priv1, id1 := genServerIdentity("localhost:2000")
	priv2, id2 := genServerIdentity("localhost:2001")
	sHost1 := NewSecureTCPHost(priv1, id1)
	sHost2 := NewSecureTCPHost(priv2, id2)

	packetToSend := SimplePacket{"HelloWorld"}
	done := make(chan error)
	doneListen := make(chan bool)
	go func() {
		err := sHost1.Listen(func(c SecureConn) {
			nm, err := c.Receive(context.TODO())
			if err != nil {
				c.Close()
				done <- fmt.Errorf("Error receiving:")
			}
			if nm.MsgType != SimplePacketType {
				done <- fmt.Errorf("Wrong type received")
			}
			sp := nm.Msg.(SimplePacket)
			if sp.Name != packetToSend.Name {
				c.Close()
				done <- fmt.Errorf("Not same packet received!")
			}
			if !nm.ServerIdentity.Equal(id2) {
				c.Close()
				done <- fmt.Errorf("Not same entity")
			}
			log.Lvl3("Connection accepted")
			close(done)
		})
		if err != nil {
			t.Fatal("Listening-error:", err)
		}
		doneListen <- true
	}()
	//time.Sleep(1 * time.Second)
	// Open connection to entity
	c, err := sHost2.Open(id1)
	if err != nil {
		t.Fatal("Error during opening connection to id1")
	}

	ctx := context.TODO()
	if err := c.Send(ctx, &packetToSend); err != nil {
		c.Close()
		t.Fatal(err)
	}
	e, more := <-done
	if more && e != nil {
		t.Fatal(e)
	}
	err = sHost1.Close()
	if err != nil {
		t.Fatal("Closing sHost1:", err)
	}
	err = sHost2.Close()
	if err != nil {
		t.Fatal("Closing sHost2:", err)
	}
	if !<-doneListen {
		t.Fatal("Couldn't close")
	}
}
コード例 #25
0
ファイル: net_test.go プロジェクト: nikirill/cothority
// Test closing and opening of SecureHost on same address
func TestSecureMultiClose(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	receiverStarted := make(chan bool)
	fn := func(s SecureConn) {
		log.Lvl3("Getting connection from", s.ServerIdentity().First())
		close(receiverStarted)
	}

	kp1 := config.NewKeyPair(Suite)
	entity1 := NewServerIdentity(kp1.Public, "localhost:2000")
	//entity3 := NewServerIdentity(kp1.Public, "localhost:2000")
	kp2 := config.NewKeyPair(Suite)
	entity2 := NewServerIdentity(kp2.Public, "localhost:2001")

	h1 := NewSecureTCPHost(kp1.Secret, entity1)
	h2 := NewSecureTCPHost(kp2.Secret, entity2)
	done := make(chan bool)
	go func() {
		err := h1.Listen(fn)
		if err != nil {
			t.Fatal("Listening failed for h1:", err)
		}
		done <- true
	}()

	_, err := h2.Open(entity1)
	if err != nil {
		t.Fatal("Couldn't open h2:", err)
	}
	<-receiverStarted
	err = h1.Close()
	if err != nil {
		t.Fatal("Couldn't close:", err)
	}
	err = h2.Close()
	if err != nil {
		t.Fatal("Couldn't close:", err)
	}
	<-done

	log.Lvl3("Finished first connection, starting 2nd")
	receiverStarted2 := make(chan bool)
	fn2 := func(s SecureConn) {
		log.Lvl3("Getting connection from", s.ServerIdentity().First())
		receiverStarted2 <- true
	}
	done2 := make(chan bool)
	go func() {
		err := h1.Listen(fn2)
		if err != nil {
			t.Fatal("Couldn't re-open listener:", err)
		}
		done2 <- true
	}()
	_, err = h2.Open(h1.entity)
	if err != nil {
		t.Fatal(err)
	}

	<-receiverStarted2
	err = h1.Close()
	if err != nil {
		t.Fatal("Couldn't close h1:", err)
	}

	<-done2
}
コード例 #26
0
ファイル: net_test.go プロジェクト: nikirill/cothority
// Test closing and opening of Host on same address
func TestMultiClose(t *testing.T) {
	defer log.AfterTest(t)

	log.TestOutput(testing.Verbose(), 4)
	gotConnect := make(chan bool)
	fn := func(s Conn) {
		log.Lvl3("Getting connection from", s)
		gotConnect <- true
	}
	h1 := NewTCPHost()
	h2 := NewTCPHost()
	done := make(chan bool)
	go func() {
		err := h1.Listen("localhost:2000", fn)
		if err != nil {
			t.Fatal("Couldn't listen:", err)
		}
		done <- true
	}()
	time.Sleep(time.Second)
	log.Lvl3("Open connection to h2")
	_, err := h2.Open("localhost:2000")
	if err != nil {
		t.Fatal(h2, "couldn't Open() connection to", h1, err)
	}
	// wait for the listener, then close h1 & h2:
	<-gotConnect
	err = h1.Close()
	if err != nil {
		t.Fatal("Couldn't Close():", err)
	}
	err = h2.Close()
	if err != nil {
		t.Fatal("Couldn't Close()", err)
	}
	<-done

	h3 := NewTCPHost()
	go func() {
		err := h3.Listen("localhost:2000", fn)
		if err != nil {
			t.Fatal("Couldn't re-open listener:", err)
		}
		done <- true
	}()
	_, err = h2.Open("localhost:2000")
	if err != nil {
		t.Fatal(h2, "couldn't Open() connection to", h3, err)
	}
	// wait for the listener and close h3 & h2
	<-gotConnect
	err = h3.Close()
	if err != nil {
		t.Fatal("Couldn't close h3:", err)
	}
	err = h2.Close()
	if err != nil {
		t.Fatal("Couldn't close h2:", err)
	}
	<-done
}