forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stake.go
1485 lines (1249 loc) · 39.1 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015 Conformal Systems LLC <info@conformal.com>
* Copyright (c) 2015 The Decred developers
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package wstakemgr
import (
"bytes"
"fmt"
"sync"
"time"
"github.com/decred/dcrd/blockchain"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainec"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
walletchain "github.com/decred/dcrwallet/chain"
"github.com/decred/dcrwallet/waddrmgr"
"github.com/decred/dcrwallet/walletdb"
)
const (
revocationFeeTestNet int64 = 10000
revocationFeeMainNet int64 = 7500000
)
// sstxRecord is the structure for a stored SStx.
type sstxRecord struct {
tx *dcrutil.Tx
ts time.Time
voteBitsSet bool
voteBits uint16
voteBitsExt []byte
}
// ssgenRecord is the structure for a stored SSGen tx. There's no
// real reason to store the actual transaction I don't think,
// the inputs and outputs are all predetermined from the block
// height and the original SStx it references.
type ssgenRecord struct {
blockHash chainhash.Hash
blockHeight uint32
txHash chainhash.Hash
voteBits uint16
ts time.Time
}
// ssrtxRecord is the structure for a stored SSRtx. While the
// ssrtx itself does not include the block hash or block height,
// we still preserve that so that we know the block ntfn that
// informed us that the sstx was missed.
type ssrtxRecord struct {
blockHash chainhash.Hash
blockHeight uint32
txHash chainhash.Hash
ts time.Time
}
// 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
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 {
mtx *sync.Mutex
namespace walletdb.Namespace
Params *chaincfg.Params
Manager *waddrmgr.Manager
chainSvr *walletchain.RPCClient
isClosed bool
ownedSStxs map[chainhash.Hash]struct{}
}
// StakeNotification is the data structure that contains information
// about an SStx (ticket), SSGen (vote), or SSRtx (revocation)
// produced by wallet.
type StakeNotification struct {
TxType int8 // These are the same as in staketx.go of stake, but int8
TxHash chainhash.Hash
BlockHash chainhash.Hash // SSGen only
Height int32 // SSGen only
Amount int64 // SStx only
SStxIn chainhash.Hash // SSGen and SSRtx
VoteBits uint16 // SSGen only
}
// checkHashInStore checks if a hash exists in ownedSStxs.
func (s *StakeStore) checkHashInStore(hash *chainhash.Hash) bool {
_, exists := s.ownedSStxs[*hash]
return exists
}
// CheckHashInStore is the exported version of CheckHashInStore that is
// safe for concurrent access.
func (s *StakeStore) CheckHashInStore(hash *chainhash.Hash) bool {
if s.isClosed {
return false
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.checkHashInStore(hash)
}
// 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(sstx *dcrutil.Tx, voteBits uint16) error {
// If we already have the SStx, no need to
// try to include twice.
exists := s.checkHashInStore(sstx.Sha())
if exists {
log.Tracef("Attempted to insert SStx %v into the stake store, "+
"but the SStx already exists.", sstx.Sha())
return nil
}
record := &sstxRecord{
sstx,
time.Now(),
true,
voteBits,
nil, // TODO Allow for extensible voteBits
}
// Add the SStx to the database.
err := s.namespace.Update(func(tx walletdb.Tx) error {
if putErr := putSStxRecord(tx, record, voteBits); putErr != nil {
return putErr
}
return nil
})
if err != nil {
return err
}
// Add the SStx's hash to the internal list in the store.
s.addHashToStore(sstx.Sha())
return nil
}
// InsertSStx is the exported version of insertSStx that is safe for concurrent
// access.
func (s *StakeStore) InsertSStx(sstx *dcrutil.Tx, voteBits uint16) error {
if s.isClosed {
str := "stake store is closed"
return stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.insertSStx(sstx, voteBits)
}
// sstxVoteBits fetches the intended voteBits for a given SStx. This per-
// ticket voteBits will override the default voteBits set by the wallet.
func (s *StakeStore) sstxVoteBits(sstx *chainhash.Hash) (bool, uint16, error) {
// If we already have the SStx, no need to
// try to include twice.
exists := s.checkHashInStore(sstx)
if !exists {
str := fmt.Sprintf("ticket %v not found in store", sstx)
return false, 0, stakeStoreError(ErrNoExist, str, nil)
}
// Attempt to update the SStx in the database.
voteBitsSet := false
voteBits := uint16(0)
err := s.namespace.View(func(tx walletdb.Tx) error {
var fetchErr error
if voteBitsSet, voteBits, fetchErr = fetchSStxRecordVoteBits(tx,
sstx); fetchErr != nil {
return fetchErr
}
return nil
})
if err != nil {
return voteBitsSet, voteBits, err
}
return voteBitsSet, voteBits, err
}
// SStxVoteBits is the exported version of sstxVoteBits that is
// safe for concurrent access.
func (s *StakeStore) SStxVoteBits(sstx *chainhash.Hash) (bool, uint16, error) {
if s.isClosed {
str := "stake store is closed"
return false, 0, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.sstxVoteBits(sstx)
}
// updateSStxVoteBits updates the intended voteBits for a given SStx. This per-
// ticket voteBits will override the default voteBits set by the wallet.
func (s *StakeStore) updateSStxVoteBits(sstx *chainhash.Hash,
voteBits uint16) error {
// If we already have the SStx, no need to
// try to include twice.
exists := s.checkHashInStore(sstx)
if !exists {
str := fmt.Sprintf("ticket %v not found in store", sstx)
return stakeStoreError(ErrNoExist, str, nil)
}
// Attempt to update the SStx in the database.
err := s.namespace.Update(func(tx walletdb.Tx) error {
if updErr := updateSStxRecordVoteBits(tx, sstx, voteBits); updErr != nil {
return updErr
}
return nil
})
if err != nil {
return err
}
return nil
}
// UpdateSStxVoteBits is the exported version of updateSStxVoteBits that is
// safe for concurrent access.
func (s *StakeStore) UpdateSStxVoteBits(sstx *chainhash.Hash,
voteBits uint16) error {
if s.isClosed {
str := "stake store is closed"
return stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.updateSStxVoteBits(sstx, voteBits)
}
// dumpSStxHashes dumps the hashes of all owned SStxs. Note
// that this doesn't use the DB.
func (s *StakeStore) dumpSStxHashes() []chainhash.Hash {
if s.isClosed {
return nil
}
// 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 is the exported version of dumpSStxHashes that is safe
// for concurrent access.
func (s *StakeStore) DumpSStxHashes() ([]chainhash.Hash, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.dumpSStxHashes(), nil
}
// dumpSStxHashes dumps the hashes of all owned SStxs for some address.
func (s *StakeStore) dumpSStxHashesForAddress(addr dcrutil.Address) ([]chainhash.Hash, error) {
// Extract the HASH160 script hash; if it's not 20 bytes
// long, return an error.
scriptHash := addr.ScriptAddress()
if len(scriptHash) != 20 {
str := "stake store is closed"
return nil, stakeStoreError(ErrInput, str, nil)
}
var err error
allTickets := s.dumpSStxHashes()
var ticketsForAddr []chainhash.Hash
// Access the database and store the result locally.
err = s.namespace.View(func(tx walletdb.Tx) error {
var err error
var thisScrHash []byte
for _, h := range allTickets {
thisScrHash, err = fetchSStxRecordSStxTicketScriptHash(tx, &h)
if err != nil {
return err
}
if bytes.Equal(scriptHash, thisScrHash) {
ticketsForAddr = append(ticketsForAddr, h)
}
}
return nil
})
if err != nil {
str := "failure getting ticket 0th out script hashes from db"
return nil, stakeStoreError(ErrDatabase, str, err)
}
return ticketsForAddr, nil
}
// DumpSStxHashesForAddress is the exported version of dumpSStxHashesForAddress
// that is safe for concurrent access.
func (s *StakeStore) DumpSStxHashesForAddress(addr dcrutil.Address) ([]chainhash.Hash, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.dumpSStxHashesForAddress(addr)
}
// sstxAddress returns the address for a given ticket.
func (s *StakeStore) sstxAddress(hash *chainhash.Hash) (dcrutil.Address, error) {
// Access the database and store the result locally.
var addr dcrutil.Address
err := s.namespace.View(func(tx walletdb.Tx) error {
thisScrHash, errFetch := fetchSStxRecordSStxTicketScriptHash(tx, hash)
if errFetch != nil {
return errFetch
}
var errAddr error
addr, errAddr = dcrutil.NewAddressScriptHashFromHash(thisScrHash,
s.Params)
if errAddr != nil {
return errAddr
}
return nil
})
if err != nil {
str := "failure getting ticket 0th out script hashes from db"
return nil, stakeStoreError(ErrDatabase, str, err)
}
return addr, nil
}
// SStxAddress is the exported, concurrency safe version of sstxAddress.
func (s *StakeStore) SStxAddress(hash *chainhash.Hash) (dcrutil.Address, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.sstxAddress(hash)
}
// dumpSSGenHashes fetches and returns the entire list of votes generated by
// this wallet, including votes that were produced but were never included in
// the blockchain.
func (s *StakeStore) dumpSSGenHashes() ([]chainhash.Hash, error) {
var voteList []chainhash.Hash
err := s.namespace.View(func(tx walletdb.Tx) error {
var errForEach error
// Open the vite records database.
bucket := tx.RootBucket().Bucket(ssgenRecordsBucketName)
// Store each hash sequentially.
errForEach = bucket.ForEach(func(k []byte, v []byte) error {
recs, errDeser := deserializeSSGenRecords(v)
if errDeser != nil {
return errDeser
}
for _, rec := range recs {
voteList = append(voteList, rec.txHash)
}
return nil
})
return errForEach
})
if err != nil {
return nil, err
}
return voteList, nil
}
// DumpSSGenHashes is the exported version of dumpSSGenHashes that is safe
// for concurrent access.
func (s *StakeStore) DumpSSGenHashes() ([]chainhash.Hash, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.dumpSSGenHashes()
}
// dumpSSRtxHashes fetches the entire list of revocations generated by this
// wallet.
func (s *StakeStore) dumpSSRtxHashes() ([]chainhash.Hash, error) {
var revocationList []chainhash.Hash
err := s.namespace.View(func(tx walletdb.Tx) error {
var errForEach error
// Open the revocation records database.
bucket := tx.RootBucket().Bucket(ssrtxRecordsBucketName)
// Store each hash sequentially.
errForEach = bucket.ForEach(func(k []byte, v []byte) error {
rec, errDeser := deserializeSSRtxRecord(v)
if errDeser != nil {
return errDeser
}
revocationList = append(revocationList, rec.txHash)
return nil
})
return errForEach
})
if err != nil {
return nil, err
}
return revocationList, nil
}
// DumpSSRtxHashes is the exported version of dumpSSRtxHashes that is safe
// for concurrent access.
func (s *StakeStore) DumpSSRtxHashes() ([]chainhash.Hash, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.dumpSSRtxHashes()
}
// dumpSSRtxTickets fetches the entire list of tickets spent as revocations
// byt this wallet.
func (s *StakeStore) dumpSSRtxTickets() ([]chainhash.Hash, error) {
var ticketList []chainhash.Hash
err := s.namespace.View(func(tx walletdb.Tx) error {
var errForEach error
// Open the revocation records database.
bucket := tx.RootBucket().Bucket(ssrtxRecordsBucketName)
// Store each hash sequentially.
errForEach = bucket.ForEach(func(k []byte, v []byte) error {
ticket, errDeser := chainhash.NewHash(k)
if errDeser != nil {
return errDeser
}
ticketList = append(ticketList, *ticket)
return nil
})
return errForEach
})
if err != nil {
return nil, err
}
return ticketList, nil
}
// DumpSSRtxTickets is the exported version of dumpSSRtxTickets that is safe
// for concurrent access.
func (s *StakeStore) DumpSSRtxTickets() ([]chainhash.Hash, error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.dumpSSRtxTickets()
}
// A function to get a single owned SStx.
func (s *StakeStore) getSStx(hash *chainhash.Hash) (*sstxRecord, error) {
var record *sstxRecord
// Access the database and store the result locally.
err := s.namespace.View(func(tx walletdb.Tx) error {
var err error
record, err = fetchSStxRecord(tx, hash)
return err
})
if err != nil {
return nil, err
}
return record, nil
}
// insertSSGen inserts an SSGen record into the DB (keyed to the SStx it
// spends.
func (s *StakeStore) insertSSGen(blockHash *chainhash.Hash, blockHeight int64,
ssgenHash *chainhash.Hash, voteBits uint16, sstxHash *chainhash.Hash) error {
if blockHeight <= 0 {
return fmt.Errorf("invalid SSGen block height")
}
record := &ssgenRecord{
*blockHash,
uint32(blockHeight),
*ssgenHash,
voteBits,
time.Now(),
}
// Add the SSGen to the database.
err := s.namespace.Update(func(tx walletdb.Tx) error {
if putErr := putSSGenRecord(tx, sstxHash, record); putErr != nil {
return putErr
}
return nil
})
if err != nil {
return err
}
return nil
}
// InsertSSGen is the exported version of insertSSGen that is safe for
// concurrent access.
func (s *StakeStore) InsertSSGen(blockHash *chainhash.Hash, blockHeight int64,
ssgenHash *chainhash.Hash, voteBits uint16, sstxHash *chainhash.Hash) error {
if s.isClosed {
str := "stake store is closed"
return stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.insertSSGen(blockHash, blockHeight, ssgenHash, voteBits, sstxHash)
}
// getSSGens gets a list of SSGens that have been generated for some stake
// ticket.
func (s *StakeStore) getSSGens(sstxHash *chainhash.Hash) ([]*ssgenRecord, error) {
var records []*ssgenRecord
// Access the database and store the result locally.
err := s.namespace.View(func(tx walletdb.Tx) error {
var err error
records, err = fetchSSGenRecords(tx, sstxHash)
return err
})
if err != nil {
return nil, err
}
return records, nil
}
// SendRawTransaction sends a raw transaction using the chainSvr.
// TODO Shouldn't this be locked? Eventually import the mutex lock
// from wallet maybe.
func (s *StakeStore) SendRawTransaction(msgTx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash,
error) {
if s.isClosed {
str := "stake store is closed"
return nil, stakeStoreError(ErrStoreClosed, str, nil)
}
if s.chainSvr != nil {
return s.chainSvr.SendRawTransaction(msgTx, allowHighFees)
}
return nil, fmt.Errorf("cannot sendrawtranscation, client not " +
"initialized")
}
// SignVRTransaction signs a vote (SSGen) or revocation (SSRtx)
// transaction. isSSGen indicates if it is an SSGen; if it's not,
// it's an SSRtx.
func (s *StakeStore) SignVRTransaction(msgTx *wire.MsgTx, sstx *dcrutil.Tx,
isSSGen bool) error {
if s.isClosed {
str := "stake store is closed"
return stakeStoreError(ErrStoreClosed, str, nil)
}
txInNumToSign := 0
hashType := txscript.SigHashAll
if isSSGen {
// For an SSGen tx, skip the first input as it is a stake base
// and doesn't need to be signed.
msgTx.TxIn[0].SignatureScript = s.Params.StakeBaseSigScript
txInNumToSign = 1
}
// Get the script for the OP_SSTX tagged output that we need
// to sign.
sstxOutScript := sstx.MsgTx().TxOut[0].PkScript
// Set up our callbacks that we pass to dcrscript so it can
// look up the appropriate keys and scripts by address.
getKey := txscript.KeyClosure(func(addr dcrutil.Address) (
chainec.PrivateKey, bool, error) {
address, err := s.Manager.Address(addr)
if err != nil {
return nil, false, err
}
pka, ok := address.(waddrmgr.ManagedPubKeyAddress)
if !ok {
return nil, false, fmt.Errorf("address is not " +
"a pubkey address")
}
key, err := pka.PrivKey()
if err != nil {
return nil, false, err
}
return key, pka.Compressed(), nil
})
getScript := txscript.ScriptClosure(func(
addr dcrutil.Address) ([]byte, error) {
address, err := s.Manager.Address(addr)
if err != nil {
return nil, err
}
sa, ok := address.(waddrmgr.ManagedScriptAddress)
if !ok {
return nil, fmt.Errorf("address is not a script" +
" address")
}
return sa.Script()
})
// Attempt to generate the signed txin.
signedScript, err := txscript.SignTxOutput(s.Params,
msgTx,
txInNumToSign,
sstxOutScript,
hashType,
getKey,
getScript,
msgTx.TxIn[txInNumToSign].SignatureScript,
chainec.ECTypeSecp256k1)
if err != nil {
return fmt.Errorf("failed to sign ssgen or "+
"ssrtx, error: %v", err.Error())
}
msgTx.TxIn[txInNumToSign].SignatureScript = signedScript
// Either it was already signed or we just signed it.
// Find out if it is completely satisfied or still needs more.
// Decred: Needed??
flags := txscript.ScriptBip16
engine, err := txscript.NewEngine(sstxOutScript,
msgTx,
txInNumToSign,
flags,
txscript.DefaultScriptVersion)
if err != nil {
return fmt.Errorf("failed to generate signature script engine for "+
"ssgen or ssrtx, error: %v", err.Error())
}
err = engine.Execute()
if err != nil {
return fmt.Errorf("failed to generate correct signature script for "+
"ssgen or ssrtx: %v", err.Error())
}
return nil
}
// GenerateVote creates a new SSGen given a header hash, height, sstx
// tx hash, and votebits.
func (s *StakeStore) generateVote(blockHash *chainhash.Hash, height int64,
sstxHash *chainhash.Hash, defaultVoteBits uint16, allowHighFees bool) (*StakeNotification, error) {
// 1. Fetch the SStx, then calculate all the values we'll need later for
// the generation of the SSGen tx outputs.
sstxRecord, err := s.getSStx(sstxHash)
if err != nil {
return nil, err
}
sstx := sstxRecord.tx
sstxMsgTx := sstx.MsgTx()
// The legacy wallet didn't store anything about the voteBits to use.
// In the case we're loading a legacy wallet and the voteBits are
// unset, just use the default voteBits as set by the user.
voteBits := defaultVoteBits
if sstxRecord.voteBitsSet {
voteBits = sstxRecord.voteBits
}
// Store the sstx pubkeyhashes and amounts as found in the transaction
// outputs.
// TODO Get information on the allowable fee range for the vote
// and check to make sure we don't overflow that.
ssgenPayTypes, ssgenPkhs, sstxAmts, _, _, _ :=
stake.GetSStxStakeOutputInfo(sstx)
// Get the current reward.
stakeVoteSubsidy := blockchain.CalcStakeVoteSubsidy(height,
s.Params)
// Calculate the output values from this data.
ssgenCalcAmts := stake.GetStakeRewards(sstxAmts,
sstxMsgTx.TxOut[0].Value,
stakeVoteSubsidy)
// 2. Add all transaction inputs to a new transaction after performing
// some validity checks. First, add the stake base, then the OP_SSTX
// tagged output.
msgTx := wire.NewMsgTx()
// Stakebase.
stakeBaseOutPoint := wire.NewOutPoint(&chainhash.Hash{},
uint32(0xFFFFFFFF),
dcrutil.TxTreeRegular)
txInStakeBase := wire.NewTxIn(stakeBaseOutPoint, []byte{})
msgTx.AddTxIn(txInStakeBase)
// Add the subsidy amount into the input.
msgTx.TxIn[0].ValueIn = stakeVoteSubsidy
// SStx tagged output as an OutPoint.
prevOut := wire.NewOutPoint(sstxHash,
0, // Index 0
1) // Tree stake
txIn := wire.NewTxIn(prevOut, []byte{})
msgTx.AddTxIn(txIn)
// 3. Add the OP_RETURN null data pushes of the block header hash,
// the block height, and votebits, then add all the OP_SSGEN tagged
// outputs.
//
// Block reference output.
blockRefScript, err := txscript.GenerateSSGenBlockRef(*blockHash,
uint32(height))
if err != nil {
return nil, err
}
blockRefOut := wire.NewTxOut(0, blockRefScript)
msgTx.AddTxOut(blockRefOut)
// Votebits output.
blockVBScript, err := txscript.GenerateSSGenVotes(voteBits)
if err != nil {
return nil, err
}
blockVBOut := wire.NewTxOut(0, blockVBScript)
msgTx.AddTxOut(blockVBOut)
// Add all the SSGen-tagged transaction outputs to the transaction after
// performing some validity checks.
for i, ssgenPkh := range ssgenPkhs {
// Create a new script which pays to the provided address specified in
// the original ticket tx.
var ssgenOutScript []byte
switch ssgenPayTypes[i] {
case false: // P2PKH
ssgenOutScript, err = txscript.PayToSSGenPKHDirect(ssgenPkh)
if err != nil {
return nil, err
}
case true: // P2SH
ssgenOutScript, err = txscript.PayToSSGenSHDirect(ssgenPkh)
if err != nil {
return nil, err
}
}
// Add the txout to our SSGen tx.
txOut := wire.NewTxOut(ssgenCalcAmts[i], ssgenOutScript)
msgTx.AddTxOut(txOut)
}
// Check to make sure our SSGen was created correctly.
ssgenTx := dcrutil.NewTx(msgTx)
ssgenTx.SetTree(dcrutil.TxTreeStake)
_, err = stake.IsSSGen(ssgenTx)
if err != nil {
return nil, err
}
// Sign the transaction.
err = s.SignVRTransaction(msgTx, sstx, true)
if err != nil {
return nil, err
}
// Store the information about the SSGen.
err = s.insertSSGen(blockHash,
height,
ssgenTx.Sha(),
voteBits,
sstx.Sha())
if err != nil {
return nil, err
}
// Send the transaction.
ssgenSha, err := s.chainSvr.SendRawTransaction(msgTx, allowHighFees)
if err != nil {
return nil, err
}
log.Debugf("Generated SSGen %v, voting on block %v at height %v. "+
"The ticket used to generate the SSGen was %v.",
ssgenSha, blockHash, height, sstxHash)
// Generate a notification to return.
ntfn := &StakeNotification{
TxType: int8(stake.TxTypeSSGen),
TxHash: *ssgenSha,
BlockHash: *blockHash,
Height: int32(height),
Amount: 0,
SStxIn: *sstx.Sha(),
VoteBits: voteBits,
}
return ntfn, nil
}
// insertSSRtx inserts an SSRtx record into the DB (keyed to the SStx it
// spends.
func (s *StakeStore) insertSSRtx(blockHash *chainhash.Hash, blockHeight int64,
ssrtxHash *chainhash.Hash, sstxHash *chainhash.Hash) error {
if blockHeight <= 0 {
return fmt.Errorf("invalid SSRtx block height")
}
record := &ssrtxRecord{
*blockHash,
uint32(blockHeight),
*ssrtxHash,
time.Now(),
}
// Add the SSRtx to the database.
err := s.namespace.Update(func(tx walletdb.Tx) error {
if putErr := putSSRtxRecord(tx, sstxHash, record); putErr != nil {
return putErr
}
return nil
})
if err != nil {
return err
}
return nil
}
// InsertSSRtx is the exported version of insertSSRtx that is safe for
// concurrent access.
func (s *StakeStore) InsertSSRtx(blockHash *chainhash.Hash, blockHeight int64,
ssrtxHash *chainhash.Hash, sstxHash *chainhash.Hash) error {
if s.isClosed {
str := "stake store is closed"
return stakeStoreError(ErrStoreClosed, str, nil)
}
s.mtx.Lock()
defer s.mtx.Unlock()
return s.insertSSRtx(blockHash, blockHeight, ssrtxHash, sstxHash)
}
// GetSSRtxs gets a list of SSRtxs that have been generated for some stake
// ticket.
func (s *StakeStore) getSSRtxs(sstxHash *chainhash.Hash) ([]*ssrtxRecord, error) {
var records []*ssrtxRecord
// Access the database and store the result locally.
err := s.namespace.View(func(tx walletdb.Tx) error {
var err error
records, err = fetchSSRtxRecords(tx, sstxHash)
return err
})
if err != nil {
return nil, err
}
return records, nil
}
// GenerateRevocation generates a revocation (SSRtx), signs it, and
// submits it by SendRawTransaction. It also stores a record of it
// in the local database.
func (s *StakeStore) generateRevocation(blockHash *chainhash.Hash, height int64,
sstxHash *chainhash.Hash, allowHighFees bool) (*StakeNotification, error) {
var revocationFee int64
switch {
case s.Params == &chaincfg.MainNetParams:
revocationFee = revocationFeeMainNet
case s.Params == &chaincfg.TestNetParams:
revocationFee = revocationFeeTestNet
default:
revocationFee = revocationFeeTestNet
}
// 1. Fetch the SStx, then calculate all the values we'll need later for
// the generation of the SSRtx tx outputs.
sstxRecord, err := s.getSStx(sstxHash)
if err != nil {
return nil, err
}