github.com/aergoio/aergo@v1.3.1/p2p/p2putil/libp2putil_test.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package p2putil
     7  
     8  import (
     9  	"net"
    10  	"os"
    11  	"path/filepath"
    12  	"reflect"
    13  	"testing"
    14  
    15  	"github.com/aergoio/aergo/internal/network"
    16  	"github.com/aergoio/aergo/p2p/p2pcommon"
    17  	"github.com/aergoio/aergo/types"
    18  	"github.com/multiformats/go-multiaddr"
    19  	"github.com/stretchr/testify/assert"
    20  )
    21  
    22  func TestFromMultiAddr(t *testing.T) {
    23  	tests := []struct {
    24  		name     string
    25  		str      string
    26  		wantIp   net.IP // verify one of them
    27  		wantPort int
    28  		wantErr  bool
    29  	}{
    30  		{"TIP4peerAddr", "/ip4/192.168.0.58/tcp/11002/p2p/16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58"), 11002, false},
    31  		{"TIP4MissingID", "/ip4/192.168.0.58/tcp/11002", net.ParseIP("192.168.0.58"), -1, true},
    32  		{"TIP4MissingPort", "/ip4/192.168.0.58/p2p/16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58"), 11002, true},
    33  		{"TIP6peerAddr", "/ip6/FE80::0202:B3FF:FE1E:8329/tcp/11003/p2p/16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("FE80::0202:B3FF:FE1E:8329"), 11003, false},
    34  	}
    35  	for _, tt := range tests {
    36  		t.Run(tt.name, func(t *testing.T) {
    37  			ma, _ := types.ParseMultiaddrWithResolve(tt.str)
    38  			got, err := FromMultiAddr(ma)
    39  			if (err != nil) != tt.wantErr {
    40  				t.Errorf("FromMultiAddr() error = %v, wantErr %v", err, tt.wantErr)
    41  				return
    42  			}
    43  			if !tt.wantErr {
    44  				ip := net.ParseIP(got.IPAddress)
    45  				if !reflect.DeepEqual(ip, tt.wantIp) {
    46  					t.Errorf("FromMultiAddr() = %v, want %v", ip.String(), tt.wantIp)
    47  				}
    48  				if !reflect.DeepEqual(got.Port, uint32(tt.wantPort)) {
    49  					t.Errorf("FromMultiAddr() = %v, want %v", got.Port, tt.wantPort)
    50  				}
    51  			}
    52  
    53  			got2, err := FromMultiAddrString(tt.str)
    54  			if !reflect.DeepEqual(got2, got) {
    55  				t.Errorf("result of FromMultiAddr and FromMultiAddrString differ %v, want %v", got2, got)
    56  			}
    57  		})
    58  	}
    59  }
    60  
    61  func TestFromMultiAddrStringWithPID(t *testing.T) {
    62  	tests := []struct {
    63  		name     string
    64  		str      string
    65  		idStr    string
    66  		wantIp   net.IP // verify one of them
    67  		wantPort int
    68  		wantErr  bool
    69  	}{
    70  		{"TIP4peerAddr", "/ip4/192.168.0.58/tcp/11002", "16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58"), 11002, false},
    71  		{"TMissingAddr", "/tcp/11002", "16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58"), 11002, true},
    72  		{"TIP4MissingPort", "/ip4/192.168.0.58", "16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58"), 11002, true},
    73  		{"TIP6peerAddr", "/ip6/FE80::0202:B3FF:FE1E:8329/tcp/11003", "16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("FE80::0202:B3FF:FE1E:8329"), 11003, false},
    74  	}
    75  	for _, tt := range tests {
    76  		t.Run(tt.name, func(t *testing.T) {
    77  			id, err := types.IDB58Decode(tt.idStr)
    78  			if err != nil {
    79  				t.Fatalf("parse id error %v ", err)
    80  			}
    81  			got, err := FromMultiAddrStringWithPID(tt.str, id)
    82  			if (err != nil) != tt.wantErr {
    83  				t.Errorf("FromMultiAddr() error = %v, wantErr %v", err, tt.wantErr)
    84  				return
    85  			}
    86  			if !tt.wantErr {
    87  				ip := net.ParseIP(got.IPAddress)
    88  				if !reflect.DeepEqual(ip, tt.wantIp) {
    89  					t.Errorf("FromMultiAddr() = %v, want %v", ip.String(), tt.wantIp)
    90  				}
    91  				if !reflect.DeepEqual(got.Port, uint32(tt.wantPort)) {
    92  					t.Errorf("FromMultiAddr() = %v, want %v", got.Port, tt.wantPort)
    93  				}
    94  			}
    95  
    96  			ma, _ := types.ParseMultiaddrWithResolve(tt.str + "/p2p/" + tt.idStr)
    97  			got2, err := FromMultiAddr(ma)
    98  			if (err != nil) != tt.wantErr {
    99  				t.Errorf("FromMultiAddr() error = %v, wantErr %v", err, tt.wantErr)
   100  				return
   101  			}
   102  			if !reflect.DeepEqual(got2, got) {
   103  				t.Errorf("result of FromMultiAddrStringWithPID and FromMultiAddr differ %v, want %v", got2, got)
   104  			}
   105  
   106  		})
   107  	}
   108  }
   109  
   110  func TestPeerMeta_ToMultiAddr(t *testing.T) {
   111  	type fields struct {
   112  		IPAddress string
   113  		Port      uint32
   114  		ID        types.PeerID
   115  	}
   116  	tests := []struct {
   117  		name         string
   118  		fields       fields
   119  		wantErr      bool
   120  		wantProtocol int
   121  	}{
   122  		{"t1", fields{"192.168.1.2", 2, "id0002"}, false, multiaddr.P_IP4},
   123  		{"t2", fields{"0.0.0.0", 2223, "id2223"}, false, multiaddr.P_IP4},
   124  		{"t3", fields{"2001:0db8:85a3:08d3:1319:8a2e:0370:7334", 444, "id0002"}, false, multiaddr.P_IP6},
   125  		{"t4", fields{"::ffff:192.0.1.2", 444, "id0002"}, false, multiaddr.P_IP4},
   126  		//{"t5", fields{"www.aergo.io", 444, "id0002"}, false, multiaddr.P_IP4},
   127  		{"t6", fields{"no1.blocko.com", 444, "id0002"}, true, multiaddr.P_IP4},
   128  		{"tErr", fields{"dw::ffff:192.0.1.2", 444, "id0002"}, true, multiaddr.P_IP4},
   129  		{"tErr2", fields{"dw!.com", 444, "id0002"}, true, multiaddr.P_IP4},
   130  		{"tErr3", fields{".google.com", 444, "id0002"}, true, multiaddr.P_IP4},
   131  	}
   132  	for _, tt := range tests {
   133  		t.Run(tt.name, func(t *testing.T) {
   134  			m := p2pcommon.PeerMeta{
   135  				ID:        tt.fields.ID,
   136  				IPAddress: tt.fields.IPAddress,
   137  				Port:      tt.fields.Port,
   138  			}
   139  			got, err := PeerMetaToMultiAddr(m)
   140  			if (err != nil) != tt.wantErr {
   141  				t.Errorf("PeerMeta.PeerMetaToMultiAddr() error = %v, wantErr %v", err, tt.wantErr)
   142  				return
   143  			}
   144  			if !tt.wantErr {
   145  				val, err := got.ValueForProtocol(tt.wantProtocol)
   146  				assert.Nil(t, err)
   147  				expIp := net.ParseIP(tt.fields.IPAddress)
   148  				if expIp == nil {
   149  					ips, _ := network.ResolveHostDomain(tt.fields.IPAddress)
   150  					expIp = ips[0]
   151  				}
   152  				assert.Equal(t, expIp, net.ParseIP(val))
   153  			}
   154  		})
   155  	}
   156  }
   157  
   158  func TestGenerateKeyFile(t *testing.T) {
   159  	// this test should not be run by root
   160  	testDir := "_tmp"
   161  	existDir := "_tmp/holder.key"
   162  	if _, err := os.Stat(testDir); !os.IsNotExist(err) {
   163  		t.Skip("can't test since test dir already exists")
   164  	} else {
   165  		err := os.MkdirAll(testDir, os.ModePerm)
   166  		if err != nil {
   167  			t.Skip("can't test. permission error. " + err.Error())
   168  		}
   169  		defer func() {
   170  			os.RemoveAll(testDir)
   171  		}()
   172  		err = os.MkdirAll(existDir, os.ModePerm)
   173  		if err != nil {
   174  			t.Skip("can't test. permission error. " + err.Error())
   175  		}
   176  	}
   177  	type args struct {
   178  		dir    string
   179  		prefix string
   180  	}
   181  	tests := []struct {
   182  		name    string
   183  		args    args
   184  		wantErr bool
   185  	}{
   186  		{"TSucc", args{filepath.Join(testDir, "abc"), "testkey"}, false},
   187  		{"TPermission", args{"/sbin/abc", "testkey"}, true},
   188  		{"TDir", args{testDir, "holder"}, true},
   189  		//{"TNotExist", args{}, true},
   190  		//{"TInvalidKey", args{}, false},
   191  		//{"TInvalidKey", args{}, false},
   192  	}
   193  	for _, tt := range tests {
   194  		t.Run(tt.name, func(t *testing.T) {
   195  			gotPriv, gotPub, err := GenerateKeyFile(tt.args.dir, tt.args.prefix)
   196  			if (err != nil) != tt.wantErr {
   197  				t.Errorf("GenerateKeyFile() error = %v, wantErr %v", err, tt.wantErr)
   198  				return
   199  			}
   200  
   201  			file := filepath.Join(tt.args.dir, tt.args.prefix+p2pcommon.DefaultPkKeyExt)
   202  			if !tt.wantErr {
   203  				if !gotPriv.GetPublic().Equals(gotPub) {
   204  					t.Errorf("priv key and pub key check failed")
   205  					return
   206  				}
   207  
   208  				ldPriv, ldPub, actErr := LoadKeyFile(file)
   209  				if actErr != nil {
   210  					t.Errorf("LoadKeyFile() should not return error, but get %v, ", actErr)
   211  				}
   212  				if !ldPriv.Equals(gotPriv) {
   213  					t.Errorf("GenerateKeyFile() and LoadKeyFile() private key is differ.")
   214  					return
   215  				}
   216  				if !ldPub.Equals(gotPub) {
   217  					t.Errorf("GenerateKeyFile() and LoadKeyFile() public key is differ.")
   218  					return
   219  				}
   220  			}
   221  		})
   222  	}
   223  }
   224  
   225  func TestExtractIPAddress(t *testing.T) {
   226  	tests := []struct {
   227  		name string
   228  		mastr string
   229  
   230  		want net.IP
   231  	}{
   232  		{"TIP4peerAddr", "/ip4/192.168.0.58/tcp/11002/p2p/16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("192.168.0.58") },
   233  		{"TIP4AndPort", "/ip4/192.168.0.58/tcp/11002", net.ParseIP("192.168.0.58") },
   234  		{"TMissingAddr", "/tcp/11002", nil},
   235  		{"TIP4Only", "/ip4/192.168.0.58", net.ParseIP("192.168.0.58"),},
   236  		{"TIP6peerAddr", "/ip6/FE80::0202:B3FF:FE1E:8329/tcp/11003/p2p/16Uiu2HAmHuBgtnisgPLbujFvxPNZw3Qvpk3VLUwTzh5C67LAZSFh", net.ParseIP("FE80::0202:B3FF:FE1E:8329")},
   237  	}
   238  	for _, tt := range tests {
   239  		t.Run(tt.name, func(t *testing.T) {
   240  			ma, _ := types.ParseMultiaddrWithResolve(tt.mastr)
   241  			if got := ExtractIPAddress(ma); !reflect.DeepEqual(got, tt.want) {
   242  				t.Errorf("ExtractIPAddress() = %v, want %v", got, tt.want)
   243  			}
   244  		})
   245  	}
   246  }