com.google.bitcoin.core
Class Block

java.lang.Object
  extended by com.google.bitcoin.core.Message
      extended by com.google.bitcoin.core.Block
All Implemented Interfaces:
Serializable

public class Block
extends Message

A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system. It records a set of Transactions together with some data that links it into a place in the global block chain, and proves that a difficult calculation was done over its contents. See the Bitcoin technical paper for more detail on blocks.

To get a block, you can either build one from the raw bytes you can get from another implementation, or request one specifically using Peer.getBlock(Sha256Hash), or grab one from a downloaded BlockChain.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class com.google.bitcoin.core.Message
Message.LazyParseException
 
Field Summary
static long EASIEST_DIFFICULTY_TARGET
          A value for difficultyTarget (nBits) that allows half of all possible hash solutions.
static int HEADER_SIZE
          How many bytes are required to represent a block header WITHOUT the trailing 00 length byte.
static int MAX_BLOCK_SIGOPS
          A "sigop" is a signature verification operation.
static int MAX_BLOCK_SIZE
          A constant shared by the entire network: how large in bytes a block is allowed to be.
 
Fields inherited from class com.google.bitcoin.core.Message
bytes, checksum, cursor, length, MAX_SIZE, offset, params, parsed, parseLazy, parseRetain, protocolVersion, recached, UNKNOWN_LENGTH
 
Constructor Summary
Block(NetworkParameters params, byte[] payloadBytes)
          Constructs a block object from the Bitcoin wire format.
Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length)
          Contruct a block object from the Bitcoin wire format.
Block(NetworkParameters params, long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, List<Transaction> transactions)
          Construct a block initialized with all the given fields.
 
Method Summary
 void addTransaction(Transaction t)
          Adds a transaction to this block.
 byte[] bitcoinSerialize()
          Special handling to check if we have a valid byte array for both header and transactions
protected  void bitcoinSerializeToStream(OutputStream stream)
          Serializes this message to the provided stream.
 Block cloneAsHeader()
          Returns a copy of the block, but without any transactions.
 Block createNextBlock(Address to)
           
 Block createNextBlock(Address to, BigInteger value)
           
 Block createNextBlock(Address to, long time)
          Returns a solved block that builds on top of this one.
 Block createNextBlock(Address to, TransactionOutPoint prevOut)
           
 Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue)
           
 void ensureParsed()
          In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException.
 void ensureParsedHeader()
          In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException.
 void ensureParsedTransactions()
          In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException.
 boolean equals(Object o)
           
 BigInteger getBlockInflation(int height)
          A utility method that calculates how much new Bitcoin would be created by the block at the given height.
 long getDifficultyTarget()
          Returns the difficulty of the proof of work that this block should meet encoded in compact form.
 BigInteger getDifficultyTargetAsInteger()
          Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash.
 Sha256Hash getHash()
          Returns the hash of the block (which for a valid, solved block should be below the target).
 String getHashAsString()
          Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen on the block explorer.
 Sha256Hash getMerkleRoot()
          Returns the merkle root in big endian form, calculating it from transactions if necessary.
 long getNonce()
          Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the difficulty target.
 int getOptimalEncodingMessageSize()
           
 Sha256Hash getPrevBlockHash()
          Returns the hash of the previous block in the chain, as defined by the block header.
 Date getTime()
          Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
 long getTimeSeconds()
          Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
 List<Transaction> getTransactions()
          Returns an immutable list of transactions held in this block.
 long getVersion()
          Returns the version of the block data structure as defined by the Bitcoin protocol.
 BigInteger getWork()
          Returns the work represented by this block.
 int hashCode()
           
protected  void maybeParse()
          Ensure the object is parsed if needed.
protected  void parseLite()
          Perform the most minimal parse possible to calculate the length of the message.
 void setDifficultyTarget(long compactForm)
          Sets the difficulty target in compact form.
 void setNonce(long nonce)
          Sets the nonce and clears any cached data.
 void setTime(long time)
           
 void solve()
          Finds a value of nonce that makes the blocks hash lower than the difficulty target.
 String toString()
          Returns a multi-line string containing a description of the contents of the block.
protected  void unCache()
          To be called before any change of internal values including any setters.
 void verify()
          Verifies both the header and that the transactions hash to the merkle root.
 void verifyHeader()
          Checks the block data to ensure it follows the rules laid out in the network parameters.
 void verifyTransactions()
          Checks the block contents
 
Methods inherited from class com.google.bitcoin.core.Message
adjustLength, bitcoinSerialize, getMessageSize, getParams, isCached, isParsed, isRecached, unsafeBitcoinSerialize
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

HEADER_SIZE

public static final int HEADER_SIZE
How many bytes are required to represent a block header WITHOUT the trailing 00 length byte.

See Also:
Constant Field Values

MAX_BLOCK_SIZE

