Renamed 'bytes', 'msg' to 'payload' in all Message classes.

* This is intended to clarify distinction between full message and its payload to match terminology advertised on https://en.bitcoin.it/wiki/Protocol_specification.
* Does not change public API.
* These refactorings were mostly automated and should not introduce bugs. All tests pass.
This commit is contained in:
Piotr Włodarek 2014-05-30 18:59:14 +02:00 committed by Mike Hearn
parent a95c2ed826
commit 7f84603e11
19 changed files with 127 additions and 129 deletions

View File

@ -8,7 +8,7 @@ import java.util.List;
/** /**
* Represents an "addr" message on the P2P network, which contains broadcast IP addresses of other peers. This is * Represents an "addr" message on the P2P network, which contains broadcast IP addresses of other peers. This is
* one of the ways peers can find each other without using the DNS or IRC discovery mechansisms. However storing and * one of the ways peers can find each other without using the DNS or IRC discovery mechanisms. However storing and
* using addr messages is not presently implemented. * using addr messages is not presently implemented.
*/ */
public class AddressMessage extends Message { public class AddressMessage extends Message {
@ -20,7 +20,7 @@ public class AddressMessage extends Message {
/** /**
* Contruct a new 'addr' message. * Contruct a new 'addr' message.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then
@ -68,7 +68,7 @@ public class AddressMessage extends Message {
throw new ProtocolException("Address message too large."); throw new ProtocolException("Address message too large.");
addresses = new ArrayList<PeerAddress>((int) numAddresses); addresses = new ArrayList<PeerAddress>((int) numAddresses);
for (int i = 0; i < numAddresses; i++) { for (int i = 0; i < numAddresses; i++) {
PeerAddress addr = new PeerAddress(params, bytes, cursor, protocolVersion, this, parseLazy, parseRetain); PeerAddress addr = new PeerAddress(params, payload, cursor, protocolVersion, this, parseLazy, parseRetain);
addresses.add(addr); addresses.add(addr);
cursor += addr.getMessageSize(); cursor += addr.getMessageSize();
} }

View File

@ -190,7 +190,7 @@ public class Block extends Message {
difficultyTarget = readUint32(); difficultyTarget = readUint32();
nonce = readUint32(); nonce = readUint32();
hash = new Sha256Hash(Utils.reverseBytes(Utils.doubleDigest(bytes, offset, cursor))); hash = new Sha256Hash(Utils.reverseBytes(Utils.doubleDigest(payload, offset, cursor)));
headerParsed = true; headerParsed = true;
headerBytesValid = parseRetain; headerBytesValid = parseRetain;
@ -202,7 +202,7 @@ public class Block extends Message {
cursor = offset + HEADER_SIZE; cursor = offset + HEADER_SIZE;
optimalEncodingMessageSize = HEADER_SIZE; optimalEncodingMessageSize = HEADER_SIZE;
if (bytes.length == cursor) { if (payload.length == cursor) {
// This message is just a header, it has no transactions. // This message is just a header, it has no transactions.
transactionsParsed = true; transactionsParsed = true;
transactionBytesValid = false; transactionBytesValid = false;
@ -213,7 +213,7 @@ public class Block extends Message {
optimalEncodingMessageSize += VarInt.sizeOf(numTransactions); optimalEncodingMessageSize += VarInt.sizeOf(numTransactions);
transactions = new ArrayList<Transaction>(numTransactions); transactions = new ArrayList<Transaction>(numTransactions);
for (int i = 0; i < numTransactions; i++) { for (int i = 0; i < numTransactions; i++) {
Transaction tx = new Transaction(params, bytes, cursor, this, parseLazy, parseRetain, UNKNOWN_LENGTH); Transaction tx = new Transaction(params, payload, cursor, this, parseLazy, parseRetain, UNKNOWN_LENGTH);
// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows. // Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.
tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
transactions.add(tx); transactions.add(tx);
@ -272,12 +272,12 @@ public class Block extends Message {
* the cached header bytes. * the cached header bytes.
*/ */
private void maybeParseHeader() { private void maybeParseHeader() {
if (headerParsed || bytes == null) if (headerParsed || payload == null)
return; return;
try { try {
parseHeader(); parseHeader();
if (!(headerBytesValid || transactionBytesValid)) if (!(headerBytesValid || transactionBytesValid))
bytes = null; payload = null;
} catch (ProtocolException e) { } catch (ProtocolException e) {
throw new LazyParseException( throw new LazyParseException(
"ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access", "ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access",
@ -286,14 +286,14 @@ public class Block extends Message {
} }
private void maybeParseTransactions() { private void maybeParseTransactions() {
if (transactionsParsed || bytes == null) if (transactionsParsed || payload == null)
return; return;
try { try {
parseTransactions(); parseTransactions();
if (!parseRetain) { if (!parseRetain) {
transactionBytesValid = false; transactionBytesValid = false;
if (headerParsed) if (headerParsed)
bytes = null; payload = null;
} }
} catch (ProtocolException e) { } catch (ProtocolException e) {
throw new LazyParseException( throw new LazyParseException(
@ -377,8 +377,8 @@ public class Block extends Message {
// default for testing // default for testing
void writeHeader(OutputStream stream) throws IOException { void writeHeader(OutputStream stream) throws IOException {
// try for cached write first // try for cached write first
if (headerBytesValid && bytes != null && bytes.length >= offset + HEADER_SIZE) { if (headerBytesValid && payload != null && payload.length >= offset + HEADER_SIZE) {
stream.write(bytes, offset, HEADER_SIZE); stream.write(payload, offset, HEADER_SIZE);
return; return;
} }
// fall back to manual write // fall back to manual write
@ -399,8 +399,8 @@ public class Block extends Message {
} }
// confirmed we must have transactions either cached or as objects. // confirmed we must have transactions either cached or as objects.
if (transactionBytesValid && bytes != null && bytes.length >= offset + length) { if (transactionBytesValid && payload != null && payload.length >= offset + length) {
stream.write(bytes, offset + HEADER_SIZE, length - HEADER_SIZE); stream.write(payload, offset + HEADER_SIZE, length - HEADER_SIZE);
return; return;
} }
@ -422,13 +422,13 @@ public class Block extends Message {
public byte[] bitcoinSerialize() { public byte[] bitcoinSerialize() {
// we have completely cached byte array. // we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) { if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(bytes, "Bytes should never be null if headerBytesValid && transactionBytesValid"); Preconditions.checkNotNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == bytes.length) { if (length == payload.length) {
return bytes; return payload;
} else { } else {
// byte array is offset so copy out the correct range. // byte array is offset so copy out the correct range.
byte[] buf = new byte[length]; byte[] buf = new byte[length];
System.arraycopy(bytes, offset, buf, 0, length); System.arraycopy(payload, offset, buf, 0, length);
return buf; return buf;
} }
} }
@ -462,7 +462,7 @@ public class Block extends Message {
*/ */
private int guessTransactionsLength() { private int guessTransactionsLength() {
if (transactionBytesValid) if (transactionBytesValid)
return bytes.length - HEADER_SIZE; return payload.length - HEADER_SIZE;
if (transactions == null) if (transactions == null)
return 0; return 0;
int len = VarInt.sizeOf(transactions.size()); int len = VarInt.sizeOf(transactions.size());
@ -484,7 +484,7 @@ public class Block extends Message {
maybeParseHeader(); maybeParseHeader();
headerBytesValid = false; headerBytesValid = false;
if (!transactionBytesValid) if (!transactionBytesValid)
bytes = null; payload = null;
hash = null; hash = null;
checksum = null; checksum = null;
} }
@ -493,7 +493,7 @@ public class Block extends Message {
maybeParseTransactions(); maybeParseTransactions();
transactionBytesValid = false; transactionBytesValid = false;
if (!headerBytesValid) if (!headerBytesValid)
bytes = null; payload = null;
// Current implementation has to uncache headers as well as any change to a tx will alter the merkle root. In // Current implementation has to uncache headers as well as any change to a tx will alter the merkle root. In
// future we can go more granular and cache merkle root separately so rest of the header does not need to be // future we can go more granular and cache merkle root separately so rest of the header does not need to be
// rewritten. // rewritten.

View File

@ -35,23 +35,23 @@ public abstract class ChildMessage extends Message {
super(params); super(params);
} }
public ChildMessage(NetworkParameters params, byte[] msg, int offset, int protocolVersion) throws ProtocolException { public ChildMessage(NetworkParameters params, byte[] payload, int offset, int protocolVersion) throws ProtocolException {
super(params, msg, offset, protocolVersion); super(params, payload, offset, protocolVersion);
} }
public ChildMessage(NetworkParameters params, byte[] msg, int offset, int protocolVersion, Message parent, boolean parseLazy, public ChildMessage(NetworkParameters params, byte[] payload, int offset, int protocolVersion, Message parent, boolean parseLazy,
boolean parseRetain, int length) throws ProtocolException { boolean parseRetain, int length) throws ProtocolException {
super(params, msg, offset, protocolVersion, parseLazy, parseRetain, length); super(params, payload, offset, protocolVersion, parseLazy, parseRetain, length);
this.parent = parent; this.parent = parent;
} }
public ChildMessage(NetworkParameters params, byte[] msg, int offset) throws ProtocolException { public ChildMessage(NetworkParameters params, byte[] payload, int offset) throws ProtocolException {
super(params, msg, offset); super(params, payload, offset);
} }
public ChildMessage(NetworkParameters params, byte[] msg, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) public ChildMessage(NetworkParameters params, byte[] payload, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, offset, parseLazy, parseRetain, length); super(params, payload, offset, parseLazy, parseRetain, length);
this.parent = parent; this.parent = parent;
} }

View File

@ -34,8 +34,8 @@ public abstract class EmptyMessage extends Message {
length = 0; length = 0;
} }
public EmptyMessage(NetworkParameters params, byte[] msg, int offset) throws ProtocolException { public EmptyMessage(NetworkParameters params, byte[] payload, int offset) throws ProtocolException {
super(params, msg, offset); super(params, payload, offset);
length = 0; length = 0;
} }

View File

@ -53,10 +53,10 @@ public class FilteredBlock extends Message {
@Override @Override
void parse() throws ProtocolException { void parse() throws ProtocolException {
byte[] headerBytes = new byte[Block.HEADER_SIZE]; byte[] headerBytes = new byte[Block.HEADER_SIZE];
System.arraycopy(bytes, 0, headerBytes, 0, Block.HEADER_SIZE); System.arraycopy(payload, 0, headerBytes, 0, Block.HEADER_SIZE);
header = new Block(params, headerBytes); header = new Block(params, headerBytes);
merkleTree = new PartialMerkleTree(params, bytes, Block.HEADER_SIZE); merkleTree = new PartialMerkleTree(params, payload, Block.HEADER_SIZE);
length = Block.HEADER_SIZE + merkleTree.getMessageSize(); length = Block.HEADER_SIZE + merkleTree.getMessageSize();
} }

View File

@ -38,8 +38,8 @@ public class GetBlocksMessage extends Message {
this.stopHash = stopHash; this.stopHash = stopHash;
} }
public GetBlocksMessage(NetworkParameters params, byte[] msg) throws ProtocolException { public GetBlocksMessage(NetworkParameters params, byte[] payload) throws ProtocolException {
super(params, msg, 0); super(params, payload, 0);
} }
@Override @Override

View File

@ -30,7 +30,7 @@ public class GetDataMessage extends ListMessage {
/** /**
* Deserializes a 'getdata' message. * Deserializes a 'getdata' message.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then
@ -39,9 +39,9 @@ public class GetDataMessage extends ListMessage {
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException * @throws ProtocolException
*/ */
public GetDataMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length) public GetDataMessage(NetworkParameters params, byte[] payload, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, parseLazy, parseRetain, length); super(params, payload, parseLazy, parseRetain, length);
} }
public GetDataMessage(NetworkParameters params) { public GetDataMessage(NetworkParameters params) {

View File

@ -29,8 +29,8 @@ public class GetHeadersMessage extends GetBlocksMessage {
super(params, locator, stopHash); super(params, locator, stopHash);
} }
public GetHeadersMessage(NetworkParameters params, byte[] msg) throws ProtocolException { public GetHeadersMessage(NetworkParameters params, byte[] payload) throws ProtocolException {
super(params, msg); super(params, payload);
} }
@Override @Override

View File

@ -34,7 +34,7 @@ public class InventoryMessage extends ListMessage {
/** /**
* Deserializes an 'inv' message. * Deserializes an 'inv' message.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then
@ -43,9 +43,9 @@ public class InventoryMessage extends ListMessage {
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException * @throws ProtocolException
*/ */
public InventoryMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length) public InventoryMessage(NetworkParameters params, byte[] payload, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, parseLazy, parseRetain, length); super(params, payload, parseLazy, parseRetain, length);
} }
public InventoryMessage(NetworkParameters params) { public InventoryMessage(NetworkParameters params) {

View File

@ -38,9 +38,9 @@ public abstract class ListMessage extends Message {
super(params, bytes, 0); super(params, bytes, 0);
} }
public ListMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length) public ListMessage(NetworkParameters params, byte[] payload, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, 0, parseLazy, parseRetain, length); super(params, payload, 0, parseLazy, parseRetain, length);
} }
public ListMessage(NetworkParameters params) { public ListMessage(NetworkParameters params) {
@ -81,7 +81,7 @@ public abstract class ListMessage extends Message {
// An inv is vector<CInv> where CInv is int+hash. The int is either 1 or 2 for tx or block. // An inv is vector<CInv> where CInv is int+hash. The int is either 1 or 2 for tx or block.
items = new ArrayList<InventoryItem>((int) arrayLen); items = new ArrayList<InventoryItem>((int) arrayLen);
for (int i = 0; i < arrayLen; i++) { for (int i = 0; i < arrayLen; i++) {
if (cursor + InventoryItem.MESSAGE_LENGTH > bytes.length) { if (cursor + InventoryItem.MESSAGE_LENGTH > payload.length) {
throw new ProtocolException("Ran off the end of the INV"); throw new ProtocolException("Ran off the end of the INV");
} }
int typeCode = (int) readUint32(); int typeCode = (int) readUint32();
@ -106,7 +106,7 @@ public abstract class ListMessage extends Message {
InventoryItem item = new InventoryItem(type, readHash()); InventoryItem item = new InventoryItem(type, readHash());
items.add(item); items.add(item);
} }
bytes = null; payload = null;
} }
@Override @Override

View File

@ -41,16 +41,16 @@ public abstract class Message implements Serializable {
// Useful to ensure serialize/deserialize are consistent with each other. // Useful to ensure serialize/deserialize are consistent with each other.
private static final boolean SELF_CHECK = false; private static final boolean SELF_CHECK = false;
// The offset is how many bytes into the provided byte array this message starts at. // The offset is how many bytes into the provided byte array this message payload starts at.
protected transient int offset; protected transient int offset;
// The cursor keeps track of where we are in the byte array as we parse it. // The cursor keeps track of where we are in the byte array as we parse it.
// Note that it's relative to the start of the array NOT the start of the message. // Note that it's relative to the start of the array NOT the start of the message payload.
protected transient int cursor; protected transient int cursor;
protected transient int length = UNKNOWN_LENGTH; protected transient int length = UNKNOWN_LENGTH;
// The raw message bytes themselves. // The raw message payload bytes themselves.
protected transient byte[] bytes; protected transient byte[] payload;
protected transient boolean parsed = false; protected transient boolean parsed = false;
protected transient boolean recached = false; protected transient boolean recached = false;
@ -80,30 +80,30 @@ public abstract class Message implements Serializable {
parseRetain = false; parseRetain = false;
} }
Message(NetworkParameters params, byte[] msg, int offset, int protocolVersion) throws ProtocolException { Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion) throws ProtocolException {
this(params, msg, offset, protocolVersion, false, false, UNKNOWN_LENGTH); this(params, payload, offset, protocolVersion, false, false, UNKNOWN_LENGTH);
} }
/** /**
* *
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param protocolVersion Bitcoin protocol version. * @param protocolVersion Bitcoin protocol version.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * 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. * the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire * @param length The length of message payload 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 * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException * @throws ProtocolException
*/ */
Message(NetworkParameters params, byte[] msg, int offset, int protocolVersion, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { Message(NetworkParameters params, byte[] payload, int offset, int protocolVersion, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException {
this.parseLazy = parseLazy; this.parseLazy = parseLazy;
this.parseRetain = parseRetain; this.parseRetain = parseRetain;
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
this.params = params; this.params = params;
this.bytes = msg; this.payload = payload;
this.cursor = this.offset = offset; this.cursor = this.offset = offset;
this.length = length; this.length = length;
if (parseLazy) { if (parseLazy) {
@ -120,33 +120,33 @@ public abstract class Message implements Serializable {
getClass().getSimpleName(), parseLazy ? "lite" : "full"); getClass().getSimpleName(), parseLazy ? "lite" : "full");
if (SELF_CHECK) { if (SELF_CHECK) {
selfCheck(msg, offset); selfCheck(payload, offset);
} }
if (parseRetain || !parsed) if (parseRetain || !parsed)
return; return;
this.bytes = null; this.payload = null;
} }
private void selfCheck(byte[] msg, int offset) { private void selfCheck(byte[] payload, int offset) {
if (!(this instanceof VersionMessage)) { if (!(this instanceof VersionMessage)) {
maybeParse(); maybeParse();
byte[] msgbytes = new byte[cursor - offset]; byte[] payloadBytes = new byte[cursor - offset];
System.arraycopy(msg, offset, msgbytes, 0, cursor - offset); System.arraycopy(payload, offset, payloadBytes, 0, cursor - offset);
byte[] reserialized = bitcoinSerialize(); byte[] reserialized = bitcoinSerialize();
if (!Arrays.equals(reserialized, msgbytes)) if (!Arrays.equals(reserialized, payloadBytes))
throw new RuntimeException("Serialization is wrong: \n" + throw new RuntimeException("Serialization is wrong: \n" +
Utils.bytesToHexString(reserialized) + " vs \n" + Utils.bytesToHexString(reserialized) + " vs \n" +
Utils.bytesToHexString(msgbytes)); Utils.bytesToHexString(payloadBytes));
} }
} }
Message(NetworkParameters params, byte[] msg, int offset) throws ProtocolException { Message(NetworkParameters params, byte[] payload, int offset) throws ProtocolException {
this(params, msg, offset, NetworkParameters.PROTOCOL_VERSION, false, false, UNKNOWN_LENGTH); this(params, payload, offset, NetworkParameters.PROTOCOL_VERSION, false, false, UNKNOWN_LENGTH);
} }
Message(NetworkParameters params, byte[] msg, int offset, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { Message(NetworkParameters params, byte[] payload, int offset, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException {
this(params, msg, offset, NetworkParameters.PROTOCOL_VERSION, parseLazy, parseRetain, length); this(params, payload, offset, NetworkParameters.PROTOCOL_VERSION, parseLazy, parseRetain, length);
} }
// These methods handle the serialization/deserialization using the custom Bitcoin protocol. // These methods handle the serialization/deserialization using the custom Bitcoin protocol.
@ -156,7 +156,7 @@ public abstract class Message implements Serializable {
abstract void parse() throws ProtocolException; abstract void parse() throws ProtocolException;
/** /**
* Perform the most minimal parse possible to calculate the length of the message. * Perform the most minimal parse possible to calculate the length of the message payload.
* This is only required for subclasses of ChildMessage as root level messages will have their length passed * This is only required for subclasses of ChildMessage as root level messages will have their length passed
* into the constructor. * into the constructor.
* <p/> * <p/>
@ -175,13 +175,13 @@ public abstract class Message implements Serializable {
* If the lazy parse flag is not set this is a method returns immediately. * If the lazy parse flag is not set this is a method returns immediately.
*/ */
protected synchronized void maybeParse() { protected synchronized void maybeParse() {
if (parsed || bytes == null) if (parsed || payload == null)
return; return;
try { try {
parse(); parse();
parsed = true; parsed = true;
if (!parseRetain) if (!parseRetain)
bytes = null; payload = null;
} catch (ProtocolException e) { } catch (ProtocolException e) {
throw new LazyParseException("ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access", e); throw new LazyParseException("ProtocolException caught during lazy parse. For safe access to fields call ensureParsed before attempting read or write access", e);
} }
@ -216,7 +216,7 @@ public abstract class Message implements Serializable {
protected void unCache() { protected void unCache() {
maybeParse(); maybeParse();
checksum = null; checksum = null;
bytes = null; payload = null;
recached = false; recached = false;
} }
@ -247,8 +247,7 @@ public abstract class Message implements Serializable {
* used for unit testing * used for unit testing
*/ */
public boolean isCached() { public boolean isCached() {
//return parseLazy ? parsed && bytes != null : bytes != null; return payload != null;
return bytes != null;
} }
public boolean isRecached() { public boolean isRecached() {
@ -307,15 +306,15 @@ public abstract class Message implements Serializable {
*/ */
public byte[] unsafeBitcoinSerialize() { public byte[] unsafeBitcoinSerialize() {
// 1st attempt to use a cached array. // 1st attempt to use a cached array.
if (bytes != null) { if (payload != null) {
if (offset == 0 && length == bytes.length) { if (offset == 0 && length == payload.length) {
// Cached byte array is the entire message with no extras so we can return as is and avoid an array // Cached byte array is the entire message with no extras so we can return as is and avoid an array
// copy. // copy.
return bytes; return payload;
} }
byte[] buf = new byte[length]; byte[] buf = new byte[length];
System.arraycopy(bytes, offset, buf, 0, length); System.arraycopy(payload, offset, buf, 0, length);
return buf; return buf;
} }
@ -336,12 +335,12 @@ public abstract class Message implements Serializable {
// merkle root calls this method. It is will frequently happen prior to serializing the block // merkle root calls this method. It is will frequently happen prior to serializing the block
// which means another call to bitcoinSerialize is coming. If we didn't recache then internal // which means another call to bitcoinSerialize is coming. If we didn't recache then internal
// serialization would occur a 2nd time and every subsequent time the message is serialized. // serialization would occur a 2nd time and every subsequent time the message is serialized.
bytes = stream.toByteArray(); payload = stream.toByteArray();
cursor = cursor - offset; cursor = cursor - offset;
offset = 0; offset = 0;
recached = true; recached = true;
length = bytes.length; length = payload.length;
return bytes; return payload;
} }
// Record length. If this Message wasn't parsed from a byte stream it won't have length field // Record length. If this Message wasn't parsed from a byte stream it won't have length field
// set (except for static length message types). Setting it makes future streaming more efficient // set (except for static length message types). Setting it makes future streaming more efficient
@ -359,8 +358,8 @@ public abstract class Message implements Serializable {
*/ */
final public void bitcoinSerialize(OutputStream stream) throws IOException { final public void bitcoinSerialize(OutputStream stream) throws IOException {
// 1st check for cached bytes. // 1st check for cached bytes.
if (bytes != null && length != UNKNOWN_LENGTH) { if (payload != null && length != UNKNOWN_LENGTH) {
stream.write(bytes, offset, length); stream.write(payload, offset, length);
return; return;
} }
@ -399,7 +398,7 @@ public abstract class Message implements Serializable {
long readUint32() throws ProtocolException { long readUint32() throws ProtocolException {
try { try {
long u = Utils.readUint32(bytes, cursor); long u = Utils.readUint32(payload, cursor);
cursor += 4; cursor += 4;
return u; return u;
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
@ -410,7 +409,7 @@ public abstract class Message implements Serializable {
Sha256Hash readHash() throws ProtocolException { Sha256Hash readHash() throws ProtocolException {
try { try {
byte[] hash = new byte[32]; byte[] hash = new byte[32];
System.arraycopy(bytes, cursor, hash, 0, 32); System.arraycopy(payload, cursor, hash, 0, 32);
// We have to flip it around, as it's been read off the wire in little endian. // We have to flip it around, as it's been read off the wire in little endian.
// Not the most efficient way to do this but the clearest. // Not the most efficient way to do this but the clearest.
hash = Utils.reverseBytes(hash); hash = Utils.reverseBytes(hash);
@ -423,7 +422,7 @@ public abstract class Message implements Serializable {
long readInt64() throws ProtocolException { long readInt64() throws ProtocolException {
try { try {
long u = Utils.readInt64(bytes, cursor); long u = Utils.readInt64(payload, cursor);
cursor += 8; cursor += 8;
return u; return u;
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
@ -435,7 +434,7 @@ public abstract class Message implements Serializable {
try { try {
// Java does not have an unsigned 64 bit type. So scrape it off the wire then flip. // Java does not have an unsigned 64 bit type. So scrape it off the wire then flip.
byte[] valbytes = new byte[8]; byte[] valbytes = new byte[8];
System.arraycopy(bytes, cursor, valbytes, 0, 8); System.arraycopy(payload, cursor, valbytes, 0, 8);
valbytes = Utils.reverseBytes(valbytes); valbytes = Utils.reverseBytes(valbytes);
cursor += valbytes.length; cursor += valbytes.length;
return new BigInteger(valbytes); return new BigInteger(valbytes);
@ -450,7 +449,7 @@ public abstract class Message implements Serializable {
long readVarInt(int offset) throws ProtocolException { long readVarInt(int offset) throws ProtocolException {
try { try {
VarInt varint = new VarInt(bytes, cursor + offset); VarInt varint = new VarInt(payload, cursor + offset);
cursor += offset + varint.getOriginalSizeInBytes(); cursor += offset + varint.getOriginalSizeInBytes();
return varint.value; return varint.value;
} catch (ArrayIndexOutOfBoundsException e) { } catch (ArrayIndexOutOfBoundsException e) {
@ -462,7 +461,7 @@ public abstract class Message implements Serializable {
byte[] readBytes(int length) throws ProtocolException { byte[] readBytes(int length) throws ProtocolException {
try { try {
byte[] b = new byte[length]; byte[] b = new byte[length];
System.arraycopy(bytes, cursor, b, 0, length); System.arraycopy(payload, cursor, b, 0, length);
cursor += length; cursor += length;
return b; return b;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
@ -477,14 +476,14 @@ public abstract class Message implements Serializable {
String readStr() throws ProtocolException { String readStr() throws ProtocolException {
try { try {
VarInt varInt = new VarInt(bytes, cursor); VarInt varInt = new VarInt(payload, cursor);
if (varInt.value == 0) { if (varInt.value == 0) {
cursor += 1; cursor += 1;
return ""; return "";
} }
cursor += varInt.getOriginalSizeInBytes(); cursor += varInt.getOriginalSizeInBytes();
byte[] characters = new byte[(int) varInt.value]; byte[] characters = new byte[(int) varInt.value];
System.arraycopy(bytes, cursor, characters, 0, characters.length); System.arraycopy(payload, cursor, characters, 0, characters.length);
cursor += characters.length; cursor += characters.length;
try { try {
return new String(characters, "UTF-8"); return new String(characters, "UTF-8");
@ -499,7 +498,7 @@ public abstract class Message implements Serializable {
} }
boolean hasMoreBytes() { boolean hasMoreBytes() {
return cursor < bytes.length; return cursor < payload.length;
} }
/** Network parameters this message was created with. */ /** Network parameters this message was created with. */

View File

@ -52,8 +52,8 @@ public class PeerAddress extends ChildMessage {
/** /**
* Construct a peer address from a serialized payload. * Construct a peer address from a serialized payload.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param protocolVersion Bitcoin protocol version. * @param protocolVersion Bitcoin protocol version.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param parseRetain Whether to retain the backing byte array for quick reserialization.
@ -61,9 +61,9 @@ public class PeerAddress extends ChildMessage {
* the cached bytes may be repopulated and retained if the message is serialized again in the future. * the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @throws ProtocolException * @throws ProtocolException
*/ */
public PeerAddress(NetworkParameters params, byte[] msg, int offset, int protocolVersion, Message parent, boolean parseLazy, public PeerAddress(NetworkParameters params, byte[] payload, int offset, int protocolVersion, Message parent, boolean parseLazy,
boolean parseRetain) throws ProtocolException { boolean parseRetain) throws ProtocolException {
super(params, msg, offset, protocolVersion, parent, parseLazy, parseRetain, UNKNOWN_LENGTH); super(params, payload, offset, protocolVersion, parent, parseLazy, parseRetain, UNKNOWN_LENGTH);
// Message length is calculated in parseLite which is guaranteed to be called before it is ever read. // Message length is calculated in parseLite which is guaranteed to be called before it is ever read.
// Even though message length is static for a PeerAddress it is safer to leave it there // Even though message length is static for a PeerAddress it is safer to leave it there
// as it will be set regardless of which constructor was used. // as it will be set regardless of which constructor was used.
@ -155,7 +155,7 @@ public class PeerAddress extends ChildMessage {
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
throw new RuntimeException(e); // Cannot happen. throw new RuntimeException(e); // Cannot happen.
} }
port = ((0xFF & bytes[cursor++]) << 8) | (0xFF & bytes[cursor++]); port = ((0xFF & payload[cursor++]) << 8) | (0xFF & payload[cursor++]);
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@ -68,13 +68,12 @@ public class RejectMessage extends Message {
private RejectCode code; private RejectCode code;
private Sha256Hash messageHash; private Sha256Hash messageHash;
public RejectMessage(NetworkParameters params, byte[] bytes) throws ProtocolException { public RejectMessage(NetworkParameters params, byte[] payload) throws ProtocolException {
super(params, bytes, 0); super(params, payload, 0);
} }
public RejectMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length) public RejectMessage(NetworkParameters params, byte[] payload, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException {
throws ProtocolException { super(params, payload, 0, parseLazy, parseRetain, length);
super(params, msg, 0, parseLazy, parseRetain, length);
} }
@Override @Override

View File

@ -184,8 +184,8 @@ public class Transaction extends ChildMessage implements Serializable {
/** /**
* Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed. * Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then
@ -194,17 +194,17 @@ public class Transaction extends ChildMessage implements Serializable {
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException * @throws ProtocolException
*/ */
public Transaction(NetworkParameters params, byte[] msg, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) public Transaction(NetworkParameters params, byte[] payload, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, offset, parent, parseLazy, parseRetain, length); super(params, payload, offset, parent, parseLazy, parseRetain, length);
} }
/** /**
* Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed. * Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
*/ */
public Transaction(NetworkParameters params, byte[] msg, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) public Transaction(NetworkParameters params, byte[] payload, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException { throws ProtocolException {
super(params, msg, 0, parent, parseLazy, parseRetain, length); super(params, payload, 0, parent, parseLazy, parseRetain, length);
} }
/** /**
@ -497,7 +497,7 @@ public class Transaction extends ChildMessage implements Serializable {
//parse(); //parse();
//parsed = true; //parsed = true;
length = calcLength(bytes, offset); length = calcLength(payload, offset);
cursor = offset + length; cursor = offset + length;
} }
} }
@ -554,7 +554,7 @@ public class Transaction extends ChildMessage implements Serializable {
optimalEncodingMessageSize += VarInt.sizeOf(numInputs); optimalEncodingMessageSize += VarInt.sizeOf(numInputs);
inputs = new ArrayList<TransactionInput>((int) numInputs); inputs = new ArrayList<TransactionInput>((int) numInputs);
for (long i = 0; i < numInputs; i++) { for (long i = 0; i < numInputs; i++) {
TransactionInput input = new TransactionInput(params, this, bytes, cursor, parseLazy, parseRetain); TransactionInput input = new TransactionInput(params, this, payload, cursor, parseLazy, parseRetain);
inputs.add(input); inputs.add(input);
long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH); long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH);
optimalEncodingMessageSize += TransactionOutPoint.MESSAGE_LENGTH + VarInt.sizeOf(scriptLen) + scriptLen + 4; optimalEncodingMessageSize += TransactionOutPoint.MESSAGE_LENGTH + VarInt.sizeOf(scriptLen) + scriptLen + 4;
@ -565,7 +565,7 @@ public class Transaction extends ChildMessage implements Serializable {
optimalEncodingMessageSize += VarInt.sizeOf(numOutputs); optimalEncodingMessageSize += VarInt.sizeOf(numOutputs);
outputs = new ArrayList<TransactionOutput>((int) numOutputs); outputs = new ArrayList<TransactionOutput>((int) numOutputs);
for (long i = 0; i < numOutputs; i++) { for (long i = 0; i < numOutputs; i++) {
TransactionOutput output = new TransactionOutput(params, this, bytes, cursor, parseLazy, parseRetain); TransactionOutput output = new TransactionOutput(params, this, payload, cursor, parseLazy, parseRetain);
outputs.add(output); outputs.add(output);
long scriptLen = readVarInt(8); long scriptLen = readVarInt(8);
optimalEncodingMessageSize += 8 + VarInt.sizeOf(scriptLen) + scriptLen; optimalEncodingMessageSize += 8 + VarInt.sizeOf(scriptLen) + scriptLen;

View File

@ -111,8 +111,8 @@ public class TransactionInput extends ChildMessage implements Serializable {
/** /**
* Deserializes an input message. This is usually part of a transaction message. * Deserializes an input message. This is usually part of a transaction message.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then
@ -120,10 +120,10 @@ public class TransactionInput extends ChildMessage implements Serializable {
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException * @throws ProtocolException
*/ */
public TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] msg, int offset, public TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] payload, int offset,
boolean parseLazy, boolean parseRetain) boolean parseLazy, boolean parseRetain)
throws ProtocolException { throws ProtocolException {
super(params, msg, offset, parentTransaction, parseLazy, parseRetain, UNKNOWN_LENGTH); super(params, payload, offset, parentTransaction, parseLazy, parseRetain, UNKNOWN_LENGTH);
this.parentTransaction = parentTransaction; this.parentTransaction = parentTransaction;
this.value = null; this.value = null;
} }
@ -138,7 +138,7 @@ public class TransactionInput extends ChildMessage implements Serializable {
@Override @Override
void parse() throws ProtocolException { void parse() throws ProtocolException {
outpoint = new TransactionOutPoint(params, bytes, cursor, this, parseLazy, parseRetain); outpoint = new TransactionOutPoint(params, payload, cursor, this, parseLazy, parseRetain);
cursor += outpoint.getMessageSize(); cursor += outpoint.getMessageSize();
int scriptLen = (int) readVarInt(); int scriptLen = (int) readVarInt();
scriptBytes = readBytes(scriptLen); scriptBytes = readBytes(scriptLen);

View File

@ -76,7 +76,7 @@ public class TransactionOutPoint extends ChildMessage implements Serializable {
/** /**
* Deserializes the message. This is usually part of a transaction message. * Deserializes the message. This is usually part of a transaction message.
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * If true and the backing byte array is invalidated due to modification of a field then

View File

@ -74,17 +74,17 @@ public class TransactionOutput extends ChildMessage implements Serializable {
* Deserializes a transaction output message. This is usually part of a transaction message. * Deserializes a transaction output message. This is usually part of a transaction message.
* *
* @param params NetworkParameters object. * @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content. * @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array. * @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization. * @param 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 * 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. * the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @throws ProtocolException * @throws ProtocolException
*/ */
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] msg, int offset, public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset,
boolean parseLazy, boolean parseRetain) throws ProtocolException { boolean parseLazy, boolean parseRetain) throws ProtocolException {
super(params, msg, offset, parent, parseLazy, parseRetain, UNKNOWN_LENGTH); super(params, payload, offset, parent, parseLazy, parseRetain, UNKNOWN_LENGTH);
parentTransaction = parent; parentTransaction = parent;
availableForSpending = true; availableForSpending = true;
} }

View File

@ -27,7 +27,7 @@ public class UnknownMessage extends EmptyMessage {
@Override @Override
public String toString() { public String toString() {
return "Unknown message [" + name + "]: " + (bytes == null ? "" : Utils.bytesToHexString(bytes)); return "Unknown message [" + name + "]: " + (payload == null ? "" : Utils.bytesToHexString(payload));
} }
} }

View File

@ -78,8 +78,8 @@ public class VersionMessage extends Message {
/** The value that is prepended to the subVer field of this application. */ /** The value that is prepended to the subVer field of this application. */
public static final String LIBRARY_SUBVER = "/BitCoinJ:" + BITCOINJ_VERSION + "/"; public static final String LIBRARY_SUBVER = "/BitCoinJ:" + BITCOINJ_VERSION + "/";
public VersionMessage(NetworkParameters params, byte[] msg) throws ProtocolException { public VersionMessage(NetworkParameters params, byte[] payload) throws ProtocolException {
super(params, msg, 0); super(params, payload, 0);
} }
// It doesn't really make sense to ever lazily parse a version message or to retain the backing bytes. // It doesn't really make sense to ever lazily parse a version message or to retain the backing bytes.
@ -131,9 +131,9 @@ public class VersionMessage extends Message {
clientVersion = (int) readUint32(); clientVersion = (int) readUint32();
localServices = readUint64().longValue(); localServices = readUint64().longValue();
time = readUint64().longValue(); time = readUint64().longValue();
myAddr = new PeerAddress(params, bytes, cursor, 0); myAddr = new PeerAddress(params, payload, cursor, 0);
cursor += myAddr.getMessageSize(); cursor += myAddr.getMessageSize();
theirAddr = new PeerAddress(params, bytes, cursor, 0); theirAddr = new PeerAddress(params, payload, cursor, 0);
cursor += theirAddr.getMessageSize(); cursor += theirAddr.getMessageSize();
// uint64 localHostNonce (random data) // uint64 localHostNonce (random data)
// We don't care about the localhost nonce. It's used to detect connecting back to yourself in cases where // We don't care about the localhost nonce. It's used to detect connecting back to yourself in cases where