mirror of
https://github.com/Qortal/altcoinj.git
synced 2025-01-31 07:12:17 +00:00
Reformat the codebase, this is pretty much whatever IntelliJ thinks the code should look like.
This will unfortunately break all patches, but it has to be done at some point.
This commit is contained in:
parent
84f738763f
commit
fb5915e4c4
@ -22,7 +22,6 @@ package com.google.bitcoin.core;
|
||||
* <p>The default method implementations do nothing.
|
||||
*
|
||||
* @author miron@google.com (Miron Cuperman)
|
||||
*
|
||||
*/
|
||||
public class AbstractPeerEventListener extends Object implements PeerEventListener {
|
||||
public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) {
|
||||
|
@ -16,8 +16,6 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* A BitCoin address is fundamentally derived from an elliptic curve public key and a set of network parameters.
|
||||
* It has several possible representations:<p>
|
||||
|
@ -42,7 +42,7 @@ public class AddressMessage extends Message {
|
||||
// Guard against ultra large messages that will crash us.
|
||||
if (numAddresses > MAX_ADDRESSES)
|
||||
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++) {
|
||||
PeerAddress addr = new PeerAddress(params, bytes, cursor, protocolVersion, this, parseLazy, parseRetain);
|
||||
addresses.add(addr);
|
||||
@ -59,7 +59,7 @@ public class AddressMessage extends Message {
|
||||
if (addresses == null)
|
||||
return;
|
||||
stream.write(new VarInt(addresses.size()).encode());
|
||||
for (PeerAddress addr: addresses) {
|
||||
for (PeerAddress addr : addresses) {
|
||||
addr.bitcoinSerialize(stream);
|
||||
}
|
||||
|
||||
@ -101,7 +101,8 @@ public class AddressMessage extends Message {
|
||||
if (length == UNKNOWN_LENGTH)
|
||||
getMessageSize();
|
||||
else
|
||||
length += address.getMessageSize();;
|
||||
length += address.getMessageSize();
|
||||
;
|
||||
}
|
||||
|
||||
public void removeAddress(int index) {
|
||||
|
@ -55,7 +55,7 @@ public class BitcoinSerializer {
|
||||
private boolean parseLazy = false;
|
||||
private boolean parseRetain = false;
|
||||
|
||||
private static Map<Class<? extends Message>, String> names = new HashMap<Class<? extends Message>,String>();
|
||||
private static Map<Class<? extends Message>, String> names = new HashMap<Class<? extends Message>, String>();
|
||||
|
||||
static {
|
||||
names.put(VersionMessage.class, "version");
|
||||
@ -142,7 +142,7 @@ public class BitcoinSerializer {
|
||||
public void serialize(Message message, OutputStream out) throws IOException {
|
||||
String name = names.get(message.getClass());
|
||||
if (name == null) {
|
||||
throw new Error("BitcoinSerializer doesn't currently know how to serialize "+ message.getClass());
|
||||
throw new Error("BitcoinSerializer doesn't currently know how to serialize " + message.getClass());
|
||||
}
|
||||
|
||||
byte[] header = new byte[4 + COMMAND_LEN + 4 + (usesChecksumming ? 4 : 0)];
|
||||
@ -348,7 +348,7 @@ public class BitcoinSerializer {
|
||||
}
|
||||
// We're looking for a run of bytes that is the same as the packet magic but we want to ignore partial
|
||||
// magics that aren't complete. So we keep track of where we're up to with magicCursor.
|
||||
int expectedByte = 0xFF & (int)(params.packetMagic >>> (magicCursor * 8));
|
||||
int expectedByte = 0xFF & (int) (params.packetMagic >>> (magicCursor * 8));
|
||||
if (b == expectedByte) {
|
||||
magicCursor--;
|
||||
if (magicCursor < 0) {
|
||||
@ -378,7 +378,6 @@ public class BitcoinSerializer {
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class BitcoinPacketHeader {
|
||||
final byte[] header;
|
||||
final String command;
|
||||
@ -402,7 +401,7 @@ public class BitcoinSerializer {
|
||||
// The command is a NULL terminated string, unless the command fills all twelve bytes
|
||||
// in which case the termination is implicit.
|
||||
int mark = cursor;
|
||||
for (; header[cursor] != 0 && cursor - mark < COMMAND_LEN; cursor++);
|
||||
for (; header[cursor] != 0 && cursor - mark < COMMAND_LEN; cursor++) ;
|
||||
byte[] commandBytes = new byte[cursor - mark];
|
||||
System.arraycopy(header, mark, commandBytes, 0, cursor - mark);
|
||||
try {
|
||||
|
@ -16,27 +16,29 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
|
||||
|
||||
import static com.google.bitcoin.core.Utils.*;
|
||||
import static com.google.bitcoin.core.Utils.doubleDigest;
|
||||
import static com.google.bitcoin.core.Utils.doubleDigestTwoBuffers;
|
||||
|
||||
/**
|
||||
* A block is the foundation of the BitCoin system. It records a set of
|
||||
* {@link 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.
|
||||
* <p>
|
||||
*
|
||||
* <p/>
|
||||
* <p/>
|
||||
* To get a block, you can either build one from the raw bytes you can get from
|
||||
* another implementation, or request one specifically using
|
||||
* {@link Peer#getBlock(Sha256Hash)}, or grab one from a downloaded
|
||||
@ -49,8 +51,7 @@ public class Block extends Message {
|
||||
/** How many bytes are required to represent a block header. */
|
||||
public static final int HEADER_SIZE = 80;
|
||||
|
||||
static final long ALLOWED_TIME_DRIFT = 2 * 60 * 60; // Same value as
|
||||
// official client.
|
||||
static final long ALLOWED_TIME_DRIFT = 2 * 60 * 60; // Same value as official client.
|
||||
|
||||
/**
|
||||
* A value for difficultyTarget (nBits) that allows half of all possible
|
||||
@ -202,7 +203,6 @@ public class Block extends Message {
|
||||
* interdependencies. For example altering a tx requires invalidating the
|
||||
* Merkle root and therefore the cached header bytes.
|
||||
*/
|
||||
|
||||
private synchronized void checkParseHeader() {
|
||||
if (headerParsed || bytes == null)
|
||||
return;
|
||||
@ -398,7 +398,7 @@ public class Block extends Message {
|
||||
if (transactions == null)
|
||||
return 0;
|
||||
int len = VarInt.sizeOf(transactions.size());
|
||||
for (Transaction tx: transactions) {
|
||||
for (Transaction tx : transactions) {
|
||||
len += tx.length == UNKNOWN_LENGTH ? 255 : tx.length;
|
||||
}
|
||||
return len;
|
||||
@ -478,8 +478,7 @@ public class Block extends Message {
|
||||
static private BigInteger LARGEST_HASH = BigInteger.ONE.shiftLeft(256);
|
||||
|
||||
/**
|
||||
* Returns the work represented by this block.
|
||||
* <p>
|
||||
* Returns the work represented by this block.<p>
|
||||
*
|
||||
* 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
|
||||
@ -902,7 +901,7 @@ public class Block extends Message {
|
||||
// Here we will do things a bit differently so a new address isn't
|
||||
// needed every time. We'll put a simple
|
||||
// counter in the scriptSig so every transaction has a different hash.
|
||||
coinbase.addInput(new TransactionInput(params, coinbase, new byte[] { (byte) txCounter++ }));
|
||||
coinbase.addInput(new TransactionInput(params, coinbase, new byte[]{(byte) txCounter++}));
|
||||
coinbase.addOutput(new TransactionOutput(params, coinbase, Script.createOutputScript(pubKeyTo)));
|
||||
transactions.add(coinbase);
|
||||
}
|
||||
|
@ -16,14 +16,14 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
|
||||
import com.google.bitcoin.store.BlockStore;
|
||||
import com.google.bitcoin.store.BlockStoreException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A BlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that the
|
||||
* chain follows the rules of the {@link NetworkParameters} for this chain.<p>
|
||||
@ -74,7 +74,7 @@ public class BlockChain {
|
||||
/**
|
||||
* Constructs a BlockChain connected to the given wallet and store. To obtain a {@link Wallet} you can construct
|
||||
* one from scratch, or you can deserialize a saved wallet from disk using {@link Wallet#loadFromFile(java.io.File)}
|
||||
* <p>
|
||||
* <p/>
|
||||
*
|
||||
* For the store you can use a {@link com.google.bitcoin.store.MemoryBlockStore} if you don't care about saving the downloaded data, or a
|
||||
* {@link com.google.bitcoin.store.BoundedOverheadBlockStore} if you'd like to ensure fast startup the next time you run the program.
|
||||
@ -150,7 +150,7 @@ public class BlockChain {
|
||||
// blocks validity so we can skip the merkle root verification if the contents aren't interesting. This saves
|
||||
// a lot of time for big blocks.
|
||||
boolean contentsImportant = false;
|
||||
HashMap<Wallet, List<Transaction>> walletToTxMap = new HashMap<Wallet, List<Transaction>>();;
|
||||
HashMap<Wallet, List<Transaction>> walletToTxMap = new HashMap<Wallet, List<Transaction>>();
|
||||
if (block.transactions != null) {
|
||||
scanTransactions(block, walletToTxMap);
|
||||
contentsImportant = walletToTxMap.size() > 0;
|
||||
|
@ -5,7 +5,6 @@ package com.google.bitcoin.core;
|
||||
* backing byte array need to invalidate their parent's caches as well as their own if they are modified.
|
||||
*
|
||||
* @author git
|
||||
*
|
||||
*/
|
||||
public abstract class ChildMessage extends Message {
|
||||
|
||||
@ -39,7 +38,7 @@ public abstract class ChildMessage extends Message {
|
||||
}
|
||||
|
||||
public void setParent(Message parent) {
|
||||
if (this.parent != null && this.parent != parent && parent !=null) {
|
||||
if (this.parent != null && this.parent != parent && parent != null) {
|
||||
//after old parent is unlinked it won't be able to receive notice if this ChildMessage
|
||||
//changes internally. To be safe we invalidate the parent cache to ensure it rebuilds
|
||||
//manually on serialization.
|
||||
|
@ -16,10 +16,6 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import com.google.bitcoin.core.AbstractPeerEventListener;
|
||||
import com.google.bitcoin.core.Block;
|
||||
import com.google.bitcoin.core.Peer;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.Semaphore;
|
||||
@ -34,7 +30,6 @@ import java.util.concurrent.Semaphore;
|
||||
* implementation does not have to be thread safe.
|
||||
*
|
||||
* @author miron@google.com (Miron Cuperman a.k.a. devrandom)
|
||||
*
|
||||
*/
|
||||
public class DownloadListener extends AbstractPeerEventListener {
|
||||
private int originalBlocksLeft = -1;
|
||||
@ -58,9 +53,9 @@ public class DownloadListener extends AbstractPeerEventListener {
|
||||
return;
|
||||
|
||||
double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft));
|
||||
if ((int)pct != lastPercent) {
|
||||
if ((int) pct != lastPercent) {
|
||||
progress(pct, new Date(block.getTimeSeconds() * 1000));
|
||||
lastPercent = (int)pct;
|
||||
lastPercent = (int) pct;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -16,20 +16,7 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import org.bouncycastle.asn1.ASN1InputStream;
|
||||
import org.bouncycastle.asn1.ASN1OutputStream;
|
||||
import org.bouncycastle.asn1.DERBitString;
|
||||
import org.bouncycastle.asn1.DERInteger;
|
||||
import org.bouncycastle.asn1.DEROctetString;
|
||||
import org.bouncycastle.asn1.DERSequence;
|
||||
import org.bouncycastle.asn1.DERSequenceGenerator;
|
||||
import org.bouncycastle.asn1.DERTaggedObject;
|
||||
import org.bouncycastle.asn1.*;
|
||||
import org.bouncycastle.asn1.sec.SECNamedCurves;
|
||||
import org.bouncycastle.asn1.x9.X9ECParameters;
|
||||
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
|
||||
@ -40,6 +27,12 @@ import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
|
||||
import org.bouncycastle.crypto.signers.ECDSASigner;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/**
|
||||
* Represents an elliptic curve keypair that we own and can use for signing transactions. Currently,
|
||||
* Bouncy Castle is used. In future this may become an interface with multiple implementations using different crypto
|
||||
@ -88,7 +81,7 @@ public class ECKey implements Serializable {
|
||||
* Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by the BitCoin reference
|
||||
* implementation in its wallet storage format.
|
||||
*/
|
||||
public byte[] toASN1(){
|
||||
public byte[] toASN1() {
|
||||
try {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream(400);
|
||||
ASN1OutputStream encoder = new ASN1OutputStream(baos);
|
||||
@ -184,6 +177,7 @@ public class ECKey implements Serializable {
|
||||
|
||||
/**
|
||||
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
|
||||
*
|
||||
* @param data Hash of the data to verify.
|
||||
* @param signature ASN.1 encoded signature.
|
||||
* @param pub The public key bytes to use.
|
||||
@ -206,6 +200,7 @@ public class ECKey implements Serializable {
|
||||
|
||||
/**
|
||||
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
|
||||
*
|
||||
* @param data Hash of the data to verify.
|
||||
* @param signature ASN.1 encoded signature.
|
||||
*/
|
||||
@ -238,7 +233,9 @@ public class ECKey implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns a 32 byte array containing the private key. */
|
||||
/**
|
||||
* Returns a 32 byte array containing the private key.
|
||||
*/
|
||||
public byte[] getPrivKeyBytes() {
|
||||
// Getting the bytes out of a BigInteger gives us an extra zero byte on the end (for signedness)
|
||||
// or less than 32 bytes (leading zeros). Coerce to 32 bytes in all cases.
|
||||
|
@ -6,8 +6,8 @@ import java.io.OutputStream;
|
||||
/**
|
||||
* Parent class for header only messages that don't have a payload.
|
||||
* Currently this includes getaddr, ping, verack as well as the special bitcoinj class UnknownMessage
|
||||
* @author git
|
||||
*
|
||||
* @author git
|
||||
*/
|
||||
public abstract class EmptyMessage extends Message {
|
||||
|
||||
@ -66,5 +66,4 @@ public abstract class EmptyMessage extends Message {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
@ -43,7 +43,8 @@ public class GetBlocksMessage extends Message {
|
||||
version = readUint32();
|
||||
int startCount = (int) readVarInt();
|
||||
if (startCount > 500)
|
||||
throw new ProtocolException("Number of locators cannot be > 500, received: " + startCount);locator = new ArrayList(startCount);
|
||||
throw new ProtocolException("Number of locators cannot be > 500, received: " + startCount);
|
||||
locator = new ArrayList(startCount);
|
||||
for (int i = 0; i < startCount; i++) {
|
||||
locator.add(readHash());
|
||||
}
|
||||
@ -81,6 +82,5 @@ public class GetBlocksMessage extends Message {
|
||||
}
|
||||
// Next, a block ID to stop at.
|
||||
stream.write(stopHash.getBytes());
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -25,8 +25,7 @@ import java.util.List;
|
||||
/**
|
||||
* Abstract superclass of classes with list based payload, i.e. InventoryMessage and GetDataMessage.
|
||||
*/
|
||||
public abstract class ListMessage extends Message
|
||||
{
|
||||
public abstract class ListMessage extends Message {
|
||||
private long arrayLen;
|
||||
// For some reason the compiler complains if this is inside InventoryItem
|
||||
private List<InventoryItem> items;
|
||||
@ -39,36 +38,31 @@ public abstract class ListMessage extends Message
|
||||
}
|
||||
|
||||
|
||||
|
||||
public ListMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length)
|
||||
throws ProtocolException {
|
||||
super(params, msg, 0, parseLazy, parseRetain, length);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public ListMessage(NetworkParameters params) {
|
||||
super(params);
|
||||
items = new ArrayList<InventoryItem>();
|
||||
length = 1; //length of 0 varint;
|
||||
}
|
||||
|
||||
public List<InventoryItem> getItems()
|
||||
{
|
||||
public List<InventoryItem> getItems() {
|
||||
checkParse();
|
||||
return Collections.unmodifiableList(items);
|
||||
}
|
||||
|
||||
public void addItem(InventoryItem item)
|
||||
{
|
||||
public void addItem(InventoryItem item) {
|
||||
unCache();
|
||||
length -= VarInt.sizeOf(items.size());
|
||||
items.add(item);
|
||||
length += VarInt.sizeOf(items.size()) + 36;
|
||||
}
|
||||
|
||||
public void removeItem(int index)
|
||||
{
|
||||
public void removeItem(int index) {
|
||||
unCache();
|
||||
length -= VarInt.sizeOf(items.size());
|
||||
items.remove(index);
|
||||
@ -86,7 +80,7 @@ public abstract class ListMessage extends Message
|
||||
@Override
|
||||
public void parse() throws ProtocolException {
|
||||
// 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++) {
|
||||
if (cursor + 4 + 32 > bytes.length) {
|
||||
throw new ProtocolException("Ran off the end of the INV");
|
||||
@ -95,9 +89,15 @@ public abstract class ListMessage extends Message
|
||||
InventoryItem.Type type;
|
||||
// See ppszTypeName in net.h
|
||||
switch (typeCode) {
|
||||
case 0: type = InventoryItem.Type.Error; break;
|
||||
case 1: type = InventoryItem.Type.Transaction; break;
|
||||
case 2: type = InventoryItem.Type.Block; break;
|
||||
case 0:
|
||||
type = InventoryItem.Type.Error;
|
||||
break;
|
||||
case 1:
|
||||
type = InventoryItem.Type.Transaction;
|
||||
break;
|
||||
case 2:
|
||||
type = InventoryItem.Type.Block;
|
||||
break;
|
||||
default:
|
||||
throw new ProtocolException("Unknown CInv type: " + typeCode);
|
||||
}
|
||||
@ -109,8 +109,7 @@ public abstract class ListMessage extends Message
|
||||
|
||||
|
||||
@Override
|
||||
public void bitcoinSerializeToStream(OutputStream stream) throws IOException
|
||||
{
|
||||
public void bitcoinSerializeToStream(OutputStream stream) throws IOException {
|
||||
stream.write(new VarInt(items.size()).encode());
|
||||
for (InventoryItem i : items) {
|
||||
// Write out the type code.
|
||||
|
@ -16,18 +16,18 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A Message is a data structure that can be serialized/deserialized using both the BitCoin proprietary serialization
|
||||
* format and built-in Java object serialization. Specific types of messages that are used both in the block chain,
|
||||
* and on the wire, are derived from this class.
|
||||
*
|
||||
* <p/>
|
||||
* This class is not useful for library users. If you want to talk to the network see the {@link Peer} class.
|
||||
*/
|
||||
public abstract class Message implements Serializable {
|
||||
@ -64,7 +64,9 @@ public abstract class Message implements Serializable {
|
||||
// This will be saved by subclasses that implement Serializable.
|
||||
protected NetworkParameters params;
|
||||
|
||||
/** This exists for the Java serialization framework to use only. */
|
||||
/**
|
||||
* This exists for the Java serialization framework to use only.
|
||||
*/
|
||||
protected Message() {
|
||||
parsed = true;
|
||||
parseLazy = false;
|
||||
@ -137,8 +139,9 @@ public abstract class Message implements Serializable {
|
||||
* Perform the most minimal parse possible to calculate the length of the message.
|
||||
* This is only required for subclasses of ChildClass as root level messages will have their length passed
|
||||
* into the constructor.
|
||||
*
|
||||
* <p/>
|
||||
* It is expected that the length field will be set before this method returns.
|
||||
*
|
||||
* @return
|
||||
* @throws ProtocolException
|
||||
*/
|
||||
@ -168,7 +171,7 @@ public abstract class Message implements Serializable {
|
||||
* In lazy parsing mode access to getters and setters may throw an unchecked LazyParseException. If guaranteed safe access is required
|
||||
* this method will force parsing to occur immediately thus ensuring LazyParseExeption will never be thrown from this Message.
|
||||
* If the Message contains child messages (e.g. a Block containing Transaction messages) this will not force child messages to parse.
|
||||
*
|
||||
* <p/>
|
||||
* This could be overidden for Transaction and it's child classes to ensure the entire tree of Message objects is parsed.
|
||||
*
|
||||
* @throws ProtocolException
|
||||
@ -186,7 +189,7 @@ public abstract class Message implements Serializable {
|
||||
/**
|
||||
* To be called before any change of internal values including any setters. This ensures any cached byte array is removed after performing
|
||||
* a lazy parse if necessary to ensure the object is fully populated.
|
||||
*
|
||||
* <p/>
|
||||
* 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.
|
||||
*/
|
||||
@ -240,6 +243,7 @@ public abstract class Message implements Serializable {
|
||||
|
||||
/**
|
||||
* Should only used by BitcoinSerializer for cached checksum
|
||||
*
|
||||
* @return the checksum
|
||||
*/
|
||||
byte[] getChecksum() {
|
||||
@ -248,6 +252,7 @@ public abstract class Message implements Serializable {
|
||||
|
||||
/**
|
||||
* Should only used by BitcoinSerializer for caching checksum
|
||||
*
|
||||
* @param checksum the checksum to set
|
||||
*/
|
||||
void setChecksum(byte[] checksum) {
|
||||
@ -324,6 +329,7 @@ public abstract class Message implements Serializable {
|
||||
|
||||
/**
|
||||
* Serialize this message to the provided OutputStream using the bitcoin wire format.
|
||||
*
|
||||
* @param stream
|
||||
* @throws IOException
|
||||
*/
|
||||
@ -347,6 +353,7 @@ public abstract class Message implements Serializable {
|
||||
/**
|
||||
* This method is a NOP for all classes except Block and Transaction. It is only declared in Message
|
||||
* so BitcoinSerializer can avoid 2 instanceof checks + a casting.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Sha256Hash getHash() {
|
||||
@ -358,6 +365,7 @@ public abstract class Message implements Serializable {
|
||||
* implemented in a subclass of ChildMessage lazy parsing may have no effect.
|
||||
*
|
||||
* This default implementation is a safe fall back that will ensure it returns a correct value by parsing the message.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
int getMessageSize() {
|
||||
@ -422,7 +430,7 @@ public abstract class Message implements Serializable {
|
||||
return "";
|
||||
}
|
||||
cursor += varInt.getSizeInBytes();
|
||||
byte[] characters = new byte[(int)varInt.value];
|
||||
byte[] characters = new byte[(int) varInt.value];
|
||||
System.arraycopy(bytes, cursor, characters, 0, characters.length);
|
||||
cursor += characters.length;
|
||||
try {
|
||||
|
@ -27,7 +27,6 @@ import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
|
||||
/**
|
||||
* A NetworkConnection handles talking to a remote BitCoin peer at a low level. It understands how to read and write
|
||||
@ -106,7 +105,7 @@ public class NetworkConnection {
|
||||
readMessage();
|
||||
// Switch to the new protocol version.
|
||||
int peerVersion = versionMessage.clientVersion;
|
||||
log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}", new Object[] {
|
||||
log.info("Connected to peer: version={}, subVer='{}', services=0x{}, time={}, blocks={}", new Object[]{
|
||||
peerVersion,
|
||||
versionMessage.subVer,
|
||||
versionMessage.localServices,
|
||||
@ -136,6 +135,7 @@ public class NetworkConnection {
|
||||
|
||||
/**
|
||||
* Sends a "ping" message to the remote node. The protocol doesn't presently use this feature much.
|
||||
*
|
||||
* @throws IOException
|
||||
*/
|
||||
public void ping() throws IOException {
|
||||
@ -187,7 +187,9 @@ public class NetworkConnection {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the version message received from the other end of the connection during the handshake. */
|
||||
/**
|
||||
* Returns the version message received from the other end of the connection during the handshake.
|
||||
*/
|
||||
public VersionMessage getVersionMessage() {
|
||||
return versionMessage;
|
||||
}
|
||||
|
@ -23,11 +23,7 @@ import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* A Peer handles the high level communication with a BitCoin node.
|
||||
|
@ -22,7 +22,6 @@ import java.math.BigInteger;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Date;
|
||||
|
||||
import static com.google.bitcoin.core.Utils.uint32ToByteStreamLE;
|
||||
import static com.google.bitcoin.core.Utils.uint64ToByteStreamLE;
|
||||
@ -59,7 +58,6 @@ public class PeerAddress extends ChildMessage {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Construct a peer address from a memorized or hardcoded address.
|
||||
*/
|
||||
@ -89,7 +87,7 @@ public class PeerAddress extends ChildMessage {
|
||||
//TODO this appears to be dynamic because the client only ever sends out it's own address
|
||||
//so assumes itself to be up. For a fuller implementation this needs to be dynamic only if
|
||||
//the address refers to this clinet.
|
||||
int secs = (int)(Utils.now().getTime() / 1000);
|
||||
int secs = (int) (Utils.now().getTime() / 1000);
|
||||
uint32ToByteStreamLE(secs, stream);
|
||||
}
|
||||
uint64ToByteStreamLE(services, stream); // nServices.
|
||||
@ -231,6 +229,6 @@ public class PeerAddress extends ChildMessage {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return addr.hashCode() ^ port ^ (int)time ^ services.hashCode();
|
||||
return addr.hashCode() ^ port ^ (int) time ^ services.hashCode();
|
||||
}
|
||||
}
|
||||
|
@ -24,12 +24,11 @@ package com.google.bitcoin.core;
|
||||
* implementation does not have to be thread safe.
|
||||
*
|
||||
* @author miron@google.com (Miron Cuperman a.k.a devrandom)
|
||||
*
|
||||
*/
|
||||
public interface PeerEventListener {
|
||||
/**
|
||||
* Called on a Peer thread when a block is received.
|
||||
*
|
||||
* <p/>
|
||||
* <p>The block may have transactions or may be a header only once getheaders is implemented.
|
||||
*
|
||||
* @param peer the peer receiving the block
|
||||
|
@ -16,18 +16,14 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import com.google.bitcoin.core.Transaction.SigHash;
|
||||
import org.bouncycastle.util.Arrays;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static com.google.bitcoin.core.Utils.bytesToHexString;
|
||||
|
||||
@ -61,6 +57,7 @@ public class Script {
|
||||
|
||||
/**
|
||||
* Construct a Script using the given network parameters and a range of the programBytes array.
|
||||
*
|
||||
* @param params Network parameters.
|
||||
* @param programBytes Array of program bytes from a transaction.
|
||||
* @param offset How many bytes into programBytes to start reading from.
|
||||
@ -72,7 +69,9 @@ public class Script {
|
||||
parse(programBytes, offset, length);
|
||||
}
|
||||
|
||||
/** Returns the program opcodes as a string, for example "[1234] DUP HAHS160" */
|
||||
/**
|
||||
* Returns the program opcodes as a string, for example "[1234] DUP HAHS160"
|
||||
*/
|
||||
public String toString() {
|
||||
StringBuffer buf = new StringBuffer();
|
||||
for (byte[] chunk : chunks) {
|
||||
@ -80,10 +79,18 @@ public class Script {
|
||||
String opName;
|
||||
int opcode = 0xFF & chunk[0];
|
||||
switch (opcode) {
|
||||
case OP_DUP: opName = "DUP"; break;
|
||||
case OP_HASH160: opName = "HASH160"; break;
|
||||
case OP_CHECKSIG: opName = "CHECKSIG"; break;
|
||||
case OP_EQUALVERIFY: opName = "EQUALVERIFY"; break;
|
||||
case OP_DUP:
|
||||
opName = "DUP";
|
||||
break;
|
||||
case OP_HASH160:
|
||||
opName = "HASH160";
|
||||
break;
|
||||
case OP_CHECKSIG:
|
||||
opName = "CHECKSIG";
|
||||
break;
|
||||
case OP_EQUALVERIFY:
|
||||
opName = "EQUALVERIFY";
|
||||
break;
|
||||
default:
|
||||
opName = "?(" + opcode + ")";
|
||||
break;
|
||||
@ -123,7 +130,7 @@ public class Script {
|
||||
/**
|
||||
* To run a script, first we parse it which breaks it up into chunks representing pushes of
|
||||
* data or logical opcodes. Then we can run the parsed chunks.
|
||||
*
|
||||
* <p/>
|
||||
* The reason for this split, instead of just interpreting directly, is to make it easier
|
||||
* to reach into a programs structure and pull out bits of data without having to run it.
|
||||
* This is necessary to render the to/from addresses of transactions in a user interface.
|
||||
@ -159,7 +166,7 @@ public class Script {
|
||||
// Read a uint32, then read that many bytes of data.
|
||||
log.error("PUSHDATA4: Unimplemented");
|
||||
} else {
|
||||
chunks.add(new byte[] { (byte) opcode });
|
||||
chunks.add(new byte[]{(byte) opcode});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -178,7 +185,7 @@ public class Script {
|
||||
/**
|
||||
* If a program matches the standard template DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG
|
||||
* then this function retrieves the third element, otherwise it throws a ScriptException.
|
||||
*
|
||||
* <p/>
|
||||
* This is useful for fetching the destination address of a transaction.
|
||||
*/
|
||||
public byte[] getPubKeyHash() throws ScriptException {
|
||||
@ -198,7 +205,7 @@ public class Script {
|
||||
/**
|
||||
* If a program has two data buffers (constants) and nothing else, the second one is returned.
|
||||
* For a scriptSig this should be the public key of the sender.
|
||||
*
|
||||
* <p/>
|
||||
* This is useful for fetching the source address of a transaction.
|
||||
*/
|
||||
public byte[] getPubKey() throws ScriptException {
|
||||
@ -224,6 +231,7 @@ public class Script {
|
||||
|
||||
/**
|
||||
* Gets the destination address from this script, if it's in the required form (see getPubKey).
|
||||
*
|
||||
* @throws ScriptException
|
||||
*/
|
||||
public Address getToAddress() throws ScriptException {
|
||||
@ -232,7 +240,9 @@ public class Script {
|
||||
|
||||
////////////////////// Interface for writing scripts from scratch ////////////////////////////////
|
||||
|
||||
/** Writes out the given byte buffer to the output stream with the correct opcode prefix */
|
||||
/**
|
||||
* Writes out the given byte buffer to the output stream with the correct opcode prefix
|
||||
*/
|
||||
static void writeBytes(OutputStream os, byte[] buf) throws IOException {
|
||||
if (buf.length < OP_PUSHDATA1) {
|
||||
os.write(buf.length);
|
||||
@ -266,7 +276,9 @@ public class Script {
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a script that sends coins directly to the given public key (eg in a coinbase transaction). */
|
||||
/**
|
||||
* Create a script that sends coins directly to the given public key (eg in a coinbase transaction).
|
||||
*/
|
||||
static byte[] createOutputScript(byte[] pubkey) {
|
||||
try {
|
||||
// TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes.
|
||||
|
@ -54,6 +54,7 @@ public class Sha256Hash implements Serializable {
|
||||
* needs to be set to a different value it should be done once and only once
|
||||
* and before any calls to hashCode() are made on any instance of Sha256Hash instances.
|
||||
* <br/>
|
||||
*
|
||||
* @param hashcodeByteLength the number of bytes in the hash to use for generating the hashcode.
|
||||
* @throws IllegalStateException if called more than once.
|
||||
*/
|
||||
@ -64,7 +65,9 @@ public class Sha256Hash implements Serializable {
|
||||
HASHCODE_BYTES_TO_CHECK_CHANGED = true;
|
||||
}
|
||||
|
||||
/** Creates a Sha256Hash by wrapping the given byte array. It must be 32 bytes long. */
|
||||
/**
|
||||
* Creates a Sha256Hash by wrapping the given byte array. It must be 32 bytes long.
|
||||
*/
|
||||
public Sha256Hash(byte[] bytes) {
|
||||
assert bytes.length == 32;
|
||||
this.bytes = bytes;
|
||||
@ -77,13 +80,17 @@ public class Sha256Hash implements Serializable {
|
||||
this.hash = hash;
|
||||
}
|
||||
|
||||
/** Creates a Sha256Hash by decoding the given hex string. It must be 64 characters long. */
|
||||
/**
|
||||
* Creates a Sha256Hash by decoding the given hex string. It must be 64 characters long.
|
||||
*/
|
||||
public Sha256Hash(String string) {
|
||||
assert string.length() == 64;
|
||||
this.bytes = Hex.decode(string);
|
||||
}
|
||||
|
||||
/** Calculates the (one-time) hash of contents and returns it as a new wrapped hash. */
|
||||
/**
|
||||
* Calculates the (one-time) hash of contents and returns it as a new wrapped hash.
|
||||
*/
|
||||
public static Sha256Hash create(byte[] contents) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
@ -93,11 +100,13 @@ public class Sha256Hash implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true if the hashes are equal. */
|
||||
/**
|
||||
* Returns true if the hashes are equal.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (!(other instanceof Sha256Hash)) return false;
|
||||
return Arrays.equals(bytes, ((Sha256Hash)other).bytes);
|
||||
return Arrays.equals(bytes, ((Sha256Hash) other).bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -120,7 +129,9 @@ public class Sha256Hash implements Serializable {
|
||||
return Utils.bytesToHexString(bytes);
|
||||
}
|
||||
|
||||
/** Returns the bytes interpreted as a positive integer. */
|
||||
/**
|
||||
* Returns the bytes interpreted as a positive integer.
|
||||
*/
|
||||
public BigInteger toBigInteger() {
|
||||
return new BigInteger(1, bytes);
|
||||
}
|
||||
|
@ -16,17 +16,13 @@
|
||||
|
||||
package com.google.bitcoin.core;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
|
||||
import static com.google.bitcoin.core.Utils.*;
|
||||
|
||||
/**
|
||||
@ -154,7 +150,9 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Calculates the sum of the outputs that are sending coins to a key in the wallet. */
|
||||
/**
|
||||
* Calculates the sum of the outputs that are sending coins to a key in the wallet.
|
||||
*/
|
||||
public BigInteger getValueSentToMe(Wallet wallet) {
|
||||
return getValueSentToMe(wallet, true);
|
||||
}
|
||||
@ -287,7 +285,7 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
/**
|
||||
* These constants are a part of a scriptSig signature on the inputs. They define the details of how a
|
||||
* transaction can be redeemed, specifically, they control how the hash of the transaction is calculated.
|
||||
*
|
||||
* <p/>
|
||||
* In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation,
|
||||
* that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags
|
||||
* exist to allow for distributed contracts.
|
||||
@ -368,7 +366,7 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
|
||||
// First come the inputs.
|
||||
long numInputs = readVarInt();
|
||||
inputs = new ArrayList<TransactionInput>((int)numInputs);
|
||||
inputs = new ArrayList<TransactionInput>((int) numInputs);
|
||||
for (long i = 0; i < numInputs; i++) {
|
||||
TransactionInput input = new TransactionInput(params, this, bytes, cursor, parseLazy, parseRetain);
|
||||
inputs.add(input);
|
||||
@ -376,7 +374,7 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
}
|
||||
// Now the outputs
|
||||
long numOutputs = readVarInt();
|
||||
outputs = new ArrayList<TransactionOutput>((int)numOutputs);
|
||||
outputs = new ArrayList<TransactionOutput>((int) numOutputs);
|
||||
for (long i = 0; i < numOutputs; i++) {
|
||||
TransactionOutput output = new TransactionOutput(params, this, bytes, cursor, parseLazy, parseRetain);
|
||||
outputs.add(output);
|
||||
@ -456,7 +454,9 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
addInput(new TransactionInput(params, this, from));
|
||||
}
|
||||
|
||||
/** Adds an input directly, with no checking that it's valid. */
|
||||
/**
|
||||
* Adds an input directly, with no checking that it's valid.
|
||||
*/
|
||||
public void addInput(TransactionInput input) {
|
||||
unCache();
|
||||
input.setParent(this);
|
||||
@ -484,7 +484,7 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
* Once a transaction has some inputs and outputs added, the signatures in the inputs can be calculated. The
|
||||
* signature is over the transaction itself, to prove the redeemer actually created that transaction,
|
||||
* so we have to do this step last.<p>
|
||||
*
|
||||
* <p/>
|
||||
* This method is similar to SignatureHash in script.cpp
|
||||
*
|
||||
* @param hashType This should always be set to SigHash.ALL currently. Other types are unused.
|
||||
@ -531,7 +531,7 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
//usually 71-73 bytes
|
||||
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73);
|
||||
bos.write(key.sign(hash));
|
||||
bos.write((hashType.ordinal() + 1) | (anyoneCanPay ? 0x80 : 0)) ;
|
||||
bos.write((hashType.ordinal() + 1) | (anyoneCanPay ? 0x80 : 0));
|
||||
signatures[i] = bos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e); // Cannot happen.
|
||||
@ -581,7 +581,6 @@ public class Transaction extends ChildMessage implements Serializable {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return the lockTime
|
||||
*/
|
||||
|
@ -48,7 +48,9 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
// A pointer to the transaction that owns this input.
|
||||
private Transaction parentTransaction;
|
||||
|
||||
/** Used only in creation of the genesis block. */
|
||||
/**
|
||||
* Used only in creation of the genesis block.
|
||||
*/
|
||||
TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] scriptBytes) {
|
||||
super(params);
|
||||
this.scriptBytes = scriptBytes;
|
||||
@ -59,7 +61,9 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
length = 40 + (scriptBytes == null ? 1 : VarInt.sizeOf(scriptBytes.length) + scriptBytes.length);
|
||||
}
|
||||
|
||||
/** Creates an UNSIGNED input that links to the given output */
|
||||
/**
|
||||
* Creates an UNSIGNED input that links to the given output
|
||||
*/
|
||||
TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) {
|
||||
super(params);
|
||||
long outputIndex = output.getIndex();
|
||||
@ -71,14 +75,18 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
length = 41;
|
||||
}
|
||||
|
||||
/** Deserializes an input message. This is usually part of a transaction message. */
|
||||
/**
|
||||
* Deserializes an input message. This is usually part of a transaction message.
|
||||
*/
|
||||
public TransactionInput(NetworkParameters params, Transaction parentTransaction,
|
||||
byte[] payload, int offset) throws ProtocolException {
|
||||
super(params, payload, offset);
|
||||
this.parentTransaction = parentTransaction;
|
||||
}
|
||||
|
||||
/** Deserializes an input message. This is usually part of a transaction message. */
|
||||
/**
|
||||
* Deserializes an input message. This is usually part of a transaction message.
|
||||
*/
|
||||
public TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] msg, int offset, boolean parseLazy, boolean parseRetain)
|
||||
throws ProtocolException {
|
||||
super(params, msg, offset, parentTransaction, parseLazy, parseRetain, UNKNOWN_LENGTH);
|
||||
@ -132,6 +140,7 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
|
||||
/**
|
||||
* Convenience method that returns the from address of this input by parsing the scriptSig.
|
||||
*
|
||||
* @throws ScriptException if the scriptSig could not be understood (eg, if this is a coinbase transaction).
|
||||
*/
|
||||
public Address getFromAddress() throws ScriptException {
|
||||
@ -189,7 +198,9 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
return parentTransaction;
|
||||
}
|
||||
|
||||
/** Returns a human readable debug string. */
|
||||
/**
|
||||
* Returns a human readable debug string.
|
||||
*/
|
||||
public String toString() {
|
||||
if (isCoinBase())
|
||||
return "TxIn: COINBASE";
|
||||
@ -212,13 +223,14 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
|
||||
/**
|
||||
* Locates the referenced output from the given pool of transactions.
|
||||
*
|
||||
* @return The TransactionOutput or null if the transactions map doesn't contain the referenced tx.
|
||||
*/
|
||||
TransactionOutput getConnectedOutput(Map<Sha256Hash, Transaction> transactions) {
|
||||
Transaction tx = transactions.get(outpoint.getHash());
|
||||
if (tx == null)
|
||||
return null;
|
||||
TransactionOutput out = tx.getOutputs().get((int)outpoint.getIndex());
|
||||
TransactionOutput out = tx.getOutputs().get((int) outpoint.getIndex());
|
||||
return out;
|
||||
}
|
||||
|
||||
@ -234,7 +246,7 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
Transaction tx = transactions.get(outpoint.getHash());
|
||||
if (tx == null)
|
||||
return TransactionInput.ConnectionResult.NO_SUCH_TX;
|
||||
TransactionOutput out = tx.getOutputs().get((int)outpoint.getIndex());
|
||||
TransactionOutput out = tx.getOutputs().get((int) outpoint.getIndex());
|
||||
if (!out.isAvailableForSpending()) {
|
||||
if (disconnect)
|
||||
out.markAsUnspent();
|
||||
@ -253,7 +265,7 @@ public class TransactionInput extends ChildMessage implements Serializable {
|
||||
*/
|
||||
boolean disconnect() {
|
||||
if (outpoint.fromTx == null) return false;
|
||||
outpoint.fromTx.getOutputs().get((int)outpoint.getIndex()).markAsUnspent();
|
||||
outpoint.fromTx.getOutputs().get((int) outpoint.getIndex()).markAsUnspent();
|
||||
outpoint.fromTx = null;
|
||||
return true;
|
||||
}
|
||||
|
@ -53,12 +53,16 @@ public class TransactionOutPoint extends ChildMessage implements Serializable {
|
||||
length = MESSAGE_LENGTH;
|
||||
}
|
||||
|
||||
/** Deserializes the message. This is usually part of a transaction message. */
|
||||
/**
|
||||
* Deserializes the message. This is usually part of a transaction message.
|
||||
*/
|
||||
public TransactionOutPoint(NetworkParameters params, byte[] payload, int offset) throws ProtocolException {
|
||||
super(params, payload, offset);
|
||||
}
|
||||
|
||||
/** Deserializes the message. This is usually part of a transaction message. */
|
||||
/**
|
||||
* Deserializes the message. This is usually part of a transaction message.
|
||||
*/
|
||||
public TransactionOutPoint(NetworkParameters params, byte[] payload, int offset, Message parent, boolean parseLazy, boolean parseRetain) throws ProtocolException {
|
||||
super(params, payload, offset, parent, parseLazy, parseRetain, MESSAGE_LENGTH);
|
||||
}
|
||||
@ -93,7 +97,7 @@ public class TransactionOutPoint extends ChildMessage implements Serializable {
|
||||
*/
|
||||
TransactionOutput getConnectedOutput() {
|
||||
if (fromTx == null) return null;
|
||||
return fromTx.getOutputs().get((int)index);
|
||||
return fromTx.getOutputs().get((int) index);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -119,7 +123,6 @@ public class TransactionOutPoint extends ChildMessage implements Serializable {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return the hash
|
||||
*/
|
||||
|
@ -52,7 +52,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
Transaction parentTransaction;
|
||||
private transient int scriptLen;
|
||||
|
||||
/** 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.
|
||||
*/
|
||||
public TransactionOutput(NetworkParameters params, Transaction parent, byte[] payload,
|
||||
int offset) throws ProtocolException {
|
||||
super(params, payload, offset);
|
||||
@ -60,7 +62,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
availableForSpending = true;
|
||||
}
|
||||
|
||||
/** 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.
|
||||
*/
|
||||
public TransactionOutput(NetworkParameters params, Transaction parent, byte[] msg, int offset, boolean parseLazy, boolean parseRetain)
|
||||
throws ProtocolException {
|
||||
super(params, msg, offset, parent, parseLazy, parseRetain, UNKNOWN_LENGTH);
|
||||
@ -77,7 +81,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
length = 8 + VarInt.sizeOf(scriptBytes.length) + scriptBytes.length;
|
||||
}
|
||||
|
||||
/** Used only in creation of the genesis blocks and in unit tests. */
|
||||
/**
|
||||
* Used only in creation of the genesis blocks and in unit tests.
|
||||
*/
|
||||
TransactionOutput(NetworkParameters params, Transaction parent, byte[] scriptBytes) {
|
||||
super(params);
|
||||
this.scriptBytes = scriptBytes;
|
||||
@ -105,7 +111,7 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void bitcoinSerializeToStream( OutputStream stream) throws IOException {
|
||||
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
|
||||
assert scriptBytes != null;
|
||||
Utils.uint64ToByteStreamLE(getValue(), stream);
|
||||
// TODO: Move script serialization into the Script class, where it belongs.
|
||||
@ -156,7 +162,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
return scriptBytes;
|
||||
}
|
||||
|
||||
/** Returns true if this output is to an address we have the keys for in the wallet. */
|
||||
/**
|
||||
* Returns true if this output is to an address we have the keys for in the wallet.
|
||||
*/
|
||||
public boolean isMine(Wallet wallet) {
|
||||
try {
|
||||
byte[] pubkeyHash = getScriptPubKey().getPubKeyHash();
|
||||
@ -167,7 +175,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns a human readable debug string. */
|
||||
/**
|
||||
* Returns a human readable debug string.
|
||||
*/
|
||||
public String toString() {
|
||||
try {
|
||||
return "TxOut of " + Utils.bitcoinValueToFriendlyString(value) + " to " + getScriptPubKey().getToAddress()
|
||||
@ -177,7 +187,9 @@ public class TransactionOutput extends ChildMessage implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the connected input. */
|
||||
/**
|
||||
* Returns the connected input.
|
||||
*/
|
||||
TransactionInput getSpentBy() {
|
||||
return spentBy;
|
||||
}
|
||||
|
@ -25,7 +25,6 @@ public class UnknownMessage extends EmptyMessage {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public String toString() {
|
||||
return "Unknown message [" + name + "]: " + (bytes == null ? "" : Utils.bytesToHexString(bytes));
|
||||
}
|
||||
@ -33,7 +32,4 @@ public class UnknownMessage extends EmptyMessage {
|
||||
@Override
|
||||
public void parse() throws ProtocolException {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
@ -9,11 +9,11 @@ import java.util.Arrays;
|
||||
* An unsynchronized implementation of ByteArrayOutputStream that will return the backing byte array if its length == size().
|
||||
* This avoids unneeded array copy where the BOS is simply being used to extract a byte array of known length from a
|
||||
* 'serialized to stream' method.
|
||||
*
|
||||
* <p/>
|
||||
* Unless the final length can be accurately predicted the only performance this will yield is due to unsynchronized
|
||||
* methods.
|
||||
* @author git
|
||||
*
|
||||
* @author git
|
||||
*/
|
||||
public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
|
||||
|
||||
@ -35,7 +35,7 @@ public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
|
||||
if (newcount > buf.length) {
|
||||
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
|
||||
}
|
||||
buf[count] = (byte)b;
|
||||
buf[count] = (byte) b;
|
||||
count = newcount;
|
||||
}
|
||||
|
||||
@ -68,7 +68,7 @@ public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
|
||||
* stream's write method using <code>out.write(buf, 0, count)</code>.
|
||||
*
|
||||
* @param out the output stream to which to write the data.
|
||||
* @exception IOException if an I/O error occurs.
|
||||
* @throws IOException if an I/O error occurs.
|
||||
*/
|
||||
public void writeTo(OutputStream out) throws IOException {
|
||||
out.write(buf, 0, count);
|
||||
|
@ -36,7 +36,7 @@ public class Utils {
|
||||
|
||||
/**
|
||||
* How many "nanocoins" there are in a BitCoin.
|
||||
*
|
||||
* <p/>
|
||||
* A nanocoin is the smallest unit that can be transferred using BitCoin.
|
||||
* The term nanocoin is very misleading, though, because there are only 100 million
|
||||
* of them in a coin (whereas one would expect 1 billion.
|
||||
@ -45,14 +45,16 @@ public class Utils {
|
||||
|
||||
/**
|
||||
* How many "nanocoins" there are in 0.01 BitCoins.
|
||||
*
|
||||
* <p/>
|
||||
* A nanocoin is the smallest unit that can be transferred using BitCoin.
|
||||
* The term nanocoin is very misleading, though, because there are only 100 million
|
||||
* of them in a coin (whereas one would expect 1 billion).
|
||||
*/
|
||||
public static final BigInteger CENT = new BigInteger("1000000", 10);
|
||||
|
||||
/** Convert an amount expressed in the way humans are used to into nanocoins. */
|
||||
/**
|
||||
* Convert an amount expressed in the way humans are used to into nanocoins.
|
||||
*/
|
||||
public static BigInteger toNanoCoins(int coins, int cents) {
|
||||
assert cents < 100;
|
||||
BigInteger bi = BigInteger.valueOf(coins).multiply(COIN);
|
||||
@ -62,13 +64,13 @@ public class Utils {
|
||||
|
||||
/**
|
||||
* Convert an amount expressed in the way humans are used to into nanocoins.<p>
|
||||
*
|
||||
* <p/>
|
||||
* This takes string in a format understood by {@link BigDecimal#BigDecimal(String)},
|
||||
* for example "0", "1", "0.10", "1.23E3", "1234.5E-5".
|
||||
*
|
||||
* @throws ArithmeticException if you try to specify fractional nanocoins
|
||||
**/
|
||||
public static BigInteger toNanoCoins(String coins){
|
||||
*/
|
||||
public static BigInteger toNanoCoins(String coins) {
|
||||
return new BigDecimal(coins).movePointRight(8).toBigIntegerExact();
|
||||
}
|
||||
|
||||
@ -87,10 +89,10 @@ public class Utils {
|
||||
}
|
||||
|
||||
public static void uint32ToByteStreamLE(long val, OutputStream stream) throws IOException {
|
||||
stream.write((int)(0xFF & (val >> 0)));
|
||||
stream.write((int)(0xFF & (val >> 8)));
|
||||
stream.write((int)(0xFF & (val >> 16)));
|
||||
stream.write((int)(0xFF & (val >> 24)));
|
||||
stream.write((int) (0xFF & (val >> 0)));
|
||||
stream.write((int) (0xFF & (val >> 8)));
|
||||
stream.write((int) (0xFF & (val >> 16)));
|
||||
stream.write((int) (0xFF & (val >> 24)));
|
||||
}
|
||||
|
||||
public static void uint64ToByteStreamLE(BigInteger val, OutputStream stream) throws IOException {
|
||||
@ -107,7 +109,7 @@ public class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* See {@link Utils#doubleDigest(byte[],int,int)}.
|
||||
* See {@link Utils#doubleDigest(byte[], int, int)}.
|
||||
*/
|
||||
public static byte[] doubleDigest(byte[] input) {
|
||||
return doubleDigest(input, 0, input.length);
|
||||
@ -154,12 +156,16 @@ public class Utils {
|
||||
}
|
||||
}
|
||||
|
||||
/** Work around lack of unsigned types in Java. */
|
||||
/**
|
||||
* Work around lack of unsigned types in Java.
|
||||
*/
|
||||
public static boolean isLessThanUnsigned(long n1, long n2) {
|
||||
return (n1 < n2) ^ ((n1 < 0) != (n2 < 0));
|
||||
}
|
||||
|
||||
/** Returns the given byte array hex encoded. */
|
||||
/**
|
||||
* Returns the given byte array hex encoded.
|
||||
*/
|
||||
public static String bytesToHexString(byte[] bytes) {
|
||||
StringBuffer buf = new StringBuffer(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
@ -172,7 +178,9 @@ public class Utils {
|
||||
}
|
||||
|
||||
|
||||
/** Returns a copy of the given byte array in reverse order. */
|
||||
/**
|
||||
* Returns a copy of the given byte array in reverse order.
|
||||
*/
|
||||
public static byte[] reverseBytes(byte[] bytes) {
|
||||
// We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a
|
||||
// performance issue the matter can be revisited.
|
||||
@ -216,7 +224,9 @@ public class Utils {
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the given value in nanocoins as a 0.12 type string. */
|
||||
/**
|
||||
* Returns the given value in nanocoins as a 0.12 type string.
|
||||
*/
|
||||
public static String bitcoinValueToFriendlyString(BigInteger value) {
|
||||
boolean negative = value.compareTo(BigInteger.ZERO) < 0;
|
||||
if (negative)
|
||||
@ -241,7 +251,7 @@ public class Utils {
|
||||
// The representation of nBits uses another home-brew encoding, as a way to represent a large
|
||||
// hash value in only 32 bits.
|
||||
static BigInteger decodeCompactBits(long compact) {
|
||||
int size = ((int)(compact >> 24)) & 0xFF;
|
||||
int size = ((int) (compact >> 24)) & 0xFF;
|
||||
byte[] bytes = new byte[4 + size];
|
||||
bytes[3] = (byte) size;
|
||||
if (size >= 1) bytes[4] = (byte) ((compact >> 16) & 0xFF);
|
||||
@ -250,10 +260,14 @@ public class Utils {
|
||||
return decodeMPI(bytes);
|
||||
}
|
||||
|
||||
/** If non-null, overrides the return value of now(). */
|
||||
/**
|
||||
* If non-null, overrides the return value of now().
|
||||
*/
|
||||
public static Date mockTime;
|
||||
|
||||
/** Advances (or rewinds) the mock clock by the given number of seconds. */
|
||||
/**
|
||||
* Advances (or rewinds) the mock clock by the given number of seconds.
|
||||
*/
|
||||
public static Date rollMockClock(int seconds) {
|
||||
if (mockTime == null)
|
||||
mockTime = new Date();
|
||||
@ -261,7 +275,9 @@ public class Utils {
|
||||
return mockTime;
|
||||
}
|
||||
|
||||
/** Returns the current time, or a mocked out equivalent. */
|
||||
/**
|
||||
* Returns the current time, or a mocked out equivalent.
|
||||
*/
|
||||
public static Date now() {
|
||||
if (mockTime != null)
|
||||
return mockTime;
|
||||
|
@ -77,9 +77,9 @@ public class VarInt {
|
||||
|
||||
public byte[] encodeBE() {
|
||||
if (isLessThanUnsigned(value, 253)) {
|
||||
return new byte[] { (byte)value };
|
||||
return new byte[]{(byte) value};
|
||||
} else if (isLessThanUnsigned(value, 65536)) {
|
||||
return new byte[] { (byte) 253, (byte) (value), (byte) (value >> 8) };
|
||||
return new byte[]{(byte) 253, (byte) (value), (byte) (value >> 8)};
|
||||
} else if (isLessThanUnsigned(value, 4294967295L)) {
|
||||
byte[] bytes = new byte[5];
|
||||
bytes[0] = (byte) 254;
|
||||
|
@ -29,22 +29,34 @@ public class VersionMessage extends Message {
|
||||
*/
|
||||
public static final int NODE_NETWORK = 1;
|
||||
|
||||
/** The version number of the protocol spoken. */
|
||||
/**
|
||||
* The version number of the protocol spoken.
|
||||
*/
|
||||
public int clientVersion;
|
||||
/** Flags defining what is supported. Right now {@link #NODE_NETWORK} is the only flag defined. */
|
||||
/**
|
||||
* Flags defining what is supported. Right now {@link #NODE_NETWORK} is the only flag defined.
|
||||
*/
|
||||
public long localServices;
|
||||
/** What the other side believes the current time to be, in seconds. */
|
||||
/**
|
||||
* What the other side believes the current time to be, in seconds.
|
||||
*/
|
||||
public long time;
|
||||
/** What the other side believes the address of this program is. Not used. */
|
||||
/**
|
||||
* What the other side believes the address of this program is. Not used.
|
||||
*/
|
||||
public PeerAddress myAddr;
|
||||
/** What the other side believes their own address is. Not used. */
|
||||
/**
|
||||
* What the other side believes their own address is. Not used.
|
||||
*/
|
||||
public PeerAddress theirAddr;
|
||||
/**
|
||||
* An additional string that today the official client sets to the empty string. We treat it as something like an
|
||||
* HTTP User-Agent header.
|
||||
*/
|
||||
public String subVer;
|
||||
/** How many blocks are in the chain, according to the other side. */
|
||||
/**
|
||||
* How many blocks are in the chain, according to the other side.
|
||||
*/
|
||||
public long bestHeight;
|
||||
|
||||
public VersionMessage(NetworkParameters params, byte[] msg) throws ProtocolException {
|
||||
@ -59,7 +71,6 @@ public class VersionMessage extends Message {
|
||||
// public VersionMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain) throws ProtocolException {
|
||||
// super(params, msg, 0, parseLazy, parseRetain);
|
||||
// }
|
||||
|
||||
public VersionMessage(NetworkParameters params, int newBestHeight) {
|
||||
super(params);
|
||||
clientVersion = NetworkParameters.PROTOCOL_VERSION;
|
||||
@ -180,7 +191,7 @@ public class VersionMessage extends Message {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return (int)bestHeight ^ clientVersion ^ (int)localServices ^ (int)time ^ subVer.hashCode() ^ myAddr.hashCode()
|
||||
return (int) bestHeight ^ clientVersion ^ (int) localServices ^ (int) time ^ subVer.hashCode() ^ myAddr.hashCode()
|
||||
^ theirAddr.hashCode();
|
||||
}
|
||||
|
||||
|
@ -20,9 +20,9 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* <p>In Bitcoin the following format is often used to represent some type of key:</p>
|
||||
*
|
||||
* <p/>
|
||||
* <pre>[one version byte] [data bytes] [4 checksum bytes]</pre>
|
||||
*
|
||||
* <p/>
|
||||
* <p>and the result is then Base58 encoded. This format is used for addresses, and private keys exported using the
|
||||
* dumpprivkey command.</p>
|
||||
*/
|
||||
@ -48,7 +48,7 @@ public class VersionedChecksummedBytes {
|
||||
// A stringified buffer is:
|
||||
// 1 byte version + data bytes + 4 bytes check code (a truncated hash)
|
||||
byte[] addressBytes = new byte[1 + bytes.length + 4];
|
||||
addressBytes[0] = (byte)version;
|
||||
addressBytes[0] = (byte) version;
|
||||
System.arraycopy(bytes, 0, addressBytes, 1, bytes.length);
|
||||
byte[] check = Utils.doubleDigest(addressBytes, 0, bytes.length + 1);
|
||||
System.arraycopy(check, 0, addressBytes, bytes.length + 1, 4);
|
||||
@ -70,6 +70,7 @@ public class VersionedChecksummedBytes {
|
||||
/**
|
||||
* Returns the "version" or "header" byte: the first byte of the data. This is used to disambiguate what the
|
||||
* contents apply to, for example, which network the key or address is valid on.
|
||||
*
|
||||
* @return A positive number between 0 and 255.
|
||||
*/
|
||||
public int getVersion() {
|
||||
|
@ -28,7 +28,7 @@ import static com.google.bitcoin.core.Utils.bitcoinValueToFriendlyString;
|
||||
/**
|
||||
* A Wallet stores keys and a record of transactions that have not yet been spent. Thus, it is capable of
|
||||
* providing transactions on demand that meet a given combined value.<p>
|
||||
*
|
||||
* <p/>
|
||||
* The Wallet is read and written from disk, so be sure to follow the Java serialization versioning rules here. We
|
||||
* use the built in Java serialization to avoid the need to pull in a potentially large (code-size) third party
|
||||
* serialization library.<p>
|
||||
@ -86,7 +86,7 @@ public class Wallet implements Serializable {
|
||||
* to pay other people and so count towards our balance. Transactions only appear in this map if they are part
|
||||
* of the best chain. Transactions we have broacast that are not confirmed yet appear in pending even though they
|
||||
* may have unspent "change" outputs.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Note: for now we will not allow spends of transactions that did not make it into the block chain. The code
|
||||
* that handles this in BitCoin C++ is complicated. Satoshis code will not allow you to spend unconfirmed coins,
|
||||
* however, it does seem to support dependency resolution entirely within the context of the memory pool so
|
||||
@ -100,7 +100,7 @@ public class Wallet implements Serializable {
|
||||
* the time to create a spend does not grow infinitely as wallets become more used. Some of these transactions
|
||||
* may not have appeared in a block yet if they were created by us to spend coins and that spend is still being
|
||||
* worked on by miners.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Transactions only appear in this map if they are part of the best chain.
|
||||
*/
|
||||
final Map<Sha256Hash, Transaction> spent;
|
||||
@ -109,7 +109,7 @@ public class Wallet implements Serializable {
|
||||
* An inactive transaction is one that is seen only in a block that is not a part of the best chain. We keep it
|
||||
* around in case a re-org promotes a different chain to be the best. In this case some (not necessarily all)
|
||||
* inactive transactions will be moved out to unspent and spent, and some might be moved in.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Note that in the case where a transaction appears in both the best chain and a side chain as well, it is not
|
||||
* placed in this map. It's an error for a transaction to be in both the inactive pool and unspent/spent.
|
||||
*/
|
||||
@ -123,7 +123,9 @@ public class Wallet implements Serializable {
|
||||
*/
|
||||
private Map<Sha256Hash, Transaction> dead;
|
||||
|
||||
/** A list of public/private EC keys owned by this user. */
|
||||
/**
|
||||
* A list of public/private EC keys owned by this user.
|
||||
*/
|
||||
public final ArrayList<ECKey> keychain;
|
||||
|
||||
private final NetworkParameters params;
|
||||
@ -198,16 +200,16 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* Called by the {@link BlockChain} when we receive a new block that sends coins to one of our addresses or
|
||||
* spends coins from one of our addresses (note that a single transaction can do both).<p>
|
||||
*
|
||||
* <p/>
|
||||
* This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us
|
||||
* coins it is added to a pool so we can use it later to create spends. When a transaction is received that
|
||||
* consumes outputs they are marked as spent so they won't be used in future.<p>
|
||||
*
|
||||
* <p/>
|
||||
* A transaction that spends our own coins can be received either because a spend we created was accepted by the
|
||||
* network and thus made it into a block, or because our keys are being shared between multiple instances and
|
||||
* some other node spent the coins instead. We still have to know about that to avoid accidentally trying to
|
||||
* double spend.<p>
|
||||
*
|
||||
* <p/>
|
||||
* A transaction may be received multiple times if is included into blocks in parallel chains. The blockType
|
||||
* parameter describes whether the containing block is on the main/best chain or whether it's on a presently
|
||||
* inactive side chain. We must still record these transactions and the blocks they appear in because a future
|
||||
@ -232,7 +234,7 @@ public class Wallet implements Serializable {
|
||||
BigInteger valueDifference = valueSentToMe.subtract(valueSentFromMe);
|
||||
|
||||
if (!reorg) {
|
||||
log.info("Received tx{} for {} BTC: {}", new Object[] { sideChain ? " on a side chain" : "",
|
||||
log.info("Received tx{} for {} BTC: {}", new Object[]{sideChain ? " on a side chain" : "",
|
||||
bitcoinValueToFriendlyString(valueDifference), tx.getHashAsString()});
|
||||
}
|
||||
|
||||
@ -384,7 +386,9 @@ public class Wallet implements Serializable {
|
||||
}
|
||||
}
|
||||
|
||||
/** If the transactions outputs are all marked as spent, and it's in the unspent map, move it. */
|
||||
/**
|
||||
* If the transactions outputs are all marked as spent, and it's in the unspent map, move it.
|
||||
*/
|
||||
private void maybeMoveTxToSpent(Transaction tx, String context) {
|
||||
if (tx.isEveryOutputSpent()) {
|
||||
// There's nothing left I can spend in this transaction.
|
||||
@ -401,7 +405,7 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* Adds an event listener object. Methods on this object are called when something interesting happens,
|
||||
* like receiving money.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Threading: Event listener methods are dispatched on library provided threads and the both the wallet and the
|
||||
* listener objects are locked during dispatch, so your listeners do not have to be thread safe. However they
|
||||
* should not block as the Peer will be unresponsive to network traffic whilst your listener is running.
|
||||
@ -454,7 +458,9 @@ public class Wallet implements Serializable {
|
||||
return all;
|
||||
}
|
||||
|
||||
/** Returns all non-dead, active transactions ordered by recency. */
|
||||
/**
|
||||
* Returns all non-dead, active transactions ordered by recency.
|
||||
*/
|
||||
public List<Transaction> getTransactionsByTime() {
|
||||
return getRecentTransactions(0, false);
|
||||
}
|
||||
@ -462,7 +468,7 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* Returns an list of N transactions, ordered by increasing age. Transactions on side chains are not included.
|
||||
* Dead transactions (overridden by double spends) are optionally included. <p>
|
||||
*
|
||||
* <p/>
|
||||
* Note: the current implementation is O(num transactions in wallet). Regardless of how many transactions are
|
||||
* requested, the cost is always the same. In future, requesting smaller numbers of transactions may be faster
|
||||
* depending on how the wallet is implemented (eg if backed by a database).
|
||||
@ -501,12 +507,18 @@ public class Wallet implements Serializable {
|
||||
|
||||
int getPoolSize(Pool pool) {
|
||||
switch (pool) {
|
||||
case UNSPENT: return unspent.size();
|
||||
case SPENT: return spent.size();
|
||||
case PENDING: return pending.size();
|
||||
case INACTIVE: return inactive.size();
|
||||
case DEAD: return dead.size();
|
||||
case ALL: return unspent.size() + spent.size() + pending.size() + inactive.size() + dead.size();
|
||||
case UNSPENT:
|
||||
return unspent.size();
|
||||
case SPENT:
|
||||
return spent.size();
|
||||
case PENDING:
|
||||
return pending.size();
|
||||
case INACTIVE:
|
||||
return inactive.size();
|
||||
case DEAD:
|
||||
return dead.size();
|
||||
case ALL:
|
||||
return unspent.size() + spent.size() + pending.size() + inactive.size() + dead.size();
|
||||
}
|
||||
throw new RuntimeException("Unreachable");
|
||||
}
|
||||
@ -514,7 +526,7 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* Statelessly creates a transaction that sends the given number of nanocoins to address. The change is sent to
|
||||
* the first address in the wallet, so you must have added at least one key.<p>
|
||||
*
|
||||
* <p/>
|
||||
* This method is stateless in the sense that calling it twice with the same inputs will result in two
|
||||
* Transaction objects which are equal. The wallet is not updated to track its pending status or to mark the
|
||||
* coins as spent until confirmSend is called on the result.
|
||||
@ -569,7 +581,7 @@ public class Wallet implements Serializable {
|
||||
|
||||
/**
|
||||
* Creates a transaction that sends $coins.$cents BTC to the given address.<p>
|
||||
*
|
||||
* <p/>
|
||||
* IMPORTANT: This method does NOT update the wallet. If you call createSend again you may get two transactions
|
||||
* that spend the same coins. You have to call confirmSend on the created transaction to prevent this,
|
||||
* but that should only occur once the transaction has been accepted by the network. This implies you cannot have
|
||||
@ -643,6 +655,7 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* Locates a keypair from the keychain given the hash of the public key. This is needed when finding out which
|
||||
* key we need to use to redeem a transaction output.
|
||||
*
|
||||
* @return ECKey object or null if no such key was found.
|
||||
*/
|
||||
public synchronized ECKey findKeyFromPubHash(byte[] pubkeyHash) {
|
||||
@ -652,13 +665,16 @@ public class Wallet implements Serializable {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Returns true if this wallet contains a public key which hashes to the given hash. */
|
||||
/**
|
||||
* Returns true if this wallet contains a public key which hashes to the given hash.
|
||||
*/
|
||||
public synchronized boolean isPubKeyHashMine(byte[] pubkeyHash) {
|
||||
return findKeyFromPubHash(pubkeyHash) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates a keypair from the keychain given the raw public key bytes.
|
||||
*
|
||||
* @return ECKey or null if no such key was found.
|
||||
*/
|
||||
public synchronized ECKey findKeyFromPubKey(byte[] pubkey) {
|
||||
@ -668,7 +684,9 @@ public class Wallet implements Serializable {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Returns true if this wallet contains a keypair with the given public key. */
|
||||
/**
|
||||
* Returns true if this wallet contains a keypair with the given public key.
|
||||
*/
|
||||
public synchronized boolean isPubKeyMine(byte[] pubkey) {
|
||||
return findKeyFromPubKey(pubkey) != null;
|
||||
}
|
||||
@ -676,7 +694,7 @@ public class Wallet implements Serializable {
|
||||
/**
|
||||
* It's possible to calculate a wallets balance from multiple points of view. This enum selects which
|
||||
* getBalance() should use.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Consider a real-world example: you buy a snack costing $5 but you only have a $10 bill. At the start you have
|
||||
* $10 viewed from every possible angle. After you order the snack you hand over your $10 bill. From the
|
||||
* perspective of your wallet you have zero dollars (AVAILABLE). But you know in a few seconds the shopkeeper
|
||||
@ -694,12 +712,14 @@ public class Wallet implements Serializable {
|
||||
* spent by pending transactions, but not including the outputs of those pending transactions.
|
||||
*/
|
||||
AVAILABLE
|
||||
};
|
||||
}
|
||||
|
||||
;
|
||||
|
||||
/**
|
||||
* Returns the AVAILABLE balance of this wallet. See {@link BalanceType#AVAILABLE} for details on what this
|
||||
* means.<p>
|
||||
*
|
||||
* <p/>
|
||||
* Note: the estimated balance is usually the one you want to show to the end user - however attempting to
|
||||
* actually spend these coins may result in temporary failure. This method returns how much you can safely
|
||||
* provide to {@link Wallet#createSend(Address, java.math.BigInteger)}.
|
||||
@ -781,7 +801,7 @@ public class Wallet implements Serializable {
|
||||
* we need to go through our transactions and find out if any have become invalid. It's possible for our balance
|
||||
* to go down in this case: money we thought we had can suddenly vanish if the rest of the network agrees it
|
||||
* should be so.<p>
|
||||
*
|
||||
* <p/>
|
||||
* The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.
|
||||
*/
|
||||
synchronized void reorganize(List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
|
||||
|
@ -40,14 +40,14 @@ public interface WalletEventListener {
|
||||
|
||||
/**
|
||||
* This is called on a Peer thread when a block is received that triggers a block chain re-organization.<p>
|
||||
*
|
||||
* <p/>
|
||||
* A re-organize means that the consensus (chain) of the network has diverged and now changed from what we
|
||||
* believed it was previously. Usually this won't matter because the new consensus will include all our old
|
||||
* transactions assuming we are playing by the rules. However it's theoretically possible for our balance to
|
||||
* change in arbitrary ways, most likely, we could lose some money we thought we had.<p>
|
||||
*
|
||||
* <p/>
|
||||
* It is safe to use methods of wallet whilst inside this callback.
|
||||
*
|
||||
* <p/>
|
||||
* TODO: Finish this interface.
|
||||
*/
|
||||
void onReorganize(Wallet wallet);
|
||||
@ -55,7 +55,7 @@ public interface WalletEventListener {
|
||||
/**
|
||||
* This is called on a Peer thread when a transaction becomes <i>dead</i>. A dead transaction is one that has
|
||||
* been overridden by a double spend from the network and so will never confirm no matter how long you wait.<p>
|
||||
*
|
||||
* <p/>
|
||||
* A dead transaction can occur if somebody is attacking the network, or by accident if keys are being shared.
|
||||
* You can use this event handler to inform the user of the situation. A dead spend will show up in the BitCoin
|
||||
* C++ client of the recipient as 0/unconfirmed forever, so if it was used to purchase something,
|
||||
|
@ -20,7 +20,8 @@ import com.google.bitcoin.core.NetworkParameters;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.*;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@ -39,7 +40,7 @@ public class DnsDiscovery implements PeerDiscovery {
|
||||
private String[] hostNames;
|
||||
private NetworkParameters netParams;
|
||||
|
||||
public static final String[] defaultHosts = new String[] {
|
||||
public static final String[] defaultHosts = new String[]{
|
||||
"dnsseed.bluematt.me", // Auto generated
|
||||
"bitseed.xf2.org", // Static
|
||||
"bitseed.bitcoin.org.uk" // Static
|
||||
@ -50,8 +51,7 @@ public class DnsDiscovery implements PeerDiscovery {
|
||||
*
|
||||
* @param netParams Network parameters to be used for port information.
|
||||
*/
|
||||
public DnsDiscovery(NetworkParameters netParams)
|
||||
{
|
||||
public DnsDiscovery(NetworkParameters netParams) {
|
||||
this(getDefaultHostNames(), netParams);
|
||||
}
|
||||
|
||||
@ -61,8 +61,7 @@ public class DnsDiscovery implements PeerDiscovery {
|
||||
* @param hostNames Host names to be examined for seed addresses.
|
||||
* @param netParams Network parameters to be used for port information.
|
||||
*/
|
||||
public DnsDiscovery(String[] hostNames, NetworkParameters netParams)
|
||||
{
|
||||
public DnsDiscovery(String[] hostNames, NetworkParameters netParams) {
|
||||
this.hostNames = hostNames;
|
||||
this.netParams = netParams;
|
||||
}
|
||||
@ -108,8 +107,7 @@ public class DnsDiscovery implements PeerDiscovery {
|
||||
/**
|
||||
* Returns the well known discovery host names on the production network.
|
||||
*/
|
||||
public static String[] getDefaultHostNames()
|
||||
{
|
||||
public static String[] getDefaultHostNames() {
|
||||
return defaultHosts;
|
||||
}
|
||||
|
||||
|
@ -22,9 +22,16 @@ import com.google.bitcoin.core.Utils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* IrcDiscovery provides a way to find network peers by joining a pre-agreed rendevouz point on the LFnet IRC network.
|
||||
@ -137,7 +144,8 @@ public class IrcDiscovery implements PeerDiscovery {
|
||||
try {
|
||||
// No matter what try to close the connection.
|
||||
connection.close();
|
||||
} catch (Exception e2) {}
|
||||
} catch (Exception e2) {
|
||||
}
|
||||
}
|
||||
return addresses.toArray(new InetSocketAddress[]{});
|
||||
}
|
||||
|
@ -17,7 +17,6 @@
|
||||
package com.google.bitcoin.discovery;
|
||||
|
||||
public class PeerDiscoveryException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = -2863411151549391392L;
|
||||
|
||||
public PeerDiscoveryException() {
|
||||
@ -28,14 +27,11 @@ public class PeerDiscoveryException extends Exception {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public PeerDiscoveryException(Throwable arg0)
|
||||
{
|
||||
public PeerDiscoveryException(Throwable arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
public PeerDiscoveryException(String message, Throwable arg0) {
|
||||
super(message, arg0);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -16,8 +16,6 @@
|
||||
package com.google.bitcoin.discovery;
|
||||
|
||||
import com.google.bitcoin.core.NetworkParameters;
|
||||
import com.google.bitcoin.discovery.PeerDiscovery;
|
||||
import com.google.bitcoin.discovery.PeerDiscoveryException;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
@ -52,12 +50,14 @@ public class SeedPeers implements PeerDiscovery {
|
||||
}
|
||||
|
||||
private InetSocketAddress nextPeer() throws UnknownHostException {
|
||||
if(pnseedIndex >= seedAddrs.length)return null;
|
||||
if (pnseedIndex >= seedAddrs.length) return null;
|
||||
return new InetSocketAddress(convertAddress(seedAddrs[pnseedIndex++]),
|
||||
params.port);
|
||||
}
|
||||
|
||||
/** Returns an array containing all the Bitcoin nodes within the list. */
|
||||
/**
|
||||
* Returns an array containing all the Bitcoin nodes within the list.
|
||||
*/
|
||||
public InetSocketAddress[] getPeers() throws PeerDiscoveryException {
|
||||
try {
|
||||
return allPeers();
|
||||
@ -68,13 +68,13 @@ public class SeedPeers implements PeerDiscovery {
|
||||
|
||||
private InetSocketAddress[] allPeers() throws UnknownHostException {
|
||||
InetSocketAddress[] addresses = new InetSocketAddress[seedAddrs.length];
|
||||
for(int i=0;i < seedAddrs.length; ++i) {
|
||||
for (int i = 0; i < seedAddrs.length; ++i) {
|
||||
addresses[i] = new InetSocketAddress(convertAddress(seedAddrs[i]), params.port);
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
private InetAddress convertAddress(int seed) throws UnknownHostException{
|
||||
private InetAddress convertAddress(int seed) throws UnknownHostException {
|
||||
byte[] v4addr = new byte[4];
|
||||
v4addr[0] = (byte) (0xFF & (seed));
|
||||
v4addr[1] = (byte) (0xFF & (seed >> 8));
|
||||
|
@ -16,13 +16,13 @@
|
||||
|
||||
package com.google.bitcoin.examples;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
import com.google.bitcoin.core.*;
|
||||
import com.google.bitcoin.core.NetworkParameters;
|
||||
import com.google.bitcoin.discovery.DnsDiscovery;
|
||||
import com.google.bitcoin.discovery.IrcDiscovery;
|
||||
import com.google.bitcoin.discovery.PeerDiscoveryException;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
/**
|
||||
* Prints a list of IP addresses connected to the rendezvous point on the LFnet IRC channel.
|
||||
*/
|
||||
|
@ -16,16 +16,20 @@
|
||||
|
||||
package com.google.bitcoin.store;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.util.*;
|
||||
|
||||
import com.google.bitcoin.core.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Stores the block chain to disk.<p>
|
||||
*
|
||||
@ -248,6 +252,7 @@ public class BoundedOverheadBlockStore implements BlockStore {
|
||||
}
|
||||
|
||||
private ByteBuffer buf = ByteBuffer.allocateDirect(Record.SIZE);
|
||||
|
||||
private Record getRecord(Sha256Hash hash) throws BlockStoreException, IOException, ProtocolException {
|
||||
long startPos = channel.position();
|
||||
// Use our own file pointer within the tight loop as updating channel positions is really expensive.
|
||||
|
@ -16,15 +16,18 @@
|
||||
|
||||
package com.google.bitcoin.store;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.bitcoin.core.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Stores the block chain to disk but still holds it in memory. This is intended for desktop apps and tests.
|
||||
* Constrained environments like mobile phones probably won't want to or be able to store all the block headers in RAM.
|
||||
|
@ -18,8 +18,6 @@ package com.google.bitcoin.store;
|
||||
|
||||
import com.google.bitcoin.core.*;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user