github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/privval/test_util.go (about)

     1  package privval
     2  
     3  // This file defines the functions only used in the test. *DON'T add functions for production use*.
     4  
     5  import (
     6  	"fmt"
     7  	"net"
     8  	"os"
     9  	"path"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/stretchr/testify/require"
    14  
    15  	"github.com/line/ostracon/crypto"
    16  	"github.com/line/ostracon/crypto/ed25519"
    17  	"github.com/line/ostracon/libs/log"
    18  )
    19  
    20  // WithMockKMS function starts/stops a mock KMS function for testing on an unused local port. The continuation function
    21  // f is passed the address to connect to and the private key that KMS uses for signing. Thus, it is possible to test
    22  // the connection to KMS and verify the signature in the continuation function.
    23  func WithMockKMS(t *testing.T, dir, chainID string, f func(string, crypto.PrivKey)) {
    24  	// This process is based on cmd/priv_validator_server/main.go
    25  
    26  	// obtain an address using a vacancy port number
    27  	listener, err := net.Listen("tcp", "127.0.0.1:0")
    28  	require.NoError(t, err)
    29  	addr := listener.Addr().String()
    30  	err = listener.Close()
    31  	require.NoError(t, err)
    32  
    33  	// start mock kms server
    34  	logger := log.NewOCLogger(log.NewSyncWriter(os.Stdout))
    35  	privKey := ed25519.GenPrivKeyFromSecret([]byte("🏺"))
    36  	shutdown := make(chan string)
    37  	go func() {
    38  		logger.Info(fmt.Sprintf("MockKMS starting: [%s] %s", chainID, addr))
    39  		pv := NewFilePV(privKey, path.Join(dir, "keyfile"), path.Join(dir, "statefile"))
    40  		connTimeout := 5 * time.Second
    41  		dialer := DialTCPFn(addr, connTimeout, ed25519.GenPrivKeyFromSecret([]byte("🔌")))
    42  		sd := NewSignerDialerEndpoint(logger, dialer)
    43  		ss := NewSignerServer(sd, chainID, pv)
    44  		err := ss.Start()
    45  		require.NoError(t, err)
    46  		logger.Info("MockKMS started")
    47  		<-shutdown
    48  		logger.Info("MockKMS stopping")
    49  		err = ss.Stop()
    50  		require.NoError(t, err)
    51  		logger.Info("MockKMS stopped")
    52  	}()
    53  	defer func() {
    54  		shutdown <- "SHUTDOWN"
    55  	}()
    56  
    57  	f(addr, privKey)
    58  }