blockchain: Remove deprecated code.

This removes the deprecated functions along with the additional code and
tests which are no longer necessary as a result of removing the
functions.

The following is a list of exported types and functions removed along
with what they were replaced by when applicable:

- DisableLog -> UseLogger(slog.Disabled)
- BlockOneCoinbasePaysTokens -> no alternative, internal only
- IsCoinBase -> standalone.IsCoinBaseTx
- IsCoinBaseTx -> standalone.IsCoinBaseTx
- BuildMerkleTreeStore -> standalone.CalcTxTreeMerkleRoot
- BuildMsgTxMerkleTreeStore -> standalone.CalcTxTreeMerkleRoot
- SubsidyCache -> standalone.SubsidyCache
- NewSubsidyCache -> standalone.NewSubsidyCache
- CalcBlockWorkSubsidy -> standalone.SubsidyCache.CalcWorkSubsidy
- CalcStakeVoteSubsidy -> standalone.SubsidyCache.CalcStakeVoteSubsidy
- CalcBlockTaxSubsidy -> standalone.SubsidyCache.CalcTreasurySubsidy
- CoinbasePaysTax -> no alternative, internal only
- CalculateAddedSubsidy -> no alternative, internal only
- BestPrevHash -> BestSnapshot.PrevHash
- TotalSubsidy -> BestSnapshot.TotalSubsidy
- FetchSubsidyCache -> standalone.NewSubsidyCache passed to chain
- HashToBig -> standalone.HashToBig
- CompactToBig -> standalone.CompactToBig
- BigToCompact -> standalone.BigToCompact
- CalcWork -> standalone.CalcWork
- CheckProofOfWork -> standalone.CheckProofOfWork
This commit is contained in:
Dave Collins 2019-08-06 00:29:55 -05:00
parent 2dac209198
commit 469f985f86
No known key found for this signature in database
GPG Key ID: B8904D9D9C93D1F2
10 changed files with 1 additions and 528 deletions

View File

@ -352,24 +352,6 @@ func (b *BlockChain) DisableVerify(disable bool) {
b.chainLock.Unlock()
}
// TotalSubsidy returns the total subsidy mined so far in the best chain.
//
// This function is safe for concurrent access.
func (b *BlockChain) TotalSubsidy() int64 {
b.chainLock.RLock()
ts := b.BestSnapshot().TotalSubsidy
b.chainLock.RUnlock()
return ts
}
// FetchSubsidyCache returns the current subsidy cache from the blockchain.
//
// This function is safe for concurrent access.
func (b *BlockChain) FetchSubsidyCache() *SubsidyCache {
return b.subsidyCache
}
// HaveBlock returns whether or not the chain instance has the block represented
// by the passed hash. This includes checking the various places a block can
// be like part of the main chain, on a side chain, or in the orphan pool.
@ -644,21 +626,6 @@ func (b *BlockChain) pruneStakeNodes() {
}
}
// BestPrevHash returns the hash of the previous block of the block at HEAD.
//
// This function is safe for concurrent access.
func (b *BlockChain) BestPrevHash() chainhash.Hash {
b.chainLock.Lock()
defer b.chainLock.Unlock()
var prevHash chainhash.Hash
tip := b.bestChain.Tip()
if tip.parent != nil {
prevHash = tip.parent.hash
}
return prevHash
}
// isMajorityVersion determines if a previous number of blocks in the chain
// starting with startNode are at least the minimum passed version.
//

View File

