/
stake.go
428 lines (364 loc) · 12.7 KB
/
stake.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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright (c) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package udb
import (
"bytes"
"sync"
"time"
"decred.org/dcrwallet/v2/errors"
"decred.org/dcrwallet/v2/wallet/walletdb"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/wire"
)
// sstxRecord is the structure for a stored SStx.
type sstxRecord struct {
tx *dcrutil.Tx
ts time.Time
voteBitsSet bool // Removed in version 3
voteBits uint16 // Removed in version 3
voteBitsExt []byte // Removed in version 3
}
// TicketStatus is the current status of a stake pool ticket.
type TicketStatus uint8
const (
// TSImmatureOrLive indicates that the ticket is either
// live or immature.
TSImmatureOrLive = iota
// TSVoted indicates that the ticket was spent as a vote.
TSVoted
// TSMissed indicates that the ticket was spent as a
// revocation.
TSMissed
)
// PoolTicket is a 73-byte struct that is used to preserve user's
// ticket information when they have an account at the stake pool.
type PoolTicket struct {
Ticket chainhash.Hash
HeightTicket uint32 // Not used or guaranteed to be correct
Status TicketStatus
HeightSpent uint32
SpentBy chainhash.Hash
}
// StakePoolUser is a list of tickets for a given user (P2SH
// address) in the stake pool.
type StakePoolUser struct {
Tickets []*PoolTicket
InvalidTickets []*chainhash.Hash
}
// StakeStore represents a safely accessible database of
// stake transactions.
type StakeStore struct {
Params *chaincfg.Params
Manager *Manager
ownedSStxs map[chainhash.Hash]struct{}
mtx sync.RWMutex // only protects ownedSStxs
}
// checkHashInStore checks if a hash exists in ownedSStxs.
func (s *StakeStore) checkHashInStore(hash *chainhash.Hash) bool {
_, exists := s.ownedSStxs[*hash]
return exists
}
// OwnTicket returns whether the ticket is tracked by the stake manager.
func (s *StakeStore) OwnTicket(hash *chainhash.Hash) bool {
s.mtx.RLock()
owned := s.checkHashInStore(hash)
s.mtx.RUnlock()
return owned
}
// addHashToStore adds a hash into ownedSStxs.
func (s *StakeStore) addHashToStore(hash *chainhash.Hash) {
s.ownedSStxs[*hash] = struct{}{}
}
// insertSStx inserts an SStx into the store.
func (s *StakeStore) insertSStx(ns walletdb.ReadWriteBucket, sstx *dcrutil.Tx) error {
// If we already have the SStx, no need to
// try to include twice.
exists := s.checkHashInStore(sstx.Hash())
if exists {
log.Tracef("Attempted to insert SStx %v into the stake store, "+
"but the SStx already exists.", sstx.Hash())
return nil
}
record := &sstxRecord{
tx: sstx,
ts: time.Now(),
}
// Add the SStx to the database.
err := putSStxRecord(ns, record, DBVersion)
if err != nil {
return err
}
// Add the SStx's hash to the internal list in the store.
s.addHashToStore(sstx.Hash())
return nil
}
// InsertSStx is the exported version of insertSStx that is safe for concurrent
// access.
func (s *StakeStore) InsertSStx(ns walletdb.ReadWriteBucket, sstx *dcrutil.Tx) error {
s.mtx.Lock()
err := s.insertSStx(ns, sstx)
s.mtx.Unlock()
return err
}
// dumpSStxHashes dumps the hashes of all owned SStxs. Note
// that this doesn't use the DB.
func (s *StakeStore) dumpSStxHashes() []chainhash.Hash {
// Copy the hash list of sstxs. You could pass the pointer
// directly but you risk that the size of the internal
// ownedSStxs is later modified while the end user is
// working with the returned list.
ownedSStxs := make([]chainhash.Hash, len(s.ownedSStxs))
itr := 0
for hash := range s.ownedSStxs {
ownedSStxs[itr] = hash
itr++
}
return ownedSStxs
}
// DumpSStxHashes returns the hashes of all wallet ticket purchase transactions.
func (s *StakeStore) DumpSStxHashes() []chainhash.Hash {
defer s.mtx.RUnlock()
s.mtx.RLock()
return s.dumpSStxHashes()
}
// dumpSStxHashes dumps the hashes of all owned SStxs for some address.
func (s *StakeStore) dumpSStxHashesForAddress(ns walletdb.ReadBucket, addr stdaddr.Address) ([]chainhash.Hash, error) {
// Extract the HASH160 script hash; if it's not 20 bytes
// long, return an error.
var hash160 []byte
switch addr := addr.(type) {
case stdaddr.Hash160er:
hash160 = addr.Hash160()[:]
default:
err := errors.Errorf("cannot get hash160 from address %v", addr)
return nil, errors.E(errors.Invalid, err)
}
_, addrIsP2SH := addr.(*stdaddr.AddressScriptHashV0)
allTickets := s.dumpSStxHashes()
var ticketsForAddr []chainhash.Hash
// Access the database and store the result locally.
for _, h := range allTickets {
thisHash160, p2sh, err := fetchSStxRecordSStxTicketHash160(ns, &h, DBVersion)
if err != nil {
return nil, errors.E(errors.IO, err)
}
if addrIsP2SH != p2sh {
continue
}
if bytes.Equal(hash160, thisHash160) {
ticketsForAddr = append(ticketsForAddr, h)
}
}
return ticketsForAddr, nil
}
// DumpSStxHashesForAddress returns the hashes of all wallet ticket purchase
// transactions for an address.
func (s *StakeStore) DumpSStxHashesForAddress(ns walletdb.ReadBucket, addr stdaddr.Address) ([]chainhash.Hash, error) {
defer s.mtx.RUnlock()
s.mtx.RLock()
return s.dumpSStxHashesForAddress(ns, addr)
}
// sstxAddress returns the address for a given ticket.
func (s *StakeStore) sstxAddress(ns walletdb.ReadBucket, hash *chainhash.Hash) (stdaddr.Address, error) {
// Access the database and store the result locally.
thisHash160, p2sh, err := fetchSStxRecordSStxTicketHash160(ns, hash, DBVersion)
if err != nil {
return nil, err
}
var addr stdaddr.Address
if p2sh {
addr, err = stdaddr.NewAddressScriptHashV0FromHash(thisHash160, s.Params)
} else {
addr, err = stdaddr.NewAddressPubKeyHashEcdsaSecp256k1V0(thisHash160, s.Params)
}
if err != nil {
return nil, err
}
return addr, nil
}
// SStxAddress is the exported, concurrency safe version of sstxAddress.
func (s *StakeStore) SStxAddress(ns walletdb.ReadBucket, hash *chainhash.Hash) (stdaddr.Address, error) {
return s.sstxAddress(ns, hash)
}
// TicketPurchase returns the ticket purchase transaction recorded in the "stake
// manager" portion of the DB.
//
// TODO: This is redundant and should be looked up in from the transaction
// manager. Left for now for compatibility.
func (s *StakeStore) TicketPurchase(dbtx walletdb.ReadTx, hash *chainhash.Hash) (*wire.MsgTx, error) {
ns := dbtx.ReadBucket(wstakemgrBucketKey)
ticketRecord, err := fetchSStxRecord(ns, hash, DBVersion)
if err != nil {
return nil, err
}
return ticketRecord.tx.MsgTx(), nil
}
// updateStakePoolUserTickets updates a stake pool ticket for a given user.
// If the ticket does not currently exist in the database, it adds it. If it
// does exist (the ticket hash exists), it replaces the old record.
func (s *StakeStore) updateStakePoolUserTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *PoolTicket) error {
// Address must be a StakeAddress with support for the Hash160 method.
var hash160 *[20]byte
switch user := user.(type) {
case interface {
stdaddr.StakeAddress
stdaddr.Hash160er
}:
hash160 = user.Hash160()
default:
return errors.E(errors.Invalid, errors.Errorf("voting address type %T", user))
}
return updateStakePoolUserTickets(ns, *hash160, ticket)
}
// UpdateStakePoolUserTickets is the exported and concurrency safe form of
// updateStakePoolUserTickets.
func (s *StakeStore) UpdateStakePoolUserTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *PoolTicket) error {
return s.updateStakePoolUserTickets(ns, user, ticket)
}
// removeStakePoolUserInvalTickets prepares the user.Address and asks stakedb
// to remove the formerly invalid tickets.
func (s *StakeStore) removeStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *chainhash.Hash) error {
// Address must be a StakeAddress with support for the Hash160 method.
var hash160 *[20]byte
switch user := user.(type) {
case interface {
stdaddr.StakeAddress
Hash160() *[20]byte
}:
hash160 = user.Hash160()
default:
return errors.E(errors.Invalid, errors.Errorf("voting address type %T", user))
}
return removeStakePoolInvalUserTickets(ns, *hash160, ticket)
}
// RemoveStakePoolUserInvalTickets is the exported and concurrency safe form of
// removetStakePoolUserInvalTickets.
func (s *StakeStore) RemoveStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *chainhash.Hash) error {
return s.removeStakePoolUserInvalTickets(ns, user, ticket)
}
// updateStakePoolUserInvalTickets updates the list of invalid stake pool
// tickets for a given user. If the ticket does not currently exist in the
// database, it adds it.
func (s *StakeStore) updateStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *chainhash.Hash) error {
// Address must be a StakeAddress with support for the Hash160 method.
var hash160 *[20]byte
switch user := user.(type) {
case interface {
stdaddr.StakeAddress
stdaddr.Hash160er
}:
hash160 = user.Hash160()
default:
return errors.E(errors.Invalid, errors.Errorf("voting address type %T", user))
}
return updateStakePoolInvalUserTickets(ns, *hash160, ticket)
}
// UpdateStakePoolUserInvalTickets is the exported and concurrency safe form of
// updateStakePoolUserInvalTickets.
func (s *StakeStore) UpdateStakePoolUserInvalTickets(ns walletdb.ReadWriteBucket, user stdaddr.Address, ticket *chainhash.Hash) error {
return s.updateStakePoolUserInvalTickets(ns, user, ticket)
}
func stakePoolUserInfo(ns walletdb.ReadBucket, user stdaddr.Address) (*StakePoolUser, error) {
// Address must be a StakeAddress with support for the Hash160 method.
var hash160 *[20]byte
switch user := user.(type) {
case interface {
stdaddr.StakeAddress
stdaddr.Hash160er
}:
hash160 = user.Hash160()
default:
return nil, errors.E(errors.Invalid, errors.Errorf("voting address type %T", user))
}
stakePoolUser := new(StakePoolUser)
// Catch missing user errors below and blank out the stake
// pool user information for the section if the user has
// no entries.
missingValidTickets, missingInvalidTickets := false, false
userTickets, err := fetchStakePoolUserTickets(ns, *hash160)
if err != nil {
missingValidTickets = errors.Is(err, errors.NotExist)
if !missingValidTickets {
return nil, err
}
}
if missingValidTickets {
userTickets = make([]*PoolTicket, 0)
}
invalTickets, err := fetchStakePoolUserInvalTickets(ns, *hash160)
if err != nil {
if errors.Is(err, errors.NotExist) {
missingInvalidTickets = true
}
if !missingInvalidTickets {
return nil, err
}
}
if missingInvalidTickets {
invalTickets = make([]*chainhash.Hash, 0)
}
stakePoolUser.Tickets = userTickets
stakePoolUser.InvalidTickets = invalTickets
return stakePoolUser, nil
}
// StakePoolUserInfo returns the stake pool user information for a given stake
// pool user, keyed to their P2SH voting address.
func (s *StakeStore) StakePoolUserInfo(ns walletdb.ReadBucket, user stdaddr.Address) (*StakePoolUser, error) {
return stakePoolUserInfo(ns, user)
}
// loadManager returns a new stake manager that results from loading it from
// the passed opened database. The public passphrase is required to decrypt the
// public keys.
func (s *StakeStore) loadOwnedSStxs(ns walletdb.ReadBucket) error {
// Regenerate the list of tickets.
// Perform all database lookups in a read-only view.
ticketList := make(map[chainhash.Hash]struct{})
// Open the sstx records database.
bucket := ns.NestedReadBucket(sstxRecordsBucketName)
// Store each key sequentially.
err := bucket.ForEach(func(k []byte, v []byte) error {
var errNewHash error
var hash *chainhash.Hash
hash, errNewHash = chainhash.NewHash(k)
if errNewHash != nil {
return errNewHash
}
ticketList[*hash] = struct{}{}
return nil
})
if err != nil {
return err
}
s.ownedSStxs = ticketList
return nil
}
// newStakeStore initializes a new stake store with the given parameters.
func newStakeStore(params *chaincfg.Params, manager *Manager) *StakeStore {
return &StakeStore{
Params: params,
Manager: manager,
ownedSStxs: make(map[chainhash.Hash]struct{}),
}
}
// openStakeStore loads an existing stake manager from the given namespace,
// waddrmgr, and network parameters.
//
// A NotExist error is returned returned when the stake store is not written to
// the db.
func openStakeStore(ns walletdb.ReadBucket, manager *Manager, params *chaincfg.Params) (*StakeStore, error) {
// Return an error if the manager has NOT already been created in the
// given database namespace.
if !stakeStoreExists(ns) {
return nil, errors.E(errors.NotExist, "no stake store")
}
ss := newStakeStore(params, manager)
err := ss.loadOwnedSStxs(ns)
if err != nil {
return nil, err
}
return ss, nil
}