-
Notifications
You must be signed in to change notification settings - Fork 292
/
treasury.go
1038 lines (914 loc) · 32.2 KB
/
treasury.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) 2020 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/decred/dcrd/blockchain/stake/v4"
"github.com/decred/dcrd/blockchain/standalone/v2"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database/v2"
"github.com/decred/dcrd/dcrec/secp256k1/v4/schnorr"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/wire"
)
const (
// yesTreasury signifies the treasury agenda should be treated as
// though it is active. It is used to increase the readability of the
// code.
yesTreasury = true
)
// errDbTreasury signifies that a problem was encountered when fetching or
// writing the treasury balance for a given block.
type errDbTreasury string
// Error implements the error interface.
func (e errDbTreasury) Error() string {
return string(e)
}
// Is implements the interface to work with the standard library's errors.Is.
//
// It returns true in the following cases:
// - The target is errDbTreasury
func (e errDbTreasury) Is(target error) bool {
var err errDbTreasury
return errors.As(target, &err)
}
// -----------------------------------------------------------------------------
// The treasury state index consists of an entry for every known block. It
// contains the balance of the treasury as of that block as well as all of the
// amounts added to and spent from the treasury in the block.
//
// The serialized key format is:
//
// <block hash>
//
// Field Type Size
// block hash chainhash.Hash chainhash.HashSize
//
// The serialized value format is:
//
// <balance><num values><values info>
//
// Field Type Size
// balance VLQ variable
// num values VLQ variable
// values
// flag VLQ variable
// value VLQ variable
//
// The flag attribute of each value is a bit field, serialized as follows:
//
// 00000ttt
// | | mask
// | \---- 0x07: treasuryValueType
// \-------------- : Unused
//
// -----------------------------------------------------------------------------
// treasuryValueType specifies the possible types of values that modify the
// treasury balance.
type treasuryValueType byte
// The following constants define the known types of values that modify the
// treasury balance.
const (
treasuryValueTBase treasuryValueType = 0x01
treasuryValueTAdd treasuryValueType = 0x02
treasuryValueFee treasuryValueType = 0x03
treasuryValueTSpend treasuryValueType = 0x04
// tvFlagTypMask is the mask of the bits used to encode the type in the
// flags field of a serialized treasuryValue.
tvFlagTypMask byte = 0x07
)
// treasuryValue specifies the type and amount that of a value that changes the
// treasury balance.
//
// NOTE: for tspends and tspend fees, the amount is *negative*.
type treasuryValue struct {
typ treasuryValueType
amount int64
}
// treasuryState records the treasury balance as of this block as well as the
// yet to mature balance-changing values (treasurybase, adds, spends and spend
// fees) included in the block itself.
//
// Note that treasurybase and tadds are positive and tspends and tspend fees
// are negative. Additionally the values are written in the exact same order
// as they appear in the block. This can be used to verify the correctness of
// the record if needed.
type treasuryState struct {
// balance is the treasury balance as of this block.
balance int64
// values stores all balance-changing values included in this block (for use
// when block is mature).
values []treasuryValue
}
// serializeTreasuryState serializes the treasury state into a single byte slice
// according to the format described in detail above.
func serializeTreasuryState(ts treasuryState) ([]byte, error) {
// Just a little sanity testing.
if ts.balance < 0 {
str := fmt.Sprintf("invalid treasury balance: %v", ts.balance)
return nil, errDbTreasury(str)
}
// Calculate total number of bytes it will take to serialize the treasury
// state according to the format described above.
serializeSize := serializeSizeVLQ(uint64(ts.balance)) +
serializeSizeVLQ(uint64(len(ts.values)))
for _, value := range ts.values {
// Prevent serialization of wrong negative value. Note that
// zero is still allowed even in negative types.
wantNegative := value.typ == treasuryValueFee ||
value.typ == treasuryValueTSpend
gotNegative := value.amount < 0
if value.amount != 0 && wantNegative != gotNegative {
str := fmt.Sprintf("incorrect negative value for type "+
"%d: %d", value.typ, value.amount)
return nil, errDbTreasury(str)
}
serializeSize += 1 // Flag which is currently a 1 byte long VLQ.
serializeSize += serializeSizeVLQ(absInt64(value.amount))
}
// Serialize the treasury state according to the format described above.
serialized := make([]byte, serializeSize)
offset := putVLQ(serialized, uint64(ts.balance))
offset += putVLQ(serialized[offset:], uint64(len(ts.values)))
for _, value := range ts.values {
// tspends and fees are negative but store them as positive to
// reduce storage needs.
amount := absInt64(value.amount)
flag := uint64(byte(value.typ) & tvFlagTypMask)
offset += putVLQ(serialized[offset:], flag)
offset += putVLQ(serialized[offset:], amount)
}
return serialized, nil
}
// deserializeTreasuryState deserializes the passed serialized treasury state
// according to the format described above.
func deserializeTreasuryState(data []byte) (*treasuryState, error) {
// Deserialize the balance.
balance, offset := deserializeVLQ(data)
if offset == 0 {
return nil, errDeserialize("unexpected end of data while reading " +
"treasury balance")
}
// Deserialize the number of values.
var values []treasuryValue
numValues, bytesRead := deserializeVLQ(data[offset:])
if bytesRead == 0 {
return nil, errDeserialize("unexpected end of data while reading " +
"number of value entries")
}
offset += bytesRead
// Deserialize individual values.
if numValues > 0 {
values = make([]treasuryValue, numValues)
for i := uint64(0); i < numValues; i++ {
flag, bytesRead := deserializeVLQ(data[offset:])
offset += bytesRead
if bytesRead == 0 {
return nil, errDeserialize(fmt.Sprintf("unexpected end of "+
"data while reading value flag #%d", i))
}
value, bytesRead := deserializeVLQ(data[offset:])
offset += bytesRead
if bytesRead == 0 {
return nil, errDeserialize(fmt.Sprintf("unexpected end of "+
"data while reading value amount #%d", i))
}
typ := treasuryValueType(byte(flag) & tvFlagTypMask)
amount := int64(value)
// tspends and fees are negative but stored as
// positive, so negate the amount if needed.
wantNegative := typ == treasuryValueFee ||
typ == treasuryValueTSpend
if wantNegative {
amount = -amount
}
values[i] = treasuryValue{
typ: typ,
amount: amount,
}
}
}
var ts treasuryState
ts.balance = int64(balance)
ts.values = values
return &ts, nil
}
// dbPutTreasuryBalance inserts a treasury state record into the database.
func dbPutTreasuryBalance(dbTx database.Tx, hash chainhash.Hash, ts treasuryState) error {
// Serialize the current treasury state.
serializedData, err := serializeTreasuryState(ts)
if err != nil {
return err
}
// Store the current treasury state into the database.
meta := dbTx.Metadata()
bucket := meta.Bucket(treasuryBucketName)
return bucket.Put(hash[:], serializedData)
}
// dbFetchTreasuryBalance uses an existing database transaction to fetch the
// treasury state.
func dbFetchTreasuryBalance(dbTx database.Tx, hash chainhash.Hash) (*treasuryState, error) {
meta := dbTx.Metadata()
bucket := meta.Bucket(treasuryBucketName)
v := bucket.Get(hash[:])
if v == nil {
str := fmt.Sprintf("treasury db missing key: %v", hash)
return nil, errDbTreasury(str)
}
return deserializeTreasuryState(v)
}
// dbFetchTreasurySingle wraps dbFetchTreasuryBalance in a view.
func (b *BlockChain) dbFetchTreasurySingle(hash chainhash.Hash) (*treasuryState, error) {
var ts *treasuryState
err := b.db.View(func(dbTx database.Tx) error {
var err error
ts, err = dbFetchTreasuryBalance(dbTx, hash)
return err
})
return ts, err
}
// serializeTSpend serializes the TSpend data for use in the database.
// The format is as follows:
// Block []chainhash.Hash (blocks where TSpend was mined).
func serializeTSpend(blocks []chainhash.Hash) ([]byte, error) {
serializedData := new(bytes.Buffer)
err := binary.Write(serializedData, byteOrder, int64(len(blocks)))
if err != nil {
return nil, err
}
for _, v := range blocks {
err := binary.Write(serializedData, byteOrder, v[:])
if err != nil {
return nil, err
}
}
return serializedData.Bytes(), nil
}
// deserializeTSpend deserializes a binary blob into a []chainhash.Hash.
func deserializeTSpend(data []byte) ([]chainhash.Hash, error) {
buf := bytes.NewReader(data)
var count int64
err := binary.Read(buf, byteOrder, &count)
if err != nil {
return nil, fmt.Errorf("failed to read count: %w", err)
}
hashes := make([]chainhash.Hash, count)
for i := int64(0); i < count; i++ {
err := binary.Read(buf, byteOrder, &hashes[i])
if err != nil {
return nil,
fmt.Errorf("failed to read idx %v: %w", i, err)
}
}
return hashes, nil
}
// dbPutTSpend inserts a number of treasury tspends into a single database
// record. Note that this call is the low level write to the database. Use
// dbUpdateTSpend instead.
func dbPutTSpend(dbTx database.Tx, tx chainhash.Hash, blocks []chainhash.Hash) error {
// Serialize the current treasury state.
serializedData, err := serializeTSpend(blocks)
if err != nil {
return err
}
// Store the current treasury state into the database.
meta := dbTx.Metadata()
bucket := meta.Bucket(treasuryTSpendBucketName)
return bucket.Put(tx[:], serializedData)
}
// errDbTSpend signifies that the provided hash was not found during a fetch.
type errDbTSpend string
// Error implements the error interface.
func (e errDbTSpend) Error() string {
return string(e)
}
// dbFetchTSpend uses an existing database transaction to fetch the block
// hashes that contains the provided transaction.
func dbFetchTSpend(dbTx database.Tx, tx chainhash.Hash) ([]chainhash.Hash, error) {
meta := dbTx.Metadata()
bucket := meta.Bucket(treasuryTSpendBucketName)
v := bucket.Get(tx[:])
if v == nil {
return nil, errDbTSpend(fmt.Sprintf("tspend db missing key: %v",
tx))
}
return deserializeTSpend(v)
}
// dbUpdateTSpend performs a read/modify/write operation on the provided
// transaction hash. It reads the record and appends the block hash and then
// writes it back to the database. Note that the append is dumb and does not
// deduplicate. This is ok because in practice a TX cannot appear in the same
// block more than once.
func dbUpdateTSpend(dbTx database.Tx, tx, block chainhash.Hash) error {
var derr errDbTSpend
hashes, err := dbFetchTSpend(dbTx, tx)
if err != nil && !errors.As(err, &derr) {
return err
}
hashes = append(hashes, block)
return dbPutTSpend(dbTx, tx, hashes)
}
// FetchTSpend returns the blocks a treasury spend tx was included in.
func (b *BlockChain) FetchTSpend(tspend chainhash.Hash) ([]chainhash.Hash, error) {
var hashes []chainhash.Hash
err := b.db.View(func(dbTx database.Tx) error {
var err error
hashes, err = dbFetchTSpend(dbTx, tspend)
return err
})
return hashes, err
}
// calculateTreasuryBalance calculates the treasury balance as of the provided
// node.
//
// The treasury balance for a given block is calculated as the balance of its
// parent block plus all maturing TADDs and TreasuryBases minus all maturing
// TSPENDS.
//
// The "maturing" TADDs, TreasuryBases and TSPENDS are those that were in the
// CoinbaseMaturity ancestor block of the passed node.
func (b *BlockChain) calculateTreasuryBalance(dbTx database.Tx, node *blockNode) int64 {
wantNode := node.RelativeAncestor(int64(b.chainParams.CoinbaseMaturity))
if wantNode == nil {
// Since the node does not exist we can safely assume the
// balance is 0. This is true at the beginning of the chain
// because before CoinbaseMaturity blocks there can be no
// mature treasurybase or funds from which to create a TADD.
return 0
}
// Current balance is in the parent node
ts, err := dbFetchTreasuryBalance(dbTx, node.parent.hash)
if err != nil {
// Since the node.parent.hash does not exist in the treasury db
// we can safely assume the balance is 0
return 0
}
// Fetch values that need to be added to the treasury balance.
wts, err := dbFetchTreasuryBalance(dbTx, wantNode.hash)
if err != nil {
// Since wantNode does not exist in the treasury db we can
// safely assume the balance is 0
return 0
}
// Add all TAdd values to the balance. Note that negative Values are
// TSpend.
var netValue int64
for _, v := range wts.values {
netValue += v.amount
}
return ts.balance + netValue
}
// dbPutTreasuryBalance inserts the current balance and the future treasury
// add/spend into the database.
func (b *BlockChain) dbPutTreasuryBalance(dbTx database.Tx, block *dcrutil.Block, node *blockNode) error {
// Calculate balance as of this node
balance := b.calculateTreasuryBalance(dbTx, node)
msgBlock := block.MsgBlock()
ts := treasuryState{
balance: balance,
values: make([]treasuryValue, 0, len(msgBlock.Transactions)*2),
}
trsyLog.Tracef("dbPutTreasuryBalance: %v start balance %v",
node.hash.String(), balance)
for _, v := range msgBlock.STransactions {
if stake.IsTAdd(v) {
// This is a TAdd, pull amount out of TxOut[0]. Note
// that TxOut[1], if it exists, contains the change
// output. We have to ignore change.
tv := treasuryValue{
typ: treasuryValueTAdd,
amount: v.TxOut[0].Value,
}
ts.values = append(ts.values, tv)
trsyLog.Tracef(" dbPutTreasuryBalance: balance TADD "+
"%v", tv.amount)
} else if stake.IsTreasuryBase(v) {
tv := treasuryValue{
typ: treasuryValueTBase,
amount: v.TxOut[0].Value,
}
ts.values = append(ts.values, tv)
trsyLog.Tracef(" dbPutTreasuryBalance: balance "+
"treasury base %v", tv.amount)
} else if stake.IsTSpend(v) {
// This is a TSpend, pull values out of block. Skip
// first TxOut since it is an OP_RETURN.
var totalOut int64
for _, vv := range v.TxOut[1:] {
tv := treasuryValue{
typ: treasuryValueTSpend,
amount: -vv.Value,
}
trsyLog.Tracef(" dbPutTreasuryBalance: "+
"balance TSPEND %v", tv.amount)
ts.values = append(ts.values, tv)
totalOut += vv.Value
}
// Fees are supposed to be stored as negative amounts
// in a treasuryValue value, so calculate it backwards
// from the usual way of `in - out`.
fee := totalOut - v.TxIn[0].ValueIn
tv := treasuryValue{
typ: treasuryValueFee,
amount: fee,
}
trsyLog.Tracef(" dbPutTreasuryBalance: "+
"balance fee %v", tv.amount)
ts.values = append(ts.values, tv)
}
}
hash := block.Hash()
return dbPutTreasuryBalance(dbTx, *hash, ts)
}
// dbPutTSpend inserts the TSpends that are included in this block to the
// database.
func (b *BlockChain) dbPutTSpend(dbTx database.Tx, block *dcrutil.Block) error {
hash := block.Hash()
msgBlock := block.MsgBlock()
trsyLog.Tracef("dbPutTSpend: processing block %v", hash)
for _, v := range msgBlock.STransactions {
if !stake.IsTSpend(v) {
continue
}
// Store TSpend and the block it was included in.
txHash := v.TxHash()
trsyLog.Tracef(" dbPutTSpend: tspend %v", txHash)
err := dbUpdateTSpend(dbTx, txHash, *hash)
if err != nil {
return err
}
}
return nil
}
// TreasuryBalanceInfo models information about the treasury balance as of a
// given block.
type TreasuryBalanceInfo struct {
// BlockHeight is the height of the requested block.
BlockHeight int64
// Balance is the balance of the treasury as of the requested block.
Balance uint64
// Updates specifies all additions to and spends from the treasury in
// the requested block.
Updates []int64
}
// TreasuryBalance returns treasury balance information as of the given block.
func (b *BlockChain) TreasuryBalance(hash *chainhash.Hash) (*TreasuryBalanceInfo, error) {
node := b.index.LookupNode(hash)
if node == nil || !b.index.CanValidate(node) {
return nil, unknownBlockError(hash)
}
// Treasury agenda is never active for the genesis block.
if node.parent == nil {
str := fmt.Sprintf("treasury balance not available for block %s", hash)
return nil, contextError(ErrNoTreasuryBalance, str)
}
// Ensure the treasury agenda is active as of the requested block.
var isActive bool
b.chainLock.Lock()
isActive, err := b.isTreasuryAgendaActive(node.parent)
b.chainLock.Unlock()
if err != nil {
return nil, err
}
if !isActive {
str := fmt.Sprintf("treasury balance not available for block %s", hash)
return nil, contextError(ErrNoTreasuryBalance, str)
}
// Load treasury balance information.
var ts *treasuryState
err = b.db.View(func(dbTx database.Tx) error {
ts, err = dbFetchTreasuryBalance(dbTx, node.hash)
return err
})
if err != nil {
return nil, err
}
updates := make([]int64, len(ts.values))
for i := range ts.values {
updates[i] = ts.values[i].amount
}
return &TreasuryBalanceInfo{
BlockHeight: node.height,
Balance: uint64(ts.balance),
Updates: updates,
}, nil
}
// verifyTSpendSignature verifies that the provided signature and public key
// were the ones that signed the provided message transaction.
func verifyTSpendSignature(msgTx *wire.MsgTx, signature, pubKey []byte) error {
// Calculate signature hash.
sigHash, err := txscript.CalcSignatureHash(nil,
txscript.SigHashAll, msgTx, 0, nil)
if err != nil {
return fmt.Errorf("CalcSignatureHash: %w", err)
}
// Lift Signature from bytes.
sig, err := schnorr.ParseSignature(signature)
if err != nil {
return fmt.Errorf("ParseSignature: %w", err)
}
// Lift public PI key from bytes.
pk, err := schnorr.ParsePubKey(pubKey)
if err != nil {
return fmt.Errorf("ParsePubKey: %w", err)
}
// Verify transaction was properly signed.
if !sig.Verify(sigHash, pk) {
return fmt.Errorf("Verify failed")
}
return nil
}
// VerifyTSpendSignature verifies that the provided signature and public key
// were the ones that signed the provided message transaction.
//
// Note: This function should only be called with a valid TSpend.
func VerifyTSpendSignature(msgTx *wire.MsgTx, signature, pubKey []byte) error {
return verifyTSpendSignature(msgTx, signature, pubKey)
}
// sumPastTreasuryExpenditure sums up all tspends found within the range
// (node-nbBlocks..node). Note that this sum is _inclusive_ of the passed block
// and is performed in descending order. Generally, the passed node will be a
// node immediately before a TVI block.
//
// It also returns the node immediately before the last checked node (that is,
// the node before node-nbBlocks).
func (b *BlockChain) sumPastTreasuryExpenditure(preTVINode *blockNode, nbBlocks uint64) (int64, *blockNode, error) {
node := preTVINode
var total int64
var derr errDbTreasury
for i := uint64(0); i < nbBlocks && node != nil; i++ {
ts, err := b.dbFetchTreasurySingle(node.hash)
if errors.As(err, &derr) {
// Record doesn't exist. Means we reached the end of
// when treasury records are available.
node = nil
continue
} else if err != nil {
return 0, nil, err
}
// Range over values.
for _, v := range ts.values {
isTreasuryDebit := v.typ == treasuryValueTSpend ||
v.typ == treasuryValueFee
if isTreasuryDebit {
// treasuryValues record debits as negative
// amounts, so invert it here.
total += -v.amount
}
}
node = node.parent
}
return total, node, nil
}
// maxTreasuryExpenditure returns the maximum amount of funds that can be spent
// from the treasury at the block after the provided node. A set of TSPENDs
// added to a TVI block that is a child to the passed node may spend up to the
// returned amount.
//
// The passed node MUST correspond to a node immediately prior to a TVI block.
func (b *BlockChain) maxTreasuryExpenditure(preTVINode *blockNode) (int64, error) {
// The expenditure policy check is roughly speaking:
//
// "The sum of tspends inside an expenditure window cannot exceed
// the average of the tspends in the previous N windows in addition
// to an X% increase."
//
// So in order to calculate the maximum expenditure for the _next_
// block (the block after `preTVINode`, which must be a TVI block) we
// need to add all the tspends in the expenditure window that ends in
// `preTVINode` and subtract that amount from the average of the
// preceding (N) windows.
//
// Currently this function is pretty naive. It simply iterates through
// prior blocks one at a time. This is very expensive and may need to
// be rethought into a proper index.
policyWindow := b.chainParams.TreasuryVoteInterval *
b.chainParams.TreasuryVoteIntervalMultiplier *
b.chainParams.TreasuryExpenditureWindow
// Each policy window starts at a TVI block and ends at the block
// immediately prior to another TVI (inclusive of preTVINode).
//
// First: sum up tspends inside the most recent policyWindow.
spentRecentWindow, node, err := b.sumPastTreasuryExpenditure(preTVINode, policyWindow)
if err != nil {
return 0, err
}
// Next, sum up all tspends inside the N prior policy windows. If a
// given policy window does not have _any_ tspends, it isn't counted
// towards the average.
var spentPriorWindows int64
var nbNonEmptyWindows int64
for i := uint64(0); i < b.chainParams.TreasuryExpenditurePolicy && node != nil; i++ {
var spent int64
spent, node, err = b.sumPastTreasuryExpenditure(node, policyWindow)
if err != nil {
return 0, err
}
if spent > 0 {
spentPriorWindows += spent
nbNonEmptyWindows++
}
}
// Calculate the average spent in each window. If there were _zero_
// prior windows with tspends, fall back to using the bootstrap
// average.
var avgSpentPriorWindows int64
if nbNonEmptyWindows > 0 {
avgSpentPriorWindows = spentPriorWindows / nbNonEmptyWindows
} else {
avgSpentPriorWindows = int64(b.chainParams.TreasuryExpenditureBootstrap)
}
// Treasury can spend up to 150% the average amount of the prior
// windows ("expenditure allowance").
avgPlusAllowance := avgSpentPriorWindows + avgSpentPriorWindows/2
// The maximum expenditure allowed for the next block is the difference
// between the maximum possible and what has already been spent in the most
// recent policy window. This is capped at zero on the lower end to account
// for cases where the policy _already_ spent more than the allowed.
var allowedToSpend int64
if avgPlusAllowance > spentRecentWindow {
allowedToSpend = avgPlusAllowance - spentRecentWindow
}
trsyLog.Tracef(" maxTSpendExpenditure: recentWindow %d priorWindows %d "+
"(%d non-empty) allowedToSpend %d", spentRecentWindow,
spentPriorWindows, nbNonEmptyWindows, allowedToSpend)
return allowedToSpend, nil
}
// MaxTreasuryExpenditure is the maximum amount of funds that can be spent from
// the treasury by a set of TSpends for a block that extends the given block
// hash. Function will return 0 if it is called on an invalid TVI.
func (b *BlockChain) MaxTreasuryExpenditure(preTVIBlock *chainhash.Hash) (int64, error) {
preTVINode := b.index.LookupNode(preTVIBlock)
if preTVINode == nil {
return 0, fmt.Errorf("unknown block %s", preTVIBlock)
}
if !standalone.IsTreasuryVoteInterval(uint64(preTVINode.height+1),
b.chainParams.TreasuryVoteInterval) {
return 0, nil
}
return b.maxTreasuryExpenditure(preTVINode)
}
// checkTSpendsExpenditure verifies that the sum of TSpend expenditures is
// within the allowable range for the chain ending in the given node. There is
// a hard requirement that the passed node is a block immediately prior to a
// TVI block (with the tspends assumed to be txs in a block that extends
// preTVINode).
//
// The expenditure check is performed against the balance at preTVINode.
//
// This function must be called with the block index read lock held.
func (b *BlockChain) checkTSpendsExpenditure(preTVINode *blockNode, totalTSpendAmount int64) error {
trsyLog.Tracef("checkTSpendExpenditure: processing %d tspent at height %d",
totalTSpendAmount, preTVINode.height+1)
if totalTSpendAmount == 0 {
// Nothing to do.
return nil
}
if totalTSpendAmount < 0 {
return fmt.Errorf("invalid precondition: totalTSpendAmount must "+
"not be negative (got %d)", totalTSpendAmount)
}
// Ensure that we are not depleting treasury.
var (
treasuryBalance int64
err error
)
err = b.db.View(func(dbTx database.Tx) error {
treasuryBalance = b.calculateTreasuryBalance(dbTx, preTVINode)
return nil
})
if err != nil {
return err
}
if treasuryBalance-totalTSpendAmount < 0 {
return fmt.Errorf("treasury balance may not become negative: "+
"balance %v spend %v", treasuryBalance, totalTSpendAmount)
}
trsyLog.Tracef(" checkTSpendExpenditure: balance %v spend %v",
treasuryBalance, totalTSpendAmount)
allowedToSpend, err := b.maxTreasuryExpenditure(preTVINode)
if err != nil {
return err
}
if totalTSpendAmount > allowedToSpend {
return fmt.Errorf("treasury spend greater than allowed %v > %v",
totalTSpendAmount, allowedToSpend)
}
return nil
}
// checkTSpendExists verifies that the provided TSpend has not been mined in a
// block on the chain of prevNode.
func (b *BlockChain) checkTSpendExists(prevNode *blockNode, tspend chainhash.Hash) error {
trsyLog.Tracef(" checkTSpendExists: tspend %v", tspend)
var derr errDbTSpend
blocks, err := b.FetchTSpend(tspend)
if errors.As(err, &derr) {
// Record does not exist.
return nil
} else if err != nil {
return err
}
// Do fork detection on all blocks.
for _, v := range blocks {
// Lookup blockNode.
node := b.index.LookupNode(&v)
if node == nil {
// This should not happen.
trsyLog.Errorf(" checkTSpendExists: block not found "+
"%v tspend %v", v, tspend)
continue
}
if prevNode.Ancestor(node.height) != node {
trsyLog.Errorf(" checkTSpendExists: not ancestor "+
"block %v tspend %v", v, tspend)
continue
}
trsyLog.Errorf(" checkTSpendExists: is ancestor "+
"block %v tspend %v", v, tspend)
return fmt.Errorf("tspend has already been mined on this "+
"chain %v", tspend)
}
return nil
}
// CheckTSpendExists verifies that the provided TSpend has not been mined in a
// block on the chain of the provided block hash.
func (b *BlockChain) CheckTSpendExists(prevHash, tspend chainhash.Hash) error {
prevNode := b.index.LookupNode(&prevHash)
if prevNode == nil {
return nil
}
return b.checkTSpendExists(prevNode, tspend)
}
// getVotes returns yes and no votes for the provided hash.
func getVotes(votes []stake.TreasuryVoteTuple, hash *chainhash.Hash) (yes int, no int) {
if votes == nil {
return
}
for _, v := range votes {
if !hash.IsEqual(&v.Hash) {
continue
}
switch v.Vote {
case stake.TreasuryVoteYes:
yes++
case stake.TreasuryVoteNo:
no++
default:
// Can't happen.
trsyLog.Criticalf("getVotes: invalid vote 0x%v", v.Vote)
}
}
return
}
// tspendVotes is a structure that contains a treasury vote tally for a given
// window.
type tspendVotes struct {
start uint32 // Start block
end uint32 // End block
yes int // Yes vote tally
no int // No vote tally
}
// tSpendCountVotes returns the vote tally for a given tspend up to the
// specified block. Note that this function errors if the block is outside the
// voting window for the given tspend.
func (b *BlockChain) tSpendCountVotes(prevNode *blockNode, tspend *dcrutil.Tx) (*tspendVotes, error) {
trsyLog.Tracef("tSpendCountVotes: processing tspend %v", tspend.Hash())
var (
t tspendVotes
err error
)
expiry := tspend.MsgTx().Expiry
t.start, t.end, err = standalone.CalcTSpendWindow(expiry,
b.chainParams.TreasuryVoteInterval,
b.chainParams.TreasuryVoteIntervalMultiplier)
if err != nil {
return nil, err
}
nextHeight := prevNode.height + 1
trsyLog.Tracef(" tSpendCountVotes: nextHeight %v start %v expiry %v",
nextHeight, t.start, t.end)
// Ensure tspend is within the window.
if !standalone.InsideTSpendWindow(nextHeight,
expiry, b.chainParams.TreasuryVoteInterval,
b.chainParams.TreasuryVoteIntervalMultiplier) {
err = fmt.Errorf("tspend outside of window: nextHeight %v "+
"start %v expiry %v", nextHeight, t.start, expiry)
return nil, err
}
// Walk prevNode back to the start of the window and count votes.
node := prevNode
for {
trsyLog.Tracef(" tSpendCountVotes height %v start %v",
node.height, t.start)
if node.height < int64(t.start) {
break
}
trsyLog.Tracef(" tSpendCountVotes count votes: %v",
node.hash)
// Find SSGen and peel out votes.
var xblock *dcrutil.Block
xblock, err = b.fetchBlockByNode(node)
if err != nil {
// Should not happen.
return nil, err
}
for _, v := range xblock.STransactions() {
votes, err := stake.CheckSSGenVotes(v.MsgTx(),
yesTreasury)
if err != nil {
// Not an SSGEN
continue
}
// Find our vote bits.
yes, no := getVotes(votes, tspend.Hash())
t.yes += yes
t.no += no
}
node = node.parent
if node == nil {
break
}
}
return &t, nil
}
// TSpendCountVotes tallies the votes given for the specified tspend during its
// voting interval, up to the specified block. It returns the number of yes and
// no votes found between the passed block's height and the start of voting.
//
// Note that this function errors if the block _after_ the specified block is
// outside the tpsend voting window. In particular, calling this function for
// the TVI block that ends the voting interval for a given tspend fails, since
// the next block is outside the voting interval.
//
// This function is safe for concurrent access.
func (b *BlockChain) TSpendCountVotes(blockHash *chainhash.Hash, tspend *dcrutil.Tx) (yesVotes, noVotes int64, err error) {
b.index.RLock()
defer b.index.RUnlock()
prevNode := b.index.lookupNode(blockHash)
if prevNode == nil {
return 0, 0, unknownBlockError(blockHash)
}
tv, err := b.tSpendCountVotes(prevNode, tspend)
if err != nil {
return 0, 0, err
}
return int64(tv.yes), int64(tv.no), nil
}
// checkTSpendHasVotes verifies that the provided TSpend has enough votes to be
// included in a block _after_ the provided block node. Such child node MUST be
// on a TVI.
func (b *BlockChain) checkTSpendHasVotes(prevNode *blockNode, tspend *dcrutil.Tx) error {
t, err := b.tSpendCountVotes(prevNode, tspend)
if err != nil {
return err
}
// Passing criteria are 20% quorum and 60% yes.
maxVotes := uint32(b.chainParams.TicketsPerBlock) * (t.end - t.start)
quorum := uint64(maxVotes) * b.chainParams.TreasuryVoteQuorumMultiplier /
b.chainParams.TreasuryVoteQuorumDivisor
numVotesCast := uint64(t.yes + t.no)
if numVotesCast < quorum {
return fmt.Errorf("quorum not met: yes %v no %v "+
"quorum %v max %v", t.yes, t.no, quorum, maxVotes)
}
// Calculate max possible votes that are left in this window.
curBlockHeight := uint32(prevNode.height + 1)