public static final int MAX_BLOCK_SIZE
A constant shared by the entire network: how large in bytes a block is allowed to be. One day we may have to upgrade everyone to change this, so Bitcoin can continue to grow. For now it exists as an anti-DoS measure to avoid somebody creating a titanically huge but valid block and forcing everyone to download/store it forever.

See Also:
Constant Field Values

MAX_BLOCK_SIGOPS

public static final int MAX_BLOCK_SIGOPS
A "sigop" is a signature verification operation. Because they're expensive we also impose a separate limit on the number in a block to prevent somebody mining a huge block that has way more sigops than normal, so is very expensive/slow to verify.

See Also:
Constant Field Values

EASIEST_DIFFICULTY_TARGET

public static final long EASIEST_DIFFICULTY_TARGET
A value for difficultyTarget (nBits) that allows half of all possible hash solutions. Used in unit testing.

See Also:
Constant Field Values
Constructor Detail

Block

public Block(NetworkParameters params,
             byte[] payloadBytes)
      throws ProtocolException
Constructs a block object from the Bitcoin wire format.

Throws:
ProtocolException

Block

public Block(NetworkParameters params,
             byte[] payloadBytes,
             boolean parseLazy,
             boolean parseRetain,
             int length)
      throws ProtocolException
Contruct a block object from the Bitcoin wire format.

Parameters:
params - NetworkParameters object.
parseLazy - Whether to perform a full parse immediately or delay until a read is requested.
parseRetain - Whether to retain the backing byte array for quick reserialization. If true and the backing byte array is invalidated due to modification of a field then the cached bytes may be repopulated and retained if the message is serialized again in the future.
length - The length of message if known. Usually this is provided when deserializing of the wire as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
Throws:
ProtocolException

Block

public Block(NetworkParameters params,
             long version,
             Sha256Hash prevBlockHash,
             Sha256Hash merkleRoot,
             long time,
             long difficultyTarget,
             long nonce,
             List<Transaction> transactions)
Construct a block initialized with all the given fields.

Parameters:
params - Which network the block is for.
version - This should usually be set to 1 or 2, depending on if the height is in the coinbase input.
prevBlockHash - Reference to previous block in the chain or Sha256Hash.ZERO_HASH if genesis.
merkleRoot - The root of the merkle tree formed by the transactions.
time - UNIX time when the block was mined.
difficultyTarget - Number which this block hashes lower than.
nonce - Arbitrary number to make the block hash lower than the target.
transactions - List of transactions including the coinbase.
Method Detail

getBlockInflation

public BigInteger getBlockInflation(int height)

A utility method that calculates how much new Bitcoin would be created by the block at the given height. The inflation of Bitcoin is predictable and drops roughly every 4 years (210,000 blocks). At the dawn of the system it was 50 coins per block, in late 2012 it went to 25 coins per block, and so on. The size of a coinbase transaction is inflation plus fees.

The half-life is controlled by NetworkParameters.getSubsidyDecreaseBlockCount().


getOptimalEncodingMessageSize

public int getOptimalEncodingMessageSize()

parseLite

protected void parseLite()
                  throws ProtocolException
Description copied from class: Message
Perform the most minimal parse possible to calculate the length of the message. This is only required for subclasses of ChildClass as root level messages will have their length passed into the constructor.

Implementations should adhere to the following contract: If parseLazy = true the 'length' field must be set before returning. If parseLazy = false the length field must be set either within the parseLite() method OR the parse() method. The overriding requirement is that length must be set to non UNKNOWN_MESSAGE value by the time the constructor exits.

Specified by:
parseLite in class Message
Throws:
ProtocolException

maybeParse

protected void maybeParse()
Ensure the object is parsed if needed. This should be called in every getter before returning a value. If the lazy parse flag is not set this is a method returns immediately.

Overrides:
maybeParse in class Message

ensureParsed

public void ensureParsed()
                  throws ProtocolException
In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction messages) this will not force child messages to parse. This method ensures parsing of both headers and transactions.

Overrides:
ensureParsed in class Message
Throws:
ProtocolException

ensureParsedHeader

public void ensureParsedHeader()
                        throws ProtocolException
In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction messages) this will not force child messages to parse. This method ensures parsing of headers only.

Throws:
ProtocolException

ensureParsedTransactions

public void ensureParsedTransactions()
                              throws ProtocolException
In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed safe access is required this method will force parsing to occur immediately thus ensuring LazyParseExeption will never be thrown from this Message. If the Message contains child messages (e.g. a Block containing Transaction messages) this will not force child messages to parse. This method ensures parsing of transactions only.

Throws:
ProtocolException

bitcoinSerialize

public byte[] bitcoinSerialize()
Special handling to check if we have a valid byte array for both header and transactions

Overrides:
bitcoinSerialize in class Message
Returns:
a freshly allocated serialized byte array
Throws:
IOException

