Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version 0.3.3 changes #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<parent>
<groupId>io.xpydev</groupId>
<artifactId>paycoinj-parent</artifactId>
<version>0.1.0</version>
<version>0.3.3</version>
</parent>

<artifactId>paycoinj</artifactId>
Expand Down Expand Up @@ -234,6 +234,9 @@
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
<exclude>lib/x86_64/darwin/libscrypt.dylib</exclude>
<exclude>lib/x86_64/freebsd/libscrypt.so</exclude>
<exclude>lib/x86_64/linux/libscrypt.so</exclude>
</excludes>
</filter>
</filters>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ public void onKeysAdded(List<ECKey> keys) {
public void onScriptsAdded(Wallet wallet, List<Script> scripts) {
onChange();
}

@Override
public void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts) {
onChange();
}

@Override
public void onWalletChanged(Wallet wallet) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ public int numCheckpoints() {
return checkpoints.size();
}

public TreeMap<Long, StoredBlock> getCheckpoints() {
return checkpoints;
}

/** Returns a hash of the concatenated checkpoint data. */
public Sha256Hash getDataHash() {
return dataHash;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package io.xpydev.paycoinj.core;
/**
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import io.xpydev.paycoinj.core.AbstractPeerEventListener;
import io.xpydev.paycoinj.core.Block;
import io.xpydev.paycoinj.core.Peer;
import io.xpydev.paycoinj.core.Utils;

/**
* <p>
* An implementation of {@link AbstractPeerEventListener} that listens to chain
* download events and tracks progress as a percentage. The default
* implementation prints progress to stdout, but you can subclass it and
* override the progress method to update a GUI instead.
* </p>
*/
public class DownloadProgressTracker extends AbstractPeerEventListener {
private static final Logger log = LoggerFactory.getLogger(DownloadProgressTracker.class);
private int originalBlocksLeft = -1;
private int lastPercent = 0;
private SettableFuture<Long> future = SettableFuture.create();
private boolean caughtUp = false;

@Override
public void onChainDownloadStarted(Peer peer, int blocksLeft) {
if (blocksLeft > 0 && originalBlocksLeft == -1) startDownload(blocksLeft);
// Only mark this the first time, because this method can be called more
// than once during a chain download
// if we switch peers during it.
if (originalBlocksLeft == -1) originalBlocksLeft = blocksLeft;
else log.info("Chain download switched to {}", peer);
if (blocksLeft <= 0) {
caughtUp = true;
doneDownload();
future.set(peer.getBestHeight());
}
}

@Override
public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) {
if (caughtUp) return;

if (blocksLeft <= 0) {
caughtUp = true;
doneDownload();
future.set(peer.getBestHeight());
}

if (blocksLeft <= 0 || originalBlocksLeft <= 0) return;

double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft));
if ((int) pct != lastPercent) {
progress(pct, blocksLeft, new Date(block.getTimeSeconds() * 1000));
lastPercent = (int) pct;
}
}

/**
* Called when download progress is made.
*
* @param pct
* the percentage of chain downloaded, estimated
* @param date
* the date of the last block downloaded
*/
protected void progress(double pct, int blocksSoFar, Date date) {
log.info(String.format("Chain download %d%% done with %d blocks to go, block date %s", (int) pct, blocksSoFar,
Utils.dateTimeFormat(date)));
}

/**
* Called when download is initiated.
*
* @param blocks
* the number of blocks to download, estimated
*/
protected void startDownload(int blocks) {
log.info("Downloading block chain of size " + blocks + ". " +
(blocks > 1000 ? "This may take a while." : ""));
}

/**
* Called when we are done downloading the block chain.
*/
protected void doneDownload() {
}

