Class Block
- java.lang.Object
-
- org.bitcoinj.core.BaseMessage
-
- org.bitcoinj.core.Block
-
- All Implemented Interfaces:
Message
public class Block extends BaseMessage
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 downloadedBlockChain.Instances of this class are not safe for use by multiple threads.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classBlock.VerifyFlagFlags used to control which elements of block validation are done on received blocks.
-
Field Summary
Fields Modifier and Type Field Description static intBLOCK_HEIGHT_GENESISHeight of the first blockstatic intBLOCK_HEIGHT_UNKNOWNValue to use if the block height is unknownstatic longBLOCK_VERSION_BIP34Block version introduced in BIP 34: Height in coinbasestatic longBLOCK_VERSION_BIP65Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFYstatic longBLOCK_VERSION_BIP66Block version introduced in BIP 66: Strict DER signaturesstatic longBLOCK_VERSION_GENESISstatic longEASIEST_DIFFICULTY_TARGETA value for difficultyTarget (nBits) that allows (slightly less than) half of all possible hash solutions.static intHEADER_SIZEHow many bytes are required to represent a block header WITHOUT the trailing 00 length byte.static intMAX_BLOCK_SIGOPSA "sigop" is a signature verification operation.static intMAX_BLOCK_SIZEA constant shared by the entire network: how large in bytes a block is allowed to be.static longSTANDARD_MAX_DIFFICULTY_TARGETStandard maximum value for difficultyTarget (nBits) (Bitcoin MainNet and TestNet)
-
Constructor Summary
Constructors Constructor Description Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, java.util.List<Transaction> transactions)Deprecated.Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, java.time.Instant time, long difficultyTarget, long nonce, java.util.List<Transaction> transactions)Construct a block initialized with all the given fields.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddTransaction(Transaction t)Adds a transaction to this block.protected voidbitcoinSerializeToStream(java.io.OutputStream stream)Serializes this message to the provided stream.protected booleancheckProofOfWork(boolean throwException)Returns true if the hash of the block is OK (lower than difficulty target).BlockcloneAsHeader()Returns a copy of the block, but without any transactions.static BlockcreateGenesis()BlockcreateNextBlock(Address to)This method is intended for test use only.BlockcreateNextBlock(Address to, long version, java.time.Instant time, int height)Returns a solved block that builds on top of this one.BlockcreateNextBlock(Address to, Coin coinbaseValue)This method is intended for test use only.BlockcreateNextBlock(Address to, TransactionOutPoint prevOut)This method is intended for test use only.BlockcreateNextBlockWithCoinbase(long version, byte[] pubKey, Coin coinbaseValue, int height)This method is intended for test use only.booleanequals(java.lang.Object o)longgetDifficultyTarget()Returns the difficulty of the proof of work that this block should meet encoded in compact form.java.math.BigIntegergetDifficultyTargetAsInteger()Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash.Sha256HashgetHash()Returns the hash of the block (which for a valid, solved block should be below the target).java.lang.StringgetHashAsString()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.Sha256HashgetMerkleRoot()Returns the merkle root in big endian form, calculating it from transactions if necessary.longgetNonce()Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the difficulty target.Sha256HashgetPrevBlockHash()Returns the hash of the previous block in the chain, as defined by the block header.java.util.DategetTime()Deprecated.usetime()longgetTimeSeconds()Deprecated.usetime()java.util.List<Transaction>getTransactions()Returns an unmodifiable list of transactions held in this block, or null if this object represents just a header.longgetVersion()Returns the version of the block data structure as defined by the Bitcoin protocol.Sha256HashgetWitnessRoot()Returns the witness root in big endian form, calculating it from transactions if necessary.java.math.BigIntegergetWork()Returns the work represented by this block.inthashCode()booleanhasTransactions()Return whether this block contains any transactions.booleanisBIP34()Returns whether this block conforms to BIP34: Height in Coinbase.booleanisBIP65()Returns whether this block conforms to BIP65: OP_CHECKLOCKTIMEVERIFY.booleanisBIP66()Returns whether this block conforms to BIP66: Strict DER signatures.intmessageSize()Return the size of the serialized message.static Blockread(java.nio.ByteBuffer payload)Deserialize this message from a given payload.voidsetDifficultyTarget(long compactForm)Sets the difficulty target in compact form.voidsetNonce(long nonce)Sets the nonce and clears any cached data.voidsetTime(java.time.Instant time)voidsolve()Finds a value of nonce that makes the blocks hash lower than the difficulty target.java.time.Instanttime()Returns the time at which the block was solved and broadcast, according to the clock of the solving node.java.lang.StringtoString()Returns a multi-line string containing a description of the contents of the block.protected voidunCache()static voidverify(NetworkParameters params, Block block, int height, java.util.EnumSet<Block.VerifyFlag> flags)Verifies both the header and that the transactions hash to the merkle root.static voidverifyHeader(Block block)Checks the block data to ensure it follows the rules laid out in the network parameters.static voidverifyTransactions(NetworkParameters params, Block block, int height, java.util.EnumSet<Block.VerifyFlag> flags)Checks the block contents-
Methods inherited from class org.bitcoinj.core.BaseMessage
serialize
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.bitcoinj.core.Message
bitcoinSerialize, getMessageSize, unsafeBitcoinSerialize
-
-
-
-
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
-
STANDARD_MAX_DIFFICULTY_TARGET
public static final long STANDARD_MAX_DIFFICULTY_TARGET
Standard maximum value for difficultyTarget (nBits) (Bitcoin MainNet and TestNet)- See Also:
- Constant Field Values
-
EASIEST_DIFFICULTY_TARGET
public static final long EASIEST_DIFFICULTY_TARGET
A value for difficultyTarget (nBits) that allows (slightly less than) half of all possible hash solutions. Used in unit testing.- See Also:
- Constant Field Values
-
BLOCK_HEIGHT_UNKNOWN
public static final int BLOCK_HEIGHT_UNKNOWN
Value to use if the block height is unknown- See Also:
- Constant Field Values
-
BLOCK_HEIGHT_GENESIS
public static final int BLOCK_HEIGHT_GENESIS
Height of the first block- See Also:
- Constant Field Values
-
BLOCK_VERSION_GENESIS
public static final long BLOCK_VERSION_GENESIS
- See Also:
- Constant Field Values
-
BLOCK_VERSION_BIP34
public static final long BLOCK_VERSION_BIP34
Block version introduced in BIP 34: Height in coinbase- See Also:
- Constant Field Values
-
BLOCK_VERSION_BIP66
public static final long BLOCK_VERSION_BIP66
Block version introduced in BIP 66: Strict DER signatures- See Also:
- Constant Field Values
-
BLOCK_VERSION_BIP65
public static final long BLOCK_VERSION_BIP65
Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFY- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Block
public Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, java.time.Instant time, long difficultyTarget, long nonce, java.util.List<Transaction> transactions)Construct a block initialized with all the given fields.- Parameters:
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_HASHif genesis.merkleRoot- The root of the merkle tree formed by the transactions.time- 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.
-
Block
@Deprecated public Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, java.util.List<Transaction> transactions)Deprecated.Construct a block initialized with all the given fields.- Parameters:
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_HASHif genesis.merkleRoot- The root of the merkle tree formed by the transactions.time- UNIX time seconds 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
-
read
public static Block read(java.nio.ByteBuffer payload) throws java.nio.BufferUnderflowException, ProtocolException
Deserialize this message from a given payload.- Parameters:
payload- payload to deserialize from- Returns:
- read message
- Throws:
java.nio.BufferUnderflowException- if the read message extends beyond the remaining bytes of the payloadProtocolException
-
createGenesis
public static Block createGenesis()
-
messageSize
public int messageSize()
Description copied from class:BaseMessageReturn the size of the serialized message. Note that if the message was deserialized from a payload, this size can differ from the size of the original payload.- Specified by:
messageSizein interfaceMessage- Overrides:
messageSizein classBaseMessage- Returns:
- size of this object when serialized (in bytes)
-
bitcoinSerializeToStream
protected void bitcoinSerializeToStream(java.io.OutputStream stream) throws java.io.IOExceptionDescription copied from class:BaseMessageSerializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize().- Specified by:
bitcoinSerializeToStreamin classBaseMessage- Throws:
java.io.IOException
-
unCache
protected void unCache()
-
getHashAsString
public java.lang.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 mainnet 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.
-
getWork
public java.math.BigInteger getWork() throws VerificationExceptionReturns 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.- Returns:
- new, header-only
Block
-
toString
public java.lang.String toString()
Returns a multi-line string containing a description of the contents of the block. Use for debugging purposes only.- Overrides:
toStringin classjava.lang.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 java.math.BigInteger 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.- Returns:
- difficulty target as 256-bit value
-
checkProofOfWork
protected boolean checkProofOfWork(boolean throwException) throws VerificationExceptionReturns true if the hash of the block is OK (lower than difficulty target).- Throws:
VerificationException
-
equals
public boolean equals(java.lang.Object o)
- Overrides:
equalsin classjava.lang.Object
-
hashCode
public int hashCode()
- Overrides:
hashCodein classjava.lang.Object
-
getMerkleRoot
public Sha256Hash getMerkleRoot()
Returns the merkle root in big endian form, calculating it from transactions if necessary.
-
getWitnessRoot
public Sha256Hash getWitnessRoot()
Returns the witness 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.
-
time
public java.time.Instant time()
Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
-
getTimeSeconds
@Deprecated public long getTimeSeconds()
Deprecated.usetime()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
@Deprecated public java.util.Date getTime()
Deprecated.usetime()Returns the time at which the block was solved and broadcast, according to the clock of the solving node.
-
setTime
public void setTime(java.time.Instant time)
-
getDifficultyTarget
public long getDifficultyTarget()
Returns the difficulty of the proof of work that this block should meet encoded in compact form. TheBlockChainverifies 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
@Nullable public java.util.List<Transaction> getTransactions()
Returns an unmodifiable list of transactions held in this block, or null if this object represents just a header.
-
createNextBlock
public Block createNextBlock(@Nullable Address to, long version, java.time.Instant time, int height)
Returns a solved block that builds on top of this one. This exists for unit tests.- Parameters:
to- if not null, 50 coins are sent to the addressversion- version of the block to createtime- time of the block to createheight- block height if known, or -1 otherwise- Returns:
- created block
-
createNextBlock
public Block createNextBlock(@Nullable Address to, TransactionOutPoint prevOut)
This method is intended for test use only.- Parameters:
to- if not null, 50 coins are sent to the addressprevOut- previous output to spend by the "50 coins transaction"- Returns:
- created block
-
createNextBlock
public Block createNextBlock(@Nullable Address to, Coin coinbaseValue)
This method is intended for test use only.- Parameters:
to- if not null, 50 coins are sent to the addresscoinbaseValue- for the coinbase- Returns:
- created block
-
createNextBlock
public Block createNextBlock(@Nullable Address to)
This method is intended for test use only.- Parameters:
to- if not null, 50 coins are sent to the address- Returns:
- created block
-
createNextBlockWithCoinbase
public Block createNextBlockWithCoinbase(long version, byte[] pubKey, Coin coinbaseValue, int height)
This method is intended for test use only.- Parameters:
version- version of the block to createpubKey- for the coinbasecoinbaseValue- for the coinbaseheight- block height if known, or -1 otherwise- Returns:
- created block
-
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.
-
verify
public static void verify(NetworkParameters params, Block block, int height, java.util.EnumSet<Block.VerifyFlag> flags) throws VerificationException
Verifies both the header and that the transactions hash to the merkle root.- Parameters:
params- parameters for the verification rulesblock- block to verifyheight- 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 at least one of the rules is violated
-
verifyHeader
public static void verifyHeader(Block block) 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.- Parameters:
block- block to verify- Throws:
VerificationException- if at least one of the rules is violated
-
verifyTransactions
public static void verifyTransactions(NetworkParameters params, Block block, int height, java.util.EnumSet<Block.VerifyFlag> flags) throws VerificationException
Checks the block contents- Parameters:
params- parameters for the verification rulesblock- block to verifyheight- 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 at least one of the rules is violated
-
-