bitcoinSerializeToStream

protected void bitcoinSerializeToStream(OutputStream stream)
                                 throws IOException
Description copied from class: Message
Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize().

Throws:
IOException

unCache

protected void unCache()
Description copied from class: Message
To be called before any change of internal values including any setters. This ensures any cached byte array is removed after performing a lazy parse if necessary to ensure the object is fully populated.

Child messages of this object(e.g. Transactions belonging to a Block) will not have their internal byte caches invalidated unless they are also modified internally.

Overrides:
unCache in class Message

getHashAsString

public String getHashAsString()
Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen on the block explorer. If you call this on block 1 in the production chain you will get "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048".


getHash

public Sha256Hash getHash()
Returns the hash of the block (which for a valid, solved block should be below the target). Big endian.

Overrides:
getHash in class Message

getWork

public BigInteger getWork()
                   throws VerificationException
Returns the work represented by this block.

Work is defined as the number of tries needed to solve a block in the average case. Consider a difficulty target that covers 5% of all possible hash values. Then the work of the block will be 20. As the target gets lower, the amount of work goes up.

Throws:
VerificationException

cloneAsHeader

public Block cloneAsHeader()
Returns a copy of the block, but without any transactions.


toString

public String toString()
Returns a multi-line string containing a description of the contents of the block. Use for debugging purposes only.

Overrides:
toString in class Object

solve

public void solve()

Finds a value of nonce that makes the blocks hash lower than the difficulty target. This is called mining, but solve() is far too slow to do real mining with. It exists only for unit testing purposes.

This can loop forever if a solution cannot be found solely by incrementing nonce. It doesn't change extraNonce.


getDifficultyTargetAsInteger

public BigInteger getDifficultyTargetAsInteger()
                                        throws VerificationException
Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception is thrown.

Throws:
VerificationException

verifyHeader

public void verifyHeader()
                  throws VerificationException
Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically, throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be. This is not everything that is required for a block to be valid, only what is checkable independent of the chain and without a transaction index.

Throws:
VerificationException

verifyTransactions

public void verifyTransactions()
                        throws VerificationException
Checks the block contents

Throws:
VerificationException

verify

public void verify()
            throws VerificationException
Verifies both the header and that the transactions hash to the merkle root.

Throws:
VerificationException

equals

public boolean equals(Object o)
Overrides:
equals in class Object

hashCode

public int hashCode()
Overrides:
hashCode in class Object

getMerkleRoot

public Sha256Hash getMerkleRoot()
Returns the merkle root in big endian form, calculating it from transactions if necessary.


addTransaction

public void addTransaction(Transaction t)
Adds a transaction to this block. The nonce and merkle root are invalid after this.


getVersion

public long getVersion()
Returns the version of the block data structure as defined by the Bitcoin protocol.


getPrevBlockHash

public Sha256Hash getPrevBlockHash()
Returns the hash of the previous block in the chain, as defined by the block header.


getTimeSeconds

public long getTimeSeconds()
Returns the time at which the block was solved and broadcast, according to the clock of the solving node. This is measured in seconds since the UNIX epoch (midnight Jan 1st 1970).


getTime

public Date getTime()
Returns the time at which the block was solved and broadcast, according to the clock of the solving node.


setTime

public void setTime(long time)

getDifficultyTarget

public long getDifficultyTarget()
Returns the difficulty of the proof of work that this block should meet encoded in compact form. The BlockChain verifies that this is not too easy by looking at the length of the chain when the block is added. To find the actual value the hash should be compared against, use getDifficultyTargetAsInteger(). Note that this is not the same as the difficulty value reported by the Bitcoin "getdifficulty" RPC that you may see on various block explorers. That number is the result of applying a formula to the underlying difficulty to normalize the minimum to 1. Calculating the difficulty that way is currently unsupported.


setDifficultyTarget

public void setDifficultyTarget(long compactForm)
Sets the difficulty target in compact form.


getNonce

public long getNonce()
Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the difficulty target.


setNonce

public void setNonce(long nonce)
Sets the nonce and clears any cached data.


getTransactions

public List<Transaction> getTransactions()
Returns an immutable list of transactions held in this block.


createNextBlock

public Block createNextBlock(Address to,
                             long time)
Returns a solved block that builds on top of this one. This exists for unit tests.


createNextBlock

public Block createNextBlock(@Nullable
                             Address to,
                             TransactionOutPoint prevOut)

createNextBlock

public Block createNextBlock(@Nullable
                             Address to,
                             BigInteger value)

createNextBlock

public Block createNextBlock(@Nullable
                             Address to)

createNextBlockWithCoinbase

public Block createNextBlockWithCoinbase(byte[] pubKey,
                                         BigInteger coinbaseValue)


Copyright © 2014. All rights reserved.