/**
* Wait for the chain to be downloaded.
*/
public void await() throws InterruptedException {
try {
future.get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}

/**
* Returns a listenable future that completes with the height of the best
* chain (as reported by the peer) once chain download seems to be finished.
*/
public ListenableFuture<Long> getFuture() {
return future;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,12 @@
* them, you are encouraged to call the static get() methods on each specific params class directly.</p>
*/
public abstract class NetworkParameters implements Serializable {
private static final long serialVersionUID = 516551887248710642L;

/**
* The protocol version this library implements.
*/
public static final int PROTOCOL_VERSION = 70003;
public static final int PROTOCOL_VERSION = 70006;

/**
* The alert signing key.
Expand Down
10 changes: 9 additions & 1 deletion core/src/main/java/io/xpydev/paycoinj/core/Peer.java
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ public void run() {

@Override
public void connectionOpened() {
// Announce ourselves. This has to come first to connect to clients beyond v0.3.20.2 which wait to hear
// Announce ourselves. This has to come first to connect to clients beyond v0.3.3 which wait to hear
// from us until they send their version message back.
PeerAddress address = getAddress();
log.info("Announcing to {} as: {}", address == null ? "Peer" : address.toSocketAddress(), versionMessage.subVer);
Expand Down Expand Up @@ -1228,6 +1228,7 @@ private ListenableFuture sendSingleGetData(GetDataMessage getdata) {
*/
public void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks) {
// For peercoin we cannot use filtered blocks until the protocol has been upgraded
useFilteredBlocks = false;
lock.lock();
try {
Preconditions.checkNotNull(blockChain);
Expand Down Expand Up @@ -1389,6 +1390,13 @@ private void blockChainDownloadLocked(Sha256Hash toHash) {
throw new RuntimeException(e);
}
}

if (blockLocator.size() > 1) {
// For some reason we lose the last block when switching peers:
// remove the head so that it gets replayed
blockLocator.remove(0);
}

// Only add the locator if we didn't already do so. If the chain is < 50 blocks we already reached it.
if (cursor != null)
blockLocator.add(params.getGenesisBlock().getHash());
Expand Down
6 changes: 5 additions & 1 deletion core/src/main/java/io/xpydev/paycoinj/core/PeerGroup.java
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public class PeerGroup extends AbstractExecutionThreadService implements Transac
// until we reach this count.
@GuardedBy("lock") private int maxConnections;
// Minimum protocol version we will allow ourselves to connect to: Do not require bloom filtering as it doesn't exist in Paycoin
private volatile int vMinRequiredProtocolVersion = 70003;
private volatile int vMinRequiredProtocolVersion = 70006;

// Runs a background thread that we use for scheduling pings to our peers, so we can measure their performance
// and network latency. We ping peers every pingIntervalMsec milliseconds.
Expand Down Expand Up @@ -202,6 +202,10 @@ private synchronized void queueRecalc(boolean andTransmit) {
queueRecalc(false);
}

@Override public void onScriptsChanged(Wallet wallet, java.util.List<Script> scripts, boolean isAddingScripts) {
queueRecalc(false);
}

@Override public void onKeysAdded(List<ECKey> keys) {
queueRecalc(false);
}
Expand Down
102 changes: 101 additions & 1 deletion core/src/main/java/io/xpydev/paycoinj/core/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,15 @@

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
Expand All @@ -61,6 +65,8 @@ public class Utils {
public static final String Paycoin_SIGNED_MESSAGE_HEADER = "Paycoin Signed Message:\n";
public static final byte[] Paycoin_SIGNED_MESSAGE_HEADER_BYTES = Paycoin_SIGNED_MESSAGE_HEADER.getBytes(Charsets.UTF_8);

private static final Joiner SPACE_JOINER = Joiner.on(" ");

private static BlockingQueue<Boolean> mockSleepQueue;

/**
Expand Down Expand Up @@ -443,6 +449,40 @@ public static long currentTimeSeconds() {
return currentTimeMillis() / 1000;
}

private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

/**
* Formats a given date+time value to an ISO 8601 string.
* @param dateTime value to format, as a Date
*/
public static String dateTimeFormat(Date dateTime) {
DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
iso8601.setTimeZone(UTC);
return iso8601.format(dateTime);
}

/**
* Formats a given date+time value to an ISO 8601 string.
* @param dateTime value to format, unix time (ms)
*/
public static String dateTimeFormat(long dateTime) {
DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
iso8601.setTimeZone(UTC);
return iso8601.format(dateTime);
}

/**
* Returns a string containing the string representation of the given items,
* delimited by a single space character.
*
* @param items the items to join
* @param <T> the item type
* @return the joined space-delimited string
*/
public static <T> String join(Iterable<T> items) {
return SPACE_JOINER.join(items);
}

public static byte[] copyOf(byte[] in, int length) {
byte[] out = new byte[length];
System.arraycopy(in, 0, out, 0, Math.min(length, in.length));
Expand All @@ -458,6 +498,44 @@ public static byte[] appendByte(byte[] bytes, byte b) {
return result;
}

/**
* Constructs a new String by decoding the given bytes using the specified charset.
* <p>
* This is a convenience method which wraps the checked exception with a RuntimeException.
* The exception can never occur given the charsets
* US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16LE or UTF-16BE.
*
* @param bytes the bytes to be decoded into characters
* @param charsetName the name of a supported {@linkplain java.nio.charset.Charset charset}
* @return the decoded String
*/
public static String toString(byte[] bytes, String charsetName) {
try {
return new String(bytes, charsetName);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

/**
* Encodes the given string into a sequence of bytes using the named charset.
* <p>
* This is a convenience method which wraps the checked exception with a RuntimeException.
* The exception can never occur given the charsets
* US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16LE or UTF-16BE.
*
* @param str the string to encode into bytes
* @param charsetName the name of a supported {@linkplain java.nio.charset.Charset charset}
* @return the encoded bytes
*/
public static byte[] toBytes(CharSequence str, String charsetName) {
try {
return str.toString().getBytes(charsetName);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

/**
* Attempts to parse the given string as arbitrary-length hex or base58 and then return the results, or null if
* neither parse was successful.
Expand Down Expand Up @@ -550,9 +628,13 @@ public static void finishMockSleep() {
}
}

private static int isAndroid = -1;
public static boolean isAndroidRuntime() {
if (isAndroid == -1) {
final String runtime = System.getProperty("java.runtime.name");
return runtime != null && runtime.equals("Android Runtime");
isAndroid = (runtime != null && runtime.equals("Android Runtime")) ? 1 : 0;
}
return isAndroid == 1;
}

private static class Pair implements Comparable<Pair> {
Expand Down Expand Up @@ -602,4 +684,22 @@ public static String getResourceAsString(URL url) throws IOException {
return Joiner.on('\n').join(lines);
}

// Can't use Closeable here because it's Java 7 only and Android devices only got that with KitKat.
public static InputStream closeUnchecked(InputStream stream) {
try {
stream.close();
return stream;
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static OutputStream closeUnchecked(OutputStream stream) {
try {
stream.close();
return stream;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public class VersionMessage extends Message {
public boolean relayTxesBeforeFilter;

/** The version of this library release, as a string. */
public static final String PAYCOINJ_VERSION = "0.1.0";
public static final String PAYCOINJ_VERSION = "0.3.3";
/** The value that is prepended to the subVer field of this application. */
public static final String LIBRARY_SUBVER = "/paycoinJ:" + PAYCOINJ_VERSION + "/";

Expand Down
Loading