-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
main.go
307 lines (259 loc) · 7.04 KB
/
main.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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/gbrlsnchs/jwt/v3"
"github.com/gorilla/mux"
logging "github.com/ipfs/go-log/v2"
"github.com/urfave/cli/v2"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-jsonrpc"
"github.com/filecoin-project/go-jsonrpc/auth"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/api/v0api"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/wallet"
ledgerwallet "github.com/filecoin-project/lotus/chain/wallet/ledger"
lcli "github.com/filecoin-project/lotus/cli"
"github.com/filecoin-project/lotus/lib/lotuslog"
"github.com/filecoin-project/lotus/metrics"
"github.com/filecoin-project/lotus/metrics/proxy"
"github.com/filecoin-project/lotus/node/modules"
"github.com/filecoin-project/lotus/node/repo"
)
var log = logging.Logger("main")
const FlagWalletRepo = "wallet-repo"
type jwtPayload struct {
Allow []auth.Permission
}
func main() {
lotuslog.SetupLogLevels()
local := []*cli.Command{
runCmd,
getApiKeyCmd,
}
app := &cli.App{
Name: "lotus-wallet",
Usage: "Basic external wallet",
Version: string(build.NodeUserVersion()),
Description: `
lotus-wallet provides a remote wallet service for lotus.
To configure your lotus node to use a remote wallet:
* Run 'lotus-wallet get-api-key' to generate API key
* Start lotus-wallet using 'lotus-wallet run' (see --help for additional flags)
* Edit lotus config (~/.lotus/config.toml)
* Find the '[Wallet]' section
* Set 'RemoteBackend' to '[api key]:http://[wallet ip]:[wallet port]'
(the default port is 1777)
* Start (or restart) the lotus daemon`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: FlagWalletRepo,
EnvVars: []string{"WALLET_PATH"},
Value: "~/.lotuswallet", // TODO: Consider XDG_DATA_HOME
},
&cli.StringFlag{
Name: "repo",
EnvVars: []string{"LOTUS_PATH"},
Hidden: true,
Value: "~/.lotus",
},
},
Commands: local,
}
app.Setup()
if err := app.Run(os.Args); err != nil {
log.Warnf("%+v", err)
return
}
}
var getApiKeyCmd = &cli.Command{
Name: "get-api-key",
Usage: "Generate API Key",
Action: func(cctx *cli.Context) error {
lr, ks, err := openRepo(cctx)
if err != nil {
return err
}
defer lr.Close() // nolint
p := jwtPayload{
Allow: []auth.Permission{api.PermAdmin},
}
authKey, err := modules.APISecret(ks, lr)
if err != nil {
return xerrors.Errorf("setting up api secret: %w", err)
}
k, err := jwt.Sign(&p, (*jwt.HMACSHA)(authKey))
if err != nil {
return xerrors.Errorf("jwt sign: %w", err)
}
fmt.Println(string(k))
return nil
},
}
var runCmd = &cli.Command{
Name: "run",
Usage: "Start lotus wallet",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "listen",
Usage: "host address and port the wallet api will listen on",
Value: "0.0.0.0:1777",
},
&cli.BoolFlag{
Name: "ledger",
Usage: "use a ledger device instead of an on-disk wallet",
},
&cli.BoolFlag{
Name: "interactive",
Usage: "prompt before performing actions (DO NOT USE FOR MINER WORKER ADDRESS)",
},
&cli.BoolFlag{
Name: "offline",
Usage: "don't query chain state in interactive mode",
},
&cli.BoolFlag{
Name: "disable-auth",
Usage: "(insecure) disable api auth",
Hidden: true,
},
&cli.StringFlag{
Name: "http-server-timeout",
Value: "30s",
},
},
Description: "Needs FULLNODE_API_INFO env-var to be set before running (see lotus-wallet --help for setup instructions)",
Action: func(cctx *cli.Context) error {
log.Info("Starting lotus wallet")
ctx := lcli.ReqContext(cctx)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Register all metric views
if err := view.Register(
metrics.DefaultViews...,
); err != nil {
log.Fatalf("Cannot register the view: %v", err)
}
lr, ks, err := openRepo(cctx)
if err != nil {
return err
}
defer lr.Close() // nolint
lw, err := wallet.NewWallet(ks)
if err != nil {
return err
}
var w api.Wallet = lw
if cctx.Bool("ledger") {
ds, err := lr.Datastore(context.Background(), "/metadata")
if err != nil {
return err
}
w = wallet.MultiWallet{
Local: lw,
Ledger: ledgerwallet.NewWallet(ds),
}
}
address := cctx.String("listen")
mux := mux.NewRouter()
log.Info("Setting up API endpoint at " + address)
if cctx.Bool("interactive") {
var ag func() (v0api.FullNode, jsonrpc.ClientCloser, error)
if !cctx.Bool("offline") {
ag = func() (v0api.FullNode, jsonrpc.ClientCloser, error) {
return lcli.GetFullNodeAPI(cctx)
}
}
w = &InteractiveWallet{
under: w,
apiGetter: ag,
}
} else {
w = &LoggedWallet{under: w}
}
rpcApi := proxy.MetricedWalletAPI(w)
if !cctx.Bool("disable-auth") {
rpcApi = api.PermissionedWalletAPI(rpcApi)
}
rpcServer := jsonrpc.NewServer(jsonrpc.WithServerErrors(api.RPCErrors))
rpcServer.Register("Filecoin", rpcApi)
mux.Handle("/rpc/v0", rpcServer)
mux.PathPrefix("/").Handler(http.DefaultServeMux) // pprof
var handler http.Handler = mux
if !cctx.Bool("disable-auth") {
authKey, err := modules.APISecret(ks, lr)
if err != nil {
return xerrors.Errorf("setting up api secret: %w", err)
}
authVerify := func(ctx context.Context, token string) ([]auth.Permission, error) {
var payload jwtPayload
if _, err := jwt.Verify([]byte(token), (*jwt.HMACSHA)(authKey), &payload); err != nil {
return nil, xerrors.Errorf("JWT Verification failed: %w", err)
}
return payload.Allow, nil
}
log.Info("API auth enabled, use 'lotus-wallet get-api-key' to get API key")
handler = &auth.Handler{
Verify: authVerify,
Next: mux.ServeHTTP,
}
}
timeout, err := time.ParseDuration(cctx.String("http-server-timeout"))
if err != nil {
return xerrors.Errorf("invalid time string %s: %x", cctx.String("http-server-timeout"), err)
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: timeout,
BaseContext: func(listener net.Listener) context.Context {
ctx, _ := tag.New(context.Background(), tag.Upsert(metrics.APIInterface, "lotus-wallet"))
return ctx
},
}
go func() {
<-ctx.Done()
log.Warn("Shutting down...")
if err := srv.Shutdown(context.TODO()); err != nil {
log.Errorf("shutting down RPC server failed: %s", err)
}
log.Warn("Graceful shutdown successful")
}()
nl, err := net.Listen("tcp", address)
if err != nil {
return err
}
return srv.Serve(nl)
},
}
func openRepo(cctx *cli.Context) (repo.LockedRepo, types.KeyStore, error) {
repoPath := cctx.String(FlagWalletRepo)
r, err := repo.NewFS(repoPath)
if err != nil {
return nil, nil, err
}
ok, err := r.Exists()
if err != nil {
return nil, nil, err
}
if !ok {
if err := r.Init(repo.Wallet); err != nil {
return nil, nil, err
}
}
lr, err := r.Lock(repo.Wallet)
if err != nil {
return nil, nil, err
}
ks, err := lr.KeyStore()
if err != nil {
return nil, nil, err
}
return lr, ks, nil
}