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 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.
Modifier and Type | Class and Description |
---|---|
static class |
Block.VerifyFlag
Flags used to control which elements of block validation are done on
received blocks.
|
Modifier and Type | Field and Description |
---|---|
static int |
BLOCK_HEIGHT_GENESIS
Height of the first block
|
static int |
BLOCK_HEIGHT_UNKNOWN
Value to use if the block height is unknown
|
static long |
BLOCK_VERSION_BIP34
Block version introduced in BIP 34: Height in coinbase
|
static long |
BLOCK_VERSION_BIP65
Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFY
|
static long |
BLOCK_VERSION_BIP66
Block version introduced in BIP 66: Strict DER signatures
|
static long |
BLOCK_VERSION_GENESIS |
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.
|
protected boolean |
headerBytesValid |
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.
|
protected int |
optimalEncodingMessageSize |
protected boolean |
transactionBytesValid |
cursor, length, MAX_SIZE, offset, params, payload, protocolVersion, recached, serializer, UNKNOWN_LENGTH
Constructor and Description |
---|
Block(NetworkParameters params,
byte[] payloadBytes)
Deprecated.
Use
MessageSerializer.makeBlock(byte[]) instead. |
Block(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.
|
Modifier and Type | Method and Description |
---|---|
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.
|
protected boolean |
checkProofOfWork(boolean throwException)
Returns true if the hash of the block is OK (lower than difficulty target).
|
Block |
cloneAsHeader()
Returns a copy of the block, but without any transactions.
|
protected void |
copyBitcoinHeaderTo(Block block)
Copy the block without transactions into the provided empty block.
|
Block |
createNextBlock(Address to) |
Block |
createNextBlock(Address to,
Coin value) |
Block |
createNextBlock(Address to,
long version,
long time,
int blockHeight)
Returns a solved block that builds on top of this one.
|
Block |
createNextBlock(Address to,
TransactionOutPoint prevOut) |
Block |
createNextBlockWithCoinbase(long version,
byte[] pubKey,
Coin coinbaseValue,
int height) |
boolean |
equals(Object o) |
Coin |
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, or null if this object represents just a header.
|
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() |
boolean |
hasTransactions()
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.
|
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(int height,
EnumSet<Block.VerifyFlag> flags)
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(int height,
EnumSet<Block.VerifyFlag> flags)
Checks the block contents
|
adjustLength, bitcoinSerialize, getMessageSize, getParams, hasMoreBytes, isCached, isRecached, readByteArray, readBytes, readHash, readInt64, readStr, readUint32, readUint64, readVarInt, readVarInt, unsafeBitcoinSerialize
public static final int HEADER_SIZE
public static final int MAX_BLOCK_SIZE
public static final int MAX_BLOCK_SIGOPS
public static final long EASIEST_DIFFICULTY_TARGET
public static final int BLOCK_HEIGHT_UNKNOWN
public static final int BLOCK_HEIGHT_GENESIS
public static final long BLOCK_VERSION_GENESIS
public static final long BLOCK_VERSION_BIP34
public static final long BLOCK_VERSION_BIP66
public static final long BLOCK_VERSION_BIP65
protected boolean headerBytesValid
protected boolean transactionBytesValid
protected int optimalEncodingMessageSize
@Deprecated public Block(NetworkParameters params, byte[] payloadBytes) throws ProtocolException
MessageSerializer.makeBlock(byte[])
instead.ProtocolException
public Block(NetworkParameters params, byte[] payloadBytes, MessageSerializer serializer, int length) throws ProtocolException
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_LENGTHProtocolException
public Block(NetworkParameters params, byte[] payloadBytes, int offset, MessageSerializer serializer, int length) throws ProtocolException
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_LENGTHProtocolException
public Block(NetworkParameters params, byte[] payloadBytes, int offset, @Nullable Message parent, MessageSerializer serializer, int length) throws ProtocolException
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_LENGTHProtocolException
public Block(NetworkParameters params, long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, List<Transaction> transactions)
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.public Coin 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()
.
protected void parseTransactions(int transactionsOffset) throws ProtocolException
transactionsOffset
- Offset of the transactions within the block.
Useful for non-Bitcoin chains where the block header may not be a fixed
size.ProtocolException
protected void parse() throws ProtocolException
parse
in class Message
ProtocolException
public int getOptimalEncodingMessageSize()
public byte[] bitcoinSerialize()
bitcoinSerialize
in class Message
IOException
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException
Message
bitcoinSerializeToStream
in class Message
IOException
protected void unCache()
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.
public String getHashAsString()
public Sha256Hash getHash()
public BigInteger getWork() throws VerificationException
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.
VerificationException
public Block cloneAsHeader()
protected final void copyBitcoinHeaderTo(Block block)
public String toString()
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.
public BigInteger getDifficultyTargetAsInteger() throws VerificationException
VerificationException
protected boolean checkProofOfWork(boolean throwException) throws VerificationException
VerificationException
public void verifyHeader() throws VerificationException
VerificationException
public void verifyTransactions(int height, EnumSet<Block.VerifyFlag> flags) throws VerificationException
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).VerificationException
- if there was an error verifying the block.public void verify(int height, EnumSet<Block.VerifyFlag> flags) throws VerificationException
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).VerificationException
- if there was an error verifying the block.public Sha256Hash getMerkleRoot()
public void addTransaction(Transaction t)
public long getVersion()
public Sha256Hash getPrevBlockHash()
public long getTimeSeconds()
public Date getTime()
public void setTime(long time)
public long getDifficultyTarget()
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.public void setDifficultyTarget(long compactForm)
public long getNonce()
public void setNonce(long nonce)
@Nullable public List<Transaction> getTransactions()
public Block createNextBlock(Address to, long version, long time, int blockHeight)
public Block createNextBlock(@Nullable Address to, TransactionOutPoint prevOut)
public Block createNextBlockWithCoinbase(long version, byte[] pubKey, Coin coinbaseValue, int height)
public boolean hasTransactions()
public boolean isBIP34()
public boolean isBIP66()
public boolean isBIP65()
Copyright © 2016. All rights reserved.