-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
177 lines (159 loc) · 4.37 KB
/
utils.go
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
// Copyright (c) 2018 The VeChainThor developers
// Copyright (c) 2019 The PlayMaker developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.com/licenses/lgpl-3.0.html>
package main
import (
"context"
"crypto/ecdsa"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/signal"
"os/user"
"path/filepath"
"runtime"
"syscall"
"time"
"github.com/ethereum/go-ethereum/crypto"
tty "github.com/mattn/go-tty"
"github.com/playmakerchain/powerplay/api/doc"
"github.com/playmakerchain/powerplay/powerplay"
)
func fatal(args ...interface{}) {
var w io.Writer
if runtime.GOOS == "windows" {
// The SameFile check below doesn't work on Windows.
// stdout is unlikely to get redirected though, so just print there.
w = os.Stdout
} else {
outf, _ := os.Stdout.Stat()
errf, _ := os.Stderr.Stat()
if outf != nil && errf != nil && os.SameFile(outf, errf) {
w = os.Stderr
} else {
w = io.MultiWriter(os.Stdout, os.Stderr)
}
}
fmt.Fprint(w, "Fatal: ")
fmt.Fprintln(w, args...)
os.Exit(1)
}
func loadOrGeneratePrivateKey(path string) (*ecdsa.PrivateKey, error) {
key, err := crypto.LoadECDSA(path)
if err == nil {
return key, nil
}
if !os.IsNotExist(err) {
return nil, err
}
key, err = crypto.GenerateKey()
if err != nil {
return nil, err
}
if err := crypto.SaveECDSA(path, key); err != nil {
return nil, err
}
return key, nil
}
func defaultConfigDir() string {
if home := homeDir(); home != "" {
return filepath.Join(home, ".com.playmakerchain.powerplay")
}
return ""
}
// copy from go-ethereum
func defaultDataDir() string {
// Try to place the data folder in the user's home dir
if home := homeDir(); home != "" {
if runtime.GOOS == "darwin" {
return filepath.Join(home, "Library", "Application Support", "com.playmakerchain.powerplay")
} else if runtime.GOOS == "windows" {
return filepath.Join(home, "AppData", "Roaming", "com.playmakerchain.powerplay")
} else {
return filepath.Join(home, ".com.playmakerchain.powerplay")
}
}
// As we cannot guess a stable location, return empty and handle later
return ""
}
func homeDir() string {
if home := os.Getenv("HOME"); home != "" {
return home
}
if usr, err := user.Current(); err == nil {
return usr.HomeDir
}
return ""
}
func handleExitSignal() context.Context {
ctx, cancel := context.WithCancel(context.Background())
go func() {
exitSignalCh := make(chan os.Signal)
signal.Notify(exitSignalCh, os.Interrupt, os.Kill, syscall.SIGTERM)
select {
case sig := <-exitSignalCh:
log.Info("exit signal received", "signal", sig)
cancel()
}
}()
return ctx
}
// middleware to limit request body size.
func requestBodyLimit(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 96*1000)
h.ServeHTTP(w, r)
})
}
// middleware to verify 'x-genesis-id' header in request, and set to response headers.
func handleXGenesisID(h http.Handler, genesisID powerplay.Bytes32) http.Handler {
const headerKey = "x-genesis-id"
expectedID := genesisID.String()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
actualID := r.Header.Get(headerKey)
if actualID == "" {
actualID = r.URL.Query().Get(headerKey)
}
w.Header().Set(headerKey, expectedID)
if actualID != "" && actualID != expectedID {
io.Copy(ioutil.Discard, r.Body)
http.Error(w, "genesis id mismatch", http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
})
}
// middleware to set 'x-thorest-ver' to response headers.
func handleXThorestVersion(h http.Handler) http.Handler {
const headerKey = "x-thorest-ver"
ver := doc.Version()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerKey, ver)
h.ServeHTTP(w, r)
})
}
// middleware for http request timeout.
func handleAPITimeout(h http.Handler, timeout time.Duration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
h.ServeHTTP(w, r)
})
}
func readPasswordFromNewTTY(prompt string) (string, error) {
t, err := tty.Open()
if err != nil {
return "", err
}
defer t.Close()
fmt.Fprint(t.Output(), prompt)
pass, err := t.ReadPasswordNoEcho()
if err != nil {
return "", err
}
return pass, err
}