Class Block
A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system.
It records a set of Transaction
s 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
.
Instances of this class are not safe for use by multiple threads.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic enum
Flags used to control which elements of block validation are done on received blocks. -
Field Summary
Modifier and TypeFieldDescriptionstatic final int
Height of the first blockstatic final int
Value to use if the block height is unknownstatic final long
Block version introduced in BIP 34: Height in coinbasestatic final long
Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFYstatic final long
Block version introduced in BIP 66: Strict DER signaturesstatic final long
static final long
A value for difficultyTarget (nBits) that allows (slightly less than) half of all possible hash solutions.static final int
How many bytes are required to represent a block header WITHOUT the trailing 00 length byte.protected boolean
static final int
A "sigop" is a signature verification operation.static final int
A constant shared by the entire network: how large in bytes a block is allowed to be.protected int
static final long
Standard maximum value for difficultyTarget (nBits) (Bitcoin MainNet and TestNet)protected boolean
Fields inherited from class org.bitcoinj.core.Message
cursor, length, MAX_SIZE, offset, params, payload, recached, serializer, UNKNOWN_LENGTH
-
Constructor Summary
ConstructorDescriptionBlock
(NetworkParameters params, byte[] payloadBytes, int offset, Message parent, MessageSerializer serializer, int length) Construct a block object from the Bitcoin wire format.Block
(NetworkParameters params, byte[] payloadBytes, int offset, MessageSerializer serializer, int length) Construct a block object from the Bitcoin wire format.Block
(NetworkParameters params, byte[] payloadBytes, MessageSerializer serializer, int length) Construct 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
Modifier and TypeMethodDescriptionvoid
Adds a transaction to this block.byte[]
Special handling to check if we have a valid byte array for both header and transactionsprotected void
bitcoinSerializeToStream
(OutputStream stream) Serializes this message to the provided stream.protected boolean
checkProofOfWork
(boolean throwException) Returns true if the hash of the block is OK (lower than difficulty target).Returns a copy of the block, but without any transactions.static Block
createNextBlock
(Address to, long version, long time, int blockHeight) Returns a solved block that builds on top of this one.createNextBlock
(Address to, Coin value) createNextBlock
(Address to, TransactionOutPoint prevOut) createNextBlockWithCoinbase
(long version, byte[] pubKey, Coin coinbaseValue, int height) boolean
getBlockInflation
(int height) Deprecated.long
Returns the difficulty of the proof of work that this block should meet encoded in compact form.Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash.getHash()
Returns the hash of the block (which for a valid, solved block should be below the target).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.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
Returns the hash of the previous block in the chain, as defined by the block header.getTime()
Returns the time at which the block was solved and broadcast, according to the clock of the solving node.long
Returns the time at which the block was solved and broadcast, according to the clock of the solving node.Returns an immutable list of transactions held in this block, or null if this object represents just a header.long
Returns the version of the block data structure as defined by the Bitcoin protocol.Returns the witness root in big endian form, calculating it from transactions if necessary.getWork()
Returns the work represented by this block.int
hashCode()
boolean
Return whether this block contains any transactions.boolean
isBIP34()
Returns whether this block conforms to BIP34: Height in Coinbase.boolean
isBIP65()
Returns whether this block conforms to BIP65: OP_CHECKLOCKTIMEVERIFY.boolean
isBIP66()
Returns whether this block conforms to BIP66: Strict DER signatures.protected void
parse()
protected void
parseTransactions
(int transactionsOffset) Parse transactions from the block.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.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
(int height, EnumSet<Block.VerifyFlag> flags) Verifies both the header and that the transactions hash to the merkle root.void
Checks the block data to ensure it follows the rules laid out in the network parameters.void
verifyTransactions
(int height, EnumSet<Block.VerifyFlag> flags) Checks the block contentsMethods inherited from class org.bitcoinj.core.Message
adjustLength, bitcoinSerialize, getMessageSize, getParams, hasMoreBytes, isCached, isRecached, readByte, readByteArray, readBytes, readHash, readInt64, readStr, readUint32, readUint64, readVarInt, readVarInt, setSerializer, unsafeBitcoinSerialize
-
Field Details
-
HEADER_SIZE
public static final int HEADER_SIZEHow many bytes are required to represent a block header WITHOUT the trailing 00 length byte.- See Also:
-
MAX_BLOCK_SIZE
public static final int MAX_BLOCK_SIZEA 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:
-
MAX_BLOCK_SIGOPS
public static final int MAX_BLOCK_SIGOPSA "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:
-
STANDARD_MAX_DIFFICULTY_TARGET
public static final long STANDARD_MAX_DIFFICULTY_TARGETStandard maximum value for difficultyTarget (nBits) (Bitcoin MainNet and TestNet)- See Also:
-
EASIEST_DIFFICULTY_TARGET
public static final long EASIEST_DIFFICULTY_TARGETA value for difficultyTarget (nBits) that allows (slightly less than) half of all possible hash solutions. Used in unit testing.- See Also:
-
BLOCK_HEIGHT_UNKNOWN
public static final int BLOCK_HEIGHT_UNKNOWNValue to use if the block height is unknown- See Also:
-
BLOCK_HEIGHT_GENESIS
public static final int BLOCK_HEIGHT_GENESISHeight of the first block- See Also:
-
BLOCK_VERSION_GENESIS
public static final long BLOCK_VERSION_GENESIS- See Also:
-
BLOCK_VERSION_BIP34
public static final long BLOCK_VERSION_BIP34Block version introduced in BIP 34: Height in coinbase- See Also:
-
BLOCK_VERSION_BIP66
public static final long BLOCK_VERSION_BIP66Block version introduced in BIP 66: Strict DER signatures- See Also:
-
BLOCK_VERSION_BIP65
public static final long BLOCK_VERSION_BIP65Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFY- See Also:
-
headerBytesValid
protected boolean headerBytesValid -
transactionBytesValid
protected boolean transactionBytesValid -
optimalEncodingMessageSize
protected int optimalEncodingMessageSize
-
-
Constructor Details
-
Block
public Block(NetworkParameters params, byte[] payloadBytes, MessageSerializer serializer, int length) throws ProtocolException Construct a block object from the Bitcoin wire format.- Parameters:
params
- NetworkParameters object.payloadBytes
- the payload to extract the block from.serializer
- the serializer to use for this message.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, byte[] payloadBytes, int offset, MessageSerializer serializer, int length) throws ProtocolException Construct a block object from the Bitcoin wire format.- Parameters:
params
- NetworkParameters object.payloadBytes
- the payload to extract the block from.offset
- The location of the first payload byte within the array.serializer
- the serializer to use for this message.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, byte[] payloadBytes, int offset, @Nullable Message parent, MessageSerializer serializer, int length) throws ProtocolException Construct a block object from the Bitcoin wire format. Used in the case of a block contained within another message (i.e. for AuxPoW header).- Parameters:
params
- NetworkParameters object.payloadBytes
- Bitcoin protocol formatted byte array containing message content.offset
- The location of the first payload byte within the array.parent
- The message element which contains this block, maybe null for no parent.serializer
- the serializer to use for this block.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 orSha256Hash.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 Details
-
getBlockInflation
Deprecated. -
parseTransactions
Parse transactions from the block.- Parameters:
transactionsOffset
- Offset of the transactions within the block. Useful for non-Bitcoin chains where the block header may not be a fixed size.- Throws:
ProtocolException
-
parse
- Specified by:
parse
in classMessage
- Throws:
ProtocolException
-
createGenesis
-
getOptimalEncodingMessageSize
public int getOptimalEncodingMessageSize() -
bitcoinSerialize
public byte[] bitcoinSerialize()Special handling to check if we have a valid byte array for both header and transactions- Overrides:
bitcoinSerialize
in classMessage
- Returns:
- a freshly allocated serialized byte array
-
bitcoinSerializeToStream
Description copied from class:Message
Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize().- Overrides:
bitcoinSerializeToStream
in classMessage
- 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.
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.
-
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 mainnet chain you will get "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048". -
getHash
Returns the hash of the block (which for a valid, solved block should be below the target). Big endian. -
getWork
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
Returns a copy of the block, but without any transactions.- Returns:
- new, header-only
Block
-
toString
Returns a multi-line string containing a description of the contents of the block. Use for debugging purposes only. -
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
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
-
checkProofOfWork
Returns true if the hash of the block is OK (lower than difficulty target).- Throws:
VerificationException
-
verifyHeader
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(int height, EnumSet<Block.VerifyFlag> flags) throws VerificationException Checks the block contents- Parameters:
height
- block height, if known, or -1 otherwise. If valid, used to validate the coinbase input script of v2 and above blocks.flags
- flags to indicate which tests should be applied (i.e. whether to test for height in the coinbase transaction).- Throws:
VerificationException
- if there was an error verifying the block.
-
verify
Verifies both the header and that the transactions hash to the merkle root.- Parameters:
height
- block height, if known, or -1 otherwise.flags
- flags to indicate which tests should be applied (i.e. whether to test for height in the coinbase transaction).- Throws:
VerificationException
- if there was an error verifying the block.
-
equals
-
hashCode
public int hashCode() -
getMerkleRoot
Returns the merkle root in big endian form, calculating it from transactions if necessary. -
getWitnessRoot
Returns the witness root in big endian form, calculating it from transactions if necessary. -
addTransaction
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
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
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. TheBlockChain
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, usegetDifficultyTargetAsInteger()
. 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
Returns an immutable list of transactions held in this block, or null if this object represents just a header. -
createNextBlock
Returns a solved block that builds on top of this one. This exists for unit tests. -
createNextBlock
-
createNextBlock
-
createNextBlock
-
createNextBlockWithCoinbase
-
hasTransactions
public boolean hasTransactions()Return whether this block contains any transactions.- Returns:
- true if the block contains transactions, false otherwise (is purely a header).
-
isBIP34
public boolean isBIP34()Returns whether this block conforms to BIP34: Height in Coinbase. -
isBIP66
public boolean isBIP66()Returns whether this block conforms to BIP66: Strict DER signatures. -
isBIP65
public boolean isBIP65()Returns whether this block conforms to BIP65: OP_CHECKLOCKTIMEVERIFY.
-
AbstractBitcoinNetParams.getBlockInflation(int)