-
Notifications
You must be signed in to change notification settings - Fork 1
/
txhelpers.go
848 lines (740 loc) · 25 KB
/
txhelpers.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
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
// package txhelpers contains helper functions for working with transactions and
// blocks (e.g. checking for a transaction in a block).
package txhelpers
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"math"
"math/big"
"sort"
"strconv"
"github.com/decred/dcrd/blockchain"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
)
var (
zeroHash = chainhash.Hash{}
zeroHashStringBytes = []byte(chainhash.Hash{}.String())
)
// RawTransactionGetter is an interface satisfied by rpcclient.Client, and
// required by functions that would otherwise require a rpcclient.Client just
// for GetRawTransaction.
type RawTransactionGetter interface {
GetRawTransaction(txHash *chainhash.Hash) (*dcrutil.Tx, error)
}
// VerboseTransactionGetter is an interface satisfied by rpcclient.Client, and
// required by functions that would otherwise require a rpcclient.Client just
// for GetRawTransactionVerbose.
type VerboseTransactionGetter interface {
GetRawTransactionVerbose(txHash *chainhash.Hash) (*dcrjson.TxRawResult, error)
}
// BlockWatchedTx contains, for a certain block, the transactions for certain
// watched addresses
type BlockWatchedTx struct {
BlockHeight int64
TxsForAddress map[string][]*dcrutil.Tx
}
// TxAction is what is happening to the transaction (mined or inserted into
// mempool).
type TxAction int32
// Valid values for TxAction
const (
TxMined TxAction = 1 << iota
TxInserted
// removed? invalidated?
)
// HashInSlice determines if a hash exists in a slice of hashes.
func HashInSlice(h chainhash.Hash, list []chainhash.Hash) bool {
for _, hash := range list {
if h == hash {
return true
}
}
return false
}
// TxhashInSlice searches a slice of *dcrutil.Tx for a transaction with the hash
// txHash. If found, it returns the corresponding *Tx, otherwise nil.
func TxhashInSlice(txs []*dcrutil.Tx, txHash *chainhash.Hash) *dcrutil.Tx {
if len(txs) < 1 {
return nil
}
for _, minedTx := range txs {
txSha := minedTx.Hash()
if txHash.IsEqual(txSha) {
return minedTx
}
}
return nil
}
// IncludesStakeTx checks if a block contains a stake transaction hash
func IncludesStakeTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) {
blockTxs := block.STransactions()
if tx := TxhashInSlice(blockTxs, txHash); tx != nil {
return tx.Index(), tx.Tree()
}
return -1, -1
}
// IncludesTx checks if a block contains a transaction hash
func IncludesTx(txHash *chainhash.Hash, block *dcrutil.Block) (int, int8) {
blockTxs := block.Transactions()
if tx := TxhashInSlice(blockTxs, txHash); tx != nil {
return tx.Index(), tx.Tree()
}
return -1, -1
}
// FilterHashSlice removes elements from the specified if the doRemove function
// evaluates to true for a given element. For example, given a slice of hashes
// called blackList that should be removed from the slice hashList:
//
// hashList = FilterHashSlice(hashList, func(h chainhash.Hash) bool {
// return HashInSlice(h, blackList)
// })
func FilterHashSlice(s []chainhash.Hash, doRemove func(h chainhash.Hash) bool) []chainhash.Hash {
_s := s[:0]
for _, h := range s {
if !doRemove(h) {
_s = append(_s, h)
}
}
return _s
}
// PrevOut contains a transaction input's previous outpoint, the Hash of the
// spending (following) transaction, and input index in the transaction.
type PrevOut struct {
TxSpending chainhash.Hash
InputIndex int
PreviousOutpoint *wire.OutPoint
}
// TxWithBlockData contains a MsgTx and the block hash and height in which it
// was mined and Time it entered MemPool.
type TxWithBlockData struct {
Tx *wire.MsgTx
BlockHeight int64
BlockHash string
MemPoolTime int64
}
// Hash returns the chainhash.Hash of the transaction.
func (t *TxWithBlockData) Hash() chainhash.Hash {
return t.Tx.TxHash()
}
// Confirmed indicates if the transaction is confirmed (mined).
func (t *TxWithBlockData) Confirmed() bool {
return t.BlockHeight > 0 && len(t.BlockHash) <= chainhash.MaxHashStringSize
}
// AddressOutpoints collects spendable and spent transactions outpoints paying
// to a certain address. The transactions referenced by the outpoints are stored
// for quick access.
type AddressOutpoints struct {
Address string
Outpoints []*wire.OutPoint
PrevOuts []PrevOut
TxnsStore map[chainhash.Hash]*TxWithBlockData
}
// NewAddressOutpoints creates a new AddressOutpoints, initializing the
// transaction store/cache, and setting the address string.
func NewAddressOutpoints(address string) *AddressOutpoints {
return &AddressOutpoints{
Address: address,
TxnsStore: make(map[chainhash.Hash]*TxWithBlockData),
}
}
// Update appends the provided outpoints, and merges the transactions.
func (a *AddressOutpoints) Update(Txns []*TxWithBlockData,
Outpoints []*wire.OutPoint, PrevOutpoint []PrevOut) {
// Relevant outpoints
a.Outpoints = append(a.Outpoints, Outpoints...)
// Previous outpoints (inputs)
a.PrevOuts = append(a.PrevOuts, PrevOutpoint...)
// Referenced transactions
for _, t := range Txns {
a.TxnsStore[t.Hash()] = t
}
}
// Merge concatenates the outpoints of two AddressOutpoints, and merges the
// transactions.
func (a *AddressOutpoints) Merge(ao *AddressOutpoints) {
// Relevant outpoints
a.Outpoints = append(a.Outpoints, ao.Outpoints...)
// Previous outpoints (inputs)
a.PrevOuts = append(a.PrevOuts, ao.PrevOuts...)
// Referenced transactions
for h, t := range ao.TxnsStore {
a.TxnsStore[h] = t
}
}
// TxInvolvesAddress checks the inputs and outputs of a transaction for
// involvement of the given address.
func TxInvolvesAddress(msgTx *wire.MsgTx, addr string, c VerboseTransactionGetter,
params *chaincfg.Params) (outpoints []*wire.OutPoint,
prevOuts []PrevOut, prevTxs []*TxWithBlockData) {
// The outpoints of this transaction paying to the address
outpoints = TxPaysToAddress(msgTx, addr, params)
// The inputs of this transaction funded by outpoints of previous
// transactions paying to the address.
prevOuts, prevTxs = TxConsumesOutpointWithAddress(msgTx, addr, c, params)
return
}
// TxConsumesOutpointWithAddress checks a transaction for inputs that spend an
// outpoint paying to the given address. Returned are the identified input
// indexes and the corresponding previous outpoints determined.
func TxConsumesOutpointWithAddress(msgTx *wire.MsgTx, addr string,
c VerboseTransactionGetter, params *chaincfg.Params) (prevOuts []PrevOut, prevTxs []*TxWithBlockData) {
// For each TxIn of this transaction, inspect the previous outpoint.
for inIdx, txIn := range msgTx.TxIn {
// Previous outpoint for this TxIn
prevOut := &txIn.PreviousOutPoint
if bytes.Equal(zeroHash[:], prevOut.Hash[:]) {
continue
}
// GetRawTransactionVerbose provides the height and hash of the block in
// which the transaction is included, if it is confirmed.
prevTxRaw, err := c.GetRawTransactionVerbose(&prevOut.Hash)
if err != nil {
fmt.Printf("Unable to get raw transaction for %s\n", prevOut.Hash.String())
continue
}
prevTx, err := MsgTxFromHex(prevTxRaw.Hex)
if err != nil {
fmt.Printf("MsgTxFromHex failed: %s\n", err)
continue
}
txHash := prevTx.TxHash()
// prevOut.Index tells indicates which output
txOut := prevTx.TxOut[prevOut.Index]
// extract the addresses from this output's PkScript
_, txAddrs, _, err := txscript.ExtractPkScriptAddrs(
txOut.Version, txOut.PkScript, params)
if err != nil {
fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error())
continue
}
// For each address that matches the address of interest, record this
// previous outpoint and the containing transactions.
for _, txAddr := range txAddrs {
addrstr := txAddr.EncodeAddress()
if addr == addrstr {
outpoint := wire.NewOutPoint(&txHash,
prevOut.Index, TxTree(prevTx))
prevOuts = append(prevOuts, PrevOut{
TxSpending: msgTx.TxHash(),
InputIndex: inIdx,
PreviousOutpoint: outpoint,
})
prevTxs = append(prevTxs, &TxWithBlockData{
Tx: prevTx,
BlockHeight: prevTxRaw.BlockHeight,
BlockHash: prevTxRaw.BlockHash,
})
}
}
}
return
}
// BlockConsumesOutpointWithAddresses checks the specified block to see if it
// includes transactions that spend from outputs created using any of the
// addresses in addrs. The TxAction for each address is not important, but it
// would logically be TxMined. Both regular and stake transactions are checked.
// The RPC client is used to get the PreviousOutPoint for each TxIn of each
// transaction in the block, from which the address is obtained from the
// PkScript of that output. chaincfg Params is required to decode the script.
func BlockConsumesOutpointWithAddresses(block *dcrutil.Block, addrs map[string]TxAction,
c RawTransactionGetter, params *chaincfg.Params) map[string][]*dcrutil.Tx {
addrMap := make(map[string][]*dcrutil.Tx)
checkForOutpointAddr := func(blockTxs []*dcrutil.Tx) {
for _, tx := range blockTxs {
for _, txIn := range tx.MsgTx().TxIn {
prevOut := &txIn.PreviousOutPoint
if bytes.Equal(zeroHash[:], prevOut.Hash[:]) {
continue
}
// For each TxIn, check the indicated vout index in the txid of the
// previous outpoint.
// txrr, err := c.GetRawTransactionVerbose(&prevOut.Hash)
prevTx, err := c.GetRawTransaction(&prevOut.Hash)
if err != nil {
fmt.Printf("Unable to get raw transaction for %s\n", prevOut.Hash.String())
continue
}
// prevOut.Index should tell us which one, but check all anyway
for _, txOut := range prevTx.MsgTx().TxOut {
_, txAddrs, _, err := txscript.ExtractPkScriptAddrs(
txOut.Version, txOut.PkScript, params)
if err != nil {
fmt.Printf("ExtractPkScriptAddrs: %v\n", err.Error())
continue
}
for _, txAddr := range txAddrs {
addrstr := txAddr.EncodeAddress()
if _, ok := addrs[addrstr]; ok {
if addrMap[addrstr] == nil {
addrMap[addrstr] = make([]*dcrutil.Tx, 0)
}
addrMap[addrstr] = append(addrMap[addrstr], prevTx)
}
}
}
}
}
}
checkForOutpointAddr(block.Transactions())
checkForOutpointAddr(block.STransactions())
return addrMap
}
// TxPaysToAddress returns a slice of outpoints of a transaction which pay to
// specified address.
func TxPaysToAddress(msgTx *wire.MsgTx, addr string,
params *chaincfg.Params) (outpoints []*wire.OutPoint) {
// Check the addresses associated with the PkScript of each TxOut
txTree := TxTree(msgTx)
hash := msgTx.TxHash()
for outIndex, txOut := range msgTx.TxOut {
_, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version,
txOut.PkScript, params)
if err != nil {
fmt.Printf("ExtractPkScriptAddrs: %v", err.Error())
continue
}
// Check if we are watching any address for this TxOut
for _, txAddr := range txOutAddrs {
addrstr := txAddr.EncodeAddress()
if addr == addrstr {
outpoints = append(outpoints, wire.NewOutPoint(&hash,
uint32(outIndex), txTree))
}
}
}
return
}
// BlockReceivesToAddresses checks a block for transactions paying to the
// specified addresses, and creates a map of addresses to a slice of dcrutil.Tx
// involving the address.
func BlockReceivesToAddresses(block *dcrutil.Block, addrs map[string]TxAction,
params *chaincfg.Params) map[string][]*dcrutil.Tx {
addrMap := make(map[string][]*dcrutil.Tx)
checkForAddrOut := func(blockTxs []*dcrutil.Tx) {
for _, tx := range blockTxs {
// Check the addresses associated with the PkScript of each TxOut
for _, txOut := range tx.MsgTx().TxOut {
_, txOutAddrs, _, err := txscript.ExtractPkScriptAddrs(txOut.Version,
txOut.PkScript, params)
if err != nil {
fmt.Printf("ExtractPkScriptAddrs: %v", err.Error())
continue
}
// Check if we are watching any address for this TxOut
for _, txAddr := range txOutAddrs {
addrstr := txAddr.EncodeAddress()
if _, ok := addrs[addrstr]; ok {
if _, gotSlice := addrMap[addrstr]; !gotSlice {
addrMap[addrstr] = make([]*dcrutil.Tx, 0) // nil
}
addrMap[addrstr] = append(addrMap[addrstr], tx)
}
}
}
}
}
checkForAddrOut(block.Transactions())
checkForAddrOut(block.STransactions())
return addrMap
}
// OutPointAddresses gets the addresses paid to by a transaction output.
func OutPointAddresses(outPoint *wire.OutPoint, c RawTransactionGetter,
params *chaincfg.Params) ([]string, dcrutil.Amount, error) {
// The addresses are encoded in the pkScript, so we need to get the
// raw transaction, and the TxOut that contains the pkScript.
prevTx, err := c.GetRawTransaction(&outPoint.Hash)
if err != nil {
return nil, 0, fmt.Errorf("unable to get raw transaction for %s", outPoint.Hash.String())
}
txOuts := prevTx.MsgTx().TxOut
if len(txOuts) <= int(outPoint.Index) {
return nil, 0, fmt.Errorf("PrevOut index (%d) is beyond the TxOuts slice (length %d)",
outPoint.Index, len(txOuts))
}
// For the TxOut of interest, extract the list of addresses
txOut := txOuts[outPoint.Index]
_, txAddrs, _, err := txscript.ExtractPkScriptAddrs(
txOut.Version, txOut.PkScript, params)
if err != nil {
return nil, 0, fmt.Errorf("ExtractPkScriptAddrs: %v", err.Error())
}
value := dcrutil.Amount(txOut.Value)
addresses := make([]string, 0, len(txAddrs))
for _, txAddr := range txAddrs {
addr := txAddr.EncodeAddress()
addresses = append(addresses, addr)
}
return addresses, value, nil
}
// OutPointAddressesFromString is the same as OutPointAddresses, but it takes
// the outpoint as the tx string, vout index, and tree.
func OutPointAddressesFromString(txid string, index uint32, tree int8,
c RawTransactionGetter, params *chaincfg.Params) ([]string, error) {
hash, err := chainhash.NewHashFromStr(txid)
if err != nil {
return nil, fmt.Errorf("Invalid hash %s", txid)
}
outPoint := wire.NewOutPoint(hash, index, tree)
outPointAddress, _, err := OutPointAddresses(outPoint, c, params)
return outPointAddress, err
}
// MedianAmount gets the median Amount from a slice of Amounts
func MedianAmount(s []dcrutil.Amount) dcrutil.Amount {
if len(s) == 0 {
return 0
}
sort.Sort(dcrutil.AmountSorter(s))
middle := len(s) / 2
if len(s) == 0 {
return 0
} else if (len(s) % 2) != 0 {
return s[middle]
}
return (s[middle] + s[middle-1]) / 2
}
// MedianCoin gets the median DCR from a slice of float64s
func MedianCoin(s []float64) float64 {
if len(s) == 0 {
return 0
}
sort.Float64s(s)
middle := len(s) / 2
if len(s) == 0 {
return 0
} else if (len(s) % 2) != 0 {
return s[middle]
}
return (s[middle] + s[middle-1]) / 2
}
// GetDifficultyRatio returns the proof-of-work difficulty as a multiple of the
// minimum difficulty using the passed bits field from the header of a block.
func GetDifficultyRatio(bits uint32, params *chaincfg.Params) float64 {
// The minimum difficulty is the max possible proof-of-work limit bits
// converted back to a number. Note this is not the same as the proof of
// work limit directly because the block difficulty is encoded in a block
// with the compact form which loses precision.
max := blockchain.CompactToBig(params.PowLimitBits)
target := blockchain.CompactToBig(bits)
difficulty := new(big.Rat).SetFrac(max, target)
outString := difficulty.FloatString(8)
diff, err := strconv.ParseFloat(outString, 64)
if err != nil {
fmt.Printf("Cannot get difficulty: %v", err)
return 0
}
return diff
}
// SSTXInBlock gets a slice containing all of the SSTX mined in a block
func SSTXInBlock(block *dcrutil.Block) []*dcrutil.Tx {
_, txns := TicketTxnsInBlock(block)
return txns
}
// SSGenVoteBlockValid determines if a vote transaction is voting yes or no to a
// block, and returns the votebits in case the caller wants to check agenda
// votes. The error return may be ignored if the input transaction is known to
// be a valid ssgen (vote), otherwise it should be checked.
func SSGenVoteBlockValid(msgTx *wire.MsgTx) (BlockValidation, uint16, error) {
if !stake.IsSSGen(msgTx) {
return BlockValidation{}, 0, fmt.Errorf("not a vote transaction")
}
ssGenVoteBits := stake.SSGenVoteBits(msgTx)
blockHash, blockHeight := stake.SSGenBlockVotedOn(msgTx)
blockValid := BlockValidation{
Hash: blockHash,
Height: int64(blockHeight),
Validity: dcrutil.IsFlagSet16(ssGenVoteBits, dcrutil.BlockValid),
}
return blockValid, ssGenVoteBits, nil
}
// VoteBitsInBlock returns a list of vote bits for the votes in a block
func VoteBitsInBlock(block *dcrutil.Block) []stake.VoteVersionTuple {
var voteBits []stake.VoteVersionTuple
for _, stx := range block.MsgBlock().STransactions {
if !stake.IsSSGen(stx) {
continue
}
voteBits = append(voteBits, stake.VoteVersionTuple{
Version: stake.SSGenVersion(stx),
Bits: stake.SSGenVoteBits(stx),
})
}
return voteBits
}
// SSGenVoteBits returns the VoteBits of txOut[1] of a ssgen tx
func SSGenVoteBits(tx *wire.MsgTx) (uint16, error) {
if len(tx.TxOut) < 2 {
return 0, fmt.Errorf("not a ssgen")
}
pkScript := tx.TxOut[1].PkScript
if len(pkScript) < 8 {
return 0, fmt.Errorf("vote consensus version abent")
}
return binary.LittleEndian.Uint16(pkScript[2:4]), nil
}
// BlockValidation models the block validation indicated by an ssgen (vote)
// transaction.
type BlockValidation struct {
// Hash is the hash of the block being targeted (in)validated
Hash chainhash.Hash
// Height is the height of the block
Height int64
// Validity indicates the vote is to validate (true) or invalidate (false)
// the block.
Validity bool
}
// VoteChoice represents the choice made by a vote transaction on a single vote
// item in an agenda. The ID, Description, and Mask fields describe the vote
// item for which the choice is being made. Those are the initial fields in
// chaincfg.Params.Deployments[VoteVersion][VoteIndex].
type VoteChoice struct {
// Single unique word identifying the vote.
ID string `json:"id"`
// Longer description of what the vote is about.
Description string `json:"description"`
// Usable bits for this vote.
Mask uint16 `json:"mask"`
// VoteVersion and VoteIndex specify which vote item is referenced by this
// VoteChoice (i.e. chaincfg.Params.Deployments[VoteVersion][VoteIndex]).
VoteVersion uint32 `json:"vote_version"`
VoteIndex int `json:"vote_index"`
// ChoiceIdx indicates the corresponding element in the vote item's []Choice
ChoiceIdx int `json:"choice_index"`
// Choice is the selected choice for the specified vote item
Choice *chaincfg.Choice `json:"choice"`
}
// VoteVersion extracts the vote version from the input pubkey script.
func VoteVersion(pkScript []byte) uint32 {
if len(pkScript) < 8 {
return stake.VoteConsensusVersionAbsent
}
return binary.LittleEndian.Uint32(pkScript[4:8])
}
// SSGenVoteChoices gets a ssgen's vote choices (block validity and any
// agendas). The vote's stake version, to which the vote choices correspond, and
// vote bits are also returned. Note that []*VoteChoice may be an empty slice if
// there are no consensus deployments for the transaction's vote version. The
// error value may be non-nil if the tx is not a valid ssgen.
func SSGenVoteChoices(tx *wire.MsgTx, params *chaincfg.Params) (BlockValidation, uint32, uint16, []*VoteChoice, error) {
validBlock, voteBits, err := SSGenVoteBlockValid(tx)
if err != nil {
return validBlock, 0, 0, nil, err
}
// Determine the ssgen's vote version and get the relevant consensus
// deployments containing the vote items targeted.
voteVersion := stake.SSGenVersion(tx)
deployments := params.Deployments[voteVersion]
// Allocate space for each choice
choices := make([]*VoteChoice, 0, len(deployments))
// For each vote item (consensus deployment), extract the choice from the
// vote bits and store the vote item's Id, Description and vote bits Mask.
for d := range deployments {
voteAgenda := &deployments[d].Vote
choiceIndex := voteAgenda.VoteIndex(voteBits)
voteChoice := VoteChoice{
ID: voteAgenda.Id,
Description: voteAgenda.Description,
Mask: voteAgenda.Mask,
VoteVersion: voteVersion,
VoteIndex: d,
ChoiceIdx: choiceIndex,
Choice: &voteAgenda.Choices[choiceIndex],
}
choices = append(choices, &voteChoice)
}
return validBlock, voteVersion, voteBits, choices, nil
}
// FeeInfoBlock computes ticket fee statistics for the tickets included in the
// specified block.
func FeeInfoBlock(block *dcrutil.Block) *dcrjson.FeeInfoBlock {
feeInfo := new(dcrjson.FeeInfoBlock)
_, sstxMsgTxns := TicketsInBlock(block)
feeInfo.Height = uint32(block.Height())
feeInfo.Number = uint32(len(sstxMsgTxns))
var minFee, maxFee, meanFee float64
minFee = math.MaxFloat64
fees := make([]float64, feeInfo.Number)
for it, msgTx := range sstxMsgTxns {
var amtIn int64
for iv := range msgTx.TxIn {
amtIn += msgTx.TxIn[iv].ValueIn
}
var amtOut int64
for iv := range msgTx.TxOut {
amtOut += msgTx.TxOut[iv].Value
}
fee := dcrutil.Amount(amtIn - amtOut).ToCoin()
if fee < minFee {
minFee = fee
}
if fee > maxFee {
maxFee = fee
}
meanFee += fee
fees[it] = fee
}
if feeInfo.Number > 0 {
N := float64(feeInfo.Number)
meanFee /= N
feeInfo.Mean = meanFee
feeInfo.Median = MedianCoin(fees)
feeInfo.Min = minFee
feeInfo.Max = maxFee
if N > 1 {
var variance float64
for _, f := range fees {
variance += (f - meanFee) * (f - meanFee)
}
variance /= (N - 1)
feeInfo.StdDev = math.Sqrt(variance)
}
}
return feeInfo
}
// FeeRateInfoBlock computes ticket fee rate statistics for the tickets included
// in the specified block.
func FeeRateInfoBlock(block *dcrutil.Block) *dcrjson.FeeInfoBlock {
feeInfo := new(dcrjson.FeeInfoBlock)
_, sstxMsgTxns := TicketsInBlock(block)
feeInfo.Height = uint32(block.Height())
feeInfo.Number = uint32(len(sstxMsgTxns))
var minFee, maxFee, meanFee float64
minFee = math.MaxFloat64
feesRates := make([]float64, feeInfo.Number)
for it, msgTx := range sstxMsgTxns {
var amtIn, amtOut int64
for iv := range msgTx.TxIn {
amtIn += msgTx.TxIn[iv].ValueIn
}
for iv := range msgTx.TxOut {
amtOut += msgTx.TxOut[iv].Value
}
fee := dcrutil.Amount(1000*(amtIn-amtOut)).ToCoin() / float64(msgTx.SerializeSize())
if fee < minFee {
minFee = fee
}
if fee > maxFee {
maxFee = fee
}
meanFee += fee
feesRates[it] = fee
}
if feeInfo.Number > 0 {
N := float64(feeInfo.Number)
feeInfo.Mean = meanFee / N
feeInfo.Median = MedianCoin(feesRates)
feeInfo.Min = minFee
feeInfo.Max = maxFee
if feeInfo.Number > 1 {
var variance float64
for _, f := range feesRates {
fDev := f - feeInfo.Mean
variance += fDev * fDev
}
variance /= (N - 1)
feeInfo.StdDev = math.Sqrt(variance)
}
}
return feeInfo
}
// MsgTxFromHex returns a wire.MsgTx struct built from the transaction hex string
func MsgTxFromHex(txhex string) (*wire.MsgTx, error) {
txBytes, err := hex.DecodeString(txhex)
if err != nil {
return nil, err
}
msgTx := wire.NewMsgTx()
if err = msgTx.FromBytes(txBytes); err != nil {
return nil, err
}
return msgTx, nil
}
// DetermineTxTypeString returns a string representing the transaction type given
// a wire.MsgTx struct
func DetermineTxTypeString(msgTx *wire.MsgTx) string {
switch stake.DetermineTxType(msgTx) {
case stake.TxTypeSSGen:
return "Vote"
case stake.TxTypeSStx:
return "Ticket"
case stake.TxTypeSSRtx:
return "Revocation"
default:
return "Regular"
}
}
// IsStakeTx indicates if the input MsgTx is a stake transaction.
func IsStakeTx(msgTx *wire.MsgTx) bool {
switch stake.DetermineTxType(msgTx) {
case stake.TxTypeSSGen:
fallthrough
case stake.TxTypeSStx:
fallthrough
case stake.TxTypeSSRtx:
return true
default:
return false
}
}
// TxTree returns for a wire.MsgTx either wire.TxTreeStake or wire.TxTreeRegular
// depending on the type of transaction.
func TxTree(msgTx *wire.MsgTx) int8 {
if IsStakeTx(msgTx) {
return wire.TxTreeStake
}
return wire.TxTreeRegular
}
// TxFee computes and returns the fee for a given tx
func TxFee(msgTx *wire.MsgTx) dcrutil.Amount {
var amtIn int64
for iv := range msgTx.TxIn {
amtIn += msgTx.TxIn[iv].ValueIn
}
var amtOut int64
for iv := range msgTx.TxOut {
amtOut += msgTx.TxOut[iv].Value
}
return dcrutil.Amount(amtIn - amtOut)
}
// TxFeeRate computes and returns the fee rate in DCR/KB for a given tx
func TxFeeRate(msgTx *wire.MsgTx) (dcrutil.Amount, dcrutil.Amount) {
var amtIn int64
for iv := range msgTx.TxIn {
amtIn += msgTx.TxIn[iv].ValueIn
}
var amtOut int64
for iv := range msgTx.TxOut {
amtOut += msgTx.TxOut[iv].Value
}
return dcrutil.Amount(amtIn - amtOut), dcrutil.Amount(1000 * (amtIn - amtOut) / int64(msgTx.SerializeSize()))
}
// TotalOutFromMsgTx computes the total value out of a MsgTx
func TotalOutFromMsgTx(msgTx *wire.MsgTx) dcrutil.Amount {
var amtOut int64
for _, v := range msgTx.TxOut {
amtOut += v.Value
}
return dcrutil.Amount(amtOut)
}
// TotalVout computes the total value of a slice of dcrjson.Vout
func TotalVout(vouts []dcrjson.Vout) dcrutil.Amount {
var total dcrutil.Amount
for _, v := range vouts {
a, err := dcrutil.NewAmount(v.Value)
if err != nil {
continue
}
total += a
}
return total
}