This repository has been archived by the owner on May 16, 2019. It is now read-only.
forked from cjepson/dcrticketbuyer
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
235 lines (208 loc) · 6.25 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
// Copyright (c) 2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strconv"
"sync/atomic"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrrpcclient"
"github.com/decred/dcrutil"
)
// Global variables are displayed below that are mainly used for the purposes
// of the HTTP server.
var (
// chainHeight is the global chainHeight. It must be accessed with
// atomic operators.
glChainHeight = int64(0)
// glBalance is the global balance. It is updated at start up and
// after every round of ticket purchases. It must be accessed with
// atomic operators.
glBalance = int64(0)
// glTicketPrice is the global ticket price. It is updated at
// start up and after every round of ticket purchases.
glTicketPrice = int64(0)
)
const (
// blockConnChanBuffer is the size of the block connected channel buffer.
blockConnChanBuffer = 100
)
// syncGlobalsStartup syncs the globals for the HTTP server on startup.
func syncGlobalsStartup(dcrdClient *dcrrpcclient.Client,
dcrwClient *dcrrpcclient.Client, cfg *config) error {
_, height, err := dcrdClient.GetBestBlock()
if err != nil {
return err
}
atomic.StoreInt64(&glChainHeight, height)
bal, err := dcrwClient.GetBalanceMinConfType(cfg.AccountName,
0, "spendable")
if err != nil {
return err
}
atomic.StoreInt64(&glBalance, int64(bal))
sd, err := dcrdClient.GetStakeDifficulty()
if err != nil {
return err
}
nsdAmt, err := dcrutil.NewAmount(sd.NextStakeDifficulty)
if err != nil {
return err
}
atomic.StoreInt64(&glTicketPrice, int64(nsdAmt))
return nil
}
func main() {
// Parse the configuration file.
cfg, err := loadConfig()
if err != nil {
fmt.Printf("Failed to load ticketbuyer config: %s\n", err.Error())
os.Exit(1)
}
defer backendLog.Flush()
dcrrpcclient.UseLogger(clientLog)
// Initialize the CSV files for the HTTP server if needed.
if cfg.HTTPSvrPort != 0 {
err := initCsvFiles()
if err != nil {
fmt.Printf("Failed to init https files: %s\n", err.Error())
os.Exit(1)
}
}
// Connect to dcrd RPC server using websockets. Set up the
// notification handler to deliver blocks through a channel.
connectChan := make(chan int64, blockConnChanBuffer)
quit := make(chan struct{})
ntfnHandlersDaemon := dcrrpcclient.NotificationHandlers{
OnBlockConnected: func(serializedBlockHeader []byte, transactions [][]byte) {
var blockHeader wire.BlockHeader
err := blockHeader.Deserialize(bytes.NewReader(serializedBlockHeader))
if err != nil {
log.Errorf("Failed to deserialize block header: %v", err.Error())
return
}
connectChan <- int64(blockHeader.Height)
},
}
var dcrdCerts []byte
if !cfg.DisableClientTLS {
dcrdCerts, err = ioutil.ReadFile(cfg.DcrdCert)
if err != nil {
fmt.Printf("Failed to read dcrd cert file at %s: %s\n", cfg.DcrdCert,
err.Error())
os.Exit(1)
}
}
log.Debugf("Attempting to connect to dcrd RPC %s as user %s "+
"using certificate located in %s",
cfg.DcrdServ, cfg.DcrdUser, cfg.DcrdCert)
connCfgDaemon := &dcrrpcclient.ConnConfig{
Host: cfg.DcrdServ,
Endpoint: "ws",
User: cfg.DcrdUser,
Pass: cfg.DcrdPass,
Certificates: dcrdCerts,
DisableTLS: cfg.DisableClientTLS,
}
dcrdClient, err := dcrrpcclient.New(connCfgDaemon, &ntfnHandlersDaemon)
if err != nil {
fmt.Printf("Failed to start dcrd rpcclient: %s\n", err.Error())
os.Exit(1)
}
// Register for block connection notifications.
if err := dcrdClient.NotifyBlocks(); err != nil {
fmt.Printf("Failed to start register daemon rpc client for "+
"block notifications: %s\n", err.Error())
os.Exit(1)
}
// Connect to the dcrwallet server RPC client.
var dcrwCerts []byte
if !cfg.DisableClientTLS {
dcrwCerts, err = ioutil.ReadFile(cfg.DcrwCert)
if err != nil {
fmt.Printf("Failed to read dcrwallet cert file at %s: %s\n",
cfg.DcrwCert, err.Error())
}
}
connCfgWallet := &dcrrpcclient.ConnConfig{
Host: cfg.DcrwServ,
Endpoint: "ws",
User: cfg.DcrwUser,
Pass: cfg.DcrwPass,
Certificates: dcrwCerts,
DisableTLS: cfg.DisableClientTLS,
}
log.Debugf("Attempting to connect to dcrwallet RPC %s as user %s "+
"using certificate located in %s",
cfg.DcrwServ, cfg.DcrwUser, cfg.DcrwCert)
dcrwClient, err := dcrrpcclient.New(connCfgWallet, nil)
if err != nil {
fmt.Printf("Failed to start dcrw rpcclient: %s\n", err.Error())
os.Exit(1)
}
wi, err := dcrwClient.WalletInfo()
if err != nil {
fmt.Printf("Failed to get WalletInfo on start: %s\n", err.Error())
os.Exit(1)
}
if !wi.DaemonConnected {
log.Warnf("Wallet was not connected to a daemon at start up! " +
"Please ensure wallet has proper connectivity.")
}
if !wi.Unlocked {
log.Warnf("Wallet is not unlocked! You will need to unlock " +
"wallet for tickets to be purchased.")
}
err = syncGlobalsStartup(dcrdClient, dcrwClient, cfg)
if err != nil {
fmt.Printf("Failed to start sync globals on startup: %s\n", err.Error())
os.Exit(1)
}
// Ctrl-C to kill.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
quit <- struct{}{}
}
}()
purchaser, err := newTicketPurchaser(cfg, dcrdClient, dcrwClient)
if err != nil {
fmt.Printf("Failed to start purchaser: %s\n", err.Error())
os.Exit(1)
}
wsm := newPurchaseManager(purchaser, connectChan, quit)
go wsm.blockConnectedHandler()
log.Infof("Daemon and wallet successfully connected, beginning " +
"to purchase tickets")
err = wsm.purchaser.purchase(atomic.LoadInt64(&glChainHeight))
if err != nil {
log.Errorf("Failed to purchase tickets this round: %s",
err.Error())
}
// If the HTTP server is enabled, spin it up and begin
// displaying the front page locally.
if cfg.HTTPSvrPort > 0 {
go func() {
port := strconv.Itoa(cfg.HTTPSvrPort)
http.HandleFunc("/", writeMainGraphs)
http.Handle("/csvdata/", http.StripPrefix("/csvdata/", http.FileServer(http.Dir(cfg.DataDir))))
err := http.ListenAndServe(cfg.HTTPSvrBind+":"+port, nil)
if err != nil {
log.Errorf("Failed to bind http server: %s", err.Error())
}
}()
}
<-quit
close(quit)
dcrdClient.Disconnect()
dcrwClient.Disconnect()
fmt.Printf("\nClosing ticket buyer.\n")
os.Exit(1)
}