Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
387 lines (322 loc) · 10 KB
/
Copy pathmain.go
File metadata and controls
387 lines (322 loc) · 10 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//go:build gtk
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/diamondburned/gotk4-adwaita/pkg/adw"
"github.com/diamondburned/gotk4/pkg/gdk/v4"
"github.com/diamondburned/gotk4/pkg/gio/v2"
"github.com/diamondburned/gotk4/pkg/glib/v2"
"github.com/diamondburned/gotk4/pkg/gtk/v4"
"github.com/gofrs/flock"
"github.com/pactus-project/gopkg/signal"
"github.com/pactus-project/pactus/cmd"
gtkapp "github.com/pactus-project/pactus/cmd/gtk/app"
"github.com/pactus-project/pactus/cmd/gtk/assets"
"github.com/pactus-project/pactus/cmd/gtk/controller"
"github.com/pactus-project/pactus/cmd/gtk/gtkutil"
"github.com/pactus-project/pactus/cmd/gtk/view"
"github.com/pactus-project/pactus/config"
"github.com/pactus-project/pactus/genesis"
"github.com/pactus-project/pactus/node"
"github.com/pactus-project/pactus/util"
"github.com/pactus-project/pactus/version"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)
const appID = "com.github.pactus-project.pactus.pactus-gui"
var (
workingDirOpt *string
passwordOpt *string
testnetOpt *bool
grpcAddrOpt *string
grpcInsecureOpt *bool
snapshotURLOpt *string
)
func init() {
workingDirOpt = flag.String("working-dir", cmd.PactusDefaultHomeDir(), "working directory path")
passwordOpt = flag.String("password", "", "wallet password")
testnetOpt = flag.Bool("testnet", false, "initializing for the testnet")
grpcAddrOpt = flag.String("grpc-addr", "", "connect to remote gRPC server instead of starting local node")
grpcInsecureOpt = flag.Bool("grpc-insecure", false, "use insecure connection to gRPC server")
snapshotURLOpt = flag.String(
"snapshot-url",
cmd.DefaultSnapshotURL,
"snapshot server base URL (network path will be appended automatically)",
)
version.NodeAgent.AppType = "gui"
if runtime.GOOS == "darwin" {
// Changing the PANGOCAIRO_BACKEND is necessary on MacOS to render emoji
_ = os.Setenv("PANGOCAIRO_BACKEND", "fontconfig")
}
// The GUI text is English only, so force GTK's built-in widget strings
// (assistant navigation, about dialog, file choosers ...) to English too
// instead of following the operating system locale. This affects message
// translation only, not number or date formatting.
// Use g_setenv, not os.Setenv: on Windows the latter uses the Win32
// environment block, which the C runtime that GTK/libintl links against
// does not read, so the change would be invisible to gettext.
glib.Setenv("LANGUAGE", "en", true)
glib.Setenv("LC_MESSAGES", "en", true)
forceEnglishUILanguage()
gtk.Init()
// Initialize libadwaita so its StyleManager controls the light/dark
// appearance, independent of the operating system theme.
adw.Init()
}
//nolint:gocognit // needs refactoring
func main() {
flag.Parse()
gtkutil.Logf("Starting Pactus GUI")
// The gtk should run on main thread.
runtime.UnlockOSThread()
runtime.LockOSThread()
gtkutil.Logf("Locking main thread")
// Create a new app.
app := gtk.NewApplication(appID, gio.ApplicationNonUnique)
gtk.WidgetSetDefaultDirection(gtk.TextDirLTR)
// apply custom css
provider := gtk.NewCSSProvider()
provider.LoadFromString(assets.MainWindowCSS)
display := gdk.DisplayGetDefault()
gtk.StyleContextAddProviderForDisplay(display, provider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
assets.InitAssets()
workingDir, err := filepath.Abs(*workingDirOpt)
if err != nil {
gtkutil.Logf("Aborted! %v", err)
return
}
ctx, cancel := context.WithCancel(context.Background())
var fileLock *flock.Flock
if *grpcAddrOpt == "" {
// If node is not initialized yet
if util.IsDirNotExistsOrEmpty(workingDir) {
network := genesis.Mainnet
if *testnetOpt {
network = genesis.Testnet
}
if !startupAssistant(ctx, workingDir, network, *snapshotURLOpt) {
return
}
}
}
var guiNode *node.Node
// Connect function to application startup event, this is not required.
app.Connect("startup", func() {
gtkutil.Logf("application startup")
})
var gui *gtkapp.GUI
var grpcConn *grpc.ClientConn
activateOnce := new(sync.Once)
shutdownOnce := new(sync.Once)
shutdown := func() {
shutdownOnce.Do(func() {
cancel()
if grpcConn != nil {
_ = grpcConn.Close()
}
if gui != nil {
gui.Cleanup()
}
if guiNode != nil {
guiNode.Stop()
}
if fileLock != nil {
_ = fileLock.Unlock()
}
})
}
// Connect function to application shutdown event, this is not required.
app.Connect("shutdown", func() {
gtkutil.Logf("Application shutdown")
shutdown()
})
// Connect function to application activate event
app.Connect("activate", func() {
activateOnce.Do(func() {
gtkutil.Logf("application activate")
splash := view.NewSplashWindow(app)
splash.SetVersion(version.NodeVersion().StringWithAlias())
gtk.WindowSetAutoStartupNotification(false)
splash.ShowAll()
gtk.WindowSetAutoStartupNotification(true)
app.AddWindow(splash.Window())
notify := func(msg string) {
gtkutil.Logf("Splash msg: %s", msg)
gtkutil.IdleAddAsync(func() {
splash.UpdateStatus(msg)
})
}
go func() {
var grpcAddr string
var grpcInsecure bool
if *grpcAddrOpt == "" {
// Define the lock file path
lockFilePath := filepath.Join(workingDir, ".pactus.lock")
fileLock = flock.New(lockFilePath)
locked, err := fileLock.TryLock()
if err != nil {
gtkutil.ShowErrorDialog(splash.Window(),
fmt.Sprintf("Aborted! Unable to acquire file lock. %v", err),
func(_ int) {
splash.Destroy()
})
return
}
if !locked {
gtkutil.ShowErrorDialog(splash.Window(),
fmt.Sprintf("Could not lock '%s', another instance is running?", lockFilePath),
func(_ int) {
splash.Destroy()
})
return
}
reportStatus(notify, "Starting local node...")
time.Sleep(1 * time.Second)
guiNode, err = newNode(ctx, workingDir, notify)
if err != nil {
gtkutil.ShowWarningDialog(splash.Window(), err.Error(),
func(_ int) {
splash.Destroy()
})
return
}
grpcAddr = guiNode.GRPC().Address()
grpcInsecure = true
} else {
reportStatus(notify, "Connecting to remote node...")
time.Sleep(1 * time.Second)
grpcAddr = *grpcAddrOpt
grpcInsecure = *grpcInsecureOpt
}
grpcConn, err = newRemoteGRPCConn(grpcAddr, grpcInsecure)
if err != nil {
gtkutil.ShowErrorDialog(splash.Window(), err.Error(),
func(_ int) {
splash.Destroy()
})
return
}
var connectionLabel, connectionValue string
var isLocal bool
if *grpcAddrOpt == "" {
isLocal = true
connectionLabel = "📁 Working Directory"
connectionValue = workingDir
} else {
isLocal = false
connectionLabel = "📡 Remote Address"
connectionValue = *grpcAddrOpt
}
gui, err = gtkapp.Run(ctx, grpcConn, app, notify,
connectionLabel, connectionValue, workingDir, isLocal)
if err != nil {
gtkutil.ShowErrorDialog(splash.Window(), err.Error(), func(_ int) {
splash.Destroy()
})
return
}
gtkutil.IdleAddSync(func() {
splash.Destroy()
})
}()
})
})
signal.HandleInterrupt(func() {
gtkutil.Logf("Exiting...")
gtkutil.IdleAddSync(func() {
shutdown()
})
})
// Launch the application
os.Exit(app.Run(nil))
}
type statusReporter func(string)
func reportStatus(cb statusReporter, msg string) {
if cb != nil {
cb(msg)
}
}
// newRemoteGRPCConn creates a gRPC client for a remote URL.
func newRemoteGRPCConn(addr string, insecureCredentials bool) (*grpc.ClientConn, error) {
target, prefix, err := util.ParseGRPCAddr(addr, insecureCredentials)
if err != nil {
return nil, err
}
var creds credentials.TransportCredentials
if insecureCredentials {
gtkutil.Logf("Connecting to node using insecure credentials. target: %s, prefix: %s", target, prefix)
creds = insecure.NewCredentials()
} else {
gtkutil.Logf("Connecting to node using TLS. target: %s, prefix: %s", target, prefix)
creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
}
opts := []grpc.DialOption{
grpc.WithTransportCredentials(creds),
grpc.WithUnaryInterceptor(methodPrefixUnaryInterceptor(prefix)),
grpc.WithStreamInterceptor(methodPrefixStreamInterceptor(prefix)),
}
return grpc.NewClient(target, opts...)
}
func methodPrefixUnaryInterceptor(prefix string) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any,
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption,
) error {
return invoker(ctx, prefix+method, req, reply, cc, opts...)
}
}
func methodPrefixStreamInterceptor(prefix string) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc,
cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption,
) (grpc.ClientStream, error) {
return streamer(ctx, desc, cc, prefix+method, opts...)
}
}
func newNode(ctx context.Context, workingDir string, statusCb statusReporter) (*node.Node, error) {
// change working directory
if err := os.Chdir(workingDir); err != nil {
gtkutil.Logf("Aborted! Unable to changes working directory. %v", err)
return nil, err
}
reportStatus(statusCb, "Opening wallet...")
passwordFetcher := func() (string, bool) {
gtkutil.Logf("Fetching wallet password")
if *passwordOpt != "" {
return *passwordOpt, true
}
password := ""
ok := false
resultChan := make(chan bool)
gtkutil.IdleAddSync(func() {
controller.PromptWalletPassword(func(_password string, _ok bool) {
password = _password
ok = _ok
resultChan <- true
})
})
<-resultChan
return password, ok
}
configModifier := func(cfg *config.Config) *config.Config {
if !cfg.GRPC.Enable {
cfg.GRPC.Enable = true
cfg.GRPC.Listen = "localhost:0"
}
cfg.GRPC.EnableWallet = true
return cfg
}
reportStatus(statusCb, "Starting node services...")
n, err := cmd.StartNode(ctx, workingDir, passwordFetcher, configModifier)
if err != nil {
return nil, err
}
return n, nil
}