github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/cli/input/input.go (about)

     1  package input
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"syscall"
     9  
    10  	"github.com/nspcc-dev/neo-go/pkg/core/transaction"
    11  	"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
    12  	"golang.org/x/term"
    13  )
    14  
    15  // Terminal is a terminal used for input. If `nil`, stdin is used.
    16  var Terminal *term.Terminal
    17  
    18  // ReadWriter combiner reader and writer.
    19  type ReadWriter struct {
    20  	io.Reader
    21  	io.Writer
    22  }
    23  
    24  // ReadLine reads a line from the input without trailing '\n'.
    25  func ReadLine(prompt string) (string, error) {
    26  	trm := Terminal
    27  	if trm == nil {
    28  		s, err := term.MakeRaw(int(syscall.Stdin))
    29  		if err != nil {
    30  			return "", err
    31  		}
    32  		defer func() { _ = term.Restore(int(syscall.Stdin), s) }()
    33  		trm = term.NewTerminal(ReadWriter{
    34  			Reader: os.Stdin,
    35  			Writer: os.Stdout,
    36  		}, "")
    37  	}
    38  	return readLine(trm, prompt)
    39  }
    40  
    41  func readLine(trm *term.Terminal, prompt string) (string, error) {
    42  	_, err := trm.Write([]byte(prompt))
    43  	if err != nil {
    44  		return "", err
    45  	}
    46  	return trm.ReadLine()
    47  }
    48  
    49  // ReadPassword reads the user's password with prompt.
    50  func ReadPassword(prompt string) (string, error) {
    51  	trm := Terminal
    52  	if trm != nil {
    53  		return trm.ReadPassword(prompt)
    54  	}
    55  	return readSecurePassword(prompt)
    56  }
    57  
    58  // ConfirmTx asks for a confirmation to send the tx.
    59  func ConfirmTx(w io.Writer, tx *transaction.Transaction) error {
    60  	fmt.Fprintf(w, "Network fee: %s\n", fixedn.Fixed8(tx.NetworkFee))
    61  	fmt.Fprintf(w, "System fee: %s\n", fixedn.Fixed8(tx.SystemFee))
    62  	fmt.Fprintf(w, "Total fee: %s\n", fixedn.Fixed8(tx.NetworkFee+tx.SystemFee))
    63  	ln, err := ReadLine("Relay transaction (y|N)> ")
    64  	if err != nil {
    65  		return err
    66  	}
    67  	if 0 < len(ln) && (ln[0] == 'y' || ln[0] == 'Y') {
    68  		return nil
    69  	}
    70  	return errors.New("cancelled")
    71  }