@ -128,7 +128,7 @@ func TestBlockchainFunctions(t *testing.T) {
"TicketsWithAddress; want %v, got %v", expectedLen, len(hs))
}
totalSubsidy := chain.TotalSubsidy()
totalSubsidy := chain.BestSnapshot().TotalSubsidy
expectedSubsidy := int64(35783267326630)
if expectedSubsidy != totalSubsidy {
t.Errorf("Failed to get correct total subsidy for "+

View File

@ -30,69 +30,6 @@ var (
oneLsh256 = new(big.Int).Lsh(bigOne, 256)
)
// HashToBig converts a chainhash.Hash into a big.Int that can be used to
// perform math comparisons.
//
// Deprecated: Use standalone.HashToBig instead.
func HashToBig(hash *chainhash.Hash) *big.Int {
return standalone.HashToBig(hash)
}
// CompactToBig converts a compact representation of a whole number N to an
// unsigned 32-bit number. The representation is similar to IEEE754 floating
// point numbers.
//
// Like IEEE754 floating point, there are three basic components: the sign,
// the exponent, and the mantissa. They are broken out as follows:
//
// * the most significant 8 bits represent the unsigned base 256 exponent
// * bit 23 (the 24th bit) represents the sign bit
// * the least significant 23 bits represent the mantissa
//
// -------------------------------------------------
// | Exponent | Sign | Mantissa |
// -------------------------------------------------
// | 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] |
// -------------------------------------------------
//
// The formula to calculate N is:
// N = (-1^sign) * mantissa * 256^(exponent-3)
//
// This compact form is only used in Decred to encode unsigned 256-bit numbers
// which represent difficulty targets, thus there really is not a need for a
// sign bit, but it is implemented here to stay consistent with bitcoind.
//
// Deprecated: Use standalone.CompactToBig instead.
func CompactToBig(compact uint32) *big.Int {
return standalone.CompactToBig(compact)
}
// BigToCompact converts a whole number N to a compact representation using
// an unsigned 32-bit number. The compact representation only provides 23 bits
// of precision, so values larger than (2^23 - 1) only encode the most
// significant digits of the number. See CompactToBig for details.
//
// Deprecated: Use standalone.BigToCompact instead.
func BigToCompact(n *big.Int) uint32 {
return standalone.BigToCompact(n)
}
// CalcWork calculates a work value from difficulty bits. Decred increases
// the difficulty for generating a block by decreasing the value which the
// generated hash must be less than. This difficulty target is stored in each
// block header using a compact representation as described in the documentation
// for CompactToBig. The main chain is selected by choosing the chain that has
// the most proof of work (highest difficulty). Since a lower target difficulty
// value equates to higher actual difficulty, the work value which will be
// accumulated must be the inverse of the difficulty. Also, in order to avoid
// potential division by zero and really small floating point numbers, the
// result adds 1 to the denominator and multiplies the numerator by 2^256.
//
// Deprecated: Use standalone.CalcWork instead.
func CalcWork(bits uint32) *big.Int {
return standalone.CalcWork(bits)
}
// calcEasiestDifficulty calculates the easiest possible difficulty that a block
// can have given starting difficulty bits and a duration. It is mainly used to
// verify that claimed proof of work by a block is sane as compared to a

View File

@ -6,7 +6,6 @@
package blockchain
import (
"math/big"
"runtime"
"testing"
"time"
@ -15,63 +14,6 @@ import (
"github.com/decred/dcrd/wire"
)
func TestBigToCompact(t *testing.T) {
tests := []struct {
in int64
out uint32
}{
{0, 0},
{-1, 25231360},
}
for x, test := range tests {
n := big.NewInt(test.in)
r := BigToCompact(n)
if r != test.out {
t.Errorf("TestBigToCompact test #%d failed: got %d want %d\n",
x, r, test.out)
return
}
}
}
func TestCompactToBig(t *testing.T) {
tests := []struct {
in uint32
out int64
}{
{10000000, 0},
}
for x, test := range tests {
n := CompactToBig(test.in)
want := big.NewInt(test.out)
if n.Cmp(want) != 0 {
t.Errorf("TestCompactToBig test #%d failed: got %d want %d\n",
x, n.Int64(), want.Int64())
return
}
}
}
func TestCalcWork(t *testing.T) {
tests := []struct {
in uint32
out int64
}{
{10000000, 0},
}
for x, test := range tests {
r := CalcWork(test.in)
if r.Int64() != test.out {
t.Errorf("TestCalcWork test #%d failed: got %v want %d\n",
x, r.Int64(), test.out)
return
}
}
}
// TestEstimateSupply ensures the supply estimation function used in the stake
// difficulty algorithm defined by DCP0001 works as expected.
func TestEstimateSupply(t *testing.T) {

View File

@ -13,14 +13,6 @@ import "github.com/decred/slog"
// The default amount of logging is none.
var log = slog.Disabled
// DisableLog disables all library log output. Logging output is disabled
// by default until UseLogger is called.
//
// Deprecated: Use UseLogger(slog.Disabled) instead.
func DisableLog() {
log = slog.Disabled
}
// UseLogger uses a specified Logger to output package logging info.
// This should be used in preference to SetLogWriter if the caller is also
// using slog.

View File

@ -15,14 +15,6 @@ import (
// The default amount of logging is none.
var log = slog.Disabled
// DisableLog disables all library log output. Logging output is disabled
// by default until UseLogger is called.
//
// Deprecated: Use UseLogger(slog.Disabled) instead.
func DisableLog() {
log = slog.Disabled
}
// UseLogger uses a specified Logger to output package logging info.
func UseLogger(logger slog.Logger) {
log = logger

View File

@ -1,157 +0,0 @@
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2019 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 (
"math"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil/v2"
"github.com/decred/dcrd/wire"
)
// nextPowerOfTwo returns the next highest power of two from a given number if
// it is not already a power of two. This is a helper function used during the
// calculation of a merkle tree.
func nextPowerOfTwo(n int) int {
// Return the number if it's already a power of 2.
if n&(n-1) == 0 {
return n
}
// Figure out and return the next power of two.
exponent := uint(math.Log2(float64(n))) + 1
return 1 << exponent // 2^exponent
}
// HashMerkleBranches takes two hashes, treated as the left and right tree
// nodes, and returns the hash of their concatenation. This is a helper
// function used to aid in the generation of a merkle tree.
//
// Deprecated: Use standalone.CalcMerkleRoot instead.
func HashMerkleBranches(left *chainhash.Hash, right *chainhash.Hash) *chainhash.Hash {
// Concatenate the left and right nodes.
var hash [chainhash.HashSize * 2]byte
copy(hash[:chainhash.HashSize], left[:])
copy(hash[chainhash.HashSize:], right[:])
newHash := chainhash.HashH(hash[:])
return &newHash
}
// populateMerkleStore constructs the merkle tree from all transaction hashes
// before offset, saving the merkle hashes to the remaining entries in merkles
// beginning at offset.
func populateMerkleStore(offset int, merkles []*chainhash.Hash) {
// Start the array offset after the last transaction and adjusted to the
// next power of two.
for i := 0; i < len(merkles)-1; i += 2 {
switch {
// When there is no left child node, the parent is nil too.
case merkles[i] == nil:
merkles[offset] = nil
// When there is no right child, the parent is generated by
// hashing the concatenation of the left child with itself.
case merkles[i+1] == nil:
newHash := HashMerkleBranches(merkles[i], merkles[i])
merkles[offset] = newHash
// The normal case sets the parent node to the hash of the
// concatenation of the left and right children.
default:
newHash := HashMerkleBranches(merkles[i], merkles[i+1])
merkles[offset] = newHash
}
offset++
}
}
// BuildMerkleTreeStore creates a merkle tree from a slice of transactions,
// stores it using a linear array, and returns a slice of the backing array. A
// linear array was chosen as opposed to an actual tree structure since it uses
// about half as much memory. The following describes a merkle tree and how it
// is stored in a linear array.
//
// A merkle tree is a tree in which every non-leaf node is the hash of its
// children nodes. A diagram depicting how this works for Decred transactions
// where h(x) is a blake256 hash follows:
//
// root = h1234 = h(h12 + h34)
// / \
// h12 = h(h1 + h2) h34 = h(h3 + h4)
// / \ / \
// h1 = h(tx1) h2 = h(tx2) h3 = h(tx3) h4 = h(tx4)
//
// The above stored as a linear array is as follows:
//
// [h1 h2 h3 h4 h12 h34 root]
//
// As the above shows, the merkle root is always the last element in the array.
//
// The number of inputs is not always a power of two which results in a
// balanced tree structure as above. In that case, parent nodes with no
// children are also zero and parent nodes with only a single left node
// are calculated by concatenating the left node with itself before hashing.
// Since this function uses nodes that are pointers to the hashes, empty nodes
// will be nil.
//
// Deprecated: Use standalone.CalcTxTreeMerkleRoot instead.
func BuildMerkleTreeStore(transactions []*dcrutil.Tx) []*chainhash.Hash {
// If there's an empty stake tree, return totally zeroed out merkle tree root
// only.
if len(transactions) == 0 {
return []*chainhash.Hash{new(chainhash.Hash)}
}
// Calculate how many entries are required to hold the binary merkle
// tree as a linear array and create an array of that size.
nextPoT := nextPowerOfTwo(len(transactions))
arraySize := nextPoT*2 - 1
merkles := make([]*chainhash.Hash, arraySize)
// Create the base transaction hashes and populate the array with them.
for i, tx := range transactions {
msgTx := tx.MsgTx()
txHashFull := msgTx.TxHashFull()
merkles[i] = &txHashFull
}
// Construct the merkle tree in the remaining entries of the merkles slice.
populateMerkleStore(nextPoT, merkles)
return merkles
}
// BuildMsgTxMerkleTreeStore is identical to BuildMerkleTreeStore but takes a
// slice of the wire.MsgTx transaction type instead of the dcrutil.Tx wrapper.
// See BuildMerkleTreeStore for more details.
//
// Deprecated: Use standalone.CalcTxTreeMerkleRoot instead.
func BuildMsgTxMerkleTreeStore(transactions []*wire.MsgTx) []*chainhash.Hash {
// If there's an empty stake tree, return totally zeroed out merkle tree root
// only.
if len(transactions) == 0 {
return []*chainhash.Hash{new(chainhash.Hash)}
}
// Calculate how many entries are required to hold the binary merkle
// tree as a linear array and create an array of that size.
nextPoT := nextPowerOfTwo(len(transactions))
arraySize := nextPoT*2 - 1
merkles := make([]*chainhash.Hash, arraySize)
// Create the base transaction hashes and populate the array with them.
for i, tx := range transactions {
txHashFull := tx.TxHashFull()
merkles[i] = &txHashFull
}
// Construct the merkle tree in the remaining entries of the merkles slice.
populateMerkleStore(nextPoT, merkles)
return merkles
}

View File

@ -16,54 +16,6 @@ import (
"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.
//
// Deprecated: Use standalone.SubsidyCache instead.
type SubsidyCache = standalone.SubsidyCache
// 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.
//
// Deprecated: Use standalone.NewSubsidyCache instead.
func NewSubsidyCache(height int64, params *chaincfg.Params) *SubsidyCache {
return standalone.NewSubsidyCache(params)
}
// CalcBlockWorkSubsidy calculates the proof of work subsidy for a block as a
// proportion of the total subsidy.
//
// Deprecated: Use standalone.SubsidyCache.CalcWorkSubsidy instead.
func CalcBlockWorkSubsidy(subsidyCache *SubsidyCache, height int64, voters uint16, params *chaincfg.Params) int64 {
return subsidyCache.CalcWorkSubsidy(height, voters)
}
// CalcStakeVoteSubsidy calculates the subsidy for a stake vote based on the height
// of its input SStx.
//
// Safe for concurrent access.
//
// Deprecated: Use standalone.SubsidyCache.CalcStakeVoteSubsidy instead.
func CalcStakeVoteSubsidy(subsidyCache *SubsidyCache, height int64, params *chaincfg.Params) int64 {
return subsidyCache.CalcStakeVoteSubsidy(height)
}
// CalcBlockTaxSubsidy calculates the subsidy for the organization address in the
// coinbase.
//
// Safe for concurrent access.
//
// Deprecated: Use standalone.SubsidyCache.CalcTreasurySubsidy instead.
func CalcBlockTaxSubsidy(subsidyCache *SubsidyCache, height int64, voters uint16, params *chaincfg.Params) int64 {
return subsidyCache.CalcTreasurySubsidy(height, voters)
}
// 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 {
@ -126,14 +78,6 @@ func blockOneCoinbasePaysTokens(tx *dcrutil.Tx, params *chaincfg.Params) error {
return nil
}
// BlockOneCoinbasePaysTokens checks to see if the first block coinbase pays
// out to the network initial token ledger.
//
// Deprecated: This will be removed in the next major version bump.
func BlockOneCoinbasePaysTokens(tx *dcrutil.Tx, params *chaincfg.Params) error {
return blockOneCoinbasePaysTokens(tx, params)
}
// coinbasePaysTreasury checks to see if a given block's coinbase correctly pays
// the treasury.
func coinbasePaysTreasury(subsidyCache *standalone.SubsidyCache, tx *dcrutil.Tx, height int64, voters uint16, params *chaincfg.Params) error {
@ -176,14 +120,6 @@ func coinbasePaysTreasury(subsidyCache *standalone.SubsidyCache, tx *dcrutil.Tx,
return nil
}
// CoinbasePaysTax checks to see if a given block's coinbase correctly pays
// tax to the developer organization.
//
// Deprecated: This will be removed in the next major version.
func CoinbasePaysTax(subsidyCache *SubsidyCache, tx *dcrutil.Tx, height int64, voters uint16, params *chaincfg.Params) error {
return coinbasePaysTreasury(subsidyCache, tx, height, voters, params)
}
// 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
@ -202,13 +138,3 @@ func calculateAddedSubsidy(block, parent *dcrutil.Block) int64 {
return subsidy
}
// 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.
//
// Deprecated: This will no longer be exported in the next major version.
func CalculateAddedSubsidy(block, parent *dcrutil.Block) int64 {
return calculateAddedSubsidy(block, parent)
}

View File

@ -1,87 +0,0 @@
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2019 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 (
"testing"
"github.com/decred/dcrd/chaincfg/v2"
)
func TestBlockSubsidy(t *testing.T) {
mainnet := chaincfg.MainNetParams()
reductionInterval := mainnet.SubsidyReductionInterval
stakeValidationHeight := mainnet.StakeValidationHeight
votesPerBlock := mainnet.TicketsPerBlock
// subsidySum returns the sum of the individual subsidy types for the given
// height. Note that this value is not exactly the same as the full subsidy
// originally used to calculate the individual proportions due to the use
// of integer math.
cache := NewSubsidyCache(0, mainnet)
subsidySum := func(height int64) int64 {
work := CalcBlockWorkSubsidy(cache, height, votesPerBlock, mainnet)
vote := CalcStakeVoteSubsidy(cache, height, mainnet) * int64(votesPerBlock)
treasury := CalcBlockTaxSubsidy(cache, height, votesPerBlock, mainnet)
return work + vote + treasury
}
// Calculate the total possible subsidy.
totalSubsidy := mainnet.BlockOneSubsidy()
for reductionNum := int64(0); ; reductionNum++ {
// The first interval contains a few special cases:
// 1) Block 0 does not produce any subsidy
// 2) Block 1 consists of a special initial coin distribution
// 3) Votes do not produce subsidy until voting begins
if reductionNum == 0 {
// Account for the block up to the point voting begins ignoring the
// first two special blocks.
subsidyCalcHeight := int64(2)
nonVotingBlocks := stakeValidationHeight - subsidyCalcHeight
totalSubsidy += subsidySum(subsidyCalcHeight) * nonVotingBlocks
// Account for the blocks remaining in the interval once voting
// begins.
subsidyCalcHeight = stakeValidationHeight
votingBlocks := reductionInterval - subsidyCalcHeight
totalSubsidy += subsidySum(subsidyCalcHeight) * votingBlocks
continue
}
// Account for the all other reduction intervals until all subsidy has
// been produced.
subsidyCalcHeight := reductionNum * reductionInterval
sum := subsidySum(subsidyCalcHeight)
if sum == 0 {
break
}
totalSubsidy += sum * reductionInterval
}
if totalSubsidy != 2099999999800912 {
t.Errorf("Bad total subsidy; want 2099999999800912, got %v", totalSubsidy)
}
}
func TestCachedCalcBlockSubsidy(t *testing.T) {
mainnet := chaincfg.MainNetParams()
cacheA := NewSubsidyCache(0, mainnet)
_ = cacheA.CalcBlockSubsidy(mainnet.SubsidyReductionInterval + 1)
// subsidyA is internally being calculated using the last cached subsidy.
subsidyA := cacheA.CalcBlockSubsidy((mainnet.SubsidyReductionInterval * 2) + 1)
cacheB := NewSubsidyCache(0, mainnet)
// subsidyB is internally being calculated from scratch.
subsidyB := cacheB.CalcBlockSubsidy((mainnet.SubsidyReductionInterval * 2) + 1)
if subsidyA != subsidyB {
t.Fatalf("Expected equal subsidies, got sudsidyA -> %v, "+
"subsidyB -> %v", subsidyA, subsidyB)
}
}

View File

@ -142,34 +142,6 @@ func isNullFraudProof(txIn *wire.TxIn) bool {
return true
}
// IsCoinBaseTx determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBase in that it works with a raw wire
// transaction as opposed to a higher level util transaction.
//
// Deprecated: Use standalone.IsCoinBaseTx instead.
func IsCoinBaseTx(msgTx *wire.MsgTx) bool {
return standalone.IsCoinBaseTx(msgTx)
}
// IsCoinBase determines whether or not a transaction is a coinbase. A
// coinbase is a special transaction created by miners that has no inputs.
// This is represented in the block chain by a transaction with a single input
// that has a previous output transaction index set to the maximum value along
// with a zero hash.
//
// This function only differs from IsCoinBaseTx in that it works with a higher
// level util transaction as opposed to a raw wire transaction.
//
// Deprecated: Use standalone.IsCoinBaseTx instead.
func IsCoinBase(tx *dcrutil.Tx) bool {
return standalone.IsCoinBaseTx(tx.MsgTx())
}
// IsExpiredTx returns where or not the passed transaction is expired according
// to the given block height.
//
@ -484,17 +456,6 @@ func checkProofOfWork(header *wire.BlockHeader, powLimit *big.Int, flags Behavio
return standaloneToChainRuleError(err)
}
// CheckProofOfWork ensures the block header bits which indicate the target
// difficulty is in min/max range and that the block hash is less than the
// target difficulty as claimed. This is equivalent to the function in the
// standalone package with the exception that that any error is converted to a
// RuleError.
//
// Deprecated: Use standalone.CheckProofOfWork instead.
func CheckProofOfWork(header *wire.BlockHeader, powLimit *big.Int) error {
return checkProofOfWork(header, powLimit, BFNone)
}
// checkBlockHeaderSanity performs some preliminary checks on a block header to
// ensure it is sane before continuing with processing. These checks are
// context free.