[NOD-142] Convert Height and ChainHeight to uint64 (#269)

* [NOD-142] Updated util.FastLog2Floor to work on uint64

* [NOD-142] Convert height and chainHeight to uint64

* [NOD-142] A couple fixes in comments of TestFastLog2Floor

* [NOD-142] Make spendableOutOffset uint64 too
This commit is contained in:
Svarog 2019-04-30 12:50:46 +03:00 committed by stasatdaglabs
parent 068a8d117d
commit e9ec8cd39c
56 changed files with 280 additions and 244 deletions

View File

@ -29,7 +29,7 @@ func (dag *BlockDAG) maybeAcceptBlock(block *util.Block, flags BehaviorFlags) er
}
bluestParent := parents.bluest()
blockHeight := int32(0)
blockHeight := uint64(0)
if !block.IsGenesis() {
blockHeight = parents.maxHeight() + 1
}

View File

@ -94,10 +94,10 @@ type blockNode struct {
workSum *big.Int
// height is the position in the block DAG.
height int32
height uint64
// chainHeight is the number of hops you need to go down the selected parent chain in order to get to the genesis block.
chainHeight uint32
chainHeight uint64
// Some fields from block headers to aid in best chain selection and
// reconstructing headers from memory. These must be treated as
@ -151,11 +151,11 @@ func initBlockNode(node *blockNode, blockHeader *wire.BlockHeader, parents block
}
}
func calculateNodeHeight(node *blockNode) int32 {
func calculateNodeHeight(node *blockNode) uint64 {
return node.parents.maxHeight() + 1
}
func calculateChainHeight(node *blockNode) uint32 {
func calculateChainHeight(node *blockNode) uint64 {
if node.isGenesis() {
return 0
}
@ -202,7 +202,7 @@ func (node *blockNode) Header() *wire.BlockHeader {
// that is lower than requested height would be returned.
//
// This function is safe for concurrent access.
func (node *blockNode) SelectedAncestor(height int32) *blockNode {
func (node *blockNode) SelectedAncestor(height uint64) *blockNode {
if height < 0 || height > node.height {
return nil
}
@ -220,7 +220,7 @@ func (node *blockNode) SelectedAncestor(height int32) *blockNode {
// height minus provided distance.
//
// This function is safe for concurrent access.
func (node *blockNode) RelativeAncestor(distance int32) *blockNode {
func (node *blockNode) RelativeAncestor(distance uint64) *blockNode {
return node.SelectedAncestor(node.height - distance)
}

View File

@ -26,7 +26,7 @@ func TestChainHeight(t *testing.T) {
tests := []struct {
node *blockNode
expectedChainHeight uint32
expectedChainHeight uint64
}{
{
node: node0,

View File

@ -24,8 +24,8 @@ func setFromSlice(blocks ...*blockNode) blockSet {
}
// maxHeight returns the height of the highest block in the block set
func (bs blockSet) maxHeight() int32 {
var maxHeight int32
func (bs blockSet) maxHeight() uint64 {
var maxHeight uint64
for _, node := range bs {
if maxHeight < node.height {
maxHeight = node.height

View File

@ -67,7 +67,7 @@ func (dag *BlockDAG) LatestCheckpoint() *dagconfig.Checkpoint {
// verifyCheckpoint returns whether the passed block height and hash combination
// match the checkpoint data. It also returns true if there is no checkpoint
// data for the passed block height.
func (dag *BlockDAG) verifyCheckpoint(height int32, hash *daghash.Hash) bool {
func (dag *BlockDAG) verifyCheckpoint(height uint64, hash *daghash.Hash) bool {
if !dag.HasCheckpoints() {
return true
}

View File

@ -47,7 +47,7 @@ func loadBlocks(filename string) (blocks []*util.Block, err error) {
var block *util.Block
err = nil
for height := 0; err == nil; height++ {
for height := uint64(0); err == nil; height++ {
var rintbuf uint32
err = binary.Read(dr, binary.LittleEndian, &rintbuf)
if err == io.EOF {
@ -74,7 +74,7 @@ func loadBlocks(filename string) (blocks []*util.Block, err error) {
if err != nil {
return
}
block.SetHeight(int32(height))
block.SetHeight(height)
blocks = append(blocks, block)
}
@ -151,7 +151,7 @@ func loadUTXOSet(filename string) (UTXOSet, error) {
// TestSetBlockRewardMaturity makes the ability to set the block reward maturity
// available when running tests.
func (dag *BlockDAG) TestSetBlockRewardMaturity(maturity uint16) {
func (dag *BlockDAG) TestSetBlockRewardMaturity(maturity uint64) {
dag.dagParams.BlockRewardMaturity = maturity
}
@ -174,7 +174,7 @@ func newTestDAG(params *dagconfig.Params) *BlockDAG {
timeSource: NewMedianTime(),
minRetargetTimespan: targetTimespan / adjustmentFactor,
maxRetargetTimespan: targetTimespan * adjustmentFactor,
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock),
blocksPerRetarget: uint64(targetTimespan / targetTimePerBlock),
index: index,
virtual: newVirtualBlock(setFromSlice(node), params.K),
genesis: index.LookupNode(params.GenesisHash),

View File

@ -63,7 +63,7 @@ type BlockDAG struct {
// be changed afterwards, so there is no need to protect them with a
// separate mutex.
checkpoints []dagconfig.Checkpoint
checkpointsByHeight map[int32]*dagconfig.Checkpoint
checkpointsByHeight map[uint64]*dagconfig.Checkpoint
db database.DB
dagParams *dagconfig.Params
timeSource MedianTimeSource
@ -75,9 +75,9 @@ type BlockDAG struct {
// parameters. They are also set when the instance is created and
// can't be changed afterwards, so there is no need to protect them with
// a separate mutex.
minRetargetTimespan int64 // target timespan / adjustment factor
maxRetargetTimespan int64 // target timespan * adjustment factor
blocksPerRetarget int32 // target timespan / target time per block
minRetargetTimespan int64 // target timespan / adjustment factor
maxRetargetTimespan int64 // target timespan * adjustment factor
blocksPerRetarget uint64 // target timespan / target time per block
// dagLock protects concurrent access to the vast majority of the
// fields in this struct below this point.
@ -333,7 +333,7 @@ func (dag *BlockDAG) addOrphanBlock(block *util.Block) {
// 'BlockHeight' has been reached.
type SequenceLock struct {
Seconds int64
BlockHeight int32
BlockHeight int64
}
// CalcSequenceLock computes a relative lock-time SequenceLock for the passed
@ -440,7 +440,7 @@ func (dag *BlockDAG) calcSequenceLock(node *blockNode, utxoSet UTXOSet, tx *util
// the input's height as its converted absolute
// lock-time. We subtract one from the relative lock in
// order to maintain the original lockTime semantics.
blockHeight := inputHeight + int32(relativeLock-1)
blockHeight := int64(inputHeight) + relativeLock - 1
if blockHeight > sequenceLock.BlockHeight {
sequenceLock.BlockHeight = blockHeight
}
@ -1131,7 +1131,7 @@ func (dag *BlockDAG) IsInSelectedPathChain(blockHash *daghash.Hash) bool {
}
// Height returns the height of the highest tip in the DAG
func (dag *BlockDAG) Height() int32 {
func (dag *BlockDAG) Height() uint64 {
return dag.virtual.tips().maxHeight()
}
@ -1231,10 +1231,10 @@ func (dag *BlockDAG) blockLocator(node *blockNode) BlockLocator {
// Requested hash itself + genesis block.
// Then floor(log2(height-10)) entries for the skip portion.
maxEntries := 2 + util.FastLog2Floor(uint32(node.height))
maxEntries := 2 + util.FastLog2Floor(node.height)
locator := make(BlockLocator, 0, maxEntries)
step := int32(1)
step := uint64(1)
for node != nil {
locator = append(locator, node.hash)
@ -1264,7 +1264,7 @@ func (dag *BlockDAG) blockLocator(node *blockNode) BlockLocator {
// DAG.
//
// This function is safe for concurrent access.
func (dag *BlockDAG) BlockHeightByHash(hash *daghash.Hash) (int32, error) {
func (dag *BlockDAG) BlockHeightByHash(hash *daghash.Hash) (uint64, error) {
node := dag.index.LookupNode(hash)
if node == nil {
str := fmt.Sprintf("block %s is not in the DAG", hash)
@ -1295,7 +1295,7 @@ func (dag *BlockDAG) ChildHashesByHash(hash *daghash.Hash) ([]*daghash.Hash, err
// end hash must belong to a block that is known to be valid.
//
// This function is safe for concurrent access.
func (dag *BlockDAG) HeightToHashRange(startHeight int32,
func (dag *BlockDAG) HeightToHashRange(startHeight uint64,
endHash *daghash.Hash, maxResults int) ([]*daghash.Hash, error) {
endNode := dag.index.LookupNode(endHash)
@ -1335,7 +1335,7 @@ func (dag *BlockDAG) HeightToHashRange(startHeight int32,
// endHash where the block height is a positive multiple of interval.
//
// This function is safe for concurrent access.
func (dag *BlockDAG) IntervalBlockHashes(endHash *daghash.Hash, interval int,
func (dag *BlockDAG) IntervalBlockHashes(endHash *daghash.Hash, interval uint64,
) ([]*daghash.Hash, error) {
endNode := dag.index.LookupNode(endHash)
@ -1347,15 +1347,15 @@ func (dag *BlockDAG) IntervalBlockHashes(endHash *daghash.Hash, interval int,
}
endHeight := endNode.height
resultsLength := int(endHeight) / interval
resultsLength := endHeight / interval
hashes := make([]*daghash.Hash, resultsLength)
dag.virtual.mtx.Lock()
defer dag.virtual.mtx.Unlock()
blockNode := endNode
for index := int(endHeight) / interval; index > 0; index-- {
blockHeight := int32(index * interval)
for index := endHeight / interval; index > 0; index-- {
blockHeight := index * interval
blockNode = blockNode.SelectedAncestor(blockHeight)
hashes[index-1] = blockNode.hash
@ -1654,10 +1654,10 @@ func New(config *Config) (*BlockDAG, error) {
// Generate a checkpoint by height map from the provided checkpoints
// and assert the provided checkpoints are sorted by height as required.
var checkpointsByHeight map[int32]*dagconfig.Checkpoint
var prevCheckpointHeight int32
var checkpointsByHeight map[uint64]*dagconfig.Checkpoint
var prevCheckpointHeight uint64
if len(config.Checkpoints) > 0 {
checkpointsByHeight = make(map[int32]*dagconfig.Checkpoint)
checkpointsByHeight = make(map[uint64]*dagconfig.Checkpoint)
for i := range config.Checkpoints {
checkpoint := &config.Checkpoints[i]
if checkpoint.Height <= prevCheckpointHeight {
@ -1685,7 +1685,7 @@ func New(config *Config) (*BlockDAG, error) {
indexManager: config.IndexManager,
minRetargetTimespan: targetTimespan / adjustmentFactor,
maxRetargetTimespan: targetTimespan * adjustmentFactor,
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock),
blocksPerRetarget: uint64(targetTimespan / targetTimePerBlock),
index: index,
virtual: newVirtualBlock(nil, params.K),
orphans: make(map[daghash.Hash]*orphanBlock),

View File

@ -231,8 +231,8 @@ func TestCalcSequenceLock(t *testing.T) {
dag := newTestDAG(netParams)
node := dag.selectedTip()
blockTime := node.Header().Timestamp
numBlocksToGenerate := uint32(5)
for i := uint32(0); i < numBlocksToGenerate; i++ {
numBlocksToGenerate := 5
for i := 0; i < numBlocksToGenerate; i++ {
blockTime = blockTime.Add(time.Second)
node = newTestNode(setFromSlice(node), blockVersion, 0, blockTime, netParams.K)
dag.index.AddNode(node)
@ -245,7 +245,7 @@ func TestCalcSequenceLock(t *testing.T) {
msgTx := wire.NewNativeMsgTx(wire.TxVersion, nil, []*wire.TxOut{{PkScript: nil, Value: 10}})
targetTx := util.NewTx(msgTx)
utxoSet := NewFullUTXOSet()
utxoSet.AddTx(targetTx.MsgTx(), int32(numBlocksToGenerate)-4)
utxoSet.AddTx(targetTx.MsgTx(), uint64(numBlocksToGenerate)-4)
// Create a utxo that spends the fake utxo created above for use in the
// transactions created in the tests. It has an age of 4 blocks. Note
@ -256,7 +256,7 @@ func TestCalcSequenceLock(t *testing.T) {
TxID: *targetTx.ID(),
Index: 0,
}
prevUtxoHeight := int32(numBlocksToGenerate) - 4
prevUtxoHeight := uint64(numBlocksToGenerate) - 4
// Obtain the median time past from the PoV of the input created above.
// The MTP for the input is the MTP from the PoV of the block *prior*
@ -348,7 +348,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet,
want: &SequenceLock{
Seconds: medianTime + (5 << wire.SequenceLockTimeGranularity) - 1,
BlockHeight: prevUtxoHeight + 3,
BlockHeight: int64(prevUtxoHeight) + 3,
},
},
// Transaction with a single input. The input's sequence number
@ -360,7 +360,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet,
want: &SequenceLock{
Seconds: -1,
BlockHeight: prevUtxoHeight + 2,
BlockHeight: int64(prevUtxoHeight) + 2,
},
},
// A transaction with two inputs with lock times expressed in
@ -397,7 +397,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet,
want: &SequenceLock{
Seconds: -1,
BlockHeight: prevUtxoHeight + 10,
BlockHeight: int64(prevUtxoHeight) + 10,
},
},
// A transaction with multiple inputs. Two inputs are time
@ -422,7 +422,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet,
want: &SequenceLock{
Seconds: medianTime + (13 << wire.SequenceLockTimeGranularity) - 1,
BlockHeight: prevUtxoHeight + 8,
BlockHeight: int64(prevUtxoHeight) + 8,
},
},
// A transaction with a single unconfirmed input. As the input
@ -437,7 +437,7 @@ func TestCalcSequenceLock(t *testing.T) {
mempool: true,
want: &SequenceLock{
Seconds: -1,
BlockHeight: nextBlockHeight + 1,
BlockHeight: int64(nextBlockHeight) + 1,
},
},
// A transaction with a single unconfirmed input. The input has
@ -587,7 +587,7 @@ func TestHeightToHashRange(t *testing.T) {
tests := []struct {
name string
startHeight int32 // locator for requested inventory
startHeight uint64 // locator for requested inventory
endHash *daghash.Hash // stop hash for locator
maxResults int // max to locate, 0 = wire const
hashes []*daghash.Hash // expected located hashes
@ -680,7 +680,7 @@ func TestIntervalBlockHashes(t *testing.T) {
tests := []struct {
name string
endHash *daghash.Hash
interval int
interval uint64
hashes []*daghash.Hash
expectError bool
}{

View File

@ -292,7 +292,7 @@ func deserializeUTXOEntry(serialized []byte) (*UTXOEntry, error) {
// Bit 0 indicates whether the containing transaction is a block reward.
// Bits 1-x encode height of containing transaction.
isBlockReward := code&0x01 != 0
blockHeight := int32(code >> 1)
blockHeight := code >> 1
// Decode the compressed unspent transaction output.
amount, pkScript, _, err := decodeCompressedTxOut(serialized[offset:])
@ -371,10 +371,10 @@ func dbPutUTXODiff(dbTx database.Tx, diff *UTXODiff) error {
// dbPutBlockIndex uses an existing database transaction to update or add the
// block index entries for the hash to height and height to hash mappings for
// the provided values.
func dbPutBlockIndex(dbTx database.Tx, hash *daghash.Hash, height int32) error {
func dbPutBlockIndex(dbTx database.Tx, hash *daghash.Hash, height uint64) error {
// Serialize the height for use in the index entries.
var serializedHeight [4]byte
byteOrder.PutUint32(serializedHeight[:], uint32(height))
var serializedHeight [8]byte
byteOrder.PutUint64(serializedHeight[:], height)
// Add the block hash to height mapping to the index.
meta := dbTx.Metadata()

View File

@ -67,7 +67,7 @@ type TestInstance interface {
type AcceptedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
Height uint64
IsOrphan bool
}
@ -85,7 +85,7 @@ func (b AcceptedBlock) FullBlockTestInstance() {}
type RejectedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
Height uint64
RejectCode blockdag.ErrorCode
}
@ -107,7 +107,7 @@ func (b RejectedBlock) FullBlockTestInstance() {}
type OrphanOrRejectedBlock struct {
Name string
Block *wire.MsgBlock
Height int32
Height uint64
}
// Ensure ExpectedTip implements the TestInstance interface.
@ -124,7 +124,7 @@ func (b OrphanOrRejectedBlock) FullBlockTestInstance() {}
type ExpectedTip struct {
Name string
Block *wire.MsgBlock
Height int32
Height uint64
}
// Ensure ExpectedTip implements the TestInstance interface.
@ -141,7 +141,7 @@ func (b ExpectedTip) FullBlockTestInstance() {}
type RejectedNonCanonicalBlock struct {
Name string
RawBlock []byte
Height int32
Height uint64
}
// FullBlockTestInstance only exists to allow RejectedNonCanonicalBlock to be treated as
@ -182,10 +182,10 @@ type testGenerator struct {
params *dagconfig.Params
tip *wire.MsgBlock
tipName string
tipHeight int32
tipHeight uint64
blocks map[daghash.Hash]*wire.MsgBlock
blocksByName map[string]*wire.MsgBlock
blockHeights map[string]int32
blockHeights map[string]uint64
// Used for tracking spendable coinbase outputs.
spendableOuts []spendableOut
@ -205,7 +205,7 @@ func makeTestGenerator(params *dagconfig.Params) (testGenerator, error) {
params: params,
blocks: map[daghash.Hash]*wire.MsgBlock{*genesisHash: genesis},
blocksByName: map[string]*wire.MsgBlock{"genesis": genesis},
blockHeights: map[string]int32{"genesis": 0},
blockHeights: map[string]uint64{"genesis": 0},
tip: genesis,
tipName: "genesis",
tipHeight: 0,
@ -243,7 +243,7 @@ func pushDataScript(items ...[]byte) []byte {
// standardCoinbaseScript returns a standard script suitable for use as the
// signature script of the coinbase transaction of a new block. In particular,
// it starts with the block height that is required by version 2 blocks.
func standardCoinbaseScript(blockHeight int32, extraNonce uint64) ([]byte, error) {
func standardCoinbaseScript(blockHeight uint64, extraNonce uint64) ([]byte, error) {
return txscript.NewScriptBuilder().AddInt64(int64(blockHeight)).
AddInt64(int64(extraNonce)).Script()
}
@ -275,7 +275,7 @@ func uniqueOpReturnScript() []byte {
// createCoinbaseTx returns a coinbase transaction paying an appropriate
// subsidy based on the passed block height. The coinbase signature script
// conforms to the requirements of version 2 blocks.
func (g *testGenerator) createCoinbaseTx(blockHeight int32) *wire.MsgTx {
func (g *testGenerator) createCoinbaseTx(blockHeight uint64) *wire.MsgTx {
extraNonce := uint64(0)
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
@ -912,7 +912,7 @@ func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
coinbaseMaturity := g.params.BlockRewardMaturity
var testInstances []TestInstance
for i := uint16(0); i < coinbaseMaturity; i++ {
for i := uint64(0); i < coinbaseMaturity; i++ {
blockName := fmt.Sprintf("bm%d", i)
g.nextBlock(blockName, nil)
g.saveTipCoinbaseOut()
@ -923,7 +923,7 @@ func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
// Collect spendable outputs. This simplifies the code below.
var outs []*spendableOut
for i := uint16(0); i < coinbaseMaturity; i++ {
for i := uint64(0); i < coinbaseMaturity; i++ {
op := g.oldestCoinbaseOut()
outs = append(outs, &op)
}
@ -2059,7 +2059,7 @@ func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
// Collect all of the spendable coinbase outputs from the previous
// collection point up to the current tip.
g.saveSpendableCoinbaseOuts()
spendableOutOffset := g.tipHeight - int32(coinbaseMaturity)
spendableOutOffset := g.tipHeight - coinbaseMaturity
// Extend the main chain by a large number of max size blocks.
//
@ -2068,7 +2068,7 @@ func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
reorgSpend := *outs[spendableOutOffset]
reorgStartBlockName := g.tipName
chain1TipName := g.tipName
for i := int32(0); i < numLargeReorgBlocks; i++ {
for i := uint64(0); i < numLargeReorgBlocks; i++ {
chain1TipName = fmt.Sprintf("br%d", i)
g.nextBlock(chain1TipName, &reorgSpend, func(b *wire.MsgBlock) {
bytesToMaxSize := maxBlockSize - b.SerializeSize() - 3
@ -2083,7 +2083,7 @@ func Generate(includeLargeReorg bool) (tests [][]TestInstance, err error) {
// Use the next available spendable output. First use up any
// remaining spendable outputs that were already popped into the
// outs slice, then just pop them from the stack.
if spendableOutOffset+1+i < int32(len(outs)) {
if spendableOutOffset+1+i < uint64(len(outs)) {
reorgSpend = *outs[spendableOutOffset+1+i]
} else {
reorgSpend = g.oldestCoinbaseOut()

View File

@ -140,7 +140,7 @@ func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, su
// outputs paying an appropriate subsidy based on the passed block height to the
// address associated with the harness. It automatically uses a standard
// signature script that starts with the block height
func createCoinbaseTxForTest(blockHeight int32, numOutputs uint32, extraNonce int64, params *dagconfig.Params) (*wire.MsgTx, error) {
func createCoinbaseTxForTest(blockHeight uint64, numOutputs uint32, extraNonce int64, params *dagconfig.Params) (*wire.MsgTx, error) {
// Create standard coinbase script.
coinbaseScript, err := txscript.NewScriptBuilder().
AddInt64(int64(blockHeight)).AddInt64(extraNonce).Script()

View File

@ -77,11 +77,11 @@ type thresholdConditionChecker interface {
// RuleChangeActivationThreshold is the number of blocks for which the
// condition must be true in order to lock in a rule change.
RuleChangeActivationThreshold() uint32
RuleChangeActivationThreshold() uint64
// MinerConfirmationWindow is the number of blocks in each threshold
// state retarget window.
MinerConfirmationWindow() uint32
MinerConfirmationWindow() uint64
// Condition returns whether or not the rule change activation condition
// has been met. This typically involves checking whether or not the
@ -129,7 +129,7 @@ func newThresholdCaches(numCaches uint32) []thresholdStateCache {
func (dag *BlockDAG) thresholdState(prevNode *blockNode, checker thresholdConditionChecker, cache *thresholdStateCache) (ThresholdState, error) {
// The threshold state for the window that contains the genesis block is
// defined by definition.
confirmationWindow := int32(checker.MinerConfirmationWindow())
confirmationWindow := checker.MinerConfirmationWindow()
if prevNode == nil || (prevNode.height+1) < confirmationWindow {
return ThresholdDefined, nil
}
@ -218,9 +218,9 @@ func (dag *BlockDAG) thresholdState(prevNode *blockNode, checker thresholdCondit
// At this point, the rule change is still being voted
// on by the miners, so iterate backwards through the
// confirmation window to count all of the votes in it.
var count uint32
var count uint64
countNode := prevNode
for i := int32(0); i < confirmationWindow; i++ {
for i := uint64(0); i < confirmationWindow; i++ {
condition, err := checker.Condition(countNode)
if err != nil {
return ThresholdFailed, err

View File

@ -22,7 +22,7 @@ type UTXOEntry struct {
amount uint64
pkScript []byte // The public key script for the output.
blockHeight int32 // Height of block containing tx.
blockHeight uint64 // Height of block containing tx.
// packedFlags contains additional info about output such as whether it
// is a block reward, and whether it has been modified
@ -38,7 +38,7 @@ func (entry *UTXOEntry) IsBlockReward() bool {
}
// BlockHeight returns the height of the block containing the output.
func (entry *UTXOEntry) BlockHeight() int32 {
func (entry *UTXOEntry) BlockHeight() uint64 {
return entry.blockHeight
}
@ -305,7 +305,7 @@ func (d UTXODiff) String() string {
}
// NewUTXOEntry creates a new utxoEntry representing the given txOut
func NewUTXOEntry(txOut *wire.TxOut, isBlockReward bool, blockHeight int32) *UTXOEntry {
func NewUTXOEntry(txOut *wire.TxOut, isBlockReward bool, blockHeight uint64) *UTXOEntry {
entry := &UTXOEntry{
amount: txOut.Value,
pkScript: txOut.PkScript,
@ -336,7 +336,7 @@ type UTXOSet interface {
diffFrom(other UTXOSet) (*UTXODiff, error)
WithDiff(utxoDiff *UTXODiff) (UTXOSet, error)
diffFromTx(tx *wire.MsgTx, node *blockNode) (*UTXODiff, error)
AddTx(tx *wire.MsgTx, blockHeight int32) (ok bool)
AddTx(tx *wire.MsgTx, blockHeight uint64) (ok bool)
clone() UTXOSet
Get(outPoint wire.OutPoint) (*UTXOEntry, bool)
}
@ -401,7 +401,7 @@ func (fus *FullUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error) {
}
// AddTx adds a transaction to this utxoSet and returns true iff it's valid in this UTXO's context
func (fus *FullUTXOSet) AddTx(tx *wire.MsgTx, blockHeight int32) bool {
func (fus *FullUTXOSet) AddTx(tx *wire.MsgTx, blockHeight uint64) bool {
isBlockReward := tx.IsBlockReward()
if !isBlockReward {
if !fus.containsInputs(tx) {
@ -493,7 +493,7 @@ func (dus *DiffUTXOSet) WithDiff(other *UTXODiff) (UTXOSet, error) {
}
// AddTx adds a transaction to this utxoSet and returns true iff it's valid in this UTXO's context
func (dus *DiffUTXOSet) AddTx(tx *wire.MsgTx, blockHeight int32) bool {
func (dus *DiffUTXOSet) AddTx(tx *wire.MsgTx, blockHeight uint64) bool {
isBlockReward := tx.IsBlockReward()
if !isBlockReward && !dus.containsInputs(tx) {
return false
@ -504,7 +504,7 @@ func (dus *DiffUTXOSet) AddTx(tx *wire.MsgTx, blockHeight int32) bool {
return true
}
func (dus *DiffUTXOSet) appendTx(tx *wire.MsgTx, blockHeight int32, isBlockReward bool) {
func (dus *DiffUTXOSet) appendTx(tx *wire.MsgTx, blockHeight uint64, isBlockReward bool) {
if !isBlockReward {
for _, txIn := range tx.TxIn {

View File

@ -663,7 +663,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) {
tests := []struct {
name string
startSet *DiffUTXOSet
startHeight int32
startHeight uint64
toAdd []*wire.MsgTx
expectedSet *DiffUTXOSet
}{
@ -776,7 +776,7 @@ func TestDiffUTXOSet_addTx(t *testing.T) {
// Apply all transactions to diffSet, in order, with the initial block height startHeight
for i, transaction := range test.toAdd {
diffSet.AddTx(transaction, test.startHeight+int32(i))
diffSet.AddTx(transaction, test.startHeight+uint64(i))
}
// Make sure that the result diffSet equals to the expectedSet

View File

@ -83,14 +83,14 @@ func IsFeeTransaction(tx *util.Tx) bool {
// SequenceLockActive determines if a transaction's sequence locks have been
// met, meaning that all the inputs of a given transaction have reached a
// height or time sufficient for their relative lock-time maturity.
func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
func SequenceLockActive(sequenceLock *SequenceLock, blockHeight uint64,
medianTimePast time.Time) bool {
// If either the seconds, or height relative-lock time has not yet
// reached, then the transaction is not yet mature according to its
// sequence locks.
if sequenceLock.Seconds >= medianTimePast.Unix() ||
sequenceLock.BlockHeight >= blockHeight {
sequenceLock.BlockHeight >= int64(blockHeight) {
return false
}
@ -98,7 +98,7 @@ func SequenceLockActive(sequenceLock *SequenceLock, blockHeight int32,
}
// IsFinalizedTransaction determines whether or not a transaction is finalized.
func IsFinalizedTransaction(tx *util.Tx, blockHeight int32, blockTime time.Time) bool {
func IsFinalizedTransaction(tx *util.Tx, blockHeight uint64, blockTime time.Time) bool {
msgTx := tx.MsgTx()
// Lock time of zero means the transaction is finalized.
@ -142,7 +142,7 @@ func IsFinalizedTransaction(tx *util.Tx, blockHeight int32, blockTime time.Time)
//
// At the target block generation rate for the main network, this is
// approximately every 4 years.
func CalcBlockSubsidy(height int32, dagParams *dagconfig.Params) uint64 {
func CalcBlockSubsidy(height uint64, dagParams *dagconfig.Params) uint64 {
if dagParams.SubsidyReductionInterval == 0 {
return baseSubsidy
}
@ -615,7 +615,7 @@ func (dag *BlockDAG) CheckBlockSanity(block *util.Block, powLimit *big.Int,
// ExtractCoinbaseHeight attempts to extract the height of the block from the
// scriptSig of a coinbase transaction.
func ExtractCoinbaseHeight(coinbaseTx *util.Tx) (int32, error) {
func ExtractCoinbaseHeight(coinbaseTx *util.Tx) (uint64, error) {
sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript
if len(sigScript) < 1 {
str := "the coinbase signature script" +
@ -631,7 +631,7 @@ func ExtractCoinbaseHeight(coinbaseTx *util.Tx) (int32, error) {
return 0, nil
}
if opcode >= txscript.Op1 && opcode <= txscript.Op16 {
return int32(opcode - (txscript.Op1 - 1)), nil
return uint64(opcode - (txscript.Op1 - 1)), nil
}
// Otherwise, the opcode is the length of the following bytes which
@ -648,7 +648,7 @@ func ExtractCoinbaseHeight(coinbaseTx *util.Tx) (int32, error) {
copy(serializedHeightBytes, sigScript[1:serializedLen+1])
serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
return int32(serializedHeight), nil
return serializedHeight, nil
}
// checkSerializedHeight checks if the signature script in the passed
@ -678,7 +678,7 @@ func checkSerializedHeight(block *util.Block) error {
// the checkpoints are not performed.
//
// This function MUST be called with the dag state lock held (for writes).
func (dag *BlockDAG) checkBlockHeaderContext(header *wire.BlockHeader, bluestParent *blockNode, blockHeight int32, fastAdd bool) error {
func (dag *BlockDAG) checkBlockHeaderContext(header *wire.BlockHeader, bluestParent *blockNode, blockHeight uint64, fastAdd bool) error {
if !fastAdd {
if err := dag.validateDifficulty(header, bluestParent); err != nil {
return err
@ -692,7 +692,7 @@ func (dag *BlockDAG) checkBlockHeaderContext(header *wire.BlockHeader, bluestPar
return dag.validateCheckpoints(header, blockHeight)
}
func (dag *BlockDAG) validateCheckpoints(header *wire.BlockHeader, blockHeight int32) error {
func (dag *BlockDAG) validateCheckpoints(header *wire.BlockHeader, blockHeight uint64) error {
// Ensure dag matches up to predetermined checkpoints.
blockHash := header.BlockHash()
if !dag.verifyCheckpoint(blockHeight, blockHash) {
@ -753,7 +753,7 @@ func (dag *BlockDAG) validateDifficulty(header *wire.BlockHeader, bluestParent *
// validateParents validates that no parent is an ancestor of another parent
func validateParents(blockHeader *wire.BlockHeader, parents blockSet) error {
minHeight := int32(math.MaxInt32)
minHeight := uint64(math.MaxUint64)
queue := newDownHeap()
visited := newSet()
for _, parent := range parents {
@ -895,7 +895,7 @@ func ensureNoDuplicateTx(block *blockNode, utxoSet UTXOSet,
//
// NOTE: The transaction MUST have already been sanity checked with the
// CheckTransactionSanity function prior to calling this function.
func CheckTransactionInputsAndCalulateFee(tx *util.Tx, txHeight int32, utxoSet UTXOSet, dagParams *dagconfig.Params, fastAdd bool) (
func CheckTransactionInputsAndCalulateFee(tx *util.Tx, txHeight uint64, utxoSet UTXOSet, dagParams *dagconfig.Params, fastAdd bool) (
txFeeInSatoshi uint64, err error) {
// Block reward transactions (a.k.a. coinbase or fee transactions)
@ -976,20 +976,19 @@ func CheckTransactionInputsAndCalulateFee(tx *util.Tx, txHeight int32, utxoSet U
return txFeeInSatoshi, nil
}
func validateBlockRewardMaturity(dagParams *dagconfig.Params, entry *UTXOEntry, txHeight int32, txIn *wire.TxIn) error {
func validateBlockRewardMaturity(dagParams *dagconfig.Params, entry *UTXOEntry, txHeight uint64, txIn *wire.TxIn) error {
// Ensure the transaction is not spending coins which have not
// yet reached the required block reward maturity.
if entry.IsBlockReward() {
originHeight := entry.BlockHeight()
blocksSincePrev := txHeight - originHeight
blockRewardMaturity := int32(dagParams.BlockRewardMaturity)
if blocksSincePrev < blockRewardMaturity {
if blocksSincePrev < dagParams.BlockRewardMaturity {
str := fmt.Sprintf("tried to spend block reward "+
"transaction output %s from height %d "+
"at height %d before required maturity "+
"of %d blocks", txIn.PreviousOutPoint,
originHeight, txHeight,
blockRewardMaturity)
dagParams.BlockRewardMaturity)
return ruleError(ErrImmatureSpend, str)
}
}

View File

@ -20,7 +20,7 @@ import (
// TestSequenceLocksActive tests the SequenceLockActive function to ensure it
// works as expected in all possible combinations/scenarios.
func TestSequenceLocksActive(t *testing.T) {
seqLock := func(h int32, s int64) *SequenceLock {
seqLock := func(h int64, s int64) *SequenceLock {
return &SequenceLock{
Seconds: s,
BlockHeight: h,
@ -29,7 +29,7 @@ func TestSequenceLocksActive(t *testing.T) {
tests := []struct {
seqLock *SequenceLock
blockHeight int32
blockHeight uint64
mtp time.Time
want bool
@ -488,7 +488,7 @@ func TestCheckSerializedHeight(t *testing.T) {
tests := []struct {
sigScript []byte // Serialized data
wantHeight int32 // Expected height
wantHeight uint64 // Expected height
err error // Expected error type
}{
// No serialized height length.

View File

@ -78,7 +78,7 @@ func (c bitConditionChecker) EndTime() uint64 {
// is associated with.
//
// This is part of the thresholdConditionChecker interface implementation.
func (c bitConditionChecker) RuleChangeActivationThreshold() uint32 {
func (c bitConditionChecker) RuleChangeActivationThreshold() uint64 {
return c.chain.dagParams.RuleChangeActivationThreshold
}
@ -89,7 +89,7 @@ func (c bitConditionChecker) RuleChangeActivationThreshold() uint32 {
// is associated with.
//
// This is part of the thresholdConditionChecker interface implementation.
func (c bitConditionChecker) MinerConfirmationWindow() uint32 {
func (c bitConditionChecker) MinerConfirmationWindow() uint64 {
return c.chain.dagParams.MinerConfirmationWindow
}
@ -159,7 +159,7 @@ func (c deploymentChecker) EndTime() uint64 {
// is associated with.
//
// This is part of the thresholdConditionChecker interface implementation.
func (c deploymentChecker) RuleChangeActivationThreshold() uint32 {
func (c deploymentChecker) RuleChangeActivationThreshold() uint64 {
return c.chain.dagParams.RuleChangeActivationThreshold
}
@ -170,7 +170,7 @@ func (c deploymentChecker) RuleChangeActivationThreshold() uint32 {
// is associated with.
//
// This is part of the thresholdConditionChecker interface implementation.
func (c deploymentChecker) MinerConfirmationWindow() uint32 {
func (c deploymentChecker) MinerConfirmationWindow() uint64 {
return c.chain.dagParams.MinerConfirmationWindow
}
@ -250,7 +250,7 @@ func (dag *BlockDAG) warnUnknownRuleActivations(node *blockNode) error {
}
case ThresholdLockedIn:
window := int32(checker.MinerConfirmationWindow())
window := checker.MinerConfirmationWindow()
activationHeight := window - (node.height % window)
log.Warnf("Unknown new rules are about to activate in "+
"%d blocks (bit %d)", activationHeight, bit)

View File

@ -719,8 +719,8 @@ func NewValidateAddressCmd(address string) *ValidateAddressCmd {
// VerifyDAGCmd defines the verifyDag JSON-RPC command.
type VerifyDAGCmd struct {
CheckLevel *int32 `jsonrpcdefault:"3"`
CheckDepth *int32 `jsonrpcdefault:"288"` // 0 = all
CheckLevel *uint64 `jsonrpcdefault:"3"`
CheckDepth *uint64 `jsonrpcdefault:"288"` // 0 = all
}
// NewVerifyDAGCmd returns a new instance which can be used to issue a
@ -728,7 +728,7 @@ type VerifyDAGCmd struct {
//
// The parameters which are pointers indicate they are optional. Passing nil
// for optional parameters will use the default value.
func NewVerifyDAGCmd(checkLevel, checkDepth *int32) *VerifyDAGCmd {
func NewVerifyDAGCmd(checkLevel, checkDepth *uint64) *VerifyDAGCmd {
return &VerifyDAGCmd{
CheckLevel: checkLevel,
CheckDepth: checkDepth,

View File

@ -1027,8 +1027,8 @@ func TestDAGSvrCmds(t *testing.T) {
},
marshalled: `{"jsonrpc":"1.0","method":"verifyDag","params":[],"id":1}`,
unmarshalled: &btcjson.VerifyDAGCmd{
CheckLevel: btcjson.Int32(3),
CheckDepth: btcjson.Int32(288),
CheckLevel: btcjson.Uint64(3),
CheckDepth: btcjson.Uint64(288),
},
},
{
@ -1037,12 +1037,12 @@ func TestDAGSvrCmds(t *testing.T) {
return btcjson.NewCmd("verifyDag", 2)
},
staticCmd: func() interface{} {
return btcjson.NewVerifyDAGCmd(btcjson.Int32(2), nil)
return btcjson.NewVerifyDAGCmd(btcjson.Uint64(2), nil)
},
marshalled: `{"jsonrpc":"1.0","method":"verifyDag","params":[2],"id":1}`,
unmarshalled: &btcjson.VerifyDAGCmd{
CheckLevel: btcjson.Int32(2),
CheckDepth: btcjson.Int32(288),
CheckLevel: btcjson.Uint64(2),
CheckDepth: btcjson.Uint64(288),
},
},
{
@ -1051,12 +1051,12 @@ func TestDAGSvrCmds(t *testing.T) {
return btcjson.NewCmd("verifyDag", 2, 500)
},
staticCmd: func() interface{} {
return btcjson.NewVerifyDAGCmd(btcjson.Int32(2), btcjson.Int32(500))
return btcjson.NewVerifyDAGCmd(btcjson.Uint64(2), btcjson.Uint64(500))
},
marshalled: `{"jsonrpc":"1.0","method":"verifyDag","params":[2,500],"id":1}`,
unmarshalled: &btcjson.VerifyDAGCmd{
CheckLevel: btcjson.Int32(2),
CheckDepth: btcjson.Int32(500),
CheckLevel: btcjson.Uint64(2),
CheckDepth: btcjson.Uint64(500),
},
},
{

View File

@ -12,7 +12,7 @@ import "encoding/json"
type GetBlockHeaderVerboseResult struct {
Hash string `json:"hash"`
Confirmations uint64 `json:"confirmations"`
Height int32 `json:"height"`
Height uint64 `json:"height"`
Version int32 `json:"version"`
VersionHex string `json:"versionHex"`
MerkleRoot string `json:"merkleRoot"`
@ -31,7 +31,7 @@ type GetBlockVerboseResult struct {
Hash string `json:"hash"`
Confirmations uint64 `json:"confirmations"`
Size int32 `json:"size"`
Height int64 `json:"height"`
Height uint64 `json:"height"`
Version int32 `json:"version"`
VersionHex string `json:"versionHex"`
MerkleRoot string `json:"merkleRoot"`
@ -99,14 +99,14 @@ type Bip9SoftForkDescription struct {
// command.
type GetBlockDAGInfoResult struct {
DAG string `json:"dag"`
Blocks int32 `json:"blocks"`
Headers int32 `json:"headers"`
Blocks uint64 `json:"blocks"`
Headers uint64 `json:"headers"`
TipHashes []string `json:"tipHashes"`
Difficulty float64 `json:"difficulty"`
MedianTime int64 `json:"medianTime"`
VerificationProgress float64 `json:"verificationProgress,omitempty"`
Pruned bool `json:"pruned"`
PruneHeight int32 `json:"pruneHeight,omitempty"`
PruneHeight uint64 `json:"pruneHeight,omitempty"`
DAGWork string `json:"dagWork,omitempty"`
SoftForks []*SoftForkDescription `json:"softForks"`
Bip9SoftForks map[string]*Bip9SoftForkDescription `json:"bip9SoftForks"`
@ -135,7 +135,7 @@ type GetBlockTemplateResult struct {
// CoinbaseTxn or CoinbaseValue must be specified, but not both.
Bits string `json:"bits"`
CurTime int64 `json:"curTime"`
Height int64 `json:"height"`
Height uint64 `json:"height"`
ParentHashes []string `json:"parentHashes"`
SigOpLimit int64 `json:"sigOpLimit,omitempty"`
SizeLimit int64 `json:"sizeLimit,omitempty"`
@ -173,7 +173,7 @@ type GetMempoolEntryResult struct {
Fee float64 `json:"fee"`
ModifiedFee float64 `json:"modifiedFee"`
Time int64 `json:"time"`
Height int64 `json:"height"`
Height uint64 `json:"height"`
StartingPriority float64 `json:"startingPriority"`
CurrentPriority float64 `json:"currentPriority"`
DescendantCount int64 `json:"descendantCount"`
@ -257,7 +257,7 @@ type GetRawMempoolVerboseResult struct {
Size int32 `json:"size"`
Fee float64 `json:"fee"`
Time int64 `json:"time"`
Height int64 `json:"height"`
Height uint64 `json:"height"`
StartingPriority float64 `json:"startingPriority"`
CurrentPriority float64 `json:"currentPriority"`
Depends []string `json:"depends"`
@ -426,7 +426,7 @@ type GetWorkResult struct {
type InfoDAGResult struct {
Version int32 `json:"version"`
ProtocolVersion int32 `json:"protocolVersion"`
Blocks int32 `json:"blocks"`
Blocks uint64 `json:"blocks"`
TimeOffset int64 `json:"timeOffset"`
Connections int32 `json:"connections"`
Proxy string `json:"proxy"`

View File

@ -62,14 +62,14 @@ const (
// FilteredBlockAddedNtfn defines the filteredBlockAdded JSON-RPC
// notification.
type FilteredBlockAddedNtfn struct {
Height int32
Height uint64
Header string
SubscribedTxs []string
}
// NewFilteredBlockAddedNtfn returns a new instance which can be used to
// issue a filteredBlockAdded JSON-RPC notification.
func NewFilteredBlockAddedNtfn(height int32, header string, subscribedTxs []string) *FilteredBlockAddedNtfn {
func NewFilteredBlockAddedNtfn(height uint64, header string, subscribedTxs []string) *FilteredBlockAddedNtfn {
return &FilteredBlockAddedNtfn{
Height: height,
Header: header,
@ -79,7 +79,7 @@ func NewFilteredBlockAddedNtfn(height int32, header string, subscribedTxs []stri
// BlockDetails describes details of a tx in a block.
type BlockDetails struct {
Height int32 `json:"height"`
Height uint64 `json:"height"`
Hash string `json:"hash"`
Index int `json:"index"`
Time int64 `json:"time"`
@ -132,7 +132,7 @@ func NewRedeemingTxNtfn(hexTx string, block *BlockDetails) *RedeemingTxNtfn {
// NOTE: Deprecated. Not used with rescanblocks command.
type RescanFinishedNtfn struct {
Hash string
Height int32
Height uint64
Time int64
}
@ -140,7 +140,7 @@ type RescanFinishedNtfn struct {
// rescanFinished JSON-RPC notification.
//
// NOTE: Deprecated. Not used with rescanblocks command.
func NewRescanFinishedNtfn(hash string, height int32, time int64) *RescanFinishedNtfn {
func NewRescanFinishedNtfn(hash string, height uint64, time int64) *RescanFinishedNtfn {
return &RescanFinishedNtfn{
Hash: hash,
Height: height,
@ -153,7 +153,7 @@ func NewRescanFinishedNtfn(hash string, height int32, time int64) *RescanFinishe
// NOTE: Deprecated. Not used with rescanblocks command.
type RescanProgressNtfn struct {
Hash string
Height int32
Height uint64
Time int64
}
@ -161,7 +161,7 @@ type RescanProgressNtfn struct {
// rescanProgress JSON-RPC notification.
//
// NOTE: Deprecated. Not used with rescanblocks command.
func NewRescanProgressNtfn(hash string, height int32, time int64) *RescanProgressNtfn {
func NewRescanProgressNtfn(hash string, height uint64, time int64) *RescanProgressNtfn {
return &RescanProgressNtfn{
Hash: hash,
Height: height,

View File

@ -157,5 +157,5 @@ type ValidateAddressWalletResult struct {
// GetBestBlockResult models the data from the getbestblock command.
type GetBestBlockResult struct {
Hash string `json:"hash"`
Height int32 `json:"height"`
Height uint64 `json:"height"`
}

View File

@ -58,7 +58,7 @@ func findCandidates(dag *blockdag.BlockDAG, highestTipHash *daghash.Hash) ([]*da
// The latest known block must be at least the last known checkpoint
// plus required checkpoint confirmations.
checkpointConfirmations := int32(blockdag.CheckpointConfirmations)
checkpointConfirmations := uint64(blockdag.CheckpointConfirmations)
requiredHeight := latestCheckpoint.Height + checkpointConfirmations
if block.Height() < requiredHeight {
return nil, fmt.Errorf("the block database is only at height "+
@ -83,7 +83,7 @@ func findCandidates(dag *blockdag.BlockDAG, highestTipHash *daghash.Hash) ([]*da
// Loop backwards through the DAG to find checkpoint candidates.
candidates := make([]*dagconfig.Checkpoint, 0, cfg.NumCandidates)
numTested := int32(0)
numTested := uint64(0)
for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight {
// Display progress.
if numTested%progressInterval == 0 {

View File

@ -226,7 +226,7 @@ func newCheckpointFromStr(checkpoint string) (dagconfig.Checkpoint, error) {
checkpoint)
}
height, err := strconv.ParseInt(parts[0], 10, 32)
height, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return dagconfig.Checkpoint{}, fmt.Errorf("unable to parse "+
"checkpoint %q due to malformed height", checkpoint)
@ -243,7 +243,7 @@ func newCheckpointFromStr(checkpoint string) (dagconfig.Checkpoint, error) {
}
return dagconfig.Checkpoint{
Height: int32(height),
Height: uint64(height),
Hash: hash,
}, nil
}

View File

@ -57,7 +57,7 @@ const phantomK = 10
// documentation for blockchain.IsCheckpointCandidate for details on the
// selection criteria.
type Checkpoint struct {
Height int32
Height uint64
Hash *daghash.Hash
}
@ -130,11 +130,11 @@ type Params struct {
// BlockRewardMaturity is the number of blocks required before newly mined
// coins (coinbase or fee transactions) can be spent.
BlockRewardMaturity uint16
BlockRewardMaturity uint64
// SubsidyReductionInterval is the interval of blocks before the subsidy
// is reduced.
SubsidyReductionInterval int32
SubsidyReductionInterval uint64
// TargetTimespan is the desired amount of time that should elapse
// before the block difficulty requirement is examined to determine how
@ -182,8 +182,8 @@ type Params struct {
//
// Deployments define the specific consensus rule changes to be voted
// on.
RuleChangeActivationThreshold uint32
MinerConfirmationWindow uint32
RuleChangeActivationThreshold uint64
MinerConfirmationWindow uint64
Deployments [DefinedDeployments]ConsensusDeployment
// Mempool parameters

View File

@ -52,12 +52,12 @@ func assertVersionBit(r *rpctest.Harness, t *testing.T, hash *daghash.Hash, bit
// assertChainHeight retrieves the current chain height from the given test
// harness and ensures it matches the provided expected height.
func assertChainHeight(r *rpctest.Harness, t *testing.T, expectedHeight uint32) {
func assertChainHeight(r *rpctest.Harness, t *testing.T, expectedHeight uint64) {
height, err := r.Node.GetBlockCount()
if err != nil {
t.Fatalf("failed to retrieve block height: %v", err)
}
if uint32(height) != expectedHeight {
if height != expectedHeight {
_, _, line, _ := runtime.Caller(1)
t.Fatalf("assertion failed at line %d: block height of %d "+
"is not the expected %d", line, height, expectedHeight)

View File

@ -88,14 +88,14 @@ func solveBlock(header *wire.BlockHeader, targetDifficulty *big.Int) bool {
// standardCoinbaseScript returns a standard script suitable for use as the
// signature script of the coinbase transaction of a new block. In particular,
// it starts with the block height that is required by version 2 blocks.
func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) {
func standardCoinbaseScript(nextBlockHeight uint64, extraNonce uint64) ([]byte, error) {
return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
AddInt64(int64(extraNonce)).Script()
}
// createCoinbaseTx returns a coinbase transaction paying an appropriate
// subsidy based on the passed block height to the provided address.
func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int32,
func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight uint64,
addr util.Address, mineTo []wire.TxOut,
net *dagconfig.Params) (*util.Tx, error) {
@ -139,7 +139,7 @@ func CreateBlock(parentBlock *util.Block, inclusionTxs []*util.Tx,
var (
parentHash *daghash.Hash
blockHeight int32
blockHeight uint64
parentBlockTime time.Time
)

View File

@ -39,20 +39,20 @@ type utxo struct {
pkScript []byte
value util.Amount
keyIndex uint32
maturityHeight int32
maturityHeight uint64
isLocked bool
}
// isMature returns true if the target utxo is considered "mature" at the
// passed block height. Otherwise, false is returned.
func (u *utxo) isMature(height int32) bool {
func (u *utxo) isMature(height uint64) bool {
return height >= u.maturityHeight
}
// dagUpdate encapsulates an update to the current DAG. This struct is
// used to sync up the memWallet each time a new block is connected to the DAG.
type dagUpdate struct {
blockHeight int32
blockHeight uint64
filteredTxns []*util.Tx
isConnect bool // True if connect, false if disconnect
}
@ -80,7 +80,7 @@ type memWallet struct {
// currentHeight is the latest height the wallet is known to be synced
// to.
currentHeight int32
currentHeight uint64
// addrs tracks all addresses belonging to the wallet. The addresses
// are indexed by their keypath from the hdRoot.
@ -93,7 +93,7 @@ type memWallet struct {
// received. Once a block is disconnected, the undo entry for the
// particular height is evaluated, thereby rewinding the effect of the
// disconnected block on the wallet's set of spendable utxos.
reorgJournal map[int32]*undoEntry
reorgJournal map[uint64]*undoEntry
dagUpdates []*dagUpdate
dagUpdateSignal chan struct{}
@ -150,7 +150,7 @@ func newMemWallet(net *dagconfig.Params, harnessID uint32) (*memWallet, error) {
addrs: addrs,
utxos: make(map[wire.OutPoint]*utxo),
dagUpdateSignal: make(chan struct{}),
reorgJournal: make(map[int32]*undoEntry),
reorgJournal: make(map[uint64]*undoEntry),
}, nil
}
@ -162,7 +162,7 @@ func (m *memWallet) Start() {
// SyncedHeight returns the height the wallet is known to be synced to.
//
// This function is safe for concurrent access.
func (m *memWallet) SyncedHeight() int32 {
func (m *memWallet) SyncedHeight() uint64 {
m.RLock()
defer m.RUnlock()
return m.currentHeight
@ -177,7 +177,7 @@ func (m *memWallet) SetRPCClient(rpcClient *rpcclient.Client) {
// IngestBlock is a call-back which is to be triggered each time a new block is
// connected to the blockDAG. It queues the update for the DAG syncer,
// calling the private version in sequential order.
func (m *memWallet) IngestBlock(height int32, header *wire.BlockHeader, filteredTxns []*util.Tx) {
func (m *memWallet) IngestBlock(height uint64, header *wire.BlockHeader, filteredTxns []*util.Tx) {
// Append this new DAG update to the end of the queue of new DAG
// updates.
m.dagMtx.Lock()
@ -260,9 +260,9 @@ func (m *memWallet) evalOutputs(outputs []*wire.TxOut, txID *daghash.TxID,
// If this is a coinbase output, then we mark the
// maturity height at the proper block height in the
// future.
var maturityHeight int32
var maturityHeight uint64
if isCoinbase {
maturityHeight = m.currentHeight + int32(m.net.BlockRewardMaturity)
maturityHeight = m.currentHeight + m.net.BlockRewardMaturity
}
op := wire.OutPoint{TxID: *txID, Index: uint32(i)}

View File

@ -171,7 +171,7 @@ func New(activeNet *dagconfig.Params, handlers *rpcclient.NotificationHandlers,
// callback.
if handlers.OnFilteredBlockAdded != nil {
obc := handlers.OnFilteredBlockAdded
handlers.OnFilteredBlockAdded = func(height int32, header *wire.BlockHeader, filteredTxns []*util.Tx) {
handlers.OnFilteredBlockAdded = func(height uint64, header *wire.BlockHeader, filteredTxns []*util.Tx) {
wallet.IngestBlock(height, header, filteredTxns)
obc(height, header, filteredTxns)
}

View File

@ -81,7 +81,7 @@ func syncBlocks(nodes []*Harness) error {
retry:
for !blocksMatch {
var parentHash *daghash.Hash
var prevHeight int32
var prevHeight uint64
for _, node := range nodes {
blockHash, blockHeight, err := node.Node.GetBestBlock()
if err != nil {

View File

@ -100,11 +100,11 @@ type observedTransaction struct {
feeRate SatoshiPerByte
// The block height when it was observed.
observed int32
observed uint64
// The height of the block in which it was mined.
// If the transaction has not yet been mined, it is zero.
mined int32
mined uint64
}
func (o *observedTransaction) Serialize(w io.Writer) {
@ -163,7 +163,7 @@ type FeeEstimator struct {
minRegisteredBlocks uint32
// The last known height.
lastKnownHeight int32
lastKnownHeight uint64
// The number of blocks that have been registered.
numBlocksRegistered uint32
@ -327,7 +327,7 @@ func (ef *FeeEstimator) RegisterBlock(block *util.Block) error {
}
// LastKnownHeight returns the height of the last block which was registered.
func (ef *FeeEstimator) LastKnownHeight() int32 {
func (ef *FeeEstimator) LastKnownHeight() uint64 {
ef.mtx.Lock()
defer ef.mtx.Unlock()

View File

@ -42,7 +42,7 @@ type estimateFeeTester struct {
ef *FeeEstimator
t *testing.T
version int32
height int32
height uint64
last *lastBlock
}

View File

@ -66,7 +66,7 @@ type Config struct {
// BestHeight defines the function to use to access the block height of
// the current best chain.
BestHeight func() int32
BestHeight func() uint64
// MedianTimePast defines the function to use in order to access the
// median time past calculated from the point-of-view of the current
@ -606,7 +606,10 @@ func (mp *TxPool) RemoveDoubleSpends(tx *util.Tx) {
// helper for maybeAcceptTransaction.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *TxPool) addTransaction(tx *util.Tx, height int32, fee uint64, parentsInPool []*wire.OutPoint) *TxDesc {
func (mp *TxPool) addTransaction(tx *util.Tx, height uint64, fee uint64, parentsInPool []*wire.OutPoint) *TxDesc {
mp.cfg.DAG.RLock()
defer mp.cfg.DAG.RUnlock()
// Add the transaction to the pool and mark the referenced outpoints
// as spent by the pool.
txD := &TxDesc{
@ -1284,7 +1287,7 @@ func (mp *TxPool) RawMempoolVerbose() map[string]*btcjson.GetRawMempoolVerboseRe
Size: int32(tx.MsgTx().SerializeSize()),
Fee: util.Amount(desc.Fee).ToBTC(),
Time: desc.Added.Unix(),
Height: int64(desc.Height),
Height: desc.Height,
StartingPriority: desc.StartingPriority,
CurrentPriority: currentPriority,
Depends: make([]string, 0),

View File

@ -35,13 +35,13 @@ import (
// transactions to appear as though they are spending completely valid utxos.
type fakeChain struct {
sync.RWMutex
currentHeight int32
currentHeight uint64
medianTimePast time.Time
}
// BestHeight returns the current height associated with the fake chain
// instance.
func (s *fakeChain) BestHeight() int32 {
func (s *fakeChain) BestHeight() uint64 {
s.RLock()
height := s.currentHeight
s.RUnlock()
@ -49,7 +49,7 @@ func (s *fakeChain) BestHeight() int32 {
}
// SetHeight sets the current height associated with the fake chain instance.
func (s *fakeChain) SetHeight(height int32) {
func (s *fakeChain) SetHeight(height uint64) {
s.Lock()
s.currentHeight = height
s.Unlock()
@ -121,7 +121,7 @@ type poolHarness struct {
// address associated with the harness. It automatically uses a standard
// signature script that starts with the block height that is required by
// version 2 blocks.
func (p *poolHarness) CreateCoinbaseTx(blockHeight int32, numOutputs uint32) (*util.Tx, error) {
func (p *poolHarness) CreateCoinbaseTx(blockHeight uint64, numOutputs uint32) (*util.Tx, error) {
// Create standard coinbase script.
extraNonce := int64(0)
coinbaseScript, err := txscript.NewScriptBuilder().
@ -344,7 +344,7 @@ func newPoolHarness(dagParams *dagconfig.Params, numOutputs uint32, dbName strin
outpoints = append(outpoints, txOutToSpendableOutpoint(coinbase, i))
}
if dagParams.BlockRewardMaturity != 0 {
harness.chain.SetHeight(int32(dagParams.BlockRewardMaturity) + curHeight)
harness.chain.SetHeight(dagParams.BlockRewardMaturity + curHeight)
} else {
harness.chain.SetHeight(curHeight + 1)
}

View File

@ -245,7 +245,7 @@ func isDust(txOut *wire.TxOut, minRelayTxFee util.Amount) bool {
// finalized, conforming to more stringent size constraints, having scripts
// of recognized forms, and not containing "dust" outputs (those that are
// so small it costs more to process them than they are worth).
func checkTransactionStandard(tx *util.Tx, height int32,
func checkTransactionStandard(tx *util.Tx, height uint64,
medianTimePast time.Time, policy *Policy) error {
// The transaction must be a currently supported version.

View File

@ -307,7 +307,7 @@ func TestCheckTransactionStandard(t *testing.T) {
tests := []struct {
name string
tx *wire.MsgTx
height int32
height uint64
isStandard bool
code wire.RejectCode
}{

View File

@ -206,7 +206,7 @@ func (m *CPUMiner) submitBlock(block *util.Block) bool {
// This function will return early with false when conditions that trigger a
// stale block such as a new block showing up or periodically when there are
// new transactions and enough time has elapsed without finding a solution.
func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int32,
func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight uint64,
ticker *time.Ticker, quit chan struct{}) bool {
// Create some convenience variables.

View File

@ -46,7 +46,7 @@ type TxDesc struct {
// Height is the block height when the entry was added to the the source
// pool.
Height int32
Height uint64
// Fee is the total fee the transaction associated with the entry pays.
Fee uint64
@ -198,9 +198,8 @@ type BlockTemplate struct {
// transaction in the generated template performs.
SigOpCounts []int64
// Height is the height at which the block template connects to the main
// chain.
Height int32
// Height is the height at which the block template connects to the DAG
Height uint64
// ValidPayAddress indicates whether or not the template coinbase pays
// to an address or is redeemable by anyone. See the documentation on
@ -213,7 +212,7 @@ type BlockTemplate struct {
// signature script of the coinbase transaction of a new block. In particular,
// it starts with the block height that is required by version 2 blocks and adds
// the extra nonce as well as additional coinbase flags.
func StandardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) {
func StandardCoinbaseScript(nextBlockHeight uint64, extraNonce uint64) ([]byte, error) {
return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)).
Script()
@ -225,7 +224,7 @@ func StandardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, e
//
// See the comment for NewBlockTemplate for more information about why the nil
// address handling is useful.
func CreateCoinbaseTx(params *dagconfig.Params, coinbaseScript []byte, nextBlockHeight int32, addr util.Address) (*util.Tx, error) {
func CreateCoinbaseTx(params *dagconfig.Params, coinbaseScript []byte, nextBlockHeight uint64, addr util.Address) (*util.Tx, error) {
// Create the script to pay to the provided payment address if one was
// specified. Otherwise create a script that allows the coinbase to be
// redeemable by anyone.
@ -721,7 +720,7 @@ func (g *BlkTmplGenerator) UpdateBlockTime(msgBlock *wire.MsgBlock) error {
// block by regenerating the coinbase script with the passed value and block
// height. It also recalculates and updates the new merkle root that results
// from changing the coinbase script.
func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error {
func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight uint64, extraNonce uint64) error {
coinbaseScript, err := StandardCoinbaseScript(blockHeight, extraNonce)
if err != nil {
return err
@ -749,7 +748,7 @@ func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight
}
// DAGHeight returns the DAG's height
func (g *BlkTmplGenerator) DAGHeight() int32 {
func (g *BlkTmplGenerator) DAGHeight() uint64 {
return g.dag.Height()
}

View File

@ -148,7 +148,7 @@ func TestNewBlockTemplate(t *testing.T) {
}
var createCoinbaseTxPatch *monkey.PatchGuard
createCoinbaseTxPatch = monkey.Patch(CreateCoinbaseTx, func(params *dagconfig.Params, coinbaseScript []byte, nextBlockHeight int32, addr util.Address) (*util.Tx, error) {
createCoinbaseTxPatch = monkey.Patch(CreateCoinbaseTx, func(params *dagconfig.Params, coinbaseScript []byte, nextBlockHeight uint64, addr util.Address) (*util.Tx, error) {
createCoinbaseTxPatch.Unpatch()
defer createCoinbaseTxPatch.Restore()
tx, err := CreateCoinbaseTx(params, coinbaseScript, nextBlockHeight, addr)
@ -298,7 +298,7 @@ func TestNewBlockTemplate(t *testing.T) {
standardCoinbaseScriptErrString := "standardCoinbaseScript err"
var standardCoinbaseScriptPatch *monkey.PatchGuard
standardCoinbaseScriptPatch = monkey.Patch(StandardCoinbaseScript, func(nextBlockHeight int32, extraNonce uint64) ([]byte, error) {
standardCoinbaseScriptPatch = monkey.Patch(StandardCoinbaseScript, func(nextBlockHeight uint64, extraNonce uint64) ([]byte, error) {
return nil, errors.New(standardCoinbaseScriptErrString)
})
defer standardCoinbaseScriptPatch.Unpatch()

View File

@ -54,7 +54,7 @@ func minInt(a, b int) int {
// age is the sum of this value for each txin. Any inputs to the transaction
// which are currently in the mempool and hence not mined into a block yet,
// contribute no additional input age to the transaction.
func calcInputValueAge(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight int32) float64 {
func calcInputValueAge(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight uint64) float64 {
var totalInputAge float64
for _, txIn := range tx.TxIn {
// Don't attempt to accumulate the total input age if the
@ -65,7 +65,7 @@ func calcInputValueAge(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight
// have their block height set to a special constant.
// Their input age should computed as zero since their
// parent hasn't made it into a block yet.
var inputAge int32
var inputAge uint64
originHeight := entry.BlockHeight()
if originHeight == UnminedHeight {
inputAge = 0
@ -86,7 +86,7 @@ func calcInputValueAge(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight
// of each of its input values multiplied by their age (# of confirmations).
// Thus, the final formula for the priority is:
// sum(inputValue * inputAge) / adjustedTxSize
func CalcPriority(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight int32) float64 {
func CalcPriority(tx *wire.MsgTx, utxoSet blockdag.UTXOSet, nextBlockHeight uint64) float64 {
// In order to encourage spending multiple old unspent transaction
// outputs thereby reducing the total set, don't count the constant
// overhead for each input as well as enough bytes of the signature

View File

@ -46,7 +46,7 @@ func hexToBytes(s string) []byte {
// provided source transactions as if there were available at the respective
// block height specified in the heights slice. The length of the source txns
// and source tx heights must match or it will panic.
func newUTXOSet(sourceTxns []*wire.MsgTx, sourceTxHeights []int32) blockdag.UTXOSet {
func newUTXOSet(sourceTxns []*wire.MsgTx, sourceTxHeights []uint64) blockdag.UTXOSet {
if len(sourceTxns) != len(sourceTxHeights) {
panic("each transaction must have its block height specified")
}
@ -130,14 +130,14 @@ func TestCalcPriority(t *testing.T) {
name string // test description
tx *wire.MsgTx // tx to calc priority for
utxoSet blockdag.UTXOSet // inputs to tx
nextHeight int32 // height for priority calc
nextHeight uint64 // height for priority calc
want float64 // expected priority
}{
{
name: "one height 7 input, prio tx height 169",
tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{7}),
[]uint64{7}),
nextHeight: 169,
want: 1.125e+10,
},
@ -145,7 +145,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 100 input, prio tx height 169",
tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{100}),
[]uint64{100}),
nextHeight: 169,
want: 4.791666666666667e+09,
},
@ -153,7 +153,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 7 input, prio tx height 100000",
tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{7}),
[]uint64{7}),
nextHeight: 100000,
want: 6.943958333333333e+12,
},
@ -161,7 +161,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 100 input, prio tx height 100000",
tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{100}),
[]uint64{100}),
nextHeight: 100000,
want: 6.9375e+12,
},

View File

@ -19,7 +19,7 @@ func newSimulatorClient(address string, connCfg *rpcclient.ConnConfig) (*simulat
onBlockAdded: make(chan struct{}, 1),
}
notificationHandlers := &rpcclient.NotificationHandlers{
OnFilteredBlockAdded: func(height int32, header *wire.BlockHeader,
OnFilteredBlockAdded: func(height uint64, header *wire.BlockHeader,
txs []*util.Tx) {
if client.notifyForNewBlocks {
client.onBlockAdded <- struct{}{}

View File

@ -123,7 +123,7 @@ type pauseMsg struct {
// headerNode is used as a node in a list of headers that are linked together
// between checkpoints.
type headerNode struct {
height int32
height uint64
hash *daghash.Hash
}
@ -180,7 +180,7 @@ type SyncManager struct {
// resetHeaderState sets the headers-first mode state to values appropriate for
// syncing from a new peer.
func (sm *SyncManager) resetHeaderState(newestHash *daghash.Hash, newestHeight int32) {
func (sm *SyncManager) resetHeaderState(newestHash *daghash.Hash, newestHeight uint64) {
sm.headersFirstMode = false
sm.headerList.Init()
sm.startHeader = nil
@ -198,7 +198,7 @@ func (sm *SyncManager) resetHeaderState(newestHash *daghash.Hash, newestHeight i
// It returns nil when there is not one either because the height is already
// later than the final checkpoint or some other reason such as disabled
// checkpoints.
func (sm *SyncManager) findNextHeaderCheckpoint(height int32) *dagconfig.Checkpoint {
func (sm *SyncManager) findNextHeaderCheckpoint(height uint64) *dagconfig.Checkpoint {
checkpoints := sm.dag.Checkpoints()
if len(checkpoints) == 0 {
return nil

View File

@ -640,7 +640,7 @@ func (c *Client) VerifyDAG() (bool, error) {
// the returned instance.
//
// See VerifyDAGLevel for the blocking version and more details.
func (c *Client) VerifyDAGLevelAsync(checkLevel int32) FutureVerifyDAGResult {
func (c *Client) VerifyDAGLevelAsync(checkLevel uint64) FutureVerifyDAGResult {
cmd := btcjson.NewVerifyDAGCmd(&checkLevel, nil)
return c.sendCmd(cmd)
}
@ -654,7 +654,7 @@ func (c *Client) VerifyDAGLevelAsync(checkLevel int32) FutureVerifyDAGResult {
//
// See VerifyDAG to use the default check level and VerifyDAGBlocks to
// override the number of blocks to verify.
func (c *Client) VerifyDAGLevel(checkLevel int32) (bool, error) {
func (c *Client) VerifyDAGLevel(checkLevel uint64) (bool, error) {
return c.VerifyDAGLevelAsync(checkLevel).Receive()
}
@ -663,7 +663,7 @@ func (c *Client) VerifyDAGLevel(checkLevel int32) (bool, error) {
// the returned instance.
//
// See VerifyDAGBlocks for the blocking version and more details.
func (c *Client) VerifyDAGBlocksAsync(checkLevel, numBlocks int32) FutureVerifyDAGResult {
func (c *Client) VerifyDAGBlocksAsync(checkLevel, numBlocks uint64) FutureVerifyDAGResult {
cmd := btcjson.NewVerifyDAGCmd(&checkLevel, &numBlocks)
return c.sendCmd(cmd)
}
@ -679,7 +679,7 @@ func (c *Client) VerifyDAGBlocksAsync(checkLevel, numBlocks int32) FutureVerifyD
// current longest dag.
//
// See VerifyDAG and VerifyDAGLevel to use defaults.
func (c *Client) VerifyDAGBlocks(checkLevel, numBlocks int32) (bool, error) {
func (c *Client) VerifyDAGBlocks(checkLevel, numBlocks uint64) (bool, error) {
return c.VerifyDAGBlocksAsync(checkLevel, numBlocks).Receive()
}

View File

@ -21,7 +21,7 @@ func main() {
// for notifications. See the documentation of the rpcclient
// NotificationHandlers type for more details about each handler.
ntfnHandlers := rpcclient.NotificationHandlers{
OnFilteredBlockAdded: func(height int32, header *wire.BlockHeader, txns []*util.Tx) {
OnFilteredBlockAdded: func(height uint64, header *wire.BlockHeader, txns []*util.Tx) {
log.Printf("Block added: %s (%d) %s",
header.BlockHash(), height, header.Timestamp)
},

View File

@ -152,7 +152,7 @@ type FutureGetBestBlockResult chan *response
// Receive waits for the response promised by the future and returns the hash
// and height of the block in the longest (best) chain.
func (r FutureGetBestBlockResult) Receive() (*daghash.Hash, int32, error) {
func (r FutureGetBestBlockResult) Receive() (*daghash.Hash, uint64, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, 0, err
@ -190,7 +190,7 @@ func (c *Client) GetBestBlockAsync() FutureGetBestBlockResult {
// chain.
//
// NOTE: This is a btcd extension.
func (c *Client) GetBestBlock() (*daghash.Hash, int32, error) {
func (c *Client) GetBestBlock() (*daghash.Hash, uint64, error) {
return c.GetBestBlockAsync().Receive()
}

View File

@ -104,7 +104,7 @@ type NotificationHandlers struct {
// NotifyBlocks has been made to register for the notification and the
// function is non-nil. Its parameters differ from OnBlockAdded: it
// receives the block's height, header, and relevant transactions.
OnFilteredBlockAdded func(height int32, header *wire.BlockHeader,
OnFilteredBlockAdded func(height uint64, header *wire.BlockHeader,
txs []*util.Tx)
// OnRecvTx is invoked when a transaction that receives funds to a
@ -464,7 +464,7 @@ func parseDAGNtfnParams(params []json.RawMessage) (*daghash.Hash,
//
// NOTE: This is a btcd extension ported from github.com/decred/dcrrpcclient
// and requires a websocket connection.
func parseFilteredBlockAddedParams(params []json.RawMessage) (int32,
func parseFilteredBlockAddedParams(params []json.RawMessage) (uint64,
*wire.BlockHeader, []*util.Tx, error) {
if len(params) < 3 {
@ -472,7 +472,7 @@ func parseFilteredBlockAddedParams(params []json.RawMessage) (int32,
}
// Unmarshal first parameter as an integer.
var blockHeight int32
var blockHeight uint64
err := json.Unmarshal(params[0], &blockHeight)
if err != nil {
return 0, nil, nil, err

View File

@ -762,7 +762,7 @@ func (sp *Peer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters) {
return
}
hashes, err := sp.server.DAG.HeightToHashRange(int32(msg.StartHeight),
hashes, err := sp.server.DAG.HeightToHashRange(msg.StartHeight,
msg.StopHash, wire.MaxGetCFiltersReqRange)
if err != nil {
peerLog.Debugf("Invalid getcfilters request: %s", err)
@ -793,7 +793,7 @@ func (sp *Peer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders) {
return
}
startHeight := int32(msg.StartHeight)
startHeight := msg.StartHeight
maxResults := wire.MaxCFHeadersPerMsg
// If StartHeight is positive, fetch the predecessor block hash so we can
@ -2474,7 +2474,7 @@ func NewServer(listenAddrs []string, db database.DB, dagParams *dagconfig.Params
MaxTxVersion: 1,
},
DAGParams: dagParams,
BestHeight: func() int32 { return s.DAG.Height() }, //TODO: (Ori) This is probably wrong. Done only for compilation
BestHeight: func() uint64 { return s.DAG.Height() }, //TODO: (Ori) This is probably wrong. Done only for compilation
MedianTimePast: func() time.Time { return s.DAG.CalcPastMedianTime() },
CalcSequenceLockNoLock: func(tx *util.Tx, utxoSet blockdag.UTXOSet) (*blockdag.SequenceLock, error) {
return s.DAG.CalcSequenceLockNoLock(tx, utxoSet, true)
@ -2843,7 +2843,7 @@ func (s checkpointSorter) Less(i, j int) bool {
func mergeCheckpoints(defaultCheckpoints, additional []dagconfig.Checkpoint) []dagconfig.Checkpoint {
// Create a map of the additional checkpoints to remove duplicates while
// leaving the most recently-specified checkpoint.
extra := make(map[int32]dagconfig.Checkpoint)
extra := make(map[uint64]dagconfig.Checkpoint)
for _, checkpoint := range additional {
extra[checkpoint.Height] = checkpoint
}

View File

@ -746,7 +746,7 @@ func createVoutList(mtx *wire.MsgTx, chainParams *dagconfig.Params, filterAddrMa
// to a raw transaction JSON object.
func createTxRawResult(dagParams *dagconfig.Params, mtx *wire.MsgTx,
txID string, blkHeader *wire.BlockHeader, blkHash string,
blkHeight int32, chainHeight int32, acceptedBy *daghash.Hash) (*btcjson.TxRawResult, error) {
blkHeight uint64, chainHeight uint64, acceptedBy *daghash.Hash) (*btcjson.TxRawResult, error) {
mtxHex, err := messageToHex(mtx)
if err != nil {
@ -1202,7 +1202,7 @@ func handleGetBlock(s *Server, cmd interface{}, closeChan <-chan struct{}) (inte
Nonce: blockHeader.Nonce,
Time: blockHeader.Timestamp.Unix(),
Confirmations: uint64(1 + s.cfg.DAG.Height() - blockHeight), //TODO: (Ori) This is probably wrong. Done only for compilation
Height: int64(blockHeight),
Height: blockHeight,
Size: int32(len(blkBytes)),
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
Difficulty: getDifficultyRatio(blockHeader.Bits, params),
@ -1270,8 +1270,8 @@ func handleGetBlockDAGInfo(s *Server, cmd interface{}, closeChan <-chan struct{}
dagInfo := &btcjson.GetBlockDAGInfoResult{
DAG: params.Name,
Blocks: dag.Height(), //TODO: (Ori) This is wrong. Done only for compilation
Headers: dag.Height(), //TODO: (Ori) This is wrong. Done only for compilation
Blocks: dag.BlockCount(),
Headers: dag.BlockCount(),
TipHashes: daghash.Strings(dag.TipHashes()),
Difficulty: getDifficultyRatio(dag.CurrentBits(), params),
MedianTime: dag.CalcPastMedianTime().Unix(),
@ -1782,7 +1782,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
reply := btcjson.GetBlockTemplateResult{
Bits: strconv.FormatInt(int64(header.Bits), 16),
CurTime: header.Timestamp.Unix(),
Height: int64(template.Height),
Height: template.Height,
ParentHashes: daghash.Strings(header.ParentHashes),
SigOpLimit: blockdag.MaxSigOpsPerBlock,
SizeLimit: wire.MaxBlockPayload,
@ -2370,7 +2370,7 @@ func handleGetInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (inter
ret := &btcjson.InfoDAGResult{
Version: int32(1000000*version.AppMajor + 10000*version.AppMinor + 100*version.AppPatch),
ProtocolVersion: int32(maxProtocolVersion),
Blocks: s.cfg.DAG.Height(), //TODO: (Ori) This is wrong. Done only for compilation
Blocks: s.cfg.DAG.BlockCount(),
TimeOffset: int64(s.cfg.TimeSource.Offset().Seconds()),
Connections: s.cfg.ConnMgr.ConnectedCount(),
Proxy: config.MainConfig().Proxy,
@ -2552,7 +2552,7 @@ func handleGetRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct
// try the block database.
var mtx *wire.MsgTx
var blkHash *daghash.Hash
var blkHeight int32
var blkHeight uint64
tx, err := s.cfg.TxMemPool.FetchTransaction(txID)
if err != nil {
if s.cfg.TxIndex == nil {
@ -2630,7 +2630,7 @@ func handleGetRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct
// The verbose flag is set, so generate the JSON object and return it.
var blkHeader *wire.BlockHeader
var blkHashStr string
var dagHeight int32
var dagHeight uint64
if blkHash != nil {
// Fetch the header from chain.
header, err := s.cfg.DAG.HeaderByHash(blkHash)
@ -2665,7 +2665,7 @@ func handleGetTxOut(s *Server, cmd interface{}, closeChan <-chan struct{}) (inte
// If requested and the tx is available in the mempool try to fetch it
// from there, otherwise attempt to fetch from the block database.
var bestBlockHash string
var confirmations int32
var confirmations uint64
var value uint64
var pkScript []byte
var isCoinbase bool
@ -3252,7 +3252,7 @@ func handleSearchRawTransactions(s *Server, cmd interface{}, closeChan <-chan st
// confirmations or block information).
var blkHeader *wire.BlockHeader
var blkHashStr string
var blkHeight int32
var blkHeight uint64
if blkHash := rtx.blkHash; blkHash != nil {
// Fetch the header from chain.
header, err := s.cfg.DAG.HeaderByHash(blkHash)
@ -3476,7 +3476,7 @@ func handleValidateAddress(s *Server, cmd interface{}, closeChan <-chan struct{}
return result, nil
}
func verifyDAG(s *Server, level, depth int32) error {
func verifyDAG(s *Server, level, depth uint64) error {
finishHeight := s.cfg.DAG.Height() - depth //TODO: (Ori) This is probably wrong. Done only for compilation
if finishHeight < 0 {
finishHeight = 0
@ -3516,7 +3516,7 @@ func verifyDAG(s *Server, level, depth int32) error {
func handleVerifyDAG(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.VerifyDAGCmd)
var checkLevel, checkDepth int32
var checkLevel, checkDepth uint64
if c.CheckLevel != nil {
checkLevel = *c.CheckLevel
}

View File

@ -8,6 +8,7 @@ import (
"bytes"
"fmt"
"io"
"math"
"github.com/daglabs/btcd/dagconfig/daghash"
"github.com/daglabs/btcd/wire"
@ -19,9 +20,8 @@ type OutOfRangeError string
const (
// BlockHeightUnknown is the value returned for a block height that is unknown.
// This is typically because the block has not been inserted into the main chain
// yet.
BlockHeightUnknown = int32(-1)
// This is typically because the block has not been inserted into the DAG yet.
BlockHeightUnknown = math.MaxUint64
// CoinbaseTransactionIndex is the index of the coinbase transaction in every block
CoinbaseTransactionIndex = 0
@ -44,7 +44,7 @@ type Block struct {
msgBlock *wire.MsgBlock // Underlying MsgBlock
serializedBlock []byte // Serialized bytes for the block
blockHash *daghash.Hash // Cached block hash
blockHeight int32 // Height in the main block chain
blockHeight uint64 // Height in the DAG
transactions []*Tx // Transactions
txnsGenerated bool // ALL wrapped transactions generated
}
@ -194,12 +194,12 @@ func (b *Block) TxLoc() ([]wire.TxLoc, error) {
// Height returns the saved height of the block in the block chain. This value
// will be BlockHeightUnknown if it hasn't already explicitly been set.
func (b *Block) Height() int32 {
func (b *Block) Height() uint64 {
return b.blockHeight
}
// SetHeight sets the height of the block in the block chain.
func (b *Block) SetHeight(height int32) {
func (b *Block) SetHeight(height uint64) {
b.blockHeight = height
}

View File

@ -30,7 +30,7 @@ func TestBlock(t *testing.T) {
}
// Ensure block height set and get work properly.
wantHeight := int32(100000)
wantHeight := uint64(100000)
b.SetHeight(wantHeight)
if gotHeight := b.Height(); gotHeight != wantHeight {
t.Errorf("Height: mismatched height - got %v, want %v",

View File

@ -14,16 +14,16 @@ var (
oneLsh256 = new(big.Int).Lsh(bigOne, 256)
// log2FloorMasks defines the masks to use when quickly calculating
// floor(log2(x)) in a constant log2(32) = 5 steps, where x is a uint32, using
// shifts. They are derived from (2^(2^x) - 1) * (2^(2^x)), for x in 4..0.
log2FloorMasks = []uint32{0xffff0000, 0xff00, 0xf0, 0xc, 0x2}
// floor(log2(x)) in a constant log2(64) = 6 steps, where x is a uint64, using
// shifts. They are derived from (2^(2^x) - 1) * (2^(2^x)), for x in 5..0.
log2FloorMasks = []uint64{0xffffffff00000000, 0xffff0000, 0xff00, 0xf0, 0xc, 0x2}
)
// FastLog2Floor calculates and returns floor(log2(x)) in a constant 5 steps.
func FastLog2Floor(n uint32) uint8 {
func FastLog2Floor(n uint64) uint8 {
rv := uint8(0)
exponent := uint8(16)
for i := 0; i < 5; i++ {
exponent := uint8(32)
for i := 0; i < 6; i++ {
if n&log2FloorMasks[i] != 0 {
rv += exponent
n >>= exponent

35
util/btcmath_test.go Normal file
View File

@ -0,0 +1,35 @@
package util
import (
"testing"
)
func TestFastLog2Floor(t *testing.T) {
tests := []struct {
n uint64
expectedResult uint8
}{
{1, 0},
{2, 1},
{3, 1},
{4, 2},
{5, 2},
{16, 4},
{31, 4},
{1684234, 20},
{4294967295, 31}, // math.MaxUint32 (2^32 - 1)
{4294967296, 32}, // 2^32
{4294967297, 32}, // 2^32 + 1
{4611686018427387904, 62},
{9223372036854775808, 63}, // 2^63
{18446744073709551615, 63}, // math.MaxUint64 (2^64 - 1).
}
for _, test := range tests {
actualResult := FastLog2Floor(test.n)
if test.expectedResult != actualResult {
t.Errorf("TestFastLog2Floor: %d: expected result: %d but got: %d", test.n, test.expectedResult, actualResult)
}
}
}

View File

@ -109,8 +109,8 @@ func TestMessage(t *testing.T) {
{msgFilterLoad, msgFilterLoad, pver, MainNet, 35},
{msgMerkleBlock, msgMerkleBlock, pver, MainNet, 183},
{msgReject, msgReject, pver, MainNet, 79},
{msgGetCFilters, msgGetCFilters, pver, MainNet, 61},
{msgGetCFHeaders, msgGetCFHeaders, pver, MainNet, 61},
{msgGetCFilters, msgGetCFilters, pver, MainNet, 65},
{msgGetCFHeaders, msgGetCFHeaders, pver, MainNet, 65},
{msgGetCFCheckpt, msgGetCFCheckpt, pver, MainNet, 57},
{msgCFilter, msgCFilter, pver, MainNet, 65},
{msgCFHeaders, msgCFHeaders, pver, MainNet, 90},

View File

@ -15,7 +15,7 @@ import (
// chain of basic (0x00) or extended (0x01) headers.
type MsgGetCFHeaders struct {
FilterType FilterType
StartHeight uint32
StartHeight uint64
StopHash *daghash.Hash
}
@ -61,14 +61,14 @@ func (msg *MsgGetCFHeaders) Command() string {
// MaxPayloadLength returns the maximum length the payload can be for the
// receiver. This is part of the Message interface implementation.
func (msg *MsgGetCFHeaders) MaxPayloadLength(pver uint32) uint32 {
// Filter type + uint32 + block hash
return 1 + 4 + daghash.HashSize
// Filter type + uint64 + block hash
return 1 + 8 + daghash.HashSize
}
// NewMsgGetCFHeaders returns a new bitcoin getcfheader message that conforms to
// the Message interface using the passed parameters and defaults for the
// remaining fields.
func NewMsgGetCFHeaders(filterType FilterType, startHeight uint32,
func NewMsgGetCFHeaders(filterType FilterType, startHeight uint64,
stopHash *daghash.Hash) *MsgGetCFHeaders {
return &MsgGetCFHeaders{
FilterType: filterType,

View File

@ -19,7 +19,7 @@ const MaxGetCFiltersReqRange = 1000
// blocks.
type MsgGetCFilters struct {
FilterType FilterType
StartHeight uint32
StartHeight uint64
StopHash *daghash.Hash
}
@ -65,14 +65,14 @@ func (msg *MsgGetCFilters) Command() string {
// MaxPayloadLength returns the maximum length the payload can be for the
// receiver. This is part of the Message interface implementation.
func (msg *MsgGetCFilters) MaxPayloadLength(pver uint32) uint32 {
// Filter type + uint32 + block hash
return 1 + 4 + daghash.HashSize
// Filter type + uint64 + block hash
return 1 + 8 + daghash.HashSize
}
// NewMsgGetCFilters returns a new bitcoin getcfilters message that conforms to
// the Message interface using the passed parameters and defaults for the
// remaining fields.
func NewMsgGetCFilters(filterType FilterType, startHeight uint32,
func NewMsgGetCFilters(filterType FilterType, startHeight uint64,
stopHash *daghash.Hash) *MsgGetCFilters {
return &MsgGetCFilters{
FilterType: filterType,