forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subsidy.go
350 lines (292 loc) · 10.5 KB
/
subsidy.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
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2016 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"
"fmt"
"sync"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
)
// The number of values to precalculate on initialization of the subsidy
// cache.
const subsidyCacheInitWidth = 4
// SubsidyCache is a structure that caches calculated values of subsidy so that
// they're not constantly recalculated. The blockchain struct itself possesses a
// pointer to a preinitialized SubsidyCache.
type SubsidyCache struct {
subsidyCache map[uint64]int64
subsidyCacheLock sync.RWMutex
params *chaincfg.Params
}
// NewSubsidyCache initializes a new subsidy cache for a given height. It
// precalculates the values of the subsidy that are most likely to be seen by
// the client when it connects to the network.
func NewSubsidyCache(height int64, params *chaincfg.Params) *SubsidyCache {
scm := make(map[uint64]int64)
sc := SubsidyCache{
subsidyCache: scm,
params: params,
}
iteration := uint64(height / params.SubsidyReductionInterval)
if iteration < subsidyCacheInitWidth {
return &sc
}
for i := iteration - 4; i <= iteration; i++ {
sc.CalcBlockSubsidy(int64(iteration) * params.SubsidyReductionInterval)
}
return &sc
}
// CalcBlockSubsidy returns the subsidy amount a block at the provided height
// should have. This is mainly used for determining how much the coinbase for
// newly generated blocks awards as well as validating the coinbase for blocks
// has the expected value.
//
// Subsidy calculation for exponential reductions:
// 0 for i in range (0, height / SubsidyReductionInterval):
// 1 subsidy *= MulSubsidy
// 2 subsidy /= DivSubsidy
//
// Safe for concurrent access.
func (s *SubsidyCache) CalcBlockSubsidy(height int64) int64 {
// Block height 1 subsidy is 'special' and used to
// distribute initial tokens, if any.
if height == 1 {
return s.params.BlockOneSubsidy()
}
iteration := uint64(height / s.params.SubsidyReductionInterval)
if iteration == 0 {
return s.params.BaseSubsidy
}
// First, check the cache.
s.subsidyCacheLock.RLock()
cachedValue, existsInCache := s.subsidyCache[iteration]
s.subsidyCacheLock.RUnlock()
if existsInCache {
return cachedValue
}
// Is the previous one in the cache? If so, calculate
// the subsidy from the previous known value and store
// it in the database and the cache.
s.subsidyCacheLock.RLock()
cachedValue, existsInCache = s.subsidyCache[iteration-1]
s.subsidyCacheLock.RUnlock()
if existsInCache {
cachedValue *= s.params.MulSubsidy
cachedValue /= s.params.DivSubsidy
s.subsidyCacheLock.Lock()
s.subsidyCache[iteration] = cachedValue
s.subsidyCacheLock.Unlock()
return cachedValue
}
// Calculate the subsidy from scratch and store in the
// cache. TODO If there's an older item in the cache,
// calculate it from that to save time.
subsidy := s.params.BaseSubsidy
for i := uint64(0); i < iteration; i++ {
subsidy *= s.params.MulSubsidy
subsidy /= s.params.DivSubsidy
}
s.subsidyCacheLock.Lock()
s.subsidyCache[iteration] = subsidy
s.subsidyCacheLock.Unlock()
return subsidy
}
// CalcBlockWorkSubsidy calculates the proof of work subsidy for a block as a
// proportion of the total subsidy.
func CalcBlockWorkSubsidy(subsidyCache *SubsidyCache, height int64,
voters uint16, params *chaincfg.Params) int64 {
subsidy := subsidyCache.CalcBlockSubsidy(height)
proportionWork := int64(params.WorkRewardProportion)
proportions := int64(params.TotalSubsidyProportions())
subsidy *= proportionWork
subsidy /= proportions
// Ignore the voters field of the header before we're at a point
// where there are any voters.
if height < params.StakeValidationHeight {
return subsidy
}
// If there are no voters, subsidy is 0. The block will fail later anyway.
if voters == 0 {
return 0
}
// Adjust for the number of voters. This shouldn't ever overflow if you start
// with 50 * 10^8 Atoms and voters and potentialVoters are uint16.
potentialVoters := params.TicketsPerBlock
actual := (int64(voters) * subsidy) / int64(potentialVoters)
return actual
}
// CalcStakeVoteSubsidy calculates the subsidy for a stake vote based on the height
// of its input SStx.
//
// Safe for concurrent access.
func CalcStakeVoteSubsidy(subsidyCache *SubsidyCache, height int64,
params *chaincfg.Params) int64 {
// Calculate the actual reward for this block, then further reduce reward
// proportional to StakeRewardProportion.
// Note that voters/potential voters is 1, so that vote reward is calculated
// irrespective of block reward.
subsidy := subsidyCache.CalcBlockSubsidy(height)
proportionStake := int64(params.StakeRewardProportion)
proportions := int64(params.TotalSubsidyProportions())
subsidy *= proportionStake
subsidy /= (proportions * int64(params.TicketsPerBlock))
return subsidy
}
// CalcBlockTaxSubsidy calculates the subsidy for the organization address in the
// coinbase.
//
// Safe for concurrent access.
func CalcBlockTaxSubsidy(subsidyCache *SubsidyCache, height int64, voters uint16,
params *chaincfg.Params) int64 {
if params.BlockTaxProportion == 0 {
return 0
}
subsidy := subsidyCache.CalcBlockSubsidy(height)
proportionTax := int64(params.BlockTaxProportion)
proportions := int64(params.TotalSubsidyProportions())
subsidy *= proportionTax
subsidy /= proportions
// Assume all voters 'present' before stake voting is turned on.
if height < params.StakeValidationHeight {
voters = 5
}
// If there are no voters, subsidy is 0. The block will fail later anyway.
if voters == 0 && height >= params.StakeValidationHeight {
return 0
}
// Adjust for the number of voters. This shouldn't ever overflow if you start
// with 50 * 10^8 Atoms and voters and potentialVoters are uint16.
potentialVoters := params.TicketsPerBlock
adjusted := (int64(voters) * subsidy) / int64(potentialVoters)
return adjusted
}
// BlockOneCoinbasePaysTokens checks to see if the first block coinbase pays
// out to the network initial token ledger.
func BlockOneCoinbasePaysTokens(tx *dcrutil.Tx,
params *chaincfg.Params) error {
// If no ledger is specified, just return true.
if len(params.BlockOneLedger) == 0 {
return nil
}
if tx.MsgTx().LockTime != 0 {
errStr := fmt.Sprintf("block 1 coinbase has invalid locktime")
return ruleError(ErrBlockOneTx, errStr)
}
if tx.MsgTx().Expiry != wire.NoExpiryValue {
errStr := fmt.Sprintf("block 1 coinbase has invalid expiry")
return ruleError(ErrBlockOneTx, errStr)
}
if tx.MsgTx().TxIn[0].Sequence != wire.MaxTxInSequenceNum {
errStr := fmt.Sprintf("block 1 coinbase not finalized")
return ruleError(ErrBlockOneInputs, errStr)
}
if len(tx.MsgTx().TxOut) == 0 {
errStr := fmt.Sprintf("coinbase outputs empty in block 1")
return ruleError(ErrBlockOneOutputs, errStr)
}
ledger := params.BlockOneLedger
if len(ledger) != len(tx.MsgTx().TxOut) {
errStr := fmt.Sprintf("wrong number of outputs in block 1 coinbase; "+
"got %v, expected %v", len(tx.MsgTx().TxOut), len(ledger))
return ruleError(ErrBlockOneOutputs, errStr)
}
// Check the addresses and output amounts against those in the ledger.
for i, txout := range tx.MsgTx().TxOut {
if txout.Version != txscript.DefaultScriptVersion {
errStr := fmt.Sprintf("bad block one output version; want %v, got %v",
txscript.DefaultScriptVersion, txout.Version)
return ruleError(ErrBlockOneOutputs, errStr)
}
// There should only be one address.
_, addrs, _, err :=
txscript.ExtractPkScriptAddrs(txout.Version, txout.PkScript, params)
if err != nil {
return ruleError(ErrBlockOneOutputs, err.Error())
}
if len(addrs) != 1 {
errStr := fmt.Sprintf("too many addresses in output")
return ruleError(ErrBlockOneOutputs, errStr)
}
addrLedger, err := dcrutil.DecodeAddress(ledger[i].Address)
if err != nil {
return err
}
if !bytes.Equal(addrs[0].ScriptAddress(), addrLedger.ScriptAddress()) {
errStr := fmt.Sprintf("address in output %v has non matching "+
"address; got %v (hash160 %x), want %v (hash160 %x)",
i,
addrs[0].EncodeAddress(),
addrs[0].ScriptAddress(),
addrLedger.EncodeAddress(),
addrLedger.ScriptAddress())
return ruleError(ErrBlockOneOutputs, errStr)
}
if txout.Value != ledger[i].Amount {
errStr := fmt.Sprintf("address in output %v has non matching "+
"amount; got %v, want %v", i, txout.Value, ledger[i].Amount)
return ruleError(ErrBlockOneOutputs, errStr)
}
}
return nil
}
// CoinbasePaysTax checks to see if a given block's coinbase correctly pays
// tax to the developer organization.
func CoinbasePaysTax(subsidyCache *SubsidyCache, tx *dcrutil.Tx, height uint32,
voters uint16, params *chaincfg.Params) error {
// Taxes only apply from block 2 onwards.
if height <= 1 {
return nil
}
// Tax is disabled.
if params.BlockTaxProportion == 0 {
return nil
}
if len(tx.MsgTx().TxOut) == 0 {
errStr := fmt.Sprintf("invalid coinbase (no outputs)")
return ruleError(ErrNoTxOutputs, errStr)
}
taxOutput := tx.MsgTx().TxOut[0]
if taxOutput.Version != params.OrganizationPkScriptVersion {
return ruleError(ErrNoTax,
"coinbase tax output uses incorrect script version")
}
if !bytes.Equal(taxOutput.PkScript, params.OrganizationPkScript) {
return ruleError(ErrNoTax,
"coinbase tax output script does not match the "+
"required script")
}
// Get the amount of subsidy that should have been paid out to
// the organization, then check it.
orgSubsidy := CalcBlockTaxSubsidy(subsidyCache, int64(height), voters, params)
if orgSubsidy != taxOutput.Value {
errStr := fmt.Sprintf("amount in output 0 has non matching org "+
"calculated amount; got %v, want %v", taxOutput.Value,
orgSubsidy)
return ruleError(ErrNoTax, errStr)
}
return nil
}
// CalculateAddedSubsidy calculates the amount of subsidy added by a block
// and its parent. The blocks passed to this function MUST be valid blocks
// that have already been confirmed to abide by the consensus rules of the
// network, or the function might panic.
func CalculateAddedSubsidy(block, parent *dcrutil.Block) int64 {
var subsidy int64
regularTxTreeValid := dcrutil.IsFlagSet16(block.MsgBlock().Header.VoteBits,
dcrutil.BlockValid)
if regularTxTreeValid {
subsidy += parent.MsgBlock().Transactions[0].TxIn[0].ValueIn
}
for _, stx := range block.MsgBlock().STransactions {
if isSSGen, _ := stake.IsSSGen(stx); isSSGen {
subsidy += stx.TxIn[0].ValueIn
}
}
return subsidy
}