github.com/igggame/nebulas-go@v2.1.0+incompatible/net/utils.go (about)

     1  // Copyright (C) 2017 go-nebulas authors
     2  //
     3  // This file is part of the go-nebulas library.
     4  //
     5  // the go-nebulas library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // the go-nebulas library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU General Public License
    16  // along with the go-nebulas library.  If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  
    19  package net
    20  
    21  import (
    22  	"errors"
    23  	"net"
    24  	"os"
    25  	"strings"
    26  	"time"
    27  
    28  	peer "github.com/libp2p/go-libp2p-peer"
    29  	ma "github.com/multiformats/go-multiaddr"
    30  )
    31  
    32  // Errors
    33  var (
    34  	ErrListenPortIsNotAvailable = errors.New("listen port is not available")
    35  	ErrConfigLackNetWork        = errors.New("config.conf should has network")
    36  )
    37  
    38  // ParseFromIPFSAddr return pid and address parsed from ipfs address
    39  func ParseFromIPFSAddr(ipfsAddr ma.Multiaddr) (peer.ID, ma.Multiaddr, error) {
    40  	addr, err := ma.NewMultiaddr(strings.Split(ipfsAddr.String(), "/ipfs/")[0])
    41  	if err != nil {
    42  		return "", nil, err
    43  	}
    44  
    45  	// TODO: @robin we should register neb multicodecs.
    46  	b58, err := ipfsAddr.ValueForProtocol(ma.P_IPFS)
    47  	if err != nil {
    48  		return "", nil, err
    49  	}
    50  
    51  	id, err := peer.IDB58Decode(b58)
    52  	if err != nil {
    53  		return "", nil, err
    54  	}
    55  
    56  	return id, addr, nil
    57  }
    58  
    59  func verifyListenAddress(listen []string) error {
    60  	for _, v := range listen {
    61  		_, err := net.ResolveTCPAddr("tcp", v)
    62  		if err != nil {
    63  			return err
    64  		}
    65  	}
    66  	return nil
    67  }
    68  
    69  func checkPathConfig(path string) bool {
    70  	if path == "" {
    71  		return true
    72  	}
    73  
    74  	if _, err := os.Stat(path); os.IsNotExist(err) {
    75  		return false
    76  	}
    77  
    78  	return true
    79  }
    80  
    81  func checkPortAvailable(listen []string) error {
    82  	for _, v := range listen {
    83  		conn, err := net.DialTimeout("tcp", v, time.Second*1)
    84  		if err == nil {
    85  			conn.Close()
    86  			return ErrListenPortIsNotAvailable
    87  		}
    88  	}
    89  	return nil
    90  }