[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() bluestParent := parents.bluest()
blockHeight := int32(0) blockHeight := uint64(0)
if !block.IsGenesis() { if !block.IsGenesis() {
blockHeight = parents.maxHeight() + 1 blockHeight = parents.maxHeight() + 1
} }

View File

@ -94,10 +94,10 @@ type blockNode struct {
workSum *big.Int workSum *big.Int
// height is the position in the block DAG. // 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 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 // Some fields from block headers to aid in best chain selection and
// reconstructing headers from memory. These must be treated as // 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 return node.parents.maxHeight() + 1
} }
func calculateChainHeight(node *blockNode) uint32 { func calculateChainHeight(node *blockNode) uint64 {
if node.isGenesis() { if node.isGenesis() {
return 0 return 0
} }
@ -202,7 +202,7 @@ func (node *blockNode) Header() *wire.BlockHeader {
// that is lower than requested height would be returned. // that is lower than requested height would be returned.
// //
// This function is safe for concurrent access. // 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 { if height < 0 || height > node.height {
return nil return nil
} }
@ -220,7 +220,7 @@ func (node *blockNode) SelectedAncestor(height int32) *blockNode {
// height minus provided distance. // height minus provided distance.
// //
// This function is safe for concurrent access. // 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) return node.SelectedAncestor(node.height - distance)
} }

View File

