forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tickets.go
324 lines (291 loc) · 9.57 KB
/
tickets.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
// Copyright (c) 2016-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"encoding/hex"
"time"
"github.com/decred/bitset"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/apperrors"
"github.com/decred/dcrwallet/chain"
"github.com/decred/dcrwallet/wallet/udb"
"github.com/decred/dcrwallet/walletdb"
)
// GenerateVoteTx creates a vote transaction for a chosen ticket purchase hash
// using the provided votebits. The ticket purchase transaction must be stored
// by the wallet.
func (w *Wallet) GenerateVoteTx(blockHash *chainhash.Hash, height int32, ticketHash *chainhash.Hash, voteBits stake.VoteBits) (*wire.MsgTx, error) {
var vote *wire.MsgTx
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
ticketPurchase, err := w.TxStore.Tx(txmgrNs, ticketHash)
if err != nil {
return err
}
if ticketPurchase == nil {
const str = "ticket purchase transaction not found"
return apperrors.New(apperrors.ErrSStxNotFound, str)
}
vote, err = createUnsignedVote(ticketHash, ticketPurchase,
height, blockHash, voteBits, w.subsidyCache, w.chainParams)
if err != nil {
return err
}
return w.signVote(addrmgrNs, ticketPurchase, vote)
})
return vote, err
}
// LiveTicketHashes returns the hashes of live tickets that have been purchased
// by the wallet.
func (w *Wallet) LiveTicketHashes(chainClient *chain.RPCClient, includeImmature bool) ([]chainhash.Hash, error) {
var ticketHashes []chainhash.Hash
var maybeLive []*chainhash.Hash
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
_, tipHeight := w.TxStore.MainChainTip(txmgrNs)
expiryConfs := int32(w.chainParams.TicketExpiry) +
int32(w.chainParams.TicketMaturity) + 1
it := w.TxStore.IterateTickets(dbtx)
for it.Next() {
// Tickets that are mined at a height beyond the expiry height can
// not be live.
if confirmed(expiryConfs, it.Block.Height, tipHeight) {
continue
}
// Tickets that have not reached ticket maturity are immature.
// Exclude them unless the caller requested to include immature
// tickets.
if !confirmed(int32(w.chainParams.TicketMaturity)+1, it.Block.Height,
tipHeight) {
if includeImmature {
ticketHashes = append(ticketHashes, it.Hash)
}
continue
}
// The ticket may be live. Because the selected state of tickets is
// not yet known by the wallet, this must be queried over RPC. Add
// this hash to a slice of ticket purchase hashes to check later.
hash := it.Hash
maybeLive = append(maybeLive, &hash)
}
return it.Err()
})
if err != nil {
return nil, err
}
// If there are no possibly live tickets to check, ticketHashes contains all
// of the results.
if len(maybeLive) == 0 {
return ticketHashes, nil
}
// Use RPC to query which of the possibly-live tickets are really live.
liveBitsetHex, err := chainClient.ExistsLiveTickets(maybeLive)
if err != nil {
return nil, err
}
liveBitset, err := hex.DecodeString(liveBitsetHex)
if err != nil {
return nil, err
}
for i, h := range maybeLive {
if bitset.Bytes(liveBitset).Get(i) {
ticketHashes = append(ticketHashes, *h)
}
}
return ticketHashes, nil
}
// TicketHashesForVotingAddress returns the hashes of all tickets with voting
// rights delegated to votingAddr. This function does not return the hashes of
// pruned tickets.
func (w *Wallet) TicketHashesForVotingAddress(votingAddr dcrutil.Address) ([]chainhash.Hash, error) {
var ticketHashes []chainhash.Hash
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
stakemgrNs := tx.ReadBucket(wstakemgrNamespaceKey)
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
var err error
ticketHashes, err = w.StakeMgr.DumpSStxHashesForAddress(
stakemgrNs, votingAddr)
if err != nil {
return err
}
// Exclude the hash if the transaction is not saved too. No
// promises of hash order are given (and at time of writing,
// they are copies of iterators of a Go map in wstakemgr) so
// when one must be removed, replace it with the last and
// decrease the len.
for i := 0; i < len(ticketHashes); {
if w.TxStore.ExistsTx(txmgrNs, &ticketHashes[i]) {
i++
continue
}
ticketHashes[i] = ticketHashes[len(ticketHashes)-1]
ticketHashes = ticketHashes[:len(ticketHashes)-1]
}
return nil
})
return ticketHashes, err
}
// updateStakePoolInvalidTicket properly updates a previously marked Invalid pool ticket,
// it then creates a new entry in the validly tracked pool ticket db.
func (w *Wallet) updateStakePoolInvalidTicket(stakemgrNs walletdb.ReadWriteBucket,
addr dcrutil.Address, ticket *chainhash.Hash, ticketHeight int64) error {
err := w.StakeMgr.RemoveStakePoolUserInvalTickets(stakemgrNs, addr, ticket)
if err != nil {
return err
}
poolTicket := &udb.PoolTicket{
Ticket: *ticket,
HeightTicket: uint32(ticketHeight),
Status: udb.TSImmatureOrLive,
}
return w.StakeMgr.UpdateStakePoolUserTickets(stakemgrNs, addr, poolTicket)
}
// AddTicket adds a ticket transaction to the stake manager. It is not added to
// the transaction manager because it is unknown where the transaction belongs
// on the blockchain. It will be used to create votes.
func (w *Wallet) AddTicket(ticket *wire.MsgTx) error {
_, err := stake.IsSStx(ticket)
if err != nil {
return err
}
return walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
stakemgrNs := tx.ReadWriteBucket(wstakemgrNamespaceKey)
// Insert the ticket to be tracked and voted.
err := w.StakeMgr.InsertSStx(stakemgrNs, dcrutil.NewTx(ticket))
if err != nil {
return err
}
if w.stakePoolEnabled {
// Pluck the ticketaddress to identify the stakepool user.
pkVersion := ticket.TxOut[0].Version
pkScript := ticket.TxOut[0].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkVersion,
pkScript, w.ChainParams())
if err != nil {
return err
}
ticketHash := ticket.TxHash()
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
rawTx, err := chainClient.GetRawTransactionVerbose(&ticketHash)
if err != nil {
return err
}
// Update the pool ticket stake. This will include removing it from the
// invalid slice and adding a ImmatureOrLive ticket to the valid ones.
err = w.updateStakePoolInvalidTicket(stakemgrNs, addrs[0], &ticketHash,
rawTx.BlockHeight)
if err != nil {
return err
}
}
return nil
})
}
// RevokeTickets creates and sends revocation transactions for any unrevoked
// missed and expired tickets. The wallet must be unlocked to generate any
// revocations.
func (w *Wallet) RevokeTickets(chainClient *chain.RPCClient) error {
var ticketHashes []chainhash.Hash
var tipHash chainhash.Hash
var tipHeight int32
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(wtxmgrNamespaceKey)
var err error
tipHash, tipHeight = w.TxStore.MainChainTip(ns)
ticketHashes, err = w.TxStore.UnspentTickets(tx, tipHeight, false)
return err
})
if err != nil {
return err
}
ticketHashPtrs := make([]*chainhash.Hash, len(ticketHashes))
for i := range ticketHashes {
ticketHashPtrs[i] = &ticketHashes[i]
}
expiredFuture := chainClient.ExistsExpiredTicketsAsync(ticketHashPtrs)
missedFuture := chainClient.ExistsMissedTicketsAsync(ticketHashPtrs)
expiredBitsHex, err := expiredFuture.Receive()
if err != nil {
return err
}
missedBitsHex, err := missedFuture.Receive()
if err != nil {
return err
}
expiredBits, err := hex.DecodeString(expiredBitsHex)
if err != nil {
return err
}
missedBits, err := hex.DecodeString(missedBitsHex)
if err != nil {
return err
}
revokableTickets := make([]*chainhash.Hash, 0, len(ticketHashes))
for i, p := range ticketHashPtrs {
if bitset.Bytes(expiredBits).Get(i) || bitset.Bytes(missedBits).Get(i) {
revokableTickets = append(revokableTickets, p)
}
}
feePerKb := w.RelayFee()
revocations := make([]*wire.MsgTx, 0, len(revokableTickets))
err = walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
for _, ticketHash := range revokableTickets {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
ticketPurchase, err := w.TxStore.Tx(txmgrNs, ticketHash)
if err != nil {
return err
}
revocation, err := createUnsignedRevocation(ticketHash,
ticketPurchase, feePerKb)
if err != nil {
return err
}
err = w.signRevocation(addrmgrNs, ticketPurchase, revocation)
if err != nil {
return err
}
revocations = append(revocations, revocation)
}
return nil
})
if err != nil {
return err
}
for i, revocation := range revocations {
rec, err := udb.NewTxRecordFromMsgTx(revocation, time.Now())
if err != nil {
return err
}
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
err = w.StakeMgr.StoreRevocationInfo(dbtx, revokableTickets[i],
&rec.Hash, &tipHash, tipHeight)
if err != nil {
return err
}
// Could be more efficient by avoiding processTransaction, as we
// know it is a revocation.
err = w.processTransactionRecord(dbtx, rec, nil, nil)
if err != nil {
return err
}
_, err = chainClient.SendRawTransaction(revocation, true)
return err
})
if err != nil {
return err
}
log.Infof("Revoked ticket %v with revocation %v", revokableTickets[i],
&rec.Hash)
}
return nil
}