github.com/braveheart12/insolar-09-08-19@v0.8.7/network/servicenetwork/servicenetwork_test.go (about)

     1  /*
     2   * The Clear BSD License
     3   *
     4   * Copyright (c) 2019 Insolar Technologies
     5   *
     6   * All rights reserved.
     7   *
     8   * Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
     9   *
    10   *  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    11   *  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    12   *  Neither the name of Insolar Technologies nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
    13   *
    14   * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    15   *
    16   */
    17  
    18  package servicenetwork
    19  
    20  import (
    21  	"testing"
    22  
    23  	"github.com/stretchr/testify/assert"
    24  )
    25  
    26  func TestNewServiceNetwork_incrementPort(t *testing.T) {
    27  	addr, err := incrementPort("0.0.0.0:8080")
    28  	assert.NoError(t, err)
    29  	assert.Equal(t, "0.0.0.0:8081", addr)
    30  
    31  	addr, err = incrementPort("[::]:8080")
    32  	assert.NoError(t, err)
    33  	assert.Equal(t, "[::]:8081", addr)
    34  
    35  	addr, err = incrementPort("0.0.0.0:0")
    36  	assert.NoError(t, err)
    37  	assert.Equal(t, "0.0.0.0:0", addr)
    38  
    39  	addr, err = incrementPort("invalid_address")
    40  	assert.Error(t, err)
    41  	assert.Equal(t, "invalid_address", addr)
    42  
    43  	addr, err = incrementPort("127.0.0.1:port")
    44  	assert.Error(t, err)
    45  	assert.Equal(t, "127.0.0.1:port", addr)
    46  }
    47  
    48  /*
    49  func newTestNodeKeeper(nodeID core.RecordRef, address string, isBootstrap bool) (network.NodeKeeper, core.Node) {
    50  	origin := nodenetwork.NewNode(nodeID, nil, nil, 0, address, "")
    51  	keeper := nodenetwork.NewNodeKeeper(origin)
    52  	if isBootstrap {
    53  		keeper.AddActiveNodes([]core.Node{origin})
    54  	}
    55  	return keeper, origin
    56  }
    57  
    58  func mockCryptographyService(t *testing.T) core.CryptographyService {
    59  	mock := testutils.NewCryptographyServiceMock(t)
    60  	mock.SignFunc = func(p []byte) (r *core.Signature, r1 error) {
    61  		signature := core.SignatureFromBytes(nil)
    62  		return &signature, nil
    63  	}
    64  	mock.VerifyFunc = func(p crypto.PublicKey, p1 core.Signature, p2 []byte) (r bool) {
    65  		return true
    66  	}
    67  	return mock
    68  }
    69  
    70  func mockParcelFactory(t *testing.T) message.ParcelFactory {
    71  	mock := mockCryptographyService(t)
    72  	delegationTokenFactory := delegationtoken.NewDelegationTokenFactory()
    73  	parcelFactory := messagebus.NewParcelFactory()
    74  	cm := &component.Manager{}
    75  	cm.Register(platformpolicy.NewPlatformCryptographyScheme())
    76  	cm.Inject(delegationTokenFactory, parcelFactory, mock)
    77  	return parcelFactory
    78  }
    79  
    80  func initComponents(t *testing.T, nodeID core.RecordRef, address string, isBootstrap bool) (core.CryptographyService, network.NodeKeeper, core.Node) {
    81  	key, _ := platformpolicy.NewKeyProcessor().GeneratePrivateKey()
    82  	require.NotNil(t, key)
    83  	cs := cryptography.NewKeyBoundCryptographyService(key)
    84  	kp := platformpolicy.NewKeyProcessor()
    85  	pk, _ := cs.GetPublicKey()
    86  	_, err := certificate.NewCertificatesWithKeys(pk, kp)
    87  
    88  	require.NoError(t, err)
    89  	keeper, origin := newTestNodeKeeper(nodeID, address, isBootstrap)
    90  
    91  	mock := mockCryptographyService(t)
    92  	return mock, keeper, origin
    93  }
    94  
    95  func TestNewServiceNetwork(t *testing.T) {
    96  	cfg := configuration.NewConfiguration()
    97  	scheme := platformpolicy.NewPlatformCryptographyScheme()
    98  
    99  	sn, err := NewServiceNetwork(cfg, scheme)
   100  	require.NoError(t, err)
   101  	require.NotNil(t, sn)
   102  }
   103  
   104  func TestServiceNetwork_GetAddress(t *testing.T) {
   105  	cfg := configuration.NewConfiguration()
   106  	scheme := platformpolicy.NewPlatformCryptographyScheme()
   107  	network, err := NewServiceNetwork(cfg, scheme)
   108  	require.NoError(t, err)
   109  	err = network.Init(context.Background())
   110  	require.NoError(t, err)
   111  	require.True(t, strings.Contains(network.GetAddress(), strings.Split(cfg.Host.Transport.Address, ":")[0]))
   112  }
   113  
   114  func TestServiceNetwork_SendMessage(t *testing.T) {
   115  	cfg := configuration.NewConfiguration()
   116  	scheme := platformpolicy.NewPlatformCryptographyScheme()
   117  	serviceNetwork, err := NewServiceNetwork(cfg, scheme)
   118  
   119  	key, _ := platformpolicy.NewKeyProcessor().GeneratePrivateKey()
   120  	require.NotNil(t, key)
   121  	cs := cryptography.NewKeyBoundCryptographyService(key)
   122  	kp := platformpolicy.NewKeyProcessor()
   123  	pk, _ := cs.GetPublicKey()
   124  	serviceNetwork.Certificate, _ = certificate.NewCertificatesWithKeys(pk, kp)
   125  	require.NoError(t, err)
   126  
   127  	ctx := context.TODO()
   128  	serviceNetwork.CryptographyService, serviceNetwork.NodeKeeper, _ = initComponents(t, testutils.RandomRef(), "", true)
   129  
   130  	err = serviceNetwork.Init(context.Background())
   131  	require.NoError(t, err)
   132  	err = serviceNetwork.Start(ctx)
   133  	require.NoError(t, err)
   134  
   135  	e := &message.CallMethod{
   136  		ObjectRef: core.NewRefFromBase58("test"),
   137  		Method:    "test",
   138  		Arguments: []byte("test"),
   139  	}
   140  
   141  	pf := mockParcelFactory(t)
   142  	parcel, err := pf.Create(ctx, e, serviceNetwork.GetNodeID(), nil)
   143  	require.NoError(t, err)
   144  
   145  	ref := testutils.RandomRef()
   146  	serviceNetwork.SendMessage(ref, "test", parcel)
   147  }
   148  
   149  func mockServiceConfiguration(host string, bootstrapHosts []string, nodeID string) configuration.Configuration {
   150  	cfg := configuration.NewConfiguration()
   151  	transport := configuration.Transport{Protocol: "TCP", Address: host, BehindNAT: false}
   152  	h := configuration.HostNetwork{
   153  		Transport:      transport,
   154  		IsRelay:        false,
   155  	}
   156  
   157  	n := configuration.NodeNetwork{Node: &configuration.Node{ID: nodeID}}
   158  	cfg.Host = h
   159  	cfg.Node = n
   160  
   161  	return cfg
   162  }
   163  
   164  func TestServiceNetwork_SendMessage2(t *testing.T) {
   165  	ctx := context.TODO()
   166  	firstNodeId := "4gU79K6woTZDvn4YUFHauNKfcHW69X42uyk8ZvRevCiMv3PLS24eM1vcA9mhKPv8b2jWj9J5RgGN9CB7PUzCtBsj"
   167  	secondNodeId := "53jNWvey7Nzyh4ZaLdJDf3SRgoD4GpWuwHgrgvVVGLbDkk3A7cwStSmBU2X7s4fm6cZtemEyJbce9dM9SwNxbsxf"
   168  	scheme := platformpolicy.NewPlatformCryptographyScheme()
   169  
   170  	firstNode, err := NewServiceNetwork(mockServiceConfiguration(
   171  		"127.0.0.1:10000",
   172  		[]string{"127.0.0.1:10001"},
   173  		firstNodeId), scheme)
   174  	require.NoError(t, err)
   175  	secondNode, err := NewServiceNetwork(mockServiceConfiguration(
   176  		"127.0.0.1:10001",
   177  		nil,
   178  		secondNodeId), scheme)
   179  	require.NoError(t, err)
   180  
   181  	var fNode, sNode core.Node
   182  	secondNode.CryptographyService, secondNode.NodeKeeper, fNode = initComponents(t, core.NewRefFromBase58(secondNodeId), "127.0.0.1:10001", true)
   183  	err = secondNode.Init(context.Background())
   184  	require.NoError(t, err)
   185  	err = secondNode.Start(ctx)
   186  	require.NoError(t, err)
   187  	firstNode.CryptographyService, firstNode.NodeKeeper, sNode = initComponents(t, core.NewRefFromBase58(firstNodeId), "127.0.0.1:10000", false)
   188  	firstNode.NodeKeeper.AddActiveNodes([]core.Node{fNode, sNode})
   189  	secondNode.NodeKeeper.AddActiveNodes([]core.Node{fNode, sNode})
   190  
   191  	err = firstNode.Init(context.Background())
   192  	require.NoError(t, err)
   193  	err = firstNode.Start(ctx)
   194  	require.NoError(t, err)
   195  
   196  	defer func() {
   197  		firstNode.Stop(ctx)
   198  		secondNode.Stop(ctx)
   199  	}()
   200  
   201  	var wg sync.WaitGroup
   202  	wg.Add(1)
   203  
   204  	secondNode.RemoteProcedureRegister("test", func(args [][]byte) ([]byte, error) {
   205  		wg.Done()
   206  		return nil, nil
   207  	})
   208  
   209  	e := &message.CallMethod{
   210  		ObjectRef: core.NewRefFromBase58("test"),
   211  		Method:    "test",
   212  		Arguments: []byte("test"),
   213  	}
   214  
   215  	pf := mockParcelFactory(t)
   216  	parcel, err := pf.Create(ctx, e, firstNode.GetNodeID(), nil)
   217  	require.NoError(t, err)
   218  
   219  	firstNode.SendMessage(core.NewRefFromBase58(secondNodeId), "test", parcel)
   220  	success := utils.WaitTimeout(&wg, 100*time.Millisecond)
   221  
   222  	require.True(t, success)
   223  }
   224  
   225  func TestServiceNetwork_SendCascadeMessage(t *testing.T) {
   226  	ctx := context.TODO()
   227  	firstNodeId := "4gU79K6woTZDvn4YUFHauNKfcHW69X42uyk8ZvRevCiMv3PLS24eM1vcA9mhKPv8b2jWj9J5RgGN9CB7PUzCtBsj"
   228  	secondNodeId := "53jNWvey7Nzyh4ZaLdJDf3SRgoD4GpWuwHgrgvVVGLbDkk3A7cwStSmBU2X7s4fm6cZtemEyJbce9dM9SwNxbsxf"
   229  	scheme := platformpolicy.NewPlatformCryptographyScheme()
   230  
   231  	firstNode, err := NewServiceNetwork(mockServiceConfiguration(
   232  		"127.0.0.1:10100",
   233  		[]string{"127.0.0.1:10101"},
   234  		firstNodeId), scheme)
   235  	require.NoError(t, err)
   236  	secondNode, err := NewServiceNetwork(mockServiceConfiguration(
   237  		"127.0.0.1:10101",
   238  		nil,
   239  		secondNodeId), scheme)
   240  	require.NoError(t, err)
   241  
   242  	var fNode, sNode core.Node
   243  	secondNode.CryptographyService, secondNode.NodeKeeper, fNode = initComponents(t, core.NewRefFromBase58(secondNodeId), "127.0.0.1:10101", true)
   244  	err = secondNode.Init(context.Background())
   245  	require.NoError(t, err)
   246  	err = secondNode.Start(ctx)
   247  	require.NoError(t, err)
   248  	firstNode.CryptographyService, firstNode.NodeKeeper, sNode = initComponents(t, core.NewRefFromBase58(firstNodeId), "127.0.0.1:10100", false)
   249  	firstNode.NodeKeeper.AddActiveNodes([]core.Node{fNode, sNode})
   250  	secondNode.NodeKeeper.AddActiveNodes([]core.Node{fNode, sNode})
   251  	err = firstNode.Init(context.Background())
   252  	require.NoError(t, err)
   253  	err = firstNode.Start(ctx)
   254  	require.NoError(t, err)
   255  
   256  	defer func() {
   257  		firstNode.Stop(ctx)
   258  		secondNode.Stop(ctx)
   259  	}()
   260  
   261  	var wg sync.WaitGroup
   262  	wg.Add(1)
   263  
   264  	secondNode.RemoteProcedureRegister("test", func(args [][]byte) ([]byte, error) {
   265  		wg.Done()
   266  		return nil, nil
   267  	})
   268  
   269  	e := &message.CallMethod{
   270  		ObjectRef: core.NewRefFromBase58("test"),
   271  		Method:    "test",
   272  		Arguments: []byte("test"),
   273  	}
   274  
   275  	c := core.Cascade{
   276  		NodeIds:           []core.RecordRef{core.NewRefFromBase58(secondNodeId)},
   277  		ReplicationFactor: 2,
   278  		Entropy:           core.Entropy{0},
   279  	}
   280  
   281  	pf := mockParcelFactory(t)
   282  	parcel, err := pf.Create(ctx, e, firstNode.GetNodeID(), nil)
   283  	require.NoError(t, err)
   284  
   285  	err = firstNode.SendCascadeMessage(c, "test", parcel)
   286  	success := utils.WaitTimeout(&wg, 100*time.Millisecond)
   287  
   288  	require.NoError(t, err)
   289  	require.True(t, success)
   290  
   291  	err = firstNode.SendCascadeMessage(c, "test", nil)
   292  	require.Error(t, err)
   293  	c.ReplicationFactor = 0
   294  	err = firstNode.SendCascadeMessage(c, "test", parcel)
   295  	require.Error(t, err)
   296  	c.ReplicationFactor = 2
   297  	c.NodeIds = nil
   298  	err = firstNode.SendCascadeMessage(c, "test", parcel)
   299  	require.Error(t, err)
   300  }
   301  
   302  func TestServiceNetwork_SendCascadeMessage2(t *testing.T) {
   303  	ctx := context.TODO()
   304  	t.Skip("fix data race INS-534")
   305  	nodeIds := []core.RecordRef{
   306  		core.NewRefFromBase58("4gU79K6woTZDvn4YUFHauNKfcHW69X42uyk8ZvRevCiMv3PLS24eM1vcA9mhKPv8b2jWj9J5RgGN9CB7PUzCtBsj"),
   307  		core.NewRefFromBase58("53jNWvey7Nzyh4ZaLdJDf3SRgoD4GpWuwHgrgvVVGLbDkk3A7cwStSmBU2X7s4fm6cZtemEyJbce9dM9SwNxbsxf"),
   308  		core.NewRefFromBase58("9uE5MEWQB2yfKY8kTgTNovWii88D4anmf7GAiovgcxx6Uc6EBmZ212mpyMa1L22u9TcUUd94i8LvULdsdBoG8ed"),
   309  		core.NewRefFromBase58("4qXdYkfL9U4tL3qRPthdbdajtafR4KArcXjpyQSEgEMtpuin3t8aZYmMzKGRnXHBauytaPQ6bfwZyKZzRPpR6gyX"),
   310  		core.NewRefFromBase58("5q5rnvayXyKszoWofxp4YyK7FnLDwhsqAXKxj6H7B5sdEsNn4HKNFoByph4Aj8rGptdWL54ucwMQrySMJgKavxX1"),
   311  		core.NewRefFromBase58("5tsFDwNLMW4GRHxSbBjjxvKpR99G4CSBLRqZAcpqdSk5SaeVcDL3hCiyjjidCRJ7Lu4VZoANWQJN2AgPvSRgCghn"),
   312  		core.NewRefFromBase58("48UWM6w7YKYCHoP7GHhogLvbravvJ6bs4FGETqXfgdhF9aPxiuwDWwHipeiuNBQvx7zyCN9wFxbuRrDYRoAiw5Fj"),
   313  		core.NewRefFromBase58("5owQeqWyHcobFaJqS2BZU2o2ZRQ33GojXkQK6f8vNLgvNx6xeWRwenJMc53eEsS7MCxrpXvAhtpTaNMPr3rjMHA"),
   314  		core.NewRefFromBase58("xF12WfbkcWrjrPXvauSYpEGhkZT2Zha53xpYh5KQdmGHMywJNNgnemfDN2JfPV45aNQobkdma4dsx1N7Xf5wCJ9"),
   315  		core.NewRefFromBase58("4VgDz9o23wmYXN9mEiLnnsGqCEEARGByx1oys2MXtC6M94K85ZpB9sEJwiGDER61gHkBxkwfJqtg9mAFR7PQcssq"),
   316  		core.NewRefFromBase58("48g7C8QnH2CGMa62sNaL1gVVyygkto8EbMRHv168psCBuFR2FXkpTfwk4ZwpY8awFFXKSnWspYWWQ7sMMk5W7s3T"),
   317  		core.NewRefFromBase58("Lvssptdwq7tatd567LUfx2AgsrWZfo4u9q6FJgJ9BgZK8cVooZv2A7F7rrs1FS5VpnTmXhr6XihXuKWVZ8i5YX9"),
   318  	}
   319  
   320  	prefix := "127.0.0.1:"
   321  	port := 10000
   322  	bootstrapNodes := nodeIds[len(nodeIds)-2:]
   323  	bootstrapHosts := make([]string, 0)
   324  	var wg sync.WaitGroup
   325  	wg.Add(len(nodeIds) - 1)
   326  	services := make([]*ServiceNetwork, 0)
   327  
   328  	defer func() {
   329  		for _, service := range services {
   330  			service.Stop(ctx)
   331  		}
   332  	}()
   333  
   334  	scheme := platformpolicy.NewPlatformCryptographyScheme()
   335  	// init node and register test function
   336  	initService := func(node string, bHosts []string) (service *ServiceNetwork, host string) {
   337  		host = prefix + strconv.Itoa(port)
   338  		service, _ = NewServiceNetwork(mockServiceConfiguration(host, bHosts, node), scheme)
   339  		service.Start(ctx)
   340  		service.RemoteProcedureRegister("test", func(args [][]byte) ([]byte, error) {
   341  			wg.Done()
   342  			return nil, nil
   343  		})
   344  		port++
   345  		services = append(services, service)
   346  		return
   347  	}
   348  
   349  	for _, node := range bootstrapNodes {
   350  		_, host := initService(node.String(), nil)
   351  		bootstrapHosts = append(bootstrapHosts, host)
   352  	}
   353  	nodes := nodeIds[:len(nodeIds)-2]
   354  	// first node that will send cascade message to all other nodes
   355  	var firstService *ServiceNetwork
   356  	for i, node := range nodes {
   357  		service, _ := initService(node.String(), bootstrapHosts)
   358  		if i == 0 {
   359  			firstService = service
   360  		}
   361  	}
   362  
   363  	e := &message.CallMethod{
   364  		ObjectRef: core.NewRefFromBase58("test"),
   365  		Method:    "test",
   366  		Arguments: []byte("test"),
   367  	}
   368  	// send cascade message to all nodes except the first
   369  	c := core.Cascade{
   370  		NodeIds:           nodeIds[1:],
   371  		ReplicationFactor: 2,
   372  		Entropy:           core.Entropy{0},
   373  	}
   374  
   375  	pf := mockParcelFactory(t)
   376  	parcel, err := pf.Create(ctx, e, firstService.GetNodeID(), nil)
   377  	require.NoError(t, err)
   378  
   379  	firstService.SendCascadeMessage(c, "test", parcel)
   380  	success := utils.WaitTimeout(&wg, 100*time.Millisecond)
   381  
   382  	require.True(t, success)
   383  }
   384  */