mirror of
https://github.com/LBRYFoundation/lbcd.git
synced 2025-08-23 17:47:24 +00:00
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.
This commit is contained in:
parent
27f7f82355
commit
0280fa0264
31 changed files with 177 additions and 177 deletions
|
@ -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
|
// The height of this block is one more than the referenced previous
|
||||||
// block.
|
// block.
|
||||||
blockHeight := int64(0)
|
blockHeight := int32(0)
|
||||||
if prevNode != nil {
|
if prevNode != nil {
|
||||||
blockHeight = prevNode.height + 1
|
blockHeight = prevNode.height + 1
|
||||||
}
|
}
|
||||||
|
|
|
@ -48,8 +48,8 @@ func (b *BlockChain) BlockLocatorFromHash(hash *wire.ShaHash) BlockLocator {
|
||||||
// Attempt to find the height of the block that corresponds to the
|
// 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
|
// passed hash, and if it's on a side chain, also find the height at
|
||||||
// which it forks from the main chain.
|
// which it forks from the main chain.
|
||||||
blockHeight := int64(-1)
|
blockHeight := int32(-1)
|
||||||
forkHeight := int64(-1)
|
forkHeight := int32(-1)
|
||||||
node, exists := b.index[*hash]
|
node, exists := b.index[*hash]
|
||||||
if !exists {
|
if !exists {
|
||||||
// Try to look up the height for passed block hash. Assume an
|
// 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
|
// in the BlockLocator comment and make sure to leave room for the
|
||||||
// final genesis hash.
|
// final genesis hash.
|
||||||
iterNode := node
|
iterNode := node
|
||||||
increment := int64(1)
|
increment := int32(1)
|
||||||
for len(locator) < wire.MaxBlockLocatorsPerMsg-1 {
|
for len(locator) < wire.MaxBlockLocatorsPerMsg-1 {
|
||||||
// Once there are 10 locators, exponentially increase the
|
// Once there are 10 locators, exponentially increase the
|
||||||
// distance between each block locator.
|
// distance between each block locator.
|
||||||
|
|
|
@ -58,7 +58,7 @@ type blockNode struct {
|
||||||
parentHash *wire.ShaHash
|
parentHash *wire.ShaHash
|
||||||
|
|
||||||
// height is the position in the block chain.
|
// 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
|
// workSum is the total amount of work in the chain up to and including
|
||||||
// this node.
|
// this node.
|
||||||
|
@ -79,7 +79,7 @@ type blockNode struct {
|
||||||
// completely disconnected from the chain and the workSum value is just the work
|
// 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
|
// for the passed block. The work sum is updated accordingly when the node is
|
||||||
// inserted into a chain.
|
// 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
|
// 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
|
// of the full block/block header preventing it from being garbage
|
||||||
// collected.
|
// collected.
|
||||||
|
@ -144,7 +144,7 @@ func removeChildNode(children []*blockNode, node *blockNode) []*blockNode {
|
||||||
type BlockChain struct {
|
type BlockChain struct {
|
||||||
db database.Db
|
db database.Db
|
||||||
chainParams *chaincfg.Params
|
chainParams *chaincfg.Params
|
||||||
checkpointsByHeight map[int64]*chaincfg.Checkpoint
|
checkpointsByHeight map[int32]*chaincfg.Checkpoint
|
||||||
notifications NotificationCallback
|
notifications NotificationCallback
|
||||||
root *blockNode
|
root *blockNode
|
||||||
bestChain *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
|
// Start at the next block after the latest one on the next loop
|
||||||
// iteration.
|
// iteration.
|
||||||
start += int64(len(hashList))
|
start += int32(len(hashList))
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
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
|
// the latter loads the node and the goal is to find nodes still in
|
||||||
// memory that can be pruned.
|
// memory that can be pruned.
|
||||||
newRootNode := b.bestChain
|
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
|
newRootNode = newRootNode.parent
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1069,9 +1069,9 @@ func (b *BlockChain) IsCurrent(timeSource MedianTimeSource) bool {
|
||||||
// interested in receiving notifications.
|
// interested in receiving notifications.
|
||||||
func New(db database.Db, params *chaincfg.Params, c NotificationCallback) *BlockChain {
|
func New(db database.Db, params *chaincfg.Params, c NotificationCallback) *BlockChain {
|
||||||
// Generate a checkpoint by height map from the provided checkpoints.
|
// 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 {
|
if len(params.Checkpoints) > 0 {
|
||||||
checkpointsByHeight = make(map[int64]*chaincfg.Checkpoint)
|
checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint)
|
||||||
for i := range params.Checkpoints {
|
for i := range params.Checkpoints {
|
||||||
checkpoint := ¶ms.Checkpoints[i]
|
checkpoint := ¶ms.Checkpoints[i]
|
||||||
checkpointsByHeight[checkpoint.Height] = checkpoint
|
checkpointsByHeight[checkpoint.Height] = checkpoint
|
||||||
|
|
|
@ -59,7 +59,7 @@ func (b *BlockChain) LatestCheckpoint() *chaincfg.Checkpoint {
|
||||||
// verifyCheckpoint returns whether the passed block height and hash combination
|
// verifyCheckpoint returns whether the passed block height and hash combination
|
||||||
// match the hard-coded checkpoint data. It also returns true if there is no
|
// match the hard-coded checkpoint data. It also returns true if there is no
|
||||||
// checkpoint data for the passed block height.
|
// 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 {
|
if b.noCheckpoints || len(b.chainParams.Checkpoints) == 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
|
@ -184,7 +184,7 @@ func loadTxStore(filename string) (blockchain.TxStore, error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
txD.BlockHeight = int64(uintBuf)
|
txD.BlockHeight = int32(uintBuf)
|
||||||
|
|
||||||
// Num spent bits.
|
// Num spent bits.
|
||||||
err = binary.Read(r, binary.LittleEndian, &uintBuf)
|
err = binary.Read(r, binary.LittleEndian, &uintBuf)
|
||||||
|
|
|
@ -25,7 +25,7 @@ const (
|
||||||
// BlocksPerRetarget is the number of blocks between each difficulty
|
// BlocksPerRetarget is the number of blocks between each difficulty
|
||||||
// retarget. It is calculated based on the desired block generation
|
// retarget. It is calculated based on the desired block generation
|
||||||
// rate.
|
// rate.
|
||||||
BlocksPerRetarget = int64(targetTimespan / targetSpacing)
|
BlocksPerRetarget = int32(targetTimespan / targetSpacing)
|
||||||
|
|
||||||
// retargetAdjustmentFactor is the adjustment factor used to limit
|
// retargetAdjustmentFactor is the adjustment factor used to limit
|
||||||
// the minimum and maximum amount of adjustment that can occur between
|
// 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
|
// Get the block node at the previous retarget (targetTimespan days
|
||||||
// worth of blocks).
|
// worth of blocks).
|
||||||
firstNode := lastNode
|
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
|
// Get the previous block node. This function is used over
|
||||||
// simply accessing firstNode.parent directly as it will
|
// simply accessing firstNode.parent directly as it will
|
||||||
// dynamically create previous block nodes as needed. This
|
// dynamically create previous block nodes as needed. This
|
||||||
|
|
|
@ -19,7 +19,7 @@ import (
|
||||||
|
|
||||||
// TstSetCoinbaseMaturity makes the ability to set the coinbase maturity
|
// TstSetCoinbaseMaturity makes the ability to set the coinbase maturity
|
||||||
// available to the test package.
|
// available to the test package.
|
||||||
func TstSetCoinbaseMaturity(maturity int64) {
|
func TstSetCoinbaseMaturity(maturity int32) {
|
||||||
coinbaseMaturity = maturity
|
coinbaseMaturity = maturity
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -17,7 +17,7 @@ import (
|
||||||
type TxData struct {
|
type TxData struct {
|
||||||
Tx *btcutil.Tx
|
Tx *btcutil.Tx
|
||||||
Hash *wire.ShaHash
|
Hash *wire.ShaHash
|
||||||
BlockHeight int64
|
BlockHeight int32
|
||||||
Spent []bool
|
Spent []bool
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,7 +55,7 @@ var (
|
||||||
// coinbaseMaturity is the internal variable used for validating the
|
// coinbaseMaturity is the internal variable used for validating the
|
||||||
// spending of coinbase outputs. A variable rather than the exported
|
// spending of coinbase outputs. A variable rather than the exported
|
||||||
// constant is used because the tests need the ability to modify it.
|
// 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
|
// 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
|
// 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.
|
// 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()
|
msgTx := tx.MsgTx()
|
||||||
|
|
||||||
// Lock time of zero means the transaction is finalized.
|
// 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.
|
// threshold it is a block height.
|
||||||
blockTimeOrHeight := int64(0)
|
blockTimeOrHeight := int64(0)
|
||||||
if lockTime < txscript.LockTimeThreshold {
|
if lockTime < txscript.LockTimeThreshold {
|
||||||
blockTimeOrHeight = blockHeight
|
blockTimeOrHeight = int64(blockHeight)
|
||||||
} else {
|
} else {
|
||||||
blockTimeOrHeight = blockTime.Unix()
|
blockTimeOrHeight = blockTime.Unix()
|
||||||
}
|
}
|
||||||
|
@ -187,13 +187,13 @@ func isBIP0030Node(node *blockNode) bool {
|
||||||
//
|
//
|
||||||
// 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 int64, chainParams *chaincfg.Params) int64 {
|
func CalcBlockSubsidy(height int32, chainParams *chaincfg.Params) int64 {
|
||||||
if chainParams.SubsidyHalvingInterval == 0 {
|
if chainParams.SubsidyHalvingInterval == 0 {
|
||||||
return baseSubsidy
|
return baseSubsidy
|
||||||
}
|
}
|
||||||
|
|
||||||
// Equivalent to: baseSubsidy / 2^(height/subsidyHalvingInterval)
|
// 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
|
// 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
|
// ExtractCoinbaseHeight attempts to extract the height of the block from the
|
||||||
// scriptSig of a coinbase transaction. Coinbase heights are only present in
|
// scriptSig of a coinbase transaction. Coinbase heights are only present in
|
||||||
// blocks of version 2 or later. This was added as part of BIP0034.
|
// 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
|
sigScript := coinbaseTx.MsgTx().TxIn[0].SignatureScript
|
||||||
if len(sigScript) < 1 {
|
if len(sigScript) < 1 {
|
||||||
str := "the coinbase signature script for blocks of " +
|
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])
|
copy(serializedHeightBytes, sigScript[1:serializedLen+1])
|
||||||
serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
|
serializedHeight := binary.LittleEndian.Uint64(serializedHeightBytes)
|
||||||
|
|
||||||
return int64(serializedHeight), nil
|
return int32(serializedHeight), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkSerializedHeight checks if the signature script in the passed
|
// checkSerializedHeight checks if the signature script in the passed
|
||||||
// transaction starts with the serialized block height of wantHeight.
|
// 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)
|
serializedHeight, err := ExtractCoinbaseHeight(coinbaseTx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
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
|
// 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,
|
// 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.
|
// 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.
|
// Coinbase transactions have no inputs.
|
||||||
if IsCoinBase(tx) {
|
if IsCoinBase(tx) {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
|
|
|
@ -82,7 +82,7 @@ func TestCheckSerializedHeight(t *testing.T) {
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
sigScript []byte // Serialized data
|
sigScript []byte // Serialized data
|
||||||
wantHeight int64 // Expected height
|
wantHeight int32 // Expected height
|
||||||
err error // Expected error type
|
err error // Expected error type
|
||||||
}{
|
}{
|
||||||
// No serialized height length.
|
// No serialized height length.
|
||||||
|
|
|
@ -150,7 +150,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 int64
|
height int32
|
||||||
sha *wire.ShaHash
|
sha *wire.ShaHash
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -163,7 +163,7 @@ type headerNode struct {
|
||||||
type chainState struct {
|
type chainState struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
newestHash *wire.ShaHash
|
newestHash *wire.ShaHash
|
||||||
newestHeight int64
|
newestHeight int32
|
||||||
pastMedianTime time.Time
|
pastMedianTime time.Time
|
||||||
pastMedianTimeErr error
|
pastMedianTimeErr error
|
||||||
}
|
}
|
||||||
|
@ -172,7 +172,7 @@ type chainState struct {
|
||||||
// chain.
|
// chain.
|
||||||
//
|
//
|
||||||
// This function is safe for concurrent access.
|
// This function is safe for concurrent access.
|
||||||
func (c *chainState) Best() (*wire.ShaHash, int64) {
|
func (c *chainState) Best() (*wire.ShaHash, int32) {
|
||||||
c.Lock()
|
c.Lock()
|
||||||
defer c.Unlock()
|
defer c.Unlock()
|
||||||
|
|
||||||
|
@ -207,7 +207,7 @@ type blockManager 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 (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight int64) {
|
func (b *blockManager) resetHeaderState(newestHash *wire.ShaHash, newestHeight int32) {
|
||||||
b.headersFirstMode = false
|
b.headersFirstMode = false
|
||||||
b.headerList.Init()
|
b.headerList.Init()
|
||||||
b.startHeader = nil
|
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
|
// This allows fast access to chain information since btcchain is currently not
|
||||||
// safe for concurrent access and the block manager is typically quite busy
|
// safe for concurrent access and the block manager is typically quite busy
|
||||||
// processing block and inventory.
|
// 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()
|
b.chainState.Lock()
|
||||||
defer b.chainState.Unlock()
|
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
|
// 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 (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
|
// There is no next checkpoint if checkpoints are disabled or there are
|
||||||
// none for this current network.
|
// none for this current network.
|
||||||
if cfg.DisableCheckpoints {
|
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
|
// 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
|
// parse an orphan, which would allow us to update the height of peers
|
||||||
// from what it was at initial handshake.
|
// 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 false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
|
|
|
@ -44,7 +44,7 @@ var (
|
||||||
// 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 int64
|
Height int32
|
||||||
Hash *wire.ShaHash
|
Hash *wire.ShaHash
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -69,8 +69,8 @@ type addrIndexer struct {
|
||||||
addrIndexJobs chan *indexBlockMsg
|
addrIndexJobs chan *indexBlockMsg
|
||||||
writeRequests chan *writeIndexReq
|
writeRequests chan *writeIndexReq
|
||||||
progressLogger *blockProgressLogger
|
progressLogger *blockProgressLogger
|
||||||
currentIndexTip int64
|
currentIndexTip int32
|
||||||
chainTip int64
|
chainTip int32
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -167,7 +167,7 @@ var errBadShaPrefix = errors.New("invalid prefix")
|
||||||
var errBadShaLen = errors.New("invalid len")
|
var errBadShaLen = errors.New("invalid len")
|
||||||
var errBadShaChar = errors.New("invalid character")
|
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 sha wire.ShaHash
|
||||||
|
|
||||||
var hashbuf string
|
var hashbuf string
|
||||||
|
@ -189,7 +189,7 @@ func parsesha(argstr string) (argtype int, height int64, psha *wire.ShaHash, err
|
||||||
var h int
|
var h int
|
||||||
h, err = strconv.Atoi(argstr)
|
h, err = strconv.Atoi(argstr)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
height = int64(h)
|
height = int32(h)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Infof("Unable to parse height %v, err %v", height, err)
|
log.Infof("Unable to parse height %v, err %v", height, err)
|
||||||
|
|
|
@ -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
|
// The latest known block must be at least the last known checkpoint
|
||||||
// plus required checkpoint confirmations.
|
// plus required checkpoint confirmations.
|
||||||
checkpointConfirmations := int64(blockchain.CheckpointConfirmations)
|
checkpointConfirmations := int32(blockchain.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 "+
|
||||||
|
@ -79,7 +79,7 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check
|
||||||
|
|
||||||
// Loop backwards through the chain to find checkpoint candidates.
|
// Loop backwards through the chain to find checkpoint candidates.
|
||||||
candidates := make([]*chaincfg.Checkpoint, 0, cfg.NumCandidates)
|
candidates := make([]*chaincfg.Checkpoint, 0, cfg.NumCandidates)
|
||||||
numTested := int64(0)
|
numTested := int32(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 {
|
||||||
|
|
|
@ -165,7 +165,7 @@ func (m *CPUMiner) submitBlock(block *btcutil.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 int64,
|
func (m *CPUMiner) solveBlock(msgBlock *wire.MsgBlock, blockHeight int32,
|
||||||
ticker *time.Ticker, quit chan struct{}) bool {
|
ticker *time.Ticker, quit chan struct{}) bool {
|
||||||
|
|
||||||
// Choose a random extra nonce offset for this block template and
|
// Choose a random extra nonce offset for this block template and
|
||||||
|
|
|
@ -28,7 +28,7 @@ var (
|
||||||
|
|
||||||
// AllShas is a special value that can be used as the final sha when requesting
|
// 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.
|
// 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
|
// 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
|
// 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)
|
FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error)
|
||||||
|
|
||||||
// FetchBlockHeightBySha returns the block height for the given hash.
|
// 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
|
// FetchBlockHeaderBySha returns a wire.BlockHeader for the given
|
||||||
// sha. The implementation may cache the underlying data if desired.
|
// 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
|
// FetchBlockShaByHeight returns a block hash based on its height in the
|
||||||
// block chain.
|
// 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
|
// FetchHeightRange looks up a range of blocks by the start and ending
|
||||||
// heights. Fetch is inclusive of the start height and exclusive of the
|
// heights. Fetch is inclusive of the start height and exclusive of the
|
||||||
// ending height. To fetch all hashes from the start height until no
|
// ending height. To fetch all hashes from the start height until no
|
||||||
// more are present, use the special id `AllShas'.
|
// 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
|
// ExistsTxSha returns whether or not the given tx hash is present in
|
||||||
// the database
|
// the database
|
||||||
|
@ -103,19 +103,19 @@ type Db interface {
|
||||||
// into the database. The first block inserted into the database
|
// into the database. The first block inserted into the database
|
||||||
// will be treated as the genesis block. Every subsequent block insert
|
// will be treated as the genesis block. Every subsequent block insert
|
||||||
// requires the referenced parent block to already exist.
|
// 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)
|
// 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
|
// 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 block height, and no error (nil) if there are not any blocks in
|
||||||
// the database yet.
|
// 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
|
// FetchAddrIndexTip returns the hash and block height of the most recent
|
||||||
// block which has had its address index populated. It will return
|
// block which has had its address index populated. It will return
|
||||||
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
|
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
|
||||||
// addrindex hasn't yet been built up.
|
// 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
|
// UpdateAddrIndexForBlock updates the stored addrindex with passed
|
||||||
// index information for a particular block height. Additionally, it
|
// index information for a particular block height. Additionally, it
|
||||||
|
@ -124,7 +124,7 @@ type Db interface {
|
||||||
// transaction which is commited before the function returns.
|
// transaction which is commited before the function returns.
|
||||||
// Addresses are indexed by the raw bytes of their base58 decoded
|
// Addresses are indexed by the raw bytes of their base58 decoded
|
||||||
// hash160.
|
// hash160.
|
||||||
UpdateAddrIndexForBlock(blkSha *wire.ShaHash, height int64,
|
UpdateAddrIndexForBlock(blkSha *wire.ShaHash, height int32,
|
||||||
addrIndex BlockAddrIndex) error
|
addrIndex BlockAddrIndex) error
|
||||||
|
|
||||||
// FetchTxsForAddr looks up and returns all transactions which either
|
// FetchTxsForAddr looks up and returns all transactions which either
|
||||||
|
@ -162,7 +162,7 @@ type TxListReply struct {
|
||||||
Sha *wire.ShaHash
|
Sha *wire.ShaHash
|
||||||
Tx *wire.MsgTx
|
Tx *wire.MsgTx
|
||||||
BlkSha *wire.ShaHash
|
BlkSha *wire.ShaHash
|
||||||
Height int64
|
Height int32
|
||||||
TxSpent []bool
|
TxSpent []bool
|
||||||
Err error
|
Err error
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,7 +26,7 @@ type testContext struct {
|
||||||
t *testing.T
|
t *testing.T
|
||||||
dbType string
|
dbType string
|
||||||
db database.Db
|
db database.Db
|
||||||
blockHeight int64
|
blockHeight int32
|
||||||
blockHash *wire.ShaHash
|
blockHash *wire.ShaHash
|
||||||
block *btcutil.Block
|
block *btcutil.Block
|
||||||
useSpends bool
|
useSpends bool
|
||||||
|
@ -213,7 +213,7 @@ func testFetchBlockShaByHeight(tc *testContext) bool {
|
||||||
|
|
||||||
func testFetchBlockShaByHeightErrors(tc *testContext) bool {
|
func testFetchBlockShaByHeightErrors(tc *testContext) bool {
|
||||||
// Invalid heights must error and return a nil hash.
|
// 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 {
|
for i, wantHeight := range tests {
|
||||||
hashFromDb, err := tc.db.FetchBlockShaByHeight(wantHeight)
|
hashFromDb, err := tc.db.FetchBlockShaByHeight(wantHeight)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
@ -545,7 +545,7 @@ func testInterface(t *testing.T, dbType string) {
|
||||||
context := testContext{t: t, dbType: dbType, db: db}
|
context := testContext{t: t, dbType: dbType, db: db}
|
||||||
|
|
||||||
t.Logf("Loaded %d blocks for testing %s", len(blocks), dbType)
|
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
|
// Get the appropriate block and hash and update the test
|
||||||
// context accordingly.
|
// context accordingly.
|
||||||
block := blocks[height]
|
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
|
// Run the data integrity tests again after all blocks have been
|
||||||
// inserted to ensure the spend tracking is working properly.
|
// inserted to ensure the spend tracking is working properly.
|
||||||
context.useSpends = true
|
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
|
// Get the appropriate block and hash and update the
|
||||||
// test context accordingly.
|
// test context accordingly.
|
||||||
block := blocks[height]
|
block := blocks[height]
|
||||||
|
@ -613,14 +613,14 @@ func testInterface(t *testing.T, dbType string) {
|
||||||
- DropAfterBlockBySha(*wire.ShaHash) (err error)
|
- DropAfterBlockBySha(*wire.ShaHash) (err error)
|
||||||
x ExistsSha(sha *wire.ShaHash) (exists bool)
|
x ExistsSha(sha *wire.ShaHash) (exists bool)
|
||||||
x FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error)
|
x FetchBlockBySha(sha *wire.ShaHash) (blk *btcutil.Block, err error)
|
||||||
x FetchBlockShaByHeight(height int64) (sha *wire.ShaHash, err error)
|
x FetchBlockShaByHeight(height int32) (sha *wire.ShaHash, err error)
|
||||||
- FetchHeightRange(startHeight, endHeight int64) (rshalist []wire.ShaHash, err error)
|
- FetchHeightRange(startHeight, endHeight int32) (rshalist []wire.ShaHash, err error)
|
||||||
x ExistsTxSha(sha *wire.ShaHash) (exists bool)
|
x ExistsTxSha(sha *wire.ShaHash) (exists bool)
|
||||||
x FetchTxBySha(txsha *wire.ShaHash) ([]*TxListReply, error)
|
x FetchTxBySha(txsha *wire.ShaHash) ([]*TxListReply, error)
|
||||||
x FetchTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
|
x FetchTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
|
||||||
x FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
|
x FetchUnSpentTxByShaList(txShaList []*wire.ShaHash) []*TxListReply
|
||||||
x InsertBlock(block *btcutil.Block) (height int64, err error)
|
x InsertBlock(block *btcutil.Block) (height int32, err error)
|
||||||
x NewestSha() (sha *wire.ShaHash, height int64, err error)
|
x NewestSha() (sha *wire.ShaHash, height int32, err error)
|
||||||
- RollbackClose()
|
- RollbackClose()
|
||||||
- Sync()
|
- Sync()
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -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
|
// FetchBlockHeightBySha returns the block height for the given hash. This is
|
||||||
// part of the database.Db interface implementation.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
|
@ -71,7 +71,7 @@ func (db *LevelDb) FetchBlockHeaderBySha(sha *wire.ShaHash) (bh *wire.BlockHeade
|
||||||
return bh, err
|
return bh, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int64, error) {
|
func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int32, error) {
|
||||||
key := shaBlkToKey(sha)
|
key := shaBlkToKey(sha)
|
||||||
|
|
||||||
data, err := db.lDb.Get(key, db.ro)
|
data, err := db.lDb.Get(key, db.ro)
|
||||||
|
@ -85,13 +85,13 @@ func (db *LevelDb) getBlkLoc(sha *wire.ShaHash) (int64, error) {
|
||||||
// deserialize
|
// deserialize
|
||||||
blkHeight := binary.LittleEndian.Uint64(data)
|
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
|
var blkVal []byte
|
||||||
|
|
||||||
key := int64ToKey(blkHeight)
|
key := int64ToKey(int64(blkHeight))
|
||||||
|
|
||||||
blkVal, err = db.lDb.Get(key, db.ro)
|
blkVal, err = db.lDb.Get(key, db.ro)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -109,8 +109,8 @@ func (db *LevelDb) getBlkByHeight(blkHeight int64) (rsha *wire.ShaHash, rbuf []b
|
||||||
return &sha, blockdata, nil
|
return &sha, blockdata, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int64, rbuf []byte, err error) {
|
func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int32, rbuf []byte, err error) {
|
||||||
var blkHeight int64
|
var blkHeight int32
|
||||||
|
|
||||||
blkHeight, err = db.getBlkLoc(sha)
|
blkHeight, err = db.getBlkLoc(sha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -126,13 +126,13 @@ func (db *LevelDb) getBlk(sha *wire.ShaHash) (rblkHeight int64, rbuf []byte, err
|
||||||
return blkHeight, buf, nil
|
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
|
// serialize
|
||||||
var lw [8]byte
|
var lw [8]byte
|
||||||
binary.LittleEndian.PutUint64(lw[0:8], uint64(blkHeight))
|
binary.LittleEndian.PutUint64(lw[0:8], uint64(blkHeight))
|
||||||
|
|
||||||
shaKey := shaBlkToKey(sha)
|
shaKey := shaBlkToKey(sha)
|
||||||
blkKey := int64ToKey(blkHeight)
|
blkKey := int64ToKey(int64(blkHeight))
|
||||||
|
|
||||||
blkVal := make([]byte, len(sha)+len(buf))
|
blkVal := make([]byte, len(sha)+len(buf))
|
||||||
copy(blkVal[0:], sha[:])
|
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
|
// insertSha stores a block hash and its associated data block with a
|
||||||
// previous sha of `prevSha'.
|
// previous sha of `prevSha'.
|
||||||
// insertSha shall be called with db lock held
|
// 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)
|
oBlkHeight, err := db.getBlkLoc(prevSha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// check current block count
|
// 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.
|
// fetchSha returns the datablock for the given ShaHash.
|
||||||
func (db *LevelDb) fetchSha(sha *wire.ShaHash) (rbuf []byte,
|
func (db *LevelDb) fetchSha(sha *wire.ShaHash) (rbuf []byte,
|
||||||
rblkHeight int64, err error) {
|
rblkHeight int32, err error) {
|
||||||
var blkHeight int64
|
var blkHeight int32
|
||||||
var buf []byte
|
var buf []byte
|
||||||
|
|
||||||
blkHeight, buf, err = db.getBlk(sha)
|
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
|
// FetchBlockShaByHeight returns a block hash based on its height in the
|
||||||
// block chain.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
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
|
// fetchBlockShaByHeight returns a block hash based on its height in the
|
||||||
// block chain.
|
// block chain.
|
||||||
func (db *LevelDb) fetchBlockShaByHeight(height int64) (rsha *wire.ShaHash, err error) {
|
func (db *LevelDb) fetchBlockShaByHeight(height int32) (rsha *wire.ShaHash, err error) {
|
||||||
key := int64ToKey(height)
|
key := int64ToKey(int64(height))
|
||||||
|
|
||||||
blkVal, err := db.lDb.Get(key, db.ro)
|
blkVal, err := db.lDb.Get(key, db.ro)
|
||||||
if err != nil {
|
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
|
// heights. Fetch is inclusive of the start height and exclusive of the
|
||||||
// ending height. To fetch all hashes from the start height until no
|
// ending height. To fetch all hashes from the start height until no
|
||||||
// more are present, use the special id `AllShas'.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
var endidx int64
|
var endidx int32
|
||||||
if endHeight == database.AllShas {
|
if endHeight == database.AllShas {
|
||||||
endidx = startHeight + 500
|
endidx = startHeight + 500
|
||||||
} else {
|
} else {
|
||||||
|
@ -251,7 +251,7 @@ func (db *LevelDb) FetchHeightRange(startHeight, endHeight int64) (rshalist []wi
|
||||||
for height := startHeight; height < endidx; height++ {
|
for height := startHeight; height < endidx; height++ {
|
||||||
// TODO(drahn) fix blkFile from height
|
// TODO(drahn) fix blkFile from height
|
||||||
|
|
||||||
key := int64ToKey(height)
|
key := int64ToKey(int64(height))
|
||||||
blkVal, lerr := db.lDb.Get(key, db.ro)
|
blkVal, lerr := db.lDb.Get(key, db.ro)
|
||||||
if lerr != nil {
|
if lerr != nil {
|
||||||
break
|
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
|
// 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
|
// 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.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
|
@ -312,7 +312,7 @@ func (db *LevelDb) checkAddrIndexVersion() error {
|
||||||
// updated accordingly by functions that modify the state. This function is
|
// 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
|
// 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.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
|
@ -326,14 +326,14 @@ func (db *LevelDb) fetchAddrIndexTip() (*wire.ShaHash, int64, error) {
|
||||||
|
|
||||||
blkHeight := binary.LittleEndian.Uint64(data[32:])
|
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
|
// FetchAddrIndexTip returns the hash and block height of the most recent
|
||||||
// block whose transactions have been indexed by address. It will return
|
// block whose transactions have been indexed by address. It will return
|
||||||
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
|
// ErrAddrIndexDoesNotExist along with a zero hash, and -1 if the
|
||||||
// addrindex hasn't yet been built up.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
|
|
|
@ -48,7 +48,7 @@ func Test_dupTx(t *testing.T) {
|
||||||
// Populate with the fisrt 256 blocks, so we have blocks to 'mess with'
|
// Populate with the fisrt 256 blocks, so we have blocks to 'mess with'
|
||||||
err = nil
|
err = nil
|
||||||
out:
|
out:
|
||||||
for height := int64(0); height < int64(len(blocks)); height++ {
|
for height := int32(0); height < int32(len(blocks)); height++ {
|
||||||
block := blocks[height]
|
block := blocks[height]
|
||||||
|
|
||||||
// except for NoVerify which does not allow lookups check inputs
|
// except for NoVerify which does not allow lookups check inputs
|
||||||
|
|
|
@ -63,7 +63,7 @@ func testUnspentInsert(t *testing.T) {
|
||||||
|
|
||||||
blocks := loadblocks(t)
|
blocks := loadblocks(t)
|
||||||
endtest:
|
endtest:
|
||||||
for height := int64(0); height < int64(len(blocks)); height++ {
|
for height := int32(0); height < int32(len(blocks)); height++ {
|
||||||
|
|
||||||
block := blocks[height]
|
block := blocks[height]
|
||||||
// look up inputs to this tx
|
// look up inputs to this tx
|
||||||
|
|
|
@ -29,7 +29,7 @@ var log = btclog.Disabled
|
||||||
|
|
||||||
type tTxInsertData struct {
|
type tTxInsertData struct {
|
||||||
txsha *wire.ShaHash
|
txsha *wire.ShaHash
|
||||||
blockid int64
|
blockid int32
|
||||||
txoff int
|
txoff int
|
||||||
txlen int
|
txlen int
|
||||||
usedbuf []byte
|
usedbuf []byte
|
||||||
|
@ -47,14 +47,14 @@ type LevelDb struct {
|
||||||
|
|
||||||
lbatch *leveldb.Batch
|
lbatch *leveldb.Batch
|
||||||
|
|
||||||
nextBlock int64
|
nextBlock int32
|
||||||
|
|
||||||
lastBlkShaCached bool
|
lastBlkShaCached bool
|
||||||
lastBlkSha wire.ShaHash
|
lastBlkSha wire.ShaHash
|
||||||
lastBlkIdx int64
|
lastBlkIdx int32
|
||||||
|
|
||||||
lastAddrIndexBlkSha wire.ShaHash
|
lastAddrIndexBlkSha wire.ShaHash
|
||||||
lastAddrIndexBlkIdx int64
|
lastAddrIndexBlkIdx int32
|
||||||
|
|
||||||
txUpdateMap map[wire.ShaHash]*txUpdateObj
|
txUpdateMap map[wire.ShaHash]*txUpdateObj
|
||||||
txSpentUpdateMap map[wire.ShaHash]*spentTxUpdate
|
txSpentUpdateMap map[wire.ShaHash]*spentTxUpdate
|
||||||
|
@ -98,9 +98,9 @@ func OpenDB(args ...interface{}) (database.Db, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Need to find last block and tx
|
// 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)
|
ldb := db.(*LevelDb)
|
||||||
|
|
||||||
var lastSha *wire.ShaHash
|
var lastSha *wire.ShaHash
|
||||||
|
@ -345,7 +345,7 @@ func (db *LevelDb) DropAfterBlockBySha(sha *wire.ShaHash) (rerr error) {
|
||||||
db.txUpdateMap[*tx.Sha()] = &txUo
|
db.txUpdateMap[*tx.Sha()] = &txUo
|
||||||
}
|
}
|
||||||
db.lBatch().Delete(shaBlkToKey(blksha))
|
db.lBatch().Delete(shaBlkToKey(blksha))
|
||||||
db.lBatch().Delete(int64ToKey(height))
|
db.lBatch().Delete(int64ToKey(int64(height)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// update the last block cache
|
// 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
|
// database. The first block inserted into the database will be treated as the
|
||||||
// genesis block. Every subsequent block insert requires the referenced parent
|
// genesis block. Every subsequent block insert requires the referenced parent
|
||||||
// block to already exist.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|
|
@ -72,7 +72,7 @@ func TestOperational(t *testing.T) {
|
||||||
|
|
||||||
// testAddrIndexOperations ensures that all normal operations concerning
|
// testAddrIndexOperations ensures that all normal operations concerning
|
||||||
// the optional address index function correctly.
|
// 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.
|
// Metadata about the current addr index state should be unset.
|
||||||
sha, height, err := db.FetchAddrIndexTip()
|
sha, height, err := db.FetchAddrIndexTip()
|
||||||
if err != database.ErrAddrIndexDoesNotExist {
|
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.
|
// Safe to ignore error, since height will be < 0 in "error" case.
|
||||||
sha, height, _ := db.FetchAddrIndexTip()
|
sha, height, _ := db.FetchAddrIndexTip()
|
||||||
if newestBlockIdx != height {
|
if newestBlockIdx != height {
|
||||||
|
@ -215,7 +215,7 @@ func testOperationalMode(t *testing.T) {
|
||||||
defer testDb.cleanUpFunc()
|
defer testDb.cleanUpFunc()
|
||||||
err = nil
|
err = nil
|
||||||
out:
|
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]
|
block := testDb.blocks[height]
|
||||||
mblock := block.MsgBlock()
|
mblock := block.MsgBlock()
|
||||||
var txneededList []*wire.ShaHash
|
var txneededList []*wire.ShaHash
|
||||||
|
@ -306,7 +306,7 @@ func testBackout(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
err = nil
|
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 {
|
if height == 100 {
|
||||||
t.Logf("Syncing at block height 100")
|
t.Logf("Syncing at block height 100")
|
||||||
testDb.db.Sync()
|
testDb.db.Sync()
|
||||||
|
@ -417,7 +417,7 @@ func loadBlocks(t *testing.T, file string) (blocks []*btcutil.Block, err error)
|
||||||
|
|
||||||
var block *btcutil.Block
|
var block *btcutil.Block
|
||||||
err = nil
|
err = nil
|
||||||
for height := int64(1); err == nil; height++ {
|
for height := int32(1); 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 {
|
||||||
|
@ -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) {
|
func testFetchHeightRange(t *testing.T, db database.Db, blocks []*btcutil.Block) {
|
||||||
|
|
||||||
var testincrement int64 = 50
|
var testincrement int32 = 50
|
||||||
var testcnt int64 = 100
|
var testcnt int32 = 100
|
||||||
|
|
||||||
shanames := make([]*wire.ShaHash, len(blocks))
|
shanames := make([]*wire.ShaHash, len(blocks))
|
||||||
|
|
||||||
nBlocks := int64(len(blocks))
|
nBlocks := int32(len(blocks))
|
||||||
|
|
||||||
for i := range blocks {
|
for i := range blocks {
|
||||||
shanames[i] = blocks[i].Sha()
|
shanames[i] = blocks[i].Sha()
|
||||||
}
|
}
|
||||||
|
|
||||||
for startheight := int64(0); startheight < nBlocks; startheight += testincrement {
|
for startheight := int32(0); startheight < nBlocks; startheight += testincrement {
|
||||||
endheight := startheight + testcnt
|
endheight := startheight + testcnt
|
||||||
|
|
||||||
if endheight > nBlocks {
|
if endheight > nBlocks {
|
||||||
|
@ -480,20 +480,20 @@ func testFetchHeightRange(t *testing.T, db database.Db, blocks []*btcutil.Block)
|
||||||
}
|
}
|
||||||
|
|
||||||
if endheight == database.AllShas {
|
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))
|
t.Errorf("FetchHeightRange: expected A %v shas, got %v", nBlocks-startheight, len(shalist))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if int64(len(shalist)) != testcnt {
|
if int32(len(shalist)) != testcnt {
|
||||||
t.Errorf("FetchHeightRange: expected %v shas, got %v", testcnt, len(shalist))
|
t.Errorf("FetchHeightRange: expected %v shas, got %v", testcnt, len(shalist))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := range shalist {
|
for i := range shalist {
|
||||||
sha0 := *shanames[int64(i)+startheight]
|
sha0 := *shanames[int32(i)+startheight]
|
||||||
sha1 := shalist[i]
|
sha1 := shalist[i]
|
||||||
if sha0 != sha1 {
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,7 +46,7 @@ var addrIndexVersionKey = []byte("addrindexversion")
|
||||||
|
|
||||||
type txUpdateObj struct {
|
type txUpdateObj struct {
|
||||||
txSha *wire.ShaHash
|
txSha *wire.ShaHash
|
||||||
blkHeight int64
|
blkHeight int32
|
||||||
txoff int
|
txoff int
|
||||||
txlen int
|
txlen int
|
||||||
ntxout int
|
ntxout int
|
||||||
|
@ -55,7 +55,7 @@ type txUpdateObj struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type spentTx struct {
|
type spentTx struct {
|
||||||
blkHeight int64
|
blkHeight int32
|
||||||
txoff int
|
txoff int
|
||||||
txlen int
|
txlen int
|
||||||
numTxO int
|
numTxO int
|
||||||
|
@ -68,13 +68,13 @@ type spentTxUpdate struct {
|
||||||
|
|
||||||
type txAddrIndex struct {
|
type txAddrIndex struct {
|
||||||
hash160 [ripemd160.Size]byte
|
hash160 [ripemd160.Size]byte
|
||||||
blkHeight int64
|
blkHeight int32
|
||||||
txoffset int
|
txoffset int
|
||||||
txlen int
|
txlen int
|
||||||
}
|
}
|
||||||
|
|
||||||
// InsertTx inserts a tx hash and its associated data into the database.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
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.
|
// insertTx inserts a tx hash and its associated data into the database.
|
||||||
// Must be called with db lock held.
|
// 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
|
var txU txUpdateObj
|
||||||
|
|
||||||
txU.txSha = txSha
|
txU.txSha = txSha
|
||||||
|
@ -113,7 +113,7 @@ func (db *LevelDb) formatTx(txu *txUpdateObj) []byte {
|
||||||
return txW[:]
|
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)
|
key := shaTxToKey(txsha)
|
||||||
buf, err := db.lDb.Get(key, db.ro)
|
buf, err := db.lDb.Get(key, db.ro)
|
||||||
if err != nil {
|
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)
|
spentBuf := make([]byte, len(buf)-16)
|
||||||
copy(spentBuf, 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) {
|
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])
|
numTxO := binary.LittleEndian.Uint32(buf[offset+16 : offset+20])
|
||||||
|
|
||||||
sTx := spentTx{
|
sTx := spentTx{
|
||||||
blkHeight: int64(blkHeight),
|
blkHeight: int32(blkHeight),
|
||||||
txoff: int(txOff),
|
txoff: int(txOff),
|
||||||
txlen: int(txLen),
|
txlen: int(txLen),
|
||||||
numTxO: int(numTxO),
|
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.
|
// 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) {
|
func (db *LevelDb) fetchTxDataBySha(txsha *wire.ShaHash) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int32, rtxspent []byte, err error) {
|
||||||
var blkHeight int64
|
var blkHeight int32
|
||||||
var txspent []byte
|
var txspent []byte
|
||||||
var txOff, txLen int
|
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
|
// fetchTxDataByLoc returns several pieces of data regarding the given tx
|
||||||
// located by the block/offset/size location
|
// 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 blksha *wire.ShaHash
|
||||||
var blkbuf []byte
|
var blkbuf []byte
|
||||||
|
|
||||||
|
@ -401,7 +401,7 @@ func addrIndexToKey(index *txAddrIndex) []byte {
|
||||||
// unpackTxIndex deserializes the raw bytes of a address tx index.
|
// unpackTxIndex deserializes the raw bytes of a address tx index.
|
||||||
func unpackTxIndex(rawIndex [12]byte) *txAddrIndex {
|
func unpackTxIndex(rawIndex [12]byte) *txAddrIndex {
|
||||||
return &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])),
|
txoffset: int(binary.BigEndian.Uint32(rawIndex[4:8])),
|
||||||
txlen: int(binary.BigEndian.Uint32(rawIndex[8:12])),
|
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
|
// append-only list for the stored value. However, this add unnecessary
|
||||||
// overhead when storing and retrieving since the entire list must
|
// overhead when storing and retrieving since the entire list must
|
||||||
// be fetched each time.
|
// 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()
|
db.dbLock.Lock()
|
||||||
defer db.dbLock.Unlock()
|
defer db.dbLock.Unlock()
|
||||||
|
|
||||||
|
|
|
@ -32,7 +32,7 @@ var (
|
||||||
// tTxInsertData holds information about the location and spent status of
|
// tTxInsertData holds information about the location and spent status of
|
||||||
// a transaction.
|
// a transaction.
|
||||||
type tTxInsertData struct {
|
type tTxInsertData struct {
|
||||||
blockHeight int64
|
blockHeight int32
|
||||||
offset int
|
offset int
|
||||||
spentBuf []bool
|
spentBuf []bool
|
||||||
}
|
}
|
||||||
|
@ -86,7 +86,7 @@ type MemDb struct {
|
||||||
|
|
||||||
// blocksBySha keeps track of block heights by hash. The height can
|
// blocksBySha keeps track of block heights by hash. The height can
|
||||||
// be used as an index into the blocks slice.
|
// 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
|
// txns holds information about transactions such as which their
|
||||||
// block height and spent status of all their outputs.
|
// 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
|
// backwards from the last block through the block just after the passed
|
||||||
// block. While doing this unspend all transactions in each block and
|
// block. While doing this unspend all transactions in each block and
|
||||||
// remove the block.
|
// remove the block.
|
||||||
endHeight := int64(len(db.blocks) - 1)
|
endHeight := int32(len(db.blocks) - 1)
|
||||||
for i := endHeight; i > height; i-- {
|
for i := endHeight; i > height; i-- {
|
||||||
// Unspend and remove each transaction in reverse order because
|
// Unspend and remove each transaction in reverse order because
|
||||||
// later transactions in a block can reference earlier ones.
|
// 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
|
// FetchBlockHeightBySha returns the block height for the given hash. This is
|
||||||
// part of the database.Db interface implementation.
|
// 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()
|
db.Lock()
|
||||||
defer db.Unlock()
|
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
|
// FetchBlockShaByHeight returns a block hash based on its height in the block
|
||||||
// chain. This is part of the database.Db interface implementation.
|
// 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()
|
db.Lock()
|
||||||
defer db.Unlock()
|
defer db.Unlock()
|
||||||
|
|
||||||
|
@ -283,7 +283,7 @@ func (db *MemDb) FetchBlockShaByHeight(height int64) (*wire.ShaHash, error) {
|
||||||
return nil, ErrDbClosed
|
return nil, ErrDbClosed
|
||||||
}
|
}
|
||||||
|
|
||||||
numBlocks := int64(len(db.blocks))
|
numBlocks := int32(len(db.blocks))
|
||||||
if height < 0 || height > numBlocks-1 {
|
if height < 0 || height > numBlocks-1 {
|
||||||
return nil, fmt.Errorf("unable to fetch block height %d since "+
|
return nil, fmt.Errorf("unable to fetch block height %d since "+
|
||||||
"it is not within the valid range (%d-%d)", height, 0,
|
"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.
|
// 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
|
// 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.
|
// 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()
|
db.Lock()
|
||||||
defer db.Unlock()
|
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
|
// When the user passes the special AllShas id, adjust the end height
|
||||||
// accordingly.
|
// accordingly.
|
||||||
if endHeight == database.AllShas {
|
if endHeight == database.AllShas {
|
||||||
endHeight = int64(len(db.blocks))
|
endHeight = int32(len(db.blocks))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure requested heights are sane.
|
// 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.
|
// 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)
|
hashList := make([]wire.ShaHash, 0, endHeight-startHeight)
|
||||||
for i := startHeight; i < endHeight; i++ {
|
for i := startHeight; i < endHeight; i++ {
|
||||||
if i > lastBlockIndex {
|
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
|
// genesis block. Every subsequent block insert requires the referenced parent
|
||||||
// block to already exist. This is part of the database.Db interface
|
// block to already exist. This is part of the database.Db interface
|
||||||
// implementation.
|
// implementation.
|
||||||
func (db *MemDb) InsertBlock(block *btcutil.Block) (int64, error) {
|
func (db *MemDb) InsertBlock(block *btcutil.Block) (int32, error) {
|
||||||
db.Lock()
|
db.Lock()
|
||||||
defer db.Unlock()
|
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
|
// 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
|
// for error conditions up front means the code below doesn't have to
|
||||||
// deal with rollback on errors.
|
// deal with rollback on errors.
|
||||||
newHeight := int64(len(db.blocks))
|
newHeight := int32(len(db.blocks))
|
||||||
for i, tx := range transactions {
|
for i, tx := range transactions {
|
||||||
// Two old blocks contain duplicate transactions due to being
|
// Two old blocks contain duplicate transactions due to being
|
||||||
// mined by faulty miners and accepted by the origin Satoshi
|
// 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
|
// 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
|
// no error (nil) if there are not any blocks in the database yet. This is part
|
||||||
// of the database.Db interface implementation.
|
// of the database.Db interface implementation.
|
||||||
func (db *MemDb) NewestSha() (*wire.ShaHash, int64, error) {
|
func (db *MemDb) NewestSha() (*wire.ShaHash, int32, error) {
|
||||||
db.Lock()
|
db.Lock()
|
||||||
defer db.Unlock()
|
defer db.Unlock()
|
||||||
|
|
||||||
|
@ -672,18 +672,18 @@ func (db *MemDb) NewestSha() (*wire.ShaHash, int64, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
blockSha := db.blocks[numBlocks-1].BlockSha()
|
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
|
// FetchAddrIndexTip isn't currently implemented. This is a part of the
|
||||||
// database.Db interface implementation.
|
// 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
|
return nil, 0, database.ErrNotImplemented
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAddrIndexForBlock isn't currently implemented. This is a part of the
|
// UpdateAddrIndexForBlock isn't currently implemented. This is a part of the
|
||||||
// database.Db interface implementation.
|
// database.Db interface implementation.
|
||||||
func (db *MemDb) UpdateAddrIndexForBlock(*wire.ShaHash, int64,
|
func (db *MemDb) UpdateAddrIndexForBlock(*wire.ShaHash, int32,
|
||||||
database.BlockAddrIndex) error {
|
database.BlockAddrIndex) error {
|
||||||
return database.ErrNotImplemented
|
return database.ErrNotImplemented
|
||||||
}
|
}
|
||||||
|
@ -737,7 +737,7 @@ func (db *MemDb) Sync() error {
|
||||||
func newMemDb() *MemDb {
|
func newMemDb() *MemDb {
|
||||||
db := MemDb{
|
db := MemDb{
|
||||||
blocks: make([]*wire.MsgBlock, 0, 200000),
|
blocks: make([]*wire.MsgBlock, 0, 200000),
|
||||||
blocksBySha: make(map[wire.ShaHash]int64),
|
blocksBySha: make(map[wire.ShaHash]int32),
|
||||||
txns: make(map[wire.ShaHash][]*tTxInsertData),
|
txns: make(map[wire.ShaHash][]*tTxInsertData),
|
||||||
}
|
}
|
||||||
return &db
|
return &db
|
||||||
|
|
|
@ -33,7 +33,7 @@ func testReorganization(t *testing.T, dbType string) {
|
||||||
t.Fatalf("Error loading file: %v", err)
|
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])
|
_, err = db.InsertBlock(blocks[i])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error inserting block %d (%v): %v", i,
|
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()
|
blkHash := blocks[i].Sha()
|
||||||
err = db.DropAfterBlockBySha(blkHash)
|
err = db.DropAfterBlockBySha(blkHash)
|
||||||
if err != nil {
|
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()
|
blkHash := blocks[i].Sha()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error getting SHA for block %dA: %v", i-2, err)
|
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")
|
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)
|
blkHash, err := db.FetchBlockShaByHeight(i)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error fetching SHA for block %d: %v", i, err)
|
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
|
var block *btcutil.Block
|
||||||
|
|
||||||
err = nil
|
err = nil
|
||||||
for height := int64(1); err == nil; height++ {
|
for height := int32(1); 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 {
|
||||||
|
|
14
mempool.go
14
mempool.go
|
@ -81,7 +81,7 @@ const (
|
||||||
type TxDesc struct {
|
type TxDesc struct {
|
||||||
Tx *btcutil.Tx // Transaction.
|
Tx *btcutil.Tx // Transaction.
|
||||||
Added time.Time // Time when added to pool.
|
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.
|
Fee int64 // Transaction fees.
|
||||||
startingPriority float64 // Priority when added to the pool.
|
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
|
// 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 (mp *txMemPool) checkTransactionStandard(tx *btcutil.Tx, height int64) error {
|
func (mp *txMemPool) checkTransactionStandard(tx *btcutil.Tx, height int32) error {
|
||||||
msgTx := tx.MsgTx()
|
msgTx := tx.MsgTx()
|
||||||
|
|
||||||
// The transaction must be a currently supported version.
|
// The transaction must be a currently supported version.
|
||||||
|
@ -700,7 +700,7 @@ func (mp *txMemPool) RemoveDoubleSpends(tx *btcutil.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 *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
|
// Add the transaction to the pool and mark the referenced outpoints
|
||||||
// as spent by the pool.
|
// as spent by the pool.
|
||||||
mp.pool[*tx.Sha()] = &TxDesc{
|
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
|
// 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(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeight int64) float64 {
|
func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeight int32) float64 {
|
||||||
var totalInputAge float64
|
var totalInputAge float64
|
||||||
for _, txIn := range txDesc.Tx.MsgTx().TxIn {
|
for _, txIn := range txDesc.Tx.MsgTx().TxIn {
|
||||||
originHash := &txIn.PreviousOutPoint.Hash
|
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.
|
// 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 int64
|
var inputAge int32
|
||||||
if txData.BlockHeight == mempoolHeight {
|
if txData.BlockHeight == mempoolHeight {
|
||||||
inputAge = 0
|
inputAge = 0
|
||||||
} else {
|
} else {
|
||||||
|
@ -817,7 +817,7 @@ func calcInputValueAge(txDesc *TxDesc, txStore blockchain.TxStore, nextBlockHeig
|
||||||
// Sum the input value times age.
|
// Sum the input value times age.
|
||||||
originTxOut := txData.Tx.MsgTx().TxOut[originIndex]
|
originTxOut := txData.Tx.MsgTx().TxOut[originIndex]
|
||||||
inputValue := originTxOut.Value
|
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
|
// CurrentPriority calculates the current priority of this tx descriptor's
|
||||||
// underlying transaction relative to the next block height.
|
// 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)
|
inputAge := calcInputValueAge(txD, txStore, nextBlockHeight)
|
||||||
return calcPriority(txD.Tx, inputAge)
|
return calcPriority(txD.Tx, inputAge)
|
||||||
}
|
}
|
||||||
|
|
12
mining.go
12
mining.go
|
@ -158,7 +158,7 @@ type BlockTemplate struct {
|
||||||
block *wire.MsgBlock
|
block *wire.MsgBlock
|
||||||
fees []int64
|
fees []int64
|
||||||
sigOpCounts []int64
|
sigOpCounts []int64
|
||||||
height int64
|
height int32
|
||||||
validPayAddress bool
|
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,
|
// 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 int64, extraNonce uint64) ([]byte, error) {
|
func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) {
|
||||||
return txscript.NewScriptBuilder().AddInt64(nextBlockHeight).
|
return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)).
|
||||||
AddInt64(int64(extraNonce)).AddData([]byte(coinbaseFlags)).
|
AddInt64(int64(extraNonce)).AddData([]byte(coinbaseFlags)).
|
||||||
Script()
|
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
|
// See the comment for NewBlockTemplate for more information about why the nil
|
||||||
// address handling is useful.
|
// 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
|
// 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.
|
||||||
|
@ -232,7 +232,7 @@ func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil
|
||||||
// spendTransaction updates the passed transaction store by marking the inputs
|
// spendTransaction updates the passed transaction store by marking the inputs
|
||||||
// to the passed transaction as spent. It also adds the passed transaction to
|
// to the passed transaction as spent. It also adds the passed transaction to
|
||||||
// the store at the provided height.
|
// 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 {
|
for _, txIn := range tx.MsgTx().TxIn {
|
||||||
originHash := &txIn.PreviousOutPoint.Hash
|
originHash := &txIn.PreviousOutPoint.Hash
|
||||||
originIndex := txIn.PreviousOutPoint.Index
|
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
|
// 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 UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int64, extraNonce uint64) error {
|
func UpdateExtraNonce(msgBlock *wire.MsgBlock, blockHeight int32, extraNonce uint64) error {
|
||||||
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
|
coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
8
peer.go
8
peer.go
|
@ -928,7 +928,7 @@ func (p *peer) handleGetBlocksMsg(msg *wire.MsgGetBlocks) {
|
||||||
// provided locator are known. This does mean the client will start
|
// provided locator are known. This does mean the client will start
|
||||||
// over with the genesis block if unknown block locators are provided.
|
// over with the genesis block if unknown block locators are provided.
|
||||||
// This mirrors the behavior in the reference implementation.
|
// This mirrors the behavior in the reference implementation.
|
||||||
startIdx := int64(1)
|
startIdx := int32(1)
|
||||||
for _, hash := range msg.BlockLocatorHashes {
|
for _, hash := range msg.BlockLocatorHashes {
|
||||||
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
@ -972,7 +972,7 @@ func (p *peer) handleGetBlocksMsg(msg *wire.MsgGetBlocks) {
|
||||||
iv := wire.NewInvVect(wire.InvTypeBlock, &hashCopy)
|
iv := wire.NewInvVect(wire.InvTypeBlock, &hashCopy)
|
||||||
invMsg.AddInvVect(iv)
|
invMsg.AddInvVect(iv)
|
||||||
}
|
}
|
||||||
start += int64(len(hashList))
|
start += int32(len(hashList))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send the inventory message if there is anything to send.
|
// 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
|
// provided locator are known. This does mean the client will start
|
||||||
// over with the genesis block if unknown block locators are provided.
|
// over with the genesis block if unknown block locators are provided.
|
||||||
// This mirrors the behavior in the reference implementation.
|
// This mirrors the behavior in the reference implementation.
|
||||||
startIdx := int64(1)
|
startIdx := int32(1)
|
||||||
for _, hash := range msg.BlockLocatorHashes {
|
for _, hash := range msg.BlockLocatorHashes {
|
||||||
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
height, err := p.server.db.FetchBlockHeightBySha(hash)
|
||||||
if err == nil {
|
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
|
// Start at the next block header after the latest one on the
|
||||||
// next loop iteration.
|
// next loop iteration.
|
||||||
start += int64(len(hashList))
|
start += int32(len(hashList))
|
||||||
}
|
}
|
||||||
p.QueueMessage(headersMsg, nil)
|
p.QueueMessage(headersMsg, nil)
|
||||||
}
|
}
|
||||||
|
|
38
rpcserver.go
38
rpcserver.go
|
@ -676,7 +676,7 @@ func createVoutList(mtx *wire.MsgTx, chainParams *chaincfg.Params) []btcjson.Vou
|
||||||
// to a raw transaction JSON object.
|
// to a raw transaction JSON object.
|
||||||
func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx,
|
func createTxRawResult(chainParams *chaincfg.Params, mtx *wire.MsgTx,
|
||||||
txHash string, blkHeader *wire.BlockHeader, blkHash string,
|
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)
|
mtxHex, err := messageToHex(mtx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1013,7 +1013,7 @@ func handleGetBlock(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i
|
||||||
Nonce: blockHeader.Nonce,
|
Nonce: blockHeader.Nonce,
|
||||||
Time: blockHeader.Timestamp.Unix(),
|
Time: blockHeader.Timestamp.Unix(),
|
||||||
Confirmations: uint64(1 + maxIdx - idx),
|
Confirmations: uint64(1 + maxIdx - idx),
|
||||||
Height: idx,
|
Height: int64(idx),
|
||||||
Size: int32(len(buf)),
|
Size: int32(len(buf)),
|
||||||
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
|
Bits: strconv.FormatInt(int64(blockHeader.Bits), 16),
|
||||||
Difficulty: getDifficultyRatio(blockHeader.Bits),
|
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.
|
// Get next block unless we are already at the top.
|
||||||
if idx < maxIdx {
|
if idx < maxIdx {
|
||||||
var shaNext *wire.ShaHash
|
var shaNext *wire.ShaHash
|
||||||
shaNext, err = s.server.db.FetchBlockShaByHeight(int64(idx + 1))
|
shaNext, err = s.server.db.FetchBlockShaByHeight(idx + 1)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
context := "No next block"
|
context := "No next block"
|
||||||
return nil, internalRPCError(err.Error(), context)
|
return nil, internalRPCError(err.Error(), context)
|
||||||
|
@ -1073,7 +1073,7 @@ func handleGetBlockCount(s *rpcServer, cmd interface{}, closeChan <-chan struct{
|
||||||
// handleGetBlockHash implements the getblockhash command.
|
// handleGetBlockHash implements the getblockhash command.
|
||||||
func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
|
func handleGetBlockHash(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
|
||||||
c := cmd.(*btcjson.GetBlockHashCmd)
|
c := cmd.(*btcjson.GetBlockHashCmd)
|
||||||
sha, err := s.server.db.FetchBlockShaByHeight(c.Index)
|
sha, err := s.server.db.FetchBlockShaByHeight(int32(c.Index))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, &btcjson.RPCError{
|
return nil, &btcjson.RPCError{
|
||||||
Code: btcjson.ErrRPCOutOfRange,
|
Code: btcjson.ErrRPCOutOfRange,
|
||||||
|
@ -1109,7 +1109,7 @@ func handleGetBlockHeader(s *rpcServer, cmd interface{}, closeChan <-chan struct
|
||||||
}
|
}
|
||||||
|
|
||||||
var shaNextStr string
|
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 {
|
if err == nil {
|
||||||
shaNextStr = shaNext.String()
|
shaNextStr = shaNext.String()
|
||||||
}
|
}
|
||||||
|
@ -1510,7 +1510,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: template.height,
|
Height: int64(template.height),
|
||||||
PreviousHash: header.PrevBlock.String(),
|
PreviousHash: header.PrevBlock.String(),
|
||||||
SigOpLimit: blockchain.MaxSigOpsPerBlock,
|
SigOpLimit: blockchain.MaxSigOpsPerBlock,
|
||||||
SizeLimit: wire.MaxBlockPayload,
|
SizeLimit: wire.MaxBlockPayload,
|
||||||
|
@ -2052,7 +2052,7 @@ func handleGetMiningInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{
|
||||||
}
|
}
|
||||||
|
|
||||||
result := btcjson.GetMiningInfoResult{
|
result := btcjson.GetMiningInfoResult{
|
||||||
Blocks: height,
|
Blocks: int64(height),
|
||||||
CurrentBlockSize: uint64(len(blockBytes)),
|
CurrentBlockSize: uint64(len(blockBytes)),
|
||||||
CurrentBlockTx: uint64(len(block.MsgBlock().Transactions)),
|
CurrentBlockTx: uint64(len(block.MsgBlock().Transactions)),
|
||||||
Difficulty: getDifficultyRatio(block.MsgBlock().Header.Bits),
|
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
|
// since we can't reasonably calculate the number of network hashes
|
||||||
// per second from invalid values. When it's negative, use the current
|
// per second from invalid values. When it's negative, use the current
|
||||||
// best block height.
|
// best block height.
|
||||||
endHeight := int64(-1)
|
endHeight := int32(-1)
|
||||||
if c.Height != nil {
|
if c.Height != nil {
|
||||||
endHeight = int64(*c.Height)
|
endHeight = int32(*c.Height)
|
||||||
}
|
}
|
||||||
if endHeight > newestHeight || endHeight == 0 {
|
if endHeight > newestHeight || endHeight == 0 {
|
||||||
return int64(0), nil
|
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
|
// blocks. When the passed value is negative, use the last block the
|
||||||
// difficulty changed as the starting height. Also make sure the
|
// difficulty changed as the starting height. Also make sure the
|
||||||
// starting height is not before the beginning of the chain.
|
// starting height is not before the beginning of the chain.
|
||||||
numBlocks := int64(120)
|
numBlocks := int32(120)
|
||||||
if c.Blocks != nil {
|
if c.Blocks != nil {
|
||||||
numBlocks = int64(*c.Blocks)
|
numBlocks = int32(*c.Blocks)
|
||||||
}
|
}
|
||||||
var startHeight int64
|
var startHeight int32
|
||||||
if numBlocks <= 0 {
|
if numBlocks <= 0 {
|
||||||
startHeight = endHeight - ((endHeight % blockchain.BlocksPerRetarget) + 1)
|
startHeight = endHeight - ((endHeight % blockchain.BlocksPerRetarget) + 1)
|
||||||
} else {
|
} else {
|
||||||
|
@ -2209,7 +2209,7 @@ func handleGetRawMempool(s *rpcServer, cmd interface{}, closeChan <-chan struct{
|
||||||
Size: int32(desc.Tx.MsgTx().SerializeSize()),
|
Size: int32(desc.Tx.MsgTx().SerializeSize()),
|
||||||
Fee: btcutil.Amount(desc.Fee).ToBTC(),
|
Fee: btcutil.Amount(desc.Fee).ToBTC(),
|
||||||
Time: desc.Added.Unix(),
|
Time: desc.Added.Unix(),
|
||||||
Height: desc.Height,
|
Height: int64(desc.Height),
|
||||||
StartingPriority: startingPriority,
|
StartingPriority: startingPriority,
|
||||||
CurrentPriority: currentPriority,
|
CurrentPriority: currentPriority,
|
||||||
Depends: make([]string, 0),
|
Depends: make([]string, 0),
|
||||||
|
@ -2252,7 +2252,7 @@ func handleGetRawTransaction(s *rpcServer, cmd interface{}, closeChan <-chan str
|
||||||
// try the block database.
|
// try the block database.
|
||||||
var mtx *wire.MsgTx
|
var mtx *wire.MsgTx
|
||||||
var blkHash *wire.ShaHash
|
var blkHash *wire.ShaHash
|
||||||
var blkHeight int64
|
var blkHeight int32
|
||||||
tx, err := s.server.txMemPool.FetchTransaction(txHash)
|
tx, err := s.server.txMemPool.FetchTransaction(txHash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
txList, err := s.server.db.FetchTxBySha(txHash)
|
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 blkHeader *wire.BlockHeader
|
||||||
var blkHashStr string
|
var blkHashStr string
|
||||||
var chainHeight int64
|
var chainHeight int32
|
||||||
if blkHash != nil {
|
if blkHash != nil {
|
||||||
blkHeader, err = s.server.db.FetchBlockHeaderBySha(blkHash)
|
blkHeader, err = s.server.db.FetchBlockHeaderBySha(blkHash)
|
||||||
if err != nil {
|
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.
|
// from there, otherwise attempt to fetch from the block database.
|
||||||
var mtx *wire.MsgTx
|
var mtx *wire.MsgTx
|
||||||
var bestBlockSha string
|
var bestBlockSha string
|
||||||
var confirmations int64
|
var confirmations int32
|
||||||
var dbSpentInfo []bool
|
var dbSpentInfo []bool
|
||||||
includeMempool := true
|
includeMempool := true
|
||||||
if c.IncludeMempool != nil {
|
if c.IncludeMempool != nil {
|
||||||
|
@ -2450,7 +2450,7 @@ func handleGetTxOut(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (i
|
||||||
|
|
||||||
txOutReply := &btcjson.GetTxOutResult{
|
txOutReply := &btcjson.GetTxOutResult{
|
||||||
BestBlock: bestBlockSha,
|
BestBlock: bestBlockSha,
|
||||||
Confirmations: confirmations,
|
Confirmations: int64(confirmations),
|
||||||
Value: btcutil.Amount(txOut.Value).ToUnit(btcutil.AmountBTC),
|
Value: btcutil.Amount(txOut.Value).ToUnit(btcutil.AmountBTC),
|
||||||
Version: mtx.Version,
|
Version: mtx.Version,
|
||||||
ScriptPubKey: btcjson.ScriptPubKeyResult{
|
ScriptPubKey: btcjson.ScriptPubKeyResult{
|
||||||
|
@ -2946,7 +2946,7 @@ func handleSearchRawTransactions(s *rpcServer, cmd interface{}, closeChan <-chan
|
||||||
// final JSON output (mempool won't have confirmations).
|
// final JSON output (mempool won't have confirmations).
|
||||||
var blkHeader *wire.BlockHeader
|
var blkHeader *wire.BlockHeader
|
||||||
var blkHashStr string
|
var blkHashStr string
|
||||||
var blkHeight int64
|
var blkHeight int32
|
||||||
if txReply.BlkSha != nil {
|
if txReply.BlkSha != nil {
|
||||||
blkHeader, err = s.server.db.FetchBlockHeaderBySha(txReply.BlkSha)
|
blkHeader, err = s.server.db.FetchBlockHeaderBySha(txReply.BlkSha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -3128,7 +3128,7 @@ func verifyChain(db database.Db, level, depth int32, timeSource blockchain.Media
|
||||||
|
|
||||||
for height := curHeight; height > finishHeight; height-- {
|
for height := curHeight; height > finishHeight; height-- {
|
||||||
// Level 0 just looks up the block.
|
// Level 0 just looks up the block.
|
||||||
sha, err := db.FetchBlockShaByHeight(int64(height))
|
sha, err := db.FetchBlockShaByHeight(height)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
rpcsLog.Errorf("Verify is unable to fetch block at "+
|
rpcsLog.Errorf("Verify is unable to fetch block at "+
|
||||||
"height %d: %v", height, err)
|
"height %d: %v", height, err)
|
||||||
|
|
|
@ -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
|
// 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
|
// range of blocks. If this condition does not hold true, the JSON-RPC error
|
||||||
// for an unrecoverable reorganize is returned.
|
// 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) {
|
lastBlock *wire.ShaHash) ([]wire.ShaHash, error) {
|
||||||
|
|
||||||
hashList, err := db.FetchHeightRange(minBlock, maxBlock)
|
hashList, err := db.FetchHeightRange(minBlock, maxBlock)
|
||||||
|
@ -2023,7 +2023,7 @@ fetchRange:
|
||||||
// A goto is used to branch executation back to
|
// A goto is used to branch executation back to
|
||||||
// before the range was evaluated, as it must be
|
// before the range was evaluated, as it must be
|
||||||
// reevaluated for the new hashList.
|
// reevaluated for the new hashList.
|
||||||
minBlock += int64(i)
|
minBlock += int32(i)
|
||||||
hashList, err = recoverFromReorg(db, minBlock,
|
hashList, err = recoverFromReorg(db, minBlock,
|
||||||
maxBlock, lastBlockHash)
|
maxBlock, lastBlockHash)
|
||||||
if err != nil {
|
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
|
// Notify websocket client of the finished rescan. Due to how btcd
|
||||||
|
|
Loading…
Add table
Reference in a new issue