-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
333 lines (285 loc) · 8.85 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
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
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/Inkeliz/go-opencl/opencl"
"github.com/bananocoin/boompow/apps/client/gql"
"github.com/bananocoin/boompow/apps/client/websocket"
"github.com/bananocoin/boompow/apps/client/work"
"github.com/bananocoin/boompow/libs/utils/misc"
"github.com/bananocoin/boompow/libs/utils/validation"
"github.com/go-co-op/gocron"
"github.com/mbndr/figlet4go"
"golang.org/x/term"
)
// Variables
var GraphQLURL = "http://localhost:8080/graphql"
var WSUrl = "ws://localhost:8080/ws/worker"
var Version = "dev"
// For pretty text
func printBanner() {
ascii := figlet4go.NewAsciiRender()
options := figlet4go.NewRenderOptions()
color, _ := figlet4go.NewTrueColorFromHexString("44B542")
options.FontColor = []figlet4go.Color{
color,
}
renderStr, _ := ascii.RenderOpts("BoomPOW", options)
fmt.Print(renderStr)
}
// Determine GPU info
type gpuINFO struct {
platformName string
vendor string
driverVersion string
device opencl.Device
}
func getGPUInfo() ([]*gpuINFO, error) {
ret := []*gpuINFO{}
platforms, err := opencl.GetPlatforms()
if err != nil {
return nil, err
}
var platform opencl.Platform
var name string
for _, curPlatform := range platforms {
err = curPlatform.GetInfo(opencl.PlatformName, &name)
if err != nil {
return nil, err
}
var devices []opencl.Device
devices, err = curPlatform.GetDevices(opencl.DeviceTypeAll)
if err != nil {
return nil, err
}
for _, device := range devices {
var available bool
err = device.GetInfo(opencl.DeviceAvailable, &available)
if err == nil && available {
platform = curPlatform
} else {
continue
}
var platformName string
err := platform.GetInfo(opencl.PlatformName, &platformName)
if err != nil {
continue
}
var vendor string
err = device.GetInfo(opencl.DeviceVendor, &vendor)
if err != nil {
continue
}
var driverVersion string
err = device.GetInfo(opencl.DriverVersion, &driverVersion)
if err != nil {
continue
}
ret = append(ret, &gpuINFO{
platformName: platformName,
vendor: vendor,
driverVersion: driverVersion,
device: device,
})
}
}
if len(ret) > 0 {
return ret, nil
}
return nil, errors.New("No GPU found")
}
func usage() {
flag.PrintDefaults()
os.Exit(2)
}
func init() {
flag.Usage = usage
flag.Set("logtostderr", "true")
flag.Set("stderrthreshold", "INFO")
flag.Set("v", "2")
}
// SetupCloseHandler creates a 'listener' on a new goroutine which will notify the
// program if it receives an interrupt from the OS. We then handle this by calling
// our clean up procedure and exiting the program.
func SetupCloseHandler(ctx context.Context, cancel context.CancelFunc) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
go func() {
<-c
fmt.Print("👋 Exiting...\n")
cancel()
os.Exit(0)
}()
}
// Represents the number of simultaneous work calculations we will run
var NConcurrentWorkers int
// Instance of websocket service
var WSService *websocket.WebsocketService
func main() {
// Parse flags
gpuOnly := flag.Bool("gpu-only", false, "If set, will only run work on GPU (otherwise, both CPU and GPU)")
maxDifficulty := flag.Int("max-difficulty", 128, "The maximum work difficulty to compute, higher than this will be ignored")
minDifficulty := flag.Int("min-difficulty", 1, "The minimum work difficulty to compute, lower than this will be ignored")
noPrecache := flag.Bool("no-precache", false, "If set, will not compute precached work requests")
// Benchmark
benchmark := flag.Int("benchmark", 0, "Run a benchmark for the given number of random hashes")
benchmarkDifficulty := flag.Int("benchmark-difficulty", 64, "The difficulty multiplier for the benchmark")
// To login without username and password prompt
argEmail := flag.String("email", "", "The email (username) to use for the worker (optional)")
argPassword := flag.String("password", "", "The password to use for the worker (optional)")
// OpenCL related things
listDevices := flag.Bool("list-devices", false, "List available OpenCL devices/GPUs (optional)")
gpus := flag.String("gpus", "0", "The GPUs to use for PoW, comma separated e.g. --gpu 0,1,2 (optional, default 0)")
version := flag.Bool("version", false, "Display the version")
flag.Parse()
if *version {
fmt.Printf("BoomPOW version: %s\n", Version)
os.Exit(0)
}
// Parse GPU argument
gpuSplit := strings.Split(*gpus, ",")
gpuSplitInt := []int{}
// Validate
for _, gpu := range gpuSplit {
asInt, err := strconv.Atoi(gpu)
if err != nil {
fmt.Printf("⚠️ Invalid GPU argument - not a number: %s", gpu)
os.Exit(1)
}
gpuSplitInt = append(gpuSplitInt, asInt)
}
printBanner()
gpuInfo, err := getGPUInfo()
// See if we just want to list the deviecs
if *listDevices {
for key := range gpuInfo {
fmt.Printf("\n⚡ GPU %d", key)
fmt.Printf("\nPlatform: %s", gpuInfo[key].platformName)
fmt.Printf("\nVendor: %s", gpuInfo[key].vendor)
fmt.Printf("\nDriver: %s", gpuInfo[key].driverVersion)
}
fmt.Printf("\n")
os.Exit(0)
}
found := false
var devicesToUse []opencl.Device
if err != nil {
fmt.Printf("\n🚨 No GPU Found!")
fmt.Printf("\nThis error is safe to ignore if you intended to generate PoW on CPU only")
fmt.Printf("\nOtherwise you may want to check your GPU drivers and ensure it is properly installed, as well as ensure your device supports OpenCL 2.0\n\n")
} else {
for key := range gpuInfo {
if !misc.Contains(gpuSplitInt, key) {
continue
}
found = true
fmt.Printf("\n⚡ Using GPU %d", key)
fmt.Printf("\nPlatform: %s", gpuInfo[key].platformName)
fmt.Printf("\nVendor: %s", gpuInfo[key].vendor)
fmt.Printf("\nDriver: %s", gpuInfo[key].driverVersion)
devicesToUse = append(devicesToUse, gpuInfo[key].device)
}
fmt.Printf("\n")
if !found {
fmt.Printf("\n🚨 No GPU Found or Invalid GPU Selected!")
fmt.Printf("\nThis error is safe to ignore if you intended to generate PoW on CPU only")
fmt.Printf("\nOtherwise you may want to check your GPU drivers and ensure it is properly installed, as well as ensure your device supports OpenCL 2.0\n\n")
}
}
if *gpuOnly && found {
fmt.Printf("\nOnly using GPU for work_generate...\n\n")
} else if !found {
fmt.Printf("\nOnly using CPU for work_generate...\n\n")
} else {
fmt.Printf("\nUsing GPU+CPU for work_generate...\n\n")
}
// Check benchmark
if *benchmark > 0 {
work.RunBenchmark(*benchmark, *benchmarkDifficulty, *gpuOnly, devicesToUse)
os.Exit(0)
}
// Define context
ctx, cancel := context.WithCancel(context.Background())
gql.InitGQLClient(GraphQLURL)
// Handle interrupts gracefully
SetupCloseHandler(ctx, cancel)
// Create WS Service
WSService = websocket.NewWebsocketService(WSUrl, *maxDifficulty, *minDifficulty, *noPrecache)
// Loop to get username and password and login
for {
// Get username/password
reader := bufio.NewReader(os.Stdin)
var email string
if *argEmail == "" {
fmt.Print("➡️ Enter Email: ")
rawEmail, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("\n⚠️ Error reading email")
continue
}
email = strings.TrimSpace(rawEmail)
if !validation.IsValidEmail(email) {
fmt.Printf("\n⚠️ Invalid email\n\n")
continue
}
} else {
if !validation.IsValidEmail(*argEmail) {
fmt.Printf("\n⚠️ Invalid email\n\n")
os.Exit(1)
}
email = *argEmail
}
var password string
if *argPassword == "" {
fmt.Print("➡️ Enter Password: ")
bytePassword, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
fmt.Printf("\n⚠️ Error reading password")
continue
}
password = strings.TrimSpace(string(bytePassword))
} else {
password = *argPassword
}
// Login
fmt.Printf("\n\n🔒 Logging in...")
resp, gqlErr := gql.Login(ctx, email, password)
if gqlErr == gql.InvalidUsernamePasssword {
fmt.Printf("\n❌ Invalid email or password\n\n")
if *argPassword != "" {
os.Exit(1)
}
continue
} else if gqlErr == gql.ServerError {
fmt.Printf("\n💥 Error reaching server, try again later\n")
os.Exit(1)
}
fmt.Printf("\n\n🔓 Successfully logged in as %s\n\n", email)
WSService.SetAuthToken(resp.Login.Token)
break
}
// Setup a cron job to auto-update auth tokens
scheduler := gocron.NewScheduler(time.UTC)
scheduler.Every(1).Hour().Do(func() {
authToken, err := gql.RefreshToken(ctx, WSService.AuthToken)
if err == nil {
WSService.SetAuthToken(authToken)
}
})
scheduler.StartAt(time.Now().Add(time.Hour))
scheduler.StartAsync()
fmt.Printf("\n🚀 Initiating connection to BoomPOW...")
// Create work processor
workProcessor := work.NewWorkProcessor(WSService, *gpuOnly, devicesToUse)
workProcessor.StartAsync()
WSService.StartWSClient(ctx, workProcessor.WorkQueueChan, workProcessor.Queue)
}