@ -26,7 +26,7 @@ func TestChainHeight(t *testing.T) {
tests := []struct { tests := []struct {
node *blockNode node *blockNode
expectedChainHeight uint32 expectedChainHeight uint64
}{ }{
{ {
node: node0, 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 // maxHeight returns the height of the highest block in the block set
func (bs blockSet) maxHeight() int32 { func (bs blockSet) maxHeight() uint64 {
var maxHeight int32 var maxHeight uint64
for _, node := range bs { for _, node := range bs {
if maxHeight < node.height { if maxHeight < node.height {
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 // verifyCheckpoint returns whether the passed block height and hash combination
// match the checkpoint data. It also returns true if there is no checkpoint // match the checkpoint data. It also returns true if there is no checkpoint
// data for the passed block height. // 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() { if !dag.HasCheckpoints() {
return true return true
} }

View File

@ -47,7 +47,7 @@ func loadBlocks(filename string) (blocks []*util.Block, err error) {
var block *util.Block var block *util.Block
err = nil err = nil
for height := 0; err == nil; height++ { for height := uint64(0); err == nil; height++ {
var rintbuf uint32 var rintbuf uint32
err = binary.Read(dr, binary.LittleEndian, &rintbuf) err = binary.Read(dr, binary.LittleEndian, &rintbuf)
if err == io.EOF { if err == io.EOF {
@ -74,7 +74,7 @@ func loadBlocks(filename string) (blocks []*util.Block, err error) {
if err != nil { if err != nil {
return return
} }
block.SetHeight(int32(height)) block.SetHeight(height)
blocks = append(blocks, block) blocks = append(blocks, block)
} }
@ -151,7 +151,7 @@ func loadUTXOSet(filename string) (UTXOSet, error) {
// TestSetBlockRewardMaturity makes the ability to set the block reward maturity // TestSetBlockRewardMaturity makes the ability to set the block reward maturity
// available when running tests. // available when running tests.
func (dag *BlockDAG) TestSetBlockRewardMaturity(maturity uint16) { func (dag *BlockDAG) TestSetBlockRewardMaturity(maturity uint64) {
dag.dagParams.BlockRewardMaturity = maturity dag.dagParams.BlockRewardMaturity = maturity
} }
@ -174,7 +174,7 @@ func newTestDAG(params *dagconfig.Params) *BlockDAG {
timeSource: NewMedianTime(), timeSource: NewMedianTime(),
minRetargetTimespan: targetTimespan / adjustmentFactor, minRetargetTimespan: targetTimespan / adjustmentFactor,
maxRetargetTimespan: targetTimespan * adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor,
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), blocksPerRetarget: uint64(targetTimespan / targetTimePerBlock),
index: index, index: index,
virtual: newVirtualBlock(setFromSlice(node), params.K), virtual: newVirtualBlock(setFromSlice(node), params.K),
genesis: index.LookupNode(params.GenesisHash), 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 // be changed afterwards, so there is no need to protect them with a
// separate mutex. // separate mutex.
checkpoints []dagconfig.Checkpoint checkpoints []dagconfig.Checkpoint
checkpointsByHeight map[int32]*dagconfig.Checkpoint checkpointsByHeight map[uint64]*dagconfig.Checkpoint
db database.DB db database.DB
dagParams *dagconfig.Params dagParams *dagconfig.Params
timeSource MedianTimeSource timeSource MedianTimeSource
@ -77,7 +77,7 @@ type BlockDAG struct {
// a separate mutex. // a separate mutex.
minRetargetTimespan int64 // target timespan / adjustment factor minRetargetTimespan int64 // target timespan / adjustment factor
maxRetargetTimespan int64 // target timespan * adjustment factor maxRetargetTimespan int64 // target timespan * adjustment factor
blocksPerRetarget int32 // target timespan / target time per block blocksPerRetarget uint64 // target timespan / target time per block
// dagLock protects concurrent access to the vast majority of the // dagLock protects concurrent access to the vast majority of the
// fields in this struct below this point. // fields in this struct below this point.
@ -333,7 +333,7 @@ func (dag *BlockDAG) addOrphanBlock(block *util.Block) {
// 'BlockHeight' has been reached. // 'BlockHeight' has been reached.
type SequenceLock struct { type SequenceLock struct {
Seconds int64 Seconds int64
BlockHeight int32 BlockHeight int64
} }
// CalcSequenceLock computes a relative lock-time SequenceLock for the passed // 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 // the input's height as its converted absolute
// lock-time. We subtract one from the relative lock in // lock-time. We subtract one from the relative lock in
// order to maintain the original lockTime semantics. // order to maintain the original lockTime semantics.
blockHeight := inputHeight + int32(relativeLock-1) blockHeight := int64(inputHeight) + relativeLock - 1
if blockHeight > sequenceLock.BlockHeight { if blockHeight > sequenceLock.BlockHeight {
sequenceLock.BlockHeight = 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 // 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() return dag.virtual.tips().maxHeight()
} }
@ -1231,10 +1231,10 @@ func (dag *BlockDAG) blockLocator(node *blockNode) BlockLocator {
// Requested hash itself + genesis block. // Requested hash itself + genesis block.
// Then floor(log2(height-10)) entries for the skip portion. // 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) locator := make(BlockLocator, 0, maxEntries)
step := int32(1) step := uint64(1)
for node != nil { for node != nil {
locator = append(locator, node.hash) locator = append(locator, node.hash)
@ -1264,7 +1264,7 @@ func (dag *BlockDAG) blockLocator(node *blockNode) BlockLocator {
// DAG. // DAG.
// //
// This function is safe for concurrent access. // 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) node := dag.index.LookupNode(hash)
if node == nil { if node == nil {
str := fmt.Sprintf("block %s is not in the DAG", hash) 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. // end hash must belong to a block that is known to be valid.
// //
// This function is safe for concurrent access. // 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) { endHash *daghash.Hash, maxResults int) ([]*daghash.Hash, error) {
endNode := dag.index.LookupNode(endHash) 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. // endHash where the block height is a positive multiple of interval.
// //
// This function is safe for concurrent access. // 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) { ) ([]*daghash.Hash, error) {
endNode := dag.index.LookupNode(endHash) endNode := dag.index.LookupNode(endHash)
@ -1347,15 +1347,15 @@ func (dag *BlockDAG) IntervalBlockHashes(endHash *daghash.Hash, interval int,
} }
endHeight := endNode.height endHeight := endNode.height
resultsLength := int(endHeight) / interval resultsLength := endHeight / interval
hashes := make([]*daghash.Hash, resultsLength) hashes := make([]*daghash.Hash, resultsLength)
dag.virtual.mtx.Lock() dag.virtual.mtx.Lock()
defer dag.virtual.mtx.Unlock() defer dag.virtual.mtx.Unlock()
blockNode := endNode blockNode := endNode
for index := int(endHeight) / interval; index > 0; index-- { for index := endHeight / interval; index > 0; index-- {
blockHeight := int32(index * interval) blockHeight := index * interval
blockNode = blockNode.SelectedAncestor(blockHeight) blockNode = blockNode.SelectedAncestor(blockHeight)
hashes[index-1] = blockNode.hash 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 // Generate a checkpoint by height map from the provided checkpoints
// and assert the provided checkpoints are sorted by height as required. // and assert the provided checkpoints are sorted by height as required.
var checkpointsByHeight map[int32]*dagconfig.Checkpoint var checkpointsByHeight map[uint64]*dagconfig.Checkpoint
var prevCheckpointHeight int32 var prevCheckpointHeight uint64
if len(config.Checkpoints) > 0 { if len(config.Checkpoints) > 0 {
checkpointsByHeight = make(map[int32]*dagconfig.Checkpoint) checkpointsByHeight = make(map[uint64]*dagconfig.Checkpoint)
for i := range config.Checkpoints { for i := range config.Checkpoints {
checkpoint := &config.Checkpoints[i] checkpoint := &config.Checkpoints[i]
if checkpoint.Height <= prevCheckpointHeight { if checkpoint.Height <= prevCheckpointHeight {
@ -1685,7 +1685,7 @@ func New(config *Config) (*BlockDAG, error) {
indexManager: config.IndexManager, indexManager: config.IndexManager,
minRetargetTimespan: targetTimespan / adjustmentFactor, minRetargetTimespan: targetTimespan / adjustmentFactor,
maxRetargetTimespan: targetTimespan * adjustmentFactor, maxRetargetTimespan: targetTimespan * adjustmentFactor,
blocksPerRetarget: int32(targetTimespan / targetTimePerBlock), blocksPerRetarget: uint64(targetTimespan / targetTimePerBlock),
index: index, index: index,
virtual: newVirtualBlock(nil, params.K), virtual: newVirtualBlock(nil, params.K),
orphans: make(map[daghash.Hash]*orphanBlock), orphans: make(map[daghash.Hash]*orphanBlock),

View File

@ -231,8 +231,8 @@ func TestCalcSequenceLock(t *testing.T) {
dag := newTestDAG(netParams) dag := newTestDAG(netParams)
node := dag.selectedTip() node := dag.selectedTip()
blockTime := node.Header().Timestamp blockTime := node.Header().Timestamp
numBlocksToGenerate := uint32(5) numBlocksToGenerate := 5
for i := uint32(0); i < numBlocksToGenerate; i++ { for i := 0; i < numBlocksToGenerate; i++ {
blockTime = blockTime.Add(time.Second) blockTime = blockTime.Add(time.Second)
node = newTestNode(setFromSlice(node), blockVersion, 0, blockTime, netParams.K) node = newTestNode(setFromSlice(node), blockVersion, 0, blockTime, netParams.K)
dag.index.AddNode(node) 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}}) msgTx := wire.NewNativeMsgTx(wire.TxVersion, nil, []*wire.TxOut{{PkScript: nil, Value: 10}})
targetTx := util.NewTx(msgTx) targetTx := util.NewTx(msgTx)
utxoSet := NewFullUTXOSet() 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 // 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 // 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(), TxID: *targetTx.ID(),
Index: 0, Index: 0,
} }
prevUtxoHeight := int32(numBlocksToGenerate) - 4 prevUtxoHeight := uint64(numBlocksToGenerate) - 4
// Obtain the median time past from the PoV of the input created above. // 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* // 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, utxoSet: utxoSet,
want: &SequenceLock{ want: &SequenceLock{
Seconds: medianTime + (5 << wire.SequenceLockTimeGranularity) - 1, Seconds: medianTime + (5 << wire.SequenceLockTimeGranularity) - 1,
BlockHeight: prevUtxoHeight + 3, BlockHeight: int64(prevUtxoHeight) + 3,
}, },
}, },
// Transaction with a single input. The input's sequence number // Transaction with a single input. The input's sequence number
@ -360,7 +360,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet, utxoSet: utxoSet,
want: &SequenceLock{ want: &SequenceLock{
Seconds: -1, Seconds: -1,
BlockHeight: prevUtxoHeight + 2, BlockHeight: int64(prevUtxoHeight) + 2,
}, },
}, },
// A transaction with two inputs with lock times expressed in // A transaction with two inputs with lock times expressed in
@ -397,7 +397,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet, utxoSet: utxoSet,
want: &SequenceLock{ want: &SequenceLock{
Seconds: -1, Seconds: -1,
BlockHeight: prevUtxoHeight + 10, BlockHeight: int64(prevUtxoHeight) + 10,
}, },
}, },
// A transaction with multiple inputs. Two inputs are time // A transaction with multiple inputs. Two inputs are time
@ -422,7 +422,7 @@ func TestCalcSequenceLock(t *testing.T) {
utxoSet: utxoSet, utxoSet: utxoSet,
want: &SequenceLock{ want: &SequenceLock{
Seconds: medianTime + (13 << wire.SequenceLockTimeGranularity) - 1, Seconds: medianTime + (13 << wire.SequenceLockTimeGranularity) - 1,
BlockHeight: prevUtxoHeight + 8, BlockHeight: int64(prevUtxoHeight) + 8,
}, },
}, },
// A transaction with a single unconfirmed input. As the input // A transaction with a single unconfirmed input. As the input
@ -437,7 +437,7 @@ func TestCalcSequenceLock(t *testing.T) {
mempool: true, mempool: true,
want: &SequenceLock{ want: &SequenceLock{
Seconds: -1, Seconds: -1,
BlockHeight: nextBlockHeight + 1, BlockHeight: int64(nextBlockHeight) + 1,
}, },
}, },
// A transaction with a single unconfirmed input. The input has // A transaction with a single unconfirmed input. The input has
@ -587,7 +587,7 @@ func TestHeightToHashRange(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
startHeight int32 // locator for requested inventory startHeight uint64 // locator for requested inventory
endHash *daghash.Hash // stop hash for locator endHash *daghash.Hash // stop hash for locator
maxResults int // max to locate, 0 = wire const maxResults int // max to locate, 0 = wire const
hashes []*daghash.Hash // expected located hashes hashes []*daghash.Hash // expected located hashes
@ -680,7 +680,7 @@ func TestIntervalBlockHashes(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
endHash *daghash.Hash endHash *daghash.Hash
interval int interval uint64
hashes []*daghash.Hash hashes []*daghash.Hash
expectError bool 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. // Bit 0 indicates whether the containing transaction is a block reward.
// Bits 1-x encode height of containing transaction. // Bits 1-x encode height of containing transaction.
isBlockReward := code&0x01 != 0 isBlockReward := code&0x01 != 0
blockHeight := int32(code >> 1) blockHeight := code >> 1
// Decode the compressed unspent transaction output. // Decode the compressed unspent transaction output.
amount, pkScript, _, err := decodeCompressedTxOut(serialized[offset:]) 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 // 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 // block index entries for the hash to height and height to hash mappings for
// the provided values. // 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. // Serialize the height for use in the index entries.
var serializedHeight [4]byte var serializedHeight [8]byte
byteOrder.PutUint32(serializedHeight[:], uint32(height)) byteOrder.PutUint64(serializedHeight[:], height)
// Add the block hash to height mapping to the index. // Add the block hash to height mapping to the index.
meta := dbTx.Metadata() meta := dbTx.Metadata()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -157,5 +157,5 @@ type ValidateAddressWalletResult struct {
// GetBestBlockResult models the data from the getbestblock command. // GetBestBlockResult models the data from the getbestblock command.
type GetBestBlockResult struct { type GetBestBlockResult struct {
Hash string `json:"hash"` 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 // The latest known block must be at least the last known checkpoint
// plus required checkpoint confirmations. // plus required checkpoint confirmations.
checkpointConfirmations := int32(blockdag.CheckpointConfirmations) checkpointConfirmations := uint64(blockdag.CheckpointConfirmations)
requiredHeight := latestCheckpoint.Height + checkpointConfirmations requiredHeight := latestCheckpoint.Height + checkpointConfirmations
if block.Height() < requiredHeight { if block.Height() < requiredHeight {
return nil, fmt.Errorf("the block database is only at height "+ 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. // Loop backwards through the DAG to find checkpoint candidates.
candidates := make([]*dagconfig.Checkpoint, 0, cfg.NumCandidates) candidates := make([]*dagconfig.Checkpoint, 0, cfg.NumCandidates)
numTested := int32(0) numTested := uint64(0)
for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight { for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight {
// Display progress. // Display progress.
if numTested%progressInterval == 0 { if numTested%progressInterval == 0 {

View File

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

View File

@ -57,7 +57,7 @@ const phantomK = 10
// documentation for blockchain.IsCheckpointCandidate for details on the // documentation for blockchain.IsCheckpointCandidate for details on the
// selection criteria. // selection criteria.
type Checkpoint struct { type Checkpoint struct {
Height int32 Height uint64
Hash *daghash.Hash Hash *daghash.Hash
} }
@ -130,11 +130,11 @@ type Params struct {
// BlockRewardMaturity is the number of blocks required before newly mined // BlockRewardMaturity is the number of blocks required before newly mined
// coins (coinbase or fee transactions) can be spent. // coins (coinbase or fee transactions) can be spent.
BlockRewardMaturity uint16 BlockRewardMaturity uint64
// SubsidyReductionInterval is the interval of blocks before the subsidy // SubsidyReductionInterval is the interval of blocks before the subsidy
// is reduced. // is reduced.
SubsidyReductionInterval int32 SubsidyReductionInterval uint64
// TargetTimespan is the desired amount of time that should elapse // TargetTimespan is the desired amount of time that should elapse
// before the block difficulty requirement is examined to determine how // 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 // Deployments define the specific consensus rule changes to be voted
// on. // on.
RuleChangeActivationThreshold uint32 RuleChangeActivationThreshold uint64
MinerConfirmationWindow uint32 MinerConfirmationWindow uint64
Deployments [DefinedDeployments]ConsensusDeployment Deployments [DefinedDeployments]ConsensusDeployment
// Mempool parameters // 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 // assertChainHeight retrieves the current chain height from the given test
// harness and ensures it matches the provided expected height. // 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() height, err := r.Node.GetBlockCount()
if err != nil { if err != nil {
t.Fatalf("failed to retrieve block height: %v", err) t.Fatalf("failed to retrieve block height: %v", err)
} }
if uint32(height) != expectedHeight { if height != expectedHeight {
_, _, line, _ := runtime.Caller(1) _, _, line, _ := runtime.Caller(1)
t.Fatalf("assertion failed at line %d: block height of %d "+ t.Fatalf("assertion failed at line %d: block height of %d "+
"is not the expected %d", line, height, expectedHeight) "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 // standardCoinbaseScript returns a standard script suitable for use as the
// signature script of the coinbase transaction of a new block. In particular, // 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. // 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)). return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
AddInt64(int64(extraNonce)).Script() AddInt64(int64(extraNonce)).Script()
} }
// createCoinbaseTx returns a coinbase transaction paying an appropriate // createCoinbaseTx returns a coinbase transaction paying an appropriate
// subsidy based on the passed block height to the provided address. // 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, addr util.Address, mineTo []wire.TxOut,
net *dagconfig.Params) (*util.Tx, error) { net *dagconfig.Params) (*util.Tx, error) {
@ -139,7 +139,7 @@ func CreateBlock(parentBlock *util.Block, inclusionTxs []*util.Tx,
var ( var (
parentHash *daghash.Hash parentHash *daghash.Hash
blockHeight int32 blockHeight uint64
parentBlockTime time.Time parentBlockTime time.Time
) )

View File

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

View File

@ -171,7 +171,7 @@ func New(activeNet *dagconfig.Params, handlers *rpcclient.NotificationHandlers,
// callback. // callback.
if handlers.OnFilteredBlockAdded != nil { if handlers.OnFilteredBlockAdded != nil {
obc := handlers.OnFilteredBlockAdded 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) wallet.IngestBlock(height, header, filteredTxns)
obc(height, header, filteredTxns) obc(height, header, filteredTxns)
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -35,13 +35,13 @@ import (
// transactions to appear as though they are spending completely valid utxos. // transactions to appear as though they are spending completely valid utxos.
type fakeChain struct { type fakeChain struct {
sync.RWMutex sync.RWMutex
currentHeight int32 currentHeight uint64
medianTimePast time.Time medianTimePast time.Time
} }
// BestHeight returns the current height associated with the fake chain // BestHeight returns the current height associated with the fake chain
// instance. // instance.
func (s *fakeChain) BestHeight() int32 { func (s *fakeChain) BestHeight() uint64 {
s.RLock() s.RLock()
height := s.currentHeight height := s.currentHeight
s.RUnlock() s.RUnlock()
@ -49,7 +49,7 @@ func (s *fakeChain) BestHeight() int32 {
} }
// SetHeight sets the current height associated with the fake chain instance. // 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.Lock()
s.currentHeight = height s.currentHeight = height
s.Unlock() s.Unlock()
@ -121,7 +121,7 @@ type poolHarness struct {
// address associated with the harness. It automatically uses a standard // address associated with the harness. It automatically uses a standard
// signature script that starts with the block height that is required by // signature script that starts with the block height that is required by
// version 2 blocks. // 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. // Create standard coinbase script.
extraNonce := int64(0) extraNonce := int64(0)
coinbaseScript, err := txscript.NewScriptBuilder(). coinbaseScript, err := txscript.NewScriptBuilder().
@ -344,7 +344,7 @@ func newPoolHarness(dagParams *dagconfig.Params, numOutputs uint32, dbName strin
outpoints = append(outpoints, txOutToSpendableOutpoint(coinbase, i)) outpoints = append(outpoints, txOutToSpendableOutpoint(coinbase, i))
} }
if dagParams.BlockRewardMaturity != 0 { if dagParams.BlockRewardMaturity != 0 {
harness.chain.SetHeight(int32(dagParams.BlockRewardMaturity) + curHeight) harness.chain.SetHeight(dagParams.BlockRewardMaturity + curHeight)
} else { } else {
harness.chain.SetHeight(curHeight + 1) 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 // finalized, conforming to more stringent size constraints, having scripts
// of recognized forms, and not containing "dust" outputs (those that are // of recognized forms, and not containing "dust" outputs (those that are
// so small it costs more to process them than they are worth). // 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 { medianTimePast time.Time, policy *Policy) error {
// The transaction must be a currently supported version. // The transaction must be a currently supported version.

View File

@ -307,7 +307,7 @@ func TestCheckTransactionStandard(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
tx *wire.MsgTx tx *wire.MsgTx
height int32 height uint64
isStandard bool isStandard bool
code wire.RejectCode 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 // 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 // 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. // 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 { ticker *time.Ticker, quit chan struct{}) bool {
// Create some convenience variables. // 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 // Height is the block height when the entry was added to the the source
// pool. // pool.
Height int32 Height uint64
// Fee is the total fee the transaction associated with the entry pays. // Fee is the total fee the transaction associated with the entry pays.
Fee uint64 Fee uint64
@ -198,9 +198,8 @@ type BlockTemplate struct {
// transaction in the generated template performs. // transaction in the generated template performs.
SigOpCounts []int64 SigOpCounts []int64
// Height is the height at which the block template connects to the main // Height is the height at which the block template connects to the DAG
// chain. Height uint64
Height int32
// ValidPayAddress indicates whether or not the template coinbase pays // ValidPayAddress indicates whether or not the template coinbase pays
// to an address or is redeemable by anyone. See the documentation on // 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, // 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 // it starts with the block height that is required by version 2 blocks and adds
// the extra nonce as well as additional coinbase flags. // 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)). return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)). AddInt64(int64(extraNonce)).AddData([]byte(CoinbaseFlags)).
Script() 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 // See the comment for NewBlockTemplate for more information about why the nil
// address handling is useful. // 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 // Create the script to pay to the provided payment address if one was
// specified. Otherwise create a script that allows the coinbase to be // specified. Otherwise create a script that allows the coinbase to be
// redeemable by anyone. // 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 // block by regenerating the coinbase script with the passed value and block
// height. It also recalculates and updates the new merkle root that results // height. It also recalculates and updates the new merkle root that results
// from changing the coinbase script. // 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) coinbaseScript, err := StandardCoinbaseScript(blockHeight, extraNonce)
if err != nil { if err != nil {
return err return err
@ -749,7 +748,7 @@ func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight
} }
// DAGHeight returns the DAG's height // DAGHeight returns the DAG's height
func (g *BlkTmplGenerator) DAGHeight() int32 { func (g *BlkTmplGenerator) DAGHeight() uint64 {
return g.dag.Height() return g.dag.Height()
} }

View File

@ -148,7 +148,7 @@ func TestNewBlockTemplate(t *testing.T) {
} }
var createCoinbaseTxPatch *monkey.PatchGuard 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() createCoinbaseTxPatch.Unpatch()
defer createCoinbaseTxPatch.Restore() defer createCoinbaseTxPatch.Restore()
tx, err := CreateCoinbaseTx(params, coinbaseScript, nextBlockHeight, addr) tx, err := CreateCoinbaseTx(params, coinbaseScript, nextBlockHeight, addr)
@ -298,7 +298,7 @@ func TestNewBlockTemplate(t *testing.T) {
standardCoinbaseScriptErrString := "standardCoinbaseScript err" standardCoinbaseScriptErrString := "standardCoinbaseScript err"
var standardCoinbaseScriptPatch *monkey.PatchGuard 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) return nil, errors.New(standardCoinbaseScriptErrString)
}) })
defer standardCoinbaseScriptPatch.Unpatch() 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 // 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, // which are currently in the mempool and hence not mined into a block yet,
// contribute no additional input age to the transaction. // 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 var totalInputAge float64
for _, txIn := range tx.TxIn { for _, txIn := range tx.TxIn {
// Don't attempt to accumulate the total input age if the // 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. // have their block height set to a special constant.
// Their input age should computed as zero since their // Their input age should computed as zero since their
// parent hasn't made it into a block yet. // parent hasn't made it into a block yet.
var inputAge int32 var inputAge uint64
originHeight := entry.BlockHeight() originHeight := entry.BlockHeight()
if originHeight == UnminedHeight { if originHeight == UnminedHeight {
inputAge = 0 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). // of each of its input values multiplied by their age (# of confirmations).
// Thus, the final formula for the priority is: // Thus, the final formula for the priority is:
// sum(inputValue * inputAge) / adjustedTxSize // 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 // In order to encourage spending multiple old unspent transaction
// outputs thereby reducing the total set, don't count the constant // outputs thereby reducing the total set, don't count the constant
// overhead for each input as well as enough bytes of the signature // 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 // provided source transactions as if there were available at the respective
// block height specified in the heights slice. The length of the source txns // block height specified in the heights slice. The length of the source txns
// and source tx heights must match or it will panic. // 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) { if len(sourceTxns) != len(sourceTxHeights) {
panic("each transaction must have its block height specified") panic("each transaction must have its block height specified")
} }
@ -130,14 +130,14 @@ func TestCalcPriority(t *testing.T) {
name string // test description name string // test description
tx *wire.MsgTx // tx to calc priority for tx *wire.MsgTx // tx to calc priority for
utxoSet blockdag.UTXOSet // inputs to tx utxoSet blockdag.UTXOSet // inputs to tx
nextHeight int32 // height for priority calc nextHeight uint64 // height for priority calc
want float64 // expected priority want float64 // expected priority
}{ }{
{ {
name: "one height 7 input, prio tx height 169", name: "one height 7 input, prio tx height 169",
tx: commonRedeemTx1, tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1}, utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{7}), []uint64{7}),
nextHeight: 169, nextHeight: 169,
want: 1.125e+10, want: 1.125e+10,
}, },
@ -145,7 +145,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 100 input, prio tx height 169", name: "one height 100 input, prio tx height 169",
tx: commonRedeemTx1, tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1}, utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{100}), []uint64{100}),
nextHeight: 169, nextHeight: 169,
want: 4.791666666666667e+09, want: 4.791666666666667e+09,
}, },
@ -153,7 +153,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 7 input, prio tx height 100000", name: "one height 7 input, prio tx height 100000",
tx: commonRedeemTx1, tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1}, utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{7}), []uint64{7}),
nextHeight: 100000, nextHeight: 100000,
want: 6.943958333333333e+12, want: 6.943958333333333e+12,
}, },
@ -161,7 +161,7 @@ func TestCalcPriority(t *testing.T) {
name: "one height 100 input, prio tx height 100000", name: "one height 100 input, prio tx height 100000",
tx: commonRedeemTx1, tx: commonRedeemTx1,
utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1}, utxoSet: newUTXOSet([]*wire.MsgTx{commonSourceTx1},
[]int32{100}), []uint64{100}),
nextHeight: 100000, nextHeight: 100000,
want: 6.9375e+12, want: 6.9375e+12,
}, },

View File

@ -19,7 +19,7 @@ func newSimulatorClient(address string, connCfg *rpcclient.ConnConfig) (*simulat
onBlockAdded: make(chan struct{}, 1), onBlockAdded: make(chan struct{}, 1),
} }
notificationHandlers := &rpcclient.NotificationHandlers{ notificationHandlers := &rpcclient.NotificationHandlers{
OnFilteredBlockAdded: func(height int32, header *wire.BlockHeader, OnFilteredBlockAdded: func(height uint64, header *wire.BlockHeader,
txs []*util.Tx) { txs []*util.Tx) {
if client.notifyForNewBlocks { if client.notifyForNewBlocks {
client.onBlockAdded <- struct{}{} 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 // headerNode is used as a node in a list of headers that are linked together
// between checkpoints. // between checkpoints.
type headerNode struct { type headerNode struct {
height int32 height uint64
hash *daghash.Hash hash *daghash.Hash
} }
@ -180,7 +180,7 @@ type SyncManager struct {
// resetHeaderState sets the headers-first mode state to values appropriate for // resetHeaderState sets the headers-first mode state to values appropriate for
// syncing from a new peer. // 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.headersFirstMode = false
sm.headerList.Init() sm.headerList.Init()
sm.startHeader = nil 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 // 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 // later than the final checkpoint or some other reason such as disabled
// checkpoints. // checkpoints.
func (sm *SyncManager) findNextHeaderCheckpoint(height int32) *dagconfig.Checkpoint { func (sm *SyncManager) findNextHeaderCheckpoint(height uint64) *dagconfig.Checkpoint {
checkpoints := sm.dag.Checkpoints() checkpoints := sm.dag.Checkpoints()
if len(checkpoints) == 0 { if len(checkpoints) == 0 {
return nil return nil

View File

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

View File

@ -21,7 +21,7 @@ func main() {
// for notifications. See the documentation of the rpcclient // for notifications. See the documentation of the rpcclient
// NotificationHandlers type for more details about each handler. // NotificationHandlers type for more details about each handler.
ntfnHandlers := rpcclient.NotificationHandlers{ 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", log.Printf("Block added: %s (%d) %s",
header.BlockHash(), height, header.Timestamp) 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 // Receive waits for the response promised by the future and returns the hash
// and height of the block in the longest (best) chain. // 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) res, err := receiveFuture(r)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
@ -190,7 +190,7 @@ func (c *Client) GetBestBlockAsync() FutureGetBestBlockResult {
// chain. // chain.
// //
// NOTE: This is a btcd extension. // 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() return c.GetBestBlockAsync().Receive()
} }

View File

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

View File

@ -762,7 +762,7 @@ func (sp *Peer) OnGetCFilters(_ *peer.Peer, msg *wire.MsgGetCFilters) {
return return
} }
hashes, err := sp.server.DAG.HeightToHashRange(int32(msg.StartHeight), hashes, err := sp.server.DAG.HeightToHashRange(msg.StartHeight,
msg.StopHash, wire.MaxGetCFiltersReqRange) msg.StopHash, wire.MaxGetCFiltersReqRange)
if err != nil { if err != nil {
peerLog.Debugf("Invalid getcfilters request: %s", err) peerLog.Debugf("Invalid getcfilters request: %s", err)
@ -793,7 +793,7 @@ func (sp *Peer) OnGetCFHeaders(_ *peer.Peer, msg *wire.MsgGetCFHeaders) {
return return
} }
startHeight := int32(msg.StartHeight) startHeight := msg.StartHeight
maxResults := wire.MaxCFHeadersPerMsg maxResults := wire.MaxCFHeadersPerMsg
// If StartHeight is positive, fetch the predecessor block hash so we can // 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, MaxTxVersion: 1,
}, },
DAGParams: dagParams, 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() }, MedianTimePast: func() time.Time { return s.DAG.CalcPastMedianTime() },
CalcSequenceLockNoLock: func(tx *util.Tx, utxoSet blockdag.UTXOSet) (*blockdag.SequenceLock, error) { CalcSequenceLockNoLock: func(tx *util.Tx, utxoSet blockdag.UTXOSet) (*blockdag.SequenceLock, error) {
return s.DAG.CalcSequenceLockNoLock(tx, utxoSet, true) 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 { func mergeCheckpoints(defaultCheckpoints, additional []dagconfig.Checkpoint) []dagconfig.Checkpoint {
// Create a map of the additional checkpoints to remove duplicates while // Create a map of the additional checkpoints to remove duplicates while
// leaving the most recently-specified checkpoint. // leaving the most recently-specified checkpoint.
extra := make(map[int32]dagconfig.Checkpoint) extra := make(map[uint64]dagconfig.Checkpoint)
for _, checkpoint := range additional { for _, checkpoint := range additional {
extra[checkpoint.Height] = checkpoint 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. // to a raw transaction JSON object.
func createTxRawResult(dagParams *dagconfig.Params, mtx *wire.MsgTx, func createTxRawResult(dagParams *dagconfig.Params, mtx *wire.MsgTx,
txID string, blkHeader *wire.BlockHeader, blkHash string, 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) mtxHex, err := messageToHex(mtx)
if err != nil { if err != nil {
@ -1202,7 +1202,7 @@ func handleGetBlock(s *Server, cmd interface{}, closeChan <-chan struct{}) (inte
Nonce: blockHeader.Nonce, Nonce: blockHeader.Nonce,
Time: blockHeader.Timestamp.Unix(), Time: blockHeader.Timestamp.Unix(),
Confirmations: uint64(1 + s.cfg.DAG.Height() - blockHeight), //TODO: (Ori) This is probably wrong. Done only for compilation 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)), Size: int32(len(blkBytes)),
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16), Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
Difficulty: getDifficultyRatio(blockHeader.Bits, params), Difficulty: getDifficultyRatio(blockHeader.Bits, params),
@ -1270,8 +1270,8 @@ func handleGetBlockDAGInfo(s *Server, cmd interface{}, closeChan <-chan struct{}
dagInfo := &btcjson.GetBlockDAGInfoResult{ dagInfo := &btcjson.GetBlockDAGInfoResult{
DAG: params.Name, DAG: params.Name,
Blocks: dag.Height(), //TODO: (Ori) This is wrong. Done only for compilation Blocks: dag.BlockCount(),
Headers: dag.Height(), //TODO: (Ori) This is wrong. Done only for compilation Headers: dag.BlockCount(),
TipHashes: daghash.Strings(dag.TipHashes()), TipHashes: daghash.Strings(dag.TipHashes()),
Difficulty: getDifficultyRatio(dag.CurrentBits(), params), Difficulty: getDifficultyRatio(dag.CurrentBits(), params),
MedianTime: dag.CalcPastMedianTime().Unix(), MedianTime: dag.CalcPastMedianTime().Unix(),
@ -1782,7 +1782,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld
reply := btcjson.GetBlockTemplateResult{ reply := btcjson.GetBlockTemplateResult{
Bits: strconv.FormatInt(int64(header.Bits), 16), Bits: strconv.FormatInt(int64(header.Bits), 16),
CurTime: header.Timestamp.Unix(), CurTime: header.Timestamp.Unix(),
Height: int64(template.Height), Height: template.Height,
ParentHashes: daghash.Strings(header.ParentHashes), ParentHashes: daghash.Strings(header.ParentHashes),
SigOpLimit: blockdag.MaxSigOpsPerBlock, SigOpLimit: blockdag.MaxSigOpsPerBlock,
SizeLimit: wire.MaxBlockPayload, SizeLimit: wire.MaxBlockPayload,
@ -2370,7 +2370,7 @@ func handleGetInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (inter
ret := &btcjson.InfoDAGResult{ ret := &btcjson.InfoDAGResult{
Version: int32(1000000*version.AppMajor + 10000*version.AppMinor + 100*version.AppPatch), Version: int32(1000000*version.AppMajor + 10000*version.AppMinor + 100*version.AppPatch),
ProtocolVersion: int32(maxProtocolVersion), 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()), TimeOffset: int64(s.cfg.TimeSource.Offset().Seconds()),
Connections: s.cfg.ConnMgr.ConnectedCount(), Connections: s.cfg.ConnMgr.ConnectedCount(),
Proxy: config.MainConfig().Proxy, Proxy: config.MainConfig().Proxy,
@ -2552,7 +2552,7 @@ func handleGetRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct
// try the block database. // try the block database.
var mtx *wire.MsgTx var mtx *wire.MsgTx
var blkHash *daghash.Hash var blkHash *daghash.Hash
var blkHeight int32 var blkHeight uint64
tx, err := s.cfg.TxMemPool.FetchTransaction(txID) tx, err := s.cfg.TxMemPool.FetchTransaction(txID)
if err != nil { if err != nil {
if s.cfg.TxIndex == 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. // The verbose flag is set, so generate the JSON object and return it.
var blkHeader *wire.BlockHeader var blkHeader *wire.BlockHeader
var blkHashStr string var blkHashStr string
var dagHeight int32 var dagHeight uint64
if blkHash != nil { if blkHash != nil {
// Fetch the header from chain. // Fetch the header from chain.
header, err := s.cfg.DAG.HeaderByHash(blkHash) 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 // If requested and the tx is available in the mempool try to fetch it
// from there, otherwise attempt to fetch from the block database. // from there, otherwise attempt to fetch from the block database.
var bestBlockHash string var bestBlockHash string
var confirmations int32 var confirmations uint64
var value uint64 var value uint64
var pkScript []byte var pkScript []byte
var isCoinbase bool var isCoinbase bool
@ -3252,7 +3252,7 @@ func handleSearchRawTransactions(s *Server, cmd interface{}, closeChan <-chan st
// confirmations or block information). // confirmations or block information).
var blkHeader *wire.BlockHeader var blkHeader *wire.BlockHeader
var blkHashStr string var blkHashStr string
var blkHeight int32 var blkHeight uint64
if blkHash := rtx.blkHash; blkHash != nil { if blkHash := rtx.blkHash; blkHash != nil {
// Fetch the header from chain. // Fetch the header from chain.
header, err := s.cfg.DAG.HeaderByHash(blkHash) header, err := s.cfg.DAG.HeaderByHash(blkHash)
@ -3476,7 +3476,7 @@ func handleValidateAddress(s *Server, cmd interface{}, closeChan <-chan struct{}
return result, nil 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 finishHeight := s.cfg.DAG.Height() - depth //TODO: (Ori) This is probably wrong. Done only for compilation
if finishHeight < 0 { if finishHeight < 0 {
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) { func handleVerifyDAG(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.VerifyDAGCmd) c := cmd.(*btcjson.VerifyDAGCmd)
var checkLevel, checkDepth int32 var checkLevel, checkDepth uint64
if c.CheckLevel != nil { if c.CheckLevel != nil {
checkLevel = *c.CheckLevel checkLevel = *c.CheckLevel
} }

View File

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

View File

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

View File

@ -14,16 +14,16 @@ var (
oneLsh256 = new(big.Int).Lsh(bigOne, 256) oneLsh256 = new(big.Int).Lsh(bigOne, 256)
// log2FloorMasks defines the masks to use when quickly calculating // 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 // 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 4..0. // shifts. They are derived from (2^(2^x) - 1) * (2^(2^x)), for x in 5..0.
log2FloorMasks = []uint32{0xffff0000, 0xff00, 0xf0, 0xc, 0x2} log2FloorMasks = []uint64{0xffffffff00000000, 0xffff0000, 0xff00, 0xf0, 0xc, 0x2}
) )
// FastLog2Floor calculates and returns floor(log2(x)) in a constant 5 steps. // 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) rv := uint8(0)
exponent := uint8(16) exponent := uint8(32)
for i := 0; i < 5; i++ { for i := 0; i < 6; i++ {
if n&log2FloorMasks[i] != 0 { if n&log2FloorMasks[i] != 0 {
rv += exponent rv += exponent
n >>= 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}, {msgFilterLoad, msgFilterLoad, pver, MainNet, 35},
{msgMerkleBlock, msgMerkleBlock, pver, MainNet, 183}, {msgMerkleBlock, msgMerkleBlock, pver, MainNet, 183},
{msgReject, msgReject, pver, MainNet, 79}, {msgReject, msgReject, pver, MainNet, 79},
{msgGetCFilters, msgGetCFilters, pver, MainNet, 61}, {msgGetCFilters, msgGetCFilters, pver, MainNet, 65},
{msgGetCFHeaders, msgGetCFHeaders, pver, MainNet, 61}, {msgGetCFHeaders, msgGetCFHeaders, pver, MainNet, 65},
{msgGetCFCheckpt, msgGetCFCheckpt, pver, MainNet, 57}, {msgGetCFCheckpt, msgGetCFCheckpt, pver, MainNet, 57},
{msgCFilter, msgCFilter, pver, MainNet, 65}, {msgCFilter, msgCFilter, pver, MainNet, 65},
{msgCFHeaders, msgCFHeaders, pver, MainNet, 90}, {msgCFHeaders, msgCFHeaders, pver, MainNet, 90},

View File

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

View File

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