From 0280fa0264f907cc9a8113f40cec0327206e0196 Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Fri, 7 Aug 2015 21:20:49 -0500 Subject: [PATCH] Convert block heights to int32. This commit converts all block height references to int32 instead of int64. The current target block production rate is 10 mins per block which means it will take roughly 40,800 years to reach the maximum height an int32 affords. Even if the target rate were lowered to one block per minute, it would still take roughly another 4,080 years to reach the maximum. In the mean time, there is no reason to use a larger type which results in higher memory and disk space usage. However, for now, in order to avoid having to reserialize a bunch of database information, the heights are still serialized to the database as 8-byte uint64s. This is being mainly being done in preparation for further upcoming infrastructure changes which will use the smaller and more efficient 4-byte serialization in the database as well. --- blockchain/accept.go | 2 +- blockchain/blocklocator.go | 6 ++-- blockchain/chain.go | 14 ++++----- blockchain/checkpoints.go | 2 +- blockchain/common_test.go | 2 +- blockchain/difficulty.go | 4 +-- blockchain/internal_test.go | 2 +- blockchain/txlookup.go | 2 +- blockchain/validate.go | 18 ++++++------ blockchain/validate_test.go | 2 +- blockmanager.go | 14 ++++----- chaincfg/params.go | 2 +- chainindexer.go | 4 +-- cmd/dropafter/dropafter.go | 4 +-- cmd/findcheckpoint/findcheckpoint.go | 4 +-- cpuminer.go | 2 +- database/db.go | 18 ++++++------ database/interface_test.go | 16 +++++----- database/ldb/block.go | 44 ++++++++++++++-------------- database/ldb/dup_test.go | 2 +- database/ldb/insertremove_test.go | 2 +- database/ldb/leveldb.go | 16 +++++----- database/ldb/operational_test.go | 26 ++++++++-------- database/ldb/tx.go | 26 ++++++++-------- database/memdb/memdb.go | 32 ++++++++++---------- database/reorg_test.go | 10 +++---- mempool.go | 14 ++++----- mining.go | 12 ++++---- peer.go | 8 ++--- rpcserver.go | 38 ++++++++++++------------ rpcwebsocket.go | 6 ++-- 31 files changed, 177 insertions(+), 177 deletions(-) diff --git a/blockchain/accept.go b/blockchain/accept.go index c5b07d52..f5dd2842 100644 --- a/blockchain/accept.go +++ b/blockchain/accept.go @@ -30,7 +30,7 @@ func (b *BlockChain) maybeAcceptBlock(block *btcutil.Block, flags BehaviorFlags) // The height of this block is one more than the referenced previous // block. - blockHeight := int64(0) + blockHeight := int32(0) if prevNode != nil { blockHeight = prevNode.height + 1 } diff --git a/blockchain/blocklocator.go b/blockchain/blocklocator.go index 7c9019bc..c05de0cf 100644 --- a/blockchain/blocklocator.go +++ b/blockchain/blocklocator.go @@ -48,8 +48,8 @@ func (b *BlockChain) BlockLocatorFromHash(hash *wire.ShaHash) BlockLocator { // Attempt to find the height of the block that corresponds to the // passed hash, and if it's on a side chain, also find the height at // which it forks from the main chain. - blockHeight := int64(-1) - forkHeight := int64(-1) + blockHeight := int32(-1) + forkHeight := int32(-1) node, exists := b.index[*hash] if !exists { // Try to look up the height for passed block hash. Assume an @@ -80,7 +80,7 @@ func (b *BlockChain) BlockLocatorFromHash(hash *wire.ShaHash) BlockLocator { // in the BlockLocator comment and make sure to leave room for the // final genesis hash. iterNode := node - increment := int64(1) + increment := int32(1) for len(locator) < wire.MaxBlockLocatorsPerMsg-1 { // Once there are 10 locators, exponentially increase the // distance between each block locator. diff --git a/blockchain/chain.go b/blockchain/chain.go index a602f1ec..dae879d7 100644 --- a/blockchain/chain.go +++ b/blockchain/chain.go @@ -58,7 +58,7 @@ type blockNode struct { parentHash *wire.ShaHash // height is the position in the block chain. - height int64 + height int32 // workSum is the total amount of work in the chain up to and including // this node. @@ -79,7 +79,7 @@ type blockNode struct { // completely disconnected from the chain and the workSum value is just the work // for the passed block. The work sum is updated accordingly when the node is // inserted into a chain. -func newBlockNode(blockHeader *wire.BlockHeader, blockSha *wire.ShaHash, height int64) *blockNode { +func newBlockNode(blockHeader *wire.BlockHeader, blockSha *wire.ShaHash, height int32) *blockNode { // Make a copy of the hash so the node doesn't keep a reference to part // of the full block/block header preventing it from being garbage // collected. @@ -144,7 +144,7 @@ func removeChildNode(children []*blockNode, node *blockNode) []*blockNode { type BlockChain struct { db database.Db chainParams *chaincfg.Params - checkpointsByHeight map[int64]*chaincfg.Checkpoint + checkpointsByHeight map[int32]*chaincfg.Checkpoint notifications NotificationCallback root *blockNode bestChain *blockNode @@ -384,7 +384,7 @@ func (b *BlockChain) GenerateInitialIndex() error { // Start at the next block after the latest one on the next loop // iteration. - start += int64(len(hashList)) + start += int32(len(hashList)) } return nil @@ -567,7 +567,7 @@ func (b *BlockChain) pruneBlockNodes() error { // the latter loads the node and the goal is to find nodes still in // memory that can be pruned. newRootNode := b.bestChain - for i := int64(0); i < minMemoryNodes-1 && newRootNode != nil; i++ { + for i := int32(0); i < minMemoryNodes-1 && newRootNode != nil; i++ { newRootNode = newRootNode.parent } @@ -1069,9 +1069,9 @@ func (b *BlockChain) IsCurrent(timeSource MedianTimeSource) bool { // interested in receiving notifications. func New(db database.Db, params *chaincfg.Params, c NotificationCallback) *BlockChain { // Generate a checkpoint by height map from the provided checkpoints. - var checkpointsByHeight map[int64]*chaincfg.Checkpoint + var checkpointsByHeight map[int32]*chaincfg.Checkpoint if len(params.Checkpoints) > 0 { - checkpointsByHeight = make(map[int64]*chaincfg.Checkpoint) + checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint) for i := range params.Checkpoints { checkpoint := ¶ms.Checkpoints[i] checkpointsByHeight[checkpoint.Height] = checkpoint diff --git a/blockchain/checkpoints.go b/blockchain/checkpoints.go index d5840f11..c0dc21c2 100644 --- a/blockchain/checkpoints.go +++ b/blockchain/checkpoints.go @@ -59,7 +59,7 @@ func (b *BlockChain) LatestCheckpoint() *chaincfg.Checkpoint { // verifyCheckpoint returns whether the passed block height and hash combination // match the hard-coded checkpoint data. It also returns true if there is no // checkpoint data for the passed block height. -func (b *BlockChain) verifyCheckpoint(height int64, hash *wire.ShaHash) bool { +func (b *BlockChain) verifyCheckpoint(height int32, hash *wire.ShaHash) bool { if b.noCheckpoints || len(b.chainParams.Checkpoints) == 0 { return true } diff --git a/blockchain/common_test.go b/blockchain/common_test.go index 8a557570..8963f6f2 100644 --- a/blockchain/common_test.go +++ b/blockchain/common_test.go @@ -184,7 +184,7 @@ func loadTxStore(filename string) (blockchain.TxStore, error) { if err != nil { return nil, err } - txD.BlockHeight = int64(uintBuf) + txD.BlockHeight = int32(uintBuf) // Num spent bits. err = binary.Read(r, binary.LittleEndian, &uintBuf) diff --git a/blockchain/difficulty.go b/blockchain/difficulty.go index 0a045571..c922df9b 100644 --- a/blockchain/difficulty.go +++ b/blockchain/difficulty.go @@ -25,7 +25,7 @@ const ( // BlocksPerRetarget is the number of blocks between each difficulty // retarget. It is calculated based on the desired block generation // rate. - BlocksPerRetarget = int64(targetTimespan / targetSpacing) + BlocksPerRetarget = int32(targetTimespan / targetSpacing) // retargetAdjustmentFactor is the adjustment factor used to limit // the minimum and maximum amount of adjustment that can occur between @@ -295,7 +295,7 @@ func (b *BlockChain) calcNextRequiredDifficulty(lastNode *blockNode, newBlockTim // Get the block node at the previous retarget (targetTimespan days // worth of blocks). firstNode := lastNode - for i := int64(0); i < BlocksPerRetarget-1 && firstNode != nil; i++ { + for i := int32(0); i < BlocksPerRetarget-1 && firstNode != nil; i++ { // Get the previous block node. This function is used over // simply accessing firstNode.parent directly as it will // dynamically create previous block nodes as needed. This diff --git a/blockchain/internal_test.go b/blockchain/internal_test.go index 87a9ba81..e31b03fd 100644 --- a/blockchain/internal_test.go +++ b/blockchain/internal_test.go @@ -19,7 +19,7 @@ import ( // TstSetCoinbaseMaturity makes the ability to set the coinbase maturity // available to the test package. -func TstSetCoinbaseMaturity(maturity int64) { +func TstSetCoinbaseMaturity(maturity int32) { coinbaseMaturity = maturity } diff --git a/blockchain/txlookup.go b/blockchain/txlookup.go index 689f0d25..b7c8fe65 100644 --- a/blockchain/txlookup.go +++ b/blockchain/txlookup.go @@ -17,7 +17,7 @@ import ( type TxData struct { Tx *btcutil.Tx Hash *wire.ShaHash - BlockHeight int64 + BlockHeight int32 Spent []bool Err error } diff --git a/blockchain/validate.go b/blockchain/validate.go index 0fc9a949..fc00be45 100644 --- a/blockchain/validate.go +++ b/blockchain/validate.go @@ -55,7 +55,7 @@ var ( // coinbaseMaturity is the internal variable used for validating the // spending of coinbase outputs. A variable rather than the exported // constant is used because the tests need the ability to modify it. - coinbaseMaturity = int64(CoinbaseMaturity) + coinbaseMaturity = int32(CoinbaseMaturity) // zeroHash is the zero value for a wire.ShaHash and is defined as // a package level variable to avoid the need to create a new instance @@ -128,7 +128,7 @@ func IsCoinBase(tx *btcutil.Tx) bool { } // IsFinalizedTransaction determines whether or not a transaction is finalized. -func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int64, blockTime time.Time) bool { +func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int32, blockTime time.Time) bool { msgTx := tx.MsgTx() // Lock time of zero means the transaction is finalized. @@ -143,7 +143,7 @@ func IsFinalizedTransaction(tx *btcutil.Tx, blockHeight int64, blockTime time.Ti // threshold it is a block height. blockTimeOrHeight := int64(0) if lockTime < txscript.LockTimeThreshold { - blockTimeOrHeight = blockHeight + blockTimeOrHeight = int64(blockHeight) } else { blockTimeOrHeight = blockTime.Unix() } @@ -187,13 +187,13 @@ func isBIP0030Node(node *blockNode) bool { // // At the target block generation rate for the main network, this is // approximately every 4 years. -func CalcBlockSubsidy(height int64, chainParams *chaincfg.Params) int64 { +func CalcBlockSubsidy(height int32, chainParams *chaincfg.Params) int64 { if chainParams.SubsidyHalvingInterval == 0 { return baseSubsidy } // Equivalent to: baseSubsidy / 2^(height/subsidyHalvingInterval) - return baseSubsidy >> uint(height/int64(chainParams.SubsidyHalvingInterval)) + return baseSubsidy >> uint(height/chainParams.SubsidyHalvingInterval) } // CheckTransactionSanity performs some preliminary checks on a transaction to @@ -738,7 +738,7 @@ func (b *BlockChain) checkBlockContext(block *btcutil.Block, prevNode *blockNode // ExtractCoinbaseHeight attempts to extract the height of the block from the // scriptSig of a coinbase transaction. Coinbase heights are only present in // blocks of version 2 or later. This was added as part of BIP0034. -func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int64, error) { +func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int32, error) { sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript if len(sigScript) < 1 { str := "the coinbase signature script for blocks of " + @@ -761,12 +761,12 @@ func ExtractCoinbaseHeight(coinbaseTx *btcutil.Tx) (int64, error) { copy(serializedHeightBytes, sigScript[1:serializedLen+1]) serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes) - return int64(serializedHeight), nil + return int32(serializedHeight), nil } // checkSerializedHeight checks if the signature script in the passed // transaction starts with the serialized block height of wantHeight. -func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int64) error { +func checkSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int32) error { serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx) if err != nil { return err @@ -849,7 +849,7 @@ func (b *BlockChain) checkBIP0030(node *blockNode, block *btcutil.Block) error { // amount, and verifying the signatures to prove the spender was the owner of // the bitcoins and therefore allowed to spend them. As it checks the inputs, // it also calculates the total fees for the transaction and returns that value. -func CheckTransactionInputs(tx *btcutil.Tx, txHeight int64, txStore TxStore) (int64, error) { +func CheckTransactionInputs(tx *btcutil.Tx, txHeight int32, txStore TxStore) (int64, error) { // Coinbase transactions have no inputs. if IsCoinBase(tx) { return 0, nil diff --git a/blockchain/validate_test.go b/blockchain/validate_test.go index 2589f1ca..cca4470e 100644 --- a/blockchain/validate_test.go +++ b/blockchain/validate_test.go @@ -82,7 +82,7 @@ func TestCheckSerializedHeight(t *testing.T) { tests := []struct { sigScript []byte // Serialized data - wantHeight int64 // Expected height + wantHeight int32 // Expected height err error // Expected error type }{ // No serialized height length. diff --git a/blockmanager.go b/blockmanager.go index 1fb90538..68d01610 100644 --- a/blockmanager.go +++ b/blockmanager.go @@ -150,7 +150,7 @@ type pauseMsg struct { // headerNode is used as a node in a list of headers that are linked together // between checkpoints. type headerNode struct { - height int64 + height int32 sha *wire.ShaHash } @@ -163,7 +163,7 @@ type headerNode struct { type chainState struct { sync.Mutex newestHash *wire.ShaHash - newestHeight int64 + newestHeight int32 pastMedianTime time.Time pastMedianTimeErr error } @@ -172,7 +172,7 @@ type chainState struct { // chain. // // This function is safe for concurrent access. -func (c *chainState) Best() (*wire.ShaHash, int64) { +func (c *chainState) Best() (*wire.ShaHash, int32) { c.Lock() defer c.Unlock() @@ -207,7 +207,7 @@ type blockManager struct { // resetHeaderState sets the headers-first mode state to values appropriate for // syncing from a new peer. -func (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight int64) { +func (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight int32) { b.headersFirstMode = false b.headerList.Init() b.startHeader = nil @@ -225,7 +225,7 @@ func (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight i // This allows fast access to chain information since btcchain is currently not // safe for concurrent access and the block manager is typically quite busy // processing block and inventory. -func (b *blockManager) updateChainState(newestHash *wire.ShaHash, newestHeight int64) { +func (b *blockManager) updateChainState(newestHash *wire.ShaHash, newestHeight int32) { b.chainState.Lock() defer b.chainState.Unlock() @@ -243,7 +243,7 @@ func (b *blockManager) updateChainState(newestHash *wire.ShaHash, newestHeight i // It returns nil when there is not one either because the height is already // later than the final checkpoint or some other reason such as disabled // checkpoints. -func (b *blockManager) findNextHeaderCheckpoint(height int64) *chaincfg.Checkpoint { +func (b *blockManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint { // There is no next checkpoint if checkpoints are disabled or there are // none for this current network. if cfg.DisableCheckpoints { @@ -524,7 +524,7 @@ func (b *blockManager) current() bool { // TODO(oga) we can get chain to return the height of each block when we // parse an orphan, which would allow us to update the height of peers // from what it was at initial handshake. - if err != nil || height < int64(b.syncPeer.lastBlock) { + if err != nil || height < b.syncPeer.lastBlock { return false } return true diff --git a/chaincfg/params.go b/chaincfg/params.go index 053c1b2a..875dbde4 100644 --- a/chaincfg/params.go +++ b/chaincfg/params.go @@ -44,7 +44,7 @@ var ( // documentation for blockchain.IsCheckpointCandidate for details on the // selection criteria. type Checkpoint struct { - Height int64 + Height int32 Hash *wire.ShaHash } diff --git a/chainindexer.go b/chainindexer.go index fd9000e9..d33dee44 100644 --- a/chainindexer.go +++ b/chainindexer.go @@ -69,8 +69,8 @@ type addrIndexer struct { addrIndexJobs chan *indexBlockMsg writeRequests chan *writeIndexReq progressLogger *blockProgressLogger - currentIndexTip int64 - chainTip int64 + currentIndexTip int32 + chainTip int32 sync.Mutex } diff --git a/cmd/dropafter/dropafter.go b/cmd/dropafter/dropafter.go index dca1041e..b29247c2 100644 --- a/cmd/dropafter/dropafter.go +++ b/cmd/dropafter/dropafter.go @@ -167,7 +167,7 @@ var errBadShaPrefix = errors.New("invalid prefix") var errBadShaLen = errors.New("invalid len") var errBadShaChar = errors.New("invalid character") -func parsesha(argstr string) (argtype int, height int64, psha *wire.ShaHash, err error) { +func parsesha(argstr string) (argtype int, height int32, psha *wire.ShaHash, err error) { var sha wire.ShaHash var hashbuf string @@ -189,7 +189,7 @@ func parsesha(argstr string) (argtype int, height int64, psha *wire.ShaHash, err var h int h, err = strconv.Atoi(argstr) if err == nil { - height = int64(h) + height = int32(h) return } log.Infof("Unable to parse height %v, err %v", height, err) diff --git a/cmd/findcheckpoint/findcheckpoint.go b/cmd/findcheckpoint/findcheckpoint.go index d7ef81e6..a2d446b8 100644 --- a/cmd/findcheckpoint/findcheckpoint.go +++ b/cmd/findcheckpoint/findcheckpoint.go @@ -61,7 +61,7 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check // The latest known block must be at least the last known checkpoint // plus required checkpoint confirmations. - checkpointConfirmations := int64(blockchain.CheckpointConfirmations) + checkpointConfirmations := int32(blockchain.CheckpointConfirmations) requiredHeight := latestCheckpoint.Height + checkpointConfirmations if block.Height() < requiredHeight { return nil, fmt.Errorf("the block database is only at height "+ @@ -79,7 +79,7 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check // Loop backwards through the chain to find checkpoint candidates. candidates := make([]*chaincfg.Checkpoint, 0, cfg.NumCandidates) - numTested := int64(0) + numTested := int32(0) for len(candidates) < cfg.NumCandidates && block.Height() > requiredHeight { // Display progress. if numTested%progressInterval == 0 { diff --git a/cpuminer.go b/cpuminer.go index eaba26cd..f8e54afb 100644 --- a/cpuminer.go +++ b/cpuminer.go @@ -165,7 +165,7 @@ func (m *CPUMiner) submitBlock(block *btcutil.Block) bool { // This function will return early with false when conditions that trigger a // stale block such as a new block showing up or periodically when there are // new transactions and enough time has elapsed without finding a solution. -func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int64, +func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int32, ticker *time.Ticker, quit chan struct{}) bool { // Choose a random extra nonce offset for this block template and diff --git a/database/db.go b/database/db.go index e17510de..8158d2af 100644 --- a/database/db.go +++ b/database/db.go @@ -28,7 +28,7 @@ var ( // AllShas is a special value that can be used as the final sha when requesting // a range of shas by height to request them all. -const AllShas = int64(^uint64(0) >> 1) +const AllShas = int32(^uint32(0) >> 1) // Db defines a generic interface that is used to request and insert data into // the bitcoin block chain. This interface is intended to be agnostic to actual @@ -53,7 +53,7 @@ type Db interface { FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error) // FetchBlockHeightBySha returns the block height for the given hash. - FetchBlockHeightBySha(sha *wire.ShaHash) (height int64, err error) + FetchBlockHeightBySha(sha *wire.ShaHash) (height int32, err error) // FetchBlockHeaderBySha returns a wire.BlockHeader for the given // sha. The implementation may cache the underlying data if desired. @@ -61,13 +61,13 @@ type Db interface { // FetchBlockShaByHeight returns a block hash based on its height in the // block chain. - FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error) + FetchBlockShaByHeight(height int32) (sha *wire.ShaHash, err error) // FetchHeightRange looks up a range of blocks by the start and ending // heights. Fetch is inclusive of the start height and exclusive of the // ending height. To fetch all hashes from the start height until no // more are present, use the special id `AllShas'. - FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error) + FetchHeightRange(startHeight, endHeight int32) (rshalist []wire.ShaHash, err error) // ExistsTxSha returns whether or not the given tx hash is present in // the database @@ -103,19 +103,19 @@ type Db interface { // into the database. The first block inserted into the database // will be treated as the genesis block. Every subsequent block insert // requires the referenced parent block to already exist. - InsertBlock(block *btcutil.Block) (height int64, err error) + InsertBlock(block *btcutil.Block) (height int32, err error) // NewestSha returns the hash and block height of the most recent (end) // block of the block chain. It will return the zero hash, -1 for // the block height, and no error (nil) if there are not any blocks in // the database yet. - NewestSha() (sha *wire.ShaHash, height int64, err error) + NewestSha() (sha *wire.ShaHash, height int32, err error) // FetchAddrIndexTip returns the hash and block height of the most recent // block which has had its address index populated. It will return // ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the // addrindex hasn't yet been built up. - FetchAddrIndexTip() (sha *wire.ShaHash, height int64, err error) + FetchAddrIndexTip() (sha *wire.ShaHash, height int32, err error) // UpdateAddrIndexForBlock updates the stored addrindex with passed // index information for a particular block height. Additionally, it @@ -124,7 +124,7 @@ type Db interface { // transaction which is commited before the function returns. // Addresses are indexed by the raw bytes of their base58 decoded // hash160. - UpdateAddrIndexForBlock(blkSha *wire.ShaHash, height int64, + UpdateAddrIndexForBlock(blkSha *wire.ShaHash, height int32, addrIndex BlockAddrIndex) error // FetchTxsForAddr looks up and returns all transactions which either @@ -162,7 +162,7 @@ type TxListReply struct { Sha *wire.ShaHash Tx *wire.MsgTx BlkSha *wire.ShaHash - Height int64 + Height int32 TxSpent []bool Err error } diff --git a/database/interface_test.go b/database/interface_test.go index e44eb765..7cd82ccf 100644 --- a/database/interface_test.go +++ b/database/interface_test.go @@ -26,7 +26,7 @@ type testContext struct { t *testing.T dbType string db database.Db - blockHeight int64 + blockHeight int32 blockHash *wire.ShaHash block *btcutil.Block useSpends bool @@ -213,7 +213,7 @@ func testFetchBlockShaByHeight(tc *testContext) bool { func testFetchBlockShaByHeightErrors(tc *testContext) bool { // Invalid heights must error and return a nil hash. - tests := []int64{-1, tc.blockHeight + 1, tc.blockHeight + 2} + tests := []int32{-1, tc.blockHeight + 1, tc.blockHeight + 2} for i, wantHeight := range tests { hashFromDb, err := tc.db.FetchBlockShaByHeight(wantHeight) if err == nil { @@ -545,7 +545,7 @@ func testInterface(t *testing.T, dbType string) { context := testContext{t: t, dbType: dbType, db: db} t.Logf("Loaded %d blocks for testing %s", len(blocks), dbType) - for height := int64(1); height < int64(len(blocks)); height++ { + for height := int32(1); height < int32(len(blocks)); height++ { // Get the appropriate block and hash and update the test // context accordingly. block := blocks[height] @@ -581,7 +581,7 @@ func testInterface(t *testing.T, dbType string) { // Run the data integrity tests again after all blocks have been // inserted to ensure the spend tracking is working properly. context.useSpends = true - for height := int64(0); height < int64(len(blocks)); height++ { + for height := int32(0); height < int32(len(blocks)); height++ { // Get the appropriate block and hash and update the // test context accordingly. block := blocks[height] @@ -613,14 +613,14 @@ func testInterface(t *testing.T, dbType string) { - DropAfterBlockBySha(*wire.ShaHash) (err error) x ExistsSha(sha *wire.ShaHash) (exists bool) x FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error) - x FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error) - - FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error) + x FetchBlockShaByHeight(height int32) (sha *wire.ShaHash, err error) + - FetchHeightRange(startHeight, endHeight int32) (rshalist []wire.ShaHash, err error) x ExistsTxSha(sha *wire.ShaHash) (exists bool) x FetchTxBySha(txsha *wire.ShaHash) ([]*TxListReply, error) x FetchTxByShaList(txShaList []*wire.ShaHash) []*TxListReply x FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*TxListReply - x InsertBlock(block *btcutil.Block) (height int64, err error) - x NewestSha() (sha *wire.ShaHash, height int64, err error) + x InsertBlock(block *btcutil.Block) (height int32, err error) + x NewestSha() (sha *wire.ShaHash, height int32, err error) - RollbackClose() - Sync() */ diff --git a/database/ldb/block.go b/database/ldb/block.go index 1079420d..b8becc33 100644 --- a/database/ldb/block.go +++ b/database/ldb/block.go @@ -41,7 +41,7 @@ func (db *LevelDb) fetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err e // FetchBlockHeightBySha returns the block height for the given hash. This is // part of the database.Db interface implementation. -func (db *LevelDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int64, error) { +func (db *LevelDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int32, error) { db.dbLock.Lock() defer db.dbLock.Unlock() @@ -71,7 +71,7 @@ func (db *LevelDb) FetchBlockHeaderBySha(sha *wire.ShaHash) (bh *wire.BlockHeade return bh, err } -func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int64, error) { +func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int32, error) { key := shaBlkToKey(sha) data, err := db.lDb.Get(key, db.ro) @@ -85,13 +85,13 @@ func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int64, error) { // deserialize blkHeight := binary.LittleEndian.Uint64(data) - return int64(blkHeight), nil + return int32(blkHeight), nil } -func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *wire.ShaHash, rbuf []byte, err error) { +func (db *LevelDb) getBlkByHeight(blkHeight int32) (rsha *wire.ShaHash, rbuf []byte, err error) { var blkVal []byte - key := int64ToKey(blkHeight) + key := int64ToKey(int64(blkHeight)) blkVal, err = db.lDb.Get(key, db.ro) if err != nil { @@ -109,8 +109,8 @@ func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *wire.ShaHash, rbuf []b return &sha, blockdata, nil } -func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int64, rbuf []byte, err error) { - var blkHeight int64 +func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int32, rbuf []byte, err error) { + var blkHeight int32 blkHeight, err = db.getBlkLoc(sha) if err != nil { @@ -126,13 +126,13 @@ func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int64, rbuf []byte, err return blkHeight, buf, nil } -func (db *LevelDb) setBlk(sha *wire.ShaHash, blkHeight int64, buf []byte) { +func (db *LevelDb) setBlk(sha *wire.ShaHash, blkHeight int32, buf []byte) { // serialize var lw [8]byte binary.LittleEndian.PutUint64(lw[0:8], uint64(blkHeight)) shaKey := shaBlkToKey(sha) - blkKey := int64ToKey(blkHeight) + blkKey := int64ToKey(int64(blkHeight)) blkVal := make([]byte, len(sha)+len(buf)) copy(blkVal[0:], sha[:]) @@ -145,7 +145,7 @@ func (db *LevelDb) setBlk(sha *wire.ShaHash, blkHeight int64, buf []byte) { // insertSha stores a block hash and its associated data block with a // previous sha of `prevSha'. // insertSha shall be called with db lock held -func (db *LevelDb) insertBlockData(sha *wire.ShaHash, prevSha *wire.ShaHash, buf []byte) (int64, error) { +func (db *LevelDb) insertBlockData(sha *wire.ShaHash, prevSha *wire.ShaHash, buf []byte) (int32, error) { oBlkHeight, err := db.getBlkLoc(prevSha) if err != nil { // check current block count @@ -175,8 +175,8 @@ func (db *LevelDb) insertBlockData(sha *wire.ShaHash, prevSha *wire.ShaHash, buf // fetchSha returns the datablock for the given ShaHash. func (db *LevelDb) fetchSha(sha *wire.ShaHash) (rbuf []byte, - rblkHeight int64, err error) { - var blkHeight int64 + rblkHeight int32, err error) { + var blkHeight int32 var buf []byte blkHeight, buf, err = db.getBlk(sha) @@ -208,7 +208,7 @@ func (db *LevelDb) blkExistsSha(sha *wire.ShaHash) (bool, error) { // FetchBlockShaByHeight returns a block hash based on its height in the // block chain. -func (db *LevelDb) FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error) { +func (db *LevelDb) FetchBlockShaByHeight(height int32) (sha *wire.ShaHash, err error) { db.dbLock.Lock() defer db.dbLock.Unlock() @@ -217,8 +217,8 @@ func (db *LevelDb) FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err e // fetchBlockShaByHeight returns a block hash based on its height in the // block chain. -func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *wire.ShaHash, err error) { - key := int64ToKey(height) +func (db *LevelDb) fetchBlockShaByHeight(height int32) (rsha *wire.ShaHash, err error) { + key := int64ToKey(int64(height)) blkVal, err := db.lDb.Get(key, db.ro) if err != nil { @@ -236,11 +236,11 @@ func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *wire.ShaHash, err // heights. Fetch is inclusive of the start height and exclusive of the // ending height. To fetch all hashes from the start height until no // more are present, use the special id `AllShas'. -func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error) { +func (db *LevelDb) FetchHeightRange(startHeight, endHeight int32) (rshalist []wire.ShaHash, err error) { db.dbLock.Lock() defer db.dbLock.Unlock() - var endidx int64 + var endidx int32 if endHeight == database.AllShas { endidx = startHeight + 500 } else { @@ -251,7 +251,7 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []wi for height := startHeight; height < endidx; height++ { // TODO(drahn) fix blkFile from height - key := int64ToKey(height) + key := int64ToKey(int64(height)) blkVal, lerr := db.lDb.Get(key, db.ro) if lerr != nil { break @@ -273,7 +273,7 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []wi // NewestSha returns the hash and block height of the most recent (end) block of // the block chain. It will return the zero hash, -1 for the block height, and // no error (nil) if there are not any blocks in the database yet. -func (db *LevelDb) NewestSha() (rsha *wire.ShaHash, rblkid int64, err error) { +func (db *LevelDb) NewestSha() (rsha *wire.ShaHash, rblkid int32, err error) { db.dbLock.Lock() defer db.dbLock.Unlock() @@ -312,7 +312,7 @@ func (db *LevelDb) checkAddrIndexVersion() error { // updated accordingly by functions that modify the state. This function is // used on start up to load the info into memory. Callers will use the public // version of this function below, which returns our cached copy. -func (db *LevelDb) fetchAddrIndexTip() (*wire.ShaHash, int64, error) { +func (db *LevelDb) fetchAddrIndexTip() (*wire.ShaHash, int32, error) { db.dbLock.Lock() defer db.dbLock.Unlock() @@ -326,14 +326,14 @@ func (db *LevelDb) fetchAddrIndexTip() (*wire.ShaHash, int64, error) { blkHeight := binary.LittleEndian.Uint64(data[32:]) - return &blkSha, int64(blkHeight), nil + return &blkSha, int32(blkHeight), nil } // FetchAddrIndexTip returns the hash and block height of the most recent // block whose transactions have been indexed by address. It will return // ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the // addrindex hasn't yet been built up. -func (db *LevelDb) FetchAddrIndexTip() (*wire.ShaHash, int64, error) { +func (db *LevelDb) FetchAddrIndexTip() (*wire.ShaHash, int32, error) { db.dbLock.Lock() defer db.dbLock.Unlock() diff --git a/database/ldb/dup_test.go b/database/ldb/dup_test.go index 7bf6ab92..e797fa67 100644 --- a/database/ldb/dup_test.go +++ b/database/ldb/dup_test.go @@ -48,7 +48,7 @@ func Test_dupTx(t *testing.T) { // Populate with the fisrt 256 blocks, so we have blocks to 'mess with' err = nil out: - for height := int64(0); height < int64(len(blocks)); height++ { + for height := int32(0); height < int32(len(blocks)); height++ { block := blocks[height] // except for NoVerify which does not allow lookups check inputs diff --git a/database/ldb/insertremove_test.go b/database/ldb/insertremove_test.go index ea635b91..07c9144e 100644 --- a/database/ldb/insertremove_test.go +++ b/database/ldb/insertremove_test.go @@ -63,7 +63,7 @@ func testUnspentInsert(t *testing.T) { blocks := loadblocks(t) endtest: - for height := int64(0); height < int64(len(blocks)); height++ { + for height := int32(0); height < int32(len(blocks)); height++ { block := blocks[height] // look up inputs to this tx diff --git a/database/ldb/leveldb.go b/database/ldb/leveldb.go index 44d24005..01e1e763 100644 --- a/database/ldb/leveldb.go +++ b/database/ldb/leveldb.go @@ -29,7 +29,7 @@ var log = btclog.Disabled type tTxInsertData struct { txsha *wire.ShaHash - blockid int64 + blockid int32 txoff int txlen int usedbuf []byte @@ -47,14 +47,14 @@ type LevelDb struct { lbatch *leveldb.Batch - nextBlock int64 + nextBlock int32 lastBlkShaCached bool lastBlkSha wire.ShaHash - lastBlkIdx int64 + lastBlkIdx int32 lastAddrIndexBlkSha wire.ShaHash - lastAddrIndexBlkIdx int64 + lastAddrIndexBlkIdx int32 txUpdateMap map[wire.ShaHash]*txUpdateObj txSpentUpdateMap map[wire.ShaHash]*spentTxUpdate @@ -98,9 +98,9 @@ func OpenDB(args ...interface{}) (database.Db, error) { } // Need to find last block and tx - var lastknownblock, nextunknownblock, testblock int64 + var lastknownblock, nextunknownblock, testblock int32 - increment := int64(100000) + increment := int32(100000) ldb := db.(*LevelDb) var lastSha *wire.ShaHash @@ -345,7 +345,7 @@ func (db *LevelDb) DropAfterBlockBySha(sha *wire.ShaHash) (rerr error) { db.txUpdateMap[*tx.Sha()] = &txUo } db.lBatch().Delete(shaBlkToKey(blksha)) - db.lBatch().Delete(int64ToKey(height)) + db.lBatch().Delete(int64ToKey(int64(height))) } // update the last block cache @@ -361,7 +361,7 @@ func (db *LevelDb) DropAfterBlockBySha(sha *wire.ShaHash) (rerr error) { // database. The first block inserted into the database will be treated as the // genesis block. Every subsequent block insert requires the referenced parent // block to already exist. -func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int64, rerr error) { +func (db *LevelDb) InsertBlock(block *btcutil.Block) (height int32, rerr error) { db.dbLock.Lock() defer db.dbLock.Unlock() defer func() { diff --git a/database/ldb/operational_test.go b/database/ldb/operational_test.go index 6767dc57..8072a884 100644 --- a/database/ldb/operational_test.go +++ b/database/ldb/operational_test.go @@ -72,7 +72,7 @@ func TestOperational(t *testing.T) { // testAddrIndexOperations ensures that all normal operations concerning // the optional address index function correctly. -func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.Block, newestSha *wire.ShaHash, newestBlockIdx int64) { +func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil.Block, newestSha *wire.ShaHash, newestBlockIdx int32) { // Metadata about the current addr index state should be unset. sha, height, err := db.FetchAddrIndexTip() if err != database.ErrAddrIndexDoesNotExist { @@ -188,7 +188,7 @@ func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *btcutil. } -func assertAddrIndexTipIsUpdated(db database.Db, t *testing.T, newestSha *wire.ShaHash, newestBlockIdx int64) { +func assertAddrIndexTipIsUpdated(db database.Db, t *testing.T, newestSha *wire.ShaHash, newestBlockIdx int32) { // Safe to ignore error, since height will be < 0 in "error" case. sha, height, _ := db.FetchAddrIndexTip() if newestBlockIdx != height { @@ -215,7 +215,7 @@ func testOperationalMode(t *testing.T) { defer testDb.cleanUpFunc() err = nil out: - for height := int64(0); height < int64(len(testDb.blocks)); height++ { + for height := int32(0); height < int32(len(testDb.blocks)); height++ { block := testDb.blocks[height] mblock := block.MsgBlock() var txneededList []*wire.ShaHash @@ -306,7 +306,7 @@ func testBackout(t *testing.T) { } err = nil - for height := int64(0); height < int64(len(testDb.blocks)); height++ { + for height := int32(0); height < int32(len(testDb.blocks)); height++ { if height == 100 { t.Logf("Syncing at block height 100") testDb.db.Sync() @@ -417,7 +417,7 @@ func loadBlocks(t *testing.T, file string) (blocks []*btcutil.Block, err error) var block *btcutil.Block err = nil - for height := int64(1); err == nil; height++ { + for height := int32(1); err == nil; height++ { var rintbuf uint32 err = binary.Read(dr, binary.LittleEndian, &rintbuf) if err == io.EOF { @@ -456,18 +456,18 @@ func loadBlocks(t *testing.T, file string) (blocks []*btcutil.Block, err error) func testFetchHeightRange(t *testing.T, db database.Db, blocks []*btcutil.Block) { - var testincrement int64 = 50 - var testcnt int64 = 100 + var testincrement int32 = 50 + var testcnt int32 = 100 shanames := make([]*wire.ShaHash, len(blocks)) - nBlocks := int64(len(blocks)) + nBlocks := int32(len(blocks)) for i := range blocks { shanames[i] = blocks[i].Sha() } - for startheight := int64(0); startheight < nBlocks; startheight += testincrement { + for startheight := int32(0); startheight < nBlocks; startheight += testincrement { endheight := startheight + testcnt if endheight > nBlocks { @@ -480,20 +480,20 @@ func testFetchHeightRange(t *testing.T, db database.Db, blocks []*btcutil.Block) } if endheight == database.AllShas { - if int64(len(shalist)) != nBlocks-startheight { + if int32(len(shalist)) != nBlocks-startheight { t.Errorf("FetchHeightRange: expected A %v shas, got %v", nBlocks-startheight, len(shalist)) } } else { - if int64(len(shalist)) != testcnt { + if int32(len(shalist)) != testcnt { t.Errorf("FetchHeightRange: expected %v shas, got %v", testcnt, len(shalist)) } } for i := range shalist { - sha0 := *shanames[int64(i)+startheight] + sha0 := *shanames[int32(i)+startheight] sha1 := shalist[i] if sha0 != sha1 { - t.Errorf("FetchHeightRange: mismatch sha at %v requested range %v %v: %v %v ", int64(i)+startheight, startheight, endheight, sha0, sha1) + t.Errorf("FetchHeightRange: mismatch sha at %v requested range %v %v: %v %v ", int32(i)+startheight, startheight, endheight, sha0, sha1) } } } diff --git a/database/ldb/tx.go b/database/ldb/tx.go index b0f5586f..cf9e6243 100644 --- a/database/ldb/tx.go +++ b/database/ldb/tx.go @@ -46,7 +46,7 @@ var addrIndexVersionKey = []byte("addrindexversion") type txUpdateObj struct { txSha *wire.ShaHash - blkHeight int64 + blkHeight int32 txoff int txlen int ntxout int @@ -55,7 +55,7 @@ type txUpdateObj struct { } type spentTx struct { - blkHeight int64 + blkHeight int32 txoff int txlen int numTxO int @@ -68,13 +68,13 @@ type spentTxUpdate struct { type txAddrIndex struct { hash160 [ripemd160.Size]byte - blkHeight int64 + blkHeight int32 txoffset int txlen int } // InsertTx inserts a tx hash and its associated data into the database. -func (db *LevelDb) InsertTx(txsha *wire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) { +func (db *LevelDb) InsertTx(txsha *wire.ShaHash, height int32, txoff int, txlen int, spentbuf []byte) (err error) { db.dbLock.Lock() defer db.dbLock.Unlock() @@ -83,7 +83,7 @@ func (db *LevelDb) InsertTx(txsha *wire.ShaHash, height int64, txoff int, txlen // insertTx inserts a tx hash and its associated data into the database. // Must be called with db lock held. -func (db *LevelDb) insertTx(txSha *wire.ShaHash, height int64, txoff int, txlen int, spentbuf []byte) (err error) { +func (db *LevelDb) insertTx(txSha *wire.ShaHash, height int32, txoff int, txlen int, spentbuf []byte) (err error) { var txU txUpdateObj txU.txSha = txSha @@ -113,7 +113,7 @@ func (db *LevelDb) formatTx(txu *txUpdateObj) []byte { return txW[:] } -func (db *LevelDb) getTxData(txsha *wire.ShaHash) (int64, int, int, []byte, error) { +func (db *LevelDb) getTxData(txsha *wire.ShaHash) (int32, int, int, []byte, error) { key := shaTxToKey(txsha) buf, err := db.lDb.Get(key, db.ro) if err != nil { @@ -127,7 +127,7 @@ func (db *LevelDb) getTxData(txsha *wire.ShaHash) (int64, int, int, []byte, erro spentBuf := make([]byte, len(buf)-16) copy(spentBuf, buf[16:]) - return int64(blkHeight), int(txOff), int(txLen), spentBuf, nil + return int32(blkHeight), int(txOff), int(txLen), spentBuf, nil } func (db *LevelDb) getTxFullySpent(txsha *wire.ShaHash) ([]*spentTx, error) { @@ -153,7 +153,7 @@ func (db *LevelDb) getTxFullySpent(txsha *wire.ShaHash) ([]*spentTx, error) { numTxO := binary.LittleEndian.Uint32(buf[offset+16 : offset+20]) sTx := spentTx{ - blkHeight: int64(blkHeight), + blkHeight: int32(blkHeight), txoff: int(txOff), txlen: int(txLen), numTxO: int(numTxO), @@ -269,8 +269,8 @@ func (db *LevelDb) FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*databas } // fetchTxDataBySha returns several pieces of data regarding the given sha. -func (db *LevelDb) fetchTxDataBySha(txsha *wire.ShaHash) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int64, rtxspent []byte, err error) { - var blkHeight int64 +func (db *LevelDb) fetchTxDataBySha(txsha *wire.ShaHash) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int32, rtxspent []byte, err error) { + var blkHeight int32 var txspent []byte var txOff, txLen int @@ -286,7 +286,7 @@ func (db *LevelDb) fetchTxDataBySha(txsha *wire.ShaHash) (rtx *wire.MsgTx, rblks // fetchTxDataByLoc returns several pieces of data regarding the given tx // located by the block/offset/size location -func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspent []byte) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int64, rtxspent []byte, err error) { +func (db *LevelDb) fetchTxDataByLoc(blkHeight int32, txOff int, txLen int, txspent []byte) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int32, rtxspent []byte, err error) { var blksha *wire.ShaHash var blkbuf []byte @@ -401,7 +401,7 @@ func addrIndexToKey(index *txAddrIndex) []byte { // unpackTxIndex deserializes the raw bytes of a address tx index. func unpackTxIndex(rawIndex [12]byte) *txAddrIndex { return &txAddrIndex{ - blkHeight: int64(binary.BigEndian.Uint32(rawIndex[0:4])), + blkHeight: int32(binary.BigEndian.Uint32(rawIndex[0:4])), txoffset: int(binary.BigEndian.Uint32(rawIndex[4:8])), txlen: int(binary.BigEndian.Uint32(rawIndex[8:12])), } @@ -511,7 +511,7 @@ func (db *LevelDb) FetchTxsForAddr(addr btcutil.Address, skip int, // append-only list for the stored value. However, this add unnecessary // overhead when storing and retrieving since the entire list must // be fetched each time. -func (db *LevelDb) UpdateAddrIndexForBlock(blkSha *wire.ShaHash, blkHeight int64, addrIndex database.BlockAddrIndex) error { +func (db *LevelDb) UpdateAddrIndexForBlock(blkSha *wire.ShaHash, blkHeight int32, addrIndex database.BlockAddrIndex) error { db.dbLock.Lock() defer db.dbLock.Unlock() diff --git a/database/memdb/memdb.go b/database/memdb/memdb.go index 98deab29..25b86c9c 100644 --- a/database/memdb/memdb.go +++ b/database/memdb/memdb.go @@ -32,7 +32,7 @@ var ( // tTxInsertData holds information about the location and spent status of // a transaction. type tTxInsertData struct { - blockHeight int64 + blockHeight int32 offset int spentBuf []bool } @@ -86,7 +86,7 @@ type MemDb struct { // blocksBySha keeps track of block heights by hash. The height can // be used as an index into the blocks slice. - blocksBySha map[wire.ShaHash]int64 + blocksBySha map[wire.ShaHash]int32 // txns holds information about transactions such as which their // block height and spent status of all their outputs. @@ -177,7 +177,7 @@ func (db *MemDb) DropAfterBlockBySha(sha *wire.ShaHash) error { // backwards from the last block through the block just after the passed // block. While doing this unspend all transactions in each block and // remove the block. - endHeight := int64(len(db.blocks) - 1) + endHeight := int32(len(db.blocks) - 1) for i := endHeight; i > height; i-- { // Unspend and remove each transaction in reverse order because // later transactions in a block can reference earlier ones. @@ -237,7 +237,7 @@ func (db *MemDb) FetchBlockBySha(sha *wire.ShaHash) (*btcutil.Block, error) { // FetchBlockHeightBySha returns the block height for the given hash. This is // part of the database.Db interface implementation. -func (db *MemDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int64, error) { +func (db *MemDb) FetchBlockHeightBySha(sha *wire.ShaHash) (int32, error) { db.Lock() defer db.Unlock() @@ -275,7 +275,7 @@ func (db *MemDb) FetchBlockHeaderBySha(sha *wire.ShaHash) (*wire.BlockHeader, er // FetchBlockShaByHeight returns a block hash based on its height in the block // chain. This is part of the database.Db interface implementation. -func (db *MemDb) FetchBlockShaByHeight(height int64) (*wire.ShaHash, error) { +func (db *MemDb) FetchBlockShaByHeight(height int32) (*wire.ShaHash, error) { db.Lock() defer db.Unlock() @@ -283,7 +283,7 @@ func (db *MemDb) FetchBlockShaByHeight(height int64) (*wire.ShaHash, error) { return nil, ErrDbClosed } - numBlocks := int64(len(db.blocks)) + numBlocks := int32(len(db.blocks)) if height < 0 || height > numBlocks-1 { return nil, fmt.Errorf("unable to fetch block height %d since "+ "it is not within the valid range (%d-%d)", height, 0, @@ -299,7 +299,7 @@ func (db *MemDb) FetchBlockShaByHeight(height int64) (*wire.ShaHash, error) { // Fetch is inclusive of the start height and exclusive of the ending height. // To fetch all hashes from the start height until no more are present, use the // special id `AllShas'. This is part of the database.Db interface implementation. -func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]wire.ShaHash, error) { +func (db *MemDb) FetchHeightRange(startHeight, endHeight int32) ([]wire.ShaHash, error) { db.Lock() defer db.Unlock() @@ -310,7 +310,7 @@ func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]wire.ShaHash, // When the user passes the special AllShas id, adjust the end height // accordingly. if endHeight == database.AllShas { - endHeight = int64(len(db.blocks)) + endHeight = int32(len(db.blocks)) } // Ensure requested heights are sane. @@ -325,7 +325,7 @@ func (db *MemDb) FetchHeightRange(startHeight, endHeight int64) ([]wire.ShaHash, } // Fetch as many as are availalbe within the specified range. - lastBlockIndex := int64(len(db.blocks) - 1) + lastBlockIndex := int32(len(db.blocks) - 1) hashList := make([]wire.ShaHash, 0, endHeight-startHeight) for i := startHeight; i < endHeight; i++ { if i > lastBlockIndex { @@ -515,7 +515,7 @@ func (db *MemDb) FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*database. // genesis block. Every subsequent block insert requires the referenced parent // block to already exist. This is part of the database.Db interface // implementation. -func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) { +func (db *MemDb) InsertBlock(block *btcutil.Block) (int32, error) { db.Lock() defer db.Unlock() @@ -547,7 +547,7 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) { // Although these checks could could be done in the loop below, checking // for error conditions up front means the code below doesn't have to // deal with rollback on errors. - newHeight := int64(len(db.blocks)) + newHeight := int32(len(db.blocks)) for i, tx := range transactions { // Two old blocks contain duplicate transactions due to being // mined by faulty miners and accepted by the origin Satoshi @@ -656,7 +656,7 @@ func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) { // the block chain. It will return the zero hash, -1 for the block height, and // no error (nil) if there are not any blocks in the database yet. This is part // of the database.Db interface implementation. -func (db *MemDb) NewestSha() (*wire.ShaHash, int64, error) { +func (db *MemDb) NewestSha() (*wire.ShaHash, int32, error) { db.Lock() defer db.Unlock() @@ -672,18 +672,18 @@ func (db *MemDb) NewestSha() (*wire.ShaHash, int64, error) { } blockSha := db.blocks[numBlocks-1].BlockSha() - return &blockSha, int64(numBlocks - 1), nil + return &blockSha, int32(numBlocks - 1), nil } // FetchAddrIndexTip isn't currently implemented. This is a part of the // database.Db interface implementation. -func (db *MemDb) FetchAddrIndexTip() (*wire.ShaHash, int64, error) { +func (db *MemDb) FetchAddrIndexTip() (*wire.ShaHash, int32, error) { return nil, 0, database.ErrNotImplemented } // UpdateAddrIndexForBlock isn't currently implemented. This is a part of the // database.Db interface implementation. -func (db *MemDb) UpdateAddrIndexForBlock(*wire.ShaHash, int64, +func (db *MemDb) UpdateAddrIndexForBlock(*wire.ShaHash, int32, database.BlockAddrIndex) error { return database.ErrNotImplemented } @@ -737,7 +737,7 @@ func (db *MemDb) Sync() error { func newMemDb() *MemDb { db := MemDb{ blocks: make([]*wire.MsgBlock, 0, 200000), - blocksBySha: make(map[wire.ShaHash]int64), + blocksBySha: make(map[wire.ShaHash]int32), txns: make(map[wire.ShaHash][]*tTxInsertData), } return &db diff --git a/database/reorg_test.go b/database/reorg_test.go index be03fc96..9fc2e1b2 100644 --- a/database/reorg_test.go +++ b/database/reorg_test.go @@ -33,7 +33,7 @@ func testReorganization(t *testing.T, dbType string) { t.Fatalf("Error loading file: %v", err) } - for i := int64(0); i <= 2; i++ { + for i := int32(0); i <= 2; i++ { _, err = db.InsertBlock(blocks[i]) if err != nil { t.Fatalf("Error inserting block %d (%v): %v", i, @@ -45,7 +45,7 @@ func testReorganization(t *testing.T, dbType string) { } } - for i := int64(1); i >= 0; i-- { + for i := int32(1); i >= 0; i-- { blkHash := blocks[i].Sha() err = db.DropAfterBlockBySha(blkHash) if err != nil { @@ -63,7 +63,7 @@ func testReorganization(t *testing.T, dbType string) { } } - for i := int64(3); i < int64(len(blocks)); i++ { + for i := int32(3); i < int32(len(blocks)); i++ { blkHash := blocks[i].Sha() if err != nil { t.Fatalf("Error getting SHA for block %dA: %v", i-2, err) @@ -79,7 +79,7 @@ func testReorganization(t *testing.T, dbType string) { t.Fatalf("Error getting newest block info") } - for i := int64(0); i <= maxHeight; i++ { + for i := int32(0); i <= maxHeight; i++ { blkHash, err := db.FetchBlockShaByHeight(i) if err != nil { t.Fatalf("Error fetching SHA for block %d: %v", i, err) @@ -126,7 +126,7 @@ func loadReorgBlocks(filename string) ([]*btcutil.Block, error) { var block *btcutil.Block err = nil - for height := int64(1); err == nil; height++ { + for height := int32(1); err == nil; height++ { var rintbuf uint32 err = binary.Read(dr, binary.LittleEndian, &rintbuf) if err == io.EOF { diff --git a/mempool.go b/mempool.go index 360ff80f..ddbd66aa 100644 --- a/mempool.go +++ b/mempool.go @@ -81,7 +81,7 @@ const ( type TxDesc struct { Tx *btcutil.Tx // Transaction. Added time.Time // Time when added to pool. - Height int64 // Blockheight when added to pool. + Height int32 // Blockheight when added to pool. Fee int64 // Transaction fees. startingPriority float64 // Priority when added to the pool. } @@ -228,7 +228,7 @@ func checkPkScriptStandard(pkScript []byte, scriptClass txscript.ScriptClass) er // finalized, conforming to more stringent size constraints, having scripts // of recognized forms, and not containing "dust" outputs (those that are // so small it costs more to process them than they are worth). -func (mp *txMemPool) checkTransactionStandard(tx *btcutil.Tx, height int64) error { +func (mp *txMemPool) checkTransactionStandard(tx *btcutil.Tx, height int32) error { msgTx := tx.MsgTx() // The transaction must be a currently supported version. @@ -700,7 +700,7 @@ func (mp *txMemPool) RemoveDoubleSpends(tx *btcutil.Tx) { // helper for maybeAcceptTransaction. // // This function MUST be called with the mempool lock held (for writes). -func (mp *txMemPool) addTransaction(tx *btcutil.Tx, height, fee int64) { +func (mp *txMemPool) addTransaction(tx *btcutil.Tx, height int32, fee int64) { // Add the transaction to the pool and mark the referenced outpoints // as spent by the pool. mp.pool[*tx.Sha()] = &TxDesc{ @@ -794,7 +794,7 @@ func (mp *txMemPool) indexScriptAddressToTx(pkScript []byte, tx *btcutil.Tx) err // age is the sum of this value for each txin. Any inputs to the transaction // which are currently in the mempool and hence not mined into a block yet, // contribute no additional input age to the transaction. -func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeight int64) float64 { +func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeight int32) float64 { var totalInputAge float64 for _, txIn := range txDesc.Tx.MsgTx().TxIn { originHash := &txIn.PreviousOutPoint.Hash @@ -807,7 +807,7 @@ func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeig // have their block height set to a special constant. // Their input age should computed as zero since their // parent hasn't made it into a block yet. - var inputAge int64 + var inputAge int32 if txData.BlockHeight == mempoolHeight { inputAge = 0 } else { @@ -817,7 +817,7 @@ func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeig // Sum the input value times age. originTxOut := txData.Tx.MsgTx().TxOut[originIndex] inputValue := originTxOut.Value - totalInputAge += float64(inputValue * inputAge) + totalInputAge += float64(inputValue * int64(inputAge)) } } @@ -890,7 +890,7 @@ func (txD *TxDesc) StartingPriority(txStore blockchain.TxStore) float64 { // CurrentPriority calculates the current priority of this tx descriptor's // underlying transaction relative to the next block height. -func (txD *TxDesc) CurrentPriority(txStore blockchain.TxStore, nextBlockHeight int64) float64 { +func (txD *TxDesc) CurrentPriority(txStore blockchain.TxStore, nextBlockHeight int32) float64 { inputAge := calcInputValueAge(txD, txStore, nextBlockHeight) return calcPriority(txD.Tx, inputAge) } diff --git a/mining.go b/mining.go index 4af91138..40f6d85b 100644 --- a/mining.go +++ b/mining.go @@ -158,7 +158,7 @@ type BlockTemplate struct { block *wire.MsgBlock fees []int64 sigOpCounts []int64 - height int64 + height int32 validPayAddress bool } @@ -180,8 +180,8 @@ func mergeTxStore(txStoreA blockchain.TxStore, txStoreB blockchain.TxStore) { // signature script of the coinbase transaction of a new block. In particular, // it starts with the block height that is required by version 2 blocks and adds // the extra nonce as well as additional coinbase flags. -func standardCoinbaseScript(nextBlockHeight int64, extraNonce uint64) ([]byte, error) { - return txscript.NewScriptBuilder().AddInt64(nextBlockHeight). +func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) { + return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)). AddInt64(int64(extraNonce)).AddData([]byte(coinbaseFlags)). Script() } @@ -192,7 +192,7 @@ func standardCoinbaseScript(nextBlockHeight int64, extraNonce uint64) ([]byte, e // // See the comment for NewBlockTemplate for more information about why the nil // address handling is useful. -func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil.Address) (*btcutil.Tx, error) { +func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int32, addr btcutil.Address) (*btcutil.Tx, error) { // Create the script to pay to the provided payment address if one was // specified. Otherwise create a script that allows the coinbase to be // redeemable by anyone. @@ -232,7 +232,7 @@ func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil // spendTransaction updates the passed transaction store by marking the inputs // to the passed transaction as spent. It also adds the passed transaction to // the store at the provided height. -func spendTransaction(txStore blockchain.TxStore, tx *btcutil.Tx, height int64) error { +func spendTransaction(txStore blockchain.TxStore, tx *btcutil.Tx, height int32) error { for _, txIn := range tx.MsgTx().TxIn { originHash := &txIn.PreviousOutPoint.Hash originIndex := txIn.PreviousOutPoint.Index @@ -793,7 +793,7 @@ func UpdateBlockTime(msgBlock *wire.MsgBlock, bManager *blockManager) error { // block by regenerating the coinbase script with the passed value and block // height. It also recalculates and updates the new merkle root that results // from changing the coinbase script. -func UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int64, extraNonce uint64) error { +func UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error { coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) if err != nil { return err diff --git a/peer.go b/peer.go index ff430e0e..e35ca028 100644 --- a/peer.go +++ b/peer.go @@ -928,7 +928,7 @@ func (p *peer) handleGetBlocksMsg(msg *wire.MsgGetBlocks) { // provided locator are known. This does mean the client will start // over with the genesis block if unknown block locators are provided. // This mirrors the behavior in the reference implementation. - startIdx := int64(1) + startIdx := int32(1) for _, hash := range msg.BlockLocatorHashes { height, err := p.server.db.FetchBlockHeightBySha(hash) if err == nil { @@ -972,7 +972,7 @@ func (p *peer) handleGetBlocksMsg(msg *wire.MsgGetBlocks) { iv := wire.NewInvVect(wire.InvTypeBlock, &hashCopy) invMsg.AddInvVect(iv) } - start += int64(len(hashList)) + start += int32(len(hashList)) } // Send the inventory message if there is anything to send. @@ -1034,7 +1034,7 @@ func (p *peer) handleGetHeadersMsg(msg *wire.MsgGetHeaders) { // provided locator are known. This does mean the client will start // over with the genesis block if unknown block locators are provided. // This mirrors the behavior in the reference implementation. - startIdx := int64(1) + startIdx := int32(1) for _, hash := range msg.BlockLocatorHashes { height, err := p.server.db.FetchBlockHeightBySha(hash) if err == nil { @@ -1083,7 +1083,7 @@ func (p *peer) handleGetHeadersMsg(msg *wire.MsgGetHeaders) { // Start at the next block header after the latest one on the // next loop iteration. - start += int64(len(hashList)) + start += int32(len(hashList)) } p.QueueMessage(headersMsg, nil) } diff --git a/rpcserver.go b/rpcserver.go index 46a901a6..d095a0b3 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -676,7 +676,7 @@ func createVoutList(mtx *wire.MsgTx, chainParams *chaincfg.Params) []btcjson.Vou // to a raw transaction JSON object. func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx, txHash string, blkHeader *wire.BlockHeader, blkHash string, - blkHeight int64, chainHeight int64) (*btcjson.TxRawResult, error) { + blkHeight int32, chainHeight int32) (*btcjson.TxRawResult, error) { mtxHex, err := messageToHex(mtx) if err != nil { @@ -1013,7 +1013,7 @@ func handleGetBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i Nonce: blockHeader.Nonce, Time: blockHeader.Timestamp.Unix(), Confirmations: uint64(1 + maxIdx - idx), - Height: idx, + Height: int64(idx), Size: int32(len(buf)), Bits: strconv.FormatInt(int64(blockHeader.Bits), 16), Difficulty: getDifficultyRatio(blockHeader.Bits), @@ -1045,7 +1045,7 @@ func handleGetBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i // Get next block unless we are already at the top. if idx < maxIdx { var shaNext *wire.ShaHash - shaNext, err = s.server.db.FetchBlockShaByHeight(int64(idx + 1)) + shaNext, err = s.server.db.FetchBlockShaByHeight(idx + 1) if err != nil { context := "No next block" return nil, internalRPCError(err.Error(), context) @@ -1073,7 +1073,7 @@ func handleGetBlockCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{ // handleGetBlockHash implements the getblockhash command. func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { c := cmd.(*btcjson.GetBlockHashCmd) - sha, err := s.server.db.FetchBlockShaByHeight(c.Index) + sha, err := s.server.db.FetchBlockShaByHeight(int32(c.Index)) if err != nil { return nil, &btcjson.RPCError{ Code: btcjson.ErrRPCOutOfRange, @@ -1109,7 +1109,7 @@ func handleGetBlockHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct } var shaNextStr string - shaNext, err := s.server.db.FetchBlockShaByHeight(int64(blk.Height() + 1)) + shaNext, err := s.server.db.FetchBlockShaByHeight(blk.Height() + 1) if err == nil { shaNextStr = shaNext.String() } @@ -1510,7 +1510,7 @@ func (state *gbtWorkState) blockTemplateResult(useCoinbaseValue bool, submitOld reply := btcjson.GetBlockTemplateResult{ Bits: strconv.FormatInt(int64(header.Bits), 16), CurTime: header.Timestamp.Unix(), - Height: template.height, + Height: int64(template.height), PreviousHash: header.PrevBlock.String(), SigOpLimit: blockchain.MaxSigOpsPerBlock, SizeLimit: wire.MaxBlockPayload, @@ -2052,7 +2052,7 @@ func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{ } result := btcjson.GetMiningInfoResult{ - Blocks: height, + Blocks: int64(height), CurrentBlockSize: uint64(len(blockBytes)), CurrentBlockTx: uint64(len(block.MsgBlock().Transactions)), Difficulty: getDifficultyRatio(block.MsgBlock().Header.Bits), @@ -2095,9 +2095,9 @@ func handleGetNetworkHashPS(s *rpcServer, cmd interface{}, closeChan <-chan stru // since we can't reasonably calculate the number of network hashes // per second from invalid values. When it's negative, use the current // best block height. - endHeight := int64(-1) + endHeight := int32(-1) if c.Height != nil { - endHeight = int64(*c.Height) + endHeight = int32(*c.Height) } if endHeight > newestHeight || endHeight == 0 { return int64(0), nil @@ -2110,11 +2110,11 @@ func handleGetNetworkHashPS(s *rpcServer, cmd interface{}, closeChan <-chan stru // blocks. When the passed value is negative, use the last block the // difficulty changed as the starting height. Also make sure the // starting height is not before the beginning of the chain. - numBlocks := int64(120) + numBlocks := int32(120) if c.Blocks != nil { - numBlocks = int64(*c.Blocks) + numBlocks = int32(*c.Blocks) } - var startHeight int64 + var startHeight int32 if numBlocks <= 0 { startHeight = endHeight - ((endHeight % blockchain.BlocksPerRetarget) + 1) } else { @@ -2209,7 +2209,7 @@ func handleGetRawMempool(s *rpcServer, cmd interface{}, closeChan <-chan struct{ Size: int32(desc.Tx.MsgTx().SerializeSize()), Fee: btcutil.Amount(desc.Fee).ToBTC(), Time: desc.Added.Unix(), - Height: desc.Height, + Height: int64(desc.Height), StartingPriority: startingPriority, CurrentPriority: currentPriority, Depends: make([]string, 0), @@ -2252,7 +2252,7 @@ func handleGetRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan str // try the block database. var mtx *wire.MsgTx var blkHash *wire.ShaHash - var blkHeight int64 + var blkHeight int32 tx, err := s.server.txMemPool.FetchTransaction(txHash) if err != nil { txList, err := s.server.db.FetchTxBySha(txHash) @@ -2287,7 +2287,7 @@ func handleGetRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan str var blkHeader *wire.BlockHeader var blkHashStr string - var chainHeight int64 + var chainHeight int32 if blkHash != nil { blkHeader, err = s.server.db.FetchBlockHeaderBySha(blkHash) if err != nil { @@ -2364,7 +2364,7 @@ func handleGetTxOut(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i // from there, otherwise attempt to fetch from the block database. var mtx *wire.MsgTx var bestBlockSha string - var confirmations int64 + var confirmations int32 var dbSpentInfo []bool includeMempool := true if c.IncludeMempool != nil { @@ -2450,7 +2450,7 @@ func handleGetTxOut(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i txOutReply := &btcjson.GetTxOutResult{ BestBlock: bestBlockSha, - Confirmations: confirmations, + Confirmations: int64(confirmations), Value: btcutil.Amount(txOut.Value).ToUnit(btcutil.AmountBTC), Version: mtx.Version, ScriptPubKey: btcjson.ScriptPubKeyResult{ @@ -2946,7 +2946,7 @@ func handleSearchRawTransactions(s *rpcServer, cmd interface{}, closeChan <-chan // final JSON output (mempool won't have confirmations). var blkHeader *wire.BlockHeader var blkHashStr string - var blkHeight int64 + var blkHeight int32 if txReply.BlkSha != nil { blkHeader, err = s.server.db.FetchBlockHeaderBySha(txReply.BlkSha) if err != nil { @@ -3128,7 +3128,7 @@ func verifyChain(db database.Db, level, depth int32, timeSource blockchain.Media for height := curHeight; height > finishHeight; height-- { // Level 0 just looks up the block. - sha, err := db.FetchBlockShaByHeight(int64(height)) + sha, err := db.FetchBlockShaByHeight(height) if err != nil { rpcsLog.Errorf("Verify is unable to fetch block at "+ "height %d: %v", height, err) diff --git a/rpcwebsocket.go b/rpcwebsocket.go index 3c1781fc..725314c7 100644 --- a/rpcwebsocket.go +++ b/rpcwebsocket.go @@ -1759,7 +1759,7 @@ func rescanBlock(wsc *wsClient, lookups *rescanKeys, blk *btcutil.Block) { // verifies that the new range of blocks is on the same fork as a previous // range of blocks. If this condition does not hold true, the JSON-RPC error // for an unrecoverable reorganize is returned. -func recoverFromReorg(db database.Db, minBlock, maxBlock int64, +func recoverFromReorg(db database.Db, minBlock, maxBlock int32, lastBlock *wire.ShaHash) ([]wire.ShaHash, error) { hashList, err := db.FetchHeightRange(minBlock, maxBlock) @@ -2023,7 +2023,7 @@ fetchRange: // A goto is used to branch executation back to // before the range was evaluated, as it must be // reevaluated for the new hashList. - minBlock += int64(i) + minBlock += int32(i) hashList, err = recoverFromReorg(db, minBlock, maxBlock, lastBlockHash) if err != nil { @@ -2083,7 +2083,7 @@ fetchRange: } } - minBlock += int64(len(hashList)) + minBlock += int32(len(hashList)) } // Notify websocket client of the finished rescan. Due to how btcd