github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/go-ethereum-master/cmd/swarm/config_test.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"io/ioutil"
    23  	"os"
    24  	"os/exec"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/rpc"
    29  	"github.com/ethereum/go-ethereum/swarm"
    30  	"github.com/ethereum/go-ethereum/swarm/api"
    31  
    32  	"github.com/docker/docker/pkg/reexec"
    33  )
    34  
    35  func TestDumpConfig(t *testing.T) {
    36  	swarm := runSwarm(t, "dumpconfig")
    37  	defaultConf := api.NewConfig()
    38  	out, err := tomlSettings.Marshal(&defaultConf)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  	swarm.Expect(string(out))
    43  	swarm.ExpectExit()
    44  }
    45  
    46  func TestConfigFailsSwapEnabledNoSwapApi(t *testing.T) {
    47  	flags := []string{
    48  		fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "42",
    49  		fmt.Sprintf("--%s", SwarmPortFlag.Name), "54545",
    50  		fmt.Sprintf("--%s", SwarmSwapEnabledFlag.Name),
    51  	}
    52  
    53  	swarm := runSwarm(t, flags...)
    54  	swarm.Expect("Fatal: " + SWARM_ERR_SWAP_SET_NO_API + "\n")
    55  	swarm.ExpectExit()
    56  }
    57  
    58  func TestConfigFailsNoBzzAccount(t *testing.T) {
    59  	flags := []string{
    60  		fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "42",
    61  		fmt.Sprintf("--%s", SwarmPortFlag.Name), "54545",
    62  	}
    63  
    64  	swarm := runSwarm(t, flags...)
    65  	swarm.Expect("Fatal: " + SWARM_ERR_NO_BZZACCOUNT + "\n")
    66  	swarm.ExpectExit()
    67  }
    68  
    69  func TestConfigCmdLineOverrides(t *testing.T) {
    70  	dir, err := ioutil.TempDir("", "bzztest")
    71  	if err != nil {
    72  		t.Fatal(err)
    73  	}
    74  	defer os.RemoveAll(dir)
    75  
    76  	conf, account := getTestAccount(t, dir)
    77  	node := &testNode{Dir: dir}
    78  
    79  	// assign ports
    80  	httpPort, err := assignTCPPort()
    81  	if err != nil {
    82  		t.Fatal(err)
    83  	}
    84  
    85  	flags := []string{
    86  		fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "42",
    87  		fmt.Sprintf("--%s", SwarmPortFlag.Name), httpPort,
    88  		fmt.Sprintf("--%s", SwarmSyncDisabledFlag.Name),
    89  		fmt.Sprintf("--%s", CorsStringFlag.Name), "*",
    90  		fmt.Sprintf("--%s", SwarmAccountFlag.Name), account.Address.String(),
    91  		fmt.Sprintf("--%s", SwarmDeliverySkipCheckFlag.Name),
    92  		fmt.Sprintf("--%s", EnsAPIFlag.Name), "",
    93  		"--datadir", dir,
    94  		"--ipcpath", conf.IPCPath,
    95  	}
    96  	node.Cmd = runSwarm(t, flags...)
    97  	node.Cmd.InputLine(testPassphrase)
    98  	defer func() {
    99  		if t.Failed() {
   100  			node.Shutdown()
   101  		}
   102  	}()
   103  	// wait for the node to start
   104  	for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
   105  		node.Client, err = rpc.Dial(conf.IPCEndpoint())
   106  		if err == nil {
   107  			break
   108  		}
   109  	}
   110  	if node.Client == nil {
   111  		t.Fatal(err)
   112  	}
   113  
   114  	// load info
   115  	var info swarm.Info
   116  	if err := node.Client.Call(&info, "bzz_info"); err != nil {
   117  		t.Fatal(err)
   118  	}
   119  
   120  	if info.Port != httpPort {
   121  		t.Fatalf("Expected port to be %s, got %s", httpPort, info.Port)
   122  	}
   123  
   124  	if info.NetworkID != 42 {
   125  		t.Fatalf("Expected network ID to be %d, got %d", 42, info.NetworkID)
   126  	}
   127  
   128  	if info.SyncEnabled {
   129  		t.Fatal("Expected Sync to be disabled, but is true")
   130  	}
   131  
   132  	if !info.DeliverySkipCheck {
   133  		t.Fatal("Expected DeliverySkipCheck to be enabled, but it is not")
   134  	}
   135  
   136  	if info.Cors != "*" {
   137  		t.Fatalf("Expected Cors flag to be set to %s, got %s", "*", info.Cors)
   138  	}
   139  
   140  	node.Shutdown()
   141  }
   142  
   143  func TestConfigFileOverrides(t *testing.T) {
   144  
   145  	// assign ports
   146  	httpPort, err := assignTCPPort()
   147  	if err != nil {
   148  		t.Fatal(err)
   149  	}
   150  
   151  	//create a config file
   152  	//first, create a default conf
   153  	defaultConf := api.NewConfig()
   154  	//change some values in order to test if they have been loaded
   155  	defaultConf.SyncEnabled = false
   156  	defaultConf.DeliverySkipCheck = true
   157  	defaultConf.NetworkID = 54
   158  	defaultConf.Port = httpPort
   159  	defaultConf.DbCapacity = 9000000
   160  	defaultConf.HiveParams.KeepAliveInterval = 6000000000
   161  	defaultConf.Swap.Params.Strategy.AutoCashInterval = 600 * time.Second
   162  	//defaultConf.SyncParams.KeyBufferSize = 512
   163  	//create a TOML string
   164  	out, err := tomlSettings.Marshal(&defaultConf)
   165  	if err != nil {
   166  		t.Fatalf("Error creating TOML file in TestFileOverride: %v", err)
   167  	}
   168  	//create file
   169  	f, err := ioutil.TempFile("", "testconfig.toml")
   170  	if err != nil {
   171  		t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
   172  	}
   173  	//write file
   174  	_, err = f.WriteString(string(out))
   175  	if err != nil {
   176  		t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
   177  	}
   178  	f.Sync()
   179  
   180  	dir, err := ioutil.TempDir("", "bzztest")
   181  	if err != nil {
   182  		t.Fatal(err)
   183  	}
   184  	defer os.RemoveAll(dir)
   185  	conf, account := getTestAccount(t, dir)
   186  	node := &testNode{Dir: dir}
   187  
   188  	flags := []string{
   189  		fmt.Sprintf("--%s", SwarmTomlConfigPathFlag.Name), f.Name(),
   190  		fmt.Sprintf("--%s", SwarmAccountFlag.Name), account.Address.String(),
   191  		"--ens-api", "",
   192  		"--ipcpath", conf.IPCPath,
   193  		"--datadir", dir,
   194  	}
   195  	node.Cmd = runSwarm(t, flags...)
   196  	node.Cmd.InputLine(testPassphrase)
   197  	defer func() {
   198  		if t.Failed() {
   199  			node.Shutdown()
   200  		}
   201  	}()
   202  	// wait for the node to start
   203  	for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
   204  		node.Client, err = rpc.Dial(conf.IPCEndpoint())
   205  		if err == nil {
   206  			break
   207  		}
   208  	}
   209  	if node.Client == nil {
   210  		t.Fatal(err)
   211  	}
   212  
   213  	// load info
   214  	var info swarm.Info
   215  	if err := node.Client.Call(&info, "bzz_info"); err != nil {
   216  		t.Fatal(err)
   217  	}
   218  
   219  	if info.Port != httpPort {
   220  		t.Fatalf("Expected port to be %s, got %s", httpPort, info.Port)
   221  	}
   222  
   223  	if info.NetworkID != 54 {
   224  		t.Fatalf("Expected network ID to be %d, got %d", 54, info.NetworkID)
   225  	}
   226  
   227  	if info.SyncEnabled {
   228  		t.Fatal("Expected Sync to be disabled, but is true")
   229  	}
   230  
   231  	if !info.DeliverySkipCheck {
   232  		t.Fatal("Expected DeliverySkipCheck to be enabled, but it is not")
   233  	}
   234  
   235  	if info.DbCapacity != 9000000 {
   236  		t.Fatalf("Expected network ID to be %d, got %d", 54, info.NetworkID)
   237  	}
   238  
   239  	if info.HiveParams.KeepAliveInterval != 6000000000 {
   240  		t.Fatalf("Expected HiveParams KeepAliveInterval to be %d, got %d", uint64(6000000000), uint64(info.HiveParams.KeepAliveInterval))
   241  	}
   242  
   243  	if info.Swap.Params.Strategy.AutoCashInterval != 600*time.Second {
   244  		t.Fatalf("Expected SwapParams AutoCashInterval to be %ds, got %d", 600, info.Swap.Params.Strategy.AutoCashInterval)
   245  	}
   246  
   247  	//	if info.SyncParams.KeyBufferSize != 512 {
   248  	//		t.Fatalf("Expected info.SyncParams.KeyBufferSize to be %d, got %d", 512, info.SyncParams.KeyBufferSize)
   249  	//	}
   250  
   251  	node.Shutdown()
   252  }
   253  
   254  func TestConfigEnvVars(t *testing.T) {
   255  	// assign ports
   256  	httpPort, err := assignTCPPort()
   257  	if err != nil {
   258  		t.Fatal(err)
   259  	}
   260  
   261  	envVars := os.Environ()
   262  	envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmPortFlag.EnvVar, httpPort))
   263  	envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmNetworkIdFlag.EnvVar, "999"))
   264  	envVars = append(envVars, fmt.Sprintf("%s=%s", CorsStringFlag.EnvVar, "*"))
   265  	envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmSyncDisabledFlag.EnvVar, "true"))
   266  	envVars = append(envVars, fmt.Sprintf("%s=%s", SwarmDeliverySkipCheckFlag.EnvVar, "true"))
   267  
   268  	dir, err := ioutil.TempDir("", "bzztest")
   269  	if err != nil {
   270  		t.Fatal(err)
   271  	}
   272  	defer os.RemoveAll(dir)
   273  	conf, account := getTestAccount(t, dir)
   274  	node := &testNode{Dir: dir}
   275  	flags := []string{
   276  		fmt.Sprintf("--%s", SwarmAccountFlag.Name), account.Address.String(),
   277  		"--ens-api", "",
   278  		"--datadir", dir,
   279  		"--ipcpath", conf.IPCPath,
   280  	}
   281  
   282  	//node.Cmd = runSwarm(t,flags...)
   283  	//node.Cmd.cmd.Env = envVars
   284  	//the above assignment does not work, so we need a custom Cmd here in order to pass envVars:
   285  	cmd := &exec.Cmd{
   286  		Path:   reexec.Self(),
   287  		Args:   append([]string{"swarm-test"}, flags...),
   288  		Stderr: os.Stderr,
   289  		Stdout: os.Stdout,
   290  	}
   291  	cmd.Env = envVars
   292  	//stdout, err := cmd.StdoutPipe()
   293  	//if err != nil {
   294  	//	t.Fatal(err)
   295  	//}
   296  	//stdout = bufio.NewReader(stdout)
   297  	var stdin io.WriteCloser
   298  	if stdin, err = cmd.StdinPipe(); err != nil {
   299  		t.Fatal(err)
   300  	}
   301  	if err := cmd.Start(); err != nil {
   302  		t.Fatal(err)
   303  	}
   304  
   305  	//cmd.InputLine(testPassphrase)
   306  	io.WriteString(stdin, testPassphrase+"\n")
   307  	defer func() {
   308  		if t.Failed() {
   309  			node.Shutdown()
   310  			cmd.Process.Kill()
   311  		}
   312  	}()
   313  	// wait for the node to start
   314  	for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
   315  		node.Client, err = rpc.Dial(conf.IPCEndpoint())
   316  		if err == nil {
   317  			break
   318  		}
   319  	}
   320  
   321  	if node.Client == nil {
   322  		t.Fatal(err)
   323  	}
   324  
   325  	// load info
   326  	var info swarm.Info
   327  	if err := node.Client.Call(&info, "bzz_info"); err != nil {
   328  		t.Fatal(err)
   329  	}
   330  
   331  	if info.Port != httpPort {
   332  		t.Fatalf("Expected port to be %s, got %s", httpPort, info.Port)
   333  	}
   334  
   335  	if info.NetworkID != 999 {
   336  		t.Fatalf("Expected network ID to be %d, got %d", 999, info.NetworkID)
   337  	}
   338  
   339  	if info.Cors != "*" {
   340  		t.Fatalf("Expected Cors flag to be set to %s, got %s", "*", info.Cors)
   341  	}
   342  
   343  	if info.SyncEnabled {
   344  		t.Fatal("Expected Sync to be disabled, but is true")
   345  	}
   346  
   347  	if !info.DeliverySkipCheck {
   348  		t.Fatal("Expected DeliverySkipCheck to be enabled, but it is not")
   349  	}
   350  
   351  	node.Shutdown()
   352  	cmd.Process.Kill()
   353  }
   354  
   355  func TestConfigCmdLineOverridesFile(t *testing.T) {
   356  
   357  	// assign ports
   358  	httpPort, err := assignTCPPort()
   359  	if err != nil {
   360  		t.Fatal(err)
   361  	}
   362  
   363  	//create a config file
   364  	//first, create a default conf
   365  	defaultConf := api.NewConfig()
   366  	//change some values in order to test if they have been loaded
   367  	defaultConf.SyncEnabled = true
   368  	defaultConf.NetworkID = 54
   369  	defaultConf.Port = "8588"
   370  	defaultConf.DbCapacity = 9000000
   371  	defaultConf.HiveParams.KeepAliveInterval = 6000000000
   372  	defaultConf.Swap.Params.Strategy.AutoCashInterval = 600 * time.Second
   373  	//defaultConf.SyncParams.KeyBufferSize = 512
   374  	//create a TOML file
   375  	out, err := tomlSettings.Marshal(&defaultConf)
   376  	if err != nil {
   377  		t.Fatalf("Error creating TOML file in TestFileOverride: %v", err)
   378  	}
   379  	//write file
   380  	fname := "testconfig.toml"
   381  	f, err := ioutil.TempFile("", fname)
   382  	if err != nil {
   383  		t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
   384  	}
   385  	defer os.Remove(fname)
   386  	//write file
   387  	_, err = f.WriteString(string(out))
   388  	if err != nil {
   389  		t.Fatalf("Error writing TOML file in TestFileOverride: %v", err)
   390  	}
   391  	f.Sync()
   392  
   393  	dir, err := ioutil.TempDir("", "bzztest")
   394  	if err != nil {
   395  		t.Fatal(err)
   396  	}
   397  	defer os.RemoveAll(dir)
   398  	conf, account := getTestAccount(t, dir)
   399  	node := &testNode{Dir: dir}
   400  
   401  	expectNetworkId := uint64(77)
   402  
   403  	flags := []string{
   404  		fmt.Sprintf("--%s", SwarmNetworkIdFlag.Name), "77",
   405  		fmt.Sprintf("--%s", SwarmPortFlag.Name), httpPort,
   406  		fmt.Sprintf("--%s", SwarmSyncDisabledFlag.Name),
   407  		fmt.Sprintf("--%s", SwarmTomlConfigPathFlag.Name), f.Name(),
   408  		fmt.Sprintf("--%s", SwarmAccountFlag.Name), account.Address.String(),
   409  		"--ens-api", "",
   410  		"--datadir", dir,
   411  		"--ipcpath", conf.IPCPath,
   412  	}
   413  	node.Cmd = runSwarm(t, flags...)
   414  	node.Cmd.InputLine(testPassphrase)
   415  	defer func() {
   416  		if t.Failed() {
   417  			node.Shutdown()
   418  		}
   419  	}()
   420  	// wait for the node to start
   421  	for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
   422  		node.Client, err = rpc.Dial(conf.IPCEndpoint())
   423  		if err == nil {
   424  			break
   425  		}
   426  	}
   427  	if node.Client == nil {
   428  		t.Fatal(err)
   429  	}
   430  
   431  	// load info
   432  	var info swarm.Info
   433  	if err := node.Client.Call(&info, "bzz_info"); err != nil {
   434  		t.Fatal(err)
   435  	}
   436  
   437  	if info.Port != httpPort {
   438  		t.Fatalf("Expected port to be %s, got %s", httpPort, info.Port)
   439  	}
   440  
   441  	if info.NetworkID != expectNetworkId {
   442  		t.Fatalf("Expected network ID to be %d, got %d", expectNetworkId, info.NetworkID)
   443  	}
   444  
   445  	if info.SyncEnabled {
   446  		t.Fatal("Expected Sync to be disabled, but is true")
   447  	}
   448  
   449  	if info.LocalStoreParams.DbCapacity != 9000000 {
   450  		t.Fatalf("Expected Capacity to be %d, got %d", 9000000, info.LocalStoreParams.DbCapacity)
   451  	}
   452  
   453  	if info.HiveParams.KeepAliveInterval != 6000000000 {
   454  		t.Fatalf("Expected HiveParams KeepAliveInterval to be %d, got %d", uint64(6000000000), uint64(info.HiveParams.KeepAliveInterval))
   455  	}
   456  
   457  	if info.Swap.Params.Strategy.AutoCashInterval != 600*time.Second {
   458  		t.Fatalf("Expected SwapParams AutoCashInterval to be %ds, got %d", 600, info.Swap.Params.Strategy.AutoCashInterval)
   459  	}
   460  
   461  	//	if info.SyncParams.KeyBufferSize != 512 {
   462  	//		t.Fatalf("Expected info.SyncParams.KeyBufferSize to be %d, got %d", 512, info.SyncParams.KeyBufferSize)
   463  	//	}
   464  
   465  	node.Shutdown()
   466  }
   467  
   468  func TestValidateConfig(t *testing.T) {
   469  	for _, c := range []struct {
   470  		cfg *api.Config
   471  		err string
   472  	}{
   473  		{
   474  			cfg: &api.Config{EnsAPIs: []string{
   475  				"/data/testnet/geth.ipc",
   476  			}},
   477  		},
   478  		{
   479  			cfg: &api.Config{EnsAPIs: []string{
   480  				"http://127.0.0.1:1234",
   481  			}},
   482  		},
   483  		{
   484  			cfg: &api.Config{EnsAPIs: []string{
   485  				"ws://127.0.0.1:1234",
   486  			}},
   487  		},
   488  		{
   489  			cfg: &api.Config{EnsAPIs: []string{
   490  				"test:/data/testnet/geth.ipc",
   491  			}},
   492  		},
   493  		{
   494  			cfg: &api.Config{EnsAPIs: []string{
   495  				"test:ws://127.0.0.1:1234",
   496  			}},
   497  		},
   498  		{
   499  			cfg: &api.Config{EnsAPIs: []string{
   500  				"314159265dD8dbb310642f98f50C066173C1259b@/data/testnet/geth.ipc",
   501  			}},
   502  		},
   503  		{
   504  			cfg: &api.Config{EnsAPIs: []string{
   505  				"314159265dD8dbb310642f98f50C066173C1259b@http://127.0.0.1:1234",
   506  			}},
   507  		},
   508  		{
   509  			cfg: &api.Config{EnsAPIs: []string{
   510  				"314159265dD8dbb310642f98f50C066173C1259b@ws://127.0.0.1:1234",
   511  			}},
   512  		},
   513  		{
   514  			cfg: &api.Config{EnsAPIs: []string{
   515  				"test:314159265dD8dbb310642f98f50C066173C1259b@/data/testnet/geth.ipc",
   516  			}},
   517  		},
   518  		{
   519  			cfg: &api.Config{EnsAPIs: []string{
   520  				"eth:314159265dD8dbb310642f98f50C066173C1259b@http://127.0.0.1:1234",
   521  			}},
   522  		},
   523  		{
   524  			cfg: &api.Config{EnsAPIs: []string{
   525  				"eth:314159265dD8dbb310642f98f50C066173C1259b@ws://127.0.0.1:12344",
   526  			}},
   527  		},
   528  		{
   529  			cfg: &api.Config{EnsAPIs: []string{
   530  				"eth:",
   531  			}},
   532  			err: "invalid format [tld:][contract-addr@]url for ENS API endpoint configuration \"eth:\": missing url",
   533  		},
   534  		{
   535  			cfg: &api.Config{EnsAPIs: []string{
   536  				"314159265dD8dbb310642f98f50C066173C1259b@",
   537  			}},
   538  			err: "invalid format [tld:][contract-addr@]url for ENS API endpoint configuration \"314159265dD8dbb310642f98f50C066173C1259b@\": missing url",
   539  		},
   540  		{
   541  			cfg: &api.Config{EnsAPIs: []string{
   542  				":314159265dD8dbb310642f98f50C066173C1259",
   543  			}},
   544  			err: "invalid format [tld:][contract-addr@]url for ENS API endpoint configuration \":314159265dD8dbb310642f98f50C066173C1259\": missing tld",
   545  		},
   546  		{
   547  			cfg: &api.Config{EnsAPIs: []string{
   548  				"@/data/testnet/geth.ipc",
   549  			}},
   550  			err: "invalid format [tld:][contract-addr@]url for ENS API endpoint configuration \"@/data/testnet/geth.ipc\": missing contract address",
   551  		},
   552  	} {
   553  		err := validateConfig(c.cfg)
   554  		if c.err != "" && err.Error() != c.err {
   555  			t.Errorf("expected error %q, got %q", c.err, err)
   556  		}
   557  		if c.err == "" && err != nil {
   558  			t.Errorf("unexpected error %q", err)
   559  		}
   560  	}
   561  }