-
Notifications
You must be signed in to change notification settings - Fork 153
/
tb.go
354 lines (307 loc) · 8.73 KB
/
tb.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Copyright (c) 2018-2023 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package ticketbuyer
import (
"context"
"runtime/trace"
"sync"
"decred.org/dcrwallet/v4/errors"
"decred.org/dcrwallet/v4/internal/vsp"
"decred.org/dcrwallet/v4/wallet"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/wire"
)
const minconf = 1
// Config modifies the behavior of TB.
type Config struct {
BuyTickets bool
// Account to buy tickets from
Account uint32
// Account to derive voting addresses from; overridden by VotingAddr
VotingAccount uint32
// Minimum amount to maintain in purchasing account
Maintain dcrutil.Amount
// Address to assign voting rights; overrides VotingAccount
VotingAddr stdaddr.StakeAddress
// Commitment address for stakepool fees
PoolFeeAddr stdaddr.StakeAddress
// Stakepool fee percentage (between 0-100)
PoolFees float64
// Limit maximum number of purchased tickets per block
Limit int
// CSPP-related options
Mixing bool
MixedAccount uint32
MixedAccountBranch uint32
TicketSplitAccount uint32
ChangeAccount uint32
MixChange bool
// VSP client
VSP *vsp.Client
}
// TB is an automated ticket buyer, buying as many tickets as possible given an
// account's available balance. TB may be configured to buy tickets for any
// arbitrary voting address or (optional) stakepool.
type TB struct {
wallet *wallet.Wallet
cfg Config
mu sync.Mutex
}
// New returns a new TB to buy tickets from a wallet using the default config.
func New(w *wallet.Wallet) *TB {
return &TB{wallet: w}
}
// Run executes the ticket buyer. If the private passphrase is incorrect, or
// ever becomes incorrect due to a wallet passphrase change, Run exits with an
// errors.Passphrase error.
func (tb *TB) Run(ctx context.Context, passphrase []byte) error {
if len(passphrase) > 0 {
err := tb.wallet.Unlock(ctx, passphrase, nil)
if err != nil {
return err
}
}
c := tb.wallet.NtfnServer.MainTipChangedNotifications()
defer c.Done()
ctx, outerCancel := context.WithCancel(ctx)
defer outerCancel()
var fatal error
var fatalMu sync.Mutex
var nextIntervalStart, expiry int32
var cancels []func()
for {
select {
case <-ctx.Done():
defer outerCancel()
fatalMu.Lock()
err := fatal
fatalMu.Unlock()
if err != nil {
return err
}
return ctx.Err()
case n := <-c.C:
if len(n.AttachedBlocks) == 0 {
continue
}
tip := n.AttachedBlocks[len(n.AttachedBlocks)-1]
w := tb.wallet
// Don't perform any actions while transactions are not synced through
// the tip block.
rp, err := w.RescanPoint(ctx)
if err != nil {
return err
}
if rp != nil {
log.Debugf("Skipping autobuyer actions: transactions are not synced")
continue
}
tipHeader, err := w.BlockHeader(ctx, tip)
if err != nil {
log.Error(err)
continue
}
height := int32(tipHeader.Height)
// Cancel any ongoing ticket purchases which are buying
// at an old ticket price or are no longer able to
// create mined tickets the window.
if height+2 >= nextIntervalStart {
for i, cancel := range cancels {
cancel()
cancels[i] = nil
}
cancels = cancels[:0]
intervalSize := int32(w.ChainParams().StakeDiffWindowSize)
currentInterval := height / intervalSize
nextIntervalStart = (currentInterval + 1) * intervalSize
// Skip this purchase when no more tickets may be purchased in the interval and
// the next sdiff is unknown. The earliest any ticket may be mined is two
// blocks from now, with the next block containing the split transaction
// that the ticket purchase spends.
if height+2 == nextIntervalStart {
log.Debugf("Skipping purchase: next sdiff interval starts soon")
continue
}
// Set expiry to prevent tickets from being mined in the next
// sdiff interval. When the next block begins the new interval,
// the ticket is being purchased for the next interval; therefore
// increment expiry by a full sdiff window size to prevent it
// being mined in the interval after the next.
expiry = nextIntervalStart
if height+1 == nextIntervalStart {
expiry += intervalSize
}
}
// Read config
tb.mu.Lock()
cfg := tb.cfg
tb.mu.Unlock()
multiple := 1
if cfg.Mixing {
multiple = cfg.Limit
cfg.Limit = 1
}
cancelCtx, cancel := context.WithCancel(ctx)
cancels = append(cancels, cancel)
buyTickets := func() {
err := tb.buy(cancelCtx, passphrase, tipHeader, expiry, &cfg)
if err != nil {
switch {
// silence these errors
case errors.Is(err, errors.InsufficientBalance):
case errors.Is(err, context.Canceled):
case errors.Is(err, context.DeadlineExceeded):
default:
log.Errorf("Ticket purchasing failed: %v", err)
}
if errors.Is(err, errors.Passphrase) {
fatalMu.Lock()
fatal = err
fatalMu.Unlock()
outerCancel()
}
}
}
for i := 0; cfg.BuyTickets && i < multiple; i++ {
go buyTickets()
}
go func() {
err := tb.mixChange(ctx, &cfg)
if err != nil {
log.Error(err)
}
}()
}
}
}
func (tb *TB) buy(ctx context.Context, passphrase []byte, tip *wire.BlockHeader, expiry int32,
cfg *Config) error {
ctx, task := trace.NewTask(ctx, "ticketbuyer.buy")
defer task.End()
tb.mu.Lock()
buyTickets := tb.cfg.BuyTickets
tb.mu.Unlock()
if !buyTickets {
return nil
}
w := tb.wallet
// Unable to publish any transactions if the network backend is unset.
n, err := w.NetworkBackend()
if err != nil {
return err
}
if len(passphrase) > 0 {
// Ensure wallet is unlocked with the current passphrase. If the passphase
// is changed, the Run exits and TB must be restarted with the new
// passphrase.
err = w.Unlock(ctx, passphrase, nil)
if err != nil {
return err
}
}
// Read config
account := cfg.Account
maintain := cfg.Maintain
votingAddr := cfg.VotingAddr
poolFeeAddr := cfg.PoolFeeAddr
poolFees := cfg.PoolFees
limit := cfg.Limit
mixing := cfg.Mixing
votingAccount := cfg.VotingAccount
mixedAccount := cfg.MixedAccount
mixedBranch := cfg.MixedAccountBranch
splitAccount := cfg.TicketSplitAccount
changeAccount := cfg.ChangeAccount
minconf := int32(minconf)
if mixing {
minconf = 2
}
sdiff, err := w.NextStakeDifficultyAfterHeader(ctx, tip)
if err != nil {
return err
}
// Determine how many tickets to buy
var buy int
if maintain != 0 {
bal, err := w.AccountBalance(ctx, account, minconf)
if err != nil {
return err
}
spendable := bal.Spendable
if spendable < maintain {
log.Debugf("Skipping purchase: low available balance")
return nil
}
spendable -= maintain
buy = int(spendable / sdiff)
if buy == 0 {
log.Debugf("Skipping purchase: low available balance")
return nil
}
max := int(w.ChainParams().MaxFreshStakePerBlock)
if buy > max {
buy = max
}
} else {
buy = int(w.ChainParams().MaxFreshStakePerBlock)
}
if limit == 0 && mixing {
buy = 1
} else if limit > 0 && buy > limit {
buy = limit
}
purchaseTicketReq := &wallet.PurchaseTicketsRequest{
Count: buy,
SourceAccount: account,
VotingAddress: votingAddr,
MinConf: minconf,
Expiry: expiry,
// CSPP
Mixing: mixing,
VotingAccount: votingAccount,
MixedAccount: mixedAccount,
MixedAccountBranch: mixedBranch,
MixedSplitAccount: splitAccount,
ChangeAccount: changeAccount,
// VSPs
VSPAddress: poolFeeAddr,
VSPFees: poolFees,
}
// If VSP is configured, we need to set the methods for vsp fee processment.
if tb.cfg.VSP != nil {
purchaseTicketReq.VSPFeePaymentProcess = tb.cfg.VSP.Process
purchaseTicketReq.VSPFeePercent = tb.cfg.VSP.FeePercentage
}
tix, err := w.PurchaseTickets(ctx, n, purchaseTicketReq)
if tix != nil {
for _, hash := range tix.TicketHashes {
log.Infof("Purchased ticket %v at stake difficulty %v", hash, sdiff)
}
}
return err
}
// AccessConfig runs f with the current config passed as a parameter. The
// config is protected by a mutex and this function is safe for concurrent
// access to read or modify the config. It is unsafe to leak a pointer to the
// config, but a copy of *cfg is legal.
func (tb *TB) AccessConfig(f func(cfg *Config)) {
tb.mu.Lock()
f(&tb.cfg)
tb.mu.Unlock()
}
func (tb *TB) mixChange(ctx context.Context, cfg *Config) error {
// Read config
mixing := cfg.Mixing
mixedAccount := cfg.MixedAccount
mixedBranch := cfg.MixedAccountBranch
changeAccount := cfg.ChangeAccount
mixChange := cfg.MixChange
if !mixChange || !mixing {
return nil
}
ctx, task := trace.NewTask(ctx, "ticketbuyer.mixChange")
defer task.End()
return tb.wallet.MixAccount(ctx, changeAccount, mixedAccount, mixedBranch)
}