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

Copied DownloadProgressTracker from bitcoinj #23

Open
wants to merge 3 commits 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
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) {
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;
}
}
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);
}
}
}