-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathutils.go
More file actions
206 lines (179 loc) · 5.32 KB
/
utils.go
File metadata and controls
206 lines (179 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package cli
import (
"bufio"
"bytes"
"context"
"encoding/hex"
"fmt"
"io"
"math/big"
"math/rand"
"os"
"strings"
"time"
"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/rpc"
"github.com/pokt-network/pocket/shared/codec"
"github.com/pokt-network/pocket/shared/converters"
"github.com/pokt-network/pocket/shared/crypto"
typesUtil "github.com/pokt-network/pocket/utility/types"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
// readEd25519PrivateKeyFromFile returns an Ed25519PrivateKey from a file where the file simply encodes it in a string (for now)
// HACK(#150): this is a temporary hack since we don't have yet a keybase, the next step would be to read from an "ArmoredJson" like in V0
func readEd25519PrivateKeyFromFile(pkPath string) (pk crypto.Ed25519PrivateKey, err error) {
pkFile, err := os.Open(pkPath)
if err != nil {
return
}
defer pkFile.Close()
pk, err = parseEd25519PrivateKeyFromReader(pkFile)
return
}
func parseEd25519PrivateKeyFromReader(reader io.Reader) (pk crypto.Ed25519PrivateKey, err error) {
if reader == nil {
return nil, fmt.Errorf("cannot read from reader %v", reader)
}
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
priv := &crypto.Ed25519PrivateKey{}
err = priv.UnmarshalJSON(buf.Bytes())
if err != nil {
return
}
pk = priv.Bytes()
return
}
// credentials reads a password from the prompt and returns the trimmed version
//
// If pwd is provided (via flag to the command), it uses that one instead of asking via prompt
func credentials(pwd string) string {
if pwd != "" && strings.TrimSpace(pwd) != "" {
return strings.TrimSpace(pwd)
}
bytePassword, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
logger.Global.Fatal().Err(err).Msg("failed to read password")
}
return strings.TrimSpace(string(bytePassword))
}
// confirmation asks the user for a yes/no answer via interactive prompt.
//
// If pwd is provided (via flag to the command), it returns true since it's assumed that a user that provides a password via flag knows what they are doing
func confirmation(pwd string) bool {
if pwd != "" && strings.TrimSpace(pwd) != "" {
return true
}
reader := bufio.NewReader(os.Stdin)
for {
fmt.Println("yes | no")
response, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading string: ", err.Error())
return false
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return true
} else if response == "n" || response == "no" {
return false
}
}
}
// prepareTxBytes wraps a Message into a Transaction and signs it with the provided pk
//
// returns the raw protobuf bytes of the signed transaction
func prepareTxBytes(msg typesUtil.Message, pk crypto.Ed25519PrivateKey) ([]byte, error) {
var err error
anyMsg, err := codec.GetCodec().ToAny(msg)
if err != nil {
return nil, err
}
tx := &typesUtil.Transaction{
Msg: anyMsg,
Nonce: getNonce(),
}
signBytes, err := tx.SignBytes()
if err != nil {
return nil, err
}
signature, err := pk.Sign(signBytes)
if err != nil {
return nil, err
}
tx.Signature = &typesUtil.Signature{
Signature: signature,
PublicKey: pk.PublicKey().Bytes(),
}
bz, err := codec.GetCodec().Marshal(tx)
if err != nil {
return nil, err
}
return bz, nil
}
// postRawTx posts a signed transaction
func postRawTx(ctx context.Context, pk crypto.Ed25519PrivateKey, j []byte) (*rpc.PostV1ClientBroadcastTxSyncResponse, error) {
client, err := rpc.NewClientWithResponses(remoteCLIURL)
if err != nil {
return nil, err
}
req := rpc.RawTXRequest{
Address: pk.Address().String(),
RawHexBytes: hex.EncodeToString(j),
}
resp, err := client.PostV1ClientBroadcastTxSyncWithResponse(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
}
func getNonce() string {
rand.Seed(time.Now().UTC().UnixNano())
return fmt.Sprintf("%d", rand.Uint64())
}
func readPassphrase(currPwd string) string {
if strings.TrimSpace(currPwd) == "" {
fmt.Println("Enter Passphrase: ")
} else {
fmt.Println("Using Passphrase provided via flag")
}
return credentials(currPwd)
}
func validateStakeAmount(amount string) error {
am, err := converters.StringToBigInt(amount)
if err != nil {
return err
}
sr := big.NewInt(stakingRecommendationAmount)
if typesUtil.BigIntLessThan(am, sr) {
fmt.Printf("The amount you are staking for is below the recommendation of %d POKT, would you still like to continue? y|n\n", sr.Div(sr, oneMillion).Int64())
if !confirmation(pwd) {
return fmt.Errorf("aborted")
}
}
return nil
}
func applySubcommandOptions(cmds []*cobra.Command, cmdDef actorCmdDef) {
for _, cmd := range cmds {
for _, opt := range cmdDef.Options {
opt(cmd)
}
}
}
func attachPwdFlagToSubcommands() []cmdOption {
return []cmdOption{func(c *cobra.Command) {
c.Flags().StringVar(&pwd, "pwd", "", "passphrase used by the cmd, non empty usage bypass interactive prompt")
}}
}
func unableToConnectToRpc(err error) error {
fmt.Printf("❌ Unable to connect to the RPC @ %s\n\nError: %s", boldText(remoteCLIURL), err)
return nil
}
func rpcResponseCodeUnhealthy(statusCode int, response []byte) error {
fmt.Printf("❌ RPC reporting unhealthy status HTTP %d @ %s\n\n%s", statusCode, boldText(remoteCLIURL), response)
return nil
}
func boldText[T string | []byte](s T) string {
return fmt.Sprintf("\033[1m%s\033[0m", s)
}