github.com/vipernet-xyz/tm@v0.34.24/privval/utils.go (about)

     1  package privval
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net"
     7  
     8  	"github.com/vipernet-xyz/tm/crypto/ed25519"
     9  	"github.com/vipernet-xyz/tm/libs/log"
    10  	tmnet "github.com/vipernet-xyz/tm/libs/net"
    11  )
    12  
    13  // IsConnTimeout returns a boolean indicating whether the error is known to
    14  // report that a connection timeout occurred. This detects both fundamental
    15  // network timeouts, as well as ErrConnTimeout errors.
    16  func IsConnTimeout(err error) bool {
    17  	_, ok := errors.Unwrap(err).(timeoutError)
    18  	switch {
    19  	case errors.As(err, &EndpointTimeoutError{}):
    20  		return true
    21  	case ok:
    22  		return true
    23  	default:
    24  		return false
    25  	}
    26  }
    27  
    28  // NewSignerListener creates a new SignerListenerEndpoint using the corresponding listen address
    29  func NewSignerListener(listenAddr string, logger log.Logger) (*SignerListenerEndpoint, error) {
    30  	var listener net.Listener
    31  
    32  	protocol, address := tmnet.ProtocolAndAddress(listenAddr)
    33  	ln, err := net.Listen(protocol, address)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	switch protocol {
    38  	case "unix":
    39  		listener = NewUnixListener(ln)
    40  	case "tcp":
    41  		// TODO: persist this key so external signer can actually authenticate us
    42  		listener = NewTCPListener(ln, ed25519.GenPrivKey())
    43  	default:
    44  		return nil, fmt.Errorf(
    45  			"wrong listen address: expected either 'tcp' or 'unix' protocols, got %s",
    46  			protocol,
    47  		)
    48  	}
    49  
    50  	pve := NewSignerListenerEndpoint(logger.With("module", "privval"), listener)
    51  
    52  	return pve, nil
    53  }
    54  
    55  // GetFreeLocalhostAddrPort returns a free localhost:port address
    56  func GetFreeLocalhostAddrPort() string {
    57  	port, err := tmnet.GetFreePort()
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  	return fmt.Sprintf("127.0.0.1:%d", port)
    62  }